index
int64 | repo_id
string | file_path
string | content
string |
|---|---|---|---|
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/DatabaseSaver.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/>.
*/
/*
* DatabaseSaver.java
* Copyright (C) 2004-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.converters;
import weka.core.Attribute;
import weka.core.Capabilities;
import weka.core.Capabilities.Capability;
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.Utils;
import weka.gui.FilePropertyMetadata;
import weka.gui.PasswordProperty;
import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Enumeration;
import java.util.Vector;
/**
* <!-- globalinfo-start --> Writes to a database (tested with MySQL, InstantDB,
* HSQLDB).
* <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>
* -T <table name>
* The name of the table.
* (default: the relation name)
* </pre>
*
* <pre>
* -truncate
* Truncate (i.e. delete any data) in table before inserting
* </pre>
*
* <pre>
* -P
* Add an ID column as primary key. The name is specified
* in the DatabaseUtils file ('idColumn'). The DatabaseLoader
* won't load this column.
* </pre>
*
* <pre>
* -custom-props <file>
* The custom properties file to use instead of default ones,
* containing the database parameters.
* (default: none)
* </pre>
*
* <pre>
* -i <input file name>
* Input file in arff format that should be saved in database.
* </pre>
*
* <!-- options-end -->
*
* @author Stefan Mutter (mutter@cs.waikato.ac.nz)
* @version $Revision$
*/
public class DatabaseSaver extends AbstractSaver implements BatchConverter,
IncrementalConverter, DatabaseConverter, OptionHandler, EnvironmentHandler {
/** for serialization. */
static final long serialVersionUID = 863971733782624956L;
/** The database connection. */
protected DatabaseConnection m_DataBaseConnection;
/** The name of the table in which the instances should be stored. */
protected String m_tableName;
/** Table name with any environment variables resolved */
protected String m_resolvedTableName;
/** An input arff file (for command line use). */
protected String m_inputFile;
/**
* The database specific type for a string (read in from the properties file).
*/
protected String m_createText;
/**
* The database specific type for a double (read in from the properties file).
*/
protected String m_createDouble;
/** The database specific type for an int (read in from the properties file). */
protected String m_createInt;
/** The database specific type for a date (read in from the properties file). */
protected String m_createDate;
/** For converting the date value into a database string. */
protected SimpleDateFormat m_DateFormat;
/**
* The name of the primary key column that will be automatically generated (if
* enabled). The name is read from DatabaseUtils.
*/
protected String m_idColumn;
/** counts the rows and used as a primary key value. */
protected int m_count;
/** Flag indicating if a primary key column should be added. */
protected boolean m_id;
/**
* Flag indicating whether the default name of the table is the relaion name
* or not.
*/
protected boolean m_tabName;
/** the database URL. */
protected String m_URL;
/** the user name for the database. */
protected String m_Username;
/** the password for the database. */
protected String m_Password = "";
/** the custom props file to use instead of default one. */
protected File m_CustomPropsFile = new File("${user.home}");
/**
* Whether to truncate (i.e. drop and then recreate) the table if it already
* exists
*/
protected boolean m_truncate;
/** Environment variables to use */
protected transient Environment m_env;
/**
* Constructor.
*
* @throws Exception throws Exception if property file cannot be read
*/
public DatabaseSaver() throws Exception {
resetOptions();
}
/**
* Main method.
*
* @param options should contain the options of a Saver.
*/
public static void main(String[] options) {
StringBuffer text = new StringBuffer();
text.append("\n\nDatabaseSaver options:\n");
try {
DatabaseSaver asv = new DatabaseSaver();
try {
Enumeration<Option> enumi = asv.listOptions();
while (enumi.hasMoreElements()) {
Option option = enumi.nextElement();
text.append(option.synopsis() + '\n');
text.append(option.description() + '\n');
}
asv.setOptions(options);
asv.setDestination(asv.getUrl());
} catch (Exception ex) {
ex.printStackTrace();
}
// incremental
/*
* asv.setRetrieval(INCREMENTAL); Instances instances =
* asv.getInstances(); asv.setStructure(instances); for(int i = 0; i <
* instances.numInstances(); i++){ //last instance is null and finishes
* incremental saving asv.writeIncremental(instances.instance(i)); }
* asv.writeIncremental(null);
*/
// batch
asv.writeBatch();
} catch (Exception ex) {
ex.printStackTrace();
System.out.println(text);
}
}
private void checkEnv() {
if (m_env == null) {
m_env = Environment.getSystemWide();
}
}
/**
* 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_Username);
setPassword(m_Password);
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* 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 = new DatabaseConnection();
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) {
}
if (pFile.isFile()) {
result = new DatabaseConnection(pFile);
}
}
m_createText = result.getProperties().getProperty("CREATE_STRING");
m_createDouble = result.getProperties().getProperty("CREATE_DOUBLE");
m_createInt = result.getProperties().getProperty("CREATE_INT");
m_createDate =
result.getProperties().getProperty("CREATE_DATE", "DATETIME");
m_DateFormat =
new SimpleDateFormat(result.getProperties().getProperty("DateFormat",
"yyyy-MM-dd HH:mm:ss"));
m_idColumn = result.getProperties().getProperty("idColumn");
return result;
}
/**
* Resets the Saver ready to save a new data set.
*/
@Override
public void resetOptions() {
super.resetOptions();
setRetrieval(NONE);
try {
if (m_DataBaseConnection != null && m_DataBaseConnection.isConnected()) {
m_DataBaseConnection.disconnectFromDatabase();
}
m_DataBaseConnection = newDatabaseConnection();
} catch (Exception ex) {
printException(ex);
}
m_URL = m_DataBaseConnection.getDatabaseURL();
m_tableName = "";
m_Username = m_DataBaseConnection.getUsername();
m_Password = m_DataBaseConnection.getPassword();
m_count = 1;
m_id = false;
m_tabName = true;
/*
* m_createText =
* m_DataBaseConnection.getProperties().getProperty("CREATE_STRING");
* m_createDouble =
* m_DataBaseConnection.getProperties().getProperty("CREATE_DOUBLE");
* m_createInt =
* m_DataBaseConnection.getProperties().getProperty("CREATE_INT");
* m_createDate =
* m_DataBaseConnection.getProperties().getProperty("CREATE_DATE",
* "DATETIME"); m_DateFormat = new
* SimpleDateFormat(m_DataBaseConnection.getProperties
* ().getProperty("DateFormat", "yyyy-MM-dd HH:mm:ss")); m_idColumn =
* m_DataBaseConnection.getProperties().getProperty("idColumn");
*/
}
/**
* Cancels the incremental saving process and tries to drop the table if the
* write mode is CANCEL.
*/
@Override
public void cancel() {
if (getWriteMode() == CANCEL) {
try {
m_DataBaseConnection.update("DROP TABLE " + m_resolvedTableName);
if (m_DataBaseConnection.tableExists(m_resolvedTableName)) {
System.err.println("Table cannot be dropped.");
}
} catch (Exception ex) {
printException(ex);
}
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 database (tested with MySQL, InstantDB, HSQLDB).";
}
/**
* Gets the table's name.
*
* @return the table's name
*/
@OptionMetadata(displayName = "Table name",
description = "Sets the name of the table", displayOrder = 4)
public String getTableName() {
return m_tableName;
}
/**
* Sets the table's name.
*
* @param tn the name of the table
*/
public void setTableName(String tn) {
m_tableName = tn;
}
/**
* Returns the tip text for this property.
*
* @return the tip text for this property
*/
public String tableNameTipText() {
return "Sets the name of the table.";
}
/**
* Get whether to truncate (i.e. drop and recreate) the table if it already
* exits. If false, then new data is appended to the table.
*
* @return true if the table should be truncated first (if it exists).
*/
@OptionMetadata(displayName = "Truncate table",
description = "Truncate (i.e. drop and recreate) table if it already exists",
displayOrder = 6)
public boolean getTruncate() {
return m_truncate;
}
/**
* Set whether to truncate (i.e. drop and recreate) the table if it already
* exits. If false, then new data is appended to the table.
*
* @param t true if the table should be truncated first (if it exists).
*/
public void setTruncate(boolean t) {
m_truncate = t;
}
/**
* Returns the tip text for this property.
*
* @return the tip text for this property
*/
public String truncateTipText() {
return "Truncate (i.e. drop and recreate) table if it already exists";
}
/**
* Gets whether or not a primary key will be generated automatically.
*
* @return true if a primary key column will be generated, false otherwise
*/
@OptionMetadata(
displayName = "Automatic primary key",
description = "If set to true, a primary key column is generated automatically (containing the row number as INTEGER). The name of the key is read from DatabaseUtils (idColumn)"
+ " This primary key can be used for incremental loading (requires an unique key). This primary key will not be loaded as an attribute.",
displayOrder = 7)
public
boolean getAutoKeyGeneration() {
return m_id;
}
/**
* En/Dis-ables the automatic generation of a primary key.
*
* @param flag flag for automatic key-genereration
*/
public void setAutoKeyGeneration(boolean flag) {
m_id = flag;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property
*/
public String autoKeyGenerationTipText() {
return "If set to true, a primary key column is generated automatically (containing the row number as INTEGER). The name of the key is read from DatabaseUtils (idColumn)"
+ " This primary key can be used for incremental loading (requires an unique key). This primary key will not be loaded as an attribute.";
}
/**
* Gets whether or not the relation name is used as name of the table.
*
* @return true if the relation name is used as the name of the table, false
* otherwise
*/
@OptionMetadata(
displayName = "Use relation name",
description = "If set to true, the relation name will be used as name for the database table. Otherwise the user has to provide a table name.",
displayOrder = 5)
public
boolean getRelationForTableName() {
return m_tabName;
}
/**
* En/Dis-ables that the relation name is used for the name of the table
* (default enabled).
*
* @param flag if true the relation name is used as table name
*/
public void setRelationForTableName(boolean flag) {
m_tabName = flag;
}
/**
* Returns the tip text fo this property.
*
* @return the tip text for this property
*/
public String relationForTableNameTipText() {
return "If set to true, the relation name will be used as name for the database table. Otherwise the user has to provide a table name.";
}
/**
* Gets the database URL.
*
* @return the URL
*/
@OptionMetadata(displayName = "Database URL",
description = "The URL of the database", displayOrder = 1)
@Override
public String getUrl() {
return m_URL;
}
/**
* Sets the database URL.
*
* @param url the URL
*/
@Override
public void setUrl(String url) {
checkEnv();
m_URL = url;
String uCopy = m_URL;
try {
uCopy = m_env.substitute(uCopy);
} catch (Exception ex) {
}
m_DataBaseConnection.setDatabaseURL(uCopy);
}
/**
* Returns the tip text for this property.
*
* @return the tip text for this property
*/
public String urlTipText() {
return "The URL of the database";
}
/**
* Gets the database user.
*
* @return the user name
*/
@Override
public String getUser() {
// return m_DataBaseConnection.getUsername();
return m_Username;
}
/**
* Sets the database user.
*
* @param user the user name
*/
@OptionMetadata(displayName = "Username",
description = "The user name for the database", displayOrder = 2)
@Override
public void setUser(String user) {
checkEnv();
m_Username = user;
String userCopy = user;
try {
userCopy = m_env.substitute(userCopy);
} catch (Exception ex) {
}
m_DataBaseConnection.setUsername(userCopy);
}
/**
* Returns the tip text for this property.
*
* @return the tip text for this property
*/
public String userTipText() {
return "The user name for the database";
}
/**
* 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;
}
/**
* Sets the database password.
*
* @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 tip text for this property.
*
* @return the tip text for this property
*/
public String passwordTipText() {
return "The database password";
}
/**
* 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;
}
/**
* 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;
}
/**
* 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 the database url
* @param userName the user name
* @param password the password
*/
public void setDestination(String url, String userName, String password) {
try {
checkEnv();
m_DataBaseConnection = newDatabaseConnection();
setUrl(url);
setUser(userName);
setPassword(password);
// m_DataBaseConnection.setDatabaseURL(url);
// m_DataBaseConnection.setUsername(userName);
// m_DataBaseConnection.setPassword(password);
} catch (Exception ex) {
printException(ex);
}
}
/**
* Sets the database url.
*
* @param url the database url
*/
public void setDestination(String url) {
try {
checkEnv();
m_DataBaseConnection = newDatabaseConnection();
// m_DataBaseConnection.setDatabaseURL(url);
setUrl(url);
setUser(m_Username);
setPassword(m_Password);
// m_DataBaseConnection.setUsername(m_Username);
// m_DataBaseConnection.setPassword(m_Password);
} catch (Exception ex) {
printException(ex);
}
}
/** Sets the database url using the DatabaseUtils file. */
public void setDestination() {
try {
checkEnv();
m_DataBaseConnection = newDatabaseConnection();
setUser(m_Username);
setPassword(m_Password);
// m_DataBaseConnection.setUsername(m_Username);
// m_DataBaseConnection.setPassword(m_Password);
} catch (Exception ex) {
printException(ex);
}
}
/**
* 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);
result.enable(Capability.STRING_ATTRIBUTES);
// class
result.enable(Capability.NOMINAL_CLASS);
result.enable(Capability.NUMERIC_CLASS);
result.enable(Capability.DATE_CLASS);
result.enable(Capability.STRING_CLASS);
result.enable(Capability.NO_CLASS);
result.enable(Capability.MISSING_CLASS_VALUES);
return result;
}
/**
* Opens a connection to the database.
*
*/
public void connectToDatabase() {
try {
if (!m_DataBaseConnection.isConnected()) {
m_DataBaseConnection.connectToDatabase();
}
} catch (Exception ex) {
printException(ex);
}
}
/**
* Writes the structure (header information) to a database by creating a new
* table.
*
* @throws Exception if something goes wrong
*/
private void writeStructure() throws Exception {
StringBuffer query = new StringBuffer();
Instances structure = getInstances();
query.append("CREATE TABLE ");
m_resolvedTableName = m_env.substitute(m_tableName);
if (m_tabName || m_resolvedTableName.equals("")) {
m_resolvedTableName =
m_DataBaseConnection.maskKeyword(structure.relationName());
}
if (m_DataBaseConnection.getUpperCase()) {
m_resolvedTableName = m_resolvedTableName.toUpperCase();
m_createInt = m_createInt.toUpperCase();
m_createDouble = m_createDouble.toUpperCase();
m_createText = m_createText.toUpperCase();
m_createDate = m_createDate.toUpperCase();
}
m_resolvedTableName = m_resolvedTableName.replaceAll("[^\\w]", "_");
m_resolvedTableName = m_DataBaseConnection.maskKeyword(m_resolvedTableName);
query.append(m_resolvedTableName);
if (structure.numAttributes() == 0) {
throw new Exception("Instances have no attribute.");
}
query.append(" ( ");
if (m_DataBaseConnection.tableExists(m_resolvedTableName)) {
if (!m_truncate) {
System.err.println("[DatabaseSaver] Table '" + m_resolvedTableName
+ "' already exists - will append data...");
// if incremental and using primary key set the correct start value
// for count
if (getRetrieval() == INCREMENTAL && m_id) {
String countS = "SELECT COUNT(*) FROM " + m_resolvedTableName;
m_DataBaseConnection.execute(countS);
ResultSet countRS = m_DataBaseConnection.getResultSet();
countRS.next();
m_count = countRS.getInt(1);
countRS.close();
m_count++;
}
return;
}
String trunc = "DROP TABLE " + m_resolvedTableName;
m_DataBaseConnection.execute(trunc);
}
if (m_id) {
if (m_DataBaseConnection.getUpperCase()) {
m_idColumn = m_idColumn.toUpperCase();
}
query.append(m_DataBaseConnection.maskKeyword(m_idColumn));
query.append(" ");
query.append(m_createInt);
query.append(" PRIMARY KEY,");
}
for (int i = 0; i < structure.numAttributes(); i++) {
Attribute att = structure.attribute(i);
String attName = att.name();
attName = attName.replaceAll("[^\\w]", "_");
attName = m_DataBaseConnection.maskKeyword(attName);
if (m_DataBaseConnection.getUpperCase()) {
query.append(attName.toUpperCase());
} else {
query.append(attName);
}
if (att.isDate()) {
query.append(" " + m_createDate);
} else {
if (att.isNumeric()) {
query.append(" " + m_createDouble);
} else {
query.append(" " + m_createText);
}
}
if (i != structure.numAttributes() - 1) {
query.append(", ");
}
}
query.append(" )");
// System.out.println(query.toString());
m_DataBaseConnection.update(query.toString());
m_DataBaseConnection.close();
if (!m_DataBaseConnection.tableExists(m_resolvedTableName)) {
throw new IOException("Table cannot be built.");
}
}
/**
* inserts the given instance into the table.
*
* @param inst the instance to insert
* @throws Exception if something goes wrong
*/
private void writeInstance(Instance inst) throws Exception {
StringBuffer insert = new StringBuffer();
insert.append("INSERT INTO ");
insert.append(m_resolvedTableName);
insert.append(" VALUES ( ");
if (m_id) {
insert.append(m_count);
insert.append(", ");
m_count++;
}
for (int j = 0; j < inst.numAttributes(); j++) {
if (inst.isMissing(j)) {
insert.append("NULL");
} else {
if ((inst.attribute(j)).isDate()) {
insert.append("'" + m_DateFormat.format((long) inst.value(j)) + "'");
} else if ((inst.attribute(j)).isNumeric()) {
insert.append(inst.value(j));
} else {
String stringInsert = "'" + inst.stringValue(j) + "'";
if (stringInsert.length() > 2) {
stringInsert = stringInsert.replaceAll("''", "'");
}
insert.append(stringInsert);
}
}
if (j != inst.numAttributes() - 1) {
insert.append(", ");
}
}
insert.append(" )");
// System.out.println(insert.toString());
if (m_DataBaseConnection.update(insert.toString()) < 1) {
throw new IOException("Tuple cannot be inserted.");
} else {
m_DataBaseConnection.close();
}
}
/**
* Saves an instances incrementally. Structure has to be set by using the
* setStructure() method or setInstances() method. When a structure is set, a
* table is created.
*
* @param inst the instance to save
* @throws IOException throws IOEXception.
*/
@Override
public void writeIncremental(Instance inst) throws IOException {
int writeMode = getWriteMode();
Instances structure = getInstances();
if (m_DataBaseConnection == null) {
throw new IOException("No database has been set up.");
}
if (getRetrieval() == BATCH) {
throw new IOException("Batch and incremental saving cannot be mixed.");
}
setRetrieval(INCREMENTAL);
try {
if (!m_DataBaseConnection.isConnected()) {
connectToDatabase();
}
if (writeMode == WAIT) {
if (structure == null) {
setWriteMode(CANCEL);
if (inst != null) {
throw new Exception(
"Structure(Header Information) has to be set in advance");
}
} else {
setWriteMode(STRUCTURE_READY);
}
writeMode = getWriteMode();
}
if (writeMode == CANCEL) {
cancel();
}
if (writeMode == STRUCTURE_READY) {
setWriteMode(WRITE);
writeStructure();
writeMode = getWriteMode();
}
if (writeMode == WRITE) {
if (structure == null) {
throw new IOException("No instances information available.");
}
if (inst != null) {
// write instance
writeInstance(inst);
} else {
// close
m_DataBaseConnection.disconnectFromDatabase();
resetStructure();
m_count = 1;
}
}
} catch (Exception ex) {
printException(ex);
}
}
/**
* Writes a Batch of instances.
*
* @throws IOException throws IOException
*/
@Override
public void writeBatch() throws IOException {
Instances instances = getInstances();
if (instances == null) {
throw new IOException("No instances to save");
}
if (getRetrieval() == INCREMENTAL) {
throw new IOException("Batch and incremental saving cannot be mixed.");
}
if (m_DataBaseConnection == null) {
throw new IOException("No database has been set up.");
}
setRetrieval(BATCH);
try {
if (!m_DataBaseConnection.isConnected()) {
connectToDatabase();
}
setWriteMode(WRITE);
writeStructure();
for (int i = 0; i < instances.numInstances(); i++) {
writeInstance(instances.instance(i));
}
m_DataBaseConnection.disconnectFromDatabase();
setWriteMode(WAIT);
resetStructure();
m_count = 1;
} catch (Exception ex) {
printException(ex);
}
}
/**
* 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("");
}
}
/**
* 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());
}
if ((m_tableName != null) && (m_tableName.length() != 0)) {
options.add("-T");
options.add(m_tableName);
}
if (m_truncate) {
options.add("-truncate");
}
if (m_id) {
options.add("-P");
}
if ((m_inputFile != null) && (m_inputFile.length() != 0)) {
options.add("-i");
options.add(m_inputFile);
}
if ((m_CustomPropsFile != null) && !m_CustomPropsFile.isDirectory()) {
options.add("-custom-props");
options.add(m_CustomPropsFile.toString());
}
return options.toArray(new String[options.size()]);
}
/**
* Sets the options.
* <p/>
*
* <!-- 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>
* -T <table name>
* The name of the table.
* (default: the relation name)
* </pre>
*
* <pre>
* -truncate
* Truncate (i.e. delete any data) in table before inserting
* </pre>
*
* <pre>
* -P
* Add an ID column as primary key. The name is specified
* in the DatabaseUtils file ('idColumn'). The DatabaseLoader
* won't load this column.
* </pre>
*
* <pre>
* -custom-props <file>
* The custom properties file to use instead of default ones,
* containing the database parameters.
* (default: none)
* </pre>
*
* <pre>
* -i <input file name>
* Input file in arff format that should be saved in database.
* </pre>
*
* <!-- options-end -->
*
* @param options the options
* @throws Exception if options cannot be set
*/
@Override
public void setOptions(String[] options) throws Exception {
String tableString, inputString, tmpStr;
resetOptions();
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);
}
tableString = Utils.getOption('T', options);
m_truncate = Utils.getFlag("truncate", options);
inputString = Utils.getOption('i', options);
if (tableString.length() != 0) {
m_tableName = tableString;
m_tabName = false;
}
m_id = Utils.getFlag('P', options);
if (inputString.length() != 0) {
try {
m_inputFile = inputString;
ArffLoader al = new ArffLoader();
File inputFile = new File(inputString);
al.setSource(inputFile);
setInstances(al.getDataSet());
// System.out.println(getInstances());
if (tableString.length() == 0) {
m_tableName = getInstances().relationName();
}
} catch (Exception ex) {
printException(ex);
ex.printStackTrace();
}
}
tmpStr = Utils.getOption("custom-props", options);
if (tmpStr.length() == 0) {
setCustomPropsFile(null);
} else {
setCustomPropsFile(new File(tmpStr));
}
Utils.checkForRemainingOptions(options);
}
/**
* Lists the available options.
*
* @return an enumeration of the available options
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> newVector = new Vector<Option>();
newVector.addElement(new Option("\tThe JDBC URL to connect to.\n"
+ "\t(default: from DatabaseUtils.props file)", "url", 1,
"-url <JDBC URL>"));
newVector.addElement(new Option(
"\tThe user to connect with to the database.\n" + "\t(default: none)",
"user", 1, "-user <name>"));
newVector
.addElement(new Option(
"\tThe password to connect with to the database.\n"
+ "\t(default: none)", "password", 1, "-password <password>"));
newVector.addElement(new Option("\tThe name of the table.\n"
+ "\t(default: the relation name)", "T", 1, "-T <table name>"));
newVector.addElement(new Option(
"\tTruncate (i.e. delete any data) in table before inserting",
"truncate", 0, "-truncate"));
newVector.addElement(new Option(
"\tAdd an ID column as primary key. The name is specified\n"
+ "\tin the DatabaseUtils file ('idColumn'). The DatabaseLoader\n"
+ "\twon't load this column.", "P", 0, "-P"));
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>"));
newVector.addElement(new Option(
"\tInput file in arff format that should be saved in database.", "i", 1,
"-i <input file name>"));
return newVector.elements();
}
/**
* 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/DictionarySaver.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/>.
*/
/*
* DictionarySaver.java
* Copyright (C) 2015 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.converters;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import weka.core.Capabilities;
import weka.core.DictionaryBuilder;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.OptionMetadata;
import weka.core.RevisionUtils;
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;
/**
* <!-- globalinfo-start --> Writes a dictionary constructed from string
* attributes in incoming instances to a destination. <br>
* <br>
* <!-- globalinfo-end -->
*
* <!-- options-start --> Valid options are:
* <p>
*
* <pre>
* -binary-dict
* Save as a binary serialized dictionary
* </pre>
*
* <pre>
* -R <range>
* Specify range of attributes to act on. This is a comma separated list of attribute
* indices, with "first" and "last" valid values.
* </pre>
*
* <pre>
* -V
* Set attributes selection mode. If false, only selected attributes in the range will
* be worked on. If true, only non-selected attributes will be processed
* </pre>
*
* <pre>
* -L
* Convert all tokens to lowercase when matching against dictionary entries.
* </pre>
*
* <pre>
* -stemmer <spec>
* The stemming algorithm (classname plus parameters) to use.
* </pre>
*
* <pre>
* -stopwords-handler <spec>
* The stopwords handler to use (default = Null)
* </pre>
*
* <pre>
* -tokenizer <spec>
* The tokenizing algorithm (classname plus parameters) to use.
* (default: weka.core.tokenizers.WordTokenizer)
* </pre>
*
* <pre>
* -P <integer>
* Prune the dictionary every x instances
* (default = 0 - i.e. no periodic pruning)
* </pre>
*
* <pre>
* -W <integer>
* The number of words (per class if there is a class attribute assigned) to attempt to keep.
* </pre>
*
* <pre>
* -M <integer>
* The minimum term frequency to use when pruning the dictionary
* (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>
* -sort
* Sort the dictionary alphabetically
* </pre>
*
* <pre>
* -i <the input file>
* The input file
* </pre>
*
* <pre>
* -o <the output file>
* The output file
* </pre>
*
* <!-- options-end -->
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision$
*/
public class DictionarySaver extends AbstractFileSaver implements
BatchConverter, IncrementalConverter {
private static final long serialVersionUID = -19891905988830722L;
protected transient OutputStream m_binaryStream;
/**
* The dictionary builder to use
*/
protected DictionaryBuilder m_dictionaryBuilder = new DictionaryBuilder();
/**
* Whether the dictionary file contains a binary serialized dictionary, rather
* than plain text
*/
protected boolean m_dictionaryIsBinary;
/**
* Prune the dictionary every x instances. <=0 means no periodic pruning
*/
private long m_periodicPruningRate;
public DictionarySaver() {
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 a dictionary constructed from string attributes in "
+ "incoming instances to a destination.";
}
/**
* Set whether to save the dictionary as a binary serialized dictionary,
* rather than a plain text one
*
* @param binary true if the dictionary is to be saved as binary rather than
* plain text
*/
@OptionMetadata(displayName = "Save dictionary in binary form",
description = "Save as a binary serialized dictionary",
commandLineParamName = "binary-dict",
commandLineParamSynopsis = "-binary-dict", commandLineParamIsFlag = true,
displayOrder = 2)
public void setSaveBinaryDictionary(boolean binary) {
m_dictionaryIsBinary = binary;
}
/**
* Get whether to save the dictionary as a binary serialized dictionary,
* rather than a plain text one
*
* @return true if the dictionary is to be saved as binary rather than plain
* text
*/
public boolean getSaveBinaryDictionary() {
return m_dictionaryIsBinary;
}
/**
* Gets the current range selection.
*
* @return a string containing a comma separated list of ranges
*/
public String getAttributeIndices() {
return m_dictionaryBuilder.getAttributeIndices();
}
/**
* 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
*/
@OptionMetadata(displayName = "Range of attributes to operate on",
description = "Specify range of attributes to act on. This is a comma "
+ "separated list of attribute\nindices, with \"first\" and "
+ "\"last\" valid values.", commandLineParamName = "R",
commandLineParamSynopsis = "-R <range>", displayOrder = 4)
public void setAttributeIndices(String rangeList) {
m_dictionaryBuilder.setAttributeIndices(rangeList);
}
/**
* 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_dictionaryBuilder.getInvertSelection();
}
/**
* Sets whether selected columns should be processed or skipped.
*
* @param invert the new invert setting
*/
@OptionMetadata(
displayName = "Invert selection",
description = "Set attributes selection mode. "
+ "If false, only selected attributes in the range will\nbe worked on. If true, "
+ "only non-selected attributes will be processed",
commandLineParamName = "V", commandLineParamSynopsis = "-V",
commandLineParamIsFlag = true, displayOrder = 5)
public
void setInvertSelection(boolean invert) {
m_dictionaryBuilder.setInvertSelection(invert);
}
/**
* Gets whether if the tokens are to be downcased or not.
*
* @return true if the tokens are to be downcased.
*/
public boolean getLowerCaseTokens() {
return m_dictionaryBuilder.getLowerCaseTokens();
}
/**
* 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.
*/
@OptionMetadata(displayName = "Lower case tokens",
description = "Convert all tokens to lowercase when matching against "
+ "dictionary entries.", commandLineParamName = "L",
commandLineParamSynopsis = "-L", commandLineParamIsFlag = true,
displayOrder = 10)
public void setLowerCaseTokens(boolean downCaseTokens) {
m_dictionaryBuilder.setLowerCaseTokens(downCaseTokens);
}
/**
* 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
*/
@OptionMetadata(displayName = "Stemmer to use",
description = "The stemming algorithm (classname plus parameters) to use.",
commandLineParamName = "stemmer",
commandLineParamSynopsis = "-stemmer <spec>", displayOrder = 11)
public void setStemmer(Stemmer value) {
if (value != null) {
m_dictionaryBuilder.setStemmer(value);
} else {
m_dictionaryBuilder.setStemmer(new NullStemmer());
}
}
/**
* Returns the current stemming algorithm, null if none is used.
*
* @return the current stemming algorithm, null if none set
*/
public Stemmer getStemmer() {
return m_dictionaryBuilder.getStemmer();
}
/**
* Sets the stopwords handler to use.
*
* @param value the stopwords handler, if null, Null is used
*/
@OptionMetadata(displayName = "Stop words handler",
description = "The stopwords handler to use (default = Null)",
commandLineParamName = "stopwords-handler",
commandLineParamSynopsis = "-stopwords-handler <spec>", displayOrder = 12)
public void setStopwordsHandler(StopwordsHandler value) {
if (value != null) {
m_dictionaryBuilder.setStopwordsHandler(value);
} else {
m_dictionaryBuilder.setStopwordsHandler(new Null());
}
}
/**
* Gets the stopwords handler.
*
* @return the stopwords handler
*/
public StopwordsHandler getStopwordsHandler() {
return m_dictionaryBuilder.getStopwordsHandler();
}
/**
* the tokenizer algorithm to use.
*
* @param value the configured tokenizing algorithm
*/
@OptionMetadata(
displayName = "Tokenizer",
description = "The tokenizing algorithm (classname plus parameters) to use.\n"
+ "(default: weka.core.tokenizers.WordTokenizer)",
commandLineParamName = "tokenizer",
commandLineParamSynopsis = "-tokenizer <spec>", displayOrder = 13)
public
void setTokenizer(Tokenizer value) {
m_dictionaryBuilder.setTokenizer(value);
}
/**
* Returns the current tokenizer algorithm.
*
* @return the current tokenizer algorithm
*/
public Tokenizer getTokenizer() {
return m_dictionaryBuilder.getTokenizer();
}
/**
* Gets the rate at which the dictionary is periodically pruned, as a
* percentage of the dataset size.
*
* @return the rate at which the dictionary is periodically pruned
*/
public long getPeriodicPruning() {
return m_periodicPruningRate;
}
/**
* Sets the rate at which the dictionary is periodically pruned, as a
* percentage of the dataset size.
*
* @param newPeriodicPruning the rate at which the dictionary is periodically
* pruned
*/
@OptionMetadata(
displayName = "Periodic pruning rate",
description = "Prune the "
+ "dictionary every x instances\n(default = 0 - i.e. no periodic pruning)",
commandLineParamName = "P", commandLineParamSynopsis = "-P <integer>",
displayOrder = 14)
public
void setPeriodicPruning(long newPeriodicPruning) {
m_periodicPruningRate = newPeriodicPruning;
}
/**
* 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_dictionaryBuilder.getWordsToKeep();
}
/**
* 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).
*/
@OptionMetadata(
displayName = "Number of words to attempt to keep",
description = "The number of words (per class if there is a class attribute "
+ "assigned) to attempt to keep.", commandLineParamName = "W",
commandLineParamSynopsis = "-W <integer>", displayOrder = 15)
public
void setWordsToKeep(int newWordsToKeep) {
m_dictionaryBuilder.setWordsToKeep(newWordsToKeep);
}
/**
* Get the MinTermFreq value.
*
* @return the MinTermFreq value.
*/
public int getMinTermFreq() {
return m_dictionaryBuilder.getMinTermFreq();
}
/**
* Set the MinTermFreq value.
*
* @param newMinTermFreq The new MinTermFreq value.
*/
@OptionMetadata(
displayName = "Minimum term frequency",
description = "The minimum term frequency to use when pruning the dictionary\n"
+ "(default = 1).", commandLineParamName = "M",
commandLineParamSynopsis = "-M <integer>", displayOrder = 16)
public
void setMinTermFreq(int newMinTermFreq) {
m_dictionaryBuilder.setMinTermFreq(newMinTermFreq);
}
/**
* Get the DoNotOperateOnPerClassBasis value.
*
* @return the DoNotOperateOnPerClassBasis value.
*/
public boolean getDoNotOperateOnPerClassBasis() {
return m_dictionaryBuilder.getDoNotOperateOnPerClassBasis();
}
/**
* Set the DoNotOperateOnPerClassBasis value.
*
* @param newDoNotOperateOnPerClassBasis The new DoNotOperateOnPerClassBasis
* value.
*/
@OptionMetadata(displayName = "Do not operate on a per-class basis",
description = "If this is set, the maximum number of words and the\n"
+ "minimum term frequency is not enforced on a per-class\n"
+ "basis but based on the documents in all the classes\n"
+ "(even if a class attribute is set).", commandLineParamName = "O",
commandLineParamSynopsis = "-O", commandLineParamIsFlag = true,
displayOrder = 17)
public void setDoNotOperateOnPerClassBasis(
boolean newDoNotOperateOnPerClassBasis) {
m_dictionaryBuilder
.setDoNotOperateOnPerClassBasis(newDoNotOperateOnPerClassBasis);
}
/**
* Set whether to keep the dictionary sorted alphabetically or not
*
* @param sorted true to keep the dictionary sorted
*/
@OptionMetadata(displayName = "Sort dictionary",
description = "Sort the dictionary alphabetically",
commandLineParamName = "sort", commandLineParamSynopsis = "-sort",
commandLineParamIsFlag = true, displayOrder = 18)
public void setKeepDictionarySorted(boolean sorted) {
m_dictionaryBuilder.setSortDictionary(sorted);
}
/**
* Get whether to keep the dictionary sorted alphabetically or not
*
* @return true to keep the dictionary sorted
*/
public boolean getKeepDictionarySorted() {
return m_dictionaryBuilder.getSortDictionary();
}
/**
* 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(Capabilities.Capability.NOMINAL_ATTRIBUTES);
result.enable(Capabilities.Capability.NUMERIC_ATTRIBUTES);
result.enable(Capabilities.Capability.DATE_ATTRIBUTES);
result.enable(Capabilities.Capability.STRING_ATTRIBUTES);
result.enable(Capabilities.Capability.MISSING_VALUES);
// class
result.enable(Capabilities.Capability.NOMINAL_CLASS);
result.enable(Capabilities.Capability.NUMERIC_CLASS);
result.enable(Capabilities.Capability.DATE_CLASS);
result.enable(Capabilities.Capability.STRING_CLASS);
result.enable(Capabilities.Capability.MISSING_CLASS_VALUES);
result.enable(Capabilities.Capability.NO_CLASS);
return result;
}
@Override
public String getFileDescription() {
return "Plain text or binary serialized dictionary files created from text "
+ "in string attributes";
}
@Override
public void writeIncremental(Instance inst) throws IOException {
int writeMode = getWriteMode();
Instances structure = getInstances();
if (getRetrieval() == BATCH || getRetrieval() == NONE) {
throw new IOException("Batch and incremental saving cannot be mixed.");
}
if (writeMode == WAIT) {
if (structure == null) {
setWriteMode(CANCEL);
if (inst != null) {
throw new IOException("Structure (header Information) has to be set "
+ "in advance");
}
} else {
setWriteMode(STRUCTURE_READY);
}
writeMode = getWriteMode();
}
if (writeMode == CANCEL) {
cancel();
}
if (writeMode == STRUCTURE_READY) {
m_dictionaryBuilder.reset();
try {
m_dictionaryBuilder.setup(structure);
} catch (Exception ex) {
throw new IOException(ex);
}
setWriteMode(WRITE);
writeMode = getWriteMode();
}
if (writeMode == WRITE) {
if (structure == null) {
throw new IOException("No instances information available.");
}
if (inst != null) {
m_dictionaryBuilder.processInstance(inst);
} else {
try {
m_dictionaryBuilder.finalizeDictionary();
} catch (Exception e) {
throw new IOException(e);
}
if (retrieveFile() == null && getWriter() == null) {
if (getSaveBinaryDictionary()) {
throw new IOException(
"Can't output binary dictionary to standard out!");
}
m_dictionaryBuilder.saveDictionary(System.out);
} else {
if (getSaveBinaryDictionary()) {
m_dictionaryBuilder.saveDictionary(m_binaryStream);
} else {
m_dictionaryBuilder.saveDictionary(getWriter());
}
}
resetStructure();
resetWriter();
}
}
}
@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);
m_dictionaryBuilder.reset();
try {
m_dictionaryBuilder.setup(getInstances());
} catch (Exception ex) {
throw new IOException(ex);
}
for (int i = 0; i < getInstances().numInstances(); i++) {
m_dictionaryBuilder.processInstance(getInstances().instance(i));
}
try {
m_dictionaryBuilder.finalizeDictionary();
} catch (Exception ex) {
throw new IOException(ex);
}
if (retrieveFile() == null && getWriter() == null) {
if (getSaveBinaryDictionary()) {
throw new IOException("Can't output binary dictionary to standard out!");
}
m_dictionaryBuilder.saveDictionary(System.out);
setWriteMode(WAIT);
return;
}
if (getSaveBinaryDictionary()) {
m_dictionaryBuilder.saveDictionary(m_binaryStream);
} else {
m_dictionaryBuilder.saveDictionary(getWriter());
}
setWriteMode(WAIT);
resetWriter();
setWriteMode(CANCEL);
}
@Override
public void resetOptions() {
super.resetOptions();
setFileExtension(".dict");
}
@Override
public void resetWriter() {
super.resetWriter();
m_binaryStream = null;
}
@Override
public void setDestination(OutputStream output) throws IOException {
super.setDestination(output);
m_binaryStream = new BufferedOutputStream(output);
}
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
public static void main(String[] args) {
runFileSaver(new DictionarySaver(), 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/FileSourcedConverter.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/>.
*/
/*
* FileSourcedConverter.java
* Copyright (C) 2004-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.converters;
import java.io.File;
import java.io.IOException;
/**
* Interface to a loader/saver that loads/saves from a file source.
*
* @author Mark Hall
* @version $Revision$
*/
public interface FileSourcedConverter {
/**
* Get the file extension used for this type of file
*
* @return the file extension
*/
public String getFileExtension();
/**
* Gets all the file extensions used for this type of file
*
* @return the file extensions
*/
public String[] getFileExtensions();
/**
* Get a one line description of the type of file
*
* @return a description of the file type
*/
public String getFileDescription();
/**
* Set the file to load from/ to save in
*
* @param file the file to load from
* @exception IOException if an error occurs
*/
public void setFile(File file) throws IOException;
/**
* Return the current source file/ destination file
*
* @return a <code>File</code> value
*/
public File retrieveFile();
/**
* Set whether to use relative rather than absolute paths
*
* @param rp true if relative paths are to be used
*/
public void setUseRelativePath(boolean rp);
/**
* Gets whether relative paths are to be used
*
* @return true if relative paths are to be used
*/
public boolean getUseRelativePath();
}
|
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/IncrementalConverter.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/>.
*/
/*
* IncremenalConverter.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 incrementally
*
* @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a>
* @version $Revision 1.0 $
*/
public interface IncrementalConverter {
}
|
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/JSONLoader.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/>.
*/
/*
* JSONLoader.java
* Copyright (C) 2009-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.converters;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.util.zip.GZIPInputStream;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.RevisionUtils;
import weka.core.json.JSONInstances;
import weka.core.json.JSONNode;
/**
<!-- globalinfo-start -->
* Reads a source that is in the JSON format.<br/>
* It automatically decompresses the data if the extension is '.json.gz'.<br/>
* <br/>
* For more information, see JSON homepage:<br/>
* http://www.json.org/
* <p/>
<!-- globalinfo-end -->
*
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision$
* @see Loader
*/
public class JSONLoader
extends AbstractFileLoader
implements BatchConverter, URLSourcedLoader {
/** for serialization. */
private static final long serialVersionUID = 3764533621135196582L;
/** the file extension. */
public static String FILE_EXTENSION = ".json";
/** the extension for compressed files. */
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 loaded JSON object. */
protected JSONNode m_JSON;
/**
* 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 the JSON format.\n"
+ "It automatically decompresses the data if the extension is '"
+ FILE_EXTENSION_COMPRESSED + "'.\n\n"
+ "For more information, see JSON homepage:\n"
+ "http://www.json.org/";
}
/**
* Get the file extension used for JSON files.
*
* @return the file extension
*/
public String getFileExtension() {
return FILE_EXTENSION;
}
/**
* Gets all the file extensions used for this type of file.
*
* @return the file extensions
*/
public String[] getFileExtensions() {
return new String[]{FILE_EXTENSION, FILE_EXTENSION_COMPRESSED};
}
/**
* Returns a description of the file type.
*
* @return a short file description
*/
public String getFileDescription() {
return "JSON Instances files";
}
/**
* Resets the Loader ready to read a new data set.
*
* @throws IOException if something goes wrong
*/
public void reset() throws IOException {
m_structure = null;
m_JSON = null;
setRetrieval(NONE);
if (m_File != null) {
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 File object.
*
* @param file the source file.
* @throws IOException if an error occurs
*/
public void setSource(File file) throws IOException {
m_structure = null;
m_JSON = null;
setRetrieval(NONE);
if (file == null)
throw new IOException("Source file object is null!");
try {
if (file.getName().endsWith(FILE_EXTENSION_COMPRESSED))
setSource(new GZIPInputStream(new FileInputStream(file)));
else
setSource(new FileInputStream(file));
}
catch (FileNotFoundException ex) {
throw new IOException("File not found");
}
m_sourceFile = file;
m_File = file.getAbsolutePath();
}
/**
* 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;
m_JSON = null;
setRetrieval(NONE);
setSource(url.openStream());
m_URL = url.toString();
}
/**
* Set the url to load from.
*
* @param url the url to load from
* @throws IOException if the url can't be set.
*/
public void setURL(String url) throws IOException {
m_URL = url;
setSource(new URL(url));
}
/**
* Return the current url.
*
* @return the current url
*/
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 if initialization of reader fails.
*/
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
*/
public Instances getStructure() throws IOException {
if (m_sourceReader == null)
throw new IOException("No source has been specified");
if (m_structure == null) {
try {
m_JSON = JSONNode.read(m_sourceReader);
m_structure = new Instances(JSONInstances.toHeader(m_JSON), 0);
}
catch (IOException ioe) {
// just re-throw it
throw ioe;
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
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
*/
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();
try {
// close the stream
m_sourceReader.close();
} catch (Exception ex) {
}
return JSONInstances.toInstances(m_JSON);
}
/**
* JSONLoader is unable to process a data set incrementally.
*
* @param structure ignored
* @return never returns without throwing an exception
* @throws IOException always. JSONLoader is unable to process a
* data set incrementally.
*/
public Instance getNextInstance(Instances structure) throws IOException {
throw new IOException("JSONLoader can't read data sets incrementally.");
}
/**
* Returns the revision string.
*
* @return the revision
*/
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 JSONLoader(), 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/JSONSaver.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/>.
*/
/*
* JSONSaver.java
* Copyright (C) 2009-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.Capabilities;
import weka.core.Capabilities.Capability;
import weka.core.Instances;
import weka.core.Option;
import weka.core.RevisionUtils;
import weka.core.SingleIndex;
import weka.core.Utils;
import weka.core.json.JSONInstances;
import weka.core.json.JSONNode;
/**
* <!-- globalinfo-start --> Writes to a destination that is in JSON format.<br/>
* The data can be compressed with gzip, in order to save space.<br/>
* <br/>
* For more information, see JSON homepage:<br/>
* http://www.json.org/
* <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 <class index>
* The class index (first and last are valid as well).
* (default: last)
* </pre>
*
* <pre>
* -compress
* Compresses the data (uses '.json.gz' as extension instead of '.json')
* (default: off)
* </pre>
*
* <!-- options-end -->
*
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision$
* @see Saver
*/
public class JSONSaver extends AbstractFileSaver implements BatchConverter {
/** for serialization. */
private static final long serialVersionUID = -1047134047244534557L;
/** the class index. */
protected SingleIndex m_ClassIndex = new SingleIndex();
/** whether to compress the output. */
protected boolean m_CompressOutput = false;
/**
* Constructor.
*/
public JSONSaver() {
this.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 JSON format.\n" + "The data can be compressed with gzip, in order to save space.\n\n" + "For more information, see JSON homepage:\n" + "http://www.json.org/";
}
/**
* 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 index (first and last are valid as well).\n" + "\t(default: last)", "C", 1, "-C <class index>"));
result.addElement(new Option("\tCompresses the data (uses '" + JSONLoader.FILE_EXTENSION_COMPRESSED + "' as extension instead of '" + JSONLoader.FILE_EXTENSION + "')\n" + "\t(default: off)", "compress", 0, "-compress"));
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 (this.getClassIndex().length() != 0) {
result.add("-C");
result.add(this.getClassIndex());
}
if (this.getCompressOutput()) {
result.add("-compress");
}
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>
* -C <class index>
* The class index (first and last are valid as well).
* (default: last)
* </pre>
*
* <pre>
* -compress
* Compresses the data (uses '.json.gz' as extension instead of '.json')
* (default: off)
* </pre>
*
* <!-- options-end -->
*
* @param options the options to use
* @throws Exception if setting of options fails
*/
@Override
public void setOptions(final String[] options) throws Exception {
String tmpStr;
tmpStr = Utils.getOption('C', options);
if (tmpStr.length() != 0) {
this.setClassIndex(tmpStr);
} else {
this.setClassIndex("last");
}
this.setCompressOutput(Utils.getFlag("compress", options));
super.setOptions(options);
Utils.checkForRemainingOptions(options);
}
/**
* Returns a description of the file type.
*
* @return a short file description
*/
@Override
public String getFileDescription() {
return "JSON data files";
}
/**
* Gets all the file extensions used for this type of file.
*
* @return the file extensions
*/
@Override
public String[] getFileExtensions() {
return new String[] { JSONLoader.FILE_EXTENSION, JSONLoader.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(final File outputFile) throws IOException {
if (outputFile.getAbsolutePath().endsWith(JSONLoader.FILE_EXTENSION_COMPRESSED)) {
this.setCompressOutput(true);
}
super.setFile(outputFile);
}
/**
* Resets the Saver.
*/
@Override
public void resetOptions() {
super.resetOptions();
if (this.getCompressOutput()) {
this.setFileExtension(JSONLoader.FILE_EXTENSION_COMPRESSED);
} else {
this.setFileExtension(JSONLoader.FILE_EXTENSION);
}
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String classIndexTipText() {
return "Sets the class index (\"first\" and \"last\" are valid values)";
}
/**
* Get the index of the class attribute.
*
* @return the index of the class attribute
*/
public String getClassIndex() {
return this.m_ClassIndex.getSingleIndex();
}
/**
* Sets index of the class attribute.
*
* @param value the index of the class attribute
*/
public void setClassIndex(final String value) {
this.m_ClassIndex.setSingleIndex(value);
}
/**
* 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 this.m_CompressOutput;
}
/**
* Sets whether to compress the output.
*
* @param value if truee the output will be compressed
*/
public void setCompressOutput(final boolean value) {
this.m_CompressOutput = value;
}
/**
* 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;
}
/**
* Sets instances that should be stored.
*
* @param instances the instances
* @throws InterruptedException
*/
@Override
public void setInstances(final Instances instances) throws InterruptedException {
if (this.m_ClassIndex.getSingleIndex().length() != 0) {
this.m_ClassIndex.setUpper(instances.numAttributes() - 1);
instances.setClassIndex(this.m_ClassIndex.getIndex());
}
super.setInstances(instances);
}
/**
* Sets the destination output stream.
*
* @param output the output stream.
* @throws IOException throws an IOException if destination cannot be set
*/
@Override
public void setDestination(final OutputStream output) throws IOException {
if (this.getCompressOutput()) {
super.setDestination(new GZIPOutputStream(output));
} else {
super.setDestination(output);
}
}
/**
* Writes a Batch of instances.
*
* @throws IOException throws IOException if saving in batch mode is not
* possible
*/
@Override
public void writeBatch() throws IOException {
if (this.getInstances() == null) {
throw new IOException("No instances to save");
}
if (this.getRetrieval() == INCREMENTAL) {
throw new IOException("Batch and incremental saving cannot be mixed.");
}
this.setRetrieval(BATCH);
this.setWriteMode(WRITE);
PrintWriter outW;
if ((this.retrieveFile() == null) && (this.getWriter() == null)) {
outW = new PrintWriter(System.out);
} else {
outW = new PrintWriter(this.getWriter());
}
JSONNode json = JSONInstances.toJSON(this.getInstances());
StringBuffer buffer = new StringBuffer();
json.toString(buffer);
outW.println(buffer.toString());
outW.flush();
if (this.getWriter() != null) {
outW.close();
}
this.setWriteMode(WAIT);
outW = null;
this.resetWriter();
this.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(final String[] args) {
runFileSaver(new JSONSaver(), 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/LibSVMLoader.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/>.
*/
/*
* LibSVMLoader.java
* Copyright (C) 2006-2012 University of Waikato, Hamilton, NZ
*
*/
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.net.URL;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.util.Vector;
import weka.core.Attribute;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.RevisionUtils;
import weka.core.SparseInstance;
/**
* <!-- globalinfo-start --> Reads a source that is in libsvm format.<br/>
* <br/>
* For more information about libsvm see:<br/>
* <br/>
* http://www.csie.ntu.edu.tw/~cjlin/libsvm/
* <p/>
* <!-- globalinfo-end -->
*
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision$
* @see Loader
*/
public class LibSVMLoader
extends AbstractFileLoader
implements BatchConverter, URLSourcedLoader {
/** for serialization. */
private static final long serialVersionUID = 4988360125354664417L;
/** the file extension. */
public static String FILE_EXTENSION = ".libsvm";
/** the url. */
protected String m_URL = "http://";
/** The reader for the source file. */
protected transient Reader m_sourceReader = null;
/** the buffer of the rows read so far. */
protected Vector<double[]> m_Buffer = null;
/**
* 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 libsvm format.\n\n"
+ "For more information about libsvm see:\n\n"
+ "http://www.csie.ntu.edu.tw/~cjlin/libsvm/";
}
/**
* Get the file extension used for libsvm 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[] { getFileExtension() };
}
/**
* Returns a description of the file type.
*
* @return a short file description
*/
@Override
public String getFileDescription() {
return "libsvm data files";
}
/**
* 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;
m_Buffer = null;
setRetrieval(NONE);
if ((m_File != null) && (new File(m_File)).isFile()) {
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;
m_Buffer = null;
setRetrieval(NONE);
setSource(url.openStream());
m_URL = url.toString();
}
/**
* 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 if initialization of reader fails.
*/
@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));
}
/**
* turns a libsvm row into a double array with the class as the last entry.
*
* @param row the row to turn into a double array
* @return the corresponding double array
*/
protected double[] libsvmToArray(String row) {
double[] result;
StringTokenizer tok;
int index;
int max;
String col;
double value;
// determine max index
max = 0;
tok = new StringTokenizer(row, " \t");
tok.nextToken(); // skip class
while (tok.hasMoreTokens()) {
col = tok.nextToken();
index = Integer.parseInt(col.substring(0, col.indexOf(":")));
if (index > max) {
max = index;
}
}
// read values into array
tok = new StringTokenizer(row, " \t");
result = new double[max + 1];
// 1. class
result[result.length - 1] = Double.parseDouble(tok.nextToken());
// 2. attributes
while (tok.hasMoreTokens()) {
col = tok.nextToken();
index = Integer.parseInt(col.substring(0, col.indexOf(":")));
value = Double.parseDouble(col.substring(col.indexOf(":") + 1));
result[index - 1] = value;
}
return result;
}
/**
* determines the number of attributes, if the number of attributes in the
* given row is greater than the current amount then this number will be
* returned, otherwise the current number.
*
* @param row row to determine the number of attributes from
* @param num the current number of attributes
* @return the new number of attributes
*/
protected int determineNumAttributes(String row, int num) {
int result;
int count;
result = num;
count = libsvmToArray(row).length;
if (count > result) {
result = count;
}
return result;
}
/**
* 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 {
String line;
int cInt;
char c;
int numAtt;
ArrayList<Attribute> atts;
int i;
String relName;
if (m_sourceReader == null) {
throw new IOException("No source has been specified");
}
if (m_structure == null) {
m_Buffer = new Vector<double[]>();
try {
// determine number of attributes
numAtt = 0;
int len = 1024 * 1024 * 8; // 8 MB
char[] cbuf = new char[len];
int iter = 0;
String linesplitter = null;
String[] lines;
String oldLine = null;
String read = null;
while ((cInt = m_sourceReader.read(cbuf, 0, len)) != -1) {
read = String.valueOf(cbuf, 0, cInt);
if (oldLine != null) {
read = oldLine + read;
}
if (linesplitter == null) {
if (read.contains("\r\n")) {
linesplitter = "\r\n";
} else if (read.contains("\n")) {
linesplitter = "\n";
}
}
if (linesplitter != null) {
lines = read.split(linesplitter, -1);
} else {
lines = new String[] { read };
}
for (int j = 0; j < lines.length - 1; j++) {
line = lines[j];
m_Buffer.add(libsvmToArray(line));
numAtt = determineNumAttributes(line, numAtt);
}
oldLine = lines[lines.length - 1];
}
// last line?
if (oldLine != null && oldLine.length() != 0) {
m_Buffer.add(libsvmToArray(oldLine));
numAtt = determineNumAttributes(oldLine, numAtt);
}
// generate header
atts = new ArrayList<Attribute>(numAtt);
for (i = 0; i < numAtt - 1; i++) {
atts.add(new Attribute("att_" + (i + 1)));
}
atts.add(new Attribute("class"));
if (!m_URL.equals("http://")) {
relName = m_URL;
} else {
relName = m_File;
}
m_structure = new Instances(relName, atts, 0);
m_structure.setClassIndex(m_structure.numAttributes() - 1);
} catch (Exception ex) {
ex.printStackTrace();
throw new IOException("Unable to determine structure as libsvm: " + ex);
}
}
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 result;
double[] sparse;
double[] data;
int i;
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();
}
result = new Instances(m_structure, 0);
// create instances from buffered arrays
for (i = 0; i < m_Buffer.size(); i++) {
sparse = m_Buffer.get(i);
if (sparse.length != m_structure.numAttributes()) {
data = new double[m_structure.numAttributes()];
// attributes
System.arraycopy(sparse, 0, data, 0, sparse.length - 1);
// class
data[data.length - 1] = sparse[sparse.length - 1];
}
else {
data = sparse;
}
result.add(new SparseInstance(1, data));
}
try {
// close the stream
m_sourceReader.close();
} catch (Exception ex) {
}
return result;
}
/**
* LibSVmLoader is unable to process a data set incrementally.
*
* @param structure ignored
* @return never returns without throwing an exception
* @throws IOException always. LibSVMLoader is unable to process a data set
* incrementally.
*/
@Override
public Instance getNextInstance(Instances structure) throws IOException {
throw new IOException("LibSVMLoader can't read data sets incrementally.");
}
/**
* 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 LibSVMLoader(), 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/LibSVMSaver.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/>.
*/
/*
* LibSVMSaver.java
* Copyright (C) 2006-2012 University of Waikato, Hamilton, NZ
*
*/
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.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.SingleIndex;
import weka.core.Utils;
/**
* <!-- globalinfo-start --> Writes to a destination that is in libsvm format.<br/>
* <br/>
* For more information about libsvm see:<br/>
* <br/>
* http://www.csie.ntu.edu.tw/~cjlin/libsvm/
* <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 <class index>
* The class index
* (default: last)
* </pre>
*
* <!-- options-end -->
*
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision$
* @see Saver
*/
public class LibSVMSaver extends AbstractFileSaver implements BatchConverter, IncrementalConverter {
/** for serialization */
private static final long serialVersionUID = 2792295817125694786L;
/** the file extension */
public static String FILE_EXTENSION = LibSVMLoader.FILE_EXTENSION;
/** the class index */
protected SingleIndex m_ClassIndex = new SingleIndex("last");
/**
* Constructor
*/
public LibSVMSaver() {
this.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 libsvm format.\n\n" + "For more information about libsvm see:\n\n" + "http://www.csie.ntu.edu.tw/~cjlin/libsvm/";
}
/**
* 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 index\n" + "\t(default: last)", "c", 1, "-c <class index>"));
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>();
result.add("-c");
result.add(this.getClassIndex());
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>
* -c <class index>
* The class index
* (default: last)
* </pre>
*
* <!-- options-end -->
*
* @param options the options to use
* @throws Exception if setting of options fails
*/
@Override
public void setOptions(final String[] options) throws Exception {
String tmpStr;
tmpStr = Utils.getOption('c', options);
if (tmpStr.length() != 0) {
this.setClassIndex(tmpStr);
} else {
this.setClassIndex("last");
}
super.setOptions(options);
Utils.checkForRemainingOptions(options);
}
/**
* Returns a description of the file type.
*
* @return a short file description
*/
@Override
public String getFileDescription() {
return "libsvm data files";
}
/**
* Resets the Saver
*/
@Override
public void resetOptions() {
super.resetOptions();
this.setFileExtension(LibSVMLoader.FILE_EXTENSION);
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String classIndexTipText() {
return "Sets the class index (\"first\" and \"last\" are valid values)";
}
/**
* Get the index of the class attribute.
*
* @return the index of the class attribute
*/
public String getClassIndex() {
return this.m_ClassIndex.getSingleIndex();
}
/**
* Sets index of the class attribute.
*
* @param value the index of the class attribute
*/
public void setClassIndex(final String value) {
this.m_ClassIndex.setSingleIndex(value);
}
/**
* 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);
// class
result.enable(Capability.NOMINAL_CLASS);
result.enable(Capability.NUMERIC_CLASS);
result.enable(Capability.DATE_CLASS);
return result;
}
/**
* Sets instances that should be stored.
*
* @param instances the instances
* @throws InterruptedException
*/
@Override
public void setInstances(final Instances instances) throws InterruptedException {
this.m_ClassIndex.setUpper(instances.numAttributes() - 1);
instances.setClassIndex(this.m_ClassIndex.getIndex());
super.setInstances(instances);
}
/**
* turns the instance into a libsvm row
*
* @param inst the instance to transform
* @return the generated libsvm row
*/
protected String instanceToLibsvm(final Instance inst) {
StringBuffer result;
int i;
// class
result = new StringBuffer("" + inst.classValue());
// attributes
for (i = 0; i < inst.numAttributes(); i++) {
if (i == inst.classIndex()) {
continue;
}
if (inst.value(i) == 0) {
continue;
}
result.append(" " + (i + 1) + ":" + inst.value(i));
}
return result.toString();
}
/**
* 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(final Instance inst) throws IOException {
int writeMode = this.getWriteMode();
Instances structure = this.getInstances();
PrintWriter outW = null;
if ((this.getRetrieval() == BATCH) || (this.getRetrieval() == NONE)) {
throw new IOException("Batch and incremental saving cannot be mixed.");
}
if (this.getWriter() != null) {
outW = new PrintWriter(this.getWriter());
}
if (writeMode == WAIT) {
if (structure == null) {
this.setWriteMode(CANCEL);
if (inst != null) {
System.err.println("Structure (Header Information) has to be set in advance");
}
} else {
this.setWriteMode(STRUCTURE_READY);
}
writeMode = this.getWriteMode();
}
if (writeMode == CANCEL) {
if (outW != null) {
outW.close();
}
this.cancel();
}
// header
if (writeMode == STRUCTURE_READY) {
this.setWriteMode(WRITE);
// no header
writeMode = this.getWriteMode();
}
// row
if (writeMode == WRITE) {
if (structure == null) {
throw new IOException("No instances information available.");
}
if (inst != null) {
// write instance
if ((this.retrieveFile() == null) && (outW == null)) {
System.out.println(this.instanceToLibsvm(inst));
} else {
outW.println(this.instanceToLibsvm(inst));
this.m_incrementalCounter++;
// flush every 100 instances
if (this.m_incrementalCounter > 100) {
this.m_incrementalCounter = 0;
outW.flush();
}
}
} else {
// close
if (outW != null) {
outW.flush();
outW.close();
}
this.m_incrementalCounter = 0;
this.resetStructure();
outW = null;
this.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 (this.getInstances() == null) {
throw new IOException("No instances to save");
}
if (this.getRetrieval() == INCREMENTAL) {
throw new IOException("Batch and incremental saving cannot be mixed.");
}
this.setRetrieval(BATCH);
this.setWriteMode(WRITE);
if ((this.retrieveFile() == null) && (this.getWriter() == null)) {
for (int i = 0; i < this.getInstances().numInstances(); i++) {
System.out.println(this.instanceToLibsvm(this.getInstances().instance(i)));
}
this.setWriteMode(WAIT);
} else {
PrintWriter outW = new PrintWriter(this.getWriter());
for (int i = 0; i < this.getInstances().numInstances(); i++) {
outW.println(this.instanceToLibsvm(this.getInstances().instance(i)));
}
outW.flush();
outW.close();
this.setWriteMode(WAIT);
outW = null;
this.resetWriter();
this.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(final String[] args) {
runFileSaver(new LibSVMSaver(), 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/Loader.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/>.
*/
/*
* Loader.java
* Copyright (C) 2000-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.converters;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.RevisionHandler;
/**
* Interface to something that can load Instances from an input source in some
* format.
*
* @author Mark Hall (mhall@cs.waikato.ac.nz)
* @version $Revision$
*/
public interface Loader extends Serializable, RevisionHandler {
/**
* Exception that implementers can throw from getStructure() when they have
* not been configured sufficiently in order to read the structure (or data).
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
*/
public static class StructureNotReadyException extends IOException {
/**
* For Serialization
*/
private static final long serialVersionUID = 1938493033987645828L;
public StructureNotReadyException(String message) {
super(message);
}
}
/** The retrieval modes */
public static final int NONE = 0;
public static final int BATCH = 1;
public static final int INCREMENTAL = 2;
/**
* Sets the retrieval mode. Note: Some loaders may not be able to implement
* incremental loading.
*
* @param mode the retrieval mode
*/
void setRetrieval(int mode);
/**
* Resets the Loader object ready to begin loading. If there is an existing
* source, implementations should attempt to reset in such a fashion as to be
* able to load from the beginning of the source.
*
* @throws Exception if Loader can't be reset for some reason.
*/
void reset() throws Exception;
/*
* @ public model instance boolean model_structureDetermined
*
* @ initially: model_structureDetermined == false;
*
* @
*/
/*
* @ public model instance boolean model_sourceSupplied
*
* @ initially: model_sourceSupplied == false;
*
* @
*/
/**
* Resets the Loader object and sets the source of the data set to be the
* supplied File object.
*
* @param file the File
* @throws IOException if an error occurs support loading from a File.
*
* <pre>
* <jml>
* public_normal_behavior
* requires: file != null
* && (* file exists *);
* modifiable: model_sourceSupplied, model_structureDetermined;
* ensures: model_sourceSupplied == true
* && model_structureDetermined == false;
* also
* public_exceptional_behavior
* requires: file == null
* || (* file does not exist *);
* signals: (IOException);
* </jml>
* </pre>
*/
void setSource(File file) throws IOException;
/**
* Resets the Loader object and sets the source of the data set to be the
* supplied InputStream.
*
* @param input the source InputStream
* @throws IOException if this Loader doesn't support loading from a File.
*/
void setSource(InputStream input) throws IOException;
/**
* 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 there is no source or parsing fails
*
* <pre>
* <jml>
* public_normal_behavior
* requires: model_sourceSupplied == true
* && model_structureDetermined == false
* && (* successful parse *);
* modifiable: model_structureDetermined;
* ensures: \result != null
* && \result.numInstances() == 0
* && model_structureDetermined == true;
* also
* public_exceptional_behavior
* requires: model_sourceSupplied == false
* || (* unsuccessful parse *);
* signals: (IOException);
* </jml>
* </pre>
*/
Instances getStructure() throws IOException;
/**
* Return the full data set. If the structure hasn't yet been determined by a
* call to getStructure then the method should do so before processing the
* rest of the data set.
*
* @return the full data set as an Instances object
* @throws IOException if there is an error during parsing or if
* getNextInstance has been called on this source (either
* incremental or batch loading can be used, not both).
*
* <pre>
* <jml>
* public_normal_behavior
* requires: model_sourceSupplied == true
* && (* successful parse *);
* modifiable: model_structureDetermined;
* ensures: \result != null
* && \result.numInstances() >= 0
* && model_structureDetermined == true;
* also
* public_exceptional_behavior
* requires: model_sourceSupplied == false
* || (* unsuccessful parse *);
* signals: (IOException);
* </jml>
* </pre>
*/
Instances getDataSet() throws IOException;
/**
* 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
* @throws IOException if there is an error during parsing or if getDataSet
* has been called on this source (either incremental or batch
* loading can be used, not both).
*/
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/MatlabLoader.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/>.
*/
/*
* MatlabLoader.java
* Copyright (C) 2009-2012 University of Waikato, Hamilton, NZ
*
*/
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.net.URL;
import java.util.ArrayList;
import java.util.Vector;
import weka.core.Attribute;
import weka.core.DenseInstance;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.RevisionUtils;
/**
<!-- globalinfo-start -->
* Reads a Matlab file containing a single matrix in ASCII format.
* <p/>
<!-- globalinfo-end -->
*
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision$
* @see Loader
*/
public class MatlabLoader
extends AbstractFileLoader
implements BatchConverter, URLSourcedLoader {
/** for serialization. */
private static final long serialVersionUID = -8861142318612875251L;
/** the file extension. */
public static String FILE_EXTENSION = ".m";
/** the url. */
protected String m_URL = "http://";
/** The reader for the source file. */
protected transient Reader m_sourceReader = null;
/** the buffer of the rows read so far. */
protected Vector<Vector<Double>> m_Buffer = null;
/**
* 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 Matlab file containing a single matrix in ASCII format.";
}
/**
* Get the file extension used for libsvm files.
*
* @return the file extension
*/
public String getFileExtension() {
return FILE_EXTENSION;
}
/**
* Gets all the file extensions used for this type of file.
*
* @return the file extensions
*/
public String[] getFileExtensions() {
return new String[]{getFileExtension()};
}
/**
* Returns a description of the file type.
*
* @return a short file description
*/
public String getFileDescription() {
return "Matlab ASCII files";
}
/**
* Resets the Loader ready to read a new data set.
*
* @throws IOException if something goes wrong
*/
public void reset() throws IOException {
m_structure = null;
m_Buffer = null;
setRetrieval(NONE);
if ((m_File != null) && (new File(m_File)).isFile()) {
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;
m_Buffer = null;
setRetrieval(NONE);
setSource(url.openStream());
m_URL = url.toString();
}
/**
* Set the url to load from.
*
* @param url the url to load from
* @throws IOException if the url can't be set.
*/
public void setURL(String url) throws IOException {
m_URL = url;
setSource(new URL(url));
}
/**
* Return the current url.
*
* @return the current url
*/
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 if initialization of reader fails.
*/
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
*/
public Instances getStructure() throws IOException {
int numAtt;
ArrayList<Attribute> atts;
int i;
String relName;
Vector<Double> row;
int c;
char chr;
StringBuffer str;
boolean isComment;
if (m_sourceReader == null)
throw new IOException("No source has been specified");
if (m_structure == null) {
numAtt = 0;
m_Buffer = new Vector<Vector<Double>>();
row = new Vector<Double>();
str = new StringBuffer();
isComment = false;
m_Buffer.add(row);
try {
// determine number of attributes
while ((c = m_sourceReader.read()) != -1) {
chr = (char) c;
// comment found?
if (chr == '%')
isComment = true;
// end of line reached
if ((chr == '\n') || (chr == '\r')) {
isComment = false;
if (str.length() > 0)
row.add(new Double(str.toString()));
if (numAtt == 0)
numAtt = row.size();
if (row.size() > 0) {
row = new Vector<Double>();
m_Buffer.add(row);
}
str = new StringBuffer();
continue;
}
// skip till end of comment line
if (isComment)
continue;
// separator found?
if ((chr == '\t') || (chr == ' ')) {
if (str.length() > 0) {
row.add(new Double(str.toString()));
str = new StringBuffer();
}
}
else {
str.append(chr);
}
}
// last number?
if (str.length() > 0)
row.add(new Double(str.toString()));
// generate header
atts = new ArrayList<Attribute>(numAtt);
for (i = 0; i < numAtt; i++)
atts.add(new Attribute("att_" + (i+1)));
if (!m_URL.equals("http://"))
relName = m_URL;
else
relName = m_File;
m_structure = new Instances(relName, atts, 0);
m_structure.setClassIndex(m_structure.numAttributes() - 1);
}
catch (Exception ex) {
ex.printStackTrace();
throw new IOException("Unable to determine structure as Matlab ASCII file: " + ex);
}
}
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
*/
public Instances getDataSet() throws IOException {
Instances result;
Vector<Double> row;
double[] data;
int i;
int n;
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();
result = new Instances(m_structure, 0);
// create instances from buffered data
for (i = 0; i < m_Buffer.size(); i++) {
row = m_Buffer.get(i);
if (row.size() == 0)
continue;
data = new double[row.size()];
for (n = 0; n < row.size(); n++)
data[n] = row.get(n);
result.add(new DenseInstance(1.0, data));
}
// close the stream
try {
m_sourceReader.close();
}
catch (Exception ex) {
// ignored
}
return result;
}
/**
* MatlabLoader is unable to process a data set incrementally.
*
* @param structure ignored
* @return never returns without throwing an exception
* @throws IOException always. MatlabLoader is unable to process a
* data set incrementally.
*/
public Instance getNextInstance(Instances structure) throws IOException {
throw new IOException("MatlabLoader can't read data sets incrementally.");
}
/**
* Returns the revision string.
*
* @return the revision
*/
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 MatlabLoader(), 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/MatlabSaver.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/>.
*/
/*
* MatlabSaver.java
* Copyright (C) 2009-2012 University of Waikato, Hamilton, NZ
*
*/
package weka.core.converters;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Vector;
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;
import weka.core.Version;
/**
* <!-- globalinfo-start --> Writes Matlab ASCII files, in single or double
* precision format.
* <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>
* -double
* Use double precision format.
* (default: single precision)
* </pre>
*
* <pre>
* -tabs
* Use tabs as separator.
* (default: blanks)
* </pre>
*
* <!-- options-end -->
*
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision$
* @see Saver
*/
public class MatlabSaver extends AbstractFileSaver implements BatchConverter,
IncrementalConverter {
/** for serialization. */
private static final long serialVersionUID = 4118356803697172614L;
/** the file extension. */
public static String FILE_EXTENSION = MatlabLoader.FILE_EXTENSION;
/** whether to save in double instead of single precision format. */
protected boolean m_UseDouble;
/** whether to use tabs instead of blanks. */
protected boolean m_UseTabs;
/** whether the header was written already. */
protected boolean m_HeaderWritten;
/** for formatting the numbers. */
protected DecimalFormat m_Format;
/**
* Constructor.
*/
public MatlabSaver() {
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 Matlab ASCII files, in single or double precision format.";
}
/**
* 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("\tUse double precision format.\n"
+ "\t(default: single precision)", "double", 0, "-double"));
result.addElement(new Option("\tUse tabs as separator.\n"
+ "\t(default: blanks)", "tabs", 0, "-tabs"));
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 (getUseDouble()) {
result.add("-double");
}
if (getUseTabs()) {
result.add("-tabs");
}
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>
* -double
* Use double precision format.
* (default: single precision)
* </pre>
*
* <pre>
* -tabs
* Use tabs as separator.
* (default: blanks)
* </pre>
*
* <!-- options-end -->
*
* @param options the options to use
* @throws Exception if setting of options fails
*/
@Override
public void setOptions(String[] options) throws Exception {
setUseDouble(Utils.getFlag("double", options));
setUseTabs(Utils.getFlag("tabs", options));
super.setOptions(options);
Utils.checkForRemainingOptions(options);
}
/**
* Returns a description of the file type.
*
* @return a short file description
*/
@Override
public String getFileDescription() {
return "Matlab ASCII files";
}
/**
* Resets the Saver.
*/
@Override
public void resetOptions() {
super.resetOptions();
setFileExtension(MatlabLoader.FILE_EXTENSION);
setUseDouble(false);
setUseTabs(false);
m_HeaderWritten = false;
}
/**
* Sets whether to use double or single precision.
*
* @param value if true then double precision is used
*/
public void setUseDouble(boolean value) {
m_UseDouble = value;
m_Format = (DecimalFormat) NumberFormat.getInstance(Locale.US);
if (m_UseDouble) {
//m_Format = new DecimalFormat(
m_Format.applyPattern(" 0.0000000000000000E00; -0.0000000000000000E00");
} else {
// m_Format = new DecimalFormat(" 0.00000000E00; -0.00000000E00");
m_Format.applyPattern(" 0.00000000E00; -0.00000000E00");
}
}
/**
* Returns whether double or single precision is used.
*
* @return true if double precision is used
*/
public boolean getUseDouble() {
return m_UseDouble;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String useDoubleTipText() {
return "Sets whether to use double instead of single precision.";
}
/**
* Sets whether to use tabs instead of blanks.
*
* @param value if true then tabs are used
*/
public void setUseTabs(boolean value) {
m_UseTabs = value;
}
/**
* Returns whether tabs are used instead of blanks.
*
* @return true if tabs are used
*/
public boolean getUseTabs() {
return m_UseTabs;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String useTabsTipText() {
return "Sets whether to use tabs as separators instead of blanks.";
}
/**
* 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.NUMERIC_ATTRIBUTES);
// class
result.enable(Capability.NUMERIC_CLASS);
result.enable(Capability.NO_CLASS);
return result;
}
/**
* Generates a comment header.
*
* @return the header
*/
protected String matlabHeader() {
StringBuffer result;
int i;
result = new StringBuffer();
result.append("% Relation: " + getInstances().relationName() + "\n");
result.append("% Generated on: " + new Date() + "\n");
result.append("% Generated by: WEKA " + Version.VERSION + "\n");
result.append("%\n");
result.append("% ");
for (i = 0; i < getInstances().numAttributes(); i++) {
if (i > 0) {
result.append((m_UseTabs ? "\t " : " "));
}
result.append(Utils.padRight(getInstances().attribute(i).name(),
(m_UseDouble ? 16 : 8) + 5));
}
return result.toString();
}
/**
* turns the instance into a Matlab row.
*
* @param inst the instance to transform
* @return the generated Matlab row
*/
protected String instanceToMatlab(Instance inst) {
StringBuffer result;
int i;
result = new StringBuffer();
// attributes
for (i = 0; i < inst.numAttributes(); i++) {
if (i > 0) {
result.append((m_UseTabs ? "\t" : " "));
}
result.append(m_Format.format(inst.value(i)));
}
return result.toString();
}
/**
* 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();
}
// header
if (writeMode == STRUCTURE_READY) {
setWriteMode(WRITE);
if ((retrieveFile() == null) && (outW == null)) {
System.out.println(matlabHeader());
} else {
outW.println(matlabHeader());
}
writeMode = getWriteMode();
}
// row
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(instanceToMatlab(inst));
} else {
outW.println(instanceToMatlab(inst));
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)) {
System.out.println(matlabHeader());
for (int i = 0; i < getInstances().numInstances(); i++) {
System.out.println(instanceToMatlab(getInstances().instance(i)));
}
setWriteMode(WAIT);
} else {
PrintWriter outW = new PrintWriter(getWriter());
outW.println(matlabHeader());
for (int i = 0; i < getInstances().numInstances(); i++) {
outW.println(instanceToMatlab(getInstances().instance(i)));
}
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 MatlabSaver(), 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/SVMLightLoader.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/>.
*/
/*
* SVMLightLoader.java
* Copyright (C) 2006-2012 University of Waikato, Hamilton, NZ
*
*/
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.net.URL;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.util.Vector;
import weka.core.Attribute;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.RevisionUtils;
import weka.core.SparseInstance;
/**
<!-- globalinfo-start -->
* Reads a source that is in svm light format.<br/>
* <br/>
* For more information about svm light see:<br/>
* <br/>
* http://svmlight.joachims.org/
* <p/>
<!-- globalinfo-end -->
*
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision$
* @see Loader
*/
public class SVMLightLoader
extends AbstractFileLoader
implements BatchConverter, URLSourcedLoader {
/** for serialization. */
private static final long serialVersionUID = 4988360125354664417L;
/** the file extension. */
public static String FILE_EXTENSION = ".dat";
/** the url. */
protected String m_URL = "http://";
/** The reader for the source file. */
protected transient Reader m_sourceReader = null;
/** the buffer of the rows read so far. */
protected Vector<double[]> m_Buffer = null;
/**
* 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 svm light format.\n\n"
+ "For more information about svm light see:\n\n"
+ "http://svmlight.joachims.org/";
}
/**
* Get the file extension used for svm light files.
*
* @return the file extension
*/
public String getFileExtension() {
return FILE_EXTENSION;
}
/**
* Gets all the file extensions used for this type of file.
*
* @return the file extensions
*/
public String[] getFileExtensions() {
return new String[]{getFileExtension()};
}
/**
* Returns a description of the file type.
*
* @return a short file description
*/
public String getFileDescription() {
return "svm light data files";
}
/**
* Resets the Loader ready to read a new data set.
*
* @throws IOException if something goes wrong
*/
public void reset() throws IOException {
m_structure = null;
m_Buffer = null;
setRetrieval(NONE);
if (m_File != null) {
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;
m_Buffer = null;
setRetrieval(NONE);
setSource(url.openStream());
m_URL = url.toString();
}
/**
* Set the url to load from.
*
* @param url the url to load from
* @throws IOException if the url can't be set.
*/
public void setURL(String url) throws IOException {
m_URL = url;
setSource(new URL(url));
}
/**
* Return the current url.
*
* @return the current url
*/
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 if initialization of reader fails.
*/
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));
}
/**
* turns a svm light row into a double array with the class as the last
* entry.
*
* @param row the row to turn into a double array
* @return the corresponding double array
* @throws Exception if a parsing error is encountered
*/
protected double[] svmlightToArray(String row) throws Exception {
double[] result;
StringTokenizer tok;
int index;
int max;
String col;
double value;
// actual data
try {
// determine max index
max = 0;
tok = new StringTokenizer(row, " \t");
tok.nextToken(); // skip class
while (tok.hasMoreTokens()) {
col = tok.nextToken();
// finished?
if (col.startsWith("#"))
break;
// qid is not supported
if (col.startsWith("qid:"))
continue;
// actual value
index = Integer.parseInt(col.substring(0, col.indexOf(":")));
if (index > max)
max = index;
}
// read values into array
tok = new StringTokenizer(row, " \t");
result = new double[max + 1];
// 1. class
result[result.length - 1] = Double.parseDouble(tok.nextToken());
// 2. attributes
while (tok.hasMoreTokens()) {
col = tok.nextToken();
// finished?
if (col.startsWith("#"))
break;
// qid is not supported
if (col.startsWith("qid:"))
continue;
// actual value
index = Integer.parseInt(col.substring(0, col.indexOf(":")));
value = Double.parseDouble(col.substring(col.indexOf(":") + 1));
result[index - 1] = value;
}
}
catch (Exception e) {
System.err.println("Error parsing line '" + row + "': " + e);
throw new Exception(e);
}
return result;
}
/**
* determines the number of attributes, if the number of attributes in the
* given row is greater than the current amount then this number will be
* returned, otherwise the current number.
*
* @param values the parsed values
* @param num the current number of attributes
* @return the new number of attributes
* @throws Exception if parsing fails
*/
protected int determineNumAttributes(double[] values, int num) throws Exception {
int result;
int count;
result = num;
count = values.length;
if (count > result)
result = count;
return result;
}
/**
* Determines the class attribute, either a binary +1/-1 or numeric attribute.
*
* @return the generated attribute
*/
protected Attribute determineClassAttribute() {
Attribute result;
boolean binary;
int i;
ArrayList<String> values;
double[] dbls;
double cls;
binary = true;
for (i = 0; i < m_Buffer.size(); i++) {
dbls = (double[]) m_Buffer.get(i);
cls = dbls[dbls.length - 1];
if ((cls != -1.0) && (cls != +1.0)) {
binary = false;
break;
}
}
if (binary) {
values = new ArrayList<String>();
values.add("+1");
values.add("-1");
result = new Attribute("class", values);
}
else {
result = new Attribute("class");
}
return result;
}
/**
* 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
*/
public Instances getStructure() throws IOException {
StringBuffer line;
int cInt;
char c;
int numAtt;
ArrayList<Attribute> atts;
int i;
String relName;
if (m_sourceReader == null)
throw new IOException("No source has been specified");
if (m_structure == null) {
m_Buffer = new Vector<double[]>();
try {
// determine number of attributes
numAtt = 0;
line = new StringBuffer();
while ((cInt = m_sourceReader.read()) != -1) {
c = (char) cInt;
if ((c == '\n') || (c == '\r')) {
if ((line.length() > 0) && (line.charAt(0) != '#')) {
// actual data
try {
m_Buffer.add(svmlightToArray(line.toString()));
numAtt = determineNumAttributes((double[]) m_Buffer.lastElement(), numAtt);
}
catch (Exception e) {
throw new Exception("Error parsing line '" + line + "': " + e);
}
}
line = new StringBuffer();
}
else {
line.append(c);
}
}
// last line?
if ((line.length() != 0) && (line.charAt(0) != '#')) {
m_Buffer.add(svmlightToArray(line.toString()));
numAtt = determineNumAttributes((double[]) m_Buffer.lastElement(), numAtt);
}
// generate header
atts = new ArrayList<Attribute>(numAtt);
for (i = 0; i < numAtt - 1; i++)
atts.add(new Attribute("att_" + (i+1)));
atts.add(determineClassAttribute());
if (!m_URL.equals("http://"))
relName = m_URL;
else
relName = m_File;
m_structure = new Instances(relName, atts, 0);
m_structure.setClassIndex(m_structure.numAttributes() - 1);
}
catch (Exception ex) {
ex.printStackTrace();
throw new IOException("Unable to determine structure as svm light: " + ex);
}
}
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
*/
public Instances getDataSet() throws IOException {
Instances result;
double[] sparse;
double[] data;
int i;
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();
result = new Instances(m_structure, 0);
// create instances from buffered arrays
for (i = 0; i < m_Buffer.size(); i++) {
sparse = (double[]) m_Buffer.get(i);
if (sparse.length != m_structure.numAttributes()) {
data = new double[m_structure.numAttributes()];
// attributes
System.arraycopy(sparse, 0, data, 0, sparse.length - 1);
// class
data[data.length - 1] = sparse[sparse.length - 1];
}
else {
data = sparse;
}
// fix class
if (result.classAttribute().isNominal()) {
if (data[data.length - 1] == 1.0)
data[data.length - 1] = result.classAttribute().indexOfValue("+1");
else if (data[data.length - 1] == -1)
data[data.length - 1] = result.classAttribute().indexOfValue("-1");
else
throw new IllegalStateException("Class is not binary!");
}
result.add(new SparseInstance(1, data));
}
try {
// close the stream
m_sourceReader.close();
} catch (Exception ex) {
}
return result;
}
/**
* SVMLightLoader is unable to process a data set incrementally.
*
* @param structure ignored
* @return never returns without throwing an exception
* @throws IOException always. SVMLightLoader is unable to process a
* data set incrementally.
*/
public Instance getNextInstance(Instances structure) throws IOException {
throw new IOException("SVMLightLoader can't read data sets incrementally.");
}
/**
* Returns the revision string.
*
* @return the revision
*/
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 SVMLightLoader(), 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/SVMLightSaver.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/>.
*/
/*
* SVMLightSaver.java
* Copyright (C) 2006-2012 University of Waikato, Hamilton, NZ
*
*/
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.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.SingleIndex;
import weka.core.Utils;
/**
* <!-- globalinfo-start --> Writes to a destination that is in svm light
* format.<br/>
* <br/>
* For more information about svm light see:<br/>
* <br/>
* http://svmlight.joachims.org/
* <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 <class index>
* The class index
* (default: last)
* </pre>
*
* <!-- options-end -->
*
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision$
* @see Saver
*/
public class SVMLightSaver extends AbstractFileSaver implements BatchConverter, IncrementalConverter {
/** for serialization. */
private static final long serialVersionUID = 2605714599263995835L;
/** the file extension. */
public static String FILE_EXTENSION = SVMLightLoader.FILE_EXTENSION;
/** the number of digits after the decimal point. */
public static int MAX_DIGITS = 18;
/** the class index. */
protected SingleIndex m_ClassIndex = new SingleIndex("last");
/**
* Constructor.
*/
public SVMLightSaver() {
this.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 svm light format.\n\n" + "For more information about svm light see:\n\n" + "http://svmlight.joachims.org/";
}
/**
* 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 index\n" + "\t(default: last)", "c", 1, "-c <class index>"));
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>();
result.add("-c");
result.add(this.getClassIndex());
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>
* -c <class index>
* The class index
* (default: last)
* </pre>
*
* <!-- options-end -->
*
* @param options the options to use
* @throws Exception if setting of options fails
*/
@Override
public void setOptions(final String[] options) throws Exception {
String tmpStr;
tmpStr = Utils.getOption('c', options);
if (tmpStr.length() != 0) {
this.setClassIndex(tmpStr);
} else {
this.setClassIndex("last");
}
super.setOptions(options);
Utils.checkForRemainingOptions(options);
}
/**
* Returns a description of the file type.
*
* @return a short file description
*/
@Override
public String getFileDescription() {
return "svm light data files";
}
/**
* Resets the Saver.
*/
@Override
public void resetOptions() {
super.resetOptions();
this.setFileExtension(SVMLightLoader.FILE_EXTENSION);
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String classIndexTipText() {
return "Sets the class index (\"first\" and \"last\" are valid values)";
}
/**
* Get the index of the class attribute.
*
* @return the index of the class attribute
*/
public String getClassIndex() {
return this.m_ClassIndex.getSingleIndex();
}
/**
* Sets index of the class attribute.
*
* @param value the index of the class attribute
*/
public void setClassIndex(final String value) {
this.m_ClassIndex.setSingleIndex(value);
}
/**
* 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);
// class
result.enable(Capability.BINARY_CLASS);
result.enable(Capability.NUMERIC_CLASS);
result.enable(Capability.DATE_CLASS);
return result;
}
/**
* Sets instances that should be stored.
*
* @param instances the instances
* @throws InterruptedException
*/
@Override
public void setInstances(final Instances instances) throws InterruptedException {
this.m_ClassIndex.setUpper(instances.numAttributes() - 1);
instances.setClassIndex(this.m_ClassIndex.getIndex());
super.setInstances(instances);
}
/**
* turns the instance into a svm light row.
*
* @param inst the instance to transform
* @return the generated svm light row
*/
protected String instanceToSvmlight(final Instance inst) {
StringBuffer result;
int i;
result = new StringBuffer();
// class
if (inst.classAttribute().isNominal()) {
if (inst.classValue() == 0) {
result.append("1");
} else if (inst.classValue() == 1) {
result.append("-1");
}
} else {
result.append("" + Utils.doubleToString(inst.classValue(), MAX_DIGITS));
}
// attributes
for (i = 0; i < inst.numAttributes(); i++) {
if (i == inst.classIndex()) {
continue;
}
if (inst.value(i) == 0) {
continue;
}
result.append(" " + (i + 1) + ":" + Utils.doubleToString(inst.value(i), MAX_DIGITS));
}
return result.toString();
}
/**
* 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(final Instance inst) throws IOException {
int writeMode = this.getWriteMode();
Instances structure = this.getInstances();
PrintWriter outW = null;
if ((this.getRetrieval() == BATCH) || (this.getRetrieval() == NONE)) {
throw new IOException("Batch and incremental saving cannot be mixed.");
}
if (this.getWriter() != null) {
outW = new PrintWriter(this.getWriter());
}
if (writeMode == WAIT) {
if (structure == null) {
this.setWriteMode(CANCEL);
if (inst != null) {
System.err.println("Structure (Header Information) has to be set in advance");
}
} else {
this.setWriteMode(STRUCTURE_READY);
}
writeMode = this.getWriteMode();
}
if (writeMode == CANCEL) {
if (outW != null) {
outW.close();
}
this.cancel();
}
// header
if (writeMode == STRUCTURE_READY) {
this.setWriteMode(WRITE);
// no header
writeMode = this.getWriteMode();
}
// row
if (writeMode == WRITE) {
if (structure == null) {
throw new IOException("No instances information available.");
}
if (inst != null) {
// write instance
if ((this.retrieveFile() == null) && (outW == null)) {
System.out.println(this.instanceToSvmlight(inst));
} else {
outW.println(this.instanceToSvmlight(inst));
this.m_incrementalCounter++;
// flush every 100 instances
if (this.m_incrementalCounter > 100) {
this.m_incrementalCounter = 0;
outW.flush();
}
}
} else {
// close
if (outW != null) {
outW.flush();
outW.close();
}
this.m_incrementalCounter = 0;
this.resetStructure();
outW = null;
this.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 (this.getInstances() == null) {
throw new IOException("No instances to save");
}
if (this.getRetrieval() == INCREMENTAL) {
throw new IOException("Batch and incremental saving cannot be mixed.");
}
this.setRetrieval(BATCH);
this.setWriteMode(WRITE);
if ((this.retrieveFile() == null) && (this.getWriter() == null)) {
for (int i = 0; i < this.getInstances().numInstances(); i++) {
System.out.println(this.instanceToSvmlight(this.getInstances().instance(i)));
}
this.setWriteMode(WAIT);
} else {
PrintWriter outW = new PrintWriter(this.getWriter());
for (int i = 0; i < this.getInstances().numInstances(); i++) {
outW.println(this.instanceToSvmlight(this.getInstances().instance(i)));
}
outW.flush();
outW.close();
this.setWriteMode(WAIT);
outW = null;
this.resetWriter();
this.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(final String[] args) {
runFileSaver(new SVMLightSaver(), 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/Saver.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/>.
*/
/*
* Saver.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.Serializable;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.RevisionHandler;
/**
* Interface to something that can save Instances to an output destination in some
* format.
*
* @author Mark Hall (mhall@cs.waikato.ac.nz)
* @author Stefan Mutter (mutter@cs.waikato.ac.nz)
* @version $Revision$
*/
public interface Saver extends Serializable, RevisionHandler {
/** The retrieval modes */
static final int NONE = 0;
static final int BATCH = 1;
static final int INCREMENTAL = 2;
/*@ public model instance boolean model_structureDetermined
@ initially: model_structureDetermined == false;
@*/
/*@ public model instance boolean model_sourceSupplied
@ initially: model_sourceSupplied == false;
@*/
/**
* Resets the Saver object and sets the destination to be
* the supplied File object.
*
* @param file the File
* @exception IOException if an error occurs
* support loading from a File.
*
* <pre><jml>
* public_normal_behavior
* requires: file != null
* && (* file exists *);
* modifiable: model_sourceSupplied, model_structureDetermined;
* ensures: model_sourceSupplied == true
* && model_structureDetermined == false;
* also
* public_exceptional_behavior
* requires: file == null
* || (* file does not exist *);
* signals: (IOException);
* </jml></pre>
*/
void setDestination(File file) throws IOException;
/** Resets the Saver object and sets the destination to be
* the supplied InputStream.
* @param output the output stream
* @exception IOException if this Loader doesn't
* support loading from a File.
*/
void setDestination(OutputStream output) throws IOException;
/** Sets the retrieval mode
* @param mode an integer representing a retrieval mode
*/
void setRetrieval(int mode);
/** Gets the file extension
* @return a string conatining the file extension (including the '.')
* @throws Exception exception if a Saver not implementing FileSourcedConverter is used.
*/
String getFileExtension() throws Exception;
/** Sets the output file
* @param file the output file
* @throws IOException exception if new output file cannot be set
*/
void setFile(File file) throws IOException;
/** Sets the file prefix.
* This method is used in the KnowledgeFlow GUI.
* @param prefix the prefix of the file name
* @throws Exception exception if a Saver not implementing FileSourcedConverter is used.
*/
void setFilePrefix(String prefix) throws Exception;
/** Gets the file prefix
* This method is used in the KnowledgeFlow GUI.
* @return the prefix of the file name
* @throws Exception exception if a Saver not implementing FileSourcedConverter is used.
*/
String filePrefix() throws Exception;
/** Sets the directory of the output file.
* This method is used in the KnowledgeFlow GUI.
* @param dir a string containing the path and name of the directory
* @throws IOException exception if a Saver not implementing FileSourcedConverter is used.
*/
void setDir(String dir) throws IOException;
/** Sets the file prefix and the directory.
* This method is used in the KnowledgeFlow GUI.
* @param relationName the name of the realtion to be saved
* @param add additional String for the file name
* @throws IOException exception if a Saver not implementing FileSourcedConverter is used.
*/
public void setDirAndPrefix(String relationName, String add) throws IOException;
/** Gets the driectory of the output file
* This method is used in the KnowledgeFlow GUI.
* @return the directory as a string
* @throws IOException exception if a Saver not implementing FileSourcedConverter is used.
*/
String retrieveDir() throws IOException;
/** Sets the instances to be saved
* @param instances the instances
* @throws InterruptedException
*/
void setInstances(Instances instances) throws InterruptedException;
/** Writes to a destination in batch mode
* @throws IOException throws exection if writting in batch mode is not possible
*/
void writeBatch() throws IOException;
/** Writes to a destination in incremental mode.
* If the instance is null, the outputfile will be closed.
* @param inst the instance to write, if null the output file is closed
* @throws IOException throws exception if incremental writting is not possible
*/
void writeIncremental(Instance inst) throws IOException;
/** Gets the write mode
* @return an integer representing the write mode
*/
public int getWriteMode();
}
|
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/SerializedInstancesLoader.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/>.
*/
/*
* SerializedInstancesLoader.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.converters;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.RevisionUtils;
/**
<!-- globalinfo-start -->
* Reads a source that contains serialized Instances.
* <p/>
<!-- globalinfo-end -->
*
* @author <a href="mailto:len@reeltwo.com">Len Trigg</a>
* @version $Revision$
* @see Loader
*/
public class SerializedInstancesLoader
extends AbstractFileLoader
implements BatchConverter, IncrementalConverter {
/** for serialization */
static final long serialVersionUID = 2391085836269030715L;
/** the file extension */
public static String FILE_EXTENSION =
Instances.SERIALIZED_OBJ_FILE_EXTENSION;
/** Holds the structure (header) of the data set. */
protected Instances m_Dataset = null;
/** The current index position for incremental reading */
protected int m_IncrementalIndex = 0;
/**
* Returns a string describing this object
*
* @return a description of the classifier suitable for
* displaying in the explorer/experimenter gui
*/
public String globalInfo() {
return "Reads a source that contains serialized Instances.";
}
/** Resets the Loader ready to read a new data set */
public void reset() {
m_Dataset = null;
m_IncrementalIndex = 0;
}
/**
* Get the file extension used for arff files
*
* @return the file extension
*/
public String getFileExtension() {
return FILE_EXTENSION;
}
/**
* Gets all the file extensions used for this type of file
*
* @return the file extensions
*/
public String[] getFileExtensions() {
return new String[]{getFileExtension()};
}
/**
* Returns a description of the file type.
*
* @return a short file description
*/
public String getFileDescription() {
return "Binary serialized instances";
}
/**
* Resets the Loader object and sets the source of the data set to be
* the supplied InputStream.
*
* @param in the source InputStream.
* @throws IOException if there is a problem with IO
*/
public void setSource(InputStream in) throws IOException {
ObjectInputStream oi = new ObjectInputStream(new BufferedInputStream(in));
try {
m_Dataset = (Instances)oi.readObject();
} catch (ClassNotFoundException ex) {
throw new IOException("Could not deserialize instances from this source.");
}
// close the stream
oi.close();
}
/**
* 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
*/
public Instances getStructure() throws IOException {
if (m_Dataset == null) {
throw new IOException("No source has been specified");
}
// We could cache a structure-only if getStructure is likely to be called
// many times.
return new Instances(m_Dataset, 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
*/
public Instances getDataSet() throws IOException {
if (m_Dataset == null) {
throw new IOException("No source has been specified");
}
return m_Dataset;
}
/**
* 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 ignored
* @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
*/
public Instance getNextInstance(Instances structure) throws IOException {
if (m_Dataset == null) {
throw new IOException("No source has been specified");
}
// We have to fake this method, since we can only deserialize an entire
// dataset at a time.
if (m_IncrementalIndex == m_Dataset.numInstances()) {
return null;
}
return m_Dataset.instance(m_IncrementalIndex++);
}
/**
* Returns the revision string.
*
* @return the revision
*/
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 SerializedInstancesLoader(), 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/SerializedInstancesSaver.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/>.
*/
/*
* SerializedInstancesSaver.java
* Copyright (C) 2004-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.converters;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import weka.core.Capabilities;
import weka.core.Capabilities.Capability;
import weka.core.RevisionUtils;
/**
<!-- globalinfo-start -->
* Serializes the instances to a file with extension bsi.
* <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>
*
<!-- options-end -->
*
* @author Stefan Mutter (mutter@cs.waikato.ac.nz)
* @version $Revision$
* @see Saver
*/
public class SerializedInstancesSaver
extends AbstractFileSaver
implements BatchConverter {
/** for serialization. */
static final long serialVersionUID = -7717010648500658872L;
/** the output stream. */
protected ObjectOutputStream m_objectstream;
/** Constructor. */
public SerializedInstancesSaver(){
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 "Serializes the instances to a file with extension bsi.";
}
/**
* Returns a description of the file type.
*
* @return a short file description
*/
public String getFileDescription() {
return "Binary serialized instances";
}
/**
* Resets the Saver.
*/
public void resetOptions() {
super.resetOptions();
setFileExtension(".bsi");
}
/**
* Returns the Capabilities of this saver.
*
* @return the capabilities of this object
* @see Capabilities
*/
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;
}
/**
* Resets the writer, setting writer and objectstream to null.
*/
public void resetWriter() {
super.resetWriter();
m_objectstream = null;
}
/**
* Sets the destination output stream.
*
* @param output the output stream.
* @throws IOException throws an IOException if destination cannot be set
*/
public void setDestination(OutputStream output) throws IOException {
super.setDestination(output);
m_objectstream = new ObjectOutputStream(output);
}
/**
* Writes a Batch of instances.
*
* @throws IOException throws IOException if saving in batch mode is not possible
*/
public void writeBatch() throws IOException {
if(getRetrieval() == INCREMENTAL)
throw new IOException("Batch and incremental saving cannot be mixed.");
if(getInstances() == null)
throw new IOException("No instances to save");
setRetrieval(BATCH);
if (m_objectstream == null)
throw new IOException("No output for serialization.");
setWriteMode(WRITE);
m_objectstream.writeObject(getInstances());
m_objectstream.flush();
m_objectstream.close();
setWriteMode(WAIT);
resetWriter();
setWriteMode(CANCEL);
}
/**
* Returns the revision string.
*
* @return the revision
*/
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 SerializedInstancesSaver(), 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/StreamTokenizerUtils.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/>.
*/
/*
* StreamTokenizerUtils.java
* Copyright (C) 2000-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.converters;
import java.io.IOException;
import java.io.Serializable;
import java.io.StreamTokenizer;
import weka.core.RevisionHandler;
import weka.core.RevisionUtils;
/**
* Helper class for using stream tokenizers
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision$
*/
public class StreamTokenizerUtils implements Serializable, RevisionHandler {
/** For serialization */
private static final long serialVersionUID = -5786996944597404253L;
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* 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 {
while (tokenizer.nextToken() == StreamTokenizer.TT_EOL) {
}
;
if ((tokenizer.ttype == '\'') || (tokenizer.ttype == '"')) {
tokenizer.ttype = StreamTokenizer.TT_WORD;
} else if ((tokenizer.ttype == StreamTokenizer.TT_WORD)
&& (tokenizer.sval.equals("?"))) {
tokenizer.ttype = '?';
}
}
/**
* Gets token.
*
* @param tokenizer the stream tokenizer
* @throws IOException if reading the next token fails
*/
public static void getToken(StreamTokenizer tokenizer) throws IOException {
tokenizer.nextToken();
if (tokenizer.ttype == StreamTokenizer.TT_EOL) {
return;
}
if ((tokenizer.ttype == '\'') || (tokenizer.ttype == '"')) {
tokenizer.ttype = StreamTokenizer.TT_WORD;
} else if ((tokenizer.ttype == StreamTokenizer.TT_WORD)
&& (tokenizer.sval.equals("?"))) {
tokenizer.ttype = '?';
}
}
/**
* 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());
}
}
|
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/TextDirectoryLoader.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/>.
*/
/*
* TextDirectoryLoader.java
* Copyright (C) 2006-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.converters;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.List;
import java.util.Vector;
import weka.core.Attribute;
import weka.core.CommandlineRunnable;
import weka.core.DenseInstance;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.Option;
import weka.core.OptionHandler;
import weka.core.RevisionUtils;
import weka.core.SerializedObject;
import weka.core.Utils;
/**
* <!-- globalinfo-start --> Loads all text files in a directory and uses the
* subdirectory names as class labels. The content of the text files will be
* stored in a String attribute, the filename can be stored as well.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -D
* Enables debug output.
* (default: off)
* </pre>
*
* <pre>
* -F
* Stores the filename in an additional attribute.
* (default: off)
* </pre>
*
* <pre>
* -dir <directory>
* The directory to work on.
* (default: current directory)
* </pre>
*
* <pre>
* -charset <charset name>
* The character set to use, e.g UTF-8.
* (default: use the default character set)
* </pre>
*
* <pre>
* -R
* Retain all string attribute values when reading incrementally.
* </pre>
*
* <!-- options-end -->
*
* Based on code from the TextDirectoryToArff tool:
* <ul>
* <li><a href=
* "https://list.scms.waikato.ac.nz/mailman/htdig/wekalist/2002-October/000685.html"
* target="_blank">Original tool</a></li>
* <li><a href=
* "https://list.scms.waikato.ac.nz/mailman/htdig/wekalist/2004-January/002160.html"
* target="_blank">Current version</a></li>
* <li><a href="http://weka.wikispaces.com/ARFF+files+from+Text+Collections"
* target="_blank">Wiki article</a></li>
* </ul>
*
* @author Ashraf M. Kibriya (amk14 at cs.waikato.ac.nz)
* @author Richard Kirkby (rkirkby at cs.waikato.ac.nz)
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision$
* @see Loader
*/
public class TextDirectoryLoader extends AbstractLoader implements
BatchConverter, IncrementalConverter, OptionHandler, CommandlineRunnable {
/** for serialization */
private static final long serialVersionUID = 2592118773712247647L;
/** Holds the determined structure (header) of the data set. */
protected Instances m_structure = null;
/** Holds the source of the data set. */
protected File m_sourceFile = new File(System.getProperty("user.dir"));
/** whether to print some debug information */
protected boolean m_Debug = false;
/** whether to include the filename as an extra attribute */
protected boolean m_OutputFilename = false;
/**
* The charset to use when loading text files (default is to just use the
* default charset).
*/
protected String m_charSet = "";
/**
* default constructor
*/
public TextDirectoryLoader() {
// No instances retrieved yet
setRetrieval(NONE);
}
/**
* Returns a string describing this loader
*
* @return a description of the evaluator suitable for displaying in the
* explorer/experimenter gui
*/
public String globalInfo() {
return "Loads all text files in a directory and uses the subdirectory names "
+ "as class labels. The content of the text files will be stored in a "
+ "String attribute, the filename can be stored as well.";
}
/**
* Lists the available options
*
* @return an enumeration of the available options
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> result = new Vector<Option>();
result.add(new Option("\tEnables debug output.\n" + "\t(default: off)",
"D", 0, "-D"));
result.add(new Option("\tStores the filename in an additional attribute.\n"
+ "\t(default: off)", "F", 0, "-F"));
result.add(new Option("\tThe directory to work on.\n"
+ "\t(default: current directory)", "dir", 0, "-dir <directory>"));
result.add(new Option("\tThe character set to use, e.g UTF-8.\n\t"
+ "(default: use the default character set)", "charset", 1,
"-charset <charset name>"));
return result.elements();
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -D
* Enables debug output.
* (default: off)
* </pre>
*
* <pre>
* -F
* Stores the filename in an additional attribute.
* (default: off)
* </pre>
*
* <pre>
* -dir <directory>
* The directory to work on.
* (default: current directory)
* </pre>
*
* <pre>
* -charset <charset name>
* The character set to use, e.g UTF-8.
* (default: use the default character set)
* </pre>
*
* <!-- options-end -->
*
* @param options the options
* @throws Exception if options cannot be set
*/
@Override
public void setOptions(String[] options) throws Exception {
setDebug(Utils.getFlag("D", options));
setOutputFilename(Utils.getFlag("F", options));
setDirectory(new File(Utils.getOption("dir", options)));
String charSet = Utils.getOption("charset", options);
m_charSet = "";
if (charSet.length() > 0) {
m_charSet = charSet;
}
}
/**
* Gets the setting
*
* @return the current setting
*/
@Override
public String[] getOptions() {
Vector<String> options = new Vector<String>();
if (getDebug()) {
options.add("-D");
}
if (getOutputFilename()) {
options.add("-F");
}
options.add("-dir");
options.add(getDirectory().getAbsolutePath());
if (m_charSet != null && m_charSet.length() > 0) {
options.add("-charset");
options.add(m_charSet);
}
return options.toArray(new String[options.size()]);
}
/**
* the tip text for this property
*
* @return the tip text
*/
public String charSetTipText() {
return "The character set to use when reading text files (eg UTF-8) - leave"
+ " blank to use the default character set.";
}
/**
* Set the character set to use when reading text files (an empty string
* indicates that the default character set will be used).
*
* @param charSet the character set to use.
*/
public void setCharSet(String charSet) {
m_charSet = charSet;
}
/**
* Get the character set to use when reading text files. An empty string
* indicates that the default character set will be used.
*
* @return the character set name to use (or empty string to indicate that the
* default character set will be used).
*/
public String getCharSet() {
return m_charSet;
}
/**
* Sets whether to print some debug information.
*
* @param value if true additional debug information will be printed.
*/
public void setDebug(boolean value) {
m_Debug = value;
}
/**
* Gets whether additional debug information is printed.
*
* @return true if additional debug information is printed
*/
public boolean getDebug() {
return m_Debug;
}
/**
* the tip text for this property
*
* @return the tip text
*/
public String debugTipText() {
return "Whether to print additional debug information to the console.";
}
/**
* Sets whether the filename will be stored as an extra attribute.
*
* @param value if true the filename will be stored in an extra attribute
*/
public void setOutputFilename(boolean value) {
m_OutputFilename = value;
reset();
}
/**
* Gets whether the filename will be stored as an extra attribute.
*
* @return true if the filename is stored in an extra attribute
*/
public boolean getOutputFilename() {
return m_OutputFilename;
}
/**
* the tip text for this property
*
* @return the tip text
*/
public String outputFilenameTipText() {
return "Whether to store the filename in an additional attribute.";
}
/**
* Returns a description of the file type, actually it's directories.
*
* @return a short file description
*/
public String getFileDescription() {
return "Directories";
}
/**
* get the Dir specified as the source
*
* @return the source directory
*/
public File getDirectory() {
return new File(m_sourceFile.getAbsolutePath());
}
/**
* sets the source directory
*
* @param dir the source directory
* @throws IOException if an error occurs
*/
public void setDirectory(File dir) throws IOException {
setSource(dir);
}
/**
* Resets the loader ready to read a new data set
*/
@Override
public void reset() {
m_structure = null;
m_filesByClass = null;
m_lastClassDir = 0;
setRetrieval(NONE);
}
/**
* Resets the Loader object and sets the source of the data set to be the
* supplied File object.
*
* @param dir the source directory.
* @throws IOException if an error occurs
*/
@Override
public void setSource(File dir) throws IOException {
reset();
if (dir == null) {
throw new IOException("Source directory object is null!");
}
m_sourceFile = dir;
if (!dir.exists() || !dir.isDirectory()) {
throw new IOException("Directory '" + dir + "' not found");
}
}
/**
* 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 (getDirectory() == null) {
throw new IOException("No directory/source has been specified");
}
// determine class labels, i.e., sub-dirs
if (m_structure == null) {
String directoryPath = getDirectory().getAbsolutePath();
ArrayList<Attribute> atts = new ArrayList<Attribute>();
ArrayList<String> classes = new ArrayList<String>();
File dir = new File(directoryPath);
String[] subdirs = dir.list();
for (String subdir2 : subdirs) {
File subdir = new File(directoryPath + File.separator + subdir2);
if (subdir.isDirectory()) {
classes.add(subdir2);
}
}
atts.add(new Attribute("text", (ArrayList<String>) null));
if (m_OutputFilename) {
atts.add(new Attribute("filename", (ArrayList<String>) null));
}
// make sure that the name of the class attribute is unlikely to
// clash with any attribute created via the StringToWordVector filter
atts.add(new Attribute("@@class@@", classes));
String relName = directoryPath.replaceAll("/", "_");
relName = relName.replaceAll("\\\\", "_").replaceAll(":", "_");
m_structure = new Instances(relName, atts, 0);
m_structure.setClassIndex(m_structure.numAttributes() - 1);
}
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
* @throws IOException if there is no source or parsing fails
*/
@Override
public Instances getDataSet() throws IOException {
if (getDirectory() == null) {
throw new IOException("No directory/source has been specified");
}
String directoryPath = getDirectory().getAbsolutePath();
ArrayList<String> classes = new ArrayList<String>();
Enumeration<Object> enm = getStructure().classAttribute().enumerateValues();
while (enm.hasMoreElements()) {
Object oo = enm.nextElement();
if (oo instanceof SerializedObject) {
classes.add(((SerializedObject) oo).getObject().toString());
} else {
classes.add(oo.toString());
}
}
Instances data = getStructure();
int fileCount = 0;
for (int k = 0; k < classes.size(); k++) {
String subdirPath = classes.get(k);
File subdir = new File(directoryPath + File.separator + subdirPath);
String[] files = subdir.list();
for (String file : files) {
try {
fileCount++;
if (getDebug()) {
System.err.println("processing " + fileCount + " : " + subdirPath
+ " : " + file);
}
double[] newInst = null;
if (m_OutputFilename) {
newInst = new double[3];
} else {
newInst = new double[2];
}
File txt =
new File(directoryPath + File.separator + subdirPath
+ File.separator + file);
BufferedReader is;
if (m_charSet == null || m_charSet.length() == 0) {
is =
new BufferedReader(
new InputStreamReader(new FileInputStream(txt)));
} else {
is =
new BufferedReader(new InputStreamReader(
new FileInputStream(txt), m_charSet));
}
StringBuffer txtStr = new StringBuffer();
int c;
while ((c = is.read()) != -1) {
txtStr.append((char) c);
}
newInst[0] = data.attribute(0).addStringValue(txtStr.toString());
if (m_OutputFilename) {
newInst[1] =
data.attribute(1).addStringValue(
subdirPath + File.separator + file);
}
newInst[data.classIndex()] = k;
data.add(new DenseInstance(1.0, newInst));
is.close();
} catch (Exception e) {
System.err.println("failed to convert file: " + directoryPath
+ File.separator + subdirPath + File.separator + file);
}
}
}
return data;
}
protected List<LinkedList<String>> m_filesByClass;
protected int m_lastClassDir = 0;
/**
* Process input directories/files incrementally.
*
* @param structure ignored
* @return never returns without throwing an exception
* @throws IOException if a problem occurs
*/
@Override
public Instance getNextInstance(Instances structure) throws IOException {
// throw new
// IOException("TextDirectoryLoader can't read data sets incrementally.");
String directoryPath = getDirectory().getAbsolutePath();
Attribute classAtt = structure.classAttribute();
if (m_filesByClass == null) {
m_filesByClass = new ArrayList<LinkedList<String>>();
for (int i = 0; i < classAtt.numValues(); i++) {
File classDir =
new File(directoryPath + File.separator + classAtt.value(i));
String[] files = classDir.list();
LinkedList<String> classDocs = new LinkedList<String>();
for (String cd : files) {
File txt =
new File(directoryPath + File.separator + classAtt.value(i)
+ File.separator + cd);
if (txt.isFile()) {
classDocs.add(cd);
}
}
m_filesByClass.add(classDocs);
}
}
// cycle through the classes
int count = 0;
LinkedList<String> classContents = m_filesByClass.get(m_lastClassDir);
boolean found = (classContents.size() > 0);
while (classContents.size() == 0) {
m_lastClassDir++;
count++;
if (m_lastClassDir == structure.classAttribute().numValues()) {
m_lastClassDir = 0;
}
classContents = m_filesByClass.get(m_lastClassDir);
if (classContents.size() > 0) {
found = true; // we have an instance we can create
break;
}
if (count == structure.classAttribute().numValues()) {
break; // must be finished
}
}
if (found) {
String nextDoc = classContents.poll();
File txt =
new File(directoryPath + File.separator
+ classAtt.value(m_lastClassDir) + File.separator + nextDoc);
BufferedReader is;
if (m_charSet == null || m_charSet.length() == 0) {
is =
new BufferedReader(new InputStreamReader(new FileInputStream(txt)));
} else {
is =
new BufferedReader(new InputStreamReader(new FileInputStream(txt),
m_charSet));
}
StringBuffer txtStr = new StringBuffer();
int c;
while ((c = is.read()) != -1) {
txtStr.append((char) c);
}
double[] newInst = null;
if (m_OutputFilename) {
newInst = new double[3];
} else {
newInst = new double[2];
}
newInst[0] = 0;
structure.attribute(0).setStringValue(txtStr.toString());
if (m_OutputFilename) {
newInst[1] = 0;
structure.attribute(1).setStringValue(txt.getAbsolutePath());
}
newInst[structure.classIndex()] = m_lastClassDir;
Instance inst = new DenseInstance(1.0, newInst);
inst.setDataset(structure);
is.close();
m_lastClassDir++;
if (m_lastClassDir == structure.classAttribute().numValues()) {
m_lastClassDir = 0;
}
return inst;
} else {
return null; // done!
}
}
/**
* 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) {
TextDirectoryLoader loader = new TextDirectoryLoader();
loader.run(loader, args);
}
/**
* Perform any setup stuff that might need to happen before commandline
* execution. Subclasses should override if they need to do something here
*
* @throws Exception if a problem occurs during setup
*/
@Override
public void preExecution() throws Exception {
}
/**
* Perform any teardown stuff that might need to happen after execution.
* Subclasses should override if they need to do something here
*
* @throws Exception if a problem occurs during teardown
*/
@Override
public void postExecution() throws Exception {
}
@Override
public void run(Object toRun, String[] args) throws IllegalArgumentException {
if (!(toRun instanceof TextDirectoryLoader)) {
throw new IllegalArgumentException("Object to execute is not a "
+ "TextDirectoryLoader!");
}
TextDirectoryLoader loader = (TextDirectoryLoader) toRun;
if (args.length > 0) {
try {
loader.setOptions(args);
// System.out.println(loader.getDataSet());
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);
} catch (Exception e) {
e.printStackTrace();
}
} else {
System.err.println("\nUsage:\n" + "\tTextDirectoryLoader [options]\n"
+ "\n" + "Options:\n");
Enumeration<Option> enm =
((OptionHandler) new TextDirectoryLoader()).listOptions();
while (enm.hasMoreElements()) {
Option option = enm.nextElement();
System.err.println(option.synopsis());
System.err.println(option.description());
}
System.err.println();
}
}
}
|
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/URLSourcedLoader.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/>.
*/
/*
* URLSourcedLoader.java
* Copyright (C) 2006-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.converters;
/**
* Interface to a loader that can load from a http url
*
* @author Mark Hall
* @version $Revision 1.0 $
*/
public interface URLSourcedLoader {
/**
* Set the url to load from
*
* @param url the url to load from
* @exception Exception if the url can't be set.
*/
void setURL(String url) throws Exception;
/**
* Return the current url
*
* @return the current url
*/
String retrieveURL();
}
|
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/XRFFLoader.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/>.
*/
/*
* XRFFLoader.java
* Copyright (C) 2006-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.converters;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.util.zip.GZIPInputStream;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.RevisionUtils;
import weka.core.xml.XMLInstances;
/**
<!-- globalinfo-start -->
* Reads a source that is in the XML version of the ARFF format. It automatically decompresses the data if the extension is '.xrff.gz'.
* <p/>
<!-- globalinfo-end -->
*
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision$
* @see Loader
*/
public class XRFFLoader
extends AbstractFileLoader
implements BatchConverter, URLSourcedLoader {
/** for serialization */
private static final long serialVersionUID = 3764533621135196582L;
/** the file extension */
public static String FILE_EXTENSION = XMLInstances.FILE_EXTENSION;
/** the extension for compressed files */
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 loaded XML document */
protected XMLInstances m_XMLInstances;
/**
* 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 the XML version of the ARFF format. "
+ "It automatically decompresses the data if the extension is '"
+ FILE_EXTENSION_COMPRESSED + "'.";
}
/**
* Get the file extension used for libsvm files
*
* @return the file extension
*/
public String getFileExtension() {
return FILE_EXTENSION;
}
/**
* Gets all the file extensions used for this type of file
*
* @return the file extensions
*/
public String[] getFileExtensions() {
return new String[]{FILE_EXTENSION, FILE_EXTENSION_COMPRESSED};
}
/**
* Returns a description of the file type.
*
* @return a short file description
*/
public String getFileDescription() {
return "XRFF data files";
}
/**
* Resets the Loader ready to read a new data set
*
* @throws IOException if something goes wrong
*/
public void reset() throws IOException {
m_structure = null;
m_XMLInstances = null;
setRetrieval(NONE);
if (m_File != null) {
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 File object.
*
* @param file the source file.
* @throws IOException if an error occurs
*/
public void setSource(File file) throws IOException {
m_structure = null;
m_XMLInstances = null;
setRetrieval(NONE);
if (file == null)
throw new IOException("Source file object is null!");
try {
if (file.getName().endsWith(FILE_EXTENSION_COMPRESSED))
setSource(new GZIPInputStream(new FileInputStream(file)));
else
setSource(new FileInputStream(file));
}
catch (FileNotFoundException ex) {
throw new IOException("File not found");
}
m_sourceFile = file;
m_File = file.getAbsolutePath();
}
/**
* 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;
m_XMLInstances = null;
setRetrieval(NONE);
setSource(url.openStream());
m_URL = url.toString();
}
/**
* Set the url to load from
*
* @param url the url to load from
* @throws IOException if the url can't be set.
*/
public void setURL(String url) throws IOException {
m_URL = url;
setSource(new URL(url));
}
/**
* Return the current url
*
* @return the current url
*/
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 if initialization of reader fails.
*/
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
*/
public Instances getStructure() throws IOException {
if (m_sourceReader == null)
throw new IOException("No source has been specified");
if (m_structure == null) {
try {
m_XMLInstances = new XMLInstances(m_sourceReader);
m_structure = new Instances(m_XMLInstances.getInstances(), 0);
}
catch (IOException ioe) {
// just re-throw it
throw ioe;
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
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
*/
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();
try {
// close the stream
m_sourceReader.close();
} catch (Exception ex) {
}
return m_XMLInstances.getInstances();
}
/**
* XRFFLoader is unable to process a data set incrementally.
*
* @param structure ignored
* @return never returns without throwing an exception
* @throws IOException always. XRFFLoader is unable to process a
* data set incrementally.
*/
public Instance getNextInstance(Instances structure) throws IOException {
throw new IOException("XRFFLoader can't read data sets incrementally.");
}
/**
* Returns the revision string.
*
* @return the revision
*/
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 XRFFLoader(), 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/XRFFSaver.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/>.
*/
/*
* XRFFSaver.java
* Copyright (C) 2006-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.Capabilities;
import weka.core.Capabilities.Capability;
import weka.core.Instances;
import weka.core.Option;
import weka.core.RevisionUtils;
import weka.core.SingleIndex;
import weka.core.Utils;
import weka.core.xml.XMLInstances;
/**
* <!-- globalinfo-start --> Writes to a destination that is in the XML version
* of the ARFF format. The data can be compressed with gzip, in order to save
* space.
* <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 <class index>
* The class index (first and last are valid as well).
* (default: last)
* </pre>
*
* <pre>
* -compress
* Compresses the data (uses '.xrff.gz' as extension instead of '.xrff')
* (default: off)
* </pre>
*
* <!-- options-end -->
*
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision$
* @see Saver
*/
public class XRFFSaver extends AbstractFileSaver implements BatchConverter {
/** for serialization */
private static final long serialVersionUID = -7226404765213522043L;
/** the class index */
protected SingleIndex m_ClassIndex = new SingleIndex();
/** the generated XML document */
protected XMLInstances m_XMLInstances;
/** whether to compress the output */
protected boolean m_CompressOutput = false;
/**
* Constructor
*/
public XRFFSaver() {
this.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 XML version of the ARFF format. " + "The data can be compressed with gzip, in order to save space.";
}
/**
* 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 index (first and last are valid as well).\n" + "\t(default: last)", "C", 1, "-C <class index>"));
result.addElement(new Option("\tCompresses the data (uses '" + XRFFLoader.FILE_EXTENSION_COMPRESSED + "' as extension instead of '" + XRFFLoader.FILE_EXTENSION + "')\n" + "\t(default: off)", "compress", 0, "-compress"));
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 (this.getClassIndex().length() != 0) {
result.add("-C");
result.add(this.getClassIndex());
}
if (this.getCompressOutput()) {
result.add("-compress");
}
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>
* -C <class index>
* The class index (first and last are valid as well).
* (default: last)
* </pre>
*
* <pre>
* -compress
* Compresses the data (uses '.xrff.gz' as extension instead of '.xrff')
* (default: off)
* </pre>
*
* <!-- options-end -->
*
* @param options the options to use
* @throws Exception if setting of options fails
*/
@Override
public void setOptions(final String[] options) throws Exception {
String tmpStr;
tmpStr = Utils.getOption('C', options);
if (tmpStr.length() != 0) {
this.setClassIndex(tmpStr);
} else {
this.setClassIndex("last");
}
this.setCompressOutput(Utils.getFlag("compress", options));
super.setOptions(options);
}
/**
* Returns a description of the file type.
*
* @return a short file description
*/
@Override
public String getFileDescription() {
return "XRFF data files";
}
/**
* Gets all the file extensions used for this type of file
*
* @return the file extensions
*/
@Override
public String[] getFileExtensions() {
return new String[] { XRFFLoader.FILE_EXTENSION, XRFFLoader.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(final File outputFile) throws IOException {
if (outputFile.getAbsolutePath().endsWith(XRFFLoader.FILE_EXTENSION_COMPRESSED)) {
this.setCompressOutput(true);
}
super.setFile(outputFile);
}
/**
* Resets the Saver
*/
@Override
public void resetOptions() {
super.resetOptions();
if (this.getCompressOutput()) {
this.setFileExtension(XRFFLoader.FILE_EXTENSION_COMPRESSED);
} else {
this.setFileExtension(XRFFLoader.FILE_EXTENSION);
}
try {
this.m_XMLInstances = new XMLInstances();
} catch (Exception e) {
this.m_XMLInstances = null;
}
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String classIndexTipText() {
return "Sets the class index (\"first\" and \"last\" are valid values)";
}
/**
* Get the index of the class attribute.
*
* @return the index of the class attribute
*/
public String getClassIndex() {
return this.m_ClassIndex.getSingleIndex();
}
/**
* Sets index of the class attribute.
*
* @param value the index of the class attribute
*/
public void setClassIndex(final String value) {
this.m_ClassIndex.setSingleIndex(value);
}
/**
* 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 this.m_CompressOutput;
}
/**
* Sets whether to compress the output.
*
* @param value if truee the output will be compressed
*/
public void setCompressOutput(final boolean value) {
this.m_CompressOutput = value;
}
/**
* 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;
}
/**
* Sets instances that should be stored.
*
* @param instances the instances
* @throws InterruptedException
*/
@Override
public void setInstances(final Instances instances) throws InterruptedException {
if (this.m_ClassIndex.getSingleIndex().length() != 0) {
this.m_ClassIndex.setUpper(instances.numAttributes() - 1);
instances.setClassIndex(this.m_ClassIndex.getIndex());
}
super.setInstances(instances);
}
/**
* Sets the destination output stream.
*
* @param output the output stream.
* @throws IOException throws an IOException if destination cannot be set
*/
@Override
public void setDestination(final OutputStream output) throws IOException {
if (this.getCompressOutput()) {
super.setDestination(new GZIPOutputStream(output));
} else {
super.setDestination(output);
}
}
/**
* Writes a Batch of instances
*
* @throws IOException throws IOException if saving in batch mode is not
* possible
*/
@Override
public void writeBatch() throws IOException {
if (this.getInstances() == null) {
throw new IOException("No instances to save");
}
if (this.getRetrieval() == INCREMENTAL) {
throw new IOException("Batch and incremental saving cannot be mixed.");
}
this.setRetrieval(BATCH);
this.setWriteMode(WRITE);
// generate XML
this.m_XMLInstances.setInstances(this.getInstances());
if ((this.retrieveFile() == null) && (this.getWriter() == null)) {
System.out.println(this.m_XMLInstances.toString());
this.setWriteMode(WAIT);
} else {
PrintWriter outW = new PrintWriter(this.getWriter());
outW.println(this.m_XMLInstances.toString());
outW.flush();
outW.close();
this.setWriteMode(WAIT);
outW = null;
this.resetWriter();
this.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(final String[] args) {
runFileSaver(new XRFFSaver(), 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/expressionlanguage/package-info.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/>.
*/
/*
* package-info.java
* Copyright (C) 2015 University of Waikato, Hamilton, New Zealand
*
*/
/**
* Package for a framework for simple, flexible and performant expression
* languages</p>
*
* <h1>Introduction & Overview</h1>
*
* The {@link weka.core.expressionlanguage} package provides functionality to
* easily create simple languages.</p>
*
* It does so through creating an AST (abstract syntax tree) that can then be
* evaluated.</p>
*
* At the heart of the AST is the {@link weka.core.expressionlanguage.core.Node}
* interface. It's an empty interface to mark types to be an AST node.</br>
* Thus there are no real constraints on AST nodes so that they have as much
* freedom as possible to reflect abstractions of programs.</p>
*
* To give a common base to build upon the {@link weka.core.expressionlanguage.common.Primitives}
* class provides the subinterfaces for the primitive boolean
* ({@link weka.core.expressionlanguage.common.Primitives.BooleanExpression}),
* double ({@link weka.core.expressionlanguage.common.Primitives.DoubleExpression})
* and String ({@link weka.core.expressionlanguage.common.Primitives.StringExpression})
* types.</br>
* It furthermore provides implementations of constants and variables of those
* types.</p>
*
* Most extensibility is achieved through adding macros to a language. Macros
* allow for powerful meta-programming since they directly work with AST nodes.
* </br>
* The {@link weka.core.expressionlanguage.core.Macro} interface defines what a
* macro looks like.</p>
*
* Variable and macro lookup is done through
* {@link weka.core.expressionlanguage.core.VariableDeclarations} and
* {@link weka.core.expressionlanguage.core.MacroDeclarations} resp. Furthermore,
* both can be combined through
* {@link weka.core.expressionlanguage.common.VariableDeclarationsCompositor}
* and {@link weka.core.expressionlanguage.common.MacroDeclarationsCompositor}
* resp.</br>
* This really allows to add built-in variables and powerful built-in functions
* to a language.</p>
*
* Useful implementations are:</br>
* <ul>
* <li>{@link weka.core.expressionlanguage.common.SimpleVariableDeclarations}</li>
* <li>{@link weka.core.expressionlanguage.common.MathFunctions}</li>
* <li>{@link weka.core.expressionlanguage.common.IfElseMacro}</li>
* <li>{@link weka.core.expressionlanguage.common.JavaMacro}</li>
* <li>{@link weka.core.expressionlanguage.common.NoVariables}</li>
* <li>{@link weka.core.expressionlanguage.common.NoMacros}</li>
* <li>{@link weka.core.expressionlanguage.weka.InstancesHelper}</li>
* <li>{@link weka.core.expressionlanguage.weka.StatsHelper}</li>
* </ul>
*
* The described framework doesn't touch the syntax of a language so far. The
* syntax is seen as a separate element of a language.</br>
* If a program is given in a textual representation (e.g. "A + sqrt(2.0)" is a
* program in a textual representation), this textual representation declares
* how the AST looks like. That's why the parser's job is to build the AST.</br>
* There is a parser in the {@link weka.core.expressionlanguage.parser} package.</br>
* However the framework allows for other means to construct an AST if needed.</p>
*
* Built-in operators like (+, -, *, / etc) are a special case, since they can
* be seen as macros, however they are strongly connected to the parser too.</br>
* To separate the parser and these special macros there is the
* {@link weka.core.expressionlanguage.common.Operators} class which can be used
* by the parser to delegate operator semantics elsewhere.
*
* <h2>A word on parsers</h2>
*
* Currently the parser is generated through the CUP parser generator and jflex
* lexer generator. While parser generators are powerful tools they suffer from
* some unfortunate drawbacks:</p>
* <ul>
* <li>The parsers are generated. So there is an additional indirection between
* the grammar file (used for parser generation) and the generated code.</li>
* <li>The grammar files usually have their own syntax which may be quite
* different from the programming language otherwise used in a project.</li>
* <li>In more complex grammars it's easy to introduce ambiguities and unwanted
* valid syntax.</li>
* </ul>
* It's for these reasons why the parser is kept as simple as possible and with
* as much functionality delegated elsewhere as possible.
*
* <h2>Summary</h2>
*
* A flexible AST structure is given by the
* {@link weka.core.expressionlanguage.core.Node} interface. The
* {@link weka.core.expressionlanguage.core.Macro} interface allows for powerful
* meta-programming which is an important part of the extensibility features. The
* {@link weka.core.expressionlanguage.common.Primitives} class gives a good
* basis for the primitive boolean, double & String types.</br>
* The parser is responsible for building up the AST structure. It delegates
* operator semantics to {@link weka.core.expressionlanguage.common.Operators}.
* Symbol lookup is done through the
* {@link weka.core.expressionlanguage.core.VariableDeclarations} and
* {@link weka.core.expressionlanguage.core.MacroDeclarations} interfaces which
* can be combined with the
* {@link weka.core.expressionlanguage.common.VariableDeclarationsCompositor}
* and {@link weka.core.expressionlanguage.common.MacroDeclarationsCompositor}
* classes resp.</p>
*
* <h1>Usage</h1>
*
* With the described framework it's possible to create languages in a declarative
* way. Examples can be found in
* {@link weka.filters.unsupervised.attribute.MathExpression},
* {@link weka.filters.unsupervised.attribute.AddExpression} and
* {@link weka.filters.unsupervised.instance.SubsetByExpression}.</p>
*
* A commonly used language is:<p>
*
* <code><pre>
* // exposes instance values and 'ismissing' macro
* InstancesHelper instancesHelper = new InstancesHelper(dataset);
*
* // creates the AST
* Node node = Parser.parse(
* // expression
* expression, // textual representation of the program
* // variables
* instancesHelper,
* // macros
* new MacroDeclarationsCompositor(
* instancesHelper,
* new MathFunctions(),
* new IfElseMacro(),
* new JavaMacro()
* )
* );
*
* // type checking is neccessary, but allows for greater flexibility
* if (!(node instanceof DoubleExpression))
* throw new Exception("Expression must be of boolean type!");
*
* DoubleExpression program = (DoubleExpression) node;
* </pre></code>
*
* <h1>History</h1>
*
* Previously there were three very similar languages in the
* <code>weka.core.mathematicalexpression</code> package,
* <code>weka.core.AttributeExpression</code> class and the
* <code>weka.filters.unsupervised.instance.subsetbyexpression</code> package.</br>
* Due to their similarities it was decided to unify them into one expressionlanguage.
* However backwards compatibility was an important goal, that's why there are
* some quite redundant parts in the language (e.g. both 'and' and '&' are operators
* for logical and).
*
* @author Benjamin Weber ( benweber at student dot ethz dot ch )
* @version $Revision: 1000 $
*/
package weka.core.expressionlanguage;
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/expressionlanguage
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/expressionlanguage/common/IfElseMacro.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/>.
*/
/*
* IfElseMacro.java
* Copyright (C) 2015 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.expressionlanguage.common;
import weka.core.expressionlanguage.core.Node;
import weka.core.expressionlanguage.core.Macro;
import weka.core.expressionlanguage.core.MacroDeclarations;
import weka.core.expressionlanguage.core.SemanticException;
import weka.core.expressionlanguage.common.Primitives.BooleanExpression;
import weka.core.expressionlanguage.common.Primitives.DoubleExpression;
import weka.core.expressionlanguage.common.Primitives.StringExpression;
/**
* A macro declaration exposing the <code>ifelse</code> function.</p>
*
* The ifelse macro can be used as follows:</br>
* <code>ifelse(condition, ifpart, elsepart)</code></p>
*
* Whith the following constraints:</br>
* <ul>
* <li>condition must be of boolean type</li>
* <li>ifpart and elsepart must be of the same type</li>
* <li>ifpart must be either of boolean, double or string type</li>
* </ul>
*
* Examples:</br>
* <ul>
* <li><code>ifelse(A < B, true, A = B)</code></li>
* <li><code>ifelse(A = B, 4.0^2, 1/5)</code></li>
* <li><code>ifelse(A > B, 'bigger', 'smaller')</code></li>
* </ul>
*
* @author Benjamin Weber ( benweber at student dot ethz dot ch )
* @version $Revision: 1000 $
*/
public class IfElseMacro implements MacroDeclarations, Macro {
private final static String IF_ELSE = "ifelse";
/**
* Whether the macro is declared
*
* @param name name of the macro
* @return whether the macro is declared
*/
@Override
public boolean hasMacro(String name) {
return IF_ELSE.equals(name);
}
/**
* Tries to fetch the macro</p>
*
* The same invariant of {@link MacroDeclarations} applies here too.
*
* @param name name of the macro
* @return a macro
*/
@Override
public Macro getMacro(String name) {
if (IF_ELSE.equals(name))
return this;
throw new RuntimeException("Undefined Macro '" + name + "'!");
}
/**
* Evaluates the ifelse macro
*
* @param params the parameters
* @return an AST (abstract syntax tree) node evaluating the ifelse function
*/
@Override
public Node evaluate(Node... params) throws SemanticException {
if (params.length != 3)
throw new SemanticException("ifelse takes exactly 3 arguments!");
if (!(params[0] instanceof BooleanExpression))
throw new SemanticException("ifelse's first parameter must be boolean!");
if (params[1] instanceof BooleanExpression
&& params[2] instanceof BooleanExpression) {
return new BooleanIfElse(
(BooleanExpression) params[0],
(BooleanExpression) params[1],
(BooleanExpression) params[2]
);
} else if (params[1] instanceof DoubleExpression
&& params[2] instanceof DoubleExpression) {
return new DoubleIfElse(
(BooleanExpression) params[0],
(DoubleExpression) params[1],
(DoubleExpression) params[2]
);
} else if (params[1] instanceof StringExpression
&& params[2] instanceof StringExpression) {
return new StringIfElse(
(BooleanExpression) params[0],
(StringExpression) params[1],
(StringExpression) params[2]
);
}
throw new SemanticException("ifelse's second and third parameter must be doubles, booleans or Strings!");
}
private static class DoubleIfElse implements DoubleExpression {
private final BooleanExpression condition;
private final DoubleExpression ifPart;
private final DoubleExpression elsePart;
public DoubleIfElse(BooleanExpression condition,
DoubleExpression ifPart,
DoubleExpression elsePart) {
this.condition = condition;
this.ifPart = ifPart;
this.elsePart = elsePart;
}
@Override
public double evaluate() {
if (condition.evaluate())
return ifPart.evaluate();
return elsePart.evaluate();
}
}
private static class BooleanIfElse implements BooleanExpression {
private final BooleanExpression condition;
private final BooleanExpression ifPart;
private final BooleanExpression elsePart;
public BooleanIfElse(BooleanExpression condition,
BooleanExpression ifPart,
BooleanExpression elsePart) {
this.condition = condition;
this.ifPart = ifPart;
this.elsePart = elsePart;
}
@Override
public boolean evaluate() {
if (condition.evaluate())
return ifPart.evaluate();
return elsePart.evaluate();
}
}
private static class StringIfElse implements StringExpression {
private final BooleanExpression condition;
private final StringExpression ifPart;
private final StringExpression elsePart;
public StringIfElse(BooleanExpression condition,
StringExpression ifPart,
StringExpression elsePart) {
this.condition = condition;
this.ifPart = ifPart;
this.elsePart = elsePart;
}
@Override
public String evaluate() {
if (condition.evaluate())
return ifPart.evaluate();
return elsePart.evaluate();
}
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/expressionlanguage
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/expressionlanguage/common/JavaMacro.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/>.
*/
/*
* JavaMacro.java
* Copyright (C) 2015 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.expressionlanguage.common;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;
import weka.core.expressionlanguage.common.Primitives.BooleanExpression;
import weka.core.expressionlanguage.common.Primitives.DoubleExpression;
import weka.core.expressionlanguage.common.Primitives.StringConstant;
import weka.core.expressionlanguage.common.Primitives.StringExpression;
import weka.core.expressionlanguage.core.Macro;
import weka.core.expressionlanguage.core.MacroDeclarations;
import weka.core.expressionlanguage.core.Node;
import weka.core.expressionlanguage.core.SemanticException;
/**
* A macro declarations that exposes the java macro to a program.</p>
*
* The java macro can be used as follows</br>
* </code>java(class, signature, arguments)</code></p>
*
* Where class is the name of class, signature is the signature of the function
* and arguments is a list of arguments passed to the java function.</p>
*
* The signature follows the pattern:</br>
* <code>type name '(' [ type [ ',' type ]* ] ')'</code></br>
* where type is one of 'boolean', 'double' or 'String' and name must be a valid
* java identifier.</p>
*
* Examples:</br>
* <ul>
* <li><code>java('java.lang.Math', 'double sqrt(double)', 4.0)</code></li>
* <li><code>java('java.lang.String', 'String valueOf(double)', 2^30)</code></li>
* </ul>
*
* @author Benjamin Weber ( benweber at student dot ethz dot ch )
* @version $Revision: 1000 $
*/
public class JavaMacro implements MacroDeclarations, Macro {
private static final String JAVA_MACRO = "java";
private static final String BOOLEAN = "boolean";
private static final String DOUBLE = "double";
private static final String STRING = "String";
/**
* Evaluates the java macro on the given arguments
*
* @param nodes the arguments to the java macro
* @retun an AST (abstract syntax tree) node
*/
@Override
public Node evaluate(Node... nodes) throws SemanticException {
if (nodes.length < 2)
throw new SemanticException("The " + JAVA_MACRO + " macro takes at least 2 arguments!");
if (!(nodes[0] instanceof StringConstant && nodes[1] instanceof StringConstant))
throw new SemanticException(JAVA_MACRO + "'s first and second argument must be String constants!");
Node[] parameterNodes = Arrays.copyOfRange(nodes, 2, nodes.length);
String className = ((StringConstant) nodes[0]).evaluate();
String signature = ((StringConstant) nodes[1]).evaluate();
// get types
List<Class<?>> parameterTypes = new ArrayList<Class<?>>();
String name = parseSignature(signature, parameterTypes);
Class<?> returnType = parameterTypes.remove(0);
// get method
Method m;
try {
m = Class.forName(className).getMethod(name, parameterTypes.toArray(new Class<?>[0]));
} catch (Exception e) {
throw new SemanticException("Failed to load method '"
+ className + "." + name + "' in " + JAVA_MACRO + " macro!", e);
}
// check parameters
if (parameterTypes.size() != parameterNodes.length)
throw new SemanticException("Wrong amount of parameters given in " + JAVA_MACRO + " macro!");
for (int i = 0; i < parameterTypes.size() && i < parameterNodes.length; i++) {
if (parameterTypes.get(i).equals(Boolean.TYPE) && parameterNodes[i] instanceof BooleanExpression)
continue;
if (parameterTypes.get(i).equals(Double.TYPE) && parameterNodes[i] instanceof DoubleExpression)
continue;
if (parameterTypes.get(i).equals(String.class) && parameterNodes[i] instanceof StringExpression)
continue;
throw new SemanticException("Type error in " + JAVA_MACRO + " macro!");
}
if (returnType.equals(Boolean.TYPE))
return new BooleanJavaMethod(m, parameterNodes);
if (returnType.equals(Double.TYPE))
return new DoubleJavaMethod(m, parameterNodes);
if (returnType.equals(String.class))
return new StringJavaMethod(m, parameterNodes);
assert false;
throw new SemanticException("Internal error in " + JAVA_MACRO + " macro!");
}
/**
* Parses a signature
*
* @param signature signature to be parsed
* @param types List into which the types get safed
* @return name of the function in the signature
* @throws InvalidSignature if the signature doesn't follow the specified pattern
*/
private String parseSignature(String signature, List<Class<?>> types) throws InvalidSignature {
// tokens now should be <returntype> <name> '(' [ <type> [ ',' <type> ]* ] ')'
List<String> tokens = tokenize(signature);
if (tokens.size() < 4)
throw new InvalidSignature("Not enough tokens in '" + signature + "'");
// get return type
types.add(getType(tokens.get(0)));
// check name
if (!isJavaIdentifier(tokens.get(1)))
throw new InvalidSignature("Invalid function name '" + tokens.get(1) + "'");
String name = tokens.get(1);
// check opening bracket
if (!"(".equals(tokens.get(2)))
throw new InvalidSignature("Missing opening bracket, got '" + tokens.get(2) + "' instead");
boolean first = true;
int i = 3;
for (; i < tokens.size() && !")".equals(tokens.get(i)); i++) {
// check comma
if (!first && !",".equals(tokens.get(i)))
throw new InvalidSignature("Missing comma between parameters, got '" + tokens.get(i) + "' instead");
if (!first)
++i;
// get parameter
if (i >= tokens.size())
throw new InvalidSignature("No parameter after comma!");
types.add(getType(tokens.get(i)));
first = false;
}
// check closing bracket
if (i < tokens.size() && !")".equals(tokens.get(i))) {
System.out.println(i);
System.out.println(tokens);
throw new InvalidSignature("Missing closing bracket, got '" + tokens.get(i) + "' instead");
}
// check end
if (i != tokens.size() - 1)
throw new InvalidSignature("Failed parsing signature at token '" + tokens.get(i) + "'");
return name;
}
/**
* Tokenizes a signature
*
* @param signature to be tokenized
* @return list of tokens
*/
private List<String> tokenize(String signature) {
// split on white spaces
String[] whiteSpaceTokens = signature.split("\\s+");
// split on ,() but also return ,()
List<String> tokens = new ArrayList<String>();
for (String token : whiteSpaceTokens) {
StringTokenizer tokenizer = new StringTokenizer(token, ",()", true);
while (tokenizer.hasMoreElements())
tokens.add(tokenizer.nextToken());
}
return tokens;
}
/**
* Tries to fetch a {@link Class<?>} for the given type
*
* @param type name of the type
* @return {@link Class<?>} for the type
* @throws InvalidSignature if the type is invalid
*/
private Class<?> getType(String type) throws InvalidSignature {
if (type.equals(BOOLEAN)) {
return Boolean.TYPE;
} else if (type.equals(DOUBLE)) {
return Double.TYPE;
} else if (type.equals(STRING)) {
return String.class;
} else {
throw new InvalidSignature("Expected type, got '" + type + "' instead");
}
}
/**
* Whether identifier is a valid java identifier
*
* @param identifier the identifier to be tested
* @return whether the identifier is a valid java identifier
*/
private boolean isJavaIdentifier(String identifier) {
if (identifier.length() == 0)
return false;
if (!Character.isJavaIdentifierStart(identifier.charAt(0)))
return false;
for (int i = 1; i < identifier.length(); i++)
if (!Character.isJavaIdentifierPart(identifier.charAt(i)))
return false;
return true;
}
private static class InvalidSignature extends SemanticException {
/** for serialization */
private static final long serialVersionUID = -4198745015342335018L;
public InvalidSignature(String reason) {
super("Invalid function signature in " + JAVA_MACRO + " macro (" + reason + ")");
}
}
/**
* Whether the macro declarations contains the macro
*
* @param name name of the macro
* @return whether the macro is declared
*/
@Override
public boolean hasMacro(String name) {
return JAVA_MACRO.equals(name);
}
@Override
public Macro getMacro(String name) {
if (hasMacro(name))
return this;
throw new RuntimeException("Undefined macro '" + name + "'!");
}
private static abstract class JavaMethod implements Node {
protected final Method method;
protected final Node[] params;
protected final Object[] args;
/**
* Constructs a JavaMethod encapsulating the given method with the given
* arguments.</p>
*
* Requires that the given arguments match the parameters of the method.
*
* @param method method to be encapsulated
* @param params the arguments for the method
*/
public JavaMethod(Method method, Node... params) {
assert Modifier.isStatic(method.getModifiers());
this.method = method;
this.params = params;
args = new Object[params.length];
}
protected void evaluateArgs() {
for (int i = 0; i < params.length; ++i) {
if (params[i] instanceof BooleanExpression) {
args[i] = new Boolean(((BooleanExpression) params[i]).evaluate());
} else if (params[i] instanceof DoubleExpression) {
args[i] = new Double(((DoubleExpression) params[i]).evaluate());
} else if (params[i] instanceof StringExpression) {
args[i] = ((StringExpression) params[i]).evaluate();
} // else shouldn't happen!
}
}
}
private static class BooleanJavaMethod extends JavaMethod implements BooleanExpression {
public BooleanJavaMethod(Method method, Node... params) {
super(method, params);
assert Boolean.TYPE.equals(method.getReturnType());
}
@Override
public boolean evaluate() {
try {
evaluateArgs();
return (Boolean) method.invoke(null, args);
} catch (Exception e) {
throw new RuntimeException(
"Failed to execute java function '" + method.getName() + "'!", e);
}
}
}
private static class DoubleJavaMethod extends JavaMethod implements DoubleExpression {
public DoubleJavaMethod(Method method, Node... params) {
super(method, params);
assert Double.TYPE.equals(method.getReturnType());
}
@Override
public double evaluate() {
try {
evaluateArgs();
return (Double) method.invoke(null, args);
} catch (Exception e) {
throw new RuntimeException(
"Failed to execute java function '" + method.getName() + "'!", e);
}
}
}
private static class StringJavaMethod extends JavaMethod implements StringExpression {
public StringJavaMethod(Method method, Node... params) {
super(method, params);
assert String.class.equals(method.getReturnType());
}
@Override
public String evaluate() {
try {
evaluateArgs();
return (String) method.invoke(null, args);
} catch (Exception e) {
throw new RuntimeException(
"Failed to execute java function '" + method.getName() + "'!", e);
}
}
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/expressionlanguage
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/expressionlanguage/common/MacroDeclarationsCompositor.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/>.
*/
/*
* MacroDeclarationsCompositor.java
* Copyright (C) 2015 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.expressionlanguage.common;
import weka.core.expressionlanguage.core.Macro;
import weka.core.expressionlanguage.core.MacroDeclarations;
/**
* A helper class that allows to combine several macro declarations together.</p>
*
* It can be though of as layering several scopes over one another.</p>
*
* It will delegate the {@link #hasMacro(String)} and {@link #getMacro(String)}
* methods to other macro declarations.</p>
*
* Each macro declaration combined is checked in sequential order.</p>
*
* No checks for conflicts are done. Thus shadowing is possible.</p>
*
* @author Benjamin Weber ( benweber at student dot ethz dot ch )
* @version $Revision: 1000 $
*/
public class MacroDeclarationsCompositor implements MacroDeclarations {
/** the declarations being combined */
private final MacroDeclarations[] declarations;
/**
* Constructs a {@link MacroDeclarationsCompositor} containing the provided
* declarations</p>
*
* The order of the declarations will determine the order of checking the
* declarations for macros.</p>
*
* @param declarations the declarations being combined
*/
public MacroDeclarationsCompositor(MacroDeclarations... declarations) {
this.declarations = declarations;
}
/**
* Whether the macro is contained in one of the combined declarations.
*
* @param name name of the macro
* @return whether the macro is contained in one of the combined declarations
*/
@Override
public boolean hasMacro(String name) {
for (MacroDeclarations declaration : declarations)
if (declaration.hasMacro(name))
return true;
return false;
}
/**
* Tries to fetch a macro from one of the combined declarations.</p>
*
* The same invariant of {@link MacroDeclarations} applies here too.
*
* @param name the name of the macro to be fetched
* @return a macro
*/
@Override
public Macro getMacro(String name) {
for (MacroDeclarations declaration : declarations)
if (declaration.hasMacro(name))
return declaration.getMacro(name);
throw new RuntimeException("Macro '" + name + "' doesn't exist!");
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/expressionlanguage
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/expressionlanguage/common/MathFunctions.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/>.
*/
/*
* MathFunctions.java
* Copyright (C) 2015 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.expressionlanguage.common;
import java.util.Map;
import java.util.HashMap;
import weka.core.expressionlanguage.core.Node;
import weka.core.expressionlanguage.core.Macro;
import weka.core.expressionlanguage.core.MacroDeclarations;
import weka.core.expressionlanguage.core.SemanticException;
import weka.core.expressionlanguage.common.Primitives.DoubleExpression;
/**
* Macro declarations for common mathematical functions.</p>
*
* The following functions are being exposed through macros:</br>
* <ul>
* <li>{@link java.lang.Math.abs(double)} as abs</li>
* <li>{@link java.lang.Math.sqrt(double)} as sqrt</li>
* <li>{@link java.lang.Math.log(double)} as log</li>
* <li>{@link java.lang.Math.exp(double)} as exp</li>
* <li>{@link java.lang.Math.sin(double)} as sin</li>
* <li>{@link java.lang.Math.cos(double)} as cos</li>
* <li>{@link java.lang.Math.tan(double)} as tan</li>
* <li>{@link java.lang.Math.rint(double)} as rint</li>
* <li>{@link java.lang.Math.floor(double)} as floor</li>
* <li>{@link java.lang.Math.ceil(double)} as ceil</li>
* <li>{@link java.lang.Math.pow(double)} as pow</li>
* </ul>
*
* @author Benjamin Weber ( benweber at student dot ethz dot ch )
* @version $Revision: 1000 $
*/
public class MathFunctions implements MacroDeclarations {
/** the macros to be exposed */
private static Map<String, Macro> macros = new HashMap<String, Macro>();
static {
macros.put("abs", new DoubleUnaryMacro(AbsFunction.class));
macros.put("sqrt", new DoubleUnaryMacro(SqrtFunction.class));
macros.put("log", new DoubleUnaryMacro(LogFunction.class));
macros.put("exp", new DoubleUnaryMacro(ExpFunction.class));
macros.put("sin", new DoubleUnaryMacro(SinFunction.class));
macros.put("cos", new DoubleUnaryMacro(CosFunction.class));
macros.put("tan", new DoubleUnaryMacro(TanFunction.class));
macros.put("rint", new DoubleUnaryMacro(RintFunction.class));
macros.put("floor", new DoubleUnaryMacro(FloorFunction.class));
macros.put("ceil", new DoubleUnaryMacro(CeilFunction.class));
macros.put("pow", new PowMacro());
}
/**
* Whether the macro is declared
*
* @param name of the macro
* @return whether the macro is declared
*/
@Override
public boolean hasMacro(String name) {
return macros.containsKey(name);
}
/**
* Tries to fetch the macro</p>
*
* The same invariant of {@link MacroDeclarations} applies here too.
*
* @param name name of the macro
* @return a macro
*/
@Override
public Macro getMacro(String name) {
if (macros.containsKey(name))
return macros.get(name);
throw new RuntimeException("Macro '" + name + "' undefined!");
}
private static class DoubleUnaryMacro implements Macro {
private final Class<? extends DoubleUnaryFunction> func;
public DoubleUnaryMacro(Class<? extends DoubleUnaryFunction> func) {
this.func = func;
}
private String name() {
return func.getSimpleName();
}
@Override
public Node evaluate(Node... params) throws SemanticException {
if (params.length != 1)
throw new SemanticException("'" + name() + "' takes exactly one argument!");
if (!(params[0] instanceof DoubleExpression))
throw new SemanticException("'" + name() + "'s first argument must be double!");
try {
Node node =(Node) func.getConstructor(DoubleExpression.class).newInstance(params[0]);
return node;
} catch (Exception e) {
throw new RuntimeException("Failed to instantiate '" + name() + "'!", e);
}
}
}
private static abstract class DoubleUnaryFunction implements DoubleExpression {
final DoubleExpression expr;
DoubleUnaryFunction(DoubleExpression expr) {
this.expr = expr;
}
}
private static class AbsFunction extends DoubleUnaryFunction {
public AbsFunction(DoubleExpression expr) {
super(expr);
}
@Override
public double evaluate() {
return Math.abs(expr.evaluate());
}
}
private static class SqrtFunction extends DoubleUnaryFunction {
public SqrtFunction(DoubleExpression expr) {
super(expr);
}
@Override
public double evaluate() {
return Math.sqrt(expr.evaluate());
}
}
private static class LogFunction extends DoubleUnaryFunction {
public LogFunction(DoubleExpression expr) {
super(expr);
}
@Override
public double evaluate() {
return Math.log(expr.evaluate());
}
}
private static class ExpFunction extends DoubleUnaryFunction {
public ExpFunction(DoubleExpression expr) {
super(expr);
}
@Override
public double evaluate() {
return Math.exp(expr.evaluate());
}
}
private static class SinFunction extends DoubleUnaryFunction {
public SinFunction(DoubleExpression expr) {
super(expr);
}
@Override
public double evaluate() {
return Math.sin(expr.evaluate());
}
}
private static class CosFunction extends DoubleUnaryFunction {
public CosFunction(DoubleExpression expr) {
super(expr);
}
@Override
public double evaluate() {
return Math.cos(expr.evaluate());
}
}
private static class TanFunction extends DoubleUnaryFunction {
public TanFunction(DoubleExpression expr) {
super(expr);
}
@Override
public double evaluate() {
return Math.tan(expr.evaluate());
}
}
private static class RintFunction extends DoubleUnaryFunction {
public RintFunction(DoubleExpression expr) {
super(expr);
}
@Override
public double evaluate() {
return Math.rint(expr.evaluate());
}
}
private static class FloorFunction extends DoubleUnaryFunction {
public FloorFunction(DoubleExpression expr) {
super(expr);
}
@Override
public double evaluate() {
return Math.floor(expr.evaluate());
}
}
private static class CeilFunction extends DoubleUnaryFunction {
public CeilFunction(DoubleExpression expr) {
super(expr);
}
@Override
public double evaluate() {
return Math.ceil(expr.evaluate());
}
}
private static class PowMacro implements Macro {
@Override
public Node evaluate(Node... params) throws SemanticException {
if (params.length != 2)
throw new SemanticException("pow takes exactly two arguments!");
if (!(params[0] instanceof DoubleExpression))
throw new SemanticException("pow's first argument must be double!");
if (!(params[1] instanceof DoubleExpression))
throw new SemanticException("pow's second argument must be double!");
return new
PowFunction((DoubleExpression) params[0], (DoubleExpression) params[1]);
}
}
private static class PowFunction implements DoubleExpression {
private final DoubleExpression base;
private final DoubleExpression exponent;
public PowFunction(DoubleExpression base, DoubleExpression exponent) {
this.base = base;
this.exponent = exponent;
}
@Override
public double evaluate() {
return Math.pow(base.evaluate(), exponent.evaluate());
}
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/expressionlanguage
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/expressionlanguage/common/NoMacros.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/>.
*/
/*
* NoMacros.java
* Copyright (C) 2015 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.expressionlanguage.common;
import weka.core.expressionlanguage.core.Macro;
import weka.core.expressionlanguage.core.MacroDeclarations;
/**
* A macro declarations that contains no macros at all
*
* @author Benjamin Weber ( benweber at student dot ethz dot ch )
* @version $Revision: 1000 $
*/
public class NoMacros implements MacroDeclarations {
/**
* Whether the macro is declared. Always returns <code>false</code>
*
* @param name name of the macro
* @return whether the macro is declared. Always <code>false</code>.
*/
@Override
public boolean hasMacro(String name) {
return false;
}
/**
* Tries to fetch a macro. Will always fail.</p>
*
* The same invariant of {@link MacroDeclarations} applies here too.
*
* @param name name of the macro
* @return nothing
*/
@Override
public Macro getMacro(String name) {
throw new RuntimeException("Macro '" + name + "' doesn't exist!");
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/expressionlanguage
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/expressionlanguage/common/NoVariables.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/>.
*/
/*
* NoVariables.java
* Copyright (C) 2015 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.expressionlanguage.common;
import weka.core.expressionlanguage.core.Node;
import weka.core.expressionlanguage.core.VariableDeclarations;
/**
* A variable declarations that contains no variables
*
* @author Benjamin Weber ( benweber at student dot ethz dot ch )
* @version $Revision: 1000 $
*/
public class NoVariables implements VariableDeclarations {
/**
* Whether the variable is declared. Will always return <code>false</code>
*
* @param name name of the variable
* @return whether the variable is declared. Always <code>false</code>.
*/
@Override
public boolean hasVariable(String name) {
return false;
}
/**
* Tries to fetch the variable. Will always fail.</p>
*
* The same invariant of {@link VariableDeclarations} applies here too.
*
* @param name name of the variable
* @return nothing
*/
@Override
public Node getVariable(String name) {
throw new RuntimeException("Variable '" + name + "' doesn't exist!");
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/expressionlanguage
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/expressionlanguage/common/Operators.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/>.
*/
/*
* Operators.java
* Copyright (C) 2015 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.expressionlanguage.common;
import java.io.Serializable;
import java.util.regex.Pattern;
import weka.core.expressionlanguage.common.Primitives.BooleanExpression;
import weka.core.expressionlanguage.common.Primitives.DoubleExpression;
import weka.core.expressionlanguage.common.Primitives.StringConstant;
import weka.core.expressionlanguage.common.Primitives.StringExpression;
import weka.core.expressionlanguage.core.Node;
import weka.core.expressionlanguage.core.SemanticException;
/**
* A class to specify the semantics of operators in the expressionlanguage</p>
*
* To move the operator semantics outside the parser they are specified
* here.</br> The parser can then call these methods so that operators can be
* resolved to AST (abstract syntax tree) nodes.
*
* @author Benjamin Weber ( benweber at student dot ethz dot ch )
* @version $Revision: 1000 $
*/
public class Operators {
/**
* '<code>+</code>' plus operator
*/
public static Node plus(Node left, Node right) throws SemanticException {
if (left instanceof DoubleExpression && right instanceof DoubleExpression)
return new Addition((DoubleExpression) left, (DoubleExpression) right);
if (left instanceof StringExpression && right instanceof StringExpression)
return new Concatenation((StringExpression) left,
(StringExpression) right);
throw new SemanticException("Plus is only applicable to doubles & Strings!");
}
/**
* '<code>-</code>' minus operator
*/
public static Node minus(Node left, Node right) throws SemanticException {
if (left instanceof DoubleExpression && right instanceof DoubleExpression)
return new Subtraction((DoubleExpression) left, (DoubleExpression) right);
throw new SemanticException("Minus is only applicable to doubles!");
}
/**
* '<code>*</code>' times operator
*/
public static Node times(Node left, Node right) throws SemanticException {
if (left instanceof DoubleExpression && right instanceof DoubleExpression)
return new Multiplication((DoubleExpression) left,
(DoubleExpression) right);
throw new SemanticException("Multiplication is only applicable to doubles!");
}
/**
* '<code>/</code>' division operator
*/
public static Node division(Node left, Node right) throws SemanticException {
if (left instanceof DoubleExpression && right instanceof DoubleExpression)
return new Division((DoubleExpression) left, (DoubleExpression) right);
throw new SemanticException("division is only applicable to doubles!");
}
/**
* '<code>+</code>' unary plus operator
*/
public static Node uplus(Node expr) throws SemanticException {
if (expr instanceof DoubleExpression)
return expr;
throw new SemanticException("unary minus is only applicable to doubles!");
}
/**
* '<code>-</code>' unary minus operator
*/
public static Node uminus(Node expr) throws SemanticException {
if (expr instanceof DoubleExpression)
return new UMinus((DoubleExpression) expr);
throw new SemanticException("unary minus is only applicable to doubles!");
}
/**
* '<code>^</code>' power operator
*/
public static Node pow(Node left, Node right) throws SemanticException {
if (left instanceof DoubleExpression && right instanceof DoubleExpression)
return new Pow((DoubleExpression) left, (DoubleExpression) right);
throw new SemanticException("Power is only applicable to doubles!");
}
/**
* '<code><</code>' less than operator
*/
public static BooleanExpression lessThan(Node left, Node right)
throws SemanticException {
if (left instanceof DoubleExpression && right instanceof DoubleExpression)
return new LessThan((DoubleExpression) left, (DoubleExpression) right);
throw new SemanticException("less than is only applicable to doubles!");
}
/**
* '<code><=</code>' less equal operator
*/
public static BooleanExpression lessEqual(Node left, Node right)
throws SemanticException {
if (left instanceof DoubleExpression && right instanceof DoubleExpression)
return new LessEqual((DoubleExpression) left, (DoubleExpression) right);
throw new SemanticException("less equal is only applicable to doubles!");
}
/**
* '<code>></code>' greater than operator
*/
public static BooleanExpression greaterThan(Node left, Node right)
throws SemanticException {
if (left instanceof DoubleExpression && right instanceof DoubleExpression)
return new GreaterThan((DoubleExpression) left, (DoubleExpression) right);
throw new SemanticException("greater than is only applicable to doubles!");
}
/**
* '<code>>=</code>' greater equal operator
*/
public static BooleanExpression greaterEqual(Node left, Node right)
throws SemanticException {
if (left instanceof DoubleExpression && right instanceof DoubleExpression)
return new GreaterEqual((DoubleExpression) left, (DoubleExpression) right);
throw new SemanticException("greater equal is only applicable to doubles!");
}
/**
* '<code>=</code>' equal operator
*/
public static BooleanExpression equal(Node left, Node right)
throws SemanticException {
if (left instanceof DoubleExpression && right instanceof DoubleExpression)
return new Equal((DoubleExpression) left, (DoubleExpression) right);
throw new SemanticException("equal is only applicable to doubles!");
}
/**
* '<code>!</code>' or '<code>not</code>' logical not operator
*/
public static BooleanExpression not(Node expr) throws SemanticException {
if (expr instanceof BooleanExpression)
return new Not((BooleanExpression) expr);
throw new SemanticException("Logical not is only applicable to booleans!");
}
/**
* '<code>&</code>' or '<code>and</code>' logical and operator
*/
public static BooleanExpression and(Node left, Node right)
throws SemanticException {
if (left instanceof BooleanExpression && right instanceof BooleanExpression)
return new And((BooleanExpression) left, (BooleanExpression) right);
throw new SemanticException("Logical and is only applicable to booleans!");
}
/**
* '<code>|</code>' or '<code>or</code>' logical or operator
*/
public static BooleanExpression or(Node left, Node right)
throws SemanticException {
if (left instanceof BooleanExpression && right instanceof BooleanExpression)
return new Or((BooleanExpression) left, (BooleanExpression) right);
throw new SemanticException("Logical or is only applicable to booleans!");
}
/**
* '<code>is</code>' is operator (to check for string equality)
*/
public static BooleanExpression is(Node left, Node right)
throws SemanticException {
if (left instanceof StringExpression && right instanceof StringExpression)
return new Is((StringExpression) left, (StringExpression) right);
throw new SemanticException("Is operator is only applicable to strings!");
}
/**
* '<code>regexp</code>' regexp operator (to check for string matching a given
* regular expression)
*/
public static BooleanExpression regexp(Node left, Node right)
throws SemanticException {
if (left instanceof StringExpression) {
if (right instanceof StringConstant)
return new CompiledRegexp((StringExpression) left,
((StringConstant) right).evaluate());
if (right instanceof StringExpression)
return new Regexp((StringExpression) left, (StringExpression) right);
}
throw new SemanticException("Is operator is only applicable to strings!");
}
private static abstract class DoubleBinaryExpression implements
DoubleExpression, Serializable {
private static final long serialVersionUID = -5632795030311662604L;
final DoubleExpression left;
final DoubleExpression right;
public DoubleBinaryExpression(DoubleExpression left, DoubleExpression right) {
this.left = left;
this.right = right;
}
}
private static class Addition extends DoubleBinaryExpression implements
Serializable {
private static final long serialVersionUID = 4742624413216069408L;
public Addition(DoubleExpression left, DoubleExpression right) {
super(left, right);
}
@Override
public double evaluate() {
return left.evaluate() + right.evaluate();
}
}
private static class Subtraction extends DoubleBinaryExpression implements
Serializable {
private static final long serialVersionUID = 2136831100085494486L;
public Subtraction(DoubleExpression left, DoubleExpression right) {
super(left, right);
}
@Override
public double evaluate() {
return left.evaluate() - right.evaluate();
}
}
private static class Multiplication extends DoubleBinaryExpression implements
Serializable {
private static final long serialVersionUID = 3119913759352807383L;
public Multiplication(DoubleExpression left, DoubleExpression right) {
super(left, right);
}
@Override
public double evaluate() {
return left.evaluate() * right.evaluate();
}
}
private static class UMinus implements DoubleExpression, Serializable {
private static final long serialVersionUID = 8950381197456945108L;
private final DoubleExpression expr;
public UMinus(DoubleExpression expr) {
this.expr = expr;
}
@Override
public double evaluate() {
return -(expr.evaluate());
}
}
private static class Division extends DoubleBinaryExpression implements
Serializable {
private static final long serialVersionUID = -8438478400061106753L;
public Division(DoubleExpression left, DoubleExpression right) {
super(left, right);
}
@Override
public double evaluate() {
return left.evaluate() / right.evaluate();
}
}
private static class Pow extends DoubleBinaryExpression implements
Serializable {
private static final long serialVersionUID = -5103792715762588751L;
public Pow(DoubleExpression left, DoubleExpression right) {
super(left, right);
}
@Override
public double evaluate() {
return Math.pow(left.evaluate(), right.evaluate());
}
}
private static abstract class BooleanBinaryExpression<T> implements
BooleanExpression, Serializable {
private static final long serialVersionUID = -5375209267408472403L;
final T left;
final T right;
public BooleanBinaryExpression(T left, T right) {
this.left = left;
this.right = right;
}
}
private static class LessThan extends
BooleanBinaryExpression<DoubleExpression> implements Serializable {
private static final long serialVersionUID = -4323355926531143842L;
public LessThan(DoubleExpression left, DoubleExpression right) {
super(left, right);
}
@Override
public boolean evaluate() {
return left.evaluate() < right.evaluate();
}
}
private static class LessEqual extends
BooleanBinaryExpression<DoubleExpression> implements Serializable {
private static final long serialVersionUID = -1949681957973467756L;
public LessEqual(DoubleExpression left, DoubleExpression right) {
super(left, right);
}
@Override
public boolean evaluate() {
return left.evaluate() <= right.evaluate();
}
}
private static class GreaterThan extends
BooleanBinaryExpression<DoubleExpression> implements Serializable {
private static final long serialVersionUID = 4541137398510802289L;
public GreaterThan(DoubleExpression left, DoubleExpression right) {
super(left, right);
}
@Override
public boolean evaluate() {
return left.evaluate() > right.evaluate();
}
}
private static class GreaterEqual extends
BooleanBinaryExpression<DoubleExpression> implements Serializable {
private static final long serialVersionUID = 3425719763247073382L;
public GreaterEqual(DoubleExpression left, DoubleExpression right) {
super(left, right);
}
@Override
public boolean evaluate() {
return left.evaluate() >= right.evaluate();
}
}
private static class Equal extends BooleanBinaryExpression<DoubleExpression>
implements Serializable {
private static final long serialVersionUID = 4154699553290213656L;
public Equal(DoubleExpression left, DoubleExpression right) {
super(left, right);
}
@Override
public boolean evaluate() {
return left.evaluate() == right.evaluate();
}
}
private static class And extends BooleanBinaryExpression<BooleanExpression>
implements Serializable {
private static final long serialVersionUID = 6786891291372905824L;
public And(BooleanExpression left, BooleanExpression right) {
super(left, right);
}
@Override
public boolean evaluate() {
return left.evaluate() && right.evaluate();
}
}
private static class Or extends BooleanBinaryExpression<BooleanExpression>
implements Serializable {
private static final long serialVersionUID = -5943051466425242059L;
public Or(BooleanExpression left, BooleanExpression right) {
super(left, right);
}
@Override
public boolean evaluate() {
return left.evaluate() || right.evaluate();
}
}
private static class Not implements BooleanExpression, Serializable {
private static final long serialVersionUID = -6235716110409152192L;
private final BooleanExpression expr;
public Not(BooleanExpression expr) {
this.expr = expr;
}
@Override
public boolean evaluate() {
return !expr.evaluate();
}
}
private static class Is extends BooleanBinaryExpression<StringExpression>
implements Serializable {
private static final long serialVersionUID = -7519297057279624722L;
public Is(StringExpression left, StringExpression right) {
super(left, right);
}
@Override
public boolean evaluate() {
return left.evaluate().equals(right.evaluate());
}
}
private static class Regexp extends BooleanBinaryExpression<StringExpression>
implements Serializable {
private static final long serialVersionUID = -3987002284718527200L;
public Regexp(StringExpression left, StringExpression right) {
super(left, right);
}
@Override
public boolean evaluate() {
return left.evaluate().matches(right.evaluate());
}
}
private static class CompiledRegexp implements BooleanExpression,
Serializable {
private static final long serialVersionUID = -224974827347001236L;
private final StringExpression expr;
private final Pattern pattern;
public CompiledRegexp(StringExpression expr, String pattern) {
this.expr = expr;
this.pattern = Pattern.compile(pattern);
}
@Override
public boolean evaluate() {
return pattern.matcher(expr.evaluate()).matches();
}
}
private static class Concatenation implements StringExpression, Serializable {
private static final long serialVersionUID = 2413200029613562555L;
private final StringExpression left;
private final StringExpression right;
public Concatenation(StringExpression left, StringExpression right) {
this.left = left;
this.right = right;
}
@Override
public String evaluate() {
return left.evaluate() + right.evaluate();
}
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/expressionlanguage
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/expressionlanguage/common/Primitives.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/>.
*/
/*
* Primitives.java
* Copyright (C) 2015 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.expressionlanguage.common;
import weka.core.expressionlanguage.core.Node;
import java.io.Serializable;
/**
* A class providing AST (abstract syntax tree) nodes to support primitive types.
*
* @author Benjamin Weber ( benweber at student dot ethz dot ch )
* @version $Revision: 1000 $
*/
public class Primitives implements Serializable {
private static final long serialVersionUID = -6356635298310530223L;
/*
* Currently the different expressions of different primitive types are all
* evaluated through an 'evaluate()' method. This has significant impact on the
* typing system.
*
* Due to java's inheritance a node can't implement two primitive types at the
* same time. Thus each node can only ever be of exactly at most one primitive
* type.
*
* It would be possible to refactor the method names to allow implementing
* different primitive expression.
*
* However this will make things much more complicated.
*
* For example the ifelse macro will check what primitive expression is
* implemented in its parameters. Knowing that each parameter will only ever
* implement one primitive type it's easy to determine whether the ifelse
* macro can be evaluated.
* If parameters could implement two types simultaneously it wouldn't be clear
* which one should be chosen/preferred.
*/
/**
* An AST node for an expression of boolean type
*
* @author Benjamin Weber ( benweber at student dot ethz dot ch )
* @version $Revision: 1000 $
*/
public static interface BooleanExpression extends Node {
public boolean evaluate();
}
/**
* An AST node for an expression of double type
*
* @author Benjamin Weber ( benweber at student dot ethz dot ch )
* @version $Revision: 1000 $
*/
public static interface DoubleExpression extends Node {
public double evaluate();
}
/**
* An AST node for an expression of String type
*
* @author Benjamin Weber ( benweber at student dot ethz dot ch )
* @version $Revision: 1000 $
*/
public static interface StringExpression extends Node {
public String evaluate();
}
/**
* An AST node representing a boolean constant
*
* @author Benjamin Weber ( benweber at student dot ethz dot ch )
* @version $Revision: 1000 $
*/
public static class BooleanConstant implements BooleanExpression, Serializable {
private static final long serialVersionUID = -7104666336890622673L;
private final boolean value;
public BooleanConstant(boolean value) {
this.value = value;
}
@Override
public boolean evaluate() {
return value;
}
}
/**
* An AST node representing a double constant
*
* @author Benjamin Weber ( benweber at student dot ethz dot ch )
* @version $Revision: 1000 $
*/
public static class DoubleConstant implements DoubleExpression, Serializable {
private static final long serialVersionUID = 6876724986473710563L;
private final double value;
public DoubleConstant(double value) {
this.value = value;
}
@Override
public double evaluate() {
return value;
}
}
/**
* An AST node representing a string constant
*
* @author Benjamin Weber ( benweber at student dot ethz dot ch )
* @version $Revision: 1000 $
*/
public static class StringConstant implements StringExpression, Serializable {
private static final long serialVersionUID = 491766938196527684L;
private final String value;
public StringConstant(String value) {
this.value = value;
}
@Override
public String evaluate() {
return value;
}
}
/**
* An AST node representing a boolean variable
*
* @author Benjamin Weber ( benweber at student dot ethz dot ch )
* @version $Revision: 1000 $
*/
public static class BooleanVariable implements BooleanExpression, Serializable {
private static final long serialVersionUID = 6041670101306161521L;
private boolean value;
private final String name;
public BooleanVariable(String name) {
this.name = name;
}
@Override
public boolean evaluate() {
return value;
}
public String getName() {
return name;
}
public boolean getValue() {
return value;
}
public void setValue(boolean value) {
this.value = value;
}
}
/**
* An AST node representing a double variable
*
* @author Benjamin Weber ( benweber at student dot ethz dot ch )
* @version $Revision: 1000 $
*/
public static class DoubleVariable implements DoubleExpression, Serializable {
private static final long serialVersionUID = -6059066803856814750L;
private double value;
private final String name;
public DoubleVariable(String name) {
this.name = name;
}
@Override
public double evaluate() {
return this.value;
}
public String getName() {
return name;
}
public double getValue() {
return value;
}
public void setValue(double value) {
this.value = value;
}
}
/**
* An AST node representing a string variable
*
* @author Benjamin Weber ( benweber at student dot ethz dot ch )
* @version $Revision: 1000 $
*/
public static class StringVariable implements StringExpression, Serializable {
private static final long serialVersionUID = -7332982581964981085L;
private final String name;
private String value;
public StringVariable(String name) {
this.name = name;
}
@Override
public String evaluate() {
return value;
}
public String getName() {
return name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/expressionlanguage
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/expressionlanguage/common/SimpleVariableDeclarations.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/>.
*/
/*
* SimpleVariableDeclarations.java
* Copyright (C) 2015 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.expressionlanguage.common;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import weka.core.expressionlanguage.core.Node;
import weka.core.expressionlanguage.core.VariableDeclarations;
import weka.core.expressionlanguage.common.Primitives.BooleanVariable;
import weka.core.expressionlanguage.common.Primitives.DoubleVariable;
import weka.core.expressionlanguage.common.Primitives.StringVariable;
/**
* A set of customizable variable declarations for primitive types.</p>
*
* @author Benjamin Weber ( benweber at student dot ethz dot ch )
* @version $Revision: 1000 $
*/
public class SimpleVariableDeclarations implements VariableDeclarations {
/** the variable declarations */
private Map<String, Node> variables = new HashMap<String, Node>();
/** the initializer to initialize the variables with values */
private VariableInitializer initializer = new VariableInitializer();
/**
* Whether the variable is declared
*
* @param name name of the variable being queried
* @return whether the variable is declared
*/
@Override
public boolean hasVariable(String name) {
return variables.containsKey(name);
}
/**
* Tries to fetch a declared variable
*
* @param name name of the variable to be fetched
* @return an AST (abstrac syntax tree) node representing the variable
*/
@Override
public Node getVariable(String name) {
if (!variables.containsKey(name))
throw new RuntimeException("Variable '" + name + "' doesn't exist!");
initializer.add(variables.get(name));
return variables.get(name);
}
/**
* Adds a variable declaration for a boolean variable</p>
*
* Requires that the variable hasn't been declared before.
*
* @param name the name of the variable
*/
public void addBoolean(String name) {
if (variables.containsKey(name))
throw new RuntimeException("Variable '" + name + "' already exists!");
variables.put(name, new BooleanVariable(name));
}
/**
* Adds a variable declaration for a double variable</p>
*
* Requires that the variable hasn't been declared before.
*
* @param name the name of the variable
*/
public void addDouble(String name) {
if (variables.containsKey(name))
throw new RuntimeException("Variable '" + name + "' already exists!");
variables.put(name, new DoubleVariable(name));
}
/**
* Adds a variable declaration for a string variable</p>
*
* Requires that the variable hasn't been declared before.
*
* @param name the name of the variable
*/
public void addString(String name) {
if (variables.containsKey(name))
throw new RuntimeException("Variable '" + name + "' already exists!");
variables.put(name, new StringVariable(name));
}
/**
* Returns an object to initialize the declared variables
*
* @return an object to initialize the declared variables
*/
public VariableInitializer getInitializer() {
return initializer;
}
/**
* A class to initialize variables that have been declared by a
* {@link SimpleVariableDeclarations} class and used inside a program</p>
*
* Note that not all variables declared can be initialized!</br>
* Particularly variables that have been declared but are never used inside a
* program can't be initialized.</p>
*
* Then variable values that are expensive to compute don't have to be computed
* if the values are never used inside a program.
*
* @author Benjamin Weber ( benweber at student dot ethz dot ch )
* @version $Revision: 1000 $
*/
public static class VariableInitializer implements Serializable {
/** The variables that have been declared and used in a program */
private Map<String, Node> variables = new HashMap<String, Node>();
/**
* Adds a variable so that it can be initialized.</p>
*
* Requires that the var parameter is one of
* <ul>
* <li>{@link Primitives.BooleanVariable}</li>
* <li>{@link Primitives.DoubleVariable}</li>
* <li>{@link Primitives.StringVariable}</li>
* </ul>
*
* @param var an AST node representing the variable
*/
private void add(Node var) {
assert var instanceof BooleanVariable || var instanceof DoubleVariable ||
var instanceof StringVariable;
if (var instanceof BooleanVariable)
variables.put(((BooleanVariable) var).getName(), var);
else if (var instanceof DoubleVariable)
variables.put(((DoubleVariable) var).getName(), var);
else if (var instanceof StringVariable)
variables.put(((StringVariable) var).getName(), var);
}
/**
* Returns the set of variable names that can be initialized
*
* @return the set of variable names that can be initialized
*/
public Set<String> getVariables() {
return variables.keySet();
}
/**
* Returns whether the {@link VariableInitializer} contains the variable</p>
*
* @param variable name of the variable
* @return whether the variable exists
*/
public boolean hasVariable(String variable) {
return variables.containsKey(variable);
}
/**
* Sets the value of a boolean variable</p>
*
* Requires that the variable exists and is of boolean type.
*
* @param name name of the boolean variable
* @param value the value the boolean variable will be set to
*/
public void setBoolean(String name, boolean value) {
if (!variables.containsKey(name))
throw new RuntimeException("Variable '" + name + "' doesn't exist!");
if (!(variables.get(name) instanceof BooleanVariable))
throw new RuntimeException("Variable '" + name + "' is not of boolean type!");
((BooleanVariable) variables.get(name)).setValue(value);
}
/**
* Sets the value of a double variable</p>
*
* Requires that the variable exists and is of double type.
*
* @param name the name of the double variable
* @param value the value the double variable will be set to
*/
public void setDouble(String name, double value) {
if (!variables.containsKey(name))
throw new RuntimeException("Variable '" + name + "' doesn't exist!");
if (!(variables.get(name) instanceof DoubleVariable))
throw new RuntimeException("Variable '" + name + "' is not of double type!");
((DoubleVariable) variables.get(name)).setValue(value);
}
/**
* Sets the value of a string variable</p>
*
* Requires that the variable exists and is of string type.
*
* @param name the name of the string variable
* @param value the value the string variable will be set to
*/
public void setString(String name, String value) {
if (!variables.containsKey(name))
throw new RuntimeException("Variable '" + name + "' doesn't exist!");
if (!(variables.get(name) instanceof StringVariable))
throw new RuntimeException("Variable '" + name + "' is not of String type!");
((StringVariable) variables.get(name)).setValue(value);
}
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/expressionlanguage
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/expressionlanguage/common/VariableDeclarationsCompositor.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/>.
*/
/*
* VariableDeclarationsCompositor.java
* Copyright (C) 2015 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.expressionlanguage.common;
import weka.core.expressionlanguage.core.Node;
import weka.core.expressionlanguage.core.VariableDeclarations;
/**
* A helper class that allows to combine several variable declarations together.</p>
*
* It can be thought of as layering several scopes over one another.</p>
*
* It will delegate the {@link #hasVariable(String)} and {@link #getVariable(String)}
* methods to other variable declarations.</p>
*
* Each variable declaration combined is checked in sequential order.</p>
*
* No checks for conflicts are done. Thus shadowing is possible.</p>
*
* @author Benjamin Weber ( benweber at student dot ethz dot ch )
* @version $Revision: 1000 $
*/
public class VariableDeclarationsCompositor implements VariableDeclarations {
/** the declarations being combined */
private VariableDeclarations[] declarations;
/**
* Constructs a {@link VariableDeclarationsCompositor} containing the provided
* declarations</p>
*
* The order of the declarations will determine the order of checking the
* declarations for variables.</p>
*
* @param declarations the declarations being combined
*/
public VariableDeclarationsCompositor(VariableDeclarations... declarations) {
this.declarations = declarations;
}
/**
* Whether the variable is contained in one of the combined declarations.
*
* @param name name of the variable
* @return whether the variable is contained in one of the combined declarations
*/
@Override
public boolean hasVariable(String name) {
for (VariableDeclarations declaration : declarations)
if (declaration.hasVariable(name))
return true;
return false;
}
/**
* Tries to fetch a variable from one of the combined declarations.</p>
*
* The same invariant of {@link VariableDeclarations} applies here too.
*
* @param name the name of the variable to be fetched
* @return an AST (abstract syntax tree) node representing the variable
*/
@Override
public Node getVariable(String name) {
for (VariableDeclarations declaration : declarations)
if (declaration.hasVariable(name))
return declaration.getVariable(name);
throw new RuntimeException("Variable '" + name + "' doesn't exist!");
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/expressionlanguage
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/expressionlanguage/core/Macro.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/>.
*/
/*
* Macro.java
* Copyright (C) 2015 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.expressionlanguage.core;
/**
* Interface for compile time macros to enable meta programming</p>
*
* Because macros have direct access to the AST (abstract syntax tree) they can
* rewrite it as they please.
*
* @author Benjamin Weber ( benweber at student dot ethz dot ch )
* @version $Revision: 1000 $
*/
public interface Macro {
/**
* Applies a macro to a set of parameter nodes.
*
* @param nodes the nodes this macro should be applied to
* @return an AST node returned by the macro
* @throws SemanticException
*/
Node evaluate(Node... nodes) throws SemanticException;
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/expressionlanguage
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/expressionlanguage/core/MacroDeclarations.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/>.
*/
/*
* MacroDeclarations.java
* Copyright (C) 2015 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.expressionlanguage.core;
/**
* Interface to expose macros to a program.</p>
*
* It is deliberately kept very simple to give as little constraints
* as possible to implementations.</p>
*
* There is an implied invariant here:</br>
* <code>{@link #hasMacro(String)} == true ->
* {@link #getMacro(String)} != null</code></p>
*
* {@link #hasMacro(String)} should be pure i.e. have no side effects.</br>
* Whereas {@link #getMacro(String)} may have side effects.</br>
* (This is useful for creating macros on the fly in {@link #getMacro(String)})
*
* @author Benjamin Weber ( benweber at student dot ethz dot ch )
* @version $Revision: 1000 $
*/
public interface MacroDeclarations {
/**
* Whether the macro is declared
*
* @param name name of the macro being queried
* @return whether the macro is declared
*/
public boolean hasMacro(String name);
/**
* Tries to fetch the macro</p>
*
* Before a macro is fetched it shold be checked whether it is declared
* through {@link #hasMacro(String)}
* @param name
* @return
*/
public Macro getMacro(String name);
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/expressionlanguage
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/expressionlanguage/core/Node.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/>.
*/
/*
* Node.java
* Copyright (C) 2015 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.expressionlanguage.core;
import java.io.Serializable;
/**
* A node of the AST (abstract syntax tree) for a program</p>
*
* This interface is at the root of the class hierarchy for AST nodes
*
* @author Benjamin Weber ( benweber at student dot ethz dot ch )
* @version $Revision: 1000 $
*/
public interface Node extends Serializable {}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/expressionlanguage
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/expressionlanguage/core/SemanticException.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/>.
*/
/*
* SemanticException.java
* Copyright (C) 2015 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.expressionlanguage.core;
/**
* An exception that should be used if a program doesn't have valid semantics
*
* @author Benjamin Weber ( benweber at student dot ethz dot ch )
* @version $Revision: 1000 $
*/
public class SemanticException extends Exception {
/** for serialization */
private static final long serialVersionUID = -1212116135142845573L;
/**
* Constructs a {@link SemanticException} with a message and cause
*
* @param msg the message of the exception
* @param e the cause of the exception
*/
public SemanticException(String msg, Exception e) {
super(msg, e);
}
/**
* Constructs a {@link SemanticException} with a message
*
* @param msg the message of the exception
*/
public SemanticException(String msg) {
super(msg);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/expressionlanguage
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/expressionlanguage/core/SyntaxException.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/>.
*/
/*
* SyntaxException.java
* Copyright (C) 2015 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.expressionlanguage.core;
/**
* An exception to represent an invalid syntax of a program
*
* @author Benjamin Weber ( benweber at student dot ethz dot ch )
* @version $Revision: 1000 $
*/
public class SyntaxException extends Exception {
/** for serialization */
private static final long serialVersionUID = 390076835893846782L;
/**
* Constructs a {@link SyntaxException} with a message
*
* @param msg the message of the exception
*/
public SyntaxException(String msg) {
super(msg);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/expressionlanguage
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/expressionlanguage/core/VariableDeclarations.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/>.
*/
/*
* VariableDeclarations.java
* Copyright (C) 2015 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.expressionlanguage.core;
import java.io.Serializable;
/**
* Interface to expose variables to a program.</p>
*
* It is deliberately kept very simple to give as little constraints
* as possible to implementations.</p>
*
* There is an implied invariant here:</br>
* <code>{@link #hasVariable(String)} == true ->
* {@link #getVariable(String)} != null</code></p>
*
* {@link #hasVariable(String)} should be pure i.e. have no side effects.</br>
* Whereas {@link #getVariable(String)} may have side effects.</br>
* (This is useful for creating variables on the fly in {@link #getVariable(String)})
*
* @author Benjamin Weber ( benweber at student dot ethz dot ch )
* @version $Revision: 1000 $
*/
public interface VariableDeclarations extends Serializable {
/**
* Whether the variable is declared
*
* @param name name of the variable being queried
* @return whether the variable is declared
*/
public boolean hasVariable(String name);
/**
* Tries to fetch a variable</p>
*
* Before a variable is fetched it should be checked whether it is declared
* through {@link #hasVariable(String)}.
*
* @param name name of the variable to be fetched
* @return an AST (abstract syntax tree) node representing the variable
*/
public Node getVariable(String name);
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/expressionlanguage
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/expressionlanguage/parser/Parser.java
|
//----------------------------------------------------
// The following code was generated by CUP v0.11b 20141202 (SVN rev 60)
//----------------------------------------------------
package weka.core.expressionlanguage.parser;
import java.util.List;
import java.util.ArrayList;
import java.io.StringReader;
import java_cup.runtime.Symbol;
import weka.core.expressionlanguage.core.Node;
import weka.core.expressionlanguage.core.VariableDeclarations;
import weka.core.expressionlanguage.core.SemanticException;
import weka.core.expressionlanguage.core.SyntaxException;
import weka.core.expressionlanguage.core.MacroDeclarations;
import weka.core.expressionlanguage.common.Operators;
import weka.core.expressionlanguage.common.NoVariables;
import weka.core.expressionlanguage.common.NoMacros;
import weka.core.expressionlanguage.common.Primitives.DoubleConstant;
import weka.core.expressionlanguage.common.Primitives.BooleanConstant;
import weka.core.expressionlanguage.common.Primitives.StringConstant;
import weka.core.expressionlanguage.parser.Scanner;
import java_cup.runtime.XMLElement;
/** CUP v0.11b 20141202 (SVN rev 60) generated parser.
*/
@SuppressWarnings({"rawtypes"})
public class Parser extends java_cup.runtime.lr_parser {
public final Class getSymbolContainer() {
return sym.class;
}
/** Default constructor. */
public Parser() {super();}
/** Constructor which sets the default scanner. */
public Parser(java_cup.runtime.Scanner s) {super(s);}
/** Constructor which sets the default scanner. */
public Parser(java_cup.runtime.Scanner s, java_cup.runtime.SymbolFactory sf) {super(s,sf);}
/** Production table. */
protected static final short _production_table[][] =
unpackFromStrings(new String[] {
"\000\035\000\002\002\004\000\002\002\003\000\002\005" +
"\005\000\002\005\003\000\002\004\003\000\002\004\002" +
"\000\002\003\005\000\002\003\006\000\002\003\003\000" +
"\002\003\003\000\002\003\003\000\002\003\003\000\002" +
"\003\004\000\002\003\004\000\002\003\005\000\002\003" +
"\005\000\002\003\005\000\002\003\005\000\002\003\005" +
"\000\002\003\005\000\002\003\005\000\002\003\004\000" +
"\002\003\005\000\002\003\005\000\002\003\005\000\002" +
"\003\005\000\002\003\005\000\002\003\005\000\002\003" +
"\005" });
/** Access to production table. */
public short[][] production_table() {return _production_table;}
/** Parse-action table. */
protected static final short[][] _action_table =
unpackFromStrings(new String[] {
"\000\064\000\022\004\010\005\015\006\007\007\005\010" +
"\014\013\006\014\004\024\013\001\002\000\022\004\010" +
"\005\015\006\007\007\005\010\014\013\006\014\004\024" +
"\013\001\002\000\044\002\ufff7\011\ufff7\012\ufff7\013\ufff7" +
"\014\ufff7\015\ufff7\016\ufff7\017\ufff7\022\ufff7\023\ufff7\025" +
"\ufff7\026\ufff7\027\ufff7\030\ufff7\031\ufff7\032\ufff7\033\ufff7" +
"\001\002\000\022\004\010\005\015\006\007\007\005\010" +
"\014\013\006\014\004\024\013\001\002\000\044\002\ufff6" +
"\011\ufff6\012\ufff6\013\ufff6\014\ufff6\015\ufff6\016\ufff6\017" +
"\ufff6\022\ufff6\023\ufff6\025\ufff6\026\ufff6\027\ufff6\030\ufff6" +
"\031\ufff6\032\ufff6\033\ufff6\001\002\000\046\002\ufff9\010" +
"\056\011\ufff9\012\ufff9\013\ufff9\014\ufff9\015\ufff9\016\ufff9" +
"\017\ufff9\022\ufff9\023\ufff9\025\ufff9\026\ufff9\027\ufff9\030" +
"\ufff9\031\ufff9\032\ufff9\033\ufff9\001\002\000\004\002\055" +
"\001\002\000\040\002\000\013\024\014\017\015\032\016" +
"\031\017\021\022\020\023\034\025\023\026\033\027\025" +
"\030\027\031\022\032\035\033\026\001\002\000\022\004" +
"\010\005\015\006\007\007\005\010\014\013\006\014\004" +
"\024\013\001\002\000\022\004\010\005\015\006\007\007" +
"\005\010\014\013\006\014\004\024\013\001\002\000\044" +
"\002\ufff8\011\ufff8\012\ufff8\013\ufff8\014\ufff8\015\ufff8\016" +
"\ufff8\017\ufff8\022\ufff8\023\ufff8\025\ufff8\026\ufff8\027\ufff8" +
"\030\ufff8\031\ufff8\032\ufff8\033\ufff8\001\002\000\040\011" +
"\030\013\024\014\017\015\032\016\031\017\021\022\020" +
"\023\034\025\023\026\033\027\025\030\027\031\022\032" +
"\035\033\026\001\002\000\022\004\010\005\015\006\007" +
"\007\005\010\014\013\006\014\004\024\013\001\002\000" +
"\022\004\010\005\015\006\007\007\005\010\014\013\006" +
"\014\004\024\013\001\002\000\022\004\010\005\015\006" +
"\007\007\005\010\014\013\006\014\004\024\013\001\002" +
"\000\022\004\010\005\015\006\007\007\005\010\014\013" +
"\006\014\004\024\013\001\002\000\022\004\010\005\015" +
"\006\007\007\005\010\014\013\006\014\004\024\013\001" +
"\002\000\022\004\010\005\015\006\007\007\005\010\014" +
"\013\006\014\004\024\013\001\002\000\022\004\010\005" +
"\015\006\007\007\005\010\014\013\006\014\004\024\013" +
"\001\002\000\022\004\010\005\015\006\007\007\005\010" +
"\014\013\006\014\004\024\013\001\002\000\022\004\010" +
"\005\015\006\007\007\005\010\014\013\006\014\004\024" +
"\013\001\002\000\044\002\ufffb\011\ufffb\012\ufffb\013\ufffb" +
"\014\ufffb\015\ufffb\016\ufffb\017\ufffb\022\ufffb\023\ufffb\025" +
"\ufffb\026\ufffb\027\ufffb\030\ufffb\031\ufffb\032\ufffb\033\ufffb" +
"\001\002\000\022\004\010\005\015\006\007\007\005\010" +
"\014\013\006\014\004\024\013\001\002\000\022\004\010" +
"\005\015\006\007\007\005\010\014\013\006\014\004\024" +
"\013\001\002\000\022\004\010\005\015\006\007\007\005" +
"\010\014\013\006\014\004\024\013\001\002\000\022\004" +
"\010\005\015\006\007\007\005\010\014\013\006\014\004" +
"\024\013\001\002\000\022\004\010\005\015\006\007\007" +
"\005\010\014\013\006\014\004\024\013\001\002\000\042" +
"\002\uffe6\011\uffe6\012\uffe6\013\024\014\017\015\032\016" +
"\031\017\021\022\uffe6\023\uffe6\025\023\026\033\027\025" +
"\030\027\031\022\033\026\001\002\000\044\002\uffed\011" +
"\uffed\012\uffed\013\024\014\017\015\032\016\031\017\021" +
"\022\020\023\uffed\025\023\026\033\027\025\030\027\031" +
"\022\032\035\033\026\001\002\000\032\002\uffea\011\uffea" +
"\012\uffea\013\024\014\017\015\032\016\031\017\021\022" +
"\uffea\023\uffea\025\uffea\032\uffea\001\002\000\044\002\ufff0" +
"\011\ufff0\012\ufff0\013\ufff0\014\ufff0\015\ufff0\016\ufff0\017" +
"\021\022\ufff0\023\ufff0\025\ufff0\026\ufff0\027\ufff0\030\ufff0" +
"\031\ufff0\032\ufff0\033\ufff0\001\002\000\044\002\uffef\011" +
"\uffef\012\uffef\013\uffef\014\uffef\015\uffef\016\uffef\017\021" +
"\022\uffef\023\uffef\025\uffef\026\uffef\027\uffef\030\uffef\031" +
"\uffef\032\uffef\033\uffef\001\002\000\032\002\uffe8\011\uffe8" +
"\012\uffe8\013\024\014\017\015\032\016\031\017\021\022" +
"\uffe8\023\uffe8\025\uffe8\032\uffe8\001\002\000\032\002\uffe5" +
"\011\uffe5\012\uffe5\013\024\014\017\015\032\016\031\017" +
"\021\022\uffe5\023\uffe5\025\uffe5\032\uffe5\001\002\000\032" +
"\002\uffe9\011\uffe9\012\uffe9\013\024\014\017\015\032\016" +
"\031\017\021\022\uffe9\023\uffe9\025\uffe9\032\uffe9\001\002" +
"\000\044\002\ufff2\011\ufff2\012\ufff2\013\ufff2\014\ufff2\015" +
"\032\016\031\017\021\022\ufff2\023\ufff2\025\ufff2\026\ufff2" +
"\027\ufff2\030\ufff2\031\ufff2\032\ufff2\033\ufff2\001\002\000" +
"\042\002\uffeb\011\uffeb\012\uffeb\013\024\014\017\015\032" +
"\016\031\017\021\022\uffeb\023\uffeb\026\033\027\025\030" +
"\027\031\022\032\uffeb\033\026\001\002\000\032\002\uffe7" +
"\011\uffe7\012\uffe7\013\024\014\017\015\032\016\031\017" +
"\021\022\uffe7\023\uffe7\025\uffe7\032\uffe7\001\002\000\044" +
"\002\ufff3\011\ufff3\012\ufff3\013\ufff3\014\ufff3\015\ufff3\016" +
"\ufff3\017\021\022\ufff3\023\ufff3\025\ufff3\026\ufff3\027\ufff3" +
"\030\ufff3\031\ufff3\032\ufff3\033\ufff3\001\002\000\044\002" +
"\uffee\011\uffee\012\uffee\013\024\014\017\015\032\016\031" +
"\017\021\022\uffee\023\uffee\025\023\026\033\027\025\030" +
"\027\031\022\032\035\033\026\001\002\000\044\002\ufff1" +
"\011\ufff1\012\ufff1\013\ufff1\014\ufff1\015\032\016\031\017" +
"\021\022\ufff1\023\ufff1\025\ufff1\026\ufff1\027\ufff1\030\ufff1" +
"\031\ufff1\032\ufff1\033\ufff1\001\002\000\044\002\uffec\011" +
"\uffec\012\uffec\013\uffec\014\uffec\015\uffec\016\uffec\017\021" +
"\022\uffec\023\uffec\025\uffec\026\uffec\027\uffec\030\uffec\031" +
"\uffec\032\uffec\033\uffec\001\002\000\004\002\001\001\002" +
"\000\024\004\010\005\015\006\007\007\005\010\014\011" +
"\ufffc\013\006\014\004\024\013\001\002\000\006\011\ufffd" +
"\012\063\001\002\000\004\011\062\001\002\000\042\011" +
"\ufffe\012\ufffe\013\024\014\017\015\032\016\031\017\021" +
"\022\020\023\034\025\023\026\033\027\025\030\027\031" +
"\022\032\035\033\026\001\002\000\044\002\ufffa\011\ufffa" +
"\012\ufffa\013\ufffa\014\ufffa\015\ufffa\016\ufffa\017\ufffa\022" +
"\ufffa\023\ufffa\025\ufffa\026\ufffa\027\ufffa\030\ufffa\031\ufffa" +
"\032\ufffa\033\ufffa\001\002\000\022\004\010\005\015\006" +
"\007\007\005\010\014\013\006\014\004\024\013\001\002" +
"\000\042\011\uffff\012\uffff\013\024\014\017\015\032\016" +
"\031\017\021\022\020\023\034\025\023\026\033\027\025" +
"\030\027\031\022\032\035\033\026\001\002\000\044\002" +
"\ufff5\011\ufff5\012\ufff5\013\ufff5\014\ufff5\015\ufff5\016\ufff5" +
"\017\021\022\ufff5\023\ufff5\025\ufff5\026\ufff5\027\ufff5\030" +
"\ufff5\031\ufff5\032\ufff5\033\ufff5\001\002\000\044\002\ufff4" +
"\011\ufff4\012\ufff4\013\ufff4\014\ufff4\015\ufff4\016\ufff4\017" +
"\021\022\ufff4\023\ufff4\025\ufff4\026\ufff4\027\ufff4\030\ufff4" +
"\031\ufff4\032\ufff4\033\ufff4\001\002" });
/** Access to parse-action table. */
public short[][] action_table() {return _action_table;}
/** <code>reduce_goto</code> table. */
protected static final short[][] _reduce_table =
unpackFromStrings(new String[] {
"\000\064\000\006\002\010\003\011\001\001\000\004\003" +
"\065\001\001\000\002\001\001\000\004\003\064\001\001" +
"\000\002\001\001\000\002\001\001\000\002\001\001\000" +
"\002\001\001\000\004\003\053\001\001\000\004\003\015" +
"\001\001\000\002\001\001\000\002\001\001\000\004\003" +
"\052\001\001\000\004\003\051\001\001\000\004\003\050" +
"\001\001\000\004\003\047\001\001\000\004\003\046\001" +
"\001\000\004\003\045\001\001\000\004\003\044\001\001" +
"\000\004\003\043\001\001\000\004\003\042\001\001\000" +
"\002\001\001\000\004\003\041\001\001\000\004\003\040" +
"\001\001\000\004\003\037\001\001\000\004\003\036\001" +
"\001\000\004\003\035\001\001\000\002\001\001\000\002" +
"\001\001\000\002\001\001\000\002\001\001\000\002\001" +
"\001\000\002\001\001\000\002\001\001\000\002\001\001" +
"\000\002\001\001\000\002\001\001\000\002\001\001\000" +
"\002\001\001\000\002\001\001\000\002\001\001\000\002" +
"\001\001\000\002\001\001\000\010\003\060\004\057\005" +
"\056\001\001\000\002\001\001\000\002\001\001\000\002" +
"\001\001\000\002\001\001\000\004\003\063\001\001\000" +
"\002\001\001\000\002\001\001\000\002\001\001" });
/** Access to <code>reduce_goto</code> table. */
public short[][] reduce_table() {return _reduce_table;}
/** Instance of action encapsulation class. */
protected CUP$Parser$actions action_obj;
/** Action encapsulation object initializer. */
protected void init_actions()
{
action_obj = new CUP$Parser$actions(this);
}
/** Invoke a user supplied parse action. */
public java_cup.runtime.Symbol do_action(
int act_num,
java_cup.runtime.lr_parser parser,
java.util.Stack stack,
int top)
throws java.lang.Exception
{
/* call code in generated class */
return action_obj.CUP$Parser$do_action(act_num, parser, stack, top);
}
/** Indicates start state. */
public int start_state() {return 0;}
/** Indicates start production. */
public int start_production() {return 0;}
/** <code>EOF</code> Symbol index. */
public int EOF_sym() {return 0;}
/** <code>error</code> Symbol index. */
public int error_sym() {return 1;}
/** the variables available to the program */
private VariableDeclarations variables = new NoVariables();
/** the macros available to the program */
private MacroDeclarations macros = new NoMacros();
/** the root node */
private Node root;
/**
* Sets the variable declarations for the program
*
* @param variables the variables that should be exposed to the program
*/
public void setVariables(VariableDeclarations variables) {
this.variables = variables;
}
/**
* Sets the macro declarations for the program
*
* @param macros the macros that should be exposed to the program
*/
public void setMacros(MacroDeclarations macros) {
this.macros = macros;
}
/**
* Sets the root node
*/
private void setRoot(Node root) {
this.root = root;
}
/**
* Returns the root node of the program
*
* @return the root node
*/
public Node getRoot() {
return root;
}
/**
* Tries to parse and compile a program from the textual representation in
* expr while exposing the variables and marcos
*
* @param expr the expression to be compiled in textual form
* @param variables the variables exposed to the program
* @param macros the macros exposed to the program
* @return the root node of the compiled program
* @throws Exception if an error occurs during compilation
*/
public static Node parse(String expr, VariableDeclarations variables,
MacroDeclarations macros) throws Exception {
Parser parser = new Parser(new Scanner(new StringReader(expr)));
parser.setVariables(variables);
parser.setMacros(macros);
parser.parse();
return parser.getRoot();
}
public void unrecovered_syntax_error(Symbol token) throws SyntaxException {
throw new SyntaxException("Syntax error at token '"
+ sym.terminalNames[token.sym] + "'!");
}
/** Cup generated class to encapsulate user supplied action code.*/
@SuppressWarnings({"rawtypes", "unchecked", "unused"})
class CUP$Parser$actions {
private final Parser parser;
/** Constructor */
CUP$Parser$actions(Parser parser) {
this.parser = parser;
}
/** Method 0 with the actual generated action code for actions 0 to 300. */
public final java_cup.runtime.Symbol CUP$Parser$do_action_part00000000(
int CUP$Parser$act_num,
java_cup.runtime.lr_parser CUP$Parser$parser,
java.util.Stack CUP$Parser$stack,
int CUP$Parser$top)
throws java.lang.Exception
{
/* Symbol object for return from actions */
java_cup.runtime.Symbol CUP$Parser$result;
/* select the action based on the action number */
switch (CUP$Parser$act_num)
{
/*. . . . . . . . . . . . . . . . . . . .*/
case 0: // $START ::= unit EOF
{
Object RESULT =null;
Node start_val = (Node)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-1)).value;
RESULT = start_val;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("$START",0, RESULT);
}
/* ACCEPT */
CUP$Parser$parser.done_parsing();
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 1: // unit ::= expr
{
Node RESULT =null;
Node e = (Node)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value;
RESULT = e;
setRoot(RESULT);
CUP$Parser$result = parser.getSymbolFactory().newSymbol("unit",0, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 2: // paramlist ::= paramlist COMMA expr
{
List<Node> RESULT =null;
List<Node> l = (List<Node>)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-2)).value;
Node e = (Node)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value;
l.add(e);
RESULT = l;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("paramlist",3, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 3: // paramlist ::= expr
{
List<Node> RESULT =null;
Node e = (Node)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value;
List<Node> l = new ArrayList<Node>();
l.add(e);
RESULT = l;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("paramlist",3, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 4: // paramlistOpt ::= paramlist
{
List<Node> RESULT =null;
List<Node> l = (List<Node>)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value;
RESULT = l;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("paramlistOpt",2, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 5: // paramlistOpt ::=
{
List<Node> RESULT =null;
RESULT = new ArrayList<Node>();
CUP$Parser$result = parser.getSymbolFactory().newSymbol("paramlistOpt",2, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 6: // expr ::= LPAREN expr RPAREN
{
Node RESULT =null;
Node e = (Node)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-1)).value;
RESULT = e;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("expr",1, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 7: // expr ::= IDENTIFIER LPAREN paramlistOpt RPAREN
{
Node RESULT =null;
String m = (String)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-3)).value;
List<Node> p = (List<Node>)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-1)).value;
if (!macros.hasMacro(m))
throw new SemanticException("Macro '" + m + "' is undefined!");
RESULT = macros.getMacro(m).evaluate(p.toArray(new Node[0]));
CUP$Parser$result = parser.getSymbolFactory().newSymbol("expr",1, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 8: // expr ::= IDENTIFIER
{
Node RESULT =null;
String v = (String)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value;
if (!variables.hasVariable(v))
throw new SemanticException("Variable '" + v + "' is undefined!");
RESULT = variables.getVariable(v);
CUP$Parser$result = parser.getSymbolFactory().newSymbol("expr",1, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 9: // expr ::= FLOAT
{
Node RESULT =null;
Double f = (Double)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value;
RESULT = new DoubleConstant(f);
CUP$Parser$result = parser.getSymbolFactory().newSymbol("expr",1, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 10: // expr ::= BOOLEAN
{
Node RESULT =null;
Boolean b = (Boolean)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value;
RESULT = new BooleanConstant(b);
CUP$Parser$result = parser.getSymbolFactory().newSymbol("expr",1, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 11: // expr ::= STRING
{
Node RESULT =null;
String s = (String)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value;
RESULT = new StringConstant(s);
CUP$Parser$result = parser.getSymbolFactory().newSymbol("expr",1, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 12: // expr ::= PLUS expr
{
Node RESULT =null;
Node e = (Node)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value;
RESULT = Operators.uplus(e);
CUP$Parser$result = parser.getSymbolFactory().newSymbol("expr",1, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 13: // expr ::= MINUS expr
{
Node RESULT =null;
Node e = (Node)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value;
RESULT = Operators.uminus(e);
CUP$Parser$result = parser.getSymbolFactory().newSymbol("expr",1, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 14: // expr ::= expr POW expr
{
Node RESULT =null;
Node l = (Node)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-2)).value;
Node r = (Node)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value;
RESULT = Operators.pow(l, r);
CUP$Parser$result = parser.getSymbolFactory().newSymbol("expr",1, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 15: // expr ::= expr PLUS expr
{
Node RESULT =null;
Node l = (Node)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-2)).value;
Node r = (Node)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value;
RESULT = Operators.plus(l, r);
CUP$Parser$result = parser.getSymbolFactory().newSymbol("expr",1, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 16: // expr ::= expr MINUS expr
{
Node RESULT =null;
Node l = (Node)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-2)).value;
Node r = (Node)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value;
RESULT = Operators.minus(l, r);
CUP$Parser$result = parser.getSymbolFactory().newSymbol("expr",1, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 17: // expr ::= expr TIMES expr
{
Node RESULT =null;
Node l = (Node)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-2)).value;
Node r = (Node)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value;
RESULT = Operators.times(l, r);
CUP$Parser$result = parser.getSymbolFactory().newSymbol("expr",1, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 18: // expr ::= expr DIVISION expr
{
Node RESULT =null;
Node l = (Node)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-2)).value;
Node r = (Node)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value;
RESULT = Operators.division(l, r);
CUP$Parser$result = parser.getSymbolFactory().newSymbol("expr",1, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 19: // expr ::= expr AND expr
{
Node RESULT =null;
Node l = (Node)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-2)).value;
Node r = (Node)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value;
RESULT = Operators.and(l, r);
CUP$Parser$result = parser.getSymbolFactory().newSymbol("expr",1, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 20: // expr ::= expr OR expr
{
Node RESULT =null;
Node l = (Node)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-2)).value;
Node r = (Node)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value;
RESULT = Operators.or(l, r);
CUP$Parser$result = parser.getSymbolFactory().newSymbol("expr",1, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 21: // expr ::= NOT expr
{
Node RESULT =null;
Node e = (Node)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value;
RESULT = Operators.not(e);
CUP$Parser$result = parser.getSymbolFactory().newSymbol("expr",1, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 22: // expr ::= expr EQUAL expr
{
Node RESULT =null;
Node l = (Node)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-2)).value;
Node r = (Node)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value;
RESULT = Operators.equal(l, r);
CUP$Parser$result = parser.getSymbolFactory().newSymbol("expr",1, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 23: // expr ::= expr LT expr
{
Node RESULT =null;
Node l = (Node)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-2)).value;
Node r = (Node)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value;
RESULT = Operators.lessThan(l, r);
CUP$Parser$result = parser.getSymbolFactory().newSymbol("expr",1, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 24: // expr ::= expr LE expr
{
Node RESULT =null;
Node l = (Node)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-2)).value;
Node r = (Node)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value;
RESULT = Operators.lessEqual(l, r);
CUP$Parser$result = parser.getSymbolFactory().newSymbol("expr",1, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 25: // expr ::= expr GT expr
{
Node RESULT =null;
Node l = (Node)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-2)).value;
Node r = (Node)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value;
RESULT = Operators.greaterThan(l, r);
CUP$Parser$result = parser.getSymbolFactory().newSymbol("expr",1, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 26: // expr ::= expr GE expr
{
Node RESULT =null;
Node l = (Node)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-2)).value;
Node r = (Node)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value;
RESULT = Operators.greaterEqual(l, r);
CUP$Parser$result = parser.getSymbolFactory().newSymbol("expr",1, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 27: // expr ::= expr IS expr
{
Node RESULT =null;
Node l = (Node)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-2)).value;
Node r = (Node)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value;
RESULT = Operators.is(l, r);
CUP$Parser$result = parser.getSymbolFactory().newSymbol("expr",1, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 28: // expr ::= expr REGEXP expr
{
Node RESULT =null;
Node l = (Node)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-2)).value;
Node r = (Node)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value;
RESULT = Operators.regexp(l, r);
CUP$Parser$result = parser.getSymbolFactory().newSymbol("expr",1, RESULT);
}
return CUP$Parser$result;
/* . . . . . .*/
default:
throw new Exception(
"Invalid action number "+CUP$Parser$act_num+"found in internal parse table");
}
} /* end of method */
/** Method splitting the generated action code into several parts. */
public final java_cup.runtime.Symbol CUP$Parser$do_action(
int CUP$Parser$act_num,
java_cup.runtime.lr_parser CUP$Parser$parser,
java.util.Stack CUP$Parser$stack,
int CUP$Parser$top)
throws java.lang.Exception
{
return CUP$Parser$do_action_part00000000(
CUP$Parser$act_num,
CUP$Parser$parser,
CUP$Parser$stack,
CUP$Parser$top);
}
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/expressionlanguage
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/expressionlanguage/parser/Scanner.java
|
/* The following code was generated by JFlex 1.6.0 */
/*
* 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/>.
*/
/*
* Scanner.java
* Copyright (C) 2015 University of Waikato, Hamilton, New Zealand
*/
package weka.core.expressionlanguage.parser;
import java_cup.runtime.*;
import weka.core.expressionlanguage.core.SyntaxException;
/**
* A lexical scanner for an expression language.
*
* It emerged as a superset of the weka.core.mathematicalexpression package,
* the weka.filers.unsupervised.instance.subsetbyexpression package and the
* weka.core.AttributeExpression class.
*
* Warning: This file (Scanner.java) has been auto generated by jflex.
*
* @author Benjamin Weber ( benweber at student dot ethz dot ch )
* @version $Revision: 1000 $
*/
public class Scanner implements java_cup.runtime.Scanner {
/** This character denotes the end of file */
public static final int YYEOF = -1;
/** initial size of the lookahead buffer */
private static final int ZZ_BUFFERSIZE = 16384;
/** lexical states */
public static final int YYINITIAL = 0;
public static final int STRING1 = 2;
public static final int STRING2 = 4;
/**
* ZZ_LEXSTATE[l] is the state in the DFA for the lexical state l
* ZZ_LEXSTATE[l+1] is the state in the DFA for the lexical state l
* at the beginning of a line
* l is of the form l = 2*k, k a non negative integer
*/
private static final int ZZ_LEXSTATE[] = {
0, 0, 1, 1, 2, 2
};
/**
* Translates characters to character classes
*/
private static final char [] ZZ_CMAP = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 35, 38, 35, 35, 35, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
35, 26, 11, 0, 0, 0, 21, 12, 13, 14, 18, 16, 15, 17, 2, 19,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 28, 27, 29, 0,
0, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34,
34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 0, 36, 0, 20, 34,
0, 8, 37, 34, 23, 6, 7, 31, 34, 30, 34, 34, 9, 34, 22, 25,
33, 34, 4, 10, 3, 5, 34, 34, 32, 34, 34, 0, 24, 0, 0, 0
};
/**
* Translates DFA states to action switch labels.
*/
private static final int [] ZZ_ACTION = zzUnpackAction();
private static final String ZZ_ACTION_PACKED_0 =
"\3\0\1\1\1\2\5\3\1\4\1\5\1\6\1\7"+
"\1\10\1\11\1\12\1\13\1\14\1\15\1\16\1\3"+
"\1\17\1\3\1\20\1\21\1\22\1\23\1\3\1\24"+
"\1\25\1\26\1\25\1\2\5\3\1\17\1\27\1\30"+
"\1\31\1\32\1\33\1\34\1\35\1\36\1\37\1\40"+
"\1\41\1\42\3\3\1\16\1\20\1\43\3\3\1\44"+
"\1\45";
private static int [] zzUnpackAction() {
int [] result = new int[63];
int offset = 0;
offset = zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result);
return result;
}
private static int zzUnpackAction(String packed, int offset, int [] result) {
int i = 0; /* index in packed string */
int j = offset; /* index in unpacked array */
int l = packed.length();
while (i < l) {
int count = packed.charAt(i++);
int value = packed.charAt(i++);
do result[j++] = value; while (--count > 0);
}
return j;
}
/**
* Translates a state to a row index in the transition table
*/
private static final int [] ZZ_ROWMAP = zzUnpackRowMap();
private static final String ZZ_ROWMAP_PACKED_0 =
"\0\0\0\47\0\116\0\165\0\234\0\303\0\352\0\u0111"+
"\0\u0138\0\u015f\0\165\0\165\0\165\0\165\0\165\0\165"+
"\0\165\0\165\0\165\0\165\0\165\0\u0186\0\165\0\u01ad"+
"\0\165\0\165\0\u01d4\0\u01fb\0\u0222\0\165\0\165\0\165"+
"\0\u0249\0\u0270\0\u0297\0\u02be\0\u02e5\0\u030c\0\u0333\0\u0111"+
"\0\165\0\165\0\u0111\0\165\0\165\0\165\0\165\0\165"+
"\0\165\0\165\0\165\0\165\0\u035a\0\u0381\0\u03a8\0\u0111"+
"\0\u0111\0\u0111\0\u03cf\0\u03f6\0\u041d\0\u0111\0\u0111";
private static int [] zzUnpackRowMap() {
int [] result = new int[63];
int offset = 0;
offset = zzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result);
return result;
}
private static int zzUnpackRowMap(String packed, int offset, int [] result) {
int i = 0; /* index in packed string */
int j = offset; /* index in unpacked array */
int l = packed.length();
while (i < l) {
int high = packed.charAt(i++) << 16;
result[j++] = high | packed.charAt(i++);
}
return j;
}
/**
* The transition table of the DFA
*/
private static final int [] ZZ_TRANS = zzUnpackTrans();
private static final String ZZ_TRANS_PACKED_0 =
"\1\4\1\5\1\4\1\6\1\7\2\10\1\11\1\12"+
"\2\10\1\13\1\14\1\15\1\16\1\17\1\20\1\21"+
"\1\22\1\23\1\24\1\25\1\26\1\10\1\27\1\30"+
"\1\31\1\32\1\33\1\34\1\35\4\10\1\36\1\4"+
"\1\10\1\36\13\37\1\40\30\37\1\41\1\37\1\4"+
"\14\37\1\40\27\37\1\41\1\37\1\4\50\0\1\5"+
"\1\42\45\0\1\10\1\0\1\10\1\43\6\10\13\0"+
"\2\10\1\0\1\10\4\0\5\10\2\0\1\10\2\0"+
"\1\10\1\0\3\10\1\44\4\10\13\0\2\10\1\0"+
"\1\10\4\0\5\10\2\0\1\10\2\0\1\10\1\0"+
"\10\10\13\0\2\10\1\0\1\10\4\0\5\10\2\0"+
"\1\10\2\0\1\10\1\0\5\10\1\45\2\10\13\0"+
"\2\10\1\0\1\10\4\0\5\10\2\0\1\10\2\0"+
"\1\10\1\0\10\10\13\0\1\46\1\10\1\0\1\10"+
"\4\0\5\10\2\0\1\10\2\0\1\10\1\0\10\10"+
"\13\0\2\10\1\0\1\47\4\0\5\10\2\0\1\10"+
"\2\0\1\10\1\0\1\10\1\50\6\10\13\0\2\10"+
"\1\0\1\10\4\0\5\10\2\0\1\10\34\0\1\51"+
"\46\0\1\52\14\0\1\10\1\0\7\10\1\53\13\0"+
"\2\10\1\0\1\10\4\0\5\10\2\0\1\10\1\0"+
"\3\54\1\55\1\56\2\54\1\57\3\54\1\60\1\61"+
"\11\54\1\62\15\54\1\63\1\64\2\0\1\42\46\0"+
"\1\10\1\0\2\10\1\65\5\10\13\0\2\10\1\0"+
"\1\10\4\0\5\10\2\0\1\10\2\0\1\10\1\0"+
"\10\10\13\0\2\10\1\0\1\10\4\0\1\10\1\66"+
"\3\10\2\0\1\10\2\0\1\10\1\0\6\10\1\67"+
"\1\10\13\0\2\10\1\0\1\10\4\0\5\10\2\0"+
"\1\10\2\0\1\10\1\0\10\10\13\0\1\10\1\70"+
"\1\0\1\10\4\0\5\10\2\0\1\10\2\0\1\10"+
"\1\0\1\71\7\10\13\0\2\10\1\0\1\10\4\0"+
"\5\10\2\0\1\10\2\0\1\10\1\0\3\10\1\72"+
"\4\10\13\0\2\10\1\0\1\10\4\0\5\10\2\0"+
"\1\10\2\0\1\10\1\0\3\10\1\73\4\10\13\0"+
"\2\10\1\0\1\10\4\0\5\10\2\0\1\10\2\0"+
"\1\10\1\0\7\10\1\74\13\0\2\10\1\0\1\10"+
"\4\0\5\10\2\0\1\10\2\0\1\10\1\0\10\10"+
"\13\0\2\10\1\0\1\10\4\0\2\10\1\75\2\10"+
"\2\0\1\10\2\0\1\10\1\0\3\10\1\76\4\10"+
"\13\0\2\10\1\0\1\10\4\0\5\10\2\0\1\10"+
"\2\0\1\10\1\0\10\10\13\0\2\10\1\0\1\10"+
"\4\0\3\10\1\77\1\10\2\0\1\10\1\0";
private static int [] zzUnpackTrans() {
int [] result = new int[1092];
int offset = 0;
offset = zzUnpackTrans(ZZ_TRANS_PACKED_0, offset, result);
return result;
}
private static int zzUnpackTrans(String packed, int offset, int [] result) {
int i = 0; /* index in packed string */
int j = offset; /* index in unpacked array */
int l = packed.length();
while (i < l) {
int count = packed.charAt(i++);
int value = packed.charAt(i++);
value--;
do result[j++] = value; while (--count > 0);
}
return j;
}
/* error codes */
private static final int ZZ_UNKNOWN_ERROR = 0;
private static final int ZZ_NO_MATCH = 1;
private static final int ZZ_PUSHBACK_2BIG = 2;
/* error messages for the codes above */
private static final String ZZ_ERROR_MSG[] = {
"Unkown internal scanner error",
"Error: could not match input",
"Error: pushback value was too large"
};
/**
* ZZ_ATTRIBUTE[aState] contains the attributes of state <code>aState</code>
*/
private static final int [] ZZ_ATTRIBUTE = zzUnpackAttribute();
private static final String ZZ_ATTRIBUTE_PACKED_0 =
"\3\0\1\11\6\1\13\11\1\1\1\11\1\1\2\11"+
"\3\1\3\11\10\1\2\11\1\1\11\11\13\1";
private static int [] zzUnpackAttribute() {
int [] result = new int[63];
int offset = 0;
offset = zzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result);
return result;
}
private static int zzUnpackAttribute(String packed, int offset, int [] result) {
int i = 0; /* index in packed string */
int j = offset; /* index in unpacked array */
int l = packed.length();
while (i < l) {
int count = packed.charAt(i++);
int value = packed.charAt(i++);
do result[j++] = value; while (--count > 0);
}
return j;
}
/** the input device */
private java.io.Reader zzReader;
/** the current state of the DFA */
private int zzState;
/** the current lexical state */
private int zzLexicalState = YYINITIAL;
/** this buffer contains the current text to be matched and is
the source of the yytext() string */
private char zzBuffer[] = new char[ZZ_BUFFERSIZE];
/** the textposition at the last accepting state */
private int zzMarkedPos;
/** the current text position in the buffer */
private int zzCurrentPos;
/** startRead marks the beginning of the yytext() string in the buffer */
private int zzStartRead;
/** endRead marks the last character in the buffer, that has been read
from input */
private int zzEndRead;
/** number of newlines encountered up to the start of the matched text */
private int yyline;
/** the number of characters up to the start of the matched text */
private int yychar;
/**
* the number of characters from the last newline up to the start of the
* matched text
*/
private int yycolumn;
/**
* zzAtBOL == true <=> the scanner is currently at the beginning of a line
*/
private boolean zzAtBOL = true;
/** zzAtEOF == true <=> the scanner is at the EOF */
private boolean zzAtEOF;
/** denotes if the user-EOF-code has already been executed */
private boolean zzEOFDone;
/**
* The number of occupied positions in zzBuffer beyond zzEndRead.
* When a lead/high surrogate has been read from the input stream
* into the final zzBuffer position, this will have a value of 1;
* otherwise, it will have a value of 0.
*/
private int zzFinalHighSurrogate = 0;
/* user code: */
private StringBuilder string = new StringBuilder();
private Symbol symbol(int type) {
return new Symbol(type);
}
private Symbol symbol(int type, Object obj) {
return new Symbol(type, obj);
}
/**
* Creates a new scanner
*
* @param in the java.io.Reader to read input from.
*/
public Scanner(java.io.Reader in) {
this.zzReader = in;
}
/**
* Refills the input buffer.
*
* @return <code>false</code>, iff there was new input.
*
* @exception java.io.IOException if any I/O-Error occurs
*/
private boolean zzRefill() throws java.io.IOException {
/* first: make room (if you can) */
if (zzStartRead > 0) {
zzEndRead += zzFinalHighSurrogate;
zzFinalHighSurrogate = 0;
System.arraycopy(zzBuffer, zzStartRead,
zzBuffer, 0,
zzEndRead-zzStartRead);
/* translate stored positions */
zzEndRead-= zzStartRead;
zzCurrentPos-= zzStartRead;
zzMarkedPos-= zzStartRead;
zzStartRead = 0;
}
/* is the buffer big enough? */
if (zzCurrentPos >= zzBuffer.length - zzFinalHighSurrogate) {
/* if not: blow it up */
char newBuffer[] = new char[zzBuffer.length*2];
System.arraycopy(zzBuffer, 0, newBuffer, 0, zzBuffer.length);
zzBuffer = newBuffer;
zzEndRead += zzFinalHighSurrogate;
zzFinalHighSurrogate = 0;
}
/* fill the buffer with new input */
int requested = zzBuffer.length - zzEndRead;
int totalRead = 0;
while (totalRead < requested) {
int numRead = zzReader.read(zzBuffer, zzEndRead + totalRead, requested - totalRead);
if (numRead == -1) {
break;
}
totalRead += numRead;
}
if (totalRead > 0) {
zzEndRead += totalRead;
if (totalRead == requested) { /* possibly more input available */
if (Character.isHighSurrogate(zzBuffer[zzEndRead - 1])) {
--zzEndRead;
zzFinalHighSurrogate = 1;
}
}
return false;
}
// totalRead = 0: End of stream
return true;
}
/**
* Closes the input stream.
*/
public final void yyclose() throws java.io.IOException {
zzAtEOF = true; /* indicate end of file */
zzEndRead = zzStartRead; /* invalidate buffer */
if (zzReader != null)
zzReader.close();
}
/**
* Resets the scanner to read from a new input stream.
* Does not close the old reader.
*
* All internal variables are reset, the old input stream
* <b>cannot</b> be reused (internal buffer is discarded and lost).
* Lexical state is set to <tt>ZZ_INITIAL</tt>.
*
* Internal scan buffer is resized down to its initial length, if it has grown.
*
* @param reader the new input stream
*/
public final void yyreset(java.io.Reader reader) {
zzReader = reader;
zzAtBOL = true;
zzAtEOF = false;
zzEOFDone = false;
zzEndRead = zzStartRead = 0;
zzCurrentPos = zzMarkedPos = 0;
zzFinalHighSurrogate = 0;
yyline = yychar = yycolumn = 0;
zzLexicalState = YYINITIAL;
if (zzBuffer.length > ZZ_BUFFERSIZE)
zzBuffer = new char[ZZ_BUFFERSIZE];
}
/**
* Returns the current lexical state.
*/
public final int yystate() {
return zzLexicalState;
}
/**
* Enters a new lexical state
*
* @param newState the new lexical state
*/
public final void yybegin(int newState) {
zzLexicalState = newState;
}
/**
* Returns the text matched by the current regular expression.
*/
public final String yytext() {
return new String( zzBuffer, zzStartRead, zzMarkedPos-zzStartRead );
}
/**
* Returns the character at position <tt>pos</tt> from the
* matched text.
*
* It is equivalent to yytext().charAt(pos), but faster
*
* @param pos the position of the character to fetch.
* A value from 0 to yylength()-1.
*
* @return the character at position pos
*/
public final char yycharat(int pos) {
return zzBuffer[zzStartRead+pos];
}
/**
* Returns the length of the matched text region.
*/
public final int yylength() {
return zzMarkedPos-zzStartRead;
}
/**
* Reports an error that occured while scanning.
*
* In a wellformed scanner (no or only correct usage of
* yypushback(int) and a match-all fallback rule) this method
* will only be called with things that "Can't Possibly Happen".
* If this method is called, something is seriously wrong
* (e.g. a JFlex bug producing a faulty scanner etc.).
*
* Usual syntax/scanner level error handling should be done
* in error fallback rules.
*
* @param errorCode the code of the errormessage to display
*/
private void zzScanError(int errorCode) throws SyntaxException {
String message;
try {
message = ZZ_ERROR_MSG[errorCode];
}
catch (ArrayIndexOutOfBoundsException e) {
message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR];
}
throw new SyntaxException(message);
}
/**
* Pushes the specified amount of characters back into the input stream.
*
* They will be read again by then next call of the scanning method
*
* @param number the number of characters to be read again.
* This number must not be greater than yylength()!
*/
public void yypushback(int number) throws SyntaxException {
if ( number > yylength() )
zzScanError(ZZ_PUSHBACK_2BIG);
zzMarkedPos -= number;
}
/**
* Resumes scanning until the next regular expression is matched,
* the end of input is encountered or an I/O-Error occurs.
*
* @return the next token
* @exception java.io.IOException if any I/O-Error occurs
*/
public java_cup.runtime.Symbol next_token() throws java.io.IOException, SyntaxException {
int zzInput;
int zzAction;
// cached fields:
int zzCurrentPosL;
int zzMarkedPosL;
int zzEndReadL = zzEndRead;
char [] zzBufferL = zzBuffer;
char [] zzCMapL = ZZ_CMAP;
int [] zzTransL = ZZ_TRANS;
int [] zzRowMapL = ZZ_ROWMAP;
int [] zzAttrL = ZZ_ATTRIBUTE;
while (true) {
zzMarkedPosL = zzMarkedPos;
zzAction = -1;
zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL;
zzState = ZZ_LEXSTATE[zzLexicalState];
// set up zzAction for empty match case:
int zzAttributes = zzAttrL[zzState];
if ( (zzAttributes & 1) == 1 ) {
zzAction = zzState;
}
zzForAction: {
while (true) {
if (zzCurrentPosL < zzEndReadL) {
zzInput = Character.codePointAt(zzBufferL, zzCurrentPosL, zzEndReadL);
zzCurrentPosL += Character.charCount(zzInput);
}
else if (zzAtEOF) {
zzInput = YYEOF;
break zzForAction;
}
else {
// store back cached positions
zzCurrentPos = zzCurrentPosL;
zzMarkedPos = zzMarkedPosL;
boolean eof = zzRefill();
// get translated positions and possibly new buffer
zzCurrentPosL = zzCurrentPos;
zzMarkedPosL = zzMarkedPos;
zzBufferL = zzBuffer;
zzEndReadL = zzEndRead;
if (eof) {
zzInput = YYEOF;
break zzForAction;
}
else {
zzInput = Character.codePointAt(zzBufferL, zzCurrentPosL, zzEndReadL);
zzCurrentPosL += Character.charCount(zzInput);
}
}
int zzNext = zzTransL[ zzRowMapL[zzState] + zzCMapL[zzInput] ];
if (zzNext == -1) break zzForAction;
zzState = zzNext;
zzAttributes = zzAttrL[zzState];
if ( (zzAttributes & 1) == 1 ) {
zzAction = zzState;
zzMarkedPosL = zzCurrentPosL;
if ( (zzAttributes & 8) == 8 ) break zzForAction;
}
}
}
// store back cached position
zzMarkedPos = zzMarkedPosL;
switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) {
case 1:
{ throw new SyntaxException("Illegal character " + yytext() + "!");
}
case 38: break;
case 2:
{ return symbol(sym.FLOAT, Double.valueOf(yytext()));
}
case 39: break;
case 3:
{ return symbol(sym.IDENTIFIER, yytext());
}
case 40: break;
case 4:
{ yybegin(STRING1); string.setLength(0);
}
case 41: break;
case 5:
{ yybegin(STRING2); string.setLength(0);
}
case 42: break;
case 6:
{ return symbol(sym.LPAREN);
}
case 43: break;
case 7:
{ return symbol(sym.RPAREN);
}
case 44: break;
case 8:
{ return symbol(sym.COMMA);
}
case 45: break;
case 9:
{ return symbol(sym.PLUS);
}
case 46: break;
case 10:
{ return symbol(sym.MINUS);
}
case 47: break;
case 11:
{ return symbol(sym.TIMES);
}
case 48: break;
case 12:
{ return symbol(sym.DIVISION);
}
case 49: break;
case 13:
{ return symbol(sym.POW);
}
case 50: break;
case 14:
{ return symbol(sym.AND);
}
case 51: break;
case 15:
{ return symbol(sym.OR);
}
case 52: break;
case 16:
{ return symbol(sym.NOT);
}
case 53: break;
case 17:
{ return symbol(sym.EQUAL);
}
case 54: break;
case 18:
{ return symbol(sym.LT);
}
case 55: break;
case 19:
{ return symbol(sym.GT);
}
case 56: break;
case 20:
{ /* ignore */
}
case 57: break;
case 21:
{ string.append(yytext());
}
case 58: break;
case 22:
{ yybegin(YYINITIAL); return symbol(sym.STRING, string.toString());
}
case 59: break;
case 23:
{ return symbol(sym.LE);
}
case 60: break;
case 24:
{ return symbol(sym.GE);
}
case 61: break;
case 25:
{ return symbol(sym.IS);
}
case 62: break;
case 26:
{ throw new SyntaxException("Invalid escape sequence '" + yytext() + "'!");
}
case 63: break;
case 27:
{ string.append('\t');
}
case 64: break;
case 28:
{ string.append('\r');
}
case 65: break;
case 29:
{ string.append('\f');
}
case 66: break;
case 30:
{ string.append('\"');
}
case 67: break;
case 31:
{ string.append('\'');
}
case 68: break;
case 32:
{ string.append('\n');
}
case 69: break;
case 33:
{ string.append('\\');
}
case 70: break;
case 34:
{ string.append('\b');
}
case 71: break;
case 35:
{ return symbol(sym.BOOLEAN, true);
}
case 72: break;
case 36:
{ return symbol(sym.BOOLEAN, false);
}
case 73: break;
case 37:
{ return symbol(sym.REGEXP);
}
case 74: break;
default:
if (zzInput == YYEOF && zzStartRead == zzCurrentPos) {
zzAtEOF = true;
{ return new java_cup.runtime.Symbol(sym.EOF); }
}
else {
zzScanError(ZZ_NO_MATCH);
}
}
}
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/expressionlanguage
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/expressionlanguage/parser/sym.java
|
//----------------------------------------------------
// The following code was generated by CUP v0.11b 20141202 (SVN rev 60)
//----------------------------------------------------
package weka.core.expressionlanguage.parser;
/** CUP generated interface containing symbol constants. */
public interface sym {
/* terminals */
public static final int TIMES = 11;
public static final int AND = 16;
public static final int IS = 24;
public static final int LT = 20;
public static final int PLUS = 9;
public static final int OR = 17;
public static final int RPAREN = 7;
public static final int EQUAL = 19;
public static final int DIVISION = 12;
public static final int NOT = 18;
public static final int IDENTIFIER = 2;
public static final int POW = 13;
public static final int GT = 22;
public static final int LPAREN = 6;
public static final int LE = 21;
public static final int REGEXP = 25;
public static final int BOOLEAN = 5;
public static final int STRING = 4;
public static final int COMMA = 8;
public static final int FLOAT = 3;
public static final int EOF = 0;
public static final int UPLUS = 15;
public static final int GE = 23;
public static final int MINUS = 10;
public static final int error = 1;
public static final int UMINUS = 14;
public static final String[] terminalNames = new String[] {
"EOF",
"error",
"IDENTIFIER",
"FLOAT",
"STRING",
"BOOLEAN",
"LPAREN",
"RPAREN",
"COMMA",
"PLUS",
"MINUS",
"TIMES",
"DIVISION",
"POW",
"UMINUS",
"UPLUS",
"AND",
"OR",
"NOT",
"EQUAL",
"LT",
"LE",
"GT",
"GE",
"IS",
"REGEXP"
};
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/expressionlanguage
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/expressionlanguage/weka/InstancesHelper.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/>.
*/
/*
* InstancesHelper.java
* Copyright (C) 2015 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.expressionlanguage.weka;
import java.util.regex.Pattern;
import weka.core.Utils;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.expressionlanguage.core.Macro;
import weka.core.expressionlanguage.core.MacroDeclarations;
import weka.core.expressionlanguage.core.Node;
import weka.core.expressionlanguage.core.SemanticException;
import weka.core.expressionlanguage.core.VariableDeclarations;
import weka.core.expressionlanguage.common.Primitives.BooleanExpression;
import weka.core.expressionlanguage.common.Primitives.DoubleExpression;
import weka.core.expressionlanguage.common.Primitives.StringExpression;
/**
* A helper class to expose instance values and macros for instance values to a
* program</p>
*
* Exposes instance values of the current instance (see
* {@link #setInstance(Instance)} and {@link #setInstance(int)} methods) as a1,
* A1 or ATT1 etc where the number is the attribute index (starting with
* 1).</br> Furthermore exposes the class value as CLASS.</p>
*
* Exposes the '<code>ismissing</code>' macro which can only be applied to
* instance values and returns whether the value is set as missing in the
* current instance.</p>
*
* @author Benjamin Weber ( benweber at student dot ethz dot ch )
* @version $Revision: 1000 $
*/
public class InstancesHelper implements VariableDeclarations, Macro,
MacroDeclarations {
// from MathExpression filter and AttributeExpression
private static final Pattern ATTRIBUTE1 = Pattern.compile("[aA][0-9]+");
// from subsetbyexpression
private static final Pattern ATTRIBUTE2 = Pattern.compile("ATT[0-9]+");
// from subsetbyexpression
private static final String CLASS = "CLASS";
// from subsetbyexpression
private static final String IS_MISSING = "ismissing";
private static final long serialVersionUID = -4398876812339967703L;
/** the dataset whose instance values should be exposed */
private final Instances dataset;
/** the current instance whose values should be exposed */
private Instance instance;
/** whether a missing value has been evaluated during computation */
private boolean missingAccessed = false;
/**
* True if this instance retains the full dataset rather than just the
* attribute information
*/
private final boolean dataRetained;
/**
* Constructs an {@link InstancesHelper} for the given dataset. Only attribute
* information is retained in memory.
*
* @param dataset the dataset whose attribute values should be exposed
*/
public InstancesHelper(Instances dataset) {
this(dataset, false);
}
/**
* Constructs an {@link InstancesHelper} for the given dataset.
*
* @param dataset the dataset
* @param retainData true if the full dataset (rather than just the attribute
* information) is to be retained
*/
public InstancesHelper(Instances dataset, boolean retainData) {
assert dataset != null;
if (retainData) {
this.dataset = dataset;
} else {
this.dataset = new Instances(dataset, 0);
}
dataRetained = retainData;
}
/**
* Whether the given macro is declared
*
* @param name name of the macro
* @return whether the given macro is declared
*/
@Override
public boolean hasMacro(String name) {
return IS_MISSING.equals(name);
}
/**
* Tries to fetch a macro</p>
*
* The same invariant of {@link MacroDeclarations} applies here too.
*
* @param name of the macro
* @return the macro
*/
@Override
public Macro getMacro(String name) {
if (hasMacro(name))
return this;
throw new RuntimeException("Macro '" + name + "' undefined!");
}
/**
* Evaluates the 'ismissing' macro
*
* @param params the arguments for the macro
* @return an AST node representing the ismissing function
*/
public Node evaluate(Node... params) throws SemanticException {
if (params.length != 1)
throw new SemanticException("Macro " + IS_MISSING
+ " takes exactly one argument!");
if (params[0] instanceof Value)
return new isMissing((Value) params[0]);
throw new SemanticException(IS_MISSING
+ " is only applicable to a dataset value!");
}
private static class isMissing implements BooleanExpression {
private static final long serialVersionUID = -3805035561340865906L;
private final Value value;
public isMissing(Value value) {
this.value = value;
}
@Override
public boolean evaluate() {
return value.isMissing();
}
}
/**
* Sets the instance at index i of the supplied dataset to be the current
* instance
*
* @param i the index of the instance to be set
* @throws UnsupportedOperationException if the full dataset has not been
* retained in memory
*/
public void setInstance(int i) {
if (!dataRetained) {
throw new UnsupportedOperationException(
"Unable to set the instance based "
+ "on index because the dataset has not been retained in memory");
}
setInstance(dataset.get(i));
}
/**
* Sets the current instance to be the supplied instance
*
* @param instance instance to be set as the current instance
*/
public void setInstance(Instance instance) {
assert dataset.equalHeaders(instance.dataset());
this.instance = instance;
missingAccessed = false;
}
/**
* Whether a missing value has been evaluated during computation.</p>
*
* Will be reset when the {@link #setInstance(int)} or
* {@link #setInstance(Instance)} method is called.
*
* @return whether a missing value has been evaluated during computation
*/
public boolean missingAccessed() {
return missingAccessed;
}
private int getIndex(String attribute) {
if (ATTRIBUTE1.matcher(attribute).matches())
return Integer.parseInt(attribute.substring(1)) - 1;
if (ATTRIBUTE2.matcher(attribute).matches())
return Integer.parseInt(attribute.substring(3)) - 1;
if (CLASS.equals(attribute))
return dataset.classIndex();
return -1;
}
/**
* Returns whether the variable is declared
*
* @param name name of the variable
* @return whether it has been declared
*/
@Override
public boolean hasVariable(String name) {
int index = getIndex(name);
if (0 <= index && index < dataset.numAttributes())
return true;
return false;
}
/**
* Tries to fetch a variable of an instance value</p>
*
* The same invariant of {@link VariableDeclarations} applies here too.
*
* @param name name of the variable
* @return node representing the instance value
*/
@Override
public Node getVariable(String name) {
int index = getIndex(name);
if (index < 0 || index >= dataset.numAttributes())
throw new RuntimeException("Variable '" + name + "' undefined!");
if (dataset.attribute(index).isNumeric())
return new DoubleValue(index);
if (dataset.attribute(index).isString()
|| dataset.attribute(index).isNominal())
return new StringValue(index);
throw new RuntimeException("Attributes of type '"
+ dataset.attribute(index).toString() + "' not supported!");
}
private abstract class Value implements Node {
private static final long serialVersionUID = 5839070716097467627L;
private final int index;
public Value(int index) {
this.index = index;
}
public int getIndex() {
return index;
}
public boolean isMissing() {
return instance.isMissing(getIndex());
}
}
private class DoubleValue extends Value implements DoubleExpression {
private static final long serialVersionUID = -1001674545929082424L;
public DoubleValue(int index) {
super(index);
assert dataset.attribute(getIndex()).isNumeric();
}
@Override
public double evaluate() {
if (isMissing()) {
missingAccessed = true;
return Utils.missingValue();
}
return instance.value(getIndex());
}
}
private class StringValue extends Value implements StringExpression {
private static final long serialVersionUID = -249974216283801876L;
public StringValue(int index) {
super(index);
assert dataset.attribute(index).isString()
|| dataset.attribute(index).isNominal();
}
@Override
public String evaluate() {
if (isMissing()) {
missingAccessed = true;
return "";
}
return instance.stringValue(getIndex());
}
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/expressionlanguage
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/expressionlanguage/weka/StatsHelper.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/>.
*/
/*
* StatsHelper.java
* Copyright (C) 2015 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.expressionlanguage.weka;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import weka.core.expressionlanguage.common.Primitives.DoubleExpression;
import weka.core.expressionlanguage.core.Node;
import weka.core.expressionlanguage.core.VariableDeclarations;
import weka.experiment.Stats;
/**
* A helper class to expose a Stats object to a program</p>
*
* Exposes the following variables that correspond to Stats' fields:</br>
* <ul>
* <li>MAX</li>
* <li>MIN</li>
* <li>MEAN</li>
* <li>SD</li>
* <li>COUNT</li>
* <li>SUM</li>
* <li>SUMSQUARED</li>
* </ul>
*
* @author Benjamin Weber ( benweber at student dot ethz dot ch )
* @version $Revision: 1000 $
*/
public class StatsHelper implements VariableDeclarations {
private final Map<String, Node> variables = new HashMap<String, Node>();
private Set<String> usedVariables = new HashSet<String>();
private Stats stats;
/**
* Construct a {@link StatsHelper}
*/
public StatsHelper() {
variables.put("MAX", new Max());
variables.put("MIN", new Min());
variables.put("MEAN", new Mean());
variables.put("SD", new StdDev());
variables.put("COUNT", new Count());
variables.put("SUM", new Sum());
variables.put("SUMSQUARED", new SumSq());
}
/**
* Sets the corresponding Stats object
*
* @param stats the Stats object whose fields should be exposed
*/
public void setStats(Stats stats) {
this.stats = stats;
}
/**
* Whether Stats fields are accessed in the program</p>
*
* This is only meaningful after compilation.
*
* @return Whether Stats fields are accessed in the program
*/
public boolean used() {
return usedVariables.isEmpty();
}
/**
* Returns whether the Stats field is used in the program</p>
*
* Must be one of the exposed variables.</p>
*
* This is only meaningful after compilation.
*
* @param name The name of the variable of the Stats field
* @return whether the Stats field is used in the program
*/
public boolean used(String name) {
return usedVariables.contains(name);
}
/**
* Returns whether the variable is declared
*
* @param name name of the variable
* @return whether the variable has been declared
*/
@Override
public boolean hasVariable(String name) {
return variables.containsKey(name);
}
/**
* Tries to fetch a Stats field</p>
*
* The same invariant of {@link VariableDeclaration} applies here too.
*
* @param name name of the variable
* @return node representing the Stats field
*/
@Override
public Node getVariable(String name) {
if (variables.containsKey(name)) {
usedVariables.add(name);
return variables.get(name);
}
throw new RuntimeException("Variable '" + name + "' undefined!");
}
private class Max implements DoubleExpression {
@Override
public double evaluate() {
return stats.max;
}
}
private class Min implements DoubleExpression {
@Override
public double evaluate() {
return stats.min;
}
}
private class Mean implements DoubleExpression {
@Override
public double evaluate() {
return stats.mean;
}
}
private class StdDev implements DoubleExpression {
@Override
public double evaluate() {
return stats.stdDev;
}
}
private class Count implements DoubleExpression {
@Override
public double evaluate() {
return stats.count;
}
}
private class Sum implements DoubleExpression {
@Override
public double evaluate() {
return stats.sum;
}
}
private class SumSq implements DoubleExpression {
@Override
public double evaluate() {
return stats.sumSq;
}
}
}
|
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/json/JSONInstances.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/>.
*/
/*
* JSONInstances.java
* Copyright (C) 2009-2012 University of Waikato, Hamilton, New Zealand
*/
package weka.core.json;
import java.util.ArrayList;
import weka.core.Attribute;
import weka.core.DenseInstance;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.SparseInstance;
import weka.core.Utils;
import weka.core.converters.ConverterUtils.DataSource;
/**
* Class for transforming Instances objects into <a href="http://www.json.org/" target="_blank">JSON</a>
* objects and vice versa. Missing values get stored as "?".
*
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision$
* @see #MISSING_VALUE
*/
public class JSONInstances {
/** the header section. */
public final static String HEADER = "header";
/** the data section. */
public final static String DATA = "data";
/** the relation name. */
public final static String RELATION = "relation";
/** the attributes object. */
public final static String ATTRIBUTES = "attributes";
/** the name attribute. */
public final static String NAME = "name";
/** the type attribute. */
public final static String TYPE = "type";
/** the class attribute indicator. */
public final static String CLASS = "class";
/** the labels attribute. */
public final static String LABELS = "labels";
/** the weight attribute. */
public final static String WEIGHT = "weight";
/** the dateformat attribute. */
public final static String DATEFORMAT = "dateformat";
/** the sparse attribute. */
public final static String SPARSE = "sparse";
/** the values attribute. */
public final static String VALUES = "values";
/** the separator for index/value in case of sparse instances. */
public final static String SPARSE_SEPARATOR = ":";
/** the missing value indicator. */
public final static String MISSING_VALUE = "?";
/**
* Turns the JSON object into an Attribute, if possible.
*
* @param att the JSON object to turn into an Attribute
* @param classAtt for storing whether the attribute is the class attribute
* @return the Attribute, null in case of an error
*/
protected static Attribute toAttribute(JSONNode att, boolean[] classAtt) {
Attribute result;
String name;
String type;
String dateformat;
JSONNode labels;
ArrayList<String> values;
String label;
int i;
double weight;
name = (String) att.getChild(NAME).getValue("noname");
type = (String) att.getChild(TYPE).getValue("");
weight = (Double) att.getChild(WEIGHT).getValue(new Double(1.0));
if (type.equals(Attribute.typeToString(Attribute.NUMERIC))) {
result = new Attribute(name);
}
else if (type.equals(Attribute.typeToString(Attribute.NOMINAL))) {
labels = att.getChild(LABELS);
values = new ArrayList<String>();
for (i = 0; i < labels.getChildCount(); i++) {
label = (String)((JSONNode) labels.getChildAt(i)).getValue();
if (label.equals("'" + MISSING_VALUE + "'"))
values.add(MISSING_VALUE);
else
values.add(label);
}
result = new Attribute(name, values);
}
else if (type.equals(Attribute.typeToString(Attribute.DATE))) {
dateformat = (String) att.getChild(DATEFORMAT).getValue("yyyy-MM-dd'T'HH:mm:ss");
result = new Attribute(name, dateformat);
}
else if (type.equals(Attribute.typeToString(Attribute.STRING))) {
result = new Attribute(name, (ArrayList<String>) null);
}
else {
System.err.println("Unhandled attribute type '" + type + "'!");
return null;
}
result.setWeight(weight);
return result;
}
/**
* Turns the JSON Object into an Instance, if possible.
*
* @param inst the JSON object to turn into an Instance
* @param data the data so far (only used for header information)
* @return the Instance, null in case of an error
*/
protected static Instance toInstance(JSONNode inst, Instances data) {
Instance result;
boolean sparse;
double weight;
JSONNode values;
int i;
int index;
int pos;
String value;
double[] vals;
sparse = (Boolean) inst.getChild(SPARSE).getValue(new Boolean(false));
weight = (Double) inst.getChild(WEIGHT).getValue(new Double(1.0));
values = inst.getChild(VALUES);
vals = new double[data.numAttributes()];
for (i = 0; i < values.getChildCount(); i++) {
if (sparse) {
value = "" + ((JSONNode) values.getChildAt(i)).getValue();
pos = value.indexOf(SPARSE_SEPARATOR);
index = Integer.parseInt(value.substring(0, pos));
value = value.substring(pos + 1);
}
else {
index = i;
value = "" + ((JSONNode) values.getChildAt(i)).getValue();
}
try {
if (value.equals(MISSING_VALUE)) {
vals[index] = Utils.missingValue();
}
else {
// unescape '?' labels
if (value.equals("'" + MISSING_VALUE + "'"))
value = MISSING_VALUE;
if (data.attribute(index).isNumeric() && !data.attribute(index).isDate()) {
vals[index] = Double.parseDouble(value);
}
else if (data.attribute(index).isNominal()) {
vals[index] = data.attribute(index).indexOfValue(value);
if ((vals[index] == -1) && value.startsWith("'") && value.endsWith("'"))
vals[index] = data.attribute(index).indexOfValue(Utils.unquote(value));
// FIXME backslashes seem to get escaped twice when creating a JSON file?
if ((vals[index] == -1) && value.startsWith("'") && value.endsWith("'"))
vals[index] = data.attribute(index).indexOfValue(Utils.unbackQuoteChars(Utils.unquote(value)));
if (vals[index] == -1) {
System.err.println("Unknown label '" + value + "' for attribute #" + (index+1) + "!");
return null;
}
}
else if (data.attribute(index).isDate()) {
vals[index] = data.attribute(index).parseDate(value);
}
else if (data.attribute(index).isString()) {
vals[index] = data.attribute(index).addStringValue(value);
}
else {
System.err.println("Unhandled attribute type '" + Attribute.typeToString(data.attribute(index).type()) + "'!");
return null;
}
}
}
catch (Exception e) {
System.err.println("Error parsing value #" + (index+1) + ": " + e.toString());
return null;
}
}
if (sparse)
result = new SparseInstance(weight, vals);
else
result = new DenseInstance(weight, vals);
result.setDataset(data);
return result;
}
/**
* Turns a JSON object, if possible, into an Instances object.
*
* @param json the JSON object to convert
* @param onlyHeader whether to retrieve only the header
* @return the generated Instances object, null if not possible
*/
protected static Instances toInstances(JSONNode json, boolean onlyHeader) {
Instances result;
JSONNode header;
JSONNode attributes;
JSONNode data;
ArrayList<Attribute> atts;
Attribute att;
Instance inst;
int i;
int classIndex;
boolean[] classAtt;
header = json.getChild(HEADER);
if (header == null) {
System.err.println("No '" + HEADER + "' section!");
return null;
}
data = json.getChild(DATA);
if (data == null) {
System.err.println("No '" + DATA + "' section!");
return null;
}
// attributes
attributes = header.getChild(ATTRIBUTES);
if (attributes == null) {
System.err.println("No '" + ATTRIBUTES + "' array!");
return null;
}
atts = new ArrayList<Attribute>();
classAtt = new boolean[1];
classIndex = -1;
for (i = 0; i < attributes.getChildCount(); i++) {
att = toAttribute((JSONNode) attributes.getChildAt(i), classAtt);
if (att == null) {
System.err.println("Could not convert attribute #" + (i+1) + "!");
return null;
}
if (classAtt[0])
classIndex = i;
atts.add(att);
}
result = new Instances(
header.getChild(RELATION).getValue("unknown").toString(),
atts,
(onlyHeader ? 0 : data.getChildCount()));
result.setClassIndex(classIndex);
// data
if (!onlyHeader) {
for (i = 0; i < data.getChildCount(); i++) {
inst = toInstance((JSONNode) data.getChildAt(i), result);
if (inst == null) {
System.err.println("Could not convert instance #" + (i+1) + "!");
return null;
}
result.add(inst);
}
}
return result;
}
/**
* Turns a JSON object, if possible, into an Instances object.
*
* @param json the JSON object to convert
* @return the generated Instances object, null if not possible
*/
public static Instances toInstances(JSONNode json) {
return toInstances(json, false);
}
/**
* Turns a JSON object, if possible, into an Instances object (only header).
*
* @param json the JSON object to convert
* @return the generated Instances header object, null if not possible
*/
public static Instances toHeader(JSONNode json) {
return toInstances(json, true);
}
/**
* Turns the Attribute into a JSON object.
*
* @param inst the corresponding dataset
* @param att the attribute to convert
* @return the JSON object
*/
protected static JSONNode toJSON(Instances inst, Attribute att) {
JSONNode result;
JSONNode labels;
int i;
result = new JSONNode();
result.addPrimitive(NAME, att.name());
result.addPrimitive(TYPE, Attribute.typeToString(att));
result.addPrimitive(CLASS, (att.index() == inst.classIndex()));
result.addPrimitive(WEIGHT, att.weight());
if (att.isNominal()) {
labels = result.addArray(LABELS);
for (i = 0; i < att.numValues(); i++) {
if (att.value(i).equals(MISSING_VALUE))
labels.addArrayElement("'" + att.value(i) + "'");
else
labels.addArrayElement(att.value(i));
}
}
if (att.isDate())
result.addPrimitive(DATEFORMAT, att.getDateFormat());
return result;
}
/**
* Turns the Instance into a JSON object.
*
* @param inst the Instance to convert
* @return the JSON object
*/
protected static JSONNode toJSON(Instance inst) {
JSONNode result;
JSONNode values;
int i;
boolean sparse;
result = new JSONNode();
sparse = (inst instanceof SparseInstance);
result.addPrimitive(SPARSE, sparse);
result.addPrimitive(WEIGHT, inst.weight());
values = result.addArray(VALUES);
if (sparse) {
for (i = 0; i < inst.numValues(); i++) {
if (inst.isMissing(inst.index(i)))
values.addArrayElement(inst.index(i) + SPARSE_SEPARATOR + MISSING_VALUE);
else if (inst.toString(inst.index(i)).equals("'" + MISSING_VALUE + "'"))
values.addArrayElement(inst.index(i) + SPARSE_SEPARATOR + "'" + MISSING_VALUE + "'"); // escape '?' labels
else
values.addArrayElement(inst.index(i) + SPARSE_SEPARATOR + inst.toString(inst.index(i)));
}
}
else {
for (i = 0; i < inst.numAttributes(); i++) {
if (inst.isMissing(i))
values.addArrayElement(MISSING_VALUE);
else if (inst.toString(i).equals("'" + MISSING_VALUE + "'"))
values.addArrayElement("'" + MISSING_VALUE + "'"); // escape '?' labels
else
values.addArrayElement(inst.toString(i));
}
}
return result;
}
/**
* Turns the Instances object into a JSON object.
*
* @param inst the Instances to turn into a JSON object
* @return the JSON object
*/
public static JSONNode toJSON(Instances inst) {
JSONNode result;
JSONNode header;
JSONNode atts;
JSONNode data;
int i;
result = new JSONNode();
// header
header = result.addObject(HEADER);
header.addPrimitive(RELATION, inst.relationName());
atts = header.addArray(ATTRIBUTES);
for (i = 0; i < inst.numAttributes(); i++)
atts.add(toJSON(inst, inst.attribute(i)));
// data
data = result.addArray(DATA);
for (i = 0; i < inst.numInstances(); i++)
data.add(toJSON(inst.instance(i)));
return result;
}
/**
* For testing only.
*
* @param args expects a dataset as first parameter
* @throws Exception if something goes wrong
*/
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.err.println("No dataset supplied!");
System.exit(1);
}
// load dataset
Instances data = DataSource.read(args[0]);
// turn Instances into JSON object and output it
JSONNode json = toJSON(data);
StringBuffer buffer = new StringBuffer();
json.toString(buffer);
System.out.println(buffer.toString());
// turn JSON object back into Instances and output it
Instances inst = toInstances(json);
System.out.println(inst);
}
}
|
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/json/JSONNode.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/>.
*/
/*
* JSONNode.java
* Copyright (C) 2009-2012 University of Waikato, Hamilton, New Zealand
*/
package weka.core.json;
import java_cup.runtime.DefaultSymbolFactory;
import java_cup.runtime.SymbolFactory;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import java.awt.BorderLayout;
import java.io.Reader;
/**
* Container class for storing a
* <a href="http://www.json.org/" target="_blank">JSON</a> data structure.
*
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public class JSONNode extends DefaultMutableTreeNode {
/** for serialization. */
private static final long serialVersionUID = -3047440914507883491L;
/**
* The type of a node.
*
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public static enum NodeType {
/** a primitive. */
PRIMITIVE, /** an object with nested key-value pairs. */
OBJECT, /** an array. */
ARRAY
}
/** the name of the node. */
protected String m_Name;
/** the value of the node. */
protected Object m_Value;
/** the type of the node. */
protected NodeType m_NodeType;
/**
* Initializes the root container.
*/
public JSONNode() {
this(null, NodeType.OBJECT);
}
/**
* Initializes the primitive container.
*
* @param name the name
* @param value the primitive value
*/
public JSONNode(String name, Boolean value) {
this(name, value, NodeType.PRIMITIVE);
}
/**
* Initializes the primitive container.
*
* @param name the name
* @param value the primitive value
*/
public JSONNode(String name, Integer value) {
this(name, value, NodeType.PRIMITIVE);
}
/**
* Initializes the primitive container.
*
* @param name the name
* @param value the primitive value
*/
public JSONNode(String name, Double value) {
this(name, value, NodeType.PRIMITIVE);
}
/**
* Initializes the primitive container.
*
* @param name the name
* @param value the primitive value
*/
public JSONNode(String name, String value) {
this(name, value, NodeType.PRIMITIVE);
}
/**
* Initializes the object container with null value.
*
* @param name the name
* @param type the node type
*/
protected JSONNode(String name, NodeType type) {
this(name, null, type);
}
/**
* Initializes the container.
*
* @param name the name
* @param value the primitive value
* @param type the type of the node, null for primitives
*/
protected JSONNode(String name, Object value, NodeType type) {
super();
m_Name = name;
m_Value = value;
m_NodeType = type;
}
/**
* Checks whether the node is anonymous.
*
* @return true if no name available
*/
public boolean isAnonymous() {
return (m_Name == null);
}
/**
* Returns the name of the node.
*
* @return the name, null for anonymous nodes
*/
public String getName() {
return m_Name;
}
/**
* Returns the stored value.
*
* @return the stored value, can be null
*/
public Object getValue() {
return getValue(null);
}
/**
* Returns the stored value.
*
* @param defValue the default value, if value is null
* @return the stored value, can be null
*/
public Object getValue(Object defValue) {
if (m_Value == null) {
return defValue;
} else {
if (m_Value instanceof String) {
return unescape(m_Value.toString());
} else {
return m_Value;
}
}
}
/**
* Returns whether the node stores a primitive value or a an array/object.
*
* @return true if a primitive, false in case of an array/object
*/
public boolean isPrimitive() {
return (m_NodeType == NodeType.PRIMITIVE);
}
/**
* Returns wether the node is an array.
*
* @return true if the node is array container
*/
public boolean isArray() {
return (m_NodeType == NodeType.ARRAY);
}
/**
* Returns wether the node is an object.
*
* @return true if the node is object container
*/
public boolean isObject() {
return (m_NodeType == NodeType.OBJECT);
}
/**
* Returns the type of the container.
*
* @return the type
*/
public NodeType getNodeType() {
return m_NodeType;
}
/**
* Adds a "null" child to the object.
*
* @param name the name of the null value
* @return the new node, or null if none added
*/
public JSONNode addNull(String name) {
return add(name, null, NodeType.PRIMITIVE);
}
/**
* Adds a key-value child to the object.
*
* @param name the name of the pair
* @param value the value
* @return the new node, or null if none added
*/
public JSONNode addPrimitive(String name, Boolean value) {
return add(name, value, NodeType.PRIMITIVE);
}
/**
* Adds a key-value child to the object.
*
* @param name the name of the pair
* @param value the value
* @return the new node, or null if none added
*/
public JSONNode addPrimitive(String name, Integer value) {
return add(name, value, NodeType.PRIMITIVE);
}
/**
* Adds a key-value child to the object.
*
* @param name the name of the pair
* @param value the value
* @return the new node, or null if none added
*/
public JSONNode addPrimitive(String name, Double value) {
return add(name, value, NodeType.PRIMITIVE);
}
/**
* Adds a key-value child to the object.
*
* @param name the name of the pair
* @param value the value
* @return the new node, or null if none added
*/
public JSONNode addPrimitive(String name, String value) {
return add(name, value, NodeType.PRIMITIVE);
}
/**
* Adds an array child to the object.
*
* @param name the name of the pair
* @return the new node, or null if none added
*/
public JSONNode addArray(String name) {
return add(name, null, NodeType.ARRAY);
}
/**
* Adds a null array element child to the array.
*
* @return the new node, or null if none added
*/
public JSONNode addNullArrayElement() {
return add(null, null, NodeType.PRIMITIVE);
}
/**
* Add a key-value object child into the array
*
* @return the newly added node
*/
public JSONNode addObjectArrayElement() {
return add(null, null, NodeType.OBJECT);
}
/**
* Adds an array element child to the array.
*
* @param value the value of the element array
* @return the new node, or null if none added
*/
public JSONNode addArrayElement(Object value) {
NodeType type;
if (getNodeType() != NodeType.ARRAY) {
return null;
}
type = null;
if (value != null) {
if (value instanceof Boolean) {
type = NodeType.PRIMITIVE;
} else if (value instanceof Integer) {
type = NodeType.PRIMITIVE;
} else if (value instanceof Double) {
type = NodeType.PRIMITIVE;
} else if (value instanceof String) {
type = NodeType.PRIMITIVE;
} else if (value.getClass().isArray()) {
type = NodeType.ARRAY;
} else {
type = NodeType.OBJECT;
}
}
return add(null, value, type);
}
/**
* Adds an object child to the object.
*
* @param name the name of the pair
* @return the new node, or null if none added
*/
public JSONNode addObject(String name) {
return add(name, null, NodeType.OBJECT);
}
/**
* Adds a key-value child to the object.
*
* @param name the name of the pair
* @param value the value
* @param type the node type, null for primitives
* @return the new node, or null if none added
*/
protected JSONNode add(String name, Object value, NodeType type) {
JSONNode child;
if (isPrimitive()) {
return null;
}
child = new JSONNode(name, value, type);
add(child);
return child;
}
/**
* Checks whether the node has a child with the given name.
*
* @param name the name of the child
* @return true if child with that name is available
*/
public boolean hasChild(String name) {
return (getChild(name) != null);
}
/**
* Returns the child with the given name.
*
* @param name the name of the child
* @return the child if available, null otherwise
*/
public JSONNode getChild(String name) {
JSONNode result;
JSONNode node;
int i;
result = null;
for (i = 0; i < getChildCount(); i++) {
node = (JSONNode) getChildAt(i);
if (!node.isAnonymous() && node.getName().equals(name)) {
result = node;
break;
}
}
return result;
}
/**
* Generates the indentation string.
*
* @param level the level
* @return the indentation string (tabs)
*/
protected String getIndentation(int level) {
StringBuffer result;
int i;
result = new StringBuffer();
for (i = 0; i < level; i++) {
result.append("\t");
}
return result.toString();
}
/**
* Escapes ", \, /, \b, \f, \n, \r, \t in strings.
*
* @param o the object to process (only strings get processed)
* @return the processed object
*/
protected Object escape(Object o) {
if (o instanceof String) {
return escape((String) o);
} else {
return o;
}
}
/**
* Escapes ", /, \b, \f, \n, \r, \t.
*
* @param s the string to process
* @return the processed
*/
protected String escape(String s) {
StringBuffer result;
int i;
char c;
// take care of already escaped characters first (like
// \n in string literals
// kind of ugly - probably a better way of handling this
// somehow.
s = s.replace("\\n", "@@-@@n").replace("\\r", "@@-@@r")
.replace("\\t", "@@-@@t").replace("\\b", "@@-@@b")
.replace("\\f", "@@-@@f");
if ((s.indexOf('\"') > -1) || (s.indexOf('\\') > -1)
|| (s.indexOf('\b') > -1) || (s.indexOf('\f') > -1)
|| (s.indexOf('\n') > -1) || (s.indexOf('\r') > -1)
|| (s.indexOf('\t') > -1)) {
result = new StringBuffer();
for (i = 0; i < s.length(); i++) {
c = s.charAt(i);
if (c == '\"') {
result.append("\\\"");
} else if (c == '\\') {
result.append("\\\\");
} else if (c == '\b') {
result.append("\\b");
} else if (c == '\f') {
result.append("\\f");
} else if (c == '\n') {
result.append("\\n");
} else if (c == '\r') {
result.append("\\r");
} else if (c == '\t') {
result.append("\\t");
} else {
result.append(c);
}
}
} else {
result = new StringBuffer(s);
}
return result.toString();
}
/**
* Un-escapes ", /, \b, \f, \n, \r, \t.
*
* @param s the string to process
* @return the processed string
*/
protected String unescape(String s) {
StringBuilder newStringBuffer;
int index;
// replace each of the following characters with the backquoted version
String charsFind[] = { "\\\\", "\\'", "\\t", "\\n", "\\r", "\\b", "\\f",
"\\\"", "\\%", "\\u001E" };
char charsReplace[] =
{ '\\', '\'', '\t', '\n', '\r', '\b', '\f', '"', '%', '\u001E' };
int pos[] = new int[charsFind.length];
int curPos;
String str = new String(s);
newStringBuffer = new StringBuilder();
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().replace("@@-@@", "\\");
}
/**
* Dumps the node structure into JSON format.
*
* @param buffer the buffer to add the data to
*/
public void toString(StringBuffer buffer) {
int level;
boolean isLast;
String indent;
int i;
level = getLevel();
isLast = (getNextSibling() == null);
indent = getIndentation(level);
buffer.append(indent);
if (m_Name != null) {
buffer.append("\"");
buffer.append(escape(m_Name));
buffer.append("\" : ");
}
if (isObject()) {
buffer.append("{\n");
for (i = 0; i < getChildCount(); i++) {
((JSONNode) getChildAt(i)).toString(buffer);
}
buffer.append(indent);
buffer.append("}");
} else if (isArray()) {
buffer.append("[\n");
for (i = 0; i < getChildCount(); i++) {
((JSONNode) getChildAt(i)).toString(buffer);
}
buffer.append(indent);
buffer.append("]");
} else {
if (m_Value == null) {
buffer.append("null");
} else if (m_Value instanceof String) {
buffer.append("\"");
buffer.append(escape((String) m_Value));
buffer.append("\"");
} else {
buffer.append(m_Value.toString());
}
}
if (!isLast) {
buffer.append(",");
}
buffer.append("\n");
}
/**
* Returns a string representation of the node.
*
* @return the string representation
*/
@Override
public String toString() {
String result;
result = null;
if (isObject()) {
if (isRoot()) {
result = "JSON";
} else if (m_Name == null) {
result = "<object>";
} else {
result = escape(m_Name) + " (Object)";
}
} else if (isArray()) {
if (m_Name == null) {
result = "<array>";
} else {
result = escape(m_Name) + " (Array)";
}
} else {
if (m_Name != null) {
result = escape(m_Name) + ": " + escape(m_Value);
} else {
result = "" + m_Value;
}
}
return result;
}
/**
* Reads the JSON object from the given reader.
*
* @param reader the reader to read the JSON object from
* @return the generated JSON object
* @throws Exception if parsing fails
*/
@SuppressWarnings("deprecation")
public static JSONNode read(Reader reader) throws Exception {
SymbolFactory sf;
Parser parser;
sf = new DefaultSymbolFactory();
parser = new Parser(new Scanner(reader, sf), sf);
parser.parse();
return parser.getResult();
}
/**
* Only for testing. Generates a simple JSON object and displays it.
*
* @param args ignored
* @throws Exception if something goes wrong
*/
public static void main(String[] args) throws Exception {
// generates the example listed here:
// http://en.wikipedia.org/wiki/JSON
JSONNode person = new JSONNode();
person.addPrimitive("firstName", "John");
person.addPrimitive("lastName", "Smith");
JSONNode address = person.addObject("address");
address.addPrimitive("streetAddress", "21 2nd Street");
address.addPrimitive("city", "New York");
address.addPrimitive("state", "NY");
address.addPrimitive("postalCode", 10021);
JSONNode phonenumbers = person.addArray("phoneNumbers");
phonenumbers.addArrayElement("212 555-1234");
phonenumbers.addArrayElement("646 555-4567");
// output in console
StringBuffer buffer = new StringBuffer();
person.toString(buffer);
System.out.println(buffer.toString());
// display GUI
JTree tree = new JTree(person);
JFrame frame = new JFrame("JSON");
frame.setSize(800, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(new JScrollPane(tree), BorderLayout.CENTER);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
|
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/json/Parser.java
|
//----------------------------------------------------
// The following code was generated by CUP v0.11b 20141202 (SVN rev 60)
//----------------------------------------------------
package weka.core.json;
import java_cup.runtime.*;
import java.io.*;
import java.util.*;
import java_cup.runtime.XMLElement;
/** CUP v0.11b 20141202 (SVN rev 60) generated parser.
*/
@SuppressWarnings({"rawtypes"})
public class Parser extends java_cup.runtime.lr_parser {
public final Class getSymbolContainer() {
return sym.class;
}
/** Default constructor. */
public Parser() {super();}
/** Constructor which sets the default scanner. */
public Parser(java_cup.runtime.Scanner s) {super(s);}
/** Constructor which sets the default scanner. */
public Parser(java_cup.runtime.Scanner s, java_cup.runtime.SymbolFactory sf) {super(s,sf);}
/** Production table. */
protected static final short _production_table[][] =
unpackFromStrings(new String[] {
"\000\053\000\002\002\004\000\002\002\004\000\002\002" +
"\005\000\002\003\005\000\002\003\003\000\002\004\003" +
"\000\002\004\003\000\002\004\003\000\002\005\003\000" +
"\002\005\003\000\002\005\003\000\002\005\003\000\002" +
"\005\003\000\002\006\005\000\002\007\005\000\002\010" +
"\005\000\002\011\005\000\002\012\005\000\002\014\004" +
"\000\002\014\005\000\002\015\005\000\002\013\004\000" +
"\002\013\005\000\002\016\003\000\002\017\003\000\002" +
"\020\003\000\002\022\004\000\002\022\005\000\002\023" +
"\005\000\002\021\004\000\002\021\005\000\002\024\003" +
"\000\002\025\003\000\002\026\003\000\002\027\005\000" +
"\002\027\003\000\002\030\003\000\002\030\003\000\002" +
"\030\003\000\002\030\003\000\002\030\003\000\002\030" +
"\003\000\002\030\003" });
/** Access to production table. */
public short[][] production_table() {return _production_table;}
/** Parse-action table. */
protected static final short[][] _action_table =
unpackFromStrings(new String[] {
"\000\073\000\004\007\005\001\002\000\004\002\075\001" +
"\002\000\006\010\020\016\014\001\002\000\006\004\062" +
"\010\074\001\002\000\006\010\060\016\014\001\002\000" +
"\022\005\035\006\043\007\051\012\042\013\041\014\037" +
"\015\047\016\045\001\002\000\006\004\ufffd\010\ufffd\001" +
"\002\000\006\004\ufffb\010\ufffb\001\002\000\006\004\ufff7" +
"\010\ufff7\001\002\000\004\011\024\001\002\000\006\004" +
"\ufff9\010\ufff9\001\002\000\006\004\ufffc\010\ufffc\001\002" +
"\000\006\004\ufff5\010\ufff5\001\002\000\004\002\001\001" +
"\002\000\006\004\ufff6\010\ufff6\001\002\000\006\004\ufffa" +
"\010\ufffa\001\002\000\006\004\ufff8\010\ufff8\001\002\000" +
"\020\005\025\007\031\012\032\013\033\014\026\015\027" +
"\016\030\001\002\000\022\005\uffe5\006\uffe5\007\uffe5\012" +
"\uffe5\013\uffe5\014\uffe5\015\uffe5\016\uffe5\001\002\000\006" +
"\004\ufff2\010\ufff2\001\002\000\006\004\ufff1\010\ufff1\001" +
"\002\000\006\004\ufff0\010\ufff0\001\002\000\006\010\uffed" +
"\016\uffed\001\002\000\006\004\ufff4\010\ufff4\001\002\000" +
"\006\004\ufff3\010\ufff3\001\002\000\006\004\067\006\uffe1" +
"\001\002\000\022\005\uffe2\006\uffe2\007\uffe2\012\uffe2\013" +
"\uffe2\014\uffe2\015\uffe2\016\uffe2\001\002\000\022\005\035" +
"\006\043\007\051\012\042\013\041\014\037\015\047\016" +
"\045\001\002\000\006\004\uffdb\006\uffdb\001\002\000\006" +
"\004\uffe7\010\uffe7\001\002\000\006\004\uffdc\006\uffdc\001" +
"\002\000\006\004\uffdd\006\uffdd\001\002\000\010\004\uffe0" +
"\006\uffe0\010\uffe0\001\002\000\006\004\uffde\006\uffde\001" +
"\002\000\006\004\uffd9\006\uffd9\001\002\000\006\010\060" +
"\016\014\001\002\000\006\004\uffda\006\uffda\001\002\000" +
"\004\006\043\001\002\000\006\010\uffea\016\uffea\001\002" +
"\000\006\004\uffd7\006\uffd7\001\002\000\006\004\uffd8\006" +
"\uffd8\001\002\000\006\004\uffe6\010\uffe6\001\002\000\006" +
"\004\062\010\uffe9\001\002\000\004\010\060\001\002\000" +
"\006\004\uffec\006\uffec\001\002\000\010\004\uffe8\006\uffe8" +
"\010\uffe8\001\002\000\006\004\uffeb\006\uffeb\001\002\000" +
"\004\016\014\001\002\000\006\004\ufffe\010\ufffe\001\002" +
"\000\006\004\uffe4\006\uffe4\001\002\000\004\006\043\001" +
"\002\000\006\004\uffe3\006\uffe3\001\002\000\020\005\035" +
"\007\051\012\042\013\041\014\037\015\047\016\045\001" +
"\002\000\006\004\uffdf\006\uffdf\001\002\000\004\010\060" +
"\001\002\000\006\004\uffef\010\uffef\001\002\000\006\004" +
"\uffee\010\uffee\001\002\000\004\002\uffff\001\002\000\004" +
"\002\000\001\002" });
/** Access to parse-action table. */
public short[][] action_table() {return _action_table;}
/** <code>reduce_goto</code> table. */
protected static final short[][] _reduce_table =
unpackFromStrings(new String[] {
"\000\073\000\004\002\003\001\001\000\002\001\001\000" +
"\032\003\005\004\010\005\015\006\014\007\022\010\012" +
"\011\020\012\016\014\011\015\006\022\021\023\007\001" +
"\001\000\002\001\001\000\036\003\054\004\010\005\015" +
"\006\014\007\022\010\012\011\020\012\016\014\011\015" +
"\006\017\070\020\071\022\021\023\007\001\001\000\022" +
"\013\052\016\045\021\051\024\035\025\047\026\037\027" +
"\033\030\043\001\001\000\002\001\001\000\002\001\001" +
"\000\002\001\001\000\002\001\001\000\002\001\001\000" +
"\002\001\001\000\002\001\001\000\002\001\001\000\002" +
"\001\001\000\002\001\001\000\002\001\001\000\002\001" +
"\001\000\002\001\001\000\002\001\001\000\002\001\001" +
"\000\002\001\001\000\002\001\001\000\002\001\001\000" +
"\002\001\001\000\002\001\001\000\002\001\001\000\022" +
"\013\052\016\045\021\051\024\035\025\064\026\063\027" +
"\033\030\043\001\001\000\002\001\001\000\002\001\001" +
"\000\002\001\001\000\002\001\001\000\002\001\001\000" +
"\002\001\001\000\002\001\001\000\036\003\054\004\010" +
"\005\015\006\014\007\022\010\012\011\020\012\016\014" +
"\011\015\006\017\055\020\056\022\021\023\007\001\001" +
"\000\002\001\001\000\004\026\053\001\001\000\002\001" +
"\001\000\002\001\001\000\002\001\001\000\002\001\001" +
"\000\002\001\001\000\004\020\060\001\001\000\002\001" +
"\001\000\002\001\001\000\002\001\001\000\030\004\062" +
"\005\015\006\014\007\022\010\012\011\020\012\016\014" +
"\011\015\006\022\021\023\007\001\001\000\002\001\001" +
"\000\002\001\001\000\004\026\065\001\001\000\002\001" +
"\001\000\014\013\052\016\045\021\051\024\035\030\067" +
"\001\001\000\002\001\001\000\004\020\072\001\001\000" +
"\002\001\001\000\002\001\001\000\002\001\001\000\002" +
"\001\001" });
/** Access to <code>reduce_goto</code> table. */
public short[][] reduce_table() {return _reduce_table;}
/** Instance of action encapsulation class. */
protected CUP$Parser$actions action_obj;
/** Action encapsulation object initializer. */
protected void init_actions()
{
action_obj = new CUP$Parser$actions(this);
}
/** Invoke a user supplied parse action. */
public java_cup.runtime.Symbol do_action(
int act_num,
java_cup.runtime.lr_parser parser,
java.util.Stack stack,
int top)
throws java.lang.Exception
{
/* call code in generated class */
return action_obj.CUP$Parser$do_action(act_num, parser, stack, top);
}
/** Indicates start state. */
public int start_state() {return 0;}
/** Indicates start production. */
public int start_production() {return 1;}
/** <code>EOF</code> Symbol index. */
public int EOF_sym() {return 0;}
/** <code>error</code> Symbol index. */
public int error_sym() {return 1;}
/** User initialization code. */
public void user_init() throws java.lang.Exception
{
m_Symbols = new HashMap();
m_Result = new JSONNode();
m_Stack = new Stack<JSONNode>();
m_Stack.push(m_Result);
}
/** variable - value relation. */
protected HashMap m_Symbols;
/** for storing the parsed JSON data structure. */
protected JSONNode m_Result;
/** the stack for keeping track of the current parent node. */
protected Stack<JSONNode> m_Stack;
/**
* Returns the JSON data structure.
*
* @return the result
*/
public JSONNode getResult() {
return m_Result;
}
/**
* Returns the stack used internally for keeping track of the current
* parent node.
*
* @return the stack
*/
protected Stack<JSONNode> getStack() {
return m_Stack;
}
/**
* Runs the parser from commandline. Expects a filename as first parameter,
* pointing to a JSON file.
*
* @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("No JSON file specified!");
System.exit(1);
}
FileInputStream stream = new FileInputStream(args[0]);
SymbolFactory sf = new DefaultSymbolFactory();
Parser parser = new Parser(new Scanner(stream, sf), sf);
parser.parse();
StringBuffer buffer = new StringBuffer();
parser.getResult().toString(buffer);
System.out.println(buffer.toString());
}
/** Cup generated class to encapsulate user supplied action code.*/
@SuppressWarnings({"rawtypes", "unchecked", "unused"})
class CUP$Parser$actions {
private final Parser parser;
/** Constructor */
CUP$Parser$actions(Parser parser) {
this.parser = parser;
}
/** Method 0 with the actual generated action code for actions 0 to 300. */
public final java_cup.runtime.Symbol CUP$Parser$do_action_part00000000(
int CUP$Parser$act_num,
java_cup.runtime.lr_parser CUP$Parser$parser,
java.util.Stack CUP$Parser$stack,
int CUP$Parser$top)
throws java.lang.Exception
{
/* Symbol object for return from actions */
java_cup.runtime.Symbol CUP$Parser$result;
/* select the action based on the action number */
switch (CUP$Parser$act_num)
{
/*. . . . . . . . . . . . . . . . . . . .*/
case 0: // json ::= LCURLY RCURLY
{
Object RESULT =null;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("json",0, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 1: // $START ::= json EOF
{
Object RESULT =null;
Object start_val = (Object)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-1)).value;
RESULT = start_val;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("$START",0, RESULT);
}
/* ACCEPT */
CUP$Parser$parser.done_parsing();
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 2: // json ::= LCURLY pairs RCURLY
{
Object RESULT =null;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("json",0, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 3: // pairs ::= pairs COMMA pair
{
Object RESULT =null;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("pairs",1, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 4: // pairs ::= pair
{
Object RESULT =null;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("pairs",1, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 5: // pair ::= primitive
{
Object RESULT =null;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("pair",2, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 6: // pair ::= named_object
{
Object RESULT =null;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("pair",2, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 7: // pair ::= named_array
{
Object RESULT =null;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("pair",2, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 8: // primitive ::= null
{
Object RESULT =null;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("primitive",3, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 9: // primitive ::= boolean
{
Object RESULT =null;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("primitive",3, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 10: // primitive ::= integer
{
Object RESULT =null;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("primitive",3, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 11: // primitive ::= double
{
Object RESULT =null;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("primitive",3, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 12: // primitive ::= string
{
Object RESULT =null;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("primitive",3, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 13: // null ::= STRING COLON NULL
{
Object RESULT =null;
String name = (String)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-2)).value;
parser.getStack().peek().addNull(name);
CUP$Parser$result = parser.getSymbolFactory().newSymbol("null",4, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 14: // boolean ::= STRING COLON BOOLEAN
{
Boolean RESULT =null;
String name = (String)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-2)).value;
Boolean b = (Boolean)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value;
parser.getStack().peek().addPrimitive(name, b);
CUP$Parser$result = parser.getSymbolFactory().newSymbol("boolean",5, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 15: // integer ::= STRING COLON INTEGER
{
Integer RESULT =null;
String name = (String)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-2)).value;
Integer i = (Integer)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value;
parser.getStack().peek().addPrimitive(name, i);
CUP$Parser$result = parser.getSymbolFactory().newSymbol("integer",6, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 16: // double ::= STRING COLON DOUBLE
{
Double RESULT =null;
String name = (String)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-2)).value;
Double d = (Double)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value;
parser.getStack().peek().addPrimitive(name, d);
CUP$Parser$result = parser.getSymbolFactory().newSymbol("double",7, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 17: // string ::= STRING COLON STRING
{
String RESULT =null;
String name = (String)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-2)).value;
String s = (String)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value;
parser.getStack().peek().addPrimitive(name, s);
CUP$Parser$result = parser.getSymbolFactory().newSymbol("string",8, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 18: // named_object ::= named_object_start object_end
{
Object RESULT =null;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("named_object",10, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 19: // named_object ::= named_object_start object_content object_end
{
Object RESULT =null;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("named_object",10, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 20: // named_object_start ::= STRING COLON LCURLY
{
Object RESULT =null;
String name = (String)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-2)).value;
JSONNode node = parser.getStack().peek().addObject(name);
parser.getStack().push(node);
CUP$Parser$result = parser.getSymbolFactory().newSymbol("named_object_start",11, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 21: // anon_object ::= anon_object_start object_end
{
Object RESULT =null;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("anon_object",9, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 22: // anon_object ::= anon_object_start object_content object_end
{
Object RESULT =null;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("anon_object",9, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 23: // anon_object_start ::= LCURLY
{
Object RESULT =null;
JSONNode node = parser.getStack().peek().addObject(null);
parser.getStack().push(node);
CUP$Parser$result = parser.getSymbolFactory().newSymbol("anon_object_start",12, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 24: // object_content ::= pairs
{
Object RESULT =null;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("object_content",13, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 25: // object_end ::= RCURLY
{
Object RESULT =null;
parser.getStack().pop();
CUP$Parser$result = parser.getSymbolFactory().newSymbol("object_end",14, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 26: // named_array ::= named_array_start array_end
{
Object RESULT =null;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("named_array",16, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 27: // named_array ::= named_array_start array_content array_end
{
Object RESULT =null;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("named_array",16, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 28: // named_array_start ::= STRING COLON LSQUARE
{
Object RESULT =null;
String name = (String)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-2)).value;
JSONNode node = parser.getStack().peek().addArray(name);
parser.getStack().push(node);
CUP$Parser$result = parser.getSymbolFactory().newSymbol("named_array_start",17, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 29: // anon_array ::= anon_array_start array_end
{
Object RESULT =null;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("anon_array",15, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 30: // anon_array ::= anon_array_start array_content array_end
{
Object RESULT =null;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("anon_array",15, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 31: // anon_array_start ::= LSQUARE
{
Object RESULT =null;
JSONNode node = parser.getStack().peek().addArray(null);
parser.getStack().push(node);
CUP$Parser$result = parser.getSymbolFactory().newSymbol("anon_array_start",18, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 32: // array_content ::= elements
{
Object RESULT =null;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("array_content",19, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 33: // array_end ::= RSQUARE
{
Object RESULT =null;
parser.getStack().pop();
CUP$Parser$result = parser.getSymbolFactory().newSymbol("array_end",20, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 34: // elements ::= elements COMMA element
{
Object RESULT =null;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("elements",21, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 35: // elements ::= element
{
Object RESULT =null;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("elements",21, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 36: // element ::= NULL
{
Object RESULT =null;
parser.getStack().peek().addArrayElement(null);
CUP$Parser$result = parser.getSymbolFactory().newSymbol("element",22, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 37: // element ::= BOOLEAN
{
Object RESULT =null;
Boolean b = (Boolean)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value;
parser.getStack().peek().addArrayElement(b);
CUP$Parser$result = parser.getSymbolFactory().newSymbol("element",22, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 38: // element ::= INTEGER
{
Object RESULT =null;
Integer i = (Integer)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value;
parser.getStack().peek().addArrayElement(i);
CUP$Parser$result = parser.getSymbolFactory().newSymbol("element",22, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 39: // element ::= DOUBLE
{
Object RESULT =null;
Double d = (Double)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value;
parser.getStack().peek().addArrayElement(d);
CUP$Parser$result = parser.getSymbolFactory().newSymbol("element",22, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 40: // element ::= STRING
{
Object RESULT =null;
String s = (String)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value;
parser.getStack().peek().addArrayElement(s);
CUP$Parser$result = parser.getSymbolFactory().newSymbol("element",22, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 41: // element ::= anon_object
{
Object RESULT =null;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("element",22, RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 42: // element ::= anon_array
{
Object RESULT =null;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("element",22, RESULT);
}
return CUP$Parser$result;
/* . . . . . .*/
default:
throw new Exception(
"Invalid action number "+CUP$Parser$act_num+"found in internal parse table");
}
} /* end of method */
/** Method splitting the generated action code into several parts. */
public final java_cup.runtime.Symbol CUP$Parser$do_action(
int CUP$Parser$act_num,
java_cup.runtime.lr_parser CUP$Parser$parser,
java.util.Stack CUP$Parser$stack,
int CUP$Parser$top)
throws java.lang.Exception
{
return CUP$Parser$do_action_part00000000(
CUP$Parser$act_num,
CUP$Parser$parser,
CUP$Parser$stack,
CUP$Parser$top);
}
}
}
|
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/json/Scanner.java
|
/* The following code was generated by JFlex 1.6.0 */
/*
* 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/>.
*/
/*
* Scanner.java
* Copyright (C) 2009-2012 University of Waikato, Hamilton, New Zealand
*/
package weka.core.json;
import java_cup.runtime.SymbolFactory;
import java.io.*;
/**
* A scanner for JSON data files.
*
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public class Scanner implements java_cup.runtime.Scanner {
/** This character denotes the end of file */
public static final int YYEOF = -1;
/** initial size of the lookahead buffer */
private static final int ZZ_BUFFERSIZE = 16384;
/** lexical states */
public static final int YYINITIAL = 0;
public static final int STRING = 2;
/**
* ZZ_LEXSTATE[l] is the state in the DFA for the lexical state l
* ZZ_LEXSTATE[l+1] is the state in the DFA for the lexical state l
* at the beginning of a line
* l is of the form l = 2*k, k a non negative integer
*/
private static final int ZZ_LEXSTATE[] = {
0, 0, 1, 1
};
/**
* Translates characters to character classes
*/
private static final char [] ZZ_CMAP = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 20, 24, 0, 20, 22, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
20, 0, 19, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 18, 17, 0,
16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 6, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 21, 4, 0, 0,
0, 14, 23, 0, 0, 12, 13, 0, 0, 0, 0, 0, 9, 0, 7, 0,
0, 0, 11, 15, 10, 8, 0, 0, 0, 0, 0, 1, 0, 2, 0, 0
};
/**
* Translates DFA states to action switch labels.
*/
private static final int [] ZZ_ACTION = zzUnpackAction();
private static final String ZZ_ACTION_PACKED_0 =
"\2\0\1\1\1\2\1\3\1\4\1\5\1\6\1\7"+
"\3\1\1\10\1\1\1\11\1\12\1\13\1\14\1\15"+
"\3\0\2\16\1\17\1\20\1\21\1\22\1\23\1\24"+
"\3\0\1\25\1\26";
private static int [] zzUnpackAction() {
int [] result = new int[35];
int offset = 0;
offset = zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result);
return result;
}
private static int zzUnpackAction(String packed, int offset, int [] result) {
int i = 0; /* index in packed string */
int j = offset; /* index in unpacked array */
int l = packed.length();
while (i < l) {
int count = packed.charAt(i++);
int value = packed.charAt(i++);
do result[j++] = value; while (--count > 0);
}
return j;
}
/**
* Translates a state to a row index in the transition table
*/
private static final int [] ZZ_ROWMAP = zzUnpackRowMap();
private static final String ZZ_ROWMAP_PACKED_0 =
"\0\0\0\31\0\62\0\62\0\62\0\62\0\62\0\62"+
"\0\62\0\113\0\144\0\175\0\226\0\257\0\62\0\62"+
"\0\310\0\62\0\341\0\372\0\u0113\0\u012c\0\u0145\0\u015e"+
"\0\62\0\62\0\62\0\62\0\62\0\62\0\u0177\0\u0190"+
"\0\u01a9\0\62\0\62";
private static int [] zzUnpackRowMap() {
int [] result = new int[35];
int offset = 0;
offset = zzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result);
return result;
}
private static int zzUnpackRowMap(String packed, int offset, int [] result) {
int i = 0; /* index in packed string */
int j = offset; /* index in unpacked array */
int l = packed.length();
while (i < l) {
int high = packed.charAt(i++) << 16;
result[j++] = high | packed.charAt(i++);
}
return j;
}
/**
* The transition table of the DFA
*/
private static final int [] ZZ_TRANS = zzUnpackTrans();
private static final String ZZ_TRANS_PACKED_0 =
"\1\3\1\4\1\5\1\6\1\7\1\10\1\11\1\12"+
"\2\3\1\13\2\3\1\14\2\3\1\15\1\3\1\16"+
"\1\17\1\20\1\3\1\20\1\3\1\20\23\21\1\22"+
"\1\21\1\23\1\3\1\21\42\0\1\24\33\0\1\25"+
"\33\0\1\26\32\0\1\15\1\27\27\0\1\30\10\0"+
"\23\21\1\0\1\21\2\0\1\21\10\0\1\31\2\0"+
"\1\32\1\33\1\0\1\34\5\0\1\35\3\0\1\36"+
"\12\0\1\37\27\0\1\40\31\0\1\41\37\0\1\27"+
"\30\0\1\30\1\27\20\0\1\42\33\0\1\43\33\0"+
"\1\40\11\0";
private static int [] zzUnpackTrans() {
int [] result = new int[450];
int offset = 0;
offset = zzUnpackTrans(ZZ_TRANS_PACKED_0, offset, result);
return result;
}
private static int zzUnpackTrans(String packed, int offset, int [] result) {
int i = 0; /* index in packed string */
int j = offset; /* index in unpacked array */
int l = packed.length();
while (i < l) {
int count = packed.charAt(i++);
int value = packed.charAt(i++);
value--;
do result[j++] = value; while (--count > 0);
}
return j;
}
/* error codes */
private static final int ZZ_UNKNOWN_ERROR = 0;
private static final int ZZ_NO_MATCH = 1;
private static final int ZZ_PUSHBACK_2BIG = 2;
/* error messages for the codes above */
private static final String ZZ_ERROR_MSG[] = {
"Unkown internal scanner error",
"Error: could not match input",
"Error: pushback value was too large"
};
/**
* ZZ_ATTRIBUTE[aState] contains the attributes of state <code>aState</code>
*/
private static final int [] ZZ_ATTRIBUTE = zzUnpackAttribute();
private static final String ZZ_ATTRIBUTE_PACKED_0 =
"\2\0\7\11\5\1\2\11\1\1\1\11\1\1\3\0"+
"\2\1\6\11\3\0\2\11";
private static int [] zzUnpackAttribute() {
int [] result = new int[35];
int offset = 0;
offset = zzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result);
return result;
}
private static int zzUnpackAttribute(String packed, int offset, int [] result) {
int i = 0; /* index in packed string */
int j = offset; /* index in unpacked array */
int l = packed.length();
while (i < l) {
int count = packed.charAt(i++);
int value = packed.charAt(i++);
do result[j++] = value; while (--count > 0);
}
return j;
}
/** the input device */
private java.io.Reader zzReader;
/** the current state of the DFA */
private int zzState;
/** the current lexical state */
private int zzLexicalState = YYINITIAL;
/** this buffer contains the current text to be matched and is
the source of the yytext() string */
private char zzBuffer[] = new char[ZZ_BUFFERSIZE];
/** the textposition at the last accepting state */
private int zzMarkedPos;
/** the current text position in the buffer */
private int zzCurrentPos;
/** startRead marks the beginning of the yytext() string in the buffer */
private int zzStartRead;
/** endRead marks the last character in the buffer, that has been read
from input */
private int zzEndRead;
/** number of newlines encountered up to the start of the matched text */
private int yyline;
/** the number of characters up to the start of the matched text */
private int yychar;
/**
* the number of characters from the last newline up to the start of the
* matched text
*/
private int yycolumn;
/**
* zzAtBOL == true <=> the scanner is currently at the beginning of a line
*/
private boolean zzAtBOL = true;
/** zzAtEOF == true <=> the scanner is at the EOF */
private boolean zzAtEOF;
/** denotes if the user-EOF-code has already been executed */
private boolean zzEOFDone;
/**
* The number of occupied positions in zzBuffer beyond zzEndRead.
* When a lead/high surrogate has been read from the input stream
* into the final zzBuffer position, this will have a value of 1;
* otherwise, it will have a value of 0.
*/
private int zzFinalHighSurrogate = 0;
/* user code: */
// Author: FracPete (fracpete at waikato dot ac dot nz)
// Version: $Revision$
protected SymbolFactory m_SF;
protected StringBuffer m_String = new StringBuffer();
public Scanner(InputStream r, SymbolFactory sf) {
this(new InputStreamReader(r));
m_SF = sf;
}
public Scanner(Reader r, SymbolFactory sf) {
this(r);
m_SF = sf;
}
/**
* Creates a new scanner
*
* @param in the java.io.Reader to read input from.
*/
public Scanner(java.io.Reader in) {
this.zzReader = in;
}
/**
* Refills the input buffer.
*
* @return <code>false</code>, iff there was new input.
*
* @exception java.io.IOException if any I/O-Error occurs
*/
private boolean zzRefill() throws java.io.IOException {
/* first: make room (if you can) */
if (zzStartRead > 0) {
zzEndRead += zzFinalHighSurrogate;
zzFinalHighSurrogate = 0;
System.arraycopy(zzBuffer, zzStartRead,
zzBuffer, 0,
zzEndRead-zzStartRead);
/* translate stored positions */
zzEndRead-= zzStartRead;
zzCurrentPos-= zzStartRead;
zzMarkedPos-= zzStartRead;
zzStartRead = 0;
}
/* is the buffer big enough? */
if (zzCurrentPos >= zzBuffer.length - zzFinalHighSurrogate) {
/* if not: blow it up */
char newBuffer[] = new char[zzBuffer.length*2];
System.arraycopy(zzBuffer, 0, newBuffer, 0, zzBuffer.length);
zzBuffer = newBuffer;
zzEndRead += zzFinalHighSurrogate;
zzFinalHighSurrogate = 0;
}
/* fill the buffer with new input */
int requested = zzBuffer.length - zzEndRead;
int totalRead = 0;
while (totalRead < requested) {
int numRead = zzReader.read(zzBuffer, zzEndRead + totalRead, requested - totalRead);
if (numRead == -1) {
break;
}
totalRead += numRead;
}
if (totalRead > 0) {
zzEndRead += totalRead;
if (totalRead == requested) { /* possibly more input available */
if (Character.isHighSurrogate(zzBuffer[zzEndRead - 1])) {
--zzEndRead;
zzFinalHighSurrogate = 1;
}
}
return false;
}
// totalRead = 0: End of stream
return true;
}
/**
* Closes the input stream.
*/
public final void yyclose() throws java.io.IOException {
zzAtEOF = true; /* indicate end of file */
zzEndRead = zzStartRead; /* invalidate buffer */
if (zzReader != null)
zzReader.close();
}
/**
* Resets the scanner to read from a new input stream.
* Does not close the old reader.
*
* All internal variables are reset, the old input stream
* <b>cannot</b> be reused (internal buffer is discarded and lost).
* Lexical state is set to <tt>ZZ_INITIAL</tt>.
*
* Internal scan buffer is resized down to its initial length, if it has grown.
*
* @param reader the new input stream
*/
public final void yyreset(java.io.Reader reader) {
zzReader = reader;
zzAtBOL = true;
zzAtEOF = false;
zzEOFDone = false;
zzEndRead = zzStartRead = 0;
zzCurrentPos = zzMarkedPos = 0;
zzFinalHighSurrogate = 0;
yyline = yychar = yycolumn = 0;
zzLexicalState = YYINITIAL;
if (zzBuffer.length > ZZ_BUFFERSIZE)
zzBuffer = new char[ZZ_BUFFERSIZE];
}
/**
* Returns the current lexical state.
*/
public final int yystate() {
return zzLexicalState;
}
/**
* Enters a new lexical state
*
* @param newState the new lexical state
*/
public final void yybegin(int newState) {
zzLexicalState = newState;
}
/**
* Returns the text matched by the current regular expression.
*/
public final String yytext() {
return new String( zzBuffer, zzStartRead, zzMarkedPos-zzStartRead );
}
/**
* Returns the character at position <tt>pos</tt> from the
* matched text.
*
* It is equivalent to yytext().charAt(pos), but faster
*
* @param pos the position of the character to fetch.
* A value from 0 to yylength()-1.
*
* @return the character at position pos
*/
public final char yycharat(int pos) {
return zzBuffer[zzStartRead+pos];
}
/**
* Returns the length of the matched text region.
*/
public final int yylength() {
return zzMarkedPos-zzStartRead;
}
/**
* Reports an error that occured while scanning.
*
* In a wellformed scanner (no or only correct usage of
* yypushback(int) and a match-all fallback rule) this method
* will only be called with things that "Can't Possibly Happen".
* If this method is called, something is seriously wrong
* (e.g. a JFlex bug producing a faulty scanner etc.).
*
* Usual syntax/scanner level error handling should be done
* in error fallback rules.
*
* @param errorCode the code of the errormessage to display
*/
private void zzScanError(int errorCode) {
String message;
try {
message = ZZ_ERROR_MSG[errorCode];
}
catch (ArrayIndexOutOfBoundsException e) {
message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR];
}
throw new Error(message);
}
/**
* Pushes the specified amount of characters back into the input stream.
*
* They will be read again by then next call of the scanning method
*
* @param number the number of characters to be read again.
* This number must not be greater than yylength()!
*/
public void yypushback(int number) {
if ( number > yylength() )
zzScanError(ZZ_PUSHBACK_2BIG);
zzMarkedPos -= number;
}
/**
* Resumes scanning until the next regular expression is matched,
* the end of input is encountered or an I/O-Error occurs.
*
* @return the next token
* @exception java.io.IOException if any I/O-Error occurs
*/
public java_cup.runtime.Symbol next_token() throws java.io.IOException {
int zzInput;
int zzAction;
// cached fields:
int zzCurrentPosL;
int zzMarkedPosL;
int zzEndReadL = zzEndRead;
char [] zzBufferL = zzBuffer;
char [] zzCMapL = ZZ_CMAP;
int [] zzTransL = ZZ_TRANS;
int [] zzRowMapL = ZZ_ROWMAP;
int [] zzAttrL = ZZ_ATTRIBUTE;
while (true) {
zzMarkedPosL = zzMarkedPos;
zzAction = -1;
zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL;
zzState = ZZ_LEXSTATE[zzLexicalState];
// set up zzAction for empty match case:
int zzAttributes = zzAttrL[zzState];
if ( (zzAttributes & 1) == 1 ) {
zzAction = zzState;
}
zzForAction: {
while (true) {
if (zzCurrentPosL < zzEndReadL) {
zzInput = Character.codePointAt(zzBufferL, zzCurrentPosL, zzEndReadL);
zzCurrentPosL += Character.charCount(zzInput);
}
else if (zzAtEOF) {
zzInput = YYEOF;
break zzForAction;
}
else {
// store back cached positions
zzCurrentPos = zzCurrentPosL;
zzMarkedPos = zzMarkedPosL;
boolean eof = zzRefill();
// get translated positions and possibly new buffer
zzCurrentPosL = zzCurrentPos;
zzMarkedPosL = zzMarkedPos;
zzBufferL = zzBuffer;
zzEndReadL = zzEndRead;
if (eof) {
zzInput = YYEOF;
break zzForAction;
}
else {
zzInput = Character.codePointAt(zzBufferL, zzCurrentPosL, zzEndReadL);
zzCurrentPosL += Character.charCount(zzInput);
}
}
int zzNext = zzTransL[ zzRowMapL[zzState] + zzCMapL[zzInput] ];
if (zzNext == -1) break zzForAction;
zzState = zzNext;
zzAttributes = zzAttrL[zzState];
if ( (zzAttributes & 1) == 1 ) {
zzAction = zzState;
zzMarkedPosL = zzCurrentPosL;
if ( (zzAttributes & 8) == 8 ) break zzForAction;
}
}
}
// store back cached position
zzMarkedPos = zzMarkedPosL;
switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) {
case 1:
{ System.err.println("Illegal character: " + yytext());
}
case 23: break;
case 2:
{ return m_SF.newSymbol("Left curly bracket", sym.LCURLY);
}
case 24: break;
case 3:
{ return m_SF.newSymbol("Right curly bracket", sym.RCURLY);
}
case 25: break;
case 4:
{ return m_SF.newSymbol("Left square bracket", sym.LSQUARE);
}
case 26: break;
case 5:
{ return m_SF.newSymbol("Right square bracket", sym.RSQUARE);
}
case 27: break;
case 6:
{ return m_SF.newSymbol("Comma", sym.COMMA);
}
case 28: break;
case 7:
{ return m_SF.newSymbol("Colon", sym.COLON);
}
case 29: break;
case 8:
{ return m_SF.newSymbol("Integer", sym.INTEGER, new Integer(yytext()));
}
case 30: break;
case 9:
{ m_String.setLength(0); yybegin(STRING);
}
case 31: break;
case 10:
{ /* ignore white space. */
}
case 32: break;
case 11:
{ m_String.append(yytext());
}
case 33: break;
case 12:
{ yybegin(YYINITIAL); return m_SF.newSymbol("String", sym.STRING, m_String.toString());
}
case 34: break;
case 13:
{ m_String.append('\\');
}
case 35: break;
case 14:
{ return m_SF.newSymbol("Double", sym.DOUBLE, new Double(yytext()));
}
case 36: break;
case 15:
{ m_String.append('\n');
}
case 37: break;
case 16:
{ m_String.append('\t');
}
case 38: break;
case 17:
{ m_String.append('\r');
}
case 39: break;
case 18:
{ m_String.append('\f');
}
case 40: break;
case 19:
{ m_String.append('\"');
}
case 41: break;
case 20:
{ m_String.append('\b');
}
case 42: break;
case 21:
{ return m_SF.newSymbol("Null", sym.NULL);
}
case 43: break;
case 22:
{ return m_SF.newSymbol("Boolean", sym.BOOLEAN, new Boolean(yytext()));
}
case 44: break;
default:
if (zzInput == YYEOF && zzStartRead == zzCurrentPos) {
zzAtEOF = true;
{ return m_SF.newSymbol("EOF", sym.EOF);
}
}
else {
zzScanError(ZZ_NO_MATCH);
}
}
}
}
}
|
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/json/sym.java
|
//----------------------------------------------------
// The following code was generated by CUP v0.11b 20141202 (SVN rev 60)
//----------------------------------------------------
package weka.core.json;
/** CUP generated interface containing symbol constants. */
public interface sym {
/* terminals */
public static final int LSQUARE = 3;
public static final int INTEGER = 10;
public static final int COLON = 7;
public static final int BOOLEAN = 9;
public static final int NULL = 8;
public static final int RSQUARE = 4;
public static final int STRING = 12;
public static final int EOF = 0;
public static final int DOUBLE = 11;
public static final int error = 1;
public static final int COMMA = 2;
public static final int RCURLY = 6;
public static final int LCURLY = 5;
public static final String[] terminalNames = new String[] {
"EOF",
"error",
"COMMA",
"LSQUARE",
"RSQUARE",
"LCURLY",
"RCURLY",
"COLON",
"NULL",
"BOOLEAN",
"INTEGER",
"DOUBLE",
"STRING"
};
}
|
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/logging/ConsoleLogger.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/>.
*/
/*
* ConsoleLogger.java
* Copyright (C) 2008-2012 University of Waikato, Hamilton, New Zealand
*/
package weka.core.logging;
import java.util.Date;
import weka.core.RevisionUtils;
/**
* A simple logger that outputs the logging information in the console.
*
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public class ConsoleLogger
extends Logger {
/**
* Performs the actual logging.
*
* @param level the level of the message
* @param msg the message to log
* @param cls the classname originating the log event
* @param method the method originating the log event
* @param lineno the line number originating the log event
*/
protected void doLog(Level level, String msg, String cls, String method, int lineno) {
System.err.println(
m_DateFormat.format(new Date()) + " " + cls + " " + method + "\n"
+ level + ": " + msg);
}
/**
* 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/logging/FileLogger.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/>.
*/
/*
* FileLogger.java
* Copyright (C) 2008-2012 University of Waikato, Hamilton, New Zealand
*/
package weka.core.logging;
import weka.core.ResourceUtils;
import weka.core.RevisionUtils;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.Date;
import java.util.regex.Matcher;
/**
* A simple file logger, that just logs to a single file. Deletes the file
* when an object gets instantiated.
*
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public class FileLogger
extends ConsoleLogger {
/** the log file. */
protected File m_LogFile;
/** the line feed. */
protected String m_LineFeed;
/**
* Initializes the logger.
*/
protected void initialize() {
super.initialize();
// log file
m_LogFile = getLogFile();
// try to remove file
try {
if ((m_LogFile != null) && m_LogFile.exists())
m_LogFile.delete();
}
catch (Exception e) {
e.printStackTrace();
}
// the line feed
m_LineFeed = System.getProperty("line.separator");
}
/**
* Returns the log file to use.
*
* @return the log file
*/
protected File getLogFile() {
String filename;
File result;
filename = m_Properties.getProperty("LogFile", "%w" + File.separator + "weka.log");
filename = filename.replaceAll("%t", Matcher.quoteReplacement(System.getProperty("java.io.tmpdir")));
filename = filename.replaceAll("%h", Matcher.quoteReplacement(System.getProperty("user.home")));
filename = filename.replaceAll("%c", Matcher.quoteReplacement(System.getProperty("user.dir")));
filename = filename.replaceAll("%w", Matcher.quoteReplacement(ResourceUtils.getWekaHome().toString()));
if (System.getProperty("%") != null && System.getProperty("%").length() > 0) {
filename = filename.replaceAll("%%", Matcher.quoteReplacement(System.getProperty("%")));
}
result = new File(filename);
return result;
}
/**
* Appends the given string to the log file (without new line!).
*
* @param s the string to append
*/
protected void append(String s) {
BufferedWriter writer;
if (m_LogFile == null)
return;
// append output to file
try {
writer = new BufferedWriter(new FileWriter(m_LogFile, true));
writer.write(s);
writer.flush();
writer.close();
}
catch (Exception e) {
// ignored
}
}
/**
* Performs the actual logging.
*
* @param level the level of the message
* @param msg the message to log
* @param cls the classname originating the log event
* @param method the method originating the log event
* @param lineno the line number originating the log event
*/
protected void doLog(Level level, String msg, String cls, String method, int lineno) {
// output to console
super.doLog(level, msg, cls, method, lineno);
// append output to file
append(
m_DateFormat.format(new Date()) + " " + cls + " " + method + m_LineFeed
+ level + ": " + msg + m_LineFeed);
}
/**
* 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/logging/Logger.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/>.
*/
/*
* Logger.java
* Copyright (C) 2008-2012 University of Waikato, Hamilton, New Zealand
*/
package weka.core.logging;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Properties;
import weka.core.RevisionHandler;
import weka.core.Utils;
/**
* Abstract superclass for all loggers.
*
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public abstract class Logger implements RevisionHandler {
/** the properties file. */
public final static String PROPERTIES_FILE =
"weka/core/logging/Logging.props";
/** the singleton instance of the logger. */
protected static Logger m_Singleton;
/** the properties file. */
protected static Properties m_Properties;
/** for formatting the dates. */
protected static SimpleDateFormat m_DateFormat;
static {
try {
m_Properties = Utils.readProperties(PROPERTIES_FILE);
} catch (Exception e) {
System.err.println("Error reading the logging properties '"
+ PROPERTIES_FILE + "': " + e);
m_Properties = new Properties();
}
}
/** the minimum level of log events to have in order to end up in the log. */
protected Level m_MinLevel;
/**
* Initializes the logger.
*/
public Logger() {
super();
initialize();
}
/**
* Returns the location the logging happened.
*
* @return the classname (= [0]), the method (= [1]) and the line number (=
* [2]) that generated the logging event
*/
protected static String[] getLocation() {
String[] result;
Throwable t;
StackTraceElement[] trace;
int i;
result = new String[3];
t = new Throwable();
t.fillInStackTrace();
trace = t.getStackTrace();
for (i = 0; i < trace.length; i++) {
// skip the Logger class
if (trace[i].getClassName().equals(Logger.class.getName()))
continue;
if (trace[i].getClassName().equals(weka.gui.LogPanel.class.getName()))
continue;
// fill in result
result[0] = trace[i].getClassName();
result[1] = trace[i].getMethodName();
result[2] = "" + trace[i].getLineNumber();
break;
}
return result;
}
/**
* Returns the singleton instance of the logger.
*
* @return the logger instance
*/
public static Logger getSingleton() {
String classname;
if (m_Singleton == null) {
// logger
classname =
m_Properties.getProperty("weka.core.logging.Logger",
ConsoleLogger.class.getName());
try {
m_Singleton = (Logger) Class.forName(classname).newInstance();
} catch (Exception e) {
e.printStackTrace();
}
// date format
m_DateFormat =
new SimpleDateFormat(m_Properties.getProperty(
"weka.core.logging.DateFormat", "yyyy-MM-dd HH:mm:ss"));
}
return m_Singleton;
}
/**
* Logs the given message under the given level.
*
* @param level the level of the message
* @param msg the message to log
*/
public static void log(Level level, String msg) {
Logger logger;
boolean log;
String[] location;
logger = getSingleton();
if (logger == null)
return;
synchronized (logger) {
log = false;
if (logger.getMinLevel() == Level.ALL)
log = true;
else if (level.getOrder() >= logger.getMinLevel().getOrder())
log = true;
if (!log)
return;
location = getLocation();
logger.doLog(level, msg, location[0], location[1],
Integer.parseInt(location[2]));
}
}
/**
* Logs the given message under the given level.
*
* @param level the level of the message
* @param t the throwable to log
*/
public static void log(Level level, Throwable t) {
StringWriter swriter;
PrintWriter pwriter;
swriter = new StringWriter();
pwriter = new PrintWriter(swriter);
t.printStackTrace(pwriter);
pwriter.close();
log(level, swriter.toString());
}
/**
* Initializes the logger.
*/
protected void initialize() {
m_MinLevel =
Level.valueOf(m_Properties.getProperty("weka.core.logging.MinLevel",
"INFO"));
}
/**
* Returns the minimum level log messages must have in order to appear in the
* log.
*
* @return the level
*/
public Level getMinLevel() {
return m_MinLevel;
}
/**
* Performs the actual logging. Actual logger implementations must override
* this method.
*
* @param level the level of the message
* @param msg the message to log
* @param cls the classname originating the log event
* @param method the method originating the log event
* @param lineno the line number originating the log event
*/
protected abstract void doLog(Level level, String msg, String cls,
String method, int lineno);
/**
* The logging level.
*
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public enum Level {
/** logs all messages. */
ALL(0),
/** FINEST level. */
FINEST(1),
/** FINEST level. */
FINER(2),
/** FINER level. */
FINE(3),
/** FINE level. */
INFO(4),
/** WARNING level. */
WARNING(5),
/** SEVERE level. */
SEVERE(6),
/** turns logging off. */
OFF(10);
/** the order of the level. */
private int m_Order;
/**
* Initializes the level.
*
* @param order the order of the level
*/
private Level(int order) {
m_Order = order;
}
/**
* Returns the order of this level.
*
* @return the order
*/
public int getOrder() {
return m_Order;
}
}
}
|
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/logging/OutputLogger.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/>.
*/
/*
* OutputLogger.java
* Copyright (C) 2008-2012 University of Waikato, Hamilton, New Zealand
*/
package weka.core.logging;
import java.io.PrintStream;
import java.util.Date;
import weka.core.RevisionUtils;
import weka.core.Tee;
/**
* A logger that logs all output on stdout and stderr to a file.
*
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public class OutputLogger
extends FileLogger {
/**
* A print stream class to capture all data from stdout and stderr.
*
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public static class OutputPrintStream
extends PrintStream {
/** the owning logger. */
protected OutputLogger m_Owner;
/** the line feed. */
protected String m_LineFeed;
/**
* Default constructor.
*
* @param owner the owning logger
* @param stream the stream
* @throws Exception if something goes wrong
*/
public OutputPrintStream(OutputLogger owner, PrintStream stream) throws Exception {
super(stream);
m_Owner = owner;
m_LineFeed = System.getProperty("line.separator");
}
/**
* ignored.
*/
public void flush() {
}
/**
* prints the given int to the streams.
*
* @param x the object to print
*/
public void print(int x) {
m_Owner.append("" + x);
}
/**
* prints the given boolean to the streams.
*
* @param x the object to print
*/
public void print(boolean x) {
m_Owner.append("" + x);
}
/**
* prints the given string to the streams.
*
* @param x the object to print
*/
public void print(String x) {
m_Owner.append("" + x);
}
/**
* prints the given object to the streams.
*
* @param x the object to print
*/
public void print(Object x) {
m_Owner.append("" + x);
}
/**
* prints a new line to the streams.
*/
public void println() {
m_Owner.append(m_LineFeed);
}
/**
* prints the given int to the streams.
*
* @param x the object to print
*/
public void println(int x) {
m_Owner.append(x + m_LineFeed);
}
/**
* prints the given boolean to the streams.
*
* @param x the object to print
*/
public void println(boolean x) {
m_Owner.append(x + m_LineFeed);
}
/**
* prints the given string to the streams.
*
* @param x the object to print
*/
public void println(String x) {
m_Owner.append(x + m_LineFeed);
}
/**
* 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) {
m_Owner.append(x + m_LineFeed);
}
}
/** the stream object used for logging stdout. */
protected OutputPrintStream m_StreamOut;
/** the stream object used for logging stderr. */
protected OutputPrintStream m_StreamErr;
/** the Tee instance to redirect stdout. */
protected Tee m_StdOut;
/** the Tee instance to redirect stderr. */
protected Tee m_StdErr;
/**
* Initializes the logger.
*/
protected void initialize() {
super.initialize();
try {
m_StdOut = new Tee(System.out);
System.setOut(m_StdOut);
m_StreamOut = new OutputPrintStream(this, m_StdOut.getDefault());
m_StdOut.add(m_StreamOut);
m_StdErr = new Tee(System.err);
System.setErr(m_StdErr);
m_StreamErr = new OutputPrintStream(this, m_StdErr.getDefault());
m_StdErr.add(m_StreamErr);
}
catch (Exception e) {
// ignored
}
}
/**
* Performs the actual logging.
*
* @param level the level of the message
* @param msg the message to log
* @param cls the classname originating the log event
* @param method the method originating the log event
* @param lineno the line number originating the log event
*/
protected void doLog(Level level, String msg, String cls, String method, int lineno) {
// append output to file
append(
m_DateFormat.format(new Date()) + " " + cls + " " + method + m_LineFeed
+ level + ": " + msg + m_LineFeed);
}
/**
* 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/matrix/CholeskyDecomposition.java
|
/*
* This software is a cooperative product of The MathWorks and the National
* Institute of Standards and Technology (NIST) which has been released to the
* public domain. Neither The MathWorks nor NIST assumes any responsibility
* whatsoever for its use by other parties, and makes no guarantees, expressed
* or implied, about its quality, reliability, or any other characteristic.
*/
/*
* CholeskyDecomposition.java
* Copyright (C) 1999 The Mathworks and NIST
*
*/
package weka.core.matrix;
import weka.core.RevisionHandler;
import weka.core.RevisionUtils;
import java.io.Serializable;
/**
* Cholesky Decomposition.
* <P>
* For a symmetric, positive definite matrix A, the Cholesky decomposition is
* an lower triangular matrix L so that A = L*L'.
* <P>
* If the matrix is not symmetric or positive definite, the constructor
* returns a partial decomposition and sets an internal flag that may
* be queried by the isSPD() method.
* <p/>
* Adapted from the <a href="http://math.nist.gov/javanumerics/jama/" target="_blank">JAMA</a> package.
*
* @author The Mathworks and NIST
* @author Fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public class CholeskyDecomposition
implements Serializable, RevisionHandler {
/** for serialization */
private static final long serialVersionUID = -8739775942782694701L;
/**
* Array for internal storage of decomposition.
* @serial internal array storage.
*/
private double[][] L;
/**
* Row and column dimension (square matrix).
* @serial matrix dimension.
*/
private int n;
/**
* Symmetric and positive definite flag.
* @serial is symmetric and positive definite flag.
*/
private boolean isspd;
/**
* Cholesky algorithm for symmetric and positive definite matrix.
*
* @param Arg Square, symmetric matrix.
*/
public CholeskyDecomposition(Matrix Arg) {
// Initialize.
double[][] A = Arg.getArray();
n = Arg.getRowDimension();
L = new double[n][n];
isspd = (Arg.getColumnDimension() == n);
// Main loop.
for (int j = 0; j < n; j++) {
double[] Lrowj = L[j];
double d = 0.0;
for (int k = 0; k < j; k++) {
double[] Lrowk = L[k];
double s = 0.0;
for (int i = 0; i < k; i++) {
s += Lrowk[i]*Lrowj[i];
}
Lrowj[k] = s = (A[j][k] - s)/L[k][k];
d = d + s*s;
isspd = isspd & (A[k][j] == A[j][k]);
}
d = A[j][j] - d;
isspd = isspd & (d > 0.0);
L[j][j] = Math.sqrt(Math.max(d,0.0));
for (int k = j+1; k < n; k++) {
L[j][k] = 0.0;
}
}
}
/**
* Is the matrix symmetric and positive definite?
* @return true if A is symmetric and positive definite.
*/
public boolean isSPD() {
return isspd;
}
/**
* Return triangular factor.
* @return L
*/
public Matrix getL() {
return new Matrix(L,n,n);
}
/**
* Solve A*X = B
* @param B A Matrix with as many rows as A and any number of columns.
* @return X so that L*L'*X = B
* @exception IllegalArgumentException Matrix row dimensions must agree.
* @exception RuntimeException Matrix is not symmetric positive definite.
*/
public Matrix solve(Matrix B) {
if (B.getRowDimension() != n) {
throw new IllegalArgumentException("Matrix row dimensions must agree.");
}
if (!isspd) {
throw new RuntimeException("Matrix is not symmetric positive definite.");
}
// Copy right hand side.
double[][] X = B.getArrayCopy();
int nx = B.getColumnDimension();
// Solve L*Y = B;
for (int k = 0; k < n; k++) {
for (int j = 0; j < nx; j++) {
for (int i = 0; i < k ; i++) {
X[k][j] -= X[i][j]*L[k][i];
}
X[k][j] /= L[k][k];
}
}
// Solve L'*X = Y;
for (int k = n-1; k >= 0; k--) {
for (int j = 0; j < nx; j++) {
for (int i = k+1; i < n ; i++) {
X[k][j] -= X[i][j]*L[i][k];
}
X[k][j] /= L[k][k];
}
}
return new Matrix(X,n,nx);
}
/**
* 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/matrix/DoubleVector.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/>.
*/
/*
* DoubleVector.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.matrix;
import java.lang.reflect.Method;
import java.util.Arrays;
import weka.core.RevisionHandler;
import weka.core.RevisionUtils;
/**
* A vector specialized on doubles.
*
* @author Yong Wang
* @version $Revision$
*/
public class DoubleVector implements Cloneable, RevisionHandler {
double[] V; // array for internal storage of elements.
private int sizeOfVector; // size of the vector
/*
* ------------------------ Constructors ------------------------
*/
/**
* Constructs a null vector.
*/
public DoubleVector() {
this(0);
}
/**
* Constructs an n-vector of zeros.
*
* @param n length.
*/
public DoubleVector(int n) {
V = new double[n];
setSize(n);
}
/**
* Constructs a constant n-vector.
*
* @param n length.
* @param s the scalar value used to fill the vector
*/
public DoubleVector(int n, double s) {
this(n);
set(s);
}
/**
* Constructs a vector directly from a double array
*
* @param v the array
*/
public DoubleVector(double v[]) {
if (v == null) {
V = new double[0];
setSize(0);
} else {
V = v;
setSize(v.length);
}
}
/*
* ------------------------ Public Methods ------------------------
*/
/**
* Set a single element.
*
* @param i Index.
* @param s a[i].
*/
public void set(int i, double s) {
V[i] = s;
}
/**
* Set all elements to a value
*
* @param s the value
*/
public void set(double s) {
set(0, size() - 1, s);
}
/**
* Set some elements to a value
*
* @param i0 the index of the first element
* @param i1 the index of the second element
* @param s the value
*/
public void set(int i0, int i1, double s) {
for (int i = i0; i <= i1; i++) {
V[i] = s;
}
}
/**
* Set some elements using a 2-D array
*
* @param i0 the index of the first element
* @param i1 the index of the second element
* @param j0 the index of the starting element in the 2-D array
* @param v the values
*/
public void set(int i0, int i1, double[] v, int j0) {
for (int i = i0; i <= i1; i++) {
V[i] = v[j0 + i - i0];
}
}
/**
* Set the elements using a DoubleVector
*
* @param v the DoubleVector
*/
public void set(DoubleVector v) {
set(0, v.size() - 1, v, 0);
}
/**
* Set some elements using a DoubleVector.
*
* @param i0 the index of the first element
* @param i1 the index of the second element
* @param v the DoubleVector
* @param j0 the index of the starting element in the DoubleVector
*/
public void set(int i0, int i1, DoubleVector v, int j0) {
for (int i = i0; i <= i1; i++) {
V[i] = v.V[j0 + i - i0];
}
}
/**
* Access the internal one-dimensional array.
*
* @return Pointer to the one-dimensional array of vector elements.
*/
public double[] getArray() {
return V;
}
void setArray(double[] a) {
V = a;
}
/**
* Returns a copy of the DoubleVector usng a double array.
*
* @return the one-dimensional array.
*/
public double[] getArrayCopy() {
double v[] = new double[size()];
for (int i = 0; i < size(); i++) {
v[i] = V[i];
}
return v;
}
/** Sorts the array in place */
public void sort() {
Arrays.sort(V, 0, size());
}
/** Sorts the array in place with index returned */
public IntVector sortWithIndex() {
IntVector index = IntVector.seq(0, size() - 1);
sortWithIndex(0, size() - 1, index);
return index;
}
/**
* Sorts the array in place with index changed
*
* @param xi first index
* @param xj last index
* @param index array that stores all indices
*/
public void sortWithIndex(int xi, int xj, IntVector index) {
if (xi < xj) {
double x;
int xm = (xi + xj) / 2; // median index
x = Math.min(V[xi], // median of three
Math.max(V[xm], V[xj]));
int i = xi;
int j = xj;
while (i < j) {
while (V[i] < x && i < xj) {
i++;
}
while (V[j] > x && j > xi) {
j--;
}
if (i <= j) {
swap(i, j);
index.swap(i, j);
i++;
j--;
}
}
sortWithIndex(xi, j, index);
sortWithIndex(i, xj, index);
}
}
/**
* Gets the size of the vector.
*
* @return the size
*/
public int size() {
return sizeOfVector;
}
/**
* Sets the size of the vector
*
* @param m the size
*/
public void setSize(int m) {
if (m > capacity()) {
throw new IllegalArgumentException("insufficient capacity");
}
sizeOfVector = m;
}
/**
* Gets the capacity of the vector.
*
* @return the capacity.
*/
public int capacity() {
if (V == null) {
return 0;
}
return V.length;
}
/**
* Sets the capacity of the vector
*
* @param n the capacity.
*/
public void setCapacity(int n) {
if (n == capacity()) {
return;
}
double[] oldV = V;
int m = Math.min(n, size());
V = new double[n];
setSize(m);
set(0, m - 1, oldV, 0);
}
/**
* Gets a single element.
*
* @param i Index.
* @return the value of the i-th element
*/
public double get(int i) {
return V[i];
}
/**
* Adds a value to an element
*
* @param i the index of the element
* @param s the value
*/
public void setPlus(int i, double s) {
V[i] += s;
}
/**
* Multiplies a value to an element
*
* @param i the index of the element
* @param s the value
*/
public void setTimes(int i, double s) {
V[i] *= s;
}
/**
* Adds an element into the vector
*
* @param x the value of the new element
*/
public void addElement(double x) {
if (capacity() == 0) {
setCapacity(10);
}
if (size() == capacity()) {
setCapacity(2 * capacity());
}
V[size()] = x;
setSize(size() + 1);
}
/**
* Returns the squared vector
*/
public DoubleVector square() {
DoubleVector v = new DoubleVector(size());
for (int i = 0; i < size(); i++) {
v.V[i] = V[i] * V[i];
}
return v;
}
/**
* Returns the square-root of all the elements in the vector
*/
public DoubleVector sqrt() {
DoubleVector v = new DoubleVector(size());
for (int i = 0; i < size(); i++) {
v.V[i] = Math.sqrt(V[i]);
}
return v;
}
/**
* Makes a deep copy of the vector
*/
public DoubleVector copy() {
return (DoubleVector) clone();
}
/**
* Clones the DoubleVector object.
*/
@Override
public Object clone() {
int n = size();
DoubleVector u = new DoubleVector(n);
for (int i = 0; i < n; i++) {
u.V[i] = V[i];
}
return u;
}
/**
* Returns the inner product of two DoubleVectors
*
* @param v the second DoubleVector
* @return the product
*/
public double innerProduct(DoubleVector v) {
if (size() != v.size()) {
throw new IllegalArgumentException("sizes unmatch");
}
double p = 0;
for (int i = 0; i < size(); i++) {
p += V[i] * v.V[i];
}
return p;
}
/**
* Returns the signs of all elements in terms of -1, 0 and +1.
*/
public DoubleVector sign() {
DoubleVector s = new DoubleVector(size());
for (int i = 0; i < size(); i++) {
if (V[i] > 0) {
s.V[i] = 1;
} else if (V[i] < 0) {
s.V[i] = -1;
} else {
s.V[i] = 0;
}
}
return s;
}
/**
* Returns the sum of all elements in the vector.
*/
public double sum() {
double s = 0;
for (int i = 0; i < size(); i++) {
s += V[i];
}
return s;
}
/**
* Returns the squared sum of all elements in the vector.
*/
public double sum2() {
double s2 = 0;
for (int i = 0; i < size(); i++) {
s2 += V[i] * V[i];
}
return s2;
}
/**
* Returns the L1-norm of the vector
*/
public double norm1() {
double s = 0;
for (int i = 0; i < size(); i++) {
s += Math.abs(V[i]);
}
return s;
}
/**
* Returns the L2-norm of the vector
*/
public double norm2() {
return Math.sqrt(sum2());
}
/**
* Returns ||u-v||^2
*
* @param v the second vector
*/
public double sum2(DoubleVector v) {
return minus(v).sum2();
}
/**
* Returns a subvector.
*
* @param i0 the index of the first element
* @param i1 the index of the last element
* @return v[i0:i1]
*/
public DoubleVector subvector(int i0, int i1) {
DoubleVector v = new DoubleVector(i1 - i0 + 1);
v.set(0, i1 - i0, this, i0);
return v;
}
/**
* Returns a subvector.
*
* @param index stores the indices of the needed elements
* @return v[index]
*/
public DoubleVector subvector(IntVector index) {
DoubleVector v = new DoubleVector(index.size());
for (int i = 0; i < index.size(); i++) {
v.V[i] = V[index.V[i]];
}
return v;
}
/**
* Returns a vector from the pivoting indices. Elements not indexed are set to
* zero.
*
* @param index stores the pivoting indices
* @param length the total number of the potential elements
* @return the subvector
*/
public DoubleVector unpivoting(IntVector index, int length) {
if (index.size() > length) {
throw new IllegalArgumentException("index.size() > length ");
}
DoubleVector u = new DoubleVector(length);
for (int i = 0; i < index.size(); i++) {
u.V[index.V[i]] = V[i];
}
return u;
}
/**
* Adds a value to all the elements
*
* @param x the value
*/
public DoubleVector plus(double x) {
return copy().plusEquals(x);
}
/**
* Adds a value to all the elements in place
*
* @param x the value
*/
public DoubleVector plusEquals(double x) {
for (int i = 0; i < size(); i++) {
V[i] += x;
}
return this;
}
/**
* Adds another vector element by element
*
* @param v the second vector
*/
public DoubleVector plus(DoubleVector v) {
return copy().plusEquals(v);
}
/**
* Adds another vector in place element by element
*
* @param v the second vector
*/
public DoubleVector plusEquals(DoubleVector v) {
for (int i = 0; i < size(); i++) {
V[i] += v.V[i];
}
return this;
}
/**
* Subtracts a value
*
* @param x the value
*/
public DoubleVector minus(double x) {
return plus(-x);
}
/**
* Subtracts a value in place
*
* @param x the value
*/
public DoubleVector minusEquals(double x) {
plusEquals(-x);
return this;
}
/**
* Subtracts another DoubleVector element by element
*
* @param v the second DoubleVector
*/
public DoubleVector minus(DoubleVector v) {
return copy().minusEquals(v);
}
/**
* Subtracts another DoubleVector element by element in place
*
* @param v the second DoubleVector
*/
public DoubleVector minusEquals(DoubleVector v) {
for (int i = 0; i < size(); i++) {
V[i] -= v.V[i];
}
return this;
}
/**
* Multiplies a scalar
*
* @param s scalar
* @return s * v
*/
public DoubleVector times(double s) {
return copy().timesEquals(s);
}
/**
* Multiply a vector by a scalar in place, u = s * u
*
* @param s scalar
* @return replace u by s * u
*/
public DoubleVector timesEquals(double s) {
for (int i = 0; i < size(); i++) {
V[i] *= s;
}
return this;
}
/**
* Multiplies another DoubleVector element by element
*
* @param v the second DoubleVector
*/
public DoubleVector times(DoubleVector v) {
return copy().timesEquals(v);
}
/**
* Multiplies another DoubleVector element by element in place
*
* @param v the second DoubleVector
*/
public DoubleVector timesEquals(DoubleVector v) {
for (int i = 0; i < size(); i++) {
V[i] *= v.V[i];
}
return this;
}
/**
* Divided by another DoubleVector element by element
*
* @param v the second DoubleVector
*/
public DoubleVector dividedBy(DoubleVector v) {
return copy().dividedByEquals(v);
}
/**
* Divided by another DoubleVector element by element in place
*
* @param v the second DoubleVector
*/
public DoubleVector dividedByEquals(DoubleVector v) {
for (int i = 0; i < size(); i++) {
V[i] /= v.V[i];
}
return this;
}
/**
* Checks if it is an empty vector
*/
public boolean isEmpty() {
if (size() == 0) {
return true;
}
return false;
}
/**
* Returns a vector that stores the cumulated values of the original vector
*/
public DoubleVector cumulate() {
return copy().cumulateInPlace();
}
/**
* Cumulates the original vector in place
*/
public DoubleVector cumulateInPlace() {
for (int i = 1; i < size(); i++) {
V[i] += V[i - 1];
}
return this;
}
/**
* Returns the index of the maximum.
* <p>
* If multiple maximums exist, the index of the first is returned.
*/
public int indexOfMax() {
int index = 0;
double ma = V[0];
for (int i = 1; i < size(); i++) {
if (ma < V[i]) {
ma = V[i];
index = i;
}
}
return index;
}
/**
* Returns true if vector not sorted
*/
public boolean unsorted() {
if (size() < 2) {
return false;
}
for (int i = 1; i < size(); i++) {
if (V[i - 1] > V[i]) {
return true;
}
}
return false;
}
/**
* Combine two vectors together
*
* @param v the second vector
*/
public DoubleVector cat(DoubleVector v) {
DoubleVector w = new DoubleVector(size() + v.size());
w.set(0, size() - 1, this, 0);
w.set(size(), size() + v.size() - 1, v, 0);
return w;
}
/**
* Swaps the values stored at i and j
*
* @param i the index i
* @param j the index j
*/
public void swap(int i, int j) {
if (i == j) {
return;
}
double t = V[i];
V[i] = V[j];
V[j] = t;
}
/**
* Returns the maximum value of all elements
*/
public double max() {
if (size() < 1) {
throw new IllegalArgumentException("zero size");
}
double ma = V[0];
if (size() < 2) {
return ma;
}
for (int i = 1; i < size(); i++) {
if (V[i] > ma) {
ma = V[i];
}
}
return ma;
}
/**
* Applies a method to the vector
*
* @param className the class name
* @param method the method
*/
public DoubleVector map(String className, String method) {
try {
Class<?> c = Class.forName(className);
Class<?>[] cs = new Class[1];
cs[0] = Double.TYPE;
Method m = c.getMethod(method, cs);
DoubleVector w = new DoubleVector(size());
Object[] obj = new Object[1];
for (int i = 0; i < size(); i++) {
obj[0] = new Double(V[i]);
w.set(i, Double.parseDouble(m.invoke(null, obj).toString()));
}
return w;
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
return null;
}
/**
* Returns the reverse vector
*/
public DoubleVector rev() {
int n = size();
DoubleVector w = new DoubleVector(n);
for (int i = 0; i < n; i++) {
w.V[i] = V[n - i - 1];
}
return w;
}
/**
* Returns a random vector of uniform distribution
*
* @param n the size of the vector
*/
public static DoubleVector random(int n) {
DoubleVector v = new DoubleVector(n);
for (int i = 0; i < n; i++) {
v.V[i] = Math.random();
}
return v;
}
/**
* Convert the DoubleVecor to a string
*/
@Override
public String toString() {
return toString(5, false);
}
/**
* Convert the DoubleVecor to a string
*
* @param digits the number of digits after decimal point
* @param trailing true if trailing zeros are to be shown
*/
public String toString(int digits, boolean trailing) {
if (isEmpty()) {
return "null vector";
}
StringBuffer text = new StringBuffer();
FlexibleDecimalFormat nf = new FlexibleDecimalFormat(digits, trailing);
nf.grouping(true);
for (int i = 0; i < size(); i++) {
nf.update(V[i]);
}
int count = 0;
int width = 80;
String number;
for (int i = 0; i < size(); i++) {
number = nf.format(V[i]);
count += 1 + number.length();
if (count > width - 1) {
text.append('\n');
count = 1 + number.length();
}
text.append(" " + number);
}
return text.toString();
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
public static void main(String args[]) {
DoubleVector v = random(10);
DoubleVector a = random(10);
DoubleVector w = a;
System.out.println(random(10).plus(v).plus(w));
}
}
|
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/matrix/EigenvalueDecomposition.java
|
/*
* This software is a cooperative product of The MathWorks and the National
* Institute of Standards and Technology (NIST) which has been released to the
* public domain. Neither The MathWorks nor NIST assumes any responsibility
* whatsoever for its use by other parties, and makes no guarantees, expressed
* or implied, about its quality, reliability, or any other characteristic.
*/
/*
* EigenvalueDecomposition.java
* Copyright (C) 1999 The Mathworks and NIST
*
*/
package weka.core.matrix;
import weka.core.RevisionHandler;
import weka.core.RevisionUtils;
import java.io.Serializable;
/**
* Eigenvalues and eigenvectors of a real matrix.
* <P>
* If A is symmetric, then A = V*D*V' where the eigenvalue matrix D is diagonal
* and the eigenvector matrix V is orthogonal. I.e. A =
* V.times(D.times(V.transpose())) and V.times(V.transpose()) equals the
* identity matrix.
* <P>
* If A is not symmetric, then the eigenvalue matrix D is block diagonal with
* the real eigenvalues in 1-by-1 blocks and any complex eigenvalues, lambda +
* i*mu, in 2-by-2 blocks, [lambda, mu; -mu, lambda]. The columns of V
* represent the eigenvectors in the sense that A*V = V*D, i.e. A.times(V)
* equals V.times(D). The matrix V may be badly conditioned, or even singular,
* so the validity of the equation A = V*D*inverse(V) depends upon V.cond().
* <p/>
* Adapted from the <a href="http://math.nist.gov/javanumerics/jama/" target="_blank">JAMA</a> package.
*
* @author The Mathworks and NIST
* @author Fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public class EigenvalueDecomposition
implements Serializable, RevisionHandler {
/** for serialization */
private static final long serialVersionUID = 4011654467211422319L;
/**
* Row and column dimension (square matrix).
* @serial matrix dimension.
*/
private int n;
/**
* Symmetry flag.
* @serial internal symmetry flag.
*/
private boolean issymmetric;
/**
* Arrays for internal storage of eigenvalues.
* @serial internal storage of eigenvalues.
*/
private double[] d, e;
/**
* Array for internal storage of eigenvectors.
* @serial internal storage of eigenvectors.
*/
private double[][] V;
/**
* Array for internal storage of nonsymmetric Hessenberg form.
* @serial internal storage of nonsymmetric Hessenberg form.
*/
private double[][] H;
/**
* Working storage for nonsymmetric algorithm.
* @serial working storage for nonsymmetric algorithm.
*/
private double[] ort;
/**
* helper variables for the comples scalar division
* @see #cdiv(double,double,double,double)
*/
private transient double cdivr, cdivi;
/**
* Symmetric Householder reduction to tridiagonal form.
* <p/>
* This is derived from the Algol procedures tred2 by Bowdler, Martin,
* Reinsch, and Wilkinson, Handbook for Auto. Comp., Vol.ii-Linear Algebra,
* and the corresponding Fortran subroutine in EISPACK.
*/
private void tred2() {
for (int j = 0; j < n; j++) {
d[j] = V[n-1][j];
}
// Householder reduction to tridiagonal form.
for (int i = n-1; i > 0; i--) {
// Scale to avoid under/overflow.
double scale = 0.0;
double h = 0.0;
for (int k = 0; k < i; k++) {
scale = scale + Math.abs(d[k]);
}
if (scale == 0.0) {
e[i] = d[i-1];
for (int j = 0; j < i; j++) {
d[j] = V[i-1][j];
V[i][j] = 0.0;
V[j][i] = 0.0;
}
} else {
// Generate Householder vector.
for (int k = 0; k < i; k++) {
d[k] /= scale;
h += d[k] * d[k];
}
double f = d[i-1];
double g = Math.sqrt(h);
if (f > 0) {
g = -g;
}
e[i] = scale * g;
h = h - f * g;
d[i-1] = f - g;
for (int j = 0; j < i; j++) {
e[j] = 0.0;
}
// Apply similarity transformation to remaining columns.
for (int j = 0; j < i; j++) {
f = d[j];
V[j][i] = f;
g = e[j] + V[j][j] * f;
for (int k = j+1; k <= i-1; k++) {
g += V[k][j] * d[k];
e[k] += V[k][j] * f;
}
e[j] = g;
}
f = 0.0;
for (int j = 0; j < i; j++) {
e[j] /= h;
f += e[j] * d[j];
}
double hh = f / (h + h);
for (int j = 0; j < i; j++) {
e[j] -= hh * d[j];
}
for (int j = 0; j < i; j++) {
f = d[j];
g = e[j];
for (int k = j; k <= i-1; k++) {
V[k][j] -= (f * e[k] + g * d[k]);
}
d[j] = V[i-1][j];
V[i][j] = 0.0;
}
}
d[i] = h;
}
// Accumulate transformations.
for (int i = 0; i < n-1; i++) {
V[n-1][i] = V[i][i];
V[i][i] = 1.0;
double h = d[i+1];
if (h != 0.0) {
for (int k = 0; k <= i; k++) {
d[k] = V[k][i+1] / h;
}
for (int j = 0; j <= i; j++) {
double g = 0.0;
for (int k = 0; k <= i; k++) {
g += V[k][i+1] * V[k][j];
}
for (int k = 0; k <= i; k++) {
V[k][j] -= g * d[k];
}
}
}
for (int k = 0; k <= i; k++) {
V[k][i+1] = 0.0;
}
}
for (int j = 0; j < n; j++) {
d[j] = V[n-1][j];
V[n-1][j] = 0.0;
}
V[n-1][n-1] = 1.0;
e[0] = 0.0;
}
/**
* Symmetric tridiagonal QL algorithm.
* <p/>
* This is derived from the Algol procedures tql2, by Bowdler, Martin,
* Reinsch, and Wilkinson, Handbook for Auto. Comp., Vol.ii-Linear Algebra,
* and the corresponding Fortran subroutine in EISPACK.
*/
private void tql2() {
for (int i = 1; i < n; i++) {
e[i-1] = e[i];
}
e[n-1] = 0.0;
double f = 0.0;
double tst1 = 0.0;
double eps = Math.pow(2.0,-52.0);
for (int l = 0; l < n; l++) {
// Find small subdiagonal element
tst1 = Math.max(tst1,Math.abs(d[l]) + Math.abs(e[l]));
int m = l;
while (m < n) {
if (Math.abs(e[m]) <= eps*tst1) {
break;
}
m++;
}
// If m == l, d[l] is an eigenvalue,
// otherwise, iterate.
if (m > l) {
int iter = 0;
do {
iter = iter + 1; // (Could check iteration count here.)
// Compute implicit shift
double g = d[l];
double p = (d[l+1] - g) / (2.0 * e[l]);
double r = Maths.hypot(p,1.0);
if (p < 0) {
r = -r;
}
d[l] = e[l] / (p + r);
d[l+1] = e[l] * (p + r);
double dl1 = d[l+1];
double h = g - d[l];
for (int i = l+2; i < n; i++) {
d[i] -= h;
}
f = f + h;
// Implicit QL transformation.
p = d[m];
double c = 1.0;
double c2 = c;
double c3 = c;
double el1 = e[l+1];
double s = 0.0;
double s2 = 0.0;
for (int i = m-1; i >= l; i--) {
c3 = c2;
c2 = c;
s2 = s;
g = c * e[i];
h = c * p;
r = Maths.hypot(p,e[i]);
e[i+1] = s * r;
s = e[i] / r;
c = p / r;
p = c * d[i] - s * g;
d[i+1] = h + s * (c * g + s * d[i]);
// Accumulate transformation.
for (int k = 0; k < n; k++) {
h = V[k][i+1];
V[k][i+1] = s * V[k][i] + c * h;
V[k][i] = c * V[k][i] - s * h;
}
}
p = -s * s2 * c3 * el1 * e[l] / dl1;
e[l] = s * p;
d[l] = c * p;
// Check for convergence.
} while (Math.abs(e[l]) > eps*tst1);
}
d[l] = d[l] + f;
e[l] = 0.0;
}
// Sort eigenvalues and corresponding vectors.
for (int i = 0; i < n-1; i++) {
int k = i;
double p = d[i];
for (int j = i+1; j < n; j++) {
if (d[j] < p) {
k = j;
p = d[j];
}
}
if (k != i) {
d[k] = d[i];
d[i] = p;
for (int j = 0; j < n; j++) {
p = V[j][i];
V[j][i] = V[j][k];
V[j][k] = p;
}
}
}
}
/**
* Nonsymmetric reduction to Hessenberg form.
* <p/>
* This is derived from the Algol procedures orthes and ortran, by Martin
* and Wilkinson, Handbook for Auto. Comp., Vol.ii-Linear Algebra, and the
* corresponding Fortran subroutines in EISPACK.
*/
private void orthes() {
int low = 0;
int high = n-1;
for (int m = low+1; m <= high-1; m++) {
// Scale column.
double scale = 0.0;
for (int i = m; i <= high; i++) {
scale = scale + Math.abs(H[i][m-1]);
}
if (scale != 0.0) {
// Compute Householder transformation.
double h = 0.0;
for (int i = high; i >= m; i--) {
ort[i] = H[i][m-1]/scale;
h += ort[i] * ort[i];
}
double g = Math.sqrt(h);
if (ort[m] > 0) {
g = -g;
}
h = h - ort[m] * g;
ort[m] = ort[m] - g;
// Apply Householder similarity transformation
// H = (I-u*u'/h)*H*(I-u*u')/h)
for (int j = m; j < n; j++) {
double f = 0.0;
for (int i = high; i >= m; i--) {
f += ort[i]*H[i][j];
}
f = f/h;
for (int i = m; i <= high; i++) {
H[i][j] -= f*ort[i];
}
}
for (int i = 0; i <= high; i++) {
double f = 0.0;
for (int j = high; j >= m; j--) {
f += ort[j]*H[i][j];
}
f = f/h;
for (int j = m; j <= high; j++) {
H[i][j] -= f*ort[j];
}
}
ort[m] = scale*ort[m];
H[m][m-1] = scale*g;
}
}
// Accumulate transformations (Algol's ortran).
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
V[i][j] = (i == j ? 1.0 : 0.0);
}
}
for (int m = high-1; m >= low+1; m--) {
if (H[m][m-1] != 0.0) {
for (int i = m+1; i <= high; i++) {
ort[i] = H[i][m-1];
}
for (int j = m; j <= high; j++) {
double g = 0.0;
for (int i = m; i <= high; i++) {
g += ort[i] * V[i][j];
}
// Double division avoids possible underflow
g = (g / ort[m]) / H[m][m-1];
for (int i = m; i <= high; i++) {
V[i][j] += g * ort[i];
}
}
}
}
}
/**
* Complex scalar division.
*/
private void cdiv(double xr, double xi, double yr, double yi) {
double r,d;
if (Math.abs(yr) > Math.abs(yi)) {
r = yi/yr;
d = yr + r*yi;
cdivr = (xr + r*xi)/d;
cdivi = (xi - r*xr)/d;
} else {
r = yr/yi;
d = yi + r*yr;
cdivr = (r*xr + xi)/d;
cdivi = (r*xi - xr)/d;
}
}
/**
* Nonsymmetric reduction from Hessenberg to real Schur form.
* <p/>
* This is derived from the Algol procedure hqr2, by Martin and Wilkinson,
* Handbook for Auto. Comp., Vol.ii-Linear Algebra, and the corresponding
* Fortran subroutine in EISPACK.
*/
private void hqr2() {
// Initialize
int nn = this.n;
int n = nn-1;
int low = 0;
int high = nn-1;
double eps = Math.pow(2.0,-52.0);
double exshift = 0.0;
double p=0,q=0,r=0,s=0,z=0,t,w,x,y;
// Store roots isolated by balanc and compute matrix norm
double norm = 0.0;
for (int i = 0; i < nn; i++) {
if (i < low | i > high) {
d[i] = H[i][i];
e[i] = 0.0;
}
for (int j = Math.max(i-1,0); j < nn; j++) {
norm = norm + Math.abs(H[i][j]);
}
}
// Outer loop over eigenvalue index
int iter = 0;
while (n >= low) {
// Look for single small sub-diagonal element
int l = n;
while (l > low) {
s = Math.abs(H[l-1][l-1]) + Math.abs(H[l][l]);
if (s == 0.0) {
s = norm;
}
if (Math.abs(H[l][l-1]) < eps * s) {
break;
}
l--;
}
// Check for convergence
// One root found
if (l == n) {
H[n][n] = H[n][n] + exshift;
d[n] = H[n][n];
e[n] = 0.0;
n--;
iter = 0;
// Two roots found
} else if (l == n-1) {
w = H[n][n-1] * H[n-1][n];
p = (H[n-1][n-1] - H[n][n]) / 2.0;
q = p * p + w;
z = Math.sqrt(Math.abs(q));
H[n][n] = H[n][n] + exshift;
H[n-1][n-1] = H[n-1][n-1] + exshift;
x = H[n][n];
// Real pair
if (q >= 0) {
if (p >= 0) {
z = p + z;
} else {
z = p - z;
}
d[n-1] = x + z;
d[n] = d[n-1];
if (z != 0.0) {
d[n] = x - w / z;
}
e[n-1] = 0.0;
e[n] = 0.0;
x = H[n][n-1];
s = Math.abs(x) + Math.abs(z);
p = x / s;
q = z / s;
r = Math.sqrt(p * p+q * q);
p = p / r;
q = q / r;
// Row modification
for (int j = n-1; j < nn; j++) {
z = H[n-1][j];
H[n-1][j] = q * z + p * H[n][j];
H[n][j] = q * H[n][j] - p * z;
}
// Column modification
for (int i = 0; i <= n; i++) {
z = H[i][n-1];
H[i][n-1] = q * z + p * H[i][n];
H[i][n] = q * H[i][n] - p * z;
}
// Accumulate transformations
for (int i = low; i <= high; i++) {
z = V[i][n-1];
V[i][n-1] = q * z + p * V[i][n];
V[i][n] = q * V[i][n] - p * z;
}
// Complex pair
} else {
d[n-1] = x + p;
d[n] = x + p;
e[n-1] = z;
e[n] = -z;
}
n = n - 2;
iter = 0;
// No convergence yet
} else {
// Form shift
x = H[n][n];
y = 0.0;
w = 0.0;
if (l < n) {
y = H[n-1][n-1];
w = H[n][n-1] * H[n-1][n];
}
// Wilkinson's original ad hoc shift
if (iter == 10) {
exshift += x;
for (int i = low; i <= n; i++) {
H[i][i] -= x;
}
s = Math.abs(H[n][n-1]) + Math.abs(H[n-1][n-2]);
x = y = 0.75 * s;
w = -0.4375 * s * s;
}
// MATLAB's new ad hoc shift
if (iter == 30) {
s = (y - x) / 2.0;
s = s * s + w;
if (s > 0) {
s = Math.sqrt(s);
if (y < x) {
s = -s;
}
s = x - w / ((y - x) / 2.0 + s);
for (int i = low; i <= n; i++) {
H[i][i] -= s;
}
exshift += s;
x = y = w = 0.964;
}
}
iter = iter + 1; // (Could check iteration count here.)
// Look for two consecutive small sub-diagonal elements
int m = n-2;
while (m >= l) {
z = H[m][m];
r = x - z;
s = y - z;
p = (r * s - w) / H[m+1][m] + H[m][m+1];
q = H[m+1][m+1] - z - r - s;
r = H[m+2][m+1];
s = Math.abs(p) + Math.abs(q) + Math.abs(r);
p = p / s;
q = q / s;
r = r / s;
if (m == l) {
break;
}
if (Math.abs(H[m][m-1]) * (Math.abs(q) + Math.abs(r)) <
eps * (Math.abs(p) * (Math.abs(H[m-1][m-1]) + Math.abs(z) +
Math.abs(H[m+1][m+1])))) {
break;
}
m--;
}
for (int i = m+2; i <= n; i++) {
H[i][i-2] = 0.0;
if (i > m+2) {
H[i][i-3] = 0.0;
}
}
// Double QR step involving rows l:n and columns m:n
for (int k = m; k <= n-1; k++) {
boolean notlast = (k != n-1);
if (k != m) {
p = H[k][k-1];
q = H[k+1][k-1];
r = (notlast ? H[k+2][k-1] : 0.0);
x = Math.abs(p) + Math.abs(q) + Math.abs(r);
if (x != 0.0) {
p = p / x;
q = q / x;
r = r / x;
}
}
if (x == 0.0) {
break;
}
s = Math.sqrt(p * p + q * q + r * r);
if (p < 0) {
s = -s;
}
if (s != 0) {
if (k != m) {
H[k][k-1] = -s * x;
} else if (l != m) {
H[k][k-1] = -H[k][k-1];
}
p = p + s;
x = p / s;
y = q / s;
z = r / s;
q = q / p;
r = r / p;
// Row modification
for (int j = k; j < nn; j++) {
p = H[k][j] + q * H[k+1][j];
if (notlast) {
p = p + r * H[k+2][j];
H[k+2][j] = H[k+2][j] - p * z;
}
H[k][j] = H[k][j] - p * x;
H[k+1][j] = H[k+1][j] - p * y;
}
// Column modification
for (int i = 0; i <= Math.min(n,k+3); i++) {
p = x * H[i][k] + y * H[i][k+1];
if (notlast) {
p = p + z * H[i][k+2];
H[i][k+2] = H[i][k+2] - p * r;
}
H[i][k] = H[i][k] - p;
H[i][k+1] = H[i][k+1] - p * q;
}
// Accumulate transformations
for (int i = low; i <= high; i++) {
p = x * V[i][k] + y * V[i][k+1];
if (notlast) {
p = p + z * V[i][k+2];
V[i][k+2] = V[i][k+2] - p * r;
}
V[i][k] = V[i][k] - p;
V[i][k+1] = V[i][k+1] - p * q;
}
} // (s != 0)
} // k loop
} // check convergence
} // while (n >= low)
// Backsubstitute to find vectors of upper triangular form
if (norm == 0.0) {
return;
}
for (n = nn-1; n >= 0; n--) {
p = d[n];
q = e[n];
// Real vector
if (q == 0) {
int l = n;
H[n][n] = 1.0;
for (int i = n-1; i >= 0; i--) {
w = H[i][i] - p;
r = 0.0;
for (int j = l; j <= n; j++) {
r = r + H[i][j] * H[j][n];
}
if (e[i] < 0.0) {
z = w;
s = r;
} else {
l = i;
if (e[i] == 0.0) {
if (w != 0.0) {
H[i][n] = -r / w;
} else {
H[i][n] = -r / (eps * norm);
}
// Solve real equations
} else {
x = H[i][i+1];
y = H[i+1][i];
q = (d[i] - p) * (d[i] - p) + e[i] * e[i];
t = (x * s - z * r) / q;
H[i][n] = t;
if (Math.abs(x) > Math.abs(z)) {
H[i+1][n] = (-r - w * t) / x;
} else {
H[i+1][n] = (-s - y * t) / z;
}
}
// Overflow control
t = Math.abs(H[i][n]);
if ((eps * t) * t > 1) {
for (int j = i; j <= n; j++) {
H[j][n] = H[j][n] / t;
}
}
}
}
// Complex vector
} else if (q < 0) {
int l = n-1;
// Last vector component imaginary so matrix is triangular
if (Math.abs(H[n][n-1]) > Math.abs(H[n-1][n])) {
H[n-1][n-1] = q / H[n][n-1];
H[n-1][n] = -(H[n][n] - p) / H[n][n-1];
} else {
cdiv(0.0,-H[n-1][n],H[n-1][n-1]-p,q);
H[n-1][n-1] = cdivr;
H[n-1][n] = cdivi;
}
H[n][n-1] = 0.0;
H[n][n] = 1.0;
for (int i = n-2; i >= 0; i--) {
double ra,sa,vr,vi;
ra = 0.0;
sa = 0.0;
for (int j = l; j <= n; j++) {
ra = ra + H[i][j] * H[j][n-1];
sa = sa + H[i][j] * H[j][n];
}
w = H[i][i] - p;
if (e[i] < 0.0) {
z = w;
r = ra;
s = sa;
} else {
l = i;
if (e[i] == 0) {
cdiv(-ra,-sa,w,q);
H[i][n-1] = cdivr;
H[i][n] = cdivi;
} else {
// Solve complex equations
x = H[i][i+1];
y = H[i+1][i];
vr = (d[i] - p) * (d[i] - p) + e[i] * e[i] - q * q;
vi = (d[i] - p) * 2.0 * q;
if (vr == 0.0 & vi == 0.0) {
vr = eps * norm * (Math.abs(w) + Math.abs(q) +
Math.abs(x) + Math.abs(y) + Math.abs(z));
}
cdiv(x*r-z*ra+q*sa,x*s-z*sa-q*ra,vr,vi);
H[i][n-1] = cdivr;
H[i][n] = cdivi;
if (Math.abs(x) > (Math.abs(z) + Math.abs(q))) {
H[i+1][n-1] = (-ra - w * H[i][n-1] + q * H[i][n]) / x;
H[i+1][n] = (-sa - w * H[i][n] - q * H[i][n-1]) / x;
} else {
cdiv(-r-y*H[i][n-1],-s-y*H[i][n],z,q);
H[i+1][n-1] = cdivr;
H[i+1][n] = cdivi;
}
}
// Overflow control
t = Math.max(Math.abs(H[i][n-1]),Math.abs(H[i][n]));
if ((eps * t) * t > 1) {
for (int j = i; j <= n; j++) {
H[j][n-1] = H[j][n-1] / t;
H[j][n] = H[j][n] / t;
}
}
}
}
}
}
// Vectors of isolated roots
for (int i = 0; i < nn; i++) {
if (i < low | i > high) {
for (int j = i; j < nn; j++) {
V[i][j] = H[i][j];
}
}
}
// Back transformation to get eigenvectors of original matrix
for (int j = nn-1; j >= low; j--) {
for (int i = low; i <= high; i++) {
z = 0.0;
for (int k = low; k <= Math.min(j,high); k++) {
z = z + V[i][k] * H[k][j];
}
V[i][j] = z;
}
}
}
/**
* Check for symmetry, then construct the eigenvalue decomposition
*
* @param Arg Square matrix
*/
public EigenvalueDecomposition(Matrix Arg) {
double[][] A = Arg.getArray();
n = Arg.getColumnDimension();
V = new double[n][n];
d = new double[n];
e = new double[n];
issymmetric = true;
for (int j = 0; (j < n) & issymmetric; j++) {
for (int i = 0; (i < n) & issymmetric; i++) {
issymmetric = (A[i][j] == A[j][i]);
}
}
if (issymmetric) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
V[i][j] = A[i][j];
}
}
// Tridiagonalize.
tred2();
// Diagonalize.
tql2();
} else {
H = new double[n][n];
ort = new double[n];
for (int j = 0; j < n; j++) {
for (int i = 0; i < n; i++) {
H[i][j] = A[i][j];
}
}
// Reduce to Hessenberg form.
orthes();
// Reduce Hessenberg to real Schur form.
hqr2();
}
}
/**
* Return the eigenvector matrix
* @return V
*/
public Matrix getV() {
return new Matrix(V,n,n);
}
/**
* Return the real parts of the eigenvalues
* @return real(diag(D))
*/
public double[] getRealEigenvalues() {
return d;
}
/**
* Return the imaginary parts of the eigenvalues
* @return imag(diag(D))
*/
public double[] getImagEigenvalues() {
return e;
}
/**
* Return the block diagonal eigenvalue matrix
* @return D
*/
public Matrix getD() {
Matrix X = new Matrix(n,n);
double[][] D = X.getArray();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
D[i][j] = 0.0;
}
D[i][i] = d[i];
if (e[i] > 0) {
D[i][i+1] = e[i];
} else if (e[i] < 0) {
D[i][i-1] = e[i];
}
}
return X;
}
/**
* 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/matrix/ExponentialFormat.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/>.
*/
/*
* ExponentialFormat.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.matrix;
import java.text.DecimalFormat;
import java.text.FieldPosition;
import weka.core.RevisionHandler;
import weka.core.RevisionUtils;
/**
* @author Yong Wang
* @version $Revision$
*/
public class ExponentialFormat
extends DecimalFormat
implements RevisionHandler {
/** for serialization */
private static final long serialVersionUID = -5298981701073897741L;
protected DecimalFormat nf ;
protected boolean sign;
protected int digits;
protected int exp;
protected boolean trailing = true;
public ExponentialFormat () {
this( 5 );
}
public ExponentialFormat( int digits ) {
this( digits, false );
}
public ExponentialFormat( int digits, boolean trailing ) {
this( digits, 2, true, trailing );
}
public ExponentialFormat( int digits, int exp, boolean sign,
boolean trailing ) {
this.digits = digits;
this.exp = exp;
this.sign = sign;
this.trailing = trailing;
nf = new DecimalFormat( pattern() );
nf.setPositivePrefix("+");
nf.setNegativePrefix("-");
}
public int width () {
if( !trailing ) throw new RuntimeException( "flexible width" );
if( sign ) return 1 + digits + 2 + exp;
else return digits + 2 + exp;
}
public StringBuffer format(double number, StringBuffer toAppendTo,
FieldPosition pos) {
StringBuffer s = new StringBuffer( nf.format(number) );
if( sign ) {
if( s.charAt(0) == '+' ) s.setCharAt(0, ' ');
}
else {
if( s.charAt(0) == '-' ) s.setCharAt(0, '*');
else s.deleteCharAt(0);
}
return toAppendTo.append( s );
}
private String pattern() {
StringBuffer s = new StringBuffer(); // "-##0.00E-00" // fw.d
s.append("0.");
for(int i = 0; i < digits - 1; i ++)
if( trailing ) s.append('0');
else s.append('#');
s.append('E');
for(int i = 0; i < exp; i ++)
s.append('0');
return s.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/core
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/matrix/FlexibleDecimalFormat.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/>.
*/
/*
* FlexibleDecimalFormat.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.matrix;
import java.text.DecimalFormat;
import java.text.FieldPosition;
import weka.core.RevisionHandler;
import weka.core.RevisionUtils;
/**
* @author Yong Wang
* @version $Revision$
*/
public class FlexibleDecimalFormat extends DecimalFormat implements
RevisionHandler {
/** for serialization */
private static final long serialVersionUID = 110912192794064140L;
private DecimalFormat nf = null;
private int digits = 7;
private boolean exp = false;
private int intDigits = 1;
private int decimalDigits = 0;
private int expDecimalDigits = 0; // ???
private int power = 2;
private boolean trailing = false;
private boolean grouping = false;
private boolean sign = false;
public FlexibleDecimalFormat() {
this(5);
}
public FlexibleDecimalFormat(int digits) {
if (digits < 1) {
throw new IllegalArgumentException("digits < 1");
}
this.digits = digits;
intDigits = 1;
}
public FlexibleDecimalFormat(int digits, boolean trailing) {
this(digits);
this.trailing = trailing;
}
public FlexibleDecimalFormat(int digits, boolean exp, boolean trailing,
boolean grouping) {
this.trailing = trailing;
this.exp = exp;
this.digits = digits;
this.grouping = grouping;
if (exp) {
this.intDigits = 1;
this.decimalDigits = digits - intDigits;
} else {
this.intDigits = Math.max(1, digits - decimalDigits);
}
}
public FlexibleDecimalFormat(double d) {
newFormat(d);
}
private void newFormat(double d) {
if (needExponentialFormat(d)) {
exp = true;
intDigits = 1;
expDecimalDigits = decimalDigits(d, true);
if (d < 0) {
sign = true;
} else {
sign = false;
}
} else {
exp = false;
intDigits = Math.max(1, intDigits(d));
decimalDigits = decimalDigits(d, false);
if (d < 0.0) {
sign = true;
} else {
sign = false;
}
}
}
public void update(double d) {
if (Math.abs(intDigits(d) - 1) > 99) {
power = 3;
}
expDecimalDigits = Math.max(expDecimalDigits, decimalDigits(d, true));
if (d < 0) {
sign = true;
}
if (needExponentialFormat(d) || exp) {
exp = true;
} else {
intDigits = Math.max(intDigits, intDigits(d));
decimalDigits = Math.max(decimalDigits, decimalDigits(d, false));
if (d < 0) {
sign = true;
}
}
}
private static int intDigits(double d) {
return (int) Math.floor(Math.log(Math.abs(d * (1 + 1e-14))) / Math.log(10)) + 1;
}
private int decimalDigits(double d, boolean expo) {
if (d == 0.0) {
return 0;
}
d = Math.abs(d);
int e = intDigits(d);
if (expo) {
d /= Math.pow(10, e - 1);
e = 1;
}
if (e >= digits) {
return 0;
}
int iD = Math.max(1, e);
int dD = digits - e;
if (!trailing && dD > 0) { // to get rid of trailing zeros
FloatingPointFormat f = new FloatingPointFormat(iD + 1 + dD, dD, true);
String dString = f.nf.format(d);
while (dD > 0) {
if (dString.charAt(iD + 1 + dD - 1) == '0') {
dD--;
} else {
break;
}
}
}
return dD;
}
public boolean needExponentialFormat(double d) {
if (d == 0.0) {
return false;
}
int e = intDigits(d);
if (e > digits + 5 || e < -3) {
return true;
} else {
return false;
}
}
public void grouping(boolean grouping) {
this.grouping = grouping;
}
private void setFormat() {
int dot = 1;
if (decimalDigits == 0) {
dot = 0;
}
if (exp) {
nf = new ExponentialFormat(1 + expDecimalDigits, power, sign, grouping
|| trailing);
} else {
int s = sign ? 1 : 0;
nf = new FloatingPointFormat(s + intDigits + dot + decimalDigits,
decimalDigits, grouping || trailing);
}
}
private void setFormat(double d) {
newFormat(d);
setFormat();
}
@Override
public StringBuffer format(double number, StringBuffer toAppendTo,
FieldPosition pos) {
if (grouping) {
if (nf == null) {
setFormat();
}
} else {
setFormat(number);
}
return toAppendTo.append(nf.format(number));
}
public int width() {
if (!trailing && !grouping) {
throw new RuntimeException("flexible width");
}
return format(0.).length();
}
public StringBuffer formatString(String str) {
int w = width();
int h = (w - str.length()) / 2;
StringBuffer text = new StringBuffer();
for (int i = 0; i < h; i++) {
text.append(' ');
}
text.append(str);
for (int i = 0; i < w - h - str.length(); i++) {
text.append(' ');
}
return text;
}
/**
* 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/matrix/FloatingPointFormat.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/>.
*/
/*
* FloatingPoint.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.matrix;
import java.text.DecimalFormat;
import java.text.FieldPosition;
import weka.core.RevisionHandler;
import weka.core.RevisionUtils;
/**
* Class for the format of floating point numbers
*
* @author Yong Wang
* @version $Revision$
*/
public class FloatingPointFormat
extends DecimalFormat
implements RevisionHandler {
/** for serialization */
private static final long serialVersionUID = 4500373755333429499L;
protected DecimalFormat nf ;
protected int width;
protected int decimal;
protected boolean trailing = true;
/**
* Default constructor
*/
public FloatingPointFormat () {
this( 8, 5 );
}
public FloatingPointFormat ( int digits ) {
this( 8, 2 );
}
public FloatingPointFormat( int w, int d ) {
width = w;
decimal = d;
nf = new DecimalFormat( pattern(w, d) );
nf.setPositivePrefix(" ");
nf.setNegativePrefix("-");
}
public FloatingPointFormat( int w, int d, boolean trailingZeros ) {
this( w, d );
this.trailing = trailingZeros;
}
public StringBuffer format(double number, StringBuffer toAppendTo,
FieldPosition pos) {
StringBuffer s = new StringBuffer( nf.format(number) );
if( s.length() > width ) {
if( s.charAt(0) == ' ' && s.length() == width + 1 ) {
s.deleteCharAt(0);
}
else {
s.setLength( width );
for( int i = 0; i < width; i ++ )
s.setCharAt(i, '*');
}
}
else {
for (int i = 0; i < width - s.length(); i++) // padding
s.insert(0,' ');
}
if( !trailing && decimal > 0 ) { // delete trailing zeros
while( s.charAt( s.length()-1 ) == '0' )
s.deleteCharAt( s.length()-1 );
if( s.charAt( s.length()-1 ) == '.' )
s.deleteCharAt( s.length()-1 );
}
return toAppendTo.append( s );
}
public static String pattern( int w, int d ) {
StringBuffer s = new StringBuffer(); // "-##0.00" // fw.d
s.append( padding(w - d - 3, '#') );
if( d == 0) s.append('0');
else {
s.append("0.");
s.append( padding( d, '0') );
}
return s.toString();
}
private static StringBuffer padding( int n, char c ) {
StringBuffer text = new StringBuffer();
for(int i = 0; i < n; i++ ){
text.append( c );
}
return text;
}
public int width () {
if( !trailing ) throw new RuntimeException( "flexible width" );
return width;
}
/**
* 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/matrix/IntVector.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/>.
*/
/*
* IntVector.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.matrix;
import java.util.Arrays;
import weka.core.RevisionHandler;
import weka.core.RevisionUtils;
/**
* A vector specialized on integers.
*
* @author Yong Wang
* @version $Revision$
*/
public class IntVector
implements Cloneable, RevisionHandler {
/** Array for internal storage of elements. */
int[] V;
/** size of the vector */
private int sizeOfVector;
/* ------------------------
Constructors
* ------------------------ */
/** Constructs a null vector.
*/
public IntVector(){
V = new int[ 0 ];
setSize( 0 );
}
/** Constructs an n-vector of zeros.
* @param n Length.
*/
public IntVector( int n ){
V = new int[ n ];
setSize( n );
}
/** Constructs an n-vector of a constant
* @param n Length.
*/
public IntVector( int n, int s ){
this(n);
set( s );
}
/** Constructs a vector given an int array
* @param v the int array
*/
public IntVector( int v[] ){
if( v == null ) {
V = new int[ 0 ];
setSize( 0 );
}
else {
V = new int[ v.length ];
setSize( v.length );
set(0, size() - 1, v, 0);
}
}
/* ------------------------
Public Methods
* ------------------------ */
/** Gets the size of the vector.
* @return Size. */
public int size(){
return sizeOfVector;
}
/**
* Sets the size of the vector. The provided size can't be greater than
* the capacity of the vector.
* @param size the new Size.
*/
public void setSize( int size ){
if( size > capacity() )
throw new IllegalArgumentException("insufficient capacity");
sizeOfVector = size;
}
/** Sets the value of an element.
* @param s the value for the element */
public void set( int s ) {
for( int i = 0; i < size(); i++ )
set(i, s);
}
/** Sets the values of elements from an int array.
* @param i0 the index of the first element
* @param i1 the index of the last element
* @param v the int array that stores the values
* @param j0 the index of the first element in the int array */
public void set( int i0, int i1, int [] v, int j0){
for(int i = i0; i<= i1; i++)
set( i, v[j0 + i - i0] );
}
/** Sets the values of elements from another IntVector.
* @param i0 the index of the first element
* @param i1 the index of the last element
* @param v the IntVector that stores the values
* @param j0 the index of the first element in the IntVector */
public void set( int i0, int i1, IntVector v, int j0){
for(int i = i0; i<= i1; i++)
set( i, v.get(j0 + i - i0) );
}
/** Sets the values of elements from another IntVector.
* @param v the IntVector that stores the values
*/
public void set( IntVector v ){
set( 0, v.size() - 1, v, 0);
}
/** Generates an IntVector that stores all integers inclusively between
* two integers.
* @param i0 the first integer
* @param i1 the second integer
*/
public static IntVector seq( int i0, int i1 ) {
if( i1 < i0 ) throw new IllegalArgumentException("i1 < i0 ");
IntVector v = new IntVector( i1 - i0 + 1 );
for( int i = 0; i < i1 - i0 + 1; i++ ) {
v.set(i, i + i0);
}
return v;
}
/** Access the internal one-dimensional array.
@return Pointer to the one-dimensional array of vector elements. */
public int [] getArray() {
return V;
}
/** Sets the internal one-dimensional array.
@param a Pointer to the one-dimensional array of vector elements. */
protected void setArray( int [] a ) {
V = a;
}
/** Sorts the elements in place
*/
public void sort() {
Arrays.sort( V, 0, size() );
}
/** Returns a copy of the internal one-dimensional array.
@return One-dimensional array copy of vector elements. */
public int[] getArrayCopy() {
int [] b = new int[ size() ];
for( int i = 0; i <= size() - 1; i++ ) {
b[i] = V[i];
}
return b;
}
/** Returns the capacity of the vector
*/
public int capacity() {
return V.length;
}
/** Sets the capacity of the vector
* @param capacity the new capacity of the vector
*/
public void setCapacity( int capacity ) {
if( capacity == capacity() ) return;
int [] old_V = V;
int m = Math.min( capacity, size() );
V = new int[ capacity ];
setSize( capacity );
set(0, m-1, old_V, 0);
}
/** Sets a single element.
* @param i the index of the element
* @param s the new value
*/
public void set( int i, int s ) {
V[i] = s;
}
/** Gets the value of an element.
* @param i the index of the element
* @return the value of the element
*/
public int get( int i ) {
return V[i];
}
/** Makes a deep copy of the vector
*/
public IntVector copy() {
return (IntVector) clone();
}
/** Clones the IntVector object.
*/
public Object clone() {
IntVector u = new IntVector( size() );
for( int i = 0; i < size(); i++)
u.V[i] = V[i];
return u;
}
/** Returns a subvector.
* @param i0 the index of the first element
* @param i1 the index of the last element
* @return the subvector
*/
public IntVector subvector( int i0, int i1 )
{
IntVector v = new IntVector( i1-i0+1 );
v.set(0, i1 - i0, this, i0);
return v;
}
/** Returns a subvector as indexed by an IntVector.
* @param index the index
* @return the subvector
*/
public IntVector subvector( IntVector index ) {
IntVector v = new IntVector( index.size() );
for( int i = 0; i < index.size(); i++ )
v.V[i] = V[index.V[i]];
return v;
}
/**
* Swaps the values stored at i and j
* @param i the index i
* @param j the index j
*/
public void swap( int i, int j ){
if( i == j ) return;
int t = get( i );
set( i, get(j) );
set( j, t );
}
/**
* Shifts an element to another position. Elements between them are
* shifted one position left.
* @param i the index of the element
* @param j the index of the new position */
public void shift( int i, int j ){
if( i == j ) return;
if( i < j ) {
int t = V[i];
for( int k = i; k <= j-1; k++ )
V[k] = V[k+1];
V[j] = t;
}
else shift( j, i );
}
/**
* Shifts an element to the end of the vector. Elements between them are
* shifted one position left.
* @param j the index of the element
*/
public void shiftToEnd( int j ){
shift( j, size()-1 );
}
/**
* Returns true if the vector is empty
*/
public boolean isEmpty() {
if( size() == 0 ) return true;
return false;
}
/** Converts the IntVecor to a string
*/
public String toString() {
return toString( 5, false );
}
/** Convert the IntVecor to a string
* @param digits number of digits to be shown
* @param trailing true if trailing zeros are to be shown
*/
public String toString( int digits, boolean trailing ) {
if( isEmpty() ) return "null vector";
StringBuffer text = new StringBuffer();
FlexibleDecimalFormat nf = new FlexibleDecimalFormat( digits,
trailing );
nf.grouping( true );
for( int i = 0; i < size(); i ++ ) nf.update( get(i) );
int count = 0;
int width = 80;
String number;
for( int i = 0; i < size(); i++ ) {
number = nf.format(get(i));
count += 1 + number.length();
if( count > width-1 ) {
text.append('\n');
count = 1 + number.length();
}
text.append( " " + number );
}
return text.toString();
}
/**
* Returns the revision string.
*
* @return the revision
*/
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Tests the IntVector class
*/
public static void main( String args[] ) {
IntVector u = new IntVector();
System.out.println( u );
IntVector v = IntVector.seq(10, 25);
System.out.println( v );
IntVector w = IntVector.seq(25, 10);
System.out.println( w );
}
}
|
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/matrix/LUDecomposition.java
|
/*
* This software is a cooperative product of The MathWorks and the National
* Institute of Standards and Technology (NIST) which has been released to the
* public domain. Neither The MathWorks nor NIST assumes any responsibility
* whatsoever for its use by other parties, and makes no guarantees, expressed
* or implied, about its quality, reliability, or any other characteristic.
*/
/*
* LUDecomposition.java
* Copyright (C) 1999 The Mathworks and NIST
*
*/
package weka.core.matrix;
import weka.core.RevisionHandler;
import weka.core.RevisionUtils;
import java.io.Serializable;
/**
* LU Decomposition.
* <P>
* For an m-by-n matrix A with m >= n, the LU decomposition is an m-by-n
* unit lower triangular matrix L, an n-by-n upper triangular matrix U, and a
* permutation vector piv of length m so that A(piv,:) = L*U. If m < n,
* then L is m-by-m and U is m-by-n.
* <P>
* The LU decompostion with pivoting always exists, even if the matrix is
* singular, so the constructor will never fail. The primary use of the LU
* decomposition is in the solution of square systems of simultaneous linear
* equations. This will fail if isNonsingular() returns false.
* <p/>
* Adapted from the <a href="http://math.nist.gov/javanumerics/jama/" target="_blank">JAMA</a> package.
*
* @author The Mathworks and NIST
* @author Fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public class LUDecomposition
implements Serializable, RevisionHandler {
/** for serialization */
private static final long serialVersionUID = -2731022568037808629L;
/**
* Array for internal storage of decomposition.
* @serial internal array storage.
*/
private double[][] LU;
/**
* Row and column dimensions, and pivot sign.
* @serial column dimension.
* @serial row dimension.
* @serial pivot sign.
*/
private int m, n, pivsign;
/**
* Internal storage of pivot vector.
* @serial pivot vector.
*/
private int[] piv;
/**
* LU Decomposition
* @param A Rectangular matrix
*/
public LUDecomposition(Matrix A) {
// Use a "left-looking", dot-product, Crout/Doolittle algorithm.
LU = A.getArrayCopy();
m = A.getRowDimension();
n = A.getColumnDimension();
piv = new int[m];
for (int i = 0; i < m; i++) {
piv[i] = i;
}
pivsign = 1;
double[] LUrowi;
double[] LUcolj = new double[m];
// Outer loop.
for (int j = 0; j < n; j++) {
// Make a copy of the j-th column to localize references.
for (int i = 0; i < m; i++) {
LUcolj[i] = LU[i][j];
}
// Apply previous transformations.
for (int i = 0; i < m; i++) {
LUrowi = LU[i];
// Most of the time is spent in the following dot product.
int kmax = Math.min(i,j);
double s = 0.0;
for (int k = 0; k < kmax; k++) {
s += LUrowi[k]*LUcolj[k];
}
LUrowi[j] = LUcolj[i] -= s;
}
// Find pivot and exchange if necessary.
int p = j;
for (int i = j+1; i < m; i++) {
if (Math.abs(LUcolj[i]) > Math.abs(LUcolj[p])) {
p = i;
}
}
if (p != j) {
for (int k = 0; k < n; k++) {
double t = LU[p][k]; LU[p][k] = LU[j][k]; LU[j][k] = t;
}
int k = piv[p]; piv[p] = piv[j]; piv[j] = k;
pivsign = -pivsign;
}
// Compute multipliers.
if (j < m & LU[j][j] != 0.0) {
for (int i = j+1; i < m; i++) {
LU[i][j] /= LU[j][j];
}
}
}
}
/**
* Is the matrix nonsingular?
* @return true if U, and hence A, is nonsingular.
*/
public boolean isNonsingular() {
for (int j = 0; j < n; j++) {
if (LU[j][j] == 0)
return false;
}
return true;
}
/**
* Return lower triangular factor
* @return L
*/
public Matrix getL() {
Matrix X = new Matrix(m,n);
double[][] L = X.getArray();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (i > j) {
L[i][j] = LU[i][j];
} else if (i == j) {
L[i][j] = 1.0;
} else {
L[i][j] = 0.0;
}
}
}
return X;
}
/**
* Return upper triangular factor
* @return U
*/
public Matrix getU() {
Matrix X = new Matrix(n,n);
double[][] U = X.getArray();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i <= j) {
U[i][j] = LU[i][j];
} else {
U[i][j] = 0.0;
}
}
}
return X;
}
/**
* Return pivot permutation vector
* @return piv
*/
public int[] getPivot() {
int[] p = new int[m];
for (int i = 0; i < m; i++) {
p[i] = piv[i];
}
return p;
}
/**
* Return pivot permutation vector as a one-dimensional double array
* @return (double) piv
*/
public double[] getDoublePivot() {
double[] vals = new double[m];
for (int i = 0; i < m; i++) {
vals[i] = (double) piv[i];
}
return vals;
}
/**
* Determinant
* @return det(A)
* @exception IllegalArgumentException Matrix must be square
*/
public double det() {
if (m != n) {
throw new IllegalArgumentException("Matrix must be square.");
}
double d = (double) pivsign;
for (int j = 0; j < n; j++) {
d *= LU[j][j];
}
return d;
}
/**
* Solve A*X = B
* @param B A Matrix with as many rows as A and any number of columns.
* @return X so that L*U*X = B(piv,:)
* @exception IllegalArgumentException Matrix row dimensions must agree.
* @exception RuntimeException Matrix is singular.
*/
public Matrix solve(Matrix B) {
if (B.getRowDimension() != m) {
throw new IllegalArgumentException("Matrix row dimensions must agree.");
}
if (!this.isNonsingular()) {
throw new RuntimeException("Matrix is singular.");
}
// Copy right hand side with pivoting
int nx = B.getColumnDimension();
Matrix Xmat = B.getMatrix(piv,0,nx-1);
double[][] X = Xmat.getArray();
// Solve L*Y = B(piv,:)
for (int k = 0; k < n; k++) {
for (int i = k+1; i < n; i++) {
for (int j = 0; j < nx; j++) {
X[i][j] -= X[k][j]*LU[i][k];
}
}
}
// Solve U*X = Y;
for (int k = n-1; k >= 0; k--) {
for (int j = 0; j < nx; j++) {
X[k][j] /= LU[k][k];
}
for (int i = 0; i < k; i++) {
for (int j = 0; j < nx; j++) {
X[i][j] -= X[k][j]*LU[i][k];
}
}
}
return Xmat;
}
/**
* 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/matrix/LinearRegression.java
|
/*
* This software is a cooperative product of The MathWorks and the National
* Institute of Standards and Technology (NIST) which has been released to the
* public domain. Neither The MathWorks nor NIST assumes any responsibility
* whatsoever for its use by other parties, and makes no guarantees, expressed
* or implied, about its quality, reliability, or any other characteristic.
*/
/*
* LinearRegression.java
* Copyright (C) 2005 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.matrix;
import weka.core.RevisionHandler;
import weka.core.RevisionUtils;
import weka.core.Utils;
/**
* Class for performing (ridged) linear regression using Tikhonov
* regularization.
*
* @author Fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public class LinearRegression
implements RevisionHandler {
/** the coefficients */
protected double[] m_Coefficients = null;
/**
* Performs a (ridged) linear regression.
*
* @param a the matrix to perform the regression on
* @param y the dependent variable vector
* @param ridge the ridge parameter
* @throws IllegalArgumentException if not successful
*/
public LinearRegression(Matrix a, Matrix y, double ridge) {
calculate(a, y, ridge);
}
/**
* Performs a weighted (ridged) linear regression.
*
* @param a the matrix to perform the regression on
* @param y the dependent variable vector
* @param w the array of data point weights
* @param ridge the ridge parameter
* @throws IllegalArgumentException if the wrong number of weights were
* provided.
*/
public LinearRegression(Matrix a, Matrix y, double[] w, double ridge) {
if (w.length != a.getRowDimension())
throw new IllegalArgumentException("Incorrect number of weights provided");
Matrix weightedThis = new Matrix(
a.getRowDimension(), a.getColumnDimension());
Matrix weightedDep = new Matrix(a.getRowDimension(), 1);
for (int i = 0; i < w.length; i++) {
double sqrt_weight = Math.sqrt(w[i]);
for (int j = 0; j < a.getColumnDimension(); j++)
weightedThis.set(i, j, a.get(i, j) * sqrt_weight);
weightedDep.set(i, 0, y.get(i, 0) * sqrt_weight);
}
calculate(weightedThis, weightedDep, ridge);
}
/**
* performs the actual regression.
*
* @param a the matrix to perform the regression on
* @param y the dependent variable vector
* @param ridge the ridge parameter
* @throws IllegalArgumentException if not successful
*/
protected void calculate(Matrix a, Matrix y, double ridge) {
if (y.getColumnDimension() > 1)
throw new IllegalArgumentException("Only one dependent variable allowed");
int nc = a.getColumnDimension();
m_Coefficients = new double[nc];
Matrix solution;
Matrix ss = aTa(a);
Matrix bb = aTy(a, y);
boolean success = true;
do {
// Set ridge regression adjustment
Matrix ssWithRidge = ss.copy();
for (int i = 0; i < nc; i++)
ssWithRidge.set(i, i, ssWithRidge.get(i, i) + ridge);
// Carry out the regression
try {
solution = ssWithRidge.solve(bb);
for (int i = 0; i < nc; i++)
m_Coefficients[i] = solution.get(i, 0);
success = true;
} catch (Exception ex) {
ridge *= 10;
success = false;
}
} while (!success);
}
/**
* Return aTa (a' * a)
*/
private static Matrix aTa(Matrix a) {
int cols = a.getColumnDimension();
double[][] A = a.getArray();
Matrix x = new Matrix(cols, cols);
double[][] X = x.getArray();
double[] Acol = new double[a.getRowDimension()];
for (int col1 = 0; col1 < cols; col1++) {
// cache the column for faster access later
for (int row = 0; row < Acol.length; row++) {
Acol[row] = A[row][col1];
}
// reference the row for faster lookup
double[] Xrow = X[col1];
for (int row = 0; row < Acol.length; row++) {
double[] Arow = A[row];
for (int col2 = col1; col2 < Xrow.length; col2++) {
Xrow[col2] += Acol[row] * Arow[col2];
}
}
// result is symmetric
for (int col2 = col1 + 1; col2 < Xrow.length; col2++) {
X[col2][col1] = Xrow[col2];
}
}
return x;
}
/**
* Return aTy (a' * y)
*/
private static Matrix aTy(Matrix a, Matrix y) {
double[][] A = a.getArray();
double[][] Y = y.getArray();
Matrix x = new Matrix(a.getColumnDimension(), 1);
double[][] X = x.getArray();
for (int row = 0; row < A.length; row++) {
// reference the rows for faster lookup
double[] Arow = A[row];
double[] Yrow = Y[row];
for (int col = 0; col < Arow.length; col++) {
X[col][0] += Arow[col] * Yrow[0];
}
}
return x;
}
/**
* returns the calculated coefficients
*
* @return the coefficients
*/
public final double[] getCoefficients() {
return m_Coefficients;
}
/**
* returns the coefficients in a string representation
*/
public String toString() {
return Utils.arrayToString(getCoefficients());
}
/**
* 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/matrix/Maths.java
|
/*
* This software is a cooperative product of The MathWorks and the National
* Institute of Standards and Technology (NIST) which has been released to the
* public domain. Neither The MathWorks nor NIST assumes any responsibility
* whatsoever for its use by other parties, and makes no guarantees, expressed
* or implied, about its quality, reliability, or any other characteristic.
*/
/*
* Maths.java
* Copyright (C) 1999 The Mathworks and NIST
*
*/
package weka.core.matrix;
import weka.core.RevisionHandler;
import weka.core.RevisionUtils;
import weka.core.Statistics;
import java.util.Random;
/**
* Utility class.
* <p/>
* Adapted from the <a href="http://math.nist.gov/javanumerics/jama/" target="_blank">JAMA</a> package.
*
* @author The Mathworks and NIST
* @author Fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public class Maths
implements RevisionHandler {
/** The constant 1 / sqrt(2 pi) */
public static final double PSI = 0.3989422804014327028632;
/** The constant - log( sqrt(2 pi) ) */
public static final double logPSI = -0.9189385332046726695410;
/** Distribution type: undefined */
public static final int undefinedDistribution = 0;
/** Distribution type: noraml */
public static final int normalDistribution = 1;
/** Distribution type: chi-squared */
public static final int chisqDistribution = 2;
/**
* sqrt(a^2 + b^2) without under/overflow.
*/
public static double hypot(double a, double b) {
double r;
if (Math.abs(a) > Math.abs(b)) {
r = b/a;
r = Math.abs(a)*Math.sqrt(1+r*r);
} else if (b != 0) {
r = a/b;
r = Math.abs(b)*Math.sqrt(1+r*r);
} else {
r = 0.0;
}
return r;
}
/**
* Returns the square of a value
* @param x
* @return the square
*/
public static double square( double x )
{
return x * x;
}
/* methods for normal distribution */
/**
* Returns the cumulative probability of the standard normal.
* @param x the quantile
*/
public static double pnorm( double x )
{
return Statistics.normalProbability( x );
}
/**
* Returns the cumulative probability of a normal distribution.
* @param x the quantile
* @param mean the mean of the normal distribution
* @param sd the standard deviation of the normal distribution.
*/
public static double pnorm( double x, double mean, double sd )
{
if( sd <= 0.0 )
throw new IllegalArgumentException("standard deviation <= 0.0");
return pnorm( (x - mean) / sd );
}
/**
* Returns the cumulative probability of a set of normal distributions
* with different means.
* @param x the vector of quantiles
* @param mean the means of the normal distributions
* @param sd the standard deviation of the normal distribution.
* @return the cumulative probability */
public static DoubleVector pnorm( double x, DoubleVector mean,
double sd )
{
DoubleVector p = new DoubleVector( mean.size() );
for( int i = 0; i < mean.size(); i++ ) {
p.set( i, pnorm(x, mean.get(i), sd) );
}
return p;
}
/** Returns the density of the standard normal.
* @param x the quantile
* @return the density
*/
public static double dnorm( double x )
{
return Math.exp( - x * x / 2. ) * PSI;
}
/** Returns the density value of a standard normal.
* @param x the quantile
* @param mean the mean of the normal distribution
* @param sd the standard deviation of the normal distribution.
* @return the density */
public static double dnorm( double x, double mean, double sd )
{
if( sd <= 0.0 )
throw new IllegalArgumentException("standard deviation <= 0.0");
return dnorm( (x - mean) / sd );
}
/** Returns the density values of a set of normal distributions with
* different means.
* @param x the quantile
* @param mean the means of the normal distributions
* @param sd the standard deviation of the normal distribution.
* @return the density */
public static DoubleVector dnorm( double x, DoubleVector mean,
double sd )
{
DoubleVector den = new DoubleVector( mean.size() );
for( int i = 0; i < mean.size(); i++ ) {
den.set( i, dnorm(x, mean.get(i), sd) );
}
return den;
}
/** Returns the log-density of the standard normal.
* @param x the quantile
* @return the density
*/
public static double dnormLog( double x )
{
return logPSI - x * x / 2.;
}
/** Returns the log-density value of a standard normal.
* @param x the quantile
* @param mean the mean of the normal distribution
* @param sd the standard deviation of the normal distribution.
* @return the density */
public static double dnormLog( double x, double mean, double sd ) {
if( sd <= 0.0 )
throw new IllegalArgumentException("standard deviation <= 0.0");
return - Math.log(sd) + dnormLog( (x - mean) / sd );
}
/** Returns the log-density values of a set of normal distributions with
* different means.
* @param x the quantile
* @param mean the means of the normal distributions
* @param sd the standard deviation of the normal distribution.
* @return the density */
public static DoubleVector dnormLog( double x, DoubleVector mean,
double sd )
{
DoubleVector denLog = new DoubleVector( mean.size() );
for( int i = 0; i < mean.size(); i++ ) {
denLog.set( i, dnormLog(x, mean.get(i), sd) );
}
return denLog;
}
/**
* Generates a sample of a normal distribution.
* @param n the size of the sample
* @param mean the mean of the normal distribution
* @param sd the standard deviation of the normal distribution.
* @param random the random stream
* @return the sample
*/
public static DoubleVector rnorm( int n, double mean, double sd,
Random random )
{
if( sd < 0.0)
throw new IllegalArgumentException("standard deviation < 0.0");
if( sd == 0.0 ) return new DoubleVector( n, mean );
DoubleVector v = new DoubleVector( n );
for( int i = 0; i < n; i++ )
v.set( i, (random.nextGaussian() + mean) / sd );
return v;
}
/* methods for Chi-square distribution */
/** Returns the cumulative probability of the Chi-squared distribution
* @param x the quantile
*/
public static double pchisq( double x )
{
double xh = Math.sqrt( x );
return pnorm( xh ) - pnorm( -xh );
}
/** Returns the cumulative probability of the noncentral Chi-squared
* distribution.
* @param x the quantile
* @param ncp the noncentral parameter */
public static double pchisq( double x, double ncp )
{
double mean = Math.sqrt( ncp );
double xh = Math.sqrt( x );
return pnorm( xh - mean ) - pnorm( -xh - mean );
}
/** Returns the cumulative probability of a set of noncentral Chi-squared
* distributions.
* @param x the quantile
* @param ncp the noncentral parameters */
public static DoubleVector pchisq( double x, DoubleVector ncp )
{
int n = ncp.size();
DoubleVector p = new DoubleVector( n );
double mean;
double xh = Math.sqrt( x );
for( int i = 0; i < n; i++ ) {
mean = Math.sqrt( ncp.get(i) );
p.set( i, pnorm( xh - mean ) - pnorm( -xh - mean ) );
}
return p;
}
/** Returns the density of the Chi-squared distribution.
* @param x the quantile
* @return the density
*/
public static double dchisq( double x )
{
if( x == 0.0 ) return Double.POSITIVE_INFINITY;
double xh = Math.sqrt( x );
return dnorm( xh ) / xh;
}
/** Returns the density of the noncentral Chi-squared distribution.
* @param x the quantile
* @param ncp the noncentral parameter
*/
public static double dchisq( double x, double ncp )
{
if( ncp == 0.0 ) return dchisq( x );
double xh = Math.sqrt( x );
double mean = Math.sqrt( ncp );
return (dnorm( xh - mean ) + dnorm( -xh - mean)) / (2 * xh);
}
/** Returns the density of the noncentral Chi-squared distribution.
* @param x the quantile
* @param ncp the noncentral parameters
*/
public static DoubleVector dchisq( double x, DoubleVector ncp )
{
int n = ncp.size();
DoubleVector d = new DoubleVector( n );
double xh = Math.sqrt( x );
double mean;
for( int i = 0; i < n; i++ ) {
mean = Math.sqrt( ncp.get(i) );
if( ncp.get(i) == 0.0 ) d.set( i, dchisq( x ) );
else d.set( i, (dnorm( xh - mean ) + dnorm( -xh - mean)) /
(2 * xh) );
}
return d;
}
/** Returns the log-density of the noncentral Chi-square distribution.
* @param x the quantile
* @return the density
*/
public static double dchisqLog( double x )
{
if( x == 0.0) return Double.POSITIVE_INFINITY;
double xh = Math.sqrt( x );
return dnormLog( xh ) - Math.log( xh );
}
/** Returns the log-density value of a noncentral Chi-square distribution.
* @param x the quantile
* @param ncp the noncentral parameter
* @return the density */
public static double dchisqLog( double x, double ncp ) {
if( ncp == 0.0 ) return dchisqLog( x );
double xh = Math.sqrt( x );
double mean = Math.sqrt( ncp );
return Math.log( dnorm( xh - mean ) + dnorm( -xh - mean) ) -
Math.log(2 * xh);
}
/** Returns the log-density of a set of noncentral Chi-squared
* distributions.
* @param x the quantile
* @param ncp the noncentral parameters */
public static DoubleVector dchisqLog( double x, DoubleVector ncp )
{
DoubleVector dLog = new DoubleVector( ncp.size() );
double xh = Math.sqrt( x );
double mean;
for( int i = 0; i < ncp.size(); i++ ) {
mean = Math.sqrt( ncp.get(i) );
if( ncp.get(i) == 0.0 ) dLog.set( i, dchisqLog( x ) );
else dLog.set( i, Math.log( dnorm( xh - mean ) + dnorm( -xh - mean) ) -
Math.log(2 * xh) );
}
return dLog;
}
/**
* Generates a sample of a Chi-square distribution.
* @param n the size of the sample
* @param ncp the noncentral parameter
* @param random the random stream
* @return the sample
*/
public static DoubleVector rchisq( int n, double ncp, Random random )
{
DoubleVector v = new DoubleVector( n );
double mean = Math.sqrt( ncp );
double x;
for( int i = 0; i < n; i++ ) {
x = random.nextGaussian() + mean;
v.set( i, x * x );
}
return v;
}
/**
* 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/matrix/Matrix.java
|
/*
* This software is a cooperative product of The MathWorks and the National
* Institute of Standards and Technology (NIST) which has been released to the
* public domain. Neither The MathWorks nor NIST assumes any responsibility
* whatsoever for its use by other parties, and makes no guarantees, expressed
* or implied, about its quality, reliability, or any other characteristic.
*/
/*
* Matrix.java
* Copyright (C) 1999 The Mathworks and NIST and 2005 University of Waikato,
* Hamilton, New Zealand
*
*/
package weka.core.matrix;
import java.io.BufferedReader;
import java.io.LineNumberReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.Serializable;
import java.io.StreamTokenizer;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.util.Locale;
import java.util.StringTokenizer;
import weka.core.RevisionHandler;
import weka.core.RevisionUtils;
import weka.core.Utils;
/**
* Jama = Java Matrix class.
* <P>
* The Java Matrix Class provides the fundamental operations of numerical linear
* algebra. Various constructors create Matrices from two dimensional arrays of
* double precision floating point numbers. Various "gets" and "sets" provide
* access to submatrices and matrix elements. Several methods implement basic
* matrix arithmetic, including matrix addition and multiplication, matrix
* norms, and element-by-element array operations. Methods for reading and
* printing matrices are also included. All the operations in this version of
* the Matrix Class involve real matrices. Complex matrices may be handled in a
* future version.
* <P>
* Five fundamental matrix decompositions, which consist of pairs or triples of
* matrices, permutation vectors, and the like, produce results in five
* decomposition classes. These decompositions are accessed by the Matrix class
* to compute solutions of simultaneous linear equations, determinants, inverses
* and other matrix functions. The five decompositions are:
* <P>
* <UL>
* <LI>Cholesky Decomposition of symmetric, positive definite matrices.
* <LI>LU Decomposition of rectangular matrices.
* <LI>QR Decomposition of rectangular matrices.
* <LI>Singular Value Decomposition of rectangular matrices.
* <LI>Eigenvalue Decomposition of both symmetric and nonsymmetric square
* matrices.
* </UL>
* <DL>
* <DT><B>Example of use:</B></DT>
* <P>
* <DD>Solve a linear system A x = b and compute the residual norm, ||b - A x||.
* <P>
*
* <PRE>
* double[][] vals = { { 1., 2., 3 }, { 4., 5., 6. }, { 7., 8., 10. } };
* Matrix A = new Matrix(vals);
* Matrix b = Matrix.random(3, 1);
* Matrix x = A.solve(b);
* Matrix r = A.times(x).minus(b);
* double rnorm = r.normInf();
* </PRE>
*
* </DD>
* </DL>
* <p/>
* Adapted from the <a href="http://math.nist.gov/javanumerics/jama/"
* target="_blank">JAMA</a> package. Additional methods are tagged with the
* <code>@author</code> tag.
*
* @author The Mathworks and NIST
* @author Fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public class Matrix implements Cloneable, Serializable, RevisionHandler {
/** for serialization */
private static final long serialVersionUID = 7856794138418366180L;
/**
* Array for internal storage of elements.
*
* @serial internal array storage.
*/
protected double[][] A;
/**
* Row and column dimensions.
*
* @serial row dimension.
* @serial column dimension.
*/
protected int m, n;
/**
* Construct an m-by-n matrix of zeros.
*
* @param m Number of rows.
* @param n Number of colums.
*/
public Matrix(int m, int n) {
this.m = m;
this.n = n;
A = new double[m][n];
}
/**
* Construct an m-by-n constant matrix.
*
* @param m Number of rows.
* @param n Number of colums.
* @param s Fill the matrix with this scalar value.
*/
public Matrix(int m, int n, double s) {
this.m = m;
this.n = n;
A = new double[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
A[i][j] = s;
}
}
}
/**
* Construct a matrix from a 2-D array.
*
* @param A Two-dimensional array of doubles.
* @throws IllegalArgumentException All rows must have the same length
* @see #constructWithCopy
*/
public Matrix(double[][] A) {
m = A.length;
n = A[0].length;
for (int i = 0; i < m; i++) {
if (A[i].length != n) {
throw new IllegalArgumentException(
"All rows must have the same length.");
}
}
this.A = A;
}
/**
* Construct a matrix quickly without checking arguments.
*
* @param A Two-dimensional array of doubles.
* @param m Number of rows.
* @param n Number of colums.
*/
public Matrix(double[][] A, int m, int n) {
this.A = A;
this.m = m;
this.n = n;
}
/**
* Construct a matrix from a one-dimensional packed array
*
* @param vals One-dimensional array of doubles, packed by columns (ala
* Fortran).
* @param m Number of rows.
* @throws IllegalArgumentException Array length must be a multiple of m.
*/
public Matrix(double vals[], int m) {
this.m = m;
n = (m != 0 ? vals.length / m : 0);
if (m * n != vals.length) {
throw new IllegalArgumentException(
"Array length must be a multiple of m.");
}
A = new double[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
A[i][j] = vals[i + j * m];
}
}
}
/**
* 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. (FracPete: taken from old weka.core.Matrix class)
*
* @param r the reader containing the matrix
* @throws Exception if an error occurs
* @see #write(Writer)
*/
public Matrix(Reader r) throws Exception {
LineNumberReader lnr = new LineNumberReader(r);
String line;
int currentRow = -1;
while ((line = lnr.readLine()) != null) {
// Comments
if (line.startsWith("%")) {
continue;
}
StringTokenizer st = new StringTokenizer(line);
// Ignore blank lines
if (!st.hasMoreTokens()) {
continue;
}
if (currentRow < 0) {
int rows = Integer.parseInt(st.nextToken());
if (!st.hasMoreTokens()) {
throw new Exception("Line " + lnr.getLineNumber()
+ ": expected number of columns");
}
int cols = Integer.parseInt(st.nextToken());
A = new double[rows][cols];
m = rows;
n = cols;
currentRow++;
continue;
} else {
if (currentRow == getRowDimension()) {
throw new Exception("Line " + lnr.getLineNumber()
+ ": too many rows provided");
}
for (int i = 0; i < getColumnDimension(); i++) {
if (!st.hasMoreTokens()) {
throw new Exception("Line " + lnr.getLineNumber()
+ ": too few matrix elements provided");
}
set(currentRow, i, Double.valueOf(st.nextToken()).doubleValue());
}
currentRow++;
}
}
if (currentRow == -1) {
throw new Exception("Line " + lnr.getLineNumber()
+ ": expected number of rows");
} else if (currentRow != getRowDimension()) {
throw new Exception("Line " + lnr.getLineNumber()
+ ": too few rows provided");
}
}
/**
* Construct a matrix from a copy of a 2-D array.
*
* @param A Two-dimensional array of doubles.
* @throws IllegalArgumentException All rows must have the same length
*/
public static Matrix constructWithCopy(double[][] A) {
int m = A.length;
int n = A[0].length;
Matrix X = new Matrix(m, n);
double[][] C = X.getArray();
for (int i = 0; i < m; i++) {
if (A[i].length != n) {
throw new IllegalArgumentException(
"All rows must have the same length.");
}
for (int j = 0; j < n; j++) {
C[i][j] = A[i][j];
}
}
return X;
}
/**
* Make a deep copy of a matrix
*/
public Matrix copy() {
Matrix X = new Matrix(m, n);
double[][] C = X.getArray();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
C[i][j] = A[i][j];
}
}
return X;
}
/**
* Clone the Matrix object.
*/
@Override
public Object clone() {
return this.copy();
}
/**
* Access the internal two-dimensional array.
*
* @return Pointer to the two-dimensional array of matrix elements.
*/
public double[][] getArray() {
return A;
}
/**
* Copy the internal two-dimensional array.
*
* @return Two-dimensional array copy of matrix elements.
*/
public double[][] getArrayCopy() {
double[][] C = new double[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
C[i][j] = A[i][j];
}
}
return C;
}
/**
* Make a one-dimensional column packed copy of the internal array.
*
* @return Matrix elements packed in a one-dimensional array by columns.
*/
public double[] getColumnPackedCopy() {
double[] vals = new double[m * n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
vals[i + j * m] = A[i][j];
}
}
return vals;
}
/**
* Make a one-dimensional row packed copy of the internal array.
*
* @return Matrix elements packed in a one-dimensional array by rows.
*/
public double[] getRowPackedCopy() {
double[] vals = new double[m * n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
vals[i * n + j] = A[i][j];
}
}
return vals;
}
/**
* Get row dimension.
*
* @return m, the number of rows.
*/
public int getRowDimension() {
return m;
}
/**
* Get column dimension.
*
* @return n, the number of columns.
*/
public int getColumnDimension() {
return n;
}
/**
* Get a single element.
*
* @param i Row index.
* @param j Column index.
* @return A(i,j)
* @throws ArrayIndexOutOfBoundsException
*/
public double get(int i, int j) {
return A[i][j];
}
/**
* Get a submatrix.
*
* @param i0 Initial row index
* @param i1 Final row index
* @param j0 Initial column index
* @param j1 Final column index
* @return A(i0:i1,j0:j1)
* @throws ArrayIndexOutOfBoundsException Submatrix indices
*/
public Matrix getMatrix(int i0, int i1, int j0, int j1) {
Matrix X = new Matrix(i1 - i0 + 1, j1 - j0 + 1);
double[][] B = X.getArray();
try {
for (int i = i0; i <= i1; i++) {
for (int j = j0; j <= j1; j++) {
B[i - i0][j - j0] = A[i][j];
}
}
} catch (ArrayIndexOutOfBoundsException e) {
throw new ArrayIndexOutOfBoundsException("Submatrix indices");
}
return X;
}
/**
* Get a submatrix.
*
* @param r Array of row indices.
* @param c Array of column indices.
* @return A(r(:),c(:))
* @throws ArrayIndexOutOfBoundsException Submatrix indices
*/
public Matrix getMatrix(int[] r, int[] c) {
Matrix X = new Matrix(r.length, c.length);
double[][] B = X.getArray();
try {
for (int i = 0; i < r.length; i++) {
for (int j = 0; j < c.length; j++) {
B[i][j] = A[r[i]][c[j]];
}
}
} catch (ArrayIndexOutOfBoundsException e) {
throw new ArrayIndexOutOfBoundsException("Submatrix indices");
}
return X;
}
/**
* Get a submatrix.
*
* @param i0 Initial row index
* @param i1 Final row index
* @param c Array of column indices.
* @return A(i0:i1,c(:))
* @throws ArrayIndexOutOfBoundsException Submatrix indices
*/
public Matrix getMatrix(int i0, int i1, int[] c) {
Matrix X = new Matrix(i1 - i0 + 1, c.length);
double[][] B = X.getArray();
try {
for (int i = i0; i <= i1; i++) {
for (int j = 0; j < c.length; j++) {
B[i - i0][j] = A[i][c[j]];
}
}
} catch (ArrayIndexOutOfBoundsException e) {
throw new ArrayIndexOutOfBoundsException("Submatrix indices");
}
return X;
}
/**
* Get a submatrix.
*
* @param r Array of row indices.
* @param j0 Initial column index
* @param j1 Final column index
* @return A(r(:),j0:j1)
* @throws ArrayIndexOutOfBoundsException Submatrix indices
*/
public Matrix getMatrix(int[] r, int j0, int j1) {
Matrix X = new Matrix(r.length, j1 - j0 + 1);
double[][] B = X.getArray();
try {
for (int i = 0; i < r.length; i++) {
for (int j = j0; j <= j1; j++) {
B[i][j - j0] = A[r[i]][j];
}
}
} catch (ArrayIndexOutOfBoundsException e) {
throw new ArrayIndexOutOfBoundsException("Submatrix indices");
}
return X;
}
/**
* Set a single element.
*
* @param i Row index.
* @param j Column index.
* @param s A(i,j).
* @throws ArrayIndexOutOfBoundsException
*/
public void set(int i, int j, double s) {
A[i][j] = s;
}
/**
* Set a submatrix.
*
* @param i0 Initial row index
* @param i1 Final row index
* @param j0 Initial column index
* @param j1 Final column index
* @param X A(i0:i1,j0:j1)
* @throws ArrayIndexOutOfBoundsException Submatrix indices
*/
public void setMatrix(int i0, int i1, int j0, int j1, Matrix X) {
try {
for (int i = i0; i <= i1; i++) {
for (int j = j0; j <= j1; j++) {
A[i][j] = X.get(i - i0, j - j0);
}
}
} catch (ArrayIndexOutOfBoundsException e) {
throw new ArrayIndexOutOfBoundsException("Submatrix indices");
}
}
/**
* Set a submatrix.
*
* @param r Array of row indices.
* @param c Array of column indices.
* @param X A(r(:),c(:))
* @throws ArrayIndexOutOfBoundsException Submatrix indices
*/
public void setMatrix(int[] r, int[] c, Matrix X) {
try {
for (int i = 0; i < r.length; i++) {
for (int j = 0; j < c.length; j++) {
A[r[i]][c[j]] = X.get(i, j);
}
}
} catch (ArrayIndexOutOfBoundsException e) {
throw new ArrayIndexOutOfBoundsException("Submatrix indices");
}
}
/**
* Set a submatrix.
*
* @param r Array of row indices.
* @param j0 Initial column index
* @param j1 Final column index
* @param X A(r(:),j0:j1)
* @throws ArrayIndexOutOfBoundsException Submatrix indices
*/
public void setMatrix(int[] r, int j0, int j1, Matrix X) {
try {
for (int i = 0; i < r.length; i++) {
for (int j = j0; j <= j1; j++) {
A[r[i]][j] = X.get(i, j - j0);
}
}
} catch (ArrayIndexOutOfBoundsException e) {
throw new ArrayIndexOutOfBoundsException("Submatrix indices");
}
}
/**
* Set a submatrix.
*
* @param i0 Initial row index
* @param i1 Final row index
* @param c Array of column indices.
* @param X A(i0:i1,c(:))
* @throws ArrayIndexOutOfBoundsException Submatrix indices
*/
public void setMatrix(int i0, int i1, int[] c, Matrix X) {
try {
for (int i = i0; i <= i1; i++) {
for (int j = 0; j < c.length; j++) {
A[i][c[j]] = X.get(i - i0, j);
}
}
} catch (ArrayIndexOutOfBoundsException e) {
throw new ArrayIndexOutOfBoundsException("Submatrix indices");
}
}
/**
* Returns true if the matrix is symmetric. (FracPete: taken from old
* weka.core.Matrix class)
*
* @return boolean true if matrix is symmetric.
*/
public boolean isSymmetric() {
int nr = A.length, nc = A[0].length;
if (nr != nc) {
return false;
}
for (int i = 0; i < nc; i++) {
for (int j = 0; j < i; j++) {
if (A[i][j] != A[j][i]) {
return false;
}
}
}
return true;
}
/**
* returns whether the matrix is a square matrix or not.
*
* @return true if the matrix is a square matrix
*/
public boolean isSquare() {
return (getRowDimension() == getColumnDimension());
}
/**
* Matrix transpose.
*
* @return A'
*/
public Matrix transpose() {
Matrix X = new Matrix(n, m);
double[][] C = X.getArray();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
C[j][i] = A[i][j];
}
}
return X;
}
/**
* One norm
*
* @return maximum column sum.
*/
public double norm1() {
double f = 0;
for (int j = 0; j < n; j++) {
double s = 0;
for (int i = 0; i < m; i++) {
s += Math.abs(A[i][j]);
}
f = Math.max(f, s);
}
return f;
}
/**
* Two norm
*
* @return maximum singular value.
*/
public double norm2() {
return (new SingularValueDecomposition(this).norm2());
}
/**
* Infinity norm
*
* @return maximum row sum.
*/
public double normInf() {
double f = 0;
for (int i = 0; i < m; i++) {
double s = 0;
for (int j = 0; j < n; j++) {
s += Math.abs(A[i][j]);
}
f = Math.max(f, s);
}
return f;
}
/**
* Frobenius norm
*
* @return sqrt of sum of squares of all elements.
*/
public double normF() {
double f = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
f = Maths.hypot(f, A[i][j]);
}
}
return f;
}
/**
* Unary minus
*
* @return -A
*/
public Matrix uminus() {
Matrix X = new Matrix(m, n);
double[][] C = X.getArray();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
C[i][j] = -A[i][j];
}
}
return X;
}
/**
* C = A + B
*
* @param B another matrix
* @return A + B
*/
public Matrix plus(Matrix B) {
checkMatrixDimensions(B);
Matrix X = new Matrix(m, n);
double[][] C = X.getArray();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
C[i][j] = A[i][j] + B.A[i][j];
}
}
return X;
}
/**
* A = A + B
*
* @param B another matrix
* @return A + B
*/
public Matrix plusEquals(Matrix B) {
checkMatrixDimensions(B);
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
A[i][j] = A[i][j] + B.A[i][j];
}
}
return this;
}
/**
* C = A - B
*
* @param B another matrix
* @return A - B
*/
public Matrix minus(Matrix B) {
checkMatrixDimensions(B);
Matrix X = new Matrix(m, n);
double[][] C = X.getArray();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
C[i][j] = A[i][j] - B.A[i][j];
}
}
return X;
}
/**
* A = A - B
*
* @param B another matrix
* @return A - B
*/
public Matrix minusEquals(Matrix B) {
checkMatrixDimensions(B);
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
A[i][j] = A[i][j] - B.A[i][j];
}
}
return this;
}
/**
* Element-by-element multiplication, C = A.*B
*
* @param B another matrix
* @return A.*B
*/
public Matrix arrayTimes(Matrix B) {
checkMatrixDimensions(B);
Matrix X = new Matrix(m, n);
double[][] C = X.getArray();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
C[i][j] = A[i][j] * B.A[i][j];
}
}
return X;
}
/**
* Element-by-element multiplication in place, A = A.*B
*
* @param B another matrix
* @return A.*B
*/
public Matrix arrayTimesEquals(Matrix B) {
checkMatrixDimensions(B);
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
A[i][j] = A[i][j] * B.A[i][j];
}
}
return this;
}
/**
* Element-by-element right division, C = A./B
*
* @param B another matrix
* @return A./B
*/
public Matrix arrayRightDivide(Matrix B) {
checkMatrixDimensions(B);
Matrix X = new Matrix(m, n);
double[][] C = X.getArray();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
C[i][j] = A[i][j] / B.A[i][j];
}
}
return X;
}
/**
* Element-by-element right division in place, A = A./B
*
* @param B another matrix
* @return A./B
*/
public Matrix arrayRightDivideEquals(Matrix B) {
checkMatrixDimensions(B);
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
A[i][j] = A[i][j] / B.A[i][j];
}
}
return this;
}
/**
* Element-by-element left division, C = A.\B
*
* @param B another matrix
* @return A.\B
*/
public Matrix arrayLeftDivide(Matrix B) {
checkMatrixDimensions(B);
Matrix X = new Matrix(m, n);
double[][] C = X.getArray();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
C[i][j] = B.A[i][j] / A[i][j];
}
}
return X;
}
/**
* Element-by-element left division in place, A = A.\B
*
* @param B another matrix
* @return A.\B
*/
public Matrix arrayLeftDivideEquals(Matrix B) {
checkMatrixDimensions(B);
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
A[i][j] = B.A[i][j] / A[i][j];
}
}
return this;
}
/**
* Multiply a matrix by a scalar, C = s*A
*
* @param s scalar
* @return s*A
*/
public Matrix times(double s) {
Matrix X = new Matrix(m, n);
double[][] C = X.getArray();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
C[i][j] = s * A[i][j];
}
}
return X;
}
/**
* Multiply a matrix by a scalar in place, A = s*A
*
* @param s scalar
* @return replace A by s*A
*/
public Matrix timesEquals(double s) {
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
A[i][j] = s * A[i][j];
}
}
return this;
}
/**
* Linear algebraic matrix multiplication, A * B
*
* @param B another matrix
* @return Matrix product, A * B
* @throws IllegalArgumentException Matrix inner dimensions must agree.
*/
public Matrix times(Matrix B) {
if (B.m != n) {
throw new IllegalArgumentException("Matrix inner dimensions must agree.");
}
Matrix X = new Matrix(m, B.n);
double[][] C = X.getArray();
double[] Bcolj = new double[n];
for (int j = 0; j < B.n; j++) {
for (int k = 0; k < n; k++) {
Bcolj[k] = B.A[k][j];
}
for (int i = 0; i < m; i++) {
double[] Arowi = A[i];
double s = 0;
for (int k = 0; k < n; k++) {
s += Arowi[k] * Bcolj[k];
}
C[i][j] = s;
}
}
return X;
}
/**
* LU Decomposition
*
* @return LUDecomposition
* @see LUDecomposition
*/
public LUDecomposition lu() {
return new LUDecomposition(this);
}
/**
* QR Decomposition
*
* @return QRDecomposition
* @see QRDecomposition
*/
public QRDecomposition qr() {
return new QRDecomposition(this);
}
/**
* Cholesky Decomposition
*
* @return CholeskyDecomposition
* @see CholeskyDecomposition
*/
public CholeskyDecomposition chol() {
return new CholeskyDecomposition(this);
}
/**
* Singular Value Decomposition
*
* @return SingularValueDecomposition
* @see SingularValueDecomposition
*/
public SingularValueDecomposition svd() {
return new SingularValueDecomposition(this);
}
/**
* Eigenvalue Decomposition
*
* @return EigenvalueDecomposition
* @see EigenvalueDecomposition
*/
public EigenvalueDecomposition eig() {
return new EigenvalueDecomposition(this);
}
/**
* Solve A*X = B
*
* @param B right hand side
* @return solution if A is square, least squares solution otherwise
*/
public Matrix solve(Matrix B) {
return (m == n ? (new LUDecomposition(this)).solve(B)
: (new QRDecomposition(this)).solve(B));
}
/**
* Solve X*A = B, which is also A'*X' = B'
*
* @param B right hand side
* @return solution if A is square, least squares solution otherwise.
*/
public Matrix solveTranspose(Matrix B) {
return transpose().solve(B.transpose());
}
/**
* Matrix inverse or pseudoinverse
*
* @return inverse(A) if A is square, pseudoinverse otherwise.
*/
public Matrix inverse() {
return solve(identity(m, m));
}
/**
* returns the square root of the matrix, i.e., X from the equation X*X = A.<br/>
* Steps in the Calculation (see <a href=
* "http://www.mathworks.com/access/helpdesk/help/techdoc/ref/sqrtm.html"
* target="blank"><code>sqrtm</code></a> in Matlab):<br/>
* <ol>
* <li>perform eigenvalue decomposition<br/>
* [V,D]=eig(A)</li>
* <li>take the square root of all elements in D (only the ones with positive
* sign are considered for further computation)<br/>
* S=sqrt(D)</li>
* <li>calculate the root<br/>
* X=V*S/V, which can be also written as X=(V'\(V*S)')'</li>
* </ol>
* <p/>
* <b>Note:</b> since this method uses other high-level methods, it generates
* several instances of matrices. This can be problematic with large matrices.
* <p/>
* Examples:
* <ol>
* <li>
*
* <pre>
* X =
* 5 -4 1 0 0
* -4 6 -4 1 0
* 1 -4 6 -4 1
* 0 1 -4 6 -4
* 0 0 1 -4 5
*
* sqrt(X) =
* 2 -1 -0 -0 -0
* -1 2 -1 0 -0
* 0 -1 2 -1 0
* -0 0 -1 2 -1
* -0 -0 -0 -1 2
*
* Matrix m = new Matrix(new double[][]{{5,-4,1,0,0},{-4,6,-4,1,0},{1,-4,6,-4,1},{0,1,-4,6,-4},{0,0,1,-4,5}});
* </pre>
*
* </li>
* <li>
*
* <pre>
* X =
* 7 10
* 15 22
*
* sqrt(X) =
* 1.5667 1.7408
* 2.6112 4.1779
*
* Matrix m = new Matrix(new double[][]{{7, 10},{15, 22}});
* </pre>
*
* </li>
* </ol>
*
* @return sqrt(A)
*/
public Matrix sqrt() {
EigenvalueDecomposition evd;
Matrix s;
Matrix v;
Matrix d;
Matrix result;
Matrix a;
Matrix b;
int i;
int n;
result = null;
// eigenvalue decomp.
// [V, D] = eig(A) with A = this
evd = this.eig();
v = evd.getV();
d = evd.getD();
// S = sqrt of cells of D
s = new Matrix(d.getRowDimension(), d.getColumnDimension());
for (i = 0; i < s.getRowDimension(); i++) {
for (n = 0; n < s.getColumnDimension(); n++) {
s.set(i, n, StrictMath.sqrt(d.get(i, n)));
}
}
// to calculate:
// result = V*S/V
//
// with X = B/A
// and B/A = (A'\B')'
// and V=A and V*S=B
// we get
// result = (V'\(V*S)')'
//
// A*X = B
// X = A\B
// which is
// X = A.solve(B)
//
// with A=V' and B=(V*S)'
// we get
// X = V'.solve((V*S)')
// or
// result = X'
//
// which is in full length
// result = (V'.solve((V*S)'))'
a = v.inverse();
b = v.times(s).inverse();
v = null;
d = null;
evd = null;
s = null;
result = a.solve(b).inverse();
return result;
}
/**
* Performs a (ridged) linear regression. (FracPete: taken from old
* weka.core.Matrix class)
*
* @param y the dependent variable vector
* @param ridge the ridge parameter
* @return the coefficients
* @throws IllegalArgumentException if not successful
*/
public LinearRegression regression(Matrix y, double ridge) {
return new LinearRegression(this, y, ridge);
}
/**
* Performs a weighted (ridged) linear regression. (FracPete: taken from old
* weka.core.Matrix class)
*
* @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 LinearRegression regression(Matrix y, double[] w, double ridge) {
return new LinearRegression(this, y, w, ridge);
}
/**
* Matrix determinant
*
* @return determinant
*/
public double det() {
return new LUDecomposition(this).det();
}
/**
* Matrix rank
*
* @return effective numerical rank, obtained from SVD.
*/
public int rank() {
return new SingularValueDecomposition(this).rank();
}
/**
* Matrix condition (2 norm)
*
* @return ratio of largest to smallest singular value.
*/
public double cond() {
return new SingularValueDecomposition(this).cond();
}
/**
* Matrix trace.
*
* @return sum of the diagonal elements.
*/
public double trace() {
double t = 0;
for (int i = 0; i < Math.min(m, n); i++) {
t += A[i][i];
}
return t;
}
/**
* Generate matrix with random elements
*
* @param m Number of rows.
* @param n Number of colums.
* @return An m-by-n matrix with uniformly distributed random elements.
*/
public static Matrix random(int m, int n) {
Matrix A = new Matrix(m, n);
double[][] X = A.getArray();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
X[i][j] = Math.random();
}
}
return A;
}
/**
* Generate identity matrix
*
* @param m Number of rows.
* @param n Number of colums.
* @return An m-by-n matrix with ones on the diagonal and zeros elsewhere.
*/
public static Matrix identity(int m, int n) {
Matrix A = new Matrix(m, n);
double[][] X = A.getArray();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
X[i][j] = (i == j ? 1.0 : 0.0);
}
}
return A;
}
/**
* Print the matrix to stdout. Line the elements up in columns with a
* Fortran-like 'Fw.d' style format.
*
* @param w Column width.
* @param d Number of digits after the decimal.
*/
public void print(int w, int d) {
print(new PrintWriter(System.out, true), w, d);
}
/**
* Print the matrix to the output stream. Line the elements up in columns with
* a Fortran-like 'Fw.d' style format.
*
* @param output Output stream.
* @param w Column width.
* @param d Number of digits after the decimal.
*/
public void print(PrintWriter output, int w, int d) {
DecimalFormat format = new DecimalFormat();
format.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));
format.setMinimumIntegerDigits(1);
format.setMaximumFractionDigits(d);
format.setMinimumFractionDigits(d);
format.setGroupingUsed(false);
print(output, format, w + 2);
}
/**
* Print the matrix to stdout. Line the elements up in columns. Use the format
* object, and right justify within columns of width characters. Note that is
* the matrix is to be read back in, you probably will want to use a
* NumberFormat that is set to US Locale.
*
* @param format A Formatting object for individual elements.
* @param width Field width for each column.
* @see java.text.DecimalFormat#setDecimalFormatSymbols
*/
public void print(NumberFormat format, int width) {
print(new PrintWriter(System.out, true), format, width);
}
// DecimalFormat is a little disappointing coming from Fortran or C's printf.
// Since it doesn't pad on the left, the elements will come out different
// widths. Consequently, we'll pass the desired column width in as an
// argument and do the extra padding ourselves.
/**
* Print the matrix to the output stream. Line the elements up in columns. Use
* the format object, and right justify within columns of width characters.
* Note that is the matrix is to be read back in, you probably will want to
* use a NumberFormat that is set to US Locale.
*
* @param output the output stream.
* @param format A formatting object to format the matrix elements
* @param width Column width.
* @see java.text.DecimalFormat#setDecimalFormatSymbols
*/
public void print(PrintWriter output, NumberFormat format, int width) {
output.println(); // start on new line.
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
String s = format.format(A[i][j]); // format the number
int padding = Math.max(1, width - s.length()); // At _least_ 1 space
for (int k = 0; k < padding; k++) {
output.print(' ');
}
output.print(s);
}
output.println();
}
output.println(); // end with blank line.
}
/**
* Read a matrix from a stream. The format is the same the print method, so
* printed matrices can be read back in (provided they were printed using US
* Locale). Elements are separated by whitespace, all the elements for each
* row appear on a single line, the last row is followed by a blank line.
* <p/>
* Note: This format differs from the one that can be read via the
* Matrix(Reader) constructor! For that format, the write(Writer) method is
* used (from the original weka.core.Matrix class).
*
* @param input the input stream.
* @see #Matrix(Reader)
* @see #write(Writer)
*/
public static Matrix read(BufferedReader input) throws java.io.IOException {
StreamTokenizer tokenizer = new StreamTokenizer(input);
// Although StreamTokenizer will parse numbers, it doesn't recognize
// scientific notation (E or D); however, Double.valueOf does.
// The strategy here is to disable StreamTokenizer's number parsing.
// We'll only get whitespace delimited words, EOL's and EOF's.
// These words should all be numbers, for Double.valueOf to parse.
tokenizer.resetSyntax();
tokenizer.wordChars(0, 255);
tokenizer.whitespaceChars(0, ' ');
tokenizer.eolIsSignificant(true);
java.util.Vector<Object> v = new java.util.Vector<Object>();
// Ignore initial empty lines
while (tokenizer.nextToken() == StreamTokenizer.TT_EOL) {
;
}
if (tokenizer.ttype == StreamTokenizer.TT_EOF) {
throw new java.io.IOException("Unexpected EOF on matrix read.");
}
do {
v.addElement(Double.valueOf(tokenizer.sval)); // Read & store 1st row.
} while (tokenizer.nextToken() == StreamTokenizer.TT_WORD);
int n = v.size(); // Now we've got the number of columns!
double row[] = new double[n];
for (int j = 0; j < n; j++) {
row[j] = ((Double) v.elementAt(j)).doubleValue();
}
v.removeAllElements();
v.addElement(row); // Start storing rows instead of columns.
while (tokenizer.nextToken() == StreamTokenizer.TT_WORD) {
// While non-empty lines
v.addElement(row = new double[n]);
int j = 0;
do {
if (j >= n) {
throw new java.io.IOException("Row " + v.size() + " is too long.");
}
row[j++] = Double.valueOf(tokenizer.sval).doubleValue();
} while (tokenizer.nextToken() == StreamTokenizer.TT_WORD);
if (j < n) {
throw new java.io.IOException("Row " + v.size() + " is too short.");
}
}
int m = v.size(); // Now we've got the number of rows.
double[][] A = new double[m][];
v.copyInto(A); // copy the rows out of the vector
return new Matrix(A);
}
/**
* Check if size(A) == size(B)
*/
private void checkMatrixDimensions(Matrix B) {
if (B.m != m || B.n != n) {
throw new IllegalArgumentException("Matrix dimensions must agree.");
}
}
/**
* Writes out a matrix. The format can be read via the Matrix(Reader)
* constructor. (FracPete: taken from old weka.core.Matrix class)
*
* @param w the output Writer
* @throws Exception if an error occurs
* @see #Matrix(Reader)
*/
public void write(Writer w) throws Exception {
w.write("% Rows\tColumns\n");
w.write("" + getRowDimension() + "\t" + getColumnDimension() + "\n");
w.write("% Matrix elements\n");
for (int i = 0; i < getRowDimension(); i++) {
for (int j = 0; j < getColumnDimension(); j++) {
w.write("" + get(i, j) + "\t");
}
w.write("\n");
}
w.flush();
}
/**
* Converts a matrix to a string. (FracPete: taken from old weka.core.Matrix
* class)
*
* @return the converted string
*/
@Override
public String toString() {
// Determine the width required for the maximum element,
// and check for fractional display requirement.
double maxval = 0;
boolean fractional = false;
for (int i = 0; i < getRowDimension(); i++) {
for (int j = 0; j < getColumnDimension(); j++) {
double current = get(i, j);
if (current < 0) {
current *= -11;
}
if (current > maxval) {
maxval = current;
}
double fract = Math.abs(current - Math.rint(current));
if (!fractional && ((Math.log(fract) / Math.log(10)) >= -2)) {
fractional = true;
}
}
}
int width = (int) (Math.log(maxval) / Math.log(10) + (fractional ? 4 : 1));
StringBuffer text = new StringBuffer();
for (int i = 0; i < getRowDimension(); i++) {
for (int j = 0; j < getColumnDimension(); j++) {
text.append(" ").append(
Utils.doubleToString(get(i, j), width, (fractional ? 2 : 0)));
}
text.append("\n");
}
return text.toString();
}
/**
* 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() {
StringBuffer result;
int i;
int n;
result = new StringBuffer();
result.append("[");
for (i = 0; i < getRowDimension(); i++) {
if (i > 0) {
result.append("; ");
}
for (n = 0; n < getColumnDimension(); n++) {
if (n > 0) {
result.append(" ");
}
result.append(Double.toString(get(i, n)));
}
}
result.append("]");
return result.toString();
}
/**
* 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 {
StringTokenizer tokRow;
StringTokenizer tokCol;
int rows;
int cols;
Matrix result;
String cells;
// get content
cells = matlab.substring(matlab.indexOf("[") + 1, matlab.indexOf("]"))
.trim();
// determine dimenions
tokRow = new StringTokenizer(cells, ";");
rows = tokRow.countTokens();
tokCol = new StringTokenizer(tokRow.nextToken(), " ");
cols = tokCol.countTokens();
// fill matrix
result = new Matrix(rows, cols);
tokRow = new StringTokenizer(cells, ";");
rows = 0;
while (tokRow.hasMoreTokens()) {
tokCol = new StringTokenizer(tokRow.nextToken(), " ");
cols = 0;
while (tokCol.hasMoreTokens()) {
result.set(rows, cols, Double.parseDouble(tokCol.nextToken()));
cols++;
}
rows++;
}
return result;
}
/**
* 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[] args) {
Matrix I;
Matrix A;
Matrix B;
try {
// Identity
System.out.println("\nIdentity\n");
I = Matrix.identity(3, 5);
System.out.println("I(3,5)\n" + I);
// basic operations - square
System.out.println("\nbasic operations - square\n");
A = Matrix.random(3, 3);
B = Matrix.random(3, 3);
System.out.println("A\n" + A);
System.out.println("B\n" + B);
System.out.println("A'\n" + A.inverse());
System.out.println("A^T\n" + A.transpose());
System.out.println("A+B\n" + A.plus(B));
System.out.println("A*B\n" + A.times(B));
System.out.println("X from A*X=B\n" + A.solve(B));
// basic operations - non square
System.out.println("\nbasic operations - non square\n");
A = Matrix.random(2, 3);
B = Matrix.random(3, 4);
System.out.println("A\n" + A);
System.out.println("B\n" + B);
System.out.println("A*B\n" + A.times(B));
// sqrt
System.out.println("\nsqrt (1)\n");
A = new Matrix(new double[][] { { 5, -4, 1, 0, 0 }, { -4, 6, -4, 1, 0 },
{ 1, -4, 6, -4, 1 }, { 0, 1, -4, 6, -4 }, { 0, 0, 1, -4, 5 } });
System.out.println("A\n" + A);
System.out.println("sqrt(A)\n" + A.sqrt());
// sqrt
System.out.println("\nsqrt (2)\n");
A = new Matrix(new double[][] { { 7, 10 }, { 15, 22 } });
System.out.println("A\n" + A);
System.out.println("sqrt(A)\n" + A.sqrt());
System.out.println("det(A)\n" + A.det() + "\n");
// eigenvalue decomp.
System.out.println("\nEigenvalue Decomposition\n");
EigenvalueDecomposition evd = A.eig();
System.out.println("[V,D] = eig(A)");
System.out.println("- V\n" + evd.getV());
System.out.println("- D\n" + evd.getD());
// LU decomp.
System.out.println("\nLU Decomposition\n");
LUDecomposition lud = A.lu();
System.out.println("[L,U,P] = lu(A)");
System.out.println("- L\n" + lud.getL());
System.out.println("- U\n" + lud.getU());
System.out.println("- P\n" + Utils.arrayToString(lud.getPivot()) + "\n");
// regression
System.out.println("\nRegression\n");
B = new Matrix(new double[][] { { 3 }, { 2 } });
double ridge = 0.5;
double[] weights = new double[] { 0.3, 0.7 };
System.out.println("A\n" + A);
System.out.println("B\n" + B);
System.out.println("ridge = " + ridge + "\n");
System.out.println("weights = " + Utils.arrayToString(weights) + "\n");
System.out.println("A.regression(B, ridge)\n" + A.regression(B, ridge)
+ "\n");
System.out.println("A.regression(B, weights, ridge)\n"
+ A.regression(B, weights, ridge) + "\n");
// writer/reader
System.out.println("\nWriter/Reader\n");
StringWriter writer = new StringWriter();
A.write(writer);
System.out.println("A.write(Writer)\n" + writer);
A = new Matrix(new StringReader(writer.toString()));
System.out.println("A = new Matrix.read(Reader)\n" + A);
// Matlab
System.out.println("\nMatlab-Format\n");
String matlab = "[ 1 2;3 4 ]";
System.out.println("Matlab: " + matlab);
System.out.println("from Matlab:\n" + Matrix.parseMatlab(matlab));
System.out
.println("to Matlab:\n" + Matrix.parseMatlab(matlab).toMatlab());
matlab = "[1 2 3 4;3 4 5 6;7 8 9 10]";
System.out.println("Matlab: " + matlab);
System.out.println("from Matlab:\n" + Matrix.parseMatlab(matlab));
System.out.println("to Matlab:\n" + Matrix.parseMatlab(matlab).toMatlab()
+ "\n");
} catch (Exception e) {
e.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/matrix/QRDecomposition.java
|
/*
* This software is a cooperative product of The MathWorks and the National
* Institute of Standards and Technology (NIST) which has been released to the
* public domain. Neither The MathWorks nor NIST assumes any responsibility
* whatsoever for its use by other parties, and makes no guarantees, expressed
* or implied, about its quality, reliability, or any other characteristic.
*/
/*
* QRDecomposition.java
* Copyright (C) 1999 The Mathworks and NIST
*
*/
package weka.core.matrix;
import weka.core.RevisionHandler;
import weka.core.RevisionUtils;
import java.io.Serializable;
/**
* QR Decomposition.
* <P>
* For an m-by-n matrix A with m >= n, the QR decomposition is an m-by-n
* orthogonal matrix Q and an n-by-n upper triangular matrix R so that A = Q*R.
* <P>
* The QR decompostion always exists, even if the matrix does not have full
* rank, so the constructor will never fail. The primary use of the QR
* decomposition is in the least squares solution of nonsquare systems of
* simultaneous linear equations. This will fail if isFullRank() returns false.
* <p/>
* Adapted from the <a href="http://math.nist.gov/javanumerics/jama/" target="_blank">JAMA</a> package.
*
* @author The Mathworks and NIST
* @author Fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public class QRDecomposition
implements Serializable, RevisionHandler {
/** for serialization */
private static final long serialVersionUID = -5013090736132211418L;
/**
* Array for internal storage of decomposition.
* @serial internal array storage.
*/
private double[][] QR;
/**
* Row and column dimensions.
* @serial column dimension.
* @serial row dimension.
*/
private int m, n;
/**
* Array for internal storage of diagonal of R.
* @serial diagonal of R.
*/
private double[] Rdiag;
/**
* QR Decomposition, computed by Householder reflections.
* @param A Rectangular matrix
*/
public QRDecomposition(Matrix A) {
// Initialize.
QR = A.getArrayCopy();
m = A.getRowDimension();
n = A.getColumnDimension();
Rdiag = new double[n];
// Main loop.
for (int k = 0; k < n; k++) {
// Compute 2-norm of k-th column without under/overflow.
double nrm = 0;
for (int i = k; i < m; i++) {
nrm = Maths.hypot(nrm,QR[i][k]);
}
if (nrm != 0.0) {
// Form k-th Householder vector.
if (QR[k][k] < 0) {
nrm = -nrm;
}
for (int i = k; i < m; i++) {
QR[i][k] /= nrm;
}
QR[k][k] += 1.0;
// Apply transformation to remaining columns.
for (int j = k+1; j < n; j++) {
double s = 0.0;
for (int i = k; i < m; i++) {
s += QR[i][k]*QR[i][j];
}
s = -s/QR[k][k];
for (int i = k; i < m; i++) {
QR[i][j] += s*QR[i][k];
}
}
}
Rdiag[k] = -nrm;
}
}
/**
* Is the matrix full rank?
* @return true if R, and hence A, has full rank.
*/
public boolean isFullRank() {
for (int j = 0; j < n; j++) {
if (Rdiag[j] == 0)
return false;
}
return true;
}
/**
* Return the Householder vectors
* @return Lower trapezoidal matrix whose columns define the reflections
*/
public Matrix getH() {
Matrix X = new Matrix(m,n);
double[][] H = X.getArray();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (i >= j) {
H[i][j] = QR[i][j];
} else {
H[i][j] = 0.0;
}
}
}
return X;
}
/**
* Return the upper triangular factor
* @return R
*/
public Matrix getR() {
Matrix X = new Matrix(n,n);
double[][] R = X.getArray();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i < j) {
R[i][j] = QR[i][j];
} else if (i == j) {
R[i][j] = Rdiag[i];
} else {
R[i][j] = 0.0;
}
}
}
return X;
}
/**
* Generate and return the (economy-sized) orthogonal factor
* @return Q
*/
public Matrix getQ() {
Matrix X = new Matrix(m,n);
double[][] Q = X.getArray();
for (int k = n-1; k >= 0; k--) {
for (int i = 0; i < m; i++) {
Q[i][k] = 0.0;
}
Q[k][k] = 1.0;
for (int j = k; j < n; j++) {
if (QR[k][k] != 0) {
double s = 0.0;
for (int i = k; i < m; i++) {
s += QR[i][k]*Q[i][j];
}
s = -s/QR[k][k];
for (int i = k; i < m; i++) {
Q[i][j] += s*QR[i][k];
}
}
}
}
return X;
}
/**
* Least squares solution of A*X = B
* @param B A Matrix with as many rows as A and any number of columns.
* @return X that minimizes the two norm of Q*R*X-B.
* @exception IllegalArgumentException Matrix row dimensions must agree.
* @exception RuntimeException Matrix is rank deficient.
*/
public Matrix solve(Matrix B) {
if (B.getRowDimension() != m) {
throw new IllegalArgumentException("Matrix row dimensions must agree.");
}
if (!this.isFullRank()) {
throw new RuntimeException("Matrix is rank deficient.");
}
// Copy right hand side
int nx = B.getColumnDimension();
double[][] X = B.getArrayCopy();
// Compute Y = transpose(Q)*B
for (int k = 0; k < n; k++) {
for (int j = 0; j < nx; j++) {
double s = 0.0;
for (int i = k; i < m; i++) {
s += QR[i][k]*X[i][j];
}
s = -s/QR[k][k];
for (int i = k; i < m; i++) {
X[i][j] += s*QR[i][k];
}
}
}
// Solve R*X = Y;
for (int k = n-1; k >= 0; k--) {
for (int j = 0; j < nx; j++) {
X[k][j] /= Rdiag[k];
}
for (int i = 0; i < k; i++) {
for (int j = 0; j < nx; j++) {
X[i][j] -= X[k][j]*QR[i][k];
}
}
}
return (new Matrix(X,n,nx).getMatrix(0,n-1,0,nx-1));
}
/**
* 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/matrix/SingularValueDecomposition.java
|
/*
* This software is a cooperative product of The MathWorks and the National
* Institute of Standards and Technology (NIST) which has been released to the
* public domain. Neither The MathWorks nor NIST assumes any responsibility
* whatsoever for its use by other parties, and makes no guarantees, expressed
* or implied, about its quality, reliability, or any other characteristic.
*/
/*
* SingularValueDecomposition.java
* Copyright (C) 1999 The Mathworks and NIST
*
*/
package weka.core.matrix;
import weka.core.RevisionHandler;
import weka.core.RevisionUtils;
import java.io.Serializable;
/**
* Singular Value Decomposition.
* <P>
* For an m-by-n matrix A with m >= n, the singular value decomposition is an
* m-by-n orthogonal matrix U, an n-by-n diagonal matrix S, and an n-by-n
* orthogonal matrix V so that A = U*S*V'.
* <P>
* The singular values, sigma[k] = S[k][k], are ordered so that sigma[0] >=
* sigma[1] >= ... >= sigma[n-1].
* <P>
* The singular value decompostion always exists, so the constructor will never
* fail. The matrix condition number and the effective numerical rank can be
* computed from this decomposition.
* <p/>
* Adapted from the <a href="http://math.nist.gov/javanumerics/jama/" target="_blank">JAMA</a> package.
*
* @author The Mathworks and NIST
* @author Fracpete (fracpete at waikato dot ac dot nz)
* @author eibe@cs.waikato.ac.nz
* @version $Revision$
*/
public class SingularValueDecomposition
implements Serializable, RevisionHandler {
/** for serialization */
private static final long serialVersionUID = -8738089610999867951L;
/**
* Arrays for internal storage of U and V.
* @serial internal storage of U.
* @serial internal storage of V.
*/
private double[][] U, V;
/**
* Array for internal storage of singular values.
* @serial internal storage of singular values.
*/
private double[] s;
/**
* Row and column dimensions.
* @serial row dimension.
* @serial column dimension.
*/
private int m, n;
/**
* Construct the singular value decomposition
* @param Arg Rectangular matrix
*/
public SingularValueDecomposition(Matrix Arg) {
// Derived from LINPACK code.
// Initialize.
double[][] A = null;
m = Arg.getRowDimension();
n = Arg.getColumnDimension();
/* Apparently the failing cases are only a proper subset of (m<n),
so let's not throw error. Correct fix to come later?
if (m<n) {
throw new IllegalArgumentException("Jama SVD only works for m >= n"); }
*/
boolean usingTranspose = false;
if (m < n) {
// Use transpose and convert back at the end
// Otherwise m < n case may yield incorrect results (see above comment)
A = Arg.transpose().getArrayCopy();
usingTranspose = true;
int temp = m;
m = n;
n = temp;
} else {
A = Arg.getArrayCopy();
}
int nu = Math.min(m,n);
s = new double [Math.min(m+1,n)];
U = new double [m][m];
V = new double [n][n];
double[] e = new double [n];
double[] work = new double [m];
boolean wantu = true;
boolean wantv = true;
// Reduce A to bidiagonal form, storing the diagonal elements
// in s and the super-diagonal elements in e.
int nct = Math.min(m-1,n);
int nrt = Math.max(0,Math.min(n-2,m));
for (int k = 0; k < Math.max(nct,nrt); k++) {
if (k < nct) {
// Compute the transformation for the k-th column and
// place the k-th diagonal in s[k].
// Compute 2-norm of k-th column without under/overflow.
s[k] = 0;
for (int i = k; i < m; i++) {
s[k] = Maths.hypot(s[k],A[i][k]);
}
if (s[k] != 0.0) {
if (A[k][k] < 0.0) {
s[k] = -s[k];
}
for (int i = k; i < m; i++) {
A[i][k] /= s[k];
}
A[k][k] += 1.0;
}
s[k] = -s[k];
}
for (int j = k+1; j < n; j++) {
if ((k < nct) & (s[k] != 0.0)) {
// Apply the transformation.
double t = 0;
for (int i = k; i < m; i++) {
t += A[i][k]*A[i][j];
}
t = -t/A[k][k];
for (int i = k; i < m; i++) {
A[i][j] += t*A[i][k];
}
}
// Place the k-th row of A into e for the
// subsequent calculation of the row transformation.
e[j] = A[k][j];
}
if (wantu & (k < nct)) {
// Place the transformation in U for subsequent back
// multiplication.
for (int i = k; i < m; i++) {
U[i][k] = A[i][k];
}
}
if (k < nrt) {
// Compute the k-th row transformation and place the
// k-th super-diagonal in e[k].
// Compute 2-norm without under/overflow.
e[k] = 0;
for (int i = k+1; i < n; i++) {
e[k] = Maths.hypot(e[k],e[i]);
}
if (e[k] != 0.0) {
if (e[k+1] < 0.0) {
e[k] = -e[k];
}
for (int i = k+1; i < n; i++) {
e[i] /= e[k];
}
e[k+1] += 1.0;
}
e[k] = -e[k];
if ((k+1 < m) & (e[k] != 0.0)) {
// Apply the transformation.
for (int i = k+1; i < m; i++) {
work[i] = 0.0;
}
for (int j = k+1; j < n; j++) {
for (int i = k+1; i < m; i++) {
work[i] += e[j]*A[i][j];
}
}
for (int j = k+1; j < n; j++) {
double t = -e[j]/e[k+1];
for (int i = k+1; i < m; i++) {
A[i][j] += t*work[i];
}
}
}
if (wantv) {
// Place the transformation in V for subsequent
// back multiplication.
for (int i = k+1; i < n; i++) {
V[i][k] = e[i];
}
}
}
}
// Set up the final bidiagonal matrix or order p.
int p = Math.min(n,m+1);
if (nct < n) {
s[nct] = A[nct][nct];
}
if (m < p) {
s[p-1] = 0.0;
}
if (nrt+1 < p) {
e[nrt] = A[nrt][p-1];
}
e[p-1] = 0.0;
// If required, generate U.
if (wantu) {
for (int j = nct; j < nu; j++) {
for (int i = 0; i < m; i++) {
U[i][j] = 0.0;
}
U[j][j] = 1.0;
}
for (int k = nct-1; k >= 0; k--) {
if (s[k] != 0.0) {
for (int j = k+1; j < nu; j++) {
double t = 0;
for (int i = k; i < m; i++) {
t += U[i][k]*U[i][j];
}
t = -t/U[k][k];
for (int i = k; i < m; i++) {
U[i][j] += t*U[i][k];
}
}
for (int i = k; i < m; i++ ) {
U[i][k] = -U[i][k];
}
U[k][k] = 1.0 + U[k][k];
for (int i = 0; i < k-1; i++) {
U[i][k] = 0.0;
}
} else {
for (int i = 0; i < m; i++) {
U[i][k] = 0.0;
}
U[k][k] = 1.0;
}
}
}
// If required, generate V.
if (wantv) {
for (int k = n-1; k >= 0; k--) {
if ((k < nrt) & (e[k] != 0.0)) {
for (int j = k+1; j < nu; j++) {
double t = 0;
for (int i = k+1; i < n; i++) {
t += V[i][k]*V[i][j];
}
t = -t/V[k+1][k];
for (int i = k+1; i < n; i++) {
V[i][j] += t*V[i][k];
}
}
}
for (int i = 0; i < n; i++) {
V[i][k] = 0.0;
}
V[k][k] = 1.0;
}
}
// Main iteration loop for the singular values.
int pp = p-1;
int iter = 0;
double eps = Math.pow(2.0,-52.0);
double tiny = Math.pow(2.0,-966.0);
while (p > 0) {
int k,kase;
// Here is where a test for too many iterations would go.
// This section of the program inspects for
// negligible elements in the s and e arrays. On
// completion the variables kase and k are set as follows.
// kase = 1 if s(p) and e[k-1] are negligible and k<p
// kase = 2 if s(k) is negligible and k<p
// kase = 3 if e[k-1] is negligible, k<p, and
// s(k), ..., s(p) are not negligible (qr step).
// kase = 4 if e(p-1) is negligible (convergence).
for (k = p-2; k >= -1; k--) {
if (k == -1) {
break;
}
if (Math.abs(e[k]) <=
tiny + eps*(Math.abs(s[k]) + Math.abs(s[k+1]))) {
e[k] = 0.0;
break;
}
}
if (k == p-2) {
kase = 4;
} else {
int ks;
for (ks = p-1; ks >= k; ks--) {
if (ks == k) {
break;
}
double t = (ks != p ? Math.abs(e[ks]) : 0.) +
(ks != k+1 ? Math.abs(e[ks-1]) : 0.);
if (Math.abs(s[ks]) <= tiny + eps*t) {
s[ks] = 0.0;
break;
}
}
if (ks == k) {
kase = 3;
} else if (ks == p-1) {
kase = 1;
} else {
kase = 2;
k = ks;
}
}
k++;
// Perform the task indicated by kase.
switch (kase) {
// Deflate negligible s(p).
case 1: {
double f = e[p-2];
e[p-2] = 0.0;
for (int j = p-2; j >= k; j--) {
double t = Maths.hypot(s[j],f);
double cs = s[j]/t;
double sn = f/t;
s[j] = t;
if (j != k) {
f = -sn*e[j-1];
e[j-1] = cs*e[j-1];
}
if (wantv) {
for (int i = 0; i < n; i++) {
t = cs*V[i][j] + sn*V[i][p-1];
V[i][p-1] = -sn*V[i][j] + cs*V[i][p-1];
V[i][j] = t;
}
}
}
}
break;
// Split at negligible s(k).
case 2: {
double f = e[k-1];
e[k-1] = 0.0;
for (int j = k; j < p; j++) {
double t = Maths.hypot(s[j],f);
double cs = s[j]/t;
double sn = f/t;
s[j] = t;
f = -sn*e[j];
e[j] = cs*e[j];
if (wantu) {
for (int i = 0; i < m; i++) {
t = cs*U[i][j] + sn*U[i][k-1];
U[i][k-1] = -sn*U[i][j] + cs*U[i][k-1];
U[i][j] = t;
}
}
}
}
break;
// Perform one qr step.
case 3: {
// Calculate the shift.
double scale = Math.max(Math.max(Math.max(Math.max(
Math.abs(s[p-1]),Math.abs(s[p-2])),Math.abs(e[p-2])),
Math.abs(s[k])),Math.abs(e[k]));
double sp = s[p-1]/scale;
double spm1 = s[p-2]/scale;
double epm1 = e[p-2]/scale;
double sk = s[k]/scale;
double ek = e[k]/scale;
double b = ((spm1 + sp)*(spm1 - sp) + epm1*epm1)/2.0;
double c = (sp*epm1)*(sp*epm1);
double shift = 0.0;
if ((b != 0.0) | (c != 0.0)) {
shift = Math.sqrt(b*b + c);
if (b < 0.0) {
shift = -shift;
}
shift = c/(b + shift);
}
double f = (sk + sp)*(sk - sp) + shift;
double g = sk*ek;
// Chase zeros.
for (int j = k; j < p-1; j++) {
double t = Maths.hypot(f,g);
double cs = f/t;
double sn = g/t;
if (j != k) {
e[j-1] = t;
}
f = cs*s[j] + sn*e[j];
e[j] = cs*e[j] - sn*s[j];
g = sn*s[j+1];
s[j+1] = cs*s[j+1];
if (wantv) {
for (int i = 0; i < n; i++) {
t = cs*V[i][j] + sn*V[i][j+1];
V[i][j+1] = -sn*V[i][j] + cs*V[i][j+1];
V[i][j] = t;
}
}
t = Maths.hypot(f,g);
cs = f/t;
sn = g/t;
s[j] = t;
f = cs*e[j] + sn*s[j+1];
s[j+1] = -sn*e[j] + cs*s[j+1];
g = sn*e[j+1];
e[j+1] = cs*e[j+1];
if (wantu && (j < m-1)) {
for (int i = 0; i < m; i++) {
t = cs*U[i][j] + sn*U[i][j+1];
U[i][j+1] = -sn*U[i][j] + cs*U[i][j+1];
U[i][j] = t;
}
}
}
e[p-2] = f;
iter = iter + 1;
}
break;
// Convergence.
case 4: {
// Make the singular values positive.
if (s[k] <= 0.0) {
s[k] = (s[k] < 0.0 ? -s[k] : 0.0);
if (wantv) {
for (int i = 0; i <= pp; i++) {
V[i][k] = -V[i][k];
}
}
}
// Order the singular values.
while (k < pp) {
if (s[k] >= s[k+1]) {
break;
}
double t = s[k];
s[k] = s[k+1];
s[k+1] = t;
if (wantv && (k < n-1)) {
for (int i = 0; i < n; i++) {
t = V[i][k+1]; V[i][k+1] = V[i][k]; V[i][k] = t;
}
}
if (wantu && (k < m-1)) {
for (int i = 0; i < m; i++) {
t = U[i][k+1]; U[i][k+1] = U[i][k]; U[i][k] = t;
}
}
k++;
}
iter = 0;
p--;
}
break;
}
}
if (usingTranspose) {
int temp = m;
m = n;
n = temp;
double[][] tempA = U;
U = V;
V = tempA;
}
}
/**
* Return the left singular vectors
* @return U
*/
public Matrix getU() {
return new Matrix(U,m,m);
}
/**
* Return the right singular vectors
* @return V
*/
public Matrix getV() {
return new Matrix(V,n,n);
}
/**
* Return the one-dimensional array of singular values
* @return diagonal of S.
*/
public double[] getSingularValues() {
return s;
}
/**
* Return the diagonal matrix of singular values
* @return S
*/
public Matrix getS() {
Matrix X = new Matrix(m,n);
double[][] S = X.getArray();
for (int i = 0; i < Math.min(m, n); i++) {
S[i][i] = this.s[i];
}
return X;
}
/**
* Two norm
* @return max(S)
*/
public double norm2() {
return s[0];
}
/**
* Two norm condition number
* @return max(S)/min(S)
*/
public double cond() {
return s[0]/s[Math.min(m,n)-1];
}
/**
* Effective numerical matrix rank
* @return Number of nonnegligible singular values.
*/
public int rank() {
double eps = Math.pow(2.0,-52.0);
double tol = Math.max(m,n)*s[0]*eps;
int r = 0;
for (int i = 0; i < s.length; i++) {
if (s[i] > tol) {
r++;
}
}
return r;
}
/**
* 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/metastore/MetaStore.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/>.
*/
/*
* KFMetaStore
* Copyright (C) 2014 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.metastore;
import java.io.IOException;
import java.util.Set;
/**
* Interface for metastore implementations. The metastore is a simple storage
* place that can be used, as an example, for storing named configuration
* settings (e.g. general application settings, reusable database connections
* etc.).
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision$
*/
public interface MetaStore {
/**
* Get a list of all named meta stores
*
* @return a list of meta stores
* @throws IOException if a problem occurs
*/
Set<String> listMetaStores() throws IOException;
/**
* Get a list of all entries in a named store
*
* @param storeName the name of the store to get entries for
* @return a list of all entries in the named store
* @throws IOException if a problem occurs
*/
Set<String> listMetaStoreEntries(String storeName) throws IOException;
/**
* Get a list of all named entries starting with the given prefix
*
* @param storeName the name of the store to get entries for
* @param prefix the prefix with which to search for entries
* @return a list of entries
* @throws IOException if a problem occurs
*/
Set<String> listMetaStoreEntries(String storeName, String prefix)
throws IOException;
/**
* Create a named store
*
* @param storeName the name of the store to create
* @throws IOException if a problem occurs
*/
void createStore(String storeName) throws IOException;
/**
* Get a named entry from the store
*
* @param storeName the name of the store to use
* @param name the full name of the entry to retrieve
* @param clazz the expected class of the entry when deserialized
* @return the deserialized entry or null if the name does not exist in the
* store
* @throws IOException if the deserialized entry does not match the expected
* class
*/
Object getEntry(String storeName, String name, Class<?> clazz)
throws IOException;
/**
* Store a named entry
*
* @param storeName the name of the store to use
* @param name the full name of the entry to store
* @param toStore a beans compliant object to store
* @throws IOException if a problem occurs
*/
void storeEntry(String storeName, String name, Object toStore)
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/metastore/XMLFileBasedMetaStore.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/>.
*/
/*
* XMLFileBasedKFMetaStore
* Copyright (C) 2014 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.metastore;
import weka.core.ResourceUtils;
import weka.core.xml.XMLBasicSerialization;
import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
/**
* A simple default implementation of MetaStore that uses Weka's XML
* serialization mechanism to persist entries as XML files in
* ${WEKA_HOME}/wekaMetaStore
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision$
*/
public class XMLFileBasedMetaStore implements MetaStore {
/** The default location for the XML files */
public static final String DEFAULT_STORE_LOCATION =
ResourceUtils.getWekaHome().toString() + File.separator + "wekaMetaStore";
/** The current home of the store */
protected File m_storeHome = new File(DEFAULT_STORE_LOCATION);
/** True if the store home has been successfully established */
protected boolean m_storeDirOK;
/**
* Lookup for entries in the stores - just holds entry names and File paths
*/
protected Map<String, Map<String, File>> m_stores =
new LinkedHashMap<String, Map<String, File>>();
/**
* Establish the home directory for the store
*
* @throws IOException if a problem occurs
*/
protected synchronized void establishStoreHome() throws IOException {
if (m_storeDirOK) {
return;
}
if (!m_storeHome.exists()) {
if (!m_storeHome.mkdir()) {
throw new IOException("Unable to create the metastore directory: "
+ m_storeHome.toString());
}
}
if (!m_storeHome.isDirectory()) {
throw new IOException("The metastore (" + m_storeHome
+ ") seems to exist, but it isn't a directory!");
}
m_storeDirOK = true;
lockStore();
// now scan the contents
File[] contents = m_storeHome.listFiles();
for (File f : contents) {
if (f.isDirectory()) {
Map<String, File> store = new LinkedHashMap<String, File>();
m_stores.put(f.getName(), store);
File[] storeEntries = f.listFiles();
for (File se : storeEntries) {
store.put(se.getName(), se);
}
}
}
unlockStore();
}
@Override
public Set<String> listMetaStores() throws IOException {
return m_stores.keySet();
}
@Override
public Set<String> listMetaStoreEntries(String storeName) throws IOException {
establishStoreHome();
Set<String> results = new HashSet<String>();
Map<String, File> store = m_stores.get(storeName);
if (store != null) {
results.addAll(store.keySet());
}
return results;
}
@Override
public synchronized Set<String> listMetaStoreEntries(String storeName,
String prefix) throws IOException {
establishStoreHome();
Set<String> matches = new HashSet<String>();
Map<String, File> store = m_stores.get(storeName);
if (store != null) {
for (Map.Entry<String, File> e : store.entrySet()) {
if (e.getKey().startsWith(prefix)) {
matches.add(e.getKey());
}
}
}
return matches;
}
@Override
public Object getEntry(String storeName, String name, Class<?> clazz)
throws IOException {
establishStoreHome();
Map<String, File> store = m_stores.get(storeName);
if (store != null) {
if (store.containsKey(name)) {
File toLoad = store.get(name);
try {
lockStore();
XMLBasicSerialization deserializer = getSerializer();
Object loaded = deserializer.read(toLoad);
if (loaded.getClass().equals(clazz)) {
throw new IOException(
"Deserialized entry (" + loaded.getClass().getName()
+ ") was not " + "the expected class: " + clazz.getName());
}
return loaded;
} catch (Exception ex) {
throw new IOException(ex);
} finally {
unlockStore();
}
}
}
return null;
}
@Override
public void createStore(String storeName) throws IOException {
File store = new File(m_storeHome, storeName);
if (store.exists()) {
throw new IOException("Meta store '" + storeName + "' already exists!");
}
lockStore();
try {
if (!store.mkdir()) {
throw new IOException(
"Unable to create meta store '" + storeName + "'");
}
} finally {
unlockStore();
}
}
@Override
public synchronized void storeEntry(String storeName, String name,
Object toStore) throws IOException {
establishStoreHome();
Map<String, File> store = m_stores.get(storeName);
if (store == null) {
createStore(storeName);
store = new LinkedHashMap<String, File>();
m_stores.put(storeName, store);
}
File loc =
new File(m_storeHome.toString() + File.separator + storeName, name);
store.put(name, loc);
try {
lockStore();
XMLBasicSerialization serializer = getSerializer();
serializer.write(loc, toStore);
} catch (Exception ex) {
throw new IOException(ex);
} finally {
unlockStore();
}
}
/**
* Lock the store
*
* @throws IOException if a problem occurs
*/
protected void lockStore() throws IOException {
int totalWaitTime = 0;
while (true) {
File lock = new File(m_storeHome, ".lock");
if (lock.createNewFile()) {
return;
}
try {
Thread.sleep(200);
} catch (InterruptedException ex) {
throw new RuntimeException(ex);
}
totalWaitTime += 200;
if (totalWaitTime > 5000) {
throw new IOException("Unable to lock store within 5 seconds");
}
}
}
/**
* Unlocks the metastore
*/
protected void unlockStore() {
File lock = new File(m_storeHome, ".lock");
lock.delete();
}
/**
* Gets a serializer to use. Creates a subclass of
* {@code XMLBasicSerialization} that has allowed properties set for common
* option handlers.
*
* @return a serializer instance
*/
protected XMLBasicSerialization getSerializer() {
try {
XMLBasicSerialization ser = new XMLBasicSerialization() {
public void clear() throws Exception {
super.clear();
m_Properties.addAllowed(weka.classifiers.Classifier.class, "debug");
m_Properties.addAllowed(weka.classifiers.Classifier.class, "options");
m_Properties.addAllowed(weka.associations.Associator.class,
"options");
m_Properties.addAllowed(weka.clusterers.Clusterer.class, "options");
m_Properties.addAllowed(weka.filters.Filter.class, "options");
m_Properties.addAllowed(weka.core.converters.Saver.class, "options");
m_Properties.addAllowed(weka.core.converters.Loader.class, "options");
m_Properties.addAllowed(weka.attributeSelection.ASSearch.class,
"options");
m_Properties.addAllowed(weka.attributeSelection.ASEvaluation.class,
"options");
m_Properties.addAllowed(weka.core.converters.DatabaseSaver.class,
"options");
m_Properties.addAllowed(weka.core.converters.DatabaseLoader.class,
"options");
m_Properties.addAllowed(
weka.core.converters.TextDirectoryLoader.class, "options");
// we assume that classes implementing SplitEvaluator also implement
// OptionHandler
m_Properties.addAllowed(weka.experiment.SplitEvaluator.class,
"options");
// we assume that classes implementing ResultProducer also implement
// OptionHandler
m_Properties.addAllowed(weka.experiment.ResultProducer.class,
"options");
}
};
ser.setSuppressWarnings(true);
return ser;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
}
|
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/neighboursearch/BallTree.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/>.
*/
/*
* BallTree.java
* Copyright (C) 2007-2012 University of Waikato
*/
package weka.core.neighboursearch;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Vector;
import weka.core.EuclideanDistance;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.Option;
import weka.core.RevisionUtils;
import weka.core.TechnicalInformation;
import weka.core.TechnicalInformation.Field;
import weka.core.TechnicalInformation.Type;
import weka.core.TechnicalInformationHandler;
import weka.core.Utils;
import weka.core.neighboursearch.balltrees.BallNode;
import weka.core.neighboursearch.balltrees.BallTreeConstructor;
import weka.core.neighboursearch.balltrees.TopDownConstructor;
/**
<!-- globalinfo-start -->
* Class implementing the BallTree/Metric Tree algorithm for nearest neighbour search.<br/>
* The connection to dataset is only a reference. For the tree structure the indexes are stored in an array.<br/>
* See the implementing classes of different construction methods of the trees for details on its construction.<br/>
* <br/>
* For more information see also:<br/>
* <br/>
* Stephen M. Omohundro (1989). Five Balltree Construction Algorithms.<br/>
* <br/>
* Jeffrey K. Uhlmann (1991). Satisfying general proximity/similarity queries with metric trees. Information Processing Letters. 40(4):175-179.
* <p/>
<!-- globalinfo-end -->
*
<!-- technical-bibtex-start -->
* BibTeX:
* <pre>
* @techreport{Omohundro1989,
* author = {Stephen M. Omohundro},
* institution = {International Computer Science Institute},
* month = {December},
* number = {TR-89-063},
* title = {Five Balltree Construction Algorithms},
* year = {1989}
* }
*
* @article{Uhlmann1991,
* author = {Jeffrey K. Uhlmann},
* journal = {Information Processing Letters},
* month = {November},
* number = {4},
* pages = {175-179},
* title = {Satisfying general proximity/similarity queries with metric trees},
* volume = {40},
* year = {1991}
* }
* </pre>
* <p/>
<!-- technical-bibtex-end -->
*
<!-- options-start -->
* Valid options are: <p/>
*
* <pre> -C <classname and options>
* The construction method to employ. Either TopDown or BottomUp
* (default: weka.core.TopDownConstructor)</pre>
*
<!-- options-end -->
*
* @author Ashraf M. Kibriya (amk14[at-the-rate]cs[dot]waikato[dot]ac[dot]nz)
* @version $Revision$
*/
public class BallTree
extends NearestNeighbourSearch
implements TechnicalInformationHandler {
/** for serialization. */
private static final long serialVersionUID = 728763855952698328L;
/**
* The instances indices sorted inorder of appearence in the tree from left
* most leaf node to the right most leaf node.
*/
protected int[] m_InstList;
/**
* The maximum number of instances in a leaf. A node is made into a leaf if
* the number of instances in it become less than or equal to this value.
*/
protected int m_MaxInstancesInLeaf = 40;
/** Tree Stats variables. */
protected TreePerformanceStats m_TreeStats = null;
/** The root node of the BallTree. */
protected BallNode m_Root;
/** The constructor method to use to build the tree. */
protected BallTreeConstructor m_TreeConstructor = new TopDownConstructor();
/** Array holding the distances of the nearest neighbours. It is filled up
* both by nearestNeighbour() and kNearestNeighbours().
*/
protected double[] m_Distances;
/**
* Creates a new instance of BallTree.
*/
public BallTree() {
super();
if(getMeasurePerformance())
m_Stats = m_TreeStats = new TreePerformanceStats();
}
/**
* Creates a new instance of BallTree.
* It also builds the tree on supplied set of Instances.
* @param insts The instances/points on which the BallTree
* should be built on.
*/
public BallTree(Instances insts) {
super(insts);
if(getMeasurePerformance())
m_Stats = m_TreeStats = new TreePerformanceStats();
}
/**
* Returns a string describing this nearest neighbour search algorithm.
*
* @return a description of the algorithm for displaying in the
* explorer/experimenter gui
*/
public String globalInfo() {
return
"Class implementing the BallTree/Metric Tree algorithm for "
+ "nearest neighbour search.\n"
+ "The connection to dataset is only a reference. For the tree "
+ "structure the indexes are stored in an array.\n"
+ "See the implementing classes of different construction methods of "
+ "the trees for details on its construction.\n\n"
+ "For more information see also:\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;
TechnicalInformation additional;
result = new TechnicalInformation(Type.TECHREPORT);
result.setValue(Field.AUTHOR, "Stephen M. Omohundro");
result.setValue(Field.YEAR, "1989");
result.setValue(Field.TITLE, "Five Balltree Construction Algorithms");
result.setValue(Field.MONTH, "December");
result.setValue(Field.NUMBER, "TR-89-063");
result.setValue(Field.INSTITUTION, "International Computer Science Institute");
additional = result.add(Type.ARTICLE);
additional.setValue(Field.AUTHOR, "Jeffrey K. Uhlmann");
additional.setValue(Field.TITLE, "Satisfying general proximity/similarity queries with metric trees");
additional.setValue(Field.JOURNAL, "Information Processing Letters");
additional.setValue(Field.MONTH, "November");
additional.setValue(Field.YEAR, "1991");
additional.setValue(Field.NUMBER, "4");
additional.setValue(Field.VOLUME, "40");
additional.setValue(Field.PAGES, "175-179");
return result;
}
/**
* Builds the BallTree on the supplied set of
* instances/points (supplied with setInstances(Instances)
* method and referenced by the m_Instances field). This
* method should not be called by outside classes. They
* should only use setInstances(Instances) method.
*
* @throws Exception If no instances are supplied
* (m_Instances is null), or if some other error in the
* supplied BallTreeConstructor occurs while building
* the tree.
*/
protected void buildTree() throws Exception {
if(m_Instances==null)
throw new Exception("No instances supplied yet. Have to call " +
"setInstances(instances) with a set of Instances " +
"first.");
m_InstList = new int[m_Instances.numInstances()];
for(int i=0; i<m_InstList.length; i++) {
m_InstList[i] = i;
} //end for
m_DistanceFunction.setInstances(m_Instances);
m_TreeConstructor.setInstances(m_Instances);
m_TreeConstructor.setInstanceList(m_InstList);
m_TreeConstructor.setEuclideanDistanceFunction(
(EuclideanDistance)m_DistanceFunction);
m_Root = m_TreeConstructor.buildTree();
}
/**
* Returns k nearest instances in the current neighbourhood to the supplied
* instance. >k instances can be returned if there is more than one instance
* at the kth boundary (i.e. if there are more than 1 instance with the
* same distance as the kth nearest neighbour).
*
* @param target The instance to find the k nearest neighbours for.
* @param k The number of nearest neighbours to find.
* @throws Exception If the neighbours could not be found.
* @return The k nearest neighbours of the given target instance
* (>k nearest neighbours, if there are more instances that have same
* distance as the kth nearest neighbour).
*/
public Instances kNearestNeighbours(Instance target, int k) throws Exception {
MyHeap heap = new MyHeap(k);
if(m_Stats!=null)
m_Stats.searchStart();
nearestNeighbours(heap, m_Root, target, k);
if(m_Stats!=null)
m_Stats.searchFinish();
Instances neighbours = new Instances(m_Instances, heap.totalSize());
m_Distances = new double[heap.totalSize()];
int [] indices = new int[heap.totalSize()];
int i=1; MyHeapElement h;
while(heap.noOfKthNearest()>0) {
h = heap.getKthNearest();
indices[indices.length-i] = h.index;
m_Distances[indices.length-i] = h.distance;
i++;
}
while(heap.size()>0) {
h = heap.get();
indices[indices.length-i] = h.index;
m_Distances[indices.length-i] = h.distance;
i++;
}
m_DistanceFunction.postProcessDistances(m_Distances);
for(i=0; i<indices.length; i++)
neighbours.add(m_Instances.instance(indices[i]));
return neighbours; // <---Check this statement
}
/**
* Does NN search according to Moore's method.
* Should not be used by outside classes. They should instead
* use kNearestNeighbours(Instance, int).
* P.S.: The distance returned are squared. Need to post process the
* distances.
* @param heap MyHeap object to store/update NNs found during the search.
* @param node The BallNode to do the NN search on.
* @param target The target instance for which the NNs are required.
* @param k The number of NNs to find.
* @throws Exception If the structure of the BallTree is not correct,
* or if there is some problem putting NNs in the heap.
*/
protected void nearestNeighbours(MyHeap heap, BallNode node, Instance target,
int k) throws Exception{
double distance = Double.NEGATIVE_INFINITY;
if (heap.totalSize() >= k)
distance = m_DistanceFunction.distance(target, node.getPivot());
// The radius is not squared so need to take sqrt before comparison
if (distance > -0.000001
&& Math.sqrt(heap.peek().distance) < distance - node.getRadius()) {
return;
} else if (node.m_Left != null && node.m_Right != null) { // if node is not
// a leaf
if (m_TreeStats != null) {
m_TreeStats.incrIntNodeCount();
}
double leftPivotDist = Math.sqrt(m_DistanceFunction.distance(target,
node.m_Left.getPivot(), Double.POSITIVE_INFINITY));
double rightPivotDist = Math.sqrt(m_DistanceFunction.distance(target,
node.m_Right.getPivot(), Double.POSITIVE_INFINITY));
double leftBallDist = leftPivotDist - node.m_Left.getRadius();
double rightBallDist = rightPivotDist - node.m_Right.getRadius();
// if target is inside both balls then see which center is closer
if (leftBallDist < 0 && rightBallDist < 0) {
if (leftPivotDist < rightPivotDist) {
nearestNeighbours(heap, node.m_Left, target, k);
nearestNeighbours(heap, node.m_Right, target, k);
} else {
nearestNeighbours(heap, node.m_Right, target, k);
nearestNeighbours(heap, node.m_Left, target, k);
}
}
// else see which ball is closer (if dist < 0 target is inside a ball, and
// hence the ball is closer).
else {
if (leftBallDist < rightBallDist) {
nearestNeighbours(heap, node.m_Left, target, k);
nearestNeighbours(heap, node.m_Right, target, k);
} else {
nearestNeighbours(heap, node.m_Right, target, k);
nearestNeighbours(heap, node.m_Left, target, k);
}
}
} else if (node.m_Left != null || node.m_Right != null) { // invalid leaves
// assignment
throw new Exception("Error: Only one leaf of the built ball tree is " +
"assigned. Please check code.");
} else if (node.m_Left == null && node.m_Right == null) { // if node is a
// leaf
if (m_TreeStats != null) {
m_TreeStats.updatePointCount(node.numInstances());
m_TreeStats.incrLeafCount();
}
for (int i = node.m_Start; i <= node.m_End; i++) {
if (target == m_Instances.instance(m_InstList[i])) //for hold-one-out cross-validation
continue;
if (heap.totalSize() < k) {
distance = m_DistanceFunction.distance(target, m_Instances
.instance(m_InstList[i]), Double.POSITIVE_INFINITY, m_Stats);
heap.put(m_InstList[i], distance);
} else {
MyHeapElement head = heap.peek();
distance = m_DistanceFunction.distance(target,
m_Instances.instance(m_InstList[i]), head.distance, m_Stats);
if (distance < head.distance) {
heap.putBySubstitute(m_InstList[i], distance);
} else if (distance == head.distance) {
heap.putKthNearest(m_InstList[i], distance);
}
}//end else(heap.totalSize())
}
}//end else if node is a leaf
}
/**
* Returns the nearest instance in the current neighbourhood to the supplied
* instance.
*
* @param target The instance to find the nearest neighbour for.
* @throws Exception if the nearest neighbour could not be found.
* @return The nearest neighbour of the given target instance.
*/
public Instance nearestNeighbour(Instance target) throws Exception {
return kNearestNeighbours(target, 1).instance(0);
}
/**
* Returns the distances of the k nearest neighbours. The kNearestNeighbours
* or nearestNeighbour must always be called before calling this function. If
* this function is called before calling either the kNearestNeighbours or
* the nearestNeighbour, then it throws an exception. If, however, any
* one of the two functions is called at any point in the past, then no
* exception is thrown and the distances of NN(s) from the training set for
* the last supplied target instance (to either one of the nearestNeighbour
* functions) is/are returned.
*
* @return array containing the distances of the
* nearestNeighbours. The length and ordering of the
* array is the same as that of the instances returned
* by nearestNeighbour functions.
* @throws Exception if called before calling kNearestNeighbours
* or nearestNeighbours.
*/
public double[] getDistances() throws Exception {
if(m_Distances==null)
throw new Exception("No distances available. Please call either "+
"kNearestNeighbours or nearestNeighbours first.");
return m_Distances;
}
/**
* Adds one instance to the BallTree. This involves creating/updating the
* structure to reflect the newly added training instance
*
* @param ins The instance to be added. Usually the newly added instance in the
* training set.
* @throws Exception If the instance cannot be added to the tree.
*/
public void update(Instance ins) throws Exception {
addInstanceInfo(ins);
m_InstList = m_TreeConstructor.addInstance(m_Root, ins);
}
/**
* Adds the given instance's info. This implementation updates the attributes'
* range datastructures of EuclideanDistance class.
*
* @param ins The instance to add the information of. Usually this is
* the test instance supplied to update the range of
* attributes in the distance function.
*/
public void addInstanceInfo(Instance ins) {
if(m_Instances!=null)
m_DistanceFunction.update(ins);
}
/**
* Builds the BallTree based on the given set of instances.
* @param insts The insts for which the BallTree is to be
* built.
* @throws Exception If some error occurs while
* building the BallTree
*/
public void setInstances(Instances insts) throws Exception {
super.setInstances(insts);
buildTree();
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for
* displaying in the explorer/experimenter gui
*/
public String ballTreeConstructorTipText() {
return "The tree constructor being used.";
}
/**
* Returns the BallTreeConstructor currently in use.
* @return The BallTreeConstructor currently in use.
*/
public BallTreeConstructor getBallTreeConstructor() {
return m_TreeConstructor;
}
/**
* Sets the BallTreeConstructor for building the BallTree
* (default TopDownConstructor).
* @param constructor The new BallTreeConstructor.
*/
public void setBallTreeConstructor(BallTreeConstructor constructor) {
m_TreeConstructor = constructor;
}
/**
* Returns the size of the tree.
*
* @return the size of the tree
*/
public double measureTreeSize() {
return m_TreeConstructor.getNumNodes();
}
/**
* Returns the number of leaves.
*
* @return the number of leaves
*/
public double measureNumLeaves() {
return m_TreeConstructor.getNumLeaves();
}
/**
* Returns the depth of the tree.
*
* @return the number of rules
*/
public double measureMaxDepth() {
return m_TreeConstructor.getMaxDepth();
}
/**
* Returns an enumeration of the additional measure names.
*
* @return an enumeration of the measure names
*/
public Enumeration<String> enumerateMeasures() {
Vector<String> newVector = new Vector<String>();
newVector.addElement("measureTreeSize");
newVector.addElement("measureNumLeaves");
newVector.addElement("measureMaxDepth");
if (m_Stats != null) {
newVector.addAll(Collections.list(m_Stats.enumerateMeasures()));
}
return newVector.elements();
}
/**
* Returns the value of the named measure.
*
* @param additionalMeasureName the name of the measure to query for
* its value.
* @return the value of the named measure.
* @throws IllegalArgumentException if the named measure is not supported.
*/
public double getMeasure(String additionalMeasureName) {
if (additionalMeasureName.compareToIgnoreCase("measureMaxDepth") == 0) {
return measureMaxDepth();
} else if (additionalMeasureName.compareToIgnoreCase("measureTreeSize") == 0) {
return measureTreeSize();
} else if (additionalMeasureName.compareToIgnoreCase("measureNumLeaves") == 0) {
return measureNumLeaves();
} else if(m_Stats!=null) {
return m_Stats.getMeasure(additionalMeasureName);
} else {
throw new IllegalArgumentException(additionalMeasureName
+ " not supported (BallTree)");
}
}
/**
* Sets whether to calculate the performance statistics or not.
* @param measurePerformance This should be true if performance
* statistics are to be calculated.
*/
public void setMeasurePerformance(boolean measurePerformance) {
m_MeasurePerformance = measurePerformance;
if (m_MeasurePerformance) {
if (m_Stats == null)
m_Stats = m_TreeStats = new TreePerformanceStats();
} else
m_Stats = m_TreeStats = null;
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
public Enumeration<Option> listOptions() {
Vector<Option> newVector = new Vector<Option>();
newVector.addElement(new Option(
"\tThe construction method to employ. Either TopDown or BottomUp\n"
+ "\t(default: weka.core.TopDownConstructor)",
"C", 1, "-C <classname and options>"));
newVector.addAll(Collections.list(super.listOptions()));
return newVector.elements();
}
/**
* Parses a given list of options.
*
<!-- options-start -->
* Valid options are: <p/>
*
* <pre> -C <classname and options>
* The construction method to employ. Either TopDown or BottomUp
* (default: weka.core.TopDownConstructor)</pre>
*
<!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
public void setOptions(String[] options)
throws Exception {
super.setOptions(options);
String optionString = Utils.getOption('C', options);
if(optionString.length() != 0) {
String constructorSpec[] = Utils.splitOptions(optionString);
if(constructorSpec.length == 0) {
throw new Exception("Invalid BallTreeConstructor specification string.");
}
String className = constructorSpec[0];
constructorSpec[0] = "";
setBallTreeConstructor( (BallTreeConstructor)
Utils.forName( BallTreeConstructor.class,
className, constructorSpec) );
}
else {
setBallTreeConstructor(new TopDownConstructor());
}
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of KDtree.
*
* @return an array of strings suitable for passing to setOptions
*/
public String[] getOptions() {
Vector<String> result = new Vector<String>();
Collections.addAll(result, super.getOptions());
result.add("-C");
result.add(
(m_TreeConstructor.getClass().getName() + " " +
Utils.joinOptions(m_TreeConstructor.getOptions())).trim());
return result.toArray(new String[result.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/core
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/neighboursearch/CoverTree.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/>.
*/
/*
* CoverTree.java
* Copyright (C) 2006 Alina Beygelzimer and Sham Kakade and John Langford
*/
package weka.core.neighboursearch;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.Serializable;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Vector;
import weka.core.DistanceFunction;
import weka.core.EuclideanDistance;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.Option;
import weka.core.RevisionHandler;
import weka.core.RevisionUtils;
import weka.core.TechnicalInformation;
import weka.core.TechnicalInformation.Field;
import weka.core.TechnicalInformation.Type;
import weka.core.TechnicalInformationHandler;
import weka.core.Utils;
import weka.core.converters.CSVLoader;
import weka.core.neighboursearch.covertrees.Stack;
/**
* <!-- globalinfo-start --> Class implementing the CoverTree datastructure.<br/>
* The class is very much a translation of the c source code made available by
* the authors.<br/>
* <br/>
* For more information and original source code see:<br/>
* <br/>
* Alina Beygelzimer, Sham Kakade, John Langford: Cover trees for nearest
* neighbor. In: ICML'06: Proceedings of the 23rd international conference on
* Machine learning, New York, NY, USA, 97-104, 2006.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- technical-bibtex-start --> BibTeX:
*
* <pre>
* @inproceedings{Beygelzimer2006,
* address = {New York, NY, USA},
* author = {Alina Beygelzimer and Sham Kakade and John Langford},
* booktitle = {ICML'06: Proceedings of the 23rd international conference on Machine learning},
* pages = {97-104},
* publisher = {ACM Press},
* title = {Cover trees for nearest neighbor},
* year = {2006},
* location = {Pittsburgh, Pennsylvania},
* HTTP = {http://hunch.net/\~jl/projects/cover_tree/cover_tree.html}
* }
* </pre>
* <p/>
* <!-- technical-bibtex-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -B <value>
* Set base of the expansion constant
* (default = 1.3).
* </pre>
*
* <!-- options-end -->
*
* @author Alina Beygelzimer (original C++ code)
* @author Sham Kakade (original C++ code)
* @author John Langford (original C++ code)
* @author Ashraf M. Kibriya (amk14[at-the-rate]cs[dot]waikato[dot]ac[dot]nz)
* (Java port)
* @version $Revision$
*/
public class CoverTree extends NearestNeighbourSearch implements
TechnicalInformationHandler {
/** for serialization. */
private static final long serialVersionUID = 7617412821497807586L;
/**
* class representing a node of the cover tree.
*
* @author Ashraf M. Kibriya (amk14[at-the-rate]cs[dot]waikato[dot]ac[dot]nz)
* @version $Revision$
*/
public class CoverTreeNode implements Serializable, RevisionHandler {
/** for serialization. */
private static final long serialVersionUID = 1808760031169036512L;
/** Index of the instance represented by this node in the index array. */
private Integer idx;
/** The distance of the furthest descendant of the node. */
private double max_dist; // The maximum distance to any grandchild.
/** The distance to the nodes parent. */
private double parent_dist; // The distance to the parent.
/** The children of the node. */
private Stack<CoverTreeNode> children;
/** The number of children node has. */
private int num_children; // The number of children.
/** The min i that makes base^i <= max_dist. */
private int scale; // Essentially, an upper bound on the distance to any
// child.
/** Constructor for the class. */
public CoverTreeNode() {
}
/**
* Constructor.
*
* @param i The index of the Instance this node is associated with.
* @param md The distance of the furthest descendant.
* @param pd The distance of the node to its parent.
* @param childs Children of the node in a stack.
* @param numchilds The number of children of the node.
* @param s The scale/level of the node in the tree.
*/
public CoverTreeNode(Integer i, double md, double pd,
Stack<CoverTreeNode> childs, int numchilds, int s) {
idx = i;
max_dist = md;
parent_dist = pd;
children = childs;
num_children = numchilds;
scale = s;
}
/**
* Returns the instance represented by the node.
*
* @return The instance represented by the node.
*/
public Instance p() {
return m_Instances.instance(idx);
}
/**
* Returns whether if the node is a leaf or not.
*
* @return true if the node is a leaf node.
*/
public boolean isALeaf() {
return num_children == 0;
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
}
/**
* Private class holding a point's distance to the current reference point p.
*
* @author Ashraf M. Kibriya (amk14[at-the-rate]cs[dot]waikato[dot]ac[dot]nz)
* @version $Revision$
*/
private class DistanceNode implements RevisionHandler {
/**
* The last distance is to the current reference point (potential current
* parent). The previous ones are to reference points that were previously
* looked at (all potential ancestors).
*/
Stack<Double> dist;
/** The index of the instance represented by this node. */
Integer idx;
/**
* Returns the instance represent by this DistanceNode.
*
* @return The instance represented by this node.
*/
public Instance q() {
return m_Instances.instance(idx);
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
}
/** The euclidean distance function to use. */
protected EuclideanDistance m_EuclideanDistance;
{ // to make sure we have only one object of EuclideanDistance
if (m_DistanceFunction instanceof EuclideanDistance) {
m_EuclideanDistance = (EuclideanDistance) m_DistanceFunction;
} else {
m_DistanceFunction = m_EuclideanDistance = new EuclideanDistance();
}
}
/** The root node. */
protected CoverTreeNode m_Root;
/**
* Array holding the distances of the nearest neighbours. It is filled up both
* by nearestNeighbour() and kNearestNeighbours().
*/
protected double[] m_DistanceList;
/** Number of nodes in the tree. */
protected int m_NumNodes, m_NumLeaves, m_MaxDepth;
/** Tree Stats variables. */
protected TreePerformanceStats m_TreeStats = null;
/**
* The base of our expansion constant. In other words the 2 in 2^i used in
* covering tree and separation invariants of a cover tree. P.S.: In paper
* it's suggested the separation invariant is relaxed in batch construction.
*/
protected double m_Base = 1.3;
/**
* if we have base 2 then this can be viewed as 1/ln(2), which can be used
* later on to do il2*ln(d) instead of ln(d)/ln(2), to get log2(d), in
* get_scale method.
*/
protected double il2 = 1.0 / Math.log(m_Base);
/**
* default constructor.
*/
public CoverTree() {
super();
if (getMeasurePerformance()) {
m_Stats = m_TreeStats = new TreePerformanceStats();
}
}
/**
* Returns a string describing this nearest neighbour search algorithm.
*
* @return a description of the algorithm for displaying in the
* explorer/experimenter gui
*/
@Override
public String globalInfo() {
return "Class implementing the CoverTree datastructure.\n"
+ "The class is very much a translation of the c source code made "
+ "available by the authors.\n\n"
+ "For more information and original source code 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.INPROCEEDINGS);
result.setValue(Field.AUTHOR,
"Alina Beygelzimer and Sham Kakade and John Langford");
result.setValue(Field.TITLE, "Cover trees for nearest neighbor");
result
.setValue(Field.BOOKTITLE,
"ICML'06: Proceedings of the 23rd international conference on Machine learning");
result.setValue(Field.PAGES, "97-104");
result.setValue(Field.YEAR, "2006");
result.setValue(Field.PUBLISHER, "ACM Press");
result.setValue(Field.ADDRESS, "New York, NY, USA");
result.setValue(Field.LOCATION, "Pittsburgh, Pennsylvania");
result.setValue(Field.HTTP,
"http://hunch.net/~jl/projects/cover_tree/cover_tree.html");
return result;
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> newVector = new Vector<Option>();
newVector.addElement(new Option("\tSet base of the expansion constant\n"
+ "\t(default = 1.3).", "B", 1, "-B <value>"));
newVector.addAll(Collections.list(super.listOptions()));
return newVector.elements();
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -B <value>
* Set base of the expansion constant
* (default = 1.3).
* </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 {
super.setOptions(options);
String optionString = Utils.getOption('B', options);
if (optionString.length() != 0) {
setBase(Double.parseDouble(optionString));
} else {
setBase(1.3);
}
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of KDtree.
*
* @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());
result.add("-B");
result.add("" + getBase());
return result.toArray(new String[result.size()]);
}
/**
* Returns the distance/value of a given scale/level. I.e. the value of base^i
* (e.g. 2^i).
*
* @param s the level/scale
* @return base^s
*/
protected double dist_of_scale(int s) {
return Math.pow(m_Base, s);
}
/**
* Finds the scale/level of a given value. I.e. the "i" in base^i.
*
* @param d the value whose scale/level is to be determined.
* @return the scale/level of the given value.
*/
protected int get_scale(double d) {
return (int) Math.ceil(il2 * Math.log(d));
}
/**
* Creates a new internal node for a given Instance/point p.
*
* @param idx The index of the instance the node represents.
* @return Newly created CoverTreeNode.
*/
protected CoverTreeNode new_node(Integer idx) { // const point &p)
CoverTreeNode new_node = new CoverTreeNode();
new_node.idx = idx;
return new_node;
}
/**
* Creates a new leaf node for a given Instance/point p.
*
* @param idx The index of the instance this leaf node represents.
* @return Newly created leaf CoverTreeNode.
*/
protected CoverTreeNode new_leaf(Integer idx) { // (const point &p)
CoverTreeNode new_leaf = new CoverTreeNode(idx, 0.0, 0.0, null, 0, 100);
return new_leaf;
}
/**
* Returns the max distance of the reference point p in current node to it's
* children nodes.
*
* @param v The stack of DistanceNode objects.
* @return Distance of the furthest child.
*/
protected double max_set(Stack<DistanceNode> v) { // rename to
// maxChildDist
double max = 0.0;
for (int i = 0; i < v.length; i++) {
DistanceNode n = v.element(i);
if (max < n.dist.element(n.dist.length - 1).floatValue()) { // v[i].dist.last())
max = n.dist.element(n.dist.length - 1).floatValue(); // v[i].dist.last();
}
}
return max;
}
/**
* Splits a given point_set into near and far based on the given scale/level.
* All points with distance > base^max_scale would be moved to far set. In
* other words, all those points that are not covered by the next child ball
* of a point p (ball made of the same point p but of smaller radius at the
* next lower level) are removed from the supplied current point_set and put
* into far_set.
*
* @param point_set The supplied set from which all far points would be
* removed.
* @param far_set The set in which all far points having distance >
* base^max_scale would be put into.
* @param max_scale The given scale based on which the distances of points are
* judged to be far or near.
*/
protected void split(Stack<DistanceNode> point_set,
Stack<DistanceNode> far_set, int max_scale) {
int new_index = 0;
double fmax = dist_of_scale(max_scale);
for (int i = 0; i < point_set.length; i++) {
DistanceNode n = point_set.element(i);
if (n.dist.element(n.dist.length - 1).doubleValue() <= fmax) {
point_set.set(new_index++, point_set.element(i));
} else {
far_set.push(point_set.element(i)); // point_set[i]);
}
}
List<DistanceNode> l = new java.util.LinkedList<DistanceNode>();
for (int i = 0; i < new_index; i++) {
l.add(point_set.element(i));
}
// removing all and adding only the near points
point_set.clear();
point_set.addAll(l); // point_set.index=new_index;
}
/**
* Moves all the points in point_set covered by (the ball of) new_point into
* new_point_set, based on the given scale/level.
*
* @param point_set The supplied set of instances from which all points
* covered by new_point will be removed.
* @param new_point_set The set in which all points covered by new_point will
* be put into.
* @param new_point The given new point.
* @param max_scale The scale based on which distances are judged (radius of
* cover ball is calculated).
*/
protected void dist_split(Stack<DistanceNode> point_set,
Stack<DistanceNode> new_point_set, DistanceNode new_point, int max_scale) {
int new_index = 0;
double fmax = dist_of_scale(max_scale);
for (int i = 0; i < point_set.length; i++) {
double new_d = Math.sqrt(m_DistanceFunction.distance(new_point.q(),
point_set.element(i).q(), fmax * fmax));
if (new_d <= fmax) {
point_set.element(i).dist.push(new_d);
new_point_set.push(point_set.element(i));
} else {
point_set.set(new_index++, point_set.element(i));
}
}
List<DistanceNode> l = new java.util.LinkedList<DistanceNode>();
for (int i = 0; i < new_index; i++) {
l.add(point_set.element(i));
}
point_set.clear();
point_set.addAll(l);
}
/**
* Creates a cover tree recursively using batch insert method.
*
* @param p The index of the instance from which to create the first node. All
* other points will be inserted beneath this node for p.
* @param max_scale The current scale/level where the node is to be created
* (Also determines the radius of the cover balls created at this
* level).
* @param top_scale The max scale in the whole tree.
* @param point_set The set of unprocessed points from which child nodes need
* to be created.
* @param consumed_set The set of processed points from which child nodes have
* already been created. This would be used to find the radius of the
* cover ball of p.
* @return the node of cover tree created with p.
*/
protected CoverTreeNode batch_insert(Integer p, int max_scale, // current
// scale/level
int top_scale, // max scale/level for this dataset
Stack<DistanceNode> point_set, // set of points that are nearer to p
// [will also contain returned unused
// points]
Stack<DistanceNode> consumed_set) // to return the set of points that have
// been used to calc. max_dist to a
// descendent
// Stack<Stack<DistanceNode>> stack) //may not be needed
{
if (point_set.length == 0) {
CoverTreeNode leaf = new_leaf(p);
m_NumNodes++; // incrementing node count
m_NumLeaves++; // incrementing leaves count
return leaf;
} else {
double max_dist = max_set(point_set); // O(|point_set|) the max dist
// in point_set to point "p".
int next_scale = Math.min(max_scale - 1, get_scale(max_dist));
if (next_scale == Integer.MIN_VALUE) { // We have points with distance
// 0. if max_dist is 0.
Stack<CoverTreeNode> children = new Stack<CoverTreeNode>();
CoverTreeNode leaf = new_leaf(p);
children.push(leaf);
m_NumLeaves++;
m_NumNodes++; // incrementing node and leaf count
while (point_set.length > 0) {
DistanceNode tmpnode = point_set.pop();
leaf = new_leaf(tmpnode.idx);
children.push(leaf);
m_NumLeaves++;
m_NumNodes++; // incrementing node and leaf count
consumed_set.push(tmpnode);
}
CoverTreeNode n = new_node(p); // make a new node out of p and assign
m_NumNodes++; // incrementing node count
n.scale = 100; // A magic number meant to be larger than all scales.
n.max_dist = 0; // since all points have distance 0 to p
n.num_children = children.length;
n.children = children;
return n;
} else {
Stack<DistanceNode> far = new Stack<DistanceNode>();
split(point_set, far, max_scale); // O(|point_set|)
CoverTreeNode child = batch_insert(p, next_scale, top_scale, point_set,
consumed_set);
if (point_set.length == 0) { // not creating any node in this
// recursive call
// push(stack,point_set);
point_set.replaceAllBy(far); // point_set=far;
return child;
} else {
CoverTreeNode n = new_node(p);
m_NumNodes++; // incrementing node count
Stack<CoverTreeNode> children = new Stack<CoverTreeNode>();
children.push(child);
while (point_set.length != 0) { // O(|point_set| * num_children)
Stack<DistanceNode> new_point_set = new Stack<DistanceNode>();
Stack<DistanceNode> new_consumed_set = new Stack<DistanceNode>();
DistanceNode tmpnode = point_set.pop();
double new_dist = tmpnode.dist.last();
consumed_set.push(tmpnode);
// putting points closer to new_point into new_point_set (and
// removing them from point_set)
dist_split(point_set, new_point_set, tmpnode, max_scale); // O(|point_saet|)
// putting points closer to new_point into new_point_set (and
// removing them from far)
dist_split(far, new_point_set, tmpnode, max_scale); // O(|far|)
CoverTreeNode new_child = batch_insert(tmpnode.idx, next_scale,
top_scale, new_point_set, new_consumed_set);
new_child.parent_dist = new_dist;
children.push(new_child);
// putting the unused points from new_point_set back into
// point_set and far
double fmax = dist_of_scale(max_scale);
tmpnode = null;
for (int i = 0; i < new_point_set.length; i++) { // O(|new_point_set|)
tmpnode = new_point_set.element(i);
tmpnode.dist.pop();
if (tmpnode.dist.last() <= fmax) {
point_set.push(tmpnode);
} else {
far.push(tmpnode);
}
}
// putting the points consumed while recursing for new_point
// into consumed_set
tmpnode = null;
for (int i = 0; i < new_consumed_set.length; i++) { // O(|new_point_set|)
tmpnode = new_consumed_set.element(i);
tmpnode.dist.pop();
consumed_set.push(tmpnode);
}
}// end while(point_size.size!=0)
point_set.replaceAllBy(far); // point_set=far;
n.scale = top_scale - max_scale;
n.max_dist = max_set(consumed_set);
n.num_children = children.length;
n.children = children;
return n;
}// end else if(pointset!=0)
}// end else if(next_scale != -214....
}// end else if(pointset!=0)
}
/**
* Builds the tree on the given set of instances. P.S.: For internal use only.
* Outside classes should call setInstances().
*
* @param insts The instances on which to build the cover tree.
* @throws Exception If the supplied set of Instances is empty, or if there
* are missing values.
*/
protected void buildCoverTree(Instances insts) throws Exception {
if (insts.numInstances() == 0) {
throw new Exception(
"CoverTree: Empty set of instances. Cannot build tree.");
}
checkMissing(insts);
if (m_EuclideanDistance == null) {
m_DistanceFunction = m_EuclideanDistance = new EuclideanDistance(insts);
} else {
m_EuclideanDistance.setInstances(insts);
}
Stack<DistanceNode> point_set = new Stack<DistanceNode>();
Stack<DistanceNode> consumed_set = new Stack<DistanceNode>();
Instance point_p = insts.instance(0);
int p_idx = 0;
double max_dist = -1, dist = 0.0;
for (int i = 1; i < insts.numInstances(); i++) {
DistanceNode temp = new DistanceNode();
temp.dist = new Stack<Double>();
dist = Math.sqrt(m_DistanceFunction.distance(point_p, insts.instance(i),
Double.POSITIVE_INFINITY));
if (dist > max_dist) {
max_dist = dist;
insts.instance(i);
}
temp.dist.push(dist);
temp.idx = i;
point_set.push(temp);
}
max_dist = max_set(point_set);
m_Root = batch_insert(p_idx, get_scale(max_dist), get_scale(max_dist),
point_set, consumed_set);
}
/********************************* NNSearch related stuff ********************/
/**
* A class for a heap to store the nearest k neighbours to an instance. The
* heap also takes care of cases where multiple neighbours are the same
* distance away. i.e. the minimum size of the heap is k.
*
* @author Ashraf M. Kibriya (amk14[at-the-rate]cs[dot]waikato[dot]ac[dot]nz)
* @version $Revision$
*/
protected class MyHeap implements RevisionHandler {
/** the heap. */
MyHeapElement m_heap[] = null;
/**
* constructor.
*
* @param maxSize the maximum size of the heap
*/
public MyHeap(int maxSize) {
if ((maxSize % 2) == 0) {
maxSize++;
}
m_heap = new MyHeapElement[maxSize + 1];
m_heap[0] = new MyHeapElement(-1);
}
/**
* returns the size of the heap.
*
* @return the size
*/
public int size() {
return m_heap[0].index;
}
/**
* peeks at the first element.
*
* @return the first element
*/
public MyHeapElement peek() {
return m_heap[1];
}
/**
* returns the first element and removes it from the heap.
*
* @return the first element
* @throws Exception if no elements in heap
*/
public MyHeapElement get() throws Exception {
if (m_heap[0].index == 0) {
throw new Exception("No elements present in the heap");
}
MyHeapElement r = m_heap[1];
m_heap[1] = m_heap[m_heap[0].index];
m_heap[0].index--;
downheap();
return r;
}
/**
* adds the distance value to the heap.
*
* @param d the distance value
* @throws Exception if the heap gets too large
*/
public void put(double d) throws Exception {
if ((m_heap[0].index + 1) > (m_heap.length - 1)) {
throw new Exception("the number of elements cannot exceed the "
+ "initially set maximum limit");
}
m_heap[0].index++;
m_heap[m_heap[0].index] = new MyHeapElement(d);
upheap();
}
/**
* Puts an element by substituting it in place of the top most element.
*
* @param d The distance value.
* @throws Exception If distance is smaller than that of the head element.
*/
public void putBySubstitute(double d) throws Exception {
MyHeapElement head = get();
put(d);
if (head.distance == m_heap[1].distance) {
putKthNearest(head.distance);
} else if (head.distance > m_heap[1].distance) {
m_KthNearest = null;
m_KthNearestSize = 0;
initSize = 10;
} else if (head.distance < m_heap[1].distance) {
throw new Exception("The substituted element is greater than the "
+ "head element. put() should have been called "
+ "in place of putBySubstitute()");
}
}
/** the kth nearest ones. */
MyHeapElement m_KthNearest[] = null;
/** The number of kth nearest elements. */
int m_KthNearestSize = 0;
/** the initial size of the heap. */
int initSize = 10;
/**
* returns the number of k nearest.
*
* @return the number of k nearest
* @see #m_KthNearestSize
*/
public int noOfKthNearest() {
return m_KthNearestSize;
}
/**
* Stores kth nearest elements (if there are more than one).
*
* @param d the distance
*/
public void putKthNearest(double d) {
if (m_KthNearest == null) {
m_KthNearest = new MyHeapElement[initSize];
}
if (m_KthNearestSize >= m_KthNearest.length) {
initSize += initSize;
MyHeapElement temp[] = new MyHeapElement[initSize];
System.arraycopy(m_KthNearest, 0, temp, 0, m_KthNearest.length);
m_KthNearest = temp;
}
m_KthNearest[m_KthNearestSize++] = new MyHeapElement(d);
}
/**
* returns the kth nearest element or null if none there.
*
* @return the kth nearest element
*/
public MyHeapElement getKthNearest() {
if (m_KthNearestSize == 0) {
return null;
}
m_KthNearestSize--;
return m_KthNearest[m_KthNearestSize];
}
/**
* performs upheap operation for the heap to maintian its properties.
*/
protected void upheap() {
int i = m_heap[0].index;
MyHeapElement temp;
while (i > 1 && m_heap[i].distance > m_heap[i / 2].distance) {
temp = m_heap[i];
m_heap[i] = m_heap[i / 2];
i = i / 2;
m_heap[i] = temp; // this is i/2 done here to avoid another division.
}
}
/**
* performs downheap operation for the heap to maintian its properties.
*/
protected void downheap() {
int i = 1;
MyHeapElement temp;
while (((2 * i) <= m_heap[0].index && m_heap[i].distance < m_heap[2 * i].distance)
|| ((2 * i + 1) <= m_heap[0].index && m_heap[i].distance < m_heap[2 * i + 1].distance)) {
if ((2 * i + 1) <= m_heap[0].index) {
if (m_heap[2 * i].distance > m_heap[2 * i + 1].distance) {
temp = m_heap[i];
m_heap[i] = m_heap[2 * i];
i = 2 * i;
m_heap[i] = temp;
} else {
temp = m_heap[i];
m_heap[i] = m_heap[2 * i + 1];
i = 2 * i + 1;
m_heap[i] = temp;
}
} else {
temp = m_heap[i];
m_heap[i] = m_heap[2 * i];
i = 2 * i;
m_heap[i] = temp;
}
}
}
/**
* returns the total size.
*
* @return the total size
*/
public int totalSize() {
return size() + noOfKthNearest();
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
}
/**
* A class for storing data about a neighboring instance.
*
* @author Ashraf M. Kibriya (amk14[at-the-rate]cs[dot]waikato[dot]ac[dot]nz)
* @version $Revision$
*/
protected class MyHeapElement implements RevisionHandler {
/** the distance. */
public double distance;
/**
* The index of this element. Also used as the size of the heap in the first
* element.
*/
int index = 0;
/**
* constructor.
*
* @param d the distance
*/
public MyHeapElement(double d) {
distance = d;
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
}
/**
* stores a CoverTreeNode and its distance to the current query node.
*
* @author Ashraf M. Kibriya (amk14[at-the-rate]cs[dot]waikato[dot]ac[dot]nz)
* @version $Revision$
*/
private class d_node implements RevisionHandler {
/** The distance of the node's point to the query point. */
double dist;
/** The node. */
CoverTreeNode n;
/**
* Constructor.
*
* @param d The distance of the node to the query.
* @param node The node.
*/
public d_node(double d, CoverTreeNode node) {
dist = d;
n = node;
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
};
/**
* Initializes a heap with k values of the the given upper_bound.
*
* @param heap The heap to put values into.
* @param upper_bound The value to put into heap (the value with which it
* should be initialized).
* @param k The number of times upper_bound should be put into heap for
* initialization.
* @throws Exception If there is some problem in initializing the heap (if k
* > size of the heap).
*/
protected void setter(MyHeap heap, double upper_bound, final int k)
throws Exception {
if (heap.size() > 0) {
heap.m_heap[0].index = 0;
}
while (heap.size() < k) {
heap.put(upper_bound);
}
}
/**
* Replaces the current top/max value in the heap with the new one. The new
* max value should be <= the old one.
*
* @param upper_bound The heap.
* @param new_bound The new value that should replace the old top one.
* @throws Exception if the new value is greater than the old value.
*/
protected void update(MyHeap upper_bound, double new_bound) throws Exception {
upper_bound.putBySubstitute(new_bound);
}
/**
* Returns a cover set for a given level/scale. A cover set for a level
* consists of nodes whose Instances/centres are which are inside the query
* ball at that level. If no cover set exists for the given level (if it is
* the first time it is going to be used), than a new one is created.
*
* @param idx The level/scale for which the cover set is required.
* @param cover_sets The covers sets. Consists of stack of a stack of d_node
* objects.
* @return The cover set for the given level/scale.
*/
protected Stack<d_node> getCoverSet(int idx, Stack<Stack<d_node>> cover_sets) {
if (cover_sets.length <= idx) {
int i = cover_sets.length - 1;
while (i < idx) {
i++;
Stack<d_node> new_cover_set = new Stack<d_node>();
cover_sets.push(new_cover_set);
}
}
return cover_sets.element(idx);
}
/**
* Copies the contents of one zero set to the other. This is required if we
* are going to inspect child of some query node (if the queries are given in
* batch in the form of a cover tree). Only those nodes are copied to the new
* zero set that are inside the query ball of query_chi. P.S.: A zero set is a
* set of all leaf nodes that are found to be inside the query ball.
*
* @param query_chi The child node of our query node that we are going to
* inspect.
* @param new_upper_k New heap that will store the distances of the k NNs for
* query_chi.
* @param zero_set The zero set of query_chi's parent that needs to be copied.
* @param new_zero_set The new zero set of query_chi where old zero sets need
* to be copied into.
* @throws Exception If there is some problem.
*/
protected void copy_zero_set(CoverTreeNode query_chi, MyHeap new_upper_k,
Stack<d_node> zero_set, Stack<d_node> new_zero_set) throws Exception {
new_zero_set.clear();
d_node ele;
for (int i = 0; i < zero_set.length; i++) {
ele = zero_set.element(i);
double upper_dist = new_upper_k.peek().distance + query_chi.max_dist;
if (shell(ele.dist, query_chi.parent_dist, upper_dist)) {
double d = Math.sqrt(m_DistanceFunction.distance(query_chi.p(),
ele.n.p(), upper_dist * upper_dist));
if (m_TreeStats != null) {
m_TreeStats.incrPointCount();
}
if (d <= upper_dist) {
if (d < new_upper_k.peek().distance) {
update(new_upper_k, d);
}
d_node temp = new d_node(d, ele.n);
new_zero_set.push(temp);
if (m_TreeStats != null) {
m_TreeStats.incrLeafCount();
}
}// end if(d<newupperbound)
}// end if(shell(...
}// end for
}
/**
* Copies the contents of one set of cover sets to the other. It is required
* if we are going to inspect child of some query node (if the queries are
* given in batch in the form of a cover tree). For each level, only those
* nodes are copied to the new set which are inside the query ball of
* query_chi at that level.
*
* @param query_chi The child node of our query node that we are going to
* inspect.
* @param new_upper_k New heap that will store the distances of the k NNs for
* query_chi.
* @param cover_sets The cover_sets of query_chi's parent, which need to be
* copied to new_cover_sets.
* @param new_cover_sets The new set of cover_sets that need to contain
* contents of cover_sets.
* @param current_scale The scale/level we are inspecting in our cover tree.
* @param max_scale The maximum level so far possible in our search (this is
* only updated as we descend and a deeper child is found inside the
* query ball).
* @throws Exception If there is problem.
*/
protected void copy_cover_sets(CoverTreeNode query_chi, MyHeap new_upper_k,
Stack<Stack<d_node>> cover_sets, Stack<Stack<d_node>> new_cover_sets,
int current_scale, int max_scale) throws Exception {
new_cover_sets.clear();
for (; current_scale <= max_scale; current_scale++) {
d_node ele;
Stack<d_node> cover_set_currentscale = getCoverSet(current_scale,
cover_sets);
for (int i = 0; i < cover_set_currentscale.length; i++) { // ; ele != end;
// ele++) {
ele = cover_set_currentscale.element(i);
double upper_dist = new_upper_k.peek().distance + query_chi.max_dist
+ ele.n.max_dist;
if (shell(ele.dist, query_chi.parent_dist, upper_dist)) {
double d = Math.sqrt(m_DistanceFunction.distance(query_chi.p(),
ele.n.p(), upper_dist * upper_dist));
if (m_TreeStats != null) {
m_TreeStats.incrPointCount();
}
if (d <= upper_dist) {
if (d < new_upper_k.peek().distance) {
update(new_upper_k, d);
}
d_node temp = new d_node(d, ele.n);
new_cover_sets.element(current_scale).push(temp);
if (m_TreeStats != null) {
m_TreeStats.incrIntNodeCount();
}
}// end if(d<=..
}// end if(shell(...
}// end for(coverset_i)
}// end for(scales)
}
/**
* Prints the given cover sets and zero set.
*
* @param cover_sets The cover sets to print.
* @param zero_set The zero set to print.
* @param current_scale The scale/level to start printing the cover sets from.
* @param max_scale The max scale/level to print the cover sets upto.
*/
void print_cover_sets(Stack<Stack<d_node>> cover_sets,
Stack<d_node> zero_set, int current_scale, int max_scale) {
d_node ele;
println("cover set = ");
for (; current_scale <= max_scale; current_scale++) {
println("" + current_scale);
for (int i = 0; i < cover_sets.element(current_scale).length; i++) {
ele = cover_sets.element(current_scale).element(i);
CoverTreeNode n = ele.n;
println(n.p());
}
}
println("infinity");
for (int i = 0; i < zero_set.length; i++) {
ele = zero_set.element(i);
CoverTreeNode n = ele.n;
println(n.p());
}
}
/**
* Swap two nodes in a cover set.
*
* @param a The index first node.
* @param b The index of second node.
* @param cover_set The cover set in which the two nodes are.
*/
protected void SWAP(int a, int b, Stack<d_node> cover_set) {
d_node tmp = cover_set.element(a);
cover_set.set(a, cover_set.element(b));
cover_set.set(b, tmp);
}
/**
* Returns the difference of two given nodes distance to the query. It is used
* in half-sorting a cover set.
*
* @param p1 The index of first node.
* @param p2 The index of second node.
* @param cover_set The cover set containing the two given nodes.
* @return dist_to_query_of_p1 - dist_to_query_of_p2
*/
protected double compare(final int p1, final int p2, Stack<d_node> cover_set) {
return cover_set.element(p1).dist - cover_set.element(p2).dist;
}
/**
* Half-sorts a cover set, so that nodes nearer to the query are at the front.
*
* @param cover_set The cover set to sort.
*/
protected void halfsort(Stack<d_node> cover_set) {
if (cover_set.length <= 1) {
return;
}
int start = 0;
int hi = cover_set.length - 1;
int right = hi;
int left;
while (right > start) {
int mid = start + ((hi - start) >> 1);
boolean jumpover = false;
if (compare(mid, start, cover_set) < 0.0) {
SWAP(mid, start, cover_set);
}
if (compare(hi, mid, cover_set) < 0.0) {
SWAP(mid, hi, cover_set);
} else {
jumpover = true;
}
if (!jumpover && compare(mid, start, cover_set) < 0.0) {
SWAP(mid, start, cover_set);
}
;
left = start + 1;
right = hi - 1;
do {
while (compare(left, mid, cover_set) < 0.0) {
left++;
}
while (compare(mid, right, cover_set) < 0.0) {
right--;
}
if (left < right) {
SWAP(left, right, cover_set);
if (mid == left) {
mid = right;
} else if (mid == right) {
mid = left;
}
left++;
right--;
} else if (left == right) {
left++;
right--;
break;
}
} while (left <= right);
hi = right;
}
}
/**
* Function to check if a child node can be inside a query ball, without
* calculating the child node's distance to the query. This further avoids
* unnecessary distance calculation.
*
* @param parent_query_dist The distance of parent to the query
* @param child_parent_dist The distance of child to the parent.
* @param upper_bound The distance to the query of the best kth NN found so
* far.
* @return true If child can be inside the query ball.
*/
protected boolean shell(double parent_query_dist, double child_parent_dist,
double upper_bound) {
return parent_query_dist - child_parent_dist <= upper_bound;
}
/**
* This functions adds nodes for inspection at the next level during NN
* search. The internal nodes are added to one of the cover sets (at the level
* of the child node which is added) and leaf nodes are added to the zero set.
*
* An optimization to consider: Make all distance evaluations occur in
* descend.
*
* Instead of passing a cover_set, pass a stack of cover sets. The last
* element holds d_nodes with your distance. The next lower element holds a
* d_node with the distance to your query parent, next = query grand parent,
* etc..
*
* Compute distances in the presence of the tighter upper bound.
*
* @param query The query (in shape of a cover tree node, as we are doing
* batch searching).
* @param upper_k Heap containing distances of best k-NNs found so far.
* @param current_scale The current scale/level being looked at in the tree.
* @param max_scale The max scale/level that has so far been looked at.
* @param cover_sets The cover sets of tree nodes for each level of our trees
* for.
* @param zero_set The set containing leaf nodes.
* @return A new max_scale, if we descend to a deeper level.
* @throws Exception If there is some problem (in updating the heap upper_k).
*/
protected int descend(final CoverTreeNode query, MyHeap upper_k,
int current_scale, int max_scale, // amk14comment: make sure this gets
// passed by reference in Java
Stack<Stack<d_node>> cover_sets, // amk14comment: contains children in
// set Q in paper
Stack<d_node> zero_set) // amk14comment: zeroset contains the children at
// the lowest level i.e. -infinity
throws Exception {
d_node parent;
Stack<d_node> cover_set_currentscale = getCoverSet(current_scale,
cover_sets);
for (int i = 0; i < cover_set_currentscale.length; i++) {
parent = cover_set_currentscale.element(i);
CoverTreeNode par = parent.n;
double upper_dist = upper_k.peek().distance + query.max_dist
+ query.max_dist; // *upper_bound + query->max_dist + query->max_dist;
if (parent.dist <= upper_dist + par.max_dist) {
CoverTreeNode chi;
if (par == m_Root && par.num_children == 0) {
// only one root(which is
// also leaf) node
chi = par;
} else {
chi = par.children.element(0);
}
if (parent.dist <= upper_dist + chi.max_dist) { // amk14comment: looking
// at child_0 (which is
// the parent itself)
if (chi.num_children > 0) {
if (max_scale < chi.scale) {
max_scale = chi.scale;
}
d_node temp = new d_node(parent.dist, chi);
getCoverSet(chi.scale, cover_sets).push(temp);
if (m_TreeStats != null) {
m_TreeStats.incrIntNodeCount();
}
} else if (parent.dist <= upper_dist) {
d_node temp = new d_node(parent.dist, chi);
zero_set.push(temp);
if (m_TreeStats != null) {
m_TreeStats.incrLeafCount();
}
}
}
for (int c = 1; c < par.num_children; c++) {
chi = par.children.element(c);
double upper_chi = upper_k.peek().distance + chi.max_dist
+ query.max_dist + query.max_dist; // *upper_bound + chi.max_dist
// + query.max_dist +
// query.max_dist;
if (shell(parent.dist, chi.parent_dist, upper_chi)) { // amk14comment:parent_query_dist
// -
// child_parent_dist
// <= upper_chi
// - if child
// can be
// inside the
// shrunk query
// ball
// NOT the same as above parent->dist <= upper_dist + chi->max_dist
double d = Math.sqrt(m_DistanceFunction.distance(query.p(),
chi.p(), upper_chi * upper_chi, m_TreeStats));
if (m_TreeStats != null) {
m_TreeStats.incrPointCount();
}
if (d <= upper_chi) { // if child is inside the shrunk query ball
if (d < upper_k.peek().distance) {
update(upper_k, d);
}
if (chi.num_children > 0) {
if (max_scale < chi.scale) {
max_scale = chi.scale;
}
d_node temp = new d_node(d, chi);
getCoverSet(chi.scale, cover_sets).push(temp);
if (m_TreeStats != null) {
m_TreeStats.incrIntNodeCount();
}
} else if (d <= upper_chi - chi.max_dist) {
d_node temp = new d_node(d, chi);
zero_set.push(temp);
if (m_TreeStats != null) {
m_TreeStats.incrLeafCount();
}
}
}// end if(d<=upper_chi)
}// end if(shell(parent.dist,...
}// end for(child_1 to n)
}// end if(parent.dist<=upper_dist..
}// end for(covers_sets[current_scale][i])
return max_scale;
}
/**
* Does a brute force NN search on the nodes in the given zero set. A zero set
* might have some nodes added to it that were not k-NNs, so need to do a
* brute-force to pick only the k-NNs (without calculating distances, as each
* node in the zero set already had its distance calculated to the query,
* which is stored with the node).
*
* @param k The k in kNN.
* @param query The query.
* @param zero_set The zero set on which the brute force NN search is
* performed.
* @param upper_k The heap storing distances of k-NNs found during the search.
* @param results The returned k-NNs.
* @throws Exception If there is somem problem.
*/
protected void brute_nearest(final int k, final CoverTreeNode query,
Stack<d_node> zero_set, MyHeap upper_k, Stack<NeighborList> results)
throws Exception {
if (query.num_children > 0) {
Stack<d_node> new_zero_set = new Stack<d_node>();
CoverTreeNode query_chi = query.children.element(0);
brute_nearest(k, query_chi, zero_set, upper_k, results);
MyHeap new_upper_k = new MyHeap(k);
for (int i = 1; i < query.children.length; i++) {
query_chi = query.children.element(i);
setter(new_upper_k, upper_k.peek().distance + query_chi.parent_dist, k);
copy_zero_set(query_chi, new_upper_k, zero_set, new_zero_set);
brute_nearest(k, query_chi, new_zero_set, new_upper_k, results);
}
} else {
NeighborList temp = new NeighborList(k);
d_node ele;
for (int i = 0; i < zero_set.length; i++) {
ele = zero_set.element(i);
if (ele.dist <= upper_k.peek().distance) {
temp.insertSorted(ele.dist, ele.n.p()); // temp.push(ele.n.p());
}
}
results.push(temp);
}
}
/**
* Performs a recursive k-NN search for a given batch of queries provided in
* the form of a cover tree. P.S.: This function should not be called from
* outside. Outside classes should use kNearestNeighbours() instead.
*
* @param k The number of NNs to find.
* @param query_node The node of the query tree to start the search from.
* @param cover_sets The set of sets that contains internal nodes that were
* found to be inside the query ball at previous scales/levels
* (intially there would be just the root node at root level).
* @param zero_set The set that'll contain the leaf nodes that are found to be
* inside the query ball.
* @param current_scale The level/scale to do the search from (this value
* would be used to inspect the cover set in the provided set of
* cover sets).
* @param max_scale The max scale/level that has so far been inspected.
* @param upper_k The heap containing distances of the best k-NNs found so far
* (initialized to Double.POSITIVE_INFINITY).
* @param results The list of returned k-NNs.
* @throws Exception If there is some problem during the search.
*/
protected void internal_batch_nearest_neighbor(final int k,
final CoverTreeNode query_node, Stack<Stack<d_node>> cover_sets,
Stack<d_node> zero_set, int current_scale, int max_scale, MyHeap upper_k,
Stack<NeighborList> results) throws Exception {
if (current_scale > max_scale) { // All remaining points are in the zero
// set.
brute_nearest(k, query_node, zero_set, upper_k, results);
} else {
// Our query_node has too much scale. Reduce.
if (query_node.scale <= current_scale && query_node.scale != 100) { // amk14comment:if
// j>=i
// in
// paper
CoverTreeNode query_chi;
Stack<d_node> new_zero_set = new Stack<d_node>();
Stack<Stack<d_node>> new_cover_sets = new Stack<Stack<d_node>>();
MyHeap new_upper_k = new MyHeap(k);
for (int i = 1; i < query_node.num_children; i++) { // processing
// child_1 and
// onwards
query_chi = query_node.children.element(i);
setter(new_upper_k, upper_k.peek().distance + query_chi.parent_dist,
k);
// copy the zero set that satisfy a certain bound to the new zero set
copy_zero_set(query_chi, new_upper_k, zero_set, new_zero_set);
// copy the coversets[current_scale] nodes that satisfy a certain
// bound to the new_cover_sets[current_scale]
copy_cover_sets(query_chi, new_upper_k, cover_sets, new_cover_sets,
current_scale, max_scale);
// search for the query_node child in the nodes nearer to it.
internal_batch_nearest_neighbor(k, query_chi, new_cover_sets,
new_zero_set, current_scale, max_scale, new_upper_k, results);
}
new_cover_sets = null;
new_zero_set = null;
new_upper_k = null;
// now doing child_0 //which is the parent itself, that's why we don't
// need new_zero_set or new_cover_sets
internal_batch_nearest_neighbor(k, query_node.children.element(0),
cover_sets, zero_set, current_scale, max_scale, upper_k, results);
} else { // reduce cover set scale -- amk14comment: if j<i in paper
Stack<d_node> cover_set_i = getCoverSet(current_scale, cover_sets);
// println("sorting");
halfsort(cover_set_i);
max_scale = descend(query_node, upper_k, current_scale, max_scale,
cover_sets, zero_set);
cover_set_i.clear();
current_scale++;
internal_batch_nearest_neighbor(k, query_node, cover_sets, zero_set,
current_scale, max_scale, upper_k, results);
}
}
}
/**
* Performs k-NN search for a batch of queries provided in the form of a cover
* tree. P.S.: Outside classes should call kNearestNeighbours().
*
* @param k The number of k-NNs to find.
* @param tree_root The root of the cover tree on which k-NN search is to be
* performed.
* @param query_root The root of the cover tree consisting of queries.
* @param results The list of returned k-NNs.
* @throws Exception If there is some problem during the search.
*/
protected void batch_nearest_neighbor(final int k, CoverTreeNode tree_root,
CoverTreeNode query_root, Stack<NeighborList> results) throws Exception {
// amk14comment: These contain the covering nodes at each level
Stack<Stack<d_node>> cover_sets = new Stack<Stack<d_node>>(100);
// amk14comment: These contain the nodes thought to be nearest at the leaf
// level
Stack<d_node> zero_set = new Stack<d_node>();
MyHeap upper_k = new MyHeap(k);
// probably not needed //amk14comment:initializes the array to MAXFLOAT
setter(upper_k, Double.POSITIVE_INFINITY, k);
// amk14comment:distance from top query point to top node point
double treeroot_to_query_dist = Math.sqrt(m_DistanceFunction.distance(
query_root.p(), tree_root.p(), Double.POSITIVE_INFINITY));
// amk14comment:probably stores the kth smallest distances encountered so
// far
update(upper_k, treeroot_to_query_dist);
d_node temp = new d_node(treeroot_to_query_dist, tree_root);
getCoverSet(0, cover_sets).push(temp);
// incrementing counts for the root node
if (m_TreeStats != null) {
m_TreeStats.incrPointCount();
if (tree_root.num_children > 0) {
m_TreeStats.incrIntNodeCount();
} else {
m_TreeStats.incrLeafCount();
}
}
internal_batch_nearest_neighbor(k, query_root, cover_sets, zero_set, 0, 0,
upper_k, results);
}
/**
* Performs k-NN serach for a single given query/test Instance.
*
* @param target The query/test instance.
* @param k Number of k-NNs to find.
* @return List of k-NNs.
* @throws Exception If there is some problem during the search for k-NNs.
*/
protected NeighborList findKNearest(final Instance target, final int k)
throws Exception {
Stack<d_node> cover_set_current = new Stack<d_node>(), cover_set_next, zero_set = new Stack<d_node>();
CoverTreeNode parent, child;
d_node par;
MyHeap upper_k = new MyHeap(k);
double d = Math.sqrt(m_DistanceFunction.distance(m_Root.p(), target,
Double.POSITIVE_INFINITY, m_TreeStats)), upper_bound;
cover_set_current.push(new d_node(d, m_Root));
setter(upper_k, Double.POSITIVE_INFINITY, k);
this.update(upper_k, d);
// updating stats for the root node
if (m_TreeStats != null) {
if (m_Root.num_children > 0) {
m_TreeStats.incrIntNodeCount();
} else {
m_TreeStats.incrLeafCount();
}
m_TreeStats.incrPointCount();
}
// if root is the only node
if (m_Root.num_children == 0) {
NeighborList list = new NeighborList(k);
list.insertSorted(d, m_Root.p());
return list;
}
// else
while (cover_set_current.length > 0) {
cover_set_next = new Stack<d_node>();
for (int i = 0; i < cover_set_current.length; i++) {
par = cover_set_current.element(i);
parent = par.n;
for (int c = 0; c < parent.num_children; c++) {
child = parent.children.element(c);
upper_bound = upper_k.peek().distance;
if (c == 0) {
d = par.dist;
} else {
d = upper_bound + child.max_dist;
d = Math.sqrt(m_DistanceFunction.distance(child.p(), target, d * d,
m_TreeStats));
if (m_TreeStats != null) {
m_TreeStats.incrPointCount();
}
}
if (d <= (upper_bound + child.max_dist)) {
if (c > 0 && d < upper_bound) {
update(upper_k, d);
}
if (child.num_children > 0) {
cover_set_next.push(new d_node(d, child));
if (m_TreeStats != null) {
m_TreeStats.incrIntNodeCount();
}
} else if (d <= upper_bound) {
zero_set.push(new d_node(d, child));
if (m_TreeStats != null) {
m_TreeStats.incrLeafCount();
}
}
}
} // end for current_set children
} // end for current_set elements
cover_set_current = cover_set_next;
} // end while(curret_set not empty)
NeighborList list = new NeighborList(k);
d_node tmpnode;
upper_bound = upper_k.peek().distance;
for (int i = 0; i < zero_set.length; i++) {
tmpnode = zero_set.element(i);
if (tmpnode.dist <= upper_bound) {
list.insertSorted(tmpnode.dist, tmpnode.n.p());
}
}
if (list.currentLength() <= 0) {
throw new Exception("Error: No neighbour found. This cannot happen");
}
return list;
}
/********************************* NNSearch related stuff above. ********************/
/**
* Returns k-NNs of a given target instance, from among the previously
* supplied training instances (supplied through setInstances method) P.S.:
* May return more than k-NNs if more one instances have the same distance to
* the target as the kth NN.
*
* @param target The instance for which k-NNs are required.
* @param k The number of k-NNs to find.
* @return The k-NN instances of the given target instance.
* @throws Exception If there is some problem find the k-NNs.
*/
@Override
public Instances kNearestNeighbours(Instance target, int k) throws Exception {
if (m_Stats != null) {
m_Stats.searchStart();
}
CoverTree querytree = new CoverTree();
Instances insts = new Instances(m_Instances, 0);
insts.add(target);
querytree.setInstances(insts);
Stack<NeighborList> result = new Stack<NeighborList>();
batch_nearest_neighbor(k, this.m_Root, querytree.m_Root, result);
if (m_Stats != null) {
m_Stats.searchFinish();
}
insts = new Instances(m_Instances, 0);
NeighborNode node = result.element(0).getFirst();
m_DistanceList = new double[result.element(0).currentLength()];
int i = 0;
while (node != null) {
insts.add(node.m_Instance);
m_DistanceList[i] = node.m_Distance;
i++;
node = node.m_Next;
}
return insts;
}
/**
* Returns the NN instance of a given target instance, from among the
* previously supplied training instances.
*
* @param target The instance for which NN is required.
* @throws Exception If there is some problem finding the nearest neighbour.
* @return The NN instance of the target instance.
*/
@Override
public Instance nearestNeighbour(Instance target) throws Exception {
return kNearestNeighbours(target, 1).instance(0);
}
/**
* Returns the distances of the (k)-NN(s) found earlier by
* kNearestNeighbours()/nearestNeighbour().
*
* @throws Exception If the tree hasn't been built (by calling
* setInstances()), or none of kNearestNeighbours() or
* nearestNeighbour() has been called before.
* @return The distances (in the same order) of the k-NNs.
*/
@Override
public double[] getDistances() throws Exception {
if (m_Instances == null || m_DistanceList == null) {
throw new Exception("The tree has not been supplied with a set of "
+ "instances or getDistances() has been called "
+ "before calling kNearestNeighbours().");
}
return m_DistanceList;
}
/**
* Checks if there is any instance with missing values. Throws an exception if
* there is, as KDTree does not handle missing values.
*
* @param instances the instances to check
* @throws Exception if missing values are encountered
*/
protected void checkMissing(Instances instances) throws Exception {
for (int i = 0; i < instances.numInstances(); i++) {
Instance ins = instances.instance(i);
for (int j = 0; j < ins.numValues(); j++) {
if (ins.index(j) != ins.classIndex()) {
if (ins.isMissingSparse(j)) {
throw new Exception("ERROR: KDTree can not deal with missing "
+ "values. Please run ReplaceMissingValues filter "
+ "on the dataset before passing it on to the KDTree.");
}
}
}
}
}
/**
* Builds the Cover Tree on the given set of instances.
*
* @param instances The insts on which the Cover Tree is to be built.
* @throws Exception If some error occurs while building the Cover Tree
*/
@Override
public void setInstances(Instances instances) throws Exception {
super.setInstances(instances);
buildCoverTree(instances);
}
/**
* Adds an instance to the cover tree. P.S.: The current version doesn't allow
* addition of instances after batch construction.
*
* @param ins The instance to add.
* @throws Exception Alway throws this, as current implementation doesn't
* allow addition of instances after building.
*/
@Override
public void update(Instance ins) throws Exception {
throw new Exception("BottomUpConstruction method does not allow addition "
+ "of new Instances.");
}
/**
* Adds the given instance info. This implementation updates only the range
* datastructures of the EuclideanDistance. Nothing is required to be updated
* in the built Cover Tree.
*
* @param ins The instance to add the information of. Usually this is the test
* instance supplied to update the range of attributes in the
* distance function.
*/
@Override
public void addInstanceInfo(Instance ins) {
if (m_Instances != null) {
try {
m_DistanceFunction.update(ins);
} catch (Exception ex) {
ex.printStackTrace();
}
} else if (m_Instances == null) {
throw new IllegalStateException(
"No instances supplied yet. Cannot update without"
+ "supplying a set of instances first.");
}
}
/**
* Sets the distance function to use for nearest neighbour search. Currently
* only EuclideanDistance is supported.
*
* @param df the distance function to use
* @throws Exception if not EuclideanDistance
*/
@Override
public void setDistanceFunction(DistanceFunction df) throws Exception {
if (!(df instanceof EuclideanDistance)) {
throw new Exception("CoverTree currently only works with "
+ "EuclideanDistanceFunction.");
}
m_DistanceFunction = m_EuclideanDistance = (EuclideanDistance) df;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String baseTipText() {
return "The base for the expansion constant.";
}
/**
* Returns the base in use for expansion constant.
*
* @return base currently in use.
*/
public double getBase() {
return m_Base;
}
/**
* Sets the base to use for expansion constant. The 2 in 2^i in the paper.
*
* @param b the new base;
*/
public void setBase(double b) {
m_Base = b;
}
/**
* Returns the size of the tree. (number of internal nodes + number of leaves)
*
* @return the size of the tree
*/
public double measureTreeSize() {
return m_NumNodes;
}
/**
* Returns the number of leaves.
*
* @return the number of leaves
*/
public double measureNumLeaves() {
return m_NumLeaves;
}
/**
* Returns the depth of the tree.
*
* @return the number of rules
*/
public double measureMaxDepth() {
return m_MaxDepth;
}
/**
* Returns an enumeration of the additional measure names.
*
* @return an enumeration of the measure names
*/
@Override
public Enumeration<String> enumerateMeasures() {
Vector<String> newVector = new Vector<String>();
newVector.addElement("measureTreeSize");
newVector.addElement("measureNumLeaves");
newVector.addElement("measureMaxDepth");
if (m_Stats != null) {
newVector.addAll(Collections.list(m_Stats.enumerateMeasures()));
}
return newVector.elements();
}
/**
* Returns the value of the named measure.
*
* @param additionalMeasureName the name of the measure to query for its value
* @return the value of the named measure
* @throws IllegalArgumentException if the named measure is not supported
*/
@Override
public double getMeasure(String additionalMeasureName) {
if (additionalMeasureName.compareToIgnoreCase("measureMaxDepth") == 0) {
return measureMaxDepth();
} else if (additionalMeasureName.compareToIgnoreCase("measureTreeSize") == 0) {
return measureTreeSize();
} else if (additionalMeasureName.compareToIgnoreCase("measureNumLeaves") == 0) {
return measureNumLeaves();
} else if (m_Stats != null) {
return m_Stats.getMeasure(additionalMeasureName);
} else {
throw new IllegalArgumentException(additionalMeasureName
+ " not supported (KDTree)");
}
}
/******** Utility print functions.****** */
/**
* Prints a string to stdout.
*
* @param s The string to print.
*/
protected static void print(String s) {
System.out.print(s);
}
/**
* Prints a string to stdout followed by newline.
*
* @param s The string to print.
*/
protected static void println(String s) {
System.out.println(s);
}
/**
* Prints an object to stdout.
*
* @param o The object to print.
*/
protected static void print(Object o) {
System.out.print(o);
}
/**
* Prints an object to stdout followed by newline.
*
* @param o The object to print.
*/
protected static void println(Object o) {
System.out.println(o);
}
/**
* Prints the specified number of spaces.
*
* @param s The number of space characters to print.
*/
protected static void print_space(int s) {
for (int i = 0; i < s; i++) {
System.out.print(" ");
}
}
/**
* Prints a cover tree starting from the given node.
*
* @param depth The depth of top_node.
* @param top_node The node to start printing from.
*/
protected static void print(int depth, CoverTreeNode top_node) {
print_space(depth);
println(top_node.p());
if (top_node.num_children > 0) {
print_space(depth);
print("scale = " + top_node.scale + "\n");
print_space(depth);
print("num children = " + top_node.num_children + "\n");
System.out.flush();
for (int i = 0; i < top_node.num_children; i++) {
print(depth + 1, top_node.children.element(i)); // top_node.children[i]);
}
}
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Method for testing the class from command line.
*
* @param args The supplied command line arguments.
*/
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("Usage: CoverTree <ARFF file>");
System.exit(-1);
}
try {
Instances insts = null;
if (args[0].endsWith(".csv")) {
CSVLoader csv = new CSVLoader();
csv.setFile(new File(args[0]));
insts = csv.getDataSet();
} else {
insts = new Instances(new BufferedReader(new FileReader(args[0])));
}
CoverTree tree = new CoverTree();
tree.setInstances(insts);
print("Created data tree:\n");
print(0, tree.m_Root);
println("");
} 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/neighboursearch/FilteredNeighbourSearch.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/>.
*/
/*
* FilteredNeighbourSearch.java
* Copyright (C) 2014 University of Waikato
*/
package weka.core.neighboursearch;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Vector;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.Option;
import weka.core.OptionHandler;
import weka.core.RevisionUtils;
import weka.core.SerializedObject;
import weka.core.Utils;
import weka.core.Capabilities;
import weka.core.Capabilities.Capability;
import weka.core.CapabilitiesHandler;
import weka.filters.AllFilter;
import weka.filters.Filter;
import weka.filters.unsupervised.attribute.AddID;
/**
* <!-- globalinfo-start -->
* Applies the given filter before calling the given neighbour search method. The filter must not change the size of the dataset or the order of the instances! Also, the range setting that is specified for the distance function is ignored: all attributes are used for the distance calculation.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start -->
* Valid options are: <p/>
*
* <pre> -F
* The filter to use. (default: weka.filters.AllFilter)</pre>
*
* <pre> -S
* The search method to use. (default: weka.core.neighboursearch.LinearNNSearch)</pre>
*
* <pre>
* Options specific to filter weka.filters.AllFilter:
* </pre>
*
* <pre> -output-debug-info
* If set, filter is run in debug mode and
* may output additional info to the console</pre>
*
* <pre> -do-not-check-capabilities
* If set, filter capabilities are not checked before filter is built
* (use with caution).</pre>
*
* <pre>
* Options specific to search method weka.core.neighboursearch.LinearNNSearch:
* </pre>
*
* <pre> -S
* Skip identical instances (distances equal to zero).
* </pre>
*
* <pre> -A <classname and options>
* Distance function to use.
* (default: weka.core.EuclideanDistance)</pre>
*
* <pre> -P
* Calculate performance statistics.</pre>
*
* <!-- options-end -->
*
* @author Eibe Frank (eibe@cs.waikato.ac.nz)
* @version $Revision: 8034 $
*/
public class FilteredNeighbourSearch extends NearestNeighbourSearch implements CapabilitiesHandler {
/** For serialization */
private static final long serialVersionUID = 1369174644087067375L;
/** Need to use ID filter to add ID so that we can identify instances */
protected AddID m_AddID = new AddID();
/** The index of the ID attribute */
protected int m_IndexOfID = -1;
/** The filter object to use. */
protected Filter m_Filter = new AllFilter();
/** The neighborhood search method to use. */
protected NearestNeighbourSearch m_SearchMethod = new LinearNNSearch();
/** The modified search method, where ID is skipped */
protected NearestNeighbourSearch m_ModifiedSearchMethod = null;
/**
* Returns default capabilities of the classifier.
*
* @return the capabilities of this classifier
*/
public Capabilities getCapabilities() {
Capabilities result = getFilter().getCapabilities();
// set dependencies
for (Capability cap : Capability.values())
result.enableDependency(cap);
return result;
}
/**
* Sets the instances to build the filtering model from.
*
* @param insts the Instances object
*/
public void setInstances(Instances data) {
try {
super.setInstances(data);
// Apply user-specified filter
getCapabilities().testWithFail(data);
Instances filteredData = new Instances(data);
getFilter().setInputFormat(filteredData);
filteredData = Filter.useFilter(data, getFilter());
if (data.numInstances() != filteredData.numInstances()) {
throw new IllegalArgumentException(
"FilteredNeighbourSearch: Filter has changed the number of instances!");
}
// Set up filter to add ID
m_IndexOfID = filteredData.numAttributes();
m_AddID.setIDIndex("" + (filteredData.numAttributes() + 1));
;
m_AddID.setInputFormat(filteredData);
filteredData = Filter.useFilter(filteredData, m_AddID);
// Modify distance function for base method to skip ID
// User-specified range setting for the distance function is simply
// ignored
m_ModifiedSearchMethod = (NearestNeighbourSearch) new SerializedObject(
getSearchMethod()).getObject();
m_ModifiedSearchMethod.getDistanceFunction().setAttributeIndices(
"1-" + m_IndexOfID);
m_ModifiedSearchMethod.getDistanceFunction().setInvertSelection(false);
// Set up the distance function
m_ModifiedSearchMethod.setInstances(filteredData);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 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 neighbour search method. The filter "
+ "must not change the size of the dataset or the order of the instances! Also, the range "
+ "setting that is specified for the distance function is ignored: all attributes are used "
+ "for the distance calculation.";
}
/**
* 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 searchMethodTipText() {
return "The search method to be used.";
}
/**
* Sets the search method
*
* @param searchMethod the search method with all options set.
*/
public void setSearchMethod(NearestNeighbourSearch search) {
m_SearchMethod = search;
}
/**
* Gets the search method used.
*
* @return the search method
*/
public NearestNeighbourSearch getSearchMethod() {
return m_SearchMethod;
}
/**
* 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.filters.AllFilter",
"F", 1, "-F"));
result
.addElement(new Option(
"\tThe search method to use. (default: weka.core.neighboursearch.LinearNNSearch)",
"S", 0, "-S"));
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_SearchMethod instanceof OptionHandler) {
result.addElement(new Option("", "", 0,
"\nOptions specific to search method "
+ m_SearchMethod.getClass().getName() + ":"));
result.addAll(Collections.list(((OptionHandler) m_SearchMethod)
.listOptions()));
}
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("-F");
result.add("" + getFilterSpec());
result.add("-S");
result.add("" + getSearchMethodSpec());
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 search method specification string, which contains the class name
* of the search method and any options to the search method
*
* @return the search method string.
*/
protected String getSearchMethodSpec() {
NearestNeighbourSearch c = getSearchMethod();
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 searchMethod = Utils.getOption('S', options);
if (searchMethod.length() != 0) {
String searchMethodSpec[] = Utils.splitOptions(searchMethod);
if (searchMethodSpec.length == 0) {
throw new Exception("Invalid search method specification string.");
}
String className = searchMethodSpec[0];
searchMethodSpec[0] = "";
setSearchMethod((NearestNeighbourSearch) Utils.forName(
NearestNeighbourSearch.class, className, searchMethodSpec));
} else {
setSearchMethod(new LinearNNSearch());
}
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 AllFilter());
}
}
/**
* Returns the revision string
*
* @return the revision
*
* @see weka.core.RevisionHandler#getRevision()
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision: 11006 $");
}
/**
* Returns the nearest neighbour for the given instance based on distance
* measured in the filtered space.
*
* @param target the instance for which to find the nearest neighbour
* @return the nearest neighbour
*
* @see weka.core.neighboursearch.NearestNeighbourSearch#nearestNeighbour(weka.core.Instance)
*/
@Override
public Instance nearestNeighbour(Instance target) throws Exception {
getFilter().input(target);
m_AddID.input(getFilter().output());
return getInstances().instance(
(int) m_ModifiedSearchMethod.nearestNeighbour(m_AddID.output()).value(
m_IndexOfID) - 1);
}
/**
* Returns the nearest neighbours for the given instance based on distance
* measured in the filtered space.
*
* @param target the instance for which to find the nearest neighbour
* @param k the number of nearest neighbours to return
* @return the nearest Neighbours
*
* @see weka.core.neighboursearch.NearestNeighbourSearch#kNearestNeighbours(weka.core.Instance,
* int)
*/
@Override
public Instances kNearestNeighbours(Instance target, int k) throws Exception {
// Get neighbors in filtered space
getFilter().input(target);
m_AddID.input(getFilter().output());
Instances neighboursInFilteredSpace = m_ModifiedSearchMethod
.kNearestNeighbours(m_AddID.output(), k);
// Collect corresponding instances in original space
Instances neighbours = new Instances(getInstances(), k);
for (Instance inst : neighboursInFilteredSpace) {
neighbours
.add(getInstances().instance((int) inst.value(m_IndexOfID) - 1));
}
return neighbours;
}
/**
* Returns the distances for the nearest neighbours in the FILTERED space
*
* @return the array of distances for the nearest neighbours
*
* @see weka.core.neighboursearch.NearestNeighbourSearch#getDistances()
*/
@Override
public double[] getDistances() throws Exception {
return m_ModifiedSearchMethod.getDistances();
}
/**
* Updates ranges based on the given instance, once it has been filtered.
*
* @see weka.core.neighboursearch.NearestNeighbourSearch#update(weka.core.Instance)
*/
@Override
public void update(Instance ins) throws Exception {
getFilter().input(ins);
m_AddID.input(getFilter().output());
m_ModifiedSearchMethod.update(m_AddID.output());
}
/**
* Updates the instance info in the underlying search method, once the
* instance has been filtered.
*
* @param ins The instance to add the information of.
*/
@Override
public void addInstanceInfo(Instance ins) {
if (m_Instances != null)
try {
getFilter().input(ins);
m_AddID.input(getFilter().output());
m_ModifiedSearchMethod.addInstanceInfo(m_AddID.output());
} 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/neighboursearch/KDTree.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/>.
*/
/*
* KDTree.java
* Copyright (C) 2000-2012 University of Waikato
*
*/
package weka.core.neighboursearch;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Vector;
import weka.core.DistanceFunction;
import weka.core.EuclideanDistance;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.Option;
import weka.core.RevisionUtils;
import weka.core.TechnicalInformation;
import weka.core.TechnicalInformation.Field;
import weka.core.TechnicalInformation.Type;
import weka.core.TechnicalInformationHandler;
import weka.core.Utils;
import weka.core.neighboursearch.kdtrees.KDTreeNode;
import weka.core.neighboursearch.kdtrees.KDTreeNodeSplitter;
import weka.core.neighboursearch.kdtrees.SlidingMidPointOfWidestSide;
/**
<!-- globalinfo-start -->
* Class implementing the KDTree search algorithm for nearest neighbour search.<br/>
* The connection to dataset is only a reference. For the tree structure the indexes are stored in an array. <br/>
* Building the tree:<br/>
* If a node has <maximal-inst-number> (option -L) instances no further splitting is done. Also if the split would leave one side empty, the branch is not split any further even if the instances in the resulting node are more than <maximal-inst-number> instances.<br/>
* **PLEASE NOTE:** The algorithm can not handle missing values, so it is advisable to run ReplaceMissingValues filter if there are any missing values in the dataset.<br/>
* <br/>
* For more information see:<br/>
* <br/>
* Jerome H. Friedman, Jon Luis Bentley, Raphael Ari Finkel (1977). An Algorithm for Finding Best Matches in Logarithmic Expected Time. ACM Transactions on Mathematics Software. 3(3):209-226.<br/>
* <br/>
* Andrew Moore (1991). A tutorial on kd-trees.
* <p/>
<!-- globalinfo-end -->
*
<!-- technical-bibtex-start -->
* BibTeX:
* <pre>
* @article{Friedman1977,
* author = {Jerome H. Friedman and Jon Luis Bentley and Raphael Ari Finkel},
* journal = {ACM Transactions on Mathematics Software},
* month = {September},
* number = {3},
* pages = {209-226},
* title = {An Algorithm for Finding Best Matches in Logarithmic Expected Time},
* volume = {3},
* year = {1977}
* }
*
* @techreport{Moore1991,
* author = {Andrew Moore},
* booktitle = {University of Cambridge Computer Laboratory Technical Report No. 209},
* howpublished = {Extract from PhD Thesis},
* title = {A tutorial on kd-trees},
* year = {1991},
* HTTP = {Available from http://www.autonlab.org/autonweb/14665.html}
* }
* </pre>
* <p/>
<!-- technical-bibtex-end -->
*
<!-- options-start -->
* Valid options are: <p/>
*
* <pre> -S <classname and options>
* Node splitting method to use.
* (default: weka.core.neighboursearch.kdtrees.SlidingMidPointOfWidestSide)</pre>
*
* <pre> -W <value>
* Set minimal width of a box
* (default: 1.0E-2).</pre>
*
* <pre> -L
* Maximal number of instances in a leaf
* (default: 40).</pre>
*
* <pre> -N
* Normalizing will be done
* (Select dimension for split, with normalising to universe).</pre>
*
<!-- options-end -->
*
* @author Gabi Schmidberger (gabi[at-the-rate]cs[dot]waikato[dot]ac[dot]nz)
* @author Malcolm Ware (mfw4[at-the-rate]cs[dot]waikato[dot]ac[dot]nz)
* @author Ashraf M. Kibriya (amk14[at-the-rate]cs[dot]waikato[dot]ac[dot]nz)
* @version $Revision$
*/
public class KDTree
extends NearestNeighbourSearch
implements TechnicalInformationHandler {
/** For serialization. */
private static final long serialVersionUID = 1505717283763272533L;
/**
* Array holding the distances of the nearest neighbours. It is filled up both
* by nearestNeighbour() and kNearestNeighbours().
*/
protected double[] m_DistanceList;
/**
* Indexlist of the instances of this kdtree. Instances get sorted according
* to the splits. the nodes of the KDTree just hold their start and end
* indices
*/
protected int[] m_InstList;
/** The root node of the tree. */
protected KDTreeNode m_Root;
/** The node splitter. */
protected KDTreeNodeSplitter m_Splitter = new SlidingMidPointOfWidestSide();
/** Tree stats. */
protected int m_NumNodes, m_NumLeaves, m_MaxDepth;
/** Tree Stats variables. */
protected TreePerformanceStats m_TreeStats = null;
// Constants
/** The index of MIN value in attributes' range array. */
public static final int MIN = EuclideanDistance.R_MIN;
/** The index of MAX value in attributes' range array. */
public static final int MAX = EuclideanDistance.R_MAX;
/** The index of WIDTH (MAX-MIN) value in attributes' range array. */
public static final int WIDTH = EuclideanDistance.R_WIDTH;
/**
* 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;
TechnicalInformation additional;
result = new TechnicalInformation(Type.ARTICLE);
result.setValue(Field.AUTHOR, "Jerome H. Friedman and Jon Luis Bentley and Raphael Ari Finkel");
result.setValue(Field.YEAR, "1977");
result.setValue(Field.TITLE, "An Algorithm for Finding Best Matches in Logarithmic Expected Time");
result.setValue(Field.JOURNAL, "ACM Transactions on Mathematics Software");
result.setValue(Field.PAGES, "209-226");
result.setValue(Field.MONTH, "September");
result.setValue(Field.VOLUME, "3");
result.setValue(Field.NUMBER, "3");
additional = result.add(Type.TECHREPORT);
additional.setValue(Field.AUTHOR, "Andrew Moore");
additional.setValue(Field.YEAR, "1991");
additional.setValue(Field.TITLE, "A tutorial on kd-trees");
additional.setValue(Field.HOWPUBLISHED, "Extract from PhD Thesis");
additional.setValue(Field.BOOKTITLE, "University of Cambridge Computer Laboratory Technical Report No. 209");
additional.setValue(Field.HTTP, "Available from http://www.autonlab.org/autonweb/14665.html");
return result;
}
/**
* Creates a new instance of KDTree.
*/
public KDTree() {
super();
if (getMeasurePerformance())
m_Stats = m_TreeStats = new TreePerformanceStats();
}
/**
* Creates a new instance of KDTree.
* It also builds the tree on supplied set of Instances.
* @param insts The instances/points on which the BallTree
* should be built on.
*/
public KDTree(Instances insts) {
super(insts);
if (getMeasurePerformance())
m_Stats = m_TreeStats = new TreePerformanceStats();
}
/**
* Builds the KDTree on the supplied set of instances/points. It
* is adviseable to run the replace missing attributes filter
* on the passed instances first.
* NOTE: This method should not be called from outside this
* class. Outside classes should call setInstances(Instances)
* instead.
*
* @param instances The instances to build the tree on
* @throws Exception if something goes wrong
*/
protected void buildKDTree(Instances instances) throws Exception {
checkMissing(instances);
if (m_EuclideanDistance == null)
m_DistanceFunction = m_EuclideanDistance = new EuclideanDistance(
instances);
else
m_EuclideanDistance.setInstances(instances);
m_Instances = instances;
int numInst = m_Instances.numInstances();
// Make the global index list
m_InstList = new int[numInst];
for (int i = 0; i < numInst; i++) {
m_InstList[i] = i;
}
double[][] universe = m_EuclideanDistance.getRanges();
// initializing internal fields of KDTreeSplitter
m_Splitter.setInstances(m_Instances);
m_Splitter.setInstanceList(m_InstList);
m_Splitter.setEuclideanDistanceFunction(m_EuclideanDistance);
m_Splitter.setNodeWidthNormalization(m_NormalizeNodeWidth);
// building tree
m_NumNodes = m_NumLeaves = 1;
m_MaxDepth = 0;
m_Root = new KDTreeNode(m_NumNodes, 0, m_Instances.numInstances() - 1,
universe);
splitNodes(m_Root, universe, m_MaxDepth + 1);
}
/**
* Recursively splits nodes of a tree starting from the supplied node.
* The splitting stops for any node for which the number of instances/points
* falls below a given threshold (given by m_MaxInstInLeaf), or if the
* maximum relative width/range of the instances/points
* (i.e. max_i(max(att_i) - min(att_i)) ) falls below a given threshold
* (given by m_MinBoxRelWidth).
*
* @param node The node to start splitting from.
* @param universe The attribute ranges of the whole dataset.
* @param depth The depth of the supplied node.
* @throws Exception If there is some problem
* splitting.
*/
protected void splitNodes(KDTreeNode node, double[][] universe,
int depth) throws Exception {
double[][] nodeRanges = m_EuclideanDistance.initializeRanges(m_InstList,
node.m_Start, node.m_End);
if (node.numInstances() <= m_MaxInstInLeaf
|| getMaxRelativeNodeWidth(nodeRanges, universe) <= m_MinBoxRelWidth)
return;
// splitting a node so it is no longer a leaf
m_NumLeaves--;
if (depth > m_MaxDepth)
m_MaxDepth = depth;
m_Splitter.splitNode(node, m_NumNodes, nodeRanges, universe);
m_NumNodes += 2;
m_NumLeaves += 2;
splitNodes(node.m_Left, universe, depth + 1);
splitNodes(node.m_Right, universe, depth + 1);
}
/**
* Returns (in the supplied heap object) the k nearest
* neighbours of the given instance starting from the give
* tree node. >k neighbours are returned if there are more than
* one neighbours at the kth boundary. NOTE: This method should
* not be used from outside this class. Outside classes should
* call kNearestNeighbours(Instance, int).
*
* @param target The instance to find the nearest neighbours for.
* @param node The KDTreeNode to start the search from.
* @param k The number of neighbours to find.
* @param heap The MyHeap object to store/update the kNNs found
* during the search.
* @param distanceToParents The distance of the supplied target
* to the parents of the supplied tree node.
* @throws Exception if the nearest neighbour could not be found.
*/
protected void findNearestNeighbours(Instance target, KDTreeNode node, int k,
MyHeap heap, double distanceToParents) throws Exception {
if (node.isALeaf()) {
if (m_TreeStats != null) {
m_TreeStats.updatePointCount(node.numInstances());
m_TreeStats.incrLeafCount();
}
double distance;
// look at all the instances in this leaf
for (int idx = node.m_Start; idx <= node.m_End; idx++) {
if (target == m_Instances.instance(m_InstList[idx])) // for
// hold-one-out
// cross-validation
continue;
if (heap.size() < k) {
distance = m_EuclideanDistance.distance(target, m_Instances
.instance(m_InstList[idx]), Double.POSITIVE_INFINITY, m_Stats);
heap.put(m_InstList[idx], distance);
} else {
MyHeapElement temp = heap.peek();
distance = m_EuclideanDistance.distance(target, m_Instances
.instance(m_InstList[idx]), temp.distance, m_Stats);
if (distance < temp.distance) {
heap.putBySubstitute(m_InstList[idx], distance);
} else if (distance == temp.distance) {
heap.putKthNearest(m_InstList[idx], distance);
}
}// end else heap.size==k
}// end for
} else {
if (m_TreeStats != null) {
m_TreeStats.incrIntNodeCount();
}
KDTreeNode nearer, further;
boolean targetInLeft = m_EuclideanDistance.valueIsSmallerEqual(target,
node.m_SplitDim, node.m_SplitValue);
if (targetInLeft) {
nearer = node.m_Left;
further = node.m_Right;
} else {
nearer = node.m_Right;
further = node.m_Left;
}
findNearestNeighbours(target, nearer, k, heap, distanceToParents);
// ... now look in further half if maxDist reaches into it
if (heap.size() < k) { // if haven't found the first k
double distanceToSplitPlane = distanceToParents
+ m_EuclideanDistance.sqDifference(node.m_SplitDim, target
.value(node.m_SplitDim), node.m_SplitValue);
findNearestNeighbours(target, further, k, heap, distanceToSplitPlane);
return;
} else { // else see if ball centered at query intersects with the other
// side.
double distanceToSplitPlane = distanceToParents
+ m_EuclideanDistance.sqDifference(node.m_SplitDim, target
.value(node.m_SplitDim), node.m_SplitValue);
if (heap.peek().distance >= distanceToSplitPlane) {
findNearestNeighbours(target, further, k, heap, distanceToSplitPlane);
}
}// end else
}// end else_if an internal node
}
/**
* Returns the k nearest neighbours of the supplied instance.
* >k neighbours are returned if there are more than one
* neighbours at the kth boundary.
*
* @param target The instance to find the nearest neighbours for.
* @param k The number of neighbours to find.
* @return The k nearest neighbours (or >k if more there are than
* one neighbours at the kth boundary).
* @throws Exception if the nearest neighbour could not be found.
*/
public Instances kNearestNeighbours(Instance target, int k) throws Exception {
checkMissing(target);
if (m_Stats != null)
m_Stats.searchStart();
MyHeap heap = new MyHeap(k);
findNearestNeighbours(target, m_Root, k, heap, 0.0);
if (m_Stats != null)
m_Stats.searchFinish();
Instances neighbours = new Instances(m_Instances, (heap.size() + heap
.noOfKthNearest()));
m_DistanceList = new double[heap.size() + heap.noOfKthNearest()];
int[] indices = new int[heap.size() + heap.noOfKthNearest()];
int i = indices.length - 1;
MyHeapElement h;
while (heap.noOfKthNearest() > 0) {
h = heap.getKthNearest();
indices[i] = h.index;
m_DistanceList[i] = h.distance;
i--;
}
while (heap.size() > 0) {
h = heap.get();
indices[i] = h.index;
m_DistanceList[i] = h.distance;
i--;
}
m_DistanceFunction.postProcessDistances(m_DistanceList);
for (int idx = 0; idx < indices.length; idx++) {
neighbours.add(m_Instances.instance(indices[idx]));
}
return neighbours;
}
/**
* Returns the nearest neighbour of the supplied target
* instance.
*
* @param target The instance to find the nearest neighbour for.
* @return The nearest neighbour from among the previously
* supplied training instances.
* @throws Exception if the neighbours could not be found.
*/
public Instance nearestNeighbour(Instance target) throws Exception {
return (kNearestNeighbours(target, 1)).instance(0);
}
/**
* Returns the distances to the kNearest or 1 nearest neighbour currently
* found with either the kNearestNeighbours or the nearestNeighbour method.
*
* @return array containing the distances of the
* nearestNeighbours. The length and ordering of the array
* is the same as that of the instances returned by
* nearestNeighbour functions.
* @throws Exception if called before calling kNearestNeighbours or
* nearestNeighbours.
*/
public double[] getDistances() throws Exception {
if (m_Instances == null || m_DistanceList == null)
throw new Exception("The tree has not been supplied with a set of "
+ "instances or getDistances() has been called "
+ "before calling kNearestNeighbours().");
return m_DistanceList;
}
/**
* Builds the KDTree on the given set of instances.
* @param instances The insts on which the KDTree is to be
* built.
* @throws Exception If some error occurs while
* building the KDTree
*/
public void setInstances(Instances instances) throws Exception {
super.setInstances(instances);
buildKDTree(instances);
}
/**
* Adds one instance to the KDTree. This updates the KDTree structure to take
* into account the newly added training instance.
*
* @param instance the instance to be added. Usually the newly added instance in the
* training set.
* @throws Exception If the instance cannot be added.
*/
public void update(Instance instance) throws Exception { // better to change
// to addInstance
if (m_Instances == null)
throw new Exception("No instances supplied yet. Have to call "
+ "setInstances(instances) with a set of Instances " + "first.");
addInstanceInfo(instance);
addInstanceToTree(instance, m_Root);
}
/**
* Recursively adds an instance to the tree starting from
* the supplied KDTreeNode.
* NOTE: This should not be called by outside classes,
* outside classes should instead call update(Instance)
* method.
*
* @param inst The instance to add to the tree
* @param node The node to start the recursive search
* from, for the leaf node where the supplied instance
* would go.
* @throws Exception If some error occurs while adding
* the instance.
*/
protected void addInstanceToTree(Instance inst, KDTreeNode node)
throws Exception {
if (node.isALeaf()) {
int instList[] = new int[m_Instances.numInstances()];
try {
System.arraycopy(m_InstList, 0, instList, 0, node.m_End + 1); // m_InstList.squeezeIn(m_End,
// index);
if (node.m_End < m_InstList.length - 1)
System.arraycopy(m_InstList, node.m_End + 1, instList,
node.m_End + 2, m_InstList.length - node.m_End - 1);
instList[node.m_End + 1] = m_Instances.numInstances() - 1;
} catch (ArrayIndexOutOfBoundsException ex) {
System.err.println("m_InstList.length: " + m_InstList.length
+ " instList.length: " + instList.length + "node.m_End+1: "
+ (node.m_End + 1) + "m_InstList.length-node.m_End+1: "
+ (m_InstList.length - node.m_End - 1));
throw ex;
}
m_InstList = instList;
node.m_End++;
node.m_NodeRanges = m_EuclideanDistance.updateRanges(inst,
node.m_NodeRanges);
m_Splitter.setInstanceList(m_InstList);
// split this leaf node if necessary
double[][] universe = m_EuclideanDistance.getRanges();
if (node.numInstances() > m_MaxInstInLeaf
&& getMaxRelativeNodeWidth(node.m_NodeRanges, universe) > m_MinBoxRelWidth) {
m_Splitter.splitNode(node, m_NumNodes, node.m_NodeRanges, universe);
m_NumNodes += 2;
}
}// end if node is a leaf
else {
if (m_EuclideanDistance.valueIsSmallerEqual(inst, node.m_SplitDim,
node.m_SplitValue)) {
addInstanceToTree(inst, node.m_Left);
afterAddInstance(node.m_Right);
} else
addInstanceToTree(inst, node.m_Right);
node.m_End++;
node.m_NodeRanges = m_EuclideanDistance.updateRanges(inst,
node.m_NodeRanges);
}
}
/**
* Corrects the start and end indices of a
* KDTreeNode after an instance is added to
* the tree. The start and end indices for
* the master index array (m_InstList)
* stored in the nodes need to be updated
* for all nodes in the subtree on the
* right of a node where the instance
* was added.
* NOTE: No outside class should call this
* method.
*
* @param node KDTreeNode whose start and end indices
* need to be updated.
*/
protected void afterAddInstance(KDTreeNode node) {
node.m_Start++;
node.m_End++;
if (!node.isALeaf()) {
afterAddInstance(node.m_Left);
afterAddInstance(node.m_Right);
}
}
/**
* Adds one instance to KDTree loosly. It only changes the ranges in
* EuclideanDistance, and does not affect the structure of the KDTree.
*
* @param instance the new instance. Usually this is the test instance
* supplied to update the range of attributes in the distance function.
*/
public void addInstanceInfo(Instance instance) {
m_EuclideanDistance.updateRanges(instance);
}
/**
* Checks if there is any instance with missing values. Throws an exception if
* there is, as KDTree does not handle missing values.
*
* @param instances the instances to check
* @throws Exception if missing values are encountered
*/
protected void checkMissing(Instances instances) throws Exception {
for (int i = 0; i < instances.numInstances(); i++) {
Instance ins = instances.instance(i);
for (int j = 0; j < ins.numValues(); j++) {
if (ins.index(j) != ins.classIndex())
if (ins.isMissingSparse(j)) {
throw new Exception("ERROR: KDTree can not deal with missing "
+ "values. Please run ReplaceMissingValues filter "
+ "on the dataset before passing it on to the KDTree.");
}
}
}
}
/**
* Checks if there is any missing value in the given
* instance.
* @param ins The instance to check missing values in.
* @throws Exception If there is a missing value in the
* instance.
*/
protected void checkMissing(Instance ins) throws Exception {
for (int j = 0; j < ins.numValues(); j++) {
if (ins.index(j) != ins.classIndex())
if (ins.isMissingSparse(j)) {
throw new Exception("ERROR: KDTree can not deal with missing "
+ "values. Please run ReplaceMissingValues filter "
+ "on the dataset before passing it on to the KDTree.");
}
}
}
/**
* Returns the maximum attribute width of instances/points
* in a KDTreeNode relative to the whole dataset.
*
* @param nodeRanges The attribute ranges of the
* KDTreeNode whose maximum relative width is to be
* determined.
* @param universe The attribute ranges of the whole
* dataset (training instances + test instances so
* far encountered).
* @return The maximum relative width
*/
protected double getMaxRelativeNodeWidth(double[][] nodeRanges,
double[][] universe) {
int widest = widestDim(nodeRanges, universe);
if(widest < 0)
return 0.0;
else
return nodeRanges[widest][WIDTH] / universe[widest][WIDTH];
}
/**
* Returns the widest dimension/attribute in a
* KDTreeNode (widest after normalizing).
* @param nodeRanges The attribute ranges of
* the KDTreeNode.
* @param universe The attribute ranges of the
* whole dataset (training instances + test
* instances so far encountered).
* @return The index of the widest
* dimension/attribute.
*/
protected int widestDim(double[][] nodeRanges, double[][] universe) {
final int classIdx = m_Instances.classIndex();
double widest = 0.0;
int w = -1;
if (m_NormalizeNodeWidth) {
for (int i = 0; i < nodeRanges.length; i++) {
double newWidest = nodeRanges[i][WIDTH] / universe[i][WIDTH];
if (newWidest > widest) {
if (i == classIdx)
continue;
widest = newWidest;
w = i;
}
}
} else {
for (int i = 0; i < nodeRanges.length; i++) {
if (nodeRanges[i][WIDTH] > widest) {
if (i == classIdx)
continue;
widest = nodeRanges[i][WIDTH];
w = i;
}
}
}
return w;
}
/**
* Returns the size of the tree.
*
* @return the size of the tree
*/
public double measureTreeSize() {
return m_NumNodes;
}
/**
* Returns the number of leaves.
*
* @return the number of leaves
*/
public double measureNumLeaves() {
return m_NumLeaves;
}
/**
* Returns the depth of the tree.
*
* @return The depth of the tree
*/
public double measureMaxDepth() {
return m_MaxDepth;
}
/**
* Returns an enumeration of the additional measure names.
*
* @return an enumeration of the measure names
*/
public Enumeration<String> enumerateMeasures() {
Vector<String> newVector = new Vector<String>();
newVector.addElement("measureTreeSize");
newVector.addElement("measureNumLeaves");
newVector.addElement("measureMaxDepth");
if (m_Stats != null) {
newVector.addAll(Collections.list(m_Stats.enumerateMeasures()));
}
return newVector.elements();
}
/**
* Returns the value of the named measure.
*
* @param additionalMeasureName the name of
* the measure to query for its value.
* @return The value of the named measure
* @throws IllegalArgumentException If the named measure
* is not supported.
*/
public double getMeasure(String additionalMeasureName) {
if (additionalMeasureName.compareToIgnoreCase("measureMaxDepth") == 0) {
return measureMaxDepth();
} else if (additionalMeasureName.compareToIgnoreCase("measureTreeSize") == 0) {
return measureTreeSize();
} else if (additionalMeasureName.compareToIgnoreCase("measureNumLeaves") == 0) {
return measureNumLeaves();
} else if (m_Stats != null) {
return m_Stats.getMeasure(additionalMeasureName);
} else {
throw new IllegalArgumentException(additionalMeasureName
+ " not supported (KDTree)");
}
}
/**
* Sets whether to calculate the performance statistics or not.
* @param measurePerformance Should be true if performance
* statistics are to be measured.
*/
public void setMeasurePerformance(boolean measurePerformance) {
m_MeasurePerformance = measurePerformance;
if (m_MeasurePerformance) {
if (m_Stats == null)
m_Stats = m_TreeStats = new TreePerformanceStats();
} else
m_Stats = m_TreeStats = null;
}
/**
* Assigns instances to centers using KDTree.
*
* @param centers the current centers
* @param assignments the centerindex for each instance
* @param pc the threshold value for pruning.
* @throws Exception If there is some problem
* assigning instances to centers.
*/
public void centerInstances(Instances centers, int[] assignments, double pc)
throws Exception {
int[] centList = new int[centers.numInstances()];
for (int i = 0; i < centers.numInstances(); i++)
centList[i] = i;
determineAssignments(m_Root, centers, centList, assignments, pc);
}
/**
* Assigns instances to the current centers called candidates.
*
* @param node The node to start assigning the instances from.
* @param centers all the current centers.
* @param candidates the current centers the method works on.
* @param assignments the center index for each instance.
* @param pc the threshold value for pruning.
* @throws Exception If there is some problem assigning
* instances to centers.
*/
protected void determineAssignments(KDTreeNode node, Instances centers,
int[] candidates, int[] assignments, double pc) throws Exception {
// reduce number of owners for current hyper rectangle
int[] owners = refineOwners(node, centers, candidates);
// only one owner
if (owners.length == 1) {
// all instances of this node are owned by one center
for (int i = node.m_Start; i <= node.m_End; i++) {
assignments[m_InstList[i]] // the assignment of this instance
= owners[0]; // is the current owner
}
} else if (!node.isALeaf()) {
// more than one owner and it is not a leaf
determineAssignments(node.m_Left, centers, owners, assignments, pc);
determineAssignments(node.m_Right, centers, owners, assignments, pc);
} else {
// this is a leaf and there are more than 1 owner
// XMeans.
assignSubToCenters(node, centers, owners, assignments);
}
}
/**
* Refines the ownerlist.
*
* @param node The current tree node.
* @param centers all centers
* @param candidates the indexes of those centers that are candidates.
* @return list of owners
* @throws Exception If some problem occurs in refining.
*/
protected int[] refineOwners(KDTreeNode node, Instances centers,
int[] candidates) throws Exception {
int[] owners = new int[candidates.length];
double minDistance = Double.POSITIVE_INFINITY;
int ownerIndex = -1;
Instance owner;
int numCand = candidates.length;
double[] distance = new double[numCand];
boolean[] inside = new boolean[numCand];
for (int i = 0; i < numCand; i++) {
distance[i] = distanceToHrect(node, centers.instance(candidates[i]));
inside[i] = (distance[i] == 0.0);
if (distance[i] < minDistance) {
minDistance = distance[i];
ownerIndex = i;
}
}
owner = (Instance)centers.instance(candidates[ownerIndex]).copy();
// are there other owners
// loop also goes over already found owner, keeps order
// in owner list
int index = 0;
for (int i = 0; i < numCand; i++) {
// 1. all centers that are points within rectangle are owners
if ((inside[i])
// 2. take all points with same distance to the rect. as the owner
|| (distance[i] == distance[ownerIndex])) {
// add competitor to owners list
owners[index++] = candidates[i];
} else {
Instance competitor = (Instance)centers.instance(candidates[i]).copy();
if
// 3. point has larger distance to rectangle but still can compete
// with owner for some points in the rectangle
(!candidateIsFullOwner(node, owner, competitor))
{
// also add competitor to owners list
owners[index++] = candidates[i];
}
}
}
int[] result = new int[index];
for (int i = 0; i < index; i++)
result[i] = owners[i];
return result;
}
/**
* Returns the distance between a point and an hyperrectangle.
*
* @param node The current node from whose hyperrectangle
* the distance is to be measured.
* @param x the point
* @return the distance
* @throws Exception If some problem occurs in determining
* the distance to the hyperrectangle.
*/
protected double distanceToHrect(KDTreeNode node, Instance x) throws Exception {
double distance = 0.0;
Instance closestPoint = (Instance)x.copy();
boolean inside;
inside = clipToInsideHrect(node, closestPoint);
if (!inside)
distance = m_EuclideanDistance.distance(closestPoint, x);
return distance;
}
/**
* Finds the closest point in the hyper rectangle to a given point. Change the
* given point to this closest point by clipping of at all the dimensions to
* be clipped of. If the point is inside the rectangle it stays unchanged. The
* return value is true if the point was not changed, so the the return value
* is true if the point was inside the rectangle.
*
* @param node The current KDTreeNode in whose hyperrectangle the closest
* point is to be found.
* @param x a point
* @return true if the input point stayed unchanged.
*/
protected boolean clipToInsideHrect(KDTreeNode node, Instance x) {
boolean inside = true;
for (int i = 0; i < m_Instances.numAttributes(); i++) {
// TODO treat nominals differently!??
if (x.value(i) < node.m_NodeRanges[i][MIN]) {
x.setValue(i, node.m_NodeRanges[i][MIN]);
inside = false;
} else if (x.value(i) > node.m_NodeRanges[i][MAX]) {
x.setValue(i, node.m_NodeRanges[i][MAX]);
inside = false;
}
}
return inside;
}
/**
* Returns true if candidate is a full owner in respect to a competitor.
* <p>
*
* The candidate has been the closer point to the current rectangle or even
* has been a point within the rectangle. The competitor is competing with the
* candidate for a few points out of the rectangle although it is a point
* further away from the rectangle then the candidate. The extrem point is the
* corner of the rectangle that is furthest away from the candidate towards
* the direction of the competitor.
*
* If the distance candidate to this extreme point is smaller then the
* distance competitor to this extreme point, then it is proven that none of
* the points in the rectangle can be owned be the competitor and the
* candidate is full owner of the rectangle in respect to this competitor. See
* also D. Pelleg and A. Moore's paper 'Accelerating exact k-means Algorithms
* with Geometric Reasoning'.
* <p>
*
* @param node The current KDTreeNode / hyperrectangle.
* @param candidate instance that is candidate to be owner
* @param competitor instance that competes against the candidate
* @return true if candidate is full owner
* @throws Exception If some problem occurs.
*/
protected boolean candidateIsFullOwner(KDTreeNode node, Instance candidate,
Instance competitor) throws Exception {
// get extreme point
double[] extreme = new double[m_Instances.numAttributes()];
for (int i = 0; i < m_Instances.numAttributes(); i++) {
if ((competitor.value(i) - candidate.value(i)) > 0) {
extreme[i] = node.m_NodeRanges[i][MAX];
} else {
extreme[i] = node.m_NodeRanges[i][MIN];
}
}
Instance extremeI = candidate.copy(extreme);
boolean isFullOwner = m_EuclideanDistance.distance(extremeI, candidate) < m_EuclideanDistance
.distance(extremeI, competitor);
return isFullOwner;
}
/**
* Assigns instances of this node to center. Center to be assign to is decided
* by the distance function.
*
* @param node The KDTreeNode whose instances are to be assigned.
* @param centers all the input centers
* @param centList the list of centers to work with
* @param assignments index list of last assignments
* @throws Exception If there is error assigning the instances.
*/
public void assignSubToCenters(KDTreeNode node, Instances centers,
int[] centList, int[] assignments) throws Exception {
// todo: undecided situations
// WARNING: assignments is "input/output-parameter"
// should not be null and the following should not happen
if (assignments == null) {
assignments = new int[m_Instances.numInstances()];
for (int i = 0; i < assignments.length; i++) {
assignments[i] = -1;
}
}
// set assignments for all instances of this node
for (int i = node.m_Start; i <= node.m_End; i++) {
int instIndex = m_InstList[i];
Instance inst = m_Instances.instance(instIndex);
// if (instList[i] == 664) System.out.println("664***");
int newC = m_EuclideanDistance.closestPoint(inst, centers, centList);
// int newC = clusterProcessedInstance(inst, centers);
assignments[instIndex] = newC;
}
}
/**
* Properties' variables =====================================================
*/
/** flag for normalizing. */
boolean m_NormalizeNodeWidth = true;
/** The euclidean distance function to use. */
protected EuclideanDistance m_EuclideanDistance;
{ // to make sure we have only one object of EuclideanDistance
if (m_DistanceFunction instanceof EuclideanDistance)
m_EuclideanDistance = (EuclideanDistance) m_DistanceFunction;
else
m_DistanceFunction = m_EuclideanDistance = new EuclideanDistance();
}
/** minimal relative width of a KDTree rectangle. */
protected double m_MinBoxRelWidth = 1.0E-2;
/** maximal number of instances in a leaf. */
protected int m_MaxInstInLeaf = 40;
/**
* the GET and SET - functions ===============================================
*/
/**
* Tip text for this property.
*
* @return the tip text for this property
*/
public String minBoxRelWidthTipText() {
return "The minimum relative width of the box. A node is only made a leaf "
+ "if the width of the split dimension of the instances in a node "
+ "normalized over the width of the split dimension of all the "
+ "instances is less than or equal to this minimum relative width.";
}
/**
* Sets the minimum relative box width.
*
* @param i the minimum relative box width
*/
public void setMinBoxRelWidth(double i) {
m_MinBoxRelWidth = i;
}
/**
* Gets the minimum relative box width.
*
* @return the minimum relative box width
*/
public double getMinBoxRelWidth() {
return m_MinBoxRelWidth;
}
/**
* Tip text for this property.
*
* @return the tip text for this property
*/
public String maxInstInLeafTipText() {
return "The max number of instances in a leaf.";
}
/**
* Sets the maximum number of instances in a leaf.
*
* @param i the maximum number of instances in a leaf
*/
public void setMaxInstInLeaf(int i) {
m_MaxInstInLeaf = i;
}
/**
* Get the maximum number of instances in a leaf.
*
* @return the maximum number of instances in a leaf
*/
public int getMaxInstInLeaf() {
return m_MaxInstInLeaf;
}
/**
* Tip text for this property.
*
* @return the tip text for this property
*/
public String normalizeNodeWidthTipText() {
return "Whether if the widths of the KDTree node should be normalized "
+ "by the width of the universe or not. "
+ "Where, width of the node is the range of the split attribute "
+ "based on the instances in that node, and width of the "
+ "universe is the range of the split attribute based on all the "
+ "instances (default: false).";
}
/**
* Sets the flag for normalizing the widths of a KDTree Node by the width of
* the dimension in the universe.
*
* @param n true to use normalizing.
*/
public void setNormalizeNodeWidth(boolean n) {
m_NormalizeNodeWidth = n;
}
/**
* Gets the normalize flag.
*
* @return True if normalizing
*/
public boolean getNormalizeNodeWidth() {
return m_NormalizeNodeWidth;
}
/**
* returns the distance function currently in use.
*
* @return the distance function
*/
public DistanceFunction getDistanceFunction() {
return (DistanceFunction) m_EuclideanDistance;
}
/**
* sets the distance function to use for nearest neighbour search.
*
* @param df the distance function to use
* @throws Exception if not EuclideanDistance
*/
public void setDistanceFunction(DistanceFunction df) throws Exception {
if (!(df instanceof EuclideanDistance))
throw new Exception("KDTree currently only works with "
+ "EuclideanDistanceFunction.");
m_DistanceFunction = m_EuclideanDistance = (EuclideanDistance) df;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for
* displaying in the explorer/experimenter gui
*/
public String nodeSplitterTipText() {
return "The the splitting method to split the nodes of the KDTree.";
}
/**
* Returns the splitting method currently in use to split the nodes of the
* KDTree.
*
* @return The KDTreeNodeSplitter currently in use.
*/
public KDTreeNodeSplitter getNodeSplitter() {
return m_Splitter;
}
/**
* Sets the splitting method to use to split the nodes of the KDTree.
*
* @param splitter The KDTreeNodeSplitter to use.
*/
public void setNodeSplitter(KDTreeNodeSplitter splitter) {
m_Splitter = splitter;
}
/**
* Returns a string describing this nearest neighbour search algorithm.
*
* @return a description of the algorithm for displaying in the
* explorer/experimenter gui
*/
public String globalInfo() {
return
"Class implementing the KDTree search algorithm for nearest "
+ "neighbour search.\n"
+ "The connection to dataset is only a reference. For the tree "
+ "structure the indexes are stored in an array. \n"
+ "Building the tree:\n"
+ "If a node has <maximal-inst-number> (option -L) instances no "
+ "further splitting is done. Also if the split would leave one "
+ "side empty, the branch is not split any further even if the "
+ "instances in the resulting node are more than "
+ "<maximal-inst-number> instances.\n"
+ "**PLEASE NOTE:** The algorithm can not handle missing values, so it "
+ "is advisable to run ReplaceMissingValues filter if there are any "
+ "missing values in the dataset.\n\n"
+ "For more information see:\n\n"
+ getTechnicalInformation().toString();
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
public Enumeration<Option> listOptions() {
Vector<Option> newVector = new Vector<Option>();
newVector.add(new Option(
"\tNode splitting method to use.\n"
+ "\t(default: weka.core.neighboursearch.kdtrees.SlidingMidPointOfWidestSide)",
"S", 1, "-S <classname and options>"));
newVector.addElement(new Option(
"\tSet minimal width of a box\n"
+ "\t(default: 1.0E-2).",
"W", 0, "-W <value>"));
newVector.addElement(new Option(
"\tMaximal number of instances in a leaf\n"
+ "\t(default: 40).",
"L", 0, "-L"));
newVector.addElement(new Option(
"\tNormalizing will be done\n"
+ "\t(Select dimension for split, with normalising to universe).",
"N", 0, "-N"));
newVector.addAll(Collections.list(super.listOptions()));
return newVector.elements();
}
/**
* Parses a given list of options. <p/>
*
<!-- options-start -->
* Valid options are: <p/>
*
* <pre> -S <classname and options>
* Node splitting method to use.
* (default: weka.core.neighboursearch.kdtrees.SlidingMidPointOfWidestSide)</pre>
*
* <pre> -W <value>
* Set minimal width of a box
* (default: 1.0E-2).</pre>
*
* <pre> -L
* Maximal number of instances in a leaf
* (default: 40).</pre>
*
* <pre> -N
* Normalizing will be done
* (Select dimension for split, with normalising to universe).</pre>
*
<!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
public void setOptions(String[] options) throws Exception {
super.setOptions(options);
String optionString = Utils.getOption('S', options);
if (optionString.length() != 0) {
String splitMethodSpec[] = Utils.splitOptions(optionString);
if (splitMethodSpec.length == 0) {
throw new Exception("Invalid DistanceFunction specification string.");
}
String className = splitMethodSpec[0];
splitMethodSpec[0] = "";
setNodeSplitter((KDTreeNodeSplitter) Utils.forName(
KDTreeNodeSplitter.class, className, splitMethodSpec));
}
else {
setNodeSplitter(new SlidingMidPointOfWidestSide());
}
optionString = Utils.getOption('W', options);
if (optionString.length() != 0)
setMinBoxRelWidth(Double.parseDouble(optionString));
else
setMinBoxRelWidth(1.0E-2);
optionString = Utils.getOption('L', options);
if (optionString.length() != 0)
setMaxInstInLeaf(Integer.parseInt(optionString));
else
setMaxInstInLeaf(40);
setNormalizeNodeWidth(Utils.getFlag('N', options));
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of KDtree.
*
* @return an array of strings suitable for passing to setOptions
*/
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]);
result.add("-S");
result.add(
(m_Splitter.getClass().getName() + " " +
Utils.joinOptions(m_Splitter.getOptions())).trim());
result.add("-W");
result.add("" + getMinBoxRelWidth());
result.add("-L");
result.add("" + getMaxInstInLeaf());
if (getNormalizeNodeWidth())
result.add("-N");
return result.toArray(new String[result.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/core
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/neighboursearch/LinearNNSearch.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/>.
*/
/*
* LinearNNSearch.java
* Copyright (C) 1999-2012 University of Waikato
*/
package weka.core.neighboursearch;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Vector;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.Option;
import weka.core.RevisionUtils;
import weka.core.Utils;
/**
* <!-- globalinfo-start --> Class implementing the brute force search algorithm for nearest neighbour search.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -S
* Skip identical instances (distances equal to zero).
* </pre>
*
* <!-- options-end -->
*
* @author Ashraf M. Kibriya (amk14[at-the-rate]cs[dot]waikato[dot]ac[dot]nz)
* @version $Revision$
*/
public class LinearNNSearch extends NearestNeighbourSearch {
/** for serialization. */
private static final long serialVersionUID = 1915484723703917241L;
/**
* Array holding the distances of the nearest neighbours. It is filled up both by nearestNeighbour() and kNearestNeighbours().
*/
protected double[] m_Distances;
/** Whether to skip instances from the neighbours that are identical to the query instance. */
protected boolean m_SkipIdentical = false;
/**
* Constructor. Needs setInstances(Instances) to be called before the class is usable.
*/
public LinearNNSearch() {
super();
}
/**
* Constructor that uses the supplied set of instances.
*
* @param insts
* the instances to use
*/
public LinearNNSearch(final Instances insts) {
super(insts);
this.m_DistanceFunction.setInstances(insts);
}
/**
* Returns a string describing this nearest neighbour search algorithm.
*
* @return a description of the algorithm for displaying in the explorer/experimenter gui
*/
@Override
public String globalInfo() {
return "Class implementing the brute force search algorithm for nearest " + "neighbour search.";
}
/**
* 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("\tSkip identical instances (distances equal to zero).\n", "S", 1, "-S"));
result.addAll(Collections.list(super.listOptions()));
return result.elements();
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -S
* Skip identical instances (distances equal to zero).
* </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(final String[] options) throws Exception {
super.setOptions(options);
this.setSkipIdentical(Utils.getFlag('S', options));
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings.
*
* @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 (this.getSkipIdentical()) {
result.add("-S");
}
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 skipIdenticalTipText() {
return "Whether to skip identical instances (with distance 0 to the target)";
}
/**
* Sets the property to skip identical instances (with distance zero from the target) from the set of neighbours returned.
*
* @param skip
* if true, identical intances are skipped
*/
public void setSkipIdentical(final boolean skip) {
this.m_SkipIdentical = skip;
}
/**
* Gets whether if identical instances are skipped from the neighbourhood.
*
* @return true if identical instances are skipped
*/
public boolean getSkipIdentical() {
return this.m_SkipIdentical;
}
/**
* Returns the nearest instance in the current neighbourhood to the supplied instance.
*
* @param target
* The instance to find the nearest neighbour for.
* @return the nearest instance
* @throws Exception
* if the nearest neighbour could not be found.
*/
@Override
public Instance nearestNeighbour(final Instance target) throws Exception {
return (this.kNearestNeighbours(target, 1)).instance(0);
}
/**
* Returns k nearest instances in the current neighbourhood to the supplied instance.
*
* @param target
* The instance to find the k nearest neighbours for.
* @param kNN
* The number of nearest neighbours to find.
* @return the k nearest neighbors
* @throws Exception
* if the neighbours could not be found.
*/
@Override
public Instances kNearestNeighbours(final Instance target, final int kNN) throws Exception {
// debug
boolean print = false;
if (this.m_Stats != null) {
this.m_Stats.searchStart();
}
MyHeap heap = new MyHeap(kNN);
double distance;
int firstkNN = 0;
for (int i = 0; i < this.m_Instances.numInstances(); i++) {
// XXX kill weka
if (Thread.interrupted()) {
throw new InterruptedException("Killed WEKA!");
}
if (target == this.m_Instances.instance(i)) {
continue;
}
if (this.m_Stats != null) {
this.m_Stats.incrPointCount();
}
if (firstkNN < kNN) {
if (print) {
System.out.println("K(a): " + (heap.size() + heap.noOfKthNearest()));
}
distance = this.m_DistanceFunction.distance(target, this.m_Instances.instance(i), Double.POSITIVE_INFINITY, this.m_Stats);
if (distance == 0.0 && this.m_SkipIdentical) {
if (i < this.m_Instances.numInstances() - 1) {
continue;
} else {
heap.put(i, distance);
}
}
heap.put(i, distance);
firstkNN++;
} else {
MyHeapElement temp = heap.peek();
if (print) {
System.out.println("K(b): " + (heap.size() + heap.noOfKthNearest()));
}
distance = this.m_DistanceFunction.distance(target, this.m_Instances.instance(i), temp.distance, this.m_Stats);
if (distance == 0.0 && this.m_SkipIdentical) {
continue;
}
if (distance < temp.distance) {
heap.putBySubstitute(i, distance);
} else if (distance == temp.distance) {
heap.putKthNearest(i, distance);
}
}
}
Instances neighbours = new Instances(this.m_Instances, (heap.size() + heap.noOfKthNearest()));
this.m_Distances = new double[heap.size() + heap.noOfKthNearest()];
int[] indices = new int[heap.size() + heap.noOfKthNearest()];
int i = 1;
MyHeapElement h;
while (heap.noOfKthNearest() > 0) {
// XXX kill weka
if (Thread.interrupted()) {
throw new InterruptedException("Killed WEKA!");
}
h = heap.getKthNearest();
indices[indices.length - i] = h.index;
this.m_Distances[indices.length - i] = h.distance;
i++;
}
while (heap.size() > 0) {
// XXX kill weka
if (Thread.interrupted()) {
throw new InterruptedException("Killed WEKA!");
}
h = heap.get();
indices[indices.length - i] = h.index;
this.m_Distances[indices.length - i] = h.distance;
i++;
}
this.m_DistanceFunction.postProcessDistances(this.m_Distances);
for (int k = 0; k < indices.length; k++) {
// XXX kill weka
if (Thread.interrupted()) {
throw new InterruptedException("Killed WEKA!");
}
neighbours.add(this.m_Instances.instance(indices[k]));
}
if (this.m_Stats != null) {
this.m_Stats.searchFinish();
}
return neighbours;
}
/**
* Returns the distances of the k nearest neighbours. The kNearestNeighbours or nearestNeighbour must always be called before calling this function. If this function is called before calling either the kNearestNeighbours or the
* nearestNeighbour, then it throws an exception. If, however, if either of the nearestNeighbour functions are called at any point in the past then no exception is thrown and the distances of the training set from the last supplied
* target instance (to either one of the nearestNeighbour functions) is/are returned.
*
* @return array containing the distances of the nearestNeighbours. The length and ordering of the array is the same as that of the instances returned by nearestNeighbour functions.
* @throws Exception
* if called before calling kNearestNeighbours or nearestNeighbours.
*/
@Override
public double[] getDistances() throws Exception {
if (this.m_Distances == null) {
throw new Exception("No distances available. Please call either " + "kNearestNeighbours or nearestNeighbours first.");
}
return this.m_Distances;
}
/**
* Sets the instances comprising the current neighbourhood.
*
* @param insts
* The set of instances on which the nearest neighbour search is carried out. Usually this set is the training set.
* @throws Exception
* if setting of instances fails
*/
@Override
public void setInstances(final Instances insts) throws Exception {
this.m_Instances = insts;
this.m_DistanceFunction.setInstances(insts);
}
/**
* Updates the LinearNNSearch to cater for the new added instance. This implementation only updates the ranges of the DistanceFunction class, since our set of instances is passed by reference and should already have the newly added
* instance.
*
* @param ins
* The instance to add. Usually this is the instance that is added to our neighbourhood i.e. the training instances.
* @throws Exception
* if the given instances are null
*/
@Override
public void update(final Instance ins) throws Exception {
if (this.m_Instances == null) {
throw new Exception("No instances supplied yet. Cannot update without" + "supplying a set of instances first.");
}
this.m_DistanceFunction.update(ins);
}
/**
* Adds the given instance info. This implementation updates the range datastructures of the DistanceFunction class.
*
* @param ins
* The instance to add the information of. Usually this is the test instance supplied to update the range of attributes in the distance function.
*/
@Override
public void addInstanceInfo(final Instance ins) {
if (this.m_Instances != null) {
try {
this.update(ins);
} 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/core
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/neighboursearch/NearestNeighbourSearch.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/>.
*/
/*
* NearestNeighbourSearch.java
* Copyright (C) 1999-2012 University of Waikato
*/
package weka.core.neighboursearch;
import java.io.Serializable;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Vector;
import weka.core.AdditionalMeasureProducer;
import weka.core.DistanceFunction;
import weka.core.EuclideanDistance;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.Option;
import weka.core.OptionHandler;
import weka.core.RevisionHandler;
import weka.core.RevisionUtils;
import weka.core.Utils;
/**
* Abstract class for nearest neighbour search. All algorithms (classes) that do
* nearest neighbour search should extend this class.
*
* @author Ashraf M. Kibriya (amk14[at-the-rate]cs[dot]waikato[dot]ac[dot]nz)
* @version $Revision$
*/
public abstract class NearestNeighbourSearch implements Serializable,
OptionHandler, AdditionalMeasureProducer, RevisionHandler {
/** ID to avoid warning */
private static final long serialVersionUID = 7516898393890379876L;
/**
* A class for a heap to store the nearest k neighbours to an instance. The
* heap also takes care of cases where multiple neighbours are the same
* distance away. i.e. the minimum size of the heap is k.
*
* @author Ashraf M. Kibriya (amk14[at-the-rate]cs[dot]waikato[dot]ac[dot]nz)
* @version $Revision$
*/
protected class MyHeap implements RevisionHandler {
/** the heap. */
MyHeapElement m_heap[] = null;
/**
* constructor.
*
* @param maxSize the maximum size of the heap
*/
public MyHeap(int maxSize) {
if ((maxSize % 2) == 0) {
maxSize++;
}
m_heap = new MyHeapElement[maxSize + 1];
m_heap[0] = new MyHeapElement(0, 0);
}
/**
* returns the size of the heap.
*
* @return the size
*/
public int size() {
return m_heap[0].index;
}
/**
* peeks at the first element.
*
* @return the first element
*/
public MyHeapElement peek() {
return m_heap[1];
}
/**
* returns the first element and removes it from the heap.
*
* @return the first element
* @throws Exception if no elements in heap
*/
public MyHeapElement get() throws Exception {
if (m_heap[0].index == 0) {
throw new Exception("No elements present in the heap");
}
MyHeapElement r = m_heap[1];
m_heap[1] = m_heap[m_heap[0].index];
m_heap[0].index--;
downheap();
return r;
}
/**
* adds the value to the heap.
*
* @param i the index
* @param d the distance
* @throws Exception if the heap gets too large
*/
public void put(int i, double d) throws Exception {
if ((m_heap[0].index + 1) > (m_heap.length - 1)) {
throw new Exception("the number of elements cannot exceed the "
+ "initially set maximum limit");
}
m_heap[0].index++;
m_heap[m_heap[0].index] = new MyHeapElement(i, d);
upheap();
}
/**
* Puts an element by substituting it in place of the top most element.
*
* @param i the index
* @param d the distance
* @throws Exception if distance is smaller than that of the head element
*/
public void putBySubstitute(int i, double d) throws Exception {
MyHeapElement head = get();
put(i, d);
// System.out.println("previous: "+head.distance+" current: "+m_heap[1].distance);
if (head.distance == m_heap[1].distance) { // Utils.eq(head.distance,
// m_heap[1].distance)) {
putKthNearest(head.index, head.distance);
} else if (head.distance > m_heap[1].distance) { // Utils.gr(head.distance,
// m_heap[1].distance)) {
m_KthNearest = null;
m_KthNearestSize = 0;
initSize = 10;
} else if (head.distance < m_heap[1].distance) {
throw new Exception("The substituted element is smaller than the "
+ "head element. put() should have been called "
+ "in place of putBySubstitute()");
}
}
/** the kth nearest ones. */
MyHeapElement m_KthNearest[] = null;
/** The number of kth nearest elements. */
int m_KthNearestSize = 0;
/** the initial size of the heap. */
int initSize = 10;
/**
* returns the number of k nearest.
*
* @return the number of k nearest
* @see #m_KthNearestSize
*/
public int noOfKthNearest() {
return m_KthNearestSize;
}
/**
* Stores kth nearest elements (if there are more than one).
*
* @param i the index
* @param d the distance
*/
public void putKthNearest(int i, double d) {
if (m_KthNearest == null) {
m_KthNearest = new MyHeapElement[initSize];
}
if (m_KthNearestSize >= m_KthNearest.length) {
initSize += initSize;
MyHeapElement temp[] = new MyHeapElement[initSize];
System.arraycopy(m_KthNearest, 0, temp, 0, m_KthNearest.length);
m_KthNearest = temp;
}
m_KthNearest[m_KthNearestSize++] = new MyHeapElement(i, d);
}
/**
* returns the kth nearest element or null if none there.
*
* @return the kth nearest element
*/
public MyHeapElement getKthNearest() {
if (m_KthNearestSize == 0) {
return null;
}
m_KthNearestSize--;
return m_KthNearest[m_KthNearestSize];
}
/**
* performs upheap operation for the heap to maintian its properties.
*/
protected void upheap() {
int i = m_heap[0].index;
MyHeapElement temp;
while (i > 1 && m_heap[i].distance > m_heap[i / 2].distance) {
temp = m_heap[i];
m_heap[i] = m_heap[i / 2];
i = i / 2;
m_heap[i] = temp; // this is i/2 done here to avoid another division.
}
}
/**
* performs downheap operation for the heap to maintian its properties.
*/
protected void downheap() {
int i = 1;
MyHeapElement temp;
while (((2 * i) <= m_heap[0].index && m_heap[i].distance < m_heap[2 * i].distance)
|| ((2 * i + 1) <= m_heap[0].index && m_heap[i].distance < m_heap[2 * i + 1].distance)) {
if ((2 * i + 1) <= m_heap[0].index) {
if (m_heap[2 * i].distance > m_heap[2 * i + 1].distance) {
temp = m_heap[i];
m_heap[i] = m_heap[2 * i];
i = 2 * i;
m_heap[i] = temp;
} else {
temp = m_heap[i];
m_heap[i] = m_heap[2 * i + 1];
i = 2 * i + 1;
m_heap[i] = temp;
}
} else {
temp = m_heap[i];
m_heap[i] = m_heap[2 * i];
i = 2 * i;
m_heap[i] = temp;
}
}
}
/**
* returns the total size.
*
* @return the total size
*/
public int totalSize() {
return size() + noOfKthNearest();
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
}
/**
* A class for storing data about a neighboring instance.
*
* @author Ashraf M. Kibriya (amk14[at-the-rate]cs[dot]waikato[dot]ac[dot]nz)
* @version $Revision$
*/
protected class MyHeapElement implements RevisionHandler {
/** the index of this element. */
public int index;
/** the distance of this element. */
public double distance;
/**
* constructor.
*
* @param i the index
* @param d the distance
*/
public MyHeapElement(int i, double d) {
distance = d;
index = i;
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
}
/**
* A class for storing data about a neighboring instance.
*
* @author Ashraf M. Kibriya (amk14[at-the-rate]cs[dot]waikato[dot]ac[dot]nz)
* @version $Revision$
*/
// better to change this into a heap element
protected class NeighborNode implements RevisionHandler {
/** The neighbor instance. */
public Instance m_Instance;
/** The distance from the current instance to this neighbor. */
public double m_Distance;
/** A link to the next neighbor instance. */
public NeighborNode m_Next;
/**
* Create a new neighbor node.
*
* @param distance the distance to the neighbor
* @param instance the neighbor instance
* @param next the next neighbor node
*/
public NeighborNode(double distance, Instance instance, NeighborNode next) {
m_Distance = distance;
m_Instance = instance;
m_Next = next;
}
/**
* Create a new neighbor node that doesn't link to any other nodes.
*
* @param distance the distance to the neighbor
* @param instance the neighbor instance
*/
public NeighborNode(double distance, Instance instance) {
this(distance, instance, null);
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
}
/**
* A class for a linked list to store the nearest k neighbours to an instance.
* We use a list so that we can take care of cases where multiple neighbours
* are the same distance away. i.e. the minimum length of the list is k.
*
* @author Ashraf M. Kibriya (amk14[at-the-rate]cs[dot]waikato[dot]ac[dot]nz)
* @version $Revision$
*/
// better to change this into a heap
protected class NeighborList implements RevisionHandler {
/** The first node in the list. */
protected NeighborNode m_First;
/** The last node in the list. */
protected NeighborNode m_Last;
/** The number of nodes to attempt to maintain in the list. */
protected int m_Length = 1;
/**
* Creates the neighborlist with a desired length.
*
* @param length the length of list to attempt to maintain
*/
public NeighborList(int length) {
m_Length = length;
}
/**
* Gets whether the list is empty.
*
* @return true if list is empty
*/
public boolean isEmpty() {
return (m_First == null);
}
/**
* Gets the current length of the list.
*
* @return the current length of the list
*/
public int currentLength() {
int i = 0;
NeighborNode current = m_First;
while (current != null) {
i++;
current = current.m_Next;
}
return i;
}
/**
* Inserts an instance neighbor into the list, maintaining the list sorted
* by distance.
*
* @param distance the distance to the instance
* @param instance the neighboring instance
*/
public void insertSorted(double distance, Instance instance) {
if (isEmpty()) {
m_First = m_Last = new NeighborNode(distance, instance);
} else {
NeighborNode current = m_First;
if (distance < m_First.m_Distance) {// Insert at head
m_First = new NeighborNode(distance, instance, m_First);
} else { // Insert further down the list
for (; (current.m_Next != null)
&& (current.m_Next.m_Distance < distance); current = current.m_Next) {
;
}
current.m_Next = new NeighborNode(distance, instance, current.m_Next);
if (current.equals(m_Last)) {
m_Last = current.m_Next;
}
}
// Trip down the list until we've got k list elements (or more if the
// distance to the last elements is the same).
int valcount = 0;
for (current = m_First; current.m_Next != null; current = current.m_Next) {
valcount++;
if ((valcount >= m_Length)
&& (current.m_Distance != current.m_Next.m_Distance)) {
m_Last = current;
current.m_Next = null;
break;
}
}
}
}
/**
* Prunes the list to contain the k nearest neighbors. If there are multiple
* neighbors at the k'th distance, all will be kept.
*
* @param k the number of neighbors to keep in the list.
*/
public void pruneToK(int k) {
if (isEmpty()) {
return;
}
if (k < 1) {
k = 1;
}
int currentK = 0;
double currentDist = m_First.m_Distance;
NeighborNode current = m_First;
for (; current.m_Next != null; current = current.m_Next) {
currentK++;
currentDist = current.m_Distance;
if ((currentK >= k) && (currentDist != current.m_Next.m_Distance)) {
m_Last = current;
current.m_Next = null;
break;
}
}
}
/**
* Prints out the contents of the neighborlist.
*/
public void printList() {
if (isEmpty()) {
System.out.println("Empty list");
} else {
NeighborNode current = m_First;
while (current != null) {
System.out.println("Node: instance " + current.m_Instance
+ ", distance " + current.m_Distance);
current = current.m_Next;
}
System.out.println();
}
}
/**
* returns the first element in the list.
*
* @return the first element
*/
public NeighborNode getFirst() {
return m_First;
}
/**
* returns the last element in the list.
*
* @return the last element
*/
public NeighborNode getLast() {
return m_Last;
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
}
/** The neighbourhood of instances to find neighbours in. */
protected Instances m_Instances;
/** The number of neighbours to find. */
protected int m_kNN;
/** the distance function used. */
protected DistanceFunction m_DistanceFunction = new EuclideanDistance();
/** Performance statistics. */
protected PerformanceStats m_Stats = null;
/** Should we measure Performance. */
protected boolean m_MeasurePerformance = false;
/**
* Constructor.
*/
public NearestNeighbourSearch() {
if (m_MeasurePerformance) {
m_Stats = new PerformanceStats();
}
}
/**
* Constructor.
*
* @param insts The set of instances that constitute the neighbourhood.
*/
public NearestNeighbourSearch(Instances insts) {
this();
m_Instances = insts;
}
/**
* Returns a string describing this nearest neighbour search algorithm.
*
* @return a description of the algorithm for displaying in the
* explorer/experimenter gui
*/
public String globalInfo() {
return "Abstract class for nearest neighbour search. All algorithms (classes) that "
+ "do nearest neighbour search should extend this class.";
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> newVector = new Vector<Option>();
newVector.add(new Option("\tDistance function to use.\n"
+ "\t(default: weka.core.EuclideanDistance)", "A", 1,
"-A <classname and options>"));
newVector.add(new Option("\tCalculate performance statistics.", "P", 0,
"-P"));
return newVector.elements();
}
/**
* Parses a given list of options. Valid options are:
*
* <!-- options-start --> <!-- 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 nnSearchClass = Utils.getOption('A', options);
if (nnSearchClass.length() != 0) {
String nnSearchClassSpec[] = Utils.splitOptions(nnSearchClass);
if (nnSearchClassSpec.length == 0) {
throw new Exception("Invalid DistanceFunction specification string.");
}
String className = nnSearchClassSpec[0];
nnSearchClassSpec[0] = "";
setDistanceFunction((DistanceFunction) Utils.forName(
DistanceFunction.class, className, nnSearchClassSpec));
} else {
setDistanceFunction(new EuclideanDistance());
}
setMeasurePerformance(Utils.getFlag('P', options));
}
/**
* Gets the current settings.
*
* @return an array of strings suitable for passing to setOptions()
*/
@Override
public String[] getOptions() {
Vector<String> result;
result = new Vector<String>();
result.add("-A");
result.add((m_DistanceFunction.getClass().getName() + " " + Utils
.joinOptions(m_DistanceFunction.getOptions())).trim());
if (getMeasurePerformance()) {
result.add("-P");
}
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 distanceFunctionTipText() {
return "The distance function to use for finding neighbours "
+ "(default: weka.core.EuclideanDistance). ";
}
/**
* returns the distance function currently in use.
*
* @return the distance function
*/
public DistanceFunction getDistanceFunction() {
return m_DistanceFunction;
}
/**
* sets the distance function to use for nearest neighbour search.
*
* @param df the new distance function to use
* @throws Exception if instances cannot be processed
*/
public void setDistanceFunction(DistanceFunction df) throws Exception {
m_DistanceFunction = df;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String measurePerformanceTipText() {
return "Whether to calculate performance statistics "
+ "for the NN search or not";
}
/**
* Gets whether performance statistics are being calculated or not.
*
* @return true if the measure performance is calculated
*/
public boolean getMeasurePerformance() {
return m_MeasurePerformance;
}
/**
* Sets whether to calculate the performance statistics or not.
*
* @param measurePerformance if true then the performance is calculated
*/
public void setMeasurePerformance(boolean measurePerformance) {
m_MeasurePerformance = measurePerformance;
if (m_MeasurePerformance) {
if (m_Stats == null) {
m_Stats = new PerformanceStats();
}
} else {
m_Stats = null;
}
}
/**
* Returns the nearest instance in the current neighbourhood to the supplied
* instance.
*
* @param target The instance to find the nearest neighbour for.
* @return the nearest neighbor
* @throws Exception if the nearest neighbour could not be found.
*/
public abstract Instance nearestNeighbour(Instance target) throws Exception;
/**
* Returns k nearest instances in the current neighbourhood to the supplied
* instance.
*
* @param target The instance to find the k nearest neighbours for.
* @param k The number of nearest neighbours to find.
* @return the k nearest neighbors
* @throws Exception if the neighbours could not be found.
*/
public abstract Instances kNearestNeighbours(Instance target, int k)
throws Exception;
/**
* Returns the distances of the k nearest neighbours. The kNearestNeighbours
* or nearestNeighbour needs to be called first for this to work.
*
* @return the distances
* @throws Exception if called before calling kNearestNeighbours or
* nearestNeighbours.
*/
public abstract double[] getDistances() throws Exception;
/**
* Updates the NearNeighbourSearch algorithm for the new added instance. P.S.:
* The method assumes the instance has already been added to the m_Instances
* object by the caller.
*
* @param ins the instance to add
* @throws Exception if updating fails
*/
public abstract void update(Instance ins) throws Exception;
/**
* Adds information from the given instance without modifying the
* datastructure a lot.
*
* @param ins the instance to add the information from
*/
public void addInstanceInfo(Instance ins) {
}
/**
* Sets the instances.
*
* @param insts the instances to use
* @throws Exception if setting fails
*/
public void setInstances(Instances insts) throws Exception {
m_Instances = insts;
}
/**
* returns the instances currently set.
*
* @return the current instances
*/
public Instances getInstances() {
return m_Instances;
}
/**
* Gets the class object that contains the performance statistics of the
* search method.
*
* @return the performance statistics
*/
public PerformanceStats getPerformanceStats() {
return m_Stats;
}
/**
* Returns an enumeration of the additional measure names.
*
* @return an enumeration of the measure names
*/
@Override
public Enumeration<String> enumerateMeasures() {
Vector<String> newVector;
if (m_Stats == null) {
newVector = new Vector<String>(0);
} else {
newVector = new Vector<String>();
Enumeration<String> en = m_Stats.enumerateMeasures();
newVector.addAll(Collections.list(en));
}
return newVector.elements();
}
/**
* Returns the value of the named measure.
*
* @param additionalMeasureName the name of the measure to query for its value
* @return the value of the named measure
* @throws IllegalArgumentException if the named measure is not supported
*/
@Override
public double getMeasure(String additionalMeasureName) {
if (m_Stats == null) {
throw new IllegalArgumentException(additionalMeasureName
+ " not supported (NearestNeighbourSearch)");
} else {
return m_Stats.getMeasure(additionalMeasureName);
}
}
/**
* sorts the two given arrays.
*
* @param arrayToSort The array sorting should be based on.
* @param linkedArray The array that should have the same ordering as
* arrayToSort.
*/
public static void combSort11(double arrayToSort[], int linkedArray[]) {
int switches, j, top, gap;
double hold1;
int hold2;
gap = arrayToSort.length;
do {
gap = (int) (gap / 1.3);
switch (gap) {
case 0:
gap = 1;
break;
case 9:
case 10:
gap = 11;
break;
default:
break;
}
switches = 0;
top = arrayToSort.length - gap;
for (int i = 0; i < top; i++) {
j = i + gap;
if (arrayToSort[i] > arrayToSort[j]) {
hold1 = arrayToSort[i];
hold2 = linkedArray[i];
arrayToSort[i] = arrayToSort[j];
linkedArray[i] = linkedArray[j];
arrayToSort[j] = hold1;
linkedArray[j] = hold2;
switches++;
}// endif
}// endfor
} while (switches > 0 || gap > 1);
}
/**
* Partitions the instances around a pivot. Used by quicksort and
* kthSmallestValue.
*
* @param arrayToSort the array of doubles to be sorted
* @param linkedArray the linked array
* @param l the first index of the subset
* @param r the last index of the subset
* @return the index of the middle element
*/
protected static int partition(double[] arrayToSort, double[] linkedArray,
int l, int r) {
double pivot = arrayToSort[(l + r) / 2];
double help;
while (l < r) {
while ((arrayToSort[l] < pivot) && (l < r)) {
l++;
}
while ((arrayToSort[r] > pivot) && (l < r)) {
r--;
}
if (l < r) {
help = arrayToSort[l];
arrayToSort[l] = arrayToSort[r];
arrayToSort[r] = help;
help = linkedArray[l];
linkedArray[l] = linkedArray[r];
linkedArray[r] = help;
l++;
r--;
}
}
if ((l == r) && (arrayToSort[r] > pivot)) {
r--;
}
return r;
}
/**
* performs quicksort.
*
* @param arrayToSort the array to sort
* @param linkedArray the linked array
* @param left the first index of the subset
* @param right the last index of the subset
*/
public static void quickSort(double[] arrayToSort, double[] linkedArray,
int left, int right) {
if (left < right) {
int middle = partition(arrayToSort, linkedArray, left, right);
quickSort(arrayToSort, linkedArray, left, middle);
quickSort(arrayToSort, linkedArray, middle + 1, right);
}
}
}
|
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/neighboursearch/PerformanceStats.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/>.
*/
/*
* PerformanceStats.java
* Copyright (C) 2007-2012 University of Waikato, Hamilton, New Zealand
*/
package weka.core.neighboursearch;
import java.io.Serializable;
import java.util.Enumeration;
import java.util.Vector;
import weka.core.AdditionalMeasureProducer;
import weka.core.RevisionHandler;
import weka.core.RevisionUtils;
/**
* The class that measures the performance of a nearest
* neighbour search (NNS) algorithm.
*
* @author Ashraf M. Kibriya (amk14[at-the-rate]cs[dot]waikato[dot]ac[dot]nz)
* @version $Revision$
*/
public class PerformanceStats
implements AdditionalMeasureProducer, Serializable, RevisionHandler {
/** for serialization. */
private static final long serialVersionUID = -7215110351388368092L;
/** The total number of queries looked at. */
protected int m_NumQueries;
//Point-stats variables
/** The min and max data points looked for a query by
* the NNS algorithm. */
public double m_MinP, m_MaxP;
/** The sum of data points looked
* at for all the queries.
*/
public double m_SumP;
/** The squared sum of data points looked
* at for all the queries.
*/
public double m_SumSqP;
/** The number of data points looked at
* for the current/last query.
*/
public double m_PointCount;
//Coord-stats variables
/** The min and max coordinates(attributes) looked
* at per query.
*/
public double m_MinC, m_MaxC;
/** The sum of coordinates/attributes looked at
* for all the queries.
*/
public double m_SumC;
/** The squared sum of coordinates/attributes looked at
* for all the queries.
*/
public double m_SumSqC;
/**
* The number of coordinates looked at for
* the current/last query.
*/
public double m_CoordCount;
/**
* default constructor.
*/
public PerformanceStats() {
reset();
}
/**
* Resets all internal fields/counters.
*/
public void reset() {
m_NumQueries = 0;
//point stats
m_SumP = m_SumSqP = m_PointCount = 0;
m_MinP = Integer.MAX_VALUE;
m_MaxP = Integer.MIN_VALUE;
//coord stats
m_SumC = m_SumSqC = m_CoordCount = 0;
m_MinC = Integer.MAX_VALUE;
m_MaxC = Integer.MIN_VALUE;
}
/**
* Signals start of the nearest neighbour search.
* Initializes the stats object.
*/
public void searchStart() {
m_PointCount = 0;
m_CoordCount = 0;
}
/**
* Signals end of the nearest neighbour search.
* Calculates the statistics for the search.
*/
public void searchFinish() {
m_NumQueries++; m_SumP += m_PointCount; m_SumSqP += m_PointCount*m_PointCount;
if (m_PointCount < m_MinP) m_MinP = m_PointCount;
if (m_PointCount > m_MaxP) m_MaxP = m_PointCount;
//coord stats
double coordsPerPt = m_CoordCount / m_PointCount;;
m_SumC += coordsPerPt; m_SumSqC += coordsPerPt*coordsPerPt;
if(coordsPerPt < m_MinC) m_MinC = coordsPerPt;
if(coordsPerPt > m_MaxC) m_MaxC = coordsPerPt;
}
/**
* Increments the point count
* (number of datapoints looked at).
*/
public void incrPointCount() {
m_PointCount++;
}
/**
* Increments the coordinate count
* (number of coordinates/attributes
* looked at).
*/
public void incrCoordCount() {
m_CoordCount++;
}
/**
* adds the given number to the point count.
*
* @param n The number to add to the point count.
*/
public void updatePointCount(int n) {
m_PointCount += n;
}
/**
* Returns the number of queries.
*
* @return The number of queries.
*/
public int getNumQueries() {
return m_NumQueries;
}
/**
* Returns the total number of points visited.
*
* @return The total number.
*/
public double getTotalPointsVisited() {
return m_SumP;
}
/**
* Returns the mean of points visited.
*
* @return The mean points visited.
*/
public double getMeanPointsVisited() {
return m_SumP/(double)m_NumQueries;
}
/**
* Returns the standard deviation of points visited.
*
* @return The standard deviation.
*/
public double getStdDevPointsVisited() {
return Math.sqrt((m_SumSqP - (m_SumP*m_SumP)/(double)m_NumQueries)/(m_NumQueries-1));
}
/**
* Returns the minimum of points visited.
*
* @return The minimum.
*/
public double getMinPointsVisited() {
return m_MinP;
}
/**
* Returns the maximum of points visited.
*
* @return The maximum.
*/
public double getMaxPointsVisited() {
return m_MaxP;
}
/*************----------Coord Stat functions---------**************/
/**
* Returns the total sum of coords per point.
*
* @return The total per point.
*/
public double getTotalCoordsPerPoint() {
return m_SumC;
}
/**
* Returns the mean of coords per point.
*
* @return The mean.
*/
public double getMeanCoordsPerPoint() {
return m_SumC/(double)m_NumQueries;
}
/**
* Returns the standard deviation of coords per point.
*
* @return The standard deviation.
*/
public double getStdDevCoordsPerPoint() {
return Math.sqrt((m_SumSqC - (m_SumC*m_SumC)/(double)m_NumQueries)/(m_NumQueries-1));
}
/**
* Returns the minimum of coords per point.
*
* @return The minimum.
*/
public double getMinCoordsPerPoint() {
return m_MinC;
}
/**
* Returns the maximum of coords per point.
*
* @return The maximum.
*/
public double getMaxCoordsPerPoint() {
return m_MaxC;
}
/*****----MiscFunctions----****/
/**
* Returns an enumeration of the additional measure names.
*
* @return An enumeration of the measure names.
*/
public Enumeration<String> enumerateMeasures() {
Vector<String> newVector = new Vector<String>();
newVector.addElement("measureTotal_points_visited");
newVector.addElement("measureMean_points_visited");
newVector.addElement("measureStdDev_points_visited");
newVector.addElement("measureMin_points_visited");
newVector.addElement("measureMax_points_visited");
//coord stats
newVector.addElement("measureTotalCoordsPerPoint");
newVector.addElement("measureMeanCoordsPerPoint");
newVector.addElement("measureStdDevCoordsPerPoint");
newVector.addElement("measureMinCoordsPerPoint");
newVector.addElement("measureMaxCoordsPerPoint");
return newVector.elements();
}
/**
* Returns the value of the named measure.
*
* @param additionalMeasureName The name of the measure to query for
* its value.
* @return The value of the named measure.
* @throws IllegalArgumentException If the named measure is not
* supported.
*/
public double getMeasure(String additionalMeasureName) throws IllegalArgumentException {
if (additionalMeasureName.compareToIgnoreCase("measureTotal_points_visited") == 0) {
return (double) getTotalPointsVisited();
} else if (additionalMeasureName.compareToIgnoreCase("measureMean_points_visited") == 0) {
return (double) getMeanPointsVisited();
} else if (additionalMeasureName.compareToIgnoreCase("measureStdDev_points_visited") == 0) {
return (double) getStdDevPointsVisited();
} else if (additionalMeasureName.compareToIgnoreCase("measureMin_points_visited") == 0) {
return (double) getMinPointsVisited();
} else if (additionalMeasureName.compareToIgnoreCase("measureMax_points_visited") == 0) {
return (double) getMaxPointsVisited();
}
//coord stats
else if (additionalMeasureName.compareToIgnoreCase("measureTotalCoordsPerPoint") == 0) {
return (double) getTotalCoordsPerPoint();
} else if (additionalMeasureName.compareToIgnoreCase("measureMeanCoordsPerPoint") == 0) {
return (double) getMeanCoordsPerPoint();
} else if (additionalMeasureName.compareToIgnoreCase("measureStdDevCoordsPerPoint") == 0) {
return (double) getStdDevCoordsPerPoint();
} else if (additionalMeasureName.compareToIgnoreCase("measureMinCoordsPerPoint") == 0) {
return (double) getMinCoordsPerPoint();
} else if (additionalMeasureName.compareToIgnoreCase("measureMaxCoordsPerPoint") == 0) {
return (double) getMaxCoordsPerPoint();
} else {
throw new IllegalArgumentException(additionalMeasureName
+ " not supported by PerformanceStats.");
}
}
/**
* Returns a string representation of the statistics.
*
* @return The statistics as string.
*/
public String getStats() {
StringBuffer buf = new StringBuffer();
buf.append(" min, max, total, mean, stddev\n");
buf.append("Points: "+getMinPointsVisited()+", "+getMaxPointsVisited()+","+getTotalPointsVisited()+
","+getMeanPointsVisited()+", "+getStdDevPointsVisited()+"\n");
return buf.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/core
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/neighboursearch/TreePerformanceStats.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/>.
*/
/*
* TreePerformanceStats.java
* Copyright (C) 2007-2012 University of Waikato, Hamilton, New Zealand
*/
package weka.core.neighboursearch;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Vector;
import weka.core.RevisionUtils;
/**
* The class that measures the performance of a tree based
* nearest neighbour search algorithm.
*
* @author Ashraf M. Kibriya (amk14[at-the-rate]cs[dot]waikato[dot]ac[dot]nz)
* @version $Revision$
*/
public class TreePerformanceStats
extends PerformanceStats {
/** for serialization. */
private static final long serialVersionUID = -6637636693340810373L;
// Variables for leaves
/** The min and max number leaf nodes looked
* for a query by the tree based NNS algorithm. */
protected int m_MinLeaves, m_MaxLeaves;
/** The sum of leaf nodes looked
* at for all the queries.
*/
protected int m_SumLeaves;
/** The squared sum of leaf nodes looked
* at for all the queries.
*/
protected int m_SumSqLeaves;
/** The number of leaf nodes looked at
* for the current/last query.
*/
protected int m_LeafCount;
// Variables for internal nodes
/** The min and max number internal nodes looked
* for a query by the tree based NNS algorithm. */
protected int m_MinIntNodes, m_MaxIntNodes;
/** The sum of internal nodes looked
* at for all the queries.
*/
protected int m_SumIntNodes;
/** The squared sum of internal nodes looked
* at for all the queries.
*/
protected int m_SumSqIntNodes;
/** The number of internal nodes looked at
* for the current/last query.
*/
protected int m_IntNodeCount;
/**
* Default constructor.
*/
public TreePerformanceStats() {
reset();
}
/**
* Resets all internal fields/counters.
*/
public void reset() {
super.reset();
//initializing leaf variables
m_SumLeaves = m_SumSqLeaves = m_LeafCount = 0;
m_MinLeaves = Integer.MAX_VALUE;
m_MaxLeaves = Integer.MIN_VALUE;
//initializing internal variables
m_SumIntNodes = m_SumSqIntNodes = m_IntNodeCount = 0;
m_MinIntNodes = Integer.MAX_VALUE;
m_MaxIntNodes = Integer.MIN_VALUE;
}
/**
* Signals start of the nearest neighbour search.
* Initializes the stats object.
*/
public void searchStart() {
super.searchStart();
m_LeafCount = 0;
m_IntNodeCount = 0;
}
/**
* Signals end of the nearest neighbour search.
* Calculates the statistics for the search.
*/
public void searchFinish() {
super.searchFinish();
//updating stats for leaf nodes
m_SumLeaves += m_LeafCount; m_SumSqLeaves += m_LeafCount*m_LeafCount;
if (m_LeafCount < m_MinLeaves) m_MinLeaves = m_LeafCount;
if (m_LeafCount > m_MaxLeaves) m_MaxLeaves = m_LeafCount;
//updating stats for internal nodes
m_SumIntNodes += m_IntNodeCount; m_SumSqIntNodes += m_IntNodeCount*m_IntNodeCount;
if (m_IntNodeCount < m_MinIntNodes) m_MinIntNodes = m_IntNodeCount;
if (m_IntNodeCount > m_MaxIntNodes) m_MaxIntNodes = m_IntNodeCount;
}
/**
* Increments the leaf count.
*/
public void incrLeafCount() {
m_LeafCount++;
}
/**
* Increments the internal node count.
*/
public void incrIntNodeCount() {
m_IntNodeCount++;
}
// Getter functions for leaves
/**
* Returns the total number of leaves visited.
*
* @return The total number.
*/
public int getTotalLeavesVisited() {
return m_SumLeaves;
}
/**
* Returns the mean of number of leaves visited.
*
* @return The mean number of leaves visited.
*/
public double getMeanLeavesVisited() {
return m_SumLeaves/(double)m_NumQueries;
}
/**
* Returns the standard deviation of leaves visited.
*
* @return The standard deviation of leaves visited.
*/
public double getStdDevLeavesVisited() {
return Math.sqrt((m_SumSqLeaves - (m_SumLeaves*m_SumLeaves)/(double)m_NumQueries)/(m_NumQueries-1));
}
/**
* Returns the minimum number of leaves visited.
*
* @return The minimum number of leaves visited.
*/
public int getMinLeavesVisited() {
return m_MinLeaves;
}
/**
* Returns the maximum number of leaves visited.
*
* @return The maximum number of leaves visited.
*/
public int getMaxLeavesVisited() {
return m_MaxLeaves;
}
// Getter functions for internal nodes
/**
* Returns the total number of internal nodes visited.
*
* @return The total number of internal nodes visited.
*/
public int getTotalIntNodesVisited() {
return m_SumIntNodes;
}
/**
* Returns the mean of internal nodes visited.
*
* @return The mean number of internal nodes
* visited.
*/
public double getMeanIntNodesVisited() {
return m_SumIntNodes/(double)m_NumQueries;
}
/**
* Returns the standard deviation of internal nodes visited.
*
* @return The standard deviation of internal nodes visited.
*/
public double getStdDevIntNodesVisited() {
return Math.sqrt((m_SumSqIntNodes - (m_SumIntNodes*m_SumIntNodes)/(double)m_NumQueries)/(m_NumQueries-1));
}
/**
* Returns the minimum of internal nodes visited.
*
* @return The minimum of internal nodes visited.
*/
public int getMinIntNodesVisited() {
return m_MinIntNodes;
}
/**
* returns the maximum of internal nodes visited.
*
* @return The maximum of internal nodes visited.
*/
public int getMaxIntNodesVisited() {
return m_MaxIntNodes;
}
/**
* Returns an enumeration of the additional measure names.
*
* @return An enumeration of the measure names.
*/
public Enumeration<String> enumerateMeasures() {
Vector<String> newVector = new Vector<String>();
newVector.addAll(Collections.list(super.enumerateMeasures()));
newVector.addElement("measureTotal_nodes_visited");
newVector.addElement("measureMean_nodes_visited");
newVector.addElement("measureStdDev_nodes_visited");
newVector.addElement("measureMin_nodes_visited");
newVector.addElement("measureMax_nodes_visited");
//coord stats
newVector.addElement("measureTotal_leaves_visited");
newVector.addElement("measureMean_leaves_visited");
newVector.addElement("measureStdDev_leaves_visited");
newVector.addElement("measureMin_leaves_visited");
newVector.addElement("measureMax_leaves_visited");
return newVector.elements();
}
/**
* Returns the value of the named measure.
*
* @param additionalMeasureName The name of the measure to query for
* its value.
* @return The value of the named measure.
* @throws IllegalArgumentException If the named measure is not
* supported.
*/
public double getMeasure(String additionalMeasureName) throws IllegalArgumentException {
if (additionalMeasureName.compareToIgnoreCase("measureTotal_nodes_visited") == 0) {
return (double) getTotalIntNodesVisited();
} else if (additionalMeasureName.compareToIgnoreCase("measureMean_nodes_visited") == 0) {
return (double) getMeanIntNodesVisited();
} else if (additionalMeasureName.compareToIgnoreCase("measureStdDev_nodes_visited") == 0) {
return (double) getStdDevIntNodesVisited();
} else if (additionalMeasureName.compareToIgnoreCase("measureMin_nodes_visited") == 0) {
return (double) getMinIntNodesVisited();
} else if (additionalMeasureName.compareToIgnoreCase("measureMax_nodes_visited") == 0) {
return (double) getMaxIntNodesVisited();
}
//coord stats
else if (additionalMeasureName.compareToIgnoreCase("measureTotal_leaves_visited") == 0) {
return (double) getTotalLeavesVisited();
} else if (additionalMeasureName.compareToIgnoreCase("measureMean_leaves_visited") == 0) {
return (double) getMeanLeavesVisited();
} else if (additionalMeasureName.compareToIgnoreCase("measureStdDev_leaves_visited") == 0) {
return (double) getStdDevLeavesVisited();
} else if (additionalMeasureName.compareToIgnoreCase("measureMin_leaves_visited") == 0) {
return (double) getMinLeavesVisited();
} else if (additionalMeasureName.compareToIgnoreCase("measureMax_leaves_visited") == 0) {
return (double) getMaxLeavesVisited();
} else {
return super.getMeasure(additionalMeasureName);
}
}
/**
* Returns a string representation of the statistics.
*
* @return The statistics as string.
*/
public String getStats() {
StringBuffer buf = new StringBuffer(super.getStats());
buf.append("leaves: "+getMinLeavesVisited()+", "+getMaxLeavesVisited()+
","+getTotalLeavesVisited()+","+getMeanLeavesVisited()+", "+getStdDevLeavesVisited()+"\n");
buf.append("Int nodes: "+getMinIntNodesVisited()+", "+getMaxIntNodesVisited()+
","+getTotalIntNodesVisited()+","+getMeanIntNodesVisited()+", "+getStdDevIntNodesVisited()+"\n");
return buf.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/core/neighboursearch
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/neighboursearch/balltrees/BallNode.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/>.
*/
/*
* BallNode.java
* Copyright (C) 2007-2012 University of Waikato, Hamilton, New Zealand
*/
package weka.core.neighboursearch.balltrees;
import java.io.Serializable;
import weka.core.DenseInstance;
import weka.core.DistanceFunction;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.RevisionHandler;
import weka.core.RevisionUtils;
/**
* Class representing a node of a BallTree.
*
* @author Ashraf M. Kibriya (amk14[at-the-rate]cs[dot]waikato[dot]ac[dot]nz)
* @version $Revision$
*/
public class BallNode
implements Serializable, RevisionHandler {
/** for serialization. */
private static final long serialVersionUID = -8289151861759883510L;
/**
* The start index of the portion of the master index array,
* which stores the indices of the instances/points the node
* contains.
*/
public int m_Start;
/**
* The end index of the portion of the master index array,
* which stores indices of the instances/points the node
* contains.
*/
public int m_End;
/** The number of instances/points in the node. */
public int m_NumInstances;
/** The node number/id. */
public int m_NodeNumber;
/** The attribute that splits this node (not
* always used). */
public int m_SplitAttrib = -1;
/** The value of m_SpiltAttrib that splits this
* node (not always used).
*/
public double m_SplitVal = -1;
/** The left child of the node. */
public BallNode m_Left = null;
/** The right child of the node. */
public BallNode m_Right = null;
/**
* The pivot/centre of the ball.
*/
protected Instance m_Pivot;
/** The radius of this ball (hyper sphere). */
protected double m_Radius;
/**
* Constructor.
* @param nodeNumber The node's number/id.
*/
public BallNode(int nodeNumber) {
m_NodeNumber = nodeNumber;
}
/**
* Creates a new instance of BallNode.
* @param start The begining index of the portion of
* the master index array belonging to this node.
* @param end The end index of the portion of the
* master index array belonging to this node.
* @param nodeNumber The node's number/id.
*/
public BallNode(int start, int end, int nodeNumber) {
m_Start = start;
m_End = end;
m_NodeNumber = nodeNumber;
m_NumInstances = end - start + 1;
}
/**
* Creates a new instance of BallNode.
* @param start The begining index of the portion of
* the master index array belonging to this node.
* @param end The end index of the portion of the
* master index array belonging to this node.
* @param nodeNumber The node's number/id.
* @param pivot The pivot/centre of the node's ball.
* @param radius The radius of the node's ball.
*/
public BallNode(int start, int end, int nodeNumber, Instance pivot, double radius) {
m_Start = start;
m_End = end;
m_NodeNumber = nodeNumber;
m_Pivot = pivot;
m_Radius = radius;
m_NumInstances = end - start + 1;
}
/**
* Returns true if the node is a leaf node (if
* both its left and right child are null).
* @return true if the node is a leaf node.
*/
public boolean isALeaf() {
return (m_Left==null && m_Right==null);
}
/**
* Sets the the start and end index of the
* portion of the master index array that is
* assigned to this node.
* @param start The start index of the
* master index array.
* @param end The end index of the master
* indext array.
*/
public void setStartEndIndices(int start, int end) {
m_Start = start;
m_End = end;
m_NumInstances = end - start + 1;
}
/**
* Sets the pivot/centre of this nodes
* ball.
* @param pivot The centre/pivot.
*/
public void setPivot(Instance pivot) {
m_Pivot = pivot;
}
/**
* Returns the pivot/centre of the
* node's ball.
* @return The ball pivot/centre.
*/
public Instance getPivot() {
return m_Pivot;
}
/**
* Sets the radius of the node's
* ball.
* @param radius The radius of the nodes ball.
*/
public void setRadius(double radius) {
m_Radius = radius;
}
/**
* Returns the radius of the node's ball.
* @return Radius of node's ball.
*/
public double getRadius() {
return m_Radius;
}
/**
* Returns the number of instances in the
* hyper-spherical region of this node.
* @return The number of instances in the
* node.
*/
public int numInstances() {
return (m_End-m_Start+1);
}
/**
* Calculates the centroid pivot of a node. The node is given
* in the form of an indices array that contains the
* indices of the points inside the node.
* @param instList The indices array pointing to the
* instances in the node.
* @param insts The actual instances. The instList
* points to instances in this object.
* @return The calculated centre/pivot of the node.
*/
public static Instance calcCentroidPivot(int[] instList, Instances insts) {
double[] attrVals = new double[insts.numAttributes()];
Instance temp;
for(int i=0; i<instList.length; i++) {
temp = insts.instance(instList[i]);
for(int j=0; j<temp.numValues(); j++) {
attrVals[j] += temp.valueSparse(j);
}
}
for(int j=0, numInsts=instList.length; j<attrVals.length; j++) {
attrVals[j] /= numInsts;
}
temp = new DenseInstance(1.0, attrVals);
return temp;
}
/**
* Calculates the centroid pivot of a node. The node is given
* in the form of the portion of an indices array that
* contains the indices of the points inside the node.
* @param start The start index marking the start of
* the portion belonging to the node.
* @param end The end index marking the end of the
* portion in the indices array that belongs to the node.
* @param instList The indices array pointing to the
* instances in the node.
* @param insts The actual instances. The instList
* points to instances in this object.
* @return The calculated centre/pivot of the node.
*/
public static Instance calcCentroidPivot(int start, int end, int[] instList,
Instances insts) {
double[] attrVals = new double[insts.numAttributes()];
Instance temp;
for(int i=start; i<=end; i++) {
temp = insts.instance(instList[i]);
for(int j=0; j<temp.numValues(); j++) {
attrVals[j] += temp.valueSparse(j);
}
}
for(int j=0, numInsts=end-start+1; j<attrVals.length; j++) {
attrVals[j] /= numInsts;
}
temp = new DenseInstance(1.0, attrVals);
return temp;
}
/**
* Calculates the radius of node.
*
* @param instList The indices array containing the indices of the
* instances inside the node.
* @param insts The actual instances object. instList points to
* instances in this object.
* @param pivot The centre/pivot of the node.
* @param distanceFunction The distance fuction to use to calculate
* the radius.
* @return The radius of the node.
* @throws Exception If there is some problem in calculating the
* radius.
*/
public static double calcRadius(int[] instList, Instances insts,Instance pivot,
DistanceFunction distanceFunction)
throws Exception {
return calcRadius(0, instList.length-1, instList, insts,
pivot, distanceFunction);
}
/**
* Calculates the radius of a node.
*
* @param start The start index of the portion in indices array
* that belongs to the node.
* @param end The end index of the portion in indices array
* that belongs to the node.
* @param instList The indices array holding indices of
* instances.
* @param insts The actual instances. instList points to
* instances in this object.
* @param pivot The centre/pivot of the node.
* @param distanceFunction The distance function to use to
* calculate the radius.
* @return The radius of the node.
* @throws Exception If there is some problem calculating the
* radius.
*/
public static double calcRadius(int start, int end, int[] instList,
Instances insts, Instance pivot,
DistanceFunction distanceFunction)
throws Exception {
double radius = Double.NEGATIVE_INFINITY;
for(int i=start; i<=end; i++) {
double dist = distanceFunction.distance(pivot,
insts.instance(instList[i]), Double.POSITIVE_INFINITY);
if(dist>radius)
radius = dist;
}
return Math.sqrt(radius);
}
/**
* Calculates the centroid pivot of a node based on its
* two child nodes (if merging two nodes).
* @param child1 The first child of the node.
* @param child2 The second child of the node.
* @param insts The set of instances on which
* the tree is (or is to be) built.
* @return The centre/pivot of the node.
* @throws Exception If there is some problem calculating
* the pivot.
*/
public static Instance calcPivot(BallNode child1, BallNode child2,
Instances insts) throws Exception {
Instance p1 = child1.getPivot(), p2 = child2.getPivot();
double[] attrVals = new double[p1.numAttributes()];
for(int j=0; j<attrVals.length; j++) {
attrVals[j] += p1.value(j);
attrVals[j] += p2.value(j);
attrVals[j] /= 2D;
}
p1 = new DenseInstance(1.0, attrVals);
return p1;
}
/**
* Calculates the radius of a node based on its two
* child nodes (if merging two nodes).
* @param child1 The first child of the node.
* @param child2 The second child of the node.
* @param pivot The centre/pivot of the node.
* @param distanceFunction The distance function to
* use to calculate the radius
* @return The radius of the node.
* @throws Exception If there is some problem
* in calculating the radius.
*/
public static double calcRadius(BallNode child1, BallNode child2,
Instance pivot,
DistanceFunction distanceFunction)
throws Exception {
Instance p1 = child1.getPivot(), p2 = child2.getPivot();
double radius = child1.getRadius() + distanceFunction.distance(p1, p2) +
child2.getRadius();
return radius/2;
}
/**
* 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/neighboursearch
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/neighboursearch/balltrees/BallSplitter.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/>.
*/
/*
* BallSplitter.java
* Copyright (C) 2007-2012 University of Waikato
*/
package weka.core.neighboursearch.balltrees;
import java.io.Serializable;
import java.util.Enumeration;
import java.util.Vector;
import weka.core.EuclideanDistance;
import weka.core.Instances;
import weka.core.Option;
import weka.core.OptionHandler;
import weka.core.RevisionHandler;
import weka.core.RevisionUtils;
/**
* Abstract class for splitting a ball tree's BallNode.
*
* @author Ashraf M. Kibriya (amk14[at-the-rate]cs[dot]waikato[dot]ac[dot]nz)
* @version $Revision$
*/
public abstract class BallSplitter implements Serializable, OptionHandler,
RevisionHandler {
/** ID to avoid warning */
private static final long serialVersionUID = -2233739562654159948L;
/** The instance on which the tree is built. */
protected Instances m_Instances;
/**
* The distance function (metric) from which the tree is (OR is to be) built.
*/
protected EuclideanDistance m_DistanceFunction;
/**
* The master index array that'll be reshuffled as nodes are split (and the
* tree is constructed).
*/
protected int[] m_Instlist;
/**
* default constructor.
*/
public BallSplitter() {
}
/**
* Creates a new instance of BallSplitter.
*
* @param instList The master index array.
* @param insts The instances on which the tree is (or is to be) built.
* @param e The Euclidean distance function to use for splitting.
*/
public BallSplitter(int[] instList, Instances insts, EuclideanDistance e) {
m_Instlist = instList;
m_Instances = insts;
m_DistanceFunction = e;
}
/**
* Checks whether if this ball splitter is correctly intialized or not (i.e.
* master index array, instances, and distance function is supplied or not)
*
* @throws Exception If the object is not correctly initialized.
*/
protected void correctlyInitialized() throws Exception {
if (m_Instances == null) {
throw new Exception("No instances supplied.");
} else if (m_Instlist == null) {
throw new Exception("No instance list supplied.");
} else if (m_DistanceFunction == null) {
throw new Exception("No Euclidean distance function supplied.");
} else if (m_Instances.numInstances() != m_Instlist.length) {
throw new Exception("The supplied instance list doesn't seem to match "
+ "the supplied instances");
}
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
return new Vector<Option>().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 {
}
/**
* Gets the current settings of the object.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
return new String[0];
}
/**
* Splits a node into two.
*
* @param node The node to split.
* @param numNodesCreated The number of nodes that so far have been created
* for the tree, so that the newly created nodes are assigned
* correct/meaningful node numbers/ids.
* @throws Exception If there is some problem in splitting the given node.
*/
public abstract void splitNode(BallNode node, int numNodesCreated)
throws Exception;
/**
* Sets the training instances on which the tree is (or is to be) built.
*
* @param inst The training instances.
*/
public void setInstances(Instances inst) {
m_Instances = inst;
}
/**
* Sets the master index array containing indices of the training instances.
* This array will be rearranged as the tree is built (or a node is split_),
* so that each node is assigned a portion in this array which contain the
* instances insides the node's region.
*
* @param instList The master index array.
*/
public void setInstanceList(int[] instList) {
m_Instlist = instList;
}
/**
* Sets the distance function used to (or to be used to) build the tree.
*
* @param func The distance function.
*/
public void setEuclideanDistanceFunction(EuclideanDistance func) {
m_DistanceFunction = func;
}
/**
* 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/neighboursearch
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/neighboursearch/balltrees/BallTreeConstructor.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/>.
*/
/*
* BallTreeConstructor.java
* Copyright (C) 2007-2012 University of Waikato, Hamilton, New Zealand
*/
package weka.core.neighboursearch.balltrees;
import java.io.Serializable;
import java.util.Enumeration;
import java.util.Vector;
import weka.core.DistanceFunction;
import weka.core.EuclideanDistance;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.Option;
import weka.core.OptionHandler;
import weka.core.RevisionHandler;
import weka.core.RevisionUtils;
import weka.core.Utils;
/**
* Abstract class for constructing a BallTree .
*
* @author Ashraf M. Kibriya (amk14[at-the-rate]cs[dot]waikato[dot]ac[dot]nz)
* @version $Revision$
*/
public abstract class BallTreeConstructor implements OptionHandler,
Serializable, RevisionHandler {
/** ID to avoid warning */
private static final long serialVersionUID = 982315539809240771L;
/** The maximum number of instances allowed in a leaf. */
protected int m_MaxInstancesInLeaf = 40;
/**
* The maximum relative radius of a leaf node (relative to the smallest ball
* enclosing all the data (training) points).
*/
protected double m_MaxRelLeafRadius = 0.001;
/**
* Should a parent ball completely enclose the balls of its two children, or
* only the points inside its children.
*/
protected boolean m_FullyContainChildBalls = false;
/** The instances on which to build the tree. */
protected Instances m_Instances;
/** The distance function to use to build the tree. */
protected DistanceFunction m_DistanceFunction;
/**
* The number of internal and leaf nodes in the built tree.
*/
protected int m_NumNodes;
/** The number of leaf nodes in the built tree. */
protected int m_NumLeaves;
/** The depth of the built tree. */
protected int m_MaxDepth;
/** The master index array. */
protected int[] m_InstList;
/**
* Creates a new instance of BallTreeConstructor.
*/
public BallTreeConstructor() {
}
/**
* Builds the ball tree.
*
* @return The root node of the tree.
* @throws Exception If there is problem building the tree.
*/
public abstract BallNode buildTree() throws Exception;
/**
* Adds an instance to the ball tree.
*
* @param node The root node of the tree.
* @param inst The instance to add to the tree.
* @return The new master index array after adding the instance.
* @throws Exception If there is some problem adding the given instance to the
* tree.
*/
public abstract int[] addInstance(BallNode node, Instance inst)
throws Exception;
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui.
*/
public String maxInstancesInLeafTipText() {
return "The maximum number of instances allowed in a leaf.";
}
/**
* Returns the maximum number of instances allowed in a leaf.
*
* @return The maximum number of instances allowed in a leaf.
*/
public int getMaxInstancesInLeaf() {
return m_MaxInstancesInLeaf;
}
/**
* Sets the maximum number of instances allowed in a leaf.
*
* @param num The maximum number of instances allowed in a leaf.
* @throws Exception If the num is < 1.
*/
public void setMaxInstancesInLeaf(int num) throws Exception {
if (num < 1) {
throw new Exception("The maximum number of instances in a leaf must "
+ "be >=1.");
}
m_MaxInstancesInLeaf = num;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui.
*/
public String maxRelativeLeafRadiusTipText() {
return "The maximum relative radius allowed for a leaf node. "
+ "Itis relative to the radius of the smallest ball "
+ "enclosing all the data points (that were used to "
+ "build the tree). This smallest ball would be the "
+ "same as the root node's ball, if ContainChildBalls "
+ "property is set to false (default).";
}
/**
* Returns the maximum relative radius of a leaf node. It is relative to the
* radius of the smallest ball enclosing all the data points (that were used
* to build the tree). This smallest ball would be the same as the root node's
* ball, if ContainChildBalls property is set to false (default).
*
* @return The maximum relative radius allowed for a leaf.
*/
public double getMaxRelativeLeafRadius() {
return m_MaxRelLeafRadius;
}
/**
* Sets the maximum relative radius, allowed for a leaf node. The radius is
* relative to the radius of the smallest ball enclosing all the data points
* (that were used to build the tree). This smallest ball would be the same as
* the root node's ball, if ContainChildBalls property is set to false
* (default).
*
* @param radius The maximum relative radius allowed for a leaf.
* @throws Exception If radius is < 0.0.
*/
public void setMaxRelativeLeafRadius(double radius) throws Exception {
if (radius < 0.0) {
throw new Exception("The radius for the leaves should be >= 0.0");
}
m_MaxRelLeafRadius = radius;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui.
*/
public String containChildBallsTipText() {
return "Whether to contain fully the child balls.";
}
/**
* Gets whether if a parent ball should completely enclose its two child
* balls.
*
* @return true if parent ball is to enclose its child balls.
*/
public boolean getContainChildBalls() {
return m_FullyContainChildBalls;
}
/**
* Sets whether if a parent ball should completely enclose its two child
* balls.
*
* @param containChildBalls Should be tree if parent ball is to enclose its
* child balls.
*/
public void setContainChildBalls(boolean containChildBalls) {
m_FullyContainChildBalls = containChildBalls;
}
/**
* Sets the instances on which the tree is to be built.
*
* @param inst The instances on which to build the ball tree.
*/
public void setInstances(Instances inst) {
m_Instances = inst;
}
/**
* Sets the master index array that points to instances in m_Instances, so
* that only this array is manipulated, and m_Instances is left untouched.
*
* @param instList The master index array.
*/
public void setInstanceList(int[] instList) {
m_InstList = instList;
}
/**
* Sets the distance function to use to build the tree.
*
* @param func The distance function.
*/
public void setEuclideanDistanceFunction(EuclideanDistance func) {
m_DistanceFunction = func;
}
/**
* Returns the number of nodes (internal + leaf) in the built tree.
*
* @return The number of nodes in the tree.
*/
public int getNumNodes() {
return m_NumNodes;
}
/**
* Returns the number of leaves in the built tree.
*
* @return The number of leaves in the tree.
*/
public int getNumLeaves() {
return m_NumLeaves;
}
/**
* Returns the depth of the built tree.
*
* @return The depth of the tree.
*/
public int getMaxDepth() {
return m_MaxDepth;
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> newVector = new Vector<Option>();
newVector.addElement(new Option(
"\tSet maximum number of instances in a leaf node\n" + "\t(default: 40)",
"N", 0, "-N <value>"));
newVector.addElement(new Option(
"\tSet internal nodes' radius to the sum \n"
+ "\tof the child balls radii. So that it \n"
+ "contains the child balls.", "R", 0, "-R"));
return newVector.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 optionString = Utils.getOption('N', options);
if (optionString.length() != 0) {
setMaxInstancesInLeaf(Integer.parseInt(optionString));
} else {
setMaxInstancesInLeaf(40);
}
setContainChildBalls(Utils.getFlag('R', options));
}
/**
* Gets the current settings.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> result = new Vector<String>();
result.add("-N");
result.add("" + getMaxInstancesInLeaf());
if (getContainChildBalls()) {
result.add("-R");
}
return result.toArray(new String[result.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/core/neighboursearch
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/neighboursearch/balltrees/BottomUpConstructor.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/>.
*/
/*
* BottomUpConstructor.java
* Copyright (C) 2007-2012 University of Waikato, Hamilton, New Zealand
*/
package weka.core.neighboursearch.balltrees;
import java.util.ArrayList;
import weka.core.DenseInstance;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.RevisionHandler;
import weka.core.RevisionUtils;
import weka.core.TechnicalInformation;
import weka.core.TechnicalInformation.Field;
import weka.core.TechnicalInformation.Type;
import weka.core.TechnicalInformationHandler;
/**
<!-- globalinfo-start -->
* The class that constructs a ball tree bottom up.
* <p/>
<!-- globalinfo-end -->
*
<!-- technical-bibtex-start -->
* BibTeX:
* <pre>
* @techreport{Omohundro1989,
* author = {Stephen M. Omohundro},
* institution = {International Computer Science Institute},
* month = {December},
* number = {TR-89-063},
* title = {Five Balltree Construction Algorithms},
* year = {1989}
* }
* </pre>
* <p/>
<!-- technical-bibtex-end -->
*
<!-- options-start -->
* Valid options are: <p/>
*
* <pre> -N <value>
* Set maximum number of instances in a leaf node
* (default: 40)</pre>
*
* <pre> -R
* Set internal nodes' radius to the sum
* of the child balls radii. So that it
* contains the child balls.</pre>
*
<!-- options-end -->
*
* @author Ashraf M. Kibriya (amk14[at-the-rate]cs[dot]waikato[dot]ac[dot]nz)
* @version $Revision$
*/
public class BottomUpConstructor
extends BallTreeConstructor
implements TechnicalInformationHandler {
/** for serialization. */
private static final long serialVersionUID = 5864250777657707687L;
/**
* Returns a string describing this nearest neighbour search algorithm.
*
* @return a description of the algorithm for displaying in the
* explorer/experimenter gui
*/
public String globalInfo() {
return "The class that constructs a ball tree bottom up.";
}
/**
* 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.TECHREPORT);
result.setValue(Field.AUTHOR, "Stephen M. Omohundro");
result.setValue(Field.YEAR, "1989");
result.setValue(Field.TITLE, "Five Balltree Construction Algorithms");
result.setValue(Field.MONTH, "December");
result.setValue(Field.NUMBER, "TR-89-063");
result.setValue(Field.INSTITUTION, "International Computer Science Institute");
return result;
}
/**
* Creates a new instance of BottomUpConstructor.
*/
public BottomUpConstructor() {
}
/**
* Builds the ball tree bottom up.
* @return The root node of the tree.
* @throws Exception If there is problem building
* the tree.
*/
public BallNode buildTree() throws Exception {
ArrayList<TempNode> list = new ArrayList<TempNode>();
for(int i=0; i<m_InstList.length; i++) {
TempNode n = new TempNode();
n.points = new int[1]; n.points[0] = m_InstList[i];
n.anchor = m_Instances.instance(m_InstList[i]);
n.radius = 0.0;
list.add(n);
}
return mergeNodes(list, 0, m_InstList.length-1, m_InstList);
}
/**
* Merges nodes into one top node.
*
* @param list List of bottom most nodes (the actual
* instances).
* @param startIdx The index marking the start of
* the portion of master index array containing
* instances that need to be merged.
* @param endIdx The index marking the end of
* the portion of master index array containing
* instances that need to be merged.
* @param instList The master index array.
* @return The root node of the tree resulting
* from merging of bottom most nodes.
* @throws Exception If there is some problem
* merging the nodes.
*/
protected BallNode mergeNodes(ArrayList<TempNode> list, int startIdx, int endIdx,
int[] instList) throws Exception {
double minRadius=Double.POSITIVE_INFINITY, tmpRadius;
Instance pivot, minPivot=null; int min1=-1, min2=-1;
int [] minInstList=null; int merge=1;
TempNode parent;
while(list.size() > 1) { //main merging loop
System.err.print("merge step: "+merge+++" \r");
minRadius = Double.POSITIVE_INFINITY;
min1 = -1; min2 = -1;
for(int i=0; i<list.size(); i++) {
TempNode first = (TempNode) list.get(i);
for(int j=i+1; j<list.size(); j++) {
TempNode second = (TempNode) list.get(j);
pivot = calcPivot(first, second, m_Instances);
tmpRadius = calcRadius(first, second);
if(tmpRadius < minRadius) {
minRadius = tmpRadius;
min1=i; min2=j;
minPivot = pivot;
}
}//end for(j)
}//end for(i)
parent = new TempNode();
parent.left = (TempNode) list.get(min1);
parent.right = (TempNode) list.get(min2);
minInstList = new int[parent.left.points.length+parent.right.points.length];
System.arraycopy(parent.left.points, 0, minInstList, 0, parent.left.points.length);
System.arraycopy(parent.right.points, 0, minInstList, parent.left.points.length,
parent.right.points.length);
parent.points = minInstList;
parent.anchor = minPivot;
parent.radius = BallNode.calcRadius(parent.points, m_Instances, minPivot, m_DistanceFunction);
list.remove(min1); list.remove(min2-1);
list.add(parent);
}//end while
System.err.println("");
TempNode tmpRoot = (TempNode)list.get(0);
if(m_InstList.length != tmpRoot.points.length)
throw new Exception("Root nodes instance list is of irregular length. " +
"Please check code.");
System.arraycopy(tmpRoot.points, 0, m_InstList, 0, tmpRoot.points.length);
m_NumNodes = m_MaxDepth = m_NumLeaves = 0;
tmpRadius = BallNode.calcRadius(instList, m_Instances, tmpRoot.anchor, m_DistanceFunction);
BallNode node = makeBallTree(tmpRoot, startIdx, endIdx, instList, 0, tmpRadius);
return node;
}
/**
* Makes ball tree nodes of temp nodes that were used
* in the merging process.
* @param node The temp root node.
* @param startidx The index marking the start of the
* portion of master index array containing instances
* to be merged.
* @param endidx The index marking the end of the
* portion of master index array containing instances
* to be merged.
* @param instList The master index array.
* @param depth The depth of the provided temp node.
* @param rootRadius The smallest ball enclosing all
* data points.
* @return The proper top BallTreeNode.
* @throws Exception If there is some problem.
*/
protected BallNode makeBallTree(TempNode node, int startidx, int endidx,
int[] instList, int depth, final double rootRadius) throws Exception {
BallNode ball=null;
Instance pivot;
if(m_MaxDepth < depth)
m_MaxDepth = depth;
if(node.points.length > m_MaxInstancesInLeaf &&
(rootRadius==0 ? false : node.radius/rootRadius >= m_MaxRelLeafRadius) &&
node.left!=null && node.right!=null) { //make an internal node
ball = new BallNode(
startidx, endidx, m_NumNodes,
(pivot=BallNode.calcCentroidPivot(startidx, endidx, instList, m_Instances)),
BallNode.calcRadius(startidx, endidx, instList, m_Instances, pivot,
m_DistanceFunction)
);
m_NumNodes += 1;
ball.m_Left = makeBallTree(node.left, startidx, startidx+node.left.points.length-1, instList, depth+1, rootRadius);
ball.m_Right= makeBallTree(node.right, startidx+node.left.points.length, endidx, instList, depth+1, rootRadius);
}
else { //make a leaf node
ball = new BallNode(startidx, endidx, m_NumNodes,
(pivot=BallNode.calcCentroidPivot(startidx, endidx, instList, m_Instances)),
BallNode.calcRadius(startidx, endidx, instList, m_Instances, pivot,
m_DistanceFunction)
);
m_NumNodes += 1;
m_NumLeaves++;
}
return ball;
}
/**
* Adds an instance to the ball tree.
* @param node The root node of the tree.
* @param inst The instance to add to the tree.
* @return The new master index array after adding the
* instance.
* @throws Exception Always as BottomUpConstructor
* does not allow addition of instances after batch
* construction.
*/
public int[] addInstance(BallNode node, Instance inst) throws Exception {
throw new Exception("BottomUpConstruction method does not allow addition " +
"of new Instances.");
}
/**
* Calculates the centroid pivot of a node based on its
* two child nodes.
* @param node1 The first child node.
* @param node2 The second child node.
* @param insts The instance on which the tree is to be
* built.
* @return The centre/pivot of the node.
* @throws Exception If there is some problem calculating
* the centre/pivot of the node.
*/
public Instance calcPivot(TempNode node1, TempNode node2, Instances insts)
throws Exception {
int classIdx = m_Instances.classIndex();
double[] attrVals = new double[insts.numAttributes()];
Instance temp;
double anchr1Ratio = (double)node1.points.length /
(node1.points.length+node2.points.length),
anchr2Ratio = (double)node2.points.length /
(node1.points.length+node2.points.length);
for(int k=0; k<node1.anchor.numValues(); k++) {
if(node1.anchor.index(k)==classIdx)
continue;
attrVals[k] += node1.anchor.valueSparse(k)*anchr1Ratio;
}
for(int k=0; k<node2.anchor.numValues(); k++) {
if(node2.anchor.index(k)==classIdx)
continue;
attrVals[k] += node2.anchor.valueSparse(k)*anchr2Ratio;
}
temp = new DenseInstance(1.0, attrVals);
return temp;
}
/**
* Calculates the radius of a node based on its two
* child nodes.
* @param n1 The first child node.
* @param n2 The second child node.
* @return The calculated radius of the the node.
* @throws Exception If there is some problem
* in calculating the radius.
*/
public double calcRadius(TempNode n1, TempNode n2) throws Exception {
Instance a1 = n1.anchor, a2 = n2.anchor;
double radius = n1.radius + m_DistanceFunction.distance(a1, a2) + n2.radius;
return radius/2;
}
/**
* Temp class to represent either a leaf node or an internal node. Should only
* have two children (could be the case one child is an instance and the
* other another node).
*
* @author Ashraf M. Kibriya (amk14[at-the-rate]cs[dot]waikato[dot]ac[dot]nz)
* @version $Revision$
*/
protected class TempNode
implements RevisionHandler {
/** The centre/pivot of the node. */
Instance anchor;
/** The radius of the node. */
double radius;
/** Indices of the points in the node. */
int [] points;
/** The node's left child. */
TempNode left = null;
/** The node's right child. */
TempNode right = null;
/**
* Prints the node.
* @return The node as a string.
*/
public String toString() {
StringBuffer bf = new StringBuffer();
bf.append("p: ");
for(int i=0; i<points.length; i++)
if(i!=0)
bf.append(", "+points[i]);
else
bf.append(""+points[i]);
return bf.toString();
}
/**
* Returns the revision string.
*
* @return the revision
*/
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
}
/**
* 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/neighboursearch
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/neighboursearch/balltrees/MedianDistanceFromArbitraryPoint.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/>.
*/
/*
* MedianDistanceFromArbitraryPoint.java
* Copyright (C) 2007-2012 University of Waikato, Hamilton, New Zealand
*/
package weka.core.neighboursearch.balltrees;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Random;
import java.util.Vector;
import weka.core.EuclideanDistance;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.Option;
import weka.core.RevisionUtils;
import weka.core.TechnicalInformation;
import weka.core.TechnicalInformation.Field;
import weka.core.TechnicalInformation.Type;
import weka.core.TechnicalInformationHandler;
import weka.core.Utils;
/**
* <!-- globalinfo-start --> Class that splits a BallNode of a ball tree using
* Uhlmann's described method.<br/>
* <br/>
* For information see:<br/>
* <br/>
* Jeffrey K. Uhlmann (1991). Satisfying general proximity/similarity queries
* with metric trees. Information Processing Letters. 40(4):175-179.<br/>
* <br/>
* Ashraf Masood Kibriya (2007). Fast Algorithms for Nearest Neighbour Search.
* Hamilton, New Zealand.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- technical-bibtex-start --> BibTeX:
*
* <pre>
* @article{Uhlmann1991,
* author = {Jeffrey K. Uhlmann},
* journal = {Information Processing Letters},
* month = {November},
* number = {4},
* pages = {175-179},
* title = {Satisfying general proximity/similarity queries with metric trees},
* volume = {40},
* year = {1991}
* }
*
* @mastersthesis{Kibriya2007,
* address = {Hamilton, New Zealand},
* author = {Ashraf Masood Kibriya},
* school = {Department of Computer Science, School of Computing and Mathematical Sciences, University of Waikato},
* title = {Fast Algorithms for Nearest Neighbour Search},
* year = {2007}
* }
* </pre>
* <p/>
* <!-- technical-bibtex-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -S <num>
* The seed value for the random number generator.
* (default: 17)
* </pre>
*
* <!-- options-end -->
*
* @author Ashraf M. Kibriya (amk14[at-the-rate]cs[dot]waikato[dot]ac[dot]nz)
* @version $Revision$
*/
public class MedianDistanceFromArbitraryPoint extends BallSplitter implements
TechnicalInformationHandler {
/** for serialization. */
private static final long serialVersionUID = 5617378551363700558L;
/** Seed for random number generator. */
protected int m_RandSeed = 17;
/**
* Random number generator for selecting an abitrary (random) point.
*/
protected Random m_Rand;
/** Constructor. */
public MedianDistanceFromArbitraryPoint() {
}
/**
* Constructor.
*
* @param instList The master index array.
* @param insts The instances on which the tree is (or is to be) built.
* @param e The Euclidean distance function to use for splitting.
*/
public MedianDistanceFromArbitraryPoint(int[] instList, Instances insts,
EuclideanDistance e) {
super(instList, insts, e);
}
/**
* Returns a string describing this nearest neighbour search algorithm.
*
* @return a description of the algorithm for displaying in the
* explorer/experimenter gui
*/
public String globalInfo() {
return "Class that splits a BallNode of a ball tree using Uhlmann's "
+ "described method.\n\n" + "For 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;
TechnicalInformation additional;
result = new TechnicalInformation(Type.ARTICLE);
result.setValue(Field.AUTHOR, "Jeffrey K. Uhlmann");
result.setValue(Field.TITLE,
"Satisfying general proximity/similarity queries with metric trees");
result.setValue(Field.JOURNAL, "Information Processing Letters");
result.setValue(Field.MONTH, "November");
result.setValue(Field.YEAR, "1991");
result.setValue(Field.NUMBER, "4");
result.setValue(Field.VOLUME, "40");
result.setValue(Field.PAGES, "175-179");
additional = result.add(Type.MASTERSTHESIS);
additional.setValue(Field.AUTHOR, "Ashraf Masood Kibriya");
additional.setValue(Field.TITLE,
"Fast Algorithms for Nearest Neighbour Search");
additional.setValue(Field.YEAR, "2007");
additional
.setValue(
Field.SCHOOL,
"Department of Computer Science, School of Computing and Mathematical Sciences, University of Waikato");
additional.setValue(Field.ADDRESS, "Hamilton, New Zealand");
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 seed value for the random number generator.\n"
+ "\t(default: 17)", "S", 1, "-S <num>"));
result.addAll(Collections.list(super.listOptions()));
return result.elements();
}
/**
* Parses a given list of options.
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -S <num>
* The seed value for the random number generator.
* (default: 17)
* </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 = Utils.getOption('S', options);
if (tmpStr.length() > 0) {
setRandomSeed(Integer.parseInt(tmpStr));
} else {
setRandomSeed(17);
}
super.setOptions(options);
}
/**
* Gets the current settings of the object.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> result = new Vector<String>();
result.add("-S");
result.add("" + getRandomSeed());
Collections.addAll(result, super.getOptions());
return result.toArray(new String[result.size()]);
}
/**
* Sets the seed for random number generator.
*
* @param seed The seed value to set.
*/
public void setRandomSeed(int seed) {
m_RandSeed = seed;
}
/**
* Returns the seed value of random number generator.
*
* @return The random seed currently in use.
*/
public int getRandomSeed() {
return m_RandSeed;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui.
*/
public String randomSeedTipText() {
return "The seed value for the random number generator.";
}
/**
* Splits a ball into two.
*
* @param node The node to split.
* @param numNodesCreated The number of nodes that so far have been created
* for the tree, so that the newly created nodes are assigned
* correct/meaningful node numbers/ids.
* @throws Exception If there is some problem in splitting the given node.
*/
@Override
public void splitNode(BallNode node, int numNodesCreated) throws Exception {
correctlyInitialized();
m_Rand = new Random(m_RandSeed);
int ridx = node.m_Start + m_Rand.nextInt(node.m_NumInstances);
Instance randomInst = (Instance) m_Instances.instance(m_Instlist[ridx])
.copy();
double[] distList = new double[node.m_NumInstances - 1];
Instance temp;
for (int i = node.m_Start, j = 0; i < node.m_End; i++, j++) {
temp = m_Instances.instance(m_Instlist[i]);
distList[j] = m_DistanceFunction.distance(randomInst, temp,
Double.POSITIVE_INFINITY);
}
int medianIdx = select(distList, m_Instlist, 0, distList.length - 1,
node.m_Start, (node.m_End - node.m_Start) / 2 + 1) + node.m_Start;
Instance pivot;
node.m_Left = new BallNode(node.m_Start, medianIdx, numNodesCreated + 1,
(pivot = BallNode.calcCentroidPivot(node.m_Start, medianIdx, m_Instlist,
m_Instances)), BallNode.calcRadius(node.m_Start, medianIdx, m_Instlist,
m_Instances, pivot, m_DistanceFunction));
node.m_Right = new BallNode(medianIdx + 1, node.m_End, numNodesCreated + 2,
(pivot = BallNode.calcCentroidPivot(medianIdx + 1, node.m_End,
m_Instlist, m_Instances)), BallNode.calcRadius(medianIdx + 1,
node.m_End, m_Instlist, m_Instances, pivot, m_DistanceFunction));
}
/**
* Partitions the instances around a pivot. Used by quicksort and
* kthSmallestValue.
*
* @param array The array of distances of the points to the arbitrarily
* selected point.
* @param index The master index array containing indices of the instances.
* @param l The relative begining index of the portion of master index array
* that should be partitioned.
* @param r The relative end index of the portion of master index array that
* should be partitioned.
* @param indexStart The absolute begining index of the portion of master
* index array that should be partitioned.
* @return the index of the middle element (in the master index array, i.e.
* index of the index of middle element).
*/
protected int partition(double[] array, int[] index, int l, int r,
final int indexStart) {
double pivot = array[(l + r) / 2];
int help;
while (l < r) {
while ((array[l] < pivot) && (l < r)) {
l++;
}
while ((array[r] > pivot) && (l < r)) {
r--;
}
if (l < r) {
help = index[indexStart + l];
index[indexStart + l] = index[indexStart + r];
index[indexStart + r] = help;
l++;
r--;
}
}
if ((l == r) && (array[r] > pivot)) {
r--;
}
return r;
}
/**
* Implements computation of the kth-smallest element according to Manber's
* "Introduction to Algorithms".
*
* @param array Array containing the distances of points from the arbitrarily
* selected.
* @param indices The master index array containing indices of the instances.
* @param left The relative begining index of the portion of the master index
* array in which to find the kth-smallest element.
* @param right The relative end index of the portion of the master index
* array in which to find the kth-smallest element.
* @param indexStart The absolute begining index of the portion of the master
* index array in which to find the kth-smallest element.
* @param k The value of k
* @return The index of the kth-smallest element
*/
protected int select(double[] array, int[] indices, int left, int right,
final int indexStart, int k) {
if (left == right) {
return left;
} else {
int middle = partition(array, indices, left, right, indexStart);
if ((middle - left + 1) >= k) {
return select(array, indices, left, middle, indexStart, k);
} else {
return select(array, indices, middle + 1, right, indexStart, k
- (middle - left + 1));
}
}
}
/**
* 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/neighboursearch
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/neighboursearch/balltrees/MedianOfWidestDimension.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/>.
*/
/*
* MedianOfWidestDimension.java
* Copyright (C) 2007-2012 University of Waikato, Hamilton, New Zealand
*/
package weka.core.neighboursearch.balltrees;
import java.util.Enumeration;
import java.util.Vector;
import weka.core.EuclideanDistance;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.NormalizableDistance;
import weka.core.Option;
import weka.core.OptionHandler;
import weka.core.RevisionUtils;
import weka.core.TechnicalInformation;
import weka.core.TechnicalInformation.Field;
import weka.core.TechnicalInformation.Type;
import weka.core.TechnicalInformationHandler;
import weka.core.Utils;
/**
* <!-- globalinfo-start --> Class that splits a BallNode of a ball tree based
* on the median value of the widest dimension of the points in the ball. It
* essentially implements Omohundro's KD construction algorithm.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- technical-bibtex-start --> BibTeX:
*
* <pre>
* @techreport{Omohundro1989,
* author = {Stephen M. Omohundro},
* institution = {International Computer Science Institute},
* month = {December},
* number = {TR-89-063},
* title = {Five Balltree Construction Algorithms},
* year = {1989}
* }
* </pre>
* <p/>
* <!-- technical-bibtex-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -N
* Normalize dimensions' widths.
* </pre>
*
* <!-- options-end -->
*
* @author Ashraf M. Kibriya (amk14[at-the-rate]cs[dot]waikato[dot]ac[dot]nz)
* @version $Revision$
*/
public class MedianOfWidestDimension extends BallSplitter implements
OptionHandler, TechnicalInformationHandler {
/** for serialization. */
private static final long serialVersionUID = 3054842574468790421L;
/**
* Should we normalize the widths(ranges) of the dimensions (attributes)
* before selecting the widest one.
*/
protected boolean m_NormalizeDimWidths = true;
/**
* Constructor.
*/
public MedianOfWidestDimension() {
}
/**
* Constructor.
*
* @param instList The master index array.
* @param insts The instances on which the tree is (or is to be) built.
* @param e The Euclidean distance function to use for splitting.
*/
public MedianOfWidestDimension(int[] instList, Instances insts,
EuclideanDistance e) {
super(instList, insts, e);
}
/**
* Returns a string describing this nearest neighbour search algorithm.
*
* @return a description of the algorithm for displaying in the
* explorer/experimenter gui
*/
public String globalInfo() {
return "Class that splits a BallNode of a ball tree based on the "
+ "median value of the widest dimension of the points in the ball. "
+ "It essentially implements Omohundro's KD construction algorithm.";
}
/**
* 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.TECHREPORT);
result.setValue(Field.AUTHOR, "Stephen M. Omohundro");
result.setValue(Field.YEAR, "1989");
result.setValue(Field.TITLE, "Five Balltree Construction Algorithms");
result.setValue(Field.MONTH, "December");
result.setValue(Field.NUMBER, "TR-89-063");
result.setValue(Field.INSTITUTION,
"International Computer Science Institute");
return result;
}
/**
* Splits a ball into two.
*
* @param node The node to split.
* @param numNodesCreated The number of nodes that so far have been created
* for the tree, so that the newly created nodes are assigned
* correct/meaningful node numbers/ids.
* @throws Exception If there is some problem in splitting the given node.
*/
@Override
public void splitNode(BallNode node, int numNodesCreated) throws Exception {
correctlyInitialized();
// int[] instList = getNodesInstsList(node);
double[][] ranges = m_DistanceFunction.initializeRanges(m_Instlist,
node.m_Start, node.m_End);
int splitAttrib = widestDim(ranges, m_DistanceFunction.getRanges());
// In this case median is defined to be either the middle value (in case of
// odd number of values) or the left of the two middle values (in case of
// even number of values).
int medianIdxIdx = node.m_Start + (node.m_End - node.m_Start) / 2;
// the following finds the median and also re-arranges the array so all
// elements to the left are < median and those to the right are > median.
int medianIdx = select(splitAttrib, m_Instlist, node.m_Start, node.m_End,
(node.m_End - node.m_Start) / 2 + 1); // Utils.select(array, indices,
// node.m_Start, node.m_End,
// (node.m_End-node.m_Start)/2+1);
// //(int)
// (node.m_NumInstances/2D+0.5D);
Instance pivot;
node.m_SplitAttrib = splitAttrib;
node.m_SplitVal = m_Instances.instance(m_Instlist[medianIdx]).value(
splitAttrib);
node.m_Left = new BallNode(node.m_Start, medianIdxIdx, numNodesCreated + 1,
(pivot = BallNode.calcCentroidPivot(node.m_Start, medianIdxIdx,
m_Instlist, m_Instances)), BallNode.calcRadius(node.m_Start,
medianIdxIdx, m_Instlist, m_Instances, pivot, m_DistanceFunction));
node.m_Right = new BallNode(medianIdxIdx + 1, node.m_End,
numNodesCreated + 2, (pivot = BallNode.calcCentroidPivot(
medianIdxIdx + 1, node.m_End, m_Instlist, m_Instances)),
BallNode.calcRadius(medianIdxIdx + 1, node.m_End, m_Instlist,
m_Instances, pivot, m_DistanceFunction));
}
/**
* Partitions the instances around a pivot. Used by quicksort and
* kthSmallestValue.
*
* @param attIdx The attribution/dimension based on which the instances should
* be partitioned.
* @param index The master index array containing indices of the instances.
* @param l The begining index of the portion of master index array that
* should be partitioned.
* @param r The end index of the portion of master index array that should be
* partitioned.
* @return the index of the middle element (in the master index array, i.e.
* index of the index of middle element).
*/
protected int partition(int attIdx, int[] index, int l, int r) {
double pivot = m_Instances.instance(index[(l + r) / 2]).value(attIdx);
int help;
while (l < r) {
while ((m_Instances.instance(index[l]).value(attIdx) < pivot) && (l < r)) {
l++;
}
while ((m_Instances.instance(index[r]).value(attIdx) > pivot) && (l < r)) {
r--;
}
if (l < r) {
help = index[l];
index[l] = index[r];
index[r] = help;
l++;
r--;
}
}
if ((l == r) && (m_Instances.instance(index[r]).value(attIdx) > pivot)) {
r--;
}
return r;
}
/**
* Implements computation of the kth-smallest element according to Manber's
* "Introduction to Algorithms".
*
* @param attIdx The dimension/attribute of the instances in which to find the
* kth-smallest element.
* @param indices The master index array containing indices of the instances.
* @param left The begining index of the portion of the master index array in
* which to find the kth-smallest element.
* @param right The end index of the portion of the master index array in
* which to find the kth-smallest element.
* @param k The value of k
* @return The index of the kth-smallest element
*/
public int select(int attIdx, int[] indices, int left, int right, int k) {
if (left == right) {
return left;
} else {
int middle = partition(attIdx, indices, left, right);
if ((middle - left + 1) >= k) {
return select(attIdx, indices, left, middle, k);
} else {
return select(attIdx, indices, middle + 1, right, k
- (middle - left + 1));
}
}
}
/**
* Returns the widest dimension. The width of each dimension (for the points
* inside the node) is normalized, if m_NormalizeNodeWidth is set to true.
*
* @param nodeRanges The attributes' range of the points inside the node that
* is to be split.
* @param universe The attributes' range for the whole point-space.
* @return The index of the attribute/dimension in which the points of the
* node have widest spread.
*/
protected int widestDim(double[][] nodeRanges, double[][] universe) {
final int classIdx = m_Instances.classIndex();
double widest = 0.0;
int w = -1;
if (m_NormalizeDimWidths) {
for (int i = 0; i < nodeRanges.length; i++) {
double newWidest = nodeRanges[i][NormalizableDistance.R_WIDTH]
/ universe[i][NormalizableDistance.R_WIDTH];
if (newWidest > widest) {
if (i == classIdx) {
continue;
}
widest = newWidest;
w = i;
}
}
} else {
for (int i = 0; i < nodeRanges.length; i++) {
if (nodeRanges[i][NormalizableDistance.R_WIDTH] > widest) {
if (i == classIdx) {
continue;
}
widest = nodeRanges[i][NormalizableDistance.R_WIDTH];
w = i;
}
}
}
return w;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String normalizeDimWidthsTipText() {
return "Whether to normalize the widths(ranges) of the dimensions "
+ "(attributes) before selecting the widest one.";
}
/**
* Should we normalize the widths(ranges) of the dimensions (attributes)
* before selecting the widest one.
*
* @param normalize Should be true if the widths are to be normalized.
*/
public void setNormalizeDimWidths(boolean normalize) {
m_NormalizeDimWidths = normalize;
}
/**
* Whether we are normalizing the widths(ranges) of the dimensions
* (attributes) or not.
*
* @return true if widths are being normalized.
*/
public boolean getNormalizeDimWidths() {
return m_NormalizeDimWidths;
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> newVector = new Vector<Option>();
newVector.addElement(new Option("\tNormalize dimensions' widths.", "N", 0,
"-N"));
return newVector.elements();
}
/**
* Parses a given list of options.
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -N
* Normalize dimensions' widths.
* </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 {
setNormalizeDimWidths(Utils.getFlag('N', options));
}
/**
* Gets the current settings.
*
* @return An array of strings suitable for passing to setOptions or to be
* displayed by a GenericObjectEditor.
*/
@Override
public String[] getOptions() {
Vector<String> result;
result = new Vector<String>();
if (getNormalizeDimWidths()) {
result.add("-N");
}
return result.toArray(new String[result.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/core/neighboursearch
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/neighboursearch/balltrees/MiddleOutConstructor.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/>.
*/
/*
* MiddleOutConstructor.java
* Copyright (C) 2007-2012 University of Waikato, Hamilton, New Zealand
*/
package weka.core.neighboursearch.balltrees;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Random;
import java.util.Vector;
import weka.core.DenseInstance;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.Option;
import weka.core.Randomizable;
import weka.core.RevisionHandler;
import weka.core.RevisionUtils;
import weka.core.TechnicalInformation;
import weka.core.TechnicalInformation.Field;
import weka.core.TechnicalInformation.Type;
import weka.core.TechnicalInformationHandler;
import weka.core.Utils;
/**
* <!-- globalinfo-start --> The class that builds a BallTree middle out.<br/>
* <br/>
* For more information see also:<br/>
* <br/>
* Andrew W. Moore: The Anchors Hierarchy: Using the Triangle Inequality to
* Survive High Dimensional Data. In: UAI '00: Proceedings of the 16th
* Conference on Uncertainty in Artificial Intelligence, San Francisco, CA, USA,
* 397-405, 2000.<br/>
* <br/>
* Ashraf Masood Kibriya (2007). Fast Algorithms for Nearest Neighbour Search.
* Hamilton, New Zealand.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- technical-bibtex-start --> BibTeX:
*
* <pre>
* @inproceedings{Moore2000,
* address = {San Francisco, CA, USA},
* author = {Andrew W. Moore},
* booktitle = {UAI '00: Proceedings of the 16th Conference on Uncertainty in Artificial Intelligence},
* pages = {397-405},
* publisher = {Morgan Kaufmann Publishers Inc.},
* title = {The Anchors Hierarchy: Using the Triangle Inequality to Survive High Dimensional Data},
* year = {2000}
* }
*
* @mastersthesis{Kibriya2007,
* address = {Hamilton, New Zealand},
* author = {Ashraf Masood Kibriya},
* school = {Department of Computer Science, School of Computing and Mathematical Sciences, University of Waikato},
* title = {Fast Algorithms for Nearest Neighbour Search},
* year = {2007}
* }
* </pre>
* <p/>
* <!-- technical-bibtex-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -S <num>
* The seed for the random number generator used
* in selecting random anchor.
* (default: 1)
* </pre>
*
* <pre>
* -R
* Use randomly chosen initial anchors.
* </pre>
*
* <!-- options-end -->
*
* @author Ashraf M. Kibriya (amk14[at-the-rate]cs[dot]waikato[dot]ac[dot]nz)
* @version $Revision$
*/
public class MiddleOutConstructor extends BallTreeConstructor implements
Randomizable, TechnicalInformationHandler {
/** for serialization. */
private static final long serialVersionUID = -8523314263062524462L;
/** Seed form random number generator. */
protected int m_RSeed = 1;
/**
* The random number generator for selecting the first anchor point randomly
* (if selecting randomly).
*/
protected Random rand = new Random(m_RSeed);
/**
* The radius of the smallest ball enclosing all the data points.
*/
private double rootRadius = -1;
/**
* True if the initial anchor is chosen randomly. False if it is the furthest
* point from the mean/centroid.
*/
protected boolean m_RandomInitialAnchor = true;
/**
* Creates a new instance of MiddleOutConstructor.
*/
public MiddleOutConstructor() {
}
/**
* Returns a string describing this nearest neighbour search algorithm.
*
* @return a description of the algorithm for displaying in the
* explorer/experimenter gui
*/
public String globalInfo() {
return "The class that builds a BallTree middle out.\n\n"
+ "For more information see also:\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;
TechnicalInformation additional;
result = new TechnicalInformation(Type.INPROCEEDINGS);
result.setValue(Field.AUTHOR, "Andrew W. Moore");
result
.setValue(
Field.TITLE,
"The Anchors Hierarchy: Using the Triangle Inequality to Survive High Dimensional Data");
result.setValue(Field.YEAR, "2000");
result
.setValue(
Field.BOOKTITLE,
"UAI '00: Proceedings of the 16th Conference on Uncertainty in Artificial Intelligence");
result.setValue(Field.PAGES, "397-405");
result.setValue(Field.PUBLISHER, "Morgan Kaufmann Publishers Inc.");
result.setValue(Field.ADDRESS, "San Francisco, CA, USA");
additional = result.add(Type.MASTERSTHESIS);
additional.setValue(Field.AUTHOR, "Ashraf Masood Kibriya");
additional.setValue(Field.TITLE,
"Fast Algorithms for Nearest Neighbour Search");
additional.setValue(Field.YEAR, "2007");
additional
.setValue(
Field.SCHOOL,
"Department of Computer Science, School of Computing and Mathematical Sciences, University of Waikato");
additional.setValue(Field.ADDRESS, "Hamilton, New Zealand");
return result;
}
/**
* Builds a ball tree middle out.
*
* @return The root node of the tree.
* @throws Exception If there is problem building the tree.
*/
@Override
public BallNode buildTree() throws Exception {
m_NumNodes = m_MaxDepth = m_NumLeaves = 0;
if (rootRadius == -1) {
rootRadius = BallNode
.calcRadius(m_InstList, m_Instances,
BallNode.calcCentroidPivot(m_InstList, m_Instances),
m_DistanceFunction);
}
BallNode root = buildTreeMiddleOut(0, m_Instances.numInstances() - 1);
return root;
}
/**
* Builds a ball tree middle out from the portion of the master index array
* given by supplied start and end index.
*
* @param startIdx The start of the portion in master index array.
* @param endIdx the end of the portion in master index array.
* @return The root node of the built tree.
* @throws Exception If there is some problem building the tree.
*/
protected BallNode buildTreeMiddleOut(int startIdx, int endIdx)
throws Exception {
Instance pivot;
double radius;
Vector<TempNode> anchors;
int numInsts = endIdx - startIdx + 1;
int numAnchors = (int) Math.round(Math.sqrt(numInsts));
// create anchor's hierarchy
if (numAnchors > 1) {
pivot = BallNode.calcCentroidPivot(startIdx, endIdx, m_InstList,
m_Instances);
radius = BallNode.calcRadius(startIdx, endIdx, m_InstList, m_Instances,
pivot, m_DistanceFunction);
if (numInsts <= m_MaxInstancesInLeaf
|| (rootRadius == 0 ? true : radius / rootRadius < m_MaxRelLeafRadius)) { // just
// make
// a
// leaf
// don't
// make
// anchors
// hierarchy
BallNode node = new BallNode(startIdx, endIdx, m_NumNodes, pivot,
radius);
return node;
}
anchors = new Vector<TempNode>(numAnchors);
createAnchorsHierarchy(anchors, numAnchors, startIdx, endIdx);
BallNode node = mergeNodes(anchors, startIdx, endIdx);
buildLeavesMiddleOut(node);
return node;
}// end anchors hierarchy
else {
BallNode node = new BallNode(startIdx, endIdx, m_NumNodes,
(pivot = BallNode.calcCentroidPivot(startIdx, endIdx, m_InstList,
m_Instances)), BallNode.calcRadius(startIdx, endIdx, m_InstList,
m_Instances, pivot, m_DistanceFunction));
return node;
}
}
/**
* Creates an anchors hierarchy from a portion of master index array.
*
* @param anchors The vector for putting the anchors into.
* @param numAnchors The number of anchors to create.
* @param startIdx The start of the portion of master index array.
* @param endIdx The end of the portion of master index array.
* @throws Exception If there is some problem in creating the hierarchy.
*/
protected void createAnchorsHierarchy(Vector<TempNode> anchors,
final int numAnchors, final int startIdx, final int endIdx)
throws Exception {
TempNode anchr1 = m_RandomInitialAnchor ? getRandomAnchor(startIdx, endIdx)
: getFurthestFromMeanAnchor(startIdx, endIdx);
TempNode amax = anchr1; // double maxradius = anchr1.radius;
TempNode newAnchor;
Vector<double[]> anchorDistances = new Vector<double[]>(numAnchors - 1);
anchors.add(anchr1);
// creating anchors
while (anchors.size() < numAnchors) {
// create new anchor
newAnchor = new TempNode();
newAnchor.points = new MyIdxList();
Instance newpivot = m_Instances.instance(amax.points.getFirst().idx);
newAnchor.anchor = newpivot;
newAnchor.idx = amax.points.getFirst().idx;
setInterAnchorDistances(anchors, newAnchor, anchorDistances);
if (stealPoints(newAnchor, anchors, anchorDistances)) {
newAnchor.radius = newAnchor.points.getFirst().distance;
} else {
newAnchor.radius = 0.0;
}
anchors.add(newAnchor);
// find new amax
amax = anchors.elementAt(0);
for (int i = 1; i < anchors.size(); i++) {
newAnchor = anchors.elementAt(i);
if (newAnchor.radius > amax.radius) {
amax = newAnchor;
}
}// end for
}// end while
}
/**
* Applies the middle out build procedure to the leaves of the tree. The leaf
* nodes should be the ones that were created by createAnchorsHierarchy(). The
* process continues recursively for the leaves created for each leaf of the
* given tree until for some leaf node <= m_MaxInstancesInLeaf instances
* remain in the leaf.
*
* @param node The root of the tree.
* @throws Exception If there is some problem in building the tree leaves.
*/
protected void buildLeavesMiddleOut(BallNode node) throws Exception {
if (node.m_Left != null && node.m_Right != null) { // if an internal node
buildLeavesMiddleOut(node.m_Left);
buildLeavesMiddleOut(node.m_Right);
} else if (node.m_Left != null || node.m_Right != null) {
throw new Exception("Invalid leaf assignment. Please check code");
} else { // if node is a leaf
BallNode n2 = buildTreeMiddleOut(node.m_Start, node.m_End);
if (n2.m_Left != null && n2.m_Right != null) {
node.m_Left = n2.m_Left;
node.m_Right = n2.m_Right;
buildLeavesMiddleOut(node);
// the stopping condition in buildTreeMiddleOut will stop the recursion,
// where it won't split a node at all, and we won't recurse here.
} else if (n2.m_Left != null || n2.m_Right != null) {
throw new Exception("Invalid leaf assignment. Please check code");
}
}
}
/**
* Merges nodes created by createAnchorsHierarchy() into one top node.
*
* @param list List of anchor nodes.
* @param startIdx The start of the portion of master index array containing
* these anchor nodes.
* @param endIdx The end of the portion of master index array containing these
* anchor nodes.
* @return The top/root node after merging the given anchor nodes.
* @throws Exception IF there is some problem in merging.
*/
protected BallNode mergeNodes(Vector<TempNode> list, int startIdx, int endIdx)
throws Exception {
for (int i = 0; i < list.size(); i++) {
TempNode n = list.get(i);
n.anchor = calcPivot(n.points, new MyIdxList(), m_Instances);
n.radius = calcRadius(n.points, new MyIdxList(), n.anchor, m_Instances);
}
double minRadius, tmpRadius; // tmpVolume, minVolume;
Instance pivot, minPivot = null;
TempNode parent;
int min1 = -1, min2 = -1;
while (list.size() > 1) { // main merging loop
minRadius = Double.POSITIVE_INFINITY;
for (int i = 0; i < list.size(); i++) {
TempNode first = list.get(i);
for (int j = i + 1; j < list.size(); j++) {
TempNode second = list.get(j);
pivot = calcPivot(first, second, m_Instances);
tmpRadius = calcRadius(first, second); // calcRadius(first.points,
// second.points, pivot,
// m_Instances);
if (tmpRadius < minRadius) { // (tmpVolume < minVolume) {
minRadius = tmpRadius; // minVolume = tmpVolume;
minPivot = pivot;
min1 = i;
min2 = j;
// minInstList = tmpInstList;
}
}// end for(j)
}// end for(i)
parent = new TempNode();
parent.left = list.get(min1);
parent.right = list.get(min2);
parent.anchor = minPivot;
parent.radius = calcRadius(parent.left.points, parent.right.points,
minPivot, m_Instances); // minRadius;
parent.points = parent.left.points.append(parent.left.points,
parent.right.points);
list.remove(min1);
list.remove(min2 - 1);
list.add(parent);
}// end while
TempNode tmpRoot = list.get(list.size() - 1);
if ((endIdx - startIdx + 1) != tmpRoot.points.length()) {
throw new Exception("Root nodes instance list is of irregular length. "
+ "Please check code. Length should " + "be: "
+ (endIdx - startIdx + 1) + " whereas it is found to be: "
+ tmpRoot.points.length());
}
for (int i = 0; i < tmpRoot.points.length(); i++) {
m_InstList[startIdx + i] = tmpRoot.points.get(i).idx;
}
BallNode node = makeBallTreeNodes(tmpRoot, startIdx, endIdx, 0);
return node;
}
/**
* Makes BallTreeNodes out of TempNodes.
*
* @param node The root TempNode
* @param startidx The start of the portion of master index array the
* TempNodes are made from.
* @param endidx The end of the portion of master index array the TempNodes
* are made from.
* @param depth The depth in the tree where this root TempNode is made (needed
* when leaves of a tree deeper down are built middle out).
* @return The root BallTreeNode.
*/
protected BallNode makeBallTreeNodes(TempNode node, int startidx, int endidx,
int depth) {
BallNode ball = null;
if (node.left != null && node.right != null) { // make an internal node
ball = new BallNode(startidx, endidx, m_NumNodes, node.anchor,
node.radius);
m_NumNodes += 1;
ball.m_Left = makeBallTreeNodes(node.left, startidx, startidx
+ node.left.points.length() - 1, depth + 1);
ball.m_Right = makeBallTreeNodes(node.right,
startidx + node.left.points.length(), endidx, depth + 1);
m_MaxDepth++;
} else { // make a leaf node
ball = new BallNode(startidx, endidx, m_NumNodes, node.anchor,
node.radius);
m_NumNodes += 1;
m_NumLeaves += 1;
}
return ball;
}
/**
* Returns an anchor point which is furthest from the mean point for a given
* set of points (instances) (The anchor instance is chosen from the given set
* of points).
*
* @param startIdx The start index of the points for which anchor point is
* required.
* @param endIdx The end index of the points for which anchor point is
* required.
* @return The furthest point/instance from the mean of given set of points.
*/
protected TempNode getFurthestFromMeanAnchor(int startIdx, int endIdx) {
TempNode anchor = new TempNode();
Instance centroid = BallNode.calcCentroidPivot(startIdx, endIdx,
m_InstList, m_Instances);
Instance temp;
double tmpr;
anchor.radius = Double.NEGATIVE_INFINITY;
for (int i = startIdx; i <= endIdx; i++) {
temp = m_Instances.instance(m_InstList[i]);
tmpr = m_DistanceFunction.distance(centroid, temp);
if (tmpr > anchor.radius) {
anchor.idx = m_InstList[i];
anchor.anchor = temp;
anchor.radius = tmpr;
}
}
setPoints(anchor, startIdx, endIdx, m_InstList);
return anchor;
}
/**
* Returns a random anchor point/instance from a given set of
* points/instances.
*
* @param startIdx The start index of the points for which anchor is required.
* @param endIdx The end index of the points for which anchor is required.
* @return The random anchor point/instance for the given set of
*/
protected TempNode getRandomAnchor(int startIdx, int endIdx) {
TempNode anchr1 = new TempNode();
anchr1.idx = m_InstList[startIdx + rand.nextInt((endIdx - startIdx + 1))];
anchr1.anchor = m_Instances.instance(anchr1.idx);
setPoints(anchr1, startIdx, endIdx, m_InstList);
anchr1.radius = anchr1.points.getFirst().distance;
return anchr1;
}
/**
* Sets the points of an anchor node. It takes the indices of points from the
* given portion of an index array and stores those indices, together with
* their distances to the given anchor node, in the point index list of the
* anchor node.
*
* @param node The node in which the points are needed to be set.
* @param startIdx The start of the portion in the given index array (the
* master index array).
* @param endIdx The end of the portion in the given index array.
* @param indices The index array.
*/
public void setPoints(TempNode node, int startIdx, int endIdx, int[] indices) {
node.points = new MyIdxList();
Instance temp;
double dist;
for (int i = startIdx; i <= endIdx; i++) {
temp = m_Instances.instance(indices[i]);
dist = m_DistanceFunction.distance(node.anchor, temp);
node.points.insertReverseSorted(indices[i], dist);
}
}
/**
* Sets the distances of a supplied new anchor to all the rest of the previous
* anchor points.
*
* @param anchors The old anchor points.
* @param newAnchor The new anchor point.
* @param anchorDistances The vector to store the distances of newAnchor to
* each of the old anchors.
* @throws Exception If there is some problem in calculating the distances.
*/
public void setInterAnchorDistances(Vector<TempNode> anchors,
TempNode newAnchor, Vector<double[]> anchorDistances) throws Exception {
double[] distArray = new double[anchors.size()];
for (int i = 0; i < anchors.size(); i++) {
Instance anchr = anchors.elementAt(i).anchor;
distArray[i] = m_DistanceFunction.distance(anchr, newAnchor.anchor);
}
anchorDistances.add(distArray);
}
/**
* Removes points from old anchors that are nearer to the given new anchor and
* adds them to the list of points of the new anchor.
*
* @param newAnchor The new anchor.
* @param anchors The old anchors.
* @param anchorDistances The distances of new anchor to each of the old
* anchors.
* @return true if any points are removed from the old anchors
*/
public boolean stealPoints(TempNode newAnchor, Vector<TempNode> anchors,
Vector<double[]> anchorDistances) {
double maxDist = Double.NEGATIVE_INFINITY;
double[] distArray = anchorDistances.lastElement();
for (double element : distArray) {
if (maxDist < element) {
maxDist = element;
}
}
boolean anyPointsStolen = false, pointsStolen = false;
TempNode anchorI;
double newDist, distI, interAnchMidDist;
Instance newAnchInst = newAnchor.anchor, anchIInst;
for (int i = 0; i < anchors.size(); i++) {
anchorI = anchors.elementAt(i);
anchIInst = anchorI.anchor;
pointsStolen = false;
interAnchMidDist = m_DistanceFunction.distance(newAnchInst, anchIInst) / 2D;
for (int j = 0; j < anchorI.points.length(); j++) {
ListNode tmp = anchorI.points.get(j);
// break if we reach a point whose distance is less than the midpoint
// of inter anchor distance
if (tmp.distance < interAnchMidDist) {
break;
}
// else test if this point can be stolen by the new anchor
newDist = m_DistanceFunction.distance(newAnchInst,
m_Instances.instance(tmp.idx));
distI = tmp.distance;
if (newDist < distI) {
newAnchor.points.insertReverseSorted(tmp.idx, newDist);
anchorI.points.remove(j);
anyPointsStolen = pointsStolen = true;
}
}
if (pointsStolen) {
anchorI.radius = anchorI.points.getFirst().distance;
}
}// end for
return anyPointsStolen;
}// end stealPoints()
/**
* /** Calculates the centroid pivot of a node based on its two child nodes
* (if merging two nodes).
*
* @param node1 The first child.
* @param node2 The second child.
* @param insts The set of instances on which the tree is being built (as
* dataset header information is required).
* @return The centroid pivot of a node.
*/
public Instance calcPivot(TempNode node1, TempNode node2, Instances insts) {
int classIdx = m_Instances.classIndex();
double[] attrVals = new double[insts.numAttributes()];
Instance temp;
double anchr1Ratio = (double) node1.points.length()
/ (node1.points.length() + node2.points.length()), anchr2Ratio = (double) node2.points
.length() / (node1.points.length() + node2.points.length());
;
for (int k = 0; k < node1.anchor.numValues(); k++) {
if (node1.anchor.index(k) == classIdx) {
continue;
}
attrVals[k] += node1.anchor.valueSparse(k) * anchr1Ratio;
}
for (int k = 0; k < node2.anchor.numValues(); k++) {
if (node2.anchor.index(k) == classIdx) {
continue;
}
attrVals[k] += node2.anchor.valueSparse(k) * anchr2Ratio;
}
temp = new DenseInstance(1.0, attrVals);
return temp;
}
/**
* Calculates the centroid pivot of a node based on the list of points that it
* contains (tbe two lists of its children are provided).
*
* @param list1 The point index list of first child.
* @param list2 The point index list of second child.
* @param insts The insts object on which the tree is being built (for header
* information).
* @return The centroid pivot of the node.
*/
public Instance calcPivot(MyIdxList list1, MyIdxList list2, Instances insts) {
int classIdx = m_Instances.classIndex();
double[] attrVals = new double[insts.numAttributes()];
Instance temp;
for (int i = 0; i < list1.length(); i++) {
temp = insts.instance(list1.get(i).idx);
for (int k = 0; k < temp.numValues(); k++) {
if (temp.index(k) == classIdx) {
continue;
}
attrVals[k] += temp.valueSparse(k);
}
}
for (int j = 0; j < list2.length(); j++) {
temp = insts.instance(list2.get(j).idx);
for (int k = 0; k < temp.numValues(); k++) {
if (temp.index(k) == classIdx) {
continue;
}
attrVals[k] += temp.valueSparse(k);
}
}
for (int j = 0, numInsts = list1.length() + list2.length(); j < attrVals.length; j++) {
attrVals[j] /= numInsts;
}
temp = new DenseInstance(1.0, attrVals);
return temp;
}
/**
* Calculates the radius of a node based on its two child nodes (if merging
* two nodes).
*
* @param n1 The first child of the node.
* @param n2 The second child of the node.
* @return The radius of the node.
* @throws Exception
*/
public double calcRadius(TempNode n1, TempNode n2) {
Instance p1 = n1.anchor, p2 = n2.anchor;
double radius = n1.radius + m_DistanceFunction.distance(p1, p2) + n2.radius;
return radius / 2;
}
/**
* Calculates the radius of a node based on the list of points that it
* contains (the two lists of its children are provided).
*
* @param list1 The point index list of first child.
* @param list2 The point index list of second child.
* @param pivot The centre/pivot of the node.
* @param insts The instances on which the tree is being built (for header
* info).
* @return The radius of the node.
*/
public double calcRadius(MyIdxList list1, MyIdxList list2, Instance pivot,
Instances insts) {
double radius = Double.NEGATIVE_INFINITY;
for (int i = 0; i < list1.length(); i++) {
double dist = m_DistanceFunction.distance(pivot,
insts.instance(list1.get(i).idx));
if (dist > radius) {
radius = dist;
}
}
for (int j = 0; j < list2.length(); j++) {
double dist = m_DistanceFunction.distance(pivot,
insts.instance(list2.get(j).idx));
if (dist > radius) {
radius = dist;
}
}
return radius;
}
/**
* Adds an instance to the tree. This implementation of MiddleOutConstructor
* doesn't support addition of instances to already built tree, hence it
* always throws an exception.
*
* @param node The root of the tree to which the instance is to be added.
* @param inst The instance to add to the tree.
* @return The updated master index array after adding the instance.
* @throws Exception Always as this implementation of MiddleOutConstructor
* doesn't support addition of instances after batch construction of
* the tree.
*/
@Override
public int[] addInstance(BallNode node, Instance inst) throws Exception {
throw new Exception("Addition of instances after the tree is built, not "
+ "possible with MiddleOutConstructor.");
}
/**
* Sets the maximum number of instances allowed in a leaf.
*
* @param num The maximum number of instances allowed in a leaf.
* @throws Exception If the num is < 2, as the method cannot work for < 2
* instances.
*/
@Override
public void setMaxInstancesInLeaf(int num) throws Exception {
if (num < 2) {
throw new Exception("The maximum number of instances in a leaf for "
+ "using MiddleOutConstructor must be >=2.");
}
super.setMaxInstancesInLeaf(num);
}
/**
* Sets the instances on which the tree is to be built.
*
* @param insts The instances on which to build the ball tree.
*/
@Override
public void setInstances(Instances insts) {
super.setInstances(insts);
rootRadius = -1; // this needs to be re-calculated by buildTree()
}
/**
* Sets the master index array that points to instances in m_Instances, so
* that only this array is manipulated, and m_Instances is left untouched.
*
* @param instList The master index array.
*/
@Override
public void setInstanceList(int[] instList) {
super.setInstanceList(instList);
rootRadius = -1; // this needs to be re-calculated by buildTree()
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String initialAnchorRandomTipText() {
return "Whether the initial anchor is chosen randomly.";
}
/**
* Gets whether if the initial anchor is chosen randomly.
*
* @return true if the initial anchor is a random one.
*/
public boolean isInitialAnchorRandom() {
return m_RandomInitialAnchor;
}
/**
* Sets whether if the initial anchor is chosen randomly. If not then if it is
* the furthest point from the mean/centroid.
*
* @param randomInitialAnchor Should be true if the first anchor is to be
* chosen randomly.
*/
public void setInitialAnchorRandom(boolean randomInitialAnchor) {
m_RandomInitialAnchor = randomInitialAnchor;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String seedTipText() {
return "The seed value for the random number generator.";
}
/**
* Returns the seed for random number generator.
*
* @return The random number seed.
*/
@Override
public int getSeed() {
return m_RSeed;
}
/**
* Sets the seed for random number generator (that is used for selecting the
* first anchor point randomly).
*
* @param seed The seed.
*/
@Override
public void setSeed(int seed) {
m_RSeed = seed;
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> newVector = new Vector<Option>();
newVector.addElement(new Option(
"\tThe seed for the random number generator used\n"
+ "\tin selecting random anchor.\n" + "(default: 1)", "S", 1,
"-S <num>"));
newVector.addElement(new Option("\tUse randomly chosen initial anchors.",
"R", 0, "-R"));
newVector.addAll(Collections.list(super.listOptions()));
return newVector.elements();
}
/**
* Parses a given list of options.
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -S <num>
* The seed for the random number generator used
* in selecting random anchor.
* (default: 1)
* </pre>
*
* <pre>
* -R
* Use randomly chosen initial anchors.
* </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 temp = Utils.getOption('S', options);
if (temp.length() > 0) {
setSeed(Integer.parseInt(temp));
} else {
setSeed(1);
}
super.setOptions(options);
setInitialAnchorRandom(Utils.getFlag('R', options));
}
/**
* Gets the current settings of this BallTree MiddleOutConstructor.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> result = new Vector<String>();
result.add("-S");
result.add("" + getSeed());
if (isInitialAnchorRandom()) {
result.add("-R");
}
Collections.addAll(result, super.getOptions());
return result.toArray(new String[result.size()]);
}
/**
* Checks whether if the points in an index list are in some specified of the
* master index array.
*
* @param list The point list.
* @param startidx The start of the portion in master index array.
* @param endidx The end of the portion in master index array.
* @throws Exception If some point in the point list is not in the specified
* portion of master index array.
*/
public void checkIndicesList(MyIdxList list, int startidx, int endidx)
throws Exception {
boolean found;
ListNode node;
for (int i = 0; i < list.size(); i++) {
node = list.get(i);
found = false;
for (int j = startidx; j <= endidx; j++) {
if (node.idx == m_InstList[j]) {
found = true;
break;
}
}
if (!found) {
throw new Exception("Error: Element " + node.idx
+ " of the list not in " + "the array." + "\nArray: "
+ printInsts(startidx, endidx) + "\nList: " + printList(list));
}
}
}
/**
* For printing indices in some given portion of the master index array.
*
* @param startIdx The start of the portion in master index array.
* @param endIdx The end of the portion in master index array.
* @return The string containing the indices in specified portion of the
* master index array.
*/
public String printInsts(int startIdx, int endIdx) {
StringBuffer bf = new StringBuffer();
try {
bf.append("i: ");
for (int i = startIdx; i <= endIdx; i++) {
if (i == startIdx) {
bf.append("" + m_InstList[i]);
} else {
bf.append(", " + m_InstList[i]);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return bf.toString();
}
/**
* For printing indices in a given point list.
*
* @param points The point list.
* @return String containing indices of the points in the point list.
*/
public String printList(MyIdxList points) {
if (points == null || points.length() == 0) {
return "";
}
StringBuffer bf = new StringBuffer();
try {
ListNode temp;
for (int i = 0; i < points.size(); i++) {
temp = points.get(i);
if (i == 0) {
bf.append("" + temp.idx);
} else {
bf.append(", " + temp.idx);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return bf.toString();
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Temp class to represent either a leaf node or an internal node. Should only
* have two children (could be the case one child is an instance and the other
* another node). Primarily used for anchor nodes. It stores the points
* contained in a node together with their distances to the node's
* centre/anchor point.
*
* @author Ashraf M. Kibriya (amk14[at-the-rate]cs[dot]waikato[dot]ac[dot]nz)
* @version $Revision$
*/
protected class TempNode implements RevisionHandler {
/** The anchor point of the node. */
Instance anchor;
/** The index of the anchor point. */
int idx;
/** The radius of the node. */
double radius;
/** The list of points inside the node. */
MyIdxList points;
/** Node's left child. */
TempNode left;
/** Node's right child. */
TempNode right;
/**
* Returns a string represention of the node.
*
* @return The string representation of the node.
*/
@Override
public String toString() {
if (points == null || points.length() == 0) {
return idx + "";
}
StringBuffer bf = new StringBuffer();
try {
bf.append(idx + " p: ");
ListNode temp;
for (int i = 0; i < points.size(); i++) {
temp = points.get(i);
if (i == 0) {
bf.append("" + temp.idx);
} else {
bf.append(", " + temp.idx);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return bf.toString();
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
}
/**
* An element of MyIdxList. It stores a points index, and its distance to some
* specific point (usually a node's anchor point).
*
* @author Ashraf M. Kibriya (amk14[at-the-rate]cs[dot]waikato[dot]ac[dot]nz)
* @version $Revision$
*/
protected class ListNode implements RevisionHandler, Serializable {
/** The index of the point. */
int idx = -1;
/** The distance of the point to the anchor. */
double distance = Double.NEGATIVE_INFINITY;
/**
* Constructor.
*
* @param i The point's index.
* @param d The point's distance to the anchor.
*/
public ListNode(int i, double d) {
idx = i;
distance = d;
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
}
/**
* Class implementing a list. It stores indices of instances/points, together
* with their distances to a nodes centre/pivot/anchor, in a (reverse sorted)
* list.
*
* @author Ashraf M. Kibriya (amk14[at-the-rate]cs[dot]waikato[dot]ac[dot]nz)
* @version $Revision$
*/
protected class MyIdxList implements Serializable, RevisionHandler {
/** for serialization. */
private static final long serialVersionUID = -2283869109722934927L;
/** The array list backing this list */
protected ArrayList<ListNode> m_List;
/**
* Constructor.
*/
public MyIdxList() {
m_List = new ArrayList<ListNode>();
}
/**
* Constructor for given capacity.
*/
public MyIdxList(int capacity) {
m_List = new ArrayList<ListNode>(capacity);
}
/**
* Returns the first element in the list.
*
* @return The list's first element.
*/
public ListNode getFirst() {
return m_List.get(0);
}
/**
* Inserts an element in reverse sorted order in the list.
*
* @param idx The index of the point to insert.
* @param distance The distance of the point to a node's anchor (this would
* be used to determine the sort order).
*/
public void insertReverseSorted(final int idx, final double distance) {
int i = 0;
for (ListNode temp : m_List) {
if (temp.distance < distance) {
break;
}
i++;
}
m_List.add(i, new ListNode(idx, distance));
}
/**
* Returns an element at the specified index in the list.
*
* @param index The index of the element in the list.
* @return The element at the given index.
*/
public ListNode get(int index) {
return m_List.get(index);
}
/**
* Removes an element at the specified index from the list.
*
* @param index The index of the element in the list to remove.
*/
public void remove(int index) {
m_List.remove(index);
}
/**
* Returns the size of the list.
*
* @return The size of the list.
*/
public int length() {
return m_List.size();
}
/**
* Returns the size of the list.
*
* @return The size of the list.
*/
public int size() {
return m_List.size();
}
/**
* Appends one list at the end of the other.
*
* @param list1 The list to which the other list would be appended.
* @param list2 The list to append to the other list.
* @return The new list with list2 appended to list1.
*/
public MyIdxList append(MyIdxList list1, MyIdxList list2) {
MyIdxList temp = new MyIdxList(list1.size() + list2.size());
temp.m_List.addAll(list1.m_List);
temp.m_List.addAll(list2.m_List);
return temp;
}
/**
* Checks the sorting of a list.
*
* @param list The list whose sorting is to be checked.
* @throws Exception If the list is not in (reverse) sorted order.
*/
public void checkSorting(MyIdxList list) throws Exception {
Iterator<ListNode> en = m_List.iterator();
ListNode first = null, second = null;
while (en.hasNext()) {
if (first == null) {
first = en.next();
} else {
second = en.next();
if (first.distance < second.distance) {
throw new Exception("List not sorted correctly."
+ " first.distance: " + first.distance + " second.distance: "
+ second.distance + " Please check code.");
}
}
}
}
/**
* 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/neighboursearch
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/neighboursearch/balltrees/PointsClosestToFurthestChildren.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/>.
*/
/*
* PointsClosestToFurthestChildren.java
* Copyright (C) 2007-2012 University of Waikato, Hamilton, New Zealand
*/
package weka.core.neighboursearch.balltrees;
import weka.core.EuclideanDistance;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.RevisionUtils;
import weka.core.TechnicalInformation;
import weka.core.TechnicalInformation.Field;
import weka.core.TechnicalInformation.Type;
import weka.core.TechnicalInformationHandler;
/**
* <!-- globalinfo-start --> Implements the Moore's method to split a node of a
* ball tree.<br/>
* <br/>
* For more information please see section 2 of the 1st and 3.2.3 of the 2nd:<br/>
* <br/>
* Andrew W. Moore: The Anchors Hierarchy: Using the Triangle Inequality to
* Survive High Dimensional Data. In: UAI '00: Proceedings of the 16th
* Conference on Uncertainty in Artificial Intelligence, San Francisco, CA, USA,
* 397-405, 2000.<br/>
* <br/>
* Ashraf Masood Kibriya (2007). Fast Algorithms for Nearest Neighbour Search.
* Hamilton, New Zealand.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- technical-bibtex-start --> BibTeX:
*
* <pre>
* @inproceedings{Moore2000,
* address = {San Francisco, CA, USA},
* author = {Andrew W. Moore},
* booktitle = {UAI '00: Proceedings of the 16th Conference on Uncertainty in Artificial Intelligence},
* pages = {397-405},
* publisher = {Morgan Kaufmann Publishers Inc.},
* title = {The Anchors Hierarchy: Using the Triangle Inequality to Survive High Dimensional Data},
* year = {2000}
* }
*
* @mastersthesis{Kibriya2007,
* address = {Hamilton, New Zealand},
* author = {Ashraf Masood Kibriya},
* school = {Department of Computer Science, School of Computing and Mathematical Sciences, University of Waikato},
* title = {Fast Algorithms for Nearest Neighbour Search},
* year = {2007}
* }
* </pre>
* <p/>
* <!-- technical-bibtex-end -->
*
* <!-- options-start --> <!-- options-end -->
*
* @author Ashraf M. Kibriya (amk14[at-the-rate]cs[dot]waikato[dot]ac[dot]nz)
* @version $Revision$
*/
// better rename to MidPoint of Furthest Pair/Children
public class PointsClosestToFurthestChildren extends BallSplitter implements
TechnicalInformationHandler {
/** for serialization. */
private static final long serialVersionUID = -2947177543565818260L;
/**
* Returns a string describing this object.
*
* @return A description of the algorithm for displaying in the
* explorer/experimenter gui.
*/
public String globalInfo() {
return "Implements the Moore's method to split a node of a ball tree.\n\n"
+ "For more information please see section 2 of the 1st and 3.2.3 of "
+ "the 2nd:\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;
TechnicalInformation additional;
result = new TechnicalInformation(Type.INPROCEEDINGS);
result.setValue(Field.AUTHOR, "Andrew W. Moore");
result
.setValue(
Field.TITLE,
"The Anchors Hierarchy: Using the Triangle Inequality to Survive High Dimensional Data");
result.setValue(Field.YEAR, "2000");
result
.setValue(
Field.BOOKTITLE,
"UAI '00: Proceedings of the 16th Conference on Uncertainty in Artificial Intelligence");
result.setValue(Field.PAGES, "397-405");
result.setValue(Field.PUBLISHER, "Morgan Kaufmann Publishers Inc.");
result.setValue(Field.ADDRESS, "San Francisco, CA, USA");
additional = result.add(Type.MASTERSTHESIS);
additional.setValue(Field.AUTHOR, "Ashraf Masood Kibriya");
additional.setValue(Field.TITLE,
"Fast Algorithms for Nearest Neighbour Search");
additional.setValue(Field.YEAR, "2007");
additional
.setValue(
Field.SCHOOL,
"Department of Computer Science, School of Computing and Mathematical Sciences, University of Waikato");
additional.setValue(Field.ADDRESS, "Hamilton, New Zealand");
return result;
}
/** Constructor. */
public PointsClosestToFurthestChildren() {
}
/**
* Constructor.
*
* @param instList The master index array.
* @param insts The instances on which the tree is (or is to be) built.
* @param e The Euclidean distance function to use for splitting.
*/
public PointsClosestToFurthestChildren(int[] instList, Instances insts,
EuclideanDistance e) {
super(instList, insts, e);
}
/**
* Splits a ball into two.
*
* @param node The node to split.
* @param numNodesCreated The number of nodes that so far have been created
* for the tree, so that the newly created nodes are assigned
* correct/meaningful node numbers/ids.
* @throws Exception If there is some problem in splitting the given node.
*/
@Override
public void splitNode(BallNode node, int numNodesCreated) throws Exception {
correctlyInitialized();
double maxDist = Double.NEGATIVE_INFINITY, dist = 0.0;
Instance furthest1 = null, furthest2 = null, pivot = node.getPivot(), temp;
double distList[] = new double[node.m_NumInstances];
for (int i = node.m_Start; i <= node.m_End; i++) {
temp = m_Instances.instance(m_Instlist[i]);
dist = m_DistanceFunction.distance(pivot, temp, Double.POSITIVE_INFINITY);
if (dist > maxDist) {
maxDist = dist;
furthest1 = temp;
}
}
maxDist = Double.NEGATIVE_INFINITY;
furthest1 = (Instance) furthest1.copy();
for (int i = 0; i < node.m_NumInstances; i++) {
temp = m_Instances.instance(m_Instlist[i + node.m_Start]);
distList[i] = m_DistanceFunction.distance(furthest1, temp,
Double.POSITIVE_INFINITY);
if (distList[i] > maxDist) {
maxDist = distList[i];
furthest2 = temp; // tempidx = i+node.m_Start;
}
}
furthest2 = (Instance) furthest2.copy();
dist = 0.0;
int numRight = 0;
// moving indices in the right branch to the right end of the array
for (int i = 0; i < node.m_NumInstances - numRight; i++) {
temp = m_Instances.instance(m_Instlist[i + node.m_Start]);
dist = m_DistanceFunction.distance(furthest2, temp,
Double.POSITIVE_INFINITY);
if (dist < distList[i]) {
int t = m_Instlist[node.m_End - numRight];
m_Instlist[node.m_End - numRight] = m_Instlist[i + node.m_Start];
m_Instlist[i + node.m_Start] = t;
double d = distList[distList.length - 1 - numRight];
distList[distList.length - 1 - numRight] = distList[i];
distList[i] = d;
numRight++;
i--;
}
}
if (!(numRight > 0 && numRight < node.m_NumInstances)) {
throw new Exception("Illegal value for numRight: " + numRight);
}
node.m_Left = new BallNode(node.m_Start, node.m_End - numRight,
numNodesCreated + 1, (pivot = BallNode.calcCentroidPivot(node.m_Start,
node.m_End - numRight, m_Instlist, m_Instances)), BallNode.calcRadius(
node.m_Start, node.m_End - numRight, m_Instlist, m_Instances, pivot,
m_DistanceFunction));
node.m_Right = new BallNode(node.m_End - numRight + 1, node.m_End,
numNodesCreated + 2, (pivot = BallNode.calcCentroidPivot(node.m_End
- numRight + 1, node.m_End, m_Instlist, m_Instances)),
BallNode.calcRadius(node.m_End - numRight + 1, node.m_End, m_Instlist,
m_Instances, pivot, m_DistanceFunction));
}
/**
* 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/neighboursearch
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/neighboursearch/balltrees/TopDownConstructor.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/>.
*/
/*
* TopDownConstructor.java
* Copyright (C) 2007-2012 University of Waikato, Hamilton, New Zealand
*/
package weka.core.neighboursearch.balltrees;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Vector;
import weka.core.EuclideanDistance;
import weka.core.Instance;
import weka.core.Option;
import weka.core.RevisionUtils;
import weka.core.TechnicalInformation;
import weka.core.TechnicalInformation.Field;
import weka.core.TechnicalInformation.Type;
import weka.core.TechnicalInformationHandler;
import weka.core.Utils;
/**
* <!-- globalinfo-start --> The class implementing the TopDown construction
* method of ball trees. It further uses one of a number of different splitting
* methods to split a ball while constructing the tree top down.<br/>
* <br/>
* For more information see also:<br/>
* <br/>
* Stephen M. Omohundro (1989). Five Balltree Construction Algorithms.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- technical-bibtex-start --> BibTeX:
*
* <pre>
* @techreport{Omohundro1989,
* author = {Stephen M. Omohundro},
* institution = {International Computer Science Institute},
* month = {December},
* number = {TR-89-063},
* title = {Five Balltree Construction Algorithms},
* year = {1989}
* }
* </pre>
* <p/>
* <!-- technical-bibtex-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -S <classname and options>
* Ball splitting algorithm to use.
* </pre>
*
* <!-- options-end -->
*
* @author Ashraf M. Kibriya (amk14[at-the-rate]cs[dot]waikato[dot]ac[dot]nz)
* @version $Revision$
*/
public class TopDownConstructor extends BallTreeConstructor implements
TechnicalInformationHandler {
/** for serialization. */
private static final long serialVersionUID = -5150140645091889979L;
/**
* The BallSplitter algorithm used by the TopDown BallTree constructor, if it
* is selected.
*/
protected BallSplitter m_Splitter = new PointsClosestToFurthestChildren();
/**
* Creates a new instance of TopDownConstructor.
*/
public TopDownConstructor() {
}
/**
* Returns a string describing this nearest neighbour search algorithm.
*
* @return a description of the algorithm for displaying in the
* explorer/experimenter gui
*/
public String globalInfo() {
return "The class implementing the TopDown construction method of "
+ "ball trees. It further uses one of a number of different splitting "
+ "methods to split a ball while constructing the tree top down.\n\n"
+ "For more information see also:\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.TECHREPORT);
result.setValue(Field.AUTHOR, "Stephen M. Omohundro");
result.setValue(Field.YEAR, "1989");
result.setValue(Field.TITLE, "Five Balltree Construction Algorithms");
result.setValue(Field.MONTH, "December");
result.setValue(Field.NUMBER, "TR-89-063");
result.setValue(Field.INSTITUTION,
"International Computer Science Institute");
return result;
}
/**
* Builds the ball tree top down.
*
* @return The root node of the tree.
* @throws Exception If there is problem building the tree.
*/
@Override
public BallNode buildTree() throws Exception {
BallNode root;
m_NumNodes = m_MaxDepth = 0;
m_NumLeaves = 1;
m_Splitter.setInstances(m_Instances);
m_Splitter.setInstanceList(m_InstList);
m_Splitter
.setEuclideanDistanceFunction((EuclideanDistance) m_DistanceFunction);
root = new BallNode(0, m_InstList.length - 1, 0);
root.setPivot(BallNode.calcCentroidPivot(m_InstList, m_Instances));
root.setRadius(BallNode.calcRadius(m_InstList, m_Instances,
root.getPivot(), m_DistanceFunction));
splitNodes(root, m_MaxDepth + 1, root.m_Radius);
return root;
}
/**
* Recursively splits nodes of a ball tree until <=m_MaxInstancesInLeaf
* instances remain in a node.
*
* @param node The node to split.
* @param depth The depth of this node in the tree, so that m_MaxDepth is
* correctly updated.
* @param rootRadius The smallest ball enclosing all the data points.
* @throws Exception If there is some problem in splitting.
*/
protected void splitNodes(BallNode node, int depth, final double rootRadius)
throws Exception {
if (node.m_NumInstances <= m_MaxInstancesInLeaf
|| (rootRadius == 0 ? true
: node.m_Radius / rootRadius < m_MaxRelLeafRadius)) {
return;
}
m_NumLeaves--;
m_Splitter.splitNode(node, m_NumNodes);
m_NumNodes += 2;
m_NumLeaves += 2;
if (m_MaxDepth < depth) {
m_MaxDepth = depth;
}
splitNodes(node.m_Left, depth + 1, rootRadius);
splitNodes(node.m_Right, depth + 1, rootRadius);
if (m_FullyContainChildBalls) {
double radius = BallNode.calcRadius(node.m_Left, node.m_Right,
node.getPivot(), m_DistanceFunction);
// The line that follows was commented out by Eibe because it does not
// have any effect
// Instance pivot = BallNode.calcPivot(node.m_Left, node.m_Right,
// m_Instances);
// System.err.println("Left Radius: "+node.m_Left.getRadius()+
// " Right Radius: "+node.m_Right.getRadius()+
// " d(p1,p2): "+
// m_DistanceFunction.distance(node.m_Left.getPivot(),
// node.m_Right.getPivot())+
// " node's old radius: "+node.getRadius()+
// " node's new Radius: "+radius+
// " node;s old pivot: "+node.getPivot()+
// " node's new pivot: "+pivot);
node.setRadius(radius);
}
}
/**
* Adds an instance to the ball tree.
*
* @param node The root node of the tree.
* @param inst The instance to add to the tree.
* @return The new master index array after adding the instance.
* @throws Exception If there is some problem adding the given instance to the
* tree.
*/
@Override
public int[] addInstance(BallNode node, Instance inst) throws Exception {
double leftDist, rightDist;
if (node.m_Left != null && node.m_Right != null) { // if node is not a leaf
// go further down the tree to look for the leaf the instance should be in
leftDist = m_DistanceFunction.distance(inst, node.m_Left.getPivot(),
Double.POSITIVE_INFINITY); // instance.value(m_SplitDim);
rightDist = m_DistanceFunction.distance(inst, node.m_Right.getPivot(),
Double.POSITIVE_INFINITY);
if (leftDist < rightDist) {
addInstance(node.m_Left, inst);
// go into right branch to correct instance list boundaries
processNodesAfterAddInstance(node.m_Right);
} else {
addInstance(node.m_Right, inst);
}
// correct end index of instance list of this node
node.m_End++;
} else if (node.m_Left != null || node.m_Right != null) {
throw new Exception("Error: Only one leaf of the built ball tree is "
+ "assigned. Please check code.");
} else { // found the leaf to insert instance
int index = m_Instances.numInstances() - 1;
int instList[] = new int[m_Instances.numInstances()];
System.arraycopy(m_InstList, 0, instList, 0, node.m_End + 1);
if (node.m_End < m_InstList.length - 1) {
System.arraycopy(m_InstList, node.m_End + 2, instList, node.m_End + 2,
m_InstList.length - node.m_End - 1);
}
instList[node.m_End + 1] = index;
node.m_End++;
node.m_NumInstances++;
m_InstList = instList;
m_Splitter.setInstanceList(m_InstList);
if (node.m_NumInstances > m_MaxInstancesInLeaf) {
m_Splitter.splitNode(node, m_NumNodes);
m_NumNodes += 2;
}
}
return m_InstList;
}
/**
* Post process method to correct the start and end indices of BallNodes on
* the right of the node where the instance was added.
*
* @param node The node whose m_Start and m_End need to be updated.
*/
protected void processNodesAfterAddInstance(BallNode node) {
// updating start and end indices for the node
node.m_Start++;
node.m_End++;
// processing child nodes
if (node.m_Left != null && node.m_Right != null) {
processNodesAfterAddInstance(node.m_Left);
processNodesAfterAddInstance(node.m_Right);
}
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String ballSplitterTipText() {
return "The BallSplitter algorithm set that would be used by the TopDown "
+ "BallTree constructor.";
}
/**
* Returns the BallSplitter algorithm set that would be used by the TopDown
* BallTree constructor.
*
* @return The BallSplitter currently in use.
*/
public BallSplitter getBallSplitter() {
return m_Splitter;
}
/**
* Sets the ball splitting algorithm to be used by the TopDown constructor.
*
* @param splitter The BallSplitter to use.
*/
public void setBallSplitter(BallSplitter splitter) {
m_Splitter = splitter;
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> newVector = new Vector<Option>();
newVector.addElement(new Option("\tBall splitting algorithm to use.", "S",
1, "-S <classname and options>"));
newVector.addAll(Collections.list(super.listOptions()));
return newVector.elements();
}
/**
* Parses a given list of options.
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -S <classname and options>
* Ball splitting algorithm to use.
* </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 optionString = Utils.getOption('S', options);
if (optionString.length() != 0) {
String nnSearchClassSpec[] = Utils.splitOptions(optionString);
if (nnSearchClassSpec.length == 0) {
throw new Exception("Invalid BallSplitter specification string.");
}
String className = nnSearchClassSpec[0];
nnSearchClassSpec[0] = "";
setBallSplitter((BallSplitter) Utils.forName(BallSplitter.class,
className, nnSearchClassSpec));
} else {
setBallSplitter(new PointsClosestToFurthestChildren());
}
super.setOptions(options);
}
/**
* Gets the current settings of KDtree.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> result = new Vector<String>();
result.add("-S");
result.add(m_Splitter.getClass().getName());
Collections.addAll(result, super.getOptions());
return result.toArray(new String[result.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/core/neighboursearch
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/neighboursearch/covertrees/Stack.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/>.
*/
/*
* Stack.java
* Copyright (C) 2006 Alina Beygelzimer and Sham Kakade and John Langford
*/
package weka.core.neighboursearch.covertrees;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import weka.core.RevisionHandler;
import weka.core.RevisionUtils;
/**
* Class implementing a stack.
*
* @param <T> The type of elements to be stored in the stack.
* @author Alina Beygelzimer (original C++ code)
* @author Sham Kakade (original C++ code)
* @author John Langford (original C++ code)
* @author Ashraf M. Kibriya (amk14[at-the-rate]cs[dot]waikato[dot]ac[dot]nz)
* (Java port)
* @version $Revision$
*/
public class Stack<T> implements Serializable, RevisionHandler {
/** for serialization. */
private static final long serialVersionUID = 5604056321825539264L;
/** The number of elements in the stack. */
public int length;
/** The elements inside the stack. */
public ArrayList<T> elements;
/** Constructor. */
public Stack() {
length = 0;
elements = new ArrayList<T>();
}
/**
* Constructor.
*
* @param capacity The initial capacity of the stack.
*/
public Stack(int capacity) {
length = 0;
elements = new ArrayList<T>(capacity);
}
/**
* Returns the last element in the stack.
*
* @return The last element.
*/
public T last() {
return elements.get(length - 1);
}
/**
* Returns the ith element in the stack.
*
* @param i The index of the element to return.
* @return The ith element.
*/
public T element(int i) {
return elements.get(i);
}
/**
* Sets the ith element in the stack.
*
* @param i The index at which the element is to be inserted.
* @param e The element to insert.
*/
public void set(int i, T e) {
elements.set(i, e);
}
/**
* Returns a sublist of the elements in the stack.
*
* @param beginIdx The start index of the sublist.
* @param uptoLength The length of the sublist.
* @return The sublist starting from beginIdx and of length uptoLength.
*/
public List<T> subList(int beginIdx, int uptoLength) {
return elements.subList(beginIdx, uptoLength);
}
/** Removes all the elements from the stack. */
public void clear() {
elements.clear();
length = 0;
}
/**
* Adds all the given elements in the stack.
*
* @param c The collection of elements to add in the stack.
*/
public void addAll(Collection<? extends T> c) {
elements.addAll(c);
length = c.size();
}
/**
* Replace all elements in the stack with the elements of another given stack.
* It first removes all the elements currently in the stack, and then adds all
* the elements of the provided stack.
*
* @param s The stack whose elements should be put in this stack.
*/
public void replaceAllBy(Stack<T> s) {
elements.clear();
elements.addAll(s.elements);
length = elements.size();
}
/**
* Pops (removes) the first (last added) element in the stack.
*
* @return The poped element.
*/
public T pop() {
length--;
return elements.remove(length);
}
/**
* Pushes the given element to the stack.
*
* @param new_ele The element to be pushed to the stack.
*/
public void push(T new_ele) {
length++;
elements.add(new_ele);
}
/**
* Pushes the given element onto the given stack.
*
* @param v The stack onto push the element.
* @param new_ele The element to push.
*/
public void push(Stack<T> v, T new_ele) {
length++;
v.elements.add(new_ele);
}
/**
* 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/neighboursearch
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/neighboursearch/kdtrees/KDTreeNode.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/>.
*/
/*
* KDTreeNode.java
* Copyright (C) 2007-2012 University of Waikato, Hamilton, New Zealand
*/
package weka.core.neighboursearch.kdtrees;
import java.io.Serializable;
import weka.core.RevisionHandler;
import weka.core.RevisionUtils;
/**
* A class representing a KDTree node. A node does not explicitly
* store the instances that it contains. Instead, it only stores
* the start and end index of a portion in a master index array. Each
* node is assigned a portion in the master index array that stores
* the indices of the instances that the node contains. Every time a
* node is split by the KDTree's contruction method, the instances of
* its left child are moved to the left and the instances of its
* right child are moved to the right, in the portion of the master
* index array belonging to the node. The start and end index in each
* of its children are then set accordingly within that portion so
* that each have their own portion which contains their instances.
* P.S.: The master index array is only stored in KDTree class.
*
* @author Ashraf M. Kibriya (amk14[at-the-rate]cs[dot]waikato[dot]ac[dot]nz)
* @version $Revision$
*/
public class KDTreeNode
implements Serializable, RevisionHandler {
/** for serialization. */
private static final long serialVersionUID = -3660396067582792648L;
/** node number (only for debug). */
public int m_NodeNumber;
/** left subtree; contains instances with smaller or equal to split value. */
public KDTreeNode m_Left = null;
/** right subtree; contains instances with larger than split value. */
public KDTreeNode m_Right = null;
/** value to split on. */
public double m_SplitValue;
/** attribute to split on. */
public int m_SplitDim;
/**
* lowest and highest value and width (= high - low) for each
* dimension.
*/
public double[][] m_NodeRanges;
/**
* The lo and high bounds of the hyper rectangle described by the
* node.
*/
public double[][] m_NodesRectBounds;
/**
* The start index of the portion of the master index array,
* which stores the indices of the instances/points the node
* contains.
*/
public int m_Start = 0;
/**
* The end index of the portion of the master index array,
* which stores indices of the instances/points the node
* contains.
*/
public int m_End = 0;
/**
* Constructor.
*/
public KDTreeNode() {}
/**
* Constructor.
*
* @param nodeNum The node number/id.
* @param startidx The start index of node's portion
* in master index array.
* @param endidx The start index of node's portion
* in master index array.
* @param nodeRanges The attribute ranges of the
* Instances/points contained in this node.
*/
public KDTreeNode(int nodeNum, int startidx, int endidx, double[][] nodeRanges) {
m_NodeNumber = nodeNum;
m_Start = startidx; m_End = endidx;
m_NodeRanges = nodeRanges;
}
/**
*
* @param nodeNum The node number/id.
* @param startidx The start index of node's portion
* in master index array.
* @param endidx The start index of node's portion
* in master index array.
* @param nodeRanges The attribute ranges of the
* Instances/points contained in this node.
* @param rectBounds The range of the rectangular
* region in the point space that this node
* represents (points inside this rectangular
* region can have different range).
*/
public KDTreeNode(int nodeNum, int startidx, int endidx, double[][] nodeRanges, double[][] rectBounds) {
m_NodeNumber = nodeNum;
m_Start = startidx; m_End = endidx;
m_NodeRanges = nodeRanges;
m_NodesRectBounds = rectBounds;
}
/**
* Gets the splitting dimension.
*
* @return splitting dimension
*/
public int getSplitDim() {
return m_SplitDim;
}
/**
* Gets the splitting value.
*
* @return splitting value
*/
public double getSplitValue() {
return m_SplitValue;
}
/**
* Checks if node is a leaf.
*
* @return true if it is a leaf
*/
public boolean isALeaf() {
return (m_Left == null);
}
/**
* Returns the number of Instances
* in the rectangular region defined
* by this node.
* @return The number of instances in
* this KDTreeNode.
*/
public int numInstances() {
return (m_End-m_Start+1);
}
/**
* 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/neighboursearch
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/neighboursearch/kdtrees/KDTreeNodeSplitter.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/>.
*/
/*
* KDTreeNodeSplitter.java
* Copyright (C) 1999-2012 University of Waikato
*/
package weka.core.neighboursearch.kdtrees;
import java.io.Serializable;
import java.util.Enumeration;
import java.util.Vector;
import weka.core.EuclideanDistance;
import weka.core.Instances;
import weka.core.Option;
import weka.core.OptionHandler;
import weka.core.RevisionHandler;
import weka.core.RevisionUtils;
/**
* Class that splits up a KDTreeNode.
*
* @author Ashraf M. Kibriya (amk14[at-the-rate]cs[dot]waikato[dot]ac[dot]nz)
* @version $Revision$
*/
public abstract class KDTreeNodeSplitter implements Serializable,
OptionHandler, RevisionHandler {
/** ID added to prevent warning */
private static final long serialVersionUID = 7222420817095067166L;
/** The instances that'll be used for tree construction. */
protected Instances m_Instances;
/** The distance function used for building the tree. */
protected EuclideanDistance m_EuclideanDistance;
/**
* The master index array that'll be reshuffled as nodes are split and the
* tree is constructed.
*/
protected int[] m_InstList;
/**
* Stores whether if the width of a KDTree node is normalized or not.
*/
protected boolean m_NormalizeNodeWidth;
// Constants
/** Index of min value in an array of attributes' range. */
public static final int MIN = EuclideanDistance.R_MIN;
/** Index of max value in an array of attributes' range. */
public static final int MAX = EuclideanDistance.R_MAX;
/** Index of width value (max-min) in an array of attributes' range. */
public static final int WIDTH = EuclideanDistance.R_WIDTH;
/**
* default constructor.
*/
public KDTreeNodeSplitter() {
}
/**
* Creates a new instance of KDTreeNodeSplitter.
*
* @param instList Reference of the master index array.
* @param insts The set of training instances on which the tree is built.
* @param e The EuclideanDistance object that is used in tree contruction.
*/
public KDTreeNodeSplitter(int[] instList, Instances insts, EuclideanDistance e) {
m_InstList = instList;
m_Instances = insts;
m_EuclideanDistance = e;
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
return new Vector<Option>().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 {
}
/**
* Gets the current settings of the object.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
return new String[0];
}
/**
* Checks whether an object of this class has been correctly initialized.
* Performs checks to see if all the necessary things (master index array,
* training instances, distance function) have been supplied or not.
*
* @throws Exception If the object has not been correctly initialized.
*/
protected void correctlyInitialized() throws Exception {
if (m_Instances == null) {
throw new Exception("No instances supplied.");
} else if (m_InstList == null) {
throw new Exception("No instance list supplied.");
} else if (m_EuclideanDistance == null) {
throw new Exception("No Euclidean distance function supplied.");
} else if (m_Instances.numInstances() != m_InstList.length) {
throw new Exception("The supplied instance list doesn't seem to match "
+ "the supplied instances");
}
}
/**
* Splits a node into two. After splitting two new nodes are created and
* correctly initialised. And, node.left and node.right are set appropriately.
*
* @param node The node to split.
* @param numNodesCreated The number of nodes that so far have been created
* for the tree, so that the newly created nodes are assigned
* correct/meaningful node numbers/ids.
* @param nodeRanges The attributes' range for the points inside the node that
* is to be split.
* @param universe The attributes' range for the whole point-space.
* @throws Exception If there is some problem in splitting the given node.
*/
public abstract void splitNode(KDTreeNode node, int numNodesCreated,
double[][] nodeRanges, double[][] universe) throws Exception;
/**
* Sets the training instances on which the tree is (or is to be) built.
*
* @param inst The training instances.
*/
public void setInstances(Instances inst) {
m_Instances = inst;
}
/**
* Sets the master index array containing indices of the training instances.
* This array will be rearranged as the tree is built, so that each node is
* assigned a portion in this array which contain the instances insides the
* node's region.
*
* @param instList The master index array.
*/
public void setInstanceList(int[] instList) {
m_InstList = instList;
}
/**
* Sets the EuclideanDistance object to use for splitting nodes.
*
* @param func The EuclideanDistance object.
*/
public void setEuclideanDistanceFunction(EuclideanDistance func) {
m_EuclideanDistance = func;
}
/**
* Sets whether if a nodes region is normalized or not. If set to true then,
* when selecting the widest attribute/dimension for splitting, the width of
* each attribute/dimension, of the points inside the node's region, is
* divided by the width of that attribute/dimension for the whole point-space.
* Thus, each attribute/dimension of that node is normalized.
*
* @param normalize Should be true if normalization is required.
*/
public void setNodeWidthNormalization(boolean normalize) {
m_NormalizeNodeWidth = normalize;
}
/**
* Returns the widest dimension. The width of each dimension (for the points
* inside the node) is normalized, if m_NormalizeNodeWidth is set to true.
*
* @param nodeRanges The attributes' range of the points inside the node that
* is to be split.
* @param universe The attributes' range for the whole point-space.
* @return The index of the attribute/dimension in which the points of the
* node have widest spread.
*/
protected int widestDim(double[][] nodeRanges, double[][] universe) {
final int classIdx = m_Instances.classIndex();
double widest = 0.0;
int w = -1;
if (m_NormalizeNodeWidth) {
for (int i = 0; i < nodeRanges.length; i++) {
double newWidest = nodeRanges[i][WIDTH] / universe[i][WIDTH];
if (newWidest > widest) {
if (i == classIdx) {
continue;
}
widest = newWidest;
w = i;
}
}
} else {
for (int i = 0; i < nodeRanges.length; i++) {
if (nodeRanges[i][WIDTH] > widest) {
if (i == classIdx) {
continue;
}
widest = nodeRanges[i][WIDTH];
w = i;
}
}
}
return w;
}
/**
* 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/neighboursearch
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/neighboursearch/kdtrees/KMeansInpiredMethod.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/>.
*/
/*
* KMeansInpiredMethod.java
* Copyright (C) 2007-2012 University of Waikato, Hamilton, New Zealand
*/
package weka.core.neighboursearch.kdtrees;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.RevisionUtils;
import weka.core.TechnicalInformation;
import weka.core.TechnicalInformation.Field;
import weka.core.TechnicalInformation.Type;
import weka.core.TechnicalInformationHandler;
/**
* <!-- globalinfo-start --> The class that splits a node into two such that the
* overall sum of squared distances of points to their centres on both sides of
* the (axis-parallel) splitting plane is minimum.<br/>
* <br/>
* For more information see also:<br/>
* <br/>
* Ashraf Masood Kibriya (2007). Fast Algorithms for Nearest Neighbour Search.
* Hamilton, New Zealand.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- technical-bibtex-start --> BibTeX:
*
* <pre>
* @mastersthesis{Kibriya2007,
* address = {Hamilton, New Zealand},
* author = {Ashraf Masood Kibriya},
* school = {Department of Computer Science, School of Computing and Mathematical Sciences, University of Waikato},
* title = {Fast Algorithms for Nearest Neighbour Search},
* year = {2007}
* }
* </pre>
* <p/>
* <!-- technical-bibtex-end -->
*
* <!-- options-start --> <!-- options-end -->
*
* @author Ashraf M. Kibriya (amk14[at-the-rate]cs[dot]waikato[dot]ac[dot]nz)
* @version $Revision$
*/
public class KMeansInpiredMethod extends KDTreeNodeSplitter implements
TechnicalInformationHandler {
/** for serialization. */
private static final long serialVersionUID = -866783749124714304L;
/**
* Returns a string describing this nearest neighbour search algorithm.
*
* @return a description of the algorithm for displaying in the
* explorer/experimenter gui
*/
public String globalInfo() {
return "The class that splits a node into two such that the overall sum "
+ "of squared distances of points to their centres on both sides "
+ "of the (axis-parallel) splitting plane is minimum.\n\n"
+ "For more information see also:\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.MASTERSTHESIS);
result.setValue(Field.AUTHOR, "Ashraf Masood Kibriya");
result
.setValue(Field.TITLE, "Fast Algorithms for Nearest Neighbour Search");
result.setValue(Field.YEAR, "2007");
result
.setValue(
Field.SCHOOL,
"Department of Computer Science, School of Computing and Mathematical Sciences, University of Waikato");
result.setValue(Field.ADDRESS, "Hamilton, New Zealand");
return result;
}
/**
* Splits a node into two such that the overall sum of squared distances of
* points to their centres on both sides of the (axis-parallel) splitting
* plane is minimum. The two nodes created after the whole splitting are
* correctly initialised. And, node.left and node.right are set appropriately.
*
* @param node The node to split.
* @param numNodesCreated The number of nodes that so far have been created
* for the tree, so that the newly created nodes are assigned
* correct/meaningful node numbers/ids.
* @param nodeRanges The attributes' range for the points inside the node that
* is to be split.
* @param universe The attributes' range for the whole point-space.
* @throws Exception If there is some problem in splitting the given node.
*/
@Override
public void splitNode(KDTreeNode node, int numNodesCreated,
double[][] nodeRanges, double[][] universe) throws Exception {
correctlyInitialized();
int splitDim = -1;
double splitVal = Double.NEGATIVE_INFINITY;
double leftAttSum[] = new double[m_Instances.numAttributes()], rightAttSum[] = new double[m_Instances
.numAttributes()], leftAttSqSum[] = new double[m_Instances
.numAttributes()], rightAttSqSum[] = new double[m_Instances
.numAttributes()], rightSqMean, leftSqMean, leftSqSum, rightSqSum, minSum = Double.POSITIVE_INFINITY, val;
for (int dim = 0; dim < m_Instances.numAttributes(); dim++) {
// m_MaxRelativeWidth in KDTree ensure there'll be atleast one dim with
// width > 0.0
if (node.m_NodeRanges[dim][WIDTH] == 0.0
|| dim == m_Instances.classIndex()) {
continue;
}
quickSort(m_Instances, m_InstList, dim, node.m_Start, node.m_End);
for (int i = node.m_Start; i <= node.m_End; i++) {
for (int j = 0; j < m_Instances.numAttributes(); j++) {
if (j == m_Instances.classIndex()) {
continue;
}
val = m_Instances.instance(m_InstList[i]).value(j);
if (m_NormalizeNodeWidth) {
if (Double.isNaN(universe[j][MIN])
|| universe[j][MIN] == universe[j][MAX]) {
val = 0.0;
} else {
val = ((val - universe[j][MIN]) / universe[j][WIDTH]); // normalizing
// value
}
}
if (i == node.m_Start) {
leftAttSum[j] = rightAttSum[j] = leftAttSqSum[j] = rightAttSqSum[j] = 0.0;
}
rightAttSum[j] += val;
rightAttSqSum[j] += val * val;
}
}
for (int i = node.m_Start; i <= node.m_End - 1; i++) {
Instance inst = m_Instances.instance(m_InstList[i]);
leftSqSum = rightSqSum = 0.0;
for (int j = 0; j < m_Instances.numAttributes(); j++) {
if (j == m_Instances.classIndex()) {
continue;
}
val = inst.value(j);
if (m_NormalizeNodeWidth) {
if (Double.isNaN(universe[j][MIN])
|| universe[j][MIN] == universe[j][MAX]) {
val = 0.0;
} else {
val = ((val - universe[j][MIN]) / universe[j][WIDTH]); // normalizing
// value
}
}
leftAttSum[j] += val;
rightAttSum[j] -= val;
leftAttSqSum[j] += val * val;
rightAttSqSum[j] -= val * val;
leftSqMean = leftAttSum[j] / (i - node.m_Start + 1);
leftSqMean *= leftSqMean;
rightSqMean = rightAttSum[j] / (node.m_End - i);
rightSqMean *= rightSqMean;
leftSqSum += leftAttSqSum[j] - (i - node.m_Start + 1) * leftSqMean;
rightSqSum += rightAttSqSum[j] - (node.m_End - i) * rightSqMean;
}
if (minSum > (leftSqSum + rightSqSum)) {
minSum = leftSqSum + rightSqSum;
if (i < node.m_End) {
splitVal = (m_Instances.instance(m_InstList[i]).value(dim) + m_Instances
.instance(m_InstList[i + 1]).value(dim)) / 2;
} else {
splitVal = m_Instances.instance(m_InstList[i]).value(dim);
}
splitDim = dim;
}
}// end for instance i
}// end for attribute dim
int rightStart = rearrangePoints(m_InstList, node.m_Start, node.m_End,
splitDim, splitVal);
if (rightStart == node.m_Start || rightStart > node.m_End) {
System.out.println("node.m_Start: " + node.m_Start + " node.m_End: "
+ node.m_End + " splitDim: " + splitDim + " splitVal: " + splitVal
+ " node.min: " + node.m_NodeRanges[splitDim][MIN] + " node.max: "
+ node.m_NodeRanges[splitDim][MAX] + " node.numInstances: "
+ node.numInstances());
if (rightStart == node.m_Start) {
throw new Exception("Left child is empty in node " + node.m_NodeNumber
+ ". Not possible with "
+ "KMeanInspiredMethod splitting method. Please " + "check code.");
} else {
throw new Exception("Right child is empty in node " + node.m_NodeNumber
+ ". Not possible with "
+ "KMeansInspiredMethod splitting method. Please " + "check code.");
}
}
node.m_SplitDim = splitDim;
node.m_SplitValue = splitVal;
node.m_Left = new KDTreeNode(numNodesCreated + 1, node.m_Start,
rightStart - 1, m_EuclideanDistance.initializeRanges(m_InstList,
node.m_Start, rightStart - 1));
node.m_Right = new KDTreeNode(numNodesCreated + 2, rightStart, node.m_End,
m_EuclideanDistance.initializeRanges(m_InstList, rightStart, node.m_End));
}
/**
* Partitions the instances around a pivot. Used by quicksort and
* kthSmallestValue.
*
* @param insts The instances on which the tree is (or is to be) built.
* @param index The master index array containing indices of the instances.
* @param attidx The attribution/dimension based on which the instances should
* be partitioned.
* @param l The begining index of the portion of master index array that
* should be partitioned.
* @param r The end index of the portion of master index array that should be
* partitioned.
* @return the index of the middle element
*/
protected static int partition(Instances insts, int[] index, int attidx,
int l, int r) {
double pivot = insts.instance(index[(l + r) / 2]).value(attidx);
int help;
while (l < r) {
while ((insts.instance(index[l]).value(attidx) < pivot) && (l < r)) {
l++;
}
while ((insts.instance(index[r]).value(attidx) > pivot) && (l < r)) {
r--;
}
if (l < r) {
help = index[l];
index[l] = index[r];
index[r] = help;
l++;
r--;
}
}
if ((l == r) && (insts.instance(index[r]).value(attidx) > pivot)) {
r--;
}
return r;
}
/**
* Sorts the instances according to the given attribute/dimension. The sorting
* is done on the master index array and not on the actual instances object.
*
* @param insts The instances on which the tree is (or is to be) built.
* @param indices The master index array containing indices of the instances.
* @param attidx The dimension/attribute based on which the instances should
* be sorted.
* @param left The begining index of the portion of the master index array
* that needs to be sorted.
* @param right The end index of the portion of the master index array that
* needs to be sorted.
*/
protected static void quickSort(Instances insts, int[] indices, int attidx,
int left, int right) {
if (left < right) {
int middle = partition(insts, indices, attidx, left, right);
quickSort(insts, indices, attidx, left, middle);
quickSort(insts, indices, attidx, middle + 1, right);
}
}
/**
* Re-arranges the indices array so that in the portion of the array belonging
* to the node to be split, the points <= to the splitVal are on the left of
* the portion and those > the splitVal are on the right.
*
* @param indices The master index array.
* @param startidx The begining index of portion of indices that needs
* re-arranging.
* @param endidx The end index of portion of indices that needs re-arranging.
* @param splitDim The split dimension/attribute.
* @param splitVal The split value.
* @return The startIdx of the points > the splitVal (the points belonging to
* the right child of the node).
*/
protected int rearrangePoints(int[] indices, final int startidx,
final int endidx, final int splitDim, final double splitVal) {
int tmp, left = startidx - 1;
for (int i = startidx; i <= endidx; i++) {
if (m_EuclideanDistance.valueIsSmallerEqual(
m_Instances.instance(indices[i]), splitDim, splitVal)) {
left++;
tmp = indices[left];
indices[left] = indices[i];
indices[i] = tmp;
}// end valueIsSmallerEqual
}// endfor
return left + 1;
}
/**
* 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/neighboursearch
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/neighboursearch/kdtrees/MedianOfWidestDimension.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/>.
*/
/*
* MedianOfWidestDimension.java
* Copyright (C) 2007-2012 University of Waikato, Hamilton, New Zealand
*/
package weka.core.neighboursearch.kdtrees;
import weka.core.RevisionUtils;
import weka.core.TechnicalInformation;
import weka.core.TechnicalInformation.Field;
import weka.core.TechnicalInformation.Type;
import weka.core.TechnicalInformationHandler;
/**
<!-- globalinfo-start -->
* The class that splits a KDTree node based on the median value of a dimension in which the node's points have the widest spread.<br/>
* <br/>
* For more information see also:<br/>
* <br/>
* Jerome H. Friedman, Jon Luis Bentley, Raphael Ari Finkel (1977). An Algorithm for Finding Best Matches in Logarithmic Expected Time. ACM Transactions on Mathematics Software. 3(3):209-226.
* <p/>
<!-- globalinfo-end -->
*
<!-- technical-bibtex-start -->
* BibTeX:
* <pre>
* @article{Friedman1977,
* author = {Jerome H. Friedman and Jon Luis Bentley and Raphael Ari Finkel},
* journal = {ACM Transactions on Mathematics Software},
* month = {September},
* number = {3},
* pages = {209-226},
* title = {An Algorithm for Finding Best Matches in Logarithmic Expected Time},
* volume = {3},
* year = {1977}
* }
* </pre>
* <p/>
<!-- technical-bibtex-end -->
*
<!-- options-start -->
<!-- options-end -->
*
* @author Ashraf M. Kibriya (amk14[at-the-rate]cs[dot]waikato[dot]ac[dot]nz)
* @version $Revision$
*/
public class MedianOfWidestDimension
extends KDTreeNodeSplitter
implements TechnicalInformationHandler {
/** for serialization. */
private static final long serialVersionUID = 1383443320160540663L;
/**
* Returns a string describing this nearest neighbour search algorithm.
*
* @return a description of the algorithm for displaying in the
* explorer/experimenter gui
*/
public String globalInfo() {
return
"The class that splits a KDTree node based on the median value of "
+ "a dimension in which the node's points have the widest spread.\n\n"
+ "For more information see also:\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.ARTICLE);
result.setValue(Field.AUTHOR, "Jerome H. Friedman and Jon Luis Bentley and Raphael Ari Finkel");
result.setValue(Field.YEAR, "1977");
result.setValue(Field.TITLE, "An Algorithm for Finding Best Matches in Logarithmic Expected Time");
result.setValue(Field.JOURNAL, "ACM Transactions on Mathematics Software");
result.setValue(Field.PAGES, "209-226");
result.setValue(Field.MONTH, "September");
result.setValue(Field.VOLUME, "3");
result.setValue(Field.NUMBER, "3");
return result;
}
/**
* Splits a node into two based on the median value of the dimension
* in which the points have the widest spread. After splitting two
* new nodes are created and correctly initialised. And, node.left
* and node.right are set appropriately.
*
* @param node The node to split.
* @param numNodesCreated The number of nodes that so far have been
* created for the tree, so that the newly created nodes are
* assigned correct/meaningful node numbers/ids.
* @param nodeRanges The attributes' range for the points inside
* the node that is to be split.
* @param universe The attributes' range for the whole
* point-space.
* @throws Exception If there is some problem in splitting the
* given node.
*/
public void splitNode(KDTreeNode node, int numNodesCreated,
double[][] nodeRanges, double[][] universe) throws Exception {
correctlyInitialized();
int splitDim = widestDim(nodeRanges, universe);
//In this case median is defined to be either the middle value (in case of
//odd number of values) or the left of the two middle values (in case of
//even number of values).
int medianIdxIdx = node.m_Start + (node.m_End-node.m_Start)/2;
//the following finds the median and also re-arranges the array so all
//elements to the left are < median and those to the right are > median.
int medianIdx = select(splitDim, m_InstList, node.m_Start, node.m_End, (node.m_End-node.m_Start)/2+1);
node.m_SplitDim = splitDim;
node.m_SplitValue = m_Instances.instance(m_InstList[medianIdx]).value(splitDim);
node.m_Left = new KDTreeNode(numNodesCreated+1, node.m_Start, medianIdxIdx,
m_EuclideanDistance.initializeRanges(m_InstList, node.m_Start, medianIdxIdx));
node.m_Right = new KDTreeNode(numNodesCreated+2, medianIdxIdx+1, node.m_End,
m_EuclideanDistance.initializeRanges(m_InstList, medianIdxIdx+1, node.m_End));
}
/**
* Partitions the instances around a pivot. Used by quicksort and
* kthSmallestValue.
*
* @param attIdx The attribution/dimension based on which the
* instances should be partitioned.
* @param index The master index array containing indices of the
* instances.
* @param l The begining index of the portion of master index
* array that should be partitioned.
* @param r The end index of the portion of master index array
* that should be partitioned.
* @return the index of the middle element
*/
protected int partition(int attIdx, int[] index, int l, int r) {
double pivot = m_Instances.instance(index[(l + r) / 2]).value(attIdx);
int help;
while (l < r) {
while ((m_Instances.instance(index[l]).value(attIdx) < pivot) && (l < r)) {
l++;
}
while ((m_Instances.instance(index[r]).value(attIdx) > pivot) && (l < r)) {
r--;
}
if (l < r) {
help = index[l];
index[l] = index[r];
index[r] = help;
l++;
r--;
}
}
if ((l == r) && (m_Instances.instance(index[r]).value(attIdx) > pivot)) {
r--;
}
return r;
}
/**
* Implements computation of the kth-smallest element according
* to Manber's "Introduction to Algorithms".
*
* @param attIdx The dimension/attribute of the instances in
* which to find the kth-smallest element.
* @param indices The master index array containing indices of
* the instances.
* @param left The begining index of the portion of the master
* index array in which to find the kth-smallest element.
* @param right The end index of the portion of the master index
* array in which to find the kth-smallest element.
* @param k The value of k
* @return The index of the kth-smallest element
*/
public int select(int attIdx, int[] indices, int left, int right, int k) {
if (left == right) {
return left;
} else {
int middle = partition(attIdx, indices, left, right);
if ((middle - left + 1) >= k) {
return select(attIdx, indices, left, middle, k);
} else {
return select(attIdx, indices, middle + 1, right, k - (middle - left + 1));
}
}
}
/**
* 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/neighboursearch
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/neighboursearch/kdtrees/MidPointOfWidestDimension.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/>.
*/
/*
* MidPointOfWidestDimension.java
* Copyright (C) 2007-2012 University of Waikato, Hamilton, New Zealand
*/
package weka.core.neighboursearch.kdtrees;
import weka.core.RevisionUtils;
import weka.core.TechnicalInformation;
import weka.core.TechnicalInformation.Field;
import weka.core.TechnicalInformation.Type;
import weka.core.TechnicalInformationHandler;
/**
<!-- globalinfo-start -->
* The class that splits a KDTree node based on the midpoint value of a dimension in which the node's points have the widest spread.<br/>
* <br/>
* For more information see also:<br/>
* <br/>
* Andrew Moore (1991). A tutorial on kd-trees.
* <p/>
<!-- globalinfo-end -->
*
<!-- technical-bibtex-start -->
* BibTeX:
* <pre>
* @techreport{Moore1991,
* author = {Andrew Moore},
* booktitle = {University of Cambridge Computer Laboratory Technical Report No. 209},
* howpublished = {Extract from PhD Thesis},
* title = {A tutorial on kd-trees},
* year = {1991},
* HTTP = {http://www.autonlab.org/autonweb/14665.html}
* }
* </pre>
* <p/>
<!-- technical-bibtex-end -->
*
<!-- options-start -->
<!-- options-end -->
*
* @author Ashraf M. Kibriya (amk14[at-the-rate]cs[dot]waikato[dot]ac[dot]nz)
* @version $Revision$
*/
public class MidPointOfWidestDimension
extends KDTreeNodeSplitter
implements TechnicalInformationHandler {
/** for serialization. */
private static final long serialVersionUID = -7617277960046591906L;
/**
* Returns a string describing this nearest neighbour search algorithm.
*
* @return a description of the algorithm for displaying in the
* explorer/experimenter gui
*/
public String globalInfo() {
return
"The class that splits a KDTree node based on the midpoint value of "
+ "a dimension in which the node's points have the widest spread.\n\n"
+ "For more information see also:\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.TECHREPORT);
result.setValue(Field.AUTHOR, "Andrew Moore");
result.setValue(Field.YEAR, "1991");
result.setValue(Field.TITLE, "A tutorial on kd-trees");
result.setValue(Field.HOWPUBLISHED, "Extract from PhD Thesis");
result.setValue(Field.BOOKTITLE, "University of Cambridge Computer Laboratory Technical Report No. 209");
result.setValue(Field.HTTP, "http://www.autonlab.org/autonweb/14665.html");
return result;
}
/**
* Splits a node into two based on the midpoint value of the dimension
* in which the points have the widest spread. After splitting two
* new nodes are created and correctly initialised. And, node.left
* and node.right are set appropriately.
* @param node The node to split.
* @param numNodesCreated The number of nodes that so far have been
* created for the tree, so that the newly created nodes are
* assigned correct/meaningful node numbers/ids.
* @param nodeRanges The attributes' range for the points inside
* the node that is to be split.
* @param universe The attributes' range for the whole
* point-space.
* @throws Exception If there is some problem in splitting the
* given node.
*/
public void splitNode(KDTreeNode node, int numNodesCreated,
double[][] nodeRanges, double[][] universe) throws Exception {
correctlyInitialized();
int splitDim = widestDim(nodeRanges, universe);
double splitVal = m_EuclideanDistance.getMiddle(nodeRanges[splitDim]);
int rightStart = rearrangePoints(m_InstList, node.m_Start, node.m_End,
splitDim, splitVal);
if (rightStart == node.m_Start || rightStart > node.m_End) {
if (rightStart == node.m_Start)
throw new Exception("Left child is empty in node "
+ node.m_NodeNumber +
". Not possible with " +
"MidPointofWidestDim splitting method. Please " +
"check code.");
else
throw new Exception("Right child is empty in node " + node.m_NodeNumber +
". Not possible with " +
"MidPointofWidestDim splitting method. Please " +
"check code.");
}
node.m_SplitDim = splitDim;
node.m_SplitValue = splitVal;
node.m_Left = new KDTreeNode(numNodesCreated + 1, node.m_Start,
rightStart - 1, m_EuclideanDistance.initializeRanges(m_InstList,
node.m_Start, rightStart - 1));
node.m_Right = new KDTreeNode(numNodesCreated + 2, rightStart, node.m_End,
m_EuclideanDistance
.initializeRanges(m_InstList, rightStart, node.m_End));
}
/**
* Re-arranges the indices array such that the points <= to the splitVal
* are on the left of the array and those > the splitVal are on the right.
*
* @param indices The master index array.
* @param startidx The begining index of portion of indices that needs
* re-arranging.
* @param endidx The end index of portion of indices that needs
* re-arranging.
* @param splitDim The split dimension/attribute.
* @param splitVal The split value.
* @return The startIdx of the points > the splitVal (the points
* belonging to the right child of the node).
*/
protected int rearrangePoints(int[] indices, final int startidx, final int endidx,
final int splitDim, final double splitVal) {
int tmp, left = startidx - 1;
for (int i = startidx; i <= endidx; i++) {
if (m_EuclideanDistance.valueIsSmallerEqual(m_Instances
.instance(indices[i]), splitDim, splitVal)) {
left++;
tmp = indices[left];
indices[left] = indices[i];
indices[i] = tmp;
}//end if valueIsSmallerEqual
}//end for
return left + 1;
}
/**
* 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/neighboursearch
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/neighboursearch/kdtrees/SlidingMidPointOfWidestSide.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/>.
*/
/*
* SlidingMidPointOfWidestSide.java
* Copyright (C) 2007-2012 University of Waikato, Hamilton, New Zealand
*/
package weka.core.neighboursearch.kdtrees;
import weka.core.RevisionUtils;
import weka.core.TechnicalInformation;
import weka.core.TechnicalInformation.Field;
import weka.core.TechnicalInformation.Type;
import weka.core.TechnicalInformationHandler;
/**
<!-- globalinfo-start -->
* The class that splits a node into two based on the midpoint value of the dimension in which the node's rectangle is widest. If after splitting one side is empty then it is slided towards the non-empty side until there is at least one point on the empty side.<br/>
* <br/>
* For more information see also:<br/>
* <br/>
* David M. Mount (2006). ANN Programming Manual. College Park, MD, USA.
* <p/>
<!-- globalinfo-end -->
*
<!-- technical-bibtex-start -->
* BibTeX:
* <pre>
* @manual{Mount2006,
* address = {College Park, MD, USA},
* author = {David M. Mount},
* organization = {Department of Computer Science, University of Maryland},
* title = {ANN Programming Manual},
* year = {2006},
* HTTP = {Available from http://www.cs.umd.edu/\~mount/ANN/}
* }
* </pre>
* <p/>
<!-- technical-bibtex-end -->
*
<!-- options-start -->
<!-- options-end -->
*
* @author Ashraf M. Kibriya (amk14@waikato.ac.nz)
* @version $Revision$
*/
public class SlidingMidPointOfWidestSide
extends KDTreeNodeSplitter
implements TechnicalInformationHandler {
/** for serialization. */
private static final long serialVersionUID = 852857628205680562L;
/** The floating point error to tolerate in finding the widest
* rectangular side. */
protected static double ERR = 0.001;
/**
* Returns a string describing this nearest neighbour search algorithm.
*
* @return a description of the algorithm for displaying in the
* explorer/experimenter gui
*/
public String globalInfo() {
return
"The class that splits a node into two based on the midpoint value of "
+ "the dimension in which the node's rectangle is widest. If after "
+ "splitting one side is empty then it is slided towards the non-empty "
+ "side until there is at least one point on the empty side.\n\n"
+ "For more information see also:\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.MANUAL);
result.setValue(Field.AUTHOR, "David M. Mount");
result.setValue(Field.YEAR, "2006");
result.setValue(Field.TITLE, "ANN Programming Manual");
result.setValue(Field.ORGANIZATION, "Department of Computer Science, University of Maryland");
result.setValue(Field.ADDRESS,
"College Park, MD, USA");
result.setValue(Field.HTTP,
"Available from http://www.cs.umd.edu/~mount/ANN/");
return result;
}
/**
* Splits a node into two based on the midpoint value of the dimension
* in which the node's rectangle is widest. If after splitting one side
* is empty then it is slided towards the non-empty side until there is
* at least one point on the empty side. The two nodes created after the
* whole splitting are correctly initialised. And, node.left and
* node.right are set appropriately.
* @param node The node to split.
* @param numNodesCreated The number of nodes that so far have been
* created for the tree, so that the newly created nodes are
* assigned correct/meaningful node numbers/ids.
* @param nodeRanges The attributes' range for the points inside
* the node that is to be split.
* @param universe The attributes' range for the whole
* point-space.
* @throws Exception If there is some problem in splitting the
* given node.
*/
public void splitNode(KDTreeNode node, int numNodesCreated,
double[][] nodeRanges, double[][] universe) throws Exception {
correctlyInitialized();
if (node.m_NodesRectBounds == null) {
node.m_NodesRectBounds = new double[2][node.m_NodeRanges.length];
for (int i = 0; i < node.m_NodeRanges.length; i++) {
node.m_NodesRectBounds[MIN][i] = node.m_NodeRanges[i][MIN];
node.m_NodesRectBounds[MAX][i] = node.m_NodeRanges[i][MAX];
}
}
// finding widest side of the hyper rectangle
double maxRectWidth = Double.NEGATIVE_INFINITY, maxPtWidth = Double.NEGATIVE_INFINITY, tempval;
int splitDim = -1, classIdx = m_Instances.classIndex();
for (int i = 0; i < node.m_NodesRectBounds[0].length; i++) {
if (i == classIdx)
continue;
tempval = node.m_NodesRectBounds[MAX][i] - node.m_NodesRectBounds[MIN][i];
if (m_NormalizeNodeWidth) {
tempval = tempval / universe[i][WIDTH];
}
if (tempval > maxRectWidth && node.m_NodeRanges[i][WIDTH] > 0.0)
maxRectWidth = tempval;
}
for (int i = 0; i < node.m_NodesRectBounds[0].length; i++) {
if (i == classIdx)
continue;
tempval = node.m_NodesRectBounds[MAX][i] - node.m_NodesRectBounds[MIN][i];
if (m_NormalizeNodeWidth) {
tempval = tempval / universe[i][WIDTH];
}
if (tempval >= maxRectWidth * (1 - ERR)
&& node.m_NodeRanges[i][WIDTH] > 0.0) {
if (node.m_NodeRanges[i][WIDTH] > maxPtWidth) {
maxPtWidth = node.m_NodeRanges[i][WIDTH];
if (m_NormalizeNodeWidth)
maxPtWidth = maxPtWidth / universe[i][WIDTH];
splitDim = i;
}
}
}
double splitVal = node.m_NodesRectBounds[MIN][splitDim]
+ (node.m_NodesRectBounds[MAX][splitDim] - node.m_NodesRectBounds[MIN][splitDim])
* 0.5;
// might want to try to slide it further to contain more than one point on
// the
// side that is resulting empty
if (splitVal < node.m_NodeRanges[splitDim][MIN])
splitVal = node.m_NodeRanges[splitDim][MIN];
else if (splitVal >= node.m_NodeRanges[splitDim][MAX])
splitVal = node.m_NodeRanges[splitDim][MAX]
- node.m_NodeRanges[splitDim][WIDTH] * 0.001;
int rightStart = rearrangePoints(m_InstList, node.m_Start, node.m_End,
splitDim, splitVal);
if (rightStart == node.m_Start || rightStart > node.m_End) {
if (rightStart == node.m_Start)
throw new Exception("Left child is empty in node " + node.m_NodeNumber
+ ". Not possible with "
+ "SlidingMidPointofWidestSide splitting method. Please "
+ "check code.");
else
throw new Exception("Right child is empty in node " + node.m_NodeNumber
+ ". Not possible with "
+ "SlidingMidPointofWidestSide splitting method. Please "
+ "check code.");
}
node.m_SplitDim = splitDim;
node.m_SplitValue = splitVal;
double[][] widths = new double[2][node.m_NodesRectBounds[0].length];
System.arraycopy(node.m_NodesRectBounds[MIN], 0, widths[MIN], 0,
node.m_NodesRectBounds[MIN].length);
System.arraycopy(node.m_NodesRectBounds[MAX], 0, widths[MAX], 0,
node.m_NodesRectBounds[MAX].length);
widths[MAX][splitDim] = splitVal;
node.m_Left = new KDTreeNode(numNodesCreated + 1, node.m_Start,
rightStart - 1, m_EuclideanDistance.initializeRanges(m_InstList,
node.m_Start, rightStart - 1), widths);
widths = new double[2][node.m_NodesRectBounds[0].length];
System.arraycopy(node.m_NodesRectBounds[MIN], 0, widths[MIN], 0,
node.m_NodesRectBounds[MIN].length);
System.arraycopy(node.m_NodesRectBounds[MAX], 0, widths[MAX], 0,
node.m_NodesRectBounds[MAX].length);
widths[MIN][splitDim] = splitVal;
node.m_Right = new KDTreeNode(numNodesCreated + 2, rightStart, node.m_End,
m_EuclideanDistance.initializeRanges(m_InstList, rightStart, node.m_End), widths);
}
/**
* Re-arranges the indices array such that the points <= to the splitVal
* are on the left of the array and those > the splitVal are on the right.
*
* @param indices The master index array.
* @param startidx The begining index of portion of indices that needs
* re-arranging.
* @param endidx The end index of portion of indices that needs
* re-arranging.
* @param splitDim The split dimension/attribute.
* @param splitVal The split value.
* @return The startIdx of the points > the splitVal (the points
* belonging to the right child of the node).
*/
protected int rearrangePoints(int[] indices, final int startidx,
final int endidx, final int splitDim, final double splitVal) {
int tmp, left = startidx - 1;
for (int i = startidx; i <= endidx; i++) {
if (m_EuclideanDistance.valueIsSmallerEqual(m_Instances
.instance(indices[i]), splitDim, splitVal)) {
left++;
tmp = indices[left];
indices[left] = indices[i];
indices[i] = tmp;
}// end valueIsSmallerEqual
}// endfor
return left + 1;
}
/**
* 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/packageManagement/DefaultPackage.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/>.
*/
/*
* DefaultPackage.java
* Copyright (C) 2015 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.packageManagement;
import java.io.File;
import java.io.Serializable;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
/**
* A concrete implementation of Package that uses Java properties files/classes
* to manage package meta data. Assumes that meta data for individual packages
* is stored on the central repository (or possibly in a local cache - both
* accessible via http) in properties files that live in a sub-directory with
* the same name as the package. Furthermore, each property file is assumed to
* be named as the version number of the package in question with a ".props"
* extension. A "Latest.props" file should exist for each package and should
* always hold meta data on the latest version of a package.
*
* @author mhall (mhall{[at]}pentaho{[dot]}com).
* @version $Revision: 52462 $
*
*/
public class DefaultPackage extends Package implements Serializable {
/**
* For serialization
*/
private static final long serialVersionUID = 3643121886457892125L;
/** Holds the home directory for installed packages */
protected File m_packageHome;
/** The package manager in use */
protected transient PackageManager m_packageManager;
/**
* Clone this package. Only makes a shallow copy of the meta data map
*
* @return a copy of this package
*/
@Override
public Object clone() {
DefaultPackage newP = null;
if (m_packageHome != null) {
newP =
new DefaultPackage(new File(m_packageHome.toString()), m_packageManager);
} else {
newP = new DefaultPackage(null, m_packageManager);
}
HashMap<Object, Object> metaData = new HashMap<Object, Object>();
Set<?> keys = m_packageMetaData.keySet();
Iterator<?> i = keys.iterator();
while (i.hasNext()) {
Object key = i.next();
Object value = m_packageMetaData.get(key);
metaData.put(key, value);
}
newP.setPackageMetaData(metaData);
return newP;
}
/**
* Set the package manager for this package
*
* @param p the package manager to use
*/
public void setPackageManager(PackageManager p) {
m_packageManager = p;
}
/**
* Constructs an new DefaultPackage.
*
* @param packageHome the directory that packages are installed into.
* @param manager the package manager in use.
* @param packageMetaData A Map of package meta data for this package.
*/
public DefaultPackage(File packageHome, PackageManager manager,
Map<?, ?> packageMetaData) {
this(packageHome, manager);
setPackageMetaData(packageMetaData);
}
/**
* Constructs a new DefaultPackage.
*
* @param packageHome the directory that packages are installed into.
* @param manager the package manager in use.
*/
public DefaultPackage(File packageHome, PackageManager manager) {
m_packageHome = packageHome;
m_packageManager = manager;
}
/**
* Convenience method that returns the URL to the package (i.e the provider's
* URL). This information is assumed to be stored in the package meta data.
*
* @return the URL to the package or null if the URL is not available for some
* reason
* @throws Exception if the URL can't be retrieved for some reason
*/
@Override
public URL getPackageURL() throws Exception {
String url = getPackageMetaDataElement("PackageURL").toString().trim();
URL packageURL = new URL(url);
return packageURL;
}
/**
* Convenience method to return the name of this package.
*
* @return the name of this package.
*/
@Override
public String getName() {
return getPackageMetaDataElement("PackageName").toString();
}
protected static String[] splitNameVersion(String nameAndVersion) {
String[] result = new String[3];
nameAndVersion = nameAndVersion.trim();
if (nameAndVersion.indexOf('(') < 0) {
result[0] = nameAndVersion;
} else if (nameAndVersion.indexOf(')') >= 0) {
boolean ok = true;
result[0] = nameAndVersion.substring(0, nameAndVersion.indexOf('('));
result[0] = result[0].trim();
String secondInequality = null;
int delimiterIndex = nameAndVersion.indexOf('|');
if (delimiterIndex >= 0) {
secondInequality =
nameAndVersion.substring(delimiterIndex + 1, nameAndVersion.length());
secondInequality = secondInequality.trim();
String[] result2 = new String[5];
result2[0] = result[0];
result = result2;
} else {
delimiterIndex = nameAndVersion.length();
}
nameAndVersion =
nameAndVersion.substring(nameAndVersion.indexOf('(') + 1,
delimiterIndex);
nameAndVersion = nameAndVersion.trim();
int pos = 1;
if (nameAndVersion.charAt(0) == '=') {
result[1] = "=";
} else if (nameAndVersion.charAt(1) == '=') {
pos++;
if (nameAndVersion.charAt(0) == '<') {
result[1] = "<=";
} else {
result[1] = ">=";
}
} else if (nameAndVersion.charAt(0) == '<') {
result[1] = "<";
} else if (nameAndVersion.charAt(0) == '>') {
result[1] = ">";
} else {
ok = false;
}
if (ok) {
if (secondInequality != null) {
delimiterIndex = nameAndVersion.length();
} else {
delimiterIndex = nameAndVersion.indexOf(')');
}
nameAndVersion = nameAndVersion.substring(pos, delimiterIndex);
result[2] = nameAndVersion.trim();
}
// do the second inequality (if present)
if (secondInequality != null) {
ok = true;
pos = 1;
if (secondInequality.charAt(0) == '=') {
result[3] = "=";
} else if (secondInequality.charAt(1) == '=') {
pos++;
if (secondInequality.charAt(0) == '<') {
result[3] = "<=";
} else {
result[3] = ">=";
}
} else if (secondInequality.charAt(0) == '<') {
result[3] = "<";
} else if (secondInequality.charAt(0) == '>') {
result[3] = ">";
} else {
ok = false;
}
if (ok) {
secondInequality =
secondInequality.substring(pos, secondInequality.indexOf(')'));
result[4] = secondInequality.trim();
}
}
}
return result;
}
/**
* Get the list of packages that this package depends on.
*
* @return the list of packages that this package depends on.
* @throws Exception if a problem occurs while getting the list of
* dependencies.
*/
@Override
public List<Dependency> getDependencies() throws Exception {
List<Dependency> dependencies = new ArrayList<Dependency>();
String dependenciesS = getPackageMetaDataElement("Depends").toString();
if (dependenciesS != null) {
StringTokenizer tok = new StringTokenizer(dependenciesS, ",");
while (tok.hasMoreTokens()) {
String nextT = tok.nextToken().trim();
String[] split = splitNameVersion(nextT);
Package toAdd = null;
// don't include the base system!
if (!(split[0].equalsIgnoreCase(m_packageManager.getBaseSystemName()))) {
// gets the latest version of this package if split[2] is null
toAdd = m_packageManager.getRepositoryPackageInfo(split[0], split[2]);
if (split.length == 3) {
VersionPackageConstraint versionConstraint =
new VersionPackageConstraint(toAdd);
if (split[2] == null) {
// assume anything up to and including the current version is
// acceptable
versionConstraint
.setVersionConstraint(VersionPackageConstraint.VersionComparison.LESSTHANOREQUAL);
} else {
versionConstraint.setVersionConstraint(split[1]);
}
Dependency dep = new Dependency(this, versionConstraint);
dependencies.add(dep);
} else {
// ranged constraint
VersionRangePackageConstraint versionConstraint =
new VersionRangePackageConstraint(toAdd);
VersionPackageConstraint.VersionComparison comp1 =
VersionPackageConstraint.getVersionComparison(split[1]);
VersionPackageConstraint.VersionComparison comp2 =
VersionPackageConstraint.getVersionComparison(split[3]);
versionConstraint.setRangeConstraint(split[2], comp1, split[4],
comp2);
Dependency dep = new Dependency(this, versionConstraint);
dependencies.add(dep);
}
}
}
}
return dependencies;
}
/**
* Gets the dependency on the base system that this package requires.
*
* @return the base system dependency(s) for this package
* @throws Exception if the base system dependency can't be determined for
* some reason.
*/
@Override
public List<Dependency> getBaseSystemDependency() throws Exception {
String dependenciesS = getPackageMetaDataElement("Depends").toString();
Dependency baseDep = null;
List<Dependency> baseDeps = new ArrayList<Dependency>();
if (dependenciesS != null) {
StringTokenizer tok = new StringTokenizer(dependenciesS, ",");
while (tok.hasMoreTokens()) {
String nextT = tok.nextToken().trim();
String[] split = splitNameVersion(nextT);
if ((split[0].equalsIgnoreCase(m_packageManager.getBaseSystemName()))) {
// construct a "dummy" package for the base system
Map<String, String> baseMap = new HashMap<String, String>();
baseMap.put("PackageName", "weka");
// use a suitably ridiculous max version number if one hasn't been
// supplied
// for some reason
split[2] = (split[2] == null ? "1000.1000.1000" : split[2]);
baseMap.put("Version", split[2]);
Package basePackage =
new DefaultPackage(null, m_packageManager, baseMap);
if (split.length == 3) {
VersionPackageConstraint baseConstraint =
new VersionPackageConstraint(basePackage);
VersionPackageConstraint.VersionComparison baseComp =
VersionPackageConstraint.VersionComparison.LESSTHANOREQUAL;
if (split[1] != null) {
baseComp =
VersionPackageConstraint.getVersionComparison(split[1]);
}
baseConstraint.setVersionConstraint(baseComp);
baseDep = new Dependency(this, baseConstraint);
baseDeps.add(baseDep);
} else {
// ranged constraint
VersionRangePackageConstraint baseConstraint =
new VersionRangePackageConstraint(basePackage);
VersionPackageConstraint.VersionComparison comp1 =
VersionPackageConstraint.getVersionComparison(split[1]);
VersionPackageConstraint.VersionComparison comp2 =
VersionPackageConstraint.getVersionComparison(split[3]);
baseConstraint.setRangeConstraint(split[2], comp1, split[4], comp2);
baseDep = new Dependency(this, baseConstraint);
baseDeps.add(baseDep);
}
}
}
}
if (baseDeps.size() == 0) {
throw new Exception("[Package] "
+ getPackageMetaDataElement("PackageName").toString()
+ " can't determine what version of the base system is required!!");
}
return baseDeps;
}
private boolean findPackage(String packageName, List<Package> packageList) {
boolean found = false;
Iterator<Package> i = packageList.iterator();
while (i.hasNext()) {
Package p = i.next();
String pName = p.getPackageMetaDataElement("PackageName").toString();
if (packageName.equals(pName)) {
found = true;
break;
}
}
return found;
}
/**
* Gets a list of packages that this package depends on that are not in the
* supplied list of packages.
*
* @param packages a list of packages to compare this package's dependencies
* against.
* @return those packages that this package depends on that aren't in the
* supplied list.
* @throws Exception if the list of missing depenencies can't be determined
* for some reason.
*/
@Override
public List<Dependency> getMissingDependencies(List<Package> packages)
throws Exception {
List<Dependency> missing = new ArrayList<Dependency>();
String dependencies = getPackageMetaDataElement("Depends").toString();
if (dependencies != null) {
StringTokenizer tok = new StringTokenizer(dependencies, ",");
while (tok.hasMoreTokens()) {
String nextT = tok.nextToken().trim();
String[] split = splitNameVersion(nextT);
// don't consider the base system!
if (!(split[0].equalsIgnoreCase(m_packageManager.getBaseSystemName()))) {
// gets the latest version of this package if split[2] is null
Package tempDep =
m_packageManager.getRepositoryPackageInfo(split[0], split[2]);
if (!findPackage(split[0], packages)) {
VersionPackageConstraint versionConstraint =
new VersionPackageConstraint(tempDep);
if (split[2] == null) {
// assume anything up to and including the current version is
// acceptable
versionConstraint
.setVersionConstraint(VersionPackageConstraint.VersionComparison.LESSTHANOREQUAL);
missing.add(new Dependency(this, versionConstraint));
} else {
if (split.length == 3) {
versionConstraint.setVersionConstraint(split[1]);
missing.add(new Dependency(this, versionConstraint));
} else {
VersionRangePackageConstraint versionRConstraint =
new VersionRangePackageConstraint(tempDep);
VersionPackageConstraint.VersionComparison comp1 =
VersionPackageConstraint.getVersionComparison(split[1]);
VersionPackageConstraint.VersionComparison comp2 =
VersionPackageConstraint.getVersionComparison(split[3]);
versionRConstraint.setRangeConstraint(split[2], comp1,
split[4], comp2);
missing.add(new Dependency(this, versionRConstraint));
}
}
}
}
}
}
return missing;
}
/**
* Gets a list of packages that this package depends on that are not currently
* installed.
*
* @return a list of missing packages that this package depends on.
*/
@Override
public List<Dependency> getMissingDependencies() throws Exception {
List<Package> installedPackages = m_packageManager.getInstalledPackages();
String dependencies = getPackageMetaDataElement("Depends").toString();
return getMissingDependencies(installedPackages);
/*
* if (dependencies != null) { StringTokenizer tok = new
* StringTokenizer(dependencies, ","); while (tok.hasMoreTokens()) { String
* nextT = tok.nextToken().trim(); String[] split = splitNameVersion(nextT);
*
* // don't consider the base system! if
* (!(split[0].equalsIgnoreCase(m_packageManager.getBaseSystemName()))) {
*
* // gets the latest version of this package if split[2] is null Package
* tempDep = m_packageManager.getRepositoryPackageInfo(split[0], split[2]);
* if (!tempDep.isInstalled()) { VersionPackageConstraint versionConstraint
* = new VersionPackageConstraint(tempDep); if (split[2] == null) { //
* assume anything up to and including the current version is acceptable
* versionConstraint.
* setVersionConstraint(VersionPackageConstraint.VersionComparison
* .LESSTHANOREQUAL); } else {
* versionConstraint.setVersionConstraint(split[1]); }
*
* missing.add(new Dependency(this, versionConstraint)); } } } }
*
* return missing;
*/
}
/**
* Compares this package's precluded list (if any) against the list of
* supplied packages. Any packages in the supplied list that match (by name
* and version constraints) any in the precluded list are returned
*
* @param packages a list of packages to compare against those in this
* package's precluded list
* @return a list of packages that are covered by those in the precluded list
* @throws Exception if a problem occurs
*/
@Override
public List<Package> getPrecludedPackages(List<Package> packages)
throws Exception {
List<Package> result = new ArrayList<>();
Object precluded = getPackageMetaDataElement("Precludes");
if (precluded != null) {
StringTokenizer tok = new StringTokenizer(precluded.toString(), ",");
while (tok.hasMoreTokens()) {
String nextT = tok.nextToken().trim();
String[] splitD = splitNameVersion(nextT);
// look for a match
for (Package p : packages) {
if (p.getName().equalsIgnoreCase(splitD[0].trim())) {
// if a version number is supplied then check, otherwise assume
// that version does not matter
if (splitD[1] != null && splitD[2] != null) {
String versionI =
p.getPackageMetaDataElement("Version").toString().trim();
if (splitD.length == 3) {
VersionPackageConstraint.VersionComparison constraint =
VersionPackageConstraint.getVersionComparison(splitD[1]);
if (VersionPackageConstraint.checkConstraint(versionI,
constraint, splitD[2])) {
result.add(p);
}
} else {
VersionRangePackageConstraint versionRConstraint =
new VersionRangePackageConstraint(p);
VersionPackageConstraint.VersionComparison comp1 =
VersionPackageConstraint.getVersionComparison(splitD[1]);
VersionPackageConstraint.VersionComparison comp2 =
VersionPackageConstraint.getVersionComparison(splitD[3]);
versionRConstraint.setRangeConstraint(splitD[2], comp1,
splitD[4], comp2);
if (versionRConstraint.checkConstraint(p)) {
result.add(p);
}
}
} else {
result.add(p);
}
}
}
}
}
return result;
}
/**
* Gets those packages from the supplied list that this package depends on and
* are currently incompatible with this package.
*
* @param packages a list of packages to compare this package's dependencies
* against
* @return those packages from the supplied list that are incompatible with
* respect to this package's dependencies
* @throws Exception if the list of incompatible dependencies can't be
* generated for some reason.
*/
@Override
public List<Dependency> getIncompatibleDependencies(List<Package> packages)
throws Exception {
List<Dependency> incompatible = new ArrayList<Dependency>();
String dependencies = getPackageMetaDataElement("Depends").toString();
if (dependencies != null) {
StringTokenizer tok = new StringTokenizer(dependencies, ",");
while (tok.hasMoreTokens()) {
String nextT = tok.nextToken().trim();
String[] splitD = splitNameVersion(nextT);
// check only if a version number was supplied in the dependency list.
if (splitD[1] != null && splitD[2] != null) {
for (Package p : packages) {
String packageNameI =
p.getPackageMetaDataElement("PackageName").toString();
if (packageNameI.trim().equalsIgnoreCase(splitD[0].trim())) {
// now check version against this one
String versionI =
p.getPackageMetaDataElement("Version").toString().trim();
// String[] splitI = splitNameVersion(versionI);
if (splitD.length == 3) {
VersionPackageConstraint.VersionComparison constraint =
VersionPackageConstraint.getVersionComparison(splitD[1]);
if (!VersionPackageConstraint.checkConstraint(versionI,
constraint, splitD[2])) {
VersionPackageConstraint vpc =
new VersionPackageConstraint(p);
vpc.setVersionConstraint(constraint);
incompatible.add(new Dependency(this, vpc));
}
} else {
VersionRangePackageConstraint versionRConstraint =
new VersionRangePackageConstraint(p);
VersionPackageConstraint.VersionComparison comp1 =
VersionPackageConstraint.getVersionComparison(splitD[1]);
VersionPackageConstraint.VersionComparison comp2 =
VersionPackageConstraint.getVersionComparison(splitD[3]);
versionRConstraint.setRangeConstraint(splitD[2], comp1,
splitD[4], comp2);
incompatible.add(new Dependency(this, versionRConstraint));
}
/*
* int comparisonResult =
* VersionPackageConstraint.compare(versionI, splitD[2]); if
* (!versionOK(splitD[1], comparisonResult)) {
* incompatible.add(p); }
*/
}
}
}
}
}
return incompatible;
}
/**
* Gets a list of installed packages that this package depends on that are
* currently incompatible with this package.
*
* @return a list of incompatible installed packages that this package depends
* on.
*/
@Override
public List<Dependency> getIncompatibleDependencies() throws Exception {
List<Package> installedP = m_packageManager.getInstalledPackages();
String dependencies = getPackageMetaDataElement("Depends").toString();
return getIncompatibleDependencies(installedP);
/*
* if (dependencies != null) { StringTokenizer tok = new
* StringTokenizer(dependencies, ","); while (tok.hasMoreTokens()) { String
* nextT = tok.nextToken().trim(); String[] splitD =
* splitNameVersion(nextT);
*
* // check only if a version number was supplied in the dependency list. if
* (splitD[1] != null && splitD[2] != null) { for (Package p : installedP) {
* String packageNameI =
* p.getPackageMetaDataElement("PackageName").toString(); if
* (packageNameI.trim().equalsIgnoreCase(splitD[0].trim())) { // now check
* version against installed String versionI =
* p.getPackageMetaDataElement("Version").toString().trim(); // String[]
* splitI = splitNameVersion(versionI);
*
* VersionPackageConstraint.VersionComparison constraint =
* VersionPackageConstraint.getVersionComparison(splitD[1]); if
* (!VersionPackageConstraint.checkConstraint(versionI, constraint,
* splitD[2])) { VersionPackageConstraint vpc = new
* VersionPackageConstraint(p); vpc.setVersionConstraint(constraint);
* incompatible.add(new Dependency(this, vpc)); } } } } } }
*
* return incompatible;
*/
}
/*
* public Object getPackageDependencyVersion(String dependsOnName) { String
* dependencies = getPackageMetaDataElement("Depends").toString(); Object
* result = null;
*
* if (dependencies != null) { StringTokenizer tok = new
* StringTokenizer(dependencies, ","); while (tok.hasMoreTokens()) { String
* nextT = tok.nextToken().trim(); String[] splitD = splitNameVersion(nextT);
* if (dependsOnName.trim().equalsIgnoreCase(splitD[0]) && splitD[2] != null)
* { result = splitD[2]; break; } } }
*
* return result; }
*/
/**
* Returns true if this package is compatible with the currently installed
* version of the base system.
*
* @return true if this package is compatible with the main software system.
* @throws Exception if a problem occurs while checking compatibility.
*/
@Override
public boolean isCompatibleBaseSystem() throws Exception {
String baseSystemName = m_packageManager.getBaseSystemName();
String systemVersion = m_packageManager.getBaseSystemVersion().toString();
// System.err.println("Base system version " + systemVersion);
String dependencies = getPackageMetaDataElement("Depends").toString();
if (dependencies == null) {
return true;
}
boolean ok = true;
StringTokenizer tok = new StringTokenizer(dependencies, ",");
while (tok.hasMoreTokens()) {
String nextT = tok.nextToken().trim();
String[] split = splitNameVersion(nextT);
if (split[0].startsWith(baseSystemName.toLowerCase())) {
// check the system version
if (split[1] != null) {
if (split.length == 3) {
VersionPackageConstraint.VersionComparison constraint =
VersionPackageConstraint.getVersionComparison(split[1]);
if (!VersionPackageConstraint.checkConstraint(systemVersion,
constraint, split[2])) {
ok = false;
break;
}
} else {
// construct a "dummy" package for the base system
Map<String, String> baseMap = new HashMap<String, String>();
baseMap.put("PackageName", "weka");
baseMap.put("Version", systemVersion);
Package basePackage =
new DefaultPackage(null, m_packageManager, baseMap);
VersionRangePackageConstraint versionRConstraint =
new VersionRangePackageConstraint(basePackage);
VersionPackageConstraint.VersionComparison comp1 =
VersionPackageConstraint.getVersionComparison(split[1]);
VersionPackageConstraint.VersionComparison comp2 =
VersionPackageConstraint.getVersionComparison(split[3]);
versionRConstraint.setRangeConstraint(split[2], comp1, split[4],
comp2);
if (!versionRConstraint.checkConstraint(basePackage)) {
ok = false;
break;
}
}
/*
* int comparisonResult =
* VersionPackageConstraint.compare(systemVersion, split[2]); ok =
* versionOK(split[1], comparisonResult); if (!ok) { break; }
*/
}
}
}
return ok;
}
/**
* Returns true if this package is good to go with the current version of the
* software and versions of any installed packages that it depends on.
*
* @return true if this package is good to go.
* @throws Exception if a problem occurs while checking compatibility.
*/
/*
* public boolean isCompatible() throws Exception { // TODO rewrite this to
* make use of getIncompatibleDependencies() // and getMissingDependencies()
* (IF this package is installed)
*
* // MIGHT just rename this method to isCompatibleWithBaseSystem
*
* boolean ok = isCompatibleBaseSystem();
*
* if (ok) { // check for any incompatible dependencies List<Dependency>
* incompatible = getIncompatibleDependencies(); if (incompatible.size() > 0)
* { ok = false; } }
*
* if (ok && isInstalled()) { // first check to see if the installed version
* is the same as us Package installedVersion =
* m_packageManager.getInstalledPackageInfo
* (getPackageMetaDataElement("PackageName").toString()); String
* installedVersionS =
* installedVersion.getPackageMetaDataElement("Version").toString(); String
* thisVersionS = getPackageMetaDataElement("Version").toString();
*
* if (VersionPackageConstraint.compare(thisVersionS, installedVersionS) ==
* VersionPackageConstraint.VersionComparison.EQUAL) { // if equal to the
* installed version then check to see if any dependencies are // missing. If
* not equal to the installed version then just assume that we // we be
* overwriting the installed version and any missing dependencies will // be
* downloaded during the install. List<Dependency> missing =
* getMissingDependencies(); if (missing.size() > 0) { ok = false; } } }
*
* return ok; }
*/
/**
* Install this package.
*
* @throws Exception if something goes wrong during installation.
*/
@Override
public void install() throws Exception {
URL packageURL = getPackageURL();
m_packageManager.installPackageFromURL(packageURL);
}
/**
* Returns true if this package is already installed
*
* @return true if this package is installed
*/
@Override
public boolean isInstalled() {
File packageDir =
new File(m_packageHome.getAbsoluteFile() + File.separator
+ m_packageMetaData.get("PackageName") + File.separator
+ "Description.props");
return (packageDir.exists());
}
public static void main(String[] args) {
String installed = args[0];
String toCheckAgainst = args[1];
String[] splitI = splitNameVersion(installed);
String[] splitA = splitNameVersion(toCheckAgainst);
try {
if (splitA.length == 3) {
System.out
.println("Checking first version number against second constraint");
VersionPackageConstraint.VersionComparison constraint =
VersionPackageConstraint.getVersionComparison(splitA[1]);
if (VersionPackageConstraint.checkConstraint(splitI[2], constraint,
splitA[2])) {
System.out.println(splitI[2] + " is compatible with " + args[1]);
} else {
System.out.println(splitI[2] + " is not compatible with " + args[1]);
}
Map<String, String> baseMap = new HashMap<String, String>();
baseMap.put("PackageName", splitA[0]);
baseMap.put("Version", splitA[2]);
Package packageA = new DefaultPackage(null, null, baseMap);
packageA.setPackageMetaData(baseMap);
VersionPackageConstraint constrA =
new VersionPackageConstraint(packageA);
constrA.setVersionConstraint(constraint);
if (splitI.length == 3) {
VersionPackageConstraint.VersionComparison constraintI =
VersionPackageConstraint.getVersionComparison(splitI[1]);
Package packageI = (Package) packageA.clone();
packageI.setPackageMetaDataElement(
VersionPackageConstraint.VERSION_KEY, splitI[2]);
VersionPackageConstraint constrI =
new VersionPackageConstraint(packageI);
constrI.setVersionConstraint(constraintI);
PackageConstraint pc = null;
if ((pc = constrI.checkConstraint(constrA)) != null) {
System.out.println(constrI + " and " + constrA
+ " are compatible\n\n" + "compatible constraint " + pc);
} else {
System.out.println(constrI + " and " + constrA
+ " are not compatible");
}
} else {
// TODO
}
} else {
System.out
.println("Checking first version number against second constraint");
Map<String, String> baseMap = new HashMap<String, String>();
baseMap.put("PackageName", splitI[0]);
baseMap.put("Version", splitI[2]);
Package p = new DefaultPackage(null, null, baseMap);
VersionRangePackageConstraint c = new VersionRangePackageConstraint(p);
VersionPackageConstraint.VersionComparison comp1 =
VersionPackageConstraint.getVersionComparison(splitA[1]);
VersionPackageConstraint.VersionComparison comp2 =
VersionPackageConstraint.getVersionComparison(splitA[3]);
c.setRangeConstraint(splitA[2], comp1, splitA[4], comp2);
if (c.checkConstraint(p)) {
System.out.println(splitI[2] + " is compatible with " + args[1]);
} else {
System.out.println(splitI[2] + " is not compatible with " + args[1]);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
/*
* int compResult = VersionPackageConstraint.compare(splitI[2], splitA[2]);
* if (versionOK(splitA[1], compResult)) { System.out.println("Compatible");
* } else { System.out.println("Not ok"); }
*/
}
/**
* Adds a key, value pair to the meta data map.
*
* @param key the key
* @param value the value to add
* @throws Exception if there is no meta data map to add to.
*/
@Override
public void setPackageMetaDataElement(Object key, Object value)
throws Exception {
if (m_packageMetaData == null) {
throw new Exception("[DefaultPackage] no meta data map has been set!");
}
// cast to Object is fine because our maps are Properties.
Map<Object, Object> meta = (Map<Object, Object>) m_packageMetaData;
meta.put(key, value);
}
@Override
public String toString() {
String packageName = getPackageMetaDataElement("PackageName").toString();
String version = getPackageMetaDataElement("Version").toString();
return packageName + " (" + version + ")";
}
}
|
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/packageManagement/DefaultPackageManager.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/>.
*/
/*
* DefaultPackageManager.java
* Copyright (C) 2015 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.packageManagement;
import weka.core.Defaults;
import weka.core.Environment;
import weka.core.Settings;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
/**
* A concrete implementation of PackageManager that uses Java properties
* files/class to manage package meta data. Assumes that meta data for
* individual packages is stored on the central repository (accessible via http)
* in properties files that live in a subdirectory with the same name as the
* package. Furthermore, each property file is assumed to be named as the
* version number of the package in question with a ".props" extension. A
* "Latest.props" file should exist for each package and should always hold meta
* data on the latest version of a package.
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision: 52515 $
*/
public class DefaultPackageManager extends PackageManager {
/** buffer size for copying files */
protected static final int BUFF_SIZE = 100000;
/** buffer used in copying files */
protected static final byte[] m_buffer = new byte[BUFF_SIZE];
protected static final String INSTALLED_PACKAGE_CACHE_FILE =
"installedPackageCache.ser";
protected static List<Package> s_installedPackageList;
/** Timeout to use for comms */
protected int m_timeout = DefaultPMDefaults.SOCKET_TIMEOUT;
/** Key for the socket timeout property */
protected static final String TIMEOUT_PROPERTY =
"weka.packageManager.timeout";
/**
* Constructor
*/
public DefaultPackageManager() {
// set timeout based on property (if set)
String timeout = System.getProperty(TIMEOUT_PROPERTY);
if (timeout != null && timeout.length() > 0) {
try {
m_timeout = Integer.parseInt(timeout);
} catch (NumberFormatException e) {
// ignore quietly
}
}
}
/**
* Get the default settings for the default package manager
*
* @return the default settings
*/
@Override
public Defaults getDefaultSettings() {
return new DefaultPMDefaults();
}
/**
* Apply settings.
*
* @param settings the settings to apply
*/
@Override
public void applySettings(Settings settings) {
m_timeout =
settings.getSetting(settings.getID(),
DefaultPMDefaults.SOCKET_TIMEOUT_KEY, DefaultPMDefaults.SOCKET_TIMEOUT,
Environment.getSystemWide());
}
/**
* Default settings for the default package manager implementation
*/
protected static final class DefaultPMDefaults extends Defaults {
protected static final String APP_ID = "defaultpackagemanager";
protected static final Settings.SettingKey SOCKET_TIMEOUT_KEY =
new Settings.SettingKey(APP_ID + ".timeout",
"Timeout (in ms) for socket " + "comms", "");
/** Default timeout for socket connections (5 seconds) */
protected static final int SOCKET_TIMEOUT = 5000;
private static final long serialVersionUID = -1428588514991146709L;
public DefaultPMDefaults() {
super("defaultpackagemanager");
m_defaults.put(SOCKET_TIMEOUT_KEY, SOCKET_TIMEOUT);
}
}
/*
* protected File downloadPackage2(URL packageURL, PrintStream... progress)
* throws Exception { String packageArchiveName = packageURL.toString();
* packageArchiveName =
* packageArchiveName.substring(packageArchiveName.lastIndexOf('/'),
* packageArchiveName.length()); packageArchiveName =
* packageArchiveName.substring(0, packageArchiveName.lastIndexOf('.'));
*
* // make a temp file to hold the downloaded archive File tmpDownload =
* File.createTempFile(packageArchiveName, ".zip");
*
* for (int i = 0; i < progress.length; i++) { progress[i].println(
* "[Package Manager] Tmp file: " + tmpDownload.toString()); }
*
* System.err.println("Here in downloadPackage..."); URLConnection conn =
* null;
*
* // setup the proxy (if we are using one) and open the connect if
* (setProxyAuthentication()) { conn = packageURL.openConnection(m_httpProxy);
* } else { conn = packageURL.openConnection(); }
*
* if (conn instanceof HttpURLConnection) { System.err.println(
* "We have a http url conn."); }
*
* BufferedReader br = new BufferedReader(new
* InputStreamReader(conn.getInputStream()));
*
* String line = null;
*
* while ((line = br.readLine()) != null) { System.err.println(line); }
*
* br.close();
*
* return null; }
*/
protected File downloadArchive(URL packageURL, String fileExtension,
PrintStream... progress) throws Exception {
String packageArchiveName = packageURL.toString();
packageArchiveName =
packageArchiveName.substring(0,
packageArchiveName.lastIndexOf("." + fileExtension) + 3);
packageArchiveName =
packageArchiveName.substring(0, packageArchiveName.lastIndexOf('.'));
packageArchiveName =
packageArchiveName.substring(packageArchiveName.lastIndexOf('/'),
packageArchiveName.length());
// make a temp file to hold the downloaded archive
File tmpDownload =
File.createTempFile(packageArchiveName, "." + fileExtension);
for (PrintStream progres : progress) {
progres.println("[DefaultPackageManager] Tmp file: "
+ tmpDownload.toString());
}
URLConnection conn = getConnection(packageURL);
BufferedInputStream bi = new BufferedInputStream(conn.getInputStream());
BufferedOutputStream bo =
new BufferedOutputStream(new FileOutputStream(tmpDownload));
// download the archive
int totalBytesRead = 0;
while (true) {
synchronized (m_buffer) {
int amountRead = bi.read(m_buffer);
if (amountRead == -1) {
for (PrintStream progres : progress) {
progres.print("[DefaultPackageManager] downloaded "
+ (totalBytesRead / 1000) + " KB\r");
}
break;
}
bo.write(m_buffer, 0, amountRead);
totalBytesRead += amountRead;
for (PrintStream progres : progress) {
progres.print("%%[DefaultPackageManager] downloaded "
+ (totalBytesRead / 1000) + " KB\r");
}
}
}
bi.close();
bo.close();
return tmpDownload;
}
/**
* Get package information on the package at the given URL.
*
* @param packageURL the URL to the package.
* @return a Package object encapsulating the package meta data
* @throws Exception if the package meta data can't be retrieved.
*/
@Override
public Package getURLPackageInfo(URL packageURL) throws Exception {
File downloaded = downloadArchive(packageURL, "zip");
// return the package info
return getPackageArchiveInfo(downloaded);
}
/**
* Get package information on the named package from the repository. If
* multiple versions of the package are available, it assumes that the most
* recent is required.
*
* @param packageName the name of the package to get information about.
* @return a Package object encapsulating the package meta data.
* @throws Exception if the package meta data can't be retrieved.
*/
@Override
public Package getRepositoryPackageInfo(String packageName) throws Exception {
return getRepositoryPackageInfo(packageName, "Latest");
}
/**
* Get a list of available versions of the named package.
*
* @param packageName the name of the package to get versions.
* @return a list of available versions (or null if not applicable)
* @throws Exception if something goes wrong while trying to retrieve the list
* of versions.
*/
@Override
public List<Object> getRepositoryPackageVersions(String packageName)
throws Exception {
if (getPackageRepositoryURL() == null) {
throw new Exception("[DefaultPackageManager] No package repository set!!");
}
String versionsS =
m_packageRepository.toString() + "/" + packageName + "/" + "versions.txt";
URL packageURL = new URL(versionsS);
URLConnection conn = getConnection(packageURL);
BufferedReader bi =
new BufferedReader(new InputStreamReader(conn.getInputStream()));
ArrayList<Object> versions = new ArrayList<Object>();
String versionNumber;
while ((versionNumber = bi.readLine()) != null) {
versions.add(versionNumber.trim());
}
bi.close();
return versions;
}
/**
* Get package information on the named package from the repository.
*
* @param packageName the name of the package to get information about.
* @param version the version of the package to retrieve (may be null if not
* applicable).
* @return a Package object encapsulating the package meta data.
* @throws Exception if the package meta data can't be retrieved.
*/
@Override
public Package getRepositoryPackageInfo(String packageName, Object version)
throws Exception {
if (getPackageRepositoryURL() == null) {
throw new Exception("[DefaultPackageManager] No package repository set!!");
}
if (version == null) {
version = "Latest";
}
String packageS =
m_packageRepository.toString() + "/" + packageName + "/"
+ version.toString() + ".props";
URL packageURL = new URL(packageS);
URLConnection conn = getConnection(packageURL);
BufferedInputStream bi = new BufferedInputStream(conn.getInputStream());
Properties packageProperties = new Properties();
packageProperties.load(bi);
bi.close();
return new DefaultPackage(m_packageHome, this, packageProperties);
}
private Package getPackageArchiveInfo(File packageArchive) throws Exception {
return getPackageArchiveInfo(packageArchive.getAbsolutePath());
}
/**
* Get package information from the supplied package archive file.
*
* @param packageArchivePath the path to the package archive file
* @return a Package object encapsulating the package meta data.
* @throws Exception if the package meta data can't be retrieved.
*/
@Override
public Package getPackageArchiveInfo(String packageArchivePath)
throws Exception {
ZipFile zip = new ZipFile(new File(packageArchivePath));
for (Enumeration e = zip.entries(); e.hasMoreElements();) {
ZipEntry entry = (ZipEntry) e.nextElement();
if (entry.getName().endsWith("Description.props")) {
InputStream is = zip.getInputStream(entry);
Properties packageProperties = new Properties();
packageProperties.load(new BufferedInputStream(is));
is.close();
DefaultPackage pkg =
new DefaultPackage(m_packageHome, this, packageProperties);
return pkg;
}
}
throw new Exception("Unable to find Description file in package archive!");
}
/**
* Get package information on the named installed package.
*
* @param packageName the name of the package to get information about.
* @return a Package object encapsulating the package meta data or null if the
* package is not installed.
*
* @throws Exception if the package meta data can't be retrieved.
*/
@Override
public Package getInstalledPackageInfo(String packageName) throws Exception {
File packageDescription =
new File(m_packageHome.getAbsoluteFile() + File.separator + packageName
+ File.separator + "Description.props");
if (!packageDescription.exists()) {
return null;
}
FileInputStream fis = new FileInputStream(packageDescription);
Properties packageProperties = new Properties();
packageProperties.load(fis);
fis.close();
DefaultPackage pkg =
new DefaultPackage(m_packageHome, this, packageProperties);
return pkg;
}
/**
* Checks to see if the package home exists and creates it if necessary.
*
* @return true if the package home exists/was created successfully.
*/
protected boolean establishPackageHome() {
if (m_packageHome == null) {
return false;
}
if (!m_packageHome.exists()) {
// create it for the user
if (!m_packageHome.mkdir()) {
System.err.println("Unable to create packages directory ("
+ m_packageHome.getAbsolutePath() + ")");
return false;
}
}
return true;
}
public static void deleteDir(File dir, PrintStream... progress)
throws Exception {
// get the contents
File[] contents = dir.listFiles();
if (contents.length != 0) {
// process contents
for (File f : contents) {
if (f.isDirectory()) {
deleteDir(f);
} else {
for (PrintStream progres : progress) {
progres
.println("[DefaultPackageManager] removing: " + f.toString());
}
if (!f.delete()) {
System.err.println("[DefaultPackageManager] can't delete file "
+ f.toString());
f.deleteOnExit();
}
}
}
}
// delete this directory
if (!dir.delete()) {
System.err.println("[DefaultPackageManager] can't delete directory "
+ dir.toString());
dir.deleteOnExit();
}
for (PrintStream progres : progress) {
progres.println("[DefaultPackageManager] removing: " + dir.toString());
}
}
/**
* Uninstall a package.
*
* @param packageName the package to uninstall.
* @param progress optional varargs parameter, that, if supplied, is expected
* to contain one or more PrintStream objects to write progress to.
* @throws Exception if the named package could not be removed for some
* reason.
*/
@Override
public void uninstallPackage(String packageName, PrintStream... progress)
throws Exception {
File packageToDel =
new File(m_packageHome.toString() + File.separator + packageName);
if (!packageToDel.exists()) {
throw new Exception("[DefaultPackageManager] Can't remove " + packageName
+ " because it doesn't seem to be installed!");
}
deleteDir(packageToDel, progress);
// invalidate cache
s_installedPackageList = null;
deleteInstalledPackageCacheFile();
}
/**
* Install a package from an archive on the local file system.
*
* @param packageArchivePath the path to the package archive file.
* @param progress optional varargs parameter, that, if supplied, is expected
* to contain one or more PrintStream objects to write progress to.
* @return the name of the package installed
* @throws Exception if the package can't be installed for some reason.
*/
@Override
public String installPackageFromArchive(String packageArchivePath,
PrintStream... progress) throws Exception {
Properties packageProps =
(Properties) getPackageArchiveInfo(packageArchivePath)
.getPackageMetaData();
String packageName = packageProps.getProperty("PackageName");
String additionalLibs = packageProps.getProperty("AdditionalLibs");
String[] additionalLibURLs = null;
if (additionalLibs != null && additionalLibs.length() > 0) {
additionalLibURLs = additionalLibs.split(",");
}
if (packageName == null) {
throw new Exception("Unable to find the name of the package in"
+ " the Description file for " + packageArchivePath);
}
installPackage(packageArchivePath, packageName, progress);
if (additionalLibURLs != null) {
installAdditionalLibs(packageName, additionalLibURLs, progress);
}
return packageName;
}
/**
* Installs additional library jar files (as specified in the AdditionalLibs
* entry in the Description.props file).
*
* @param packageName the name of the package that will receive the downloaded
* libraries into its lib directory
* @param additionalLibURLs an array of urls to the libraries to download
* @param progress for progress reporting
* @throws Exception if a problem occurs
*/
protected void installAdditionalLibs(String packageName,
String[] additionalLibURLs, PrintStream... progress) throws Exception {
if (!establishPackageHome()) {
throw new Exception("Unable to install additional libraries"
+ " because package home (" + m_packageHome.getAbsolutePath()
+ ") can't be established.");
}
for (String libU : additionalLibURLs) {
libU = libU.trim();
if (libU.trim().length() > 0) {
URL libURL = new URL(libU.trim());
File libPath = downloadArchive(libURL, "jar", progress);
String destName = libU.substring(0, libU.lastIndexOf("." + "jar") + 3);
destName = destName.substring(0, destName.lastIndexOf('.'));
destName =
destName.substring(destName.lastIndexOf('/'), destName.length());
destName += ".jar";
File destDir =
new File(m_packageHome, packageName + File.separator + "lib");
if (!destDir.mkdir()) {
// hopefully failure is because the directory already exists
}
File destPath = new File(destDir, destName);
InputStream input =
new BufferedInputStream(new FileInputStream(libPath));
OutputStream output =
new BufferedOutputStream(new FileOutputStream(destPath));
copyStreams(input, output);
input.close();
output.flush();
output.close();
}
}
}
/**
* Installs all the packages in the supplied list.
*
* @param toInstall a list of Packages to install.
* @param progress optional varargs parameter, that, if supplied, is expected
* to contain one or more PrintStream objects to write progress to.
* @throws Exception if something goes wrong during the installation process.
*/
@Override
public void installPackages(List<Package> toInstall, PrintStream... progress)
throws Exception {
File[] archivePaths = new File[toInstall.size()];
for (int i = 0; i < toInstall.size(); i++) {
Package toDownload = toInstall.get(i);
if (toDownload.isInstalled()) {
for (PrintStream p : progress) {
p.println("[DefaultPackageManager] cleaning installed package: "
+ toDownload.getName());
uninstallPackage(toDownload.getName(), progress);
}
}
archivePaths[i] =
downloadArchive(toDownload.getPackageURL(), "zip", progress);
}
// OK, all downloaded successfully, now install them
for (File archivePath : archivePaths) {
installPackageFromArchive(archivePath.getAbsolutePath(), progress);
}
}
/**
* Checks a given package's list of dependencies for any conflicts with the
* packages in the supplied Map. Any packages from this packages dependency
* list that are not in the Map are simply added and checkDependencies is
* called recursively for each.
*
* @param toCheck the package to check.
* @param lookup a Map of package name, Dependency pairs to check against.
* @param conflicts a list of Dependency objects for any conflicts that are
* detected.
* @return true if no conflicts are found.
* @throws Exception if a problem occurs when checking for conflicts.
*/
protected static boolean checkDependencies(PackageConstraint toCheck,
Map<String, Dependency> lookup, Map<String, List<Dependency>> conflicts)
throws Exception {
boolean ok = true;
// get the dependencies for the package to check
List<Dependency> deps = toCheck.getPackage().getDependencies();
for (Dependency p : deps) {
String depName =
p.getTarget().getPackage().getPackageMetaDataElement("PackageName")
.toString();
if (!lookup.containsKey(depName)) {
// just add this package to the lookup
lookup.put(depName, p);
// check its dependencies
ok = checkDependencies(p.getTarget(), lookup, conflicts);
} else {
// we have to see if the version number for this package is compatible
// with the one already in the lookup
Dependency checkAgainst = lookup.get(depName);
PackageConstraint result =
checkAgainst.getTarget().checkConstraint(p.getTarget());
if (result != null) {
checkAgainst.setTarget(result);
lookup.put(depName, checkAgainst);
} else {
// there is a conflict here
List<Dependency> conflictList = conflicts.get(depName);
conflictList.add(p);
ok = false;
}
}
}
return ok;
}
/**
* Gets a full list of packages (encapsulated in Dependency objects) that are
* required by directly and indirectly by the named target package. Also
* builds a Map of any packages that are required by more than one package and
* where there is a conflict of some sort (e.g. multiple conflicting
* versions). The keys of this map are package names (strings), and each
* associated value is a list of Dependency objects.
*
* @param target the package for which a list of dependencies is required.
* @param conflicts will hold any conflicts that are discovered while building
* the full dependency list.
* @return a list of packages that are directly and indirectly required by the
* named target package.
* @throws Exception if a problem occurs while building the dependency list.
*/
@Override
public List<Dependency> getAllDependenciesForPackage(Package target,
Map<String, List<Dependency>> conflicts) throws Exception {
// start with the target package's list of dependencies
List<Dependency> initialList = target.getDependencies();
// load them into a map for quick lookup
Map<String, Dependency> lookup = new HashMap<String, Dependency>();
for (Dependency d : initialList) {
lookup.put(
d.getTarget().getPackage().getPackageMetaDataElement("PackageName")
.toString(), d);
ArrayList<Dependency> deps = new ArrayList<Dependency>();
deps.add(d);
// Pre-load a conficts Map
conflicts.put(
d.getTarget().getPackage().getPackageMetaDataElement("PackageName")
.toString(), deps);
}
// now process each of these to build the full list
for (Dependency d : initialList) {
checkDependencies(d.getTarget(), lookup, conflicts);
}
List<Dependency> fullList = new ArrayList<Dependency>(lookup.values());
// Prune packages from conflicts Map that only have one
// item in their list (i.e. these ones have no conflicts)
ArrayList<String> removeList = new ArrayList<String>();
Iterator<String> keyIt = conflicts.keySet().iterator();
while (keyIt.hasNext()) {
String key = keyIt.next();
List<Dependency> tempD = conflicts.get(key);
if (tempD.size() == 1) {
// remove this one
removeList.add(key);
}
}
for (String s : removeList) {
conflicts.remove(s);
}
return fullList;
}
/**
* Install a package sourced from the repository.
*
* @param packageName the name of the package to install
* @param version the version of the package to install (may be null if not
* applicable).
* @param progress optional varargs parameter, that, if supplied, is expected
* to contain one or more PrintStream objects to write progress to.
* @throws Exception if the package can't be installed for some reason.
*/
@Override
public void installPackageFromRepository(String packageName, Object version,
PrintStream... progress) throws Exception {
Package toInstall = getRepositoryPackageInfo(packageName, version);
if (toInstall.isInstalled()) {
for (PrintStream p : progress) {
p.println("[DefaultPackageManager] cleaning installed package: "
+ toInstall.getName());
uninstallPackage(toInstall.getName(), progress);
}
}
String urlString =
toInstall.getPackageMetaDataElement("PackageURL").toString();
URL packageURL = new URL(urlString);
installPackageFromURL(packageURL, progress);
}
/**
* Install a package sourced from a given URL.
*
* @param packageURL the URL to the package.
* @param progress optional varargs parameter, that, if supplied, is expected
* to contain one or more PrintStream objects to write progress to.
* @return the name of the package installed
* @throws Exception if the package can't be installed for some reason.
*/
@Override
public String installPackageFromURL(URL packageURL, PrintStream... progress)
throws Exception {
File downloaded = downloadArchive(packageURL, "zip", progress);
return installPackageFromArchive(downloaded.getAbsolutePath(), progress);
}
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);
}
}
/**
* Installs a package from a zip/jar archive.
*
* @param packageArchivePath the full path to the archived package to install.
* @param packageName the name of the package to install.
* @param progress optional varargs parameter, that, if supplied, is expected
* to contain one or more PrintStream objects to write progress to.
* @throws Exception if the package can't be installed for some reason.
*/
protected void installPackage(String packageArchivePath, String packageName,
PrintStream... progress) throws Exception {
if (!establishPackageHome()) {
throw new Exception("Unable to install " + packageArchivePath
+ " because package home (" + m_packageHome.getAbsolutePath()
+ ") can't be established.");
}
File destDir = new File(m_packageHome, packageName);
if (!destDir.mkdir()) {
/*
* throw new Exception("Unable to create package directory " +
* destDir.getAbsolutePath());
*/
// hopefully failure is because the directory already exists
}
InputStream input = null;
OutputStream output = null;
ZipFile zipFile = new ZipFile(packageArchivePath);
Enumeration enumeration = zipFile.entries();
while (enumeration.hasMoreElements()) {
ZipEntry zipEntry = (ZipEntry) enumeration.nextElement();
if (zipEntry.isDirectory()) {
new File(destDir, zipEntry.getName()).mkdirs();
continue;
} else {
File temp = new File(destDir, zipEntry.getName()).getParentFile();
if (temp != null && !temp.exists()) {
temp.mkdirs();
}
}
for (PrintStream progres : progress) {
progres.println("[DefaultPackageManager] Installing: "
+ zipEntry.getName());
}
input = new BufferedInputStream(zipFile.getInputStream(zipEntry));
File destFile = new File(destDir, zipEntry.getName());
FileOutputStream fos = new FileOutputStream(destFile);
output = new BufferedOutputStream(fos);
copyStreams(input, output);
input.close();
output.flush();
output.close();
}
// invalidate the cache
s_installedPackageList = null;
deleteInstalledPackageCacheFile();
}
private URLConnection getConnection(String urlString) throws IOException {
URL connURL = new URL(urlString);
return getConnection(connURL);
}
private URLConnection openConnection(URL connURL) throws IOException {
URLConnection conn = null;
// setup the proxy (if we are using one) and open the connect
if (setProxyAuthentication(connURL)) {
conn = connURL.openConnection(m_httpProxy);
} else {
conn = connURL.openConnection();
}
// Set a timeout for establishing the connection
conn.setConnectTimeout(m_timeout);
return conn;
}
private URLConnection getConnection(URL connURL) throws IOException {
URLConnection conn = openConnection(connURL);
if (conn instanceof HttpURLConnection) {
int status = 0;
try {
status = ((HttpURLConnection) conn).getResponseCode();
} catch (Exception ex) {
if (connURL.toString().startsWith("https://")) {
String newURL = connURL.toString().replace("https://", "http://");
conn = openConnection(new URL(newURL));
status = ((HttpURLConnection) conn).getResponseCode();
} else {
throw ex;
}
}
int redirectCount = 0;
while (status == HttpURLConnection.HTTP_MOVED_TEMP
|| status == HttpURLConnection.HTTP_MOVED_PERM
|| status == HttpURLConnection.HTTP_SEE_OTHER) {
redirectCount++;
if (redirectCount > 2) {
throw new IOException(
"Three redirects were generated when trying to " + "download "
+ connURL);
}
String newURL = conn.getHeaderField("Location");
try {
conn = openConnection(new URL(newURL));
status = ((HttpURLConnection) conn).getResponseCode();
} catch (Exception ex) {
if (newURL.startsWith("https://")) {
// try http instead
System.out.println("[DefaultPackageManager] trying http instead "
+ "of https for " + newURL);
newURL = newURL.replace("https://", "http://");
conn = openConnection(new URL(newURL));
status = ((HttpURLConnection) conn).getResponseCode();
} else {
throw ex;
}
}
}
}
return conn;
}
private void transToBAOS(BufferedInputStream bi, ByteArrayOutputStream bos)
throws Exception {
while (true) {
synchronized (m_buffer) {
int amountRead = bi.read(m_buffer);
if (amountRead == -1) {
break;
}
bos.write(m_buffer, 0, amountRead);
}
}
bi.close();
}
private void writeZipEntryForPackage(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");
URLConnection conn =
getConnection(m_packageRepository.toString() + "/" + packageName
+ "/Latest.props");
BufferedInputStream bi = new BufferedInputStream(conn.getInputStream());
ByteArrayOutputStream bos = new ByteArrayOutputStream();
transToBAOS(bi, bos);
zos.putNextEntry(z);
zos.write(bos.toByteArray());
conn =
getConnection(m_packageRepository.toString() + "/" + packageName
+ "/Latest.html");
bi = new BufferedInputStream(conn.getInputStream());
bos = new ByteArrayOutputStream();
transToBAOS(bi, bos);
zos.putNextEntry(z2);
zos.write(bos.toByteArray());
// write the versions.txt file to the zip
z = new ZipEntry(packageName + "/versions.txt");
conn =
getConnection(m_packageRepository.toString() + "/" + packageName
+ "/versions.txt");
bi = new BufferedInputStream(conn.getInputStream());
bos = new ByteArrayOutputStream();
transToBAOS(bi, bos);
zos.putNextEntry(z);
zos.write(bos.toByteArray());
// write the index.html to the zip
z = new ZipEntry(packageName + "/index.html");
conn =
getConnection(m_packageRepository.toString() + "/" + packageName
+ "/index.html");
bi = new BufferedInputStream(conn.getInputStream());
bos = new ByteArrayOutputStream();
transToBAOS(bi, bos);
zos.putNextEntry(z);
zos.write(bos.toByteArray());
// Now process the available versions
List<Object> versions = getRepositoryPackageVersions(packageName);
for (Object o : versions) {
conn =
getConnection(m_packageRepository.toString() + "/" + packageName + "/"
+ o.toString() + ".props");
z = new ZipEntry(packageName + "/" + o.toString() + ".props");
bi = new BufferedInputStream(conn.getInputStream());
bos = new ByteArrayOutputStream();
transToBAOS(bi, bos);
zos.putNextEntry(z);
zos.write(bos.toByteArray());
conn =
getConnection(m_packageRepository.toString() + "/" + packageName + "/"
+ o.toString() + ".html");
z = new ZipEntry(packageName + "/" + o.toString() + ".html");
bi = new BufferedInputStream(conn.getInputStream());
bos = new ByteArrayOutputStream();
transToBAOS(bi, bos);
zos.putNextEntry(z);
zos.write(bos.toByteArray());
}
}
/**
* Gets an array of bytes containing a zip of all the repository meta data and
* supporting files. Does *not* contain any package archives etc., only a
* snapshot of the meta data. Could be used by clients to establish a cache of
* meta data.
*
* @return a zip compressed array of bytes.
*/
@Override
public byte[] getRepositoryPackageMetaDataOnlyAsZip(PrintStream... progress)
throws Exception {
if (getPackageRepositoryURL() == null) {
throw new Exception("[DefaultPackageManager] No package repository set!!");
}
try {
String repoZip = m_packageRepository.toString() + "/repo.zip";
URLConnection conn = null;
conn = getConnection(repoZip);
BufferedInputStream bi = new BufferedInputStream(conn.getInputStream());
ByteArrayOutputStream bos = new ByteArrayOutputStream();
// ZipOutputStream zos = new ZipOutputStream(bos);
int totalBytesRead = 0;
while (true) {
synchronized (m_buffer) {
int amountRead = bi.read(m_buffer);
if (amountRead == -1) {
for (PrintStream progres : progress) {
progres.println("[DefaultPackageManager] downloaded "
+ (totalBytesRead / 1000) + " KB\r");
}
break;
}
bos.write(m_buffer, 0, amountRead);
totalBytesRead += amountRead;
for (PrintStream progres : progress) {
progres.print("[DefaultPackageManager] downloaded "
+ (totalBytesRead / 1000) + " KB\r");
}
}
}
bi.close();
return bos.toByteArray();
} catch (Exception ex) {
System.err.println("Unable to download repository zip archve " + "("
+ ex.getMessage() + ") - trying legacy routine...");
return getRepositoryPackageMetaDataOnlyAsZipLegacy(progress);
}
}
/**
* Gets an array of bytes containing a zip of all the repository meta data and
* supporting files using the legacy approach. Does *not* contain any package
* archives etc., only a snapshot of the meta data. Could be used by clients
* to establish a cache of meta data.
*
* @return a zip compressed array of bytes.
*/
public byte[] getRepositoryPackageMetaDataOnlyAsZipLegacy(
PrintStream... progress) throws Exception {
if (getPackageRepositoryURL() == null) {
throw new Exception("[DefaultPackageManager] No package repository set!!");
}
String packageList = m_packageRepository.toString() + "/packageList.txt";
String packageListWithVersion =
m_packageRepository.toString() + "/packageListWithVersion.txt";
URLConnection conn = null;
conn = getConnection(packageList);
BufferedReader bi =
new BufferedReader(new InputStreamReader(conn.getInputStream()));
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(bos);
// Process the packages
String packageName;
while ((packageName = bi.readLine()) != null) {
for (PrintStream p : progress) {
p.println("Fetching meta data for " + packageName);
}
writeZipEntryForPackage(packageName, zos);
}
bi.close();
// include the package list (legacy) in the zip
conn = getConnection(packageList);
ZipEntry z = new ZipEntry("packageList.txt");
BufferedInputStream bi2 = new BufferedInputStream(conn.getInputStream());
ByteArrayOutputStream bos2 = new ByteArrayOutputStream();
transToBAOS(bi2, bos2);
zos.putNextEntry(z);
zos.write(bos2.toByteArray());
bi2.close();
// include the package list with latest version numbers
conn = getConnection(packageListWithVersion);
z = new ZipEntry("packageListWithVersion.txt");
bi2 = new BufferedInputStream(conn.getInputStream());
bos2 = new ByteArrayOutputStream();
transToBAOS(bi2, bos2);
zos.putNextEntry(z);
zos.write(bos2.toByteArray());
bi2.close();
// Include the top level images
String imageList = m_packageRepository.toString() + "/images.txt";
conn = getConnection(imageList);
bi = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String imageName;
while ((imageName = bi.readLine()) != null) {
// System.err.println("Processing " + imageName);
z = new ZipEntry(imageName);
URLConnection conn2 =
getConnection(m_packageRepository.toString() + "/" + imageName);
bi2 = new BufferedInputStream(conn2.getInputStream());
bos2 = new ByteArrayOutputStream();
transToBAOS(bi2, bos2);
zos.putNextEntry(z);
zos.write(bos2.toByteArray());
bi2.close();
}
// include the image list in the zip
conn = getConnection(imageList);
z = new ZipEntry("images.txt");
bi2 = new BufferedInputStream(conn.getInputStream());
bos2 = new ByteArrayOutputStream();
transToBAOS(bi2, bos2);
zos.putNextEntry(z);
zos.write(bos2.toByteArray());
bi2.close();
zos.close();
return bos.toByteArray();
}
/**
* Get all packages that the system knows about (i.e. all packages contained
* in the repository).
*
* @param progress optional varargs parameter, that, if supplied is expected
* to contain one or more PrintStream objects to write progress to.
* @return a list of all packages.
* @throws Exception if a list of packages can't be determined.
*/
@Override
public List<Package> getAllPackages(PrintStream... progress) throws Exception {
ArrayList<Package> allPackages = new ArrayList<Package>();
if (getPackageRepositoryURL() == null) {
throw new Exception("[DefaultPackageManager] No package repository set!!");
}
String packageList = m_packageRepository.toString() + "/packageList.txt";
URL packageListURL = new URL(packageList);
URLConnection conn = getConnection(packageListURL);
BufferedReader bi =
new BufferedReader(new InputStreamReader(conn.getInputStream()));
String packageName;
while ((packageName = bi.readLine()) != null) {
Package temp = getRepositoryPackageInfo(packageName);
allPackages.add(temp);
}
return allPackages;
}
/**
* Get a list of packages that are not currently installed.
*
* @return a list of packages that are not currently installed.
* @throws Exception if a list of packages can't be determined.
*/
@Override
public List<Package> getAvailablePackages() throws Exception {
List<Package> allP = getAllPackages();
List<Package> available = new ArrayList<Package>();
for (int i = 0; i < allP.size(); i++) {
if (!allP.get(i).isInstalled()) {
available.add(allP.get(i));
}
}
return available;
}
/**
* Get a list of installed packages.
*
* @return a list of installed packages.
* @throws Exception if a list of packages can't be determined.
*/
@Override
public List<Package> getInstalledPackages() throws Exception {
if (!establishPackageHome()) {
throw new Exception("Unable to get list of installed packages "
+ "because package home (" + m_packageHome.getAbsolutePath()
+ ") can't be established.");
}
if (s_installedPackageList != null) {
return s_installedPackageList;
}
s_installedPackageList = loadInstalledPackageCache();
if (s_installedPackageList != null) {
return s_installedPackageList;
}
List<Package> installedP = new ArrayList<Package>();
File[] contents = m_packageHome.listFiles();
for (File content : contents) {
if (content.isDirectory()) {
File description =
new File(content.getAbsolutePath() + File.separator
+ "Description.props");
if (description.exists()) {
try {
Properties packageProperties = new Properties();
BufferedInputStream bi =
new BufferedInputStream(new FileInputStream(description));
packageProperties.load(bi);
bi.close();
bi = null;
DefaultPackage pkg =
new DefaultPackage(m_packageHome, this, packageProperties);
installedP.add(pkg);
} catch (Exception ex) {
// ignore if we can't load the description file for some reason
}
}
}
}
s_installedPackageList = installedP;
saveInstalledPackageCache(installedP);
return installedP;
}
protected void deleteInstalledPackageCacheFile() throws Exception {
if (!establishPackageHome()) {
throw new Exception("Unable to delete installed package cache file "
+ "because package home (" + m_packageHome.getAbsolutePath()
+ ") can't be established.");
}
File cache = new File(m_packageHome, INSTALLED_PACKAGE_CACHE_FILE);
if (cache.exists()) {
if (!cache.delete()) {
System.err.println("Unable to delete installed package cache file '"
+ cache.toString() + "'");
cache.deleteOnExit();
}
}
}
/**
* Save the supplied list of Packages to the installed package cache file
*
* @param cacheToSave the list of packages to save
* @throws Exception if a problem occurs
*/
protected void saveInstalledPackageCache(List<Package> cacheToSave)
throws Exception {
if (!establishPackageHome()) {
throw new Exception("Unable to save installed package cache file "
+ "because package home (" + m_packageHome.getAbsolutePath()
+ ") can't be established.");
}
ObjectOutputStream oos = null;
try {
oos =
new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(
new File(m_packageHome, INSTALLED_PACKAGE_CACHE_FILE))));
oos.writeObject(cacheToSave);
oos.flush();
} finally {
if (oos != null) {
oos.close();
}
}
}
/**
* Load the serialized installed package cache file
*
* @return a list of installed packages (loaded from the cache file)
* @throws Exception if a problem occurs
*/
protected List<Package> loadInstalledPackageCache() throws Exception {
if (!establishPackageHome()) {
throw new Exception("Unable to load installed package cache file "
+ "because package home (" + m_packageHome.getAbsolutePath()
+ ") can't be established.");
}
List<Package> installedP = null;
if (new File(m_packageHome, INSTALLED_PACKAGE_CACHE_FILE).exists()) {
ObjectInputStream ois = null;
try {
ois =
new ObjectInputStream(new BufferedInputStream(new FileInputStream(
new File(m_packageHome.toString(), INSTALLED_PACKAGE_CACHE_FILE))));
installedP = (List) ois.readObject();
} catch (Exception ex) {
deleteInstalledPackageCacheFile();
} finally {
if (ois != null) {
ois.close();
}
}
}
if (installedP != null) {
for (Package p : installedP) {
if (p instanceof DefaultPackage) {
((DefaultPackage) p).setPackageManager(this);
}
}
}
return installedP;
}
/**
* 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
*/
protected static String padLeft(String inString, int length) {
return fixStringLength(inString, length, false);
}
/**
* 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
*/
protected static String padRight(String inString, int length) {
return fixStringLength(inString, length, true);
}
/**
* Pads a string to a specified length, inserting spaces 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
* @param right true if inserted spaces should be added to the right
* @return the output string
*/
private static/* @pure@ */String fixStringLength(String inString, int length,
boolean right) {
if (inString.length() < length) {
while (inString.length() < length) {
inString = (right ? inString.concat(" ") : " ".concat(inString));
}
} else if (inString.length() > length) {
inString = inString.substring(0, length);
}
return inString;
}
/*
* public void printPackageInfo(String packagePath) throws Exception {
* Properties packageProps = (Properties)getPackageArchiveInfo(packagePath);
* Enumeration<?> e = packageProps.propertyNames(); while
* (e.hasMoreElements()) { String key = (String) e.nextElement(); String value
* = packageProps.getProperty(key); System.out.println(padLeft(key, 11) +
* ":\t" + value); } }
*/
public static void main(String[] args) {
try {
URL url = new URL(args[0]);
DefaultPackageManager pm = new DefaultPackageManager();
pm.downloadArchive(url, args[1], System.out);
} 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/packageManagement/Dependency.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/>.
*/
/*
* Dependency.java
* Copyright (C) 2015 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.packageManagement;
/**
* Class that encapsulates a dependency between two packages
*
* @author mhall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision: 44030 $
*/
public class Dependency {
/** The source package */
protected Package m_sourcePackage;
/** The target package (wrapped in a PackageConstraint) */
protected PackageConstraint m_targetPackage;
/**
* Construct a new Dependency from a supplied source package and
* PackageConstraint containing the target package.
*
* @param source the source package.
* @param target the target package (wrapped in a PackageConstraint).
*/
public Dependency(Package source, PackageConstraint target) {
m_sourcePackage = source;
m_targetPackage = target;
}
/**
* Set the source package.
*
* @param source the source package.
*/
public void setSource(Package source) {
m_sourcePackage = source;
}
/**
* Get the source package.
*
* @return the source package.
*/
public Package getSource() {
return m_sourcePackage;
}
/**
* Set the target package constraint.
*
* @param target the target package (wrapped in a PackageConstraint).
*/
public void setTarget(PackageConstraint target) {
m_targetPackage = target;
}
/**
* Get the target package constraint.
*
* @return the target package (wrapped in a PackageConstraint).
*/
public PackageConstraint getTarget() {
return m_targetPackage;
}
public String toString() {
return m_sourcePackage.toString() + " --> " + m_targetPackage.toString();
}
}
|
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/packageManagement/Package.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/>.
*/
/*
* Package.java
* Copyright (C) 2015 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.packageManagement;
import java.io.Serializable;
import java.net.URL;
import java.util.List;
import java.util.Map;
/**
* Abstract base class for Packages.
*
* @author mhall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision: 52462 $
*
*/
public abstract class Package implements Cloneable, Serializable {
/**
* For serialization
*/
private static final long serialVersionUID = -8193697646938632764L;
/**
* The meta data for the package
*/
protected Map<?, ?> m_packageMetaData;
/**
* Set the meta data for this package.
*
* @param metaData the meta data for this package.
*/
public void setPackageMetaData(Map<?, ?> metaData) {
m_packageMetaData = metaData;
}
/**
* Get the meta data for this package.
*
* @return the meta data for this package
*/
public Map<?, ?> getPackageMetaData() {
return m_packageMetaData;
}
/**
* Convenience method to return the name of this package.
*
* @return the name of this package.
*/
public abstract String getName();
/**
* Convenience method that returns the URL to the package (i.e the provider's
* URL). This information is assumed to be stored in the package meta data.
*
* @return the URL to the package or null if the URL is not available for some
* reason
* @throws Exception if the URL can't be retrieved for some reason
*/
public abstract URL getPackageURL() throws Exception;
/**
* Compare the supplied package to this package. Simply does an equals()
* comparison between the two. Concrete subclasses should override if they
* wan't to do comparison based on specific package meta data elements.
*
* @param toCompare the package to compare against.
* @return true if the supplied package is equal to this one.
*/
public boolean equals(Package toCompare) {
return m_packageMetaData.equals(toCompare.getPackageMetaData());
}
/**
* Get the list of packages that this package depends on.
*
* @return the list of packages that this package depends on.
* @throws Exception if a problem occurs while getting the list of
* dependencies.
*/
public abstract List<Dependency> getDependencies() throws Exception;
/**
* Returns true if this package is already installed
*
* @return true if this package is installed
*/
public abstract boolean isInstalled();
/**
* Install this package.
*
* @throws Exception if something goes wrong during installation.
*/
public abstract void install() throws Exception;
/**
* Returns true if this package is compatible with the currently installed
* version of the base system.
*
* @return true if this package is compatible with the main software system.
* @throws Exception if a problem occurs while checking compatibility.
*/
public abstract boolean isCompatibleBaseSystem() throws Exception;
/**
* Returns true if this package is good to go with the current version of the
* software and versions of any installed packages that it depends on.
*
* @return true if this package is good to go.
* @throws Exception if a problem occurs while checking compatibility.
*/
/*
* public abstract boolean isCompatible() throws Exception;
*/
/**
* Gets the dependency on the base system that this package requires.
*
* @return the base system dependency(s) for this package
* @throws Exception if the base system dependency can't be determined for
* some reason.
*/
public abstract List<Dependency> getBaseSystemDependency() throws Exception;
/**
* Gets a list of packages that this package depends on that are not currently
* installed.
*
* @return a list of missing packages that this package depends on.
*/
public abstract List<Dependency> getMissingDependencies() throws Exception;
/**
* Gets a list of packages that this package depends on that are not in the
* supplied list of packages.
*
* @param packages a list of packages to compare this package's dependencies
* against.
* @return those packages that this package depends on that aren't in the
* supplied list.
* @throws Exception if the list of missing depenencies can't be determined
* for some reason.
*/
public abstract List<Dependency>
getMissingDependencies(List<Package> packages) throws Exception;
/**
* Gets a list of installed packages that this package depends on that are
* currently incompatible with this package.
*
* @return a list of incompatible installed packages that this package depends
* on.
*/
public abstract List<Dependency> getIncompatibleDependencies()
throws Exception;
/**
* Compares this package's precluded list (if any) against the list of
* supplied packages. Any packages in the supplied list that match (by name
* and version constraints) any in the precluded list are returned
*
* @param packages a list of packages to compare against those in this
* package's precluded list
* @return a list of packages that are covered by those in the precluded list
* @throws Exception if a problem occurs
*/
public abstract List<Package> getPrecludedPackages(List<Package> packages)
throws Exception;
/**
* Gets those packages from the supplied list that this package depends on and
* are currently incompatible with this package.
*
* @param packages a list of packages to compare this package's dependencies
* against
* @return those packages from the supplied list that are incompatible with
* respect to this package's dependencies
* @throws Exception if the list of incompatible dependencies can't be
* generated for some reason.
*/
public abstract List<Dependency> getIncompatibleDependencies(
List<Package> packages) throws Exception;
/**
* Gets the package meta data element associated with the supplied key.
*
* @param key the key to use to look up a value in the meta data
* @return the meta data value or null if the key does not exist.
*/
public Object getPackageMetaDataElement(Object key) {
if (m_packageMetaData == null) {
return null;
}
return m_packageMetaData.get(key);
}
/**
* Adds a key, value pair to the meta data map.
*
* @param key the key
* @param value the value to add
* @throws Exception if there is no meta data map to add to.
*/
public abstract void setPackageMetaDataElement(Object key, Object value)
throws Exception;
@Override
public abstract Object clone();
}
|
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/packageManagement/PackageConstraint.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/>.
*/
/*
* PackageConstraint.java
* Copyright (C) 2015 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.packageManagement;
/**
* Abstract base class for package constraints. An example implementation
* might be to encapsulate a constraint with respect to a version
* number. Checking against a target in this case would
* typically assume the same package for both this and the target.
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision: 44030 $
*/
public abstract class PackageConstraint {
protected Package m_thePackage;
/**
* Set the package that this constraint applies to.
*
* @param p the package that this constraint applies to.
*/
public void setPackage(Package p) {
m_thePackage = p;
}
/**
* Get the package that this constraint applies to.
*
* @return the Package that this constraint applies to.
*/
public Package getPackage() {
return m_thePackage;
}
/**
* Check the target package against the constraint embodied
* in this PackageConstraint.
*
* @param target a package to check with respect to the
* encapsulated package and the constraint.
*
* @return true if the constraint is met by the target package
* with respect to the encapsulated package + constraint.
* @throws Exception if the constraint can't be checked for some
* reason.
*/
public abstract boolean checkConstraint(Package target) throws Exception;
/**
* Check the target package constraint against the constraint embodied
* in this package constraint. Returns either the package constraint that
* covers both this and the target constraint, or null if this and the target
* are incompatible.
*
* @param target the package constraint to compare against
* @return a package constraint that covers this and the supplied constraint,
* or null if they are incompatible.
*/
public abstract PackageConstraint checkConstraint(PackageConstraint target)
throws Exception;
}
|
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/packageManagement/PackageManager.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/>.
*/
/*
* PackageManager.java
* Copyright (C) 2015 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.packageManagement;
import weka.core.Defaults;
import weka.core.Settings;
import java.awt.GraphicsEnvironment;
import java.beans.Beans;
import java.io.File;
import java.io.FileInputStream;
import java.io.PrintStream;
import java.net.Authenticator;
import java.net.InetSocketAddress;
import java.net.PasswordAuthentication;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.Properties;
/**
* Abstract base class for package managers. Contains methods to manage the
* location of the central package repository, the home directory for installing
* packages, the name and version of the base software system and a http proxy.
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision: 52568 $
*/
public abstract class PackageManager {
public static PackageManager create() {
PackageManager pm = new DefaultPackageManager();
pm.establishProxy();
try {
// See if org.pentaho.packageManagement.manager has been set
String managerName =
System.getProperty("org.pentaho.packageManagement.manager");
if (managerName != null && managerName.length() > 0) {
Object manager =
Beans.instantiate(pm.getClass().getClassLoader(), managerName);
if (manager instanceof PackageManager) {
pm = (PackageManager) manager;
}
} else {
// See if there is a named package manager specified in
// $HOME/PackageManager.props
// that we should try to instantiate
File packageManagerPropsFile = new File(System.getProperty("user.home")
+ File.separator + "PackageManager.props");
if (packageManagerPropsFile.exists()) {
Properties pmProps = new Properties();
pmProps.load(new FileInputStream(packageManagerPropsFile));
managerName =
pmProps.getProperty("org.pentaho.packageManager.manager");
if (managerName != null && managerName.length() > 0) {
Object manager =
Beans.instantiate(pm.getClass().getClassLoader(), managerName);
if (manager instanceof PackageManager) {
pm = (PackageManager) manager;
}
}
}
}
} catch (Exception ex) {
// ignore any problems and just return the default package manager
System.err.println(
"Problem instantiating package manager. Using DefaultPackageManager.");
}
return pm;
}
/** The local directory for storing the user's installed packages */
protected File m_packageHome;
/** The URL to the global package meta data repository */
protected URL m_packageRepository;
/** The name of the base system being managed by this package manager */
protected String m_baseSystemName;
/** The version of the base system being managed by this package manager */
protected Object m_baseSystemVersion;
/** Proxy for http connections */
protected transient Proxy m_httpProxy;
/** The user name for the proxy */
protected transient String m_proxyUsername;
/** The password for the proxy */
protected transient String m_proxyPassword;
/** True if an authenticator has been set */
protected transient boolean m_authenticatorSet;
/**
* Tries to configure a Proxy object for use in an Authenticator if there is a
* proxy defined by the properties http.proxyHost and http.proxyPort, and if
* the user has set values for the properties (note, these are not standard
* java properties) http.proxyUser and http.proxyPassword.
*
*/
public void establishProxy() {
// pick up system-wide proxy if possible
// String useSystemProxies = System.getProperty(
// "weka.packageManager.useSystemProxies", "true");
//
// if (useSystemProxies.toLowerCase().equals("true")) {
// System.setProperty("java.net.useSystemProxies", "true");
// }
// check for user-supplied proxy properties
String proxyHost = System.getProperty("http.proxyHost");
String proxyPort = System.getProperty("http.proxyPort");
if (proxyHost != null && proxyHost.length() > 0) {
int portNum = 80;
if (proxyPort != null && proxyPort.length() > 0) {
portNum = Integer.parseInt(proxyPort);
}
InetSocketAddress sa = new InetSocketAddress(proxyHost, portNum);
setProxy(new Proxy(Proxy.Type.HTTP, sa));
}
// check for authentication
String proxyUserName = System.getProperty("http.proxyUser");
String proxyPassword = System.getProperty("http.proxyPassword");
if (proxyUserName != null && proxyUserName.length() > 0
&& proxyPassword != null && proxyPassword.length() > 0) {
setProxyUsername(proxyUserName);
setProxyPassword(proxyPassword);
}
}
/**
* Sets an new default Authenticator that will return the values set through
* setProxyUsername() and setProxyPassword() (if applicable).
*
* @return true if a proxy is to be used and (if applicable) the Authenticator
* was set successfully.
*/
public synchronized boolean setProxyAuthentication(URL urlToConnectTo) {
if (m_httpProxy == null) {
// try the proxy selector to see if we can get a system-wide one
ProxySelector ps = ProxySelector.getDefault();
List<Proxy> proxyList;
try {
proxyList = ps.select(urlToConnectTo.toURI());
Proxy proxy = proxyList.get(0);
setProxy(proxy);
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
if (m_httpProxy != null) {
if (m_proxyUsername != null && m_proxyPassword != null
&& !m_authenticatorSet) {
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(m_proxyUsername,
m_proxyPassword.toCharArray());
}
});
} else {
if (!m_authenticatorSet && !GraphicsEnvironment.isHeadless()) {
Authenticator
.setDefault(new org.bounce.net.DefaultAuthenticator(null));
m_authenticatorSet = true;
}
}
return true;
}
if (m_httpProxy != null) {
return true;
}
return false;
}
/**
* Set the location (directory) of installed packages.
*
* @param packageHome the file system location of installed packages.
*/
public void setPackageHome(File packageHome) {
m_packageHome = packageHome;
}
/**
* Get the location (directory) of installed packages
*
* @return the directory containing installed packages.
*/
public File getPackageHome() {
return m_packageHome;
}
/**
* Set the name of the main software system for which we manage packages.
*
* @param baseS the name of the base software system
*/
public void setBaseSystemName(String baseS) {
m_baseSystemName = baseS;
}
/**
* Get the name of the main software system for which we manage packages.
*
* @return the name of the base software system.
*/
public String getBaseSystemName() {
return m_baseSystemName;
}
/**
* Set the current version of the base system for which we manage packages.
*
* @param systemV the current version of the main software system.
*/
public void setBaseSystemVersion(Object systemV) {
m_baseSystemVersion = systemV;
}
/**
* Get the current installed version of the main system for which we manage
* packages.
*
* @return the installed version of the base system.
*/
public Object getBaseSystemVersion() {
return m_baseSystemVersion;
}
/**
* Set the URL to the repository of package meta data.
*
* @param repositoryURL the URL to the repository of package meta data.
*/
public void setPackageRepositoryURL(URL repositoryURL) {
m_packageRepository = repositoryURL;
}
/**
* Get the URL to the repository of package meta data.
*
* @return the URL to the repository of package meta data.
*/
public URL getPackageRepositoryURL() {
return m_packageRepository;
}
/**
* Set a proxy to use for accessing the internet (default is no proxy).
*
* @param proxyToUse a proxy to use.
*/
public void setProxy(Proxy proxyToUse) {
m_httpProxy = proxyToUse;
}
/**
* Get the proxy in use.
*
* @return the proxy in use or null if no proxy is being used.
*/
public Proxy getProxy() {
return m_httpProxy;
}
/**
* Set the user name for authentication with the proxy.
*
* @param proxyUsername the user name to use for proxy authentication.
*/
public void setProxyUsername(String proxyUsername) {
m_proxyUsername = proxyUsername;
}
/**
* Set the password for authentication with the proxy.
*
* @param proxyPassword the password to use for proxy authentication.
*/
public void setProxyPassword(String proxyPassword) {
m_proxyPassword = proxyPassword;
}
/**
* Get the default settings of this package manager. Default implementation
* returns null. Subclasses to override if they have default settings
*
* @return the default settings of this package manager
*/
public Defaults getDefaultSettings() {
return null;
}
/**
* Apply the supplied settings. Default implementation does nothing.
* Subclasses should override to take note of settings changes.
*
* @param settings the settings to apply
*/
public void applySettings(Settings settings) {
}
/**
* Gets an array of bytes containing a zip of all the repository meta data and
* supporting files. Does *not* contain any package archives etc., only a
* snapshot of the meta data. Could be used by clients to establish a cache of
* meta data.
*
* @param progress optional varargs parameter, that, if supplied, is expected
* to contain one or more PrintStream objects to write progress to.
* @return a zip compressed array of bytes.
* @throws Exception if the repository meta data can't be returned as a zip
*/
public abstract byte[] getRepositoryPackageMetaDataOnlyAsZip(
PrintStream... progress) throws Exception;
/**
* Get package information from the supplied package archive file.
*
* @param packageArchivePath the path to the package archive file
* @return a Package object encapsulating the package meta data.
* @throws Exception if the package meta data can't be retrieved.
*/
public abstract Package getPackageArchiveInfo(String packageArchivePath)
throws Exception;
/**
* Get package information on the named installed package.
*
* @param packageName the name of the package to get information about.
* @return a Package object encapsulating the package meta data or null if the
* package is not installed.
*
* @throws Exception if the package meta data can't be retrieved.
*/
public abstract Package getInstalledPackageInfo(String packageName)
throws Exception;
/**
* Get package information on the named package from the repository. If
* multiple versions of the package are available, it assumes that the most
* recent is required.
*
* @param packageName the name of the package to get information about.
* @return a Package object encapsulating the package meta data.
* @throws Exception if the package meta data can't be retrieved.
*/
public abstract Package getRepositoryPackageInfo(String packageName)
throws Exception;
/**
* Get package information on the named package from the repository.
*
* @param packageName the name of the package to get information about.
* @param version the version of the package to retrieve (may be null if not
* applicable).
* @return a Package object encapsulating the package meta data.
* @throws Exception if the package meta data can't be retrieved.
*/
public abstract Package getRepositoryPackageInfo(String packageName,
Object version) throws Exception;
/**
* Get a list of available versions of the named package.
*
* @param packageName the name of the package to get versions.
* @return a list of available versions (or null if not applicable)
* @throws Exception if something goes wrong while trying to retrieve the list
* of versions.
*/
public abstract List<Object> getRepositoryPackageVersions(String packageName)
throws Exception;
/**
* Get package information on the package at the given URL.
*
* @param packageURL the URL to the package.
* @return a Package object encapsulating the package meta data
* @throws Exception if the package meta data can't be retrieved.
*/
public abstract Package getURLPackageInfo(URL packageURL) throws Exception;
/**
* Install a package from an archive on the local file system.
*
* @param packageArchivePath the path to the package archive file.
* @param progress optional varargs parameter, that, if supplied, is expected
* to contain one or more PrintStream objects to write progress to.
* @return the name of the package installed
* @throws Exception if the package can't be installed for some reason.
*/
public abstract String installPackageFromArchive(String packageArchivePath,
PrintStream... progress) throws Exception;
/**
* Install a package sourced from the repository.
*
* @param packageName the name of the package to install
* @param version the version of the package to install (may be null if not
* applicable).
* @param progress optional varargs parameter, that, if supplied, is expected
* to contain one or more PrintStream objects to write progress to.
* @throws Exception if the package can't be installed for some reason.
*/
public abstract void installPackageFromRepository(String packageName,
Object version, PrintStream... progress) throws Exception;
/**
* Install a package sourced from a given URL.
*
* @param packageURL the URL to the package.
* @param progress optional varargs parameter, that, if supplied, is expected
* to contain one or more PrintStream objects to write progress to.
* @return the name of the package installed
* @throws Exception if the package can't be installed for some reason.
*/
public abstract String installPackageFromURL(URL packageURL,
PrintStream... progress) throws Exception;
/**
* Installs all the packages in the supplied list.
*
* @param toInstall a list of Packages to install.
* @param progress optional varargs parameter, that, if supplied, is expected
* to contain one or more PrintStream objects to write progress to.
* @throws Exception if something goes wrong during the installation process.
*/
public abstract void installPackages(List<Package> toInstall,
PrintStream... progress) throws Exception;
/**
* Uninstall a package.
*
* @param packageName the package to uninstall.
* @param progress optional varargs parameter, that, if supplied, is expected
* to contain one or more PrintStream objects to write progress to.
* @throws Exception if the named package could not be removed for some
* reason.
*/
public abstract void uninstallPackage(String packageName,
PrintStream... progress) throws Exception;
/**
* Get a list of installed packages.
*
* @return a list of installed packages.
* @throws Exception if a list of packages can't be determined.
*/
public abstract List<Package> getInstalledPackages() throws Exception;
/**
* Get all packages that the system knows about (i.e. all packages contained
* in the repository).
*
* @param progress optional varargs parameter, that, if supplied is expected
* to contain one or more PrintStream objects to write progress to.
* @return a list of all packages.
* @throws Exception if a list of packages can't be determined.
*/
public abstract List<Package> getAllPackages(PrintStream... progress)
throws Exception;
/**
* Get a list of packages that are not currently installed.
*
* @return a list of packages that are not currently installed.
* @throws Exception if a list of packages can't be determined.
*/
public abstract List<Package> getAvailablePackages() throws Exception;
/**
* Gets a full list of packages (encapsulated in Dependency objects) that are
* required by directly and indirectly by the named target package. Also
* builds a Map of any packages that are required by more than one package and
* where there is a conflict of some sort (e.g. multiple conflicting
* versions). The keys of this map are package names (strings), and each
* associated value is a list of Dependency objects.
*
* @param target the package for which a list of dependencies is required.
* @param conflicts will hold any conflicts that are discovered while building
* the full dependency list.
* @return a list of packages that are directly and indirectly required by the
* named target package.
* @throws Exception if a problem occurs while building the dependency list.
*/
public abstract List<Dependency> getAllDependenciesForPackage(Package target,
Map<String, List<Dependency>> conflicts) throws Exception;
}
|
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/packageManagement/VersionPackageConstraint.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/>.
*/
/*
* VersionPackageConstraint.java
* Copyright (C) 2015 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.packageManagement;
/**
* Concrete implementation of PackageConstraint that encapsulates constraints
* related to version numbers. Handles equality = and open-ended inequalities
* (e.g. > x, < x, >= x, <= x).
*
* @author mhall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision: 51469 $
*/
public class VersionPackageConstraint extends PackageConstraint {
/** The meta data key for the version number */
public static String VERSION_KEY = "Version";
/** Enumeration encapsulating version comparison operations */
public enum VersionComparison {
EQUAL("=") {
@Override
boolean compatibleWith(VersionComparison v) {
if (v == VersionComparison.EQUAL) {
return true;
}
return false;
}
},
GREATERTHAN(">") {
@Override
boolean compatibleWith(VersionComparison v) {
if (v == VersionComparison.GREATERTHAN) {
return true;
}
return false;
}
},
GREATERTHANOREQUAL(">=") {
@Override
boolean compatibleWith(VersionComparison v) {
if (v == VersionComparison.LESSTHAN
|| v == VersionComparison.LESSTHANOREQUAL) {
return false;
}
return true;
}
},
LESSTHAN("<") {
@Override
boolean compatibleWith(VersionComparison v) {
if (v == VersionComparison.LESSTHAN) {
return true;
}
return false;
}
},
LESSTHANOREQUAL("<=") {
@Override
boolean compatibleWith(VersionComparison v) {
if (v == VersionComparison.GREATERTHAN
|| v == VersionComparison.GREATERTHANOREQUAL) {
return false;
}
return true;
}
};
private final String m_stringVal;
VersionComparison(String name) {
m_stringVal = name;
}
abstract boolean compatibleWith(VersionComparison v);
@Override
public String toString() {
return m_stringVal;
}
}
/** The comparison operator for this constraint */
protected VersionComparison m_constraint = null;
/**
* Returns a VersionComparison equivalent to the supplied String operator.
*
* @param compOpp the comparison operator as a string.
* @return a VersionComparison object.
*/
protected static VersionComparison getVersionComparison(String compOpp) {
for (VersionComparison v : VersionComparison.values()) {
if (v.toString().equalsIgnoreCase(compOpp)) {
return v;
}
}
return null;
}
/**
* Parses a version number and returns major, minor and revision numbers in an
* array of integers.
*
* @param version the version number as a string.
* @return an array of integers containing the major, minor and revision
* numbers.
*/
protected static int[] parseVersion(String version) {
int major = 0;
int minor = 0;
int revision = 0;
int point = 0;
int[] majMinRev = new int[4];
try {
String tmpStr = version;
tmpStr = tmpStr.toLowerCase().replace("-snapshot", "");
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("")) {
point = Integer.parseInt(tmpStr);
} else {
point = 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 {
majMinRev[0] = major;
majMinRev[1] = minor;
majMinRev[2] = revision;
}
return majMinRev;
}
/**
* Evaluates the supplied constraint with respect to two supplied version
* numbers as strings.
*
* @param version1 String containing version number 1
* @param constraint the constraint comparison to use
* @param version2 String containing version number 2
* @return true if version 1 is compatible with version two with respect to
* the constraint.
*/
protected static boolean checkConstraint(String version1,
VersionComparison constraint, String version2) {
VersionComparison c = compare(version1, version2);
return constraint.compatibleWith(c);
}
/**
* Returns a VersionComparison that represents the comparison between the
* supplied version 1 and version 2.
*
* @param version1 String containing version number 1.
* @param version2 String containing version number 2.
* @return a VersionComparison object.
*/
public static VersionComparison compare(String version1, String version2) {
// parse both of the versions
int[] majMinRev1 = VersionPackageConstraint.parseVersion(version1);
int[] majMinRev2 = VersionPackageConstraint.parseVersion(version2);
VersionComparison result;
if (majMinRev1[0] < majMinRev2[0]) {
result = VersionComparison.LESSTHAN;
} else if (majMinRev1[0] == majMinRev2[0]) {
if (majMinRev1[1] < majMinRev2[1]) {
result = VersionComparison.LESSTHAN;
} else if (majMinRev1[1] == majMinRev2[1]) {
if (majMinRev1[2] < majMinRev2[2]) {
result = VersionComparison.LESSTHAN;
} else if (majMinRev1[2] == majMinRev2[2]) {
if (majMinRev1[3] == majMinRev2[3]) {
result = VersionComparison.EQUAL;
} else {
result = VersionComparison.GREATERTHAN;
}
} else {
result = VersionComparison.GREATERTHAN;
}
} else {
result = VersionComparison.GREATERTHAN;
}
} else {
result = VersionComparison.GREATERTHAN;
}
return result;
}
public VersionPackageConstraint(Package p) {
setPackage(p);
}
public void setVersionConstraint(VersionComparison c) {
m_constraint = c;
}
public VersionComparison getVersionComparison() {
return m_constraint;
}
public void setVersionConstraint(String constraint) {
for (VersionComparison v : VersionComparison.values()) {
if (v.toString().equalsIgnoreCase(constraint)) {
m_constraint = v;
break;
}
}
}
/**
* Check the target package constraint against the constraint embodied in this
* package constraint. Returns either the package constraint that covers both
* this and the target constraint, or null if this and the target are
* incompatible.
*
* Try and return the *least* restrictive constraint that satisfies this and
* the target.
*
* @param target the package constraint to compare against
* @return a package constraint that covers this and the supplied constraint,
* or null if they are incompatible.
*/
@Override
public PackageConstraint checkConstraint(PackageConstraint target)
throws Exception {
if (m_constraint == null) {
throw new Exception(
"[VersionPackageConstraint] No constraint has been set!");
}
// delegate to VersionRangePackageConstraint if necessary
if (target instanceof VersionRangePackageConstraint) {
return target.checkConstraint(this);
}
String targetVersion = target.getPackage()
.getPackageMetaDataElement(VERSION_KEY).toString();
String thisVersion = m_thePackage.getPackageMetaDataElement(VERSION_KEY)
.toString();
VersionComparison comp = compare(thisVersion, targetVersion);
if (comp == VersionComparison.EQUAL) { // equal version numbers
// return this if the constraints are the same for both this and target
if (m_constraint == ((VersionPackageConstraint) target)
.getVersionComparison()) {
return this;
} else if (m_constraint == VersionComparison.GREATERTHAN
&& (((VersionPackageConstraint) target).getVersionComparison() == VersionComparison.GREATERTHAN || ((VersionPackageConstraint) target)
.getVersionComparison() == VersionComparison.GREATERTHANOREQUAL)) {
return this; // satisfies both
} else if ((m_constraint == VersionComparison.GREATERTHANOREQUAL || m_constraint == VersionComparison.GREATERTHAN)
&& ((VersionPackageConstraint) target).getVersionComparison() == VersionComparison.GREATERTHAN) {
return target; // satisfies both
}
return null; // can't satisfy
} else {
// target constraint >/>=
if (((VersionPackageConstraint) target).getVersionComparison() == VersionComparison.GREATERTHAN
|| ((VersionPackageConstraint) target).getVersionComparison() == VersionComparison.GREATERTHANOREQUAL) {
if (m_constraint == VersionComparison.EQUAL
|| m_constraint == VersionComparison.GREATERTHAN
|| m_constraint == VersionComparison.GREATERTHANOREQUAL) {
// return the higher of the two versions
if (comp == VersionComparison.GREATERTHAN) {
return this;
} else {
return target;
}
}
return null; // can't satisfy
// target constraint </<=
} else if (((VersionPackageConstraint) target).getVersionComparison() == VersionComparison.LESSTHAN
|| ((VersionPackageConstraint) target).getVersionComparison() == VersionComparison.LESSTHANOREQUAL) {
if (m_constraint == VersionComparison.EQUAL
|| m_constraint == VersionComparison.LESSTHAN
|| m_constraint == VersionComparison.LESSTHANOREQUAL) {
// return the lower of the two versions
if (comp == VersionComparison.GREATERTHAN) {
return target; // satisfies both
} else {
return this;
}
}
return null; // can't satisfy
}
return null; // can't satisfy
// Could also be compatible in the case where
// our constraint is < and target is > (but would need to implement a
// y < x < z type of version constraint
}
}
/**
* Check the target package against the constraint embodied in this
* PackageConstraint.
*
* @param target a package to check with respect to the encapsulated package
* and the constraint.
*
* @return true if the constraint is met by the target package with respect to
* the encapsulated package + constraint.
* @throws Exception if the constraint can't be checked for some reason.
*/
@Override
public boolean checkConstraint(Package target) throws Exception {
if (m_constraint == null) {
throw new Exception(
"[VersionPackageConstraint] No constraint has been set!");
}
String targetVersion = target.getPackageMetaDataElement(VERSION_KEY)
.toString();
String thisVersion = m_thePackage.getPackageMetaDataElement(VERSION_KEY)
.toString();
return checkConstraint(targetVersion, m_constraint, thisVersion);
}
@Override
public String toString() {
String result = m_thePackage.getPackageMetaDataElement("PackageName")
.toString()
+ " ("
+ m_constraint
+ m_thePackage.getPackageMetaDataElement("Version").toString() + ")";
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/packageManagement/VersionRangePackageConstraint.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/>.
*/
/*
* VersionRangePackageConstraint.java
* Copyright (C) 2015 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.packageManagement;
/**
* A concrete implementation of PackgageConstraint that encapsulates ranged
* version number constraints. Handles constraints of the form (u.v.w < package
* < x.y.z) and (package < u.v.w OR package > x.y.z)
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision: 44030 $
*/
public class VersionRangePackageConstraint extends PackageConstraint {
/** the lower bound */
protected String m_lowerBound;
/** the comparison for the lower bound */
protected VersionPackageConstraint.VersionComparison m_lowerConstraint;
/** the upper bound */
protected String m_upperBound;
/** the comparison for the upper bound */
protected VersionPackageConstraint.VersionComparison m_upperConstraint;
/** is false for version1 <= package <= version2 */
protected boolean m_boundOr;
/**
* Constructor
*
* @param p the package to base this constraint on
*/
public VersionRangePackageConstraint(Package p) {
setPackage(p);
}
/**
* Set the range bounds and constraints.
*
* @param bound1 the first bound
* @param comp1 the first comparison
* @param bound2 the second bound
* @param comp2 the second comparison
* @throws Exception if the range constraint is malformed
*/
public void setRangeConstraint(String bound1,
VersionPackageConstraint.VersionComparison comp1, String bound2,
VersionPackageConstraint.VersionComparison comp2) throws Exception {
// ranged constraint doesn't allow =
if (comp1 == VersionPackageConstraint.VersionComparison.EQUAL
|| comp2 == VersionPackageConstraint.VersionComparison.EQUAL) {
throw new Exception("[VersionRangePackageConstraint] malformed version "
+ "range constraint (= not allowed)!");
}
// if both inequalities are in the same direction then a plain
// VersionPackageConstraint could be used to cover them both
if (comp1.compatibleWith(comp2)) {
throw new Exception("[VersionRangePackageConstraint] malformed "
+ "version range constraint!");
}
// determine which type of range this is
VersionPackageConstraint.VersionComparison boundsComp =
VersionPackageConstraint.compare(bound1, bound2);
if (boundsComp == VersionPackageConstraint.VersionComparison.EQUAL) {
throw new Exception("[VersionRangePackageConstraint] malformed version"
+ " range - both bounds are equal!");
}
if (comp1 == VersionPackageConstraint.VersionComparison.GREATERTHAN
|| comp1 == VersionPackageConstraint.VersionComparison.GREATERTHANOREQUAL) {
if (boundsComp == VersionPackageConstraint.VersionComparison.GREATERTHAN) {
m_boundOr = true; // it is an OR with respect to the two inequalities
}
} else {
if (boundsComp == VersionPackageConstraint.VersionComparison.LESSTHAN) {
m_boundOr = true; // it is an OR with respect to the two inequalities
}
}
// store bounds in ascending order
if (boundsComp == VersionPackageConstraint.VersionComparison.LESSTHAN) {
m_lowerBound = bound1;
m_lowerConstraint = comp1;
m_upperBound = bound2;
m_upperConstraint = comp2;
} else {
m_lowerBound = bound2;
m_lowerConstraint = comp2;
m_upperBound = bound1;
m_upperConstraint = comp1;
}
}
/**
* Get the lower bound of this range
*
* @return the lower bound
*/
public String getLowerBound() {
return m_lowerBound;
}
/**
* Get the upper bound of this range
*
* @return the upper bound
*/
public String getUpperBound() {
return m_upperBound;
}
/**
* Get the lower comparison
*
* @return the lower comparison
*/
public VersionPackageConstraint.VersionComparison getLowerComparison() {
return m_lowerConstraint;
}
/**
* Get the upper comparison
*
* @return the upper comparison
*/
public VersionPackageConstraint.VersionComparison getUpperComparison() {
return m_upperConstraint;
}
/**
* Returns true if this is a bounded OR type of constraint
*
* @return true if this is a bounded OR type of constraint
*/
public boolean isBoundOR() {
return m_boundOr;
}
protected static boolean checkConstraint(String toCheck,
VersionPackageConstraint.VersionComparison comp1, String bound1,
VersionPackageConstraint.VersionComparison comp2, String bound2,
boolean boundOr) {
boolean result1 =
VersionPackageConstraint.checkConstraint(toCheck, comp1, bound1);
boolean result2 =
VersionPackageConstraint.checkConstraint(toCheck, comp2, bound2);
if (boundOr) {
return (result1 || result2);
} else {
return (result1 && result2);
}
}
/**
* Check the target package against the constraint embodied in this
* PackageConstraint.
*
* @param target a package to check with respect to the encapsulated package
* and the constraint.
*
* @return true if the constraint is met by the target package with respect to
* the encapsulated package + constraint.
* @throws Exception if the constraint can't be checked for some reason.
*/
@Override
public boolean checkConstraint(Package target) throws Exception {
if (m_lowerConstraint == null || m_upperConstraint == null) {
throw new Exception("[VersionRangePackageConstraint] No constraint has"
+ " been set!");
}
String targetVersion =
target.getPackageMetaDataElement(VersionPackageConstraint.VERSION_KEY)
.toString();
return checkConstraint(targetVersion, m_lowerConstraint, m_lowerBound,
m_upperConstraint, m_upperBound, m_boundOr);
}
protected PackageConstraint checkTargetVersionRangePackageConstraint(
VersionRangePackageConstraint target) throws Exception {
// TODO
String targetLowerBound = target.getLowerBound();
String targetUpperBound = target.getUpperBound();
VersionPackageConstraint.VersionComparison targetLowerComp =
target.getLowerComparison();
VersionPackageConstraint.VersionComparison targetUpperComp =
target.getUpperComparison();
if (!m_boundOr) {
if (target.isBoundOR()) {
// construct two VersionPackageConstraints to represent the two
// target open-ended inequalities
Package p = (Package) target.getPackage().clone();
p.setPackageMetaDataElement(VersionPackageConstraint.VERSION_KEY,
target.getLowerBound());
VersionPackageConstraint lowerC = new VersionPackageConstraint(p);
lowerC.setVersionConstraint(target.getLowerComparison());
p = (Package) p.clone();
p.setPackageMetaDataElement(VersionPackageConstraint.VERSION_KEY,
target.getUpperBound());
VersionPackageConstraint upperC = new VersionPackageConstraint(p);
upperC.setVersionConstraint(target.getUpperComparison());
PackageConstraint coveringLower =
checkTargetVersionPackageConstraint(lowerC);
if (coveringLower != null) {
// return this one. It is possible that both could be covered, but one
// is
// sufficient (and we have no mechanism for handling two fully bounded
// ranges!
return coveringLower;
}
PackageConstraint coveringUpper =
checkTargetVersionPackageConstraint(upperC);
return coveringUpper; // if we can't cover target at all then this will
// be null
} else {
// us and target are both bounded AND
String resultLowerBound = null;
String resultUpperBound = null;
VersionPackageConstraint.VersionComparison resultLowerComp = null;
VersionPackageConstraint.VersionComparison resultUpperComp = null;
VersionPackageConstraint.VersionComparison lowerComp =
VersionPackageConstraint.compare(m_lowerBound, targetLowerBound);
if (lowerComp == VersionPackageConstraint.VersionComparison.EQUAL) {
resultLowerBound = m_lowerBound;
resultLowerComp =
VersionPackageConstraint.VersionComparison.GREATERTHANOREQUAL;
// select the most restrictive inequality
if (targetLowerComp == VersionPackageConstraint.VersionComparison.GREATERTHAN
|| m_lowerConstraint == VersionPackageConstraint.VersionComparison.GREATERTHAN) {
resultLowerComp =
VersionPackageConstraint.VersionComparison.GREATERTHAN;
}
} else if (lowerComp == VersionPackageConstraint.VersionComparison.GREATERTHAN) {
resultLowerBound = m_lowerBound;
resultLowerComp = m_lowerConstraint;
} else {
resultLowerBound = targetLowerBound;
resultLowerComp = targetLowerComp;
}
VersionPackageConstraint.VersionComparison upperComp =
VersionPackageConstraint.compare(m_upperBound, targetUpperBound);
if (upperComp == VersionPackageConstraint.VersionComparison.EQUAL) {
resultUpperBound = m_upperBound;
resultUpperComp =
VersionPackageConstraint.VersionComparison.LESSTHANOREQUAL;
// select the most restrictive inequality
if (targetUpperComp == VersionPackageConstraint.VersionComparison.LESSTHAN
|| m_upperConstraint == VersionPackageConstraint.VersionComparison.LESSTHAN) {
resultUpperComp =
VersionPackageConstraint.VersionComparison.LESSTHAN;
}
} else if (upperComp == VersionPackageConstraint.VersionComparison.LESSTHAN) {
resultUpperBound = m_upperBound;
resultUpperComp = m_upperConstraint;
} else {
resultUpperBound = targetUpperBound;
resultUpperComp = targetUpperComp;
}
// now check for incompatibility - if resultUpper is less than result
// lower
// then the ranges are disjoint
VersionPackageConstraint.VersionComparison disjointCheck =
VersionPackageConstraint.compare(resultUpperBound, resultLowerBound);
if (disjointCheck == VersionPackageConstraint.VersionComparison.LESSTHAN
|| disjointCheck == VersionPackageConstraint.VersionComparison.EQUAL) {
// TODO if EQUAL then could actually return a VersionPackageConstraint
// with an EQUAL constraint.
return null;
}
// otherwise, we're good to go...
VersionRangePackageConstraint result =
new VersionRangePackageConstraint(getPackage());
result.setRangeConstraint(resultLowerBound, resultLowerComp,
resultUpperBound, resultUpperComp);
return result;
}
} else {
// we are bounded OR
if (!target.isBoundOR()) {
// construct two VersionPackageConstraints to represent our two
// open-ended inequalities
Package p = (Package) getPackage().clone();
p.setPackageMetaDataElement(VersionPackageConstraint.VERSION_KEY,
m_lowerBound);
VersionPackageConstraint lowerC = new VersionPackageConstraint(p);
lowerC.setVersionConstraint(m_lowerConstraint);
p = (Package) p.clone();
p.setPackageMetaDataElement(VersionPackageConstraint.VERSION_KEY,
m_upperBound);
VersionPackageConstraint upperC = new VersionPackageConstraint(p);
upperC.setVersionConstraint(m_upperConstraint);
PackageConstraint coveringLower =
target.checkTargetVersionPackageConstraint(lowerC);
if (coveringLower != null) {
// return this one. It is possible that both could be covered, but one
// is
// sufficient (and we have no mechanism for handling two fully bounded
// ranges!
return coveringLower;
}
PackageConstraint coveringUpper =
checkTargetVersionPackageConstraint(upperC);
return coveringUpper; // if the target can't cover us then this will be
// null
} else {
// both us and target are bounded ORs. Just need the greatest upper
// bound
// and the smallest lower bound of the two
String resultLowerBound = null;
String resultUpperBound = null;
VersionPackageConstraint.VersionComparison resultLowerComp = null;
VersionPackageConstraint.VersionComparison resultUpperComp = null;
VersionPackageConstraint.VersionComparison lowerComp =
VersionPackageConstraint.compare(m_lowerBound, targetLowerBound);
if (lowerComp == VersionPackageConstraint.VersionComparison.EQUAL) {
resultLowerBound = m_lowerBound;
resultLowerComp =
VersionPackageConstraint.VersionComparison.LESSTHANOREQUAL;
// select the most restrictive inequality
if (targetLowerComp == VersionPackageConstraint.VersionComparison.LESSTHAN
|| m_lowerConstraint == VersionPackageConstraint.VersionComparison.LESSTHAN) {
resultLowerComp =
VersionPackageConstraint.VersionComparison.LESSTHAN;
}
} else if (lowerComp == VersionPackageConstraint.VersionComparison.LESSTHAN) {
resultLowerBound = m_lowerBound;
resultLowerComp = m_lowerConstraint;
} else {
resultLowerBound = targetLowerBound;
resultLowerComp = targetLowerComp;
}
VersionPackageConstraint.VersionComparison upperComp =
VersionPackageConstraint.compare(m_upperBound, targetUpperBound);
if (upperComp == VersionPackageConstraint.VersionComparison.EQUAL) {
resultUpperBound = m_upperBound;
resultUpperComp =
VersionPackageConstraint.VersionComparison.GREATERTHANOREQUAL;
// select the most restrictive inequality
if (targetUpperComp == VersionPackageConstraint.VersionComparison.GREATERTHAN
|| m_upperConstraint == VersionPackageConstraint.VersionComparison.GREATERTHAN) {
resultUpperComp =
VersionPackageConstraint.VersionComparison.GREATERTHAN;
}
} else if (upperComp == VersionPackageConstraint.VersionComparison.GREATERTHAN) {
resultUpperBound = m_upperBound;
resultUpperComp = m_upperConstraint;
} else {
resultUpperBound = targetUpperBound;
resultUpperComp = targetUpperComp;
}
VersionRangePackageConstraint result =
new VersionRangePackageConstraint(getPackage());
result.setRangeConstraint(resultLowerBound, resultLowerComp,
resultUpperBound, resultUpperComp);
return result;
}
}
}
protected PackageConstraint checkTargetVersionPackageConstraint(
VersionPackageConstraint target) throws Exception {
VersionPackageConstraint.VersionComparison targetComp =
target.getVersionComparison();
String targetVersion =
target.getPackage()
.getPackageMetaDataElement(VersionPackageConstraint.VERSION_KEY)
.toString();
VersionPackageConstraint.VersionComparison lowerComp =
VersionPackageConstraint.compare(targetVersion, m_lowerBound);
VersionPackageConstraint.VersionComparison upperComp =
VersionPackageConstraint.compare(targetVersion, m_upperBound);
boolean lowerCheck = false;
boolean upperCheck = false;
String coveringLowerBound = null;
String coveringUpperBound = null;
VersionPackageConstraint.VersionComparison coveringLowerConstraint = null;
VersionPackageConstraint.VersionComparison coveringUpperConstraint = null;
// equals is easy
if (targetComp == VersionPackageConstraint.VersionComparison.EQUAL) {
// If our range contains the target version number then the target
// is the least restrictive constraint that covers both
if (checkConstraint(target.getPackage())) {
return target;
} else {
return null; // incompatible
}
} else {
if (m_boundOr) {
// Check against our lower bound (our lower bound is a < or <=)
// --------------
// lower bound < case
if (m_lowerConstraint == VersionPackageConstraint.VersionComparison.LESSTHAN) {
if (lowerComp == VersionPackageConstraint.VersionComparison.EQUAL
|| lowerComp == VersionPackageConstraint.VersionComparison.GREATERTHAN) {
if (targetComp == VersionPackageConstraint.VersionComparison.GREATERTHAN
|| targetComp == VersionPackageConstraint.VersionComparison.GREATERTHANOREQUAL) {
// not compatible with our lower bound
lowerCheck = false;
} else {
lowerCheck = true;
// adjust the bounds
coveringLowerBound = m_lowerBound;
coveringLowerConstraint = m_lowerConstraint;
}
} else if (lowerComp == VersionPackageConstraint.VersionComparison.LESSTHAN) {
lowerCheck = true;
coveringLowerBound = targetVersion;
coveringLowerConstraint = targetComp;
if (targetComp == VersionPackageConstraint.VersionComparison.LESSTHAN
|| targetComp == VersionPackageConstraint.VersionComparison.LESSTHANOREQUAL) {
coveringUpperBound = null; // same direction as our lower
// constraint (so no upper bound)
} else {
// target's comparison is > or >= (new upper bound = our lower
// bound)
coveringUpperBound = m_lowerBound;
coveringUpperConstraint = m_lowerConstraint;
}
}
} else {
// lower bound <= case
if (lowerComp == VersionPackageConstraint.VersionComparison.GREATERTHAN) {
if (targetComp == VersionPackageConstraint.VersionComparison.GREATERTHAN
|| targetComp == VersionPackageConstraint.VersionComparison.GREATERTHANOREQUAL) {
// not compatible with our lower bound
lowerCheck = false;
} else {
lowerCheck = true;
// adjust bounds
coveringLowerBound = m_lowerBound;
coveringLowerConstraint = m_lowerConstraint;
}
} else if (lowerComp == VersionPackageConstraint.VersionComparison.EQUAL) {
// if the target version is equal to our lower bound then the target
// constraint
// can't be >
if (targetComp == VersionPackageConstraint.VersionComparison.GREATERTHAN) {
lowerCheck = false;
} else {
// target constraint is < or <=
lowerCheck = true;
coveringLowerBound = targetVersion;
coveringLowerConstraint = targetComp;
coveringUpperBound = null; // same direction as our lower bound
// (so no upper bound)
}
} else {
// target version is < or = to our lower bound
lowerCheck = true;
coveringLowerBound = targetVersion;
coveringLowerConstraint = targetComp;
if (targetComp == VersionPackageConstraint.VersionComparison.LESSTHAN
|| targetComp == VersionPackageConstraint.VersionComparison.LESSTHANOREQUAL) {
coveringUpperBound = null; // same direction as our lower
// constraint (so no upper bound)
} else {
// target's comparison is > or >= (new upper bound = our lower
// bound)
coveringUpperBound = m_lowerBound;
coveringUpperConstraint = m_lowerConstraint;
}
}
}
// end check against our lower bound ----------------
// check against our upper bound (if necessary)
if (!lowerCheck) {
// Check against our upper bound (our upper bound is a > or >=)
// --------------
// upper bound > case
if (m_upperConstraint == VersionPackageConstraint.VersionComparison.GREATERTHAN) {
if (upperComp == VersionPackageConstraint.VersionComparison.EQUAL
|| upperComp == VersionPackageConstraint.VersionComparison.LESSTHAN) {
if (targetComp == VersionPackageConstraint.VersionComparison.LESSTHAN
|| targetComp == VersionPackageConstraint.VersionComparison.LESSTHANOREQUAL) {
// not compatible with our upper bound
upperCheck = false;
} else {
lowerCheck = true;
// adjust the bounds
coveringUpperBound = m_upperBound;
coveringUpperConstraint = m_upperConstraint;
}
} else if (upperComp == VersionPackageConstraint.VersionComparison.GREATERTHAN) {
upperCheck = true;
coveringUpperBound = targetVersion;
coveringUpperConstraint = targetComp;
if (targetComp == VersionPackageConstraint.VersionComparison.GREATERTHAN
|| targetComp == VersionPackageConstraint.VersionComparison.GREATERTHANOREQUAL) {
coveringLowerBound = null; // same direction as our upper
// constraint (so no lower bound)
} else {
// target's comparison is < or <= (new lower bound = our upper
// bound)
coveringLowerBound = m_upperBound;
coveringLowerConstraint = m_upperConstraint;
}
}
} else {
// upper bound >= case
if (upperComp == VersionPackageConstraint.VersionComparison.LESSTHAN) {
if (targetComp == VersionPackageConstraint.VersionComparison.LESSTHAN
|| targetComp == VersionPackageConstraint.VersionComparison.LESSTHANOREQUAL) {
// not compatible with our upper bound
upperCheck = false;
} else {
upperCheck = true;
// adjust bounds
coveringUpperBound = m_upperBound;
coveringUpperConstraint = m_upperConstraint;
}
} else if (upperComp == VersionPackageConstraint.VersionComparison.EQUAL) {
// if the target version is equal to our upper bound then the
// target constraint
// can't be <
if (targetComp == VersionPackageConstraint.VersionComparison.LESSTHAN) {
upperCheck = false;
} else {
// target constraint is > or >=
upperCheck = true;
coveringUpperBound = targetVersion;
coveringUpperConstraint = targetComp;
coveringLowerBound = null; // same direction as our upper bound
// (so no lower bound)
}
} else {
// target version is > or = to our upper bound
upperCheck = true;
coveringUpperBound = targetVersion;
coveringUpperConstraint = targetComp;
if (targetComp == VersionPackageConstraint.VersionComparison.GREATERTHAN
|| targetComp == VersionPackageConstraint.VersionComparison.GREATERTHANOREQUAL) {
coveringLowerBound = null; // same direction as our upper
// constraint (so no lower bound)
} else {
// target's comparison is < or <= (new lower bound = our upper
// bound)
coveringLowerBound = m_upperBound;
coveringLowerConstraint = m_upperConstraint;
}
}
}
}
// now return the appropriate type of package constraint to cover this
// and the
// target
if (!lowerCheck && !upperCheck) {
// this shouldn't be possible
throw new Exception(
"[VersionRangePackageConstraint] This shouldn't be possible!!");
}
if (coveringLowerBound != null && coveringUpperBound != null) {
VersionRangePackageConstraint result =
new VersionRangePackageConstraint(getPackage());
result.setRangeConstraint(coveringLowerBound,
coveringLowerConstraint, coveringUpperBound,
coveringUpperConstraint);
return result;
}
String newVersionNumber =
(coveringLowerBound != null) ? coveringLowerBound
: coveringUpperBound;
VersionPackageConstraint.VersionComparison newConstraint =
(coveringLowerConstraint != null) ? coveringLowerConstraint
: coveringUpperConstraint;
Package p = (Package) getPackage().clone();
p.setPackageMetaDataElement(VersionPackageConstraint.VERSION_KEY,
newVersionNumber);
VersionPackageConstraint result = new VersionPackageConstraint(p);
result.setVersionConstraint(newConstraint);
return result;
} // end bounded OR case //////////
else {
// bounded AND case
if (lowerComp == VersionPackageConstraint.VersionComparison.LESSTHAN) {
if (targetComp == VersionPackageConstraint.VersionComparison.LESSTHAN
|| targetComp == VersionPackageConstraint.VersionComparison.LESSTHANOREQUAL
|| targetComp == VersionPackageConstraint.VersionComparison.EQUAL) {
// outside of our range and inequality is in the wrong direction
lowerCheck = false;
} else {
// outside our range, but inequality in right direction - our range
// satisfies both
lowerCheck = true;
coveringLowerBound = m_lowerBound;
coveringLowerConstraint = m_lowerConstraint;
coveringUpperBound = m_upperBound;
coveringUpperConstraint = m_upperConstraint;
}
} else if (lowerComp == VersionPackageConstraint.VersionComparison.EQUAL) {
// satisfiable if target comp is > or >=
if (targetComp == VersionPackageConstraint.VersionComparison.GREATERTHANOREQUAL
|| targetComp == VersionPackageConstraint.VersionComparison.GREATERTHAN) {
lowerCheck = true;
coveringLowerBound = m_lowerBound;
coveringLowerConstraint =
(m_lowerConstraint == VersionPackageConstraint.VersionComparison.GREATERTHAN || targetComp == VersionPackageConstraint.VersionComparison.GREATERTHAN) ? VersionPackageConstraint.VersionComparison.GREATERTHAN
: VersionPackageConstraint.VersionComparison.GREATERTHANOREQUAL;
coveringUpperBound = m_upperBound;
coveringUpperConstraint = m_upperConstraint;
} else {
// target comp is < or <= - can satisfy only if <= and our lower
// constraint is >=
if (targetComp == VersionPackageConstraint.VersionComparison.LESSTHANOREQUAL
&& m_lowerConstraint == VersionPackageConstraint.VersionComparison.GREATERTHANOREQUAL) {
VersionPackageConstraint.VersionComparison newComp =
VersionPackageConstraint.VersionComparison.EQUAL;
VersionPackageConstraint result =
new VersionPackageConstraint(target.getPackage());
result.setVersionConstraint(newComp);
// we're done
return result;
}
}
} else if (lowerComp == VersionPackageConstraint.VersionComparison.GREATERTHAN) {
// handle the within range (but not on the upper boundary) case here
if (upperComp == VersionPackageConstraint.VersionComparison.LESSTHAN) {
if (targetComp == VersionPackageConstraint.VersionComparison.LESSTHAN
|| targetComp == VersionPackageConstraint.VersionComparison.LESSTHANOREQUAL) {
lowerCheck = true;
upperCheck = true;
coveringLowerBound = m_lowerBound;
coveringLowerConstraint = m_lowerConstraint;
coveringUpperBound = targetVersion;
coveringUpperConstraint = targetComp;
} else {
coveringLowerBound = targetVersion;
coveringLowerConstraint = targetComp;
coveringUpperBound = m_upperBound;
coveringUpperConstraint = m_upperConstraint;
}
}
}
if (coveringLowerBound == null || coveringUpperBound == null) {
// consider the upper bound
if (upperComp == VersionPackageConstraint.VersionComparison.EQUAL) {
// satisfiable if target comp is < or <=
if (targetComp == VersionPackageConstraint.VersionComparison.LESSTHANOREQUAL
|| targetComp == VersionPackageConstraint.VersionComparison.LESSTHAN) {
upperCheck = true;
coveringUpperBound = m_upperBound;
coveringUpperConstraint =
(m_upperConstraint == VersionPackageConstraint.VersionComparison.LESSTHAN || targetComp == VersionPackageConstraint.VersionComparison.LESSTHAN) ? VersionPackageConstraint.VersionComparison.LESSTHAN
: VersionPackageConstraint.VersionComparison.LESSTHANOREQUAL;
coveringLowerBound = m_lowerBound;
coveringLowerConstraint = m_lowerConstraint;
} else {
// target comp is > or >= - can satisfy only if >= and our upper
// constraint is <=
if (targetComp == VersionPackageConstraint.VersionComparison.GREATERTHANOREQUAL
&& m_upperConstraint == VersionPackageConstraint.VersionComparison.LESSTHANOREQUAL) {
VersionPackageConstraint.VersionComparison newComp =
VersionPackageConstraint.VersionComparison.EQUAL;
VersionPackageConstraint result =
new VersionPackageConstraint(target.getPackage());
result.setVersionConstraint(newComp);
// we're done
return result;
}
}
} else if (upperComp == VersionPackageConstraint.VersionComparison.GREATERTHAN) {
if (targetComp == VersionPackageConstraint.VersionComparison.GREATERTHAN
|| targetComp == VersionPackageConstraint.VersionComparison.GREATERTHANOREQUAL
|| targetComp == VersionPackageConstraint.VersionComparison.EQUAL) {
// outside of our range and inequality is in the wrong direction
upperCheck = false;
} else {
// outside our range, but inequality in right direction - our
// range satisfies both
upperCheck = true;
coveringUpperBound = m_upperBound;
coveringUpperConstraint = m_upperConstraint;
coveringLowerBound = m_lowerBound;
coveringLowerConstraint = m_lowerConstraint;
}
}
}
if (coveringUpperBound == null && coveringLowerBound == null) {
// we can't satisfy both
return null;
}
if (coveringUpperBound == null || coveringLowerBound == null) {
// this shouldn't happen - either we can't cover it (in which case
// both should be null) or we can (in which case both are non-null).
throw new Exception(
"[VersionRangePackageConstraint] This shouldn't be possible!!");
}
VersionRangePackageConstraint result =
new VersionRangePackageConstraint(getPackage());
result.setRangeConstraint(coveringLowerBound, coveringLowerConstraint,
coveringUpperBound, coveringUpperConstraint);
return result;
}
// check for incompatible first
/*
* boolean checkLower =
* VersionPackageConstraint.checkConstraint(targetVersion,
* m_lowerConstraint, m_lowerBound);
*/
/*
* VersionPackageConstraint lowerBoundCover = new
* VersionPackageConstraint((Package)(getPackage().clone()));
* lowerBoundCover.setVersionConstraint(m_lowerConstraint);
*/
}
}
@Override
public PackageConstraint checkConstraint(PackageConstraint target)
throws Exception {
if (m_lowerConstraint == null || m_upperConstraint == null) {
throw new Exception("[VersionRangePackageConstraint] No constraint has"
+ " been set!");
}
// have to cover the case where the target is a VersionPackageConstraint or
// a VersionRangePackageConstraint
if (!(target instanceof VersionRangePackageConstraint)
&& !(target instanceof VersionPackageConstraint)) {
throw new Exception("[VersionRangePackageConstraint] incompatible "
+ "target constraint!");
}
// target is a VersionPackageConstraint
if (target instanceof VersionPackageConstraint) {
PackageConstraint result =
checkTargetVersionPackageConstraint((VersionPackageConstraint) target);
return result;
} else if (target instanceof VersionRangePackageConstraint) {
// target is VersionRangePackageConstraint
PackageConstraint result =
checkTargetVersionRangePackageConstraint((VersionRangePackageConstraint) target);
return result;
}
return null;
}
@Override
public String toString() {
String result =
m_thePackage.getPackageMetaDataElement("PackageName").toString() + " ("
+ m_lowerConstraint + m_lowerBound + "|" + m_upperConstraint
+ m_upperBound + ")";
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/pmml/Apply.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/>.
*/
/*
* Apply.java
* Copyright (C) 2008-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.pmml;
import java.util.ArrayList;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import weka.core.Attribute;
/**
* Class encapsulating an Apply Expression.
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision 1.0 $
*/
class Apply extends Expression {
/**
* For serialization
*/
private static final long serialVersionUID = -2790648331300695083L;
/** The list of arguments the function encapsulated in this Apply Expression */
protected ArrayList<Expression> m_arguments = new ArrayList<Expression>();
/** The function to apply (either built-in or a DefineFunction) */
protected Function m_function = null;
/** The structure of the result of Apply Expression */
protected Attribute m_outputStructure = null;
/**
* Constructor. Reads the function name and argument Expressions for
* this Apply Expression.
*
* @param apply the Element encapsulating this Apply
* @param opType the optype for this expression (taken from either the
* enclosing DefineFunction or DerivedField)
* @param fieldDefs an ArrayList of Attributes for the fields that this
* Expression might need to access
* @param transDict the TransformationDictionary (may be null if there is
* no dictionary)
* @throws Exception if there is a problem parsing this Apply Expression
*/
protected Apply(Element apply, FieldMetaInfo.Optype opType, ArrayList<Attribute> fieldDefs,
TransformationDictionary transDict)
throws Exception {
super(opType, fieldDefs);
String functionName = apply.getAttribute("function");
if (functionName == null || functionName.length() == 0) {
// try the attribute "name" - a sample file produced by MARS
// uses this attribute name rather than "function" as defined
// in the PMML spec
functionName = apply.getAttribute("name");
}
if (functionName == null || functionName.length() == 0) {
throw new Exception("[Apply] No function name specified!!");
}
//System.err.println(" *** " + functionName);
m_function = Function.getFunction(functionName, transDict);
// now read the arguments
NodeList children = apply.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if (child.getNodeType() == Node.ELEMENT_NODE) {
String tagName = ((Element)child).getTagName();
if (!tagName.equals("Extension")) {
//System.err.println(" ++ " + tagName);
Expression tempExpression =
Expression.getExpression(tagName, child, m_opType, m_fieldDefs, transDict);
if (tempExpression != null) {
m_arguments.add(tempExpression);
}
}
}
}
if (fieldDefs != null) {
updateDefsForArgumentsAndFunction();
}
}
public void setFieldDefs(ArrayList<Attribute> fieldDefs) throws Exception {
super.setFieldDefs(fieldDefs);
updateDefsForArgumentsAndFunction();
}
private void updateDefsForArgumentsAndFunction() throws Exception {
for (int i = 0; i < m_arguments.size(); i++) {
m_arguments.get(i).setFieldDefs(m_fieldDefs);
}
// set the parameter defs for the function here so that we can determine
// the structure of the output we produce
ArrayList<Attribute> functionFieldDefs = new ArrayList<Attribute>(m_arguments.size());
for (int i = 0; i < m_arguments.size(); i++) {
functionFieldDefs.add(m_arguments.get(i).getOutputDef());
}
m_function.setParameterDefs(functionFieldDefs);
m_outputStructure = m_function.getOutputDef();
}
/**
* Get the result of evaluating the expression. In the case
* of a continuous optype, a real number is returned; in
* the case of a categorical/ordinal optype, the index of the nominal
* value is returned as a double.
*
* @param incoming the incoming parameter values
* @return the result of evaluating the expression
* @throws Exception if there is a problem computing the result
*/
public double getResult(double[] incoming)
throws Exception {
// assemble incoming to apply function to by processing each Expression
// in the list of arguments
double[] functionIncoming = new double[m_arguments.size()];
//ArrayList<Attribute> functionParamTypes = m_function.getParameters();
for (int i = 0; i < m_arguments.size(); i++) {
functionIncoming[i] = m_arguments.get(i).getResult(incoming);
}
double result = m_function.getResult(functionIncoming);
return result;
}
/**
* Get the result of evaluating the expression for continuous
* optype. Is the same as calling getResult() when the optype
* is continuous.
*
* @param incoming the incoming parameter values
* mining schema
* @return the result of evaluating the expression.
* @throws Exception if the optype is not continuous.
*/
public String getResultCategorical(double[] incoming) throws Exception {
if (m_opType == FieldMetaInfo.Optype.CONTINUOUS) {
throw new IllegalArgumentException("[Apply] Can't return result as "
+ "categorical/ordinal because optype is continuous!");
}
double result = getResult(incoming);
return m_outputStructure.value((int)result);
}
/**
* Return the structure of the result of applying this Expression
* as an Attribute.
*
* @return the structure of the result of applying this Expression as an
* Attribute.
*/
public Attribute getOutputDef() {
if (m_outputStructure == null) {
// return a "default" output def. This will get replaced
// by a final one when the final field defs are are set
// for all expressions after all derived fields are collected
return (m_opType == FieldMetaInfo.Optype.CATEGORICAL ||
m_opType == FieldMetaInfo.Optype.ORDINAL)
? new Attribute("Placeholder", new ArrayList<String>())
: new Attribute("Placeholder");
}
return m_outputStructure;//.copy(attName);
}
public String toString(String pad) {
StringBuffer buff = new StringBuffer();
// Used for DefineFunctions so that we can see which arguments
// correspond to which parameters
String[] parameterNames = null;
buff.append(pad + "Apply [" + m_function.toString() +"]:\n");
buff.append(pad + "args:");
if (m_function instanceof DefineFunction) {
parameterNames = m_function.getParameterNames();
}
for (int i = 0; i < m_arguments.size(); i++) {
Expression e = m_arguments.get(i);
buff.append("\n" +
((parameterNames != null)
? pad + parameterNames[i] + " = "
: "")
+ e.toString(pad + " "));
}
return buff.toString();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.