index
int64 | repo_id
string | file_path
string | content
string |
|---|---|---|---|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/AbstractTrainingSetProducerBeanInfo.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/>.
*/
/*
* AbstractTrainingSetProducerBeanInfo.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.beans.EventSetDescriptor;
import java.beans.SimpleBeanInfo;
/**
* BeanInfo class for AbstractTrainingSetProducer
*
* @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a>
* @version $Revision$
*/
public class AbstractTrainingSetProducerBeanInfo extends SimpleBeanInfo {
/**
* Returns event set descriptors for this type of bean
*
* @return an <code>EventSetDescriptor[]</code> value
*/
public EventSetDescriptor [] getEventSetDescriptors() {
try {
EventSetDescriptor [] esds = {
new EventSetDescriptor(TrainingSetProducer.class,
"trainingSet",
TrainingSetListener.class,
"acceptTrainingSet")
};
return esds;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/Appender.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/>.
*/
/*
* Appender.java
* Copyright (C) 2011-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.awt.BorderLayout;
import java.beans.EventSetDescriptor;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import javax.swing.JPanel;
import weka.core.Attribute;
import weka.core.DenseInstance;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.Utils;
import weka.core.converters.ArffLoader;
import weka.core.converters.ArffSaver;
import weka.core.converters.SerializedInstancesLoader;
import weka.gui.Logger;
/**
* A bean that appends multiple incoming data connections into a single data
* set. The incoming connections can be either all instance connections or all
* batch-oriented connections (i.e. data set, training set and test set).
* Instance and batch connections can't be mixed. An amalgamated output is
* created that is a combination of all the incoming attributes. Missing values
* are used to fill columns that don't exist in a particular incoming data set.
* If all incoming connections are instance connections, then the outgoing
* connection must be an instance connection (and vice versa for incoming batch
* connections).
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision$
*/
@KFStep(category = "Flow", toolTipText = "Append multiple sets of instances")
public class Appender extends JPanel implements BeanCommon, Visible, Serializable, DataSource, DataSourceListener, TrainingSetListener, TestSetListener, InstanceListener, EventConstraints {
/**
* For serialization
*/
private static final long serialVersionUID = 9177433051794199463L;
/** Logging */
protected transient Logger m_log;
/** Upstream components sending us data */
protected Set<String> m_listeneeTypes = new HashSet<String>();
protected Map<Object, Object> m_listenees = new HashMap<Object, Object>();
/**
* Used to keep track of how many have sent us complete data sets (batch) or
* structure available events (incremental) so far + store headers from each
*/
protected transient Map<Object, Instances> m_completed;
/** Handles on temp files used to store batches of instances in batch mode */
protected transient Map<Object, File> m_tempBatchFiles;
/** Used to hold the final header in the case of incremental operation */
protected transient Instances m_completeHeader;
/**
* Holds savers used for incrementally saving incoming instance streams. After
* we've seen the structure from each incoming connection we can create the
* final output structure, pull any saved instances from the temp files and
* discard these savers as they will no longer be needed.
*/
protected transient Map<Object, ArffSaver> m_incrementalSavers;
/** Instance event to use for incremental mode */
protected InstanceEvent m_ie = new InstanceEvent(this);
/** Keeps track of how many incoming instance streams have finished */
protected int m_finishedCount;
/** For printing status updates in incremental mode */
protected transient int m_incrementalCounter;
/** True if we are busy */
protected boolean m_busy;
/**
* Default visual for data sources
*/
protected BeanVisual m_visual = new BeanVisual("Appender", BeanVisual.ICON_PATH + "Appender.png", BeanVisual.ICON_PATH + "Appender.png");
/** Downstream steps listening to batch data events */
protected ArrayList<DataSourceListener> m_dataListeners = new ArrayList<DataSourceListener>();
/** Downstream steps listening to instance events */
protected ArrayList<InstanceListener> m_instanceListeners = new ArrayList<InstanceListener>();
/**
* Constructs a new Appender.
*/
public Appender() {
this.useDefaultVisual();
this.setLayout(new BorderLayout());
this.add(this.m_visual, BorderLayout.CENTER);
}
/**
* Returns true if, at the current time, the named event could be generated.
*
* @param eventName the name of the event in question
* @return true if the named event could be generated
*/
@Override
public boolean eventGeneratable(final String eventName) {
if (eventName.equals("instance")) {
if (!this.m_listeneeTypes.contains(eventName)) {
return false;
}
for (Object listenee : this.m_listenees.values()) {
if (listenee instanceof EventConstraints && !((EventConstraints) listenee).eventGeneratable(eventName)) {
return false;
}
}
}
if (eventName.equals("dataSet") || eventName.equals("trainingSet") || eventName.equals("testSet")) {
if (!this.m_listeneeTypes.contains("dataSet") && !this.m_listeneeTypes.contains("trainingSet") && !this.m_listeneeTypes.contains("testSet")) {
return false;
}
for (Object listenee : this.m_listenees.values()) {
if (listenee instanceof EventConstraints) {
if (!((EventConstraints) listenee).eventGeneratable("dataSet") && !((EventConstraints) listenee).eventGeneratable("trainingSet") && !((EventConstraints) listenee).eventGeneratable("testSet")) {
return false;
}
}
}
}
return true;
}
/**
* Accept and process an instance event
*
* @param e an <code>InstanceEvent</code> value
*/
@Override
public synchronized void acceptInstance(final InstanceEvent e) {
this.m_busy = true;
if (this.m_completed == null) {
this.m_completed = new HashMap<Object, Instances>();
// until we have a header from each incoming connection, we'll have
// to store instances to temp files. If sequential start points are
// being used, or the operation of the flow results in all instances
// from one input path getting passed in before any subsequent input
// paths are processed, then this will be inefficient. Parallel start
// points will be most efficient
this.m_incrementalSavers = new HashMap<Object, ArffSaver>();
this.m_finishedCount = 0;
this.m_incrementalCounter = 0;
}
if (e.getStatus() == InstanceEvent.FORMAT_AVAILABLE) {
// reset if we get a new start of stream from one of streams that
// we've seen a FORMAT_AVAILABLE from previously
if (this.m_completed.containsKey(e.getSource())) {
if (this.m_log != null) {
String msg = this.statusMessagePrefix() + "Resetting appender.";
this.m_log.statusMessage(msg);
this.m_log.logMessage("[Appender] " + msg + " New start of stream detected before " + "all incoming streams have finished!");
}
this.m_completed = new HashMap<Object, Instances>();
this.m_incrementalSavers = new HashMap<Object, ArffSaver>();
this.m_incrementalCounter = 0;
this.m_completeHeader = null;
this.m_finishedCount = 0;
}
this.m_completed.put(e.getSource(), e.getStructure());
if (this.m_completed.size() == this.m_listenees.size()) {
// create mondo header...
try {
if (this.m_log != null) {
String msg = this.statusMessagePrefix() + "Making output header";
this.m_log.statusMessage(msg);
this.m_log.logMessage("[Appender] " + msg);
}
this.m_completeHeader = this.makeOutputHeader();
// notify listeners of output format
this.m_ie.setStructure(this.m_completeHeader);
this.notifyInstanceListeners(this.m_ie);
// now check for any buffered instances...
if (this.m_incrementalSavers.size() > 0) {
// read in and convert these instances now
for (ArffSaver s : this.m_incrementalSavers.values()) {
// finish off the saving process first
s.writeIncremental(null);
File tmpFile = s.retrieveFile();
ArffLoader loader = new ArffLoader();
loader.setFile(tmpFile);
Instances tempStructure = loader.getStructure();
Instance tempLoaded = loader.getNextInstance(tempStructure);
while (tempLoaded != null) {
Instance converted = this.makeOutputInstance(this.m_completeHeader, tempLoaded);
this.m_ie.setStatus(InstanceEvent.INSTANCE_AVAILABLE);
this.m_ie.setInstance(converted);
this.notifyInstanceListeners(this.m_ie);
this.m_incrementalCounter++;
if (this.m_incrementalCounter % 10000 == 0) {
if (this.m_log != null) {
this.m_log.statusMessage(this.statusMessagePrefix() + "Processed " + this.m_incrementalCounter + " instances");
}
}
tempLoaded = loader.getNextInstance(tempStructure);
}
}
this.m_incrementalSavers.clear();
}
} catch (Exception e1) {
String msg = this.statusMessagePrefix() + "ERROR: unable to create output instances structure.";
if (this.m_log != null) {
this.m_log.statusMessage(msg);
this.m_log.logMessage("[Appender] " + e1.getMessage());
}
this.stop();
e1.printStackTrace();
this.m_busy = false;
return;
}
}
this.m_busy = false;
return;
}
if (e.getStatus() == InstanceEvent.BATCH_FINISHED || e.getStatus() == InstanceEvent.INSTANCE_AVAILABLE) {
// get the instance (if available)
Instance currentI = e.getInstance();
if (this.m_completeHeader == null) {
if (currentI != null) {
// save this instance to a temp file
ArffSaver saver = this.m_incrementalSavers.get(e.getSource());
if (saver == null) {
saver = new ArffSaver();
try {
File tmpFile = File.createTempFile("weka", ".arff");
saver.setFile(tmpFile);
saver.setRetrieval(weka.core.converters.Saver.INCREMENTAL);
saver.setInstances(new Instances(currentI.dataset(), 0));
this.m_incrementalSavers.put(e.getSource(), saver);
} catch (IOException e1) {
this.stop();
e1.printStackTrace();
String msg = this.statusMessagePrefix() + "ERROR: unable to save instance to temp file";
if (this.m_log != null) {
this.m_log.statusMessage(msg);
this.m_log.logMessage("[Appender] " + e1.getMessage());
}
this.m_busy = false;
return;
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
try {
saver.writeIncremental(currentI);
if (e.getStatus() == InstanceEvent.BATCH_FINISHED) {
this.m_finishedCount++;
}
} catch (IOException e1) {
this.stop();
e1.printStackTrace();
String msg = this.statusMessagePrefix() + "ERROR: unable to save instance to temp file";
if (this.m_log != null) {
this.m_log.statusMessage(msg);
this.m_log.logMessage("[Appender] " + e1.getMessage());
}
this.m_busy = false;
return;
}
}
} else {
if (currentI != null) {
int code = InstanceEvent.INSTANCE_AVAILABLE;
if (e.getStatus() == InstanceEvent.BATCH_FINISHED) {
this.m_finishedCount++;
if (this.m_finishedCount == this.m_listenees.size()) {
// We're all done!
code = InstanceEvent.BATCH_FINISHED;
}
}
// convert instance and output immediately
Instance newI = this.makeOutputInstance(this.m_completeHeader, currentI);
this.m_ie.setStatus(code);
this.m_ie.setInstance(newI);
this.notifyInstanceListeners(this.m_ie);
this.m_incrementalCounter++;
if (this.m_incrementalCounter % 10000 == 0) {
if (this.m_log != null) {
this.m_log.statusMessage(this.statusMessagePrefix() + "Processed " + this.m_incrementalCounter + " instances");
}
}
if (code == InstanceEvent.BATCH_FINISHED) {
if (this.m_log != null) {
this.m_log.statusMessage(this.statusMessagePrefix() + "Finished");
}
this.m_completed = null;
this.m_incrementalSavers = null;
this.m_incrementalCounter = 0;
this.m_completeHeader = null;
this.m_finishedCount = 0;
}
}
}
}
this.m_busy = false;
}
/**
* Accept and process a test set event
*
* @param e a <code>TestSetEvent</code> value
*/
@Override
public void acceptTestSet(final TestSetEvent e) {
DataSetEvent de = new DataSetEvent(e.getSource(), e.getTestSet());
this.acceptDataSet(de);
}
/**
* Accept and process a training set event
*
* @param e a <code>TrainingSetEvent</code> value
*/
@Override
public void acceptTrainingSet(final TrainingSetEvent e) {
DataSetEvent de = new DataSetEvent(e.getSource(), e.getTrainingSet());
this.acceptDataSet(de);
}
/**
* Accept and process a data set event
*
* @param e a <code>DataSetEvent</code> value
*/
@Override
public synchronized void acceptDataSet(final DataSetEvent e) {
this.m_busy = true;
if (this.m_completed == null) {
// new batch of batches
this.m_completed = new HashMap<Object, Instances>();
this.m_tempBatchFiles = new HashMap<Object, File>();
}
// who is this that's sent us data?
Object source = e.getSource();
if (this.m_completed.containsKey(source)) {
// Can't accept more than one data set from a particular source
if (this.m_log != null && !e.isStructureOnly()) {
String msg = this.statusMessagePrefix() + "Resetting appender.";
this.m_log.statusMessage(msg);
this.m_log.logMessage("[Appender] " + msg + " New batch for an incoming connection " + "detected before " + "all incoming connections have sent data!");
}
this.m_completed = new HashMap<Object, Instances>();
this.m_tempBatchFiles = new HashMap<Object, File>();
}
Instances header = new Instances(e.getDataSet(), 0);
this.m_completed.put(source, header);
// write these instances (serialized) to a tmp file.
try {
File tmpF = File.createTempFile("weka", SerializedInstancesLoader.FILE_EXTENSION);
tmpF.deleteOnExit();
ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(tmpF)));
oos.writeObject(e.getDataSet());
oos.flush();
oos.close();
this.m_tempBatchFiles.put(source, tmpF);
} catch (IOException e1) {
this.stop();
e1.printStackTrace();
String msg = this.statusMessagePrefix() + "ERROR: unable to save batch instances to temp file";
if (this.m_log != null) {
this.m_log.statusMessage(msg);
this.m_log.logMessage("[Appender] " + e1.getMessage());
}
this.m_busy = false;
return;
}
// check to see if we've had one from everyone.
// Not much we can do if one source fails somewhere - won't know this
// fact...
if (this.m_completed.size() == this.m_listenees.size()) {
// process all headers and create mongo header for new output.
// missing values will fill columns that don't exist in particular data
// sets
try {
Instances output = this.makeOutputHeader();
if (this.m_log != null) {
String msg = this.statusMessagePrefix() + "Making output header";
this.m_log.statusMessage(msg);
this.m_log.logMessage("[Appender] " + msg);
}
for (File f : this.m_tempBatchFiles.values()) {
ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(f)));
Instances temp = (Instances) ois.readObject();
ois.close();
// copy each instance over
for (int i = 0; i < temp.numInstances(); i++) {
Instance converted = this.makeOutputInstance(output, temp.instance(i));
output.add(converted);
}
}
DataSetEvent d = new DataSetEvent(this, output);
this.notifyDataListeners(d);
} catch (Exception ex) {
this.stop();
ex.printStackTrace();
String msg = this.statusMessagePrefix() + "ERROR: unable to output appended data set";
if (this.m_log != null) {
this.m_log.statusMessage(msg);
this.m_log.logMessage("[Appender] " + ex.getMessage());
}
}
// finished
this.m_completed = null;
this.m_tempBatchFiles = null;
if (this.m_log != null) {
this.m_log.statusMessage(this.statusMessagePrefix() + "Finished");
}
}
this.m_busy = false;
}
private Instance makeOutputInstance(final Instances output, final Instance source) {
double[] newVals = new double[output.numAttributes()];
for (int i = 0; i < newVals.length; i++) {
newVals[i] = Utils.missingValue();
}
for (int i = 0; i < source.numAttributes(); i++) {
if (!source.isMissing(i)) {
Attribute s = source.attribute(i);
int outputIndex = output.attribute(s.name()).index();
if (s.isNumeric()) {
newVals[outputIndex] = source.value(s);
} else if (s.isString()) {
String sVal = source.stringValue(s);
newVals[outputIndex] = output.attribute(outputIndex).addStringValue(sVal);
} else if (s.isRelationValued()) {
Instances rVal = source.relationalValue(s);
newVals[outputIndex] = output.attribute(outputIndex).addRelation(rVal);
} else if (s.isNominal()) {
String nomVal = source.stringValue(s);
newVals[outputIndex] = output.attribute(outputIndex).indexOfValue(nomVal);
}
}
}
Instance newInst = new DenseInstance(source.weight(), newVals);
newInst.setDataset(output);
return newInst;
}
private Instances makeOutputHeader() throws Exception {
// process each header in turn...
Map<String, Attribute> attLookup = new HashMap<String, Attribute>();
List<Attribute> attList = new ArrayList<Attribute>();
Map<String, Set<String>> nominalLookups = new HashMap<String, Set<String>>();
for (Instances h : this.m_completed.values()) {
for (int i = 0; i < h.numAttributes(); i++) {
Attribute a = h.attribute(i);
if (!attLookup.containsKey(a.name())) {
attLookup.put(a.name(), a);
attList.add(a);
if (a.isNominal()) {
TreeSet<String> nVals = new TreeSet<String>();
for (int j = 0; j < a.numValues(); j++) {
nVals.add(a.value(j));
}
nominalLookups.put(a.name(), nVals);
}
} else {
Attribute storedVersion = attLookup.get(a.name());
if (storedVersion.type() != a.type()) {
// mismatched types between headers - can't continue
throw new Exception("Conflicting types for attribute " + "name '" + a.name() + "' between incoming " + "instance sets");
}
if (storedVersion.isNominal()) {
Set<String> storedVals = nominalLookups.get(a.name());
for (int j = 0; j < a.numValues(); j++) {
storedVals.add(a.value(j));
}
}
}
}
}
ArrayList<Attribute> finalAttList = new ArrayList<Attribute>();
for (Attribute a : attList) {
Attribute newAtt = null;
if (a.isDate()) {
newAtt = new Attribute(a.name(), a.getDateFormat());
} else if (a.isNumeric()) {
newAtt = new Attribute(a.name());
} else if (a.isRelationValued()) {
newAtt = new Attribute(a.name(), a.relation());
} else if (a.isNominal()) {
Set<String> vals = nominalLookups.get(a.name());
List<String> newVals = new ArrayList<String>();
for (String v : vals) {
newVals.add(v);
}
newAtt = new Attribute(a.name(), newVals);
} else if (a.isString()) {
newAtt = new Attribute(a.name(), (List<String>) null);
// transfer all string values
/*
* for (int i = 0; i < a.numValues(); i++) {
* newAtt.addStringValue(a.value(i)); }
*/
}
finalAttList.add(newAtt);
}
Instances outputHeader = new Instances("Appended_" + this.m_listenees.size() + "_sets", finalAttList, 0);
return outputHeader;
}
/**
* Add a data source listener
*
* @param dsl a <code>DataSourceListener</code> value
*/
@Override
public synchronized void addDataSourceListener(final DataSourceListener dsl) {
this.m_dataListeners.add(dsl);
}
/**
* Remove a data source listener
*
* @param dsl a <code>DataSourceListener</code> value
*/
@Override
public synchronized void removeDataSourceListener(final DataSourceListener dsl) {
this.m_dataListeners.remove(dsl);
}
/**
* Add an instance listener
*
* @param tsl an <code>InstanceListener</code> value
*/
@Override
public synchronized void addInstanceListener(final InstanceListener tsl) {
this.m_instanceListeners.add(tsl);
}
/**
* Remove an instance listener
*
* @param tsl an <code>InstanceListener</code> value
*/
@Override
public synchronized void removeInstanceListener(final InstanceListener tsl) {
this.m_instanceListeners.remove(tsl);
}
/**
* Use the default visual representation
*/
@Override
public void useDefaultVisual() {
this.m_visual.loadIcons(BeanVisual.ICON_PATH + "Appender.png", BeanVisual.ICON_PATH + "Appender.png");
this.m_visual.setText("Appender");
}
/**
* Set a new visual representation
*
* @param newVisual a <code>BeanVisual</code> value
*/
@Override
public void setVisual(final BeanVisual newVisual) {
this.m_visual = newVisual;
}
/**
* Get the visual representation
*
* @return a <code>BeanVisual</code> value
*/
@Override
public BeanVisual getVisual() {
return this.m_visual;
}
/**
* Set a custom (descriptive) name for this bean
*
* @param name the name to use
*/
@Override
public void setCustomName(final String name) {
this.m_visual.setText(name);
}
/**
* Get the custom (descriptive) name for this bean (if one has been set)
*
* @return the custom name (or the default name)
*/
@Override
public String getCustomName() {
return this.m_visual.getText();
}
/**
* Stop any processing that the bean might be doing.
*/
@Override
public void stop() {
// tell any upstream listenees to stop
if (this.m_listenees != null && this.m_listenees.size() > 0) {
for (Object l : this.m_listenees.values()) {
if (l instanceof BeanCommon) {
((BeanCommon) l).stop();
}
}
}
this.m_busy = false;
}
/**
* Returns true if. at this time, the bean is busy with some (i.e. perhaps a
* worker thread is performing some calculation).
*
* @return true if the bean is busy.
*/
@Override
public boolean isBusy() {
return this.m_busy;
}
/**
* Set a logger
*
* @param logger a <code>weka.gui.Logger</code> value
*/
@Override
public void setLog(final Logger logger) {
this.m_log = logger;
}
/**
* Returns true if, at this time, the object will accept a connection via the
* named event
*
* @param esd the EventSetDescriptor for the event in question
* @return true if the object will accept a connection
*/
@Override
public boolean connectionAllowed(final EventSetDescriptor esd) {
return this.connectionAllowed(esd.getName());
}
/**
* Returns true if, at this time, the object will accept a connection via the
* named event
*
* @param eventName the name of the event
* @return true if the object will accept a connection
*/
@Override
public boolean connectionAllowed(final String eventName) {
if (!eventName.equals("dataSet") && !eventName.equals("trainingSet") && !eventName.equals("testSet") && !eventName.equals("instance")) {
return false;
}
if (this.m_listeneeTypes.size() == 0) {
return true;
}
if (this.m_listeneeTypes.contains("instance") && !eventName.equals("instance")) {
return false;
}
if (!this.m_listeneeTypes.contains("instance") && eventName.equals("instance")) {
return false;
}
return true;
}
/**
* Notify this object that it has been registered as a listener with a source
* for recieving events described by the named event This object is
* responsible for recording this fact.
*
* @param eventName the event
* @param source the source with which this object has been registered as a
* listener
*/
@Override
public void connectionNotification(final String eventName, final Object source) {
if (this.connectionAllowed(eventName)) {
this.m_listeneeTypes.add(eventName);
this.m_listenees.put(source, source);
}
}
/**
* Notify this object that it has been deregistered as a listener with a
* source for named event. This object is responsible for recording this fact.
*
* @param eventName the event
* @param source the source with which this object has been registered as a
* listener
*/
@Override
public void disconnectionNotification(final String eventName, final Object source) {
this.m_listenees.remove(source);
if (this.m_listenees.size() == 0) {
this.m_listeneeTypes.clear();
}
}
private String statusMessagePrefix() {
return this.getCustomName() + "$" + this.hashCode() + "|";
}
@SuppressWarnings("unchecked")
private void notifyInstanceListeners(final InstanceEvent e) {
List<InstanceListener> l;
synchronized (this) {
l = (List<InstanceListener>) this.m_instanceListeners.clone();
}
if (l.size() > 0) {
for (InstanceListener il : l) {
il.acceptInstance(e);
}
}
}
@SuppressWarnings("unchecked")
private void notifyDataListeners(final DataSetEvent e) {
List<DataSourceListener> l;
synchronized (this) {
l = (List<DataSourceListener>) this.m_dataListeners.clone();
}
if (l.size() > 0) {
for (DataSourceListener ds : l) {
ds.acceptDataSet(e);
}
}
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/AppenderBeanInfo.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/>.
*/
/*
* AppenderBeanInfo.java
* Copyright (C) 2011-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.beans.EventSetDescriptor;
import java.beans.SimpleBeanInfo;
/**
* Bean info class for the appender bean
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision$
*/
public class AppenderBeanInfo extends SimpleBeanInfo {
/**
* Returns the event set descriptors
*
* @return an <code>EventSetDescriptor[]</code> value
*/
@Override
public EventSetDescriptor[] getEventSetDescriptors() {
try {
EventSetDescriptor[] esds = {
new EventSetDescriptor(DataSource.class, "dataSet",
DataSourceListener.class, "acceptDataSet"),
new EventSetDescriptor(DataSource.class, "instance",
InstanceListener.class, "acceptInstance"), };
return esds;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/Associator.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/>.
*/
/*
* Associator.java
* Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.awt.BorderLayout;
import java.beans.EventSetDescriptor;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.EventListener;
import java.util.Hashtable;
import java.util.Vector;
import javax.swing.JPanel;
import weka.associations.Apriori;
import weka.associations.AssociationRules;
import weka.associations.AssociationRulesProducer;
import weka.core.Attribute;
import weka.core.Environment;
import weka.core.EnvironmentHandler;
import weka.core.Instances;
import weka.core.OptionHandler;
import weka.core.Utils;
import weka.gui.Logger;
/**
* Bean that wraps around weka.associations. If used in a non-graphical
* environment, options for the wrapped associator can be provided by setting an
* environment variable: weka.gui.beans.associator.schemeOptions. The value of
* this environment variable needs to be a string containing command-line option
* settings.
*
* @author Mark Hall (mhall at cs dot waikato dot ac dot nz)
* @version $Revision$
* @since 1.0
* @see JPanel
* @see BeanCommon
* @see Visible
* @see WekaWrapper
* @see Serializable
* @see UserRequestAcceptor
* @see TrainingSetListener
* @see DataSourceListener
*/
public class Associator extends JPanel implements BeanCommon, Visible,
WekaWrapper, EventConstraints, Serializable, UserRequestAcceptor,
DataSourceListener, TrainingSetListener, ConfigurationProducer,
StructureProducer, EnvironmentHandler {
/** for serialization */
private static final long serialVersionUID = -7843500322130210057L;
protected BeanVisual m_visual = new BeanVisual("Associator",
BeanVisual.ICON_PATH + "DefaultAssociator.gif", BeanVisual.ICON_PATH
+ "DefaultAssociator_animated.gif");
private static int IDLE = 0;
private static int BUILDING_MODEL = 1;
private int m_state = IDLE;
private Thread m_buildThread = null;
/**
* Global info for the wrapped associator (if it exists).
*/
protected String m_globalInfo;
/**
* Objects talking to us
*/
private final Hashtable<String, Object> m_listenees = new Hashtable<String, Object>();
/**
* Objects listening for text events
*/
private final Vector<EventListener> m_textListeners = new Vector<EventListener>();
/**
* Objects listening for graph events
*/
private final Vector<EventListener> m_graphListeners = new Vector<EventListener>();
/** The objects listening for batchAssociationRules events **/
private final Vector<BatchAssociationRulesListener> m_rulesListeners = new Vector<BatchAssociationRulesListener>();
private weka.associations.Associator m_Associator = new Apriori();
private transient Logger m_log = null;
/** The environment variables */
private transient Environment m_env = null;
/**
* Global info (if it exists) for the wrapped classifier
*
* @return the global info
*/
public String globalInfo() {
return m_globalInfo;
}
/**
* Creates a new <code>Associator</code> instance.
*/
public Associator() {
setLayout(new BorderLayout());
add(m_visual, BorderLayout.CENTER);
setAssociator(m_Associator);
}
/**
* Set environment variables to use.
*
* @param env the environment variables to use
*/
@Override
public void setEnvironment(Environment env) {
m_env = env;
}
/**
* Set a custom (descriptive) name for this bean
*
* @param name the name to use
*/
@Override
public void setCustomName(String name) {
m_visual.setText(name);
}
/**
* Get the custom (descriptive) name for this bean (if one has been set)
*
* @return the custom name (or the default name)
*/
@Override
public String getCustomName() {
return m_visual.getText();
}
/**
* Set the associator for this wrapper
*
* @param c a <code>weka.associations.Associator</code> value
*/
public void setAssociator(weka.associations.Associator c) {
boolean loadImages = true;
if (c.getClass().getName().compareTo(m_Associator.getClass().getName()) == 0) {
loadImages = false;
}
m_Associator = c;
String associatorName = c.getClass().toString();
associatorName = associatorName.substring(
associatorName.lastIndexOf('.') + 1, associatorName.length());
if (loadImages) {
if (!m_visual.loadIcons(BeanVisual.ICON_PATH + associatorName + ".gif",
BeanVisual.ICON_PATH + associatorName + "_animated.gif")) {
useDefaultVisual();
}
}
m_visual.setText(associatorName);
// get global info
m_globalInfo = KnowledgeFlowApp.getGlobalInfo(m_Associator);
}
/**
* Get the associator currently set for this wrapper
*
* @return a <code>weka.associations.Associator</code> value
*/
public weka.associations.Associator getAssociator() {
return m_Associator;
}
/**
* Sets the algorithm (associator) for this bean
*
* @param algorithm an <code>Object</code> value
* @exception IllegalArgumentException if an error occurs
*/
@Override
public void setWrappedAlgorithm(Object algorithm) {
if (!(algorithm instanceof weka.associations.Associator)) {
throw new IllegalArgumentException(algorithm.getClass() + " : incorrect "
+ "type of algorithm (Associator)");
}
setAssociator((weka.associations.Associator) algorithm);
}
/**
* Returns the wrapped associator
*
* @return an <code>Object</code> value
*/
@Override
public Object getWrappedAlgorithm() {
return getAssociator();
}
/**
* Accept a training set
*
* @param e a <code>TrainingSetEvent</code> value
*/
@Override
public void acceptTrainingSet(TrainingSetEvent e) {
// construct and pass on a DataSetEvent
Instances trainingSet = e.getTrainingSet();
DataSetEvent dse = new DataSetEvent(this, trainingSet);
acceptDataSet(dse);
}
@Override
public void acceptDataSet(final DataSetEvent e) {
if (e.isStructureOnly()) {
// no need to build an associator, just absorb and return
return;
}
if (m_buildThread == null) {
try {
if (m_state == IDLE) {
synchronized (this) {
m_state = BUILDING_MODEL;
}
final Instances trainingData = e.getDataSet();
// final String oldText = m_visual.getText();
m_buildThread = new Thread() {
@SuppressWarnings("deprecation")
@Override
public void run() {
try {
if (trainingData != null) {
m_visual.setAnimated();
// m_visual.setText("Building model...");
if (m_log != null) {
m_log.statusMessage(statusMessagePrefix()
+ "Building model...");
}
buildAssociations(trainingData);
if (m_textListeners.size() > 0) {
String modelString = m_Associator.toString();
String titleString = m_Associator.getClass().getName();
titleString = titleString.substring(
titleString.lastIndexOf('.') + 1, titleString.length());
modelString = "=== Associator model ===\n\n" + "Scheme: "
+ titleString + "\n" + "Relation: "
+ trainingData.relationName() + "\n\n" + modelString;
titleString = "Model: " + titleString;
TextEvent nt = new TextEvent(Associator.this, modelString,
titleString);
notifyTextListeners(nt);
}
if (m_Associator instanceof weka.core.Drawable
&& m_graphListeners.size() > 0) {
String grphString = ((weka.core.Drawable) m_Associator)
.graph();
int grphType = ((weka.core.Drawable) m_Associator)
.graphType();
String grphTitle = m_Associator.getClass().getName();
grphTitle = grphTitle.substring(
grphTitle.lastIndexOf('.') + 1, grphTitle.length());
grphTitle = " (" + e.getDataSet().relationName() + ") "
+ grphTitle;
GraphEvent ge = new GraphEvent(Associator.this, grphString,
grphTitle, grphType);
notifyGraphListeners(ge);
}
if ((m_Associator instanceof AssociationRulesProducer)
&& m_rulesListeners.size() > 0) {
AssociationRules rules = ((AssociationRulesProducer) m_Associator)
.getAssociationRules();
BatchAssociationRulesEvent bre = new BatchAssociationRulesEvent(
Associator.this, rules);
notifyRulesListeners(bre);
}
}
} catch (Exception ex) {
Associator.this.stop();
if (m_log != null) {
m_log.statusMessage(statusMessagePrefix()
+ "ERROR (See log for details)");
m_log.logMessage("[Associator] " + statusMessagePrefix()
+ " problem training associator. " + ex.getMessage());
}
ex.printStackTrace();
} finally {
// m_visual.setText(oldText);
m_visual.setStatic();
m_state = IDLE;
if (isInterrupted()) {
if (m_log != null) {
String titleString = m_Associator.getClass().getName();
titleString = titleString.substring(
titleString.lastIndexOf('.') + 1, titleString.length());
m_log.logMessage("[Associator] " + statusMessagePrefix()
+ " Build associator interrupted!");
m_log.statusMessage(statusMessagePrefix() + "INTERRUPTED");
}
} else {
if (m_log != null) {
m_log.statusMessage(statusMessagePrefix() + "Finished.");
}
}
block(false);
}
}
};
m_buildThread.setPriority(Thread.MIN_PRIORITY);
m_buildThread.start();
// make sure the thread is still running before we block
// if (m_buildThread.isAlive()) {
block(true);
// }
m_buildThread = null;
m_state = IDLE;
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
private void buildAssociations(Instances data) throws Exception {
// see if there is an environment variable with
// options for the associator
if (m_env != null && m_Associator instanceof OptionHandler) {
String opts = m_env
.getVariableValue("weka.gui.beans.associator.schemeOptions");
if (opts != null && opts.length() > 0) {
String[] options = Utils.splitOptions(opts);
if (options.length > 0) {
try {
((OptionHandler) m_Associator).setOptions(options);
} catch (Exception ex) {
String warningMessage = "[Associator] WARNING: unable to set options \""
+ opts + "\"for " + m_Associator.getClass().getName();
if (m_log != null) {
m_log.logMessage(warningMessage);
} else {
System.err.print(warningMessage);
}
}
}
}
}
m_Associator.buildAssociations(data);
}
/**
* Sets the visual appearance of this wrapper bean
*
* @param newVisual a <code>BeanVisual</code> value
*/
@Override
public void setVisual(BeanVisual newVisual) {
m_visual = newVisual;
}
/**
* Gets the visual appearance of this wrapper bean
*/
@Override
public BeanVisual getVisual() {
return m_visual;
}
/**
* Use the default visual appearance for this bean
*/
@Override
public void useDefaultVisual() {
m_visual.loadIcons(BeanVisual.ICON_PATH + "DefaultAssociator.gif",
BeanVisual.ICON_PATH + "DefaultAssociator_animated.gif");
}
/**
* Add a batch association rules listener
*
* @param al a <code>BatchAssociationRulesListener</code>
*/
public synchronized void addBatchAssociationRulesListener(
BatchAssociationRulesListener al) {
m_rulesListeners.add(al);
}
/**
* Remove a batch association rules listener
*
* @param al a <code>BatchAssociationRulesListener</code>
*/
public synchronized void removeBatchAssociationRulesListener(
BatchAssociationRulesListener al) {
m_rulesListeners.remove(al);
}
/**
* Add a text listener
*
* @param cl a <code>TextListener</code> value
*/
public synchronized void addTextListener(TextListener cl) {
m_textListeners.addElement(cl);
}
/**
* Remove a text listener
*
* @param cl a <code>TextListener</code> value
*/
public synchronized void removeTextListener(TextListener cl) {
m_textListeners.remove(cl);
}
/**
* Add a graph listener
*
* @param cl a <code>GraphListener</code> value
*/
public synchronized void addGraphListener(GraphListener cl) {
m_graphListeners.addElement(cl);
}
/**
* Remove a graph listener
*
* @param cl a <code>GraphListener</code> value
*/
public synchronized void removeGraphListener(GraphListener cl) {
m_graphListeners.remove(cl);
}
/**
* We don't have to keep track of configuration listeners (see the
* documentation for ConfigurationListener/ConfigurationEvent).
*
* @param cl a ConfigurationListener.
*/
@Override
public synchronized void addConfigurationListener(ConfigurationListener cl) {
}
/**
* We don't have to keep track of configuration listeners (see the
* documentation for ConfigurationListener/ConfigurationEvent).
*
* @param cl a ConfigurationListener.
*/
@Override
public synchronized void removeConfigurationListener(ConfigurationListener cl) {
}
/**
* Notify all text listeners of a text event
*
* @param ge a <code>TextEvent</code> value
*/
@SuppressWarnings("unchecked")
private void notifyTextListeners(TextEvent ge) {
Vector<EventListener> l;
synchronized (this) {
l = (Vector<EventListener>) m_textListeners.clone();
}
if (l.size() > 0) {
for (int i = 0; i < l.size(); i++) {
((TextListener) l.elementAt(i)).acceptText(ge);
}
}
}
/**
* Notify all graph listeners of a graph event
*
* @param ge a <code>GraphEvent</code> value
*/
@SuppressWarnings("unchecked")
private void notifyGraphListeners(GraphEvent ge) {
Vector<EventListener> l;
synchronized (this) {
l = (Vector<EventListener>) m_graphListeners.clone();
}
if (l.size() > 0) {
for (int i = 0; i < l.size(); i++) {
((GraphListener) l.elementAt(i)).acceptGraph(ge);
}
}
}
/**
* Notify all batch association rules listeners of a rules event.
*
* @param are a <code>BatchAssociationRulesEvent</code> value
*/
@SuppressWarnings("unchecked")
private void notifyRulesListeners(BatchAssociationRulesEvent are) {
Vector<BatchAssociationRulesListener> l;
synchronized (this) {
l = (Vector<BatchAssociationRulesListener>) m_rulesListeners.clone();
for (int i = 0; i < l.size(); i++) {
l.get(i).acceptAssociationRules(are);
}
}
}
/**
* Returns true if, at this time, the object will accept a connection with
* respect to the named event
*
* @param eventName the event
* @return true if the object will accept a connection
*/
@Override
public boolean connectionAllowed(String eventName) {
if (m_listenees.containsKey(eventName)) {
return false;
}
return true;
}
/**
* Returns true if, at this time, the object will accept a connection
* according to the supplied EventSetDescriptor
*
* @param esd the EventSetDescriptor
* @return true if the object will accept a connection
*/
@Override
public boolean connectionAllowed(EventSetDescriptor esd) {
return connectionAllowed(esd.getName());
}
/**
* Notify this object that it has been registered as a listener with a source
* with respect to the named event
*
* @param eventName the event
* @param source the source with which this object has been registered as a
* listener
*/
@Override
public synchronized void connectionNotification(String eventName,
Object source) {
if (connectionAllowed(eventName)) {
m_listenees.put(eventName, source);
}
}
/**
* Notify this object that it has been deregistered as a listener with a
* source with respect to the supplied event name
*
* @param eventName the event
* @param source the source with which this object has been registered as a
* listener
*/
@Override
public synchronized void disconnectionNotification(String eventName,
Object source) {
m_listenees.remove(eventName);
}
/**
* Function used to stop code that calls acceptTrainingSet. This is needed as
* classifier construction is performed inside a separate thread of execution.
*
* @param tf a <code>boolean</code> value
*/
private synchronized void block(boolean tf) {
if (tf) {
try {
// only block if thread is still doing something useful!
if (m_buildThread.isAlive() && m_state != IDLE) {
wait();
}
} catch (InterruptedException ex) {
}
} else {
notifyAll();
}
}
/**
* Returns true if. at this time, the bean is busy with some (i.e. perhaps a
* worker thread is performing some calculation).
*
* @return true if the bean is busy.
*/
@Override
public boolean isBusy() {
return (m_buildThread != null);
}
/**
* Stop any associator action
*/
@SuppressWarnings("deprecation")
@Override
public void stop() {
// tell all listenees (upstream beans) to stop
Enumeration<String> en = m_listenees.keys();
while (en.hasMoreElements()) {
Object tempO = m_listenees.get(en.nextElement());
if (tempO instanceof BeanCommon) {
((BeanCommon) tempO).stop();
}
}
// stop the build thread
if (m_buildThread != null) {
m_buildThread.interrupt();
m_buildThread.stop();
m_buildThread = null;
m_visual.setStatic();
}
}
/**
* Set a logger
*
* @param logger a <code>Logger</code> value
*/
@Override
public void setLog(Logger logger) {
m_log = logger;
}
/**
* Return an enumeration of requests that can be made by the user
*
* @return an <code>Enumeration</code> value
*/
@Override
public Enumeration<String> enumerateRequests() {
Vector<String> newVector = new Vector<String>(0);
if (m_buildThread != null) {
newVector.addElement("Stop");
}
return newVector.elements();
}
/**
* Perform a particular request
*
* @param request the request to perform
* @exception IllegalArgumentException if an error occurs
*/
@Override
public void performRequest(String request) {
if (request.compareTo("Stop") == 0) {
stop();
} else {
throw new IllegalArgumentException(request
+ " not supported (Associator)");
}
}
/**
* Returns true, if at the current time, the event described by the supplied
* event descriptor could be generated.
*
* @param esd an <code>EventSetDescriptor</code> value
* @return a <code>boolean</code> value
*/
public boolean eventGeneratable(EventSetDescriptor esd) {
String eventName = esd.getName();
return eventGeneratable(eventName);
}
/**
* Get the structure of the output encapsulated in the named event. If the
* structure can't be determined in advance of seeing input, or this
* StructureProducer does not generate the named event, null should be
* returned.
*
* @param eventName the name of the output event that encapsulates the
* requested output.
*
* @return the structure of the output encapsulated in the named event or null
* if it can't be determined in advance of seeing input or the named
* event is not generated by this StructureProduce.
*/
@Override
public Instances getStructure(String eventName) {
Instances structure = null;
if (eventName.equals("text")) {
ArrayList<Attribute> attInfo = new ArrayList<Attribute>();
attInfo.add(new Attribute("Title", (ArrayList<String>) null));
attInfo.add(new Attribute("Text", (ArrayList<String>) null));
structure = new Instances("TextEvent", attInfo, 0);
} else if (eventName.equals("batchAssociationRules")) {
if (m_Associator != null
&& m_Associator instanceof AssociationRulesProducer) {
// we make the assumption here that consumers of
// batchAssociationRules events will utilize a structure
// consisting of the RHS of the rule (String), LHS of the
// rule (String) and one numeric attribute for each metric
// associated with the rules.
String[] metricNames = ((AssociationRulesProducer) m_Associator)
.getRuleMetricNames();
ArrayList<Attribute> attInfo = new ArrayList<Attribute>();
attInfo.add(new Attribute("LHS", (ArrayList<String>) null));
attInfo.add(new Attribute("RHS", (ArrayList<String>) null));
attInfo.add(new Attribute("Support"));
for (String metricName : metricNames) {
attInfo.add(new Attribute(metricName));
}
structure = new Instances("batchAssociationRulesEvent", attInfo, 0);
}
}
return structure;
}
/**
* Returns true, if at the current time, the named event could be generated.
* Assumes that the supplied event name is an event that could be generated by
* this bean
*
* @param eventName the name of the event in question
* @return true if the named event could be generated at this point in time
*/
@Override
public boolean eventGeneratable(String eventName) {
if (eventName.compareTo("text") == 0 || eventName.compareTo("graph") == 0
|| eventName.equals("batchAssociationRules")) {
if (!m_listenees.containsKey("dataSet")
&& !m_listenees.containsKey("trainingSet")) {
return false;
}
Object source = m_listenees.get("trainingSet");
if (source != null && source instanceof EventConstraints) {
if (!((EventConstraints) source).eventGeneratable("trainingSet")) {
return false;
}
}
source = m_listenees.get("dataSet");
if (source != null && source instanceof EventConstraints) {
if (!((EventConstraints) source).eventGeneratable("dataSet")) {
return false;
}
}
if (eventName.compareTo("graph") == 0
&& !(m_Associator instanceof weka.core.Drawable)) {
return false;
}
if (eventName.equals("batchAssociationRules")) {
if (!(m_Associator instanceof AssociationRulesProducer)) {
return false;
}
if (!((AssociationRulesProducer) m_Associator).canProduceRules()) {
return false;
}
}
}
return true;
}
private String statusMessagePrefix() {
return getCustomName()
+ "$"
+ hashCode()
+ "|"
+ ((m_Associator instanceof OptionHandler && Utils.joinOptions(
((OptionHandler) m_Associator).getOptions()).length() > 0) ? Utils
.joinOptions(((OptionHandler) m_Associator).getOptions()) + "|" : "");
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/AssociatorBeanInfo.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/>.
*/
/*
* AssociatorBeanInfo.java
* Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.beans.BeanDescriptor;
import java.beans.EventSetDescriptor;
import java.beans.SimpleBeanInfo;
/**
* BeanInfo class for the Associator wrapper bean
*
* @author Mark Hall (mhall at cs dot waikato dot ac dot nz)
* @version $Revision$
*/
public class AssociatorBeanInfo extends SimpleBeanInfo {
public EventSetDescriptor [] getEventSetDescriptors() {
try {
EventSetDescriptor [] esds = {
new EventSetDescriptor(Associator.class,
"text",
TextListener.class,
"acceptText"),
new EventSetDescriptor(Associator.class,
"graph",
GraphListener.class,
"acceptGraph"),
new EventSetDescriptor(Associator.class,
"configuration",
ConfigurationListener.class,
"acceptConfiguration"),
new EventSetDescriptor(Associator.class,
"batchAssociationRules",
BatchAssociationRulesListener.class,
"acceptAssociationRules")
};
return esds;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
/**
* Get the bean descriptor for this bean
*
* @return a <code>BeanDescriptor</code> value
*/
public BeanDescriptor getBeanDescriptor() {
return new BeanDescriptor(weka.gui.beans.Associator.class,
AssociatorCustomizer.class);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/AssociatorCustomizer.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/>.
*/
/*
* AssociatorCustomizer.java
* Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import javax.swing.JButton;
import javax.swing.JPanel;
import weka.gui.GenericObjectEditor;
import weka.gui.PropertySheetPanel;
/**
* GUI customizer for the associator wrapper bean
*
* @author Mark Hall (mhall at cs dot waikato dot ac dot nz)
* @version $Revision$
*/
public class AssociatorCustomizer
extends JPanel
implements BeanCustomizer, CustomizerCloseRequester {
/** for serialization */
private static final long serialVersionUID = 5767664969353495974L;
static {
GenericObjectEditor.registerEditors();
}
private PropertyChangeSupport m_pcSupport =
new PropertyChangeSupport(this);
private weka.gui.beans.Associator m_dsAssociator;
/* private GenericObjectEditor m_ClassifierEditor =
new GenericObjectEditor(true); */
private PropertySheetPanel m_AssociatorEditor =
new PropertySheetPanel();
protected Window m_parentWindow;
/** Backup is user presses cancel */
private weka.associations.Associator m_backup;
private ModifyListener m_modifyListener;
public AssociatorCustomizer() {
setLayout(new BorderLayout());
add(m_AssociatorEditor, BorderLayout.CENTER);
JPanel butHolder = new JPanel();
butHolder.setLayout(new GridLayout(1,2));
JButton OKBut = new JButton("OK");
OKBut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (m_modifyListener != null) {
m_modifyListener.setModifiedStatus(AssociatorCustomizer.this, true);
}
m_parentWindow.dispose();
}
});
JButton CancelBut = new JButton("Cancel");
CancelBut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// cancel requested, so revert to backup and then
// close the dialog
if (m_backup != null) {
m_dsAssociator.setAssociator(m_backup);
}
if (m_modifyListener != null) {
m_modifyListener.setModifiedStatus(AssociatorCustomizer.this, false);
}
m_parentWindow.dispose();
}
});
butHolder.add(OKBut);
butHolder.add(CancelBut);
add(butHolder, BorderLayout.SOUTH);
}
/**
* Set the classifier object to be edited
*
* @param object an <code>Object</code> value
*/
public void setObject(Object object) {
m_dsAssociator = (weka.gui.beans.Associator)object;
// System.err.println(Utils.joinOptions(((OptionHandler)m_dsClassifier.getClassifier()).getOptions()));
try {
m_backup =
(weka.associations.Associator)GenericObjectEditor.makeCopy(m_dsAssociator.getAssociator());
} catch (Exception ex) {
// ignore
}
m_AssociatorEditor.setTarget(m_dsAssociator.getAssociator());
}
/**
* Add a property change listener
*
* @param pcl a <code>PropertyChangeListener</code> value
*/
public void addPropertyChangeListener(PropertyChangeListener pcl) {
m_pcSupport.addPropertyChangeListener(pcl);
}
/**
* Remove a property change listener
*
* @param pcl a <code>PropertyChangeListener</code> value
*/
public void removePropertyChangeListener(PropertyChangeListener pcl) {
m_pcSupport.removePropertyChangeListener(pcl);
}
public void setParentWindow(Window parent) {
m_parentWindow = parent;
}
@Override
public void setModifiedListener(ModifyListener l) {
m_modifyListener = l;
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/AttributeSummarizer.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/>.
*/
/*
* AttributeSummarizer.java
* Copyright (C) 2003-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Vector;
import javax.swing.BorderFactory;
import javax.swing.DefaultComboBoxModel;
import javax.swing.Icon;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import weka.core.Attribute;
import weka.core.Environment;
import weka.core.Instance;
import weka.core.Instances;
import weka.gui.AttributeVisualizationPanel;
/**
* Bean that encapsulates displays bar graph summaries for attributes in a data
* set.
*
* @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a>
* @version $Revision$
*/
public class AttributeSummarizer extends DataVisualizer implements
KnowledgeFlowApp.KFPerspective {
/** for serialization */
private static final long serialVersionUID = -294354961169372758L;
/**
* The number of plots horizontally in the display
*/
protected int m_gridWidth = 4;
/**
* The maximum number of plots to show
*/
protected int m_maxPlots = 100;
/**
* Index on which to color the plots.
*/
protected int m_coloringIndex = -1;
protected boolean m_showClassCombo = false;
protected boolean m_runningAsPerspective = false;
protected boolean m_activePerspective = false;
protected transient List<AttributeVisualizationPanel> m_plots;
/**
* Creates a new <code>AttributeSummarizer</code> instance.
*/
public AttributeSummarizer() {
useDefaultVisual();
m_visual.setText("AttributeSummarizer");
// java.awt.GraphicsEnvironment ge =
// java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment();
if (!GraphicsEnvironment.isHeadless()) {
appearanceFinal();
}
}
/**
* Global info for this bean
*
* @return a <code>String</code> value
*/
@Override
public String globalInfo() {
return "Plot summary bar charts for incoming data/training/test sets.";
}
/**
* Set the coloring index for the attribute summary plots
*
* @param ci an <code>int</code> value
*/
public void setColoringIndex(int ci) {
m_coloringIndex = ci;
}
/**
* Return the coloring index for the attribute summary plots
*
* @return an <code>int</code> value
*/
public int getColoringIndex() {
return m_coloringIndex;
}
/**
* Set the width of the grid of plots
*
* @param gw the width of the grid
*/
public void setGridWidth(int gw) {
if (gw > 0) {
m_bcSupport.firePropertyChange("gridWidth", new Integer(m_gridWidth),
new Integer(gw));
m_gridWidth = gw;
}
}
/**
* Get the width of the grid of plots
*
* @return the grid width
*/
public int getGridWidth() {
return m_gridWidth;
}
/**
* Set the maximum number of plots to display
*
* @param mp the number of plots to display
*/
public void setMaxPlots(int mp) {
if (mp > 0) {
m_bcSupport.firePropertyChange("maxPlots", new Integer(m_maxPlots),
new Integer(mp));
m_maxPlots = mp;
}
}
/**
* Get the number of plots to display
*
* @return the number of plots to display
*/
public int getMaxPlots() {
return m_maxPlots;
}
/**
* Set whether the appearance of this bean should be design or application
*
* @param design true if bean should appear in design mode
*/
public void setDesign(boolean design) {
m_design = true;
appearanceDesign();
}
@Override
protected void appearanceDesign() {
removeAll();
setLayout(new BorderLayout());
add(m_visual, BorderLayout.CENTER);
}
@Override
protected void appearanceFinal() {
removeAll();
setLayout(new BorderLayout());
}
@Override
protected void setUpFinal() {
removeAll();
if (m_visualizeDataSet == null) {
return;
}
if (!m_runningAsPerspective || m_activePerspective) {
final JScrollPane hp = makePanel();
add(hp, BorderLayout.CENTER);
if (m_showClassCombo) {
Vector<String> atts = new Vector<String>();
for (int i = 0; i < m_visualizeDataSet.numAttributes(); i++) {
atts.add("("
+ Attribute.typeToStringShort(m_visualizeDataSet.attribute(i))
+ ") " + m_visualizeDataSet.attribute(i).name());
}
final JComboBox classCombo = new JComboBox();
classCombo.setModel(new DefaultComboBoxModel(atts));
if (atts.size() > 0) {
if (m_visualizeDataSet.classIndex() < 0) {
classCombo.setSelectedIndex(atts.size() - 1);
} else {
classCombo.setSelectedIndex(m_visualizeDataSet.classIndex());
}
classCombo.setEnabled(true);
for (int i = 0; i < m_plots.size(); i++) {
m_plots.get(i).setColoringIndex(classCombo.getSelectedIndex());
}
}
JPanel comboHolder = new JPanel();
comboHolder.setLayout(new BorderLayout());
JPanel tempHolder = new JPanel();
tempHolder.setLayout(new BorderLayout());
tempHolder.add(new JLabel("Class: "), BorderLayout.WEST);
tempHolder.add(classCombo, BorderLayout.EAST);
comboHolder.add(tempHolder, BorderLayout.WEST);
add(comboHolder, BorderLayout.NORTH);
classCombo.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int selected = classCombo.getSelectedIndex();
if (selected >= 0) {
for (int i = 0; i < m_plots.size(); i++) {
m_plots.get(i).setColoringIndex(selected);
}
}
}
});
}
}
}
/**
* Use the default appearance for this bean
*/
@Override
public void useDefaultVisual() {
m_visual.loadIcons(BeanVisual.ICON_PATH + "AttributeSummarizer.gif",
BeanVisual.ICON_PATH + "AttributeSummarizer_animated.gif");
}
/**
* Return an enumeration of actions that the user can ask this bean to perform
*
* @return an <code>Enumeration</code> value
*/
@Override
public Enumeration<String> enumerateRequests() {
Vector<String> newVector = new Vector<String>(0);
if (m_visualizeDataSet != null) {
newVector.addElement("Show summaries");
}
return newVector.elements();
}
private JScrollPane makePanel() {
String fontFamily = this.getFont().getFamily();
Font newFont = new Font(fontFamily, Font.PLAIN, 10);
JPanel hp = new JPanel();
hp.setFont(newFont);
int numPlots = Math.min(m_visualizeDataSet.numAttributes(), m_maxPlots);
int gridHeight = numPlots / m_gridWidth;
if (numPlots % m_gridWidth != 0) {
gridHeight++;
}
hp.setLayout(new GridLayout(gridHeight, 4));
m_plots = new ArrayList<AttributeVisualizationPanel>();
for (int i = 0; i < numPlots; i++) {
JPanel temp = new JPanel();
temp.setLayout(new BorderLayout());
temp.setBorder(BorderFactory.createTitledBorder(m_visualizeDataSet
.attribute(i).name()));
AttributeVisualizationPanel ap = new AttributeVisualizationPanel();
m_plots.add(ap);
ap.setInstances(m_visualizeDataSet);
if (m_coloringIndex < 0 && m_visualizeDataSet.classIndex() >= 0) {
ap.setColoringIndex(m_visualizeDataSet.classIndex());
} else {
ap.setColoringIndex(m_coloringIndex);
}
temp.add(ap, BorderLayout.CENTER);
ap.setAttribute(i);
hp.add(temp);
}
Dimension d = new Dimension(830, gridHeight * 100);
hp.setMinimumSize(d);
hp.setMaximumSize(d);
hp.setPreferredSize(d);
JScrollPane scroller = new JScrollPane(hp);
return scroller;
}
/**
* Set a bean context for this bean
*
* @param bc a <code>BeanContext</code> value
*/
/*
* public void setBeanContext(BeanContext bc) { m_beanContext = bc; m_design =
* m_beanContext.isDesignTime(); if (m_design) { appearanceDesign(); } }
*/
/**
* Set instances for this bean. This method is a convenience method for
* clients who use this component programatically
*
* @param inst an <code>Instances</code> value
* @exception Exception if an error occurs
*/
@Override
public void setInstances(Instances inst) throws Exception {
if (m_design) {
throw new Exception("This method is not to be used during design "
+ "time. It is meant to be used if this "
+ "bean is being used programatically as as "
+ "stand alone component.");
}
m_visualizeDataSet = inst;
setUpFinal();
}
/**
* Returns true if this perspective accepts instances
*
* @return true if this perspective can accept instances
*/
@Override
public boolean acceptsInstances() {
return true;
}
/**
* Get the title of this perspective
*
* @return the title of this perspective
*/
@Override
public String getPerspectiveTitle() {
return "Attribute summary";
}
/**
* Get the tool tip text for this perspective.
*
* @return the tool tip text for this perspective
*/
@Override
public String getPerspectiveTipText() {
return "Matrix of attribute summary histograms";
}
/**
* Get the icon for this perspective.
*
* @return the Icon for this perspective (or null if the perspective does not
* have an icon)
*/
@Override
public Icon getPerspectiveIcon() {
java.awt.Image pic = null;
java.net.URL imageURL = this.getClass().getClassLoader()
.getResource("weka/gui/beans/icons/chart_bar.png");
if (imageURL == null) {
} else {
pic = java.awt.Toolkit.getDefaultToolkit().getImage(imageURL);
}
return new javax.swing.ImageIcon(pic);
}
/**
* Set active status of this perspective. True indicates that this perspective
* is the visible active perspective in the KnowledgeFlow
*
* @param active true if this perspective is the active one
*/
@Override
public void setActive(boolean active) {
m_activePerspective = active;
m_plots = null;
setUpFinal();
}
/**
* Set whether this perspective is "loaded" - i.e. whether or not the user has
* opted to have it available in the perspective toolbar. The perspective can
* make the decision as to allocating or freeing resources on the basis of
* this.
*
* @param loaded true if the perspective is available in the perspective
* toolbar of the KnowledgeFlow
*/
@Override
public void setLoaded(boolean loaded) {
}
/**
* Set a reference to the main KnowledgeFlow perspective - i.e. the
* perspective that manages flow layouts.
*
* @param main the main KnowledgeFlow perspective.
*/
@Override
public void setMainKFPerspective(KnowledgeFlowApp.MainKFPerspective main) {
m_showClassCombo = true;
m_runningAsPerspective = true;
}
/**
* Perform a named user request
*
* @param request a string containing the name of the request to perform
* @exception IllegalArgumentException if request is not supported
*/
@Override
public void performRequest(String request) {
if (m_design == false) {
setUpFinal();
return;
}
if (request.compareTo("Show summaries") == 0) {
try {
// popup matrix panel
if (!m_framePoppedUp) {
m_framePoppedUp = true;
final JScrollPane holderP = makePanel();
final javax.swing.JFrame jf = new javax.swing.JFrame("Visualize");
jf.setSize(800, 600);
jf.getContentPane().setLayout(new BorderLayout());
jf.getContentPane().add(holderP, BorderLayout.CENTER);
jf.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
jf.dispose();
m_framePoppedUp = false;
}
});
jf.setVisible(true);
m_popupFrame = jf;
} else {
m_popupFrame.toFront();
}
} catch (Exception ex) {
ex.printStackTrace();
m_framePoppedUp = false;
}
} else {
throw new IllegalArgumentException(request
+ " not supported (AttributeSummarizer)");
}
}
@Override
protected void renderOffscreenImage(DataSetEvent e) {
if (m_env == null) {
m_env = Environment.getSystemWide();
}
if (m_imageListeners.size() > 0 && !m_processingHeadlessEvents) {
// configure the renderer (if necessary)
setupOffscreenRenderer();
m_offscreenPlotData = new ArrayList<Instances>();
Instances predictedI = e.getDataSet();
if (predictedI.classIndex() >= 0
&& predictedI.classAttribute().isNominal()) {
// set up multiple series - one for each class
Instances[] classes = new Instances[predictedI.numClasses()];
for (int i = 0; i < predictedI.numClasses(); i++) {
classes[i] = new Instances(predictedI, 0);
classes[i].setRelationName(predictedI.classAttribute().value(i));
}
for (int i = 0; i < predictedI.numInstances(); i++) {
Instance current = predictedI.instance(i);
classes[(int) current.classValue()].add((Instance) current.copy());
}
for (Instances classe : classes) {
m_offscreenPlotData.add(classe);
}
} else {
m_offscreenPlotData.add(new Instances(predictedI));
}
List<String> options = new ArrayList<String>();
String additional = m_additionalOptions;
if (m_additionalOptions != null && m_additionalOptions.length() > 0) {
try {
additional = m_env.substitute(additional);
} catch (Exception ex) {
}
}
if (additional != null && additional.indexOf("-color") < 0) {
// for WekaOffscreenChartRenderer only
if (additional.length() > 0) {
additional += ",";
}
if (predictedI.classIndex() >= 0) {
additional += "-color=" + predictedI.classAttribute().name();
} else {
additional += "-color=/last";
}
}
String[] optionsParts = additional.split(",");
for (String p : optionsParts) {
options.add(p.trim());
}
// only need the x-axis (used to specify the attribute to plot)
String xAxis = m_xAxis;
try {
xAxis = m_env.substitute(xAxis);
} catch (Exception ex) {
}
String width = m_width;
String height = m_height;
int defWidth = 500;
int defHeight = 400;
try {
width = m_env.substitute(width);
height = m_env.substitute(height);
defWidth = Integer.parseInt(width);
defHeight = Integer.parseInt(height);
} catch (Exception ex) {
}
try {
BufferedImage osi = m_offscreenRenderer.renderHistogram(defWidth,
defHeight, m_offscreenPlotData, xAxis, options);
ImageEvent ie = new ImageEvent(this, osi);
notifyImageListeners(ie);
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
public static void main(String[] args) {
try {
if (args.length != 1) {
System.err.println("Usage: AttributeSummarizer <dataset>");
System.exit(1);
}
java.io.Reader r = new java.io.BufferedReader(new java.io.FileReader(
args[0]));
Instances inst = new Instances(r);
final javax.swing.JFrame jf = new javax.swing.JFrame();
jf.getContentPane().setLayout(new java.awt.BorderLayout());
final AttributeSummarizer as = new AttributeSummarizer();
as.setInstances(inst);
jf.getContentPane().add(as, java.awt.BorderLayout.CENTER);
jf.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
jf.dispose();
System.exit(0);
}
});
jf.setSize(830, 600);
jf.setVisible(true);
} catch (Exception ex) {
ex.printStackTrace();
System.err.println(ex.getMessage());
}
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/AttributeSummarizerBeanInfo.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/>.
*/
/*
* AttributeSummarizerBeanInfo.java
* Copyright (C) 2003-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.beans.BeanDescriptor;
import java.beans.EventSetDescriptor;
import java.beans.SimpleBeanInfo;
/**
* Bean info class for the attribute summarizer bean
*
* @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a>
* @version $Revision$
*/
public class AttributeSummarizerBeanInfo extends SimpleBeanInfo {
/**
* Get the event set descriptors for this bean
*
* @return an <code>EventSetDescriptor[]</code> value
*/
public EventSetDescriptor [] getEventSetDescriptors() {
// hide all gui events
try {
EventSetDescriptor [] esds = {
new EventSetDescriptor(DataVisualizer.class,
"image",
ImageListener.class,
"acceptImage")
};
return esds;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
/**
* Get the bean descriptor for this bean
*
* @return a <code>BeanDescriptor</code> value
*/
public BeanDescriptor getBeanDescriptor() {
return new BeanDescriptor(weka.gui.beans.AttributeSummarizer.class,
AttributeSummarizerCustomizer.class);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/AttributeSummarizerCustomizer.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/>.
*/
/*
* AttributeSummarizerCustomizer.java
* Copyright (C) 2011-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import weka.core.Environment;
import weka.core.EnvironmentHandler;
import weka.core.PluginManager;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Set;
import java.util.Vector;
/**
* GUI customizer for attribute summarizer. Allows the customization of
* options for offscreen chart rendering (i.e. the payload of "ImageEvent"
* connections).
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision$
*/
public class AttributeSummarizerCustomizer extends JPanel implements
BeanCustomizer, EnvironmentHandler, CustomizerClosingListener,
CustomizerCloseRequester {
/**
* For serialization
*/
private static final long serialVersionUID = -6973666187676272788L;
private DataVisualizer m_dataVis;
private Environment m_env = Environment.getSystemWide();
private ModifyListener m_modifyListener;
private Window m_parent;
private String m_rendererNameBack;
private String m_xAxisBack;
private String m_widthBack;
private String m_heightBack;
private String m_optsBack;
private JComboBox m_rendererCombo;
private EnvironmentField m_xAxis;
private EnvironmentField m_width;
private EnvironmentField m_height;
private EnvironmentField m_opts;
/**
* Constructor
*/
public AttributeSummarizerCustomizer() {
setLayout(new BorderLayout());
}
/**
* Set the model performance chart object to customize
*
* @param object the model performance chart to customize
*/
public void setObject(Object object) {
m_dataVis = (DataVisualizer)object;
m_rendererNameBack = m_dataVis.getOffscreenRendererName();
m_xAxisBack = m_dataVis.getOffscreenXAxis();
m_widthBack = m_dataVis.getOffscreenWidth();
m_heightBack = m_dataVis.getOffscreenHeight();
m_optsBack = m_dataVis.getOffscreenAdditionalOpts();
setup();
}
private void setup() {
JPanel holder = new JPanel();
holder.setLayout(new GridLayout(5, 2));
Vector<String> comboItems = new Vector<String>();
comboItems.add("Weka Chart Renderer");
Set<String> pluginRenderers =
PluginManager.getPluginNamesOfType("weka.gui.beans.OffscreenChartRenderer");
if (pluginRenderers != null) {
for (String plugin : pluginRenderers) {
comboItems.add(plugin);
}
}
JLabel rendererLab = new JLabel("Renderer", SwingConstants.RIGHT);
holder.add(rendererLab);
m_rendererCombo = new JComboBox(comboItems);
holder.add(m_rendererCombo);
JLabel xLab = new JLabel("Attribute to chart", SwingConstants.RIGHT);
xLab.setToolTipText("Attribute name or /first or /last or /<index>");
m_xAxis = new EnvironmentField(m_env);
m_xAxis.setText(m_xAxisBack);
JLabel widthLab = new JLabel("Chart width (pixels)", SwingConstants.RIGHT);
m_width = new EnvironmentField(m_env);
m_width.setText(m_widthBack);
JLabel heightLab = new JLabel("Chart height (pixels)", SwingConstants.RIGHT);
m_height = new EnvironmentField(m_env);
m_height.setText(m_heightBack);
final JLabel optsLab = new JLabel("Renderer options", SwingConstants.RIGHT);
m_opts = new EnvironmentField(m_env);
m_opts.setText(m_optsBack);
holder.add(xLab); holder.add(m_xAxis);
holder.add(widthLab); holder.add(m_width);
holder.add(heightLab); holder.add(m_height);
holder.add(optsLab); holder.add(m_opts);
add(holder, BorderLayout.CENTER);
String globalInfo = m_dataVis.globalInfo();
globalInfo += " This dialog allows you to configure offscreen " +
"rendering options. Offscreen images are passed via" +
" 'image' connections.";
JTextArea jt = new JTextArea();
jt.setColumns(30);
jt.setFont(new Font("SansSerif", Font.PLAIN,12));
jt.setEditable(false);
jt.setLineWrap(true);
jt.setWrapStyleWord(true);
jt.setText(globalInfo);
jt.setBackground(getBackground());
JPanel jp = new JPanel();
jp.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createTitledBorder("About"),
BorderFactory.createEmptyBorder(5, 5, 5, 5)
));
jp.setLayout(new BorderLayout());
jp.add(jt, BorderLayout.CENTER);
add(jp, BorderLayout.NORTH);
addButtons();
m_rendererCombo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setupRendererOptsTipText(optsLab);
}
});
m_rendererCombo.setSelectedItem(m_rendererNameBack);
setupRendererOptsTipText(optsLab);
}
private void setupRendererOptsTipText(JLabel optsLab) {
String renderer = m_rendererCombo.getSelectedItem().toString();
if (renderer.equalsIgnoreCase("weka chart renderer")) {
// built-in renderer
WekaOffscreenChartRenderer rcr = new WekaOffscreenChartRenderer();
String tipText = rcr.optionsTipTextHTML();
tipText = tipText.replace("<html>", "<html>Comma separated list of options:<br>");
optsLab.setToolTipText(tipText);
} else {
try {
Object rendererO = PluginManager.getPluginInstance("weka.gui.beans.OffscreenChartRenderer",
renderer);
if (rendererO != null) {
String tipText = ((OffscreenChartRenderer)rendererO).optionsTipTextHTML();
if (tipText != null && tipText.length() > 0) {
optsLab.setToolTipText(tipText);
}
}
} catch (Exception ex) {
}
}
}
private void addButtons() {
JButton okBut = new JButton("OK");
JButton cancelBut = new JButton("Cancel");
JPanel butHolder = new JPanel();
butHolder.setLayout(new GridLayout(1, 2));
butHolder.add(okBut); butHolder.add(cancelBut);
add(butHolder, BorderLayout.SOUTH);
okBut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
m_dataVis.setOffscreenXAxis(m_xAxis.getText());
m_dataVis.setOffscreenWidth(m_width.getText());
m_dataVis.setOffscreenHeight(m_height.getText());
m_dataVis.setOffscreenAdditionalOpts(m_opts.getText());
m_dataVis.setOffscreenRendererName(m_rendererCombo.
getSelectedItem().toString());
if (m_modifyListener != null) {
m_modifyListener.
setModifiedStatus(AttributeSummarizerCustomizer.this, true);
}
if (m_parent != null) {
m_parent.dispose();
}
}
});
cancelBut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
customizerClosing();
if (m_parent != null) {
m_parent.dispose();
}
}
});
}
/**
* Set the parent window of this dialog
*
* @param parent the parent window
*/
public void setParentWindow(Window parent) {
m_parent = parent;
}
/**
* Gets called if the use closes the dialog via the
* close widget on the window - is treated as cancel,
* so restores the ImageSaver to its previous state.
*/
public void customizerClosing() {
m_dataVis.setOffscreenXAxis(m_xAxisBack);
m_dataVis.setOffscreenWidth(m_widthBack);
m_dataVis.setOffscreenHeight(m_heightBack);
m_dataVis.setOffscreenAdditionalOpts(m_optsBack);
m_dataVis.setOffscreenRendererName(m_rendererNameBack);
}
/**
* Set the environment variables to use
*
* @param env the environment variables to use
*/
public void setEnvironment(Environment env) {
m_env = env;
}
/**
* Set a listener interested in whether we've modified
* the ImageSaver that we're customizing
*
* @param l the listener
*/
public void setModifiedListener(ModifyListener l) {
m_modifyListener = l;
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/BatchAssociationRulesEvent.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/>.
*/
/*
* AssociationRulesEvent.java
* Copyright (C) 2010-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.util.EventObject;
import weka.associations.AssociationRules;
/**
* Class encapsulating a set of association rules.
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision$
*/
public class BatchAssociationRulesEvent extends EventObject {
/** For serialization */
private static final long serialVersionUID = 6332614648885439492L;
/** The encapsulated rules */
protected AssociationRules m_rules;
/**
* Creates a new <code>BatchAssociationRulesEvent</code> instance.
*
* @param source the source object.
* @param rules the association rules.
*/
public BatchAssociationRulesEvent(Object source, AssociationRules rules) {
super(source);
m_rules = rules;
}
/**
* Get the encapsulated association rules.
*
* @return the encapsulated association rules.
*/
public AssociationRules getRules() {
return m_rules;
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/BatchAssociationRulesListener.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/>.
*/
/*
* BatchAssociationRulesListener.java
* Copyright (C) 2010-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
/**
* Interface to something that can process a BatchAssociationRulesEvent.
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
*
*/
public interface BatchAssociationRulesListener {
/**
* Accept a <code>BatchAssociationRulesEvent</code>
*
* @param e a <code>BatchAssociationRulesEvent</code>
*/
void acceptAssociationRules(BatchAssociationRulesEvent e);
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/BatchClassifierEvent.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/>.
*/
/*
* BatchClassifierEvent.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.util.EventObject;
import weka.classifiers.Classifier;
/**
* Class encapsulating a built classifier and a batch of instances to test on.
*
* @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a>
* @version $Revision$
* @since 1.0
* @see EventObject
*/
public class BatchClassifierEvent extends EventObject {
/** for serialization */
private static final long serialVersionUID = 878097199815991084L;
/**
* The classifier
*/
protected Classifier m_classifier;
// protected Instances m_trainingSet;
/**
* Instances that can be used for testing the classifier
*/
// protected Instances m_testSet;
protected DataSetEvent m_testSet;
/**
* Instances that were used to train the classifier (may be null if not
* available)
*/
protected DataSetEvent m_trainSet;
/**
* The run number that this classifier was generated for
*/
protected int m_runNumber = 1;
/**
* The maximum number of runs
*/
protected int m_maxRunNumber = 1;
/**
* The set number for the test set
*/
protected int m_setNumber;
/**
* The last set number for this series
*/
protected int m_maxSetNumber;
/**
* An identifier that can be used to group all related runs/sets together.
*/
protected long m_groupIdentifier = Long.MAX_VALUE;
/**
* Label for this event
*/
protected String m_eventLabel = "";
/**
* Creates a new <code>BatchClassifierEvent</code> instance.
*
* @param source the source object
* @param scheme a Classifier
* @param trsI the training instances used to train the classifier
* @param tstI the test instances
* @param setNum the set number of the test instances
* @param maxSetNum the last set number in the series
*/
public BatchClassifierEvent(Object source, Classifier scheme,
DataSetEvent trsI, DataSetEvent tstI, int setNum, int maxSetNum) {
super(source);
// m_trainingSet = trnI;
m_classifier = scheme;
m_testSet = tstI;
m_trainSet = trsI;
m_setNumber = setNum;
m_maxSetNumber = maxSetNum;
}
/**
* Creates a new <code>BatchClassifierEvent</code> instance.
*
* @param source the source object
* @param scheme a Classifier
* @param trsI the training instances used to train the classifier
* @param tstI the test instances
* @param runNum the run number
* @param maxRunNum the maximum run number
* @param setNum the set number of the test instances
* @param maxSetNum the last set number in the series
*/
public BatchClassifierEvent(Object source, Classifier scheme,
DataSetEvent trsI, DataSetEvent tstI, int runNum, int maxRunNum,
int setNum, int maxSetNum) {
this(source, scheme, trsI, tstI, setNum, maxSetNum);
m_runNumber = runNum;
m_maxRunNumber = maxRunNum;
}
/**
* Set the label for this event.
*
* @param lab the label to use
*/
public void setLabel(String lab) {
m_eventLabel = lab;
}
/**
* Get the label for this event
*
* @return the label for this event
*/
public String getLabel() {
return m_eventLabel;
}
/**
* Get the classifier
*
* @return the classifier
*/
public Classifier getClassifier() {
return m_classifier;
}
/**
* Set the classifier
*
* @param classifier the classifier
*/
public void setClassifier(Classifier classifier) {
m_classifier = classifier;
}
/**
* Set the test set
*
* @param tse the test set
*/
public void setTestSet(DataSetEvent tse) {
m_testSet = tse;
}
/**
* Get the test set
*
* @return the test set
*/
public DataSetEvent getTestSet() {
return m_testSet;
}
/**
* Set the training set
*
* @param tse the training set
*/
public void setTrainSet(DataSetEvent tse) {
m_trainSet = tse;
}
/**
* Get the train set
*
* @return the training set
*/
public DataSetEvent getTrainSet() {
return m_trainSet;
}
/**
* Get the run number.
*
* @return the run number
*/
public int getRunNumber() {
return m_runNumber;
}
/**
* Get the maximum run number
*
* @return the maximum run number
*/
public int getMaxRunNumber() {
return m_maxRunNumber;
}
/**
* Get the set number (ie which fold this is)
*
* @return the set number for the training and testing data sets encapsulated
* in this event
*/
public int getSetNumber() {
return m_setNumber;
}
/**
* Get the maximum set number (ie the total number of training and testing
* sets in the series).
*
* @return the maximum set number
*/
public int getMaxSetNumber() {
return m_maxSetNumber;
}
public void setGroupIdentifier(long identifier) {
m_groupIdentifier = identifier;
}
public long getGroupIdentifier() {
return m_groupIdentifier;
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/BatchClassifierListener.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/>.
*/
/*
* BatchClassifierListener.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.util.EventListener;
/**
* Interface to something that can process a BatchClassifierEvent
*
* @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a>
* @version $Revision$
* @since 1.0
* @see EventListener
*/
public interface BatchClassifierListener extends EventListener {
/**
* Accept a BatchClassifierEvent
*
* @param e a <code>BatchClassifierEvent</code> value
*/
void acceptClassifier(BatchClassifierEvent e);
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/BatchClustererEvent.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/>.
*/
/*
* BatchClustererEvent.java
* Copyright (C) 2004-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.util.EventObject;
import weka.clusterers.Clusterer;
/**
* Class encapsulating a built clusterer and a batch of instances to
* test on.
*
* @author <a href="mailto:mutter@cs.waikato.ac.nz">Stefan Mutter</a>
* @version $Revision$
* @since 1.0
* @see EventObject
*/
public class BatchClustererEvent
extends EventObject {
/** for serialization */
private static final long serialVersionUID = 7268777944939129714L;
/**
* The clusterer
*/
protected Clusterer m_clusterer;
// protected Instances m_trainingSet;
/**
* Training or Test Instances
*/
// protected Instances m_testSet;
protected DataSetEvent m_testSet;
/**
* The set number for the test set
*/
protected int m_setNumber;
/**
* Indicates if m_testSet is a training or a test set. 0 for test, >0 for training
*/
protected int m_testOrTrain;
/**
* The last set number for this series
*/
protected int m_maxSetNumber;
public static int TEST = 0;
public static int TRAINING = 1;
/**
* Creates a new <code>BatchClustererEvent</code> instance.
*
* @param source the source object
* @param scheme a Clusterer
* @param tstI the training/test instances
* @param setNum the set number of the training/testinstances
* @param maxSetNum the last set number in the series
* @param testOrTrain 0 if the set is a test set, >0 if it is a training set
*/
public BatchClustererEvent(Object source, Clusterer scheme, DataSetEvent tstI, int setNum, int maxSetNum, int testOrTrain) {
super(source);
// m_trainingSet = trnI;
m_clusterer = scheme;
m_testSet = tstI;
m_setNumber = setNum;
m_maxSetNumber = maxSetNum;
if(testOrTrain == 0)
m_testOrTrain = TEST;
else
m_testOrTrain = TRAINING;
}
/**
* Get the clusterer
*
* @return the clusterer
*/
public Clusterer getClusterer() {
return m_clusterer;
}
/**
* Get the training/test set
*
* @return the training/testing instances
*/
public DataSetEvent getTestSet() {
return m_testSet;
}
/**
* Get the set number (ie which fold this is)
*
* @return the set number for the training and testing data sets
* encapsulated in this event
*/
public int getSetNumber() {
return m_setNumber;
}
/**
* Get the maximum set number (ie the total number of training
* and testing sets in the series).
*
* @return the maximum set number
*/
public int getMaxSetNumber() {
return m_maxSetNumber;
}
/**
* Get whether the set of instances is a test or a training set
*
* @return 0 for test set, >0 fro training set
*/
public int getTestOrTrain(){
return m_testOrTrain;
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/BatchClustererListener.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/>.
*/
/*
* BatchClustererListener.java
* Copyright (C) 2004-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.util.EventListener;
/**
* Interface to something that can process a BatchClustererEvent
*
* @author <a href="mailto:mutter@cs.waikato.ac.nz">MStefan Mutter</a>
* @version $Revision$
* @see EventListener
*/
public interface BatchClustererListener extends EventListener {
/**
* Accept a BatchClustererEvent
*
* @param e a <code>BatchClustererEvent</code> value
*/
void acceptClusterer(BatchClustererEvent e);
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/BeanCommon.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/>.
*/
/*
* BeanCommon.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.beans.EventSetDescriptor;
/**
* Interface specifying routines that all weka beans should implement
* in order to allow the bean environment to exercise some control over the
* bean and also to allow the bean to exercise some control over connections.
*
* Beans may want to impose constraints in terms of
* the number of connections they will allow via a particular
* listener interface. Some beans may only want to be registered
* as a listener for a particular event type with only one source, or
* perhaps a limited number of sources.
*
* @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a>
* @version $Revision$
* @since 1.0
*/
public interface BeanCommon {
/**
* Set a custom (descriptive) name for this bean
*
* @param name the name to use
*/
void setCustomName(String name);
/**
* Get the custom (descriptive) name for this bean (if one has been set)
*
* @return the custom name (or the default name)
*/
String getCustomName();
/**
* Stop any processing that the bean might be doing.
*/
void stop();
/**
* Returns true if. at this time, the bean is busy with some
* (i.e. perhaps a worker thread is performing some calculation).
*
* @return true if the bean is busy.
*/
boolean isBusy();
/**
* Set a logger
*
* @param logger a <code>weka.gui.Logger</code> value
*/
void setLog(weka.gui.Logger logger);
/**
* Returns true if, at this time,
* the object will accept a connection via the named event
*
* @param esd the EventSetDescriptor for the event in question
* @return true if the object will accept a connection
*/
boolean connectionAllowed(EventSetDescriptor esd);
/**
* Returns true if, at this time,
* the object will accept a connection via the named event
*
* @param eventName the name of the event
* @return true if the object will accept a connection
*/
boolean connectionAllowed(String eventName);
/**
* Notify this object that it has been registered as a listener with
* a source for recieving events described by the named event
* This object is responsible for recording this fact.
*
* @param eventName the event
* @param source the source with which this object has been registered as
* a listener
*/
void connectionNotification(String eventName, Object source);
/**
* Notify this object that it has been deregistered as a listener with
* a source for named event. This object is responsible
* for recording this fact.
*
* @param eventName the event
* @param source the source with which this object has been registered as
* a listener
*/
void disconnectionNotification(String eventName, Object source);
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/BeanConnection.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/>.
*/
/*
* BeanConnection.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.BeanInfo;
import java.beans.EventSetDescriptor;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Vector;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.SwingConstants;
/**
* Class for encapsulating a connection between two beans. Also maintains a list
* of all connections
*
* @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a>
* @version $Revision$
*/
public class BeanConnection implements Serializable {
/** for serialization */
private static final long serialVersionUID = 8804264241791332064L;
private static ArrayList<Vector<BeanConnection>> TABBED_CONNECTIONS = new ArrayList<Vector<BeanConnection>>();
/*
* static { Vector initial = new Vector(); TABBED_CONNECTIONS.add(initial); }
*/
// details for this connection
private final BeanInstance m_source;
private final BeanInstance m_target;
/**
* The name of the event for this connection
*/
private final String m_eventName;
// Should the connection be painted?
private boolean m_hidden = false;
/**
* Sets up just a single collection of bean connections in the first element
* of the list. This is useful for clients that are using XMLBeans to load
* beans.
*/
public static void init() {
// CONNECTIONS = new Vector();
// TODO remove this soon!!!
// TABBED_CONNECTIONS.set(0, new Vector());
TABBED_CONNECTIONS.clear();
TABBED_CONNECTIONS.add(new Vector<BeanConnection>());
}
/**
* Returns the list of connections
*
* @return the list of connections
*/
public static Vector<BeanConnection> getConnections(Integer... tab) {
Vector<BeanConnection> returnV = null;
int index = 0;
if (tab.length > 0) {
index = tab[0].intValue();
}
if (TABBED_CONNECTIONS.size() > 0) {
returnV = TABBED_CONNECTIONS.get(index);
}
return returnV;
}
/**
* Describe <code>setConnections</code> method here.
*
* @param connections a <code>Vector</code> value
*/
public static void setConnections(Vector<BeanConnection> connections,
Integer... tab) {
int index = 0;
if (tab.length > 0) {
index = tab[0].intValue();
}
if (index < TABBED_CONNECTIONS.size()) {
TABBED_CONNECTIONS.set(index, connections);
}
}
/**
* Add the supplied collection of connections to the end of the list.
*
*
* @param connections the connections to add
*/
public static void addConnections(Vector<BeanConnection> connections) {
TABBED_CONNECTIONS.add(connections);
}
/**
* Append the supplied connections to the list for the given tab index
*
* @param connections the connections to append
* @param tab the index of the list to append to
*/
public static void appendConnections(Vector<BeanConnection> connections,
int tab) {
if (tab < TABBED_CONNECTIONS.size()) {
Vector<BeanConnection> cons = TABBED_CONNECTIONS.get(tab);
for (int i = 0; i < connections.size(); i++) {
cons.add(connections.get(i));
}
}
}
/**
* Returns true if there is a link between the supplied source and target
* BeanInstances at an earlier index than the supplied index
*
* @param source the source BeanInstance
* @param target the target BeanInstance
* @param index the index to compare to
* @return true if there is already a link at an earlier index
*/
private static boolean previousLink(BeanInstance source, BeanInstance target,
int index, Integer... tab) {
int tabIndex = 0;
if (tab.length > 0) {
tabIndex = tab[0].intValue();
}
Vector<BeanConnection> connections = TABBED_CONNECTIONS.get(tabIndex);
for (int i = 0; i < connections.size(); i++) {
BeanConnection bc = connections.elementAt(i);
BeanInstance compSource = bc.getSource();
BeanInstance compTarget = bc.getTarget();
if (compSource == source && compTarget == target && index < i) {
return true;
}
}
return false;
}
/**
* A candidate BeanInstance can't be an input if it is the target of a
* connection from a source that is in the listToCheck
*/
private static boolean checkTargetConstraint(BeanInstance candidate,
Vector<Object> listToCheck, Integer... tab) {
int tabIndex = 0;
if (tab.length > 0) {
tabIndex = tab[0].intValue();
}
Vector<BeanConnection> connections = TABBED_CONNECTIONS.get(tabIndex);
for (int i = 0; i < connections.size(); i++) {
BeanConnection bc = connections.elementAt(i);
if (bc.getTarget() == candidate) {
for (int j = 0; j < listToCheck.size(); j++) {
BeanInstance tempSource = (BeanInstance) listToCheck.elementAt(j);
if (bc.getSource() == tempSource) {
return false;
}
}
}
}
return true;
}
/**
* Returns a vector of BeanConnections associated with the supplied vector of
* BeanInstances, i.e. all connections that exist between those BeanInstances
* in the subFlow.
*
* @param subFlow a Vector of BeanInstances
* @return a Vector of BeanConnections
*/
public static Vector<BeanConnection> associatedConnections(
Vector<Object> subFlow, Integer... tab) {
int tabIndex = 0;
if (tab.length > 0) {
tabIndex = tab[0].intValue();
}
Vector<BeanConnection> connections = TABBED_CONNECTIONS.get(tabIndex);
Vector<BeanConnection> associatedConnections = new Vector<BeanConnection>();
for (int i = 0; i < connections.size(); i++) {
BeanConnection bc = connections.elementAt(i);
BeanInstance tempSource = bc.getSource();
BeanInstance tempTarget = bc.getTarget();
boolean sourceInSubFlow = false;
boolean targetInSubFlow = false;
for (int j = 0; j < subFlow.size(); j++) {
BeanInstance toCheck = (BeanInstance) subFlow.elementAt(j);
if (toCheck == tempSource) {
sourceInSubFlow = true;
}
if (toCheck == tempTarget) {
targetInSubFlow = true;
}
if (sourceInSubFlow && targetInSubFlow) {
associatedConnections.add(bc);
break;
}
}
}
return associatedConnections;
}
/**
* Returns a vector of BeanInstances that can be considered as inputs (or the
* left-hand side of a sub-flow)
*
* @param subset the sub-flow to examine
* @return a Vector of inputs to the sub-flow
*/
public static Vector<Object> inputs(Vector<Object> subset, Integer... tab) {
Vector<Object> result = new Vector<Object>();
for (int i = 0; i < subset.size(); i++) {
BeanInstance temp = (BeanInstance) subset.elementAt(i);
// if (checkForSource(temp, subset)) {
// now check target constraint
if (checkTargetConstraint(temp, subset, tab)) {
result.add(temp);
}
// }
}
return result;
}
/**
* A candidate BeanInstance can be an output if it is in the listToCheck and
* it is the target of a connection from a source that is in the listToCheck
*/
private static boolean checkForTarget(BeanInstance candidate,
Vector<Object> listToCheck, Integer... tab) {
int tabIndex = 0;
if (tab.length > 0) {
tabIndex = tab[0].intValue();
}
Vector<BeanConnection> connections = TABBED_CONNECTIONS.get(tabIndex);
for (int i = 0; i < connections.size(); i++) {
BeanConnection bc = connections.elementAt(i);
if (bc.getTarget() != candidate) {
continue;
}
// check to see if source is in list
for (int j = 0; j < listToCheck.size(); j++) {
BeanInstance tempSource = (BeanInstance) listToCheck.elementAt(j);
if (bc.getSource() == tempSource) {
return true;
}
}
}
return false;
}
private static boolean isInList(BeanInstance candidate,
Vector<Object> listToCheck) {
for (int i = 0; i < listToCheck.size(); i++) {
BeanInstance temp = (BeanInstance) listToCheck.elementAt(i);
if (candidate == temp) {
return true;
}
}
return false;
}
/**
* A candidate BeanInstance can't be an output if it is the source of a
* connection only to target(s) that are in the listToCheck
*/
private static boolean checkSourceConstraint(BeanInstance candidate,
Vector<Object> listToCheck, Integer... tab) {
int tabIndex = 0;
if (tab.length > 0) {
tabIndex = tab[0].intValue();
}
Vector<BeanConnection> connections = TABBED_CONNECTIONS.get(tabIndex);
boolean result = true;
for (int i = 0; i < connections.size(); i++) {
BeanConnection bc = connections.elementAt(i);
if (bc.getSource() == candidate) {
BeanInstance cTarget = bc.getTarget();
// is the target of this connection external to the list to check?
if (!isInList(cTarget, listToCheck)) {
return true;
}
for (int j = 0; j < listToCheck.size(); j++) {
BeanInstance tempTarget = (BeanInstance) listToCheck.elementAt(j);
if (bc.getTarget() == tempTarget) {
result = false;
}
}
}
}
return result;
}
/**
* Returns a vector of BeanInstances that can be considered as outputs (or the
* right-hand side of a sub-flow)
*
* @param subset the sub-flow to examine
* @return a Vector of outputs of the sub-flow
*/
public static Vector<Object> outputs(Vector<Object> subset, Integer... tab) {
Vector<Object> result = new Vector<Object>();
for (int i = 0; i < subset.size(); i++) {
BeanInstance temp = (BeanInstance) subset.elementAt(i);
if (checkForTarget(temp, subset, tab)) {
// now check source constraint
if (checkSourceConstraint(temp, subset, tab)) {
// now check that this bean can actually produce some events
try {
BeanInfo bi = Introspector.getBeanInfo(temp.getBean().getClass());
EventSetDescriptor[] esd = bi.getEventSetDescriptors();
if (esd != null && esd.length > 0) {
result.add(temp);
}
} catch (IntrospectionException ex) {
// quietly ignore
}
}
}
}
return result;
}
/**
* Renders the connections and their names on the supplied graphics context
*
* @param gx a <code>Graphics</code> value
*/
public static void paintConnections(Graphics gx, Integer... tab) {
int tabIndex = 0;
if (tab.length > 0) {
tabIndex = tab[0].intValue();
}
Vector<BeanConnection> connections = TABBED_CONNECTIONS.get(tabIndex);
for (int i = 0; i < connections.size(); i++) {
BeanConnection bc = connections.elementAt(i);
if (!bc.isHidden()) {
BeanInstance source = bc.getSource();
BeanInstance target = bc.getTarget();
EventSetDescriptor srcEsd = bc.getSourceEventSetDescriptor();
BeanVisual sourceVisual = (source.getBean() instanceof Visible) ? ((Visible) source
.getBean()).getVisual() : null;
BeanVisual targetVisual = (target.getBean() instanceof Visible) ? ((Visible) target
.getBean()).getVisual() : null;
if (sourceVisual != null && targetVisual != null) {
Point bestSourcePt = sourceVisual.getClosestConnectorPoint(new Point(
(target.getX() + (target.getWidth() / 2)), (target.getY() + (target
.getHeight() / 2))));
Point bestTargetPt = targetVisual.getClosestConnectorPoint(new Point(
(source.getX() + (source.getWidth() / 2)), (source.getY() + (source
.getHeight() / 2))));
gx.setColor(Color.red);
boolean active = true;
if (source.getBean() instanceof EventConstraints) {
if (!((EventConstraints) source.getBean()).eventGeneratable(srcEsd
.getName())) {
gx.setColor(Color.gray); // link not active at this time
active = false;
}
}
gx.drawLine((int) bestSourcePt.getX(), (int) bestSourcePt.getY(),
(int) bestTargetPt.getX(), (int) bestTargetPt.getY());
// paint an arrow head
double angle;
try {
double a = (bestSourcePt.getY() - bestTargetPt.getY())
/ (bestSourcePt.getX() - bestTargetPt.getX());
angle = Math.atan(a);
} catch (Exception ex) {
angle = Math.PI / 2;
}
// Point arrowstart = new Point((p1.x + p2.x) / 2, (p1.y + p2.y) / 2);
Point arrowstart = new Point(bestTargetPt.x, bestTargetPt.y);
Point arrowoffset = new Point((int) (7 * Math.cos(angle)),
(int) (7 * Math.sin(angle)));
Point arrowend;
if (bestSourcePt.getX() >= bestTargetPt.getX()) {
arrowend = new Point(arrowstart.x + arrowoffset.x, arrowstart.y
+ arrowoffset.y);
} else {
arrowend = new Point(arrowstart.x - arrowoffset.x, arrowstart.y
- arrowoffset.y);
}
int xs[] = { arrowstart.x,
arrowend.x + (int) (7 * Math.cos(angle + (Math.PI / 2))),
arrowend.x + (int) (7 * Math.cos(angle - (Math.PI / 2))) };
int ys[] = { arrowstart.y,
arrowend.y + (int) (7 * Math.sin(angle + (Math.PI / 2))),
arrowend.y + (int) (7 * Math.sin(angle - (Math.PI / 2))) };
gx.fillPolygon(xs, ys, 3);
// ----
// paint the connection name
int midx = (int) bestSourcePt.getX();
midx += (int) ((bestTargetPt.getX() - bestSourcePt.getX()) / 2);
int midy = (int) bestSourcePt.getY();
midy += (int) ((bestTargetPt.getY() - bestSourcePt.getY()) / 2) - 2;
gx.setColor((active) ? Color.blue : Color.gray);
if (previousLink(source, target, i, tab)) {
midy -= 15;
}
gx.drawString(srcEsd.getName(), midx, midy);
}
}
}
}
/**
* Return a list of connections within some delta of a point
*
* @param pt the point at which to look for connections
* @param delta connections have to be within this delta of the point
* @return a list of connections
*/
public static Vector<BeanConnection> getClosestConnections(Point pt,
int delta, Integer... tab) {
int tabIndex = 0;
if (tab.length > 0) {
tabIndex = tab[0].intValue();
}
Vector<BeanConnection> connections = TABBED_CONNECTIONS.get(tabIndex);
Vector<BeanConnection> closestConnections = new Vector<BeanConnection>();
for (int i = 0; i < connections.size(); i++) {
BeanConnection bc = connections.elementAt(i);
BeanInstance source = bc.getSource();
BeanInstance target = bc.getTarget();
bc.getSourceEventSetDescriptor();
BeanVisual sourceVisual = (source.getBean() instanceof Visible) ? ((Visible) source
.getBean()).getVisual() : null;
BeanVisual targetVisual = (target.getBean() instanceof Visible) ? ((Visible) target
.getBean()).getVisual() : null;
if (sourceVisual != null && targetVisual != null) {
Point bestSourcePt = sourceVisual.getClosestConnectorPoint(new Point(
(target.getX() + (target.getWidth() / 2)), (target.getY() + (target
.getHeight() / 2))));
Point bestTargetPt = targetVisual.getClosestConnectorPoint(new Point(
(source.getX() + (source.getWidth() / 2)), (source.getY() + (source
.getHeight() / 2))));
int minx = (int) Math.min(bestSourcePt.getX(), bestTargetPt.getX());
int maxx = (int) Math.max(bestSourcePt.getX(), bestTargetPt.getX());
int miny = (int) Math.min(bestSourcePt.getY(), bestTargetPt.getY());
int maxy = (int) Math.max(bestSourcePt.getY(), bestTargetPt.getY());
// check to see if supplied pt is inside bounding box
if (pt.getX() >= minx - delta && pt.getX() <= maxx + delta
&& pt.getY() >= miny - delta && pt.getY() <= maxy + delta) {
// now see if the point is within delta of the line
// formulate ax + by + c = 0
double a = bestSourcePt.getY() - bestTargetPt.getY();
double b = bestTargetPt.getX() - bestSourcePt.getX();
double c = (bestSourcePt.getX() * bestTargetPt.getY())
- (bestTargetPt.getX() * bestSourcePt.getY());
double distance = Math.abs((a * pt.getX()) + (b * pt.getY()) + c);
distance /= Math.abs(Math.sqrt((a * a) + (b * b)));
if (distance <= delta) {
closestConnections.addElement(bc);
}
}
}
}
return closestConnections;
}
/**
* Remove the list of connections at the supplied index
*
* @param tab the index of the list to remove (correspods to a tab in the
* Knowledge Flow UI)
*
* @param tab the index of the list of connections to remove
*/
public static void removeConnectionList(Integer tab) {
TABBED_CONNECTIONS.remove(tab.intValue());
}
/**
* Remove all connections for a bean. If the bean is a target for receiving
* events then it gets deregistered from the corresonding source bean. If the
* bean is a source of events then all targets implementing BeanCommon are
* notified via their disconnectionNotification methods that the source (and
* hence the connection) is going away.
*
* @param instance the bean to remove connections to/from
*/
public static void removeConnections(BeanInstance instance, Integer... tab) {
int tabIndex = 0;
if (tab.length > 0) {
tabIndex = tab[0].intValue();
}
Vector<BeanConnection> connections = TABBED_CONNECTIONS.get(tabIndex);
Vector<Object> instancesToRemoveFor = new Vector<Object>();
if (instance.getBean() instanceof MetaBean) {
instancesToRemoveFor = ((MetaBean) instance.getBean())
.getBeansInSubFlow();
} else {
instancesToRemoveFor.add(instance);
}
Vector<BeanConnection> removeVector = new Vector<BeanConnection>();
for (int j = 0; j < instancesToRemoveFor.size(); j++) {
BeanInstance tempInstance = (BeanInstance) instancesToRemoveFor
.elementAt(j);
for (int i = 0; i < connections.size(); i++) {
// In cases where this instance is the target, deregister it
// as a listener for the source
BeanConnection bc = connections.elementAt(i);
BeanInstance tempTarget = bc.getTarget();
BeanInstance tempSource = bc.getSource();
EventSetDescriptor tempEsd = bc.getSourceEventSetDescriptor();
if (tempInstance == tempTarget) {
// try to deregister the target as a listener for the source
try {
Method deregisterMethod = tempEsd.getRemoveListenerMethod();
Object targetBean = tempTarget.getBean();
Object[] args = new Object[1];
args[0] = targetBean;
deregisterMethod.invoke(tempSource.getBean(), args);
// System.err.println("Deregistering listener");
removeVector.addElement(bc);
} catch (Exception ex) {
ex.printStackTrace();
}
} else if (tempInstance == tempSource) {
removeVector.addElement(bc);
if (tempTarget.getBean() instanceof BeanCommon) {
// tell the target that the source is going away, therefore
// this type of connection is as well
((BeanCommon) tempTarget.getBean()).disconnectionNotification(
tempEsd.getName(), tempSource.getBean());
}
}
}
}
for (int i = 0; i < removeVector.size(); i++) {
// System.err.println("removing connection");
connections.removeElement(removeVector.elementAt(i));
}
}
public static void doMetaConnection(BeanInstance source, BeanInstance target,
final EventSetDescriptor esd, final JComponent displayComponent,
final int tab) {
Object targetBean = target.getBean();
BeanInstance realTarget = null;
final BeanInstance realSource = source;
if (targetBean instanceof MetaBean) {
Vector<BeanInstance> receivers = ((MetaBean) targetBean)
.getSuitableTargets(esd);
if (receivers.size() == 1) {
realTarget = receivers.elementAt(0);
new BeanConnection(realSource, realTarget, esd, tab);
} else {
// have to do the popup thing here
int menuItemCount = 0;
JPopupMenu targetConnectionMenu = new JPopupMenu();
targetConnectionMenu.insert(new JLabel("Select target",
SwingConstants.CENTER), menuItemCount++);
for (int i = 0; i < receivers.size(); i++) {
final BeanInstance tempTarget = receivers.elementAt(i);
String tName = ""
+ (i + 1)
+ ": "
+ ((tempTarget.getBean() instanceof BeanCommon) ? ((BeanCommon) tempTarget
.getBean()).getCustomName() : tempTarget.getBean().getClass()
.getName());
JMenuItem targetItem = new JMenuItem(tName);
targetItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
new BeanConnection(realSource, tempTarget, esd, tab);
displayComponent.repaint();
}
});
targetConnectionMenu.add(targetItem);
menuItemCount++;
}
targetConnectionMenu.show(displayComponent, target.getX(),
target.getY());
// m_target = (BeanInstance)finalTarget.elementAt(0);
}
}
}
/**
* Creates a new <code>BeanConnection</code> instance.
*
* @param source the source bean
* @param target the target bean
* @param esd the EventSetDescriptor for the connection be displayed
*/
public BeanConnection(BeanInstance source, BeanInstance target,
EventSetDescriptor esd, Integer... tab) {
int tabIndex = 0;
if (tab.length > 0) {
tabIndex = tab[0].intValue();
}
Vector<BeanConnection> connections = TABBED_CONNECTIONS.get(tabIndex);
m_source = source;
m_target = target;
// m_sourceEsd = sourceEsd;
m_eventName = esd.getName();
// System.err.println(m_eventName);
// attempt to connect source and target beans
Method registrationMethod =
// m_sourceEsd.getAddListenerMethod();
// getSourceEventSetDescriptor().getAddListenerMethod();
esd.getAddListenerMethod();
Object targetBean = m_target.getBean();
Object[] args = new Object[1];
args[0] = targetBean;
Class<?> listenerClass = esd.getListenerType();
if (listenerClass.isInstance(targetBean)) {
try {
registrationMethod.invoke(m_source.getBean(), args);
// if the target implements BeanCommon, then inform
// it that it has been registered as a listener with a source via
// the named listener interface
if (targetBean instanceof BeanCommon) {
((BeanCommon) targetBean).connectionNotification(esd.getName(),
m_source.getBean());
}
connections.addElement(this);
} catch (Exception ex) {
System.err.println("[BeanConnection] Unable to connect beans");
ex.printStackTrace();
}
} else {
System.err.println("[BeanConnection] Unable to connect beans");
}
}
/**
* Make this connection invisible on the display
*
* @param hidden true to make the connection invisible
*/
public void setHidden(boolean hidden) {
m_hidden = hidden;
}
/**
* Returns true if this connection is invisible
*
* @return true if connection is invisible
*/
public boolean isHidden() {
return m_hidden;
}
/**
* Remove this connection
*/
public void remove(Integer... tab) {
int tabIndex = 0;
if (tab.length > 0) {
tabIndex = tab[0].intValue();
}
Vector<BeanConnection> connections = TABBED_CONNECTIONS.get(tabIndex);
EventSetDescriptor tempEsd = getSourceEventSetDescriptor();
// try to deregister the target as a listener for the source
try {
Method deregisterMethod = tempEsd.getRemoveListenerMethod();
Object targetBean = getTarget().getBean();
Object[] args = new Object[1];
args[0] = targetBean;
deregisterMethod.invoke(getSource().getBean(), args);
// System.err.println("Deregistering listener");
} catch (Exception ex) {
ex.printStackTrace();
}
if (getTarget().getBean() instanceof BeanCommon) {
// tell the target that this connection is going away
((BeanCommon) getTarget().getBean()).disconnectionNotification(
tempEsd.getName(), getSource().getBean());
}
connections.remove(this);
}
/**
* returns the source BeanInstance for this connection
*
* @return a <code>BeanInstance</code> value
*/
public BeanInstance getSource() {
return m_source;
}
/**
* Returns the target BeanInstance for this connection
*
* @return a <code>BeanInstance</code> value
*/
public BeanInstance getTarget() {
return m_target;
}
/**
* Returns the name of the event for this conncetion
*
* @return the name of the event for this connection
*/
public String getEventName() {
return m_eventName;
}
/**
* Returns the event set descriptor for the event generated by the source for
* this connection
*
* @return an <code>EventSetDescriptor</code> value
*/
protected EventSetDescriptor getSourceEventSetDescriptor() {
JComponent bc = (JComponent) m_source.getBean();
try {
BeanInfo sourceInfo = Introspector.getBeanInfo(bc.getClass());
if (sourceInfo == null) {
System.err
.println("[BeanConnection] Error getting bean info, source info is null.");
} else {
EventSetDescriptor[] esds = sourceInfo.getEventSetDescriptors();
for (EventSetDescriptor esd : esds) {
if (esd.getName().compareTo(m_eventName) == 0) {
return esd;
}
}
}
} catch (Exception ex) {
System.err
.println("[BeanConnection] Problem retrieving event set descriptor");
}
return null;
// return m_sourceEsd;
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/BeanCustomizer.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/>.
*/
/*
* BeanCustomizer.java
* Copyright (C) 2011-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.beans.Customizer;
/**
* Extends java.beans.Customizer and provides a method to register
* a listener interested in notification about whether the customizer
* has modified the object that it is customizing. Typically, an implementation
* would notify the listener about the modification state when it's window
* is closed.
*
* @author Mark Hall (mhall{[at]}penthao{[dot]}com)
* @version $Revision$
*
*/
public interface BeanCustomizer extends Customizer {
/**
* Interface for something that is interested in the modified status
* of a source object (typically a BeanCustomizer that is editing an
* object)
*
* @author mhall
*
*/
public interface ModifyListener {
/**
* Tell the listener about the modified status of the source object.
*
* @param source the source object
* @param modified true if the source object has been modified
*/
void setModifiedStatus(Object source, boolean modified);
}
/**
* Set a listener to be notified about the modified status of this
* object
*
* @param l the ModifiedListener
*/
void setModifiedListener(ModifyListener l);
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/BeanInstance.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/>.
*/
/*
* BeanInstance.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;
import java.beans.Beans;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import javax.swing.JComponent;
/**
* Class that manages a set of beans.
*
* @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a>
* @version $Revision$
* @since 1.0
*/
public class BeanInstance implements Serializable {
/** for serialization */
private static final long serialVersionUID = -7575653109025406342L;
private static ArrayList<Vector<Object>> TABBED_COMPONENTS = new ArrayList<Vector<Object>>();
/*
* static { Vector initial = new Vector(); TABBED_COMPONENTS.add(initial); }
*/
/**
* Sets up just a single collection of bean instances in the first element of
* the list. This is useful for clients that are using XMLBeans to load beans.
*/
public static void init() {
TABBED_COMPONENTS.clear();
TABBED_COMPONENTS.add(new Vector<Object>());
}
/**
* class variable holding all the beans
*/
// private static Vector COMPONENTS = new Vector();
public static final int IDLE = 0;
public static final int BEAN_EXECUTING = 1;
/**
* Holds the bean encapsulated in this instance
*/
private Object m_bean;
private int m_x;
private int m_y;
/**
* Removes all beans from containing component
*
* @param container a <code>JComponent</code> value
*/
public static void removeAllBeansFromContainer(JComponent container,
Integer... tab) {
int index = 0;
if (tab.length > 0) {
index = tab[0].intValue();
}
Vector<Object> components = null;
if (TABBED_COMPONENTS.size() > 0 && index < TABBED_COMPONENTS.size()) {
components = TABBED_COMPONENTS.get(index);
}
if (container != null) {
if (components != null) {
for (int i = 0; i < components.size(); i++) {
Object tempInstance = components.elementAt(i);
Object tempBean = ((BeanInstance) tempInstance).getBean();
if (Beans.isInstanceOf(tempBean, JComponent.class)) {
container.remove((JComponent) tempBean);
}
}
}
container.revalidate();
}
}
/**
* Adds all beans to the supplied component
*
* @param container a <code>JComponent</code> value
*/
public static void addAllBeansToContainer(JComponent container,
Integer... tab) {
int index = 0;
if (tab.length > 0) {
index = tab[0].intValue();
}
Vector<Object> components = null;
if (TABBED_COMPONENTS.size() > 0 && index < TABBED_COMPONENTS.size()) {
components = TABBED_COMPONENTS.get(index);
}
if (container != null) {
if (components != null) {
for (int i = 0; i < components.size(); i++) {
BeanInstance tempInstance = (BeanInstance) components.elementAt(i);
Object tempBean = tempInstance.getBean();
if (Beans.isInstanceOf(tempBean, JComponent.class)) {
container.add((JComponent) tempBean);
}
}
}
container.revalidate();
}
}
/**
* Return the list of displayed beans
*
* @param tab varargs parameter specifying the index of the collection of
* beans to return - if omitted then the first (i.e. primary)
* collection of beans is returned
*
* @return a vector of beans
*/
public static Vector<Object> getBeanInstances(Integer... tab) {
Vector<Object> returnV = null;
int index = 0;
if (tab.length > 0) {
index = tab[0].intValue();
}
if (TABBED_COMPONENTS.size() > 0) {
returnV = TABBED_COMPONENTS.get(index);
}
return returnV;
}
/**
* Adds the supplied collection of beans at the supplied index in the list of
* collections. If the index is not supplied then the primary collection is
* set (i.e. index 0). Also adds the beans to the supplied JComponent
* container (if not null)
*
* @param beanInstances a <code>Vector</code> value
* @param container a <code>JComponent</code> value
*/
public static void setBeanInstances(Vector<Object> beanInstances,
JComponent container, Integer... tab) {
removeAllBeansFromContainer(container, tab);
if (container != null) {
for (int i = 0; i < beanInstances.size(); i++) {
Object bean = ((BeanInstance) beanInstances.elementAt(i)).getBean();
if (Beans.isInstanceOf(bean, JComponent.class)) {
container.add((JComponent) bean);
}
}
container.revalidate();
container.repaint();
}
int index = 0;
if (tab.length > 0) {
index = tab[0].intValue();
}
if (index < TABBED_COMPONENTS.size()) {
TABBED_COMPONENTS.set(index, beanInstances);
}
// COMPONENTS = beanInstances;
}
/**
* Adds the supplied collection of beans to the end of the list of collections
* and to the JComponent container (if not null)
*
* @param beanInstances the vector of bean instances to add
* @param container
*/
public static void addBeanInstances(Vector<Object> beanInstances,
JComponent container) {
// reset(container);
if (container != null) {
for (int i = 0; i < beanInstances.size(); i++) {
Object bean = ((BeanInstance) beanInstances.elementAt(i)).getBean();
if (Beans.isInstanceOf(bean, JComponent.class)) {
container.add((JComponent) bean);
}
}
container.revalidate();
container.repaint();
}
TABBED_COMPONENTS.add(beanInstances);
}
/**
* Remove the vector of bean instances from the supplied index in the list of
* collections.
*
* @param tab the index of the vector of beans to remove.
*/
public static void removeBeanInstances(JComponent container, Integer tab) {
if (tab >= 0 && tab < TABBED_COMPONENTS.size()) {
System.out.println("Removing vector of beans at index: " + tab);
removeAllBeansFromContainer(container, tab);
TABBED_COMPONENTS.remove(tab.intValue());
}
}
/**
* Renders the textual labels for the beans.
*
* @param gx a <code>Graphics</code> object on which to render the labels
*/
public static void paintLabels(Graphics gx, Integer... tab) {
int index = 0;
if (tab.length > 0) {
index = tab[0].intValue();
}
Vector<Object> components = null;
if (TABBED_COMPONENTS.size() > 0 && index < TABBED_COMPONENTS.size()) {
components = TABBED_COMPONENTS.get(index);
}
if (components != null) {
gx.setFont(new Font(null, Font.PLAIN, 9));
FontMetrics fm = gx.getFontMetrics();
int hf = fm.getAscent();
for (int i = 0; i < components.size(); i++) {
BeanInstance bi = (BeanInstance) components.elementAt(i);
if (!(bi.getBean() instanceof Visible)) {
continue;
}
int cx = bi.getX();
int cy = bi.getY();
int width = ((JComponent) bi.getBean()).getWidth();
int height = ((JComponent) bi.getBean()).getHeight();
String label = ((Visible) bi.getBean()).getVisual().getText();
int labelwidth = fm.stringWidth(label);
if (labelwidth < width) {
gx.drawString(label, (cx + (width / 2)) - (labelwidth / 2), cy
+ height + hf + 2);
} else {
// split label
// find mid point
int mid = label.length() / 2;
// look for split point closest to the mid
int closest = label.length();
int closestI = -1;
for (int z = 0; z < label.length(); z++) {
if (label.charAt(z) < 'a') {
if (Math.abs(mid - z) < closest) {
closest = Math.abs(mid - z);
closestI = z;
}
}
}
if (closestI != -1) {
String left = label.substring(0, closestI);
String right = label.substring(closestI, label.length());
if (left.length() > 1 && right.length() > 1) {
gx.drawString(left, (cx + (width / 2))
- (fm.stringWidth(left) / 2), cy + height + (hf * 1) + 2);
gx.drawString(right, (cx + (width / 2))
- (fm.stringWidth(right) / 2), cy + height + (hf * 2) + 2);
} else {
gx.drawString(label, (cx + (width / 2))
- (fm.stringWidth(label) / 2), cy + height + (hf * 1) + 2);
}
} else {
gx.drawString(label, (cx + (width / 2))
- (fm.stringWidth(label) / 2), cy + height + (hf * 1) + 2);
}
}
}
}
}
/**
* Returns a list of start points (if any) in the indexed flow
*
* @param tab varargs integer index of the flow to search for start points.
* Defaults to 0 if not supplied.
* @return a list of BeanInstances who's beans implement Startable
*/
public static List<BeanInstance> getStartPoints(Integer... tab) {
List<BeanInstance> startPoints = new ArrayList<BeanInstance>();
int index = 0;
if (tab.length > 0) {
index = tab[0].intValue();
}
Vector<Object> components = null;
if (TABBED_COMPONENTS.size() > 0 && index < TABBED_COMPONENTS.size()) {
components = TABBED_COMPONENTS.get(index);
for (int i = 0; i < components.size(); i++) {
BeanInstance t = (BeanInstance) components.elementAt(i);
if (t.getBean() instanceof Startable) {
startPoints.add(t);
}
}
}
return startPoints;
}
/**
* Search for a named bean in the indexed flow
*
* @param beanName the name of the bean to look for
* @param tab varargs integer index of the flow to search in
* @return a matching BeanInstance or null if no match was found
*/
public static BeanInstance findInstance(String beanName, Integer... tab) {
BeanInstance found = null;
int index = 0;
if (tab.length > 0) {
index = tab[0].intValue();
}
Vector<Object> components = null;
if (TABBED_COMPONENTS.size() > 0 && index < TABBED_COMPONENTS.size()) {
components = TABBED_COMPONENTS.get(index);
for (int i = 0; i < components.size(); i++) {
BeanInstance t = (BeanInstance) components.elementAt(i);
if (t.getBean() instanceof BeanCommon) {
String bN = ((BeanCommon) t).getCustomName();
if (bN.equals(beanName)) {
found = t;
break;
}
}
}
}
return found;
}
/**
* Looks for a bean (if any) whose bounds contain the supplied point
*
* @param p a point
* @return a bean that contains the supplied point or null if no bean contains
* the point
*/
public static BeanInstance findInstance(Point p, Integer... tab) {
int index = 0;
if (tab.length > 0) {
index = tab[0].intValue();
}
Vector<Object> components = null;
if (TABBED_COMPONENTS.size() > 0 && index < TABBED_COMPONENTS.size()) {
components = TABBED_COMPONENTS.get(index);
}
Rectangle tempBounds = new Rectangle();
for (int i = 0; i < components.size(); i++) {
BeanInstance t = (BeanInstance) components.elementAt(i);
JComponent temp = (JComponent) t.getBean();
tempBounds = temp.getBounds(tempBounds);
if (tempBounds.contains(p)) {
return t;
}
}
return null;
}
/**
* Looks for all beans (if any) located within the supplied bounding box. Also
* adjusts the bounding box to be a tight fit around all contained beans
*
* @param boundingBox the bounding rectangle
* @return a Vector of BeanInstances
*/
public static Vector<Object> findInstances(Rectangle boundingBox,
Integer... tab) {
int index = 0;
if (tab.length > 0) {
index = tab[0].intValue();
}
Vector<Object> components = null;
if (TABBED_COMPONENTS.size() > 0 && index < TABBED_COMPONENTS.size()) {
components = TABBED_COMPONENTS.get(index);
}
Graphics gx = null;
FontMetrics fm = null;
int centerX, centerY;
int minX = Integer.MAX_VALUE;
int minY = Integer.MAX_VALUE;
int maxX = Integer.MIN_VALUE;
int maxY = Integer.MIN_VALUE;
Vector<Object> result = new Vector<Object>();
for (int i = 0; i < components.size(); i++) {
BeanInstance t = (BeanInstance) components.elementAt(i);
centerX = t.getX() + (t.getWidth() / 2);
centerY = t.getY() + (t.getHeight() / 2);
if (boundingBox.contains(centerX, centerY)) {
result.addElement(t);
// adjust bounding box stuff
// int hf = 0;
if (gx == null) {
gx = ((JComponent) t.getBean()).getGraphics();
gx.setFont(new Font(null, Font.PLAIN, 9));
fm = gx.getFontMetrics();
// hf = fm.getAscent();
}
String label = "";
if (t.getBean() instanceof Visible) {
label = ((Visible) t.getBean()).getVisual().getText();
}
int labelwidth = fm.stringWidth(label);
/*
* if (label.length() == 0) { heightMultiplier = 0; }
*/
int brx = 0;
int blx = 0;
if (centerX - (labelwidth / 2) - 2 < t.getX()) {
blx = (centerX - (labelwidth / 2) - 2);
brx = centerX + (labelwidth / 2) + 2;
} else {
blx = t.getX() - 2;
brx = t.getX() + t.getWidth() + 2;
}
if (blx < minX) {
minX = blx;
}
if (brx > maxX) {
maxX = brx;
}
if (t.getY() - 2 < minY) {
minY = t.getY() - 2;
}
if (t.getY() + t.getHeight() + 2 > maxY) {
maxY = t.getY() + t.getHeight() + 2;
}
}
}
boundingBox.setBounds(minX, minY, maxX - minX, maxY - minY);
return result;
}
/**
* Creates a new <code>BeanInstance</code> instance.
*
* @param container a <code>JComponent</code> to add the bean to
* @param bean the bean to add
* @param x the x coordinate of the bean
* @param y the y coordinate of the bean
*/
public BeanInstance(JComponent container, Object bean, int x, int y,
Integer... tab) {
m_bean = bean;
m_x = x;
m_y = y;
addBean(container, tab);
}
/**
* Creates a new <code>BeanInstance</code> instance given the fully qualified
* name of the bean
*
* @param container a <code>JComponent</code> to add the bean to
* @param beanName the fully qualified name of the bean
* @param x the x coordinate of the bean
* @param y th y coordinate of the bean
*/
public BeanInstance(JComponent container, String beanName, int x, int y,
Integer... tab) {
m_x = x;
m_y = y;
// try and instantiate the named component
try {
m_bean = Beans.instantiate(null, beanName);
} catch (Exception ex) {
ex.printStackTrace();
return;
}
addBean(container, tab);
}
/**
* Remove this bean from the list of beans and from the containing component
*
* @param container the <code>JComponent</code> that holds the bean
*/
public void removeBean(JComponent container, Integer... tab) {
int index = 0;
if (tab.length > 0) {
index = tab[0].intValue();
}
Vector<Object> components = null;
if (TABBED_COMPONENTS.size() > 0 && index < TABBED_COMPONENTS.size()) {
components = TABBED_COMPONENTS.get(index);
}
for (int i = 0; i < components.size(); i++) {
if (components.elementAt(i) == this) {
System.out.println("Removing bean");
components.removeElementAt(i);
}
}
if (container != null) {
container.remove((JComponent) m_bean);
container.revalidate();
container.repaint();
}
}
public static void appendBeans(JComponent container, Vector<Object> beans,
int tab) {
if (TABBED_COMPONENTS.size() > 0 && tab < TABBED_COMPONENTS.size()) {
Vector<Object> components = TABBED_COMPONENTS.get(tab);
//
for (int i = 0; i < beans.size(); i++) {
components.add(beans.get(i));
if (container != null) {
Object bean = ((BeanInstance) beans.elementAt(i)).getBean();
if (Beans.isInstanceOf(bean, JComponent.class)) {
container.add((JComponent) bean);
}
}
}
if (container != null) {
container.revalidate();
container.repaint();
}
}
}
/**
* Adds this bean to the global list of beans and to the supplied container.
* The constructor calls this method, so a client should not need to unless
* they have called removeBean and then wish to have it added again.
*
* @param container the Component on which this BeanInstance will be displayed
*/
public void addBean(JComponent container, Integer... tab) {
int index = 0;
if (tab.length > 0) {
index = tab[0].intValue();
}
Vector<Object> components = null;
if (TABBED_COMPONENTS.size() > 0 && index < TABBED_COMPONENTS.size()) {
components = TABBED_COMPONENTS.get(index);
}
// do nothing if we are already in the list
if (components.contains(this)) {
return;
}
// Ignore invisible components
if (!Beans.isInstanceOf(m_bean, JComponent.class)) {
System.out.println("Component is invisible!");
return;
}
components.addElement(this);
// Position and layout the component
JComponent c = (JComponent) m_bean;
Dimension d = c.getPreferredSize();
int dx = (int) (d.getWidth() / 2);
int dy = (int) (d.getHeight() / 2);
m_x -= dx;
m_y -= dy;
c.setLocation(m_x, m_y);
// c.doLayout();
c.validate();
// bp.addBean(c);
// c.repaint();
if (container != null) {
container.add(c);
container.revalidate();
}
}
/**
* Gets the bean encapsulated in this instance
*
* @return an <code>Object</code> value
*/
public Object getBean() {
return m_bean;
}
/**
* Gets the x coordinate of this bean
*
* @return an <code>int</code> value
*/
public int getX() {
return m_x;
}
/**
* Gets the y coordinate of this bean
*
* @return an <code>int</code> value
*/
public int getY() {
return m_y;
}
/**
* Gets the width of this bean
*
* @return an <code>int</code> value
*/
public int getWidth() {
return ((JComponent) m_bean).getWidth();
}
/**
* Gets the height of this bean
*
* @return an <code>int</code> value
*/
public int getHeight() {
return ((JComponent) m_bean).getHeight();
}
/**
* Set the x and y coordinates of this bean
*
* @param newX the x coordinate
* @param newY the y coordinate
*/
public void setXY(int newX, int newY) {
setX(newX);
setY(newY);
if (getBean() instanceof MetaBean) {
((MetaBean) getBean()).shiftBeans(this, false);
}
}
/**
* Sets the x coordinate of this bean
*
* @param newX an <code>int</code> value
*/
public void setX(int newX) {
m_x = newX;
((JComponent) m_bean).setLocation(m_x, m_y);
((JComponent) m_bean).validate();
}
/**
* Sets the y coordinate of this bean
*
* @param newY an <code>int</code> value
*/
public void setY(int newY) {
m_y = newY;
((JComponent) m_bean).setLocation(m_x, m_y);
((JComponent) m_bean).validate();
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/BeanVisual.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/>.
*/
/*
* BeanVisual.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import weka.core.WekaPackageClassLoaderManager;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
/**
* BeanVisual encapsulates icons and label for a given bean. Has methods to load
* icons, set label text and toggle between static and animated versions of a
* bean's icon.
*
* @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a>
* @version $Revision$
* @since 1.0
* @see JPanel
* @see Serializable
*/
public class BeanVisual extends JPanel {
/** for serialization */
private static final long serialVersionUID = -6677473561687129614L;
public static final String ICON_PATH = "weka/gui/beans/icons/";
public static final int NORTH_CONNECTOR = 0;
public static final int SOUTH_CONNECTOR = 1;
public static final int EAST_CONNECTOR = 2;
public static final int WEST_CONNECTOR = 3;
/**
* Holds name (including path) of the static icon
*/
protected String m_iconPath;
/**
* Holds name (including path) of the animated icon
*/
protected String m_animatedIconPath;
/**
* ImageIcons for the icons. Is transient because for some reason animated
* gifs cease to be animated after restoring from serialization. Icons are
* re-loaded from source after deserialization
*/
protected transient ImageIcon m_icon;
protected transient ImageIcon m_animatedIcon;
/**
* Name for the bean
*/
protected String m_visualName;
protected JLabel m_visualLabel;
/**
* Container for the icon
*/
// protected IconHolder m_visualHolder;
// protected JLabel m_textLabel;
// private final boolean m_stationary = true;
private final PropertyChangeSupport m_pcs = new PropertyChangeSupport(this);
private boolean m_displayConnectors = false;
private Color m_connectorColor = Color.blue;
/**
* Constructor
*
* @param visualName name for the bean
* @param iconPath path to the icon file
* @param animatedIconPath path to the animated icon file
*/
public BeanVisual(String visualName, String iconPath, String animatedIconPath) {
loadIcons(iconPath, animatedIconPath);
m_visualName = visualName;
// m_textLabel = new JLabel(m_visualName, JLabel.CENTER);
m_visualLabel = new JLabel(m_icon);
setLayout(new BorderLayout());
// m_visualHolder = new IconHolder(m_visualLabel);
add(m_visualLabel, BorderLayout.CENTER);
Dimension d = m_visualLabel.getPreferredSize();
// this.setSize((int)d.getWidth()+50, (int)d.getHeight()+50);
Dimension d2 = new Dimension((int) d.getWidth() + 10,
(int) d.getHeight() + 10);
setMinimumSize(d2);
setPreferredSize(d2);
setMaximumSize(d2);
}
/**
* Reduce this BeanVisual's icon size by the given factor
*
* @param factor the factor by which to reduce the icon size by
*/
public void scale(int factor) {
if (m_icon != null) {
removeAll();
Image pic = m_icon.getImage();
int width = m_icon.getIconWidth();
int height = m_icon.getIconHeight();
int reduction = width / factor;
width -= reduction;
height -= reduction;
pic = pic.getScaledInstance(width, height, Image.SCALE_SMOOTH);
m_icon = new ImageIcon(pic);
m_visualLabel = new JLabel(m_icon);
add(m_visualLabel, BorderLayout.CENTER);
Dimension d = m_visualLabel.getPreferredSize();
// this.setSize((int)d.getWidth()+50, (int)d.getHeight()+50);
Dimension d2 = new Dimension((int) d.getWidth() + 10,
(int) d.getHeight() + 10);
setMinimumSize(d2);
setPreferredSize(d2);
setMaximumSize(d2);
}
}
public Image scale(double percent) {
if (m_icon != null) {
Image pic = m_icon.getImage();
double width = m_icon.getIconWidth();
double height = m_icon.getIconHeight();
width *= percent;
height *= percent;
pic = pic
.getScaledInstance((int) width, (int) height, Image.SCALE_SMOOTH);
return pic;
}
return null;
}
/**
* Loads static and animated versions of a beans icons. These are assumed to
* be defined in the system resource location (i.e. in the CLASSPATH). If the
* named icons do not exist, no changes to the visual appearance is made.
* Since default icons for generic types of beans (eg. DataSource, Classifier
* etc) are assumed to exist, it allows developers to add custom icons for for
* specific instantiations of these beans (eg. J48, DiscretizeFilter etc) at
* their leisure.
*
* @param iconPath path to
* @param animatedIconPath a <code>String</code> value
*/
public boolean loadIcons(String iconPath, String animatedIconPath) {
boolean success = true;
// java.net.URL imageURL = ClassLoader.getSystemResource(iconPath);
java.net.URL imageURL = WekaPackageClassLoaderManager.getWekaPackageClassLoaderManager().findResource(iconPath);
//java.net.URL imageURL = this.getClass().getClassLoader()
// .getResource(iconPath);
if (imageURL == null) {
// System.err.println("Warning: unable to load "+iconPath);
} else {
Image pic = Toolkit.getDefaultToolkit().getImage(imageURL);
m_icon = new ImageIcon(pic);
if (m_visualLabel != null) {
m_visualLabel.setIcon(m_icon);
}
}
// imageURL = ClassLoader.getSystemResource(animatedIconPath);
imageURL = WekaPackageClassLoaderManager.getWekaPackageClassLoaderManager().findResource(animatedIconPath);
// imageURL = this.getClass().getClassLoader().getResource(animatedIconPath);
if (imageURL == null) {
// System.err.println("Warning: unable to load "+animatedIconPath);
success = false;
} else {
Image pic2 = Toolkit.getDefaultToolkit().getImage(imageURL);
m_animatedIcon = new ImageIcon(pic2);
}
m_iconPath = iconPath;
m_animatedIconPath = animatedIconPath;
return success;
}
/**
* Set the label for the visual. Informs any property change listeners
*
* @param text the label
*/
public void setText(String text) {
m_visualName = text;
// m_textLabel.setText(m_visualName);
m_pcs.firePropertyChange("label", null, null);
}
/**
* Get the visual's label
*
* @return a <code>String</code> value
*/
public String getText() {
return m_visualName;
}
/**
* Set the static version of the icon.
*
* This method has been deprecated and now has no affect. A future version of
* the KnowledgeFlow application may orchestrate the display of which
* components are active graphically
*/
@Deprecated
public void setStatic() {
// setDisplayConnectors(false);
// m_visualLabel.setIcon(m_icon);
}
/**
* Set the animated version of the icon
*
* This method has been deprecated and now has no affect. A future version of
* the KnowledgeFlow application may orchestrate the display of which
* components are active graphically
*/
@Deprecated
public void setAnimated() {
// setDisplayConnectors(true);
// m_visualLabel.setIcon(m_animatedIcon);
}
/**
* Returns the coordinates of the closest "connector" point to the supplied
* point. Coordinates are in the parent containers coordinate space.
*
* @param pt the reference point
* @return the closest connector point
*/
public Point getClosestConnectorPoint(Point pt) {
int sourceX = getParent().getX();
int sourceY = getParent().getY();
int sourceWidth = getWidth();
int sourceHeight = getHeight();
int sourceMidX = sourceX + (sourceWidth / 2);
int sourceMidY = sourceY + (sourceHeight / 2);
int x = (int) pt.getX();
int y = (int) pt.getY();
Point closest = new Point();
int cx = (Math.abs(x - sourceMidX) < Math.abs(y - sourceMidY)) ? sourceMidX
: ((x < sourceMidX) ? sourceX : sourceX + sourceWidth);
int cy = (Math.abs(y - sourceMidY) < Math.abs(x - sourceMidX)) ? sourceMidY
: ((y < sourceMidY) ? sourceY : sourceY + sourceHeight);
closest.setLocation(cx, cy);
return closest;
}
/**
* Returns the coordinates of the connector point given a compass point
*
* @param compassPoint a compass point
* @return a <code>Point</code> value
*/
public Point getConnectorPoint(int compassPoint) {
int sourceX = getParent().getX();
int sourceY = getParent().getY();
int sourceWidth = getWidth();
int sourceHeight = getHeight();
int sourceMidX = sourceX + (sourceWidth / 2);
int sourceMidY = sourceY + (sourceHeight / 2);
switch (compassPoint) {
case NORTH_CONNECTOR:
return new Point(sourceMidX, sourceY);
case SOUTH_CONNECTOR:
return new Point(sourceMidX, sourceY + sourceHeight);
case WEST_CONNECTOR:
return new Point(sourceX, sourceMidY);
case EAST_CONNECTOR:
return new Point(sourceX + sourceWidth, sourceMidY);
default:
System.err.println("Unrecognised connectorPoint (BeanVisual)");
}
return new Point(sourceX, sourceY);
}
/**
* Returns the static icon
*
* @return an <code>ImageIcon</code> value
*/
public ImageIcon getStaticIcon() {
return m_icon;
}
/**
* Returns the animated icon
*
* @return an <code>ImageIcon</code> value
*/
public ImageIcon getAnimatedIcon() {
return m_animatedIcon;
}
/**
* returns the path for the icon
*
* @return the path for the icon
*/
public String getIconPath() {
return m_iconPath;
}
/**
* returns the path for the animated icon
*
* @return the path for the animated icon
*/
public String getAnimatedIconPath() {
return m_animatedIconPath;
}
/**
* Turn on/off the connector points
*
* @param dc a <code>boolean</code> value
*/
public void setDisplayConnectors(boolean dc) {
// m_visualHolder.setDisplayConnectors(dc);
m_displayConnectors = dc;
m_connectorColor = Color.blue;
repaint();
}
/**
* Turn on/off the connector points
*
* @param dc a <code>boolean</code> value
* @param c the Color to use
*/
public void setDisplayConnectors(boolean dc, Color c) {
setDisplayConnectors(dc);
m_connectorColor = c;
}
/**
* Add a listener for property change events
*
* @param pcl a <code>PropertyChangeListener</code> value
*/
@Override
public void addPropertyChangeListener(PropertyChangeListener pcl) {
if (m_pcs != null && pcl != null) {
m_pcs.addPropertyChangeListener(pcl);
}
}
/**
* Remove a property change listener
*
* @param pcl a <code>PropertyChangeListener</code> value
*/
@Override
public void removePropertyChangeListener(PropertyChangeListener pcl) {
if (m_pcs != null && pcl != null) {
m_pcs.removePropertyChangeListener(pcl);
}
}
@Override
public void paintComponent(Graphics gx) {
((Graphics2D) gx).setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
super.paintComponent(gx);
if (m_displayConnectors) {
gx.setColor(m_connectorColor);
int midx = (int) (this.getWidth() / 2.0);
int midy = (int) (this.getHeight() / 2.0);
gx.fillOval(midx - 2, 0, 5, 5);
gx.fillOval(midx - 2, this.getHeight() - 5, 5, 5);
gx.fillOval(0, midy - 2, 5, 5);
gx.fillOval(this.getWidth() - 5, midy - 2, 5, 5);
}
}
/**
* Overides default read object in order to reload icons. This is necessary
* because for some strange reason animated gifs stop being animated after
* being serialized/deserialized.
*
* @param ois an <code>ObjectInputStream</code> value
* @exception IOException if an error occurs
* @exception ClassNotFoundException if an error occurs
*/
private void readObject(ObjectInputStream ois) throws IOException,
ClassNotFoundException {
try {
ois.defaultReadObject();
remove(m_visualLabel);
m_visualLabel = new JLabel(m_icon);
loadIcons(m_iconPath, m_animatedIconPath);
add(m_visualLabel, BorderLayout.CENTER);
Dimension d = m_visualLabel.getPreferredSize();
Dimension d2 = new Dimension((int) d.getWidth() + 10,
(int) d.getHeight() + 10);
setMinimumSize(d2);
setPreferredSize(d2);
setMaximumSize(d2);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/BeansProperties.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/>.
*/
/*
* BeansProperties.java
* Copyright (C) 2009-2013 University of Waikato, Hamilton, New Zealand
*/
package weka.gui.beans;
import weka.core.PluginManager;
import weka.core.Utils;
import weka.core.WekaPackageClassLoaderManager;
import weka.core.metastore.MetaStore;
import weka.core.metastore.XMLFileBasedMetaStore;
import javax.swing.JOptionPane;
import java.io.File;
import java.io.FileInputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;
import java.util.SortedSet;
import java.util.StringTokenizer;
import java.util.TreeSet;
/**
* Utility class encapsulating various properties for the KnowledgeFlow and
* providing methods to register and deregister plugin Bean components
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision$
*/
public class BeansProperties implements Serializable {
/**
* For serialization
*/
private static final long serialVersionUID = 7183413615090695785L;
/**
* Location of the property file for the KnowledgeFlowApp
*/
protected static final String PROPERTY_FILE = "weka/gui/beans/Beans.props";
/** Location of the property file listing available templates */
protected static final String TEMPLATE_PROPERTY_FILE =
"weka/gui/beans/templates/templates.props";
/** The paths to template resources */
protected static List<String> TEMPLATE_PATHS;
/** Short descriptions for templates suitable for displaying in a menu */
protected static List<String> TEMPLATE_DESCRIPTIONS;
/** Contains the editor properties */
protected static Properties BEAN_PROPERTIES;
/** Contains the plugin components properties */
protected static ArrayList<Properties> BEAN_PLUGINS_PROPERTIES =
new ArrayList<Properties>();
/**
* Contains the user's selection of available perspectives to be visible in
* the perspectives toolbar
*/
protected static String VISIBLE_PERSPECTIVES_PROPERTIES_FILE =
"weka/gui/beans/VisiblePerspectives.props";
/** Those perspectives that the user has opted to have visible in the toolbar */
protected static SortedSet<String> VISIBLE_PERSPECTIVES;
private static boolean s_pluginManagerIntialized = false;
/** Default metastore for configurations etc. */
protected static MetaStore s_kfMetaStore = new XMLFileBasedMetaStore();
/**
* Get the metastore
*
* @return the metastore
*/
public static MetaStore getMetaStore() {
return s_kfMetaStore;
}
public static void addToPluginBeanProps(File beanPropsFile) throws Exception {
Properties tempP = new Properties();
tempP.load(new FileInputStream(beanPropsFile));
if (!BEAN_PLUGINS_PROPERTIES.contains(tempP)) {
BEAN_PLUGINS_PROPERTIES.add(tempP);
}
}
public static void removeFromPluginBeanProps(File beanPropsFile)
throws Exception {
Properties tempP = new Properties();
FileInputStream fis = new FileInputStream(beanPropsFile);
try {
tempP.load(fis);
if (BEAN_PLUGINS_PROPERTIES.contains(tempP)) {
BEAN_PLUGINS_PROPERTIES.remove(tempP);
}
} finally {
fis.close();
}
}
/**
* Loads KnowledgeFlow properties and any plugins (adds jars to the classpath)
*/
public static synchronized void loadProperties() {
if (BEAN_PROPERTIES == null) {
weka.core.WekaPackageManager.loadPackages(false);
weka.core.logging.Logger.log(weka.core.logging.Logger.Level.INFO,
"[KnowledgeFlow] Loading properties and plugins...");
/** Loads the configuration property file */
// static {
// Allow a properties file in the current directory to override
try {
BEAN_PROPERTIES = Utils.readProperties(PROPERTY_FILE);
java.util.Enumeration<?> keys = BEAN_PROPERTIES.propertyNames();
if (!keys.hasMoreElements()) {
throw new Exception(
"Could not read a configuration file for the bean\n"
+ "panel. An example file is included with the Weka distribution.\n"
+ "This file should be named \"" + PROPERTY_FILE + "\" and\n"
+ "should be placed either in your user home (which is set\n"
+ "to \"" + System.getProperties().getProperty("user.home")
+ "\")\n" + "or the directory that java was started from\n");
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getMessage(), "KnowledgeFlow",
JOptionPane.ERROR_MESSAGE);
}
if (VISIBLE_PERSPECTIVES == null) {
// set up built-in perspectives
Properties pp = new Properties();
pp.setProperty("weka.gui.beans.KnowledgeFlow.Perspectives",
"weka.gui.beans.ScatterPlotMatrix,weka.gui.beans.AttributeSummarizer,"
+ "weka.gui.beans.SQLViewerPerspective");
BEAN_PLUGINS_PROPERTIES.add(pp);
VISIBLE_PERSPECTIVES = new TreeSet<String>();
try {
Properties visible =
Utils.readProperties(VISIBLE_PERSPECTIVES_PROPERTIES_FILE);
Enumeration<?> keys = visible.propertyNames();
if (keys.hasMoreElements()) {
String listedPerspectives =
visible
.getProperty("weka.gui.beans.KnowledgeFlow.SelectedPerspectives");
if (listedPerspectives != null && listedPerspectives.length() > 0) {
// split up the list of user selected perspectives and populate
// VISIBLE_PERSPECTIVES
StringTokenizer st =
new StringTokenizer(listedPerspectives, ", ");
while (st.hasMoreTokens()) {
String perspectiveName = st.nextToken().trim();
weka.core.logging.Logger.log(
weka.core.logging.Logger.Level.INFO, "Adding perspective "
+ perspectiveName + " to visible list");
VISIBLE_PERSPECTIVES.add(perspectiveName);
}
}
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getMessage(), "KnowledgeFlow",
JOptionPane.ERROR_MESSAGE);
}
}
}
// System templates
if (TEMPLATE_PATHS == null) {
TEMPLATE_PATHS = new ArrayList<String>();
TEMPLATE_DESCRIPTIONS = new ArrayList<String>();
try {
Properties templateProps = Utils.readProperties(TEMPLATE_PROPERTY_FILE);
String paths =
templateProps.getProperty("weka.gui.beans.KnowledgeFlow.templates");
String descriptions =
templateProps
.getProperty("weka.gui.beans.KnowledgeFlow.templates.desc");
if (paths == null || paths.length() == 0) {
weka.core.logging.Logger.log(weka.core.logging.Logger.Level.WARNING,
"[KnowledgeFlow] WARNING: no templates found in classpath");
} else {
String[] templates = paths.split(",");
String[] desc = descriptions.split(",");
if (templates.length != desc.length) {
throw new Exception("Number of template descriptions does "
+ "not match number of templates.");
}
for (String template : templates) {
TEMPLATE_PATHS.add(template.trim());
}
for (String d : desc) {
TEMPLATE_DESCRIPTIONS.add(d.trim());
}
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getMessage(), "KnowledgeFlow",
JOptionPane.ERROR_MESSAGE);
}
}
if (!s_pluginManagerIntialized && BEAN_PLUGINS_PROPERTIES != null
&& BEAN_PLUGINS_PROPERTIES.size() > 0) {
for (int i = 0; i < BEAN_PLUGINS_PROPERTIES.size(); i++) {
Properties tempP = BEAN_PLUGINS_PROPERTIES.get(i);
// Check for OffScreenChartRenderers
String offscreenRenderers =
tempP.getProperty("weka.gui.beans.OffscreenChartRenderer");
if (offscreenRenderers != null && offscreenRenderers.length() > 0) {
String[] parts = offscreenRenderers.split(",");
for (String renderer : parts) {
renderer = renderer.trim();
// Check that we can instantiate it successfully
try {
Object p = WekaPackageClassLoaderManager.objectForName(renderer);
// Class.forName(renderer).newInstance();
if (p instanceof OffscreenChartRenderer) {
String name = ((OffscreenChartRenderer) p).rendererName();
PluginManager.addPlugin(
"weka.gui.beans.OffscreenChartRenderer", name, renderer);
weka.core.logging.Logger.log(
weka.core.logging.Logger.Level.INFO,
"[KnowledgeFlow] registering chart rendering " + "plugin: "
+ renderer);
}
} catch (Exception ex) {
weka.core.logging.Logger
.log(weka.core.logging.Logger.Level.WARNING,
"[KnowledgeFlow] WARNING: "
+ "unable to instantiate chart renderer \"" + renderer
+ "\"");
ex.printStackTrace();
}
}
}
// Check for user templates
String templatePaths =
tempP.getProperty("weka.gui.beans.KnowledgeFlow.templates");
String templateDesc =
tempP.getProperty("weka.gui.beans.KnowledgeFlow.templates.desc");
if (templatePaths != null && templatePaths.length() > 0
&& templateDesc != null && templateDesc.length() > 0) {
String[] templates = templatePaths.split(",");
String[] desc = templateDesc.split(",");
// quietly ignore any user-templates that are not consistent
if (templates.length == desc.length) {
for (int kk = 0; kk < templates.length; kk++) {
String pth = templates[kk];
String d = desc[kk];
if (!TEMPLATE_PATHS.contains(pth)) {
TEMPLATE_PATHS.add(pth.trim());
TEMPLATE_DESCRIPTIONS.add(d.trim());
}
}
}
}
}
s_pluginManagerIntialized = true;
}
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/ChartEvent.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/>.
*/
/*
* ChartEvent.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.util.EventObject;
import java.util.Vector;
/**
* Event encapsulating info for plotting a data point on the StripChart
*
* @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a>
* @version $Revision$
*/
public class ChartEvent extends EventObject {
/** for serialization */
private static final long serialVersionUID = 7812460715499569390L;
private Vector<String> m_legendText;
private double m_max;
private double m_min;
private boolean m_reset;
/**
* Y values of the data points
*/
private double[] m_dataPoint;
/**
* Creates a new <code>ChartEvent</code> instance.
*
* @param source the source of the event
* @param legendText a vector of strings to display in the legend
* @param min minimum y value
* @param max maximum y value
* @param dataPoint an array of y values to plot
* @param reset true if display is to be reset
*/
public ChartEvent(Object source, Vector<String> legendText, double min,
double max, double[] dataPoint, boolean reset) {
super(source);
m_legendText = legendText;
m_max = max;
m_min = min;
m_dataPoint = dataPoint;
m_reset = reset;
}
/**
* Creates a new <code>ChartEvent</code> instance.
*
* @param source the source of the event
*/
public ChartEvent(Object source) {
super(source);
}
/**
* Get the legend text vector
*
* @return a <code>Vector</code> value
*/
public Vector<String> getLegendText() {
return m_legendText;
}
/**
* Set the legend text vector
*
* @param lt a <code>Vector</code> value
*/
public void setLegendText(Vector<String> lt) {
m_legendText = lt;
}
/**
* Get the min y value
*
* @return a <code>double</code> value
*/
public double getMin() {
return m_min;
}
/**
* Set the min y value
*
* @param m a <code>double</code> value
*/
public void setMin(double m) {
m_min = m;
}
/**
* Get the max y value
*
* @return a <code>double</code> value
*/
public double getMax() {
return m_max;
}
/**
* Set the max y value
*
* @param m a <code>double</code> value
*/
public void setMax(double m) {
m_max = m;
}
/**
* Get the data point
*
* @return a <code>double[]</code> value
*/
public double[] getDataPoint() {
return m_dataPoint;
}
/**
* Set the data point
*
* @param dp a <code>double[]</code> value
*/
public void setDataPoint(double[] dp) {
m_dataPoint = dp;
}
/**
* Set the reset flag
*
* @param reset a <code>boolean</code> value
*/
public void setReset(boolean reset) {
m_reset = reset;
}
/**
* get the value of the reset flag
*
* @return a <code>boolean</code> value
*/
public boolean getReset() {
return m_reset;
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/ChartListener.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/>.
*/
/*
* ChartListener.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.util.EventListener;
/**
* Interface to something that can process a ChartEvent
*
* @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a>
* @version $Revision$
*/
public interface ChartListener extends EventListener {
void acceptDataPoint(ChartEvent e);
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/ClassAssigner.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/>.
*/
/*
* ClassAssigner.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.awt.BorderLayout;
import java.beans.EventSetDescriptor;
import java.io.Serializable;
import java.util.Vector;
import javax.swing.JPanel;
import weka.core.Attribute;
import weka.core.Instances;
/**
* Bean that assigns a class attribute to a data set.
*
* @author Mark Hall
* @version $Revision$
*/
public class ClassAssigner extends JPanel implements Visible,
DataSourceListener, TrainingSetListener, TestSetListener, DataSource,
TrainingSetProducer, TestSetProducer, BeanCommon, EventConstraints,
Serializable, InstanceListener, StructureProducer {
/** for serialization */
private static final long serialVersionUID = 4011131665025817924L;
private String m_classColumn = "last";
/** format of instances for current incoming connection (if any) */
private Instances m_connectedFormat;
private Object m_trainingProvider;
private Object m_testProvider;
private Object m_dataProvider;
private Object m_instanceProvider;
private final Vector<TrainingSetListener> m_trainingListeners = new Vector<TrainingSetListener>();
private final Vector<TestSetListener> m_testListeners = new Vector<TestSetListener>();
private final Vector<DataSourceListener> m_dataListeners = new Vector<DataSourceListener>();
private final Vector<InstanceListener> m_instanceListeners = new Vector<InstanceListener>();
private final Vector<DataFormatListener> m_dataFormatListeners = new Vector<DataFormatListener>();
protected transient weka.gui.Logger m_logger = null;
protected BeanVisual m_visual = new BeanVisual("ClassAssigner",
BeanVisual.ICON_PATH + "ClassAssigner.gif", BeanVisual.ICON_PATH
+ "ClassAssigner_animated.gif");
/**
* Global info for this bean
*
* @return a <code>String</code> value
*/
public String globalInfo() {
return "Designate which column is to be considered the class column "
+ "in incoming data.";
}
public ClassAssigner() {
setLayout(new BorderLayout());
add(m_visual, BorderLayout.CENTER);
}
/**
* Set a custom (descriptive) name for this bean
*
* @param name the name to use
*/
@Override
public void setCustomName(String name) {
m_visual.setText(name);
}
/**
* Get the custom (descriptive) name for this bean (if one has been set)
*
* @return the custom name (or the default name)
*/
@Override
public String getCustomName() {
return m_visual.getText();
}
/**
* Tool tip text for this property
*
* @return a <code>String</code> value
*/
public String classColumnTipText() {
return "Specify the number of the column that contains the class attribute";
}
private Instances getUpstreamStructure() {
if (m_dataProvider != null && m_dataProvider instanceof StructureProducer) {
return ((StructureProducer) m_dataProvider).getStructure("dataSet");
}
if (m_trainingProvider != null
&& m_trainingProvider instanceof StructureProducer) {
return ((StructureProducer) m_trainingProvider)
.getStructure("trainingSet");
}
if (m_testProvider != null && m_testProvider instanceof StructureProducer) {
return ((StructureProducer) m_testProvider).getStructure("testSet");
}
if (m_instanceProvider != null
&& m_instanceProvider instanceof StructureProducer) {
return ((StructureProducer) m_instanceProvider).getStructure("instance");
}
return null;
}
/**
* Get the structure of the output encapsulated in the named event. If the
* structure can't be determined in advance of seeing input, or this
* StructureProducer does not generate the named event, null should be
* returned.
*
* @param eventName the name of the output event that encapsulates the
* requested output.
*
* @return the structure of the output encapsulated in the named event or null
* if it can't be determined in advance of seeing input or the named
* event is not generated by this StructureProduce.
*/
@Override
public Instances getStructure(String eventName) {
if (!eventName.equals("trainingSet") && !eventName.equals("testSet")
&& !eventName.equals("dataSet") && !eventName.equals("instance")) {
return null;
}
if (m_trainingProvider == null && m_testProvider == null
&& m_dataProvider == null && m_instanceProvider == null) {
return null;
}
if (eventName.equals("dataSet") && m_dataListeners.size() == 0) {
// downstream has asked for the structure of something that we
// are not producing at the moment
return null;
}
if (eventName.equals("trainingSet") && m_trainingListeners.size() == 0) {
// downstream has asked for the structure of something that we
// are not producing at the moment
return null;
}
if (eventName.equals("testSet") && m_testListeners.size() == 0) {
// downstream has asked for the structure of something that we
// are not producing at the moment
return null;
}
if (eventName.equals("instance") && m_instanceListeners.size() == 0) {
// downstream has asked for the structure of something that we
// are not producing at the moment
return null;
}
if (m_connectedFormat == null) {
m_connectedFormat = getUpstreamStructure();
}
if (m_connectedFormat != null) {
assignClass(m_connectedFormat);
}
return m_connectedFormat;
}
/**
* Returns the structure of the incoming instances (if any)
*
* @return an <code>Instances</code> value
*/
public Instances getConnectedFormat() {
// loaders will push instances format to us
// when the user makes configuration changes
// to the loader in the gui. However, if a fully
// configured flow is loaded then we won't get
// this information pushed to us until the
// flow is run. In this case we want to pull
// it (if possible) from upstream steps so
// that our customizer can provide the nice
// UI with the drop down box of class names.
if (m_connectedFormat == null) {
// try and pull the incoming structure
// from the upstream step (if possible)
m_connectedFormat = getUpstreamStructure();
}
return m_connectedFormat;
}
public void setClassColumn(String col) {
m_classColumn = col;
if (m_connectedFormat != null) {
assignClass(m_connectedFormat);
}
}
public String getClassColumn() {
return m_classColumn;
}
@Override
public void acceptDataSet(DataSetEvent e) {
Instances dataSet = e.getDataSet();
assignClass(dataSet);
notifyDataListeners(e);
if (e.isStructureOnly()) {
m_connectedFormat = e.getDataSet();
// tell any listening customizers (or other
notifyDataFormatListeners();
}
}
@Override
public void acceptTrainingSet(TrainingSetEvent e) {
Instances trainingSet = e.getTrainingSet();
assignClass(trainingSet);
notifyTrainingListeners(e);
if (e.isStructureOnly()) {
m_connectedFormat = e.getTrainingSet();
// tell any listening customizers (or other
notifyDataFormatListeners();
}
}
@Override
public void acceptTestSet(TestSetEvent e) {
Instances testSet = e.getTestSet();
assignClass(testSet);
notifyTestListeners(e);
if (e.isStructureOnly()) {
m_connectedFormat = e.getTestSet();
// tell any listening customizers (or other
notifyDataFormatListeners();
}
}
@Override
public void acceptInstance(InstanceEvent e) {
if (e.getStatus() == InstanceEvent.FORMAT_AVAILABLE) {
// Instances dataSet = e.getInstance().dataset();
m_connectedFormat = e.getStructure();
// System.err.println("Assigning class column...");
assignClass(m_connectedFormat);
notifyInstanceListeners(e);
// tell any listening customizers (or other interested parties)
System.err.println("Notifying customizer...");
notifyDataFormatListeners();
} else {
// Instances dataSet = e.getInstance().dataset();
// assignClass(dataSet);
notifyInstanceListeners(e);
}
}
private void assignClass(Instances dataSet) {
int classCol = -1;
if (m_classColumn.trim().toLowerCase().compareTo("last") == 0
|| m_classColumn.equalsIgnoreCase("/last")) {
dataSet.setClassIndex(dataSet.numAttributes() - 1);
} else if (m_classColumn.trim().toLowerCase().compareTo("first") == 0
|| m_classColumn.equalsIgnoreCase("/first")) {
dataSet.setClassIndex(0);
} else {
// try to look up the class attribute as a string
Attribute classAtt = dataSet.attribute(m_classColumn.trim());
if (classAtt != null) {
dataSet.setClass(classAtt);
} else {
// parse it as a number
try {
classCol = Integer.parseInt(m_classColumn.trim()) - 1;
} catch (NumberFormatException ex) {
if (m_logger != null) {
m_logger
.logMessage("Warning : can't parse '"
+ m_classColumn.trim()
+ "' as a number "
+ " or find it as an attribute in the incoming data (ClassAssigner)");
}
}
if (/* classCol < 0 || */classCol > dataSet.numAttributes() - 1) {
if (m_logger != null) {
m_logger.logMessage("Class column outside range of data "
+ "(ClassAssigner)");
}
} else {
dataSet.setClassIndex(classCol);
}
}
}
}
@SuppressWarnings("unchecked")
protected void notifyTestListeners(TestSetEvent tse) {
Vector<TestSetListener> l;
synchronized (this) {
l = (Vector<TestSetListener>) m_testListeners.clone();
}
if (l.size() > 0) {
for (int i = 0; i < l.size(); i++) {
System.err.println("Notifying test listeners " + "(ClassAssigner)");
l.elementAt(i).acceptTestSet(tse);
}
}
}
@SuppressWarnings("unchecked")
protected void notifyTrainingListeners(TrainingSetEvent tse) {
Vector<TrainingSetListener> l;
synchronized (this) {
l = (Vector<TrainingSetListener>) m_trainingListeners.clone();
}
if (l.size() > 0) {
for (int i = 0; i < l.size(); i++) {
System.err.println("Notifying training listeners " + "(ClassAssigner)");
l.elementAt(i).acceptTrainingSet(tse);
}
}
}
@SuppressWarnings("unchecked")
protected void notifyDataListeners(DataSetEvent tse) {
Vector<DataSourceListener> l;
synchronized (this) {
l = (Vector<DataSourceListener>) m_dataListeners.clone();
}
if (l.size() > 0) {
for (int i = 0; i < l.size(); i++) {
System.err.println("Notifying data listeners " + "(ClassAssigner)");
l.elementAt(i).acceptDataSet(tse);
}
}
}
@SuppressWarnings("unchecked")
protected void notifyInstanceListeners(InstanceEvent tse) {
Vector<InstanceListener> l;
synchronized (this) {
l = (Vector<InstanceListener>) m_instanceListeners.clone();
}
if (l.size() > 0) {
for (int i = 0; i < l.size(); i++) {
// System.err.println("Notifying instance listeners "
// +"(ClassAssigner)");
l.elementAt(i).acceptInstance(tse);
}
}
}
@SuppressWarnings("unchecked")
protected void notifyDataFormatListeners() {
Vector<DataFormatListener> l;
synchronized (this) {
l = (Vector<DataFormatListener>) m_dataFormatListeners.clone();
}
if (l.size() > 0) {
DataSetEvent dse = new DataSetEvent(this, m_connectedFormat);
for (int i = 0; i < l.size(); i++) {
// System.err.println("Notifying instance listeners "
// +"(ClassAssigner)");
l.elementAt(i).newDataFormat(dse);
}
}
}
@Override
public synchronized void addInstanceListener(InstanceListener tsl) {
m_instanceListeners.addElement(tsl);
if (m_connectedFormat != null) {
InstanceEvent e = new InstanceEvent(this, m_connectedFormat);
tsl.acceptInstance(e);
}
}
@Override
public synchronized void removeInstanceListener(InstanceListener tsl) {
m_instanceListeners.removeElement(tsl);
}
@Override
public synchronized void addDataSourceListener(DataSourceListener tsl) {
m_dataListeners.addElement(tsl);
// pass on any format that we might know about
if (m_connectedFormat != null) {
DataSetEvent e = new DataSetEvent(this, m_connectedFormat);
tsl.acceptDataSet(e);
}
}
@Override
public synchronized void removeDataSourceListener(DataSourceListener tsl) {
m_dataListeners.removeElement(tsl);
}
@Override
public synchronized void addTrainingSetListener(TrainingSetListener tsl) {
m_trainingListeners.addElement(tsl);
// pass on any format that we might know about
if (m_connectedFormat != null) {
TrainingSetEvent e = new TrainingSetEvent(this, m_connectedFormat);
tsl.acceptTrainingSet(e);
}
}
@Override
public synchronized void removeTrainingSetListener(TrainingSetListener tsl) {
m_trainingListeners.removeElement(tsl);
}
@Override
public synchronized void addTestSetListener(TestSetListener tsl) {
m_testListeners.addElement(tsl);
// pass on any format that we might know about
if (m_connectedFormat != null) {
TestSetEvent e = new TestSetEvent(this, m_connectedFormat);
tsl.acceptTestSet(e);
}
}
@Override
public synchronized void removeTestSetListener(TestSetListener tsl) {
m_testListeners.removeElement(tsl);
}
public synchronized void addDataFormatListener(DataFormatListener dfl) {
m_dataFormatListeners.addElement(dfl);
}
public synchronized void removeDataFormatListener(DataFormatListener dfl) {
m_dataFormatListeners.removeElement(dfl);
}
@Override
public void setVisual(BeanVisual newVisual) {
m_visual = newVisual;
}
@Override
public BeanVisual getVisual() {
return m_visual;
}
@Override
public void useDefaultVisual() {
m_visual.loadIcons(BeanVisual.ICON_PATH + "ClassAssigner.gif",
BeanVisual.ICON_PATH + "ClassAssigner_animated.gif");
}
/**
* Returns true if, at this time, the object will accept a connection
* according to the supplied event name
*
* @param eventName the event
* @return true if the object will accept a connection
*/
@Override
public boolean connectionAllowed(String eventName) {
if (eventName.compareTo("trainingSet") == 0
&& (m_trainingProvider != null || m_dataProvider != null || m_instanceProvider != null)) {
return false;
}
if (eventName.compareTo("testSet") == 0 && m_testProvider != null) {
return false;
}
if (eventName.compareTo("instance") == 0 && m_instanceProvider != null
|| m_trainingProvider != null || m_dataProvider != null) {
return false;
}
return true;
}
/**
* Returns true if, at this time, the object will accept a connection
* according to the supplied EventSetDescriptor
*
* @param esd the EventSetDescriptor
* @return true if the object will accept a connection
*/
@Override
public boolean connectionAllowed(EventSetDescriptor esd) {
return connectionAllowed(esd.getName());
}
/**
* Notify this object that it has been registered as a listener with a source
* with respect to the supplied event name
*
* @param eventName the event
* @param source the source with which this object has been registered as a
* listener
*/
@Override
public synchronized void connectionNotification(String eventName,
Object source) {
if (connectionAllowed(eventName)) {
if (eventName.compareTo("trainingSet") == 0) {
m_trainingProvider = source;
} else if (eventName.compareTo("testSet") == 0) {
m_testProvider = source;
} else if (eventName.compareTo("dataSet") == 0) {
m_dataProvider = source;
} else if (eventName.compareTo("instance") == 0) {
m_instanceProvider = source;
}
m_connectedFormat = null;
}
}
/**
* Notify this object that it has been deregistered as a listener with a
* source with respect to the supplied event name
*
* @param eventName the event
* @param source the source with which this object has been registered as a
* listener
*/
@Override
public synchronized void disconnectionNotification(String eventName,
Object source) {
if (eventName.compareTo("trainingSet") == 0) {
if (m_trainingProvider == source) {
m_trainingProvider = null;
}
}
if (eventName.compareTo("testSet") == 0) {
if (m_testProvider == source) {
m_testProvider = null;
}
}
if (eventName.compareTo("dataSet") == 0) {
if (m_dataProvider == source) {
m_dataProvider = null;
}
}
if (eventName.compareTo("instance") == 0) {
if (m_instanceProvider == source) {
m_instanceProvider = null;
}
}
m_connectedFormat = null;
}
@Override
public void setLog(weka.gui.Logger logger) {
m_logger = logger;
}
@Override
public void stop() {
// Pass on to upstream beans
if (m_trainingProvider != null && m_trainingProvider instanceof BeanCommon) {
((BeanCommon) m_trainingProvider).stop();
}
if (m_testProvider != null && m_testProvider instanceof BeanCommon) {
((BeanCommon) m_testProvider).stop();
}
if (m_dataProvider != null && m_dataProvider instanceof BeanCommon) {
((BeanCommon) m_dataProvider).stop();
}
if (m_instanceProvider != null && m_instanceProvider instanceof BeanCommon) {
((BeanCommon) m_instanceProvider).stop();
}
}
/**
* Returns true if. at this time, the bean is busy with some (i.e. perhaps a
* worker thread is performing some calculation).
*
* @return true if the bean is busy.
*/
@Override
public boolean isBusy() {
return false;
}
/**
* Returns true, if at the current time, the named event could be generated.
* Assumes that the supplied event name is an event that could be generated by
* this bean
*
* @param eventName the name of the event in question
* @return true if the named event could be generated at this point in time
*/
@Override
public boolean eventGeneratable(String eventName) {
if (eventName.compareTo("trainingSet") == 0) {
if (m_trainingProvider == null) {
return false;
} else {
if (m_trainingProvider instanceof EventConstraints) {
if (!((EventConstraints) m_trainingProvider)
.eventGeneratable("trainingSet")) {
return false;
}
}
}
}
if (eventName.compareTo("dataSet") == 0) {
if (m_dataProvider == null) {
if (m_instanceProvider == null) {
m_connectedFormat = null;
notifyDataFormatListeners();
}
return false;
} else {
if (m_dataProvider instanceof EventConstraints) {
if (!((EventConstraints) m_dataProvider).eventGeneratable("dataSet")) {
m_connectedFormat = null;
notifyDataFormatListeners();
return false;
}
}
}
}
if (eventName.compareTo("instance") == 0) {
if (m_instanceProvider == null) {
if (m_dataProvider == null) {
m_connectedFormat = null;
notifyDataFormatListeners();
}
return false;
} else {
if (m_instanceProvider instanceof EventConstraints) {
if (!((EventConstraints) m_instanceProvider)
.eventGeneratable("instance")) {
m_connectedFormat = null;
notifyDataFormatListeners();
return false;
}
}
}
}
if (eventName.compareTo("testSet") == 0) {
if (m_testProvider == null) {
return false;
} else {
if (m_testProvider instanceof EventConstraints) {
if (!((EventConstraints) m_testProvider).eventGeneratable("testSet")) {
return false;
}
}
}
}
return true;
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/ClassAssignerBeanInfo.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/>.
*/
/*
* ClassAssignerBeanInfo.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.beans.BeanDescriptor;
import java.beans.EventSetDescriptor;
import java.beans.PropertyDescriptor;
import java.beans.SimpleBeanInfo;
/**
* BeanInfo class for the class assigner bean
*
* @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a>
* @version $Revision$
*/
public class ClassAssignerBeanInfo
extends SimpleBeanInfo {
/**
* Returns the event set descriptors
*
* @return an <code>EventSetDescriptor[]</code> value
*/
public EventSetDescriptor [] getEventSetDescriptors() {
try {
EventSetDescriptor [] esds =
{ new EventSetDescriptor(DataSource.class,
"dataSet",
DataSourceListener.class,
"acceptDataSet"),
new EventSetDescriptor(DataSource.class,
"instance",
InstanceListener.class,
"acceptInstance"),
new EventSetDescriptor(TrainingSetProducer.class,
"trainingSet",
TrainingSetListener.class,
"acceptTrainingSet"),
new EventSetDescriptor(TestSetProducer.class,
"testSet",
TestSetListener.class,
"acceptTestSet") };
return esds;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
/**
* Returns the property descriptors
*
* @return a <code>PropertyDescriptor[]</code> value
*/
public PropertyDescriptor[] getPropertyDescriptors() {
try {
PropertyDescriptor p1;
p1 = new PropertyDescriptor("classColumn", ClassAssigner.class);
PropertyDescriptor [] pds = { p1 };
return pds;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public BeanDescriptor getBeanDescriptor() {
return new BeanDescriptor(weka.gui.beans.ClassAssigner.class,
ClassAssignerCustomizer.class);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/ClassAssignerCustomizer.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/>.
*/
/*
* ClassAssignerCustomizer.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import javax.swing.BorderFactory;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JPanel;
import weka.core.Attribute;
import weka.core.Instances;
import weka.gui.PropertySheetPanel;
/**
* GUI customizer for the class assigner bean
*
* @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a>
* @version $Revision$
*/
public class ClassAssignerCustomizer
extends JPanel
implements BeanCustomizer, CustomizerClosingListener,
CustomizerCloseRequester, DataFormatListener {
/** for serialization */
private static final long serialVersionUID = 476539385765301907L;
private boolean m_displayColNames = false;
private transient ClassAssigner m_classAssigner;
private transient PropertyChangeSupport m_pcSupport =
new PropertyChangeSupport(this);
private transient PropertySheetPanel m_caEditor =
new PropertySheetPanel();
private transient JComboBox m_ClassCombo = new JComboBox();
private transient JPanel m_holderP = new JPanel();
private transient ModifyListener m_modifyListener;
private transient Window m_parent;
private transient String m_backup;
public ClassAssignerCustomizer() {
setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 5, 5, 5));
setLayout(new BorderLayout());
add(new javax.swing.JLabel("ClassAssignerCustomizer"),
BorderLayout.NORTH);
m_holderP.setLayout(new BorderLayout());
m_holderP.setBorder(BorderFactory.createTitledBorder("Choose class attribute"));
m_holderP.add(m_ClassCombo, BorderLayout.CENTER);
m_ClassCombo.setEditable(true);
m_ClassCombo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (m_classAssigner != null && m_displayColNames == true) {
//m_classAssigner.setClassColumn(""+(m_ClassCombo.getSelectedIndex()));
String selectedI = (String)m_ClassCombo.getSelectedItem();
selectedI = selectedI.replace("(Num)", "").replace("(Nom)", "").
replace("(Str)", "").replace("(Dat)", "").replace("(Rel)", "").
replace("(???)", "").trim();
if (selectedI.equals("NO CLASS")) {
// this will be parsed as a number by ClassAssigner and get decremented
// by 1 (zero-based indexing), thus unsetting the class
selectedI = "0";
}
m_classAssigner.setClassColumn(selectedI);
}
}
});
add(m_caEditor, BorderLayout.CENTER);
addButtons();
}
private void addButtons() {
JButton okBut = new JButton("OK");
JButton cancelBut = new JButton("Cancel");
JPanel butHolder = new JPanel();
butHolder.setLayout(new GridLayout(1, 2));
butHolder.add(okBut); butHolder.add(cancelBut);
add(butHolder, BorderLayout.SOUTH);
okBut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
m_modifyListener.setModifiedStatus(ClassAssignerCustomizer.this, true);
if (m_parent != null) {
m_parent.dispose();
}
}
});
cancelBut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
customizerClosing();
if (m_parent != null) {
m_parent.dispose();
}
}
});
}
private void setUpStandardSelection() {
if (m_displayColNames == true) {
remove(m_holderP);
m_caEditor.setTarget(m_classAssigner);
add(m_caEditor, BorderLayout.CENTER);
m_displayColNames = false;
}
validate(); repaint();
}
private void setUpColumnSelection(Instances format) {
if (m_displayColNames == false) {
remove(m_caEditor);
}
int existingClassCol = 0;
String classColString = m_classAssigner.getClassColumn();
if (classColString.trim().toLowerCase().compareTo("last") == 0 ||
classColString.equalsIgnoreCase("/last")) {
existingClassCol = format.numAttributes() - 1;
} else if (classColString.trim().toLowerCase().compareTo("first") == 0 ||
classColString.equalsIgnoreCase("/first")) {
// nothing to do
} else {
// try to look up class attribute as a label
Attribute classAtt = format.attribute(classColString);
if (classAtt != null) {
existingClassCol = classAtt.index();
} else {
// parse it as a number
try {
existingClassCol = Integer.parseInt(classColString);
} catch (NumberFormatException ex) {
System.err.println("Warning : can't parse '" + classColString + "' as a number "
+" or find it as an attribute in the incoming data (ClassAssigner)");
}
if (existingClassCol < 0) {
existingClassCol = -1; // no class
} else if (existingClassCol > format.numAttributes() - 1) {
existingClassCol = format.numAttributes() - 1;
} else {
existingClassCol--; // make it zero-based (rather than 1-based)
}
}
}
//int existingClassCol = format.classIndex();
/* if (existingClassCol < 0) {
existingClassCol = 0;
} */
String [] attribNames = new String [format.numAttributes()+1];
attribNames[0] = "NO CLASS";
for (int i = 1; i < attribNames.length; i++) {
String type = "(" + Attribute.typeToStringShort(format.attribute(i-1)) + ") ";
attribNames[i] = type + format.attribute(i-1).name();
}
m_ClassCombo.setModel(new DefaultComboBoxModel(attribNames));
if (attribNames.length > 0) {
m_ClassCombo.setSelectedIndex(existingClassCol+1);
}
if (m_displayColNames == false) {
add(m_holderP, BorderLayout.CENTER);
m_displayColNames = true;
}
validate(); repaint();
}
/**
* Set the bean to be edited
*
* @param object an <code>Object</code> value
*/
public void setObject(Object object) {
if (m_classAssigner != (ClassAssigner)object) {
m_classAssigner = (ClassAssigner)object;
// remove ourselves as a listener from the old ClassAssigner (if necessary)
/* if (m_classAssigner != null) {
m_classAssigner.removeDataFormatListener(this);
}
// add ourselves as a data format listener
m_classAssigner.addDataFormatListener(this); */
m_caEditor.setTarget(m_classAssigner);
if (m_classAssigner.getConnectedFormat() != null) {
setUpColumnSelection(m_classAssigner.getConnectedFormat());
}
m_backup = m_classAssigner.getClassColumn();
}
}
public void customizerClosing() {
// remove ourselves as a listener from the ClassAssigner (if necessary)
if (m_classAssigner != null) {
//System.out.println("Customizer deregistering with class assigner");
m_classAssigner.removeDataFormatListener(this);
}
if (m_backup != null) {
m_classAssigner.setClassColumn(m_backup);
}
}
public void newDataFormat(DataSetEvent dse) {
if (dse.getDataSet() != null) {
// System.err.println("Setting up column selection.........");
setUpColumnSelection(m_classAssigner.getConnectedFormat());
} else {
setUpStandardSelection();
}
}
/**
* Add a property change listener
*
* @param pcl a <code>PropertyChangeListener</code> value
*/
public void addPropertyChangeListener(PropertyChangeListener pcl) {
m_pcSupport.addPropertyChangeListener(pcl);
}
/**
* Remove a property change listener
*
* @param pcl a <code>PropertyChangeListener</code> value
*/
public void removePropertyChangeListener(PropertyChangeListener pcl) {
m_pcSupport.removePropertyChangeListener(pcl);
}
@Override
public void setModifiedListener(ModifyListener l) {
m_modifyListener = l;
}
@Override
public void setParentWindow(Window parent) {
m_parent = parent;
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/ClassValuePicker.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/>.
*/
/*
* ClassValuePicker.java
* Copyright (C) 2004-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.awt.BorderLayout;
import java.beans.EventSetDescriptor;
import java.io.Serializable;
import java.util.Vector;
import javax.swing.JPanel;
import weka.core.Attribute;
import weka.core.Instances;
import weka.filters.Filter;
import weka.filters.unsupervised.attribute.SwapValues;
/**
* @author Mark Hall
* @version $Revision$
*/
public class ClassValuePicker extends JPanel implements Visible,
DataSourceListener, BeanCommon, EventConstraints, Serializable,
StructureProducer {
/** for serialization */
private static final long serialVersionUID = -1196143276710882989L;
/** the class value considered to be the positive class */
private String m_classValue;
/** format of instances for the current incoming connection (if any) */
private Instances m_connectedFormat;
private Object m_dataProvider;
private final Vector<DataSourceListener> m_dataListeners =
new Vector<DataSourceListener>();
private final Vector<DataFormatListener> m_dataFormatListeners =
new Vector<DataFormatListener>();
protected transient weka.gui.Logger m_logger = null;
protected BeanVisual m_visual = new BeanVisual("ClassValuePicker",
BeanVisual.ICON_PATH + "ClassValuePicker.gif", BeanVisual.ICON_PATH
+ "ClassValuePicker_animated.gif");
/**
* Global info for this bean
*
* @return a <code>String</code> value
*/
public String globalInfo() {
return "Designate which class value is to be considered the \"positive\" "
+ "class value (useful for ROC style curves).";
}
public ClassValuePicker() {
setLayout(new BorderLayout());
add(m_visual, BorderLayout.CENTER);
}
/**
* Set a custom (descriptive) name for this bean
*
* @param name the name to use
*/
@Override
public void setCustomName(String name) {
m_visual.setText(name);
}
/**
* Get the custom (descriptive) name for this bean (if one has been set)
*
* @return the custom name (or the default name)
*/
@Override
public String getCustomName() {
return m_visual.getText();
}
@Override
public Instances getStructure(String eventName) {
if (!eventName.equals("dataSet")) {
return null;
}
if (m_dataProvider == null) {
return null;
}
if (m_dataProvider != null && m_dataProvider instanceof StructureProducer) {
m_connectedFormat = ((StructureProducer) m_dataProvider)
.getStructure("dataSet");
}
return m_connectedFormat;
}
protected Instances getStructure() {
if (m_dataProvider != null) {
return getStructure("dataSet");
}
return null;
}
/**
* Returns the structure of the incoming instances (if any)
*
* @return an <code>Instances</code> value
*/
public Instances getConnectedFormat() {
// loaders will push instances format to us
// when the user makes configuration changes
// to the loader in the gui. However, if a fully
// configured flow is loaded then we won't get
// this information pushed to us until the
// flow is run. In this case we want to pull
// it (if possible) from upstream steps so
// that our customizer can provide the nice
// UI with the drop down box of class names.
// if (m_connectedFormat == null) {
// try and pull the incoming structure
// from the upstream step (if possible)
// m_connectedFormat = getStructure();
// }
return getStructure();
}
/**
* Set the class value considered to be the "positive" class value.
*
* @param index the class value index to use
*/
public void setClassValue(String value) {
m_classValue = value;
if (m_connectedFormat != null) {
notifyDataFormatListeners();
}
}
/**
* Gets the class value considered to be the "positive" class value.
*
* @return the class value index
*/
public String getClassValue() {
return m_classValue;
}
@Override
public void acceptDataSet(DataSetEvent e) {
if (e.isStructureOnly()) {
if (m_connectedFormat == null
|| !m_connectedFormat.equalHeaders(e.getDataSet())) {
m_connectedFormat = new Instances(e.getDataSet(), 0);
// tell any listening customizers (or other
notifyDataFormatListeners();
}
}
Instances dataSet = e.getDataSet();
Instances newDataSet = assignClassValue(dataSet);
if (newDataSet != null) {
e = new DataSetEvent(this, newDataSet);
notifyDataListeners(e);
} else {
if (m_logger != null) {
m_logger.logMessage("[ClassValuePicker] " + statusMessagePrefix()
+ " Class value '" + m_classValue + "' does not seem to exist!");
m_logger
.statusMessage(statusMessagePrefix()
+ "ERROR: Class value '" + m_classValue
+ "' does not seem to exist!");
}
}
}
private Instances assignClassValue(Instances dataSet) {
if (dataSet.classIndex() < 0) {
if (m_logger != null) {
m_logger.logMessage("[ClassValuePicker] " + statusMessagePrefix()
+ " No class attribute defined in data set.");
m_logger.statusMessage(statusMessagePrefix()
+ "WARNING: No class attribute defined in data set.");
}
return dataSet;
}
if (dataSet.classAttribute().isNumeric()) {
if (m_logger != null) {
m_logger.logMessage("[ClassValuePicker] " + statusMessagePrefix()
+ " Class attribute must be nominal (ClassValuePicker)");
m_logger.statusMessage(statusMessagePrefix()
+ "WARNING: Class attribute must be nominal.");
}
return dataSet;
} else {
if (m_logger != null) {
m_logger.statusMessage(statusMessagePrefix() + "remove");
}
}
if ((m_classValue == null || m_classValue.length() == 0)
&& dataSet.numInstances() > 0) {
if (m_logger != null) {
m_logger.logMessage("[ClassValuePicker] " + statusMessagePrefix()
+ " Class value to consider as positive has not been set"
+ " (ClassValuePicker)");
m_logger.statusMessage(statusMessagePrefix()
+ "WARNING: Class value to consider as positive has not been set.");
}
return dataSet;
}
if (m_classValue == null) {
// in this case we must just have a structure only
// dataset, so don't fuss about it and return the
// exsting structure so that it can get pushed downstream
return dataSet;
}
Attribute classAtt = dataSet.classAttribute();
int classValueIndex = -1;
// if first char is "/" then see if we have "first" or "last"
// or if the remainder can be parsed as a number
if (m_classValue.startsWith("/") && m_classValue.length() > 1) {
String remainder = m_classValue.substring(1);
remainder = remainder.trim();
if (remainder.equalsIgnoreCase("first")) {
classValueIndex = 0;
} else if (remainder.equalsIgnoreCase("last")) {
classValueIndex = classAtt.numValues() - 1;
} else {
// try and parse as a number
try {
classValueIndex = Integer.parseInt(remainder);
classValueIndex--; // 0-based index
if (classValueIndex < 0 || classValueIndex > classAtt.numValues() - 1) {
if (m_logger != null) {
m_logger
.logMessage("[ClassValuePicker] " + statusMessagePrefix()
+ " Class value index is out of range!"
+ " (ClassValuePicker)");
m_logger.statusMessage(statusMessagePrefix()
+ "ERROR: Class value index is out of range!.");
}
}
} catch (NumberFormatException n) {
if (m_logger != null) {
m_logger.logMessage("[ClassValuePicker] " + statusMessagePrefix()
+ " Unable to parse supplied class value index as an integer"
+ " (ClassValuePicker)");
m_logger.statusMessage(statusMessagePrefix()
+ "WARNING: Unable to parse supplied class value index "
+ "as an integer.");
return dataSet;
}
}
}
} else {
// treat the string as the label to look for
classValueIndex = classAtt.indexOfValue(m_classValue.trim());
}
if (classValueIndex < 0) {
return null; // error
}
if (classValueIndex != 0) { // nothing to do if == 0
// swap selected index with index 0
try {
SwapValues sv = new SwapValues();
sv.setAttributeIndex("" + (dataSet.classIndex() + 1));
sv.setFirstValueIndex("first");
sv.setSecondValueIndex("" + (classValueIndex + 1));
sv.setInputFormat(dataSet);
Instances newDataSet = Filter.useFilter(dataSet, sv);
newDataSet.setRelationName(dataSet.relationName());
return newDataSet;
} catch (Exception ex) {
if (m_logger != null) {
m_logger.logMessage("[ClassValuePicker] " + statusMessagePrefix()
+ " Unable to swap class attibute values.");
m_logger.statusMessage(statusMessagePrefix()
+ "ERROR: (See log for details)");
return null;
}
}
}
return dataSet;
}
@SuppressWarnings("unchecked")
protected void notifyDataListeners(DataSetEvent tse) {
Vector<DataSourceListener> l;
synchronized (this) {
l = (Vector<DataSourceListener>) m_dataListeners.clone();
}
if (l.size() > 0) {
for (int i = 0; i < l.size(); i++) {
System.err.println("Notifying data listeners " + "(ClassValuePicker)");
l.elementAt(i).acceptDataSet(tse);
}
}
}
@SuppressWarnings("unchecked")
protected void notifyDataFormatListeners() {
Vector<DataFormatListener> l;
synchronized (this) {
l = (Vector<DataFormatListener>) m_dataFormatListeners.clone();
}
if (l.size() > 0) {
DataSetEvent dse = new DataSetEvent(this, m_connectedFormat);
for (int i = 0; i < l.size(); i++) {
l.elementAt(i).newDataFormat(dse);
}
}
}
public synchronized void addDataSourceListener(DataSourceListener tsl) {
m_dataListeners.addElement(tsl);
}
public synchronized void removeDataSourceListener(DataSourceListener tsl) {
m_dataListeners.removeElement(tsl);
}
public synchronized void addDataFormatListener(DataFormatListener dfl) {
m_dataFormatListeners.addElement(dfl);
}
public synchronized void removeDataFormatListener(DataFormatListener dfl) {
m_dataFormatListeners.removeElement(dfl);
}
@Override
public void setVisual(BeanVisual newVisual) {
m_visual = newVisual;
}
@Override
public BeanVisual getVisual() {
return m_visual;
}
@Override
public void useDefaultVisual() {
m_visual.loadIcons(BeanVisual.ICON_PATH + "ClassValuePicker.gif",
BeanVisual.ICON_PATH + "ClassValuePicker_animated.gif");
}
/**
* Returns true if, at this time, the object will accept a connection
* according to the supplied event name
*
* @param eventName the event
* @return true if the object will accept a connection
*/
@Override
public boolean connectionAllowed(String eventName) {
if (eventName.compareTo("dataSet") == 0 && (m_dataProvider != null)) {
return false;
}
return true;
}
/**
* Returns true if, at this time, the object will accept a connection
* according to the supplied EventSetDescriptor
*
* @param esd the EventSetDescriptor
* @return true if the object will accept a connection
*/
@Override
public boolean connectionAllowed(EventSetDescriptor esd) {
return connectionAllowed(esd.getName());
}
/**
* Notify this object that it has been registered as a listener with a source
* with respect to the supplied event name
*
* @param eventName the event
* @param source the source with which this object has been registered as a
* listener
*/
@Override
public synchronized void connectionNotification(String eventName,
Object source) {
if (connectionAllowed(eventName)) {
if (eventName.compareTo("dataSet") == 0) {
m_dataProvider = source;
}
}
m_connectedFormat = null;
}
/**
* Notify this object that it has been deregistered as a listener with a
* source with respect to the supplied event name
*
* @param eventName the event
* @param source the source with which this object has been registered as a
* listener
*/
@Override
public synchronized void disconnectionNotification(String eventName,
Object source) {
if (eventName.compareTo("dataSet") == 0) {
if (m_dataProvider == source) {
m_dataProvider = null;
}
}
m_connectedFormat = null;
}
@Override
public void setLog(weka.gui.Logger logger) {
m_logger = logger;
}
@Override
public void stop() {
// nothing to do
}
/**
* Returns true if. at this time, the bean is busy with some (i.e. perhaps a
* worker thread is performing some calculation).
*
* @return true if the bean is busy.
*/
@Override
public boolean isBusy() {
return false;
}
/**
* Returns true, if at the current time, the named event could be generated.
* Assumes that the supplied event name is an event that could be generated by
* this bean
*
* @param eventName the name of the event in question
* @return true if the named event could be generated at this point in time
*/
@Override
public boolean eventGeneratable(String eventName) {
if (eventName.compareTo("dataSet") != 0) {
return false;
}
if (eventName.compareTo("dataSet") == 0) {
if (m_dataProvider == null) {
m_connectedFormat = null;
notifyDataFormatListeners();
return false;
} else {
if (m_dataProvider instanceof EventConstraints) {
if (!((EventConstraints) m_dataProvider).eventGeneratable("dataSet")) {
m_connectedFormat = null;
notifyDataFormatListeners();
return false;
}
}
}
}
return true;
}
private String statusMessagePrefix() {
return getCustomName() + "$" + hashCode() + "|";
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/ClassValuePickerBeanInfo.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/>.
*/
/*
* ClassValuePickerBeanInfo.java
* Copyright (C) 2004-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.beans.BeanDescriptor;
import java.beans.EventSetDescriptor;
import java.beans.PropertyDescriptor;
import java.beans.SimpleBeanInfo;
/**
* BeanInfo class for the class value picker bean
*
* @author Mark Hall
* @version $Revision$
*/
public class ClassValuePickerBeanInfo
extends SimpleBeanInfo {
/**
* Returns the event set descriptors
*
* @return an <code>EventSetDescriptor[]</code> value
*/
public EventSetDescriptor [] getEventSetDescriptors() {
try {
EventSetDescriptor [] esds =
{ new EventSetDescriptor(ClassValuePicker.class,
"dataSet",
DataSourceListener.class,
"acceptDataSet") };
return esds;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
/**
* Returns the property descriptors
*
* @return a <code>PropertyDescriptor[]</code> value
*/
public PropertyDescriptor[] getPropertyDescriptors() {
try {
PropertyDescriptor p1;
p1 = new PropertyDescriptor("classValue", ClassValuePicker.class);
PropertyDescriptor [] pds = { p1 };
return pds;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public BeanDescriptor getBeanDescriptor() {
return new BeanDescriptor(weka.gui.beans.ClassValuePicker.class,
ClassValuePickerCustomizer.class);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/ClassValuePickerCustomizer.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/>.
*/
/*
* ClassValuePickerCustomizer.java
* Copyright (C) 2004-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import javax.swing.BorderFactory;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import weka.core.Attribute;
import weka.core.Instances;
/**
* @author Mark Hall
* @version $Revision$
*/
public class ClassValuePickerCustomizer
extends JPanel
implements BeanCustomizer, CustomizerClosingListener,
CustomizerCloseRequester /* , DataFormatListener */{
/** for serialization */
private static final long serialVersionUID = 8213423053861600469L;
private boolean m_displayValNames = false;
private ClassValuePicker m_classValuePicker;
private final PropertyChangeSupport m_pcSupport =
new PropertyChangeSupport(this);
private final JComboBox m_ClassValueCombo =
new EnvironmentField.WideComboBox();
private final JPanel m_holderP = new JPanel();
private final JLabel m_messageLabel = new JLabel(
"No customization possible at present.");
private ModifyListener m_modifyListener;
private boolean m_modified = false;
private Window m_parent;
private String m_backup;
private boolean m_textBoxEntryMode = false;
private JTextField m_valueTextBox;
public ClassValuePickerCustomizer() {
setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 5, 5, 5));
m_ClassValueCombo.setEditable(true);
m_ClassValueCombo.setToolTipText("Class label. /first, /last and /<num> " +
"can be used to specify the first, last or specific index " +
"of the label to use respectively.");
setLayout(new BorderLayout());
add(new javax.swing.JLabel("ClassValuePickerCustomizer"),
BorderLayout.NORTH);
m_holderP.setLayout(new BorderLayout());
m_holderP.setBorder(BorderFactory.createTitledBorder("Choose class value"));
m_holderP.setToolTipText("Class label. /first, /last and /<num> " +
"can be used to specify the first, last or specific index " +
"of the label to use respectively.");
m_holderP.add(m_ClassValueCombo, BorderLayout.CENTER);
m_ClassValueCombo.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (m_classValuePicker != null) {
m_classValuePicker.
setClassValue(m_ClassValueCombo.getSelectedItem().toString());
m_modified = true;
}
}
});
add(m_messageLabel, BorderLayout.CENTER);
addButtons();
}
private void addButtons() {
JButton okBut = new JButton("OK");
JButton cancelBut = new JButton("Cancel");
JPanel butHolder = new JPanel();
butHolder.setLayout(new GridLayout(1, 2));
butHolder.add(okBut);
butHolder.add(cancelBut);
add(butHolder, BorderLayout.SOUTH);
okBut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (m_modifyListener != null) {
m_modifyListener.setModifiedStatus(ClassValuePickerCustomizer.this,
m_modified);
}
if (m_textBoxEntryMode) {
m_classValuePicker.setClassValue(m_valueTextBox.getText().trim());
}
if (m_parent != null) {
m_parent.dispose();
}
}
});
cancelBut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
m_classValuePicker.setClassValue(m_backup);
customizerClosing();
if (m_parent != null) {
m_parent.dispose();
}
}
});
}
private void setupTextBoxSelection() {
m_textBoxEntryMode = true;
JPanel holderPanel = new JPanel();
holderPanel.setLayout(new BorderLayout());
holderPanel.setBorder(BorderFactory
.createTitledBorder("Specify class label"));
JLabel label = new JLabel("Class label ", SwingConstants.RIGHT);
holderPanel.add(label, BorderLayout.WEST);
m_valueTextBox = new JTextField(15);
m_valueTextBox.setToolTipText("Class label. /first, /last and /<num> " +
"can be used to specify the first, last or specific index " +
"of the label to use respectively.");
holderPanel.add(m_valueTextBox, BorderLayout.CENTER);
JPanel holder2 = new JPanel();
holder2.setLayout(new BorderLayout());
holder2.add(holderPanel, BorderLayout.NORTH);
add(holder2, BorderLayout.CENTER);
String existingClassVal = m_classValuePicker.getClassValue();
if (existingClassVal != null) {
m_valueTextBox.setText(existingClassVal);
}
}
private void setUpValueSelection(Instances format) {
if (format.classIndex() < 0 || format.classAttribute().isNumeric()) {
// cant do anything in this case
m_messageLabel.setText((format.classIndex() < 0) ?
"EROR: no class attribute set" : "ERROR: class is numeric");
return;
}
if (m_displayValNames == false) {
remove(m_messageLabel);
}
m_textBoxEntryMode = false;
if (format.classAttribute().numValues() == 0) {
// loader may not be able to give us the set of legal
// values for a nominal attribute until it has read
// the data (e.g. database loader or csv loader).
// In this case we'll use a text box and the user
// can enter the class value.
setupTextBoxSelection();
validate();
repaint();
return;
}
String existingClassVal = m_classValuePicker.getClassValue();
String existingCopy = existingClassVal;
if (existingClassVal == null) {
existingClassVal = "";
}
int classValIndex = format.classAttribute().indexOfValue(existingClassVal);
// do we have a special (last, first or number)
// if (existingClassVal.startsWith("/")) {
// existingClassVal = existingClassVal.substring(1);
// if (existingClassVal.equalsIgnoreCase("first")) {
// classValIndex = 0;
// } else if (existingClassVal.equalsIgnoreCase("last")) {
// classValIndex = format.classAttribute().numValues() - 1;
// } else {
// // try and parse as a number
// classValIndex = Integer.parseInt(existingClassVal);
// classValIndex--;
// }
// }
// if (classValIndex < 0) {
// classValIndex = 0;
// }
String[] attribValNames = new String[format.classAttribute().numValues()];
for (int i = 0; i < attribValNames.length; i++) {
attribValNames[i] = format.classAttribute().value(i);
}
m_ClassValueCombo.setModel(new DefaultComboBoxModel(attribValNames));
if (attribValNames.length > 0) {
// if (existingClassVal < attribValNames.length) {
if (classValIndex >= 0) {
m_ClassValueCombo.setSelectedIndex(classValIndex);
} else {
String toSet = existingCopy != null ? existingCopy : attribValNames[0];
m_ClassValueCombo.setSelectedItem(toSet);
}
// }
}
if (m_displayValNames == false) {
add(m_holderP, BorderLayout.CENTER);
m_displayValNames = true;
}
validate();
repaint();
}
/**
* Set the bean to be edited
*
* @param object an <code>Object</code> value
*/
@Override
public void setObject(Object object) {
if (m_classValuePicker != (ClassValuePicker) object) {
// remove ourselves as a listener from the old ClassvaluePicker (if
// necessary)
/*
* if (m_classValuePicker != null) {
* m_classValuePicker.removeDataFormatListener(this); }
*/
m_classValuePicker = (ClassValuePicker) object;
// add ourselves as a data format listener
// m_classValuePicker.addDataFormatListener(this);
if (m_classValuePicker.getConnectedFormat() != null) {
setUpValueSelection(m_classValuePicker.getConnectedFormat());
}
m_backup = m_classValuePicker.getClassValue();
}
}
@Override
public void customizerClosing() {
// remove ourselves as a listener from the ClassValuePicker (if necessary)
// if (m_classValuePicker != null) {
// System.out.println("Customizer deregistering with class value picker");
// m_classValuePicker.removeDataFormatListener(this);
// }
m_classValuePicker.setClassValue(m_backup);
}
/*
* public void newDataFormat(DataSetEvent dse) { if (dse.getDataSet() != null)
* { setUpValueSelection(m_classValuePicker.getConnectedFormat()); } else {
* setUpNoCustPossible(); } }
*/
/**
* Add a property change listener
*
* @param pcl a <code>PropertyChangeListener</code> value
*/
@Override
public void addPropertyChangeListener(PropertyChangeListener pcl) {
m_pcSupport.addPropertyChangeListener(pcl);
}
/**
* Remove a property change listener
*
* @param pcl a <code>PropertyChangeListener</code> value
*/
@Override
public void removePropertyChangeListener(PropertyChangeListener pcl) {
m_pcSupport.removePropertyChangeListener(pcl);
}
@Override
public void setModifiedListener(ModifyListener l) {
m_modifyListener = l;
}
@Override
public void setParentWindow(Window parent) {
m_parent = parent;
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/Classifier.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/>.
*/
/*
* Classifier.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.awt.BorderLayout;
import java.awt.GraphicsEnvironment;
import java.beans.EventSetDescriptor;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.filechooser.FileFilter;
import weka.classifiers.UpdateableBatchProcessor;
import weka.classifiers.rules.ZeroR;
import weka.core.Environment;
import weka.core.EnvironmentHandler;
import weka.core.Instances;
import weka.core.OptionHandler;
import weka.core.SerializationHelper;
import weka.core.Utils;
import weka.core.xml.KOML;
import weka.core.xml.XStream;
import weka.experiment.Task;
import weka.experiment.TaskStatusInfo;
import weka.gui.ExtensionFileFilter;
import weka.gui.Logger;
/**
* Bean that wraps around weka.classifiers
*
* @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a>
* @version $Revision$
* @since 1.0
* @see JPanel
* @see BeanCommon
* @see Visible
* @see WekaWrapper
* @see Serializable
* @see UserRequestAcceptor
* @see TrainingSetListener
* @see TestSetListener
* @see EnvironmentHandler
*/
public class Classifier extends JPanel implements BeanCommon, Visible,
WekaWrapper, EventConstraints, Serializable, UserRequestAcceptor,
TrainingSetListener, TestSetListener, InstanceListener,
ConfigurationProducer, EnvironmentHandler {
/** for serialization */
private static final long serialVersionUID = 659603893917736008L;
protected BeanVisual m_visual = new BeanVisual("Classifier",
BeanVisual.ICON_PATH + "DefaultClassifier.gif", BeanVisual.ICON_PATH
+ "DefaultClassifier_animated.gif");
private static int IDLE = 0;
private static int BUILDING_MODEL = 1;
private int m_state = IDLE;
// private Thread m_buildThread = null;
/**
* Global info for the wrapped classifier (if it exists).
*/
protected String m_globalInfo;
/**
* Objects talking to us. String connection event key, 2 element list
* containing source and count
*/
// protected Hashtable m_listenees = new Hashtable();
protected HashMap<String, List<Object>> m_listenees =
new HashMap<String, List<Object>>();
/**
* Objects listening for batch classifier events
*/
private final Vector<BatchClassifierListener> m_batchClassifierListeners =
new Vector<BatchClassifierListener>();
/**
* Objects listening for incremental classifier events
*/
private final Vector<IncrementalClassifierListener> m_incrementalClassifierListeners =
new Vector<IncrementalClassifierListener>();
/**
* Objects listening for graph events
*/
private final Vector<GraphListener> m_graphListeners =
new Vector<GraphListener>();
/**
* Objects listening for text events
*/
private final Vector<TextListener> m_textListeners =
new Vector<TextListener>();
/**
* Holds training instances for batch training. Not transient because header
* is retained for validating any instance events that this classifier might
* be asked to predict in the future.
*/
private Instances m_trainingSet;
private weka.classifiers.Classifier m_Classifier = new ZeroR();
/** Template used for creating copies when building in parallel */
private weka.classifiers.Classifier m_ClassifierTemplate = m_Classifier;
private final IncrementalClassifierEvent m_ie =
new IncrementalClassifierEvent(this);
/** the extension for serialized models (binary Java serialization) */
public final static String FILE_EXTENSION = "model";
private transient JFileChooser m_fileChooser = null;
protected FileFilter m_binaryFilter = new ExtensionFileFilter("."
+ FILE_EXTENSION, "Binary serialized model file (*" + FILE_EXTENSION + ")");
protected FileFilter m_KOMLFilter = new ExtensionFileFilter(
KOML.FILE_EXTENSION + FILE_EXTENSION, "XML serialized model file (*"
+ KOML.FILE_EXTENSION + FILE_EXTENSION + ")");
protected FileFilter m_XStreamFilter = new ExtensionFileFilter(
XStream.FILE_EXTENSION + FILE_EXTENSION, "XML serialized model file (*"
+ XStream.FILE_EXTENSION + FILE_EXTENSION + ")");
protected transient Environment m_env;
/**
* If the classifier is an incremental classifier, should we reset it (i.e.
* call buildClassifier()) and discard any previously learned model before
* processing the first instance in the stream. Note that this happens
* automatically if the incoming instance structure does not match that (if
* any) that the classifier was trained with previously.
*/
private boolean m_resetIncrementalClassifier = false;
/**
* If the classifier is an incremental classifier, should we update it (ie
* train it on incoming instances). This makes it possible incrementally test
* on a separate stream of instances without updating the classifier, or mix
* batch training/testing with incremental training/testing
*/
private boolean m_updateIncrementalClassifier = true;
private transient Logger m_log = null;
/**
* Event to handle when processing incremental updates
*/
private InstanceEvent m_incrementalEvent;
/**
* Number of threads to use to train models with
*/
protected int m_executionSlots = 2;
// protected int m_queueSize = 5;
/**
* Pool of threads to train models on incoming data
*/
protected transient ThreadPoolExecutor m_executorPool;
/**
* Stores completed models and associated data sets.
*/
protected transient BatchClassifierEvent[][] m_outputQueues;
/**
* Stores which sets from which runs have been completed.
*/
protected transient boolean[][] m_completedSets;
/**
* Identifier for the current batch. A batch is a group of related runs/sets.
*/
protected transient Date m_currentBatchIdentifier;
protected transient boolean m_batchStarted = false;
/**
* Holds original icon label text
*/
protected String m_oldText = "";
/**
* true if we should reject any further training data sets, until all
* processing has been finished, once we've received the last fold of the last
* run.
*/
protected boolean m_reject = false;
/**
* True if we should block rather reject until all processing has been
* completed.
*/
protected boolean m_block = false;
/**
* Optional file to load a pre-trained model to score with (batch, or to score
* and update (incremental) in the case of testSet only (batch) or instance
* (incremental) connections
*/
protected String m_loadModelFileName = "";
/**
* Global info (if it exists) for the wrapped classifier
*
* @return the global info
*/
public String globalInfo() {
return m_globalInfo;
}
/**
* Creates a new <code>Classifier</code> instance.
*/
public Classifier() {
setLayout(new BorderLayout());
add(m_visual, BorderLayout.CENTER);
setClassifierTemplate(m_ClassifierTemplate);
// setupFileChooser();
}
private void startExecutorPool() {
if (m_executorPool != null) {
m_executorPool.shutdownNow();
}
m_executorPool =
new ThreadPoolExecutor(m_executionSlots, m_executionSlots, 120,
TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
}
/**
* Set a custom (descriptive) name for this bean
*
* @param name the name to use
*/
@Override
public void setCustomName(String name) {
m_visual.setText(name);
}
/**
* Get the custom (descriptive) name for this bean (if one has been set)
*
* @return the custom name (or the default name)
*/
@Override
public String getCustomName() {
return m_visual.getText();
}
protected void setupFileChooser() {
if (m_fileChooser == null) {
m_fileChooser =
new JFileChooser(new File(System.getProperty("user.dir")));
}
m_fileChooser.addChoosableFileFilter(m_binaryFilter);
if (KOML.isPresent()) {
m_fileChooser.addChoosableFileFilter(m_KOMLFilter);
}
if (XStream.isPresent()) {
m_fileChooser.addChoosableFileFilter(m_XStreamFilter);
}
m_fileChooser.setFileFilter(m_binaryFilter);
}
/**
* Get the number of execution slots (threads) used to train models.
*
* @return the number of execution slots.
*/
public int getExecutionSlots() {
return m_executionSlots;
}
/**
* Set the number of execution slots (threads) to use to train models with.
*
* @param slots the number of execution slots to use.
*/
public void setExecutionSlots(int slots) {
m_executionSlots = slots;
}
/**
* Set whether to block on receiving the last fold of the last run rather than
* rejecting any further data until all processing is complete.
*
* @param block true if we should block on the last fold of the last run.
*/
public void setBlockOnLastFold(boolean block) {
m_block = block;
}
/**
* Gets whether we are blocking on the last fold of the last run rather than
* rejecting any further data until all processing has been completed.
*
* @return true if we are blocking on the last fold of the last run
*/
public boolean getBlockOnLastFold() {
return m_block;
}
/**
* Set the template classifier for this wrapper
*
* @param c a <code>weka.classifiers.Classifier</code> value
*/
public void setClassifierTemplate(weka.classifiers.Classifier c) {
boolean loadImages = true;
if (c.getClass().getName()
.compareTo(m_ClassifierTemplate.getClass().getName()) == 0) {
loadImages = false;
} else {
// classifier has changed so any batch training status is now
// invalid
m_trainingSet = null;
}
m_ClassifierTemplate = c;
String classifierName = c.getClass().toString();
classifierName =
classifierName.substring(classifierName.lastIndexOf('.') + 1,
classifierName.length());
if (loadImages) {
if (!m_visual.loadIcons(BeanVisual.ICON_PATH + classifierName + ".gif",
BeanVisual.ICON_PATH + classifierName + "_animated.gif")) {
useDefaultVisual();
}
m_visual.setText(classifierName);
}
if (!(m_ClassifierTemplate instanceof weka.classifiers.UpdateableClassifier)
&& (m_listenees.containsKey("instance"))) {
if (m_log != null) {
m_log.logMessage("[Classifier] " + statusMessagePrefix()
+ " WARNING : " + getCustomName()
+ " is not an incremental classifier");
}
}
// get global info
m_globalInfo = KnowledgeFlowApp.getGlobalInfo(m_ClassifierTemplate);
try {
if (m_ClassifierTemplate instanceof weka.classifiers.misc.InputMappedClassifier) {
m_Classifier =
weka.classifiers.AbstractClassifier.makeCopy(m_ClassifierTemplate);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Return the classifier template currently in use.
*
* @return the classifier template currently in use.
*/
public weka.classifiers.Classifier getClassifierTemplate() {
return m_ClassifierTemplate;
}
private void setTrainedClassifier(weka.classifiers.Classifier tc)
throws Exception {
// set the template
weka.classifiers.Classifier newTemplate = null;
String[] options = ((OptionHandler) tc).getOptions();
newTemplate =
weka.classifiers.AbstractClassifier.forName(tc.getClass().getName(),
options);
if (!newTemplate.getClass().equals(m_ClassifierTemplate.getClass())) {
throw new Exception("Classifier model " + tc.getClass().getName()
+ " is not the same type " + "of classifier as this one ("
+ m_ClassifierTemplate.getClass().getName() + ")");
}
setClassifierTemplate(newTemplate);
m_Classifier = tc;
}
/**
* Returns true if this classifier has an incoming connection that is an
* instance stream
*
* @return true if has an incoming connection that is an instance stream
*/
public boolean hasIncomingStreamInstances() {
if (m_listenees.size() == 0) {
return false;
}
if (m_listenees.containsKey("instance")) {
return true;
}
return false;
}
/**
* Returns true if this classifier has an incoming connection that is a batch
* set of instances
*
* @return a <code>boolean</code> value
*/
public boolean hasIncomingBatchInstances() {
if (m_listenees.size() == 0) {
return false;
}
if (m_listenees.containsKey("trainingSet")
|| m_listenees.containsKey("testSet")) {
return true;
}
return false;
}
/**
* Get the currently trained classifier.
*
* @return a <code>weka.classifiers.Classifier</code> value
*/
public weka.classifiers.Classifier getClassifier() {
return m_Classifier;
}
/**
* Sets the algorithm (classifier) for this bean
*
* @param algorithm an <code>Object</code> value
* @exception IllegalArgumentException if an error occurs
*/
@Override
public void setWrappedAlgorithm(Object algorithm) {
if (!(algorithm instanceof weka.classifiers.Classifier)) {
throw new IllegalArgumentException(algorithm.getClass() + " : incorrect "
+ "type of algorithm (Classifier)");
}
setClassifierTemplate((weka.classifiers.Classifier) algorithm);
}
/**
* Returns the wrapped classifier
*
* @return an <code>Object</code> value
*/
@Override
public Object getWrappedAlgorithm() {
return getClassifierTemplate();
}
/**
* Set the name of the classifier to load at execution time. This only applies
* in the case where the only incoming connection is a test set connection
* (batch mode) or an instance connection (incremental mode).
*
* @param filename the name of the file to load the model from
*/
public void setLoadClassifierFileName(String filename) {
m_loadModelFileName = filename;
}
/**
* Get the name of the classifier to load at execution time. This only applies
* in the case where the only incoming connection is a test set connection
* (batch mode) or an instance connection (incremental mode).
*
* @return the name of the file to load the model from
*/
public String getLoadClassifierFileName() {
return m_loadModelFileName;
}
/**
* Set whether to reset (by calling buildClassifier()) an incremental
* classifier, and thus discarding any previously learned model, before
* processing the first instance in the incoming stream. Note that this
* happens automatically if the incoming instances structure does not match
* that of any previous structure used to train the model.
*
* @param reset true if the incremental classifier should be reset before
* processing the first instance in the incoming data stream
*/
public void setResetIncrementalClassifier(boolean reset) {
m_resetIncrementalClassifier = reset;
}
/**
* Get whether to reset (by calling buildClassifier()) an incremental
* classifier, and thus discarding any previously learned model, before
* processing the first instance in the incoming stream. Note that this
* happens automatically if the incoming instances structure does not match
* that of any previous structure used to train the model.
*
*/
public boolean getResetIncrementalClassifier() {
return m_resetIncrementalClassifier;
}
/**
* Get whether an incremental classifier will be updated on the incoming
* instance stream.
*
* @return true if an incremental classifier is to be updated.
*/
public boolean getUpdateIncrementalClassifier() {
return m_updateIncrementalClassifier;
}
/**
* Set whether an incremental classifier will be updated on the incoming
* instance stream.
*
* @param update true if an incremental classifier is to be updated.
*/
public void setUpdateIncrementalClassifier(boolean update) {
m_updateIncrementalClassifier = update;
}
/**
* Accepts an instance for incremental processing.
*
* @param e an <code>InstanceEvent</code> value
*/
@Override
public void acceptInstance(InstanceEvent e) {
if (m_log == null) {
System.err.println("Log is null");
}
m_incrementalEvent = e;
handleIncrementalEvent();
}
protected transient StreamThroughput m_throughput;
/**
* Handles initializing and updating an incremental classifier
*/
private void handleIncrementalEvent() {
if (m_executorPool != null
&& (m_executorPool.getQueue().size() > 0 || m_executorPool
.getActiveCount() > 0)) {
String messg =
"[Classifier] " + statusMessagePrefix()
+ " is currently batch training!";
if (m_log != null) {
m_log.logMessage(messg);
m_log.statusMessage(statusMessagePrefix() + "WARNING: "
+ "Can't accept instance - batch training in progress.");
} else {
System.err.println(messg);
}
return;
}
if (m_incrementalEvent.getStatus() == InstanceEvent.FORMAT_AVAILABLE) {
m_throughput = new StreamThroughput(statusMessagePrefix());
// clear any warnings/errors from the log
if (m_log != null) {
m_log.statusMessage(statusMessagePrefix() + "remove");
}
// Instances dataset = m_incrementalEvent.getInstance().dataset();
Instances dataset = m_incrementalEvent.getStructure();
// default to the last column if no class is set
if (dataset.classIndex() < 0) {
stop();
String errorMessage =
statusMessagePrefix()
+ "ERROR: no class attribute set in incoming stream!";
if (m_log != null) {
m_log.statusMessage(errorMessage);
m_log.logMessage("[" + getCustomName() + "] " + errorMessage);
} else {
System.err.println("[" + getCustomName() + "] " + errorMessage);
}
return;
// System.err.println("Classifier : setting class index...");
// dataset.setClassIndex(dataset.numAttributes()-1);
}
if (m_loadModelFileName != null && m_loadModelFileName.length() > 0
&& m_state == IDLE && !m_listenees.containsKey("trainingSet")) {
// load model (if specified)
String resolvedFileName = m_loadModelFileName;
if (m_env != null) {
try {
resolvedFileName = m_env.substitute(resolvedFileName);
} catch (Exception ex) {
}
}
File loadFrom = new File(resolvedFileName);
try {
loadFromFile(loadFrom);
} catch (Exception ex) {
// stop();
m_log.statusMessage(statusMessagePrefix()
+ "WARNING: unable to load " + "model (see log).");
m_log.logMessage("[Classifier] " + statusMessagePrefix()
+ "Problem loading classifier - training from scratch... "
+ ex.getMessage());
// return;
}
}
try {
// initialize classifier if m_trainingSet is null
// otherwise assume that classifier has been pre-trained in batch
// mode, *if* headers match
if (m_trainingSet == null || !m_trainingSet.equalHeaders(dataset)
|| m_resetIncrementalClassifier) {
if (!(m_ClassifierTemplate instanceof weka.classifiers.UpdateableClassifier)
&& !(m_ClassifierTemplate instanceof weka.classifiers.misc.InputMappedClassifier)) {
stop(); // stop all processing
if (m_log != null) {
String msg =
(m_trainingSet == null) ? statusMessagePrefix()
+ "ERROR: classifier has not been batch "
+ "trained; can't process instance events."
: statusMessagePrefix()
+ "ERROR: instance event's structure is different from "
+ "the data that "
+ "was used to batch train this classifier; can't continue.";
m_log.logMessage("[Classifier] " + msg);
m_log.statusMessage(msg);
}
return;
}
if (m_ClassifierTemplate instanceof weka.classifiers.misc.InputMappedClassifier) {
m_trainingSet =
((weka.classifiers.misc.InputMappedClassifier) m_Classifier)
.getModelHeader(m_trainingSet);
/*
* // check to see if the classifier that gets loaded is updateable
* weka.classifiers.Classifier tempC =
* ((weka.classifiers.misc.InputMappedClassifier
* )m_Classifier).getClassifier(); if (!(tempC instanceof
* weka.classifiers.UpdateableClassifier)) {
*
* }
*/
}
if (m_trainingSet != null && (!dataset.equalHeaders(m_trainingSet))) {
if (m_log != null) {
String msg =
statusMessagePrefix()
+ " WARNING : structure of instance events differ "
+ "from data used in batch training this "
+ "classifier. Resetting classifier...";
m_log.logMessage("[Classifier] " + msg);
m_log.statusMessage(msg);
}
m_trainingSet = null;
}
if (m_resetIncrementalClassifier) {
if (m_log != null) {
String msg =
statusMessagePrefix() + " Reseting incremental classifier";
m_log.logMessage("[Classifier] " + msg);
m_log.statusMessage(msg);
}
m_trainingSet = null;
}
if (m_trainingSet == null) {
// initialize the classifier if it hasn't been trained yet
m_trainingSet = new Instances(dataset, 0);
m_Classifier =
weka.classifiers.AbstractClassifier
.makeCopy(m_ClassifierTemplate);
if (m_Classifier instanceof EnvironmentHandler && m_env != null) {
((EnvironmentHandler) m_Classifier).setEnvironment(m_env);
}
m_Classifier.buildClassifier(m_trainingSet);
}
}
} catch (Exception ex) {
stop();
if (m_log != null) {
m_log.statusMessage(statusMessagePrefix()
+ "ERROR (See log for details)");
m_log.logMessage("[Classifier] " + statusMessagePrefix()
+ " problem during incremental processing. " + ex.getMessage());
}
ex.printStackTrace();
return;
}
if (!m_incrementalEvent.m_formatNotificationOnly) {
String msg =
m_updateIncrementalClassifier ? statusMessagePrefix()
+ "Training incrementally..." : statusMessagePrefix()
+ "Predicting incrementally...";
if (m_log != null) {
m_log.statusMessage(msg);
}
}
// Notify incremental classifier listeners of new batch
System.err.println("NOTIFYING NEW BATCH");
m_ie.setStructure(dataset);
m_ie.setClassifier(m_Classifier);
notifyIncrementalClassifierListeners(m_ie);
return;
} else {
if (m_trainingSet == null) {
// simply return. If the training set is still null after
// the first instance then the classifier must not be updateable
// and hasn't been previously batch trained - therefore we can't
// do anything meaningful
return;
}
}
try {
// test on this instance
if (m_incrementalEvent.getInstance() != null) {
if (m_incrementalEvent.getInstance().dataset().classIndex() < 0) {
// System.err.println("Classifier : setting class index...");
m_incrementalEvent
.getInstance()
.dataset()
.setClassIndex(
m_incrementalEvent.getInstance().dataset().numAttributes() - 1);
}
}
int status = IncrementalClassifierEvent.WITHIN_BATCH;
/*
* if (m_incrementalEvent.getStatus() == InstanceEvent.FORMAT_AVAILABLE) {
* status = IncrementalClassifierEvent.NEW_BATCH;
*/
/* } else */
if (m_incrementalEvent.getStatus() == InstanceEvent.BATCH_FINISHED
|| m_incrementalEvent.getInstance() == null) {
status = IncrementalClassifierEvent.BATCH_FINISHED;
}
if (m_incrementalEvent.getInstance() != null) {
m_throughput.updateStart();
}
m_ie.setStatus(status);
m_ie.setClassifier(m_Classifier);
m_ie.setCurrentInstance(m_incrementalEvent.getInstance());
if (status == InstanceEvent.BATCH_FINISHED
&& m_Classifier instanceof UpdateableBatchProcessor) {
((UpdateableBatchProcessor) m_Classifier).batchFinished();
}
notifyIncrementalClassifierListeners(m_ie);
// now update on this instance (if class is not missing and classifier
// is updateable and user has specified that classifier is to be
// updated)
if (m_ClassifierTemplate instanceof weka.classifiers.UpdateableClassifier
&& m_updateIncrementalClassifier == true
&& m_incrementalEvent.getInstance() != null
&& !(m_incrementalEvent.getInstance().isMissing(m_incrementalEvent
.getInstance().dataset().classIndex()))) {
((weka.classifiers.UpdateableClassifier) m_Classifier)
.updateClassifier(m_incrementalEvent.getInstance());
}
if (m_incrementalEvent.getInstance() != null) {
m_throughput.updateEnd(m_log);
}
if (m_incrementalEvent.getStatus() == InstanceEvent.BATCH_FINISHED
|| m_incrementalEvent.getInstance() == null) {
if (m_textListeners.size() > 0) {
String modelString = m_Classifier.toString();
String titleString = m_Classifier.getClass().getName();
titleString =
titleString.substring(titleString.lastIndexOf('.') + 1,
titleString.length());
modelString =
"=== Classifier model ===\n\n" + "Scheme: " + titleString + "\n"
+ "Relation: " + m_trainingSet.relationName() + "\n\n"
+ modelString;
titleString = "Model: " + titleString;
TextEvent nt = new TextEvent(this, modelString, titleString);
notifyTextListeners(nt);
}
m_throughput.finished(m_log);
}
} catch (Exception ex) {
stop();
if (m_log != null) {
m_log.logMessage("[Classifier] " + statusMessagePrefix()
+ ex.getMessage());
m_log.statusMessage(statusMessagePrefix()
+ "ERROR (see log for details)");
ex.printStackTrace();
} else {
ex.printStackTrace();
}
}
}
protected class TrainingTask implements Runnable, Task {
/** Added ID to prevent warning */
private static final long serialVersionUID = -7918128680624169641L;
private final int m_runNum;
private final int m_maxRunNum;
private final int m_setNum;
private final int m_maxSetNum;
private Instances m_train = null;
private final TaskStatusInfo m_taskInfo = new TaskStatusInfo();
public TrainingTask(int runNum, int maxRunNum, int setNum, int maxSetNum,
Instances train) {
m_runNum = runNum;
m_maxRunNum = maxRunNum;
m_setNum = setNum;
m_maxSetNum = maxSetNum;
m_train = train;
m_taskInfo.setExecutionStatus(TaskStatusInfo.TO_BE_RUN);
}
@Override
public void run() {
execute();
}
@SuppressWarnings("deprecation")
@Override
public void execute() {
try {
if (m_train != null) {
if (m_train.classIndex() < 0) {
// stop all processing
stop();
String errorMessage =
statusMessagePrefix()
+ "ERROR: no class attribute set in test data!";
if (m_log != null) {
m_log.statusMessage(errorMessage);
m_log.logMessage("[Classifier] " + errorMessage);
} else {
System.err.println("[Classifier] " + errorMessage);
}
return;
// assume last column is the class
/*
* m_train.setClassIndex(m_train.numAttributes()-1); if (m_log !=
* null) { m_log.logMessage("[Classifier] " + statusMessagePrefix()
* + " : assuming last " +"column is the class"); }
*/
}
if (m_runNum == 1 && m_setNum == 1) {
// set this back to idle once the last fold
// of the last run has completed
m_state = BUILDING_MODEL; // global state
// local status of this runnable
m_taskInfo.setExecutionStatus(TaskStatusInfo.PROCESSING);
}
// m_visual.setAnimated();
// m_visual.setText("Building model...");
String msg =
statusMessagePrefix() + "Building model for run " + m_runNum
+ " fold " + m_setNum;
if (m_log != null) {
m_log.statusMessage(msg);
} else {
System.err.println(msg);
}
// buildClassifier();
// copy the classifier configuration
weka.classifiers.Classifier classifierCopy =
weka.classifiers.AbstractClassifier.makeCopy(m_ClassifierTemplate);
if (classifierCopy instanceof EnvironmentHandler && m_env != null) {
((EnvironmentHandler) classifierCopy).setEnvironment(m_env);
}
// build this model
classifierCopy.buildClassifier(m_train);
if (m_runNum == m_maxRunNum && m_setNum == m_maxSetNum) {
// Save the last classifier (might be used later on for
// classifying further test sets.
m_Classifier = classifierCopy;
m_trainingSet = new Instances(m_train, 0);
}
// if (m_batchClassifierListeners.size() > 0) {
// notify anyone who might be interested in just the model
// and training set.
BatchClassifierEvent ce =
new BatchClassifierEvent(Classifier.this, classifierCopy,
new DataSetEvent(this, m_train), null, // no test
// set
// (yet)
m_setNum, m_maxSetNum);
ce.setGroupIdentifier(m_currentBatchIdentifier.getTime());
ce.setLabel(getCustomName());
notifyBatchClassifierListeners(ce);
// store in the output queue (if we have incoming test set events)
ce =
new BatchClassifierEvent(Classifier.this, classifierCopy,
new DataSetEvent(this, m_train), null, // no test set (yet)
m_setNum, m_maxSetNum);
ce.setGroupIdentifier(m_currentBatchIdentifier.getTime());
ce.setLabel(getCustomName());
classifierTrainingComplete(ce);
// }
if (classifierCopy instanceof weka.core.Drawable
&& m_graphListeners.size() > 0) {
String grphString = ((weka.core.Drawable) classifierCopy).graph();
int grphType = ((weka.core.Drawable) classifierCopy).graphType();
String grphTitle = classifierCopy.getClass().getName();
grphTitle =
grphTitle.substring(grphTitle.lastIndexOf('.') + 1,
grphTitle.length());
grphTitle =
"Set " + m_setNum + " (" + m_train.relationName() + ") "
+ grphTitle;
GraphEvent ge =
new GraphEvent(Classifier.this, grphString, grphTitle, grphType);
notifyGraphListeners(ge);
}
if (m_textListeners.size() > 0) {
String modelString = classifierCopy.toString();
String titleString = classifierCopy.getClass().getName();
titleString =
titleString.substring(titleString.lastIndexOf('.') + 1,
titleString.length());
modelString =
"=== Classifier model ===\n\n" + "Scheme: " + titleString
+ "\n" + "Relation: " + m_train.relationName()
+ ((m_maxSetNum > 1) ? "\nTraining Fold: " + m_setNum : "")
+ "\n\n" + modelString;
titleString = "Model: " + titleString;
TextEvent nt =
new TextEvent(Classifier.this, modelString, titleString
+ (m_maxSetNum > 1 ? (" (fold " + m_setNum + ")") : ""));
notifyTextListeners(nt);
}
}
} catch (Exception ex) {
ex.printStackTrace();
if (m_log != null) {
String titleString = "[Classifier] " + statusMessagePrefix();
titleString +=
" run " + m_runNum + " fold " + m_setNum + " failed to complete.";
m_log.logMessage(titleString + " (build classifier). "
+ ex.getMessage());
m_log.statusMessage(statusMessagePrefix()
+ "ERROR (see log for details)");
ex.printStackTrace();
}
m_taskInfo.setExecutionStatus(TaskStatusInfo.FAILED);
// Stop all processing
stop();
} finally {
m_visual.setStatic();
if (m_log != null) {
if (m_setNum == m_maxSetNum) {
m_log.statusMessage(statusMessagePrefix() + "Finished.");
}
}
m_state = IDLE;
if (Thread.currentThread().isInterrupted()) {
// prevent any classifier events from being fired
m_trainingSet = null;
if (m_log != null) {
String titleString = "[Classifier] " + statusMessagePrefix();
m_log.logMessage(titleString + " (" + " run " + m_runNum + " fold "
+ m_setNum + ") interrupted!");
m_log.statusMessage(statusMessagePrefix() + "INTERRUPTED");
/*
* // are we the last active thread? if
* (m_executorPool.getActiveCount() == 1) { String msg =
* "[Classifier] " + statusMessagePrefix() +
* " last classifier unblocking..."; System.err.println(msg +
* " (interrupted)"); m_log.logMessage(msg + " (interrupted)"); //
* m_log.statusMessage(statusMessagePrefix() + "finished."); m_block
* = false; m_state = IDLE; block(false); }
*/
}
/*
* System.err.println("Queue size: " +
* m_executorPool.getQueue().size() + " Active count: " +
* m_executorPool.getActiveCount());
*/
} /*
* else { // check to see if we are the last active thread if
* (m_executorPool == null || (m_executorPool.getQueue().size() == 0
* && m_executorPool.getActiveCount() == 1)) {
*
* String msg = "[Classifier] " + statusMessagePrefix() +
* " last classifier unblocking..."; System.err.println(msg); if
* (m_log != null) { m_log.logMessage(msg); } else {
* System.err.println(msg); } //m_visual.setText(m_oldText);
*
* if (m_log != null) { m_log.statusMessage(statusMessagePrefix() +
* "Finished."); } // m_outputQueues = null; // free memory m_block =
* false; block(false); } }
*/
}
}
@Override
public TaskStatusInfo getTaskStatus() {
// TODO
return null;
}
}
/**
* Accepts a training set and builds batch classifier
*
* @param e a <code>TrainingSetEvent</code> value
*/
@Override
public void acceptTrainingSet(final TrainingSetEvent e) {
if (e.isStructureOnly()) {
// no need to build a classifier, instead just generate a dummy
// BatchClassifierEvent in order to pass on instance structure to
// any listeners - eg. PredictionAppender can use it to determine
// the final structure of instances with predictions appended
BatchClassifierEvent ce =
new BatchClassifierEvent(this, m_Classifier, new DataSetEvent(this,
e.getTrainingSet()), new DataSetEvent(this, e.getTrainingSet()),
e.getSetNumber(), e.getMaxSetNumber());
notifyBatchClassifierListeners(ce);
return;
}
if (m_reject) {
// block(true);
if (m_log != null) {
m_log.statusMessage(statusMessagePrefix() + "BUSY. Can't accept data "
+ "at this time.");
m_log.logMessage("[Classifier] " + statusMessagePrefix()
+ " BUSY. Can't accept data at this time.");
}
return;
}
// Do some initialization if this is the first set of the first run
if (e.getRunNumber() == 1 && e.getSetNumber() == 1) {
// m_oldText = m_visual.getText();
// store the training header
m_trainingSet = new Instances(e.getTrainingSet(), 0);
m_state = BUILDING_MODEL;
String msg =
"[Classifier] " + statusMessagePrefix() + " starting executor pool ("
+ getExecutionSlots() + " slots)...";
if (m_log != null) {
m_log.logMessage(msg);
} else {
System.err.println(msg);
}
// start the execution pool (always re-create the executor because the
// user
// might have changed the number of execution slots since the last time)
// if (m_executorPool == null) {
startExecutorPool();
// }
// setup output queues
msg = "[Classifier] " + statusMessagePrefix() + " setup output queues.";
if (m_log != null) {
m_log.logMessage(msg);
} else {
System.err.println(msg);
}
if (!m_batchStarted) {
m_outputQueues =
new BatchClassifierEvent[e.getMaxRunNumber()][e.getMaxSetNumber()];
m_completedSets = new boolean[e.getMaxRunNumber()][e.getMaxSetNumber()];
m_currentBatchIdentifier = new Date();
m_batchStarted = true;
}
}
// create a new task and schedule for execution
TrainingTask newTask =
new TrainingTask(e.getRunNumber(), e.getMaxRunNumber(), e.getSetNumber(),
e.getMaxSetNumber(), e.getTrainingSet());
String msg =
"[Classifier] " + statusMessagePrefix() + " scheduling run "
+ e.getRunNumber() + " fold " + e.getSetNumber() + " for execution...";
if (m_log != null) {
m_log.logMessage(msg);
} else {
System.err.println(msg);
}
// delay just a little bit
/*
* try { Thread.sleep(10); } catch (Exception ex){}
*/
m_executorPool.execute(newTask);
}
/**
* Check if the class is missing for all instances in the supplied set
*
* @param toCheck the instances to check
* @return true if all class values are missing
*/
protected static boolean allMissingClass(Instances toCheck) {
if (toCheck.classIndex() < 0) {
return false;
}
for (int i = 0; i < toCheck.numInstances(); i++) {
if (!toCheck.instance(i).classIsMissing()) {
return false;
}
}
return true;
}
/**
* Accepts a test set for a batch trained classifier
*
* @param e a <code>TestSetEvent</code> value
*/
@Override
public synchronized void acceptTestSet(TestSetEvent e) {
if (m_reject) {
if (m_log != null) {
m_log.statusMessage(statusMessagePrefix() + "BUSY. Can't accept data "
+ "at this time.");
m_log.logMessage("[Classifier] " + statusMessagePrefix()
+ " BUSY. Can't accept data at this time.");
}
return;
}
Instances testSet = e.getTestSet();
if (testSet != null) {
if (testSet.classIndex() < 0) {
// testSet.setClassIndex(testSet.numAttributes() - 1);
// stop all processing
stop();
String errorMessage =
statusMessagePrefix() + "ERROR: no class attribute set in test data!";
if (m_log != null) {
m_log.statusMessage(errorMessage);
m_log.logMessage("[Classifier] " + errorMessage);
} else {
System.err.println("[Classifier] " + errorMessage);
}
return;
}
}
if (m_loadModelFileName != null && m_loadModelFileName.length() > 0
&& m_state == IDLE && !m_listenees.containsKey("trainingSet")
&& e.getMaxRunNumber() == 1 && e.getMaxSetNumber() == 1) {
// load model (if specified)
String resolvedFileName = m_loadModelFileName;
if (m_env != null) {
try {
resolvedFileName = m_env.substitute(resolvedFileName);
} catch (Exception ex) {
}
}
File loadFrom = new File(resolvedFileName);
try {
loadFromFile(loadFrom);
} catch (Exception ex) {
stop();
m_log.statusMessage(statusMessagePrefix() + "ERROR: unable to load "
+ "model (see log).");
m_log.logMessage("[Classifier] " + statusMessagePrefix()
+ "Problem loading classifier. " + ex.getMessage());
return;
}
}
weka.classifiers.Classifier classifierToUse = m_Classifier;
// If we just have a test set connection or
// there is just one run involving one set (and we are not
// currently building a model), then use the
// last saved model
if (classifierToUse != null && m_state == IDLE
&& (!m_listenees.containsKey("trainingSet") /*
* || (e.getMaxRunNumber() ==
* 1 && e .getMaxSetNumber()
* == 1)
*/)) {
// if this is structure only then just return at this point
if (e.getTestSet() != null && e.isStructureOnly()) {
return;
}
if (classifierToUse instanceof EnvironmentHandler && m_env != null) {
((EnvironmentHandler) classifierToUse).setEnvironment(m_env);
}
if (classifierToUse instanceof weka.classifiers.misc.InputMappedClassifier) {
// make sure that we have the correct training header (if
// InputMappedClassifier
// is loading a model from a file).
try {
m_trainingSet =
((weka.classifiers.misc.InputMappedClassifier) classifierToUse)
.getModelHeader(m_trainingSet); // this returns the argument if a
// model is not being loaded
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
// check that we have a training set/header (if we don't,
// then it means that no model has been loaded
if (m_trainingSet == null) {
stop();
String errorMessage =
statusMessagePrefix()
+ "ERROR: no trained/loaded classifier to use for prediction!";
if (m_log != null) {
m_log.statusMessage(errorMessage);
m_log.logMessage("[Classifier] " + errorMessage);
} else {
System.err.println("[Classifier] " + errorMessage);
}
return;
}
testSet = e.getTestSet();
if (e.getRunNumber() == 1 && e.getSetNumber() == 1) {
m_currentBatchIdentifier = new Date();
}
if (testSet != null) {
if (!m_trainingSet.equalHeaders(testSet)
&& !(classifierToUse instanceof weka.classifiers.misc.InputMappedClassifier)) {
boolean wrapClassifier = false;
if (!Utils
.getDontShowDialog("weka.gui.beans.Classifier.AutoWrapInInputMappedClassifier")) {
// java.awt.GraphicsEnvironment ge = java.awt.GraphicsEnvironment
// .getLocalGraphicsEnvironment();
if (!GraphicsEnvironment.isHeadless()) {
JCheckBox dontShow =
new JCheckBox("Do not show this message again");
Object[] stuff = new Object[2];
stuff[0] =
"Data used to train model and test set are not compatible.\n"
+ "Would you like to automatically wrap the classifier in\n"
+ "an \"InputMappedClassifier\" before proceeding?.\n";
stuff[1] = dontShow;
int result =
JOptionPane.showConfirmDialog(this, stuff,
"KnowledgeFlow:Classifier", JOptionPane.YES_OPTION);
if (result == JOptionPane.YES_OPTION) {
wrapClassifier = true;
}
if (dontShow.isSelected()) {
String response = (wrapClassifier) ? "yes" : "no";
try {
Utils
.setDontShowDialogResponse(
"weka.gui.explorer.ClassifierPanel.AutoWrapInInputMappedClassifier",
response);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
} else {
// running headless, so just go ahead and wrap anyway
wrapClassifier = true;
}
} else {
// What did the user say - do they want to autowrap or not?
String response;
try {
response =
Utils
.getDontShowDialogResponse("weka.gui.explorer.ClassifierPanel.AutoWrapInInputMappedClassifier");
if (response != null && response.equalsIgnoreCase("yes")) {
wrapClassifier = true;
}
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
if (wrapClassifier) {
weka.classifiers.misc.InputMappedClassifier temp =
new weka.classifiers.misc.InputMappedClassifier();
temp.setClassifier(classifierToUse);
temp.setModelHeader(new Instances(m_trainingSet, 0));
classifierToUse = temp;
}
}
if (m_trainingSet.equalHeaders(testSet)
|| (classifierToUse instanceof weka.classifiers.misc.InputMappedClassifier)) {
BatchClassifierEvent ce =
new BatchClassifierEvent(this, classifierToUse, new DataSetEvent(
this, m_trainingSet), new DataSetEvent(this, e.getTestSet()),
e.getRunNumber(), e.getMaxRunNumber(), e.getSetNumber(),
e.getMaxSetNumber());
ce.setGroupIdentifier(m_currentBatchIdentifier.getTime());
ce.setLabel(getCustomName());
if (m_log != null && !e.isStructureOnly()) {
m_log.statusMessage(statusMessagePrefix() + "Finished.");
}
m_batchStarted = false;
notifyBatchClassifierListeners(ce);
} else {
// if headers do not match check to see if it's
// just the class that is different and that
// all class values are missing
if (testSet.numInstances() > 0) {
if (testSet.classIndex() == m_trainingSet.classIndex()
&& allMissingClass(testSet)) {
// now check the other attributes against the training
// structure
boolean ok = true;
for (int i = 0; i < testSet.numAttributes(); i++) {
if (i != testSet.classIndex()) {
ok = testSet.attribute(i).equals(m_trainingSet.attribute(i));
if (!ok) {
break;
}
}
}
if (ok) {
BatchClassifierEvent ce =
new BatchClassifierEvent(this, classifierToUse,
new DataSetEvent(this, m_trainingSet), new DataSetEvent(
this, e.getTestSet()), e.getRunNumber(),
e.getMaxRunNumber(), e.getSetNumber(), e.getMaxSetNumber());
ce.setGroupIdentifier(m_currentBatchIdentifier.getTime());
ce.setLabel(getCustomName());
if (m_log != null && !e.isStructureOnly()) {
m_log.statusMessage(statusMessagePrefix() + "Finished.");
}
m_batchStarted = false;
notifyBatchClassifierListeners(ce);
} else {
stop();
String errorMessage =
statusMessagePrefix()
+ "ERROR: structure of training and test sets is not compatible!";
if (m_log != null) {
m_log.statusMessage(errorMessage);
m_log.logMessage("[Classifier] " + errorMessage);
} else {
System.err.println("[Classifier] " + errorMessage);
}
}
}
}
}
}
} else {
/*
* System.err.println("[Classifier] accepting test set: run " +
* e.getRunNumber() + " fold " + e.getSetNumber());
*/
if (e.getRunNumber() == 1 && e.getSetNumber() == 1) {
if (!m_batchStarted) {
m_outputQueues =
new BatchClassifierEvent[e.getMaxRunNumber()][e.getMaxSetNumber()];
m_completedSets =
new boolean[e.getMaxRunNumber()][e.getMaxSetNumber()];
m_currentBatchIdentifier = new Date();
m_batchStarted = true;
}
}
if (m_outputQueues[e.getRunNumber() - 1][e.getSetNumber() - 1] == null) {
if (!e.isStructureOnly()) {
// store an event with a null model and training set (to be filled in
// later)
m_outputQueues[e.getRunNumber() - 1][e.getSetNumber() - 1] =
new BatchClassifierEvent(this, null, null, new DataSetEvent(this,
e.getTestSet()), e.getRunNumber(), e.getMaxRunNumber(),
e.getSetNumber(), e.getMaxSetNumber());
m_outputQueues[e.getRunNumber() - 1][e.getSetNumber() - 1]
.setLabel(getCustomName());
if (e.getRunNumber() == e.getMaxRunNumber()
&& e.getSetNumber() == e.getMaxSetNumber()) {
// block on the last fold of the last run (unless there is only one
// fold and one run)
/*
* System.err.println(
* "[Classifier] blocking on last fold of last run..." );
* block(true);
*/
if (e.getMaxSetNumber() != 1) {
m_reject = true;
if (m_block) {
block(true);
}
}
}
}
} else {
// Otherwise, there is a model here waiting for a test set...
m_outputQueues[e.getRunNumber() - 1][e.getSetNumber() - 1]
.setTestSet(new DataSetEvent(this, e.getTestSet()));
checkCompletedRun(e.getRunNumber(), e.getMaxRunNumber(),
e.getMaxSetNumber());
}
}
}
private synchronized void classifierTrainingComplete(BatchClassifierEvent ce) {
// check the output queues if we have an incoming test set connection
if (m_listenees.containsKey("testSet")) {
String msg =
"[Classifier] " + statusMessagePrefix() + " storing model for run "
+ ce.getRunNumber() + " fold " + ce.getSetNumber();
if (m_log != null) {
m_log.logMessage(msg);
} else {
System.err.println(msg);
}
if (m_outputQueues[ce.getRunNumber() - 1][ce.getSetNumber() - 1] == null) {
// store the event - test data filled in later
m_outputQueues[ce.getRunNumber() - 1][ce.getSetNumber() - 1] = ce;
} else {
// there is a test set here waiting for a model and training set
m_outputQueues[ce.getRunNumber() - 1][ce.getSetNumber() - 1]
.setClassifier(ce.getClassifier());
m_outputQueues[ce.getRunNumber() - 1][ce.getSetNumber() - 1]
.setTrainSet(ce.getTrainSet());
}
checkCompletedRun(ce.getRunNumber(), ce.getMaxRunNumber(),
ce.getMaxSetNumber());
}
}
private synchronized void checkCompletedRun(int runNum, int maxRunNum,
int maxSets) {
// look to see if there are any completed classifiers that we can pass
// on for evaluation
for (int i = 0; i < maxSets; i++) {
if (m_outputQueues[runNum - 1][i] != null) {
if (m_outputQueues[runNum - 1][i].getClassifier() != null
&& m_outputQueues[runNum - 1][i].getTestSet() != null) {
String msg =
"[Classifier] " + statusMessagePrefix() + " dispatching run/set "
+ runNum + "/" + (i + 1) + " to listeners.";
if (m_log != null) {
m_log.logMessage(msg);
} else {
System.err.println(msg);
}
// dispatch this one
m_outputQueues[runNum - 1][i]
.setGroupIdentifier(m_currentBatchIdentifier.getTime());
m_outputQueues[runNum - 1][i].setLabel(getCustomName());
notifyBatchClassifierListeners(m_outputQueues[runNum - 1][i]);
// save memory
m_outputQueues[runNum - 1][i] = null;
// mark as done
m_completedSets[runNum - 1][i] = true;
}
}
}
// scan for completion
boolean done = true;
for (int i = 0; i < maxRunNum; i++) {
for (int j = 0; j < maxSets; j++) {
if (!m_completedSets[i][j]) {
done = false;
break;
}
}
if (!done) {
break;
}
}
if (done) {
String msg =
"[Classifier] " + statusMessagePrefix()
+ " last classifier unblocking...";
if (m_log != null) {
m_log.logMessage(msg);
} else {
System.err.println(msg);
}
// m_visual.setText(m_oldText);
if (m_log != null) {
m_log.statusMessage(statusMessagePrefix() + "Finished.");
}
// m_outputQueues = null; // free memory
m_reject = false;
m_batchStarted = false;
block(false);
m_state = IDLE;
}
}
/*
* private synchronized void checkCompletedRun(int runNum, int maxRunNum, int
* maxSets) { boolean runOK = true; for (int i = 0; i < maxSets; i++) { if
* (m_outputQueues[runNum - 1][i] == null) { runOK = false; break; } else if
* (m_outputQueues[runNum - 1][i].getClassifier() == null ||
* m_outputQueues[runNum - 1][i].getTestSet() == null) { runOK = false; break;
* } }
*
* if (runOK) { String msg = "[Classifier] " + statusMessagePrefix() +
* " dispatching run " + runNum + " to listeners."; if (m_log != null) {
* m_log.logMessage(msg); } else { System.err.println(msg); } // dispatch this
* run to listeners for (int i = 0; i < maxSets; i++) {
* notifyBatchClassifierListeners(m_outputQueues[runNum - 1][i]); // save
* memory m_outputQueues[runNum - 1][i] = null; }
*
* if (runNum == maxRunNum) { // unblock msg = "[Classifier] " +
* statusMessagePrefix() + " last classifier unblocking...";
*
* if (m_log != null) { m_log.logMessage(msg); } else {
* System.err.println(msg); } //m_visual.setText(m_oldText);
*
* if (m_log != null) { m_log.statusMessage(statusMessagePrefix() +
* "Finished."); } // m_outputQueues = null; // free memory m_reject = false;
* block(false); m_state = IDLE; } } }
*/
/**
* Sets the visual appearance of this wrapper bean
*
* @param newVisual a <code>BeanVisual</code> value
*/
@Override
public void setVisual(BeanVisual newVisual) {
m_visual = newVisual;
}
/**
* Gets the visual appearance of this wrapper bean
*/
@Override
public BeanVisual getVisual() {
return m_visual;
}
/**
* Use the default visual appearance for this bean
*/
@Override
public void useDefaultVisual() {
// try to get a default for this package of classifiers
String name = m_ClassifierTemplate.getClass().toString();
String packageName = name.substring(0, name.lastIndexOf('.'));
packageName =
packageName.substring(packageName.lastIndexOf('.') + 1,
packageName.length());
if (!m_visual.loadIcons(BeanVisual.ICON_PATH + "Default_" + packageName
+ "Classifier.gif", BeanVisual.ICON_PATH + "Default_" + packageName
+ "Classifier_animated.gif")) {
m_visual.loadIcons(BeanVisual.ICON_PATH + "DefaultClassifier.gif",
BeanVisual.ICON_PATH + "DefaultClassifier_animated.gif");
}
}
/**
* Add a batch classifier listener
*
* @param cl a <code>BatchClassifierListener</code> value
*/
public synchronized void
addBatchClassifierListener(BatchClassifierListener cl) {
m_batchClassifierListeners.addElement(cl);
}
/**
* Remove a batch classifier listener
*
* @param cl a <code>BatchClassifierListener</code> value
*/
public synchronized void removeBatchClassifierListener(
BatchClassifierListener cl) {
m_batchClassifierListeners.remove(cl);
}
/**
* Notify all batch classifier listeners of a batch classifier event
*
* @param ce a <code>BatchClassifierEvent</code> value
*/
@SuppressWarnings("unchecked")
private synchronized void notifyBatchClassifierListeners(
BatchClassifierEvent ce) {
// don't do anything if the thread that we've been running in has been
// interrupted
if (Thread.currentThread().isInterrupted()) {
return;
}
Vector<BatchClassifierListener> l;
synchronized (this) {
l = (Vector<BatchClassifierListener>) m_batchClassifierListeners.clone();
}
if (l.size() > 0) {
for (int i = 0; i < l.size(); i++) {
if (l.size() > 1) {
try {
// make serialized copies here in order to protect classifiers that
// might not be thread safe in the predict/distributionForInstance()
// methods (e.g. FilteredClassifier). ClassifierPerformanceEvaluator
// is multi-threaded, so we could potentially have two different
// steps
// calling distributionForInstance() at the same time
weka.classifiers.Classifier newC =
weka.classifiers.AbstractClassifier.makeCopy(ce.getClassifier());
BatchClassifierEvent ne =
new BatchClassifierEvent(Classifier.this, newC, ce.getTrainSet(),
ce.getTestSet(), ce.getRunNumber(), ce.getMaxRunNumber(),
ce.getSetNumber(), ce.getMaxSetNumber());
l.elementAt(i).acceptClassifier(ne);
} catch (Exception e) {
stop(); // stop all processing
if (m_log != null) {
String msg =
statusMessagePrefix()
+ "ERROR: unable to make copy of classifier - see log ";
m_log.logMessage("[Classifier] " + msg + " (" + e.getMessage()
+ ")");
m_log.statusMessage(msg);
}
e.printStackTrace();
break;
}
} else {
l.elementAt(i).acceptClassifier(ce);
}
}
}
}
/**
* Add a graph listener
*
* @param cl a <code>GraphListener</code> value
*/
public synchronized void addGraphListener(GraphListener cl) {
m_graphListeners.addElement(cl);
}
/**
* Remove a graph listener
*
* @param cl a <code>GraphListener</code> value
*/
public synchronized void removeGraphListener(GraphListener cl) {
m_graphListeners.remove(cl);
}
/**
* Notify all graph listeners of a graph event
*
* @param ge a <code>GraphEvent</code> value
*/
@SuppressWarnings("unchecked")
private void notifyGraphListeners(GraphEvent ge) {
Vector<GraphListener> l;
synchronized (this) {
l = (Vector<GraphListener>) m_graphListeners.clone();
}
if (l.size() > 0) {
for (int i = 0; i < l.size(); i++) {
l.elementAt(i).acceptGraph(ge);
}
}
}
/**
* Add a text listener
*
* @param cl a <code>TextListener</code> value
*/
public synchronized void addTextListener(TextListener cl) {
m_textListeners.addElement(cl);
}
/**
* Remove a text listener
*
* @param cl a <code>TextListener</code> value
*/
public synchronized void removeTextListener(TextListener cl) {
m_textListeners.remove(cl);
}
/**
* We don't have to keep track of configuration listeners (see the
* documentation for ConfigurationListener/ConfigurationEvent).
*
* @param cl a ConfigurationListener.
*/
@Override
public synchronized void addConfigurationListener(ConfigurationListener cl) {
}
/**
* We don't have to keep track of configuration listeners (see the
* documentation for ConfigurationListener/ConfigurationEvent).
*
* @param cl a ConfigurationListener.
*/
@Override
public synchronized void
removeConfigurationListener(ConfigurationListener cl) {
}
/**
* Notify all text listeners of a text event
*
* @param ge a <code>TextEvent</code> value
*/
@SuppressWarnings("unchecked")
private void notifyTextListeners(TextEvent ge) {
Vector<TextListener> l;
synchronized (this) {
l = (Vector<TextListener>) m_textListeners.clone();
}
if (l.size() > 0) {
for (int i = 0; i < l.size(); i++) {
l.elementAt(i).acceptText(ge);
}
}
}
/**
* Add an incremental classifier listener
*
* @param cl an <code>IncrementalClassifierListener</code> value
*/
public synchronized void addIncrementalClassifierListener(
IncrementalClassifierListener cl) {
m_incrementalClassifierListeners.add(cl);
}
/**
* Remove an incremental classifier listener
*
* @param cl an <code>IncrementalClassifierListener</code> value
*/
public synchronized void removeIncrementalClassifierListener(
IncrementalClassifierListener cl) {
m_incrementalClassifierListeners.remove(cl);
}
/**
* Notify all incremental classifier listeners of an incremental classifier
* event
*
* @param ce an <code>IncrementalClassifierEvent</code> value
*/
@SuppressWarnings("unchecked")
private void notifyIncrementalClassifierListeners(
IncrementalClassifierEvent ce) {
// don't do anything if the thread that we've been running in has been
// interrupted
if (Thread.currentThread().isInterrupted()) {
return;
}
Vector<IncrementalClassifierListener> l;
synchronized (this) {
l =
(Vector<IncrementalClassifierListener>) m_incrementalClassifierListeners
.clone();
}
if (l.size() > 0) {
for (int i = 0; i < l.size(); i++) {
l.elementAt(i).acceptClassifier(ce);
}
}
}
/**
* Returns true if, at this time, the object will accept a connection with
* respect to the named event
*
* @param eventName the event
* @return true if the object will accept a connection
*/
@Override
public boolean connectionAllowed(String eventName) {
/*
* if (eventName.compareTo("instance") == 0) { if (!(m_Classifier instanceof
* weka.classifiers.UpdateableClassifier)) { return false; } }
*/
if (eventName.equals("trainingSet") && m_listenees.containsKey(eventName)) {
return false;
}
return true;
}
/**
* Returns true if, at this time, the object will accept a connection
* according to the supplied EventSetDescriptor
*
* @param esd the EventSetDescriptor
* @return true if the object will accept a connection
*/
@Override
public boolean connectionAllowed(EventSetDescriptor esd) {
return connectionAllowed(esd.getName());
}
/**
* Notify this object that it has been registered as a listener with a source
* with respect to the named event
*
* @param eventName the event
* @param source the source with which this object has been registered as a
* listener
*/
@Override
public synchronized void connectionNotification(String eventName,
Object source) {
if (eventName.compareTo("instance") == 0) {
if (!(m_ClassifierTemplate instanceof weka.classifiers.UpdateableClassifier)) {
if (m_log != null) {
String msg =
statusMessagePrefix() + "WARNING: "
+ m_ClassifierTemplate.getClass().getName()
+ " Is not an updateable classifier. This "
+ "classifier will only be evaluated on incoming "
+ "instance events and not trained on them.";
m_log.logMessage("[Classifier] " + msg);
m_log.statusMessage(msg);
}
}
}
if (eventName.equals("testSet") && m_listenees.containsKey("testSet")
&& m_log != null) {
if (!Utils
.getDontShowDialog("weka.gui.beans.ClassifierMultipleTestSetConnections")
&& !java.awt.GraphicsEnvironment.isHeadless()) {
String msg =
"You have more than one incoming test set connection to \n"
+ "'"
+ getCustomName()
+ "'. In order for this setup to run properly\n"
+ "and generate correct evaluation results you MUST execute the flow\n"
+ "by launching start points sequentially (second play button). In order\n"
+ "to specify the order you'd like the start points launched in you can\n"
+ "set the name of each start point (right click on start point and select\n"
+ "'Set name') to include a number prefix - e.g. '1: load my arff file'.";
JCheckBox dontShow = new JCheckBox("Do not show this message again");
Object[] stuff = new Object[2];
stuff[0] = msg;
stuff[1] = dontShow;
JOptionPane.showMessageDialog(null, stuff,
"Classifier test connection", JOptionPane.OK_OPTION);
if (dontShow.isSelected()) {
try {
Utils
.setDontShowDialog("weka.gui.beans.ClassifierMultipleTestSetConnections");
} catch (Exception ex) {
// quietly ignore
}
}
}
}
if (connectionAllowed(eventName)) {
List<Object> listenee = m_listenees.get(eventName);
if (listenee == null) {
listenee = new ArrayList<Object>();
m_listenees.put(eventName, listenee);
}
listenee.add(source);
/*
* if (eventName.compareTo("instance") == 0) { startIncrementalHandler();
* }
*/
}
}
/**
* Notify this object that it has been deregistered as a listener with a
* source with respect to the supplied event name
*
* @param eventName the event
* @param source the source with which this object has been registered as a
* listener
*/
@Override
public synchronized void disconnectionNotification(String eventName,
Object source) {
List<Object> listenees = m_listenees.get(eventName);
if (listenees != null) {
listenees.remove(source);
if (listenees.size() == 0) {
m_listenees.remove(eventName);
}
}
if (eventName.compareTo("instance") == 0) {
stop(); // kill the incremental handler thread if it is running
}
}
/**
* Function used to stop code that calls acceptTrainingSet. This is needed as
* classifier construction is performed inside a separate thread of execution.
*
* @param tf a <code>boolean</code> value
*/
private synchronized void block(boolean tf) {
if (tf) {
try {
// only block if thread is still doing something useful!
// if (m_state != IDLE) {
wait();
// }
} catch (InterruptedException ex) {
}
} else {
notifyAll();
}
}
/**
* Stop any classifier action
*/
@SuppressWarnings("deprecation")
@Override
public void stop() {
// tell all listenees (upstream beans) to stop
for (Map.Entry<String, List<Object>> e : m_listenees.entrySet()) {
List<Object> l = e.getValue();
for (Object o : l) {
if (o instanceof BeanCommon) {
((BeanCommon) o).stop();
}
}
}
/*
* Enumeration en = m_listenees.keys(); while (en.hasMoreElements()) {
* Object tempO = m_listenees.get(en.nextElement()); if (tempO instanceof
* BeanCommon) { ((BeanCommon) tempO).stop(); } }
*/
// shutdown the executor pool and reclaim storage
if (m_executorPool != null) {
m_executorPool.shutdownNow();
m_executorPool.purge();
m_executorPool = null;
}
m_reject = false;
m_batchStarted = false;
block(false);
m_visual.setStatic();
if (m_oldText.length() > 0) {
// m_visual.setText(m_oldText);
}
// stop the build thread
/*
* if (m_buildThread != null) { m_buildThread.interrupt();
* m_buildThread.stop(); m_buildThread = null; m_visual.setStatic(); }
*/
}
public void loadModel() {
try {
if (m_fileChooser == null) {
// i.e. after de-serialization
setupFileChooser();
}
int returnVal = m_fileChooser.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File loadFrom = m_fileChooser.getSelectedFile();
// add extension if necessary
if (m_fileChooser.getFileFilter() == m_binaryFilter) {
if (!loadFrom.getName().toLowerCase().endsWith("." + FILE_EXTENSION)) {
loadFrom =
new File(loadFrom.getParent(), loadFrom.getName() + "."
+ FILE_EXTENSION);
}
} else if (m_fileChooser.getFileFilter() == m_KOMLFilter) {
if (!loadFrom.getName().toLowerCase()
.endsWith(KOML.FILE_EXTENSION + FILE_EXTENSION)) {
loadFrom =
new File(loadFrom.getParent(), loadFrom.getName()
+ KOML.FILE_EXTENSION + FILE_EXTENSION);
}
} else if (m_fileChooser.getFileFilter() == m_XStreamFilter) {
if (!loadFrom.getName().toLowerCase()
.endsWith(XStream.FILE_EXTENSION + FILE_EXTENSION)) {
loadFrom =
new File(loadFrom.getParent(), loadFrom.getName()
+ XStream.FILE_EXTENSION + FILE_EXTENSION);
}
}
loadFromFile(loadFrom);
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(Classifier.this,
"Problem loading classifier.\n" + ex.getMessage(), "Load Model",
JOptionPane.ERROR_MESSAGE);
if (m_log != null) {
m_log.statusMessage(statusMessagePrefix() + "ERROR: unable to load "
+ "model (see log).");
m_log.logMessage("[Classifier] " + statusMessagePrefix()
+ "Problem loading classifier. " + ex.getMessage());
}
}
}
protected void loadFromFile(File loadFrom) throws Exception {
weka.classifiers.Classifier temp = null;
Instances tempHeader = null;
// KOML ?
if ((KOML.isPresent())
&& (loadFrom.getAbsolutePath().toLowerCase().endsWith(KOML.FILE_EXTENSION
+ FILE_EXTENSION))) {
@SuppressWarnings("unchecked")
Vector<Object> v = (Vector<Object>) KOML.read(loadFrom.getAbsolutePath());
temp = (weka.classifiers.Classifier) v.elementAt(0);
if (v.size() == 2) {
// try and grab the header
tempHeader = (Instances) v.elementAt(1);
}
} /* XStream */else if ((XStream.isPresent())
&& (loadFrom.getAbsolutePath().toLowerCase()
.endsWith(XStream.FILE_EXTENSION + FILE_EXTENSION))) {
@SuppressWarnings("unchecked")
Vector<Object> v =
(Vector<Object>) XStream.read(loadFrom.getAbsolutePath());
temp = (weka.classifiers.Classifier) v.elementAt(0);
if (v.size() == 2) {
// try and grab the header
tempHeader = (Instances) v.elementAt(1);
}
} /* binary */else {
ObjectInputStream is =
SerializationHelper.getObjectInputStream(new FileInputStream(loadFrom));
// try and read the model
temp = (weka.classifiers.Classifier) is.readObject();
// try and read the header (if present)
try {
tempHeader = (Instances) is.readObject();
} catch (Exception ex) {
// System.err.println("No header...");
// quietly ignore
}
is.close();
}
// Update name and icon
setTrainedClassifier(temp);
// restore header
m_trainingSet = tempHeader;
if (m_log != null) {
m_log.statusMessage(statusMessagePrefix() + "Loaded model.");
m_log.logMessage("[Classifier] " + statusMessagePrefix()
+ "Loaded classifier: " + m_Classifier.getClass().toString()
+ " from file '" + loadFrom.toString() + "'");
}
}
public void saveModel() {
try {
if (m_fileChooser == null) {
// i.e. after de-serialization
setupFileChooser();
}
int returnVal = m_fileChooser.showSaveDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File saveTo = m_fileChooser.getSelectedFile();
String fn = saveTo.getAbsolutePath();
if (m_fileChooser.getFileFilter() == m_binaryFilter) {
if (!fn.toLowerCase().endsWith("." + FILE_EXTENSION)) {
fn += "." + FILE_EXTENSION;
}
} else if (m_fileChooser.getFileFilter() == m_KOMLFilter) {
if (!fn.toLowerCase().endsWith(KOML.FILE_EXTENSION + FILE_EXTENSION)) {
fn += KOML.FILE_EXTENSION + FILE_EXTENSION;
}
} else if (m_fileChooser.getFileFilter() == m_XStreamFilter) {
if (!fn.toLowerCase().endsWith(
XStream.FILE_EXTENSION + FILE_EXTENSION)) {
fn += XStream.FILE_EXTENSION + FILE_EXTENSION;
}
}
saveTo = new File(fn);
// now serialize model
// KOML?
if ((KOML.isPresent())
&& saveTo.getAbsolutePath().toLowerCase()
.endsWith(KOML.FILE_EXTENSION + FILE_EXTENSION)) {
SerializedModelSaver.saveKOML(saveTo, m_Classifier,
(m_trainingSet != null) ? new Instances(m_trainingSet, 0) : null);
/*
* Vector v = new Vector(); v.add(m_Classifier); if (m_trainingSet !=
* null) { v.add(new Instances(m_trainingSet, 0)); } v.trimToSize();
* KOML.write(saveTo.getAbsolutePath(), v);
*/
} /* XStream */else if ((XStream.isPresent())
&& saveTo.getAbsolutePath().toLowerCase()
.endsWith(XStream.FILE_EXTENSION + FILE_EXTENSION)) {
SerializedModelSaver.saveXStream(saveTo, m_Classifier,
(m_trainingSet != null) ? new Instances(m_trainingSet, 0) : null);
/*
* Vector v = new Vector(); v.add(m_Classifier); if (m_trainingSet !=
* null) { v.add(new Instances(m_trainingSet, 0)); } v.trimToSize();
* XStream.write(saveTo.getAbsolutePath(), v);
*/
} else /* binary */{
ObjectOutputStream os =
new ObjectOutputStream(new BufferedOutputStream(
new FileOutputStream(saveTo)));
os.writeObject(m_Classifier);
if (m_trainingSet != null) {
Instances header = new Instances(m_trainingSet, 0);
os.writeObject(header);
}
os.close();
}
if (m_log != null) {
m_log.statusMessage(statusMessagePrefix() + "Model saved.");
m_log.logMessage("[Classifier] " + statusMessagePrefix()
+ " Saved classifier " + getCustomName());
}
}
} catch (Exception ex) {
JOptionPane
.showMessageDialog(Classifier.this, "Problem saving classifier.\n",
"Save Model", JOptionPane.ERROR_MESSAGE);
if (m_log != null) {
m_log.statusMessage(statusMessagePrefix() + "ERROR: unable to"
+ " save model (see log).");
m_log.logMessage("[Classifier] " + statusMessagePrefix()
+ " Problem saving classifier " + getCustomName() + ex.getMessage());
}
}
}
/**
* Set a logger
*
* @param logger a <code>Logger</code> value
*/
@Override
public void setLog(Logger logger) {
m_log = logger;
}
/**
* Return an enumeration of requests that can be made by the user
*
* @return an <code>Enumeration</code> value
*/
@Override
public Enumeration<String> enumerateRequests() {
Vector<String> newVector = new Vector<String>(0);
if (m_executorPool != null
&& (m_executorPool.getQueue().size() > 0 || m_executorPool
.getActiveCount() > 0)) {
newVector.addElement("Stop");
}
if ((m_executorPool == null || (m_executorPool.getQueue().size() == 0 && m_executorPool
.getActiveCount() == 0)) && m_Classifier != null) {
newVector.addElement("Save model");
}
if (m_executorPool == null
|| (m_executorPool.getQueue().size() == 0 && m_executorPool
.getActiveCount() == 0)) {
newVector.addElement("Load model");
}
return newVector.elements();
}
/**
* Perform a particular request
*
* @param request the request to perform
* @exception IllegalArgumentException if an error occurs
*/
@Override
public void performRequest(String request) {
if (request.compareTo("Stop") == 0) {
stop();
} else if (request.compareTo("Save model") == 0) {
saveModel();
} else if (request.compareTo("Load model") == 0) {
loadModel();
} else {
throw new IllegalArgumentException(request
+ " not supported (Classifier)");
}
}
/**
* Returns true, if at the current time, the event described by the supplied
* event descriptor could be generated.
*
* @param esd an <code>EventSetDescriptor</code> value
* @return a <code>boolean</code> value
*/
public boolean eventGeneratable(EventSetDescriptor esd) {
String eventName = esd.getName();
return eventGeneratable(eventName);
}
/**
* @param name of the event to check
* @return true if eventName is one of the possible events that this component
* can generate
*/
private boolean generatableEvent(String eventName) {
if (eventName.compareTo("graph") == 0 || eventName.compareTo("text") == 0
|| eventName.compareTo("batchClassifier") == 0
|| eventName.compareTo("incrementalClassifier") == 0
|| eventName.compareTo("configuration") == 0) {
return true;
}
return false;
}
/**
* Returns true, if at the current time, the named event could be generated.
* Assumes that the supplied event name is an event that could be generated by
* this bean
*
* @param eventName the name of the event in question
* @return true if the named event could be generated at this point in time
*/
@Override
public boolean eventGeneratable(String eventName) {
if (!generatableEvent(eventName)) {
return false;
}
if (eventName.compareTo("graph") == 0) {
// can't generate a GraphEvent if classifier is not drawable
if (!(m_ClassifierTemplate instanceof weka.core.Drawable)) {
return false;
}
// need to have a training set before the classifier
// can generate a graph!
if (!m_listenees.containsKey("trainingSet")) {
return false;
}
// Source needs to be able to generate a trainingSet
// before we can generate a graph
Object source = m_listenees.get("trainingSet");
if (source instanceof EventConstraints) {
if (!((EventConstraints) source).eventGeneratable("trainingSet")) {
return false;
}
}
}
if (eventName.compareTo("batchClassifier") == 0) {
/*
* if (!m_listenees.containsKey("testSet")) { return false; } if
* (!m_listenees.containsKey("trainingSet") && m_trainingSet == null) {
* return false; }
*/
if (!m_listenees.containsKey("testSet")
&& !m_listenees.containsKey("trainingSet")) {
return false;
}
Object source = m_listenees.get("testSet");
if (source instanceof EventConstraints) {
if (!((EventConstraints) source).eventGeneratable("testSet")) {
return false;
}
}
/*
* source = m_listenees.get("trainingSet"); if (source instanceof
* EventConstraints) { if
* (!((EventConstraints)source).eventGeneratable("trainingSet")) { return
* false; } }
*/
}
if (eventName.compareTo("text") == 0) {
if (!m_listenees.containsKey("trainingSet")
&& !m_listenees.containsKey("instance")) {
return false;
}
Object source = m_listenees.get("trainingSet");
if (source != null && source instanceof EventConstraints) {
if (!((EventConstraints) source).eventGeneratable("trainingSet")) {
return false;
}
}
source = m_listenees.get("instance");
if (source != null && source instanceof EventConstraints) {
if (!((EventConstraints) source).eventGeneratable("instance")) {
return false;
}
}
}
if (eventName.compareTo("incrementalClassifier") == 0) {
/*
* if (!(m_Classifier instanceof weka.classifiers.UpdateableClassifier)) {
* return false; }
*/
if (!m_listenees.containsKey("instance")) {
return false;
}
Object source = m_listenees.get("instance");
if (source instanceof EventConstraints) {
if (!((EventConstraints) source).eventGeneratable("instance")) {
return false;
}
}
}
if (eventName.equals("configuration") && m_Classifier == null) {
return false;
}
return true;
}
/**
* Returns true if. at this time, the bean is busy with some (i.e. perhaps a
* worker thread is performing some calculation).
*
* @return true if the bean is busy.
*/
@Override
public boolean isBusy() {
if (m_executorPool == null
|| (m_executorPool.getQueue().size() == 0 && m_executorPool
.getActiveCount() == 0) && m_state == IDLE) {
return false;
}
/*
* System.err.println("isBusy() Q:" + m_executorPool.getQueue().size()
* +" A:" + m_executorPool.getActiveCount());
*/
return true;
}
private String statusMessagePrefix() {
return getCustomName()
+ "$"
+ hashCode()
+ "|"
+ ((m_ClassifierTemplate instanceof OptionHandler && Utils.joinOptions(
((OptionHandler) m_ClassifierTemplate).getOptions()).length() > 0) ? Utils
.joinOptions(((OptionHandler) m_ClassifierTemplate).getOptions()) + "|"
: "");
}
/**
* Set environment variables to pass on to the classifier (if if is an
* EnvironmentHandler)
*/
@Override
public void setEnvironment(Environment env) {
m_env = env;
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/ClassifierBeanInfo.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/>.
*/
/*
* ClassifierBeanInfo.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.beans.BeanDescriptor;
import java.beans.EventSetDescriptor;
import java.beans.SimpleBeanInfo;
/**
* BeanInfo class for the Classifier wrapper bean
*
* @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a>
* @version $Revision$
*/
public class ClassifierBeanInfo extends SimpleBeanInfo {
public EventSetDescriptor [] getEventSetDescriptors() {
try {
EventSetDescriptor [] esds = {
new EventSetDescriptor(Classifier.class,
"batchClassifier",
BatchClassifierListener.class,
"acceptClassifier"),
new EventSetDescriptor(Classifier.class,
"graph",
GraphListener.class,
"acceptGraph"),
new EventSetDescriptor(Classifier.class,
"text",
TextListener.class,
"acceptText"),
new EventSetDescriptor(Classifier.class,
"incrementalClassifier",
IncrementalClassifierListener.class,
"acceptClassifier"),
new EventSetDescriptor(Classifier.class,
"configuration",
ConfigurationListener.class,
"acceptConfiguration")
};
return esds;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
/**
* Get the bean descriptor for this bean
*
* @return a <code>BeanDescriptor</code> value
*/
public BeanDescriptor getBeanDescriptor() {
return new BeanDescriptor(weka.gui.beans.Classifier.class,
ClassifierCustomizer.class);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/ClassifierCustomizer.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/>.
*/
/*
* ClassifierCustomizer.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import weka.classifiers.Classifier;
import weka.core.Environment;
import weka.core.EnvironmentHandler;
import weka.gui.GenericObjectEditor;
import weka.gui.PropertySheetPanel;
/**
* GUI customizer for the classifier wrapper bean
*
* @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a>
* @version $Revision$
*/
public class ClassifierCustomizer extends JPanel implements BeanCustomizer,
CustomizerClosingListener, CustomizerCloseRequester, EnvironmentHandler {
/** for serialization */
private static final long serialVersionUID = -6688000820160821429L;
static {
GenericObjectEditor.registerEditors();
}
private final PropertyChangeSupport m_pcSupport = new PropertyChangeSupport(
this);
private weka.gui.beans.Classifier m_dsClassifier;
/*
* private GenericObjectEditor m_ClassifierEditor = new
* GenericObjectEditor(true);
*/
private final PropertySheetPanel m_ClassifierEditor = new PropertySheetPanel();
private final JPanel m_incrementalPanel = new JPanel();
private final JCheckBox m_resetIncrementalClassifier = new JCheckBox(
"Reset classifier at the start of the stream");
private final JCheckBox m_updateIncrementalClassifier = new JCheckBox(
"Update classifier on incoming instance stream");
private boolean m_panelVisible = false;
private final JPanel m_holderPanel = new JPanel();
private final JTextField m_executionSlotsText = new JTextField();
private final JLabel m_executionSlotsLabel;
private final JPanel m_executionSlotsPanel;
private final JCheckBox m_blockOnLastFold = new JCheckBox(
"Block on last fold of last run");
private FileEnvironmentField m_loadModelField;
private Window m_parentWindow;
/** Copy of the current classifier in case cancel is selected */
protected weka.classifiers.Classifier m_backup;
private Environment m_env = Environment.getSystemWide();
/**
* Listener that wants to know the the modified status of the object that
* we're customizing
*/
private ModifyListener m_modifyListener;
public ClassifierCustomizer() {
m_ClassifierEditor.setBorder(BorderFactory
.createTitledBorder("Classifier options"));
m_incrementalPanel.setLayout(new GridLayout(0, 1));
m_resetIncrementalClassifier.setToolTipText("Reset the classifier "
+ "before processing the first incoming instance");
m_updateIncrementalClassifier.setToolTipText("Train the classifier on "
+ "each individual incoming streamed instance.");
m_updateIncrementalClassifier.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (m_dsClassifier != null) {
m_dsClassifier
.setUpdateIncrementalClassifier(m_updateIncrementalClassifier
.isSelected());
}
}
});
m_resetIncrementalClassifier.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (m_dsClassifier != null) {
m_dsClassifier
.setResetIncrementalClassifier(m_resetIncrementalClassifier
.isSelected());
}
}
});
m_incrementalPanel.add(m_resetIncrementalClassifier);
m_incrementalPanel.add(m_updateIncrementalClassifier);
m_executionSlotsText.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (m_dsClassifier != null
&& m_executionSlotsText.getText().length() > 0) {
int newSlots = Integer.parseInt(m_executionSlotsText.getText());
m_dsClassifier.setExecutionSlots(newSlots);
}
}
});
m_executionSlotsText.addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent e) {
}
@Override
public void focusLost(FocusEvent e) {
if (m_dsClassifier != null
&& m_executionSlotsText.getText().length() > 0) {
int newSlots = Integer.parseInt(m_executionSlotsText.getText());
m_dsClassifier.setExecutionSlots(newSlots);
}
}
});
m_blockOnLastFold.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (m_dsClassifier != null) {
m_dsClassifier.setBlockOnLastFold(m_blockOnLastFold.isSelected());
}
}
});
m_executionSlotsPanel = new JPanel();
m_executionSlotsPanel
.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
m_executionSlotsLabel = new JLabel("Execution slots");
m_executionSlotsPanel.setLayout(new BorderLayout());
m_executionSlotsPanel.add(m_executionSlotsLabel, BorderLayout.WEST);
m_executionSlotsPanel.add(m_executionSlotsText, BorderLayout.CENTER);
m_holderPanel.setBorder(BorderFactory.createTitledBorder("More options"));
m_holderPanel.setLayout(new BorderLayout());
m_holderPanel.add(m_executionSlotsPanel, BorderLayout.NORTH);
// m_blockOnLastFold.setHorizontalTextPosition(SwingConstants.RIGHT);
m_holderPanel.add(m_blockOnLastFold, BorderLayout.SOUTH);
JPanel holder2 = new JPanel();
holder2.setLayout(new BorderLayout());
holder2.add(m_holderPanel, BorderLayout.NORTH);
JButton OKBut = new JButton("OK");
JButton CancelBut = new JButton("Cancel");
OKBut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// forces the template to be deep copied to the actual classifier.
// necessary for InputMappedClassifier that is loading from a file
m_dsClassifier.setClassifierTemplate(m_dsClassifier
.getClassifierTemplate());
if (m_loadModelField != null) {
String loadFName = m_loadModelField.getText();
if (loadFName != null && loadFName.length() > 0) {
m_dsClassifier.setLoadClassifierFileName(m_loadModelField.getText());
} else {
m_dsClassifier.setLoadClassifierFileName("");
}
}
if (m_modifyListener != null) {
m_modifyListener.setModifiedStatus(ClassifierCustomizer.this, true);
}
m_parentWindow.dispose();
}
});
CancelBut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// cancel requested, so revert to backup and then
// close the dialog
if (m_backup != null) {
m_dsClassifier.setClassifierTemplate(m_backup);
}
if (m_modifyListener != null) {
m_modifyListener.setModifiedStatus(ClassifierCustomizer.this, false);
}
m_parentWindow.dispose();
}
});
JPanel butHolder = new JPanel();
butHolder.setLayout(new GridLayout(1, 2));
butHolder.add(OKBut);
butHolder.add(CancelBut);
holder2.add(butHolder, BorderLayout.SOUTH);
setLayout(new BorderLayout());
add(m_ClassifierEditor, BorderLayout.CENTER);
add(holder2, BorderLayout.SOUTH);
}
private void checkOnClassifierType() {
Classifier editedC = m_dsClassifier.getClassifierTemplate();
if (editedC instanceof weka.classifiers.UpdateableClassifier
&& m_dsClassifier.hasIncomingStreamInstances()) {
if (!m_panelVisible) {
m_holderPanel.add(m_incrementalPanel, BorderLayout.SOUTH);
m_panelVisible = true;
m_executionSlotsText.setEnabled(false);
m_loadModelField = new FileEnvironmentField("Load model from file",
m_env);
m_incrementalPanel.add(m_loadModelField);
m_loadModelField.setText(m_dsClassifier.getLoadClassifierFileName());
}
} else {
if (m_panelVisible) {
m_holderPanel.remove(m_incrementalPanel);
}
if (m_dsClassifier.hasIncomingStreamInstances()) {
m_loadModelField = new FileEnvironmentField("Load model from file",
m_env);
m_executionSlotsPanel.add(m_loadModelField, BorderLayout.SOUTH);
m_executionSlotsText.setEnabled(false);
m_blockOnLastFold.setEnabled(false);
m_loadModelField.setText(m_dsClassifier.getLoadClassifierFileName());
} else {
m_executionSlotsText.setEnabled(true);
m_blockOnLastFold.setEnabled(true);
}
m_panelVisible = false;
if (m_dsClassifier.hasIncomingBatchInstances()
&& !m_dsClassifier.m_listenees.containsKey("trainingSet")) {
m_holderPanel.remove(m_blockOnLastFold);
m_holderPanel.remove(m_executionSlotsPanel);
m_loadModelField = new FileEnvironmentField("Load model from file",
m_env);
m_holderPanel.add(m_loadModelField, BorderLayout.SOUTH);
m_loadModelField.setText(m_dsClassifier.getLoadClassifierFileName());
}
}
}
/**
* Set the classifier object to be edited
*
* @param object an <code>Object</code> value
*/
@Override
public void setObject(Object object) {
m_dsClassifier = (weka.gui.beans.Classifier) object;
// System.err.println(Utils.joinOptions(((OptionHandler)m_dsClassifier.getClassifier()).getOptions()));
try {
m_backup = (weka.classifiers.Classifier) GenericObjectEditor
.makeCopy(m_dsClassifier.getClassifierTemplate());
} catch (Exception ex) {
// ignore
}
m_ClassifierEditor.setEnvironment(m_env);
m_ClassifierEditor.setTarget(m_dsClassifier.getClassifierTemplate());
m_resetIncrementalClassifier.setSelected(m_dsClassifier
.getResetIncrementalClassifier());
m_updateIncrementalClassifier.setSelected(m_dsClassifier
.getUpdateIncrementalClassifier());
m_executionSlotsText.setText("" + m_dsClassifier.getExecutionSlots());
m_blockOnLastFold.setSelected(m_dsClassifier.getBlockOnLastFold());
checkOnClassifierType();
}
/*
* (non-Javadoc)
*
* @see weka.gui.beans.CustomizerClosingListener#customizerClosing()
*/
@Override
public void customizerClosing() {
if (m_executionSlotsText.getText().length() > 0) {
int newSlots = Integer.parseInt(m_executionSlotsText.getText());
m_dsClassifier.setExecutionSlots(newSlots);
}
}
/**
* Add a property change listener
*
* @param pcl a <code>PropertyChangeListener</code> value
*/
@Override
public void addPropertyChangeListener(PropertyChangeListener pcl) {
m_pcSupport.addPropertyChangeListener(pcl);
}
/**
* Remove a property change listener
*
* @param pcl a <code>PropertyChangeListener</code> value
*/
@Override
public void removePropertyChangeListener(PropertyChangeListener pcl) {
m_pcSupport.removePropertyChangeListener(pcl);
}
@Override
public void setParentWindow(Window parent) {
m_parentWindow = parent;
}
/**
* Set any environment variables to pass to the PropertySheetPanel
*
* @param env environment variables to pass to the property sheet panel
*/
@Override
public void setEnvironment(Environment env) {
m_env = env;
}
@Override
public void setModifiedListener(ModifyListener l) {
m_modifyListener = l;
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/ClassifierPerformanceEvaluator.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/>.
*/
/*
* ClassifierPerformanceEvaluator.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import weka.classifiers.AggregateableEvaluation;
import weka.classifiers.Classifier;
import weka.classifiers.Evaluation;
import weka.classifiers.evaluation.ThresholdCurve;
import weka.core.BatchPredictor;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.OptionHandler;
import weka.core.Utils;
import weka.experiment.Task;
import weka.experiment.TaskStatusInfo;
import weka.gui.explorer.ClassifierErrorsPlotInstances;
import weka.gui.explorer.ExplorerDefaults;
import weka.gui.visualize.PlotData2D;
/**
* A bean that evaluates the performance of batch trained classifiers
*
* @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a>
* @version $Revision$
*/
public class ClassifierPerformanceEvaluator extends AbstractEvaluator implements
BatchClassifierListener, Serializable, UserRequestAcceptor, EventConstraints {
/** for serialization */
private static final long serialVersionUID = -3511801418192148690L;
/**
* Evaluation object used for evaluating a classifier
*/
private transient AggregateableEvaluation m_eval;
private transient Instances m_aggregatedPlotInstances = null;
private transient ArrayList<Object> m_aggregatedPlotSizes = null;
private transient ArrayList<Integer> m_aggregatedPlotShapes = null;
// private transient Thread m_evaluateThread = null;
private transient long m_currentBatchIdentifier;
private transient int m_setsComplete;
private final Vector<TextListener> m_textListeners =
new Vector<TextListener>();
private final Vector<ThresholdDataListener> m_thresholdListeners =
new Vector<ThresholdDataListener>();
private final Vector<VisualizableErrorListener> m_visualizableErrorListeners =
new Vector<VisualizableErrorListener>();
protected transient ThreadPoolExecutor m_executorPool;
protected transient List<EvaluationTask> m_tasks;
protected boolean m_errorPlotPointSizeProportionalToMargin;
/**
* Number of threads to use to train models with
*/
protected int m_executionSlots = 2;
/** Evaluation metrics to output */
protected String m_selectedEvalMetrics = "";
protected List<String> m_metricsList = new ArrayList<String>();
public ClassifierPerformanceEvaluator() {
m_visual.loadIcons(BeanVisual.ICON_PATH
+ "ClassifierPerformanceEvaluator.gif", BeanVisual.ICON_PATH
+ "ClassifierPerformanceEvaluator_animated.gif");
m_visual.setText("ClassifierPerformanceEvaluator");
m_metricsList = Evaluation.getAllEvaluationMetricNames();
m_metricsList.remove("Coverage");
m_metricsList.remove("Region size");
StringBuilder b = new StringBuilder();
for (String s : m_metricsList) {
b.append(s).append(",");
}
m_selectedEvalMetrics = b.substring(0, b.length() - 1);
}
protected void stringToList(String l) {
if (l != null && l.length() > 0) {
String[] parts = l.split(",");
m_metricsList.clear();
for (String s : parts) {
m_metricsList.add(s.trim());
}
}
}
/**
* Set the evaluation metrics to output (as a comma-separated list).
*
* @param m the evaluation metrics to output
*/
public void setEvaluationMetricsToOutput(String m) {
m_selectedEvalMetrics = m;
stringToList(m);
}
/**
* Get the evaluation metrics to output (as a comma-separated list).
*
* @return the evaluation metrics to output
*/
public String getEvaluationMetricsToOutput() {
return m_selectedEvalMetrics;
}
/**
* Get the tip text for this property.
*
* @return the tip text for this property.
*/
public String evaluationMetricsToOutputTipText() {
return "A comma-separated list of evaluation metrics to output";
}
/**
* Set whether the point size on classification error plots should be
* proportional to the prediction margin.
*
* @param e true if the point size is to be proportional to the margin.
*/
public void setErrorPlotPointSizeProportionalToMargin(boolean e) {
m_errorPlotPointSizeProportionalToMargin = e;
}
/**
* Get whether the point size on classification error plots should be
* proportional to the prediction margin.
*
* @return true if the point size is to be proportional to the margin.
*/
public boolean getErrorPlotPointSizeProportionalToMargin() {
return m_errorPlotPointSizeProportionalToMargin;
}
/**
* Get the tip text for this property.
*
* @return the tip text for this property.
*/
public String errorPlotPointSizeProportionalToMarginTipText() {
return "Set the point size proportional to the prediction "
+ "margin for classification error plots";
}
/**
* Get the number of execution slots to use.
*
* @return the number of execution slots to use
*/
public int getExecutionSlots() {
return m_executionSlots;
}
/**
* Set the number of executions slots to use.
*
* @param slots the number of execution slots to use
*/
public void setExecutionSlots(int slots) {
m_executionSlots = slots;
}
/**
* Get the tip text for this property.
*
* @return the tip text for this property.
*/
public String executionSlotsTipText() {
return "Set the number of evaluation tasks to run in parallel.";
}
private void startExecutorPool() {
if (m_executorPool != null) {
m_executorPool.shutdownNow();
}
m_executorPool =
new ThreadPoolExecutor(m_executionSlots, m_executionSlots, 120,
TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
}
/**
* Set a custom (descriptive) name for this bean
*
* @param name the name to use
*/
@Override
public void setCustomName(String name) {
m_visual.setText(name);
}
/**
* Get the custom (descriptive) name for this bean (if one has been set)
*
* @return the custom name (or the default name)
*/
@Override
public String getCustomName() {
return m_visual.getText();
}
/**
* Global info for this bean
*
* @return a <code>String</code> value
*/
public String globalInfo() {
return "Evaluate the performance of batch trained classifiers.";
}
/** for generating plottable instance with predictions appended. */
private transient ClassifierErrorsPlotInstances m_PlotInstances = null;
protected static Evaluation adjustForInputMappedClassifier(Evaluation eval,
weka.classifiers.Classifier classifier, Instances inst,
ClassifierErrorsPlotInstances plotInstances) throws Exception {
if (classifier instanceof weka.classifiers.misc.InputMappedClassifier) {
Instances mappedClassifierHeader =
((weka.classifiers.misc.InputMappedClassifier) classifier)
.getModelHeader(new Instances(inst, 0));
eval = new Evaluation(new Instances(mappedClassifierHeader, 0));
if (!eval.getHeader().equalHeaders(inst)) {
// When the InputMappedClassifier is loading a model,
// we need to make a new dataset that maps the test instances to
// the structure expected by the mapped classifier - this is only
// to ensure that the ClassifierPlotInstances object is configured
// in accordance with what the embeded classifier was trained with
Instances mappedClassifierDataset =
((weka.classifiers.misc.InputMappedClassifier) classifier)
.getModelHeader(new Instances(mappedClassifierHeader, 0));
for (int zz = 0; zz < inst.numInstances(); zz++) {
Instance mapped =
((weka.classifiers.misc.InputMappedClassifier) classifier)
.constructMappedInstance(inst.instance(zz));
mappedClassifierDataset.add(mapped);
}
eval.setPriors(mappedClassifierDataset);
plotInstances.setInstances(mappedClassifierDataset);
plotInstances.setClassifier(classifier);
plotInstances.setClassIndex(mappedClassifierDataset.classIndex());
plotInstances.setEvaluation(eval);
}
}
return eval;
}
/**
* Inner class for running an evaluation on a split
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision$
*/
protected class EvaluationTask implements Runnable, Task {
private static final long serialVersionUID = -8939077467030259059L;
protected Instances m_testData;
protected Instances m_trainData;
protected int m_setNum;
protected int m_maxSetNum;
protected Classifier m_classifier;
protected boolean m_stopped;
protected String m_evalLabel = "";
/**
* Constructor for an EvaluationTask
*
* @param classifier the classifier being evaluated
* @param trainData the training data
* @param testData the test data
* @param setNum the set number
* @param maxSetNum maximum number of sets
* @param eventLabel the label to associate with this evaluation (for
* charting)
*/
public EvaluationTask(Classifier classifier, Instances trainData,
Instances testData, int setNum, int maxSetNum, String evalLabel) {
m_classifier = classifier;
m_setNum = setNum;
m_maxSetNum = maxSetNum;
m_testData = testData;
m_trainData = trainData;
if (evalLabel != null) {
m_evalLabel = evalLabel;
}
}
public void setStopped() {
m_stopped = true;
}
@Override
public void run() {
execute();
}
@Override
public void execute() {
if (m_stopped) {
return;
}
if (m_logger != null) {
m_logger.statusMessage(statusMessagePrefix() + "Evaluating ("
+ m_setNum + ")...");
}
try {
ClassifierErrorsPlotInstances plotInstances =
ExplorerDefaults.getClassifierErrorsPlotInstances();
Evaluation eval = null;
if (m_trainData == null || m_trainData.numInstances() == 0) {
eval = new Evaluation(m_testData);
plotInstances.setInstances(m_testData);
plotInstances.setClassifier(m_classifier);
plotInstances.setClassIndex(m_testData.classIndex());
plotInstances.setEvaluation(eval);
plotInstances
.setPointSizeProportionalToMargin(m_errorPlotPointSizeProportionalToMargin);
eval =
adjustForInputMappedClassifier(eval, m_classifier, m_testData,
plotInstances);
eval.useNoPriors();
eval.setMetricsToDisplay(m_metricsList);
} else {
eval = new Evaluation(m_trainData);
plotInstances.setInstances(m_trainData);
plotInstances.setClassifier(m_classifier);
plotInstances.setClassIndex(m_trainData.classIndex());
plotInstances.setEvaluation(eval);
plotInstances
.setPointSizeProportionalToMargin(m_errorPlotPointSizeProportionalToMargin);
eval =
adjustForInputMappedClassifier(eval, m_classifier, m_trainData,
plotInstances);
eval.setMetricsToDisplay(m_metricsList);
}
plotInstances.setUp();
if (m_classifier instanceof BatchPredictor
&& ((BatchPredictor) m_classifier)
.implementsMoreEfficientBatchPrediction()) {
double[][] predictions =
((BatchPredictor) m_classifier)
.distributionsForInstances(m_testData);
plotInstances.process(m_testData, predictions, eval);
} else {
for (int i = 0; i < m_testData.numInstances(); i++) {
if (m_stopped) {
break;
}
Instance temp = m_testData.instance(i);
plotInstances.process(temp, m_classifier, eval);
}
}
if (m_stopped) {
return;
}
aggregateEvalTask(eval, m_classifier, m_testData, plotInstances,
m_setNum, m_maxSetNum, m_evalLabel);
} catch (Exception ex) {
ClassifierPerformanceEvaluator.this.stop(); // stop all processing
if (m_logger != null) {
m_logger.logMessage("[ClassifierPerformanceEvaluator] "
+ statusMessagePrefix() + " problem evaluating classifier. "
+ ex.getMessage());
}
ex.printStackTrace();
}
}
@Override
public TaskStatusInfo getTaskStatus() {
// TODO Auto-generated method stub
return null;
}
}
/**
* Subclass of ClassifierErrorsPlotInstances to allow plot point sizes to be
* scaled according to global min/max values.
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
*/
protected static class AggregateableClassifierErrorsPlotInstances extends
ClassifierErrorsPlotInstances {
/**
* For serialization
*/
private static final long serialVersionUID = 2012744784036684168L;
/**
* Set the vector of plot shapes to use;
*
* @param plotShapes
*/
@Override
public void setPlotShapes(ArrayList<Integer> plotShapes) {
m_PlotShapes = plotShapes;
}
/**
* Set the vector of plot sizes to use
*
* @param plotSizes the plot sizes to use
*/
@Override
public void setPlotSizes(ArrayList<Object> plotSizes) {
m_PlotSizes = plotSizes;
}
public void setPlotInstances(Instances inst) {
m_PlotInstances = inst;
}
@Override
protected void finishUp() {
m_FinishUpCalled = true;
if (!m_SaveForVisualization) {
return;
}
if (m_Instances.classAttribute().isNumeric()
|| m_pointSizeProportionalToMargin) {
scaleNumericPredictions();
}
}
}
/**
* Takes an evaluation object from a task and aggregates it with the overall
* one.
*
* @param eval the evaluation object to aggregate
* @param classifier the classifier used by the task
* @param testData the testData from the task
* @param plotInstances the ClassifierErrorsPlotInstances object from the task
* @param setNum the set number processed by the task
* @param maxSetNum the maximum number of sets in this batch
* @param evalLabel the label to associate with the results of this evaluation
*/
@SuppressWarnings({ "deprecation", "unchecked" })
protected synchronized void aggregateEvalTask(Evaluation eval,
Classifier classifier, Instances testData,
ClassifierErrorsPlotInstances plotInstances, int setNum, int maxSetNum,
String evalLabel) {
m_eval.aggregate(eval);
if (m_aggregatedPlotInstances == null) {
// get these first so that the post-processing does not scale the sizes!!
m_aggregatedPlotShapes =
(ArrayList<Integer>) plotInstances.getPlotShapes().clone();
m_aggregatedPlotSizes =
(ArrayList<Object>) plotInstances.getPlotSizes().clone();
// this calls the post-processing, so do this last
m_aggregatedPlotInstances =
new Instances(plotInstances.getPlotInstances());
} else {
// get these first so that post-processing does not scale sizes
ArrayList<Object> tmpSizes =
(ArrayList<Object>) plotInstances.getPlotSizes().clone();
ArrayList<Integer> tmpShapes =
(ArrayList<Integer>) plotInstances.getPlotShapes().clone();
Instances temp = plotInstances.getPlotInstances();
for (int i = 0; i < temp.numInstances(); i++) {
m_aggregatedPlotInstances.add(temp.get(i));
m_aggregatedPlotShapes.add(tmpShapes.get(i));
m_aggregatedPlotSizes.add(tmpSizes.get(i));
}
}
m_setsComplete++;
if (m_logger != null) {
if (m_setsComplete < maxSetNum) {
m_logger.statusMessage(statusMessagePrefix() + "Completed ("
+ m_setsComplete + ").");
}
}
// if (ce.getSetNumber() == ce.getMaxSetNumber()) {
if (m_setsComplete == maxSetNum) {
try {
AggregateableClassifierErrorsPlotInstances aggPlot =
new AggregateableClassifierErrorsPlotInstances();
aggPlot.setInstances(testData);
aggPlot.setPlotInstances(m_aggregatedPlotInstances);
aggPlot.setPlotShapes(m_aggregatedPlotShapes);
aggPlot.setPlotSizes(m_aggregatedPlotSizes);
aggPlot
.setPointSizeProportionalToMargin(m_errorPlotPointSizeProportionalToMargin);
// triggers scaling of shape sizes
aggPlot.getPlotInstances();
String textTitle = "";
textTitle += classifier.getClass().getName();
String textOptions = "";
if (classifier instanceof OptionHandler) {
textOptions =
Utils.joinOptions(((OptionHandler) classifier).getOptions());
}
textTitle =
textTitle.substring(textTitle.lastIndexOf('.') + 1,
textTitle.length());
if (evalLabel != null && evalLabel.length() > 0) {
if (!textTitle.toLowerCase().startsWith(evalLabel.toLowerCase())) {
textTitle = evalLabel + " : " + textTitle;
}
}
String resultT =
"=== Evaluation result ===\n\n"
+ "Scheme: "
+ textTitle
+ "\n"
+ ((textOptions.length() > 0) ? "Options: " + textOptions + "\n"
: "") + "Relation: " + testData.relationName() + "\n\n"
+ m_eval.toSummaryString();
if (testData.classAttribute().isNominal()) {
resultT +=
"\n" + m_eval.toClassDetailsString() + "\n"
+ m_eval.toMatrixString();
}
TextEvent te =
new TextEvent(ClassifierPerformanceEvaluator.this, resultT, textTitle);
notifyTextListeners(te);
// set up visualizable errors
if (m_visualizableErrorListeners.size() > 0) {
PlotData2D errorD = new PlotData2D(m_aggregatedPlotInstances);
errorD.setShapeSize(m_aggregatedPlotSizes);
errorD.setShapeType(m_aggregatedPlotShapes);
errorD.setPlotName(textTitle + " " + textOptions);
/*
* PlotData2D errorD = m_PlotInstances.getPlotData( textTitle + " " +
* textOptions);
*/
VisualizableErrorEvent vel =
new VisualizableErrorEvent(ClassifierPerformanceEvaluator.this,
errorD);
notifyVisualizableErrorListeners(vel);
m_PlotInstances.cleanUp();
}
if (testData.classAttribute().isNominal()
&& m_thresholdListeners.size() > 0) {
ThresholdCurve tc = new ThresholdCurve();
Instances result = tc.getCurve(m_eval.predictions(), 0);
result.setRelationName(testData.relationName());
PlotData2D pd = new PlotData2D(result);
String htmlTitle = "<html><font size=-2>" + textTitle;
String newOptions = "";
if (classifier instanceof OptionHandler) {
String[] options = ((OptionHandler) classifier).getOptions();
if (options.length > 0) {
for (int ii = 0; ii < options.length; ii++) {
if (options[ii].length() == 0) {
continue;
}
if (options[ii].charAt(0) == '-'
&& !(options[ii].charAt(1) >= '0' && options[ii].charAt(1) <= '9')) {
newOptions += "<br>";
}
newOptions += options[ii];
}
}
}
htmlTitle +=
" " + newOptions + "<br>" + " (class: "
+ testData.classAttribute().value(0) + ")" + "</font></html>";
pd.setPlotName(textTitle + " (class: "
+ testData.classAttribute().value(0) + ")");
pd.setPlotNameHTML(htmlTitle);
boolean[] connectPoints = new boolean[result.numInstances()];
for (int jj = 1; jj < connectPoints.length; jj++) {
connectPoints[jj] = true;
}
pd.setConnectPoints(connectPoints);
ThresholdDataEvent rde =
new ThresholdDataEvent(ClassifierPerformanceEvaluator.this, pd,
testData.classAttribute());
notifyThresholdListeners(rde);
}
if (m_logger != null) {
m_logger.statusMessage(statusMessagePrefix() + "Finished.");
}
} catch (Exception ex) {
if (m_logger != null) {
m_logger.logMessage("[ClassifierPerformanceEvaluator] "
+ statusMessagePrefix()
+ " problem constructing evaluation results. " + ex.getMessage());
}
ex.printStackTrace();
} finally {
m_visual.setStatic();
// save memory
m_PlotInstances = null;
m_setsComplete = 0;
m_tasks = null;
m_aggregatedPlotInstances = null;
}
}
}
/**
* Accept a classifier to be evaluated.
*
* @param ce a <code>BatchClassifierEvent</code> value
*/
@Override
public void acceptClassifier(BatchClassifierEvent ce) {
if (ce.getTestSet() == null || ce.getTestSet().isStructureOnly()) {
return; // can't evaluate empty/non-existent test instances
}
Classifier classifier = ce.getClassifier();
try {
if (ce.getGroupIdentifier() != m_currentBatchIdentifier) {
if (m_setsComplete > 0) {
if (m_logger != null) {
m_logger.statusMessage(statusMessagePrefix()
+ "BUSY. Can't accept data " + "at this time.");
m_logger.logMessage("[ClassifierPerformanceEvaluator] "
+ statusMessagePrefix()
+ " BUSY. Can't accept data at this time.");
}
return;
}
if (ce.getTrainSet().getDataSet() == null
|| ce.getTrainSet().getDataSet().numInstances() == 0) {
// we have no training set to estimate majority class
// or mean of target from
Evaluation eval = new Evaluation(ce.getTestSet().getDataSet());
m_PlotInstances = ExplorerDefaults.getClassifierErrorsPlotInstances();
m_PlotInstances.setInstances(ce.getTestSet().getDataSet());
m_PlotInstances.setClassifier(ce.getClassifier());
m_PlotInstances.setClassIndex(ce.getTestSet().getDataSet()
.classIndex());
m_PlotInstances.setEvaluation(eval);
eval =
adjustForInputMappedClassifier(eval, ce.getClassifier(), ce
.getTestSet().getDataSet(), m_PlotInstances);
eval.useNoPriors();
m_eval = new AggregateableEvaluation(eval);
m_eval.setMetricsToDisplay(m_metricsList);
} else {
// we can set up with the training set here
Evaluation eval = new Evaluation(ce.getTrainSet().getDataSet());
m_PlotInstances = ExplorerDefaults.getClassifierErrorsPlotInstances();
m_PlotInstances.setInstances(ce.getTrainSet().getDataSet());
m_PlotInstances.setClassifier(ce.getClassifier());
m_PlotInstances.setClassIndex(ce.getTestSet().getDataSet()
.classIndex());
m_PlotInstances.setEvaluation(eval);
eval =
adjustForInputMappedClassifier(eval, ce.getClassifier(), ce
.getTrainSet().getDataSet(), m_PlotInstances);
m_eval = new AggregateableEvaluation(eval);
m_eval.setMetricsToDisplay(m_metricsList);
}
m_PlotInstances.setUp();
m_currentBatchIdentifier = ce.getGroupIdentifier();
m_setsComplete = 0;
m_aggregatedPlotInstances = null;
String msg =
"[ClassifierPerformanceEvaluator] " + statusMessagePrefix()
+ " starting executor pool (" + getExecutionSlots() + " slots)...";
// start the execution pool
startExecutorPool();
m_tasks = new ArrayList<EvaluationTask>();
if (m_logger != null) {
m_logger.logMessage(msg);
} else {
System.out.println(msg);
}
}
// if m_tasks == null then we've been stopped
if (m_setsComplete < ce.getMaxSetNumber() && m_tasks != null) {
EvaluationTask newTask =
new EvaluationTask(classifier, ce.getTrainSet().getDataSet(), ce
.getTestSet().getDataSet(), ce.getSetNumber(),
ce.getMaxSetNumber(), ce.getLabel());
String msg =
"[ClassifierPerformanceEvaluator] " + statusMessagePrefix()
+ " scheduling " + " evaluation of fold " + ce.getSetNumber()
+ " for execution...";
if (m_logger != null) {
m_logger.logMessage(msg);
} else {
System.out.println(msg);
}
m_tasks.add(newTask);
m_executorPool.execute(newTask);
}
} catch (Exception ex) {
ex.printStackTrace();
// stop everything
stop();
}
}
/**
* Returns true if. at this time, the bean is busy with some (i.e. perhaps a
* worker thread is performing some calculation).
*
* @return true if the bean is busy.
*/
@Override
public boolean isBusy() {
// return (m_evaluateThread != null);
if (m_executorPool == null
|| (m_executorPool.getQueue().size() == 0 && m_executorPool
.getActiveCount() == 0) && m_setsComplete == 0) {
return false;
}
return true;
}
/**
* Try and stop any action
*/
@SuppressWarnings("deprecation")
@Override
public void stop() {
// tell the listenee (upstream bean) to stop
if (m_listenee instanceof BeanCommon) {
// System.err.println("Listener is BeanCommon");
((BeanCommon) m_listenee).stop();
}
if (m_tasks != null) {
for (EvaluationTask t : m_tasks) {
t.setStopped();
}
}
m_tasks = null;
m_visual.setStatic();
m_setsComplete = 0;
// shutdown the executor pool and reclaim storage
if (m_executorPool != null) {
m_executorPool.shutdownNow();
m_executorPool.purge();
m_executorPool = null;
}
// stop the evaluate thread
/*
* if (m_evaluateThread != null) { m_evaluateThread.interrupt();
* m_evaluateThread.stop(); m_evaluateThread = null; m_visual.setStatic(); }
*/
}
/**
* Function used to stop code that calls acceptClassifier. This is needed as
* classifier evaluation is performed inside a separate thread of execution.
*
* @param tf a <code>boolean</code> value
*
* private synchronized void block(boolean tf) { if (tf) { try { //
* only block if thread is still doing something useful! if
* (m_evaluateThread != null && m_evaluateThread.isAlive()) { wait();
* } } catch (InterruptedException ex) { } } else { notifyAll(); } }
*/
/**
* Return an enumeration of user activated requests for this bean
*
* @return an <code>Enumeration</code> value
*/
@Override
public Enumeration<String> enumerateRequests() {
Vector<String> newVector = new Vector<String>(0);
/*
* if (m_evaluateThread != null) { newVector.addElement("Stop"); }
*/
if (m_executorPool != null
&& (m_executorPool.getQueue().size() > 0 || m_executorPool
.getActiveCount() > 0)) {
newVector.addElement("Stop");
}
return newVector.elements();
}
/**
* Perform the named request
*
* @param request the request to perform
* @exception IllegalArgumentException if an error occurs
*/
@Override
public void performRequest(String request) {
if (request.compareTo("Stop") == 0) {
stop();
} else {
throw new IllegalArgumentException(request
+ " not supported (ClassifierPerformanceEvaluator)");
}
}
/**
* Add a text listener
*
* @param cl a <code>TextListener</code> value
*/
public synchronized void addTextListener(TextListener cl) {
m_textListeners.addElement(cl);
}
/**
* Remove a text listener
*
* @param cl a <code>TextListener</code> value
*/
public synchronized void removeTextListener(TextListener cl) {
m_textListeners.remove(cl);
}
/**
* Add a threshold data listener
*
* @param cl a <code>ThresholdDataListener</code> value
*/
public synchronized void addThresholdDataListener(ThresholdDataListener cl) {
m_thresholdListeners.addElement(cl);
}
/**
* Remove a Threshold data listener
*
* @param cl a <code>ThresholdDataListener</code> value
*/
public synchronized void
removeThresholdDataListener(ThresholdDataListener cl) {
m_thresholdListeners.remove(cl);
}
/**
* Add a visualizable error listener
*
* @param vel a <code>VisualizableErrorListener</code> value
*/
public synchronized void addVisualizableErrorListener(
VisualizableErrorListener vel) {
m_visualizableErrorListeners.add(vel);
}
/**
* Remove a visualizable error listener
*
* @param vel a <code>VisualizableErrorListener</code> value
*/
public synchronized void removeVisualizableErrorListener(
VisualizableErrorListener vel) {
m_visualizableErrorListeners.remove(vel);
}
/**
* Notify all text listeners of a TextEvent
*
* @param te a <code>TextEvent</code> value
*/
@SuppressWarnings("unchecked")
private void notifyTextListeners(TextEvent te) {
Vector<TextListener> l;
synchronized (this) {
l = (Vector<TextListener>) m_textListeners.clone();
}
if (l.size() > 0) {
for (int i = 0; i < l.size(); i++) {
// System.err.println("Notifying text listeners "
// +"(ClassifierPerformanceEvaluator)");
l.elementAt(i).acceptText(te);
}
}
}
/**
* Notify all ThresholdDataListeners of a ThresholdDataEvent
*
* @param te a <code>ThresholdDataEvent</code> value
*/
@SuppressWarnings("unchecked")
private void notifyThresholdListeners(ThresholdDataEvent re) {
Vector<ThresholdDataListener> l;
synchronized (this) {
l = (Vector<ThresholdDataListener>) m_thresholdListeners.clone();
}
if (l.size() > 0) {
for (int i = 0; i < l.size(); i++) {
// System.err.println("Notifying text listeners "
// +"(ClassifierPerformanceEvaluator)");
l.elementAt(i).acceptDataSet(re);
}
}
}
/**
* Notify all VisualizableErrorListeners of a VisualizableErrorEvent
*
* @param te a <code>VisualizableErrorEvent</code> value
*/
@SuppressWarnings("unchecked")
private void notifyVisualizableErrorListeners(VisualizableErrorEvent re) {
Vector<VisualizableErrorListener> l;
synchronized (this) {
l =
(Vector<VisualizableErrorListener>) m_visualizableErrorListeners
.clone();
}
if (l.size() > 0) {
for (int i = 0; i < l.size(); i++) {
// System.err.println("Notifying text listeners "
// +"(ClassifierPerformanceEvaluator)");
l.elementAt(i).acceptDataSet(re);
}
}
}
/**
* Returns true, if at the current time, the named event could be generated.
* Assumes that supplied event names are names of events that could be
* generated by this bean.
*
* @param eventName the name of the event in question
* @return true if the named event could be generated at this point in time
*/
@Override
public boolean eventGeneratable(String eventName) {
if (m_listenee == null) {
return false;
}
if (m_listenee instanceof EventConstraints) {
if (!((EventConstraints) m_listenee).eventGeneratable("batchClassifier")) {
return false;
}
}
return true;
}
private String statusMessagePrefix() {
return getCustomName() + "$" + hashCode() + "|";
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/ClassifierPerformanceEvaluatorBeanInfo.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/>.
*/
/*
* ClassifierPerformanceEvaluatorBeanInfo.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.beans.BeanDescriptor;
import java.beans.EventSetDescriptor;
import java.beans.PropertyDescriptor;
import java.beans.SimpleBeanInfo;
/**
* Bean info class for the classifier performance evaluator
*
* @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a>
* @version $Revision$
*/
public class ClassifierPerformanceEvaluatorBeanInfo extends SimpleBeanInfo {
@Override
public EventSetDescriptor[] getEventSetDescriptors() {
try {
EventSetDescriptor[] esds = {
new EventSetDescriptor(ClassifierPerformanceEvaluator.class, "text",
TextListener.class, "acceptText"),
new EventSetDescriptor(ClassifierPerformanceEvaluator.class,
"thresholdData", ThresholdDataListener.class, "acceptDataSet"),
new EventSetDescriptor(ClassifierPerformanceEvaluator.class,
"visualizableError", VisualizableErrorListener.class,
"acceptDataSet") };
return esds;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
/**
* Get the property descriptors for this bean
*
* @return a <code>PropertyDescriptor[]</code> value
*/
@Override
public PropertyDescriptor[] getPropertyDescriptors() {
try {
PropertyDescriptor p1;
PropertyDescriptor p2;
p1 = new PropertyDescriptor("executionSlots",
ClassifierPerformanceEvaluator.class);
p2 = new PropertyDescriptor("errorPlotPointSizeProportionalToMargin",
ClassifierPerformanceEvaluator.class);
PropertyDescriptor[] pds = { p1, p2 };
return pds;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
/**
* Get the bean descriptor for this bean
*
* @return a <code>BeanDescriptor</code> value
*/
@Override
public BeanDescriptor getBeanDescriptor() {
return new BeanDescriptor(
weka.gui.beans.ClassifierPerformanceEvaluator.class,
ClassifierPerformanceEvaluatorCustomizer.class);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/ClassifierPerformanceEvaluatorCustomizer.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/>.
*/
/*
* ClassifierPerformanceEvaluatorCustomizer.java
* Copyright (C) 2011-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JPanel;
import weka.gui.EvaluationMetricSelectionDialog;
import weka.gui.PropertySheetPanel;
/**
* GUI customizer for the classifier performance evaluator component
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision$
*/
public class ClassifierPerformanceEvaluatorCustomizer extends JPanel implements
BeanCustomizer, CustomizerCloseRequester, CustomizerClosingListener {
/**
* For serialization
*/
private static final long serialVersionUID = -1055460295546483853L;
private final PropertyChangeSupport m_pcSupport = new PropertyChangeSupport(
this);
private final PropertySheetPanel m_splitEditor = new PropertySheetPanel();
private ClassifierPerformanceEvaluator m_cpe;
private ModifyListener m_modifyListener;
private int m_executionSlotsBackup;
private Window m_parent;
private final JButton m_evalMetricsBut = new JButton("Evaluation metrics...");
private List<String> m_evaluationMetrics;
/**
* Constructor
*/
public ClassifierPerformanceEvaluatorCustomizer() {
setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 5, 5, 5));
setLayout(new BorderLayout());
JPanel holder = new JPanel();
holder.setLayout(new BorderLayout());
holder.add(m_splitEditor, BorderLayout.NORTH);
holder.add(m_evalMetricsBut, BorderLayout.SOUTH);
add(holder, BorderLayout.NORTH);
m_evalMetricsBut
.setToolTipText("Enable/disable output of specific evaluation metrics");
addButtons();
}
private void addButtons() {
JButton okBut = new JButton("OK");
JButton cancelBut = new JButton("Cancel");
JPanel butHolder = new JPanel();
butHolder.setLayout(new GridLayout(1, 2));
butHolder.add(okBut);
butHolder.add(cancelBut);
add(butHolder, BorderLayout.SOUTH);
okBut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (m_modifyListener != null) {
m_modifyListener.setModifiedStatus(
ClassifierPerformanceEvaluatorCustomizer.this, true);
}
if (m_evaluationMetrics.size() > 0) {
StringBuilder b = new StringBuilder();
for (String s : m_evaluationMetrics) {
b.append(s).append(",");
}
String newList = b.substring(0, b.length() - 1);
m_cpe.setEvaluationMetricsToOutput(newList);
}
if (m_parent != null) {
m_parent.dispose();
}
}
});
cancelBut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
customizerClosing();
if (m_parent != null) {
m_parent.dispose();
}
}
});
}
/**
* Set the ClassifierPerformanceEvaluator to be customized
*
* @param object an <code>Object</code> value
*/
@Override
public void setObject(Object object) {
m_cpe = (ClassifierPerformanceEvaluator) object;
m_executionSlotsBackup = m_cpe.getExecutionSlots();
m_splitEditor.setTarget(m_cpe);
String list = m_cpe.getEvaluationMetricsToOutput();
m_evaluationMetrics = new ArrayList<String>();
if (list != null && list.length() > 0) {
String[] parts = list.split(",");
for (String s : parts) {
m_evaluationMetrics.add(s.trim());
}
}
}
/**
* Add a property change listener
*
* @param pcl a <code>PropertyChangeListener</code> value
*/
@Override
public void addPropertyChangeListener(PropertyChangeListener pcl) {
m_pcSupport.addPropertyChangeListener(pcl);
}
/**
* Remove a property change listener
*
* @param pcl a <code>PropertyChangeListener</code> value
*/
@Override
public void removePropertyChangeListener(PropertyChangeListener pcl) {
m_pcSupport.removePropertyChangeListener(pcl);
}
@Override
public void setModifiedListener(ModifyListener l) {
m_modifyListener = l;
}
@Override
public void customizerClosing() {
// restore the backup
m_cpe.setExecutionSlots(m_executionSlotsBackup);
}
@Override
public void setParentWindow(Window parent) {
m_parent = parent;
m_evalMetricsBut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
EvaluationMetricSelectionDialog esd = new EvaluationMetricSelectionDialog(
m_parent, m_evaluationMetrics);
esd.setLocation(m_evalMetricsBut.getLocationOnScreen());
esd.pack();
esd.setVisible(true);
m_evaluationMetrics = esd.getSelectedEvalMetrics();
}
});
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/Clusterer.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/>.
*/
/*
* Clusterer.java
* Copyright (C) 2004-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.awt.BorderLayout;
import java.beans.EventSetDescriptor;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import weka.clusterers.EM;
import weka.core.Instances;
import weka.core.OptionHandler;
import weka.core.Utils;
import weka.filters.Filter;
import weka.filters.unsupervised.attribute.Remove;
import weka.gui.ExtensionFileFilter;
import weka.gui.Logger;
/**
* Bean that wraps around weka.clusterers
*
* @author <a href="mailto:mutter@cs.waikato.ac.nz">Stefan Mutter</a>
* @version $Revision$
* @see JPanel
* @see BeanCommon
* @see Visible
* @see WekaWrapper
* @see Serializable
* @see UserRequestAcceptor
* @see TrainingSetListener
* @see TestSetListener
*/
public class Clusterer extends JPanel implements BeanCommon, Visible,
WekaWrapper, EventConstraints, UserRequestAcceptor, TrainingSetListener,
TestSetListener, ConfigurationProducer {
/** for serialization */
private static final long serialVersionUID = 7729795159836843810L;
protected BeanVisual m_visual = new BeanVisual("Clusterer",
BeanVisual.ICON_PATH + "EM.gif", BeanVisual.ICON_PATH + "EM_animated.gif");
private static int IDLE = 0;
private static int BUILDING_MODEL = 1;
private static int CLUSTERING = 2;
private int m_state = IDLE;
private Thread m_buildThread = null;
/**
* Global info for the wrapped classifier (if it exists).
*/
protected String m_globalInfo;
/**
* Objects talking to us
*/
private final Hashtable<String, Object> m_listenees = new Hashtable<String, Object>();
/**
* Objects listening for batch clusterer events
*/
private final Vector<BatchClustererListener> m_batchClustererListeners = new Vector<BatchClustererListener>();
/**
* Objects listening for graph events
*/
private final Vector<GraphListener> m_graphListeners = new Vector<GraphListener>();
/**
* Objects listening for text events
*/
private final Vector<TextListener> m_textListeners = new Vector<TextListener>();
/**
* Holds training instances for batch training.
*/
private Instances m_trainingSet;
private transient Instances m_testingSet;
private weka.clusterers.Clusterer m_Clusterer = new EM();
private transient Logger m_log = null;
@SuppressWarnings("unused")
private final Double m_dummy = new Double(0.0);
private transient JFileChooser m_fileChooser = null;
/**
* Global info (if it exists) for the wrapped classifier
*
* @return the global info
*/
public String globalInfo() {
return m_globalInfo;
}
/**
* Creates a new <code>Clusterer</code> instance.
*/
public Clusterer() {
setLayout(new BorderLayout());
add(m_visual, BorderLayout.CENTER);
setClusterer(m_Clusterer);
}
/**
* Set a custom (descriptive) name for this bean
*
* @param name the name to use
*/
@Override
public void setCustomName(String name) {
m_visual.setText(name);
}
/**
* Get the custom (descriptive) name for this bean (if one has been set)
*
* @return the custom name (or the default name)
*/
@Override
public String getCustomName() {
return m_visual.getText();
}
/**
* Set the clusterer for this wrapper
*
* @param c a <code>weka.clusterers.Clusterer</code> value
*/
public void setClusterer(weka.clusterers.Clusterer c) {
boolean loadImages = true;
if (c.getClass().getName().compareTo(m_Clusterer.getClass().getName()) == 0) {
loadImages = false;
} else {
// clusterer has changed so any batch training status is now
// invalid
m_trainingSet = null;
}
m_Clusterer = c;
String clustererName = c.getClass().toString();
clustererName = clustererName.substring(clustererName.lastIndexOf('.') + 1,
clustererName.length());
if (loadImages) {
if (!m_visual.loadIcons(BeanVisual.ICON_PATH + clustererName + ".gif",
BeanVisual.ICON_PATH + clustererName + "_animated.gif")) {
useDefaultVisual();
}
}
m_visual.setText(clustererName);
// get global info
m_globalInfo = KnowledgeFlowApp.getGlobalInfo(m_Clusterer);
}
/**
* Returns true if this clusterer has an incoming connection that is a batch
* set of instances
*
* @return a <code>boolean</code> value
*/
public boolean hasIncomingBatchInstances() {
if (m_listenees.size() == 0) {
return false;
}
if (m_listenees.containsKey("trainingSet")
|| m_listenees.containsKey("testSet")
|| m_listenees.containsKey("dataSet")) {
return true;
}
return false;
}
/**
* Get the clusterer currently set for this wrapper
*
* @return a <code>weka.clusterers.Clusterer</code> value
*/
public weka.clusterers.Clusterer getClusterer() {
return m_Clusterer;
}
/**
* Sets the algorithm (clusterer) for this bean
*
* @param algorithm an <code>Object</code> value
* @exception IllegalArgumentException if an error occurs
*/
@Override
public void setWrappedAlgorithm(Object algorithm) {
if (!(algorithm instanceof weka.clusterers.Clusterer)) {
throw new IllegalArgumentException(algorithm.getClass() + " : incorrect "
+ "type of algorithm (Clusterer)");
}
setClusterer((weka.clusterers.Clusterer) algorithm);
}
/**
* Returns the wrapped clusterer
*
* @return an <code>Object</code> value
*/
@Override
public Object getWrappedAlgorithm() {
return getClusterer();
}
/**
* Accepts a training set and builds batch clusterer
*
* @param e a <code>TrainingSetEvent</code> value
*/
@Override
public void acceptTrainingSet(final TrainingSetEvent e) {
if (e.isStructureOnly()) {
// no need to build a clusterer, instead just generate a dummy
// BatchClustererEvent in order to pass on instance structure to
// any listeners
BatchClustererEvent ce = new BatchClustererEvent(this, m_Clusterer,
new DataSetEvent(this, e.getTrainingSet()), e.getSetNumber(),
e.getMaxSetNumber(), 1);
notifyBatchClustererListeners(ce);
return;
}
if (m_buildThread == null) {
try {
if (m_state == IDLE) {
synchronized (this) {
m_state = BUILDING_MODEL;
}
m_trainingSet = e.getTrainingSet();
// final String oldText = m_visual.getText();
m_buildThread = new Thread() {
@SuppressWarnings("deprecation")
@Override
public void run() {
try {
if (m_trainingSet != null) {
m_visual.setAnimated();
// m_visual.setText("Building clusters...");
if (m_log != null) {
m_log.statusMessage(statusMessagePrefix()
+ "Building clusters...");
}
buildClusterer();
if (m_batchClustererListeners.size() > 0) {
BatchClustererEvent ce = new BatchClustererEvent(this,
m_Clusterer, new DataSetEvent(this, e.getTrainingSet()),
e.getSetNumber(), e.getMaxSetNumber(), 1);
notifyBatchClustererListeners(ce);
}
if (m_Clusterer instanceof weka.core.Drawable
&& m_graphListeners.size() > 0) {
String grphString = ((weka.core.Drawable) m_Clusterer)
.graph();
int grphType = ((weka.core.Drawable) m_Clusterer)
.graphType();
String grphTitle = m_Clusterer.getClass().getName();
grphTitle = grphTitle.substring(
grphTitle.lastIndexOf('.') + 1, grphTitle.length());
grphTitle = "Set " + e.getSetNumber() + " ("
+ e.getTrainingSet().relationName() + ") " + grphTitle;
GraphEvent ge = new GraphEvent(Clusterer.this, grphString,
grphTitle, grphType);
notifyGraphListeners(ge);
}
if (m_textListeners.size() > 0) {
String modelString = m_Clusterer.toString();
String titleString = m_Clusterer.getClass().getName();
titleString = titleString.substring(
titleString.lastIndexOf('.') + 1, titleString.length());
modelString = "=== Clusterer model ===\n\n"
+ "Scheme: "
+ titleString
+ "\n"
+ "Relation: "
+ m_trainingSet.relationName()
+ ((e.getMaxSetNumber() > 1) ? "\nTraining Fold: "
+ e.getSetNumber() : "") + "\n\n" + modelString;
titleString = "Model: " + titleString;
TextEvent nt = new TextEvent(Clusterer.this, modelString,
titleString);
notifyTextListeners(nt);
}
}
} catch (Exception ex) {
Clusterer.this.stop(); // stop processing
if (m_log != null) {
m_log.statusMessage(statusMessagePrefix()
+ "ERROR (See log for details");
m_log.logMessage("[Clusterer] " + statusMessagePrefix()
+ " problem training clusterer. " + ex.getMessage());
}
ex.printStackTrace();
} finally {
// m_visual.setText(oldText);
m_visual.setStatic();
m_state = IDLE;
if (isInterrupted()) {
// prevent any clusterer events from being fired
m_trainingSet = null;
if (m_log != null) {
m_log.logMessage("[Clusterer]" + statusMessagePrefix()
+ " Build clusterer interrupted!");
m_log.statusMessage(statusMessagePrefix() + "INTERRUPTED");
}
} else {
// save header
m_trainingSet = new Instances(m_trainingSet, 0);
if (m_log != null) {
m_log.statusMessage(statusMessagePrefix() + "Finished.");
}
}
block(false);
}
}
};
m_buildThread.setPriority(Thread.MIN_PRIORITY);
m_buildThread.start();
// make sure the thread is still running before we block
// if (m_buildThread.isAlive()) {
block(true);
// }
m_buildThread = null;
m_state = IDLE;
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
/**
* Accepts a test set for a batch trained clusterer
*
* @param e a <code>TestSetEvent</code> value
*/
@Override
public void acceptTestSet(TestSetEvent e) {
if (m_trainingSet != null) {
try {
if (m_state == IDLE) {
synchronized (this) {
m_state = CLUSTERING;
}
m_testingSet = e.getTestSet();
if (m_trainingSet.equalHeaders(m_testingSet)) {
BatchClustererEvent ce = new BatchClustererEvent(this, m_Clusterer,
new DataSetEvent(this, e.getTestSet()), e.getSetNumber(),
e.getMaxSetNumber(), 0);
notifyBatchClustererListeners(ce);
}
m_state = IDLE;
}
} catch (Exception ex) {
stop(); // stop any processing
if (m_log != null) {
m_log.statusMessage(statusMessagePrefix()
+ "ERROR (see log for details");
m_log.logMessage("[Clusterer] " + statusMessagePrefix()
+ " problem during testing. " + ex.getMessage());
}
ex.printStackTrace();
}
}
}
/**
* Builds the clusters
*/
private void buildClusterer() throws Exception {
if (m_trainingSet.classIndex() < 0) {
m_Clusterer.buildClusterer(m_trainingSet);
} else { // class based evaluation if class attribute is set
Remove removeClass = new Remove();
removeClass.setAttributeIndices("" + (m_trainingSet.classIndex() + 1));
removeClass.setInvertSelection(false);
removeClass.setInputFormat(m_trainingSet);
Instances clusterTrain = Filter.useFilter(m_trainingSet, removeClass);
m_Clusterer.buildClusterer(clusterTrain);
}
}
/**
* Sets the visual appearance of this wrapper bean
*
* @param newVisual a <code>BeanVisual</code> value
*/
@Override
public void setVisual(BeanVisual newVisual) {
m_visual = newVisual;
}
/**
* Gets the visual appearance of this wrapper bean
*/
@Override
public BeanVisual getVisual() {
return m_visual;
}
/**
* Use the default visual appearance for this bean
*/
@Override
public void useDefaultVisual() {
m_visual.loadIcons(BeanVisual.ICON_PATH + "DefaultClusterer.gif",
BeanVisual.ICON_PATH + "DefaultClusterer_animated.gif");
}
/**
* Add a batch clusterer listener
*
* @param cl a <code>BatchClustererListener</code> value
*/
public synchronized void addBatchClustererListener(BatchClustererListener cl) {
m_batchClustererListeners.addElement(cl);
}
/**
* Remove a batch clusterer listener
*
* @param cl a <code>BatchClustererListener</code> value
*/
public synchronized void removeBatchClustererListener(
BatchClustererListener cl) {
m_batchClustererListeners.remove(cl);
}
/**
* Notify all batch clusterer listeners of a batch clusterer event
*
* @param ce a <code>BatchClustererEvent</code> value
*/
@SuppressWarnings("unchecked")
private void notifyBatchClustererListeners(BatchClustererEvent ce) {
Vector<BatchClustererListener> l;
synchronized (this) {
l = (Vector<BatchClustererListener>) m_batchClustererListeners.clone();
}
if (l.size() > 0) {
for (int i = 0; i < l.size(); i++) {
l.elementAt(i).acceptClusterer(ce);
}
}
}
/**
* Add a graph listener
*
* @param cl a <code>GraphListener</code> value
*/
public synchronized void addGraphListener(GraphListener cl) {
m_graphListeners.addElement(cl);
}
/**
* Remove a graph listener
*
* @param cl a <code>GraphListener</code> value
*/
public synchronized void removeGraphListener(GraphListener cl) {
m_graphListeners.remove(cl);
}
/**
* Notify all graph listeners of a graph event
*
* @param ge a <code>GraphEvent</code> value
*/
@SuppressWarnings("unchecked")
private void notifyGraphListeners(GraphEvent ge) {
Vector<GraphListener> l;
synchronized (this) {
l = (Vector<GraphListener>) m_graphListeners.clone();
}
if (l.size() > 0) {
for (int i = 0; i < l.size(); i++) {
l.elementAt(i).acceptGraph(ge);
}
}
}
/**
* Add a text listener
*
* @param cl a <code>TextListener</code> value
*/
public synchronized void addTextListener(TextListener cl) {
m_textListeners.addElement(cl);
}
/**
* Remove a text listener
*
* @param cl a <code>TextListener</code> value
*/
public synchronized void removeTextListener(TextListener cl) {
m_textListeners.remove(cl);
}
/**
* Notify all text listeners of a text event
*
* @param ge a <code>TextEvent</code> value
*/
@SuppressWarnings("unchecked")
private void notifyTextListeners(TextEvent ge) {
Vector<TextListener> l;
synchronized (this) {
l = (Vector<TextListener>) m_textListeners.clone();
}
if (l.size() > 0) {
for (int i = 0; i < l.size(); i++) {
l.elementAt(i).acceptText(ge);
}
}
}
/**
* We don't have to keep track of configuration listeners (see the
* documentation for ConfigurationListener/ConfigurationEvent).
*
* @param cl a ConfigurationListener.
*/
@Override
public synchronized void addConfigurationListener(ConfigurationListener cl) {
}
/**
* We don't have to keep track of configuration listeners (see the
* documentation for ConfigurationListener/ConfigurationEvent).
*
* @param cl a ConfigurationListener.
*/
@Override
public synchronized void removeConfigurationListener(ConfigurationListener cl) {
}
/**
* Returns true if, at this time, the object will accept a connection with
* respect to the named event
*
* @param eventName the event
* @return true if the object will accept a connection
*/
@Override
public boolean connectionAllowed(String eventName) {
/*
* if (eventName.compareTo("instance") == 0) { if (!(m_Clusterer instanceof
* weka.classifiers.UpdateableClassifier)) { return false; } }
*/
if (m_listenees.containsKey(eventName)) {
return false;
}
return true;
}
/**
* Returns true if, at this time, the object will accept a connection
* according to the supplied EventSetDescriptor
*
* @param esd the EventSetDescriptor
* @return true if the object will accept a connection
*/
@Override
public boolean connectionAllowed(EventSetDescriptor esd) {
return connectionAllowed(esd.getName());
}
/**
* Notify this object that it has been registered as a listener with a source
* with respect to the named event
*
* @param eventName the event
* @param source the source with which this object has been registered as a
* listener
*/
@Override
public synchronized void connectionNotification(String eventName,
Object source) {
if (connectionAllowed(eventName)) {
m_listenees.put(eventName, source);
/*
* if (eventName.compareTo("instance") == 0) { startIncrementalHandler();
* }
*/
}
}
/**
* Notify this object that it has been deregistered as a listener with a
* source with respect to the supplied event name
*
* @param eventName the event
* @param source the source with which this object has been registered as a
* listener
*/
@Override
public synchronized void disconnectionNotification(String eventName,
Object source) {
m_listenees.remove(eventName);
}
/**
* Function used to stop code that calls acceptTrainingSet. This is needed as
* clusterer construction is performed inside a separate thread of execution.
*
* @param tf a <code>boolean</code> value
*/
private synchronized void block(boolean tf) {
if (tf) {
try {
// only block if thread is still doing something useful!
if (m_buildThread.isAlive() && m_state != IDLE) {
wait();
}
} catch (InterruptedException ex) {
}
} else {
notifyAll();
}
}
/**
* Returns true if. at this time, the bean is busy with some (i.e. perhaps a
* worker thread is performing some calculation).
*
* @return true if the bean is busy.
*/
@Override
public boolean isBusy() {
return (m_buildThread != null);
}
/**
* Stop any clusterer action
*/
@SuppressWarnings("deprecation")
@Override
public void stop() {
// tell all listenees (upstream beans) to stop
Enumeration<String> en = m_listenees.keys();
while (en.hasMoreElements()) {
Object tempO = m_listenees.get(en.nextElement());
if (tempO instanceof BeanCommon) {
((BeanCommon) tempO).stop();
}
}
// stop the build thread
if (m_buildThread != null) {
m_buildThread.interrupt();
m_buildThread.stop();
m_buildThread = null;
m_visual.setStatic();
}
}
/**
* Set a logger
*
* @param logger a <code>Logger</code> value
*/
@Override
public void setLog(Logger logger) {
m_log = logger;
}
public void saveModel() {
try {
if (m_fileChooser == null) {
// i.e. after de-serialization
m_fileChooser = new JFileChooser(new File(
System.getProperty("user.dir")));
ExtensionFileFilter ef = new ExtensionFileFilter("model",
"Serialized weka clusterer");
m_fileChooser.setFileFilter(ef);
}
int returnVal = m_fileChooser.showSaveDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File saveTo = m_fileChooser.getSelectedFile();
String fn = saveTo.getAbsolutePath();
if (!fn.endsWith(".model")) {
fn += ".model";
saveTo = new File(fn);
}
ObjectOutputStream os = new ObjectOutputStream(
new BufferedOutputStream(new FileOutputStream(saveTo)));
os.writeObject(m_Clusterer);
if (m_trainingSet != null) {
Instances header = new Instances(m_trainingSet, 0);
os.writeObject(header);
}
os.close();
if (m_log != null) {
m_log.logMessage("[Clusterer] Saved clusterer " + getCustomName());
}
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(Clusterer.this,
"Problem saving clusterer.\n", "Save Model", JOptionPane.ERROR_MESSAGE);
if (m_log != null) {
m_log.logMessage("[Clusterer] Problem saving clusterer. "
+ getCustomName() + ex.getMessage());
}
}
}
public void loadModel() {
try {
if (m_fileChooser == null) {
// i.e. after de-serialization
m_fileChooser = new JFileChooser(new File(
System.getProperty("user.dir")));
ExtensionFileFilter ef = new ExtensionFileFilter("model",
"Serialized weka clusterer");
m_fileChooser.setFileFilter(ef);
}
int returnVal = m_fileChooser.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File loadFrom = m_fileChooser.getSelectedFile();
ObjectInputStream is = new ObjectInputStream(new BufferedInputStream(
new FileInputStream(loadFrom)));
// try and read the model
weka.clusterers.Clusterer temp = (weka.clusterers.Clusterer) is
.readObject();
// Update name and icon
setClusterer(temp);
// try and read the header (if present)
try {
m_trainingSet = (Instances) is.readObject();
} catch (Exception ex) {
// quietly ignore
}
is.close();
if (m_log != null) {
m_log.logMessage("[Clusterer] Loaded clusterer: "
+ m_Clusterer.getClass().toString());
}
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(Clusterer.this,
"Problem loading classifier.\n", "Load Model",
JOptionPane.ERROR_MESSAGE);
if (m_log != null) {
m_log.logMessage("[Clusterer] Problem loading classifier. "
+ ex.getMessage());
}
}
}
/**
* Return an enumeration of requests that can be made by the user
*
* @return an <code>Enumeration</code> value
*/
@Override
public Enumeration<String> enumerateRequests() {
Vector<String> newVector = new Vector<String>(0);
if (m_buildThread != null) {
newVector.addElement("Stop");
}
if (m_buildThread == null && m_Clusterer != null) {
newVector.addElement("Save model");
}
if (m_buildThread == null) {
newVector.addElement("Load model");
}
return newVector.elements();
}
/**
* Perform a particular request
*
* @param request the request to perform
* @exception IllegalArgumentException if an error occurs
*/
@Override
public void performRequest(String request) {
if (request.compareTo("Stop") == 0) {
stop();
} else if (request.compareTo("Save model") == 0) {
saveModel();
} else if (request.compareTo("Load model") == 0) {
loadModel();
} else {
throw new IllegalArgumentException(request + " not supported (Clusterer)");
}
}
/**
* Returns true, if at the current time, the event described by the supplied
* event descriptor could be generated.
*
* @param esd an <code>EventSetDescriptor</code> value
* @return a <code>boolean</code> value
*/
public boolean eventGeneratable(EventSetDescriptor esd) {
String eventName = esd.getName();
return eventGeneratable(eventName);
}
/**
* Returns true, if at the current time, the named event could be generated.
* Assumes that the supplied event name is an event that could be generated by
* this bean
*
* @param eventName the name of the event in question
* @return true if the named event could be generated at this point in time
*/
@Override
public boolean eventGeneratable(String eventName) {
if (eventName.compareTo("graph") == 0) {
// can't generate a GraphEvent if clusterer is not drawable
if (!(m_Clusterer instanceof weka.core.Drawable)) {
return false;
}
// need to have a training set before the clusterer
// can generate a graph!
if (!m_listenees.containsKey("trainingSet")) {
return false;
}
// Source needs to be able to generate a trainingSet
// before we can generate a graph
Object source = m_listenees.get("trainingSet");
if (source instanceof EventConstraints) {
if (!((EventConstraints) source).eventGeneratable("trainingSet")) {
return false;
}
}
}
if (eventName.compareTo("batchClusterer") == 0) {
if (!m_listenees.containsKey("trainingSet")) {
return false;
}
Object source = m_listenees.get("trainingSet");
if (source != null && source instanceof EventConstraints) {
if (!((EventConstraints) source).eventGeneratable("trainingSet")) {
return false;
}
}
}
if (eventName.compareTo("text") == 0) {
if (!m_listenees.containsKey("trainingSet")) {
return false;
}
Object source = m_listenees.get("trainingSet");
if (source != null && source instanceof EventConstraints) {
if (!((EventConstraints) source).eventGeneratable("trainingSet")) {
return false;
}
}
}
if (eventName.compareTo("batchClassifier") == 0) {
return false;
}
if (eventName.compareTo("incrementalClassifier") == 0) {
return false;
}
return true;
}
private String statusMessagePrefix() {
return getCustomName()
+ "$"
+ hashCode()
+ "|"
+ ((m_Clusterer instanceof OptionHandler && Utils.joinOptions(
((OptionHandler) m_Clusterer).getOptions()).length() > 0) ? Utils
.joinOptions(((OptionHandler) m_Clusterer).getOptions()) + "|" : "");
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/ClustererBeanInfo.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/>.
*/
/*
* ClustererBeanInfo.java
* Copyright (C) 2004-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.beans.BeanDescriptor;
import java.beans.EventSetDescriptor;
import java.beans.SimpleBeanInfo;
/**
* BeanInfo class for the Clusterer wrapper bean
*
* @author <a href="mailto:mutter@cs.waikato.ac.nz">Stefan Mutter</a>
* @version $Revision$
*/
public class ClustererBeanInfo extends SimpleBeanInfo {
public EventSetDescriptor [] getEventSetDescriptors() {
try {
EventSetDescriptor [] esds = {
new EventSetDescriptor(Clusterer.class,
"batchClusterer",
BatchClustererListener.class,
"acceptClusterer"),
new EventSetDescriptor(Clusterer.class,
"graph",
GraphListener.class,
"acceptGraph"),
new EventSetDescriptor(Clusterer.class,
"text",
TextListener.class,
"acceptText"),
new EventSetDescriptor(Clusterer.class,
"configuration",
ConfigurationListener.class,
"acceptConfiguration")
};
return esds;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
/**
* Get the bean descriptor for this bean
*
* @return a <code>BeanDescriptor</code> value
*/
public BeanDescriptor getBeanDescriptor() {
return new BeanDescriptor(weka.gui.beans.Clusterer.class,
ClustererCustomizer.class);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/ClustererCustomizer.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/>.
*/
/*
* ClustererCustomizer.java
* Copyright (C) 2004-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import javax.swing.JButton;
import javax.swing.JPanel;
import weka.gui.GenericObjectEditor;
import weka.gui.PropertySheetPanel;
/**
* GUI customizer for the Clusterer wrapper bean
*
* @author <a href="mailto:mutter@cs.waikato.ac.nz">Stefan Mutter</a>
* @version $Revision$
*/
public class ClustererCustomizer
extends JPanel
implements BeanCustomizer, CustomizerCloseRequester {
/** for serialization */
private static final long serialVersionUID = -2035688458149534161L;
static {
GenericObjectEditor.registerEditors();
}
private PropertyChangeSupport m_pcSupport =
new PropertyChangeSupport(this);
private weka.gui.beans.Clusterer m_dsClusterer;
private PropertySheetPanel m_ClustererEditor =
new PropertySheetPanel();
private Window m_parentWindow;
/** Backup if the user presses cancel */
private weka.clusterers.Clusterer m_backup;
private ModifyListener m_modifyListener;
public ClustererCustomizer() {
setLayout(new BorderLayout());
add(m_ClustererEditor, BorderLayout.CENTER);
JPanel butHolder = new JPanel();
butHolder.setLayout(new GridLayout(1,2));
JButton OKBut = new JButton("OK");
OKBut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (m_modifyListener != null) {
m_modifyListener.setModifiedStatus(ClustererCustomizer.this, true);
}
m_parentWindow.dispose();
}
});
JButton CancelBut = new JButton("Cancel");
CancelBut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// cancel requested, so revert to backup and then
// close the dialog
if (m_backup != null) {
m_dsClusterer.setClusterer(m_backup);
}
if (m_modifyListener != null) {
m_modifyListener.setModifiedStatus(ClustererCustomizer.this, false);
}
m_parentWindow.dispose();
}
});
butHolder.add(OKBut);
butHolder.add(CancelBut);
add(butHolder, BorderLayout.SOUTH);
}
/**
* Set the Clusterer object to be edited
*
* @param object an <code>Object</code> value
*/
public void setObject(Object object) {
m_dsClusterer = (weka.gui.beans.Clusterer)object;
try {
m_backup =
(weka.clusterers.Clusterer)GenericObjectEditor.makeCopy(m_dsClusterer.getClusterer());
} catch (Exception ex) {
// ignore
}
m_ClustererEditor.setTarget(m_dsClusterer.getClusterer());
}
/**
* Add a property change listener
*
* @param pcl a <code>PropertyChangeListener</code> value
*/
public void addPropertyChangeListener(PropertyChangeListener pcl) {
m_pcSupport.addPropertyChangeListener(pcl);
}
/**
* Remove a property change listener
*
* @param pcl a <code>PropertyChangeListener</code> value
*/
public void removePropertyChangeListener(PropertyChangeListener pcl) {
m_pcSupport.removePropertyChangeListener(pcl);
}
public void setParentWindow(Window parent) {
m_parentWindow = parent;
}
@Override
public void setModifiedListener(ModifyListener l) {
m_modifyListener = l;
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/ClustererPerformanceEvaluator.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/>.
*/
/*
* ClustererPerformanceEvaluator.java
* Copyright (C) 2004-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.io.Serializable;
import java.util.Enumeration;
import java.util.Vector;
import weka.clusterers.ClusterEvaluation;
import weka.clusterers.Clusterer;
/**
* A bean that evaluates the performance of batch trained clusterers
*
* @author <a href="mailto:mutter@cs.waikato.ac.nz">Stefan Mutter</a>
* @version $Revision$
*/
public class ClustererPerformanceEvaluator extends AbstractEvaluator implements
BatchClustererListener, Serializable, UserRequestAcceptor, EventConstraints {
/** for serialization */
private static final long serialVersionUID = 8041163601333978584L;
/**
* Evaluation object used for evaluating a clusterer
*/
private transient ClusterEvaluation m_eval;
/**
* Holds the clusterer to be evaluated
*/
private transient Clusterer m_clusterer;
private transient Thread m_evaluateThread = null;
private final Vector<TextListener> m_textListeners = new Vector<TextListener>();
public ClustererPerformanceEvaluator() {
m_visual.loadIcons(BeanVisual.ICON_PATH
+ "ClustererPerformanceEvaluator.gif", BeanVisual.ICON_PATH
+ "ClustererPerformanceEvaluator_animated.gif");
m_visual.setText("ClustererPerformanceEvaluator");
}
/**
* Set a custom (descriptive) name for this bean
*
* @param name the name to use
*/
@Override
public void setCustomName(String name) {
m_visual.setText(name);
}
/**
* Get the custom (descriptive) name for this bean (if one has been set)
*
* @return the custom name (or the default name)
*/
@Override
public String getCustomName() {
return m_visual.getText();
}
/**
* Global info for this bean
*
* @return a <code>String</code> value
*/
public String globalInfo() {
return "Evaluate the performance of batch trained clusterers.";
}
/**
* Accept a clusterer to be evaluated
*
* @param ce a <code>BatchClustererEvent</code> value
*/
@Override
public void acceptClusterer(final BatchClustererEvent ce) {
if (ce.getTestSet().isStructureOnly()) {
return; // cant evaluate empty instances
}
try {
if (m_evaluateThread == null) {
m_evaluateThread = new Thread() {
@Override
@SuppressWarnings("deprecation")
public void run() {
boolean numericClass = false;
// final String oldText = m_visual.getText();
try {
if (ce.getSetNumber() == 1 /*
* || ce.getClusterer() != m_clusterer
*/) {
m_eval = new ClusterEvaluation();
m_clusterer = ce.getClusterer();
m_eval.setClusterer(m_clusterer);
}
if (ce.getSetNumber() <= ce.getMaxSetNumber()) {
// m_visual.setText("Evaluating ("+ce.getSetNumber()+")...");
if (m_logger != null) {
m_logger.statusMessage(statusMessagePrefix() + "Evaluating ("
+ ce.getSetNumber() + ")...");
}
m_visual.setAnimated();
if (ce.getTestSet().getDataSet().classIndex() != -1
&& ce.getTestSet().getDataSet().classAttribute().isNumeric()) {
numericClass = true;
ce.getTestSet().getDataSet().setClassIndex(-1);
}
m_eval.evaluateClusterer(ce.getTestSet().getDataSet());
}
if (ce.getSetNumber() == ce.getMaxSetNumber()) {
String textTitle = m_clusterer.getClass().getName();
textTitle = textTitle.substring(textTitle.lastIndexOf('.') + 1,
textTitle.length());
String test;
if (ce.getTestOrTrain() == 0) {
test = "test";
} else {
test = "training";
}
String resultT = "=== Evaluation result for " + test
+ " instances ===\n\n" + "Scheme: " + textTitle + "\n"
+ "Relation: " + ce.getTestSet().getDataSet().relationName()
+ "\n\n" + m_eval.clusterResultsToString();
if (numericClass) {
resultT = resultT
+ "\n\nNo class based evaluation possible. Class attribute has to be nominal.";
}
TextEvent te = new TextEvent(
ClustererPerformanceEvaluator.this, resultT, textTitle);
notifyTextListeners(te);
if (m_logger != null) {
m_logger.statusMessage(statusMessagePrefix() + "Finished.");
}
}
} catch (Exception ex) {
// stop all processing
ClustererPerformanceEvaluator.this.stop();
if (m_logger != null) {
m_logger.statusMessage(statusMessagePrefix()
+ "ERROR (see log for details");
m_logger.logMessage("[ClustererPerformanceEvaluator] "
+ statusMessagePrefix()
+ " problem while evaluating clusterer. " + ex.getMessage());
}
ex.printStackTrace();
} finally {
// m_visual.setText(oldText);
m_visual.setStatic();
m_evaluateThread = null;
if (isInterrupted()) {
if (m_logger != null) {
m_logger.logMessage("[" + getCustomName()
+ "] Evaluation interrupted!");
m_logger.statusMessage(statusMessagePrefix() + "INTERRUPTED");
}
}
block(false);
}
}
};
m_evaluateThread.setPriority(Thread.MIN_PRIORITY);
m_evaluateThread.start();
// make sure the thread is still running before we block
// if (m_evaluateThread.isAlive()) {
block(true);
// }
m_evaluateThread = null;
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* Returns true if. at this time, the bean is busy with some (i.e. perhaps a
* worker thread is performing some calculation).
*
* @return true if the bean is busy.
*/
@Override
public boolean isBusy() {
return (m_evaluateThread != null);
}
/**
* Try and stop any action
*/
@Override
@SuppressWarnings("deprecation")
public void stop() {
// tell the listenee (upstream bean) to stop
if (m_listenee instanceof BeanCommon) {
// System.err.println("Listener is BeanCommon");
((BeanCommon) m_listenee).stop();
}
// stop the evaluate thread
if (m_evaluateThread != null) {
m_evaluateThread.interrupt();
m_evaluateThread.stop();
m_evaluateThread = null;
m_visual.setStatic();
}
}
/**
* Function used to stop code that calls acceptClusterer. This is needed as
* clusterer evaluation is performed inside a separate thread of execution.
*
* @param tf a <code>boolean</code> value
*/
private synchronized void block(boolean tf) {
if (tf) {
try {
// only block if thread is still doing something useful!
if (m_evaluateThread != null && m_evaluateThread.isAlive()) {
wait();
}
} catch (InterruptedException ex) {
}
} else {
notifyAll();
}
}
/**
* Return an enumeration of user activated requests for this bean
*
* @return an <code>Enumeration</code> value
*/
@Override
public Enumeration<String> enumerateRequests() {
Vector<String> newVector = new Vector<String>(0);
if (m_evaluateThread != null) {
newVector.addElement("Stop");
}
return newVector.elements();
}
/**
* Perform the named request
*
* @param request the request to perform
* @exception IllegalArgumentException if an error occurs
*/
@Override
public void performRequest(String request) {
if (request.compareTo("Stop") == 0) {
stop();
} else {
throw new IllegalArgumentException(request
+ " not supported (ClustererPerformanceEvaluator)");
}
}
/**
* Add a text listener
*
* @param cl a <code>TextListener</code> value
*/
public synchronized void addTextListener(TextListener cl) {
m_textListeners.addElement(cl);
}
/**
* Remove a text listener
*
* @param cl a <code>TextListener</code> value
*/
public synchronized void removeTextListener(TextListener cl) {
m_textListeners.remove(cl);
}
/**
* Notify all text listeners of a TextEvent
*
* @param te a <code>TextEvent</code> value
*/
@SuppressWarnings("unchecked")
private void notifyTextListeners(TextEvent te) {
Vector<TextListener> l;
synchronized (this) {
l = (Vector<TextListener>) m_textListeners.clone();
}
if (l.size() > 0) {
for (int i = 0; i < l.size(); i++) {
// System.err.println("Notifying text listeners "
// +"(ClustererPerformanceEvaluator)");
l.elementAt(i).acceptText(te);
}
}
}
/**
* Returns true, if at the current time, the named event could be generated.
* Assumes that supplied event names are names of events that could be
* generated by this bean.
*
* @param eventName the name of the event in question
* @return true if the named event could be generated at this point in time
*/
@Override
public boolean eventGeneratable(String eventName) {
if (m_listenee == null) {
return false;
}
if (m_listenee instanceof EventConstraints) {
if (!((EventConstraints) m_listenee).eventGeneratable("batchClusterer")) {
return false;
}
}
return true;
}
private String statusMessagePrefix() {
return getCustomName() + "$" + hashCode() + "|";
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/ClustererPerformanceEvaluatorBeanInfo.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/>.
*/
/*
* ClustererPerformanceEvaluatorBeanInfo.java
* Copyright (C) 2004-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.beans.EventSetDescriptor;
import java.beans.SimpleBeanInfo;
/**
* Bean info class for the clusterer performance evaluator
*
* @author <a href="mailto:mutter@cs.waikato.ac.nz">Stefan Mutter</a>
* @version $Revision$
*/
public class ClustererPerformanceEvaluatorBeanInfo extends SimpleBeanInfo {
public EventSetDescriptor [] getEventSetDescriptors() {
try {
EventSetDescriptor [] esds = {
new EventSetDescriptor(ClustererPerformanceEvaluator.class,
"text",
TextListener.class,
"acceptText")};
return esds;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/ConfigurationEvent.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/>.
*/
/*
* ConfigurationEvent.java
* Copyright (C) 2009-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.util.EventObject;
/**
* Matching event for ConfigurationListener. Implementers of
* ConfigurationProducer do not actually have to generate this
* event (nor will listeners ever need to process ConfigurationEvent).
* Configurations will be pulled (rather than pushed) by
* ConfigurationListeners. It is a listener's responsibility (if
* they are interested in utilizing configurations) to implement
* BeanCommon and store/delete reference(s) to ConfigurationProducers
* when connectionNotification() and disconnectionNotification() are
* called on them.
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}org)
* @version $Revision $
*/
public class ConfigurationEvent extends EventObject {
/** For serialization */
private static final long serialVersionUID = 5433562112093780868L;
public ConfigurationEvent(Object source) {
super(source);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/ConfigurationListener.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/>.
*/
/*
* ConfigurationListener.java
* Copyright (C) 2009-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
/**
* Matching listener for ConfigurationEvent. Implementers of
* ConfigurationProducer do not actually have to generate the
* event (nor will listeners ever need to process ConfigurationEvent).
* Configurations will be pulled (rather than pushed) by
* ConfigurationListeners. It is a listener's responsibility (if
* they are interested in utilizing configurations) to implement
* BeanCommon and store/delete reference(s) to ConfigurationProducers
* when connectionNotification() and disconnectionNotification() are
* called on them.
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}org)
* @version $Revision $
*/
public interface ConfigurationListener {
/**
* Implementers do not have to do anything in this
* method (see the above documentation).
*
* @param e a ConfigurationEvent
*/
void acceptConfiguration(ConfigurationEvent e);
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/ConfigurationProducer.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/>.
*/
/*
* ConfigurationProducer.java
* Copyright (C) 2009-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
/**
* Marker interface for components that can share their configuration.
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}org)
* @version $Revision $
*/
public interface ConfigurationProducer {
/**
* We don't have to keep track of configuration listeners (see the
* documentation for ConfigurationListener/ConfigurationEvent).
*
* @param cl a ConfigurationListener.
*/
void addConfigurationListener(ConfigurationListener cl);
/**
* We don't have to keep track of configuration listeners (see the
* documentation for ConfigurationListener/ConfigurationEvent).
*
* @param cl a ConfigurationListener.
*/
void removeConfigurationListener(ConfigurationListener cl);
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/ConnectionNotificationConsumer.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/>.
*/
/*
* ConnectionNotificationConsumer.java
* Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand
*/
package weka.gui.beans;
/**
* Interface for Beans that can receive (dis-)connection events generated when
* (dis-)connecting data processing nodes in the Weka KnowledgeFlow.
*
* This is useful, for example, for "intelligent" filters that are able to share
* configuration information with preceding nodes in the processing chain.
*
* @author Carsten Pohle (cp AT cpohle de)
* @version $Revision$
*/
public interface ConnectionNotificationConsumer {
/**
* Notify this object that it has been registered as a listener with a source
* with respect to the supplied event name.
*
* This method should be implemented <emph>synchronized</emph>.
*
* @param eventName
* @param source
* the source with which this object has been registered as a
* listener
*/
public void connectionNotification(String eventName, Object source);
/**
* Notify this object that it has been deregistered as a listener with a
* source with respect to the supplied event name
*
* This method should be implemented <emph>synchronized</emph>.
*
* @param eventName
* the event
* @param source
* the source with which this object has been registered as a
* listener
*/
public void disconnectionNotification(String eventName, Object source);
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/CostBenefitAnalysis.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/>.
*/
/*
* CostBenefitAnalysis.java
* Copyright (C) 2009-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.GraphicsEnvironment;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.beans.EventSetDescriptor;
import java.beans.PropertyVetoException;
import java.beans.VetoableChangeListener;
import java.beans.beancontext.BeanContext;
import java.beans.beancontext.BeanContextChild;
import java.beans.beancontext.BeanContextChildSupport;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.EventObject;
import java.util.List;
import java.util.Vector;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JSlider;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import weka.classifiers.evaluation.Prediction;
import weka.classifiers.evaluation.ThresholdCurve;
import weka.core.Attribute;
import weka.core.DenseInstance;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.Utils;
import weka.gui.Logger;
import weka.gui.visualize.PlotData2D;
import weka.gui.visualize.VisualizePanel;
/**
* Bean that aids in analyzing cost/benefit tradeoffs.
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision$
*/
@KFStep(category = "Visualize", toolTipText = "Interactive cost/benefit analysis")
public class CostBenefitAnalysis extends JPanel implements BeanCommon,
ThresholdDataListener, Visible, UserRequestAcceptor, Serializable,
BeanContextChild, HeadlessEventCollector {
/** For serialization */
private static final long serialVersionUID = 8647471654613320469L;
protected BeanVisual m_visual = new BeanVisual("CostBenefitAnalysis",
BeanVisual.ICON_PATH + "ModelPerformanceChart.gif", BeanVisual.ICON_PATH
+ "ModelPerformanceChart_animated.gif");
protected transient JFrame m_popupFrame;
protected boolean m_framePoppedUp = false;
private transient AnalysisPanel m_analysisPanel;
/**
* True if this bean's appearance is the design mode appearance
*/
protected boolean m_design;
/**
* BeanContex that this bean might be contained within
*/
protected transient BeanContext m_beanContext = null;
/**
* BeanContextChild support
*/
protected BeanContextChildSupport m_bcSupport = new BeanContextChildSupport(
this);
/**
* The object sending us data (we allow only one connection at any one time)
*/
protected Object m_listenee;
protected List<EventObject> m_headlessEvents;
/**
* Inner class for displaying the plots and all control widgets.
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
*/
protected static class AnalysisPanel extends JPanel {
/** For serialization */
private static final long serialVersionUID = 5364871945448769003L;
/** Displays the performance graphs(s) */
protected VisualizePanel m_performancePanel = new VisualizePanel();
/** Displays the cost/benefit (profit/loss) graph */
protected VisualizePanel m_costBenefitPanel = new VisualizePanel();
/**
* The class attribute from the data that was used to generate the threshold
* curve
*/
protected Attribute m_classAttribute;
/** Data for the threshold curve */
protected PlotData2D m_masterPlot;
/** Data for the cost/benefit curve */
protected PlotData2D m_costBenefit;
/** The size of the points being plotted */
protected int[] m_shapeSizes;
/** The index of the previous plotted point that was highlighted */
protected int m_previousShapeIndex = -1;
/** The slider for adjusting the threshold */
protected JSlider m_thresholdSlider = new JSlider(0, 100, 0);
protected JRadioButton m_percPop = new JRadioButton("% of Population");
protected JRadioButton m_percOfTarget = new JRadioButton(
"% of Target (recall)");
protected JRadioButton m_threshold = new JRadioButton("Score Threshold");
protected JLabel m_percPopLab = new JLabel();
protected JLabel m_percOfTargetLab = new JLabel();
protected JLabel m_thresholdLab = new JLabel();
// Confusion matrix stuff
protected JLabel m_conf_predictedA = new JLabel("Predicted (a)",
SwingConstants.RIGHT);
protected JLabel m_conf_predictedB = new JLabel("Predicted (b)",
SwingConstants.RIGHT);
protected JLabel m_conf_actualA = new JLabel(" Actual (a):");
protected JLabel m_conf_actualB = new JLabel(" Actual (b):");
protected ConfusionCell m_conf_aa = new ConfusionCell();
protected ConfusionCell m_conf_ab = new ConfusionCell();
protected ConfusionCell m_conf_ba = new ConfusionCell();
protected ConfusionCell m_conf_bb = new ConfusionCell();
// Cost matrix stuff
protected JLabel m_cost_predictedA = new JLabel("Predicted (a)",
SwingConstants.RIGHT);
protected JLabel m_cost_predictedB = new JLabel("Predicted (b)",
SwingConstants.RIGHT);
protected JLabel m_cost_actualA = new JLabel(" Actual (a)");
protected JLabel m_cost_actualB = new JLabel(" Actual (b)");
protected JTextField m_cost_aa = new JTextField("0.0", 5);
protected JTextField m_cost_ab = new JTextField("1.0", 5);
protected JTextField m_cost_ba = new JTextField("1.0", 5);
protected JTextField m_cost_bb = new JTextField("0.0", 5);
protected JButton m_maximizeCB = new JButton("Maximize Cost/Benefit");
protected JButton m_minimizeCB = new JButton("Minimize Cost/Benefit");
protected JRadioButton m_costR = new JRadioButton("Cost");
protected JRadioButton m_benefitR = new JRadioButton("Benefit");
protected JLabel m_costBenefitL = new JLabel("Cost: ", SwingConstants.RIGHT);
protected JLabel m_costBenefitV = new JLabel("0");
protected JLabel m_randomV = new JLabel("0");
protected JLabel m_gainV = new JLabel("0");
protected int m_originalPopSize;
/** Population text field */
protected JTextField m_totalPopField = new JTextField(6);
protected int m_totalPopPrevious;
/** Classification accuracy */
protected JLabel m_classificationAccV = new JLabel("-");
// Only update curve & stats if values in cost matrix have changed
protected double m_tpPrevious;
protected double m_fpPrevious;
protected double m_tnPrevious;
protected double m_fnPrevious;
/**
* Inner class for handling a single cell in the confusion matrix. Displays
* the value, value as a percentage of total population and graphical
* depiction of percentage.
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
*/
protected static class ConfusionCell extends JPanel {
/** For serialization */
private static final long serialVersionUID = 6148640235434494767L;
private final JLabel m_conf_cell = new JLabel("-", SwingConstants.RIGHT);
JLabel m_conf_perc = new JLabel("-", SwingConstants.RIGHT);
private final JPanel m_percentageP;
protected double m_percentage = 0;
@SuppressWarnings("serial")
public ConfusionCell() {
setLayout(new BorderLayout());
setBorder(BorderFactory.createEtchedBorder());
add(m_conf_cell, BorderLayout.NORTH);
m_percentageP = new JPanel() {
@Override
public void paintComponent(Graphics gx) {
super.paintComponent(gx);
if (m_percentage > 0) {
gx.setColor(Color.BLUE);
int height = this.getHeight();
double width = this.getWidth();
int barWidth = (int) (m_percentage * width);
gx.fillRect(0, 0, barWidth, height);
}
}
};
Dimension d = new Dimension(30, 5);
m_percentageP.setMinimumSize(d);
m_percentageP.setPreferredSize(d);
JPanel percHolder = new JPanel();
percHolder.setLayout(new BorderLayout());
percHolder.add(m_percentageP, BorderLayout.CENTER);
percHolder.add(m_conf_perc, BorderLayout.EAST);
add(percHolder, BorderLayout.SOUTH);
}
/**
* Set the value of a cell.
*
* @param cellValue the value of the cell
* @param max the max (for setting value as a percentage)
* @param scaleFactor scale the value by this amount
* @param precision precision for the percentage value
*/
public void setCellValue(double cellValue, double max,
double scaleFactor, int precision) {
if (!Utils.isMissingValue(cellValue)) {
m_percentage = cellValue / max;
} else {
m_percentage = 0;
}
m_conf_cell.setText(Utils.doubleToString((cellValue * scaleFactor), 0));
m_conf_perc.setText(Utils.doubleToString(m_percentage * 100.0,
precision) + "%");
// refresh the percentage bar
m_percentageP.repaint();
}
}
public AnalysisPanel() {
setLayout(new BorderLayout());
m_performancePanel.setShowAttBars(false);
m_performancePanel.setShowClassPanel(false);
m_costBenefitPanel.setShowAttBars(false);
m_costBenefitPanel.setShowClassPanel(false);
Dimension size = new Dimension(500, 400);
m_performancePanel.setPreferredSize(size);
m_performancePanel.setMinimumSize(size);
size = new Dimension(500, 400);
m_costBenefitPanel.setMinimumSize(size);
m_costBenefitPanel.setPreferredSize(size);
m_thresholdSlider.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
updateInfoForSliderValue(m_thresholdSlider.getValue() / 100.0);
}
});
JPanel plotHolder = new JPanel();
plotHolder.setLayout(new GridLayout(1, 2));
plotHolder.add(m_performancePanel);
plotHolder.add(m_costBenefitPanel);
add(plotHolder, BorderLayout.CENTER);
JPanel lowerPanel = new JPanel();
lowerPanel.setLayout(new BorderLayout());
ButtonGroup bGroup = new ButtonGroup();
bGroup.add(m_percPop);
bGroup.add(m_percOfTarget);
bGroup.add(m_threshold);
ButtonGroup bGroup2 = new ButtonGroup();
bGroup2.add(m_costR);
bGroup2.add(m_benefitR);
ActionListener rl = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (m_costR.isSelected()) {
m_costBenefitL.setText("Cost: ");
} else {
m_costBenefitL.setText("Benefit: ");
}
double gain = Double.parseDouble(m_gainV.getText());
gain = -gain;
m_gainV.setText(Utils.doubleToString(gain, 2));
}
};
m_costR.addActionListener(rl);
m_benefitR.addActionListener(rl);
m_costR.setSelected(true);
m_percPop.setSelected(true);
JPanel threshPanel = new JPanel();
threshPanel.setLayout(new BorderLayout());
JPanel radioHolder = new JPanel();
radioHolder.setLayout(new FlowLayout());
radioHolder.add(m_percPop);
radioHolder.add(m_percOfTarget);
radioHolder.add(m_threshold);
threshPanel.add(radioHolder, BorderLayout.NORTH);
threshPanel.add(m_thresholdSlider, BorderLayout.SOUTH);
JPanel threshInfoPanel = new JPanel();
threshInfoPanel.setLayout(new GridLayout(3, 2));
threshInfoPanel
.add(new JLabel("% of Population: ", SwingConstants.RIGHT));
threshInfoPanel.add(m_percPopLab);
threshInfoPanel.add(new JLabel("% of Target: ", SwingConstants.RIGHT));
threshInfoPanel.add(m_percOfTargetLab);
threshInfoPanel
.add(new JLabel("Score Threshold: ", SwingConstants.RIGHT));
threshInfoPanel.add(m_thresholdLab);
JPanel threshHolder = new JPanel();
threshHolder.setBorder(BorderFactory.createTitledBorder("Threshold"));
threshHolder.setLayout(new BorderLayout());
threshHolder.add(threshPanel, BorderLayout.CENTER);
threshHolder.add(threshInfoPanel, BorderLayout.EAST);
lowerPanel.add(threshHolder, BorderLayout.NORTH);
// holder for the two matrixes
JPanel matrixHolder = new JPanel();
matrixHolder.setLayout(new GridLayout(1, 2));
// confusion matrix
JPanel confusionPanel = new JPanel();
confusionPanel.setLayout(new GridLayout(3, 3));
confusionPanel.add(m_conf_predictedA);
confusionPanel.add(m_conf_predictedB);
confusionPanel.add(new JLabel()); // dummy
confusionPanel.add(m_conf_aa);
confusionPanel.add(m_conf_ab);
confusionPanel.add(m_conf_actualA);
confusionPanel.add(m_conf_ba);
confusionPanel.add(m_conf_bb);
confusionPanel.add(m_conf_actualB);
JPanel tempHolderCA = new JPanel();
tempHolderCA.setLayout(new BorderLayout());
tempHolderCA.setBorder(BorderFactory
.createTitledBorder("Confusion Matrix"));
tempHolderCA.add(confusionPanel, BorderLayout.CENTER);
JPanel accHolder = new JPanel();
accHolder.setLayout(new FlowLayout(FlowLayout.LEFT));
accHolder.add(new JLabel("Classification Accuracy: "));
accHolder.add(m_classificationAccV);
tempHolderCA.add(accHolder, BorderLayout.SOUTH);
matrixHolder.add(tempHolderCA);
// cost matrix
JPanel costPanel = new JPanel();
costPanel.setBorder(BorderFactory.createTitledBorder("Cost Matrix"));
costPanel.setLayout(new BorderLayout());
JPanel cmHolder = new JPanel();
cmHolder.setLayout(new GridLayout(3, 3));
cmHolder.add(m_cost_predictedA);
cmHolder.add(m_cost_predictedB);
cmHolder.add(new JLabel()); // dummy
cmHolder.add(m_cost_aa);
cmHolder.add(m_cost_ab);
cmHolder.add(m_cost_actualA);
cmHolder.add(m_cost_ba);
cmHolder.add(m_cost_bb);
cmHolder.add(m_cost_actualB);
costPanel.add(cmHolder, BorderLayout.CENTER);
FocusListener fl = new FocusListener() {
@Override
public void focusGained(FocusEvent e) {
}
@Override
public void focusLost(FocusEvent e) {
if (constructCostBenefitData()) {
try {
m_costBenefitPanel.setMasterPlot(m_costBenefit);
m_costBenefitPanel.validate();
m_costBenefitPanel.repaint();
} catch (Exception ex) {
ex.printStackTrace();
}
updateCostBenefit();
}
}
};
ActionListener al = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (constructCostBenefitData()) {
try {
m_costBenefitPanel.setMasterPlot(m_costBenefit);
m_costBenefitPanel.validate();
m_costBenefitPanel.repaint();
} catch (Exception ex) {
ex.printStackTrace();
}
updateCostBenefit();
}
}
};
m_cost_aa.addFocusListener(fl);
m_cost_aa.addActionListener(al);
m_cost_ab.addFocusListener(fl);
m_cost_ab.addActionListener(al);
m_cost_ba.addFocusListener(fl);
m_cost_ba.addActionListener(al);
m_cost_bb.addFocusListener(fl);
m_cost_bb.addActionListener(al);
m_totalPopField.addFocusListener(fl);
m_totalPopField.addActionListener(al);
JPanel cbHolder = new JPanel();
cbHolder.setLayout(new BorderLayout());
JPanel tempP = new JPanel();
tempP.setLayout(new GridLayout(3, 2));
tempP.add(m_costBenefitL);
tempP.add(m_costBenefitV);
tempP.add(new JLabel("Random: ", SwingConstants.RIGHT));
tempP.add(m_randomV);
tempP.add(new JLabel("Gain: ", SwingConstants.RIGHT));
tempP.add(m_gainV);
cbHolder.add(tempP, BorderLayout.NORTH);
JPanel butHolder = new JPanel();
butHolder.setLayout(new GridLayout(2, 1));
butHolder.add(m_maximizeCB);
butHolder.add(m_minimizeCB);
m_maximizeCB.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
findMaxMinCB(true);
}
});
m_minimizeCB.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
findMaxMinCB(false);
}
});
cbHolder.add(butHolder, BorderLayout.SOUTH);
costPanel.add(cbHolder, BorderLayout.EAST);
JPanel popCBR = new JPanel();
popCBR.setLayout(new GridLayout(1, 2));
JPanel popHolder = new JPanel();
popHolder.setLayout(new FlowLayout(FlowLayout.LEFT));
popHolder.add(new JLabel("Total Population: "));
popHolder.add(m_totalPopField);
JPanel radioHolder2 = new JPanel();
radioHolder2.setLayout(new FlowLayout(FlowLayout.RIGHT));
radioHolder2.add(m_costR);
radioHolder2.add(m_benefitR);
popCBR.add(popHolder);
popCBR.add(radioHolder2);
costPanel.add(popCBR, BorderLayout.SOUTH);
matrixHolder.add(costPanel);
lowerPanel.add(matrixHolder, BorderLayout.SOUTH);
// popAccHolder.add(popHolder);
// popAccHolder.add(accHolder);
/*
* JPanel lowerPanel2 = new JPanel(); lowerPanel2.setLayout(new
* BorderLayout()); lowerPanel2.add(lowerPanel, BorderLayout.NORTH);
* lowerPanel2.add(popAccHolder, BorderLayout.SOUTH);
*/
add(lowerPanel, BorderLayout.SOUTH);
}
private void findMaxMinCB(boolean max) {
double maxMin = (max) ? Double.NEGATIVE_INFINITY
: Double.POSITIVE_INFINITY;
Instances cBCurve = m_costBenefit.getPlotInstances();
int maxMinIndex = 0;
for (int i = 0; i < cBCurve.numInstances(); i++) {
Instance current = cBCurve.instance(i);
if (max) {
if (current.value(1) > maxMin) {
maxMin = current.value(1);
maxMinIndex = i;
}
} else {
if (current.value(1) < maxMin) {
maxMin = current.value(1);
maxMinIndex = i;
}
}
}
// set the slider to the correct position
int indexOfSampleSize = m_masterPlot.getPlotInstances()
.attribute(ThresholdCurve.SAMPLE_SIZE_NAME).index();
int indexOfPercOfTarget = m_masterPlot.getPlotInstances()
.attribute(ThresholdCurve.RECALL_NAME).index();
int indexOfThreshold = m_masterPlot.getPlotInstances()
.attribute(ThresholdCurve.THRESHOLD_NAME).index();
int indexOfMetric;
if (m_percPop.isSelected()) {
indexOfMetric = indexOfSampleSize;
} else if (m_percOfTarget.isSelected()) {
indexOfMetric = indexOfPercOfTarget;
} else {
indexOfMetric = indexOfThreshold;
}
double valueOfMetric = m_masterPlot.getPlotInstances()
.instance(maxMinIndex).value(indexOfMetric);
valueOfMetric *= 100.0;
// set the approximate location of the slider
m_thresholdSlider.setValue((int) valueOfMetric);
// make sure the actual values relate to the true min/max rather
// than being off due to slider location error.
updateInfoGivenIndex(maxMinIndex);
}
private void updateCostBenefit() {
double value = m_thresholdSlider.getValue() / 100.0;
Instances plotInstances = m_masterPlot.getPlotInstances();
int indexOfSampleSize = m_masterPlot.getPlotInstances()
.attribute(ThresholdCurve.SAMPLE_SIZE_NAME).index();
int indexOfPercOfTarget = m_masterPlot.getPlotInstances()
.attribute(ThresholdCurve.RECALL_NAME).index();
int indexOfThreshold = m_masterPlot.getPlotInstances()
.attribute(ThresholdCurve.THRESHOLD_NAME).index();
int indexOfMetric;
if (m_percPop.isSelected()) {
indexOfMetric = indexOfSampleSize;
} else if (m_percOfTarget.isSelected()) {
indexOfMetric = indexOfPercOfTarget;
} else {
indexOfMetric = indexOfThreshold;
}
int index = findIndexForValue(value, plotInstances, indexOfMetric);
updateCBRandomGainInfo(index);
}
private void updateCBRandomGainInfo(int index) {
double requestedPopSize = m_originalPopSize;
try {
requestedPopSize = Double.parseDouble(m_totalPopField.getText());
} catch (NumberFormatException e) {
}
double scaleFactor = requestedPopSize / m_originalPopSize;
double CB = m_costBenefit.getPlotInstances().instance(index).value(1);
m_costBenefitV.setText(Utils.doubleToString(CB, 2));
double totalRandomCB = 0.0;
Instance first = m_masterPlot.getPlotInstances().instance(0);
double totalPos = first.value(m_masterPlot.getPlotInstances()
.attribute(ThresholdCurve.TRUE_POS_NAME).index())
* scaleFactor;
double totalNeg = first.value(m_masterPlot.getPlotInstances().attribute(
ThresholdCurve.FALSE_POS_NAME))
* scaleFactor;
double posInSample = (totalPos * (Double.parseDouble(m_percPopLab
.getText()) / 100.0));
double negInSample = (totalNeg * (Double.parseDouble(m_percPopLab
.getText()) / 100.0));
double posOutSample = totalPos - posInSample;
double negOutSample = totalNeg - negInSample;
double tpCost = 0.0;
try {
tpCost = Double.parseDouble(m_cost_aa.getText());
} catch (NumberFormatException n) {
}
double fpCost = 0.0;
try {
fpCost = Double.parseDouble(m_cost_ba.getText());
} catch (NumberFormatException n) {
}
double tnCost = 0.0;
try {
tnCost = Double.parseDouble(m_cost_bb.getText());
} catch (NumberFormatException n) {
}
double fnCost = 0.0;
try {
fnCost = Double.parseDouble(m_cost_ab.getText());
} catch (NumberFormatException n) {
}
totalRandomCB += posInSample * tpCost;
totalRandomCB += negInSample * fpCost;
totalRandomCB += posOutSample * fnCost;
totalRandomCB += negOutSample * tnCost;
m_randomV.setText(Utils.doubleToString(totalRandomCB, 2));
double gain = (m_costR.isSelected()) ? totalRandomCB - CB : CB
- totalRandomCB;
m_gainV.setText(Utils.doubleToString(gain, 2));
// update classification rate
Instance currentInst = m_masterPlot.getPlotInstances().instance(index);
double tp = currentInst.value(m_masterPlot.getPlotInstances()
.attribute(ThresholdCurve.TRUE_POS_NAME).index());
double tn = currentInst.value(m_masterPlot.getPlotInstances()
.attribute(ThresholdCurve.TRUE_NEG_NAME).index());
m_classificationAccV.setText(Utils.doubleToString((tp + tn)
/ (totalPos + totalNeg) * 100.0, 4)
+ "%");
}
private void updateInfoGivenIndex(int index) {
Instances plotInstances = m_masterPlot.getPlotInstances();
int indexOfSampleSize = m_masterPlot.getPlotInstances()
.attribute(ThresholdCurve.SAMPLE_SIZE_NAME).index();
int indexOfPercOfTarget = m_masterPlot.getPlotInstances()
.attribute(ThresholdCurve.RECALL_NAME).index();
int indexOfThreshold = m_masterPlot.getPlotInstances()
.attribute(ThresholdCurve.THRESHOLD_NAME).index();
// update labels
m_percPopLab.setText(Utils.doubleToString(
100.0 * plotInstances.instance(index).value(indexOfSampleSize), 4));
m_percOfTargetLab.setText(Utils.doubleToString(100.0 * plotInstances
.instance(index).value(indexOfPercOfTarget), 4));
m_thresholdLab.setText(Utils.doubleToString(plotInstances.instance(index)
.value(indexOfThreshold), 4));
/*
* if (m_percPop.isSelected()) {
* m_percPopLab.setText(Utils.doubleToString(100.0 * value, 4)); } else if
* (m_percOfTarget.isSelected()) {
* m_percOfTargetLab.setText(Utils.doubleToString(100.0 * value, 4)); }
* else { m_thresholdLab.setText(Utils.doubleToString(value, 4)); }
*/
// Update the highlighted point on the graphs */
if (m_previousShapeIndex >= 0) {
m_shapeSizes[m_previousShapeIndex] = 1;
}
m_shapeSizes[index] = 10;
m_previousShapeIndex = index;
// Update the confusion matrix
// double totalInstances =
int tp = plotInstances.attribute(ThresholdCurve.TRUE_POS_NAME).index();
int fp = plotInstances.attribute(ThresholdCurve.FALSE_POS_NAME).index();
int tn = plotInstances.attribute(ThresholdCurve.TRUE_NEG_NAME).index();
int fn = plotInstances.attribute(ThresholdCurve.FALSE_NEG_NAME).index();
Instance temp = plotInstances.instance(index);
double totalInstances = temp.value(tp) + temp.value(fp) + temp.value(tn)
+ temp.value(fn);
// get the value out of the total pop field (if possible)
double requestedPopSize = totalInstances;
try {
requestedPopSize = Double.parseDouble(m_totalPopField.getText());
} catch (NumberFormatException e) {
}
m_conf_aa.setCellValue(temp.value(tp), totalInstances, requestedPopSize
/ totalInstances, 2);
m_conf_ab.setCellValue(temp.value(fn), totalInstances, requestedPopSize
/ totalInstances, 2);
m_conf_ba.setCellValue(temp.value(fp), totalInstances, requestedPopSize
/ totalInstances, 2);
m_conf_bb.setCellValue(temp.value(tn), totalInstances, requestedPopSize
/ totalInstances, 2);
updateCBRandomGainInfo(index);
repaint();
}
private void updateInfoForSliderValue(double value) {
int indexOfSampleSize = m_masterPlot.getPlotInstances()
.attribute(ThresholdCurve.SAMPLE_SIZE_NAME).index();
int indexOfPercOfTarget = m_masterPlot.getPlotInstances()
.attribute(ThresholdCurve.RECALL_NAME).index();
int indexOfThreshold = m_masterPlot.getPlotInstances()
.attribute(ThresholdCurve.THRESHOLD_NAME).index();
int indexOfMetric;
if (m_percPop.isSelected()) {
indexOfMetric = indexOfSampleSize;
} else if (m_percOfTarget.isSelected()) {
indexOfMetric = indexOfPercOfTarget;
} else {
indexOfMetric = indexOfThreshold;
}
Instances plotInstances = m_masterPlot.getPlotInstances();
int index = findIndexForValue(value, plotInstances, indexOfMetric);
updateInfoGivenIndex(index);
}
private int findIndexForValue(double value, Instances plotInstances,
int indexOfMetric) {
// binary search
// threshold curve is sorted ascending in the threshold (thus
// descending for recall and pop size)
int index = -1;
int lower = 0;
int upper = plotInstances.numInstances() - 1;
int mid = (upper - lower) / 2;
boolean done = false;
while (!done) {
if (upper - lower <= 1) {
// choose the one closest to the value
double comp1 = plotInstances.instance(upper).value(indexOfMetric);
double comp2 = plotInstances.instance(lower).value(indexOfMetric);
if (Math.abs(comp1 - value) < Math.abs(comp2 - value)) {
index = upper;
} else {
index = lower;
}
break;
}
double comparisonVal = plotInstances.instance(mid).value(indexOfMetric);
if (value > comparisonVal) {
if (m_threshold.isSelected()) {
lower = mid;
mid += (upper - lower) / 2;
} else {
upper = mid;
mid -= (upper - lower) / 2;
}
} else if (value < comparisonVal) {
if (m_threshold.isSelected()) {
upper = mid;
mid -= (upper - lower) / 2;
} else {
lower = mid;
mid += (upper - lower) / 2;
}
} else {
index = mid;
done = true;
}
}
// now check for ties in the appropriate direction
if (!m_threshold.isSelected()) {
while (index + 1 < plotInstances.numInstances()) {
if (plotInstances.instance(index + 1).value(indexOfMetric) == plotInstances
.instance(index).value(indexOfMetric)) {
index++;
} else {
break;
}
}
} else {
while (index - 1 >= 0) {
if (plotInstances.instance(index - 1).value(indexOfMetric) == plotInstances
.instance(index).value(indexOfMetric)) {
index--;
} else {
break;
}
}
}
return index;
}
/**
* Set the threshold data for the panel to use.
*
* @param data PlotData2D object encapsulating the threshold data.
* @param classAtt the class attribute from the original data used to
* generate the threshold data.
* @throws Exception if something goes wrong.
*/
public synchronized void setDataSet(PlotData2D data, Attribute classAtt)
throws Exception {
// make a copy of the PlotData2D object
m_masterPlot = new PlotData2D(data.getPlotInstances());
boolean[] connectPoints = new boolean[m_masterPlot.getPlotInstances()
.numInstances()];
for (int i = 1; i < connectPoints.length; i++) {
connectPoints[i] = true;
}
m_masterPlot.setConnectPoints(connectPoints);
m_masterPlot.m_alwaysDisplayPointsOfThisSize = 10;
setClassForConfusionMatrix(classAtt);
m_performancePanel.setMasterPlot(m_masterPlot);
m_performancePanel.validate();
m_performancePanel.repaint();
m_shapeSizes = new int[m_masterPlot.getPlotInstances().numInstances()];
for (int i = 0; i < m_shapeSizes.length; i++) {
m_shapeSizes[i] = 1;
}
m_masterPlot.setShapeSize(m_shapeSizes);
constructCostBenefitData();
m_costBenefitPanel.setMasterPlot(m_costBenefit);
m_costBenefitPanel.validate();
m_costBenefitPanel.repaint();
m_totalPopPrevious = 0;
m_fpPrevious = 0;
m_tpPrevious = 0;
m_tnPrevious = 0;
m_fnPrevious = 0;
m_previousShapeIndex = -1;
// set the total population size
Instance first = m_masterPlot.getPlotInstances().instance(0);
double totalPos = first.value(m_masterPlot.getPlotInstances()
.attribute(ThresholdCurve.TRUE_POS_NAME).index());
double totalNeg = first.value(m_masterPlot.getPlotInstances().attribute(
ThresholdCurve.FALSE_POS_NAME));
m_originalPopSize = (int) (totalPos + totalNeg);
m_totalPopField.setText("" + m_originalPopSize);
m_performancePanel.setYIndex(5);
m_performancePanel.setXIndex(10);
m_costBenefitPanel.setXIndex(0);
m_costBenefitPanel.setYIndex(1);
// System.err.println(m_masterPlot.getPlotInstances());
updateInfoForSliderValue(m_thresholdSlider.getValue() / 100.0);
}
private void setClassForConfusionMatrix(Attribute classAtt) {
m_classAttribute = classAtt;
m_conf_actualA.setText(" Actual (a): " + classAtt.value(0));
m_conf_actualA.setToolTipText(classAtt.value(0));
String negClasses = "";
for (int i = 1; i < classAtt.numValues(); i++) {
negClasses += classAtt.value(i);
if (i < classAtt.numValues() - 1) {
negClasses += ",";
}
}
m_conf_actualB.setText(" Actual (b): " + negClasses);
m_conf_actualB.setToolTipText(negClasses);
}
private boolean constructCostBenefitData() {
double tpCost = 0.0;
try {
tpCost = Double.parseDouble(m_cost_aa.getText());
} catch (NumberFormatException n) {
}
double fpCost = 0.0;
try {
fpCost = Double.parseDouble(m_cost_ba.getText());
} catch (NumberFormatException n) {
}
double tnCost = 0.0;
try {
tnCost = Double.parseDouble(m_cost_bb.getText());
} catch (NumberFormatException n) {
}
double fnCost = 0.0;
try {
fnCost = Double.parseDouble(m_cost_ab.getText());
} catch (NumberFormatException n) {
}
double requestedPopSize = m_originalPopSize;
try {
requestedPopSize = Double.parseDouble(m_totalPopField.getText());
} catch (NumberFormatException e) {
}
double scaleFactor = 1.0;
if (m_originalPopSize != 0) {
scaleFactor = requestedPopSize / m_originalPopSize;
}
if (tpCost == m_tpPrevious && fpCost == m_fpPrevious
&& tnCost == m_tnPrevious && fnCost == m_fnPrevious
&& requestedPopSize == m_totalPopPrevious) {
return false;
}
// First construct some Instances for the curve
ArrayList<Attribute> fv = new ArrayList<Attribute>();
fv.add(new Attribute("Sample Size"));
fv.add(new Attribute("Cost/Benefit"));
fv.add(new Attribute("Threshold"));
Instances costBenefitI = new Instances("Cost/Benefit Curve", fv, 100);
// process the performance data to make this curve
Instances performanceI = m_masterPlot.getPlotInstances();
for (int i = 0; i < performanceI.numInstances(); i++) {
Instance current = performanceI.instance(i);
double[] vals = new double[3];
vals[0] = current.value(10); // sample size
vals[1] = (current.value(0) * tpCost + current.value(1) * fnCost
+ current.value(2) * fpCost + current.value(3) * tnCost)
* scaleFactor;
vals[2] = current.value(current.numAttributes() - 1);
Instance newInst = new DenseInstance(1.0, vals);
costBenefitI.add(newInst);
}
costBenefitI.compactify();
// now set up the plot data
m_costBenefit = new PlotData2D(costBenefitI);
m_costBenefit.m_alwaysDisplayPointsOfThisSize = 10;
m_costBenefit.setPlotName("Cost/benefit curve");
boolean[] connectPoints = new boolean[costBenefitI.numInstances()];
for (int i = 0; i < connectPoints.length; i++) {
connectPoints[i] = true;
}
try {
m_costBenefit.setConnectPoints(connectPoints);
m_costBenefit.setShapeSize(m_shapeSizes);
} catch (Exception ex) {
// ignore
}
m_tpPrevious = tpCost;
m_fpPrevious = fpCost;
m_tnPrevious = tnCost;
m_fnPrevious = fnCost;
return true;
}
}
/**
* Constructor.
*/
public CostBenefitAnalysis() {
if (!GraphicsEnvironment.isHeadless()) {
appearanceFinal();
} else {
m_headlessEvents = new ArrayList<EventObject>();
}
}
/**
* Global info for this bean
*
* @return a <code>String</code> value
*/
public String globalInfo() {
return "Visualize performance charts (such as ROC).";
}
/**
* Accept a threshold data event and set up the visualization.
*
* @param e a threshold data event
*/
@Override
public void acceptDataSet(ThresholdDataEvent e) {
if (!GraphicsEnvironment.isHeadless()) {
try {
setCurveData(e.getDataSet(), e.getClassAttribute());
} catch (Exception ex) {
System.err
.println("[CostBenefitAnalysis] Problem setting up visualization.");
ex.printStackTrace();
}
} else {
m_headlessEvents = new ArrayList<EventObject>();
m_headlessEvents.add(e);
}
}
/**
* Set the threshold curve data to use.
*
* @param curveData a PlotData2D object set up with the curve data.
* @param origClassAtt the class attribute from the original data used to
* generate the curve.
* @throws Exception if somthing goes wrong during the setup process.
*/
public void setCurveData(PlotData2D curveData, Attribute origClassAtt)
throws Exception {
if (m_analysisPanel == null) {
m_analysisPanel = new AnalysisPanel();
}
m_analysisPanel.setDataSet(curveData, origClassAtt);
}
@Override
public BeanVisual getVisual() {
return m_visual;
}
@Override
public void setVisual(BeanVisual newVisual) {
m_visual = newVisual;
}
@Override
public void useDefaultVisual() {
m_visual.loadIcons(BeanVisual.ICON_PATH + "DefaultDataVisualizer.gif",
BeanVisual.ICON_PATH + "DefaultDataVisualizer_animated.gif");
}
@Override
public Enumeration<String> enumerateRequests() {
Vector<String> newVector = new Vector<String>(0);
if (m_analysisPanel != null) {
if (m_analysisPanel.m_masterPlot != null) {
newVector.addElement("Show analysis");
}
}
return newVector.elements();
}
@Override
public void performRequest(String request) {
if (request.compareTo("Show analysis") == 0) {
try {
// popup visualize panel
if (!m_framePoppedUp) {
m_framePoppedUp = true;
final javax.swing.JFrame jf = new javax.swing.JFrame(
"Cost/Benefit Analysis");
jf.setSize(1000, 600);
jf.getContentPane().setLayout(new BorderLayout());
jf.getContentPane().add(m_analysisPanel, BorderLayout.CENTER);
jf.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
jf.dispose();
m_framePoppedUp = false;
}
});
jf.setVisible(true);
m_popupFrame = jf;
} else {
m_popupFrame.toFront();
}
} catch (Exception ex) {
ex.printStackTrace();
m_framePoppedUp = false;
}
} else {
throw new IllegalArgumentException(request
+ " not supported (Cost/Benefit Analysis");
}
}
@Override
public void addVetoableChangeListener(String name, VetoableChangeListener vcl) {
m_bcSupport.addVetoableChangeListener(name, vcl);
}
@Override
public BeanContext getBeanContext() {
return m_beanContext;
}
@Override
public void removeVetoableChangeListener(String name,
VetoableChangeListener vcl) {
m_bcSupport.removeVetoableChangeListener(name, vcl);
}
protected void appearanceFinal() {
removeAll();
setLayout(new BorderLayout());
setUpFinal();
}
protected void setUpFinal() {
if (m_analysisPanel == null) {
m_analysisPanel = new AnalysisPanel();
}
add(m_analysisPanel, BorderLayout.CENTER);
}
protected void appearanceDesign() {
removeAll();
useDefaultVisual();
setLayout(new BorderLayout());
add(m_visual, BorderLayout.CENTER);
}
@Override
public void setBeanContext(BeanContext bc) throws PropertyVetoException {
m_beanContext = bc;
m_design = m_beanContext.isDesignTime();
if (m_design) {
appearanceDesign();
} else {
if (!GraphicsEnvironment.isHeadless()) {
appearanceFinal();
}
}
}
/**
* Returns true if, at this time, the object will accept a connection via the
* named event
*
* @param eventName the name of the event in question
* @return true if the object will accept a connection
*/
@Override
public boolean connectionAllowed(String eventName) {
return (m_listenee == null);
}
/**
* Notify this object that it has been registered as a listener with a source
* for recieving events described by the named event This object is
* responsible for recording this fact.
*
* @param eventName the event
* @param source the source with which this object has been registered as a
* listener
*/
@Override
public void connectionNotification(String eventName, Object source) {
if (connectionAllowed(eventName)) {
m_listenee = source;
}
}
/**
* Returns true if, at this time, the object will accept a connection
* according to the supplied EventSetDescriptor
*
* @param esd the EventSetDescriptor
* @return true if the object will accept a connection
*/
@Override
public boolean connectionAllowed(EventSetDescriptor esd) {
return connectionAllowed(esd.getName());
}
/**
* Notify this object that it has been deregistered as a listener with a
* source for named event. This object is responsible for recording this fact.
*
* @param eventName the event
* @param source the source with which this object has been registered as a
* listener
*/
@Override
public void disconnectionNotification(String eventName, Object source) {
if (m_listenee == source) {
m_listenee = null;
}
}
/**
* Get the custom (descriptive) name for this bean (if one has been set)
*
* @return the custom name (or the default name)
*/
@Override
public String getCustomName() {
return m_visual.getText();
}
/**
* Returns true if. at this time, the bean is busy with some (i.e. perhaps a
* worker thread is performing some calculation).
*
* @return true if the bean is busy.
*/
@Override
public boolean isBusy() {
return false;
}
/**
* Set a custom (descriptive) name for this bean
*
* @param name the name to use
*/
@Override
public void setCustomName(String name) {
m_visual.setText(name);
}
/**
* Set a logger
*
* @param logger a <code>weka.gui.Logger</code> value
*/
@Override
public void setLog(Logger logger) {
// we don't need to do any logging
}
/**
* Stop any processing that the bean might be doing.
*/
@Override
public void stop() {
// nothing to do here
}
public static void main(String[] args) {
try {
Instances train = new Instances(new java.io.BufferedReader(
new java.io.FileReader(args[0])));
train.setClassIndex(train.numAttributes() - 1);
weka.classifiers.evaluation.ThresholdCurve tc = new weka.classifiers.evaluation.ThresholdCurve();
weka.classifiers.evaluation.EvaluationUtils eu = new weka.classifiers.evaluation.EvaluationUtils();
// weka.classifiers.Classifier classifier = new
// weka.classifiers.functions.Logistic();
weka.classifiers.Classifier classifier = new weka.classifiers.bayes.NaiveBayes();
ArrayList<Prediction> predictions = new ArrayList<Prediction>();
eu.setSeed(1);
predictions.addAll(eu.getCVPredictions(classifier, train, 10));
Instances result = tc.getCurve(predictions, 0);
PlotData2D pd = new PlotData2D(result);
pd.m_alwaysDisplayPointsOfThisSize = 10;
boolean[] connectPoints = new boolean[result.numInstances()];
for (int i = 1; i < connectPoints.length; i++) {
connectPoints[i] = true;
}
pd.setConnectPoints(connectPoints);
final javax.swing.JFrame jf = new javax.swing.JFrame("CostBenefitTest");
jf.setSize(1000, 600);
// jf.pack();
jf.getContentPane().setLayout(new BorderLayout());
final CostBenefitAnalysis.AnalysisPanel analysisPanel = new CostBenefitAnalysis.AnalysisPanel();
jf.getContentPane().add(analysisPanel, BorderLayout.CENTER);
jf.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
jf.dispose();
System.exit(0);
}
});
jf.setVisible(true);
analysisPanel.setDataSet(pd, train.classAttribute());
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* Get the list of events processed in headless mode. May return null or an
* empty list if not running in headless mode or no events were processed
*
* @return a list of EventObjects or null.
*/
@Override
public List<EventObject> retrieveHeadlessEvents() {
return m_headlessEvents;
}
/**
* Process a list of events that have been collected earlier. Has no affect if
* the component is running in headless mode.
*
* @param headless a list of EventObjects to process.
*/
@Override
public void processHeadlessEvents(List<EventObject> headless) {
// only process if we're not headless
if (!GraphicsEnvironment.isHeadless()) {
for (EventObject e : headless) {
if (e instanceof ThresholdDataEvent) {
acceptDataSet((ThresholdDataEvent) e);
}
}
}
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/CostBenefitAnalysisBeanInfo.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/>.
*/
/*
* CostBenefitAnalysisBeanInfo.java
* Copyright (C) 2009-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.beans.EventSetDescriptor;
import java.beans.SimpleBeanInfo;
/**
* Bean info class for the cost/benefit analysis
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision$
*/
public class CostBenefitAnalysisBeanInfo extends SimpleBeanInfo {
/**
* Get the event set descriptors for this bean
*
* @return an <code>EventSetDescriptor[]</code> value
*/
public EventSetDescriptor [] getEventSetDescriptors() {
// hide all gui events
EventSetDescriptor [] esds = { };
return esds;
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/CrossValidationFoldMaker.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/>.
*/
/*
* CrossValidationFoldMaker.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.io.Serializable;
import java.util.Enumeration;
import java.util.Random;
import java.util.Vector;
import weka.core.Instances;
/**
* Bean for splitting instances into training ant test sets according to a cross
* validation
*
* @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a>
* @version $Revision$
*/
public class CrossValidationFoldMaker extends AbstractTrainAndTestSetProducer
implements DataSourceListener, TrainingSetListener, TestSetListener,
UserRequestAcceptor, EventConstraints, Serializable, StructureProducer {
/** for serialization */
private static final long serialVersionUID = -6350179298851891512L;
private int m_numFolds = 10;
private int m_randomSeed = 1;
private boolean m_preserveOrder = false;
private transient Thread m_foldThread = null;
private boolean m_dataProvider = false;
private boolean m_trainingProvider = false;
private boolean m_testProvider = false;
public CrossValidationFoldMaker() {
m_visual.loadIcons(BeanVisual.ICON_PATH + "CrossValidationFoldMaker.gif",
BeanVisual.ICON_PATH + "CrossValidationFoldMaker_animated.gif");
m_visual.setText("CrossValidationFoldMaker");
}
private Instances getUpstreamStructure() {
if (m_listenee != null && m_listenee instanceof StructureProducer) {
if (m_dataProvider) {
return ((StructureProducer) m_listenee).getStructure("dataSet");
}
if (m_trainingProvider) {
return ((StructureProducer) m_listenee).getStructure("trainingSet");
}
if (m_testProvider) {
return ((StructureProducer) m_listenee).getStructure("testSet");
}
}
return null;
}
/**
* Get the structure of the output encapsulated in the named event. If the
* structure can't be determined in advance of seeing input, or this
* StructureProducer does not generate the named event, null should be
* returned.
*
* @param eventName the name of the output event that encapsulates the
* requested output.
*
* @return the structure of the output encapsulated in the named event or null
* if it can't be determined in advance of seeing input or the named
* event is not generated by this StructureProduce.
*/
@Override
public Instances getStructure(String eventName) {
if (!eventName.equals("trainingSet") && !eventName.equals("testSet")) {
return null;
}
if (m_listenee == null) {
return null;
}
if (eventName.equals("trainingSet") && m_trainingListeners.size() == 0) {
// downstream has asked for the structure of something that we
// are not producing at the moment
return null;
}
if (eventName.equals("testSet") && m_testListeners.size() == 0) {
// downstream has asked for the structure of something that we
// are not producing at the moment
return null;
}
return getUpstreamStructure();
}
/**
* Notify this object that it has been registered as a listener with a source
* with respect to the supplied event name
*
* @param eventName the event
* @param source the source with which this object has been registered as a
* listener
*/
@Override
public synchronized void connectionNotification(String eventName,
Object source) {
super.connectionNotification(eventName, source);
if (connectionAllowed(eventName)) {
if (eventName.equals("dataSet")) {
m_dataProvider = true;
m_trainingProvider = false;
m_testProvider = false;
} else if (eventName.equals("trainingSet")) {
m_dataProvider = false;
m_trainingProvider = true;
m_testProvider = false;
} else if (eventName.equals("testSet")) {
m_dataProvider = false;
m_trainingProvider = false;
m_testProvider = true;
}
}
}
/**
* Notify this object that it has been deregistered as a listener with a
* source with respect to the supplied event name
*
* @param eventName the event
* @param source the source with which this object has been registered as a
* listener
*/
@Override
public synchronized void disconnectionNotification(String eventName,
Object source) {
super.disconnectionNotification(eventName, source);
if (m_listenee == null) {
m_dataProvider = false;
m_trainingProvider = false;
m_testProvider = false;
}
}
/**
* Set a custom (descriptive) name for this bean
*
* @param name the name to use
*/
@Override
public void setCustomName(String name) {
m_visual.setText(name);
}
/**
* Get the custom (descriptive) name for this bean (if one has been set)
*
* @return the custom name (or the default name)
*/
@Override
public String getCustomName() {
return m_visual.getText();
}
/**
* Global info for this bean
*
* @return a <code>String</code> value
*/
public String globalInfo() {
return "Split an incoming data set into cross validation folds. "
+ "Separate train and test sets are produced for each of the k folds.";
}
/**
* Accept a training set
*
* @param e a <code>TrainingSetEvent</code> value
*/
@Override
public void acceptTrainingSet(TrainingSetEvent e) {
Instances trainingSet = e.getTrainingSet();
DataSetEvent dse = new DataSetEvent(this, trainingSet);
acceptDataSet(dse);
}
/**
* Accept a test set
*
* @param e a <code>TestSetEvent</code> value
*/
@Override
public void acceptTestSet(TestSetEvent e) {
Instances testSet = e.getTestSet();
DataSetEvent dse = new DataSetEvent(this, testSet);
acceptDataSet(dse);
}
/**
* Accept a data set
*
* @param e a <code>DataSetEvent</code> value
*/
@Override
public void acceptDataSet(DataSetEvent e) {
if (e.isStructureOnly()) {
// Pass on structure to training and test set listeners
TrainingSetEvent tse = new TrainingSetEvent(this, e.getDataSet());
TestSetEvent tsee = new TestSetEvent(this, e.getDataSet());
notifyTrainingSetProduced(tse);
notifyTestSetProduced(tsee);
return;
}
if (m_foldThread == null) {
final Instances dataSet = new Instances(e.getDataSet());
m_foldThread = new Thread() {
@Override
public void run() {
boolean errorOccurred = false;
try {
Random random = new Random(getSeed());
if (!m_preserveOrder) {
dataSet.randomize(random);
}
if (dataSet.classIndex() >= 0
&& dataSet.attribute(dataSet.classIndex()).isNominal()
&& !m_preserveOrder) {
dataSet.stratify(getFolds());
if (m_logger != null) {
m_logger.logMessage("[" + getCustomName() + "] "
+ "stratifying data");
}
}
for (int i = 0; i < getFolds(); i++) {
if (m_foldThread == null) {
if (m_logger != null) {
m_logger.logMessage("[" + getCustomName()
+ "] Cross validation has been canceled!");
}
// exit gracefully
break;
}
Instances train = (!m_preserveOrder) ? dataSet.trainCV(
getFolds(), i, random) : dataSet.trainCV(getFolds(), i);
Instances test = dataSet.testCV(getFolds(), i);
// inform all training set listeners
TrainingSetEvent tse = new TrainingSetEvent(this, train);
tse.m_setNumber = i + 1;
tse.m_maxSetNumber = getFolds();
String msg = getCustomName() + "$"
+ CrossValidationFoldMaker.this.hashCode() + "|";
if (m_logger != null) {
m_logger.statusMessage(msg + "seed: " + getSeed() + " folds: "
+ getFolds() + "|Training fold " + (i + 1));
}
if (m_foldThread != null) {
// System.err.println("--Just before notify training set");
notifyTrainingSetProduced(tse);
// System.err.println("---Just after notify");
}
// inform all test set listeners
TestSetEvent teste = new TestSetEvent(this, test);
teste.m_setNumber = i + 1;
teste.m_maxSetNumber = getFolds();
if (m_logger != null) {
m_logger.statusMessage(msg + "seed: " + getSeed() + " folds: "
+ getFolds() + "|Test fold " + (i + 1));
}
if (m_foldThread != null) {
notifyTestSetProduced(teste);
}
}
} catch (Exception ex) {
// stop all processing
errorOccurred = true;
if (m_logger != null) {
m_logger.logMessage("[" + getCustomName()
+ "] problem during fold creation. " + ex.getMessage());
}
ex.printStackTrace();
CrossValidationFoldMaker.this.stop();
} finally {
m_foldThread = null;
if (errorOccurred) {
if (m_logger != null) {
m_logger.statusMessage(getCustomName() + "$"
+ CrossValidationFoldMaker.this.hashCode() + "|"
+ "ERROR (See log for details).");
}
} else if (isInterrupted()) {
String msg = "[" + getCustomName()
+ "] Cross validation interrupted";
if (m_logger != null) {
m_logger.logMessage("[" + getCustomName()
+ "] Cross validation interrupted");
m_logger.statusMessage(getCustomName() + "$"
+ CrossValidationFoldMaker.this.hashCode() + "|"
+ "INTERRUPTED");
} else {
System.err.println(msg);
}
} else {
String msg = getCustomName() + "$"
+ CrossValidationFoldMaker.this.hashCode() + "|";
if (m_logger != null) {
m_logger.statusMessage(msg + "Finished.");
}
}
block(false);
}
}
};
m_foldThread.setPriority(Thread.MIN_PRIORITY);
m_foldThread.start();
// if (m_foldThread.isAlive()) {
block(true);
// }
m_foldThread = null;
}
}
/**
* Notify all test set listeners of a TestSet event
*
* @param tse a <code>TestSetEvent</code> value
*/
@SuppressWarnings("unchecked")
private void notifyTestSetProduced(TestSetEvent tse) {
Vector<TestSetListener> l;
synchronized (this) {
l = (Vector<TestSetListener>) m_testListeners.clone();
}
if (l.size() > 0) {
for (int i = 0; i < l.size(); i++) {
if (m_foldThread == null) {
break;
}
// System.err.println("Notifying test listeners "
// +"(cross validation fold maker)");
l.elementAt(i).acceptTestSet(tse);
}
}
}
/**
* Notify all listeners of a TrainingSet event
*
* @param tse a <code>TrainingSetEvent</code> value
*/
@SuppressWarnings("unchecked")
protected void notifyTrainingSetProduced(TrainingSetEvent tse) {
Vector<TrainingSetListener> l;
synchronized (this) {
l = (Vector<TrainingSetListener>) m_trainingListeners.clone();
}
if (l.size() > 0) {
for (int i = 0; i < l.size(); i++) {
if (m_foldThread == null) {
break;
}
// System.err.println("Notifying training listeners "
// +"(cross validation fold maker)");
l.elementAt(i).acceptTrainingSet(tse);
}
}
}
/**
* Set the number of folds for the cross validation
*
* @param numFolds an <code>int</code> value
*/
public void setFolds(int numFolds) {
m_numFolds = numFolds;
}
/**
* Get the currently set number of folds
*
* @return an <code>int</code> value
*/
public int getFolds() {
return m_numFolds;
}
/**
* Tip text for this property
*
* @return a <code>String</code> value
*/
public String foldsTipText() {
return "The number of train and test splits to produce";
}
/**
* Set the seed
*
* @param randomSeed an <code>int</code> value
*/
public void setSeed(int randomSeed) {
m_randomSeed = randomSeed;
}
/**
* Get the currently set seed
*
* @return an <code>int</code> value
*/
public int getSeed() {
return m_randomSeed;
}
/**
* Tip text for this property
*
* @return a <code>String</code> value
*/
public String seedTipText() {
return "The randomization seed";
}
/**
* Returns true if the order of the incoming instances is to be preserved
* under cross-validation (no randomization or stratification is done in this
* case).
*
* @return true if the order of the incoming instances is to be preserved.
*/
public boolean getPreserveOrder() {
return m_preserveOrder;
}
/**
* Sets whether the order of the incoming instances is to be preserved under
* cross-validation (no randomization or stratification is done in this case).
*
* @param p true if the order is to be preserved.
*/
public void setPreserveOrder(boolean p) {
m_preserveOrder = p;
}
/**
* Returns true if. at this time, the bean is busy with some (i.e. perhaps a
* worker thread is performing some calculation).
*
* @return true if the bean is busy.
*/
@Override
public boolean isBusy() {
return (m_foldThread != null);
}
/**
* Stop any action
*/
@Override
@SuppressWarnings("deprecation")
public void stop() {
// tell the listenee (upstream bean) to stop
if (m_listenee instanceof BeanCommon) {
// System.err.println("Listener is BeanCommon");
((BeanCommon) m_listenee).stop();
}
// stop the fold thread
if (m_foldThread != null) {
Thread temp = m_foldThread;
m_foldThread = null;
temp.interrupt();
temp.stop();
}
}
/**
* Function used to stop code that calls acceptDataSet. This is needed as
* cross validation is performed inside a separate thread of execution.
*
* @param tf a <code>boolean</code> value
*/
private synchronized void block(boolean tf) {
if (tf) {
try {
// make sure the thread is still running before we block
if (m_foldThread != null && m_foldThread.isAlive()) {
wait();
}
} catch (InterruptedException ex) {
}
} else {
notifyAll();
}
}
/**
* Return an enumeration of user requests
*
* @return an <code>Enumeration</code> value
*/
@Override
public Enumeration<String> enumerateRequests() {
Vector<String> newVector = new Vector<String>(0);
if (m_foldThread != null) {
newVector.addElement("Stop");
}
return newVector.elements();
}
/**
* Perform the named request
*
* @param request a <code>String</code> value
* @exception IllegalArgumentException if an error occurs
*/
@Override
public void performRequest(String request) {
if (request.compareTo("Stop") == 0) {
stop();
} else {
throw new IllegalArgumentException(request
+ " not supported (CrossValidation)");
}
}
/**
* Returns true, if at the current time, the named event could be generated.
* Assumes that the supplied event name is an event that could be generated by
* this bean
*
* @param eventName the name of the event in question
* @return true if the named event could be generated at this point in time
*/
@Override
public boolean eventGeneratable(String eventName) {
if (m_listenee == null) {
return false;
}
if (m_listenee instanceof EventConstraints) {
if (((EventConstraints) m_listenee).eventGeneratable("dataSet")
|| ((EventConstraints) m_listenee).eventGeneratable("trainingSet")
|| ((EventConstraints) m_listenee).eventGeneratable("testSet")) {
return true;
} else {
return false;
}
}
return true;
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/CrossValidationFoldMakerBeanInfo.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/>.
*/
/*
* CrossValidationFoldMakerBeanInfo.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.beans.BeanDescriptor;
import java.beans.PropertyDescriptor;
/**
* BeanInfo class for the cross validation fold maker bean
*
* @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a>
* @version $Revision$
*/
public class CrossValidationFoldMakerBeanInfo
extends AbstractTrainAndTestSetProducerBeanInfo {
/**
* Return the property descriptors for this bean
*
* @return a <code>PropertyDescriptor[]</code> value
*/
public PropertyDescriptor[] getPropertyDescriptors() {
try {
PropertyDescriptor p1;
PropertyDescriptor p2;
PropertyDescriptor p3;
p1 = new PropertyDescriptor("folds", CrossValidationFoldMaker.class);
p2 = new PropertyDescriptor("seed", CrossValidationFoldMaker.class);
p3 = new PropertyDescriptor("preserveOrder", CrossValidationFoldMaker.class);
PropertyDescriptor [] pds = { p1, p2, p3 };
return pds;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
/**
* Return the bean descriptor for this bean
*
* @return a <code>BeanDescriptor</code> value
*/
public BeanDescriptor getBeanDescriptor() {
return new BeanDescriptor(weka.gui.beans.CrossValidationFoldMaker.class,
CrossValidationFoldMakerCustomizer.class);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/CrossValidationFoldMakerCustomizer.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/>.
*/
/*
* CrossValidationFoldMakerCustomizer.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import javax.swing.JButton;
import javax.swing.JPanel;
import weka.gui.PropertySheetPanel;
/**
* GUI Customizer for the cross validation fold maker bean
*
* @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a>
* @version $Revision$
*/
public class CrossValidationFoldMakerCustomizer
extends JPanel
implements BeanCustomizer, CustomizerCloseRequester,
CustomizerClosingListener {
/** for serialization */
private static final long serialVersionUID = 1229878140258668581L;
private PropertyChangeSupport m_pcSupport =
new PropertyChangeSupport(this);
private PropertySheetPanel m_cvEditor =
new PropertySheetPanel();
private CrossValidationFoldMaker m_cvMaker;
private ModifyListener m_modifyListener;
private int m_foldsBackup;
private boolean m_orderBackup;
private int m_seedBackup;
private Window m_parent;
public CrossValidationFoldMakerCustomizer() {
setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 5, 5, 5));
setLayout(new BorderLayout());
add(m_cvEditor, BorderLayout.CENTER);
add(new javax.swing.JLabel("CrossValidationFoldMakerCustomizer"),
BorderLayout.NORTH);
addButtons();
}
private void addButtons() {
JButton okBut = new JButton("OK");
JButton cancelBut = new JButton("Cancel");
JPanel butHolder = new JPanel();
butHolder.setLayout(new GridLayout(1, 2));
butHolder.add(okBut); butHolder.add(cancelBut);
add(butHolder, BorderLayout.SOUTH);
okBut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (m_modifyListener != null) {
m_modifyListener.
setModifiedStatus(CrossValidationFoldMakerCustomizer.this, true);
}
if (m_parent != null) {
m_parent.dispose();
}
}
});
cancelBut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
customizerClosing();
if (m_parent != null) {
m_parent.dispose();
}
}
});
}
/**
* Set the object to be edited
*
* @param object a CrossValidationFoldMaker object
*/
public void setObject(Object object) {
m_cvMaker = ((CrossValidationFoldMaker)object);
m_foldsBackup = m_cvMaker.getFolds();
m_orderBackup = m_cvMaker.getPreserveOrder();
m_seedBackup = m_cvMaker.getSeed();
m_cvEditor.setTarget(m_cvMaker);
}
/**
* Add a property change listener
*
* @param pcl a <code>PropertyChangeListener</code> value
*/
public void addPropertyChangeListener(PropertyChangeListener pcl) {
m_pcSupport.addPropertyChangeListener(pcl);
}
/**
* Remove a property change listener
*
* @param pcl a <code>PropertyChangeListener</code> value
*/
public void removePropertyChangeListener(PropertyChangeListener pcl) {
m_pcSupport.removePropertyChangeListener(pcl);
}
@Override
public void setModifiedListener(ModifyListener l) {
m_modifyListener = l;
}
@Override
public void setParentWindow(Window parent) {
m_parent = parent;
}
@Override
public void customizerClosing() {
// restore the backup
m_cvMaker.setSeed(m_seedBackup);
m_cvMaker.setFolds(m_foldsBackup);
m_cvMaker.setPreserveOrder(m_orderBackup);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/CustomizerCloseRequester.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/>.
*/
/*
* CustomizerCloseRequester.java
* Copyright (C) 2004-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.awt.Window;
/**
* Customizers who want to be able to close the customizer window
* themselves can implement this window. The KnowledgeFlow will
* pass in the reference to the parent Window when constructing
* the customizer. The customizer can then call dispose() the
* Frame whenever it suits them.
*
* @author Mark Hall
* @version $Revision$
*/
public interface CustomizerCloseRequester {
/**
* A reference to the parent is passed in
*
* @param parent the parent Window
*/
void setParentWindow(Window parent);
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/CustomizerClosingListener.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/>.
*/
/*
* CustomizerClosingListener.java
* Copyright (C) 2004-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
/**
* @author Mark Hall
* @version $Revision$
*/
public interface CustomizerClosingListener {
/**
* Customizer classes that want to know when they are being
* disposed of can implement this method.
*/
void customizerClosing();
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/DataFormatListener.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/>.
*/
/*
* DataFormatListener.java
* Copyright (C) 2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
/**
* Listener interface that customizer classes that are interested
* in data format changes can implement.
*
* @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a>
* @version $Revision$
*/
public interface DataFormatListener {
/**
* Recieve a DataSetEvent that encapsulates a new data format. The
* DataSetEvent may contain null for the encapsulated format. This indicates
* that there is no data format available (ie. user may have disconnected
* an input source of data in the KnowledgeFlow).
*
* @param e a <code>DataSetEvent</code> value
*/
void newDataFormat(DataSetEvent e);
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/DataSetEvent.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/>.
*/
/*
* DataSetEvent.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.util.EventObject;
import weka.core.Instances;
/**
* Event encapsulating a data set
*
* @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a>
* @version $Revision$
* @see EventObject
*/
public class DataSetEvent
extends EventObject {
/** for serialization */
private static final long serialVersionUID = -5111218447577318057L;
private Instances m_dataSet;
private boolean m_structureOnly;
public DataSetEvent(Object source, Instances dataSet) {
super(source);
m_dataSet = dataSet;
if (m_dataSet != null && m_dataSet.numInstances() == 0) {
m_structureOnly = true;
}
}
/**
* Return the instances of the data set
*
* @return an <code>Instances</code> value
*/
public Instances getDataSet() {
return m_dataSet;
}
/**
* Returns true if the encapsulated instances
* contain just header information
*
* @return true if only header information is
* available in this DataSetEvent
*/
public boolean isStructureOnly() {
return m_structureOnly;
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/DataSink.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/>.
*/
/*
* DataSink.java
* Copyright (C) 2003-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
/**
* Indicator interface to something that can store instances to some
* destination
*
* @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a>
* @version $Revision$
*/
public interface DataSink {
// empty at present
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/DataSource.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/>.
*/
/*
* DataSource.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
/**
* Interface to something that is capable of being a source for data -
* either batch or incremental data
*
* @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a>
* @version $Revision$
* @since 1.0
*/
public interface DataSource {
/**
* Add a data source listener
*
* @param dsl a <code>DataSourceListener</code> value
*/
void addDataSourceListener(DataSourceListener dsl);
/**
* Remove a data source listener
*
* @param dsl a <code>DataSourceListener</code> value
*/
void removeDataSourceListener(DataSourceListener dsl);
/**
* Add an instance listener
*
* @param dsl an <code>InstanceListener</code> value
*/
void addInstanceListener(InstanceListener dsl);
/**
* Remove an instance listener
*
* @param dsl an <code>InstanceListener</code> value
*/
void removeInstanceListener(InstanceListener dsl);
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/DataSourceListener.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/>.
*/
/*
* DataSourceListener.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.util.EventListener;
/**
* Interface to something that can accept DataSetEvents
*
* @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a>
* @version $Revision$
* @since 1.0
* @see EventListener
*/
public interface DataSourceListener extends EventListener {
void acceptDataSet(DataSetEvent e);
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/DataVisualizer.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/>.
*/
/*
* DataVisualizer.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import weka.core.*;
import weka.core.PluginManager;
import weka.gui.Logger;
import weka.gui.visualize.PlotData2D;
import weka.gui.visualize.VisualizePanel;
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.GraphicsEnvironment;
import java.awt.image.BufferedImage;
import java.beans.EventSetDescriptor;
import java.beans.PropertyChangeListener;
import java.beans.VetoableChangeListener;
import java.beans.beancontext.BeanContext;
import java.beans.beancontext.BeanContextChild;
import java.beans.beancontext.BeanContextChildSupport;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.EventObject;
import java.util.List;
import java.util.Vector;
/**
* Bean that encapsulates weka.gui.visualize.VisualizePanel
*
* @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a>
* @version $Revision$
*/
public class DataVisualizer extends JPanel implements DataSourceListener,
TrainingSetListener, TestSetListener, Visible, UserRequestAcceptor,
Serializable, BeanContextChild, HeadlessEventCollector, EnvironmentHandler,
BeanCommon, EventConstraints {
/** for serialization */
private static final long serialVersionUID = 1949062132560159028L;
protected BeanVisual m_visual = new BeanVisual("DataVisualizer",
BeanVisual.ICON_PATH + "DefaultDataVisualizer.gif", BeanVisual.ICON_PATH
+ "DefaultDataVisualizer_animated.gif");
protected transient Instances m_visualizeDataSet;
protected transient JFrame m_popupFrame;
protected boolean m_framePoppedUp = false;
/**
* True if this bean's appearance is the design mode appearance
*/
protected boolean m_design;
/**
* BeanContex that this bean might be contained within
*/
protected transient BeanContext m_beanContext = null;
private VisualizePanel m_visPanel;
/** Events received and stored during headless execution */
protected List<EventObject> m_headlessEvents;
/**
* Set to true when processing events stored during headless execution. Used
* to prevent sending ImageEvents to listeners a second time (since these will
* have been passed on during headless execution).
*/
protected transient boolean m_processingHeadlessEvents = false;
protected ArrayList<ImageListener> m_imageListeners = new ArrayList<ImageListener>();
protected List<Object> m_listenees = new ArrayList<Object>();
/**
* Objects listening for data set events
*/
private final Vector<DataSourceListener> m_dataSetListeners = new Vector<DataSourceListener>();
/** For rendering plots to encapsulate in ImageEvents */
protected transient List<Instances> m_offscreenPlotData;
protected transient OffscreenChartRenderer m_offscreenRenderer;
/** Name of the renderer to use for offscreen chart rendering */
protected String m_offscreenRendererName = "Weka Chart Renderer";
/**
* The name of the attribute to use for the x-axis of offscreen plots. If left
* empty, False Positive Rate is used for threshold curves
*/
protected String m_xAxis = "";
/**
* The name of the attribute to use for the y-axis of offscreen plots. If left
* empty, True Positive Rate is used for threshold curves
*/
protected String m_yAxis = "";
/**
* Additional options for the offscreen renderer
*/
protected String m_additionalOptions = "";
/** Width of offscreen plots */
protected String m_width = "500";
/** Height of offscreen plots */
protected String m_height = "400";
/**
* The environment variables.
*/
protected transient Environment m_env;
/**
* BeanContextChild support
*/
protected BeanContextChildSupport m_bcSupport = new BeanContextChildSupport(
this);
public DataVisualizer() {
java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment();
if (!GraphicsEnvironment.isHeadless()) {
appearanceFinal();
} else {
m_headlessEvents = new ArrayList<EventObject>();
}
}
/**
* Global info for this bean
*
* @return a <code>String</code> value
*/
public String globalInfo() {
return "Visualize incoming data/training/test sets in a 2D scatter plot.";
}
protected void appearanceDesign() {
m_visPanel = null;
removeAll();
useDefaultVisual();
setLayout(new BorderLayout());
add(m_visual, BorderLayout.CENTER);
}
protected void appearanceFinal() {
java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment();
removeAll();
if (!GraphicsEnvironment.isHeadless()) {
setLayout(new BorderLayout());
setUpFinal();
}
}
protected void setUpFinal() {
if (m_visPanel == null) {
m_visPanel = new VisualizePanel();
}
add(m_visPanel, BorderLayout.CENTER);
}
/**
* Accept a training set
*
* @param e a <code>TrainingSetEvent</code> value
*/
@Override
public void acceptTrainingSet(TrainingSetEvent e) {
Instances trainingSet = e.getTrainingSet();
DataSetEvent dse = new DataSetEvent(this, trainingSet);
acceptDataSet(dse);
}
/**
* Accept a test set
*
* @param e a <code>TestSetEvent</code> value
*/
@Override
public void acceptTestSet(TestSetEvent e) {
Instances testSet = e.getTestSet();
DataSetEvent dse = new DataSetEvent(this, testSet);
acceptDataSet(dse);
}
/**
* Accept a data set
*
* @param e a <code>DataSetEvent</code> value
*/
@Override
public synchronized void acceptDataSet(DataSetEvent e) {
// ignore structure only events
if (e.isStructureOnly()) {
return;
}
m_visualizeDataSet = new Instances(e.getDataSet());
if (m_visualizeDataSet.classIndex() < 0) {
m_visualizeDataSet.setClassIndex(m_visualizeDataSet.numAttributes() - 1);
}
if (!m_design) {
try {
setInstances(m_visualizeDataSet);
} catch (Exception ex) {
ex.printStackTrace();
}
} else {
if (m_headlessEvents != null) {
m_headlessEvents = new ArrayList<EventObject>();
m_headlessEvents.add(e);
}
}
// pass on the event to any listeners
notifyDataSetListeners(e);
renderOffscreenImage(e);
}
protected void renderOffscreenImage(DataSetEvent e) {
if (m_env == null) {
m_env = Environment.getSystemWide();
}
if (m_imageListeners.size() > 0 && !m_processingHeadlessEvents) {
// configure the renderer (if necessary)
setupOffscreenRenderer();
m_offscreenPlotData = new ArrayList<Instances>();
Instances predictedI = e.getDataSet();
if (predictedI.classIndex() >= 0
&& predictedI.classAttribute().isNominal()) {
// set up multiple series - one for each class
Instances[] classes = new Instances[predictedI.numClasses()];
for (int i = 0; i < predictedI.numClasses(); i++) {
classes[i] = new Instances(predictedI, 0);
classes[i].setRelationName(predictedI.classAttribute().value(i));
}
for (int i = 0; i < predictedI.numInstances(); i++) {
Instance current = predictedI.instance(i);
classes[(int) current.classValue()].add((Instance) current.copy());
}
for (Instances classe : classes) {
m_offscreenPlotData.add(classe);
}
} else {
m_offscreenPlotData.add(new Instances(predictedI));
}
List<String> options = new ArrayList<String>();
String additional = m_additionalOptions;
if (m_additionalOptions != null && m_additionalOptions.length() > 0) {
try {
additional = m_env.substitute(additional);
} catch (Exception ex) {
}
}
if (additional != null && additional.indexOf("-color") < 0) {
// for WekaOffscreenChartRenderer only
if (additional.length() > 0) {
additional += ",";
}
if (predictedI.classIndex() >= 0) {
additional += "-color=" + predictedI.classAttribute().name();
} else {
additional += "-color=/last";
}
}
String[] optionsParts = additional.split(",");
for (String p : optionsParts) {
options.add(p.trim());
}
String xAxis = m_xAxis;
try {
xAxis = m_env.substitute(xAxis);
} catch (Exception ex) {
}
String yAxis = m_yAxis;
try {
yAxis = m_env.substitute(yAxis);
} catch (Exception ex) {
}
String width = m_width;
String height = m_height;
int defWidth = 500;
int defHeight = 400;
try {
width = m_env.substitute(width);
height = m_env.substitute(height);
defWidth = Integer.parseInt(width);
defHeight = Integer.parseInt(height);
} catch (Exception ex) {
}
try {
BufferedImage osi = m_offscreenRenderer.renderXYScatterPlot(defWidth,
defHeight, m_offscreenPlotData, xAxis, yAxis, options);
ImageEvent ie = new ImageEvent(this, osi);
notifyImageListeners(ie);
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
/**
* Notify all image listeners of a ImageEvent
*
* @param te a <code>ImageEvent</code> value
*/
@SuppressWarnings("unchecked")
protected void notifyImageListeners(ImageEvent te) {
ArrayList<ImageListener> l;
synchronized (this) {
l = (ArrayList<ImageListener>) m_imageListeners.clone();
}
if (l.size() > 0) {
for (int i = 0; i < l.size(); i++) {
l.get(i).acceptImage(te);
}
}
}
/**
* Get the list of events processed in headless mode. May return null or an
* empty list if not running in headless mode or no events were processed
*
* @return a list of EventObjects or null.
*/
@Override
public List<EventObject> retrieveHeadlessEvents() {
return m_headlessEvents;
}
/**
* Process a list of events that have been collected earlier. Has no affect if
* the component is running in headless mode.
*
* @param headless a list of EventObjects to process.
*/
@Override
public void processHeadlessEvents(List<EventObject> headless) {
// only process if we're not headless
if (!java.awt.GraphicsEnvironment.isHeadless()) {
m_processingHeadlessEvents = true;
for (EventObject e : headless) {
if (e instanceof DataSetEvent) {
acceptDataSet((DataSetEvent) e);
}
}
}
m_processingHeadlessEvents = false;
}
/**
* Set the visual appearance of this bean
*
* @param newVisual a <code>BeanVisual</code> value
*/
@Override
public void setVisual(BeanVisual newVisual) {
m_visual = newVisual;
}
/**
* Return the visual appearance of this bean
*/
@Override
public BeanVisual getVisual() {
return m_visual;
}
/**
* Use the default appearance for this bean
*/
@Override
public void useDefaultVisual() {
m_visual.loadIcons(BeanVisual.ICON_PATH + "DefaultDataVisualizer.gif",
BeanVisual.ICON_PATH + "DefaultDataVisualizer_animated.gif");
}
/**
* Describe <code>enumerateRequests</code> method here.
*
* @return an <code>Enumeration</code> value
*/
@Override
public Enumeration<String> enumerateRequests() {
Vector<String> newVector = new Vector<String>(0);
if (m_visualizeDataSet != null) {
newVector.addElement("Show plot");
}
return newVector.elements();
}
/**
* Add a property change listener to this bean
*
* @param name the name of the property of interest
* @param pcl a <code>PropertyChangeListener</code> value
*/
@Override
public void addPropertyChangeListener(String name, PropertyChangeListener pcl) {
m_bcSupport.addPropertyChangeListener(name, pcl);
}
/**
* Remove a property change listener from this bean
*
* @param name the name of the property of interest
* @param pcl a <code>PropertyChangeListener</code> value
*/
@Override
public void removePropertyChangeListener(String name,
PropertyChangeListener pcl) {
m_bcSupport.removePropertyChangeListener(name, pcl);
}
/**
* Add a vetoable change listener to this bean
*
* @param name the name of the property of interest
* @param vcl a <code>VetoableChangeListener</code> value
*/
@Override
public void addVetoableChangeListener(String name, VetoableChangeListener vcl) {
m_bcSupport.addVetoableChangeListener(name, vcl);
}
/**
* Remove a vetoable change listener from this bean
*
* @param name the name of the property of interest
* @param vcl a <code>VetoableChangeListener</code> value
*/
@Override
public void removeVetoableChangeListener(String name,
VetoableChangeListener vcl) {
m_bcSupport.removeVetoableChangeListener(name, vcl);
}
/**
* Set a bean context for this bean
*
* @param bc a <code>BeanContext</code> value
*/
@Override
public void setBeanContext(BeanContext bc) {
m_beanContext = bc;
m_design = m_beanContext.isDesignTime();
if (m_design) {
appearanceDesign();
} else {
java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment();
if (!GraphicsEnvironment.isHeadless()) {
appearanceFinal();
}
}
}
/**
* Return the bean context (if any) that this bean is embedded in
*
* @return a <code>BeanContext</code> value
*/
@Override
public BeanContext getBeanContext() {
return m_beanContext;
}
/**
* Set instances for this bean. This method is a convenience method for
* clients who use this component programatically
*
* @param inst an <code>Instances</code> value
* @exception Exception if an error occurs
*/
public void setInstances(Instances inst) throws Exception {
if (m_design) {
throw new Exception("This method is not to be used during design "
+ "time. It is meant to be used if this "
+ "bean is being used programatically as as "
+ "stand alone component.");
}
m_visualizeDataSet = inst;
PlotData2D pd1 = new PlotData2D(m_visualizeDataSet);
String relationName = m_visualizeDataSet.relationName();
pd1.setPlotName(relationName);
try {
m_visPanel.setMasterPlot(pd1);
} catch (Exception ex) {
System.err.println("Problem setting up "
+ "visualization (DataVisualizer)");
ex.printStackTrace();
}
}
/**
* Notify all data set listeners of a data set event
*
* @param ge a <code>DataSetEvent</code> value
*/
@SuppressWarnings("unchecked")
private void notifyDataSetListeners(DataSetEvent ge) {
Vector<DataSourceListener> l;
synchronized (this) {
l = (Vector<DataSourceListener>) m_dataSetListeners.clone();
}
if (l.size() > 0) {
for (int i = 0; i < l.size(); i++) {
l.elementAt(i).acceptDataSet(ge);
}
}
}
/**
* Describe <code>performRequest</code> method here.
*
* @param request a <code>String</code> value
* @exception IllegalArgumentException if an error occurs
*/
@Override
public void performRequest(String request) {
if (request.compareTo("Show plot") == 0) {
try {
// popup visualize panel
if (!m_framePoppedUp) {
m_framePoppedUp = true;
final VisualizePanel vis = new VisualizePanel();
PlotData2D pd1 = new PlotData2D(m_visualizeDataSet);
String relationName = m_visualizeDataSet.relationName();
// A bit of a nasty hack. Allows producers of instances-based
// events to specify that the points should be connected
if (relationName.startsWith("__")) {
boolean[] connect = new boolean[m_visualizeDataSet.numInstances()];
for (int i = 1; i < connect.length; i++) {
connect[i] = true;
}
pd1.setConnectPoints(connect);
relationName = relationName.substring(2);
}
pd1.setPlotName(relationName);
try {
vis.setMasterPlot(pd1);
} catch (Exception ex) {
System.err.println("Problem setting up "
+ "visualization (DataVisualizer)");
ex.printStackTrace();
}
final JFrame jf = Utils.getWekaJFrame("Visualize", m_visual);
jf.getContentPane().setLayout(new BorderLayout());
jf.getContentPane().add(vis, BorderLayout.CENTER);
jf.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
jf.dispose();
m_framePoppedUp = false;
}
});
jf.pack();
jf.setSize(800, 600);
jf.setLocationRelativeTo(SwingUtilities.getWindowAncestor(m_visual));
jf.setVisible(true);
m_popupFrame = jf;
} else {
m_popupFrame.toFront();
}
} catch (Exception ex) {
ex.printStackTrace();
m_framePoppedUp = false;
}
} else {
throw new IllegalArgumentException(request
+ " not supported (DataVisualizer)");
}
}
protected void setupOffscreenRenderer() {
if (m_offscreenRenderer == null) {
if (m_offscreenRendererName == null
|| m_offscreenRendererName.length() == 0) {
m_offscreenRenderer = new WekaOffscreenChartRenderer();
return;
}
if (m_offscreenRendererName.equalsIgnoreCase("weka chart renderer")) {
m_offscreenRenderer = new WekaOffscreenChartRenderer();
} else {
try {
Object r = PluginManager.getPluginInstance(
"weka.gui.beans.OffscreenChartRenderer", m_offscreenRendererName);
if (r != null && r instanceof weka.gui.beans.OffscreenChartRenderer) {
m_offscreenRenderer = (OffscreenChartRenderer) r;
} else {
// use built-in default
m_offscreenRenderer = new WekaOffscreenChartRenderer();
}
} catch (Exception ex) {
// use built-in default
m_offscreenRenderer = new WekaOffscreenChartRenderer();
}
}
}
}
/**
* Add a listener
*
* @param dsl a <code>DataSourceListener</code> value
*/
public synchronized void addDataSourceListener(DataSourceListener dsl) {
m_dataSetListeners.addElement(dsl);
}
/**
* Remove a listener
*
* @param dsl a <code>DataSourceListener</code> value
*/
public synchronized void removeDataSourceListener(DataSourceListener dsl) {
m_dataSetListeners.remove(dsl);
}
public static void main(String[] args) {
try {
if (args.length != 1) {
System.err.println("Usage: DataVisualizer <dataset>");
System.exit(1);
}
java.io.Reader r = new java.io.BufferedReader(new java.io.FileReader(
args[0]));
Instances inst = new Instances(r);
final javax.swing.JFrame jf = new javax.swing.JFrame();
jf.getContentPane().setLayout(new java.awt.BorderLayout());
final DataVisualizer as = new DataVisualizer();
as.setInstances(inst);
jf.getContentPane().add(as, java.awt.BorderLayout.CENTER);
jf.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
jf.dispose();
System.exit(0);
}
});
jf.setSize(800, 600);
jf.setVisible(true);
} catch (Exception ex) {
ex.printStackTrace();
System.err.println(ex.getMessage());
}
}
@Override
public void setEnvironment(Environment env) {
m_env = env;
}
/**
* Set the name of the attribute for the x-axis in offscreen plots. This
* defaults to "False Positive Rate" for threshold curves if not specified.
*
* @param xAxis the name of the xAxis
*/
public void setOffscreenXAxis(String xAxis) {
m_xAxis = xAxis;
}
/**
* Get the name of the attribute for the x-axis in offscreen plots
*
* @return the name of the xAxis
*/
public String getOffscreenXAxis() {
return m_xAxis;
}
/**
* Set the name of the attribute for the y-axis in offscreen plots. This
* defaults to "True Positive Rate" for threshold curves if not specified.
*
* @param yAxis the name of the xAxis
*/
public void setOffscreenYAxis(String yAxis) {
m_yAxis = yAxis;
}
/**
* Get the name of the attribute for the y-axix of offscreen plots.
*
* @return the name of the yAxis.
*/
public String getOffscreenYAxis() {
return m_yAxis;
}
/**
* Set the width (in pixels) of the offscreen image to generate.
*
* @param width the width in pixels.
*/
public void setOffscreenWidth(String width) {
m_width = width;
}
/**
* Get the width (in pixels) of the offscreen image to generate.
*
* @return the width in pixels.
*/
public String getOffscreenWidth() {
return m_width;
}
/**
* Set the height (in pixels) of the offscreen image to generate
*
* @param height the height in pixels
*/
public void setOffscreenHeight(String height) {
m_height = height;
}
/**
* Get the height (in pixels) of the offscreen image to generate
*
* @return the height in pixels
*/
public String getOffscreenHeight() {
return m_height;
}
/**
* Set the name of the renderer to use for offscreen chart rendering
* operations
*
* @param rendererName the name of the renderer to use
*/
public void setOffscreenRendererName(String rendererName) {
m_offscreenRendererName = rendererName;
m_offscreenRenderer = null;
}
/**
* Get the name of the renderer to use for offscreen chart rendering
* operations
*
* @return the name of the renderer to use
*/
public String getOffscreenRendererName() {
return m_offscreenRendererName;
}
/**
* Set the additional options for the offscreen renderer
*
* @param additional additional options
*/
public void setOffscreenAdditionalOpts(String additional) {
m_additionalOptions = additional;
}
/**
* Get the additional options for the offscreen renderer
*
* @return the additional options
*/
public String getOffscreenAdditionalOpts() {
return m_additionalOptions;
}
/**
* Add an image listener
*
* @param cl a <code>ImageListener</code> value
*/
public synchronized void addImageListener(ImageListener cl) {
m_imageListeners.add(cl);
}
/**
* Remove an image listener
*
* @param cl a <code>ImageListener</code> value
*/
public synchronized void removeImageListener(ImageListener cl) {
m_imageListeners.remove(cl);
}
/**
* Set a custom (descriptive) name for this bean
*
* @param name the name to use
*/
@Override
public void setCustomName(String name) {
m_visual.setText(name);
}
/**
* Get the custom (descriptive) name for this bean (if one has been set)
*
* @return the custom name (or the default name)
*/
@Override
public String getCustomName() {
// TODO Auto-generated method stub
return m_visual.getText();
}
/**
* Stop any processing that the bean might be doing.
*/
@Override
public void stop() {
}
/**
* Returns true if. at this time, the bean is busy with some (i.e. perhaps a
* worker thread is performing some calculation).
*
* @return true if the bean is busy.
*/
@Override
public boolean isBusy() {
return false;
}
/**
* Set a logger
*
* @param logger a <code>Logger</code> value
*/
@Override
public void setLog(Logger logger) {
}
/**
* Returns true if, at this time, the object will accept a connection via the
* supplied EventSetDescriptor
*
* @param esd the EventSetDescriptor
* @return true if the object will accept a connection
*/
@Override
public boolean connectionAllowed(EventSetDescriptor esd) {
return connectionAllowed(esd.getName());
}
/**
* Returns true if, at this time, the object will accept a connection via the
* named event
*
* @param eventName the name of the event
* @return true if the object will accept a connection
*/
@Override
public boolean connectionAllowed(String eventName) {
return eventName.equals("dataSet") || eventName.equals("trainingSet")
|| eventName.equals("testSet");
}
/**
* Notify this object that it has been registered as a listener with a source
* for recieving events described by the named event This object is
* responsible for recording this fact.
*
* @param eventName the event
* @param source the source with which this object has been registered as a
* listener
*/
@Override
public void connectionNotification(String eventName, Object source) {
if (connectionAllowed(eventName)) {
m_listenees.add(source);
}
}
/**
* Notify this object that it has been deregistered as a listener with a
* source for named event. This object is responsible for recording this fact.
*
* @param eventName the event
* @param source the source with which this object has been registered as a
* listener
*/
@Override
public void disconnectionNotification(String eventName, Object source) {
m_listenees.remove(source);
}
/**
* Returns true, if at the current time, the named event could be generated.
* Assumes that supplied event names are names of events that could be
* generated by this bean.
*
* @param eventName the name of the event in question
* @return true if the named event could be generated at this point in time
*/
@Override
public boolean eventGeneratable(String eventName) {
if (m_listenees.size() == 0) {
return false;
}
boolean ok = false;
for (Object o : m_listenees) {
if (o instanceof EventConstraints) {
if (((EventConstraints) o).eventGeneratable("dataSet")
|| ((EventConstraints) o).eventGeneratable("trainingSet")
|| ((EventConstraints) o).eventGeneratable("testSet")) {
ok = true;
break;
}
}
}
return ok;
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/DataVisualizerBeanInfo.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/>.
*/
/*
* DataVisualizerBeanInfo.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.beans.BeanDescriptor;
import java.beans.EventSetDescriptor;
import java.beans.SimpleBeanInfo;
/**
* Bean info class for the data visualizer
*
* @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a>
* @version $Revision$
*/
public class DataVisualizerBeanInfo extends SimpleBeanInfo {
/**
* Get the event set descriptors for this bean
*
* @return an <code>EventSetDescriptor[]</code> value
*/
public EventSetDescriptor [] getEventSetDescriptors() {
try {
EventSetDescriptor [] esds = {
new EventSetDescriptor(DataVisualizer.class,
"dataSet",
DataSourceListener.class,
"acceptDataSet"),
new EventSetDescriptor(DataVisualizer.class,
"image",
ImageListener.class,
"acceptImage")
};
return esds;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
/**
* Get the bean descriptor for this bean
*
* @return a <code>BeanDescriptor</code> value
*/
public BeanDescriptor getBeanDescriptor() {
return new BeanDescriptor(weka.gui.beans.DataVisualizer.class,
DataVisualizerCustomizer.class);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/DataVisualizerCustomizer.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/>.
*/
/*
* DataVisualizerCustomizer.java
* Copyright (C) 2011-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import weka.core.Environment;
import weka.core.EnvironmentHandler;
import weka.core.PluginManager;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Set;
import java.util.Vector;
/**
* GUI customizer for data visualizer. Allows the customization of
* options for offscreen chart rendering (i.e. the payload of "ImageEvent"
* connections).
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision$
*/
public class DataVisualizerCustomizer extends JPanel implements
BeanCustomizer, EnvironmentHandler, CustomizerClosingListener,
CustomizerCloseRequester {
/**
* For serialization
*/
private static final long serialVersionUID = 27802741348090392L;
private DataVisualizer m_dataVis;
private Environment m_env = Environment.getSystemWide();
private ModifyListener m_modifyListener;
private Window m_parent;
private String m_rendererNameBack;
private String m_xAxisBack;
private String m_yAxisBack;
private String m_widthBack;
private String m_heightBack;
private String m_optsBack;
private JComboBox m_rendererCombo;
private EnvironmentField m_xAxis;
private EnvironmentField m_yAxis;
private EnvironmentField m_width;
private EnvironmentField m_height;
private EnvironmentField m_opts;
/**
* Constructor
*/
public DataVisualizerCustomizer() {
setLayout(new BorderLayout());
}
/**
* Set the model performance chart object to customize
*
* @param object the model performance chart to customize
*/
public void setObject(Object object) {
m_dataVis = (DataVisualizer)object;
m_rendererNameBack = m_dataVis.getOffscreenRendererName();
m_xAxisBack = m_dataVis.getOffscreenXAxis();
m_yAxisBack = m_dataVis.getOffscreenYAxis();
m_widthBack = m_dataVis.getOffscreenWidth();
m_heightBack = m_dataVis.getOffscreenHeight();
m_optsBack = m_dataVis.getOffscreenAdditionalOpts();
setup();
}
private void setup() {
JPanel holder = new JPanel();
holder.setLayout(new GridLayout(6, 2));
Vector<String> comboItems = new Vector<String>();
comboItems.add("Weka Chart Renderer");
Set<String> pluginRenderers =
PluginManager.getPluginNamesOfType("weka.gui.beans.OffscreenChartRenderer");
if (pluginRenderers != null) {
for (String plugin : pluginRenderers) {
comboItems.add(plugin);
}
}
JLabel rendererLab = new JLabel("Renderer", SwingConstants.RIGHT);
holder.add(rendererLab);
m_rendererCombo = new JComboBox(comboItems);
holder.add(m_rendererCombo);
JLabel xLab = new JLabel("X-axis attribute", SwingConstants.RIGHT);
xLab.setToolTipText("Attribute name or /first or /last or /<index>");
m_xAxis = new EnvironmentField(m_env);
m_xAxis.setText(m_xAxisBack);
JLabel yLab = new JLabel("Y-axis attribute", SwingConstants.RIGHT);
yLab.setToolTipText("Attribute name or /first or /last or /<index>");
m_yAxis = new EnvironmentField(m_env);
m_yAxis.setText(m_yAxisBack);
JLabel widthLab = new JLabel("Chart width (pixels)", SwingConstants.RIGHT);
m_width = new EnvironmentField(m_env);
m_width.setText(m_widthBack);
JLabel heightLab = new JLabel("Chart height (pixels)", SwingConstants.RIGHT);
m_height = new EnvironmentField(m_env);
m_height.setText(m_heightBack);
final JLabel optsLab = new JLabel("Renderer options", SwingConstants.RIGHT);
m_opts = new EnvironmentField(m_env);
m_opts.setText(m_optsBack);
holder.add(xLab); holder.add(m_xAxis);
holder.add(yLab); holder.add(m_yAxis);
holder.add(widthLab); holder.add(m_width);
holder.add(heightLab); holder.add(m_height);
holder.add(optsLab); holder.add(m_opts);
add(holder, BorderLayout.CENTER);
String globalInfo = m_dataVis.globalInfo();
globalInfo += " This dialog allows you to configure offscreen " +
"rendering options. Offscreen images are passed via" +
" 'image' connections.";
JTextArea jt = new JTextArea();
jt.setColumns(30);
jt.setFont(new Font("SansSerif", Font.PLAIN,12));
jt.setEditable(false);
jt.setLineWrap(true);
jt.setWrapStyleWord(true);
jt.setText(globalInfo);
jt.setBackground(getBackground());
JPanel jp = new JPanel();
jp.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createTitledBorder("About"),
BorderFactory.createEmptyBorder(5, 5, 5, 5)
));
jp.setLayout(new BorderLayout());
jp.add(jt, BorderLayout.CENTER);
add(jp, BorderLayout.NORTH);
addButtons();
m_rendererCombo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setupRendererOptsTipText(optsLab);
}
});
m_rendererCombo.setSelectedItem(m_rendererNameBack);
setupRendererOptsTipText(optsLab);
}
private void setupRendererOptsTipText(JLabel optsLab) {
String renderer = m_rendererCombo.getSelectedItem().toString();
if (renderer.equalsIgnoreCase("weka chart renderer")) {
// built-in renderer
WekaOffscreenChartRenderer rcr = new WekaOffscreenChartRenderer();
String tipText = rcr.optionsTipTextHTML();
tipText = tipText.replace("<html>", "<html>Comma separated list of options:<br>");
optsLab.setToolTipText(tipText);
} else {
try {
Object rendererO = PluginManager.getPluginInstance("weka.gui.beans.OffscreenChartRenderer",
renderer);
if (rendererO != null) {
String tipText = ((OffscreenChartRenderer)rendererO).optionsTipTextHTML();
if (tipText != null && tipText.length() > 0) {
optsLab.setToolTipText(tipText);
}
}
} catch (Exception ex) {
}
}
}
private void addButtons() {
JButton okBut = new JButton("OK");
JButton cancelBut = new JButton("Cancel");
JPanel butHolder = new JPanel();
butHolder.setLayout(new GridLayout(1, 2));
butHolder.add(okBut); butHolder.add(cancelBut);
add(butHolder, BorderLayout.SOUTH);
okBut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
m_dataVis.setOffscreenXAxis(m_xAxis.getText());
m_dataVis.setOffscreenYAxis(m_yAxis.getText());
m_dataVis.setOffscreenWidth(m_width.getText());
m_dataVis.setOffscreenHeight(m_height.getText());
m_dataVis.setOffscreenAdditionalOpts(m_opts.getText());
m_dataVis.setOffscreenRendererName(m_rendererCombo.
getSelectedItem().toString());
if (m_modifyListener != null) {
m_modifyListener.
setModifiedStatus(DataVisualizerCustomizer.this, true);
}
if (m_parent != null) {
m_parent.dispose();
}
}
});
cancelBut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
customizerClosing();
if (m_parent != null) {
m_parent.dispose();
}
}
});
}
/**
* Set the parent window of this dialog
*
* @param parent the parent window
*/
public void setParentWindow(Window parent) {
m_parent = parent;
}
/**
* Gets called if the use closes the dialog via the
* close widget on the window - is treated as cancel,
* so restores the ImageSaver to its previous state.
*/
public void customizerClosing() {
m_dataVis.setOffscreenXAxis(m_xAxisBack);
m_dataVis.setOffscreenYAxis(m_yAxisBack);
m_dataVis.setOffscreenWidth(m_widthBack);
m_dataVis.setOffscreenHeight(m_heightBack);
m_dataVis.setOffscreenAdditionalOpts(m_optsBack);
m_dataVis.setOffscreenRendererName(m_rendererNameBack);
}
/**
* Set the environment variables to use
*
* @param env the environment variables to use
*/
public void setEnvironment(Environment env) {
m_env = env;
}
/**
* Set a listener interested in whether we've modified
* the ImageSaver that we're customizing
*
* @param l the listener
*/
public void setModifiedListener(ModifyListener l) {
m_modifyListener = l;
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/EnvironmentField.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/>.
*/
/*
* EnvironmentField.java
* Copyright (C) 2009-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.beans.PropertyEditor;
import java.util.Vector;
import javax.swing.BorderFactory;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import weka.core.Environment;
import weka.core.EnvironmentHandler;
import weka.gui.CustomPanelSupplier;
/**
* Widget that displays a label and a combo box for selecting environment
* variables. The enter arbitrary text, select an environment variable or a
* combination of both. Any variables are resolved (if possible) and resolved
* values are displayed in a tip-text.<p></p>
*
* This class is deprecated - use the version in weka.gui instead.
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision$
*/
@Deprecated
public class EnvironmentField extends JPanel implements EnvironmentHandler,
PropertyEditor, CustomPanelSupplier {
/** For serialization */
private static final long serialVersionUID = -3125404573324734121L;
/** The label for the widget */
protected JLabel m_label;
/** The combo box */
protected JComboBox m_combo;
/** The current environment variables */
protected Environment m_env;
protected String m_currentContents = "";
protected int m_firstCaretPos = 0;
protected int m_previousCaretPos = 0;
protected int m_currentCaretPos = 0;
protected PropertyChangeSupport m_support = new PropertyChangeSupport(this);
/**
* Combo box that allows the drop-down list to be wider than the component
* itself.
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
*/
public static class WideComboBox extends JComboBox {
/**
* For serialization
*/
private static final long serialVersionUID = -6512065375459733517L;
public WideComboBox() {
}
public WideComboBox(final Object items[]) {
super(items);
}
public WideComboBox(Vector<Object> items) {
super(items);
}
public WideComboBox(ComboBoxModel aModel) {
super(aModel);
}
private boolean m_layingOut = false;
@Override
public void doLayout() {
try {
m_layingOut = true;
super.doLayout();
} finally {
m_layingOut = false;
}
}
@Override
public Dimension getSize() {
Dimension dim = super.getSize();
if (!m_layingOut) {
dim.width = Math.max(dim.width, getPreferredSize().width);
}
return dim;
}
}
/**
* Construct an EnvironmentField with no label.
*/
public EnvironmentField() {
this("");
setEnvironment(Environment.getSystemWide());
}
/**
* Construct an EnvironmentField with no label.
*
* @param env the environment variables to display in the drop-down box
*/
public EnvironmentField(Environment env) {
this("");
setEnvironment(env);
}
/**
* Constructor.
*
* @param label the label to use
* @param env the environment variables to display in the drop-down box
*/
public EnvironmentField(String label, Environment env) {
this(label);
setEnvironment(env);
}
/**
* Constructor.
*
* @param label the label to use
*/
public EnvironmentField(String label) {
setLayout(new BorderLayout());
m_label = new JLabel(label);
if (label.length() > 0) {
m_label.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5));
}
add(m_label, BorderLayout.WEST);
m_combo = new WideComboBox();
m_combo.setEditable(true);
// m_combo.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
java.awt.Component theEditor = m_combo.getEditor().getEditorComponent();
if (theEditor instanceof JTextField) {
((JTextField) m_combo.getEditor().getEditorComponent())
.addCaretListener(new CaretListener() {
@Override
public void caretUpdate(CaretEvent e) {
m_firstCaretPos = m_previousCaretPos;
m_previousCaretPos = m_currentCaretPos;
m_currentCaretPos = e.getDot();
}
});
m_combo.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
m_support.firePropertyChange("", null, null);
}
});
((JTextField) m_combo.getEditor().getEditorComponent())
.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
m_support.firePropertyChange("", null, null);
}
});
}
add(m_combo, BorderLayout.CENTER);
setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
Dimension d = getPreferredSize();
setPreferredSize(new Dimension(250, d.height));
}
/**
* Set the label for this widget.
*
* @param label the label to use
*/
public void setLabel(String label) {
m_label.setText(label);
}
/**
* Set the text to display in the editable combo box.
*
* @param text the text to display
*/
public void setText(String text) {
m_currentContents = text;
java.awt.Component theEditor = m_combo.getEditor().getEditorComponent();
if (theEditor instanceof JTextField) {
((JTextField) theEditor).setText(text);
} else {
m_combo.setSelectedItem(m_currentContents);
}
m_support.firePropertyChange("", null, null);
}
/**
* Return the text from the combo box.
*
* @return the text from the combo box
*/
public String getText() {
java.awt.Component theEditor = m_combo.getEditor().getEditorComponent();
String text = m_combo.getSelectedItem().toString();
if (theEditor instanceof JTextField) {
text = ((JTextField) theEditor).getText();
}
return text;
}
@Override
public void setAsText(String s) {
setText(s);
}
@Override
public String getAsText() {
return getText();
}
@Override
public void setValue(Object o) {
setAsText((String) o);
}
@Override
public Object getValue() {
return getAsText();
}
@Override
public String getJavaInitializationString() {
return null;
}
@Override
public boolean isPaintable() {
return true; // we don't want to appear in a separate popup
}
@Override
public String[] getTags() {
return null;
}
@Override
public boolean supportsCustomEditor() {
return true;
}
@Override
public Component getCustomEditor() {
return this;
}
@Override
public JPanel getCustomPanel() {
return this;
}
@Override
public void addPropertyChangeListener(PropertyChangeListener pcl) {
if (m_support != null && pcl != null) {
m_support.addPropertyChangeListener(pcl);
}
}
@Override
public void removePropertyChangeListener(PropertyChangeListener pcl) {
if (m_support != null && pcl != null) {
m_support.removePropertyChangeListener(pcl);
}
}
@Override
public void paintValue(Graphics gfx, Rectangle box) {
// TODO Auto-generated method stub
}
private String processSelected(String selected) {
if (selected.equals(m_currentContents)) {
// don't do anything if the user has just pressed return
// without adding anything new
return selected;
}
if (m_firstCaretPos == 0) {
m_currentContents = selected + m_currentContents;
} else if (m_firstCaretPos >= m_currentContents.length()) {
m_currentContents = m_currentContents + selected;
} else {
String left = m_currentContents.substring(0, m_firstCaretPos);
String right = m_currentContents.substring(m_firstCaretPos,
m_currentContents.length());
m_currentContents = left + selected + right;
}
/*
* java.awt.Component theEditor = m_combo.getEditor().getEditorComponent();
* if (theEditor instanceof JTextField) {
* System.err.println("Setting current contents..." + m_currentContents);
* ((JTextField)theEditor).setText(m_currentContents); }
*/
m_combo.setSelectedItem(m_currentContents);
m_support.firePropertyChange("", null, null);
return m_currentContents;
}
/**
* Set the environment variables to display in the drop down list.
*
* @param env the environment variables to display
*/
@Override
public void setEnvironment(final Environment env) {
m_env = env;
Vector<String> varKeys = new Vector<String>(env.getVariableNames());
@SuppressWarnings("serial")
DefaultComboBoxModel dm = new DefaultComboBoxModel(varKeys) {
@Override
public Object getSelectedItem() {
Object item = super.getSelectedItem();
if (item instanceof String) {
if (env.getVariableValue((String) item) != null) {
String newS = "${" + (String) item + "}";
item = newS;
}
}
return item;
}
};
m_combo.setModel(dm);
m_combo.setSelectedItem("");
m_combo.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String selected = (String) m_combo.getSelectedItem();
try {
selected = processSelected(selected);
selected = m_env.substitute(selected);
} catch (Exception ex) {
// quietly ignore unresolved variables
}
m_combo.setToolTipText(selected);
}
});
m_combo.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
java.awt.Component theEditor = m_combo.getEditor().getEditorComponent();
if (theEditor instanceof JTextField) {
String selected = ((JTextField) theEditor).getText();
m_currentContents = selected;
if (m_env != null) {
try {
selected = m_env.substitute(selected);
} catch (Exception ex) {
// quietly ignore unresolved variables
}
}
m_combo.setToolTipText(selected);
}
}
});
}
/**
* Set the enabled status of the combo box.
*
* @param enabled true if the combo box is enabled
*/
@Override
public void setEnabled(boolean enabled) {
m_combo.setEnabled(enabled);
}
/**
* Set the editable status of the combo box.
*
* @param editable true if the combo box is editable
*/
public void setEditable(boolean editable) {
m_combo.setEditable(editable);
}
/**
* Main method for testing this class
*
* @param args command line args (ignored)
*/
public static void main(String[] args) {
try {
final javax.swing.JFrame jf = new javax.swing.JFrame("EnvironmentField");
jf.getContentPane().setLayout(new BorderLayout());
final EnvironmentField f = new EnvironmentField("A label here");
jf.getContentPane().add(f, BorderLayout.CENTER);
Environment env = Environment.getSystemWide();
f.setEnvironment(env);
jf.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
jf.dispose();
System.exit(0);
}
});
jf.pack();
jf.setVisible(true);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/EventConstraints.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/>.
*/
/*
* EventConstraints.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
/**
* Interface for objects that want to be able to specify at any given
* time whether their current configuration allows a particular event
* to be generated.
*
* @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a>
* @version $Revision$
*/
public interface EventConstraints {
/**
* Returns true if, at the current time, the named event could be
* generated.
*
* @param eventName the name of the event in question
* @return true if the named event could be generated
*/
boolean eventGeneratable(String eventName);
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/FileEnvironmentField.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/>.
*/
/*
* FileEnvironmentField.java
* Copyright (C) 2010-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.filechooser.FileFilter;
import weka.core.Environment;
import weka.gui.ExtensionFileFilter;
import weka.gui.FileEditor;
import weka.gui.PropertyDialog;
/**
* Widget that displays a label, editable combo box for selecting environment
* variables and a button for brining up a file browser. The user can enter
* arbitrary text, select an environment variable or a combination of both. Any
* variables are resolved (if possible) and resolved values are displayed in a
* tip-text.<p></p>
*
* This class is deprecated - use the version in weka.gui instead.
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision$
*/
@Deprecated
public class FileEnvironmentField extends EnvironmentField {
/** For serialization */
private static final long serialVersionUID = -233731548086207652L;
/** File editor component */
protected FileEditor m_fileEditor = new FileEditor();
/** Dialog to hold the file editor */
protected PropertyDialog m_fileEditorDialog;
/** The button to pop up the file dialog */
protected JButton m_browseBut;
/**
* Constructor
*/
public FileEnvironmentField() {
this("", JFileChooser.OPEN_DIALOG, false);
setEnvironment(Environment.getSystemWide());
}
/**
* Constructor
*
* @param env an Environment object to use
*/
public FileEnvironmentField(Environment env) {
this("", JFileChooser.OPEN_DIALOG, false);
setEnvironment(env);
}
public FileEnvironmentField(String label, Environment env) {
this(label, JFileChooser.OPEN_DIALOG, false);
setEnvironment(env);
}
/**
* Constructor
*
* @param label a label to display alongside the field.
* @param env an Environment object to use.
* @param fileChooserType the type of file chooser to use (either
* JFileChooser.OPEN_DIALOG or JFileChooser.SAVE_DIALOG)
*/
public FileEnvironmentField(String label, Environment env, int fileChooserType) {
this(label, fileChooserType, false);
setEnvironment(env);
}
/**
* Constructor
*
* @param label a label to display alongside the field.
* @param env an Environment object to use.
* @param fileChooserType the type of file chooser to use (either
* JFileChooser.OPEN_DIALOG or JFileChooser.SAVE_DIALOG)
* @param directoriesOnly true if file chooser should allow only directories
* to be selected
*/
public FileEnvironmentField(String label, Environment env,
int fileChooserType, boolean directoriesOnly) {
this(label, fileChooserType, directoriesOnly);
setEnvironment(env);
}
/**
* Constructor
*
* @param label a label to display alongside the field.
* @param fileChooserType the type of file chooser to use (either
* JFileChooser.OPEN_DIALOG or JFileChooser.SAVE_DIALOG)
*/
public FileEnvironmentField(String label, int fileChooserType,
boolean directoriesOnly) {
super(label);
m_fileEditor.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
File selected = (File) m_fileEditor.getValue();
if (selected != null) {
FileEnvironmentField.this.setText(selected.toString());
}
}
});
final JFileChooser embeddedEditor = (JFileChooser) m_fileEditor
.getCustomEditor();
if (directoriesOnly) {
embeddedEditor.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
} else {
embeddedEditor.setFileSelectionMode(JFileChooser.FILES_ONLY);
}
embeddedEditor.setDialogType(fileChooserType);
ExtensionFileFilter ff = new ExtensionFileFilter(".model",
"Serialized Weka classifier (*.model)");
embeddedEditor.addChoosableFileFilter(ff);
m_browseBut = new JButton("Browse...");
m_browseBut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
String modelPath = getText();
if (modelPath != null) {
try {
modelPath = m_env.substitute(modelPath);
} catch (Exception ex) {
}
File toSet = new File(modelPath);
if (toSet.isFile()) {
m_fileEditor.setValue(new File(modelPath));
toSet = toSet.getParentFile();
}
if (toSet.isDirectory()) {
embeddedEditor.setCurrentDirectory(toSet);
}
}
showFileEditor();
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
JPanel bP = new JPanel();
bP.setLayout(new BorderLayout());
// bP.setBorder(BorderFactory.createEmptyBorder(5,0,5,5));
bP.add(m_browseBut, BorderLayout.CENTER);
add(bP, BorderLayout.EAST);
}
/**
* Add a file filter to use
*
* @param toSet the file filter to use
*/
public void addFileFilter(FileFilter toSet) {
JFileChooser embeddedEditor = (JFileChooser) m_fileEditor.getCustomEditor();
embeddedEditor.addChoosableFileFilter(toSet);
}
/**
* Resets the list of choosable file filters.
*/
public void resetFileFilters() {
JFileChooser embeddedEditor = (JFileChooser) m_fileEditor.getCustomEditor();
embeddedEditor.resetChoosableFileFilters();
}
private void showFileEditor() {
if (m_fileEditorDialog == null) {
if (PropertyDialog.getParentDialog(this) != null) {
m_fileEditorDialog = new PropertyDialog(
PropertyDialog.getParentDialog(this), m_fileEditor, -1, -1);
} else {
m_fileEditorDialog = new PropertyDialog(
PropertyDialog.getParentFrame(this), m_fileEditor, -1, -1);
}
}
if (PropertyDialog.getParentDialog(this) != null) {
m_fileEditorDialog.setLocationRelativeTo(PropertyDialog.getParentDialog(this));
} else {
m_fileEditorDialog.setLocationRelativeTo(PropertyDialog.getParentFrame(this));
}
m_fileEditorDialog.setVisible(true);
}
@Override
public void removeNotify() {
super.removeNotify();
if (m_fileEditorDialog != null) {
m_fileEditorDialog.dispose();
m_fileEditorDialog = null;
}
}
/**
* Set the enabled status of the combo box and button
*
* @param enabled true if the combo box and button are to be enabled
*/
@Override
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
m_browseBut.setEnabled(enabled);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/Filter.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/>.
*/
/*
* Filter.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.awt.BorderLayout;
import java.beans.EventSetDescriptor;
import java.io.Serializable;
import java.util.Enumeration;
import java.util.EventObject;
import java.util.Hashtable;
import java.util.Vector;
import javax.swing.JPanel;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.OptionHandler;
import weka.core.SerializedObject;
import weka.core.Utils;
import weka.filters.AllFilter;
import weka.filters.StreamableFilter;
import weka.filters.SupervisedFilter;
import weka.gui.Logger;
/**
* A wrapper bean for Weka filters
*
* @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a>
* @version $Revision$
*/
public class Filter extends JPanel implements BeanCommon, Visible, WekaWrapper,
Serializable, UserRequestAcceptor, TrainingSetListener, TestSetListener,
TrainingSetProducer, TestSetProducer, DataSource, DataSourceListener,
InstanceListener, EventConstraints, ConfigurationProducer {
/** for serialization */
private static final long serialVersionUID = 8249759470189439321L;
protected BeanVisual m_visual = new BeanVisual("Filter", BeanVisual.ICON_PATH
+ "DefaultFilter.gif", BeanVisual.ICON_PATH + "DefaultFilter_animated.gif");
private static int IDLE = 0;
private static int FILTERING_TRAINING = 1;
private static int FILTERING_TEST = 2;
private int m_state = IDLE;
protected transient Thread m_filterThread = null;
private transient Instances m_trainingSet;
private transient Instances m_testingSet;
/**
* Global info for the wrapped filter (if it exists).
*/
protected String m_globalInfo;
/**
* Objects talking to us
*/
private final Hashtable<String, Object> m_listenees = new Hashtable<String, Object>();
/**
* Objects listening for training set events
*/
private final Vector<TrainingSetListener> m_trainingListeners = new Vector<TrainingSetListener>();
/**
* Objects listening for test set events
*/
private final Vector<TestSetListener> m_testListeners = new Vector<TestSetListener>();
/**
* Objects listening for instance events
*/
private final Vector<InstanceListener> m_instanceListeners = new Vector<InstanceListener>();
/**
* Objects listening for data set events
*/
private final Vector<DataSourceListener> m_dataListeners = new Vector<DataSourceListener>();
/**
* The filter to use.
*/
private weka.filters.Filter m_Filter = new AllFilter();
/**
* Instance event object for passing on filtered instance streams
*/
private final InstanceEvent m_ie = new InstanceEvent(this);
/**
* Logging.
*/
private transient Logger m_log = null;
/**
* Counts incoming streamed instances.
*/
private transient int m_instanceCount;
/**
* Global info (if it exists) for the wrapped filter
*
* @return the global info
*/
public String globalInfo() {
return m_globalInfo;
}
public Filter() {
setLayout(new BorderLayout());
add(m_visual, BorderLayout.CENTER);
setFilter(m_Filter);
}
/**
* Set a custom (descriptive) name for this bean
*
* @param name the name to use
*/
@Override
public void setCustomName(String name) {
m_visual.setText(name);
}
/**
* Get the custom (descriptive) name for this bean (if one has been set)
*
* @return the custom name (or the default name)
*/
@Override
public String getCustomName() {
return m_visual.getText();
}
/**
* Set the filter to be wrapped by this bean
*
* @param c a <code>weka.filters.Filter</code> value
*/
public void setFilter(weka.filters.Filter c) {
boolean loadImages = true;
if (c.getClass().getName().compareTo(m_Filter.getClass().getName()) == 0) {
loadImages = false;
}
m_Filter = c;
String filterName = c.getClass().toString();
filterName = filterName.substring(filterName.indexOf('.') + 1,
filterName.length());
if (loadImages) {
if (m_Filter instanceof Visible) {
m_visual = ((Visible) m_Filter).getVisual();
} else {
if (!m_visual.loadIcons(BeanVisual.ICON_PATH + filterName + ".gif",
BeanVisual.ICON_PATH + filterName + "_animated.gif")) {
useDefaultVisual();
}
}
}
m_visual.setText(filterName.substring(filterName.lastIndexOf('.') + 1,
filterName.length()));
if (m_Filter instanceof LogWriter && m_log != null) {
((LogWriter) m_Filter).setLog(m_log);
}
if (!(m_Filter instanceof StreamableFilter)
&& (m_listenees.containsKey("instance"))) {
if (m_log != null) {
m_log.logMessage("[Filter] " + statusMessagePrefix() + " WARNING : "
+ m_Filter.getClass().getName() + " is not an incremental filter");
m_log.statusMessage(statusMessagePrefix()
+ "WARNING: Not an incremental filter.");
}
}
// get global info
m_globalInfo = KnowledgeFlowApp.getGlobalInfo(m_Filter);
}
public weka.filters.Filter getFilter() {
return m_Filter;
}
/**
* Set the filter to be wrapped by this bean
*
* @param algorithm a weka.filters.Filter
* @exception IllegalArgumentException if an error occurs
*/
@Override
public void setWrappedAlgorithm(Object algorithm) {
if (!(algorithm instanceof weka.filters.Filter)) {
throw new IllegalArgumentException(algorithm.getClass() + " : incorrect "
+ "type of algorithm (Filter)");
}
setFilter((weka.filters.Filter) algorithm);
}
/**
* Get the filter wrapped by this bean
*
* @return an <code>Object</code> value
*/
@Override
public Object getWrappedAlgorithm() {
return getFilter();
}
/**
* Accept a training set
*
* @param e a <code>TrainingSetEvent</code> value
*/
@Override
public void acceptTrainingSet(TrainingSetEvent e) {
processTrainingOrDataSourceEvents(e);
}
private boolean m_structurePassedOn = false;
/**
* Accept an instance for processing by StreamableFilters only
*
* @param e an <code>InstanceEvent</code> value
*/
@Override
public void acceptInstance(InstanceEvent e) {
// to do!
if (m_filterThread != null) {
String messg = "[Filter] " + statusMessagePrefix()
+ " is currently batch processing!";
if (m_log != null) {
m_log.logMessage(messg);
m_log.statusMessage(statusMessagePrefix()
+ "WARNING: Filter is currently batch processing.");
} else {
System.err.println(messg);
}
return;
}
if (!(m_Filter instanceof StreamableFilter)) {
stop(); // stop all processing
if (m_log != null) {
m_log.logMessage("[Filter] " + statusMessagePrefix() + " ERROR : "
+ m_Filter.getClass().getName()
+ "can't process streamed instances; can't continue");
m_log.statusMessage(statusMessagePrefix()
+ "ERROR: Can't process streamed instances; can't continue.");
}
return;
}
if (e.getStatus() == InstanceEvent.FORMAT_AVAILABLE) {
try {
m_instanceCount = 0;
// notifyInstanceListeners(e);
// Instances dataset = e.getInstance().dataset();
Instances dataset = e.getStructure();
if (m_Filter instanceof SupervisedFilter) {
// defualt to last column if no class is set
if (dataset.classIndex() < 0) {
dataset.setClassIndex(dataset.numAttributes() - 1);
}
}
// initialize filter
m_Filter.setInputFormat(dataset);
// attempt to determine post-filtering
// structure. If successful this can be passed on to instance
// listeners as a new FORMAT_AVAILABLE event.
m_structurePassedOn = false;
try {
if (m_Filter.isOutputFormatDefined()) {
// System.err.println("Filter - passing on output format...");
// System.err.println(m_Filter.getOutputFormat());
m_ie.setStructure(new Instances(m_Filter.getOutputFormat(), 0));
m_ie.m_formatNotificationOnly = e.m_formatNotificationOnly;
notifyInstanceListeners(m_ie);
m_structurePassedOn = true;
}
} catch (Exception ex) {
stop(); // stop all processing
if (m_log != null) {
m_log
.logMessage("[Filter] " + statusMessagePrefix()
+ " Error in obtaining post-filter structure. "
+ ex.getMessage());
m_log.statusMessage(statusMessagePrefix()
+ "ERROR (See log for details).");
} else {
System.err.println("[Filter] " + statusMessagePrefix()
+ " Error in obtaining post-filter structure");
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return;
}
if (e.getStatus() == InstanceEvent.BATCH_FINISHED
|| e.getInstance() == null) {
// get the last instance (if available)
try {
if (m_log != null) {
m_log.statusMessage(statusMessagePrefix() + "Stream finished.");
}
if (e.getInstance() != null) {
if (m_Filter.input(e.getInstance())) {
Instance filteredInstance = m_Filter.output();
if (filteredInstance != null) {
if (!m_structurePassedOn) {
// pass on the new structure first
m_ie.setStructure(new Instances(filteredInstance.dataset(), 0));
notifyInstanceListeners(m_ie);
m_structurePassedOn = true;
}
m_ie.setInstance(filteredInstance);
// if there are instances pending for output don't want to send
// a batch finisehd at this point...
// System.err.println("Filter - in batch finisehd...");
if (m_Filter.batchFinished() && m_Filter.numPendingOutput() > 0) {
m_ie.setStatus(InstanceEvent.INSTANCE_AVAILABLE);
} else {
m_ie.setStatus(e.getStatus());
}
notifyInstanceListeners(m_ie);
}
}
}
if (m_log != null) {
m_log.statusMessage(statusMessagePrefix() + "Finished.");
}
} catch (Exception ex) {
stop(); // stop all processing
if (m_log != null) {
m_log.logMessage("[Filter] " + statusMessagePrefix()
+ ex.getMessage());
m_log.statusMessage(statusMessagePrefix()
+ "ERROR (See log for details).");
}
ex.printStackTrace();
}
// check for any pending instances that we might need to pass on
try {
if (m_Filter.batchFinished() && m_Filter.numPendingOutput() > 0) {
if (m_log != null) {
m_log.statusMessage(statusMessagePrefix()
+ "Passing on pending instances...");
}
Instance filteredInstance = m_Filter.output();
if (filteredInstance != null) {
if (!m_structurePassedOn) {
// pass on the new structure first
m_ie.setStructure((Instances) (new SerializedObject(
filteredInstance.dataset()).getObject()));
notifyInstanceListeners(m_ie);
m_structurePassedOn = true;
}
m_ie.setInstance(filteredInstance);
// TODO here is the problem I think
m_ie.setStatus(InstanceEvent.INSTANCE_AVAILABLE);
notifyInstanceListeners(m_ie);
}
while (m_Filter.numPendingOutput() > 0) {
filteredInstance = m_Filter.output();
if (filteredInstance.dataset().checkForStringAttributes()) {
for (int i = 0; i < filteredInstance.dataset().numAttributes(); i++) {
if (filteredInstance.dataset().attribute(i).isString()
&& !filteredInstance.isMissing(i)) {
String val = filteredInstance.stringValue(i);
m_ie.getStructure().attribute(i).setStringValue(val);
filteredInstance.setValue(i, 0);
}
}
}
filteredInstance.setDataset(m_ie.getStructure());
m_ie.setInstance(filteredInstance);
// System.err.println("Filter - sending pending...");
if (m_Filter.numPendingOutput() == 0) {
m_ie.setStatus(InstanceEvent.BATCH_FINISHED);
} else {
m_ie.setStatus(InstanceEvent.INSTANCE_AVAILABLE);
}
notifyInstanceListeners(m_ie);
}
if (m_log != null) {
m_log.statusMessage(statusMessagePrefix() + "Finished.");
}
}
} catch (Exception ex) {
stop(); // stop all processing
if (m_log != null) {
m_log.logMessage("[Filter] " + statusMessagePrefix() + ex.toString());
m_log.statusMessage(statusMessagePrefix()
+ "ERROR (See log for details.");
}
ex.printStackTrace();
}
} else {
// pass instance through the filter
try {
if (!m_Filter.input(e.getInstance())) {
// System.err.println("Filter - inputing instance into filter...");
/*
* if (m_log != null) {
* m_log.logMessage("ERROR : filter not ready to output instance"); }
*/
// quietly return. Filter might be able to output some instances
// once the batch is finished.
return;
}
// collect output instance.
Instance filteredInstance = m_Filter.output();
if (filteredInstance == null) {
return;
}
m_instanceCount++;
if (!m_structurePassedOn) {
// pass on the new structure first
m_ie.setStructure(new Instances(filteredInstance.dataset(), 0));
notifyInstanceListeners(m_ie);
m_structurePassedOn = true;
}
filteredInstance.setDataset(m_ie.getStructure());
if (filteredInstance.dataset().checkForStringAttributes()) {
for (int i = 0; i < filteredInstance.dataset().numAttributes(); i++) {
if (filteredInstance.dataset().attribute(i).isString()
&& !filteredInstance.isMissing(i)) {
String val = filteredInstance.stringValue(i);
filteredInstance.dataset().attribute(i).setStringValue(val);
filteredInstance.setValue(i, 0);
}
}
}
m_ie.setInstance(filteredInstance);
m_ie.setStatus(e.getStatus());
if (m_log != null && (m_instanceCount % 10000 == 0)) {
m_log.statusMessage(statusMessagePrefix() + "Received "
+ m_instanceCount + " instances.");
}
notifyInstanceListeners(m_ie);
} catch (Exception ex) {
stop(); // stop all processing
if (m_log != null) {
m_log.logMessage("[Filter] " + statusMessagePrefix() + ex.toString());
m_log.statusMessage(statusMessagePrefix()
+ "ERROR (See log for details).");
}
ex.printStackTrace();
}
}
}
private void processTrainingOrDataSourceEvents(final EventObject e) {
boolean structureOnly = false;
if (e instanceof DataSetEvent) {
structureOnly = ((DataSetEvent) e).isStructureOnly();
if (structureOnly) {
notifyDataOrTrainingListeners(e);
}
}
if (e instanceof TrainingSetEvent) {
structureOnly = ((TrainingSetEvent) e).isStructureOnly();
if (structureOnly) {
notifyDataOrTrainingListeners(e);
}
}
if (structureOnly && !(m_Filter instanceof StreamableFilter)) {
return; // nothing can be done
}
if (m_filterThread == null) {
try {
if (m_state == IDLE) {
synchronized (this) {
m_state = FILTERING_TRAINING;
}
m_trainingSet = (e instanceof TrainingSetEvent) ? ((TrainingSetEvent) e)
.getTrainingSet() : ((DataSetEvent) e).getDataSet();
// final String oldText = m_visual.getText();
m_filterThread = new Thread() {
@SuppressWarnings("deprecation")
@Override
public void run() {
try {
if (m_trainingSet != null) {
m_visual.setAnimated();
// m_visual.setText("Filtering training data...");
if (m_log != null) {
m_log.statusMessage(statusMessagePrefix()
+ "Filtering training data ("
+ m_trainingSet.relationName() + ")");
}
m_Filter.setInputFormat(m_trainingSet);
Instances filteredData = weka.filters.Filter.useFilter(
m_trainingSet, m_Filter);
// m_visual.setText(oldText);
m_visual.setStatic();
EventObject ne;
if (e instanceof TrainingSetEvent) {
ne = new TrainingSetEvent(weka.gui.beans.Filter.this,
filteredData);
((TrainingSetEvent) ne).m_setNumber = ((TrainingSetEvent) e).m_setNumber;
((TrainingSetEvent) ne).m_maxSetNumber = ((TrainingSetEvent) e).m_maxSetNumber;
} else {
ne = new DataSetEvent(weka.gui.beans.Filter.this,
filteredData);
}
notifyDataOrTrainingListeners(ne);
}
} catch (Exception ex) {
ex.printStackTrace();
if (m_log != null) {
m_log.logMessage("[Filter] " + statusMessagePrefix()
+ ex.getMessage());
m_log.statusMessage(statusMessagePrefix()
+ "ERROR (See log for details).");
// m_log.statusMessage("Problem filtering: see log for details.");
}
Filter.this.stop(); // stop all processing
} finally {
// m_visual.setText(oldText);
m_visual.setStatic();
m_state = IDLE;
if (isInterrupted()) {
m_trainingSet = null;
if (m_log != null) {
m_log.logMessage("[Filter] " + statusMessagePrefix()
+ " training set interrupted!");
m_log.statusMessage(statusMessagePrefix() + "INTERRUPTED");
}
} else {
if (m_log != null) {
m_log.statusMessage(statusMessagePrefix() + "Finished.");
}
}
block(false);
m_filterThread = null;
}
}
};
m_filterThread.setPriority(Thread.MIN_PRIORITY);
m_filterThread.start();
block(true);
m_filterThread = null;
m_state = IDLE;
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
/**
* Accept a test set
*
* @param e a <code>TestSetEvent</code> value
*/
@Override
public void acceptTestSet(final TestSetEvent e) {
if (e.isStructureOnly()) {
notifyTestListeners(e);
}
if (m_trainingSet != null && m_trainingSet.equalHeaders(e.getTestSet())
&& m_filterThread == null) {
try {
if (m_state == IDLE) {
m_state = FILTERING_TEST;
}
m_testingSet = e.getTestSet();
// final String oldText = m_visual.getText();
m_filterThread = new Thread() {
@SuppressWarnings("deprecation")
@Override
public void run() {
try {
if (m_testingSet != null) {
m_visual.setAnimated();
// m_visual.setText("Filtering test data...");
if (m_log != null) {
m_log.statusMessage(statusMessagePrefix()
+ "Filtering test data (" + m_testingSet.relationName()
+ ")");
}
Instances filteredTest = weka.filters.Filter.useFilter(
m_testingSet, m_Filter);
// m_visual.setText(oldText);
m_visual.setStatic();
TestSetEvent ne = new TestSetEvent(weka.gui.beans.Filter.this,
filteredTest);
ne.m_setNumber = e.m_setNumber;
ne.m_maxSetNumber = e.m_maxSetNumber;
notifyTestListeners(ne);
}
} catch (Exception ex) {
ex.printStackTrace();
if (m_log != null) {
m_log.logMessage("[Filter] " + statusMessagePrefix()
+ ex.getMessage());
m_log.statusMessage(statusMessagePrefix()
+ "ERROR (See log for details).");
}
Filter.this.stop();
} finally {
// m_visual.setText(oldText);
m_visual.setStatic();
m_state = IDLE;
if (isInterrupted()) {
m_trainingSet = null;
if (m_log != null) {
m_log.logMessage("[Filter] " + statusMessagePrefix()
+ " test set interrupted!");
m_log.statusMessage(statusMessagePrefix() + "INTERRUPTED");
// m_log.statusMessage("OK");
}
} else {
if (m_log != null) {
m_log.statusMessage(statusMessagePrefix() + "Finished.");
}
}
block(false);
m_filterThread = null;
}
}
};
m_filterThread.setPriority(Thread.MIN_PRIORITY);
m_filterThread.start();
block(true);
m_filterThread = null;
m_state = IDLE;
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
/**
* Accept a data set
*
* @param e a <code>DataSetEvent</code> value
*/
@Override
public void acceptDataSet(DataSetEvent e) {
processTrainingOrDataSourceEvents(e);
}
/**
* Set the visual appearance of this bean
*
* @param newVisual a <code>BeanVisual</code> value
*/
@Override
public void setVisual(BeanVisual newVisual) {
m_visual = newVisual;
}
/**
* Get the visual appearance of this bean
*
* @return a <code>BeanVisual</code> value
*/
@Override
public BeanVisual getVisual() {
return m_visual;
}
/**
* Use the default visual appearance
*/
@Override
public void useDefaultVisual() {
m_visual.loadIcons(BeanVisual.ICON_PATH + "DefaultFilter.gif",
BeanVisual.ICON_PATH + "DefaultFilter_animated.gif");
}
/**
* Add a training set listener
*
* @param tsl a <code>TrainingSetListener</code> value
*/
@Override
public synchronized void addTrainingSetListener(TrainingSetListener tsl) {
m_trainingListeners.addElement(tsl);
}
/**
* Remove a training set listener
*
* @param tsl a <code>TrainingSetListener</code> value
*/
@Override
public synchronized void removeTrainingSetListener(TrainingSetListener tsl) {
m_trainingListeners.removeElement(tsl);
}
/**
* Add a test set listener
*
* @param tsl a <code>TestSetListener</code> value
*/
@Override
public synchronized void addTestSetListener(TestSetListener tsl) {
m_testListeners.addElement(tsl);
}
/**
* Remove a test set listener
*
* @param tsl a <code>TestSetListener</code> value
*/
@Override
public synchronized void removeTestSetListener(TestSetListener tsl) {
m_testListeners.removeElement(tsl);
}
/**
* Add a data source listener
*
* @param dsl a <code>DataSourceListener</code> value
*/
@Override
public synchronized void addDataSourceListener(DataSourceListener dsl) {
m_dataListeners.addElement(dsl);
}
/**
* Remove a data source listener
*
* @param dsl a <code>DataSourceListener</code> value
*/
@Override
public synchronized void removeDataSourceListener(DataSourceListener dsl) {
m_dataListeners.remove(dsl);
}
/**
* Add an instance listener
*
* @param tsl an <code>InstanceListener</code> value
*/
@Override
public synchronized void addInstanceListener(InstanceListener tsl) {
m_instanceListeners.addElement(tsl);
}
/**
* Remove an instance listener
*
* @param tsl an <code>InstanceListener</code> value
*/
@Override
public synchronized void removeInstanceListener(InstanceListener tsl) {
m_instanceListeners.removeElement(tsl);
}
/**
* We don't have to keep track of configuration listeners (see the
* documentation for ConfigurationListener/ConfigurationEvent).
*
* @param cl a ConfigurationListener.
*/
@Override
public synchronized void addConfigurationListener(ConfigurationListener cl) {
}
/**
* We don't have to keep track of configuration listeners (see the
* documentation for ConfigurationListener/ConfigurationEvent).
*
* @param cl a ConfigurationListener.
*/
@Override
public synchronized void removeConfigurationListener(ConfigurationListener cl) {
}
private void notifyDataOrTrainingListeners(EventObject ce) {
Vector<?> l;
synchronized (this) {
l = (ce instanceof TrainingSetEvent) ? (Vector<?>) m_trainingListeners
.clone() : (Vector<?>) m_dataListeners.clone();
}
if (l.size() > 0) {
for (int i = 0; i < l.size(); i++) {
if (ce instanceof TrainingSetEvent) {
((TrainingSetListener) l.elementAt(i))
.acceptTrainingSet((TrainingSetEvent) ce);
} else {
((DataSourceListener) l.elementAt(i))
.acceptDataSet((DataSetEvent) ce);
}
}
}
}
@SuppressWarnings("unchecked")
private void notifyTestListeners(TestSetEvent ce) {
Vector<TestSetListener> l;
synchronized (this) {
l = (Vector<TestSetListener>) m_testListeners.clone();
}
if (l.size() > 0) {
for (int i = 0; i < l.size(); i++) {
l.elementAt(i).acceptTestSet(ce);
}
}
}
@SuppressWarnings("unchecked")
protected void notifyInstanceListeners(InstanceEvent tse) {
Vector<InstanceListener> l;
synchronized (this) {
l = (Vector<InstanceListener>) m_instanceListeners.clone();
}
if (l.size() > 0) {
for (int i = 0; i < l.size(); i++) {
// System.err.println("Notifying instance listeners "
// +"(Filter)");
l.elementAt(i).acceptInstance(tse);
}
}
}
/**
* Returns true if, at this time, the object will accept a connection with
* respect to the supplied event name
*
* @param eventName the event
* @return true if the object will accept a connection
*/
@Override
public boolean connectionAllowed(String eventName) {
if (m_listenees.containsKey(eventName)) {
return false;
}
/*
* reject a test event if we don't have a training or data set event if
* (eventName.compareTo("testSet") == 0) { if
* (!m_listenees.containsKey("trainingSet") &&
* !m_listenees.containsKey("dataSet")) { return false; } }
*/
// will need to reject train/test listener if we have a
// data source listener and vis versa
if (m_listenees.containsKey("dataSet")
&& (eventName.compareTo("trainingSet") == 0
|| eventName.compareTo("testSet") == 0 || eventName
.compareTo("instance") == 0)) {
return false;
}
if ((m_listenees.containsKey("trainingSet") || m_listenees
.containsKey("testSet"))
&& (eventName.compareTo("dataSet") == 0 || eventName
.compareTo("instance") == 0)) {
return false;
}
if (m_listenees.containsKey("instance")
&& (eventName.compareTo("trainingSet") == 0
|| eventName.compareTo("testSet") == 0 || eventName
.compareTo("dataSet") == 0)) {
return false;
}
// reject an instance event connection if our filter isn't
// streamable
if (eventName.compareTo("instance") == 0
&& !(m_Filter instanceof StreamableFilter)) {
return false;
}
return true;
}
/**
* Returns true if, at this time, the object will accept a connection
* according to the supplied EventSetDescriptor
*
* @param esd the EventSetDescriptor
* @return true if the object will accept a connection
*/
@Override
public boolean connectionAllowed(EventSetDescriptor esd) {
return connectionAllowed(esd.getName());
}
/**
* Notify this object that it has been registered as a listener with a source
* with respect to the supplied event name
*
* @param eventName
* @param source the source with which this object has been registered as a
* listener
*/
@Override
public synchronized void connectionNotification(String eventName,
Object source) {
if (connectionAllowed(eventName)) {
m_listenees.put(eventName, source);
if (m_Filter instanceof ConnectionNotificationConsumer) {
((ConnectionNotificationConsumer) m_Filter).connectionNotification(
eventName, source);
}
}
}
/**
* Notify this object that it has been deregistered as a listener with a
* source with respect to the supplied event name
*
* @param eventName the event
* @param source the source with which this object has been registered as a
* listener
*/
@Override
public synchronized void disconnectionNotification(String eventName,
Object source) {
if (m_Filter instanceof ConnectionNotificationConsumer) {
((ConnectionNotificationConsumer) m_Filter).disconnectionNotification(
eventName, source);
}
m_listenees.remove(eventName);
}
/**
* Function used to stop code that calls acceptTrainingSet, acceptTestSet, or
* acceptDataSet. This is needed as filtering is performed inside a separate
* thread of execution.
*
* @param tf a <code>boolean</code> value
*/
private synchronized void block(boolean tf) {
if (tf) {
try {
// only block if thread is still doing something useful!
if (m_filterThread.isAlive() && m_state != IDLE) {
wait();
}
} catch (InterruptedException ex) {
}
} else {
notifyAll();
}
}
/**
* Stop all action if possible
*/
@SuppressWarnings("deprecation")
@Override
public void stop() {
// tell all listenees (upstream beans) to stop
Enumeration<String> en = m_listenees.keys();
while (en.hasMoreElements()) {
Object tempO = m_listenees.get(en.nextElement());
if (tempO instanceof BeanCommon) {
((BeanCommon) tempO).stop();
}
}
// stop the filter thread
if (m_filterThread != null) {
m_filterThread.interrupt();
m_filterThread.stop();
m_filterThread = null;
m_visual.setStatic();
}
}
/**
* Returns true if. at this time, the bean is busy with some (i.e. perhaps a
* worker thread is performing some calculation).
*
* @return true if the bean is busy.
*/
@Override
public boolean isBusy() {
return (m_filterThread != null);
}
/**
* Set a logger
*
* @param logger a <code>Logger</code> value
*/
@Override
public void setLog(Logger logger) {
m_log = logger;
if (m_Filter != null && m_Filter instanceof LogWriter) {
((LogWriter) m_Filter).setLog(m_log);
}
}
/**
* Return an enumeration of user requests
*
* @return an <code>Enumeration</code> value
*/
@Override
public Enumeration<String> enumerateRequests() {
Vector<String> newVector = new Vector<String>(0);
if (m_filterThread != null) {
newVector.addElement("Stop");
}
return newVector.elements();
}
/**
* Perform the named request
*
* @param request a <code>String</code> value
* @exception IllegalArgumentException if an error occurs
*/
@Override
public void performRequest(String request) {
if (request.compareTo("Stop") == 0) {
stop();
} else {
throw new IllegalArgumentException(request + " not supported (Filter)");
}
}
/**
* Returns true, if at the current time, the named event could be generated.
* Assumes that supplied event names are names of events that could be
* generated by this bean.
*
* @param eventName the name of the event in question
* @return true if the named event could be generated at this point in time
*/
@Override
public boolean eventGeneratable(String eventName) {
if (eventName.equals("configuration") && m_Filter != null) {
return true;
}
// can't generate the named even if we are not receiving it as an
// input!
if (!m_listenees.containsKey(eventName)) {
return false;
}
Object source = m_listenees.get(eventName);
if (source instanceof EventConstraints) {
if (!((EventConstraints) source).eventGeneratable(eventName)) {
return false;
}
}
if (eventName.compareTo("instance") == 0) {
if (!(m_Filter instanceof StreamableFilter)) {
return false;
}
}
return true;
}
private String statusMessagePrefix() {
return getCustomName()
+ "$"
+ hashCode()
+ "|"
+ ((m_Filter instanceof OptionHandler && Utils.joinOptions(
((OptionHandler) m_Filter).getOptions()).length() > 0) ? Utils
.joinOptions(((OptionHandler) m_Filter).getOptions()) + "|" : "");
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/FilterBeanInfo.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/>.
*/
/*
* FilterBeanInfo.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.beans.BeanDescriptor;
import java.beans.EventSetDescriptor;
import java.beans.SimpleBeanInfo;
/**
* Bean info class for the Filter bean
*
* @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a>
* @version $Revision$
*/
public class FilterBeanInfo extends SimpleBeanInfo {
/**
* Get the event set descriptors for this bean
*
* @return an <code>EventSetDescriptor[]</code> value
*/
public EventSetDescriptor [] getEventSetDescriptors() {
try {
EventSetDescriptor [] esds = {
new EventSetDescriptor(TrainingSetProducer.class,
"trainingSet",
TrainingSetListener.class,
"acceptTrainingSet"),
new EventSetDescriptor(TestSetProducer.class,
"testSet",
TestSetListener.class,
"acceptTestSet"),
new EventSetDescriptor(DataSource.class,
"dataSet",
DataSourceListener.class,
"acceptDataSet"),
new EventSetDescriptor(DataSource.class,
"instance",
InstanceListener.class,
"acceptInstance"),
new EventSetDescriptor(Filter.class,
"configuration",
ConfigurationListener.class,
"acceptConfiguration")
};
return esds;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
/**
* Get the bean descriptor for this bean
*
* @return a <code>BeanDescriptor</code> value
*/
public BeanDescriptor getBeanDescriptor() {
return new BeanDescriptor(weka.gui.beans.Filter.class,
FilterCustomizer.class);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/FilterCustomizer.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/>.
*/
/*
* FilterCustomizer.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JPanel;
import weka.gui.GenericObjectEditor;
import weka.gui.PropertySheetPanel;
/**
* GUI customizer for the filter bean
*
* @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a>
* @version $Revision$
*/
public class FilterCustomizer extends JPanel implements BeanCustomizer,
CustomizerCloseRequester {
/** for serialization */
private static final long serialVersionUID = 2049895469240109738L;
static {
GenericObjectEditor.registerEditors();
}
private final PropertyChangeSupport m_pcSupport = new PropertyChangeSupport(
this);
private weka.gui.beans.Filter m_filter;
/*
* private GenericObjectEditor m_filterEditor = new GenericObjectEditor(true);
*/
/** Backup if user presses cancel */
private weka.filters.Filter m_backup;
private final PropertySheetPanel m_filterEditor = new PropertySheetPanel();
private Window m_parentWindow;
private ModifyListener m_modifyListener;
public FilterCustomizer() {
m_filterEditor
.setBorder(BorderFactory.createTitledBorder("Filter options"));
setLayout(new BorderLayout());
add(m_filterEditor, BorderLayout.CENTER);
JPanel butHolder = new JPanel();
butHolder.setLayout(new GridLayout(1, 2));
JButton OKBut = new JButton("OK");
OKBut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Tell the editor that we are closing under an OK condition
// so that it can pass on the message to any customizer that
// might be in use
m_filterEditor.closingOK();
if (m_modifyListener != null) {
m_modifyListener.setModifiedStatus(FilterCustomizer.this, true);
}
m_parentWindow.dispose();
}
});
JButton CancelBut = new JButton("Cancel");
CancelBut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Tell the editor that we are closing under a CANCEL condition
// so that it can pass on the message to any customizer that
// might be in use
m_filterEditor.closingCancel();
// cancel requested, so revert to backup and then
// close the dialog
if (m_backup != null) {
m_filter.setFilter(m_backup);
}
if (m_modifyListener != null) {
m_modifyListener.setModifiedStatus(FilterCustomizer.this, false);
}
m_parentWindow.dispose();
}
});
butHolder.add(OKBut);
butHolder.add(CancelBut);
add(butHolder, BorderLayout.SOUTH);
}
/**
* Set the filter bean to be edited
*
* @param object a Filter bean
*/
@Override
public void setObject(Object object) {
m_filter = (weka.gui.beans.Filter) object;
try {
m_backup = (weka.filters.Filter) GenericObjectEditor.makeCopy(m_filter
.getFilter());
} catch (Exception ex) {
// ignore
}
m_filterEditor.setTarget(m_filter.getFilter());
}
/**
* Add a property change listener
*
* @param pcl a <code>PropertyChangeListener</code> value
*/
@Override
public void addPropertyChangeListener(PropertyChangeListener pcl) {
m_pcSupport.addPropertyChangeListener(pcl);
}
/**
* Remove a property change listener
*
* @param pcl a <code>PropertyChangeListener</code> value
*/
@Override
public void removePropertyChangeListener(PropertyChangeListener pcl) {
m_pcSupport.removePropertyChangeListener(pcl);
}
@Override
public void setParentWindow(Window parent) {
m_parentWindow = parent;
}
@Override
public void setModifiedListener(ModifyListener l) {
m_modifyListener = l;
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/FlowByExpression.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/>.
*/
/*
* FlowByExpression.java
* Copyright (C) 2011-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.awt.BorderLayout;
import java.beans.EventSetDescriptor;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import javax.swing.JPanel;
import javax.swing.tree.DefaultMutableTreeNode;
import weka.core.Attribute;
import weka.core.Environment;
import weka.core.EnvironmentHandler;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.Utils;
import weka.gui.Logger;
/**
* A bean that splits incoming instances (or instance streams) according to the
* evaluation of a logical expression. The expression can test the values of one
* or more incoming attributes. The test can involve constants or comparing one
* attribute's values to another. Inequalities along with string operations such
* as contains, starts-with, ends-with and regular expressions may be used as
* operators.
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision$
*/
@KFStep(category = "Flow", toolTipText = "Route instances according to a boolean expression")
public class FlowByExpression extends JPanel implements BeanCommon, Visible,
Serializable, InstanceListener, TrainingSetListener, TestSetListener,
DataSourceListener, EventConstraints, EnvironmentHandler, DataSource,
StructureProducer {
/** Added ID to avoid warning */
private static final long serialVersionUID = 2492050246494259885L;
/**
* Abstract base class for parts of a boolean expression.
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
*/
protected static abstract class ExpressionNode implements Serializable {
/** For serialization */
private static final long serialVersionUID = -8427857202322768762L;
/** boolean operator for combining with result so far */
protected boolean m_isAnOr;
/** is this node negated? */
protected boolean m_isNegated;
/** Environment variables */
protected transient Environment m_env;
/** Whether to show the combination operator in the textual representation */
protected boolean m_showAndOr = true;
/**
* Set whether this node is to be OR'ed to the result so far
*
* @param isOr true if this node is to be OR'd
*/
public void setIsOr(boolean isOr) {
m_isAnOr = isOr;
}
/**
* Get whether this node is to be OR'ed
*
* @return true if this node is to be OR'ed with the result so far
*/
public boolean isOr() {
return m_isAnOr;
}
/**
* Get whether this node is negated.
*
* @return
*/
public boolean isNegated() {
return m_isNegated;
}
/**
* Set whether this node is negated
*
* @param negated true if this node is negated
*/
public void setNegated(boolean negated) {
m_isNegated = negated;
}
/**
* Set whether to show the combination operator in the textual description
*
* @param show true if the combination operator is to be shown
*/
public void setShowAndOr(boolean show) {
m_showAndOr = show;
}
/**
* Initialize the node
*
* @param structure the structure of the incoming instances
* @param env Environment variables
*/
public void init(Instances structure, Environment env) {
m_env = env;
}
/**
* Evaluate this node and combine with the result so far
*
* @param inst the incoming instance to evalute with
* @param result the result to combine with
* @return the result after combining with this node
*/
public abstract boolean evaluate(Instance inst, boolean result);
/**
* Get the internal representation of this node
*
* @param buff the string buffer to append to
*/
protected abstract void toStringInternal(StringBuffer buff);
/**
* Get the display representation of this node
*
* @param buff the string buffer to append to
*/
public abstract void toStringDisplay(StringBuffer buff);
/**
* Parse and initialize from the internal representation
*
* @param expression the expression to parse in internal representation
* @return the remaining parts of the expression after parsing and removing
* the part for this node
*/
protected abstract String parseFromInternal(String expression);
/**
* Get a DefaultMutableTreeNode for this node
*
* @param parent the parent of this node (if any)
* @return the DefaultMutableTreeNode for this node
*/
public abstract DefaultMutableTreeNode toJTree(DefaultMutableTreeNode parent);
}
/**
* An expression node that encloses other expression nodes in brackets
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
*/
protected static class BracketNode extends ExpressionNode implements
Serializable {
/** For serialization */
private static final long serialVersionUID = 8732159083173001115L;
protected List<ExpressionNode> m_children = new ArrayList<ExpressionNode>();
@Override
public void init(Instances structure, Environment env) {
super.init(structure, env);
for (ExpressionNode n : m_children) {
n.init(structure, env);
}
}
@Override
public boolean evaluate(Instance inst, boolean result) {
boolean thisNode = true;
if (m_children.size() > 0) {
for (ExpressionNode n : m_children) {
thisNode = n.evaluate(inst, thisNode);
}
if (isNegated()) {
thisNode = !thisNode;
}
}
return (isOr() ? (result || thisNode) : (result && thisNode));
}
/**
* Add a child to this bracket node
*
* @param child the ExpressionNode to add
*/
public void addChild(ExpressionNode child) {
m_children.add(child);
if (m_children.size() > 0) {
m_children.get(0).setShowAndOr(false);
}
}
/**
* Remove a child from this bracket node
*
* @param child the ExpressionNode to remove
*/
public void removeChild(ExpressionNode child) {
m_children.remove(child);
if (m_children.size() > 0) {
m_children.get(0).setShowAndOr(false);
}
}
@Override
public String toString() {
// just the representation of this node (suitable for the abbreviated
// JTree node label
String result = "( )";
if (isNegated()) {
result = "!" + result;
}
if (m_showAndOr) {
if (m_isAnOr) {
result = "|| " + result;
} else {
result = "&& " + result;
}
}
return result;
}
@Override
public DefaultMutableTreeNode toJTree(DefaultMutableTreeNode parent) {
DefaultMutableTreeNode current = new DefaultMutableTreeNode(this);
if (parent != null) {
parent.add(current);
}
for (ExpressionNode child : m_children) {
child.toJTree(current);
}
return current;
}
private void toString(StringBuffer buff, boolean internal) {
if (m_children.size() >= 0) {
if (internal || m_showAndOr) {
if (m_isAnOr) {
buff.append("|| ");
} else {
buff.append("&& ");
}
}
if (isNegated()) {
buff.append("!");
}
buff.append("(");
int count = 0;
for (ExpressionNode child : m_children) {
if (internal) {
child.toStringInternal(buff);
} else {
child.toStringDisplay(buff);
}
count++;
if (count != m_children.size()) {
buff.append(" ");
}
}
buff.append(")");
}
}
@Override
public void toStringDisplay(StringBuffer buff) {
toString(buff, false);
}
@Override
protected void toStringInternal(StringBuffer buff) {
toString(buff, true);
}
@Override
protected String parseFromInternal(String expression) {
if (expression.startsWith("|| ")) {
m_isAnOr = true;
}
if (expression.startsWith("|| ") || expression.startsWith("&& ")) {
expression = expression.substring(3, expression.length());
}
if (expression.charAt(0) == '!') {
setNegated(true);
expression = expression.substring(1, expression.length());
}
if (expression.charAt(0) != '(') {
throw new IllegalArgumentException(
"Malformed expression! Was expecting a \"(\"");
}
expression = expression.substring(1, expression.length());
while (expression.charAt(0) != ')') {
int offset = 3;
if (expression.charAt(offset) == '(') {
ExpressionNode child = new BracketNode();
expression = child.parseFromInternal(expression);
m_children.add(child);
} else {
// must be an ExpressionClause
ExpressionNode child = new ExpressionClause();
expression = child.parseFromInternal(expression);
m_children.add(child);
}
}
if (m_children.size() > 0) {
m_children.get(0).setShowAndOr(false);
}
return expression;
}
}
protected static class ExpressionClause extends ExpressionNode implements
Serializable {
/** For serialization */
private static final long serialVersionUID = 2754006654981248325L;
/** The operator for this expression */
protected ExpressionType m_operator;
/** The name of the lhs attribute */
protected String m_lhsAttributeName;
/** The index of the lhs attribute */
protected int m_lhsAttIndex = -1;
/** The rhs operand (constant value or attribute name) */
protected String m_rhsOperand;
/** True if the rhs operand is an attribute */
protected boolean m_rhsIsAttribute;
/** index of the rhs if it is an attribute */
protected int m_rhsAttIndex = -1;
/** The name of the lhs attribute after resolving variables */
protected String m_resolvedLhsName;
/** The rhs operand after resolving variables */
protected String m_resolvedRhsOperand;
/** the compiled regex pattern (if the operator is REGEX) */
protected Pattern m_regexPattern;
/** The rhs operand (if constant and is a number ) */
protected double m_numericOperand;
public static enum ExpressionType {
EQUALS(" = ") {
@Override
boolean evaluate(Instance inst, int lhsAttIndex, String rhsOperand,
double numericOperand, Pattern regexPattern, boolean rhsIsAttribute,
int rhsAttIndex) {
if (rhsIsAttribute) {
if (inst.isMissing(lhsAttIndex) && inst.isMissing(rhsAttIndex)) {
return true;
}
if (inst.isMissing(lhsAttIndex) || inst.isMissing(rhsAttIndex)) {
return false;
}
return Utils.eq(inst.value(lhsAttIndex), inst.value(rhsAttIndex));
}
if (inst.isMissing(lhsAttIndex)) {
return false;
}
return (Utils.eq(inst.value(lhsAttIndex), numericOperand));
}
},
NOTEQUAL(" != ") {
@Override
boolean evaluate(Instance inst, int lhsAttIndex, String rhsOperand,
double numericOperand, Pattern regexPattern, boolean rhsIsAttribute,
int rhsAttIndex) {
return !EQUALS.evaluate(inst, lhsAttIndex, rhsOperand,
numericOperand, regexPattern, rhsIsAttribute, rhsAttIndex);
}
},
LESSTHAN(" < ") {
@Override
boolean evaluate(Instance inst, int lhsAttIndex, String rhsOperand,
double numericOperand, Pattern regexPattern, boolean rhsIsAttribute,
int rhsAttIndex) {
if (rhsIsAttribute) {
if (inst.isMissing(lhsAttIndex) || inst.isMissing(rhsAttIndex)) {
return false;
}
return (inst.value(lhsAttIndex) < inst.value(rhsAttIndex));
}
if (inst.isMissing(lhsAttIndex)) {
return false;
}
return (inst.value(lhsAttIndex) < numericOperand);
}
},
LESSTHANEQUAL(" <= ") {
@Override
boolean evaluate(Instance inst, int lhsAttIndex, String rhsOperand,
double numericOperand, Pattern regexPattern, boolean rhsIsAttribute,
int rhsAttIndex) {
if (rhsIsAttribute) {
if (inst.isMissing(lhsAttIndex) || inst.isMissing(rhsAttIndex)) {
return false;
}
return (inst.value(lhsAttIndex) <= inst.value(rhsAttIndex));
}
if (inst.isMissing(lhsAttIndex)) {
return false;
}
return (inst.value(lhsAttIndex) <= numericOperand);
}
},
GREATERTHAN(" > ") {
@Override
boolean evaluate(Instance inst, int lhsAttIndex, String rhsOperand,
double numericOperand, Pattern regexPattern, boolean rhsIsAttribute,
int rhsAttIndex) {
return !LESSTHANEQUAL.evaluate(inst, lhsAttIndex, rhsOperand,
numericOperand, regexPattern, rhsIsAttribute, rhsAttIndex);
}
},
GREATERTHANEQUAL(" >= ") {
@Override
boolean evaluate(Instance inst, int lhsAttIndex, String rhsOperand,
double numericOperand, Pattern regexPattern, boolean rhsIsAttribute,
int rhsAttIndex) {
return !LESSTHAN.evaluate(inst, lhsAttIndex, rhsOperand,
numericOperand, regexPattern, rhsIsAttribute, rhsAttIndex);
}
},
ISMISSING(" isMissing ") {
@Override
boolean evaluate(Instance inst, int lhsAttIndex, String rhsOperand,
double numericOperand, Pattern regexPattern, boolean rhsIsAttribute,
int rhsAttIndex) {
return (inst.isMissing(lhsAttIndex));
}
},
CONTAINS(" contains ") {
@Override
boolean evaluate(Instance inst, int lhsAttIndex, String rhsOperand,
double numericOperand, Pattern regexPattern, boolean rhsIsAttribute,
int rhsAttIndex) {
if (inst.isMissing(lhsAttIndex)) {
return false;
}
String lhsString = "";
try {
lhsString = inst.stringValue(lhsAttIndex);
} catch (IllegalArgumentException ex) {
return false;
}
if (rhsIsAttribute) {
if (inst.isMissing(rhsAttIndex)) {
return false;
}
try {
String rhsString = inst.stringValue(rhsAttIndex);
return lhsString.contains(rhsString);
} catch (IllegalArgumentException ex) {
return false;
}
}
return lhsString.contains(rhsOperand);
}
},
STARTSWITH(" startsWith ") {
@Override
boolean evaluate(Instance inst, int lhsAttIndex, String rhsOperand,
double numericOperand, Pattern regexPattern, boolean rhsIsAttribute,
int rhsAttIndex) {
if (inst.isMissing(lhsAttIndex)) {
return false;
}
String lhsString = "";
try {
lhsString = inst.stringValue(lhsAttIndex);
} catch (IllegalArgumentException ex) {
return false;
}
if (rhsIsAttribute) {
if (inst.isMissing(rhsAttIndex)) {
return false;
}
try {
String rhsString = inst.stringValue(rhsAttIndex);
return lhsString.startsWith(rhsString);
} catch (IllegalArgumentException ex) {
return false;
}
}
return lhsString.startsWith(rhsOperand);
}
},
ENDSWITH(" endsWith ") {
@Override
boolean evaluate(Instance inst, int lhsAttIndex, String rhsOperand,
double numericOperand, Pattern regexPattern, boolean rhsIsAttribute,
int rhsAttIndex) {
if (inst.isMissing(lhsAttIndex)) {
return false;
}
String lhsString = "";
try {
lhsString = inst.stringValue(lhsAttIndex);
} catch (IllegalArgumentException ex) {
return false;
}
if (rhsIsAttribute) {
if (inst.isMissing(rhsAttIndex)) {
return false;
}
try {
String rhsString = inst.stringValue(rhsAttIndex);
return lhsString.endsWith(rhsString);
} catch (IllegalArgumentException ex) {
return false;
}
}
return lhsString.endsWith(rhsOperand);
}
},
REGEX(" regex ") {
@Override
boolean evaluate(Instance inst, int lhsAttIndex, String rhsOperand,
double numericOperand, Pattern regexPattern, boolean rhsIsAttribute,
int rhsAttIndex) {
if (inst.isMissing(lhsAttIndex)) {
return false;
}
if (regexPattern == null) {
return false;
}
String lhsString = "";
try {
lhsString = inst.stringValue(lhsAttIndex);
} catch (IllegalArgumentException ex) {
return false;
}
return regexPattern.matcher(lhsString).matches();
}
};
abstract boolean evaluate(Instance inst, int lhsAttIndex,
String rhsOperand, double numericOperand, Pattern regexPattern,
boolean rhsIsAttribute, int rhsAttIndex);
private final String m_stringVal;
ExpressionType(String name) {
m_stringVal = name;
}
@Override
public String toString() {
return m_stringVal;
}
}
public ExpressionClause() {
}
/**
* Construct a new ExpressionClause
*
* @param operator the operator to use
* @param lhsAttributeName the lhs attribute name
* @param rhsOperand the rhs operand
* @param rhsIsAttribute true if the rhs operand is an attribute
* @param isAnOr true if the result of this expression is to be OR'ed with
* the result so far
*/
public ExpressionClause(ExpressionType operator, String lhsAttributeName,
String rhsOperand, boolean rhsIsAttribute, boolean isAnOr) {
m_operator = operator;
m_lhsAttributeName = lhsAttributeName;
m_rhsOperand = rhsOperand;
m_rhsIsAttribute = rhsIsAttribute;
m_isAnOr = isAnOr;
}
@Override
public void init(Instances structure, Environment env) {
super.init(structure, env);
m_resolvedLhsName = m_lhsAttributeName;
m_resolvedRhsOperand = m_rhsOperand;
try {
m_resolvedLhsName = m_env.substitute(m_resolvedLhsName);
m_resolvedRhsOperand = m_env.substitute(m_resolvedRhsOperand);
} catch (Exception ex) {
}
Attribute lhs = null;
// try as an index or "special" label first
if (m_resolvedLhsName.toLowerCase().startsWith("/first")) {
lhs = structure.attribute(0);
} else if (m_resolvedLhsName.toLowerCase().startsWith("/last")) {
lhs = structure.attribute(structure.numAttributes() - 1);
} else {
// try as an index
try {
int indx = Integer.parseInt(m_resolvedLhsName);
indx--;
lhs = structure.attribute(indx);
} catch (NumberFormatException ex) {
}
}
if (lhs == null) {
lhs = structure.attribute(m_resolvedLhsName);
}
if (lhs == null) {
throw new IllegalArgumentException("Data does not contain attribute "
+ "\"" + m_resolvedLhsName + "\"");
}
m_lhsAttIndex = lhs.index();
if (m_rhsIsAttribute) {
Attribute rhs = null;
// try as an index or "special" label first
if (m_resolvedRhsOperand.toLowerCase().equals("/first")) {
rhs = structure.attribute(0);
} else if (m_resolvedRhsOperand.toLowerCase().equals("/last")) {
rhs = structure.attribute(structure.numAttributes() - 1);
} else {
// try as an index
try {
int indx = Integer.parseInt(m_resolvedRhsOperand);
indx--;
rhs = structure.attribute(indx);
} catch (NumberFormatException ex) {
}
}
if (rhs == null) {
rhs = structure.attribute(m_resolvedRhsOperand);
}
if (rhs == null) {
throw new IllegalArgumentException("Data does not contain attribute "
+ "\"" + m_resolvedRhsOperand + "\"");
}
m_rhsAttIndex = rhs.index();
} else if (m_operator != ExpressionType.CONTAINS
&& m_operator != ExpressionType.STARTSWITH
&& m_operator != ExpressionType.ENDSWITH
&& m_operator != ExpressionType.REGEX
&& m_operator != ExpressionType.ISMISSING) {
// make sure the operand is parseable as a number (unless missing has
// been specified - equals only)
if (lhs.isNominal()) {
m_numericOperand = lhs.indexOfValue(m_resolvedRhsOperand);
if (m_numericOperand < 0) {
throw new IllegalArgumentException("Unknown nominal value '"
+ m_resolvedRhsOperand + "' for attribute '" + lhs.name() + "'");
}
} else {
try {
m_numericOperand = Double.parseDouble(m_resolvedRhsOperand);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("\"" + m_resolvedRhsOperand
+ "\" is not parseable as a number!");
}
}
}
if (m_operator == ExpressionType.REGEX) {
m_regexPattern = Pattern.compile(m_resolvedRhsOperand);
}
}
@Override
public boolean evaluate(Instance inst, boolean result) {
boolean thisNode = m_operator.evaluate(inst, m_lhsAttIndex, m_rhsOperand,
m_numericOperand, m_regexPattern, m_rhsIsAttribute, m_rhsAttIndex);
if (isNegated()) {
thisNode = !thisNode;
}
return (isOr() ? (result || thisNode) : (result && thisNode));
}
@Override
public String toString() {
StringBuffer buff = new StringBuffer();
toStringDisplay(buff);
return buff.toString();
}
@Override
public void toStringDisplay(StringBuffer buff) {
toString(buff, false);
}
@Override
protected void toStringInternal(StringBuffer buff) {
toString(buff, true);
}
@Override
public DefaultMutableTreeNode toJTree(DefaultMutableTreeNode parent) {
parent.add(new DefaultMutableTreeNode(this));
return parent;
}
private void toString(StringBuffer buff, boolean internal) {
if (internal || m_showAndOr) {
if (m_isAnOr) {
buff.append("|| ");
} else {
buff.append("&& ");
}
}
if (isNegated()) {
buff.append("!");
}
buff.append("[");
buff.append(m_lhsAttributeName);
if (internal) {
buff.append("@EC@" + m_operator.toString());
} else {
buff.append(" " + m_operator.toString());
}
if (m_operator != ExpressionType.ISMISSING) {
// @@ indicates that the rhs is an attribute
if (internal) {
buff.append("@EC@" + (m_rhsIsAttribute ? "@@" : "") + m_rhsOperand);
} else {
buff.append(" " + (m_rhsIsAttribute ? "ATT: " : "") + m_rhsOperand);
}
} else {
if (internal) {
buff.append("@EC@");
} else {
buff.append(" ");
}
}
buff.append("]");
}
@Override
protected String parseFromInternal(String expression) {
// first the boolean operator for this clause
if (expression.startsWith("|| ")) {
m_isAnOr = true;
}
if (expression.startsWith("|| ") || expression.startsWith("&& ")) {
// strip the boolean operator
expression = expression.substring(3, expression.length());
}
if (expression.charAt(0) == '!') {
setNegated(true);
expression = expression.substring(1, expression.length());
}
if (expression.charAt(0) != '[') {
throw new IllegalArgumentException(
"Was expecting a \"[\" to start this ExpressionClause!");
}
expression = expression.substring(1, expression.length());
m_lhsAttributeName = expression.substring(0, expression.indexOf("@EC@"));
expression = expression.substring(expression.indexOf("@EC@") + 4,
expression.length());
String oppName = expression.substring(0, expression.indexOf("@EC@"));
expression = expression.substring(expression.indexOf("@EC@") + 4,
expression.length());
for (ExpressionType n : ExpressionType.values()) {
if (n.toString().equals(oppName)) {
m_operator = n;
break;
}
}
if (expression.startsWith("@@")) {
// rhs is an attribute
expression = expression.substring(2, expression.length()); // strip off
// "@@"
m_rhsIsAttribute = true;
}
m_rhsOperand = expression.substring(0, expression.indexOf(']'));
expression = expression.substring(expression.indexOf(']') + 1,
expression.length()); // remove "]"
if (expression.charAt(0) == ' ') {
expression = expression.substring(1, expression.length());
}
return expression;
}
}
/** The root of the expression tree */
protected ExpressionNode m_root;
/** The expression tree to use in internal textual format */
protected String m_expressionString = "";
/**
* The one or two downstream steps - one for instances that match the
* expression and the other for instances that don't
*/
protected Object[] m_downstream;
/**
* Name of the step to receive instances that evaluate to true via the
* expression
*/
protected String m_customNameOfTrueStep = "";
/**
* Name of the step to receive instances that evaluate to false via the
* expression
*/
protected String m_customNameOfFalseStep = "";
protected int m_indexOfTrueStep;
protected int m_indexOfFalseStep;
/** Logging */
protected transient Logger m_log;
/** Busy indicator */
protected transient boolean m_busy;
/** Component talking to us */
protected Object m_listenee;
/** The type of the incoming connection */
protected String m_connectionType;
/** format of instances for current incoming connection (if any) */
private Instances m_connectedFormat;
protected transient Environment m_env;
/** Instance event to use */
protected InstanceEvent m_ie = new InstanceEvent(this);
/**
* Default visual filters
*/
protected BeanVisual m_visual = new BeanVisual("FlowByExpression",
BeanVisual.ICON_PATH + "FlowByExpression.png", BeanVisual.ICON_PATH
+ "FlowByExpression.png");
/**
* Constructor
*/
public FlowByExpression() {
setLayout(new BorderLayout());
add(m_visual, BorderLayout.CENTER);
m_env = Environment.getSystemWide();
}
public String globalInfo() {
return "Splits incoming instances (or instance stream) according to the "
+ "evaluation of a logical expression. The expression can test the values of "
+ "one or more incoming attributes. The test can involve constants or comparing "
+ "one attribute's values to another. Inequalities along with string operations "
+ "such as contains, starts-with, ends-with and regular expressions may be used "
+ "as operators. \"True\" instances can be sent to one downstream step and "
+ "\"False\" instances sent to another.";
}
/**
* Set the expression (in internal format)
*
* @param expressionString the expression to use (in internal format)
*/
public void setExpressionString(String expressionString) {
m_expressionString = expressionString;
}
/**
* Get the current expression (in internal format)
*
* @return the current expression (in internal format)
*/
public String getExpressionString() {
return m_expressionString;
}
/**
* Set the name of the connected step to send "true" instances to
*
* @param trueStep the name of the step to send "true" instances to
*/
public void setTrueStepName(String trueStep) {
m_customNameOfTrueStep = trueStep;
}
/**
* Get the name of the connected step to send "true" instances to
*
* @return the name of the step to send "true" instances to
*/
public String getTrueStepName() {
return m_customNameOfTrueStep;
}
/**
* Set the name of the connected step to send "false" instances to
*
* @param falseStep the name of the step to send "false" instances to
*/
public void setFalseStepName(String falseStep) {
m_customNameOfFalseStep = falseStep;
}
/**
* Get the name of the connected step to send "false" instances to
*
* @return the name of the step to send "false" instances to
*/
public String getFalseStepName() {
return m_customNameOfFalseStep;
}
@Override
public void addDataSourceListener(DataSourceListener dsl) {
if (m_downstream == null) {
m_downstream = new Object[2];
}
if (m_downstream[0] == null && m_downstream[1] == null) {
m_downstream[0] = dsl;
return;
}
if (m_downstream[0] == null || m_downstream[1] == null) {
if (m_downstream[0] == null
&& m_downstream[1] instanceof DataSourceListener) {
m_downstream[0] = dsl;
return;
} else if (m_downstream[1] == null
&& m_downstream[0] instanceof DataSourceListener) {
m_downstream[1] = dsl;
return;
}
}
}
protected void remove(Object dsl) {
if (m_downstream[0] == dsl) {
m_downstream[0] = null;
return;
}
if (m_downstream[1] == dsl) {
m_downstream[1] = null;
}
}
@Override
public void removeDataSourceListener(DataSourceListener dsl) {
if (m_downstream == null) {
m_downstream = new Object[2];
}
remove(dsl);
}
@Override
public void addInstanceListener(InstanceListener dsl) {
if (m_downstream == null) {
m_downstream = new Object[2];
}
if (m_downstream[0] == null && m_downstream[1] == null) {
m_downstream[0] = dsl;
return;
}
if (m_downstream[0] == null || m_downstream[1] == null) {
if (m_downstream[0] == null
&& m_downstream[1] instanceof InstanceListener) {
m_downstream[0] = dsl;
return;
} else if (m_downstream[1] == null
&& m_downstream[0] instanceof InstanceListener) {
m_downstream[1] = dsl;
return;
}
}
}
@Override
public void removeInstanceListener(InstanceListener dsl) {
if (m_downstream == null) {
m_downstream = new Object[2];
}
remove(dsl);
}
@Override
public void setEnvironment(Environment env) {
m_env = env;
}
@Override
public boolean eventGeneratable(String eventName) {
if (m_listenee == null) {
return false;
}
if (m_listenee instanceof EventConstraints) {
if (eventName.equals("dataSet")) {
return ((EventConstraints) m_listenee).eventGeneratable(eventName)
|| ((EventConstraints) m_listenee).eventGeneratable("trainingSet")
|| ((EventConstraints) m_listenee).eventGeneratable("testSet");
}
return ((EventConstraints) m_listenee).eventGeneratable(eventName);
}
return true;
}
/**
* Initialize with respect to the incoming instance format
*
* @param data the incoming instance format
*/
protected void init(Instances data) {
m_indexOfTrueStep = -1;
m_indexOfFalseStep = -1;
m_connectedFormat = data;
if (m_downstream == null) {
return;
}
if (m_downstream[0] != null
&& ((BeanCommon) m_downstream[0]).getCustomName().equals(
m_customNameOfTrueStep)) {
m_indexOfTrueStep = 0;
}
if (m_downstream[0] != null
&& ((BeanCommon) m_downstream[0]).getCustomName().equals(
m_customNameOfFalseStep)) {
m_indexOfFalseStep = 0;
}
if (m_downstream[1] != null
&& ((BeanCommon) m_downstream[1]).getCustomName().equals(
m_customNameOfTrueStep)) {
m_indexOfTrueStep = 1;
}
if (m_downstream[1] != null
&& ((BeanCommon) m_downstream[1]).getCustomName().equals(
m_customNameOfFalseStep)) {
m_indexOfFalseStep = 1;
}
if (m_env == null) {
m_env = Environment.getSystemWide();
}
try {
if (m_expressionString != null && m_expressionString.length() > 0) {
m_root = new BracketNode();
m_root.parseFromInternal(m_expressionString);
}
if (m_root != null) {
m_root.init(data, m_env);
}
} catch (Exception ex) {
ex.printStackTrace();
stop();
m_busy = false;
}
}
@Override
public void acceptDataSet(DataSetEvent e) {
m_busy = true;
if (m_log != null && !e.isStructureOnly()) {
m_log.statusMessage(statusMessagePrefix() + "Processing batch...");
}
init(new Instances(e.getDataSet(), 0));
if (m_root != null) {
Instances trueBatch = new Instances(e.getDataSet(), 0);
Instances falseBatch = new Instances(e.getDataSet(), 0);
for (int i = 0; i < e.getDataSet().numInstances(); i++) {
Instance current = e.getDataSet().instance(i);
boolean result = m_root.evaluate(current, true);
if (result) {
if (m_indexOfTrueStep >= 0) {
trueBatch.add(current);
}
} else {
if (m_indexOfFalseStep >= 0) {
falseBatch.add(current);
}
}
}
if (m_indexOfTrueStep >= 0) {
DataSetEvent d = new DataSetEvent(this, trueBatch);
((DataSourceListener) m_downstream[m_indexOfTrueStep]).acceptDataSet(d);
}
if (m_indexOfFalseStep >= 0) {
DataSetEvent d = new DataSetEvent(this, falseBatch);
((DataSourceListener) m_downstream[m_indexOfFalseStep])
.acceptDataSet(d);
}
} else {
if (m_indexOfTrueStep >= 0) {
DataSetEvent d = new DataSetEvent(this, e.getDataSet());
((DataSourceListener) m_downstream[m_indexOfTrueStep]).acceptDataSet(d);
}
}
if (m_log != null && !e.isStructureOnly()) {
m_log.statusMessage(statusMessagePrefix() + "Finished");
}
m_busy = false;
}
@Override
public void acceptTestSet(TestSetEvent e) {
Instances test = e.getTestSet();
DataSetEvent d = new DataSetEvent(this, test);
acceptDataSet(d);
}
@Override
public void acceptTrainingSet(TrainingSetEvent e) {
Instances train = e.getTrainingSet();
DataSetEvent d = new DataSetEvent(this, train);
acceptDataSet(d);
}
@Override
public void acceptInstance(InstanceEvent e) {
m_busy = true;
if (e.getStatus() == InstanceEvent.FORMAT_AVAILABLE) {
Instances structure = e.getStructure();
init(structure);
if (m_log != null) {
m_log.statusMessage(statusMessagePrefix() + "Processing stream...");
}
// notify listeners of structure
m_ie.setStructure(structure);
if (m_indexOfTrueStep >= 0) {
((InstanceListener) m_downstream[m_indexOfTrueStep])
.acceptInstance(m_ie);
}
if (m_indexOfFalseStep >= 0) {
((InstanceListener) m_downstream[m_indexOfFalseStep])
.acceptInstance(m_ie);
}
} else {
Instance inst = e.getInstance();
m_ie.setStatus(e.getStatus());
if (inst == null || e.getStatus() == InstanceEvent.BATCH_FINISHED) {
if (inst != null) {
// evaluate and notify
boolean result = true;
if (m_root != null) {
result = m_root.evaluate(inst, true);
}
if (result) {
if (m_indexOfTrueStep >= 0) {
m_ie.setInstance(inst);
((InstanceListener) m_downstream[m_indexOfTrueStep])
.acceptInstance(m_ie);
}
if (m_indexOfFalseStep >= 0) {
m_ie.setInstance(null);
((InstanceListener) m_downstream[m_indexOfFalseStep])
.acceptInstance(m_ie);
}
} else {
if (m_indexOfFalseStep >= 0) {
m_ie.setInstance(inst);
((InstanceListener) m_downstream[m_indexOfFalseStep])
.acceptInstance(m_ie);
}
if (m_indexOfTrueStep >= 0) {
m_ie.setInstance(null);
((InstanceListener) m_downstream[m_indexOfTrueStep])
.acceptInstance(m_ie);
}
}
} else {
// notify both of end of stream
m_ie.setInstance(null);
if (m_indexOfTrueStep >= 0) {
((InstanceListener) m_downstream[m_indexOfTrueStep])
.acceptInstance(m_ie);
}
if (m_indexOfFalseStep >= 0) {
((InstanceListener) m_downstream[m_indexOfFalseStep])
.acceptInstance(m_ie);
}
}
if (m_log != null) {
m_log.statusMessage(statusMessagePrefix() + "Finished");
}
} else {
boolean result = true;
if (m_root != null) {
result = m_root.evaluate(inst, true);
}
m_ie.setInstance(inst);
if (result) {
if (m_indexOfTrueStep >= 0) {
((InstanceListener) m_downstream[m_indexOfTrueStep])
.acceptInstance(m_ie);
}
} else {
if (m_indexOfFalseStep >= 0) {
((InstanceListener) m_downstream[m_indexOfFalseStep])
.acceptInstance(m_ie);
}
}
}
}
m_busy = false;
}
@Override
public void useDefaultVisual() {
m_visual.loadIcons(BeanVisual.ICON_PATH + "FlowByExpression.png",
BeanVisual.ICON_PATH + "FlowByExpression.png");
m_visual.setText("FlowByExpression");
}
@Override
public void setVisual(BeanVisual newVisual) {
m_visual = newVisual;
}
@Override
public BeanVisual getVisual() {
return m_visual;
}
@Override
public void setCustomName(String name) {
m_visual.setText(name);
}
@Override
public String getCustomName() {
return m_visual.getText();
}
@Override
public void stop() {
if (m_listenee != null) {
if (m_listenee instanceof BeanCommon) {
((BeanCommon) m_listenee).stop();
}
}
if (m_log != null) {
m_log.statusMessage(statusMessagePrefix() + "Stopped");
}
m_busy = false;
}
@Override
public boolean isBusy() {
return m_busy;
}
@Override
public void setLog(Logger logger) {
m_log = logger;
}
@Override
public boolean connectionAllowed(EventSetDescriptor esd) {
return connectionAllowed(esd.getName());
}
@Override
public boolean connectionAllowed(String eventName) {
if (m_listenee != null) {
return false;
}
return true;
}
@Override
public void connectionNotification(String eventName, Object source) {
if (connectionAllowed(eventName)) {
m_listenee = source;
m_connectionType = eventName;
}
}
@Override
public void disconnectionNotification(String eventName, Object source) {
if (source == m_listenee) {
m_listenee = null;
}
}
protected String statusMessagePrefix() {
return getCustomName() + "$" + hashCode() + "|";
}
private Instances getUpstreamStructure() {
if (m_listenee != null && m_listenee instanceof StructureProducer) {
return ((StructureProducer) m_listenee).getStructure(m_connectionType);
}
return null;
}
/**
* Get the structure of the output encapsulated in the named event. If the
* structure can't be determined in advance of seeing input, or this
* StructureProducer does not generate the named event, null should be
* returned.
*
* @param eventName the name of the output event that encapsulates the
* requested output.
*
* @return the structure of the output encapsulated in the named event or null
* if it can't be determined in advance of seeing input or the named
* event is not generated by this StructureProducer.
*/
@Override
public Instances getStructure(String eventName) {
if (!eventName.equals("dataSet") && !eventName.equals("instance")) {
return null;
}
if (eventName.equals("dataSet")
&& (m_downstream == null || m_downstream.length == 0)) {
return null;
}
if (eventName.equals("instance")
&& (m_downstream == null || m_downstream.length == 0)) {
return null;
}
if (m_connectedFormat == null) {
m_connectedFormat = getUpstreamStructure();
}
return m_connectedFormat;
}
/**
* Returns the structure of the incoming instances (if any)
*
* @return an <code>Instances</code> value
*/
public Instances getConnectedFormat() {
if (m_connectedFormat == null) {
m_connectedFormat = getUpstreamStructure();
}
return m_connectedFormat;
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/FlowByExpressionBeanInfo.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/>.
*/
/*
* FlowByExpressionBeanInfo.java
* Copyright (C) 2011-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.beans.BeanDescriptor;
import java.beans.EventSetDescriptor;
import java.beans.SimpleBeanInfo;
/**
* BeanInfo class for FlowByExpression
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision$
*/
public class FlowByExpressionBeanInfo extends SimpleBeanInfo {
/**
* Returns the event set descriptors
*
* @return an <code>EventSetDescriptor[]</code> value
*/
@Override
public EventSetDescriptor[] getEventSetDescriptors() {
try {
EventSetDescriptor[] esds = {
new EventSetDescriptor(DataSource.class, "instance",
InstanceListener.class, "acceptInstance"),
new EventSetDescriptor(DataSource.class, "dataSet",
DataSourceListener.class, "acceptDataSet") };
return esds;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
/**
* Get the bean descriptor for this bean
*
* @return a <code>BeanDescriptor</code> value
*/
@Override
public BeanDescriptor getBeanDescriptor() {
return new BeanDescriptor(FlowByExpression.class,
FlowByExpressionCustomizer.class);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/FlowByExpressionCustomizer.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/>.
*/
/*
* FlowByExpressionCustomizer.java
* Copyright (C) 2011-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.SwingConstants;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.DefaultTreeSelectionModel;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
import weka.core.Environment;
import weka.core.EnvironmentHandler;
import weka.core.Instances;
import weka.gui.PropertySheetPanel;
/**
* Customizer for the FlowByExpression node
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision$
*/
public class FlowByExpressionCustomizer extends JPanel implements
EnvironmentHandler, BeanCustomizer, CustomizerCloseRequester {
/** For serialization */
private static final long serialVersionUID = -3574741335754017794L;
protected Environment m_env = Environment.getSystemWide();
protected ModifyListener m_modifyL = null;
protected FlowByExpression m_expression;
protected JComboBox m_lhsField = new EnvironmentField.WideComboBox();
protected JComboBox m_operatorCombo = new JComboBox();
protected JComboBox m_rhsField = new EnvironmentField.WideComboBox();
protected JCheckBox m_rhsIsAttribute = new JCheckBox("RHS is attribute");
protected JLabel m_expressionLab = new JLabel();
protected JComboBox m_trueData = new JComboBox();
protected JComboBox m_falseData = new JComboBox();
protected JTree m_expressionTree;
protected DefaultMutableTreeNode m_treeRoot;
protected JButton m_addExpressionNode = new JButton("Add Expression node");
protected JButton m_addBracketNode = new JButton("Add bracket node");
protected JButton m_toggleNegation = new JButton("Toggle negation");
protected JButton m_andOr = new JButton("And/Or");
protected JButton m_deleteNode = new JButton("Delete node");
protected PropertySheetPanel m_tempEditor = new PropertySheetPanel();
protected Window m_parent;
/**
* Constructor
*/
public FlowByExpressionCustomizer() {
setLayout(new BorderLayout());
}
private void setup() {
JPanel aboutAndControlHolder = new JPanel();
aboutAndControlHolder.setLayout(new BorderLayout());
JPanel controlHolder = new JPanel();
controlHolder.setLayout(new BorderLayout());
JPanel fieldHolder = new JPanel();
fieldHolder.setLayout(new GridLayout(0, 4));
JPanel lhsP = new JPanel();
lhsP.setLayout(new BorderLayout());
lhsP.setBorder(BorderFactory.createTitledBorder("Attribute"));
// m_lhsField = new EnvironmentField(m_env);
m_lhsField.setEditable(true);
lhsP.add(m_lhsField, BorderLayout.CENTER);
lhsP.setToolTipText("<html>Name or index of attribute. "
+ "also accepts<br>the special labels \"/first\" and \"/last\""
+ " to indicate<br>the first and last attribute respecitively</html>");
m_lhsField.setToolTipText("<html>Name or index of attribute. "
+ "also accepts<br>the special labels \"/first\" and \"/last\""
+ " to indicate<br>the first and last attribute respecitively</html>");
JPanel operatorP = new JPanel();
operatorP.setLayout(new BorderLayout());
operatorP.setBorder(BorderFactory.createTitledBorder("Operator"));
m_operatorCombo.addItem(" = ");
m_operatorCombo.addItem(" != ");
m_operatorCombo.addItem(" < ");
m_operatorCombo.addItem(" <= ");
m_operatorCombo.addItem(" > ");
m_operatorCombo.addItem(" >= ");
m_operatorCombo.addItem(" isMissing ");
m_operatorCombo.addItem(" contains ");
m_operatorCombo.addItem(" startsWith ");
m_operatorCombo.addItem(" endsWith ");
m_operatorCombo.addItem(" regex ");
operatorP.add(m_operatorCombo, BorderLayout.CENTER);
JPanel rhsP = new JPanel();
rhsP.setLayout(new BorderLayout());
rhsP.setBorder(BorderFactory.createTitledBorder("Constant or attribute"));
rhsP.setToolTipText("<html>Constant value to test/check for. If "
+ "testing<br>against an attribute, then this specifies"
+ "an attribute index or name</html>");
// m_rhsField = new EnvironmentField(m_env);
m_rhsField.setEditable(true);
rhsP.add(m_rhsField, BorderLayout.CENTER);
fieldHolder.add(lhsP);
fieldHolder.add(operatorP);
fieldHolder.add(rhsP);
fieldHolder.add(m_rhsIsAttribute);
controlHolder.add(fieldHolder, BorderLayout.SOUTH);
JPanel tempPanel = new JPanel();
tempPanel.setLayout(new BorderLayout());
JPanel expressionP = new JPanel();
expressionP.setLayout(new BorderLayout());
expressionP.setBorder(BorderFactory.createTitledBorder("Expression"));
JPanel tempE = new JPanel();
tempE.setLayout(new BorderLayout());
tempE.setBorder(BorderFactory.createEmptyBorder(5, 0, 5, 0));
tempE.add(m_expressionLab, BorderLayout.CENTER);
JScrollPane expressionScroller = new JScrollPane(tempE);
expressionP.add(expressionScroller, BorderLayout.CENTER);
tempPanel.add(expressionP, BorderLayout.SOUTH);
//
JPanel flowControlP = new JPanel();
flowControlP.setLayout(new GridLayout(2, 2));
flowControlP.add(new JLabel("Send true instances to node",
SwingConstants.RIGHT));
flowControlP.add(m_trueData);
flowControlP.add(new JLabel("Send false instances to node",
SwingConstants.RIGHT));
flowControlP.add(m_falseData);
tempPanel.add(flowControlP, BorderLayout.NORTH);
String falseStepN = m_expression.getFalseStepName();
String trueStepN = m_expression.getTrueStepName();
Object[] connectedSteps = m_expression.m_downstream;
m_trueData.addItem("<none>");
m_falseData.addItem("<none>");
if (connectedSteps != null && connectedSteps.length > 0) {
if (connectedSteps[0] != null) {
String first = ((BeanCommon) connectedSteps[0]).getCustomName();
m_trueData.addItem(first);
m_falseData.addItem(first);
}
if (connectedSteps.length > 1 && connectedSteps[1] != null) {
String second = ((BeanCommon) connectedSteps[1]).getCustomName();
m_trueData.addItem(second);
m_falseData.addItem(second);
}
}
if (falseStepN != null && falseStepN.length() > 0) {
m_falseData.setSelectedItem(falseStepN);
}
if (trueStepN != null && trueStepN.length() > 0) {
m_trueData.setSelectedItem(trueStepN);
}
controlHolder.add(tempPanel, BorderLayout.NORTH);
aboutAndControlHolder.add(controlHolder, BorderLayout.SOUTH);
JPanel aboutP = m_tempEditor.getAboutPanel();
aboutAndControlHolder.add(aboutP, BorderLayout.NORTH);
add(aboutAndControlHolder, BorderLayout.NORTH);
addButtons();
m_rhsIsAttribute.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (m_expressionTree != null) {
TreePath p = m_expressionTree.getSelectionPath();
if (p != null) {
if (p.getLastPathComponent() instanceof DefaultMutableTreeNode) {
DefaultMutableTreeNode tNode =
(DefaultMutableTreeNode) p.getLastPathComponent();
FlowByExpression.ExpressionNode thisNode =
(FlowByExpression.ExpressionNode) tNode.getUserObject();
if (thisNode instanceof FlowByExpression.ExpressionClause) {
((FlowByExpression.ExpressionClause) thisNode).m_rhsIsAttribute =
m_rhsIsAttribute.isSelected();
DefaultTreeModel tmodel =
(DefaultTreeModel) m_expressionTree.getModel();
tmodel.nodeStructureChanged(tNode);
updateExpressionLabel();
}
}
}
}
}
});
m_operatorCombo.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (m_operatorCombo.getSelectedIndex() > 5) {
m_rhsIsAttribute.setSelected(false);
m_rhsIsAttribute.setEnabled(false);
} else {
m_rhsIsAttribute.setEnabled(true);
}
if (m_expressionTree != null) {
TreePath p = m_expressionTree.getSelectionPath();
if (p != null) {
if (p.getLastPathComponent() instanceof DefaultMutableTreeNode) {
DefaultMutableTreeNode tNode =
(DefaultMutableTreeNode) p.getLastPathComponent();
FlowByExpression.ExpressionNode thisNode =
(FlowByExpression.ExpressionNode) tNode.getUserObject();
if (thisNode instanceof FlowByExpression.ExpressionClause) {
String selection = m_operatorCombo.getSelectedItem().toString();
FlowByExpression.ExpressionClause.ExpressionType t =
FlowByExpression.ExpressionClause.ExpressionType.EQUALS;
for (FlowByExpression.ExpressionClause.ExpressionType et : FlowByExpression.ExpressionClause.ExpressionType
.values()) {
if (et.toString().equals(selection)) {
t = et;
break;
}
}
((FlowByExpression.ExpressionClause) thisNode).m_operator = t;
DefaultTreeModel tmodel =
(DefaultTreeModel) m_expressionTree.getModel();
tmodel.nodeStructureChanged(tNode);
updateExpressionLabel();
}
}
}
}
}
});
m_lhsField.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (m_expressionTree != null) {
TreePath p = m_expressionTree.getSelectionPath();
if (p != null) {
if (p.getLastPathComponent() instanceof DefaultMutableTreeNode) {
DefaultMutableTreeNode tNode =
(DefaultMutableTreeNode) p.getLastPathComponent();
FlowByExpression.ExpressionNode thisNode =
(FlowByExpression.ExpressionNode) tNode.getUserObject();
if (thisNode instanceof FlowByExpression.ExpressionClause) {
Object text = m_lhsField.getSelectedItem();
if (text != null) {
((FlowByExpression.ExpressionClause) thisNode).m_lhsAttributeName =
text.toString();
DefaultTreeModel tmodel =
(DefaultTreeModel) m_expressionTree.getModel();
tmodel.nodeStructureChanged(tNode);
updateExpressionLabel();
}
}
}
}
}
}
});
m_lhsField.getEditor().getEditorComponent()
.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
if (m_expressionTree != null) {
TreePath p = m_expressionTree.getSelectionPath();
if (p != null) {
if (p.getLastPathComponent() instanceof DefaultMutableTreeNode) {
DefaultMutableTreeNode tNode =
(DefaultMutableTreeNode) p.getLastPathComponent();
FlowByExpression.ExpressionNode thisNode =
(FlowByExpression.ExpressionNode) tNode.getUserObject();
if (thisNode instanceof FlowByExpression.ExpressionClause) {
String text = "";
if (m_lhsField.getSelectedItem() != null) {
text = m_lhsField.getSelectedItem().toString();
}
java.awt.Component theEditor =
m_lhsField.getEditor().getEditorComponent();
if (theEditor instanceof JTextField) {
text = ((JTextField) theEditor).getText();
}
((FlowByExpression.ExpressionClause) thisNode).m_lhsAttributeName =
text;
DefaultTreeModel tmodel =
(DefaultTreeModel) m_expressionTree.getModel();
tmodel.nodeStructureChanged(tNode);
updateExpressionLabel();
}
}
}
}
}
});
m_rhsField.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (m_expressionTree != null) {
TreePath p = m_expressionTree.getSelectionPath();
if (p != null) {
if (p.getLastPathComponent() instanceof DefaultMutableTreeNode) {
DefaultMutableTreeNode tNode =
(DefaultMutableTreeNode) p.getLastPathComponent();
FlowByExpression.ExpressionNode thisNode =
(FlowByExpression.ExpressionNode) tNode.getUserObject();
if (thisNode instanceof FlowByExpression.ExpressionClause) {
Object text = m_rhsField.getSelectedItem();
if (text != null) {
((FlowByExpression.ExpressionClause) thisNode).m_rhsOperand =
text.toString();
DefaultTreeModel tmodel =
(DefaultTreeModel) m_expressionTree.getModel();
tmodel.nodeStructureChanged(tNode);
updateExpressionLabel();
}
}
}
}
}
}
});
m_rhsField.getEditor().getEditorComponent()
.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
if (m_expressionTree != null) {
TreePath p = m_expressionTree.getSelectionPath();
if (p != null) {
if (p.getLastPathComponent() instanceof DefaultMutableTreeNode) {
DefaultMutableTreeNode tNode =
(DefaultMutableTreeNode) p.getLastPathComponent();
FlowByExpression.ExpressionNode thisNode =
(FlowByExpression.ExpressionNode) tNode.getUserObject();
if (thisNode instanceof FlowByExpression.ExpressionClause) {
String text = "";
if (m_rhsField.getSelectedItem() != null) {
text = m_rhsField.getSelectedItem().toString();
}
java.awt.Component theEditor =
m_rhsField.getEditor().getEditorComponent();
if (theEditor instanceof JTextField) {
text = ((JTextField) theEditor).getText();
}
if (m_rhsField.getSelectedItem() != null) {
((FlowByExpression.ExpressionClause) thisNode).m_rhsOperand =
text;
DefaultTreeModel tmodel =
(DefaultTreeModel) m_expressionTree.getModel();
tmodel.nodeStructureChanged(tNode);
updateExpressionLabel();
}
}
}
}
}
}
});
// try and setup combo boxes with incoming attribute names
if (m_expression.getConnectedFormat() != null) {
Instances incoming = m_expression.getConnectedFormat();
m_lhsField.removeAllItems();
m_rhsField.removeAllItems();
for (int i = 0; i < incoming.numAttributes(); i++) {
m_lhsField.addItem(incoming.attribute(i).name());
m_rhsField.addItem(incoming.attribute(i).name());
}
}
Dimension d = operatorP.getPreferredSize();
lhsP.setPreferredSize(d);
rhsP.setPreferredSize(d);
}
private void addButtons() {
JButton okBut = new JButton("OK");
JButton cancelBut = new JButton("Cancel");
JPanel butHolder = new JPanel();
butHolder.setLayout(new GridLayout(1, 2));
butHolder.add(okBut);
butHolder.add(cancelBut);
add(butHolder, BorderLayout.SOUTH);
okBut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
closingOK();
m_parent.dispose();
}
});
cancelBut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
closingCancel();
m_parent.dispose();
}
});
}
private void updateExpressionLabel() {
StringBuffer buff = new StringBuffer();
FlowByExpression.ExpressionNode root =
(FlowByExpression.ExpressionNode) m_treeRoot.getUserObject();
root.toStringDisplay(buff);
m_expressionLab.setText(buff.toString());
}
private void setExpressionEditor(FlowByExpression.ExpressionClause node) {
String lhs = node.m_lhsAttributeName;
if (lhs != null) {
m_lhsField.setSelectedItem(lhs);
}
String rhs = node.m_rhsOperand;
if (rhs != null) {
m_rhsField.setSelectedItem(rhs);
}
FlowByExpression.ExpressionClause.ExpressionType opp = node.m_operator;
int oppIndex = opp.ordinal();
m_operatorCombo.setSelectedIndex(oppIndex);
m_rhsIsAttribute.setSelected(node.m_rhsIsAttribute);
}
private void setupTree() {
JPanel treeHolder = new JPanel();
treeHolder.setLayout(new BorderLayout());
treeHolder.setBorder(BorderFactory.createTitledBorder("Expression tree"));
String expressionString = m_expression.getExpressionString();
if (expressionString == null || expressionString.length() == 0) {
expressionString = "()";
}
FlowByExpression.BracketNode root = new FlowByExpression.BracketNode();
root.parseFromInternal(expressionString);
root.setShowAndOr(false);
m_treeRoot = root.toJTree(null);
DefaultTreeModel model = new DefaultTreeModel(m_treeRoot);
m_expressionTree = new JTree(model);
m_expressionTree.setEnabled(true);
m_expressionTree.setRootVisible(true);
m_expressionTree.setShowsRootHandles(true);
DefaultTreeSelectionModel selectionModel = new DefaultTreeSelectionModel();
selectionModel.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
m_expressionTree.setSelectionModel(selectionModel);
// add mouse listener to tree
m_expressionTree.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
TreePath p = m_expressionTree.getSelectionPath();
if (p != null) {
if (p.getLastPathComponent() instanceof DefaultMutableTreeNode) {
DefaultMutableTreeNode tNode =
(DefaultMutableTreeNode) p.getLastPathComponent();
FlowByExpression.ExpressionNode thisNode =
(FlowByExpression.ExpressionNode) tNode.getUserObject();
if (thisNode instanceof FlowByExpression.ExpressionClause) {
setExpressionEditor((FlowByExpression.ExpressionClause) thisNode);
}
}
}
}
});
updateExpressionLabel();
JScrollPane treeView = new JScrollPane(m_expressionTree);
treeHolder.add(treeView, BorderLayout.CENTER);
JPanel butHolder = new JPanel();
// butHolder.setLayout(new BorderLayout());
butHolder.add(m_addExpressionNode);
butHolder.add(m_addBracketNode);
butHolder.add(m_toggleNegation);
butHolder.add(m_andOr);
butHolder.add(m_deleteNode);
treeHolder.add(butHolder, BorderLayout.NORTH);
add(treeHolder, BorderLayout.CENTER);
Dimension d = treeHolder.getPreferredSize();
treeHolder.setPreferredSize(new Dimension(d.width, d.height / 2));
m_andOr.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
TreePath p = m_expressionTree.getSelectionPath();
if (p != null) {
if (p.getLastPathComponent() instanceof DefaultMutableTreeNode) {
DefaultMutableTreeNode tNode =
(DefaultMutableTreeNode) p.getLastPathComponent();
FlowByExpression.ExpressionNode thisNode =
(FlowByExpression.ExpressionNode) tNode.getUserObject();
thisNode.setIsOr(!thisNode.isOr());
DefaultTreeModel tmodel =
(DefaultTreeModel) m_expressionTree.getModel();
tmodel.nodeStructureChanged(tNode);
updateExpressionLabel();
}
} else {
JOptionPane
.showMessageDialog(
FlowByExpressionCustomizer.this,
"Please select a node in the tree to alter the boolean operator of",
"And/Or", JOptionPane.INFORMATION_MESSAGE);
}
}
});
m_toggleNegation.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
TreePath p = m_expressionTree.getSelectionPath();
if (p != null) {
if (p.getLastPathComponent() instanceof DefaultMutableTreeNode) {
DefaultMutableTreeNode tNode =
(DefaultMutableTreeNode) p.getLastPathComponent();
FlowByExpression.ExpressionNode thisNode =
(FlowByExpression.ExpressionNode) tNode.getUserObject();
thisNode.setNegated(!thisNode.isNegated());
DefaultTreeModel tmodel =
(DefaultTreeModel) m_expressionTree.getModel();
tmodel.nodeStructureChanged(tNode);
updateExpressionLabel();
}
} else {
JOptionPane.showMessageDialog(FlowByExpressionCustomizer.this,
"Please select a node in the tree to toggle its negation",
"Toggle negation", JOptionPane.INFORMATION_MESSAGE);
}
}
});
m_deleteNode.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
TreePath p = m_expressionTree.getSelectionPath();
if (p != null) {
if (p.getLastPathComponent() instanceof DefaultMutableTreeNode) {
DefaultMutableTreeNode tNode =
(DefaultMutableTreeNode) p.getLastPathComponent();
if (tNode == m_treeRoot) {
JOptionPane.showMessageDialog(FlowByExpressionCustomizer.this,
"You can't delete the root of the tree!", "Delete node",
JOptionPane.INFORMATION_MESSAGE);
} else {
FlowByExpression.ExpressionNode thisNode =
(FlowByExpression.ExpressionNode) tNode.getUserObject();
FlowByExpression.BracketNode parentNode =
(FlowByExpression.BracketNode) ((DefaultMutableTreeNode) tNode
.getParent()).getUserObject();
// remove from internal tree structure
parentNode.removeChild(thisNode);
// remove from jtree structure
DefaultTreeModel tmodel =
(DefaultTreeModel) m_expressionTree.getModel();
tmodel.removeNodeFromParent(tNode);
updateExpressionLabel();
}
}
} else {
JOptionPane.showMessageDialog(FlowByExpressionCustomizer.this,
"Please select a node in the tree to delete.", "Delete node",
JOptionPane.INFORMATION_MESSAGE);
}
}
});
m_addExpressionNode.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
TreePath p = m_expressionTree.getSelectionPath();
if (p != null) {
if (p.getLastPathComponent() instanceof DefaultMutableTreeNode) {
DefaultMutableTreeNode tNode =
(DefaultMutableTreeNode) p.getLastPathComponent();
FlowByExpression.ExpressionNode thisNode =
(FlowByExpression.ExpressionNode) tNode.getUserObject();
if (thisNode instanceof FlowByExpression.BracketNode) {
FlowByExpression.ExpressionClause newNode =
new FlowByExpression.ExpressionClause(
FlowByExpression.ExpressionClause.ExpressionType.EQUALS,
"<att name>", "<value>", false, false);
((FlowByExpression.BracketNode) thisNode).addChild(newNode);
DefaultMutableTreeNode childNode =
new DefaultMutableTreeNode(newNode);
DefaultTreeModel tmodel =
(DefaultTreeModel) m_expressionTree.getModel();
tNode.add(childNode);
tmodel.nodeStructureChanged(tNode);
updateExpressionLabel();
} else {
JOptionPane.showMessageDialog(FlowByExpressionCustomizer.this,
"An expression can only be added to a bracket node.",
"Add expression", JOptionPane.INFORMATION_MESSAGE);
}
}
} else {
JOptionPane
.showMessageDialog(
FlowByExpressionCustomizer.this,
"You must select a bracket node in the tree view to add a new expression to.",
"Add expression", JOptionPane.INFORMATION_MESSAGE);
}
}
});
m_addBracketNode.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
TreePath p = m_expressionTree.getSelectionPath();
if (p != null) {
if (p.getLastPathComponent() instanceof DefaultMutableTreeNode) {
DefaultMutableTreeNode tNode =
(DefaultMutableTreeNode) p.getLastPathComponent();
FlowByExpression.ExpressionNode thisNode =
(FlowByExpression.ExpressionNode) tNode.getUserObject();
if (thisNode instanceof FlowByExpression.BracketNode) {
FlowByExpression.BracketNode newNode =
new FlowByExpression.BracketNode();
((FlowByExpression.BracketNode) thisNode).addChild(newNode);
DefaultMutableTreeNode childNode =
new DefaultMutableTreeNode(newNode);
DefaultTreeModel tmodel =
(DefaultTreeModel) m_expressionTree.getModel();
tNode.add(childNode);
tmodel.nodeStructureChanged(tNode);
updateExpressionLabel();
} else {
JOptionPane
.showMessageDialog(
FlowByExpressionCustomizer.this,
"An new bracket node can only be added to an existing bracket node.",
"Add bracket", JOptionPane.INFORMATION_MESSAGE);
}
}
} else {
JOptionPane
.showMessageDialog(
FlowByExpressionCustomizer.this,
"You must select an existing bracket node in the tree in order to add a new bracket node.",
"Add bracket", JOptionPane.INFORMATION_MESSAGE);
}
}
});
}
@Override
public void setObject(Object o) {
if (o instanceof FlowByExpression) {
m_expression = (FlowByExpression) o;
m_tempEditor.setTarget(o);
setup();
setupTree();
}
}
@Override
public void setParentWindow(Window parent) {
m_parent = parent;
}
@Override
public void setModifiedListener(ModifyListener l) {
m_modifyL = l;
}
@Override
public void setEnvironment(Environment env) {
m_env = env;
}
/**
* Set the current editor contents on the object being edited
*/
private void closingOK() {
if (m_treeRoot != null) {
FlowByExpression.ExpressionNode en =
(FlowByExpression.ExpressionNode) m_treeRoot.getUserObject();
StringBuffer buff = new StringBuffer();
en.toStringInternal(buff);
m_expression.setExpressionString(buff.toString());
if (m_trueData.getSelectedItem() != null
&& m_trueData.getSelectedItem().toString().length() > 0) {
m_expression.setTrueStepName(m_trueData.getSelectedItem().toString());
}
if (m_falseData.getSelectedItem() != null
&& m_falseData.getSelectedItem().toString().length() > 0) {
m_expression.setFalseStepName(m_falseData.getSelectedItem().toString());
}
}
}
/**
* Stuff to do when cancel is pressed
*/
private void closingCancel() {
// nothing to do here
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/FlowRunner.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/>.
*/
/*
* FlowRunner.java
* Copyright (C) 2008-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Set;
import java.util.TreeMap;
import java.util.Vector;
import weka.core.Environment;
import weka.core.EnvironmentHandler;
import weka.core.RevisionHandler;
import weka.gui.Logger;
import weka.gui.beans.xml.XMLBeans;
/**
* Small utility class for executing KnowledgeFlow flows outside of the
* KnowledgeFlow application
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}org)
* @version $Revision$
*/
public class FlowRunner implements RevisionHandler {
/** The potential flow(s) to execute */
protected Vector<Object> m_beans;
protected int m_runningCount = 0;
protected transient Logger m_log = null;
/** Whether to register the set log object with the beans */
protected boolean m_registerLog = true;
protected transient Environment m_env;
/** run each Startable bean sequentially? (default in parallel) */
protected boolean m_startSequentially = false;
public static class SimpleLogger implements weka.gui.Logger {
SimpleDateFormat m_DateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@Override
public void logMessage(String lm) {
System.out.println(m_DateFormat.format(new Date()) + ": " + lm);
}
@Override
public void statusMessage(String lm) {
System.out.println(m_DateFormat.format(new Date()) + ": " + lm);
}
}
/**
* Constructor
*/
public FlowRunner() {
this(true, true);
}
public FlowRunner(boolean loadProps, boolean registerLog) {
if (loadProps) {
// make sure that properties and plugins are loaded
BeansProperties.loadProperties();
}
m_registerLog = registerLog;
}
public void setLog(Logger log) {
m_log = log;
}
protected void runSequentially(TreeMap<Integer, Startable> startables) {
Set<Integer> s = startables.keySet();
for (Integer i : s) {
try {
Startable startPoint = startables.get(i);
startPoint.start();
Thread.sleep(200);
waitUntilFinished();
} catch (Exception ex) {
ex.printStackTrace();
if (m_log != null) {
m_log.logMessage(ex.getMessage());
m_log.logMessage("Aborting...");
} else {
System.err.println(ex.getMessage());
System.err.println("Aborting...");
}
break;
}
}
}
protected synchronized void launchThread(final Startable s, final int flowNum) {
Thread t = new Thread() {
// private int m_num = flowNum;
@Override
public void run() {
try {
s.start();
} catch (Exception ex) {
ex.printStackTrace();
if (m_log != null) {
m_log.logMessage(ex.getMessage());
} else {
System.err.println(ex.getMessage());
}
} finally {
/*
* if (m_log != null) { m_log.logMessage("[FlowRunner] flow " + m_num
* + " finished."); } else { System.out.println("[FlowRunner] Flow " +
* m_num + " finished."); }
*/
decreaseCount();
}
}
};
m_runningCount++;
t.setPriority(Thread.MIN_PRIORITY);
t.start();
}
protected synchronized void decreaseCount() {
m_runningCount--;
}
public synchronized void stopAllFlows() {
for (int i = 0; i < m_beans.size(); i++) {
BeanInstance temp = (BeanInstance) m_beans.elementAt(i);
if (temp.getBean() instanceof BeanCommon) {
// try to stop any execution
((BeanCommon) temp.getBean()).stop();
}
}
}
/**
* Waits until all flows have finished executing before returning
*
*/
public void waitUntilFinished() {
try {
while (m_runningCount > 0) {
Thread.sleep(200);
}
// now poll beans to see if there are any that are still busy
// (i.e. any multi-threaded ones that queue data instead of blocking)
while (true) {
boolean busy = false;
for (int i = 0; i < m_beans.size(); i++) {
BeanInstance temp = (BeanInstance) m_beans.elementAt(i);
if (temp.getBean() instanceof BeanCommon) {
if (((BeanCommon) temp.getBean()).isBusy()) {
busy = true;
break; // for
}
}
}
if (busy) {
Thread.sleep(3000);
} else {
break; // while
}
}
} catch (Exception ex) {
if (m_log != null) {
m_log.logMessage("[FlowRunner] Attempting to stop all flows...");
} else {
System.err.println("[FlowRunner] Attempting to stop all flows...");
}
stopAllFlows();
// ex.printStackTrace();
}
}
/**
* Load a serialized KnowledgeFlow (either binary or xml)
*
* @param fileName the name of the file to load from
* @throws Exception if something goes wrong
*/
public void load(String fileName) throws Exception {
if (!fileName.endsWith(".kf") && !fileName.endsWith(".kfml")) {
throw new Exception(
"Can only load and run binary or xml serialized KnowledgeFlows "
+ "(*.kf | *.kfml)");
}
if (fileName.endsWith(".kf")) {
loadBinary(fileName);
} else if (fileName.endsWith(".kfml")) {
loadXML(fileName);
}
}
/**
* Load a binary serialized KnowledgeFlow
*
* @param fileName the name of the file to load from
* @throws Exception if something goes wrong
*/
@SuppressWarnings("unchecked")
public void loadBinary(String fileName) throws Exception {
if (!fileName.endsWith(".kf")) {
throw new Exception("File must be a binary flow (*.kf)");
}
InputStream is = new FileInputStream(fileName);
ObjectInputStream ois = new ObjectInputStream(is);
m_beans = (Vector<Object>) ois.readObject();
// don't need the graphical connections
ois.close();
if (m_env != null) {
String parentDir = (new File(fileName)).getParent();
if (parentDir == null) {
parentDir = "./";
}
m_env.addVariable("Internal.knowledgeflow.directory", parentDir);
}
}
/**
* Load an XML serialized KnowledgeFlow
*
* @param fileName the name of the file to load from
* @throws Exception if something goes wrong
*/
@SuppressWarnings("unchecked")
public void loadXML(String fileName) throws Exception {
if (!fileName.endsWith(".kfml")) {
throw new Exception("File must be an XML flow (*.kfml)");
}
BeanConnection.init();
BeanInstance.init();
XMLBeans xml = new XMLBeans(null, null, 0);
Vector<?> v = (Vector<?>) xml.read(new File(fileName));
m_beans = (Vector<Object>) v.get(XMLBeans.INDEX_BEANINSTANCES);
if (m_env != null) {
String parentDir = (new File(fileName)).getParent();
if (parentDir == null) {
parentDir = "./";
}
m_env.addVariable("Internal.knowledgeflow.directory", parentDir);
} else {
System.err.println("++++++++++++ Environment variables null!!...");
}
}
/**
* Get the vector holding the flow(s)
*
* @return the Vector holding the flow(s)
*/
public Vector<Object> getFlows() {
return m_beans;
}
/**
* Set the vector holding the flows(s) to run
*
* @param beans the Vector holding the flows to run
*/
public void setFlows(Vector<Object> beans) {
m_beans = beans;
}
/**
* Set the environment variables to use. NOTE: this needs to be called BEFORE
* a load method is invoked to ensure that the
* ${Internal.knowledgeflow.directory} variable get set in the supplied
* Environment object.
*
* @param env the environment variables to use.
*/
public void setEnvironment(Environment env) {
m_env = env;
}
/**
* Get the environment variables that are in use.
*
* @return the environment variables that are in ues.
*/
public Environment getEnvironment() {
return m_env;
}
/**
* Set whether to launch Startable beans one after the other or all in
* parallel.
*
* @param s true if Startable beans are to be launched sequentially
*/
public void setStartSequentially(boolean s) {
m_startSequentially = s;
}
/**
* Gets whether Startable beans will be launched sequentially or all in
* parallel.
*
* @return true if Startable beans will be launched sequentially
*/
public boolean getStartSequentially() {
return m_startSequentially;
}
/**
* Launch all loaded KnowledgeFlow
*
* @throws Exception if something goes wrong during execution
*/
public void run() throws Exception {
if (m_beans == null) {
throw new Exception("Don't seem to have any beans I can execute.");
}
// register the log (if set) with the beans
for (int i = 0; i < m_beans.size(); i++) {
BeanInstance tempB = (BeanInstance) m_beans.elementAt(i);
if (m_log != null && m_registerLog) {
if (tempB.getBean() instanceof BeanCommon) {
((BeanCommon) tempB.getBean()).setLog(m_log);
}
}
if (tempB.getBean() instanceof EnvironmentHandler) {
((EnvironmentHandler) tempB.getBean()).setEnvironment(m_env);
}
}
int numFlows = 1;
if (m_log != null) {
if (m_startSequentially) {
m_log
.logMessage("[FlowRunner] launching flow start points sequentially...");
} else {
m_log
.logMessage("[FlowRunner] launching flow start points in parallel...");
}
}
TreeMap<Integer, Startable> startables = new TreeMap<Integer, Startable>();
// look for a Startable bean...
for (int i = 0; i < m_beans.size(); i++) {
BeanInstance tempB = (BeanInstance) m_beans.elementAt(i);
boolean launch = true;
if (tempB.getBean() instanceof Startable) {
Startable s = (Startable) tempB.getBean();
String beanName = s.getClass().getName();
String customName = beanName;
if (s instanceof BeanCommon) {
customName = ((BeanCommon) s).getCustomName();
beanName = customName;
if (customName.indexOf(':') > 0) {
if (customName.substring(0, customName.indexOf(':'))
.startsWith("!")) {
launch = false;
}
}
}
// start that sucker (if it's happy to be started)...
if (!m_startSequentially) {
if (s.getStartMessage().charAt(0) != '$') {
if (launch) {
if (m_log != null) {
m_log.logMessage("[FlowRunner] Launching flow " + numFlows
+ "...");
} else {
System.out.println("[FlowRunner] Launching flow " + numFlows
+ "...");
}
launchThread(s, numFlows);
numFlows++;
}
} else {
if (m_log != null) {
m_log.logMessage("[FlowRunner] WARNING: Can't start " + beanName
+ " at this time.");
} else {
System.out.println("[FlowRunner] WARNING: Can't start "
+ beanName + " at this time.");
}
}
} else {
boolean ok = false;
Integer position = null;
// String beanName = s.getClass().getName();
if (s instanceof BeanCommon) {
// String customName = ((BeanCommon)s).getCustomName();
// beanName = customName;
// see if we have a parseable integer at the start of the name
if (customName.indexOf(':') > 0) {
if (customName.substring(0, customName.indexOf(':')).startsWith(
"!")) {
launch = false;
} else {
String startPos = customName.substring(0,
customName.indexOf(':'));
try {
position = new Integer(startPos);
ok = true;
} catch (NumberFormatException n) {
}
}
}
}
if (!ok && launch) {
if (startables.size() == 0) {
position = new Integer(0);
} else {
int newPos = startables.lastKey().intValue();
newPos++;
position = new Integer(newPos);
}
}
if (s.getStartMessage().charAt(0) != '$') {
if (launch) {
if (m_log != null) {
m_log.logMessage("[FlowRunner] adding start point " + beanName
+ " to the execution list (position " + position + ")");
} else {
System.out.println("[FlowRunner] adding start point "
+ beanName + " to the execution list (position " + position
+ ")");
}
startables.put(position, s);
}
} else {
if (m_log != null) {
m_log.logMessage("[FlowRunner] WARNING: Can't start " + beanName
+ " at this time.");
} else {
System.out.println("[FlowRunner] WARNING: Can't start "
+ beanName + " at this time.");
}
}
}
if (!launch) {
if (m_log != null) {
m_log.logMessage("[FlowRunner] start point " + beanName
+ " will not be launched.");
} else {
System.out.println("[FlowRunner] start point " + beanName
+ " will not be launched.");
}
}
}
}
if (m_startSequentially) {
runSequentially(startables);
}
}
/**
* Main method for testing this class.
*
* <pre>
* Usage:\n\nFlowRunner <serialized kf file>
* </pre>
*
* @param args command line arguments
*/
public static void main(String[] args) {
System.setProperty("apple.awt.UIElement", "true");
weka.core.logging.Logger.log(weka.core.logging.Logger.Level.INFO,
"Logging started");
if (args.length < 1) {
System.err.println("Usage:\n\nFlowRunner <serialized kf file> [-s]\n\n"
+ "\tUse -s to launch start points sequentially (default launches "
+ "in parallel).");
} else {
try {
FlowRunner fr = new FlowRunner();
FlowRunner.SimpleLogger sl = new FlowRunner.SimpleLogger();
String fileName = args[0];
if (args.length == 2 && args[1].equals("-s")) {
fr.setStartSequentially(true);
}
// start with the system-wide vars
Environment env = Environment.getSystemWide();
fr.setLog(sl);
fr.setEnvironment(env);
fr.load(fileName);
fr.run();
fr.waitUntilFinished();
System.out.println("Finished all flows.");
System.exit(1);
} catch (Exception ex) {
ex.printStackTrace();
System.err.println(ex.getMessage());
}
}
}
@Override
public String getRevision() {
return "$Revision$";
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/GOECustomizer.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/>.
*/
/*
* GOECustomizer.java
* Copyright (C) 2011-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
/**
* Extends BeanCustomizer. Exists primarily for those customizers
* that can be displayed in the GenericObjectEditor (in preference
* to individual property editors). Provides a method to tell
* the customizer not to show any OK and CANCEL buttons if being
* displayed in the GOE (since the GOE provides those). Also specifies
* the methods for handling closing under OK or CANCEL conditions.
*
* Implementers of this interface should *not* use the GOE internally
* to implement the customizer because this will result in an cyclic
* loop of initializations that will end up in a stack overflow when
* the customizer is displayed by the GOE at the top level.
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision$
*/
public interface GOECustomizer extends BeanCustomizer {
/**
* Tells the customizer not to display its own OK and
* CANCEL buttons
*/
void dontShowOKCancelButtons();
/**
* Gets called when the customizer is closing under an OK
* condition
*/
void closingOK();
/**
* Gets called when the customizer is closing under a
* CANCEL condition
*/
void closingCancel();
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/GraphEvent.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/>.
*/
/*
* GraphEvent.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.util.EventObject;
/**
* Event for graphs
*
* @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a>
* @version $Revision$
*/
public class GraphEvent
extends EventObject {
/** for serialization */
private static final long serialVersionUID = 2099494034652519986L;
protected String m_graphString;
protected String m_graphTitle;
protected int m_graphType;
/**
* Creates a new <code>GraphEvent</code> instance.
*
* @param source the source of the event
* @param graphString a string describing the graph in "dot" format
* @param graphTitle the title for the graph
* @param graphType the type for the graph
*/
public GraphEvent(Object source, String graphString,
String graphTitle, int graphType) {
super(source);
m_graphString = graphString;
m_graphTitle = graphTitle;
m_graphType = graphType;
}
/**
* Return the dot string for the graph
*
* @return a <code>String</code> value
*/
public String getGraphString() {
return m_graphString;
}
/**
* Return the graph title
*
* @return a <code>String</code> value
*/
public String getGraphTitle() {
return m_graphTitle;
}
/**
* Return the graph type
*
* @return a <code>int</code> value
*/
public int getGraphType() {
return m_graphType;
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/GraphListener.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/>.
*/
/*
* GraphListener.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.util.EventListener;
/**
* Describe interface <code>TextListener</code> here.
*
* @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a>
* @version $Revision$
*/
public interface GraphListener extends EventListener {
/**
* Describe <code>acceptGraph</code> method here.
*
* @param e a <code>GraphEvent</code> value
*/
void acceptGraph(GraphEvent e);
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/GraphViewer.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/>.
*/
/*
* GraphViewer.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.awt.BorderLayout;
import java.awt.GraphicsEnvironment;
import java.awt.event.MouseEvent;
import java.beans.VetoableChangeListener;
import java.beans.beancontext.BeanContext;
import java.beans.beancontext.BeanContextChild;
import java.beans.beancontext.BeanContextChildSupport;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.Vector;
import javax.swing.*;
import weka.core.Drawable;
import weka.core.Utils;
import weka.gui.ResultHistoryPanel;
import weka.gui.graphvisualizer.BIFFormatException;
import weka.gui.graphvisualizer.GraphVisualizer;
import weka.gui.treevisualizer.PlaceNode2;
import weka.gui.treevisualizer.TreeVisualizer;
/**
* A bean encapsulating weka.gui.treevisualize.TreeVisualizer
*
* @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a>
* @version $Revision$
*/
public class GraphViewer extends JPanel implements Visible, GraphListener,
UserRequestAcceptor, Serializable, BeanContextChild {
/** for serialization */
private static final long serialVersionUID = -5183121972114900617L;
protected BeanVisual m_visual;
private transient JFrame m_resultsFrame = null;
protected transient ResultHistoryPanel m_history;
/**
* BeanContex that this bean might be contained within
*/
protected transient BeanContext m_beanContext = null;
/**
* BeanContextChild support
*/
protected BeanContextChildSupport m_bcSupport = new BeanContextChildSupport(
this);
/**
* True if this bean's appearance is the design mode appearance
*/
protected boolean m_design;
public GraphViewer() {
/*
* setUpResultHistory(); setLayout(new BorderLayout()); add(m_visual,
* BorderLayout.CENTER);
*/
if (!GraphicsEnvironment.isHeadless()) {
appearanceFinal();
}
}
protected void appearanceDesign() {
setUpResultHistory();
removeAll();
m_visual = new BeanVisual("GraphViewer", BeanVisual.ICON_PATH
+ "DefaultGraph.gif", BeanVisual.ICON_PATH + "DefaultGraph_animated.gif");
setLayout(new BorderLayout());
add(m_visual, BorderLayout.CENTER);
}
protected void appearanceFinal() {
removeAll();
setLayout(new BorderLayout());
setUpFinal();
}
protected void setUpFinal() {
setUpResultHistory();
add(m_history, BorderLayout.CENTER);
}
/**
* Global info for this bean
*
* @return a <code>String</code> value
*/
public String globalInfo() {
return "Graphically visualize trees or graphs produced by classifiers/clusterers.";
}
private void setUpResultHistory() {
if (m_history == null) {
m_history = new ResultHistoryPanel(null);
}
m_history.setBorder(BorderFactory.createTitledBorder("Graph list"));
m_history.setHandleRightClicks(false);
m_history.getList().addMouseListener(
new ResultHistoryPanel.RMouseAdapter() {
/** for serialization */
private static final long serialVersionUID = -4984130887963944249L;
@Override
public void mouseClicked(MouseEvent e) {
int index = m_history.getList().locationToIndex(e.getPoint());
if (index != -1) {
String name = m_history.getNameAtIndex(index);
doPopup(name);
}
}
});
}
/**
* Set a bean context for this bean
*
* @param bc a <code>BeanContext</code> value
*/
@Override
public void setBeanContext(BeanContext bc) {
m_beanContext = bc;
m_design = m_beanContext.isDesignTime();
if (m_design) {
appearanceDesign();
} else {
if (!GraphicsEnvironment.isHeadless()) {
appearanceFinal();
}
}
}
/**
* Return the bean context (if any) that this bean is embedded in
*
* @return a <code>BeanContext</code> value
*/
@Override
public BeanContext getBeanContext() {
return m_beanContext;
}
/**
* Add a vetoable change listener to this bean
*
* @param name the name of the property of interest
* @param vcl a <code>VetoableChangeListener</code> value
*/
@Override
public void addVetoableChangeListener(String name, VetoableChangeListener vcl) {
m_bcSupport.addVetoableChangeListener(name, vcl);
}
/**
* Remove a vetoable change listener from this bean
*
* @param name the name of the property of interest
* @param vcl a <code>VetoableChangeListener</code> value
*/
@Override
public void removeVetoableChangeListener(String name,
VetoableChangeListener vcl) {
m_bcSupport.removeVetoableChangeListener(name, vcl);
}
/**
* Accept a graph
*
* @param e a <code>GraphEvent</code> value
*/
@Override
public synchronized void acceptGraph(GraphEvent e) {
ArrayList<Object> graphInfo = new ArrayList<Object>();
if (m_history == null) {
setUpResultHistory();
}
String name = (new SimpleDateFormat("HH:mm:ss - ")).format(new Date());
name += e.getGraphTitle();
graphInfo.add(new Integer(e.getGraphType()));
graphInfo.add(e.getGraphString());
m_history.addResult(name, new StringBuffer());
m_history.addObject(name, graphInfo);
}
/**
* Set the visual appearance of this bean
*
* @param newVisual a <code>BeanVisual</code> value
*/
@Override
public void setVisual(BeanVisual newVisual) {
m_visual = newVisual;
}
/**
* Get the visual appearance of this bean
*
*/
@Override
public BeanVisual getVisual() {
return m_visual;
}
/**
* Use the default visual appearance
*
*/
@Override
public void useDefaultVisual() {
m_visual.loadIcons(BeanVisual.ICON_PATH + "DefaultGraph.gif",
BeanVisual.ICON_PATH + "DefaultGraph_animated.gif");
}
/**
* Popup a result list from which the user can select a graph to view
*
*/
public void showResults() {
if (m_resultsFrame == null) {
if (m_history == null) {
setUpResultHistory();
}
m_resultsFrame = Utils.getWekaJFrame("Graph Viewer", m_visual);
m_resultsFrame.getContentPane().setLayout(new BorderLayout());
m_resultsFrame.getContentPane().add(m_history, BorderLayout.CENTER);
m_resultsFrame.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
m_resultsFrame.dispose();
m_resultsFrame = null;
}
});
m_resultsFrame.pack();
m_resultsFrame.setLocationRelativeTo(SwingUtilities.getWindowAncestor(m_visual));
m_resultsFrame.setVisible(true);
} else {
m_resultsFrame.toFront();
}
}
@SuppressWarnings("unchecked")
private void doPopup(String name) {
ArrayList<Object> graph;
String grphString;
int grphType;
graph = (ArrayList<Object>) m_history.getNamedObject(name);
grphType = ((Integer) graph.get(0)).intValue();
grphString = (String) graph.get(graph.size() - 1);
if (grphType == Drawable.TREE) {
final javax.swing.JFrame jf = Utils.getWekaJFrame(
"Weka Classifier Tree Visualizer: " + name, m_resultsFrame);
jf.getContentPane().setLayout(new BorderLayout());
TreeVisualizer tv = new TreeVisualizer(null, grphString, new PlaceNode2());
jf.getContentPane().add(tv, BorderLayout.CENTER);
jf.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
jf.dispose();
}
});
jf.pack();
jf.setSize(500, 400);
jf.setLocationRelativeTo(m_resultsFrame);
jf.setVisible(true);
}
if (grphType == Drawable.BayesNet) {
final javax.swing.JFrame jf = Utils.getWekaJFrame(
"Weka Classifier Graph Visualizer: " + name, m_resultsFrame);
jf.getContentPane().setLayout(new BorderLayout());
GraphVisualizer gv = new GraphVisualizer();
try {
gv.readBIF(grphString);
} catch (BIFFormatException be) {
System.err.println("unable to visualize BayesNet");
be.printStackTrace();
}
gv.layoutGraph();
jf.getContentPane().add(gv, BorderLayout.CENTER);
jf.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
jf.dispose();
}
});
jf.pack();
jf.setSize(500, 400);
jf.setLocationRelativeTo(m_resultsFrame);
jf.setVisible(true);
}
}
/**
* Return an enumeration of user requests
*
* @return an <code>Enumeration</code> value
*/
@Override
public Enumeration<String> enumerateRequests() {
Vector<String> newVector = new Vector<String>(0);
newVector.addElement("Show results");
return newVector.elements();
}
/**
* Perform the named request
*
* @param request a <code>String</code> value
* @exception IllegalArgumentException if an error occurs
*/
@Override
public void performRequest(String request) {
if (request.compareTo("Show results") == 0) {
showResults();
} else {
throw new IllegalArgumentException(request
+ " not supported (GraphViewer)");
}
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/GraphViewerBeanInfo.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/>.
*/
/*
* GraphViewerBeanInfo.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.beans.EventSetDescriptor;
import java.beans.SimpleBeanInfo;
/**
* Bean info class for the graph viewer
*
* @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a>
* @version $Revision$
*/
public class GraphViewerBeanInfo extends SimpleBeanInfo {
/**
* Get the event set descriptors for this bean
*
* @return an <code>EventSetDescriptor[]</code> value
*/
public EventSetDescriptor [] getEventSetDescriptors() {
// hide all gui events
EventSetDescriptor [] esds = { };
return esds;
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/HeadlessEventCollector.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/>.
*/
/*
* HeadlessEventCollector.java
* Copyright (C) 2011-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.util.EventObject;
import java.util.List;
/**
* Interface for Knowledge Flow components that (typically) provide
* an interactive graphical visualization to implement. This allows
* events that would normally be processed to provide a graphical display
* to be collected and retrieved when running in headless mode (perhaps on
* a server for example). A copy of the component that is running with
* access to a display can be passed the list of events in order to
* construct its display-dependent output.
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com).
* @version $Revision$
*/
public interface HeadlessEventCollector {
/**
* Get the list of events processed in headless mode. May return
* null or an empty list if not running in headless mode or no
* events were processed
*
* @return a list of EventObjects or null.
*/
List<EventObject> retrieveHeadlessEvents();
/**
* Process a list of events that have been collected earlier. Has
* no affect if the component is running in headless mode.
*
* @param headless a list of EventObjects to process.
*/
void processHeadlessEvents(List<EventObject> headless);
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/ImageEvent.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/>.
*/
/*
* ImageEvent.java
* Copyright (C) 2011-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.awt.image.BufferedImage;
import java.util.EventObject;
/**
* Event that encapsulates an Image
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision$
*/
public class ImageEvent extends EventObject {
/** For serialization */
private static final long serialVersionUID = -8126533743311557969L;
/** The image */
protected BufferedImage m_image;
/** The name of the image */
protected String m_imageName = "";
/**
* Construct a new ImageEvent
*
* @param source the source of this event
* @param image the image to encapsulate
*/
public ImageEvent(Object source, BufferedImage image) {
this(source, image, "");
}
/**
* Construct an ImageEvent
*
* @param source the source of this event
* @param image the image to encapsulate
* @param imageName the name of the image
*/
public ImageEvent(Object source, BufferedImage image, String imageName) {
super(source);
m_image = image;
m_imageName = imageName;
}
/**
* Get the encapsulated image
*
* @return the encapsulated image
*/
public BufferedImage getImage() {
return m_image;
}
/**
* Get the name of the image
*
* @return
*/
public String getImageName() {
return m_imageName;
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/ImageListener.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/>.
*/
/*
* ImageListener.java
* Copyright (C) 2011-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.util.EventListener;
/**
* Interface to something that can process an ImageEvent
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision$
*/
public interface ImageListener extends EventListener {
/**
* Accept and process an ImageEvent
*
* @param image the image to process
*/
void acceptImage(ImageEvent image);
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/ImageSaver.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/>.
*/
/*
* ImageSaver.java
* Copyright (C) 2011-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.awt.BorderLayout;
import java.awt.image.BufferedImage;
import java.beans.EventSetDescriptor;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
import weka.core.Environment;
import weka.core.EnvironmentHandler;
import weka.gui.Logger;
/**
* Component that can accept ImageEvents and save their encapsulated
* images to a file.
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision$
*/
public class ImageSaver extends JPanel implements ImageListener, BeanCommon,
Visible, Serializable, EnvironmentHandler {
/**
* For serialization
*/
private static final long serialVersionUID = -641438159956934314L;
/**
* Default visual for data sources
*/
protected BeanVisual m_visual =
new BeanVisual("AbstractDataSink",
BeanVisual.ICON_PATH+"SerializedModelSaver.gif",
BeanVisual.ICON_PATH+"SerializedModelSaver_animated.gif");
/**
* Non null if this object is a target for any events.
* Provides for the simplest case when only one incomming connection
* is allowed.
*/
protected Object m_listenee = null;
/**
* The log for this bean
*/
protected transient weka.gui.Logger m_logger = null;
/**
* The environment variables.
*/
protected transient Environment m_env;
/** The file to save to */
protected String m_fileName;
/**
* Global info for this bean
*
* @return a <code>String</code> value
*/
public String globalInfo() {
return "Save static images (such as those produced by " +
"ModelPerformanceChart) to a file.";
}
/**
* Constructs a new ImageSaver
*/
public ImageSaver() {
useDefaultVisual();
setLayout(new BorderLayout());
add(m_visual, BorderLayout.CENTER);
m_env = Environment.getSystemWide();
}
/**
* Set the filename to save to
*
* @param filename the filename to save to
*/
public void setFilename(String filename) {
m_fileName = filename;
}
/**
* Get the filename to save to
*
* @return the filename to save to
*/
public String getFilename() {
return m_fileName;
}
/**
* Set environment variables to use
*
* @param env the environment variables to use
*/
public void setEnvironment(Environment env) {
m_env = env;
}
@Override
public void useDefaultVisual() {
m_visual.loadIcons(BeanVisual.ICON_PATH+"SerializedModelSaver.gif",
BeanVisual.ICON_PATH+"SerializedModelSaver_animated.gif");
m_visual.setText("ImageSaver");
}
@Override
public void setVisual(BeanVisual newVisual) {
m_visual = newVisual;
}
@Override
public BeanVisual getVisual() {
return m_visual;
}
@Override
public void setCustomName(String name) {
m_visual.setText(name);
}
@Override
public String getCustomName() {
return m_visual.getText();
}
@Override
public void stop() {
}
@Override
public boolean isBusy() {
return false;
}
@Override
public void setLog(Logger logger) {
m_logger = logger;
}
@Override
public boolean connectionAllowed(EventSetDescriptor esd) {
return connectionAllowed(esd.getName());
}
@Override
public boolean connectionAllowed(String eventName) {
return (m_listenee == null);
}
@Override
public void connectionNotification(String eventName, Object source) {
if (connectionAllowed(eventName)) {
m_listenee = source;
}
}
@Override
public void disconnectionNotification(String eventName, Object source) {
if (m_listenee == source) {
m_listenee = null;
}
}
/**
* Accept and process an ImageEvent
*
* @param imageE the ImageEvent to process
*/
public void acceptImage(ImageEvent imageE) {
BufferedImage image = imageE.getImage();
if (m_fileName != null && m_fileName.length() > 0) {
if (m_env == null) {
m_env = Environment.getSystemWide();
}
String filename = m_fileName;
try {
filename = m_env.substitute(m_fileName);
} catch (Exception ex) {
}
// append .png if necessary
if (filename.toLowerCase().indexOf(".png") < 0) {
filename += ".png";
}
File file = new File(filename);
if (!file.isDirectory()) {
try {
ImageIO.write(image, "png", file);
} catch (IOException e) {
if (m_logger != null) {
m_logger.statusMessage(statusMessagePrefix() + "WARNING: "
+ "an error occurred whilte trying to write image (see log)");
m_logger.logMessage("[" + getCustomName() + "] "
+ "an error occurred whilte trying to write image: " + e.getMessage());
} else {
e.printStackTrace();
}
}
} else {
String message = "Can't write image to file because supplied filename" +
" is a directory!";
if (m_logger != null) {
m_logger.statusMessage(statusMessagePrefix() + "WARNING: " + message);
m_logger.logMessage("[" + getCustomName() + "] " + message);
}
}
} else {
String message = "Can't write image bacause no filename has been supplied!" +
" is a directory!";
if (m_logger != null) {
m_logger.statusMessage(statusMessagePrefix() + "WARNING: " + message);
m_logger.logMessage("[" + getCustomName() + "] " + message);
}
}
}
private String statusMessagePrefix() {
return getCustomName() + "$" + hashCode() + "|";
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/ImageSaverBeanInfo.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/>.
*/
/*
* ImageSaverBeanInfo.java
* Copyright (C) 2011-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.beans.BeanDescriptor;
import java.beans.EventSetDescriptor;
import java.beans.SimpleBeanInfo;
/**
* BeanInfo class for the ImageSaver component.
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision$
*/
public class ImageSaverBeanInfo extends SimpleBeanInfo {
/**
* Get the event set descriptors for this bean
*
* @return an <code>EventSetDescriptor[]</code> value
*/
public EventSetDescriptor [] getEventSetDescriptors() {
// hide all gui events
EventSetDescriptor [] esds = { };
return esds;
}
/**
* Get the bean descriptor for this bean
*
* @return a <code>BeanDescriptor</code> value
*/
public BeanDescriptor getBeanDescriptor() {
return new BeanDescriptor(weka.gui.beans.ImageSaver.class,
ImageSaverCustomizer.class);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/ImageSaverCustomizer.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/>.
*/
/*
* ImageSaverCustomizer.java
* Copyright (C) 2011-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import weka.core.Environment;
import weka.core.EnvironmentHandler;
/**
* Customizer for the ImageSaver component.
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision$
*/
public class ImageSaverCustomizer extends JPanel implements BeanCustomizer,
EnvironmentHandler, CustomizerClosingListener, CustomizerCloseRequester {
/**
* For serialization
*/
private static final long serialVersionUID = 5215477777077643368L;
private ImageSaver m_imageSaver;
private FileEnvironmentField m_fileEditor;
private Environment m_env = Environment.getSystemWide();
private ModifyListener m_modifyListener;
private Window m_parent;
private String m_fileBackup;
/**
* Constructor
*/
public ImageSaverCustomizer() {
setLayout(new BorderLayout());
}
/**
* Set the ImageSaver object to customize.
*
* @param object the ImageSaver to customize
*/
public void setObject(Object object) {
m_imageSaver = (ImageSaver)object;
m_fileBackup = m_imageSaver.getFilename();
setup();
}
private void setup() {
JPanel holder = new JPanel();
holder.setLayout(new BorderLayout());
m_fileEditor = new FileEnvironmentField("Filename", m_env,
JFileChooser.SAVE_DIALOG);
m_fileEditor.resetFileFilters();
holder.add(m_fileEditor, BorderLayout.SOUTH);
String globalInfo = m_imageSaver.globalInfo();
JTextArea jt = new JTextArea();
jt.setColumns(30);
jt.setFont(new Font("SansSerif", Font.PLAIN,12));
jt.setEditable(false);
jt.setLineWrap(true);
jt.setWrapStyleWord(true);
jt.setText(globalInfo);
jt.setBackground(getBackground());
JPanel jp = new JPanel();
jp.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createTitledBorder("About"),
BorderFactory.createEmptyBorder(5, 5, 5, 5)
));
jp.setLayout(new BorderLayout());
jp.add(jt, BorderLayout.CENTER);
holder.add(jp, BorderLayout.NORTH);
add(holder, BorderLayout.CENTER);
addButtons();
m_fileEditor.setText(m_imageSaver.getFilename());
}
private void addButtons() {
JButton okBut = new JButton("OK");
JButton cancelBut = new JButton("Cancel");
JPanel butHolder = new JPanel();
butHolder.setLayout(new GridLayout(1, 2));
butHolder.add(okBut); butHolder.add(cancelBut);
add(butHolder, BorderLayout.SOUTH);
okBut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
m_imageSaver.setFilename(m_fileEditor.getText());
if (m_modifyListener != null) {
m_modifyListener.
setModifiedStatus(ImageSaverCustomizer.this, true);
}
if (m_parent != null) {
m_parent.dispose();
}
}
});
cancelBut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
customizerClosing();
if (m_parent != null) {
m_parent.dispose();
}
}
});
}
/**
* Set the environment variables to use
*
* @param env the environment variables to use
*/
public void setEnvironment(Environment env) {
m_env = env;
}
/**
* Set a listener interested in whether we've modified
* the ImageSaver that we're customizing
*
* @param l the listener
*/
public void setModifiedListener(ModifyListener l) {
m_modifyListener = l;
}
/**
* Set the parent window of this dialog
*
* @param parent the parent window
*/
public void setParentWindow(Window parent) {
m_parent = parent;
}
/**
* Gets called if the use closes the dialog via the
* close widget on the window - is treated as cancel,
* so restores the ImageSaver to its previous state.
*/
public void customizerClosing() {
m_imageSaver.setFilename(m_fileBackup);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/ImageViewer.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/>.
*/
/*
* ImageViewer.java
* Copyright (C) 2002-2014 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.beans.EventSetDescriptor;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.Vector;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import weka.core.Environment;
import weka.core.Utils;
import weka.gui.Logger;
import weka.gui.ResultHistoryPanel;
/**
* A KF component that can accept imageEvent connections in order to display
* static images in a popup window
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision$
*/
@KFStep(category = "Visualization", toolTipText = "Display static images")
public class ImageViewer extends JPanel implements ImageListener, BeanCommon,
Visible, Serializable, UserRequestAcceptor {
/**
* For serialization
*/
private static final long serialVersionUID = 7976930810628389750L;
/** Panel for displaying the image */
protected ImageDisplayer m_plotter;
/** Keeps a history of the images received */
protected ResultHistoryPanel m_history;
/** Frame for displaying the images in */
private transient JFrame m_resultsFrame = null;
/**
* Default visual for data sources
*/
protected BeanVisual m_visual = new BeanVisual("ImageVisualizer",
BeanVisual.ICON_PATH + "StripChart.gif", BeanVisual.ICON_PATH
+ "StripChart_animated.gif");
/**
* The log for this bean
*/
protected transient weka.gui.Logger m_logger = null;
/**
* The environment variables.
*/
protected transient Environment m_env;
/**
* Constructs a new ImageViewer
*/
public ImageViewer() {
useDefaultVisual();
setLayout(new BorderLayout());
add(m_visual, BorderLayout.CENTER);
m_env = Environment.getSystemWide();
m_plotter = new ImageDisplayer();
// m_plotter.setBorder(BorderFactory.createTitledBorder("Image"));
m_plotter.setMinimumSize(new Dimension(810, 610));
m_plotter.setPreferredSize(new Dimension(810, 610));
setUpResultHistory();
}
/**
* Global info for this bean
*
* @return a <code>String</code> value
*/
public String globalInfo() {
return "Display static images";
}
@Override
public void useDefaultVisual() {
m_visual.loadIcons(BeanVisual.ICON_PATH + "StripChart.gif",
BeanVisual.ICON_PATH + "StripChart_animated.gif");
m_visual.setText("ImageViewer");
}
@Override
public void setVisual(BeanVisual newVisual) {
m_visual = newVisual;
}
@Override
public BeanVisual getVisual() {
return m_visual;
}
@Override
public void setCustomName(String name) {
m_visual.setText(name);
}
@Override
public String getCustomName() {
return m_visual.getText();
}
@Override
public void stop() {
}
@Override
public boolean isBusy() {
return false;
}
@Override
public void setLog(Logger logger) {
m_logger = logger;
}
@Override
public boolean connectionAllowed(EventSetDescriptor esd) {
return connectionAllowed(esd.getName());
}
@Override
public boolean connectionAllowed(String eventName) {
return true;
}
@Override
public void connectionNotification(String eventName, Object source) {
}
@Override
public void disconnectionNotification(String eventName, Object source) {
}
@Override
public synchronized void acceptImage(ImageEvent imageE) {
BufferedImage image = imageE.getImage();
String name = (new SimpleDateFormat("HH:mm:ss:SS")).format(new Date());
name =
(imageE.getImageName() == null || imageE.getImageName().length() == 0 ? "Image at "
: imageE.getImageName() + " ")
+ name;
m_history.addResult(name, new StringBuffer());
m_history.addObject(name, image);
m_plotter.setImage(image);
m_plotter.repaint();
}
/**
* Popup the window to display the images in
*/
protected void showResults() {
if (m_resultsFrame == null) {
if (m_history == null) {
setUpResultHistory();
}
m_resultsFrame = Utils.getWekaJFrame("Image Viewer", m_visual);
m_resultsFrame.getContentPane().setLayout(new BorderLayout());
m_resultsFrame.getContentPane().add(new MainPanel(m_history, m_plotter),
BorderLayout.CENTER);
m_resultsFrame.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
m_resultsFrame.dispose();
m_resultsFrame = null;
}
});
m_resultsFrame.pack();
m_resultsFrame.setLocationRelativeTo(SwingUtilities.getWindowAncestor(m_visual));
m_resultsFrame.setVisible(true);
} else {
m_resultsFrame.toFront();
}
}
private void setUpResultHistory() {
if (m_history == null) {
m_history = new ResultHistoryPanel(null);
}
m_history.setBorder(BorderFactory.createTitledBorder("Image list"));
m_history.setHandleRightClicks(false);
m_history.getList().addMouseListener(
new ResultHistoryPanel.RMouseAdapter() {
/** for serialization */
private static final long serialVersionUID = -4984130887963944249L;
@Override
public void mouseClicked(MouseEvent e) {
int index = m_history.getList().locationToIndex(e.getPoint());
if (index != -1) {
String name = m_history.getNameAtIndex(index);
// doPopup(name);
Object pic = m_history.getNamedObject(name);
if (pic instanceof BufferedImage) {
m_plotter.setImage((BufferedImage) pic);
m_plotter.repaint();
}
}
}
});
m_history.getList().getSelectionModel()
.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
ListSelectionModel lm = (ListSelectionModel) e.getSource();
for (int i = e.getFirstIndex(); i <= e.getLastIndex(); i++) {
if (lm.isSelectedIndex(i)) {
// m_AttSummaryPanel.setAttribute(i);
if (i != -1) {
String name = m_history.getNameAtIndex(i);
Object pic = m_history.getNamedObject(name);
if (pic != null && pic instanceof BufferedImage) {
m_plotter.setImage((BufferedImage) pic);
m_plotter.repaint();
}
}
break;
}
}
}
}
});
}
/**
* Small inner class for laying out the main parts of the popup display
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
*/
private static class MainPanel extends JPanel {
private static Image loadImage(String path) {
Image pic = null;
java.net.URL imageURL =
ImageViewer.class.getClassLoader().getResource(path);
// end modifications
if (imageURL == null) {
} else {
pic = Toolkit.getDefaultToolkit().getImage(imageURL);
}
return pic;
}
/**
* For serialization
*/
private static final long serialVersionUID = 5648976848887609072L;
public MainPanel(ResultHistoryPanel p, final ImageDisplayer id) {
super();
setLayout(new BorderLayout());
JPanel topP = new JPanel();
topP.setLayout(new BorderLayout());
JPanel holder = new JPanel();
holder.setLayout(new BorderLayout());
holder.setBorder(BorderFactory.createTitledBorder("Image"));
JToolBar tools = new JToolBar();
tools.setOrientation(JToolBar.HORIZONTAL);
JButton zoomInB =
new JButton(new ImageIcon(loadImage(BeanVisual.ICON_PATH
+ "zoom_in.png")));
zoomInB.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int z = id.getZoom();
z += 25;
if (z >= 200) {
z = 200;
}
id.setZoom(z);
id.repaint();
}
});
JButton zoomOutB =
new JButton(new ImageIcon(loadImage(BeanVisual.ICON_PATH
+ "zoom_out.png")));
zoomOutB.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int z = id.getZoom();
z -= 25;
if (z <= 50) {
z = 50;
}
id.setZoom(z);
id.repaint();
}
});
tools.add(zoomInB);
tools.add(zoomOutB);
holder.add(tools, BorderLayout.NORTH);
JScrollPane js = new JScrollPane(id);
holder.add(js, BorderLayout.CENTER);
topP.add(holder, BorderLayout.CENTER);
topP.add(p, BorderLayout.WEST);
add(topP, BorderLayout.CENTER);
}
}
/**
* Inner class for displaying a BufferedImage.
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision$
*/
private static class ImageDisplayer extends JPanel {
/** For serialization */
private static final long serialVersionUID = 4161957589912537357L;
/** The image to display */
private BufferedImage m_image;
private int m_imageZoom = 100;
/**
* Set the image to display
*
* @param image the image to display
*/
public void setImage(BufferedImage image) {
m_image = image;
}
public void setZoom(int zoom) {
m_imageZoom = zoom;
}
public int getZoom() {
return m_imageZoom;
}
/**
* Render the image
*
* @param g the graphics context
*/
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (m_image != null) {
double lz = m_imageZoom / 100.0;
((Graphics2D) g).scale(lz, lz);
int plotWidth = m_image.getWidth();
int plotHeight = m_image.getHeight();
int ourWidth = getWidth();
int ourHeight = getHeight();
// center if plot is smaller than us
int x = 0, y = 0;
if (plotWidth < ourWidth) {
x = (ourWidth - plotWidth) / 2;
}
if (plotHeight < ourHeight) {
y = (ourHeight - plotHeight) / 2;
}
g.drawImage(m_image, x, y, this);
setPreferredSize(new Dimension(plotWidth, plotHeight));
revalidate();
}
}
}
@Override
public Enumeration<String> enumerateRequests() {
Vector<String> newVector = new Vector<String>(0);
newVector.addElement("Show results");
return newVector.elements();
}
@Override
public void performRequest(String request) {
if (request.compareTo("Show results") == 0) {
showResults();
} else {
throw new IllegalArgumentException(request
+ " not supported (ImageViewer)");
}
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/ImageViewerBeanInfo.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/>.
*/
/*
* ImageViewerBeanInfo.java
* Copyright (C) 2002-2014 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.beans.EventSetDescriptor;
import java.beans.SimpleBeanInfo;
/**
* BeanInfo class for the ImageViewer component
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision$
*/
public class ImageViewerBeanInfo extends SimpleBeanInfo {
/**
* Get the event set descriptors for this bean
*
* @return an <code>EventSetDescriptor[]</code> value
*/
@Override
public EventSetDescriptor[] getEventSetDescriptors() {
// hide all gui events
EventSetDescriptor[] esds = {};
return esds;
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/IncrementalClassifierEvaluator.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/>.
*/
/*
* IncrementalClassifierEvaluator.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.util.LinkedList;
import java.util.Vector;
import weka.classifiers.Evaluation;
import weka.core.Instance;
import weka.core.Utils;
/**
* Bean that evaluates incremental classifiers
*
* @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a>
* @version $Revision$
*/
public class IncrementalClassifierEvaluator extends AbstractEvaluator implements
IncrementalClassifierListener, EventConstraints {
/** for serialization */
private static final long serialVersionUID = -3105419818939541291L;
private transient Evaluation m_eval;
private final Vector<ChartListener> m_listeners = new Vector<ChartListener>();
private final Vector<TextListener> m_textListeners = new Vector<TextListener>();
private Vector<String> m_dataLegend = new Vector<String>();
private final ChartEvent m_ce = new ChartEvent(this);
private double[] m_dataPoint = new double[1];
private boolean m_reset = false;
private double m_min = Double.MAX_VALUE;
private double m_max = Double.MIN_VALUE;
// how often (in milliseconds) to report throughput to the log
private int m_statusFrequency = 2000;
private int m_instanceCount = 0;
// output info retrieval and auc stats for each class (if class is nominal)
private boolean m_outputInfoRetrievalStats = false;
// window size for computing performance metrics - 0 means no window, i.e
// don't "forget" performance on any instances
private int m_windowSize = 0;
private Evaluation m_windowEval;
private LinkedList<Instance> m_window;
private LinkedList<double[]> m_windowedPreds;
public IncrementalClassifierEvaluator() {
m_visual.loadIcons(BeanVisual.ICON_PATH
+ "IncrementalClassifierEvaluator.gif", BeanVisual.ICON_PATH
+ "IncrementalClassifierEvaluator_animated.gif");
m_visual.setText("IncrementalClassifierEvaluator");
}
/**
* Set a custom (descriptive) name for this bean
*
* @param name the name to use
*/
@Override
public void setCustomName(String name) {
m_visual.setText(name);
}
/**
* Get the custom (descriptive) name for this bean (if one has been set)
*
* @return the custom name (or the default name)
*/
@Override
public String getCustomName() {
return m_visual.getText();
}
/**
* Global info for this bean
*
* @return a <code>String</code> value
*/
public String globalInfo() {
return "Evaluate the performance of incrementally trained classifiers.";
}
protected transient StreamThroughput m_throughput;
/**
* Accepts and processes a classifier encapsulated in an incremental
* classifier event
*
* @param ce an <code>IncrementalClassifierEvent</code> value
*/
@Override
public void acceptClassifier(final IncrementalClassifierEvent ce) {
try {
if (ce.getStatus() == IncrementalClassifierEvent.NEW_BATCH) {
m_throughput = new StreamThroughput(statusMessagePrefix());
m_throughput.setSamplePeriod(m_statusFrequency);
// m_eval = new Evaluation(ce.getCurrentInstance().dataset());
m_eval = new Evaluation(ce.getStructure());
m_eval.useNoPriors();
m_dataLegend = new Vector<String>();
m_reset = true;
m_dataPoint = new double[0];
ce.getStructure();
System.err.println("NEW BATCH");
m_instanceCount = 0;
if (m_windowSize > 0) {
m_window = new LinkedList<Instance>();
m_windowEval = new Evaluation(ce.getStructure());
m_windowEval.useNoPriors();
m_windowedPreds = new LinkedList<double[]>();
if (m_logger != null) {
m_logger.logMessage(statusMessagePrefix()
+ "[IncrementalClassifierEvaluator] Chart output using windowed "
+ "evaluation over " + m_windowSize + " instances");
}
}
/*
* if (m_logger != null) { m_logger.statusMessage(statusMessagePrefix()
* + "IncrementalClassifierEvaluator: started processing...");
* m_logger.logMessage(statusMessagePrefix() +
* " [IncrementalClassifierEvaluator]" + statusMessagePrefix() +
* " started processing..."); }
*/
} else {
Instance inst = ce.getCurrentInstance();
if (inst != null) {
m_throughput.updateStart();
m_instanceCount++;
// if (inst.attribute(inst.classIndex()).isNominal()) {
double[] dist = ce.getClassifier().distributionForInstance(inst);
double pred = 0;
if (!inst.isMissing(inst.classIndex())) {
if (m_outputInfoRetrievalStats) {
// store predictions so AUC etc can be output.
m_eval.evaluateModelOnceAndRecordPrediction(dist, inst);
} else {
m_eval.evaluateModelOnce(dist, inst);
}
if (m_windowSize > 0) {
m_windowEval.evaluateModelOnce(dist, inst);
m_window.addFirst(inst);
m_windowedPreds.addFirst(dist);
if (m_instanceCount > m_windowSize) {
// "forget" the oldest prediction
Instance oldest = m_window.removeLast();
double[] oldDist = m_windowedPreds.removeLast();
oldest.setWeight(-oldest.weight());
m_windowEval.evaluateModelOnce(oldDist, oldest);
oldest.setWeight(-oldest.weight());
}
}
} else {
pred = ce.getClassifier().classifyInstance(inst);
}
if (inst.classIndex() >= 0) {
// need to check that the class is not missing
if (inst.attribute(inst.classIndex()).isNominal()) {
if (!inst.isMissing(inst.classIndex())) {
if (m_dataPoint.length < 2) {
m_dataPoint = new double[3];
m_dataLegend.addElement("Accuracy");
m_dataLegend.addElement("RMSE (prob)");
m_dataLegend.addElement("Kappa");
}
// int classV = (int) inst.value(inst.classIndex());
if (m_windowSize > 0) {
m_dataPoint[1] = m_windowEval.rootMeanSquaredError();
m_dataPoint[2] = m_windowEval.kappa();
} else {
m_dataPoint[1] = m_eval.rootMeanSquaredError();
m_dataPoint[2] = m_eval.kappa();
}
// int maxO = Utils.maxIndex(dist);
// if (maxO == classV) {
// dist[classV] = -1;
// maxO = Utils.maxIndex(dist);
// }
// m_dataPoint[1] -= dist[maxO];
} else {
if (m_dataPoint.length < 1) {
m_dataPoint = new double[1];
m_dataLegend.addElement("Confidence");
}
}
double primaryMeasure = 0;
if (!inst.isMissing(inst.classIndex())) {
if (m_windowSize > 0) {
primaryMeasure = 1.0 - m_windowEval.errorRate();
} else {
primaryMeasure = 1.0 - m_eval.errorRate();
}
} else {
// record confidence as the primary measure
// (another possibility would be entropy of
// the distribution, or perhaps average
// confidence)
primaryMeasure = dist[Utils.maxIndex(dist)];
}
// double [] dataPoint = new double[1];
m_dataPoint[0] = primaryMeasure;
// double min = 0; double max = 100;
/*
* ChartEvent e = new
* ChartEvent(IncrementalClassifierEvaluator.this, m_dataLegend,
* min, max, dataPoint);
*/
m_ce.setLegendText(m_dataLegend);
m_ce.setMin(0);
m_ce.setMax(1);
m_ce.setDataPoint(m_dataPoint);
m_ce.setReset(m_reset);
m_reset = false;
} else {
// numeric class
if (m_dataPoint.length < 1) {
m_dataPoint = new double[1];
if (inst.isMissing(inst.classIndex())) {
m_dataLegend.addElement("Prediction");
} else {
m_dataLegend.addElement("RMSE");
}
}
if (!inst.isMissing(inst.classIndex())) {
double update;
if (!inst.isMissing(inst.classIndex())) {
if (m_windowSize > 0) {
update = m_windowEval.rootMeanSquaredError();
} else {
update = m_eval.rootMeanSquaredError();
}
} else {
update = pred;
}
m_dataPoint[0] = update;
if (update > m_max) {
m_max = update;
}
if (update < m_min) {
m_min = update;
}
}
m_ce.setLegendText(m_dataLegend);
m_ce.setMin((inst.isMissing(inst.classIndex()) ? m_min : 0));
m_ce.setMax(m_max);
m_ce.setDataPoint(m_dataPoint);
m_ce.setReset(m_reset);
m_reset = false;
}
notifyChartListeners(m_ce);
}
m_throughput.updateEnd(m_logger);
}
if (ce.getStatus() == IncrementalClassifierEvent.BATCH_FINISHED
|| inst == null) {
if (m_logger != null) {
m_logger.logMessage("[IncrementalClassifierEvaluator]"
+ statusMessagePrefix() + " Finished processing.");
}
m_throughput.finished(m_logger);
// save memory if using windowed evaluation for charting
m_windowEval = null;
m_window = null;
m_windowedPreds = null;
if (m_textListeners.size() > 0) {
String textTitle = ce.getClassifier().getClass().getName();
textTitle = textTitle.substring(textTitle.lastIndexOf('.') + 1,
textTitle.length());
String results = "=== Performance information ===\n\n"
+ "Scheme: " + textTitle + "\n" + "Relation: "
+ m_eval.getHeader().relationName() + "\n\n"
+ m_eval.toSummaryString();
if (m_eval.getHeader().classIndex() >= 0
&& m_eval.getHeader().classAttribute().isNominal()
&& (m_outputInfoRetrievalStats)) {
results += "\n" + m_eval.toClassDetailsString();
}
if (m_eval.getHeader().classIndex() >= 0
&& m_eval.getHeader().classAttribute().isNominal()) {
results += "\n" + m_eval.toMatrixString();
}
textTitle = "Results: " + textTitle;
TextEvent te = new TextEvent(this, results, textTitle);
notifyTextListeners(te);
}
}
}
} catch (Exception ex) {
if (m_logger != null) {
m_logger.logMessage("[IncrementalClassifierEvaluator]"
+ statusMessagePrefix() + " Error processing prediction "
+ ex.getMessage());
m_logger.statusMessage(statusMessagePrefix()
+ "ERROR: problem processing prediction (see log for details)");
}
ex.printStackTrace();
stop();
}
}
/**
* Returns true, if at the current time, the named event could be generated.
* Assumes that supplied event names are names of events that could be
* generated by this bean.
*
* @param eventName the name of the event in question
* @return true if the named event could be generated at this point in time
*/
@Override
public boolean eventGeneratable(String eventName) {
if (m_listenee == null) {
return false;
}
if (m_listenee instanceof EventConstraints) {
if (!((EventConstraints) m_listenee)
.eventGeneratable("incrementalClassifier")) {
return false;
}
}
return true;
}
/**
* Stop all action
*/
@Override
public void stop() {
// tell the listenee (upstream bean) to stop
if (m_listenee instanceof BeanCommon) {
// System.err.println("Listener is BeanCommon");
((BeanCommon) m_listenee).stop();
}
}
/**
* Returns true if. at this time, the bean is busy with some (i.e. perhaps a
* worker thread is performing some calculation).
*
* @return true if the bean is busy.
*/
@Override
public boolean isBusy() {
return false;
}
@SuppressWarnings("unchecked")
private void notifyChartListeners(ChartEvent ce) {
Vector<ChartListener> l;
synchronized (this) {
l = (Vector<ChartListener>) m_listeners.clone();
}
if (l.size() > 0) {
for (int i = 0; i < l.size(); i++) {
l.elementAt(i).acceptDataPoint(ce);
}
}
}
/**
* Notify all text listeners of a TextEvent
*
* @param te a <code>TextEvent</code> value
*/
@SuppressWarnings("unchecked")
private void notifyTextListeners(TextEvent te) {
Vector<TextListener> l;
synchronized (this) {
l = (Vector<TextListener>) m_textListeners.clone();
}
if (l.size() > 0) {
for (int i = 0; i < l.size(); i++) {
// System.err.println("Notifying text listeners "
// +"(ClassifierPerformanceEvaluator)");
l.elementAt(i).acceptText(te);
}
}
}
/**
* Set how often progress is reported to the status bar.
*
* @param s report progress every s instances
*/
public void setStatusFrequency(int s) {
m_statusFrequency = s;
}
/**
* Get how often progress is reported to the status bar.
*
* @return after how many instances, progress is reported to the status bar
*/
public int getStatusFrequency() {
return m_statusFrequency;
}
/**
* Return a tip text string for this property
*
* @return a string for the tip text
*/
public String statusFrequencyTipText() {
return "How often to report progress to the status bar.";
}
/**
* Set whether to output per-class information retrieval statistics (nominal
* class only).
*
* @param i true if info retrieval stats are to be output
*/
public void setOutputPerClassInfoRetrievalStats(boolean i) {
m_outputInfoRetrievalStats = i;
}
/**
* Get whether per-class information retrieval stats are to be output.
*
* @return true if info retrieval stats are to be output
*/
public boolean getOutputPerClassInfoRetrievalStats() {
return m_outputInfoRetrievalStats;
}
/**
* Return a tip text string for this property
*
* @return a string for the tip text
*/
public String outputPerClassInfoRetrievalStatsTipText() {
return "Output per-class info retrieval stats. If set to true, predictions get "
+ "stored so that stats such as AUC can be computed. Note: this consumes some memory.";
}
/**
* Set whether to compute evaluation for charting over a fixed sized window of
* the most recent instances (rather than the whole stream).
*
* @param windowSize the size of the window to use for computing the
* evaluation metrics used for charting. Setting a value of zero or
* less specifies that no windowing is to be used.
*/
public void setChartingEvalWindowSize(int windowSize) {
m_windowSize = windowSize;
}
/**
* Get whether to compute evaluation for charting over a fixed sized window of
* the most recent instances (rather than the whole stream).
*
* @return the size of the window to use for computing the evaluation metrics
* used for charting. Setting a value of zero or less specifies that
* no windowing is to be used.
*/
public int getChartingEvalWindowSize() {
return m_windowSize;
}
/**
* Return a tip text string for this property
*
* @return a string for the tip text
*/
public String chartingEvalWindowSizeTipText() {
return "For charting only, specify a sliding window size over which to compute "
+ "performance stats. <= 0 means eval on whole stream";
}
/**
* Add a chart listener
*
* @param cl a <code>ChartListener</code> value
*/
public synchronized void addChartListener(ChartListener cl) {
m_listeners.addElement(cl);
}
/**
* Remove a chart listener
*
* @param cl a <code>ChartListener</code> value
*/
public synchronized void removeChartListener(ChartListener cl) {
m_listeners.remove(cl);
}
/**
* Add a text listener
*
* @param cl a <code>TextListener</code> value
*/
public synchronized void addTextListener(TextListener cl) {
m_textListeners.addElement(cl);
}
/**
* Remove a text listener
*
* @param cl a <code>TextListener</code> value
*/
public synchronized void removeTextListener(TextListener cl) {
m_textListeners.remove(cl);
}
private String statusMessagePrefix() {
return getCustomName() + "$" + hashCode() + "|";
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/IncrementalClassifierEvaluatorBeanInfo.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/>.
*/
/*
* IncrementalClassifierEvaluatorBeanInfo.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.beans.BeanDescriptor;
import java.beans.EventSetDescriptor;
import java.beans.PropertyDescriptor;
import java.beans.SimpleBeanInfo;
/**
* Bean info class for the incremental classifier evaluator bean
*
* @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a>
* @version $Revision$
*/
public class IncrementalClassifierEvaluatorBeanInfo extends SimpleBeanInfo {
/**
* Return the property descriptors for this bean
*
* @return a <code>PropertyDescriptor[]</code> value
*/
public PropertyDescriptor[] getPropertyDescriptors() {
try {
PropertyDescriptor p1;
PropertyDescriptor p2;
PropertyDescriptor p3;
p1 = new PropertyDescriptor("statusFrequency", IncrementalClassifierEvaluator.class);
p2 = new PropertyDescriptor("outputPerClassInfoRetrievalStats",
IncrementalClassifierEvaluator.class);
p3 = new PropertyDescriptor("chartingEvalWindowSize",
IncrementalClassifierEvaluator.class);
PropertyDescriptor [] pds = { p1, p2, p3 };
return pds;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
/**
* Get the event set descriptors for this bean
*
* @return an <code>EventSetDescriptor[]</code> value
*/
public EventSetDescriptor [] getEventSetDescriptors() {
try {
EventSetDescriptor [] esds = {
new EventSetDescriptor(IncrementalClassifierEvaluator.class,
"chart",
ChartListener.class,
"acceptDataPoint"),
new EventSetDescriptor(IncrementalClassifierEvaluator.class,
"text",
TextListener.class,
"acceptText")
};
return esds;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
/**
* Return the bean descriptor for this bean
*
* @return a <code>BeanDescriptor</code> value
*/
public BeanDescriptor getBeanDescriptor() {
return new BeanDescriptor(weka.gui.beans.IncrementalClassifierEvaluator.class,
IncrementalClassifierEvaluatorCustomizer.class);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/IncrementalClassifierEvaluatorCustomizer.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/>.
*/
/*
* IncrementalClassifierEvaluatorCustomizer.java
* Copyright (C) 2008-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import javax.swing.JButton;
import javax.swing.JPanel;
import weka.gui.PropertySheetPanel;
/**
* GUI Customizer for the incremental classifier evaluator bean
*
* @author Mark Hall (mhall{[at}]pentaho{[dot]}org
* @version $Revision$
*/
public class IncrementalClassifierEvaluatorCustomizer extends JPanel implements
BeanCustomizer, CustomizerCloseRequester, CustomizerClosingListener {
/** Added ID to avoid warning */
private static final long serialVersionUID = 443506897387629418L;
/** for serialization */
// private static final long serialVersionUID = 1229878140258668581L;
private final PropertyChangeSupport m_pcSupport = new PropertyChangeSupport(
this);
private final PropertySheetPanel m_ieEditor = new PropertySheetPanel();
private IncrementalClassifierEvaluator m_evaluator;
private ModifyListener m_modifyListener;
private Window m_parent;
private int m_freqBackup;
private boolean m_perClassBackup;
public IncrementalClassifierEvaluatorCustomizer() {
setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 5, 5, 5));
setLayout(new BorderLayout());
add(m_ieEditor, BorderLayout.CENTER);
add(new javax.swing.JLabel("IncrementalClassifierEvaluatorCustomizer"),
BorderLayout.NORTH);
addButtons();
}
private void addButtons() {
JButton okBut = new JButton("OK");
JButton cancelBut = new JButton("Cancel");
JPanel butHolder = new JPanel();
butHolder.setLayout(new GridLayout(1, 2));
butHolder.add(okBut);
butHolder.add(cancelBut);
add(butHolder, BorderLayout.SOUTH);
okBut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
m_modifyListener.setModifiedStatus(
IncrementalClassifierEvaluatorCustomizer.this, true);
if (m_parent != null) {
m_parent.dispose();
}
}
});
cancelBut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
customizerClosing();
if (m_parent != null) {
m_parent.dispose();
}
}
});
}
/**
* Set the object to be edited
*
* @param object a IncrementalClassifierEvaluator object
*/
@Override
public void setObject(Object object) {
m_evaluator = ((IncrementalClassifierEvaluator) object);
m_ieEditor.setTarget(m_evaluator);
m_freqBackup = m_evaluator.getStatusFrequency();
m_perClassBackup = m_evaluator.getOutputPerClassInfoRetrievalStats();
}
/**
* Add a property change listener
*
* @param pcl a <code>PropertyChangeListener</code> value
*/
@Override
public void addPropertyChangeListener(PropertyChangeListener pcl) {
m_pcSupport.addPropertyChangeListener(pcl);
}
/**
* Remove a property change listener
*
* @param pcl a <code>PropertyChangeListener</code> value
*/
@Override
public void removePropertyChangeListener(PropertyChangeListener pcl) {
m_pcSupport.removePropertyChangeListener(pcl);
}
@Override
public void setModifiedListener(ModifyListener l) {
m_modifyListener = l;
}
@Override
public void setParentWindow(Window parent) {
m_parent = parent;
}
@Override
public void customizerClosing() {
// restore original state (window closed or cancel pressed)
m_evaluator.setStatusFrequency(m_freqBackup);
m_evaluator.setOutputPerClassInfoRetrievalStats(m_perClassBackup);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/IncrementalClassifierEvent.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/>.
*/
/*
* IncrementalClassifierEvent.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.util.EventObject;
import weka.classifiers.Classifier;
import weka.core.Instance;
import weka.core.Instances;
/**
* Class encapsulating an incrementally built classifier and current instance
*
* @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a>
* @version $Revision$
* @since 1.0
* @see EventObject
*/
public class IncrementalClassifierEvent
extends EventObject {
/** for serialization */
private static final long serialVersionUID = 28979464317643232L;
public static final int NEW_BATCH = 0;
public static final int WITHIN_BATCH = 1;
public static final int BATCH_FINISHED = 2;
private Instances m_structure;
private int m_status;
protected Classifier m_classifier;
protected Instance m_currentInstance;
/**
* Creates a new <code>IncrementalClassifierEvent</code> instance.
*
* @param source the source of the event
* @param scheme the classifier
* @param currentI the current instance
* @param status the status
*/
public IncrementalClassifierEvent(Object source, Classifier scheme,
Instance currentI, int status) {
super(source);
// m_trainingSet = trnI;
m_classifier = scheme;
m_currentInstance = currentI;
m_status = status;
}
/**
* Creates a new incremental classifier event that encapsulates
* header information and classifier.
*
* @param source an <code>Object</code> value
* @param scheme a <code>Classifier</code> value
* @param structure an <code>Instances</code> value
*/
public IncrementalClassifierEvent(Object source, Classifier scheme,
Instances structure) {
super(source);
m_structure = structure;
m_status = NEW_BATCH;
m_classifier = scheme;
}
public IncrementalClassifierEvent(Object source) {
super(source);
}
/**
* Get the classifier
*
* @return the classifier
*/
public Classifier getClassifier() {
return m_classifier;
}
public void setClassifier(Classifier c) {
m_classifier = c;
}
/**
* Get the current instance
*
* @return the current instance
*/
public Instance getCurrentInstance() {
return m_currentInstance;
}
/**
* Set the current instance for this event
*
* @param i an <code>Instance</code> value
*/
public void setCurrentInstance(Instance i) {
m_currentInstance = i;
}
/**
* Get the status
*
* @return an <code>int</code> value
*/
public int getStatus() {
return m_status;
}
/**
* Set the status
*
* @param s an <code>int</code> value
*/
public void setStatus(int s) {
m_status = s;
}
/**
* Set the instances structure
*
* @param structure an <code>Instances</code> value
*/
public void setStructure(Instances structure) {
m_structure = structure;
m_currentInstance = null;
m_status = NEW_BATCH;
}
/**
* Get the instances structure (may be null if this is not
* a NEW_BATCH event)
*
* @return an <code>Instances</code> value
*/
public Instances getStructure() {
return m_structure;
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/IncrementalClassifierListener.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/>.
*/
/*
* IncrementalClassifierListener.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.util.EventListener;
/**
* Interface to something that can process a IncrementalClassifierEvent
*
* @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a>
* @version $Revision$
* @since 1.0
* @see EventListener
*/
public interface IncrementalClassifierListener extends EventListener {
/**
* Accept the event
*
* @param e a <code>ClassifierEvent</code> value
*/
void acceptClassifier(IncrementalClassifierEvent e);
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/InstanceEvent.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/>.
*/
/*
* InstanceEvent.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.util.EventObject;
import weka.core.Instance;
import weka.core.Instances;
/**
* Event that encapsulates a single instance or header information only
*
* @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a>
* @version $Revision$
* @see EventObject
*/
public class InstanceEvent extends EventObject {
/** for serialization */
private static final long serialVersionUID = 6104920894559423946L;
public static final int FORMAT_AVAILABLE = 0;
public static final int INSTANCE_AVAILABLE = 1;
public static final int BATCH_FINISHED = 2;
private Instances m_structure;
private Instance m_instance;
private int m_status;
/**
* for FORMAT_AVAILABLE, if this is true then it indicates that this is not
* the actual start of stream processing, but rather that a file/source has
* changed via the user from the UI
*/
protected boolean m_formatNotificationOnly = false;
/**
* Creates a new <code>InstanceEvent</code> instance that encapsulates a
* single instance only.
*
* @param source the source of the event
* @param instance the instance
* @param status status code (either INSTANCE_AVAILABLE or BATCH_FINISHED)
*/
public InstanceEvent(Object source, Instance instance, int status) {
super(source);
m_instance = instance;
m_status = status;
}
/**
* Creates a new <code>InstanceEvent</code> instance which encapsulates header
* information only.
*
* @param source an <code>Object</code> value
* @param structure an <code>Instances</code> value
*/
public InstanceEvent(Object source, Instances structure) {
super(source);
m_structure = structure;
m_status = FORMAT_AVAILABLE;
}
public InstanceEvent(Object source) {
super(source);
}
/**
* Get the instance
*
* @return an <code>Instance</code> value
*/
public Instance getInstance() {
return m_instance;
}
/**
* Set the instance
*
* @param i an <code>Instance</code> value
*/
public void setInstance(Instance i) {
m_instance = i;
}
/**
* Get the status
*
* @return an <code>int</code> value
*/
public int getStatus() {
return m_status;
}
/**
* Set the status
*
* @param s an <code>int</code> value
*/
public void setStatus(int s) {
m_status = s;
if (m_status != FORMAT_AVAILABLE) {
m_formatNotificationOnly = false;
}
}
/**
* Set the instances structure
*
* @param structure an <code>Instances</code> value
*/
public void setStructure(Instances structure) {
m_structure = structure;
m_instance = null;
m_status = FORMAT_AVAILABLE;
}
/**
* Get the instances structure (may be null if this is not a FORMAT_AVAILABLE
* event)
*
* @return an <code>Instances</code> value
*/
public Instances getStructure() {
return m_structure;
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/InstanceListener.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/>.
*/
/*
* InstanceListener.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.util.EventListener;
/**
* Interface to something that can accept instance events
*
* @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a>
* @version $Revision$
*/
public interface InstanceListener extends EventListener {
/**
* Accept and process an instance event
*
* @param e an <code>InstanceEvent</code> value
*/
void acceptInstance(InstanceEvent e);
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/InstanceStreamToBatchMaker.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/>.
*/
/*
* InstanceStreamToBatchMaker.java
* Copyright (C) 2008-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.awt.BorderLayout;
import java.beans.EventSetDescriptor;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import javax.swing.JPanel;
import weka.core.Instance;
import weka.core.Instances;
import weka.gui.Logger;
/**
* Bean that converts an instance stream into a (batch) data set. Useful in
* conjunction with the Reservoir sampling filter.
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision$
*/
@KFStep(category = "Flow", toolTipText = "Converts an incoming instance stream into a data set batch")
public class InstanceStreamToBatchMaker extends JPanel implements BeanCommon,
Visible, InstanceListener, EventConstraints, DataSource {
/**
* For serialization
*/
private static final long serialVersionUID = -7037141087208627799L;
protected BeanVisual m_visual = new BeanVisual("InstanceStreamToBatchMaker",
BeanVisual.ICON_PATH + "InstanceStreamToBatchMaker.gif",
BeanVisual.ICON_PATH + "InstanceStreamToBatchMaker_animated.gif");
/**
* The log.
*/
private transient Logger m_log;
/**
* Component connected to us.
*/
private Object m_listenee;
private final ArrayList<DataSourceListener> m_dataListeners = new ArrayList<DataSourceListener>();
/**
* Collects up the instances.
*/
private List<Instance> m_batch;
private Instances m_structure;
public InstanceStreamToBatchMaker() {
setLayout(new BorderLayout());
add(m_visual, BorderLayout.CENTER);
}
/**
* Accept an instance to add to the batch.
*
* @param e an <code>InstanceEvent</code> value
*/
@Override
public void acceptInstance(InstanceEvent e) {
if (e.getStatus() == InstanceEvent.FORMAT_AVAILABLE) {
m_batch = new LinkedList<Instance>();
m_structure = e.getStructure();
// notify dataset listeners of structure available
if (m_log != null) {
m_log.logMessage("[InstanceStreamToBatch] passing on structure.");
}
DataSetEvent dse = new DataSetEvent(this, m_structure);
notifyDataListeners(dse);
} else if (e.getStatus() == InstanceEvent.INSTANCE_AVAILABLE) {
m_batch.add(e.getInstance());
} else {
// batch finished
if (e.getInstance() != null) {
// add the last instance
m_batch.add(e.getInstance());
}
// create the new Instances
Instances dataSet = new Instances(m_structure, m_batch.size());
for (Instance i : m_batch) {
dataSet.add(i);
}
dataSet.compactify();
// save memory
m_batch = null;
if (m_log != null) {
m_log.logMessage("[InstanceStreamToBatch] sending batch to listeners.");
}
// notify dataset listeners
DataSetEvent dse = new DataSetEvent(this, dataSet);
notifyDataListeners(dse);
}
}
/**
* Returns true if, at this time, the object will accept a connection
* according to the supplied EventSetDescriptor
*
* @param esd the EventSetDescriptor
* @return true if the object will accept a connection
*/
@Override
public boolean connectionAllowed(EventSetDescriptor esd) {
return connectionAllowed(esd.getName());
}
/**
* Returns true if, at this time, the object will accept a connection with
* respect to the named event
*
* @param eventName the event
* @return true if the object will accept a connection
*/
@Override
public boolean connectionAllowed(String eventName) {
if (m_listenee != null || !eventName.equals("instance")) {
return false;
}
return true;
}
/**
* Notify this object that it has been registered as a listener with a source
* with respect to the named event
*
* @param eventName the event
* @param source the source with which this object has been registered as a
* listener
*/
@Override
public void connectionNotification(String eventName, Object source) {
if (connectionAllowed(eventName)) {
m_listenee = source;
}
}
/**
* Notify this object that it has been deregistered as a listener with a
* source with respect to the supplied event name
*
* @param eventName the event
* @param source the source with which this object has been registered as a
* listener
*/
@Override
public void disconnectionNotification(String eventName, Object source) {
m_listenee = null;
}
/**
* Returns true if, at the current time, the named event could be generated.
*
* @param eventName the name of the event in question
* @return true if the named event could be generated
*/
@Override
public boolean eventGeneratable(String eventName) {
if (!eventName.equals("dataSet")) {
return false;
}
if (m_listenee == null) {
return false;
}
if (m_listenee instanceof EventConstraints) {
if (!((EventConstraints) m_listenee).eventGeneratable("instance")) {
return false;
}
}
return true;
}
/**
* Get the custom (descriptive) name for this bean (if one has been set)
*
* @return the custom name (or the default name)
*/
@Override
public String getCustomName() {
return m_visual.getText();
}
/**
* Set a custom (descriptive) name for this bean
*
* @param name the name to use
*/
@Override
public void setCustomName(String name) {
m_visual.setText(name);
}
/**
* Set a logger
*
* @param logger a <code>Logger</code> value
*/
@Override
public void setLog(Logger logger) {
m_log = logger;
}
/**
* Returns true if. at this time, the bean is busy with some (i.e. perhaps a
* worker thread is performing some calculation).
*
* @return true if the bean is busy.
*/
@Override
public boolean isBusy() {
return false;
}
/**
* Stop any action (if possible).
*/
@Override
public void stop() {
// not much we can do. Stopping depends on upstream components.
}
/**
* Gets the visual appearance of this wrapper bean
*/
@Override
public BeanVisual getVisual() {
return m_visual;
}
/**
* Sets the visual appearance of this wrapper bean
*
* @param newVisual a <code>BeanVisual</code> value
*/
@Override
public void setVisual(BeanVisual newVisual) {
m_visual = newVisual;
}
/**
* Use the default visual appearance for this bean
*/
@Override
public void useDefaultVisual() {
m_visual.loadIcons(BeanVisual.ICON_PATH + "InstanceStreamToBatchMaker.gif",
BeanVisual.ICON_PATH + "InstanceStreamToBatchMaker_animated.gif");
}
/**
* Notify all data source listeners.
*
* @param tse the DataSetEvent to pass on.
*/
@SuppressWarnings("unchecked")
protected void notifyDataListeners(DataSetEvent tse) {
ArrayList<DataSourceListener> l;
synchronized (this) {
l = (ArrayList<DataSourceListener>) m_dataListeners.clone();
}
if (l.size() > 0) {
for (int i = 0; i < l.size(); i++) {
l.get(i).acceptDataSet(tse);
}
}
}
@Override
public synchronized void addDataSourceListener(DataSourceListener tsl) {
m_dataListeners.add(tsl);
// pass on any format that we might know about
if (m_structure != null) {
DataSetEvent e = new DataSetEvent(this, m_structure);
tsl.acceptDataSet(e);
}
}
@Override
public synchronized void removeDataSourceListener(DataSourceListener tsl) {
m_dataListeners.remove(tsl);
}
@Override
public synchronized void addInstanceListener(InstanceListener il) {
// we don't produce instance events
}
@Override
public synchronized void removeInstanceListener(InstanceListener il) {
// we don't produce instance events
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/InstanceStreamToBatchMakerBeanInfo.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/>.
*/
/*
* InstanceStreamToBatchMakerBeanInfo.java
* Copyright (C) 2008-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.beans.EventSetDescriptor;
import java.beans.SimpleBeanInfo;
/**
* BeanInfo class for the InstanceStreamToBatchMaker bean
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision$
*/
public class InstanceStreamToBatchMakerBeanInfo
extends SimpleBeanInfo {
/**
* Returns the event set descriptors
*
* @return an <code>EventSetDescriptor[]</code> value
*/
public EventSetDescriptor [] getEventSetDescriptors() {
try {
EventSetDescriptor [] esds =
{ new EventSetDescriptor(DataSource.class,
"dataSet",
DataSourceListener.class,
"acceptDataSet")};
return esds;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/InteractiveTableModel.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/>.
*/
/*
* InteractiveTableModel.java
* Copyright (C) 2011-2013 University of Waikato, Hamilton, New Zealand
*/
package weka.gui.beans;
/**
* Table model that automatically adds a new row to the table on pressing enter
* in the last cell of a row.
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision: 47640 $
* @deprecated Use {@code weka.gui.InteractiveTableModel} instead. Retained for
* backward compatibility
*/
@Deprecated
public class InteractiveTableModel extends weka.gui.InteractiveTableModel {
private static final long serialVersionUID = 7628124449228704885L;
/**
* Constructor
*
* @param columnNames the names of the columns
*/
public InteractiveTableModel(String[] columnNames) {
super(columnNames);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/InteractiveTablePanel.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/>.
*/
/*
* InteractiveTablePanel.java
* Copyright (C) 2011-2013 University of Waikato, Hamilton, New Zealand
*/
package weka.gui.beans;
/**
* Provides a panel using an interactive table model.
*
* @author Mark Hall (mhall{[at]}penthao{[dot]}com)
* @version $Revision$
* @deprecated Use {@code weka.gui.InteractiveTablePanel} instead. Retained for
* backward compatibility
*/
@Deprecated
public class InteractiveTablePanel extends weka.gui.InteractiveTablePanel {
private static final long serialVersionUID = -5331129312037269302L;
/**
* Constructor
*
* @param colNames the names of the columns
*/
public InteractiveTablePanel(String[] colNames) {
super(colNames);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/Join.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/>.
*/
/*
* Join.java
* Copyright (C) 2014 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.awt.BorderLayout;
import java.beans.EventSetDescriptor;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import javax.swing.JPanel;
import weka.core.Attribute;
import weka.core.DenseInstance;
import weka.core.Environment;
import weka.core.EnvironmentHandler;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.Range;
import weka.core.SerializedObject;
import weka.gui.Logger;
/**
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision$
*/
@KFStep(category = "Flow", toolTipText = "Inner join on one or more key fields")
public class Join extends JPanel implements BeanCommon, Visible, Serializable,
DataSource, DataSourceListener, TrainingSetListener, TestSetListener,
InstanceListener, EventConstraints, StructureProducer, EnvironmentHandler {
/** Separator used to separate first and second input key specifications */
protected static final String KEY_SPEC_SEPARATOR = "@@KS@@";
/** For serialization */
private static final long serialVersionUID = 398021880509558185L;
/** Logging */
protected transient Logger m_log;
/** Environment variables */
protected transient Environment m_env;
/** Upstream components sending us data */
protected boolean m_incomingBatchConnections;
/** The first source of data */
protected Object m_firstInput;
/** The second source of data */
protected Object m_secondInput;
/** Whether the first is finished (incremental mode) */
protected transient boolean m_firstFinished;
/** Whether the second is finished (incremental mode) */
protected transient boolean m_secondFinished;
/** Connection type of the first input */
protected String m_firstInputConnectionType = "";
/** Connection type of the second input */
protected String m_secondInputConnectionType = "";
/** Buffer for the first input (capped at 100 for incremental) */
protected transient Queue<InstanceHolder> m_firstBuffer;
/** Buffer for the second input (capped at 100 for incremental) */
protected transient Queue<InstanceHolder> m_secondBuffer;
/** Instance event to use for incremental mode */
protected InstanceEvent m_ie = new InstanceEvent(this);
/** The structure of the first incoming dataset */
protected transient Instances m_headerOne;
/** The structure of the second incoming dataset */
protected transient Instances m_headerTwo;
/** The structure of the outgoing dataset */
protected transient Instances m_mergedHeader;
/**
* A set of copied outgoing structure instances. Used when there are string
* attributes present in the incremental case in order to prevent concurrency
* problems where string values could get clobbered in the header.
*/
protected transient List<Instances> m_headerPool;
/** Used to cycle over the headers in the header pool */
protected transient AtomicInteger m_count;
/** True if string attributes are present in the incoming data */
protected boolean m_stringAttsPresent;
/** True if the step is running incrementally */
protected boolean m_runningIncrementally;
/** Indexes of the key fields for the first input */
protected int[] m_keyIndexesOne;
/** Indexes of the key fields for the second input */
protected int[] m_keyIndexesTwo;
/** Holds the internal representation of the key specification */
protected String m_keySpec = "";
/** True if we are busy */
protected boolean m_busy;
/** True if the step has been told to stop processing */
protected AtomicBoolean m_stopRequested;
/** Holds indexes of string attributes, keyed by attribute name */
protected Map<String, Integer> m_stringAttIndexesOne;
/** Holds indexes of string attributes, keyed by attribute name */
protected Map<String, Integer> m_stringAttIndexesTwo;
/**
* True if the first input stream is waiting due to a full buffer (incremental
* mode only)
*/
protected boolean m_firstIsWaiting;
/**
* True if the second input stream is waiting due to a full buffer
* (incremental mode only)
*/
protected boolean m_secondIsWaiting;
/**
* Default visual for data sources
*/
protected BeanVisual m_visual = new BeanVisual("Join", BeanVisual.ICON_PATH
+ "Join.gif", BeanVisual.ICON_PATH + "Join.gif");
/** Downstream steps listening to batch data events */
protected ArrayList<DataSourceListener> m_dataListeners =
new ArrayList<DataSourceListener>();
/** Downstream steps listening to instance events */
protected ArrayList<InstanceListener> m_instanceListeners =
new ArrayList<InstanceListener>();
/** Used for computing streaming throughput stats */
protected transient StreamThroughput m_throughput;
/**
* Small helper class for holding an instance and the values of any string
* attributes it might have. This is needed in the streaming case as the
* KnowledgeFlow only ever keeps the current instances string values in the
* header (to save memory). Since we have to buffer a certain number of
* instances from each input, it is necessary to have a separate copy of the
* string values so that they can be restored to correct values in the
* outgoing instances.
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
*/
protected static class InstanceHolder implements Serializable {
/**
* For serialization
*/
private static final long serialVersionUID = -2554438923824758088L;
/** The instance */
protected Instance m_instance;
/**
* for incremental operation, if string attributes are present then we need
* to store them with each instance - since incremental streaming in the
* knowledge flow only maintains one string value in memory (and hence in
* the header) at any one time
*/
protected Map<String, String> m_stringVals;
}
/**
* Constructor
*/
public Join() {
useDefaultVisual();
setLayout(new BorderLayout());
add(m_visual, BorderLayout.CENTER);
m_env = Environment.getSystemWide();
m_stopRequested = new AtomicBoolean(false);
}
/**
* Global info for the method
*
* @return the global help info
*/
public String globalInfo() {
return "Performs an inner join on two incoming datasets/instance streams (IMPORTANT: assumes that "
+ "both datasets are sorted in ascending order of the key fields). If data is not sorted then use"
+ "a Sorter step to sort both into ascending order of the key fields. Does not handle the case where"
+ "keys are not unique in one or both inputs.";
}
/**
* Set the key specification (in internal format -
* k11,k12,...,k1nKEY_SPEC_SEPARATORk21,k22,...,k2n)
*
* @param ks the keys specification
*/
public void setKeySpec(String ks) {
m_keySpec = ks;
}
/**
* Get the key specification (in internal format -
* k11,k12,...,k1nKEY_SPEC_SEPARATORk21,k22,...,k2n)
*
* @return the keys specification
*/
public String getKeySpec() {
return m_keySpec;
}
@Override
public boolean eventGeneratable(String eventName) {
// Auto-generated method stub
if (m_firstInput == null || m_secondInput == null) {
return false;
}
if (eventName.equals("instance") && m_incomingBatchConnections) {
return false;
}
if (!eventName.equals("instance") && !m_incomingBatchConnections) {
return false;
}
return true;
}
/**
* Generate the header of the output instance structure
*/
protected void generateMergedHeader() {
// check validity of key fields first
if (m_keySpec == null || m_keySpec.length() == 0) {
if (m_log != null) {
String msg = statusMessagePrefix() + "ERROR: Key fields are null!";
m_log.statusMessage(msg);
m_log.logMessage(msg);
stop();
m_busy = false;
return;
}
}
String resolvedKeySpec = m_keySpec;
try {
resolvedKeySpec = m_env.substitute(m_keySpec);
} catch (Exception ex) {
}
String[] parts = resolvedKeySpec.split(KEY_SPEC_SEPARATOR);
if (parts.length != 2) {
if (m_log != null) {
String msg =
statusMessagePrefix() + "ERROR: Invalid key specification: "
+ m_keySpec;
m_log.statusMessage(msg);
m_log.logMessage(msg);
stop();
m_busy = false;
return;
}
}
// try to parse as a Range first
for (int i = 0; i < 2; i++) {
String rangeS = parts[i].trim();
Range r = new Range();
r.setUpper(i == 0 ? m_headerOne.numAttributes() : m_headerTwo
.numAttributes());
try {
r.setRanges(rangeS);
if (i == 0) {
m_keyIndexesOne = r.getSelection();
} else {
m_keyIndexesTwo = r.getSelection();
}
} catch (IllegalArgumentException e) {
// assume a list of attribute names
String[] names = rangeS.split(",");
if (i == 0) {
m_keyIndexesOne = new int[names.length];
} else {
m_keyIndexesTwo = new int[names.length];
}
for (int j = 0; j < names.length; j++) {
String aName = names[j].trim();
Attribute anAtt =
(i == 0) ? m_headerOne.attribute(aName) : m_headerTwo
.attribute(aName);
if (anAtt == null) {
String msg =
statusMessagePrefix() + "ERROR: Invalid key attribute name: "
+ aName;
if (m_log != null) {
m_log.statusMessage(msg);
m_log.logMessage(msg);
} else {
System.err.println(msg);
}
stop();
m_busy = false;
return;
}
if (i == 0) {
m_keyIndexesOne[j] = anAtt.index();
} else {
m_keyIndexesTwo[j] = anAtt.index();
}
}
}
}
if (m_keyIndexesOne == null || m_keyIndexesTwo == null) {
if (m_log != null) {
String msg = statusMessagePrefix() + "ERROR: Key fields are null!";
m_log.statusMessage(msg);
m_log.logMessage(msg);
stop();
m_busy = false;
return;
}
}
if (m_keyIndexesOne.length != m_keyIndexesTwo.length) {
if (m_log != null) {
String msg =
statusMessagePrefix()
+ "ERROR: number of key fields are different for each input!";
m_log.statusMessage(msg);
m_log.logMessage(msg);
stop();
m_busy = false;
return;
}
}
// check types
for (int i = 0; i < m_keyIndexesOne.length; i++) {
if (m_headerOne.attribute(m_keyIndexesOne[i]).type() != m_headerTwo
.attribute(m_keyIndexesTwo[i]).type()) {
if (m_log != null) {
String msg =
statusMessagePrefix()
+ "ERROR: type of key corresponding key fields differ: "
+ "input 1 - "
+ Attribute.typeToStringShort(m_headerOne
.attribute(m_keyIndexesOne[i]))
+ " input 2 - "
+ Attribute.typeToStringShort(m_headerTwo
.attribute(m_keyIndexesTwo[i]));
m_log.statusMessage(msg);
m_log.logMessage(msg);
stop();
m_busy = false;
return;
}
}
}
ArrayList<Attribute> newAtts = new ArrayList<Attribute>();
Set<String> nameLookup = new HashSet<String>();
for (int i = 0; i < m_headerOne.numAttributes(); i++) {
newAtts.add((Attribute) m_headerOne.attribute(i).copy());
nameLookup.add(m_headerOne.attribute(i).name());
}
for (int i = 0; i < m_headerTwo.numAttributes(); i++) {
String name = m_headerTwo.attribute(i).name();
if (nameLookup.contains(name)) {
name = name + "_2";
}
newAtts.add(m_headerTwo.attribute(i).copy(name));
}
m_mergedHeader =
new Instances(m_headerOne.relationName() + "+"
+ m_headerTwo.relationName(), newAtts, 0);
m_ie.setStructure(m_mergedHeader);
notifyInstanceListeners(m_ie);
m_stringAttsPresent = false;
if (m_mergedHeader.checkForStringAttributes()) {
m_stringAttsPresent = true;
m_headerPool = new ArrayList<Instances>();
m_count = new AtomicInteger();
for (int i = 0; i < 10; i++) {
try {
m_headerPool.add((Instances) (new SerializedObject(m_mergedHeader))
.getObject());
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
/**
* Generate a merged instance from two input instances that match on the key
* fields
*
* @param one the first input instance
* @param two the second input instance
* @return the merged instance
*/
protected synchronized Instance generateMergedInstance(InstanceHolder one,
InstanceHolder two) {
double[] vals = new double[m_mergedHeader.numAttributes()];
int count = 0;
Instances currentStructure = m_mergedHeader;
if (m_runningIncrementally && m_stringAttsPresent) {
currentStructure = m_headerPool.get(m_count.getAndIncrement() % 10);
}
for (int i = 0; i < m_headerOne.numAttributes(); i++) {
vals[count] = one.m_instance.value(i);
if (one.m_stringVals != null && one.m_stringVals.size() > 0
&& m_mergedHeader.attribute(count).isString()) {
String valToSetInHeader =
one.m_stringVals.get(one.m_instance.attribute(i).name());
currentStructure.attribute(count).setStringValue(valToSetInHeader);
vals[count] = 0;
}
count++;
}
for (int i = 0; i < m_headerTwo.numAttributes(); i++) {
vals[count] = two.m_instance.value(i);
if (two.m_stringVals != null && two.m_stringVals.size() > 0
&& m_mergedHeader.attribute(count).isString()) {
String valToSetInHeader =
one.m_stringVals.get(two.m_instance.attribute(i).name());
currentStructure.attribute(count).setStringValue(valToSetInHeader);
vals[count] = 0;
}
count++;
}
Instance newInst = new DenseInstance(1.0, vals);
newInst.setDataset(currentStructure);
return newInst;
}
@Override
public synchronized void acceptInstance(InstanceEvent e) {
if (e.m_formatNotificationOnly) {
return;
}
m_busy = true;
Object source = e.getSource();
if (e.getStatus() == InstanceEvent.FORMAT_AVAILABLE) {
m_runningIncrementally = true;
m_stopRequested.set(false);
if (!m_stopRequested.get() && source == m_firstInput
&& m_firstBuffer == null) {
System.err.println("Allocating first buffer");
m_firstFinished = false;
m_firstBuffer = new LinkedList<InstanceHolder>();
m_headerOne = e.getStructure();
m_stringAttIndexesOne = new HashMap<String, Integer>();
for (int i = 0; i < m_headerOne.numAttributes(); i++) {
if (m_headerOne.attribute(i).isString()) {
m_stringAttIndexesOne.put(m_headerOne.attribute(i).name(),
new Integer(i));
}
}
}
if (!m_stopRequested.get() && source == m_secondInput
&& m_secondBuffer == null) {
System.err.println("Allocating second buffer");
m_secondFinished = false;
m_secondBuffer = new LinkedList<InstanceHolder>();
m_headerTwo = e.getStructure();
m_stringAttIndexesTwo = new HashMap<String, Integer>();
for (int i = 0; i < m_headerTwo.numAttributes(); i++) {
if (m_headerTwo.attribute(i).isString()) {
m_stringAttIndexesTwo.put(m_headerTwo.attribute(i).name(),
new Integer(i));
}
}
}
if (m_stopRequested.get()) {
return;
}
if (m_mergedHeader == null) {
// can we determine the header?
m_throughput = new StreamThroughput(statusMessagePrefix());
if (m_headerOne != null && m_headerTwo != null && m_keySpec != null
&& m_keySpec.length() > 0) {
// construct merged header & check validity of indexes
generateMergedHeader();
}
}
} else {
if (m_stopRequested.get()) {
return;
}
Instance current = e.getInstance();
if (current == null || e.getStatus() == InstanceEvent.BATCH_FINISHED) {
if (source == m_firstInput) {
System.err.println("Finished first");
m_firstFinished = true;
}
if (source == m_secondInput) {
System.err.println("Finished second");
m_secondFinished = true;
}
}
if (current != null) {
if (source == m_firstInput) {
// m_firstBuffer.add(current);
addToFirstBuffer(current);
} else if (source == m_secondInput) {
// m_secondBuffer.add(current);
addToSecondBuffer(current);
}
}
if (source == m_firstInput && m_secondBuffer != null
&& m_secondBuffer.size() <= 100 && m_secondIsWaiting) {
notifyAll();
m_secondIsWaiting = false;
} else if (source == m_secondInput && m_firstBuffer != null
&& m_firstBuffer.size() <= 100 && m_firstIsWaiting) {
notifyAll();
m_firstIsWaiting = false;
}
if (m_firstFinished && m_secondFinished && !m_stopRequested.get()) {
// finished - now just clear buffers and reset headers etc
clearBuffers();
return;
}
if (m_stopRequested.get()) {
return;
}
m_throughput.updateStart();
Instance outputI = processBuffers();
m_throughput.updateEnd(m_log);
if (outputI != null && !m_stopRequested.get()) {
// notify instance listeners
m_ie.setStatus(InstanceEvent.INSTANCE_AVAILABLE);
m_ie.setInstance(outputI);
notifyInstanceListeners(m_ie);
}
}
}
/**
* Copy the string values out of an instance into the temporary storage in
* InstanceHolder
*
* @param holder the InstanceHolder encapsulating the instance and it's string
* values
* @param stringAttIndexes indices of string attributes in the instance
*/
private static void copyStringAttVals(InstanceHolder holder,
Map<String, Integer> stringAttIndexes) {
for (String attName : stringAttIndexes.keySet()) {
Attribute att = holder.m_instance.dataset().attribute(attName);
String val = holder.m_instance.stringValue(att);
if (holder.m_stringVals == null) {
holder.m_stringVals = new HashMap<String, String>();
}
holder.m_stringVals.put(attName, val);
}
}
/**
* Adds an instance to the first input's buffer
*
* @param inst the instance to add
*/
protected synchronized void addToFirstBuffer(Instance inst) {
if (m_stopRequested.get()) {
return;
}
InstanceHolder newH = new InstanceHolder();
newH.m_instance = inst;
copyStringAttVals(newH, m_stringAttIndexesOne);
if (!m_stopRequested.get()) {
m_firstBuffer.add(newH);
} else {
return;
}
if (m_firstBuffer.size() > 100 && !m_secondFinished) {
try {
m_firstIsWaiting = true;
wait();
} catch (InterruptedException ex) {
}
}
}
/**
* Adds an instance to the second input's buffer
*
* @param inst the instance to add
*/
protected synchronized void addToSecondBuffer(Instance inst) {
if (m_stopRequested.get()) {
return;
}
InstanceHolder newH = new InstanceHolder();
newH.m_instance = inst;
copyStringAttVals(newH, m_stringAttIndexesTwo);
if (!m_stopRequested.get()) {
m_secondBuffer.add(newH);
} else {
return;
}
if (m_secondBuffer.size() > 100 && !m_firstFinished) {
try {
m_secondIsWaiting = true;
wait();
} catch (InterruptedException e) {
}
}
}
/**
* Clear remaining instances in the buffers
*/
protected synchronized void clearBuffers() {
while (m_firstBuffer.size() > 0 && m_secondBuffer.size() > 0) {
m_throughput.updateStart();
Instance newInst = processBuffers();
m_throughput.updateEnd(m_log);
if (newInst != null) {
m_ie.setInstance(newInst);
m_ie.setStatus(InstanceEvent.INSTANCE_AVAILABLE);
notifyInstanceListeners(m_ie);
}
}
// indicate end of stream
m_ie.setInstance(null);
m_ie.setStatus(InstanceEvent.BATCH_FINISHED);
notifyInstanceListeners(m_ie);
if (m_log != null) {
m_log.statusMessage(statusMessagePrefix() + "Finished");
}
m_headerOne = null;
m_headerTwo = null;
m_mergedHeader = null;
m_firstBuffer = null;
m_secondBuffer = null;
m_firstFinished = false;
m_secondFinished = false;
m_busy = false;
}
/**
* Process the current state of the two buffers. Compares the head of both
* buffers and will return a merged instance if they match on the key fields.
* Will remove instances from one or the other buffer if it is behind
* according to the keys comparison
*
* @return a merged instance if keys match, otherwise null
*/
protected synchronized Instance processBuffers() {
if (m_firstBuffer != null && m_secondBuffer != null
&& m_firstBuffer.size() > 0 && m_secondBuffer.size() > 0) {
// System.err.println("Buffer sizes: " + m_firstBuffer.size() + " "
// + m_secondBuffer.size());
if (m_stopRequested.get()) {
return null;
}
InstanceHolder firstH = m_firstBuffer.peek();
InstanceHolder secondH = m_secondBuffer.peek();
Instance first = firstH.m_instance;
Instance second = secondH.m_instance;
// System.err.println("Keys " + first.value(0) + " " + second.value(0));
// try {
// Thread.sleep(500);
// } catch (InterruptedException ex) {
//
// }
int cmp = compare(first, second, firstH, secondH);
if (cmp == 0) {
// match on all keys - output joined instance
Instance newInst =
generateMergedInstance(m_firstBuffer.remove(),
m_secondBuffer.remove());
return newInst;
} else if (cmp < 0) {
// second is ahead of first - discard rows from first
do {
m_firstBuffer.remove();
if (m_firstBuffer.size() > 0) {
firstH = m_firstBuffer.peek();
first = firstH.m_instance;
cmp = compare(first, second, firstH, secondH);
}
} while (cmp < 0 && m_firstBuffer.size() > 0);
} else {
// first is ahead of second - discard rows from second
do {
m_secondBuffer.remove();
if (m_secondBuffer.size() > 0) {
secondH = m_secondBuffer.peek();
second = secondH.m_instance;
cmp = compare(first, second, firstH, secondH);
}
} while (cmp > 0 && m_secondBuffer.size() > 0);
}
}
return null;
}
/**
* Compares two instances according to the keys
*
* @param one the first instance
* @param two the second instance
* @param oneH the first instance holder (in case string attributes are
* present and we are running incrementally)
* @param twoH the second instance holder
* @return the comparison according to the keys
*/
protected int compare(Instance one, Instance two, InstanceHolder oneH,
InstanceHolder twoH) {
for (int i = 0; i < m_keyIndexesOne.length; i++) {
if (one.isMissing(m_keyIndexesOne[i])
&& two.isMissing(m_keyIndexesTwo[i])) {
continue;
}
if (one.isMissing(m_keyIndexesOne[i])
|| two.isMissing(m_keyIndexesTwo[i])) {
// ensure that the input with the missing value gets discarded
if (one.isMissing(m_keyIndexesOne[i])) {
return -1;
} else {
return 1;
}
}
if (m_mergedHeader.attribute(m_keyIndexesOne[i]).isNumeric()) {
double v1 = one.value(m_keyIndexesOne[i]);
double v2 = two.value(m_keyIndexesTwo[i]);
if (v1 != v2) {
return v1 < v2 ? -1 : 1;
}
} else if (m_mergedHeader.attribute(m_keyIndexesOne[i]).isNominal()) {
String oneS = one.stringValue(m_keyIndexesOne[i]);
String twoS = two.stringValue(m_keyIndexesTwo[i]);
int cmp = oneS.compareTo(twoS);
if (cmp != 0) {
return cmp;
}
} else if (m_mergedHeader.attribute(m_keyIndexesOne[i]).isString()) {
String attNameOne = m_mergedHeader.attribute(m_keyIndexesOne[i]).name();
String attNameTwo = m_mergedHeader.attribute(m_keyIndexesTwo[i]).name();
String oneS =
oneH.m_stringVals == null || oneH.m_stringVals.size() == 0 ? one
.stringValue(m_keyIndexesOne[i]) : oneH.m_stringVals
.get(attNameOne);
String twoS =
twoH.m_stringVals == null || twoH.m_stringVals.size() == 0 ? two
.stringValue(m_keyIndexesTwo[i]) : twoH.m_stringVals
.get(attNameTwo);
int cmp = oneS.compareTo(twoS);
if (cmp != 0) {
return cmp;
}
}
}
return 0;
}
/**
* Accept and process a test set
*
* @param e the test set event encapsulating the test set
*/
@Override
public void acceptTestSet(TestSetEvent e) {
DataSetEvent de = new DataSetEvent(e.getSource(), e.getTestSet());
acceptDataSet(de);
}
/**
* Accept and process a training set
*
* @param e the training set event encapsulating the training set
*/
@Override
public void acceptTrainingSet(TrainingSetEvent e) {
DataSetEvent de = new DataSetEvent(e.getSource(), e.getTrainingSet());
acceptDataSet(de);
}
/**
* Accept and process a data set
*
* @param e the data set event encapsulating the data set
*/
@Override
public synchronized void acceptDataSet(DataSetEvent e) {
m_runningIncrementally = false;
m_stopRequested.set(false);
if (e.getSource() == m_firstInput) {
if (e.isStructureOnly() || e.getDataSet().numInstances() == 0) {
m_headerOne = e.getDataSet();
return;
}
if (m_headerOne == null) {
m_headerOne = new Instances(e.getDataSet(), 0);
}
m_firstBuffer = new LinkedList<InstanceHolder>();
for (int i = 0; i < e.getDataSet().numInstances()
&& !m_stopRequested.get(); i++) {
InstanceHolder tempH = new InstanceHolder();
tempH.m_instance = e.getDataSet().instance(i);
m_firstBuffer.add(tempH);
}
} else if (e.getSource() == m_secondInput) {
if (e.isStructureOnly() || e.getDataSet().numInstances() == 0) {
m_headerTwo = e.getDataSet();
return;
}
if (m_headerTwo == null) {
m_headerTwo = new Instances(e.getDataSet(), 0);
}
m_secondBuffer = new LinkedList<InstanceHolder>();
for (int i = 0; i < e.getDataSet().numInstances()
&& !m_stopRequested.get(); i++) {
InstanceHolder tempH = new InstanceHolder();
tempH.m_instance = e.getDataSet().instance(i);
m_secondBuffer.add(tempH);
}
}
if (m_firstBuffer != null && m_firstBuffer.size() > 0
&& m_secondBuffer != null && m_secondBuffer.size() > 0) {
m_busy = true;
generateMergedHeader();
DataSetEvent dse = new DataSetEvent(this, m_mergedHeader);
notifyDataListeners(dse);
Instances newData = new Instances(m_mergedHeader, 0);
while (!m_stopRequested.get() && m_firstBuffer.size() > 0
&& m_secondBuffer.size() > 0) {
Instance newI = processBuffers();
if (newI != null) {
newData.add(newI);
}
}
if (!m_stopRequested.get()) {
dse = new DataSetEvent(this, newData);
notifyDataListeners(dse);
}
m_busy = false;
m_headerOne = null;
m_headerTwo = null;
m_mergedHeader = null;
m_firstBuffer = null;
m_secondBuffer = null;
}
}
/**
* Add a data source listener
*
* @param dsl the data source listener to add
*/
@Override
public void addDataSourceListener(DataSourceListener dsl) {
m_dataListeners.add(dsl);
}
/**
* Remove a data souce listener
*
* @param dsl the data source listener to remove
*/
@Override
public void removeDataSourceListener(DataSourceListener dsl) {
m_dataListeners.remove(dsl);
}
/**
* Add an instance listener
*
* @param dsl the instance listener to add
*/
@Override
public void addInstanceListener(InstanceListener dsl) {
m_instanceListeners.add(dsl);
}
/**
* Remove an instance listener
*
* @param dsl the instance listener to remove
*/
@Override
public void removeInstanceListener(InstanceListener dsl) {
m_instanceListeners.remove(dsl);
}
/**
* Use the default visual for this step
*/
@Override
public void useDefaultVisual() {
m_visual.loadIcons(BeanVisual.ICON_PATH + "Join.gif", BeanVisual.ICON_PATH
+ "Join.gif");
m_visual.setText("Join");
}
/**
* Set the visual for this step
*
* @param newVisual the visual to use
*/
@Override
public void setVisual(BeanVisual newVisual) {
m_visual = newVisual;
}
/**
* Get the visual for this step
*
* @return the visual (icon)
*/
@Override
public BeanVisual getVisual() {
return m_visual;
}
/**
* Set a custom name for this step
*
* @param name the custom name to use
*/
@Override
public void setCustomName(String name) {
m_visual.setText(name);
}
/**
* Get the custom name of this step
*
* @return the custom name of this step
*/
@Override
public String getCustomName() {
return m_visual.getText();
}
/**
* Attempt to stop processing
*/
@Override
public void stop() {
if (m_firstInput != null && m_firstInput instanceof BeanCommon) {
((BeanCommon) m_firstInput).stop();
}
if (m_secondInput != null && m_secondInput instanceof BeanCommon) {
((BeanCommon) m_secondInput).stop();
}
if (m_log != null) {
m_log.statusMessage(statusMessagePrefix() + "Stopped");
}
m_busy = false;
m_stopRequested.set(true);
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
}
if (m_firstIsWaiting || m_secondIsWaiting) {
notifyAll();
}
m_firstBuffer = null;
m_secondBuffer = null;
m_headerOne = null;
m_headerTwo = null;
m_firstFinished = false;
m_secondFinished = false;
m_mergedHeader = null;
}
/**
* Returns true if we are doing something
*
* @return true if processing is occurring
*/
@Override
public boolean isBusy() {
return m_busy;
}
/**
* Set a log to use
*
* @param logger the log to use
*/
@Override
public void setLog(Logger logger) {
m_log = logger;
}
/**
* Returns true if the named connection can be made at this time
*
* @param esd the event set descriptor of the connection
* @return true if the connection is allowed
*/
@Override
public boolean connectionAllowed(EventSetDescriptor esd) {
return connectionAllowed(esd.getName());
}
/**
* Returns true if the named connection can be made at this time
*
* @param eventName the name of the connection
* @return true if the connection is allowed
*/
@Override
public boolean connectionAllowed(String eventName) {
if (m_firstInput != null && m_secondInput != null) {
return false;
}
if (m_firstInput == null || m_secondInput == null) {
if (m_firstInput != null) {
if (m_firstInputConnectionType.equals("instance")
&& !eventName.equals("instance")) {
return false;
} else if (!m_firstInputConnectionType.equals("instance")
&& eventName.equals("instance")) {
return false;
}
return true;
} else if (m_secondInput != null) {
if (m_secondInputConnectionType.equals("instance")
&& !eventName.equals("instance")) {
return false;
} else if (!m_secondInputConnectionType.equals("instance")
&& eventName.equals("instance")) {
return false;
}
return true;
}
// both unset as yet
return true;
}
return false;
}
/**
* Deals with a new connection
*
* @param eventName the event type of the connection
* @param source the source step
*/
@Override
public void connectionNotification(String eventName, Object source) {
if (connectionAllowed(eventName)) {
if (m_firstInput == null) {
m_firstInput = source;
m_firstInputConnectionType = eventName;
} else {
m_secondInput = source;
m_secondInputConnectionType = eventName;
}
}
if (m_firstInput != null && m_secondInput != null) {
if (m_firstInputConnectionType.length() > 0
|| m_secondInputConnectionType.length() > 0) {
if (!m_firstInputConnectionType.equals("instance")
&& !m_secondInputConnectionType.equals("instance")) {
m_incomingBatchConnections = true;
} else {
m_incomingBatchConnections = false;
}
} else {
m_incomingBatchConnections = false;
}
}
}
/**
* Handles cleanup when an upstream step disconnects
*
* @param eventName the event type of the connection
* @param source the source step
*/
@Override
public void disconnectionNotification(String eventName, Object source) {
if (source == m_firstInput) {
m_firstInput = null;
m_firstInputConnectionType = "";
} else if (source == m_secondInput) {
m_secondInput = null;
m_secondInputConnectionType = "";
}
if (m_firstInput != null && m_secondInput != null) {
if (m_firstInputConnectionType.length() > 0
|| m_secondInputConnectionType.length() > 0) {
if (!m_firstInputConnectionType.equals("instance")
&& !m_secondInputConnectionType.equals("instance")) {
m_incomingBatchConnections = true;
} else {
m_incomingBatchConnections = false;
}
} else {
m_incomingBatchConnections = false;
}
}
}
/**
* Unique prefix to use for status messages to the log
*
* @return the prefix to use
*/
private String statusMessagePrefix() {
return getCustomName() + "$" + hashCode() + "|";
}
/**
* Notify instance listeners of an output instance
*
* @param e the event to notify with
*/
private void notifyInstanceListeners(InstanceEvent e) {
for (InstanceListener il : m_instanceListeners) {
il.acceptInstance(e);
}
}
/**
* Notify data listeners of an output data set
*
* @param e the event to notify with
*/
private void notifyDataListeners(DataSetEvent e) {
for (DataSourceListener l : m_dataListeners) {
l.acceptDataSet(e);
}
}
/**
* Get the incoming instance structure from the first upstream step (if
* possible)
*
* @return the incoming instance structure of the first upstream step
*/
protected Instances getUpstreamStructureFirst() {
if (m_firstInput != null && m_firstInput instanceof StructureProducer) {
return ((StructureProducer) m_firstInput)
.getStructure(m_firstInputConnectionType);
}
return null;
}
/**
* Get the incoming instance structure from the second upstream step (if
* possible)
*
* @return the incoming instance structure of the second upstream step
*/
protected Instances getUpstreamStructureSecond() {
if (m_secondInput != null && m_secondInput instanceof StructureProducer) {
return ((StructureProducer) m_secondInput)
.getStructure(m_secondInputConnectionType);
}
return null;
}
/**
* Get the first input step
*
* @return the first input step
*/
protected Object getFirstInput() {
return m_firstInput;
}
/**
* Get the first input structure
*
* @return the first incoming instance structure (or null if unavailable)
*/
protected Instances getFirstInputStructure() {
Instances result = null;
if (m_firstInput instanceof StructureProducer) {
result =
((StructureProducer) m_firstInput)
.getStructure(m_firstInputConnectionType);
}
return result;
}
/**
* Get the second input step
*
* @return the second input step
*/
protected Object getSecondInput() {
return m_secondInput;
}
/**
* Get the second input structure
*
* @return the second incoming instance structure (or null if unavailable)
*/
protected Instances getSecondInputStructure() {
Instances result = null;
if (m_secondInput instanceof StructureProducer) {
result =
((StructureProducer) m_secondInput)
.getStructure(m_secondInputConnectionType);
}
return result;
}
/**
* Get the output instances structure given an input event type
*
* @param eventName the name of the input event type
* @return the output instances structure (or null)
*/
@Override
public Instances getStructure(String eventName) {
if (!eventName.equals("dataSet") && !eventName.equals("instance")) {
return null;
}
if (eventName.equals("dataSet") && m_dataListeners.size() == 0) {
return null;
}
if (eventName.equals("instance") && m_instanceListeners.size() == 0) {
return null;
}
if (m_mergedHeader == null) {
generateMergedHeader();
}
return m_mergedHeader;
}
/**
* Set environment variables to use
*
* @param env the environment variables to use
*/
@Override
public void setEnvironment(Environment env) {
m_env = env;
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/JoinBeanInfo.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/>.
*/
/*
* JoinBeanInfo.java
* Copyright (C) 2014 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.beans.BeanDescriptor;
import java.beans.EventSetDescriptor;
import java.beans.SimpleBeanInfo;
/**
* BeanInfo for the Join step
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision$
*/
public class JoinBeanInfo extends SimpleBeanInfo {
/**
* Returns the event set descriptors
*
* @return an <code>EventSetDescriptor[]</code> value
*/
@Override
public EventSetDescriptor[] getEventSetDescriptors() {
try {
EventSetDescriptor[] esds =
{
new EventSetDescriptor(DataSource.class, "instance",
InstanceListener.class, "acceptInstance"),
new EventSetDescriptor(DataSource.class, "dataSet",
DataSourceListener.class, "acceptDataSet") };
return esds;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
/**
* Get the bean descriptor for this bean
*
* @return a <code>BeanDescriptor</code> value
*/
@Override
public BeanDescriptor getBeanDescriptor() {
return new BeanDescriptor(weka.gui.beans.Join.class, JoinCustomizer.class);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/JoinCustomizer.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/>.
*/
/*
* JoinCustomizer.java
* Copyright (C) 2014 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingConstants;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import weka.core.Environment;
import weka.core.EnvironmentHandler;
import weka.core.Instances;
import weka.gui.JListHelper;
import weka.gui.PropertySheetPanel;
/**
* Customizer component for the Join step
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision$
*/
public class JoinCustomizer extends JPanel implements EnvironmentHandler,
BeanCustomizer, CustomizerCloseRequester {
/** For serialization */
private static final long serialVersionUID = 5797383368777382010L;
protected Environment m_env = Environment.getSystemWide();
protected ModifyListener m_modifyL = null;
protected Join m_join;
protected JComboBox m_firstKeyFields = new EnvironmentField.WideComboBox();
protected JComboBox m_secondKeyFields = new EnvironmentField.WideComboBox();
protected JList m_firstList = new JList();
protected JList m_secondList = new JList();
protected DefaultListModel m_firstListModel;
protected DefaultListModel m_secondListModel;
protected JButton m_addOneBut = new JButton("Add");
protected JButton m_deleteOneBut = new JButton("Delete");
protected JButton m_upOneBut = new JButton("Up");
protected JButton m_downOneBut = new JButton("Down");
protected JButton m_addTwoBut = new JButton("Add");
protected JButton m_deleteTwoBut = new JButton("Delete");
protected JButton m_upTwoBut = new JButton("Up");
protected JButton m_downTwoBut = new JButton("Down");
protected Window m_parent;
protected PropertySheetPanel m_tempEditor = new PropertySheetPanel();
public JoinCustomizer() {
setLayout(new BorderLayout());
}
@SuppressWarnings("unchecked")
private void setup() {
JPanel aboutAndControlHolder = new JPanel();
aboutAndControlHolder.setLayout(new BorderLayout());
JPanel controlHolder = new JPanel();
controlHolder.setLayout(new BorderLayout());
// input source names
JPanel firstSourceP = new JPanel();
firstSourceP.setLayout(new BorderLayout());
firstSourceP.add(new JLabel("First input ", SwingConstants.RIGHT),
BorderLayout.CENTER);
Object firstInput = m_join.getFirstInput();
String firstName = "<not connected>";
if (firstInput != null && firstInput instanceof BeanCommon) {
firstName = ((BeanCommon) firstInput).getCustomName();
}
firstSourceP.add(new JLabel(firstName, SwingConstants.LEFT),
BorderLayout.EAST);
JPanel secondSourceP = new JPanel();
secondSourceP.setLayout(new BorderLayout());
secondSourceP.add(new JLabel("Second input ", SwingConstants.RIGHT),
BorderLayout.CENTER);
Object secondInput = m_join.getSecondInput();
String secondName = "<not connected>";
if (secondInput != null && secondInput instanceof BeanCommon) {
secondName = ((BeanCommon) secondInput).getCustomName();
}
secondSourceP.add(new JLabel(secondName, SwingConstants.LEFT),
BorderLayout.EAST);
JPanel sourcePHolder = new JPanel();
sourcePHolder.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5));
sourcePHolder.setLayout(new BorderLayout());
sourcePHolder.add(firstSourceP, BorderLayout.NORTH);
sourcePHolder.add(secondSourceP, BorderLayout.SOUTH);
controlHolder.add(sourcePHolder, BorderLayout.NORTH);
// lists and controls
m_firstList.setVisibleRowCount(5);
m_secondList.setVisibleRowCount(5);
m_firstKeyFields.setEditable(true);
JPanel listOneP = new JPanel();
m_deleteOneBut.setEnabled(false);
listOneP.setLayout(new BorderLayout());
JPanel butOneHolder = new JPanel();
butOneHolder.setLayout(new GridLayout(1, 0));
butOneHolder.add(m_addOneBut);
butOneHolder.add(m_deleteOneBut);
butOneHolder.add(m_upOneBut);
butOneHolder.add(m_downOneBut);
m_upOneBut.setEnabled(false);
m_downOneBut.setEnabled(false);
JPanel fieldsAndButsOne = new JPanel();
fieldsAndButsOne.setLayout(new BorderLayout());
fieldsAndButsOne.add(m_firstKeyFields, BorderLayout.NORTH);
fieldsAndButsOne.add(butOneHolder, BorderLayout.SOUTH);
listOneP.add(fieldsAndButsOne, BorderLayout.NORTH);
JScrollPane js1 = new JScrollPane(m_firstList);
js1.setBorder(BorderFactory.createTitledBorder("First input key fields"));
listOneP.add(js1, BorderLayout.CENTER);
controlHolder.add(listOneP, BorderLayout.WEST);
m_secondKeyFields.setEditable(true);
JPanel listTwoP = new JPanel();
m_deleteTwoBut.setEnabled(false);
listTwoP.setLayout(new BorderLayout());
JPanel butTwoHolder = new JPanel();
butTwoHolder.setLayout(new GridLayout(1, 0));
butTwoHolder.add(m_addTwoBut);
butTwoHolder.add(m_deleteTwoBut);
butTwoHolder.add(m_upTwoBut);
butTwoHolder.add(m_downTwoBut);
m_upTwoBut.setEnabled(false);
m_downTwoBut.setEnabled(false);
JPanel fieldsAndButsTwo = new JPanel();
fieldsAndButsTwo.setLayout(new BorderLayout());
fieldsAndButsTwo.add(m_secondKeyFields, BorderLayout.NORTH);
fieldsAndButsTwo.add(butTwoHolder, BorderLayout.SOUTH);
listTwoP.add(fieldsAndButsTwo, BorderLayout.NORTH);
JScrollPane js2 = new JScrollPane(m_secondList);
js2.setBorder(BorderFactory.createTitledBorder("Second input key fields"));
listTwoP.add(js2, BorderLayout.CENTER);
controlHolder.add(listTwoP, BorderLayout.EAST);
aboutAndControlHolder.add(controlHolder, BorderLayout.SOUTH);
JPanel aboutP = m_tempEditor.getAboutPanel();
aboutAndControlHolder.add(aboutP, BorderLayout.NORTH);
add(aboutAndControlHolder, BorderLayout.NORTH);
// setup incoming atts combos
if (m_join.getFirstInputStructure() != null) {
m_firstKeyFields.removeAllItems();
Instances incoming = m_join.getFirstInputStructure();
for (int i = 0; i < incoming.numAttributes(); i++) {
m_firstKeyFields.addItem(incoming.attribute(i).name());
}
}
if (m_join.getSecondInputStructure() != null) {
m_secondKeyFields.removeAllItems();
Instances incoming = m_join.getSecondInputStructure();
for (int i = 0; i < incoming.numAttributes(); i++) {
m_secondKeyFields.addItem(incoming.attribute(i).name());
}
}
m_firstList.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
if (!m_deleteOneBut.isEnabled()) {
m_deleteOneBut.setEnabled(true);
}
}
}
});
m_secondList.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
if (!m_deleteTwoBut.isEnabled()) {
m_deleteTwoBut.setEnabled(true);
}
}
}
});
m_addOneBut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (m_firstKeyFields.getSelectedItem() != null
&& m_firstKeyFields.getSelectedItem().toString().length() > 0) {
m_firstListModel.addElement(m_firstKeyFields.getSelectedItem());
if (m_firstListModel.size() > 1) {
m_upOneBut.setEnabled(true);
m_downOneBut.setEnabled(true);
}
}
}
});
m_addTwoBut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (m_secondKeyFields.getSelectedItem() != null
&& m_secondKeyFields.getSelectedItem().toString().length() > 0) {
m_secondListModel.addElement(m_secondKeyFields.getSelectedItem());
if (m_secondListModel.size() > 1) {
m_upTwoBut.setEnabled(true);
m_downTwoBut.setEnabled(true);
}
}
}
});
m_deleteOneBut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int selected = m_firstList.getSelectedIndex();
if (selected >= 0) {
m_firstListModel.remove(selected);
}
if (m_firstListModel.size() <= 1) {
m_upOneBut.setEnabled(false);
m_downOneBut.setEnabled(false);
}
}
});
m_deleteTwoBut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int selected = m_secondList.getSelectedIndex();
if (selected >= 0) {
m_secondListModel.remove(selected);
}
if (m_secondListModel.size() <= 1) {
m_upTwoBut.setEnabled(false);
m_downTwoBut.setEnabled(false);
}
}
});
m_upOneBut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JListHelper.moveUp(m_firstList);
;
}
});
m_upTwoBut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JListHelper.moveUp(m_secondList);
}
});
m_downOneBut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JListHelper.moveDown(m_firstList);
}
});
m_downTwoBut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JListHelper.moveDown(m_secondList);
;
}
});
addButtons();
}
private void addButtons() {
JButton okBut = new JButton("OK");
JButton cancelBut = new JButton("Cancel");
JPanel butHolder = new JPanel();
butHolder.setLayout(new GridLayout(1, 2));
butHolder.add(okBut);
butHolder.add(cancelBut);
add(butHolder, BorderLayout.SOUTH);
okBut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
closingOK();
m_parent.dispose();
}
});
cancelBut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
closingCancel();
m_parent.dispose();
}
});
}
@SuppressWarnings("unchecked")
protected void initialize() {
m_firstListModel = new DefaultListModel();
m_secondListModel = new DefaultListModel();
m_firstList.setModel(m_firstListModel);
m_secondList.setModel(m_secondListModel);
String keySpec = m_join.getKeySpec();
if (keySpec != null && keySpec.length() > 0) {
try {
keySpec = m_env.substitute(keySpec);
} catch (Exception ex) {
}
String[] parts = keySpec.split(Join.KEY_SPEC_SEPARATOR);
if (parts.length > 0) {
String[] firstParts = parts[0].trim().split(",");
for (String s : firstParts) {
m_firstListModel.addElement(s);
}
}
if (parts.length > 1) {
String[] secondParts = parts[1].trim().split(",");
for (String s : secondParts) {
m_secondListModel.addElement(s);
}
}
}
}
@Override
public void setObject(Object bean) {
if (bean instanceof Join) {
m_join = (Join) bean;
m_tempEditor.setTarget(bean);
setup();
initialize();
}
}
@Override
public void setParentWindow(Window parent) {
m_parent = parent;
}
@Override
public void setModifiedListener(ModifyListener l) {
m_modifyL = l;
}
@Override
public void setEnvironment(Environment env) {
m_env = env;
}
private void closingOK() {
StringBuilder b = new StringBuilder();
for (int i = 0; i < m_firstListModel.size(); i++) {
if (i != 0) {
b.append(",");
}
b.append(m_firstListModel.get(i));
}
b.append(Join.KEY_SPEC_SEPARATOR);
for (int i = 0; i < m_secondListModel.size(); i++) {
if (i != 0) {
b.append(",");
}
b.append(m_secondListModel.get(i));
}
m_join.setKeySpec(b.toString());
}
private void closingCancel() {
// nothing to do
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/KFIgnore.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/>.
*/
/*
* KFIgnore.java
* Copyright (C) 2014 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Marker annotation. Used to prevent the Knowledge Flow from making something
* available in it's design pallete.
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision$
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface KFIgnore {
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/KFStep.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/>.
*/
/*
* KFStep.java
* Copyright (C) 2011-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Optional annotation for plugin beans in the Knowledge Flow. The main
* purpose is to provide info on which top-level folder (category) the
* plugin should appear under in the GUI. Note that learning algorithms
* automatically appear in the Knowledge Flow under the correct category
* as long as they are in the classpath or are provided in packages. This
* annotation mechanism is useful for plugin components that are not
* standard Weka classifiers, clusterers, associators, loaders etc.
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision$
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface KFStep {
/**
* The top-level folder in the JTree that this plugin bean
* should appear in
*
* @return the name of the top-level folder that this plugin
* bean should appear in
*/
String category();
/**
* Mouse-over tool tip for this plugin component (appears when the
* mouse hovers over the entry in the JTree)
*
* @return the tool tip text for this plugin bean
*/
String toolTipText();
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/KnowledgeFlow.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/>.
*/
/*
* KnowledgeFlow.java
* Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import weka.core.Copyright;
import weka.core.Version;
import java.util.Arrays;
import java.util.List;
/**
* Startup class for the KnowledgeFlow. Displays a splash screen.
*
* @author Mark Hall
* @version $Revision$
*/
public class KnowledgeFlow {
/**
* Static method that can be called from a running program to launch the
* KnowledgeFlow
*/
public static void startApp() {
KnowledgeFlowApp.addStartupListener(new StartUpListener() {
public void startUpComplete() {
weka.gui.SplashWindow.disposeSplash();
}
});
List<String> message =
Arrays.asList("WEKA Knowledge Flow", "Version " + Version.VERSION,
"(c) " + Copyright.getFromYear() + " - " + Copyright.getToYear(),
"The University of Waikato", "Hamilton, New Zealand");
weka.gui.SplashWindow.splash(
ClassLoader.getSystemResource("weka/gui/weka_icon_new.png"),
message);
Thread nt = new Thread() {
public void run() {
weka.gui.SplashWindow.invokeMethod("weka.gui.beans.KnowledgeFlowApp",
"createSingleton", null);
}
};
nt.start();
}
/**
* Shows the splash screen, launches the application and then disposes the
* splash screen.
*
* @param args the command line arguments
*/
public static void main(String[] args) {
weka.core.logging.Logger.log(weka.core.logging.Logger.Level.INFO,
"Logging started");
List<String> message =
Arrays.asList("WEKA Knowledge Flow", "Version " + Version.VERSION,
"(c) " + Copyright.getFromYear() + " - " + Copyright.getToYear(),
"The University of Waikato", "Hamilton, New Zealand");
weka.gui.SplashWindow.splash(ClassLoader.
// getSystemResource("weka/gui/beans/icons/splash.jpg"));
getSystemResource("weka/gui/weka_icon_new.png"), message);
weka.gui.SplashWindow.invokeMain("weka.gui.beans.KnowledgeFlowApp", args);
weka.gui.SplashWindow.disposeSplash();
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/KnowledgeFlowApp.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/>.
*/
/*
* KnowledgeFlowApp.java
* Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.gui.beans;
import weka.core.Attribute;
import weka.core.Copyright;
import weka.core.Environment;
import weka.core.EnvironmentHandler;
import weka.core.Instances;
import weka.core.Memory;
import weka.core.PluginManager;
import weka.core.SerializedObject;
import weka.core.Utils;
import weka.core.WekaEnumeration;
import weka.core.WekaPackageClassLoaderManager;
import weka.core.WekaPackageManager;
import weka.core.converters.FileSourcedConverter;
import weka.core.xml.KOML;
import weka.core.xml.XStream;
import weka.gui.AttributeSelectionPanel;
import weka.gui.ExtensionFileFilter;
import weka.gui.GenericObjectEditor;
import weka.gui.GenericPropertiesCreator;
import weka.gui.HierarchyPropertyParser;
import weka.gui.LookAndFeel;
import weka.gui.beans.xml.XMLBeans;
import weka.gui.visualize.PrintablePanel;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.filechooser.FileFilter;
import javax.swing.plaf.basic.BasicButtonUI;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.DefaultTreeSelectionModel;
import javax.swing.tree.MutableTreeNode;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Dialog.ModalityType;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Menu;
import java.awt.MenuItem;
import java.awt.Point;
import java.awt.PopupMenu;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.image.BufferedImage;
import java.beans.BeanInfo;
import java.beans.Customizer;
import java.beans.EventSetDescriptor;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.beancontext.BeanContextChild;
import java.beans.beancontext.BeanContextSupport;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.SortedSet;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.Vector;
/**
* Main GUI class for the KnowledgeFlow. Modifications to allow interoperability
* with swt provided by Davide Zerbetto (davide dot zerbetto at eng dot it).
*
* @author Mark Hall
* @version $Revision$
* @since 1.0
* @see JPanel
* @see PropertyChangeListener
*/
public class KnowledgeFlowApp extends JPanel implements PropertyChangeListener,
BeanCustomizer.ModifyListener {
/** for serialization */
private static final long serialVersionUID = -7064906770289728431L;
/** Map of all plugin perspectives */
protected Map<String, String> m_pluginPerspectiveLookup =
new HashMap<String, String>();
/** Those perspectives that have been instantiated */
protected Map<String, KFPerspective> m_perspectiveCache =
new HashMap<String, KFPerspective>();
/**
* Holds the details needed to construct button bars for various supported
* classes of weka algorithms/tools
*/
private static Vector<Vector<?>> TOOLBARS = new Vector<Vector<?>>();
/**
* Add a plugin bean props file
*
* @param beanPropsFile the plugin properties to add
* @throws Exception if a problem occurs
*/
public static void addToPluginBeanProps(File beanPropsFile) throws Exception {
BeansProperties.addToPluginBeanProps(beanPropsFile);
}
/**
* Remove a plugin bean props file
*
* @param beanPropsFile the plugin properties to remove
* @throws Exception if a problem occurs
*/
public static void removeFromPluginBeanProps(File beanPropsFile)
throws Exception {
BeansProperties.removeFromPluginBeanProps(beanPropsFile);
}
/**
* Loads KnowledgeFlow properties and any plugins (adds jars to the classpath)
*/
public static synchronized void loadProperties() {
BeansProperties.loadProperties();
}
public static void reInitialize() {
loadProperties();
init();
}
/**
* Initializes the temporary files necessary to construct the toolbars from.
*/
private static void init() {
weka.core.logging.Logger.log(weka.core.logging.Logger.Level.INFO,
"[KnowledgeFlow] Initializing KF...");
// suppress these benign warnings when loading/deserializing XML flows
if (!XMLBeans.SUPPRESS_PROPERTY_WARNINGS.contains("visual.iconPath")) {
XMLBeans.SUPPRESS_PROPERTY_WARNINGS.add("visual.iconPath");
}
if (!XMLBeans.SUPPRESS_PROPERTY_WARNINGS
.contains("visual.animatedIconPath")) {
XMLBeans.SUPPRESS_PROPERTY_WARNINGS.add("visual.animatedIconPath");
}
try {
TOOLBARS = new Vector<Vector<?>>();
TreeMap<Integer, Object> wrapList = new TreeMap<Integer, Object>();
Properties GEOProps = GenericPropertiesCreator
.getGlobalOutputProperties();
if (GEOProps == null) {
GenericPropertiesCreator creator = new GenericPropertiesCreator();
if (creator.useDynamic()) {
creator.execute(false);
/*
* now process the keys in the GenericObjectEditor.props. For each key
* that has an entry in the Beans.props associating it with a bean
* component a button tool bar will be created
*/
GEOProps = creator.getOutputProperties();
} else {
// Read the static information from the GenericObjectEditor.props
GEOProps = Utils.readProperties("weka/gui/GenericObjectEditor.props");
}
}
Enumeration<?> en = GEOProps.propertyNames();
while (en.hasMoreElements()) {
String geoKey = (String) en.nextElement();
// System.err.println("GEOKey " + geoKey);
// try to match this key with one in the Beans.props file
String beanCompName = BeansProperties.BEAN_PROPERTIES
.getProperty(geoKey);
if (beanCompName != null) {
// add details necessary to construct a button bar for this class
// of algorithms
Vector<Object> newV = new Vector<Object>();
// check for a naming alias for this toolbar
String toolBarNameAlias = BeansProperties.BEAN_PROPERTIES
.getProperty(geoKey + ".alias");
String toolBarName = (toolBarNameAlias != null) ? toolBarNameAlias
: geoKey.substring(geoKey.lastIndexOf('.') + 1, geoKey.length());
// look for toolbar ordering information for this wrapper type
String order = BeansProperties.BEAN_PROPERTIES.getProperty(geoKey
+ ".order");
Integer intOrder = (order != null) ? new Integer(order)
: new Integer(0);
// Name for the toolbar (name of weka algorithm class)
newV.addElement(toolBarName);
// Name of bean capable of handling this class of algorithm
newV.addElement(beanCompName);
// add the root package for this key
String rootPackage = geoKey.substring(0, geoKey.lastIndexOf('.'));
newV.addElement(rootPackage);
// All the weka algorithms of this class of algorithm
String wekaAlgs = GEOProps.getProperty(geoKey);
Hashtable<String, String> roots = GenericObjectEditor
.sortClassesByRoot(wekaAlgs);
Hashtable<String, HierarchyPropertyParser> hpps =
new Hashtable<String, HierarchyPropertyParser>();
Enumeration<String> enm = roots.keys();
while (enm.hasMoreElements()) {
String root = enm.nextElement();
String classes = roots.get(root);
weka.gui.HierarchyPropertyParser hpp =
new weka.gui.HierarchyPropertyParser();
hpp.build(classes, ", ");
// System.err.println(hpp.showTree());
hpps.put(root, hpp);
}
// ------ test the HierarchyPropertyParser
/*
* weka.gui.HierarchyPropertyParser hpp = new
* weka.gui.HierarchyPropertyParser(); hpp.build(wekaAlgs, ", ");
*
* System.err.println(hpp.showTree());
*/
// ----- end test the HierarchyPropertyParser
// newV.addElement(hpp); // add the hierarchical property parser
newV.addElement(hpps); // add the hierarchical property parser
StringTokenizer st = new StringTokenizer(wekaAlgs, ", ");
while (st.hasMoreTokens()) {
String current = st.nextToken().trim();
newV.addElement(current);
}
wrapList.put(intOrder, newV);
// TOOLBARS.addElement(newV);
}
}
Iterator<Integer> keysetIt = wrapList.keySet().iterator();
while (keysetIt.hasNext()) {
Integer key = keysetIt.next();
@SuppressWarnings("unchecked")
Vector<Object> newV = (Vector<Object>) wrapList.get(key);
if (newV != null) {
TOOLBARS.addElement(newV);
}
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null,
"Could not read a configuration file for the generic objecte editor"
+ ". An example file is included with the Weka distribution.\n"
+ "This file should be named \"GenericObjectEditor.props\" and\n"
+ "should be placed either in your user home (which is set\n"
+ "to \"" + System.getProperties().getProperty("user.home") + "\")\n"
+ "or the directory that java was started from\n", "KnowledgeFlow",
JOptionPane.ERROR_MESSAGE);
}
try {
String standardToolBarNames = BeansProperties.BEAN_PROPERTIES
.getProperty("weka.gui.beans.KnowledgeFlow.standardToolBars");
StringTokenizer st = new StringTokenizer(standardToolBarNames, ", ");
while (st.hasMoreTokens()) {
String tempBarName = st.nextToken().trim();
// construct details for this toolbar
Vector<String> newV = new Vector<String>();
// add the name of the toolbar
newV.addElement(tempBarName);
// indicate that this is a standard toolbar (no wrapper bean)
newV.addElement("null");
String toolBarContents = BeansProperties.BEAN_PROPERTIES
.getProperty("weka.gui.beans.KnowledgeFlow." + tempBarName);
StringTokenizer st2 = new StringTokenizer(toolBarContents, ", ");
while (st2.hasMoreTokens()) {
String tempBeanName = st2.nextToken().trim();
newV.addElement(tempBeanName);
}
TOOLBARS.addElement(newV);
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getMessage(), "KnowledgeFlow",
JOptionPane.ERROR_MESSAGE);
}
}
protected class BeanIconRenderer extends DefaultTreeCellRenderer {
/** Added ID to avoid warning. */
private static final long serialVersionUID = -4488876734500244945L;
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value,
boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row,
hasFocus);
if (leaf) {
Object userO = ((DefaultMutableTreeNode) value).getUserObject();
if (userO instanceof JTreeLeafDetails) {
Icon i = ((JTreeLeafDetails) userO).getIcon();
if (i != null) {
setIcon(i);
}
}
}
return this;
}
}
protected class InvisibleNode extends DefaultMutableTreeNode {
/**
*
*/
private static final long serialVersionUID = -9064396835384819887L;
protected boolean m_isVisible;
public InvisibleNode() {
this(null);
}
public InvisibleNode(Object userObject) {
this(userObject, true, true);
}
public InvisibleNode(Object userObject, boolean allowsChildren,
boolean isVisible) {
super(userObject, allowsChildren);
this.m_isVisible = isVisible;
}
public TreeNode getChildAt(int index, boolean filterIsActive) {
if (!filterIsActive) {
return super.getChildAt(index);
}
if (children == null) {
throw new ArrayIndexOutOfBoundsException("node has no children");
}
int realIndex = -1;
int visibleIndex = -1;
Enumeration<TreeNode> e = new WekaEnumeration<TreeNode>(
children);
while (e.hasMoreElements()) {
InvisibleNode node = (InvisibleNode)e.nextElement();
if (node.isVisible()) {
visibleIndex++;
}
realIndex++;
if (visibleIndex == index) {
return (TreeNode) children.elementAt(realIndex);
}
}
throw new ArrayIndexOutOfBoundsException("index unmatched");
}
public int getChildCount(boolean filterIsActive) {
if (!filterIsActive) {
return super.getChildCount();
}
if (children == null) {
return 0;
}
int count = 0;
Enumeration<TreeNode> e = new WekaEnumeration<TreeNode>(
children);
while (e.hasMoreElements()) {
InvisibleNode node = (InvisibleNode)e.nextElement();
if (node.isVisible()) {
count++;
}
}
return count;
}
public void setVisible(boolean visible) {
this.m_isVisible = visible;
}
public boolean isVisible() {
return m_isVisible;
}
}
protected class InvisibleTreeModel extends DefaultTreeModel {
/**
*
*/
private static final long serialVersionUID = 6940101211275068260L;
protected boolean m_filterIsActive;
public InvisibleTreeModel(TreeNode root) {
this(root, false);
}
public InvisibleTreeModel(TreeNode root, boolean asksAllowsChildren) {
this(root, false, false);
}
public InvisibleTreeModel(TreeNode root, boolean asksAllowsChildren,
boolean filterIsActive) {
super(root, asksAllowsChildren);
this.m_filterIsActive = filterIsActive;
}
public void activateFilter(boolean newValue) {
m_filterIsActive = newValue;
}
public boolean isActivatedFilter() {
return m_filterIsActive;
}
@Override
public Object getChild(Object parent, int index) {
if (m_filterIsActive) {
if (parent instanceof InvisibleNode) {
return ((InvisibleNode) parent).getChildAt(index, m_filterIsActive);
}
}
return ((TreeNode) parent).getChildAt(index);
}
@Override
public int getChildCount(Object parent) {
if (m_filterIsActive) {
if (parent instanceof InvisibleNode) {
return ((InvisibleNode) parent).getChildCount(m_filterIsActive);
}
}
return ((TreeNode) parent).getChildCount();
}
}
/**
* Inner class for encapsulating information about a bean that is represented
* at a leaf in the JTree.
*/
protected class JTreeLeafDetails implements Serializable {
/**
* For serialization
*/
private static final long serialVersionUID = 6197221540272931626L;
/** fully qualified bean name */
protected String m_fullyQualifiedCompName = "";
/**
* the label (usually derived from the qualified name or wrapped algorithm)
* for the leaf
*/
protected String m_leafLabel = "";
/** the fully qualified wrapped weka algorithm name */
protected String m_wekaAlgoName = "";
/** icon to display at the leaf (scaled appropriately) */
protected transient Icon m_scaledIcon = null;
/** XML serialized MetaBean (if this is a user component) */
// protected StringBuffer m_metaBean = null;
protected Vector<Object> m_metaBean = null;
/** true if this is a MetaBean (user component) */
protected boolean m_isMeta = false;
/** tool tip text to display */
protected String m_toolTipText = null;
/**
* Constructor.
*
* @param fullName flully qualified name of the bean
* @param icon icon for the bean
*/
protected JTreeLeafDetails(String fullName, Icon icon) {
this(fullName, "", icon);
}
/**
* Constructor
*
* @param name fully qualified name of the bean
* @param serializedMeta empty string or XML serialized MetaBean if this
* leaf represents a "user" component
*
* @param icon icon for the bean
*/
protected JTreeLeafDetails(String name, Vector<Object> serializedMeta,
Icon icon) {
this(name, "", icon);
// m_isMeta = isMeta;
m_metaBean = serializedMeta;
m_isMeta = true;
m_toolTipText = "Hold down shift and click to remove";
}
/**
* Constructor
*
* @param fullName fully qualified name of the bean
* @param wekaAlgoName fully qualified name of the encapsulated (wrapped)
* weka algorithm, or null if this bean does not wrap a Weka
* algorithm
*
* @param icon icon for the bean
*/
protected JTreeLeafDetails(String fullName, String wekaAlgoName, Icon icon) {
m_fullyQualifiedCompName = fullName;
m_wekaAlgoName = wekaAlgoName;
m_leafLabel = (wekaAlgoName.length() > 0) ? wekaAlgoName
: m_fullyQualifiedCompName;
if (m_leafLabel.lastIndexOf('.') > 0) {
m_leafLabel = m_leafLabel.substring(m_leafLabel.lastIndexOf('.') + 1,
m_leafLabel.length());
}
m_scaledIcon = icon;
}
/**
* Get the tool tip for this leaf
*
* @return the tool tip
*/
protected String getToolTipText() {
return m_toolTipText;
}
protected void setToolTipText(String tipText) {
m_toolTipText = tipText;
}
/**
* Returns the leaf label
*
* @return the leaf label
*/
@Override
public String toString() {
return m_leafLabel;
}
/**
* Gets the icon for this bean
*
* @return the icon for this bean
*/
protected Icon getIcon() {
return m_scaledIcon;
}
/**
* Set the icon to use for this bean
*
* @param icon the icon to use
*/
protected void setIcon(Icon icon) {
m_scaledIcon = icon;
}
/**
* Returns true if this leaf represents a wrapped Weka algorithm (i.e.
* filter, classifier, clusterer etc.).
*
* @return true if this leaf represents a wrapped algorithm
*/
protected boolean isWrappedAlgorithm() {
return (m_wekaAlgoName != null && m_wekaAlgoName.length() > 0);
}
/**
* Returns true if this leaf represents a MetaBean (i.e. "user" component)
*
* @return true if this leaf represents a MetaBean
*/
protected boolean isMetaBean() {
return (m_metaBean != null);
// return (m_wekaAlgoName.length() == 0);
// return m_isMeta;
}
/**
* Gets the XML serialized MetaBean and associated information (icon,
* displayname)
*
* @return the XML serialized MetaBean as a 3-element Vector containing
* display name serialized bean and icon
*/
protected Vector<Object> getMetaBean() {
return m_metaBean;
}
/**
* "Instantiates" the bean represented by this leaf.
*/
protected void instantiateBean() {
try {
if (isMetaBean()) {
// MetaBean copy = copyMetaBean(m_metaBean, false);
// copy.addPropertyChangeListenersSubFlow(KnowledgeFlowApp.this);
m_toolBarBean = m_metaBean.get(1);
} else {
m_toolBarBean = WekaPackageClassLoaderManager.objectForName(m_fullyQualifiedCompName);
//m_toolBarBean = Beans.instantiate(KnowledgeFlowApp.this.getClass()
// .getClassLoader(), m_fullyQualifiedCompName);
if (isWrappedAlgorithm()) {
Object algo = WekaPackageClassLoaderManager.objectForName(m_wekaAlgoName);
//Object algo = Beans.instantiate(KnowledgeFlowApp.this.getClass()
// .getClassLoader(), m_wekaAlgoName);
((WekaWrapper) m_toolBarBean).setWrappedAlgorithm(algo);
}
}
KnowledgeFlowApp.this.setCursor(Cursor
.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
m_mode = ADDING;
m_pasteB.setEnabled(false);
} catch (Exception ex) {
System.err
.println("Problem instantiating bean \"" + m_fullyQualifiedCompName
+ "\" (JTreeLeafDetails.instantiateBean()");
ex.printStackTrace();
}
}
}
/**
* Used for displaying the bean components and their visible connections
*
* @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a>
* @version $Revision$
* @since 1.0
* @see PrintablePanel
*/
protected class BeanLayout extends PrintablePanel {
/** for serialization */
private static final long serialVersionUID = -146377012429662757L;
@Override
public void paintComponent(Graphics gx) {
double lz = m_layoutZoom / 100.0;
((Graphics2D) gx).scale(lz, lz);
if (m_layoutZoom < 100) {
((Graphics2D) gx).setStroke(new BasicStroke(2));
}
super.paintComponent(gx);
((Graphics2D) gx).setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
((Graphics2D) gx).setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_GASP);
BeanInstance.paintLabels(gx, m_mainKFPerspective.getCurrentTabIndex());
BeanConnection.paintConnections(gx,
m_mainKFPerspective.getCurrentTabIndex());
// BeanInstance.paintConnections(gx);
if (m_mode == CONNECTING) {
gx.drawLine(m_startX, m_startY, m_oldX, m_oldY);
} else if (m_mode == SELECTING) {
gx.drawRect((m_startX < m_oldX) ? m_startX : m_oldX,
(m_startY < m_oldY) ? m_startY : m_oldY, Math.abs(m_oldX - m_startX),
Math.abs(m_oldY - m_startY));
}
}
@Override
public void doLayout() {
super.doLayout();
Vector<Object> comps = BeanInstance.getBeanInstances(m_mainKFPerspective
.getCurrentTabIndex());
for (int i = 0; i < comps.size(); i++) {
BeanInstance bi = (BeanInstance) comps.elementAt(i);
JComponent c = (JComponent) bi.getBean();
Dimension d = c.getPreferredSize();
c.setBounds(bi.getX(), bi.getY(), d.width, d.height);
c.revalidate();
}
}
}
/**
* Interface for perspectives.
*/
public static interface KFPerspective {
/**
* Set instances (if the perspective accepts them)
*
* @param insts the instances
*/
void setInstances(Instances insts) throws Exception;
/**
* Returns true if this perspective accepts instances
*
* @return true if this perspective can accept instances
*/
boolean acceptsInstances();
/**
* Get the title of this perspective
*
* @return the title of this perspective
*/
String getPerspectiveTitle();
/**
* Get the tool tip text for this perspective.
*
* @return the tool tip text for this perspective
*/
String getPerspectiveTipText();
/**
* Get the icon for this perspective.
*
* @return the Icon for this perspective (or null if the perspective does
* not have an icon)
*/
Icon getPerspectiveIcon();
/**
* Set active status of this perspective. True indicates that this
* perspective is the visible active perspective in the KnowledgeFlow
*
* @param active true if this perspective is the active one
*/
void setActive(boolean active);
/**
* Set whether this perspective is "loaded" - i.e. whether or not the user
* has opted to have it available in the perspective toolbar. The
* perspective can make the decision as to allocating or freeing resources
* on the basis of this.
*
* @param loaded true if the perspective is available in the perspective
* toolbar of the KnowledgeFlow
*/
void setLoaded(boolean loaded);
/**
* Set a reference to the main KnowledgeFlow perspective - i.e. the
* perspective that manages flow layouts.
*
* @param main the main KnowledgeFlow perspective.
*/
void setMainKFPerspective(KnowledgeFlowApp.MainKFPerspective main);
}
/**
* Main Knowledge Flow perspective
*
*/
public class MainKFPerspective extends JPanel implements KFPerspective {
/**
*
*/
private static final long serialVersionUID = 7666381888012259527L;
/** Holds the tabs of the perspective */
protected JTabbedPane m_flowTabs = new JTabbedPane();
/** List of layouts - one for each tab */
protected List<BeanLayout> m_beanLayouts = new ArrayList<BeanLayout>();
/** List of zoom settings - one for each tab */
protected List<Integer> m_zoomSettings = new ArrayList<Integer>();
/** List of log panels - one for each tab */
protected List<KFLogPanel> m_logPanels = new ArrayList<KFLogPanel>();
/** List of environment variable settings - one for each tab */
protected List<Environment> m_environmentSettings =
new ArrayList<Environment>();
/** List of flow file paths - one for each tab */
protected List<File> m_filePaths = new ArrayList<File>();
/** Keeps track of which tabs have been edited but not saved */
protected List<Boolean> m_editedList = new ArrayList<Boolean>();
/** Keeps track of which tabs have flows that are executing */
protected List<Boolean> m_executingList = new ArrayList<Boolean>();
/** Keeps track of the threads used for execution */
protected List<RunThread> m_executionThreads = new ArrayList<RunThread>();
/** Keeps track of any highlighted beans on the canvas for a tab */
protected List<Vector<Object>> m_selectedBeans =
new ArrayList<Vector<Object>>();
/** Keeps track of the undo buffers for each tab */
protected List<Stack<File>> m_undoBufferList = new ArrayList<Stack<File>>();
protected Map<String, DefaultMutableTreeNode> m_nodeTextIndex =
new LinkedHashMap<String, DefaultMutableTreeNode>();
@Override
public void setActive(boolean active) {
// nothing to do here
}
@Override
public void setLoaded(boolean loaded) {
// we are always loaded and part of the set of perspectives
}
@Override
public void setMainKFPerspective(MainKFPerspective main) {
// we don't need this :-)
}
public JTabbedPane getTabbedPane() {
return m_flowTabs;
}
public synchronized int getNumTabs() {
return m_flowTabs.getTabCount();
}
public synchronized String getTabTitle(int index) {
if (index < getNumTabs() && index >= 0) {
return m_flowTabs.getTitleAt(index);
}
return null;
}
public synchronized int getCurrentTabIndex() {
return m_flowTabs.getSelectedIndex();
}
public synchronized KFLogPanel getCurrentLogPanel() {
if (getCurrentTabIndex() >= 0) {
return m_logPanels.get(getCurrentTabIndex());
}
return null;
}
public synchronized KFLogPanel getLogPanel(int index) {
if (index >= 0 && index < m_logPanels.size()) {
return m_logPanels.get(index);
}
return null;
}
public synchronized BeanLayout getCurrentBeanLayout() {
if (getCurrentTabIndex() >= 0) {
return m_beanLayouts.get(getCurrentTabIndex());
}
return null;
}
public synchronized BeanLayout getBeanLayout(int index) {
if (index >= 0 && index < m_logPanels.size()) {
return m_beanLayouts.get(getCurrentTabIndex());
}
return null;
}
public synchronized int getCurrentZoomSetting() {
if (getCurrentTabIndex() >= 0) {
return m_zoomSettings.get(getCurrentTabIndex()).intValue();
}
// no scaling
return 100;
}
public synchronized int getZoomSetting(int index) {
if (index >= 0 && index < m_zoomSettings.size()) {
return m_zoomSettings.get(index);
}
// no scaling
return 100;
}
public synchronized void setCurrentZoomSetting(int z) {
if (getNumTabs() > 0) {
setZoomSetting(getCurrentTabIndex(), z);
}
}
public synchronized void setZoomSetting(int index, int z) {
if (index < getNumTabs() && index >= 0) {
m_zoomSettings.set(index, new Integer(z));
}
}
public synchronized void setActiveTab(int index) {
if (index < getNumTabs() && index >= 0) {
m_flowTabs.setSelectedIndex(index);
// set the log and layout to the ones belonging to this tab
m_logPanel = m_logPanels.get(index);
m_beanLayout = m_beanLayouts.get(index);
m_layoutZoom = m_zoomSettings.get(index);
m_flowEnvironment = m_environmentSettings.get(index);
m_saveB.setEnabled(!getExecuting());
m_saveBB.setEnabled(!getExecuting());
m_playB.setEnabled(!getExecuting());
m_playBB.setEnabled(!getExecuting());
m_saveB.setEnabled(!getExecuting());
m_saveBB.setEnabled(!getExecuting());
m_zoomOutB.setEnabled(!getExecuting());
m_zoomInB.setEnabled(!getExecuting());
if (m_layoutZoom == 50) {
m_zoomOutB.setEnabled(false);
}
if (m_layoutZoom == 200) {
m_zoomInB.setEnabled(false);
}
m_groupB.setEnabled(false);
if (getSelectedBeans().size() > 0 && !getExecuting()) {
// Able to group selected subflow?
final Vector<Object> selected = m_mainKFPerspective
.getSelectedBeans();
// check if sub flow is valid
final Vector<Object> inputs = BeanConnection.inputs(selected,
m_mainKFPerspective.getCurrentTabIndex());
final Vector<Object> outputs = BeanConnection.outputs(selected,
m_mainKFPerspective.getCurrentTabIndex());
if (groupable(selected, inputs, outputs)) {
m_groupB.setEnabled(true);
}
}
m_cutB.setEnabled(getSelectedBeans().size() > 0 && !getExecuting());
m_copyB.setEnabled(getSelectedBeans().size() > 0 && !getExecuting());
m_deleteB.setEnabled(getSelectedBeans().size() > 0 && !getExecuting());
m_selectAllB.setEnabled(BeanInstance.getBeanInstances(
getCurrentTabIndex()).size() > 0
&& !getExecuting());
m_pasteB
.setEnabled((m_pasteBuffer != null && m_pasteBuffer.length() > 0)
&& !getExecuting());
m_stopB.setEnabled(getExecuting());
m_undoB.setEnabled(!getExecuting() && getUndoBuffer().size() > 0);
}
}
public synchronized void setExecuting(boolean executing) {
if (getNumTabs() > 0) {
setExecuting(getCurrentTabIndex(), executing);
}
}
public synchronized void setExecuting(int index, boolean executing) {
if (index < getNumTabs() && index >= 0) {
m_executingList.set(index, new Boolean(executing));
((CloseableTabTitle) m_flowTabs.getTabComponentAt(index))
.setButtonEnabled(!executing);
m_saveB.setEnabled(!getExecuting());
m_saveBB.setEnabled(!getExecuting());
m_playB.setEnabled(!getExecuting());
m_playBB.setEnabled(!getExecuting());
m_stopB.setEnabled(getExecuting());
m_groupB.setEnabled(false);
if (getSelectedBeans().size() > 0 && !getExecuting()) {
// Able to group selected subflow?
final Vector<Object> selected = m_mainKFPerspective
.getSelectedBeans();
// check if sub flow is valid
final Vector<Object> inputs = BeanConnection.inputs(selected,
m_mainKFPerspective.getCurrentTabIndex());
final Vector<Object> outputs = BeanConnection.outputs(selected,
m_mainKFPerspective.getCurrentTabIndex());
if (groupable(selected, inputs, outputs)) {
m_groupB.setEnabled(true);
}
}
m_cutB.setEnabled(getSelectedBeans().size() > 0 && !getExecuting());
m_deleteB.setEnabled(getSelectedBeans().size() > 0 && !getExecuting());
m_selectAllB.setEnabled(BeanInstance.getBeanInstances(
getCurrentTabIndex()).size() > 0
&& !getExecuting());
m_copyB.setEnabled(getSelectedBeans().size() > 0 && !getExecuting());
m_pasteB
.setEnabled((m_pasteBuffer != null && m_pasteBuffer.length() > 0)
&& !getExecuting());
m_undoB.setEnabled(!getExecuting() && getUndoBuffer().size() > 0);
}
}
public synchronized boolean getExecuting() {
return getExecuting(getCurrentTabIndex());
}
public synchronized boolean getExecuting(int index) {
if (index < getNumTabs() && index >= 0) {
return m_executingList.get(index);
}
return false;
}
public synchronized void setExecutionThread(RunThread execution) {
if (getNumTabs() > 0) {
setExecutionThread(getCurrentTabIndex(), execution);
}
}
public synchronized void setExecutionThread(int index, RunThread execution) {
if (index < getNumTabs() && index >= 0) {
m_executionThreads.set(index, execution);
}
}
public synchronized RunThread getExecutionThread() {
return getExecutionThread(getCurrentTabIndex());
}
public synchronized RunThread getExecutionThread(int index) {
if (index < getNumTabs() && index >= 0) {
return m_executionThreads.get(index);
}
return null;
}
public synchronized File getFlowFile() {
if (getNumTabs() > 0) {
return getFlowFile(getCurrentTabIndex());
}
return null;
}
public synchronized File getFlowFile(int index) {
if (index >= 0 && index < getNumTabs()) {
return m_filePaths.get(index);
}
return null;
}
public synchronized void setFlowFile(File flowFile) {
if (getNumTabs() > 0) {
setFlowFile(getCurrentTabIndex(), flowFile);
}
}
public synchronized void setFlowFile(int index, File flowFile) {
if (index < getNumTabs() && index >= 0) {
m_filePaths.set(index, flowFile);
}
}
public synchronized void setTabTitle(String title) {
if (getNumTabs() > 0) {
setTabTitle(getCurrentTabIndex(), title);
}
}
public synchronized void setTabTitle(int index, String title) {
if (index < getNumTabs() && index >= 0) {
m_flowTabs.setTitleAt(index, title);
((CloseableTabTitle) m_flowTabs.getTabComponentAt(index)).revalidate();
}
}
public synchronized void setEditedStatus(boolean status) {
if (getNumTabs() > 0) {
int current = getCurrentTabIndex();
setEditedStatus(current, status);
}
}
public synchronized void setEditedStatus(int index, boolean status) {
if (index < getNumTabs() && index >= 0) {
Boolean newStatus = new Boolean(status);
m_editedList.set(index, newStatus);
((CloseableTabTitle) m_flowTabs.getTabComponentAt(index))
.setBold(status);
}
}
/**
* Get the edited status of the currently selected tab. Returns false if
* there are no tabs
*
* @return the edited status of the currently selected tab or false if there
* are no tabs
*/
public synchronized boolean getEditedStatus() {
if (getNumTabs() <= 0) {
return false;
}
return getEditedStatus(getCurrentTabIndex());
}
/**
* Get the edited status of the tab at the supplied index. Returns false if
* the index is out of bounds or there are no tabs
*
* @param index the index of the tab to check
* @return the edited status of the tab
*/
public synchronized boolean getEditedStatus(int index) {
if (index < getNumTabs() && index >= 0) {
return m_editedList.get(index);
}
return false;
}
public synchronized void setUndoBuffer(Stack<File> buffer) {
if (getNumTabs() > 0) {
setUndoBuffer(getCurrentTabIndex(), buffer);
}
}
public synchronized void setUndoBuffer(int index, Stack<File> buffer) {
if (index < getNumTabs() && index >= 0) {
m_undoBufferList.set(index, buffer);
}
}
public synchronized Stack<File> getUndoBuffer() {
if (getNumTabs() > 0) {
return getUndoBuffer(getCurrentTabIndex());
}
return null;
}
public synchronized Stack<File> getUndoBuffer(int index) {
if (index >= 0 && index < getNumTabs()) {
return m_undoBufferList.get(index);
}
return null;
}
public synchronized Vector<Object> getSelectedBeans() {
if (getNumTabs() > 0) {
return getSelectedBeans(getCurrentTabIndex());
}
return null;
}
public synchronized Vector<Object> getSelectedBeans(int index) {
if (index < getNumTabs() && index >= 0) {
return m_selectedBeans.get(index);
}
return null;
}
public synchronized void setSelectedBeans(Vector<Object> beans) {
if (getNumTabs() > 0) {
setSelectedBeans(getCurrentTabIndex(), beans);
m_groupB.setEnabled(false);
if (getSelectedBeans().size() > 0 && !getExecuting()) {
// Able to group selected subflow?
final Vector<Object> selected = m_mainKFPerspective
.getSelectedBeans();
// check if sub flow is valid
final Vector<Object> inputs = BeanConnection.inputs(selected,
m_mainKFPerspective.getCurrentTabIndex());
final Vector<Object> outputs = BeanConnection.outputs(selected,
m_mainKFPerspective.getCurrentTabIndex());
if (groupable(selected, inputs, outputs)) {
m_groupB.setEnabled(true);
}
}
m_cutB.setEnabled(getSelectedBeans().size() > 0 && !getExecuting());
m_copyB.setEnabled(getSelectedBeans().size() > 0 && !getExecuting());
m_deleteB.setEnabled(getSelectedBeans().size() > 0 && !getExecuting());
}
}
public synchronized void setSelectedBeans(int index, Vector<Object> beans) {
if (index < getNumTabs() && index >= 0) {
// turn turn off any set ones
for (int i = 0; i < m_selectedBeans.get(index).size(); i++) {
BeanInstance temp = (BeanInstance) m_selectedBeans.get(index)
.elementAt(i);
if (temp.getBean() instanceof Visible) {
((Visible) temp.getBean()).getVisual().setDisplayConnectors(false);
} else if (temp.getBean() instanceof Note) {
((Note) temp.getBean()).setHighlighted(false);
}
}
m_selectedBeans.set(index, beans);
// highlight any new ones
for (int i = 0; i < beans.size(); i++) {
BeanInstance temp = (BeanInstance) beans.elementAt(i);
if (temp.getBean() instanceof Visible) {
((Visible) temp.getBean()).getVisual().setDisplayConnectors(true);
} else if (temp.getBean() instanceof Note) {
((Note) temp.getBean()).setHighlighted(true);
}
}
}
}
public synchronized Environment getEnvironmentSettings() {
if (getNumTabs() > 0) {
return getEnvironmentSettings(getCurrentTabIndex());
}
return null;
}
public synchronized Environment getEnvironmentSettings(int index) {
if (index < getNumTabs() && index >= 0) {
return m_environmentSettings.get(index);
}
return null;
}
@Override
public void setInstances(Instances insts) {
// nothing to do as we don't process externally supplied instances
}
@Override
public boolean acceptsInstances() {
// not needed
return false;
}
/**
* Get the title of this perspective
*/
@Override
public String getPerspectiveTitle() {
return "Data mining processes";
}
/**
* Get the tool tip text for this perspective
*/
@Override
public String getPerspectiveTipText() {
return "Knowledge Flow processes";
}
/**
* Get the icon for this perspective
*/
@Override
public Icon getPerspectiveIcon() {
Image wekaI = loadImage("weka/gui/weka_icon_new.png");
ImageIcon icon = new ImageIcon(wekaI);
double width = icon.getIconWidth();
double height = icon.getIconHeight();
width *= 0.035;
height *= 0.035;
wekaI = wekaI.getScaledInstance((int) width, (int) height,
Image.SCALE_SMOOTH);
icon = new ImageIcon(wekaI);
return icon;
}
@SuppressWarnings("unchecked")
private void setUpToolsAndJTree() {
JPanel toolBarPanel = new JPanel();
toolBarPanel.setLayout(new BorderLayout());
// modifications by Zerbetto
// first construct the toolbar for saving, loading etc
if (m_showFileMenu) {
// set up an action for closing the curren tab
final Action closeAction = new AbstractAction("Close") {
/**
*
*/
private static final long serialVersionUID = 4762166880144590384L;
@Override
public void actionPerformed(ActionEvent e) {
if (m_mainKFPerspective.getCurrentTabIndex() >= 0) {
m_mainKFPerspective.removeTab(getCurrentTabIndex());
}
}
};
KeyStroke closeKey = KeyStroke.getKeyStroke(KeyEvent.VK_W,
InputEvent.CTRL_DOWN_MASK);
MainKFPerspective.this.getActionMap().put("Close", closeAction);
MainKFPerspective.this.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
.put(closeKey, "Close");
JToolBar fixedTools = new JToolBar();
fixedTools.setOrientation(JToolBar.HORIZONTAL);
m_groupB = new JButton(new ImageIcon(loadImage(BeanVisual.ICON_PATH
+ "bricks.png")));
m_groupB.setBorder(BorderFactory.createEmptyBorder(0, 8, 0, 0));
m_groupB.setToolTipText("Group selected (Ctrl+Z)");
m_cutB = new JButton(new ImageIcon(loadImage(BeanVisual.ICON_PATH
+ "cut.png")));
m_cutB.setBorder(BorderFactory.createEmptyBorder(0, 8, 0, 0));
m_cutB.setToolTipText("Cut selected (Ctrl+X)");
m_copyB = new JButton(new ImageIcon(loadImage(BeanVisual.ICON_PATH
+ "page_copy.png")));
m_copyB.setBorder(BorderFactory.createEmptyBorder(0, 8, 0, 0));
m_copyB.setToolTipText("Copy selected (Ctrl+C)");
m_pasteB = new JButton(new ImageIcon(loadImage(BeanVisual.ICON_PATH
+ "paste_plain.png")));
m_pasteB.setBorder(BorderFactory.createEmptyBorder(0, 8, 0, 0));
m_pasteB.setToolTipText("Paste from clipboard (Ctrl+V)");
m_deleteB = new JButton(new ImageIcon(loadImage(BeanVisual.ICON_PATH
+ "delete.png")));
m_deleteB.setBorder(BorderFactory.createEmptyBorder(0, 8, 0, 0));
m_deleteB.setToolTipText("Delete selected (DEL)");
m_snapToGridB = new JToggleButton(new ImageIcon(
loadImage(BeanVisual.ICON_PATH + "shape_handles.png")));
// m_snapToGridB.setBorder(BorderFactory.createEmptyBorder(0, 8, 0, 0));
m_snapToGridB.setToolTipText("Snap to grid (Ctrl+G)");
m_saveB = new JButton(new ImageIcon(loadImage(BeanVisual.ICON_PATH
+ "disk.png")));
m_saveB.setBorder(BorderFactory.createEmptyBorder(0, 8, 0, 0));
m_saveB.setToolTipText("Save layout (Ctrl+S)");
m_saveBB = new JButton(new ImageIcon(loadImage(BeanVisual.ICON_PATH
+ "disk_multiple.png")));
m_saveBB.setBorder(BorderFactory.createEmptyBorder(0, 8, 0, 0));
m_saveBB.setToolTipText("Save layout with new name");
m_loadB = new JButton(new ImageIcon(loadImage(BeanVisual.ICON_PATH
+ "folder_add.png")));
m_loadB.setToolTipText("Open (Ctrl+O)");
m_loadB.setBorder(BorderFactory.createEmptyBorder(0, 8, 0, 0));
m_newB = new JButton(new ImageIcon(loadImage(BeanVisual.ICON_PATH
+ "page_add.png")));
m_newB.setToolTipText("New layout (Ctrl+N)");
m_newB.setBorder(BorderFactory.createEmptyBorder(0, 8, 0, 0));
m_newB.setEnabled(getAllowMultipleTabs());
m_helpB = new JButton(new ImageIcon(loadImage(BeanVisual.ICON_PATH
+ "help.png")));
m_helpB.setBorder(BorderFactory.createEmptyBorder(0, 8, 0, 0));
m_helpB.setToolTipText("Display help (Ctrl+H)");
m_togglePerspectivesB = new JButton(new ImageIcon(
loadImage(BeanVisual.ICON_PATH + "cog_go.png")));
m_togglePerspectivesB.setBorder(BorderFactory.createEmptyBorder(0, 8,
0, 0));
m_togglePerspectivesB
.setToolTipText("Show/hide perspectives toolbar (Ctrl+P)");
m_templatesB = new JButton(new ImageIcon(loadImage(BeanVisual.ICON_PATH
+ "application_view_tile.png")));
m_templatesB.setBorder(BorderFactory.createEmptyBorder(0, 8, 0, 0));
m_templatesB.setToolTipText("Load a template layout");
m_noteB = new JButton(new ImageIcon(loadImage(BeanVisual.ICON_PATH
+ "note_add.png")));
m_noteB.setBorder(BorderFactory.createEmptyBorder(0, 8, 0, 0));
m_noteB.setToolTipText("Add a note to the layout (Ctrl+I)");
m_selectAllB = new JButton(new ImageIcon(loadImage(BeanVisual.ICON_PATH
+ "shape_group.png")));
m_selectAllB.setBorder(BorderFactory.createEmptyBorder(0, 8, 0, 0));
m_selectAllB.setToolTipText("Select all (Ctrl+A)");
m_zoomInB = new JButton(new ImageIcon(loadImage(BeanVisual.ICON_PATH
+ "zoom_in.png")));
m_zoomInB.setBorder(BorderFactory.createEmptyBorder(0, 8, 0, 0));
m_zoomInB.setToolTipText("Zoom in (Ctrl++)");
m_zoomOutB = new JButton(new ImageIcon(loadImage(BeanVisual.ICON_PATH
+ "zoom_out.png")));
m_zoomOutB.setBorder(BorderFactory.createEmptyBorder(0, 8, 0, 0));
m_zoomOutB.setToolTipText("Zoom out (Ctrl+-)");
m_undoB = new JButton(new ImageIcon(loadImage(BeanVisual.ICON_PATH
+ "arrow_undo.png")));
m_undoB.setBorder(BorderFactory.createEmptyBorder(0, 8, 0, 0));
m_undoB.setToolTipText("Undo (Ctrl+U)");
fixedTools.add(m_zoomInB);
fixedTools.add(m_zoomOutB);
fixedTools.addSeparator();
fixedTools.add(m_selectAllB);
fixedTools.add(m_groupB);
fixedTools.add(m_cutB);
fixedTools.add(m_copyB);
fixedTools.add(m_deleteB);
fixedTools.add(m_pasteB);
fixedTools.add(m_undoB);
fixedTools.add(m_noteB);
fixedTools.addSeparator();
fixedTools.add(m_snapToGridB);
fixedTools.addSeparator();
fixedTools.add(m_newB);
fixedTools.add(m_saveB);
fixedTools.add(m_saveBB);
fixedTools.add(m_loadB);
fixedTools.add(m_templatesB);
fixedTools.addSeparator();
fixedTools.add(m_togglePerspectivesB);
fixedTools.add(m_helpB);
Dimension d = m_undoB.getPreferredSize();
Dimension d2 = fixedTools.getMinimumSize();
Dimension d3 = new Dimension(d2.width, d.height + 4);
fixedTools.setPreferredSize(d3);
fixedTools.setMaximumSize(d3);
final Action saveAction = new AbstractAction("Save") {
/**
*
*/
private static final long serialVersionUID = 5182044142154404706L;
@Override
public void actionPerformed(ActionEvent e) {
if (m_mainKFPerspective.getCurrentTabIndex() >= 0) {
saveLayout(m_mainKFPerspective.getCurrentTabIndex(), false);
}
}
};
KeyStroke saveKey = KeyStroke.getKeyStroke(KeyEvent.VK_S,
InputEvent.CTRL_DOWN_MASK);
MainKFPerspective.this.getActionMap().put("Save", saveAction);
MainKFPerspective.this.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
.put(saveKey, "Save");
m_saveB.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
saveAction.actionPerformed(e);
}
});
m_saveBB.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
saveLayout(m_mainKFPerspective.getCurrentTabIndex(), true);
}
});
final Action openAction = new AbstractAction("Open") {
/**
*
*/
private static final long serialVersionUID = -5106547209818805444L;
@Override
public void actionPerformed(ActionEvent e) {
m_flowEnvironment = new Environment();
loadLayout();
}
};
KeyStroke openKey = KeyStroke.getKeyStroke(KeyEvent.VK_O,
InputEvent.CTRL_DOWN_MASK);
MainKFPerspective.this.getActionMap().put("Open", openAction);
MainKFPerspective.this.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
.put(openKey, "Open");
m_loadB.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
openAction.actionPerformed(e);
}
});
final Action newAction = new AbstractAction("New") {
/**
*
*/
private static final long serialVersionUID = 8002244400334262966L;
@Override
public void actionPerformed(ActionEvent e) {
clearLayout();
}
};
KeyStroke newKey = KeyStroke.getKeyStroke(KeyEvent.VK_N,
InputEvent.CTRL_DOWN_MASK);
MainKFPerspective.this.getActionMap().put("New", newAction);
MainKFPerspective.this.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
.put(newKey, "New");
m_newB.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
newAction.actionPerformed(ae);
}
});
final Action selectAllAction = new AbstractAction("SelectAll") {
/**
*
*/
private static final long serialVersionUID = -8086754050844707658L;
@Override
public void actionPerformed(ActionEvent e) {
if (BeanInstance.getBeanInstances(
m_mainKFPerspective.getCurrentTabIndex()).size() > 0) {
// select all beans
Vector<Object> allBeans = BeanInstance
.getBeanInstances(m_mainKFPerspective.getCurrentTabIndex());
Vector<Object> newSelected = new Vector<Object>();
for (int i = 0; i < allBeans.size(); i++) {
newSelected.add(allBeans.get(i));
}
// toggle
if (newSelected.size() == m_mainKFPerspective.getSelectedBeans()
.size()) {
// unselect all beans
m_mainKFPerspective.setSelectedBeans(new Vector<Object>());
} else {
// select all beans
m_mainKFPerspective.setSelectedBeans(newSelected);
}
}
revalidate();
repaint();
notifyIsDirty();
}
};
KeyStroke selectAllKey = KeyStroke.getKeyStroke(KeyEvent.VK_A,
InputEvent.CTRL_DOWN_MASK);
MainKFPerspective.this.getActionMap().put("SelectAll", selectAllAction);
MainKFPerspective.this.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
.put(selectAllKey, "SelectAll");
m_selectAllB.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
selectAllAction.actionPerformed(e);
}
});
final Action zoomInAction = new AbstractAction("ZoomIn") {
/**
*
*/
private static final long serialVersionUID = 1348383794897269484L;
@Override
public void actionPerformed(ActionEvent e) {
m_layoutZoom += 25;
m_zoomOutB.setEnabled(true);
if (m_layoutZoom >= 200) {
m_layoutZoom = 200;
m_zoomInB.setEnabled(false);
}
m_mainKFPerspective.setCurrentZoomSetting(m_layoutZoom);
revalidate();
repaint();
notifyIsDirty();
}
};
KeyStroke zoomInKey = KeyStroke.getKeyStroke(KeyEvent.VK_EQUALS,
InputEvent.CTRL_DOWN_MASK);
MainKFPerspective.this.getActionMap().put("ZoomIn", zoomInAction);
MainKFPerspective.this.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
.put(zoomInKey, "ZoomIn");
m_zoomInB.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
zoomInAction.actionPerformed(e);
}
});
final Action zoomOutAction = new AbstractAction("ZoomOut") {
/**
*
*/
private static final long serialVersionUID = -1120096894263455918L;
@Override
public void actionPerformed(ActionEvent e) {
m_layoutZoom -= 25;
m_zoomInB.setEnabled(true);
if (m_layoutZoom <= 50) {
m_layoutZoom = 50;
m_zoomOutB.setEnabled(false);
}
m_mainKFPerspective.setCurrentZoomSetting(m_layoutZoom);
revalidate();
repaint();
notifyIsDirty();
}
};
KeyStroke zoomOutKey = KeyStroke.getKeyStroke(KeyEvent.VK_MINUS,
InputEvent.CTRL_DOWN_MASK);
MainKFPerspective.this.getActionMap().put("ZoomOut", zoomOutAction);
MainKFPerspective.this.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
.put(zoomOutKey, "ZoomOut");
m_zoomOutB.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
zoomOutAction.actionPerformed(e);
}
});
final Action groupAction = new AbstractAction("Group") {
/**
*
*/
private static final long serialVersionUID = -5752742619180091435L;
@Override
public void actionPerformed(ActionEvent e) {
final Vector<Object> selected = m_mainKFPerspective
.getSelectedBeans();
final Vector<Object> inputs = BeanConnection.inputs(selected,
m_mainKFPerspective.getCurrentTabIndex());
final Vector<Object> outputs = BeanConnection.outputs(selected,
m_mainKFPerspective.getCurrentTabIndex());
groupSubFlow(selected, inputs, outputs);
}
};
KeyStroke groupKey = KeyStroke.getKeyStroke(KeyEvent.VK_Z,
InputEvent.CTRL_DOWN_MASK);
MainKFPerspective.this.getActionMap().put("Group", groupAction);
MainKFPerspective.this.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
.put(groupKey, "Group");
m_groupB.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
groupAction.actionPerformed(e);
}
});
final Action cutAction = new AbstractAction("Cut") {
/**
*
*/
private static final long serialVersionUID = -4955878102742013040L;
@Override
public void actionPerformed(ActionEvent e) {
// only delete if our copy was successful!
if (copyToClipboard()) {
deleteSelectedBeans();
}
}
};
KeyStroke cutKey = KeyStroke.getKeyStroke(KeyEvent.VK_X,
InputEvent.CTRL_DOWN_MASK);
MainKFPerspective.this.getActionMap().put("Cut", cutAction);
MainKFPerspective.this.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
.put(cutKey, "Cut");
m_cutB.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
cutAction.actionPerformed(e);
}
});
final Action deleteAction = new AbstractAction("Delete") {
/**
*
*/
private static final long serialVersionUID = 4621688037874199553L;
@Override
public void actionPerformed(ActionEvent e) {
deleteSelectedBeans();
}
};
KeyStroke deleteKey = KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0);
MainKFPerspective.this.getActionMap().put("Delete", deleteAction);
MainKFPerspective.this.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
.put(deleteKey, "Delete");
m_deleteB.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
deleteAction.actionPerformed(e);
}
});
final Action copyAction = new AbstractAction("Copy") {
/**
*
*/
private static final long serialVersionUID = 117010390180468707L;
@Override
public void actionPerformed(ActionEvent e) {
copyToClipboard();
m_mainKFPerspective.setSelectedBeans(new Vector<Object>());
}
};
KeyStroke copyKey = KeyStroke.getKeyStroke(KeyEvent.VK_C,
InputEvent.CTRL_DOWN_MASK);
MainKFPerspective.this.getActionMap().put("Copy", copyAction);
MainKFPerspective.this.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
.put(copyKey, "Copy");
m_copyB.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
copyAction.actionPerformed(e);
}
});
final Action pasteAction = new AbstractAction("Paste") {
/**
*
*/
private static final long serialVersionUID = 5935121051028929455L;
@Override
public void actionPerformed(ActionEvent e) {
KnowledgeFlowApp.this.setCursor(Cursor
.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
m_mode = PASTING;
}
};
KeyStroke pasteKey = KeyStroke.getKeyStroke(KeyEvent.VK_V,
InputEvent.CTRL_DOWN_MASK);
MainKFPerspective.this.getActionMap().put("Paste", pasteAction);
MainKFPerspective.this.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
.put(pasteKey, "Paste");
m_pasteB.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
pasteAction.actionPerformed(e);
}
});
final Action snapAction = new AbstractAction("Snap") {
/**
*
*/
private static final long serialVersionUID = 7820689847829357449L;
@Override
public void actionPerformed(ActionEvent e) {
// toggle first
m_snapToGridB.setSelected(!m_snapToGridB.isSelected());
if (m_snapToGridB.isSelected()) {
snapSelectedToGrid();
}
}
};
KeyStroke snapKey = KeyStroke.getKeyStroke(KeyEvent.VK_G,
InputEvent.CTRL_DOWN_MASK);
MainKFPerspective.this.getActionMap().put("Snap", snapAction);
MainKFPerspective.this.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
.put(snapKey, "Snap");
m_snapToGridB.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (m_snapToGridB.isSelected()) {
snapSelectedToGrid();
}
}
});
fixedTools.setFloatable(false);
toolBarPanel.add(fixedTools, BorderLayout.EAST);
}
final Action noteAction = new AbstractAction("Note") {
/**
*
*/
private static final long serialVersionUID = 2991743619130024875L;
@Override
public void actionPerformed(ActionEvent e) {
Note n = new Note();
m_toolBarBean = n;
KnowledgeFlowApp.this.setCursor(Cursor
.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
m_mode = ADDING;
}
};
KeyStroke noteKey = KeyStroke.getKeyStroke(KeyEvent.VK_I,
InputEvent.CTRL_DOWN_MASK);
MainKFPerspective.this.getActionMap().put("Note", noteAction);
MainKFPerspective.this.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
.put(noteKey, "Note");
m_noteB.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
noteAction.actionPerformed(e);
}
});
final Action undoAction = new AbstractAction("Undo") {
/**
*
*/
private static final long serialVersionUID = 7248362305594881263L;
@Override
public void actionPerformed(ActionEvent e) {
Stack<File> undo = m_mainKFPerspective.getUndoBuffer();
if (undo.size() > 0) {
File undoF = undo.pop();
if (undo.size() == 0) {
m_undoB.setEnabled(false);
}
loadLayout(undoF, false, true);
}
}
};
KeyStroke undoKey = KeyStroke.getKeyStroke(KeyEvent.VK_U,
InputEvent.CTRL_DOWN_MASK);
MainKFPerspective.this.getActionMap().put("Undo", undoAction);
MainKFPerspective.this.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
.put(undoKey, "Undo");
m_undoB.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
undoAction.actionPerformed(e);
}
});
m_playB = new JButton(new ImageIcon(loadImage(BeanVisual.ICON_PATH
+ "resultset_next.png")));
m_playB.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0));
m_playB
.setToolTipText("Run this flow (all start points launched in parallel)");
m_playB.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (BeanInstance.getBeanInstances(
m_mainKFPerspective.getCurrentTabIndex()).size() == 0) {
return;
}
boolean proceed = true;
if (m_Memory.memoryIsLow()) {
proceed = m_Memory.showMemoryIsLow();
}
if (proceed) {
runFlow(false);
}
}
});
m_playBB = new JButton(new ImageIcon(loadImage(BeanVisual.ICON_PATH
+ "resultset_last.png")));
m_playBB.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0));
m_playBB
.setToolTipText("Run this flow (start points launched sequentially)");
m_playBB.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (BeanInstance.getBeanInstances(
m_mainKFPerspective.getCurrentTabIndex()).size() == 0) {
return;
}
if (!Utils
.getDontShowDialog("weka.gui.beans.KnowledgeFlow.SequentialRunInfo")) {
JCheckBox dontShow =
new JCheckBox("Do not show this message again");
Object[] stuff = new Object[2];
stuff[0] =
"The order that data sources are launched in can be\n"
+ "specified by setting a custom name for each data source that\n"
+ "that includes a number. E.g. \"1:MyArffLoader\". To set a name,\n"
+ "right-click over a data source and select \"Set name\"\n\n"
+ "If the prefix is not specified, then the order of execution\n"
+ "will correspond to the order that the components were added\n"
+ "to the layout. Note that it is also possible to prevent a data\n"
+ "source from executing by prefixing its name with a \"!\". E.g\n"
+ "\"!:MyArffLoader\"";
stuff[1] = dontShow;
JOptionPane.showMessageDialog(KnowledgeFlowApp.this, stuff,
"Sequential execution information", JOptionPane.OK_OPTION);
if (dontShow.isSelected()) {
try {
Utils
.setDontShowDialog("weka.gui.beans.KnowledgeFlow.SequentialRunInfo");
} catch (Exception ex) {
// quietly ignore
}
}
}
boolean proceed = true;
if (m_Memory.memoryIsLow()) {
proceed = m_Memory.showMemoryIsLow();
}
if (proceed) {
runFlow(true);
}
}
});
m_stopB = new JButton(new ImageIcon(loadImage(BeanVisual.ICON_PATH
+ "shape_square.png")));
m_stopB.setBorder(BorderFactory.createEmptyBorder(0, 8, 0, 0));
m_stopB.setToolTipText("Stop all execution");
Image tempI = loadImage(BeanVisual.ICON_PATH + "cursor.png");
m_pointerB = new JButton(new ImageIcon(tempI));
m_pointerB.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0));
m_pointerB.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
m_toolBarBean = null;
m_mode = NONE;
KnowledgeFlowApp.this.setCursor(Cursor
.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
m_componentTree.clearSelection();
}
});
// Dimension dP = m_saveB.getPreferredSize();
// Dimension dM = m_saveB.getMaximumSize();
// Dimension dP = m_stopB.getPreferredSize();
// Dimension dM = m_stopB.getMaximumSize();
// m_pointerB.setPreferredSize(dP);
// m_pointerB.setMaximumSize(dM);
// m_toolBarGroup.add(m_pointerB);
JToolBar fixedTools2 = new JToolBar();
fixedTools2.setOrientation(JToolBar.HORIZONTAL);
fixedTools2.setFloatable(false);
fixedTools2.add(m_pointerB);
fixedTools2.add(m_playB);
fixedTools2.add(m_playBB);
fixedTools2.add(m_stopB);
Dimension d = m_playB.getPreferredSize();
Dimension d2 = fixedTools2.getMinimumSize();
Dimension d3 = new Dimension(d2.width, d.height + 4);
fixedTools2.setPreferredSize(d3);
fixedTools2.setMaximumSize(d3);
// m_helpB.setPreferredSize(dP);
// m_helpB.setMaximumSize(dP);
// m_helpB.setSize(m_pointerB.getSize().width,
// m_pointerB.getSize().height);
toolBarPanel.add(fixedTools2, BorderLayout.WEST);
// end modifications by Zerbetto
m_stopB.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
m_logPanel
.statusMessage("@!@[KnowledgeFlow]|Attempting to stop all components...");
stopFlow();
m_logPanel.statusMessage("@!@[KnowledgeFlow]|OK.");
}
});
final Action helpAction = new AbstractAction("Help") {
/**
*
*/
private static final long serialVersionUID = 3301809940717051925L;
@Override
public void actionPerformed(ActionEvent e) {
popupHelp();
}
};
KeyStroke helpKey = KeyStroke.getKeyStroke(KeyEvent.VK_H,
InputEvent.CTRL_DOWN_MASK);
MainKFPerspective.this.getActionMap().put("Help", helpAction);
MainKFPerspective.this.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
.put(helpKey, "Help");
m_helpB.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
helpAction.actionPerformed(ae);
}
});
m_templatesB.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
createTemplateMenuPopup();
}
});
m_templatesB.setEnabled(BeansProperties.TEMPLATE_PATHS.size() > 0);
final Action togglePerspectivesAction = new AbstractAction(
"Toggle perspectives") {
/**
*
*/
private static final long serialVersionUID = 5394622655137498495L;
@Override
public void actionPerformed(ActionEvent e) {
if (m_firstUserComponentOpp) {
installWindowListenerForSavingUserStuff();
m_firstUserComponentOpp = false;
}
if (!Utils
.getDontShowDialog("weka.gui.beans.KnowledgeFlow.PerspectiveInfo")) {
JCheckBox dontShow =
new JCheckBox("Do not show this message again");
Object[] stuff = new Object[2];
stuff[0] =
"Perspectives are environments that take over the\n"
+ "Knowledge Flow UI and provide major additional functionality.\n"
+ "Many perspectives will operate on a set of instances. Instances\n"
+ "Can be sent to a perspective by placing a DataSource on the\n"
+ "layout canvas, configuring it and then selecting \"Send to perspective\"\n"
+ "from the contextual popup menu that appears when you right-click on\n"
+ "it. Several perspectives are built in to the Knowledge Flow, others\n"
+ "can be installed via the package manager.\n";
stuff[1] = dontShow;
JOptionPane.showMessageDialog(KnowledgeFlowApp.this, stuff,
"Perspective information", JOptionPane.OK_OPTION);
if (dontShow.isSelected()) {
try {
Utils
.setDontShowDialog("weka.gui.beans.KnowledgeFlow.PerspectiveInfo");
} catch (Exception ex) {
// quietly ignore
}
}
}
if (m_configAndPerspectivesVisible) {
KnowledgeFlowApp.this.remove(m_configAndPerspectives);
m_configAndPerspectivesVisible = false;
} else {
KnowledgeFlowApp.this.add(m_configAndPerspectives,
BorderLayout.NORTH);
m_configAndPerspectivesVisible = true;
}
revalidate();
repaint();
notifyIsDirty();
}
};
KeyStroke togglePerspectivesKey = KeyStroke.getKeyStroke(KeyEvent.VK_P,
InputEvent.CTRL_DOWN_MASK);
MainKFPerspective.this.getActionMap().put("Toggle perspectives",
togglePerspectivesAction);
MainKFPerspective.this.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
.put(togglePerspectivesKey, "Toggle perspectives");
m_togglePerspectivesB.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
togglePerspectivesAction.actionPerformed(e);
}
});
final int standard_toolset = 0;
final int wrapper_toolset = 1;
int toolBarType = standard_toolset;
DefaultMutableTreeNode jtreeRoot = new DefaultMutableTreeNode("Weka");
// set up wrapper toolsets
for (int i = 0; i < TOOLBARS.size(); i++) {
Vector<?> tempBarSpecs = TOOLBARS.elementAt(i);
// name for the tool bar
String tempToolSetName = (String) tempBarSpecs.elementAt(0);
DefaultMutableTreeNode subTreeNode = new InvisibleNode(tempToolSetName);
jtreeRoot.add(subTreeNode);
// Used for weka leaf packages
// Box singletonHolderPanel = null;
// name of the bean component to handle this class of weka algorithms
String tempBeanCompName = (String) tempBarSpecs.elementAt(1);
// the root package for weka algorithms
String rootPackage = "";
weka.gui.HierarchyPropertyParser hpp = null;
Hashtable<String, HierarchyPropertyParser> hpps = null;
// Is this a wrapper toolbar?
if (tempBeanCompName.compareTo("null") != 0) {
toolBarType = wrapper_toolset;
rootPackage = (String) tempBarSpecs.elementAt(2);
// hpp = (weka.gui.HierarchyPropertyParser)tempBarSpecs.elementAt(3);
hpps = (Hashtable<String, HierarchyPropertyParser>) tempBarSpecs
.elementAt(3);
try {
// modifications by Zerbetto
// Beans.instantiate(null, tempBeanCompName);
WekaPackageClassLoaderManager.objectForName(tempBeanCompName);
//Beans.instantiate(this.getClass().getClassLoader(),
// tempBeanCompName);
// end modifications by Zerbetto
} catch (Exception ex) {
// ignore
weka.core.logging.Logger.log(
weka.core.logging.Logger.Level.WARNING,
"[KnowledgeFlow] Failed to instantiate: "
+ tempBeanCompName);
break;
}
} else {
toolBarType = standard_toolset;
}
// a toolbar to hold buttons---one for each algorithm
// JToolBar tempToolBar = new JToolBar();
// System.err.println(tempToolBar.getLayout());
// tempToolBar.setLayout(new FlowLayout());
int z = 2;
if (toolBarType == wrapper_toolset) {
Enumeration<String> enm = hpps.keys();
while (enm.hasMoreElements()) {
String root = enm.nextElement();
hpp = hpps.get(root);
if (!hpp.goTo(rootPackage)) {
}
String[] primaryPackages = hpp.childrenValues();
for (String primaryPackage : primaryPackages) {
hpp.goToChild(primaryPackage);
// check to see if this is a leaf - if so then there are no
// sub packages
if (hpp.isLeafReached()) {
/*
* if (singletonHolderPanel == null) { singletonHolderPanel =
* Box.createHorizontalBox();
* singletonHolderPanel.setBorder(javax
* .swing.BorderFactory.createTitledBorder( tempToolSetName)); }
*/
String algName = hpp.fullValue();
// -- tempBean = instantiateToolBarBean(true, tempBeanCompName,
// algName);
Object visibleCheck = instantiateBean(
(toolBarType == wrapper_toolset), tempBeanCompName, algName);
// if (tempBean != null) {
if (visibleCheck != null) {
// tempToolBar.add(tempBean);
// singletonHolderPanel.add(tempBean);
/*
* Object visibleCheck = instantiateBean((toolBarType ==
* wrapper_toolset), tempBeanCompName, algName);
*/
if (visibleCheck instanceof BeanContextChild) {
m_bcSupport.add(visibleCheck);
}
ImageIcon scaledForTree = null;
if (visibleCheck instanceof Visible) {
BeanVisual bv = ((Visible) visibleCheck).getVisual();
if (bv != null) {
scaledForTree = new ImageIcon(bv.scale(0.33));
// m_iconLookup.put(algName, scaledForTree);
}
}
// try and get a tool tip
String toolTip = "";
try {
Object wrappedA = WekaPackageClassLoaderManager.objectForName(algName);
// Object wrappedA = Class.forName(algName).newInstance();
toolTip = getGlobalInfo(wrappedA);
} catch (Exception ex) {
}
JTreeLeafDetails leafData = new JTreeLeafDetails(
tempBeanCompName, algName, scaledForTree);
if (toolTip != null && toolTip.length() > 0) {
leafData.setToolTipText(toolTip);
}
DefaultMutableTreeNode leafAlgo = new InvisibleNode(leafData);
subTreeNode.add(leafAlgo);
m_nodeTextIndex.put(algName.toLowerCase() + " "
+ (toolTip != null ? toolTip.toLowerCase() + " " : ""),
leafAlgo);
}
hpp.goToParent();
} else {
// make a titledborder JPanel to hold all the schemes in this
// package
// JPanel holderPanel = new JPanel();
/*
* Box holderPanel = Box.createHorizontalBox();
* holderPanel.setBorder
* (javax.swing.BorderFactory.createTitledBorder(userPrefix +
* primaryPackages[kk]));
*/
DefaultMutableTreeNode firstLevelOfMainAlgoType =
new InvisibleNode(
primaryPackage);
subTreeNode.add(firstLevelOfMainAlgoType);
// processPackage(holderPanel, tempBeanCompName, hpp,
// firstLevelOfMainAlgoType);
processPackage(tempBeanCompName, hpp, firstLevelOfMainAlgoType,
m_nodeTextIndex);
// tempToolBar.add(holderPanel);
}
}
/*
* if (singletonHolderPanel != null) {
* tempToolBar.add(singletonHolderPanel); singletonHolderPanel =
* null; }
*/
}
} else {
/*
* Box holderPanel = Box.createHorizontalBox();
* holderPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(
* tempToolSetName));
*/
for (int j = z; j < tempBarSpecs.size(); j++) {
tempBeanCompName = (String) tempBarSpecs.elementAt(j);
Object visibleCheck = instantiateBean(
(toolBarType == wrapper_toolset), tempBeanCompName, "");
/*
* -- tempBean = instantiateToolBarBean((toolBarType ==
* wrapper_toolset), tempBeanCompName, "");
*/
// if (tempBean != null) {
if (visibleCheck != null) {
// set tool tip text (if any)
// setToolTipText(tempBean)
// holderPanel.add(tempBean);
String treeName = tempBeanCompName;
if (treeName.lastIndexOf('.') > 0) {
treeName = treeName.substring(treeName.lastIndexOf('.') + 1,
treeName.length());
}
/*
* Object visibleCheck = instantiateBean((toolBarType ==
* wrapper_toolset), tempBeanCompName, "");
*/
if (visibleCheck instanceof BeanContextChild) {
m_bcSupport.add(visibleCheck);
}
ImageIcon scaledForTree = null;
if (visibleCheck instanceof Visible) {
BeanVisual bv = ((Visible) visibleCheck).getVisual();
if (bv != null) {
scaledForTree = new ImageIcon(bv.scale(0.33));
// m_iconLookup.put(treeName, scaledForTree);
}
}
String tipText = null;
tipText = getGlobalInfo(visibleCheck);
// check for annotation and let this override any global info tool
// tip
Class<?> compClass = visibleCheck.getClass();
Annotation[] annotations = compClass.getDeclaredAnnotations();
String category = null;
DefaultMutableTreeNode targetFolder = null;
for (Annotation ann : annotations) {
if (ann instanceof KFStep) {
tipText = "<html><font color=blue>"
+ ((KFStep) ann).toolTipText() + "</font></html>";
category = ((KFStep) ann).category();
// Does this category already exist?
Enumeration<TreeNode> children = jtreeRoot.children();
while (children.hasMoreElements()) {
Object child = children.nextElement();
if (child instanceof DefaultMutableTreeNode) {
if (((DefaultMutableTreeNode) child).getUserObject()
.toString().equals(category)) {
targetFolder = (DefaultMutableTreeNode) child;
break;
}
}
}
break;
}
}
JTreeLeafDetails leafData = new JTreeLeafDetails(
tempBeanCompName, "", scaledForTree);
if (tipText != null) {
leafData.setToolTipText(tipText);
}
DefaultMutableTreeNode fixedLeafNode =
new InvisibleNode(leafData);
if (targetFolder != null) {
targetFolder.add(fixedLeafNode);
} else {
subTreeNode.add(fixedLeafNode);
}
m_nodeTextIndex
.put(tempBeanCompName.toLowerCase() + " "
+ (tipText != null ? tipText.toLowerCase() : ""),
fixedLeafNode);
}
}
// tempToolBar.add(holderPanel);
}
// JScrollPane tempJScrollPane =
// createScrollPaneForToolBar(tempToolBar);
// ok, now create tabbed pane to hold this toolbar
// m_toolBars.addTab(tempToolSetName, null, tempJScrollPane,
// tempToolSetName);
}
// / ----
// TODO Prescan for bean plugins and only create user tree node if there
// are actually some beans (rather than just all perspectives)
// Any plugin components to process?
if (BeansProperties.BEAN_PLUGINS_PROPERTIES != null
&& BeansProperties.BEAN_PLUGINS_PROPERTIES.size() > 0) {
boolean pluginBeans = false;
DefaultMutableTreeNode userSubTree = null;
for (int i = 0; i < BeansProperties.BEAN_PLUGINS_PROPERTIES.size(); i++) {
Properties tempP = BeansProperties.BEAN_PLUGINS_PROPERTIES.get(i);
String components = tempP
.getProperty("weka.gui.beans.KnowledgeFlow.Plugins");
if (components != null && components.length() > 0) {
StringTokenizer st2 = new StringTokenizer(components, ", ");
while (st2.hasMoreTokens()) {
String tempBeanCompName = st2.nextToken().trim();
String treeName = tempBeanCompName;
if (treeName.lastIndexOf('.') > 0) {
treeName = treeName.substring(treeName.lastIndexOf('.') + 1,
treeName.length());
}
// tempBean = instantiateToolBarBean(false, tempBeanCompName, "");
/*
* if (m_pluginsToolBar == null) { // need to create the plugins
* tab and toolbar setUpPluginsToolBar(); }
* m_pluginsBoxPanel.add(tempBean);
*/
Object visibleCheck = instantiateBean(
(toolBarType == wrapper_toolset), tempBeanCompName, "");
if (visibleCheck instanceof BeanContextChild) {
m_bcSupport.add(visibleCheck);
}
ImageIcon scaledForTree = null;
if (visibleCheck instanceof Visible) {
BeanVisual bv = ((Visible) visibleCheck).getVisual();
if (bv != null) {
scaledForTree = new ImageIcon(bv.scale(0.33));
// m_iconLookup.put(tempBeanCompName, scaledForTree);
}
}
String tipText = null;
tipText = getGlobalInfo(visibleCheck);
// check for annotation
Class<?> compClass = visibleCheck.getClass();
Annotation[] annotations = compClass.getDeclaredAnnotations();
DefaultMutableTreeNode targetFolder = null;
String category = null;
for (Annotation ann : annotations) {
if (ann instanceof KFStep) {
category = ((KFStep) ann).category();
tipText = "<html><font color=red>"
+ ((KFStep) ann).toolTipText() + "</font></html>";
// Does this category already exist?
Enumeration<TreeNode> children = jtreeRoot.children();
while (children.hasMoreElements()) {
Object child = children.nextElement();
if (child instanceof DefaultMutableTreeNode) {
if (((DefaultMutableTreeNode) child).getUserObject()
.toString().equals(category)) {
targetFolder = (DefaultMutableTreeNode) child;
break;
}
}
}
break;
}
}
JTreeLeafDetails leafData = new JTreeLeafDetails(
tempBeanCompName, "", scaledForTree);
if (tipText != null) {
leafData.setToolTipText(tipText);
}
DefaultMutableTreeNode pluginLeaf = new InvisibleNode(leafData);
m_nodeTextIndex.put(tempBeanCompName.toLowerCase()
+ (tipText != null ? " " + tipText.toLowerCase() : ""),
pluginLeaf);
if (targetFolder != null) {
targetFolder.add(pluginLeaf);
} else if (category != null) {
// make a new category folder
DefaultMutableTreeNode newCategoryNode = new InvisibleNode(
category);
jtreeRoot.add(newCategoryNode);
newCategoryNode.add(pluginLeaf);
} else {
// add to the default "Plugins" folder
if (!pluginBeans) {
// make the Plugins tree node entry
userSubTree = new InvisibleNode("Plugins");
jtreeRoot.add(userSubTree);
pluginBeans = true;
}
userSubTree.add(pluginLeaf);
}
}
}
// check for perspectives
String perspectives = tempP
.getProperty(("weka.gui.beans.KnowledgeFlow.Perspectives"));
if (perspectives != null && perspectives.length() > 0) {
StringTokenizer st2 = new StringTokenizer(perspectives, ",");
while (st2.hasMoreTokens()) {
String className = st2.nextToken();
try {
if (PluginManager.isInDisabledList(className)) {
continue;
}
Object p = WekaPackageClassLoaderManager.objectForName(className);
// Object p = Class.forName(className).newInstance();
if (p instanceof KFPerspective && p instanceof JPanel) {
String title = ((KFPerspective) p).getPerspectiveTitle();
weka.core.logging.Logger.log(
weka.core.logging.Logger.Level.INFO,
"[KnowledgeFlow] loaded perspective: "
+ title);
m_pluginPerspectiveLookup.put(className, title);
// not selected as part of the users set of perspectives
// yet...
((KFPerspective) p).setLoaded(false);
// check to see if user has selected to use this perspective
if (BeansProperties.VISIBLE_PERSPECTIVES.contains(className)) {
// add to the perspective cache. After processing
// all plugins we will iterate over the sorted
// VISIBLE_PERSPECTIVES in order to add them
// to the toolbar in consistent sorted order
// ((KFPerspective)p).setMainKFPerspective(m_mainKFPerspective);
m_perspectiveCache.put(className, (KFPerspective) p);
}
}
} catch (Exception ex) {
if (m_logPanel != null) {
m_logPanel
.logMessage("[KnowledgeFlow] WARNING: "
+ "unable to instantiate perspective \"" + className
+ "\"");
ex.printStackTrace();
} else {
System.err
.println("[KnowledgeFlow] WARNING: "
+ "unable to instantiate perspective \"" + className
+ "\"");
ex.printStackTrace();
}
}
}
}
}
}
m_togglePerspectivesB.setEnabled(m_pluginPerspectiveLookup.keySet()
.size() > 0);
// toolBarPanel.add(m_toolBars, BorderLayout.CENTER);
// add(m_toolBars, BorderLayout.NORTH);
add(toolBarPanel, BorderLayout.NORTH);
InvisibleTreeModel model = new InvisibleTreeModel(jtreeRoot);// new
// DefaultTreeModel(jtreeRoot);
model.activateFilter(true);
// subclass JTree so that tool tips can be displayed for leaves (if
// necessary)
m_componentTree = new JTree(model) {
/**
*
*/
private static final long serialVersionUID = 6628795889296634120L;
@Override
public String getToolTipText(MouseEvent e) {
if ((getRowForLocation(e.getX(), e.getY())) == -1) {
return null;
}
TreePath currPath = getPathForLocation(e.getX(), e.getY());
if (currPath.getLastPathComponent() instanceof DefaultMutableTreeNode) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) currPath
.getLastPathComponent();
if (node.isLeaf()) {
JTreeLeafDetails leaf = (JTreeLeafDetails) node.getUserObject();
return leaf.getToolTipText();
}
}
return null;
}
};
m_componentTree.setEnabled(true);
m_componentTree.setToolTipText("");
m_componentTree.setRootVisible(false);
m_componentTree.setShowsRootHandles(true);
m_componentTree.setCellRenderer(new BeanIconRenderer());
DefaultTreeSelectionModel selectionModel =
new DefaultTreeSelectionModel();
selectionModel.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
m_componentTree.setSelectionModel(selectionModel);
m_componentTree.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (((e.getModifiers() & InputEvent.BUTTON1_MASK) != InputEvent.BUTTON1_MASK)
|| e.isAltDown()) {
boolean clearSelection = true;
if (clearSelection) {
// right click cancels selected component
m_toolBarBean = null;
m_mode = NONE;
KnowledgeFlowApp.this.setCursor(Cursor
.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
m_componentTree.clearSelection();
}
}
TreePath p = m_componentTree.getSelectionPath();
if (p != null) {
if (p.getLastPathComponent() instanceof DefaultMutableTreeNode) {
DefaultMutableTreeNode tNode = (DefaultMutableTreeNode) p
.getLastPathComponent();
if (tNode.isLeaf()) {
// System.err.println("Selected : " +
// tNode.getUserObject().toString());
Object userObject = tNode.getUserObject();
if (userObject instanceof JTreeLeafDetails) {
if ((e.getModifiers() & InputEvent.SHIFT_MASK) != 0
&& ((JTreeLeafDetails) userObject).isMetaBean()) {
if (m_firstUserComponentOpp) {
installWindowListenerForSavingUserStuff();
m_firstUserComponentOpp = false;
}
Vector<Object> toRemove = ((JTreeLeafDetails) userObject)
.getMetaBean();
DefaultTreeModel model = (DefaultTreeModel) m_componentTree
.getModel();
MutableTreeNode userRoot = (MutableTreeNode) tNode
.getParent(); // The "User" folder
model.removeNodeFromParent(tNode);
m_userComponents.remove(toRemove);
if (m_userComponents.size() == 0) {
model.removeNodeFromParent(userRoot);
m_userCompNode = null;
}
} else {
((JTreeLeafDetails) userObject).instantiateBean();
}
}
}
}
}
}
});
}
public MainKFPerspective() {
setLayout(new BorderLayout());
setUpToolsAndJTree();
JScrollPane treeView = new JScrollPane(m_componentTree);
JPanel treeHolder = new JPanel();
treeHolder.setLayout(new BorderLayout());
treeHolder.setBorder(BorderFactory.createTitledBorder("Design"));
treeHolder.add(treeView, BorderLayout.CENTER);
final JTextField searchField = new JTextField();
treeHolder.add(searchField, BorderLayout.NORTH);
searchField.setToolTipText("Search (clear field to reset)");
searchField.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
String searchTerm = searchField.getText();
List<DefaultMutableTreeNode> nonhits =
new ArrayList<DefaultMutableTreeNode>();
List<DefaultMutableTreeNode> hits =
new ArrayList<DefaultMutableTreeNode>();
DefaultTreeModel model = (DefaultTreeModel) m_componentTree
.getModel();
model.reload(); // collapse all nodes first
for (Map.Entry<String, DefaultMutableTreeNode> entry : m_nodeTextIndex
.entrySet()) {
if (entry.getValue() instanceof InvisibleNode) {
((InvisibleNode) entry.getValue()).setVisible(true);
}
if (searchTerm != null && searchTerm.length() > 0) {
if (entry.getKey().contains(searchTerm.toLowerCase())) {
hits.add(entry.getValue());
} else {
nonhits.add(entry.getValue());
}
}
}
if (searchTerm == null || searchTerm.length() == 0) {
model.reload(); // just reset everything
}
// if we have some hits then set all the non-hits to invisible
if (hits.size() > 0) {
for (DefaultMutableTreeNode h : nonhits) {
if (h instanceof InvisibleNode) {
((InvisibleNode) h).setVisible(false);
}
}
model.reload(); // collapse all the nodes first
// expand all the hits
for (DefaultMutableTreeNode h : hits) {
TreeNode[] path = model.getPathToRoot(h);
TreePath tpath = new TreePath(path);
tpath = tpath.getParentPath();
m_componentTree.expandPath(tpath);
}
}
}
});
// m_perspectiveHolder.add(treeHolder, BorderLayout.WEST);
JSplitPane p2 = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, treeHolder,
m_flowTabs);
p2.setOneTouchExpandable(true);
add(p2, BorderLayout.CENTER);
Dimension d = treeView.getPreferredSize();
d = new Dimension((int) (d.getWidth() * 1.5), (int) d.getHeight());
treeView.setPreferredSize(d);
treeView.setMinimumSize(d);
m_flowTabs.addChangeListener(new ChangeListener() {
// This method is called whenever the selected tab changes
@Override
public void stateChanged(ChangeEvent evt) {
// Get current tab
int sel = m_flowTabs.getSelectedIndex();
setActiveTab(sel);
}
});
}
public synchronized void removeTab(int tabIndex) {
if (tabIndex < 0 || tabIndex >= getNumTabs()) {
return;
}
if (m_editedList.get(tabIndex)) {
// prompt for save
String tabTitle = m_flowTabs.getTitleAt(tabIndex);
String message = "\"" + tabTitle
+ "\" has been modified. Save changes " + "before closing?";
int result = JOptionPane.showConfirmDialog(KnowledgeFlowApp.this,
message, "Save changes", JOptionPane.YES_NO_CANCEL_OPTION);
if (result == JOptionPane.YES_OPTION) {
saveLayout(tabIndex, false);
} else if (result == JOptionPane.CANCEL_OPTION) {
return;
}
}
BeanLayout bl = m_beanLayouts.get(tabIndex);
BeanInstance.removeBeanInstances(bl, tabIndex);
BeanConnection.removeConnectionList(tabIndex);
m_beanLayouts.remove(tabIndex);
m_zoomSettings.remove(tabIndex);
m_logPanels.remove(tabIndex);
m_editedList.remove(tabIndex);
m_environmentSettings.remove(tabIndex);
m_selectedBeans.remove(tabIndex);
bl = null;
m_flowTabs.remove(tabIndex);
if (getCurrentTabIndex() < 0) {
m_beanLayout = null;
m_logPanel = null;
m_saveB.setEnabled(false);
}
}
public synchronized void addTab(String tabTitle) {
// new beans for this tab
BeanInstance.addBeanInstances(new Vector<Object>(), null);
// new connections for this tab
BeanConnection.addConnections(new Vector<BeanConnection>());
JPanel p1 = new JPanel();
p1.setLayout(new BorderLayout());
/*
* p1.setBorder(javax.swing.BorderFactory.createCompoundBorder(
* javax.swing.BorderFactory. createTitledBorder("Knowledge Flow Layout"),
* javax.swing.BorderFactory.createEmptyBorder(0, 5, 5, 5) ));
*/
BeanLayout tabBeanLayout = new BeanLayout();
final JScrollPane js = new JScrollPane(tabBeanLayout);
p1.add(js, BorderLayout.CENTER);
js.getVerticalScrollBar().setUnitIncrement(m_ScrollBarIncrementLayout);
js.getHorizontalScrollBar().setUnitIncrement(m_ScrollBarIncrementLayout);
configureBeanLayout(tabBeanLayout);
m_beanLayouts.add(tabBeanLayout);
tabBeanLayout.setSize(m_FlowWidth, m_FlowHeight);
Dimension d = tabBeanLayout.getPreferredSize();
tabBeanLayout.setMinimumSize(d);
// tabBeanLayout.setMaximumSize(d);
tabBeanLayout.setPreferredSize(d);
m_zoomSettings.add(new Integer(100));
KFLogPanel tabLogPanel = new KFLogPanel();
setUpLogPanel(tabLogPanel);
Dimension d2 = new Dimension(100, 170);
tabLogPanel.setPreferredSize(d2);
tabLogPanel.setMinimumSize(d2);
m_logPanels.add(tabLogPanel);
m_environmentSettings.add(new Environment());
m_filePaths.add(new File("-NONE-"));
JSplitPane p2 =
new JSplitPane(JSplitPane.VERTICAL_SPLIT, p1, tabLogPanel);
p2.setOneTouchExpandable(true);
// p2.setDividerLocation(500);
p2.setDividerLocation(0.7);
p2.setResizeWeight(1.0);
JPanel splitHolder = new JPanel();
splitHolder.setLayout(new BorderLayout());
splitHolder.add(p2, BorderLayout.CENTER);
// add(splitHolder, BorderLayout.CENTER);
m_editedList.add(new Boolean(false));
m_executingList.add(new Boolean(false));
m_executionThreads.add((RunThread) null);
m_selectedBeans.add(new Vector<Object>());
m_undoBufferList.add(new Stack<File>());
m_flowTabs.addTab(tabTitle, splitHolder);
int tabIndex = getNumTabs() - 1;
m_flowTabs.setTabComponentAt(tabIndex, new CloseableTabTitle(m_flowTabs));
setActiveTab(getNumTabs() - 1);
m_saveB.setEnabled(true);
}
}
private class CloseableTabTitle extends JPanel {
/**
*
*/
private static final long serialVersionUID = -6844232025394346426L;
private final JTabbedPane m_enclosingPane;
private JLabel m_tabLabel;
private TabButton m_tabButton;
public CloseableTabTitle(final JTabbedPane pane) {
super(new FlowLayout(FlowLayout.LEFT, 0, 0));
m_enclosingPane = pane;
setOpaque(false);
setBorder(BorderFactory.createEmptyBorder(2, 0, 0, 0));
// read the title from the JTabbedPane
m_tabLabel = new JLabel() {
/**
*
*/
private static final long serialVersionUID = 8515052190461050324L;
@Override
public String getText() {
int index = m_enclosingPane
.indexOfTabComponent(CloseableTabTitle.this);
if (index >= 0) {
return m_enclosingPane.getTitleAt(index);
}
return null;
}
};
add(m_tabLabel);
m_tabLabel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5));
m_tabButton = new TabButton();
add(m_tabButton);
}
public void setBold(boolean bold) {
m_tabLabel.setEnabled(bold);
}
public void setButtonEnabled(boolean enabled) {
m_tabButton.setEnabled(enabled);
}
private class TabButton extends JButton implements ActionListener {
/**
*
*/
private static final long serialVersionUID = -4915800749132175968L;
public TabButton() {
int size = 17;
setPreferredSize(new Dimension(size, size));
setToolTipText("close this tab");
// Make the button looks the same for all Laf's
setUI(new BasicButtonUI());
// Make it transparent
setContentAreaFilled(false);
// No need to be focusable
setFocusable(false);
setBorder(BorderFactory.createEtchedBorder());
setBorderPainted(false);
// Making nice rollover effect
// we use the same listener for all buttons
addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
Component component = e.getComponent();
if (component instanceof AbstractButton) {
AbstractButton button = (AbstractButton) component;
button.setBorderPainted(true);
int i = m_enclosingPane
.indexOfTabComponent(CloseableTabTitle.this);
if (i == m_mainKFPerspective.getCurrentTabIndex()) {
button.setToolTipText("close this tab (Ctrl+W)");
} else {
button.setToolTipText("close this tab");
}
}
}
@Override
public void mouseExited(MouseEvent e) {
Component component = e.getComponent();
if (component instanceof AbstractButton) {
AbstractButton button = (AbstractButton) component;
button.setBorderPainted(false);
}
}
});
setRolloverEnabled(true);
// Close the proper tab by clicking the button
addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e) {
int i = m_enclosingPane.indexOfTabComponent(CloseableTabTitle.this);
if (i >= 0 && getAllowMultipleTabs()) {
// m_enclosingPane.remove(i);
m_mainKFPerspective.removeTab(i);
}
}
// we don't want to update UI for this button
@Override
public void updateUI() {
}
// paint the cross
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g.create();
// shift the image for pressed buttons
if (getModel().isPressed()) {
g2.translate(1, 1);
}
g2.setStroke(new BasicStroke(2));
g2.setColor(Color.BLACK);
if (!isEnabled()) {
g2.setColor(Color.GRAY);
}
if (getModel().isRollover()) {
g2.setColor(Color.MAGENTA);
}
int delta = 6;
g2.drawLine(delta, delta, getWidth() - delta - 1, getHeight() - delta
- 1);
g2.drawLine(getWidth() - delta - 1, delta, delta, getHeight() - delta
- 1);
g2.dispose();
}
}
}
// Used for measuring and splitting icon labels
// over multiple lines
FontMetrics m_fontM;
// constants for operations in progress
protected static final int NONE = 0;
protected static final int MOVING = 1;
protected static final int CONNECTING = 2;
protected static final int ADDING = 3;
protected static final int SELECTING = 4;
protected static final int PASTING = 5;
// which operation is in progress
private int m_mode = NONE;
/** the extension for the user components, when serialized to XML */
protected final static String USERCOMPONENTS_XML_EXTENSION = ".xml";
/**
* Holds the selected toolbar bean
*/
private Object m_toolBarBean;
/** Snap-to-grid spacing */
private final int m_gridSpacing = 40;
/** Number of untitled tabs so far */
protected int m_untitledCount = 1;
/**
* The layout area
*/
private BeanLayout m_beanLayout = null;// new BeanLayout();
private int m_layoutZoom = 100;
/** Whether to allow more than one tab or not */
private boolean m_allowMultipleTabs = true;
private final Vector<Object> m_userComponents = new Vector<Object>();
private boolean m_firstUserComponentOpp = true;
protected JButton m_pointerB;
protected JButton m_saveB;
protected JButton m_saveBB;
protected JButton m_loadB;
protected JButton m_stopB;
protected JButton m_playB;
protected JButton m_playBB;
protected JButton m_helpB;
protected JButton m_newB;
protected JButton m_togglePerspectivesB;
protected JButton m_templatesB;
protected JButton m_groupB;
protected JButton m_cutB;
protected JButton m_copyB;
protected JButton m_pasteB;
protected JButton m_deleteB;
protected JButton m_noteB;
protected JButton m_selectAllB;
protected JButton m_undoB;
protected JButton m_zoomInB;
protected JButton m_zoomOutB;
protected JToggleButton m_snapToGridB;
/**
* Reference to bean being manipulated
*/
private BeanInstance m_editElement;
/**
* Event set descriptor for the bean being manipulated
*/
private EventSetDescriptor m_sourceEventSetDescriptor;
/**
* Used to record screen coordinates during move, select and connect
* operations
*/
private int m_oldX, m_oldY;
private int m_startX, m_startY;
/** The file chooser for selecting layout files */
protected JFileChooser m_FileChooser = new JFileChooser(new File(
System.getProperty("user.dir")));
protected class KFLogPanel extends LogPanel {
/**
*
*/
private static final long serialVersionUID = -2224509243343105276L;
public synchronized void
setMessageOnAll(boolean mainKFLine, String message) {
for (String key : m_tableIndexes.keySet()) {
if (!mainKFLine && key.equals("[KnowledgeFlow]")) {
continue;
}
String tm = key + "|" + message;
statusMessage(tm);
}
}
}
protected KFLogPanel m_logPanel = null; // new LogPanel();//new LogPanel(null,
// true);
/** Toolbar to hold the perspective buttons */
protected JToolBar m_perspectiveToolBar = new JToolBar(JToolBar.HORIZONTAL);
/** Panel to hold the perspectives toolbar and config button */
protected JPanel m_configAndPerspectives;
/**
* Whether the perspectives toolbar is visible at present (will never be
* visible if there are no plugin perspectives installed)
*/
protected boolean m_configAndPerspectivesVisible = true;
/**
* Button group to manage all perspective toggle buttons
*/
private final ButtonGroup m_perspectiveGroup = new ButtonGroup();
/** Component that holds the currently visible perspective */
protected JPanel m_perspectiveHolder;
/**
* Holds the list of currently loaded perspectives. Element at 0 is always the
* main KF data mining flow perspective
*/
protected List<KFPerspective> m_perspectives = new ArrayList<KFPerspective>();
/** Thread for loading data for perspectives */
protected Thread m_perspectiveDataLoadThread = null;
protected AttributeSelectionPanel m_perspectiveConfigurer;
/** Shortcut to the main perspective */
protected MainKFPerspective m_mainKFPerspective;
protected BeanContextSupport m_bcSupport = new BeanContextSupport();
/** the extension for the serialized setups (Java serialization) */
public final static String FILE_EXTENSION = ".kf";
/** the extension for the serialized setups (Java serialization) */
public final static String FILE_EXTENSION_XML = ".kfml";
/**
* A filter to ensure only KnowledgeFlow files in binary format get shown in
* the chooser
*/
protected FileFilter m_KfFilter = new ExtensionFileFilter(FILE_EXTENSION,
"Binary KnowledgeFlow configuration files (*" + FILE_EXTENSION + ")");
/**
* A filter to ensure only KnowledgeFlow files in KOML format get shown in the
* chooser
*/
protected FileFilter m_KOMLFilter = new ExtensionFileFilter(
KOML.FILE_EXTENSION + "kf", "XML KnowledgeFlow configuration files (*"
+ KOML.FILE_EXTENSION + "kf)");
/**
* A filter to ensure only KnowledgeFlow files in XStream format get shown in
* the chooser
*/
protected FileFilter m_XStreamFilter = new ExtensionFileFilter(
XStream.FILE_EXTENSION + "kf", "XML KnowledgeFlow configuration files (*"
+ XStream.FILE_EXTENSION + "kf)");
/**
* A filter to ensure only KnowledgeFlow layout files in XML format get shown
* in the chooser
*/
protected FileFilter m_XMLFilter = new ExtensionFileFilter(
FILE_EXTENSION_XML, "XML KnowledgeFlow layout files (*"
+ FILE_EXTENSION_XML + ")");
/** the scrollbar increment of the layout scrollpane */
protected int m_ScrollBarIncrementLayout = 20;
/** the scrollbar increment of the components scrollpane */
protected int m_ScrollBarIncrementComponents = 50;
/** the flow layout width */
protected int m_FlowWidth = 2560;
/** the flow layout height */
protected int m_FlowHeight = 1440;
/** the preferred file extension */
protected String m_PreferredExtension = FILE_EXTENSION;
/** whether to store the user components in XML or in binary format */
protected boolean m_UserComponentsInXML = false;
/** Environment variables for the current flow */
protected Environment m_flowEnvironment = new Environment();
/** Palette of components stored in a JTree */
protected JTree m_componentTree;
/** The node of the JTree that holds "user" (metabean) components */
protected DefaultMutableTreeNode m_userCompNode;
/** The clip board */
protected StringBuffer m_pasteBuffer;
/**
* Set the environment variables to use. NOTE: loading a new layout resets
* back to the default set of variables
*
* @param env
*/
public void setEnvironment(Environment env) {
m_flowEnvironment = env;
setEnvironment();
}
private void setEnvironment() {
// pass m_flowEnvironment to all components
// that implement EnvironmentHandler
Vector<Object> beans = BeanInstance.getBeanInstances(m_mainKFPerspective
.getCurrentTabIndex());
for (int i = 0; i < beans.size(); i++) {
Object temp = ((BeanInstance) beans.elementAt(i)).getBean();
if (temp instanceof EnvironmentHandler) {
((EnvironmentHandler) temp).setEnvironment(m_flowEnvironment);
}
}
}
/**
* Creates a new <code>KnowledgeFlowApp</code> instance.
*/
// modifications by Zerbetto
// public KnowledgeFlowApp() {
public KnowledgeFlowApp(boolean showFileMenu) {
if (BeansProperties.BEAN_PROPERTIES == null) {
loadProperties();
init();
}
m_showFileMenu = showFileMenu;
// end modifications by Zerbetto
// Grab a fontmetrics object
JWindow temp = new JWindow();
temp.setVisible(true);
temp.getGraphics().setFont(new Font(null, Font.PLAIN, 9));
m_fontM = temp.getGraphics().getFontMetrics();
temp.setVisible(false);
// some GUI defaults
try {
m_ScrollBarIncrementLayout = Integer
.parseInt(BeansProperties.BEAN_PROPERTIES.getProperty(
"ScrollBarIncrementLayout", "" + m_ScrollBarIncrementLayout));
m_ScrollBarIncrementComponents = Integer
.parseInt(BeansProperties.BEAN_PROPERTIES.getProperty(
"ScrollBarIncrementComponents", "" + m_ScrollBarIncrementComponents));
m_FlowWidth = Integer.parseInt(BeansProperties.BEAN_PROPERTIES
.getProperty("FlowWidth", "" + m_FlowWidth));
m_FlowHeight = Integer.parseInt(BeansProperties.BEAN_PROPERTIES
.getProperty("FlowHeight", "" + m_FlowHeight));
m_PreferredExtension = BeansProperties.BEAN_PROPERTIES.getProperty(
"PreferredExtension", m_PreferredExtension);
m_UserComponentsInXML = Boolean.valueOf(
BeansProperties.BEAN_PROPERTIES.getProperty("UserComponentsInXML", ""
+ m_UserComponentsInXML)).booleanValue();
} catch (Exception ex) {
ex.printStackTrace();
}
// FileChooser
m_FileChooser.addChoosableFileFilter(m_KfFilter);
if (KOML.isPresent()) {
m_FileChooser.addChoosableFileFilter(m_KOMLFilter);
}
if (XStream.isPresent()) {
m_FileChooser.addChoosableFileFilter(m_XStreamFilter);
}
m_FileChooser.addChoosableFileFilter(m_XMLFilter);
if (m_PreferredExtension.equals(FILE_EXTENSION_XML)) {
m_FileChooser.setFileFilter(m_XMLFilter);
} else if (KOML.isPresent()
&& m_PreferredExtension.equals(KOML.FILE_EXTENSION + "kf")) {
m_FileChooser.setFileFilter(m_KOMLFilter);
} else if (XStream.isPresent()
&& m_PreferredExtension.equals(XStream.FILE_EXTENSION + "kf")) {
m_FileChooser.setFileFilter(m_XStreamFilter);
} else {
m_FileChooser.setFileFilter(m_KfFilter);
}
m_FileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
m_bcSupport.setDesignTime(true);
m_perspectiveHolder = new JPanel();
m_perspectiveHolder.setLayout(new BorderLayout());
// TODO North will hold main perspective toggle buttons
// WEST will hold JTree - perhaps not
// CENTER will hold perspective
/*
* JPanel p2 = new JPanel(); p2.setLayout(new BorderLayout());
*/
m_mainKFPerspective = new MainKFPerspective();
// m_perspectiveHolder.add(m_mainKFPerspective, BorderLayout.CENTER);
m_perspectives.add(m_mainKFPerspective);
// mainPanel.add(m_perspectiveHolder, BorderLayout.CENTER);
setLayout(new BorderLayout());
add(m_perspectiveHolder, BorderLayout.CENTER);
// setUpToolBars(p2);
// setUpToolsAndJTree(m_mainKFPerspective);
m_perspectiveHolder.add(m_mainKFPerspective, BorderLayout.CENTER);
if (m_pluginPerspectiveLookup.size() > 0) {
// add the main perspective first
String titleM = m_mainKFPerspective.getPerspectiveTitle();
Icon icon = m_mainKFPerspective.getPerspectiveIcon();
JToggleButton tBut = new JToggleButton(titleM, icon, true);
tBut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
KFPerspective current = (KFPerspective) m_perspectiveHolder
.getComponent(0);
current.setActive(false);
m_perspectiveHolder.remove(0);
m_perspectiveHolder.add((JComponent) m_perspectives.get(0),
BorderLayout.CENTER);
m_perspectives.get(0).setActive(true);
// KnowledgeFlowApp.this.invalidate();
KnowledgeFlowApp.this.revalidate();
KnowledgeFlowApp.this.repaint();
notifyIsDirty();
}
});
m_perspectiveToolBar.add(tBut);
m_perspectiveGroup.add(tBut);
// set up the perspective toolbar toggle buttons
// first load the perspectives list in sorted order (kf perspective
// is always at index 0)
setupUserPerspectives();
}
if (m_pluginPerspectiveLookup.size() > 0) {
m_configAndPerspectives = new JPanel();
m_configAndPerspectives.setLayout(new BorderLayout());
m_configAndPerspectives.add(m_perspectiveToolBar, BorderLayout.CENTER);
try {
Properties visible = Utils
.readProperties(BeansProperties.VISIBLE_PERSPECTIVES_PROPERTIES_FILE);
Enumeration<?> keys = visible.propertyNames();
if (keys.hasMoreElements()) {
String toolBarIsVisible =
visible
.getProperty("weka.gui.beans.KnowledgeFlow.PerspectiveToolBarVisisble");
if (toolBarIsVisible != null && toolBarIsVisible.length() > 0) {
m_configAndPerspectivesVisible = toolBarIsVisible
.equalsIgnoreCase("yes");
}
}
} catch (Exception ex) {
System.err
.println("Problem reading visible perspectives property file");
ex.printStackTrace();
}
// add the perspectives toolbar
// does the user want it visible?
if (m_configAndPerspectivesVisible) {
add(m_configAndPerspectives, BorderLayout.NORTH);
}
JButton configB = new JButton(new ImageIcon(
loadImage(BeanVisual.ICON_PATH + "cog.png")));
configB.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 1));
configB.setToolTipText("Enable/disable perspectives");
m_configAndPerspectives.add(configB, BorderLayout.WEST);
configB.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (!Utils
.getDontShowDialog("weka.gui.beans.KnowledgeFlow.PerspectiveInfo")) {
JCheckBox dontShow =
new JCheckBox("Do not show this message again");
Object[] stuff = new Object[2];
stuff[0] =
"Perspectives are environments that take over the\n"
+ "Knowledge Flow UI and provide major additional functionality.\n"
+ "Many perspectives will operate on a set of instances. Instances\n"
+ "Can be sent to a perspective by placing a DataSource on the\n"
+ "layout canvas, configuring it and then selecting \"Send to perspective\"\n"
+ "from the contextual popup menu that appears when you right-click on\n"
+ "it. Several perspectives are built in to the Knowledge Flow, others\n"
+ "can be installed via the package manager.\n";
stuff[1] = dontShow;
JOptionPane.showMessageDialog(KnowledgeFlowApp.this, stuff,
"Perspective information", JOptionPane.OK_OPTION);
if (dontShow.isSelected()) {
try {
Utils
.setDontShowDialog("weka.gui.beans.KnowledgeFlow.PerspectiveInfo");
} catch (Exception ex) {
// quietly ignore
}
}
}
popupPerspectiveConfigurer();
}
});
}
// set main perspective on all cached perspectives
for (String pName : m_perspectiveCache.keySet()) {
m_perspectiveCache.get(pName).setMainKFPerspective(m_mainKFPerspective);
}
loadUserComponents();
clearLayout(); // add an initial "Untitled" tab
}
/**
* Gets the main knowledge flow perspective
*
* @return the main knowledge flow perspective
*/
public MainKFPerspective getMainPerspective() {
return m_mainKFPerspective;
}
private void popupPerspectiveConfigurer() {
if (m_perspectiveConfigurer == null) {
m_perspectiveConfigurer = new AttributeSelectionPanel(true, true, true,
true);
}
if (m_firstUserComponentOpp) {
installWindowListenerForSavingUserStuff();
m_firstUserComponentOpp = false;
}
ArrayList<Attribute> atts = new ArrayList<Attribute>();
final ArrayList<String> pClasses = new ArrayList<String>();
SortedSet<String> sortedPerspectives = new TreeSet<String>();
for (String clName : m_pluginPerspectiveLookup.keySet()) {
sortedPerspectives.add(clName);
}
for (String clName : sortedPerspectives) {
pClasses.add(clName);
String pName = m_pluginPerspectiveLookup.get(clName);
atts.add(new Attribute(pName));
}
Instances perspectiveInstances = new Instances("Perspectives", atts, 1);
boolean[] selectedPerspectives = new boolean[perspectiveInstances
.numAttributes()];
for (String selected : BeansProperties.VISIBLE_PERSPECTIVES) {
String pName = m_pluginPerspectiveLookup.get(selected);
// check here - just in case the user has uninstalled/deleted a plugin
// perspective since the last time that the user-selected visible
// perspectives
// list was written out to the props file
if (pName != null) {
int index = perspectiveInstances.attribute(pName).index();
selectedPerspectives[index] = true;
}
}
m_perspectiveConfigurer.setInstances(perspectiveInstances);
try {
m_perspectiveConfigurer.setSelectedAttributes(selectedPerspectives);
} catch (Exception ex) {
ex.printStackTrace();
return;
}
final JDialog d = new JDialog(
(JFrame) KnowledgeFlowApp.this.getTopLevelAncestor(),
"Manage Perspectives", ModalityType.DOCUMENT_MODAL);
d.setLayout(new BorderLayout());
JPanel holder = new JPanel();
holder.setLayout(new BorderLayout());
holder.add(m_perspectiveConfigurer, BorderLayout.CENTER);
JButton okBut = new JButton("OK");
JButton cancelBut = new JButton("Cancel");
JPanel butHolder = new JPanel();
butHolder.setLayout(new GridLayout(1, 2));
butHolder.add(okBut);
butHolder.add(cancelBut);
holder.add(butHolder, BorderLayout.SOUTH);
okBut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
BeansProperties.VISIBLE_PERSPECTIVES = new TreeSet<String>();
int[] selected = m_perspectiveConfigurer.getSelectedAttributes();
for (int element : selected) {
String selectedClassName = pClasses.get(element);
// first check to see if it's in the cache already
if (m_perspectiveCache.get(selectedClassName) == null) {
// need to instantiate and add to the cache
try {
Object p = WekaPackageClassLoaderManager.objectForName(selectedClassName);
// Object p = Class.forName(selectedClassName).newInstance();
if (p instanceof KFPerspective && p instanceof JPanel) {
String title = ((KFPerspective) p).getPerspectiveTitle();
weka.core.logging.Logger.log(
weka.core.logging.Logger.Level.INFO,
"[KnowledgeFlow] loaded perspective: "
+ title);
((KFPerspective) p).setLoaded(true);
((KFPerspective) p).setMainKFPerspective(m_mainKFPerspective);
m_perspectiveCache.put(selectedClassName, (KFPerspective) p);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
BeansProperties.VISIBLE_PERSPECTIVES.add(selectedClassName);
}
setupUserPerspectives();
d.dispose();
}
});
cancelBut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
d.dispose();
}
});
d.getContentPane().add(holder, BorderLayout.CENTER);
/*
* d.addWindowListener(new java.awt.event.WindowAdapter() { public void
* windowClosing(java.awt.event.WindowEvent e) {
*
*
* d.dispose(); } });
*/
d.pack();
d.setLocationRelativeTo(SwingUtilities.getWindowAncestor(this));
d.setVisible(true);
}
private void setupUserPerspectives() {
// first clear the toolbar
for (int i = m_perspectiveToolBar.getComponentCount() - 1; i > 0; i--) {
m_perspectiveToolBar.remove(i);
m_perspectives.remove(i);
}
int index = 1;
for (String c : BeansProperties.VISIBLE_PERSPECTIVES) {
KFPerspective toAdd = m_perspectiveCache.get(c);
if (toAdd instanceof JComponent) {
toAdd.setLoaded(true);
m_perspectives.add(toAdd);
String titleM = toAdd.getPerspectiveTitle();
Icon icon = toAdd.getPerspectiveIcon();
JToggleButton tBut = null;
if (icon != null) {
tBut = new JToggleButton(titleM, icon, false);
} else {
tBut = new JToggleButton(titleM, false);
}
tBut.setToolTipText(toAdd.getPerspectiveTipText());
final int theIndex = index;
tBut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setActivePerspective(theIndex);
}
});
m_perspectiveToolBar.add(tBut);
m_perspectiveGroup.add(tBut);
index++;
}
}
KFPerspective current = (KFPerspective) m_perspectiveHolder.getComponent(0);
if (current != m_mainKFPerspective) {
current.setActive(false);
m_perspectiveHolder.remove(0);
m_perspectiveHolder.add(m_mainKFPerspective);
((JToggleButton) m_perspectiveToolBar.getComponent(0)).setSelected(true);
}
revalidate();
repaint();
notifyIsDirty();
}
protected void setActivePerspective(int theIndex) {
if (theIndex < 0 || theIndex > m_perspectives.size() - 1) {
return;
}
KFPerspective current = (KFPerspective) m_perspectiveHolder.getComponent(0);
current.setActive(false);
m_perspectiveHolder.remove(0);
m_perspectiveHolder.add((JComponent) m_perspectives.get(theIndex),
BorderLayout.CENTER);
m_perspectives.get(theIndex).setActive(true);
((JToggleButton) m_perspectiveToolBar.getComponent(theIndex))
.setSelected(true);
// KnowledgeFlowApp.this.invalidate();
KnowledgeFlowApp.this.revalidate();
KnowledgeFlowApp.this.repaint();
notifyIsDirty();
}
private void snapSelectedToGrid() {
Vector<Object> v = m_mainKFPerspective.getSelectedBeans();
if (v.size() > 0) {
for (int i = 0; i < v.size(); i++) {
BeanInstance b = (BeanInstance) v.get(i);
// if (!(b.getBean() instanceof Note)) {
int x = b.getX();
int y = b.getY();
b.setXY(snapToGrid(x), snapToGrid(y));
// }
}
revalidate();
m_beanLayout.repaint();
notifyIsDirty();
m_mainKFPerspective.setEditedStatus(true);
}
}
private int snapToGrid(int val) {
int r = val % m_gridSpacing;
val /= m_gridSpacing;
if (r > (m_gridSpacing / 2)) {
val++;
}
val *= m_gridSpacing;
return val;
}
private void configureBeanLayout(final BeanLayout layout) {
layout.setLayout(null);
// handle mouse events
layout.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent me) {
layout.requestFocusInWindow();
double z = m_layoutZoom / 100.0;
double px = me.getX();
double py = me.getY();
py /= z;
px /= z;
if (m_toolBarBean == null) {
if (((me.getModifiers() & InputEvent.BUTTON1_MASK) == InputEvent.BUTTON1_MASK)
&& m_mode == NONE) {
/*
* BeanInstance bi = BeanInstance.findInstance(me.getPoint(),
* m_mainKFPerspective.getCurrentTabIndex());
*/
BeanInstance bi = BeanInstance.findInstance(new Point((int) px,
(int) py), m_mainKFPerspective.getCurrentTabIndex());
JComponent bc = null;
if (bi != null) {
bc = (JComponent) (bi.getBean());
}
if (bc != null /* && (bc instanceof Visible) */) {
m_editElement = bi;
/*
* m_oldX = me.getX(); m_oldY = me.getY();
*/
m_oldX = (int) px;
m_oldY = (int) py;
m_mode = MOVING;
}
if (m_mode != MOVING) {
m_mode = SELECTING;
/*
* m_oldX = me.getX(); m_oldY = me.getY();
*/
m_oldX = (int) px;
m_oldY = (int) py;
m_startX = m_oldX;
m_startY = m_oldY;
Graphics2D gx = (Graphics2D) layout.getGraphics();
gx.setXORMode(java.awt.Color.white);
// gx.drawRect(m_oldX, m_oldY, m_oldX, m_oldY);
// gx.drawLine(m_startX, m_startY, m_startX, m_startY);
gx.dispose();
m_mode = SELECTING;
}
}
}
}
@Override
public void mouseReleased(MouseEvent me) {
layout.requestFocusInWindow();
if (m_editElement != null && m_mode == MOVING) {
if (m_snapToGridB.isSelected()) {
int x = snapToGrid(m_editElement.getX());
int y = snapToGrid(m_editElement.getY());
m_editElement.setXY(x, y);
snapSelectedToGrid();
}
m_editElement = null;
revalidate();
layout.repaint();
m_mode = NONE;
}
if (m_mode == SELECTING) {
revalidate();
layout.repaint();
m_mode = NONE;
double z = m_layoutZoom / 100.0;
double px = me.getX();
double py = me.getY();
py /= z;
px /= z;
// highlightSubFlow(m_startX, m_startY, me.getX(), me.getY());
highlightSubFlow(m_startX, m_startY, (int) px, (int) py);
}
}
@Override
public void mouseClicked(MouseEvent me) {
layout.requestFocusInWindow();
Point p = me.getPoint();
Point np = new Point();
double z = m_layoutZoom / 100.0;
np.setLocation(p.getX() / z, p.getY() / z);
BeanInstance bi = BeanInstance.findInstance(np,
m_mainKFPerspective.getCurrentTabIndex());
if (m_mode == ADDING || m_mode == NONE) {
// try and popup a context sensitive menu if we have
// been clicked over a bean.
if (bi != null) {
JComponent bc = (JComponent) bi.getBean();
// if we've been double clicked, then popup customizer
// as long as we're not a meta bean
if (me.getClickCount() == 2 && !(bc instanceof MetaBean)) {
try {
Class<?> custClass = Introspector.getBeanInfo(bc.getClass())
.getBeanDescriptor().getCustomizerClass();
if (custClass != null) {
if (bc instanceof BeanCommon) {
if (!((BeanCommon) bc).isBusy()
&& !m_mainKFPerspective.getExecuting()) {
popupCustomizer(custClass, bc);
}
} else {
popupCustomizer(custClass, bc);
}
}
} catch (IntrospectionException ex) {
ex.printStackTrace();
}
} else if (((me.getModifiers() & InputEvent.BUTTON1_MASK) != InputEvent.BUTTON1_MASK)
|| me.isAltDown()) {
// doPopup(me.getPoint(), bi, me.getX(), me.getY());
doPopup(me.getPoint(), bi, (int) (p.getX() / z),
(int) (p.getY() / z));
return;
} else {
// just select this bean
Vector<Object> v = m_mainKFPerspective.getSelectedBeans();
if (me.isShiftDown()) {
} else {
v = new Vector<Object>();
}
v.add(bi);
m_mainKFPerspective.setSelectedBeans(v);
return;
}
} else {
if (((me.getModifiers() & InputEvent.BUTTON1_MASK) != InputEvent.BUTTON1_MASK)
|| me.isAltDown()) {
double px = me.getX();
double py = me.getY();
py /= z;
px /= z;
// find connections if any close to this point
if (!m_mainKFPerspective.getExecuting()) {
// rightClickCanvasPopup(me.getX(), me.getY());
rightClickCanvasPopup((int) px, (int) py);
revalidate();
repaint();
notifyIsDirty();
}
return;
/*
* int delta = 10; deleteConnectionPopup(BeanConnection.
* getClosestConnections(new Point(me.getX(), me.getY()), delta,
* m_mainKFPerspective.getCurrentTabIndex()), me.getX(),
* me.getY());
*/
} else if (m_toolBarBean != null) {
// otherwise, if a toolbar button is active then
// add the component
// snap to grid
double x = me.getX();
double y = me.getY();
x /= z;
y /= z;
if (m_snapToGridB.isSelected()) {
// x = snapToGrid(me.getX());
x = snapToGrid((int) x);
// y = snapToGrid(me.getY());
y = snapToGrid((int) y);
}
addUndoPoint();
if (m_toolBarBean instanceof StringBuffer) {
// serialized user meta bean
pasteFromClipboard((int) x, (int) y,
(StringBuffer) m_toolBarBean, false);
m_mode = NONE;
KnowledgeFlowApp.this.setCursor(Cursor
.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
m_toolBarBean = null;
} else {
// saveLayout(m_mainKFPerspective.getCurrentTabIndex(), false);
addComponent((int) x, (int) y);
}
m_componentTree.clearSelection();
m_mainKFPerspective.setEditedStatus(true);
}
}
revalidate();
repaint();
notifyIsDirty();
}
double px = me.getX();
double py = me.getY();
px /= z;
py /= z;
if (m_mode == PASTING && m_pasteBuffer.length() > 0) {
// pasteFromClipboard(me.getX(), me.getY(), m_pasteBuffer, true);
pasteFromClipboard((int) px, (int) py, m_pasteBuffer, true);
m_mode = NONE;
KnowledgeFlowApp.this.setCursor(Cursor
.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
return;
}
if (m_mode == CONNECTING) {
// turn off connecting points and remove connecting line
layout.repaint();
Vector<Object> beanInstances = BeanInstance
.getBeanInstances(m_mainKFPerspective.getCurrentTabIndex());
for (int i = 0; i < beanInstances.size(); i++) {
JComponent bean = (JComponent) ((BeanInstance) beanInstances
.elementAt(i)).getBean();
if (bean instanceof Visible) {
((Visible) bean).getVisual().setDisplayConnectors(false);
}
}
if (bi != null) {
boolean doConnection = false;
if (!(bi.getBean() instanceof BeanCommon)) {
doConnection = true;
} else {
// Give the target bean a chance to veto the proposed
// connection
if (((BeanCommon) bi.getBean()).
// connectionAllowed(m_sourceEventSetDescriptor.getName())) {
connectionAllowed(m_sourceEventSetDescriptor)) {
doConnection = true;
}
}
if (doConnection) {
addUndoPoint();
// attempt to connect source and target beans
if (bi.getBean() instanceof MetaBean) {
BeanConnection.doMetaConnection(m_editElement, bi,
m_sourceEventSetDescriptor, layout,
m_mainKFPerspective.getCurrentTabIndex());
} else {
new BeanConnection(m_editElement, bi,
m_sourceEventSetDescriptor, m_mainKFPerspective
.getCurrentTabIndex());
}
m_mainKFPerspective.setEditedStatus(true);
}
layout.repaint();
}
m_mode = NONE;
m_editElement = null;
m_sourceEventSetDescriptor = null;
}
if (m_mainKFPerspective.getSelectedBeans().size() > 0) {
m_mainKFPerspective.setSelectedBeans(new Vector<Object>());
}
}
});
layout.addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseDragged(MouseEvent me) {
double z = m_layoutZoom / 100.0;
double px = me.getX();
double py = me.getY();
px /= z;
py /= z;
if (m_editElement != null && m_mode == MOVING) {
/*
* int deltaX = me.getX() - m_oldX; int deltaY = me.getY() - m_oldY;
*/
int deltaX = (int) px - m_oldX;
int deltaY = (int) py - m_oldY;
m_editElement.setXY(m_editElement.getX() + deltaX,
m_editElement.getY() + deltaY);
if (m_mainKFPerspective.getSelectedBeans().size() > 0) {
Vector<Object> v = m_mainKFPerspective.getSelectedBeans();
for (int i = 0; i < v.size(); i++) {
BeanInstance b = (BeanInstance) v.get(i);
if (b != m_editElement) {
b.setXY(b.getX() + deltaX, b.getY() + deltaY);
}
}
}
layout.repaint();
// note the new points
/*
* m_oldX = me.getX(); m_oldY = me.getY();
*/
m_oldX = (int) px;
m_oldY = (int) py;
m_mainKFPerspective.setEditedStatus(true);
}
if (m_mode == SELECTING) {
layout.repaint();
/*
* m_oldX = me.getX(); m_oldY = me.getY();
*/
m_oldX = (int) px;
m_oldY = (int) py;
}
}
@Override
public void mouseMoved(MouseEvent e) {
double z = m_layoutZoom / 100.0;
double px = e.getX();
double py = e.getY();
px /= z;
py /= z;
if (m_mode == CONNECTING) {
layout.repaint();
// note the new coordinates
/*
* m_oldX = e.getX(); m_oldY = e.getY();
*/
m_oldX = (int) px;
m_oldY = (int) py;
}
}
});
}
private void setUpLogPanel(final LogPanel logPanel) {
String date = (new SimpleDateFormat("EEEE, d MMMM yyyy"))
.format(new Date());
logPanel.logMessage("Weka Knowledge Flow was written by Mark Hall");
logPanel.logMessage("Weka Knowledge Flow");
logPanel.logMessage("(c) 2002-" + Copyright.getToYear() + " "
+ Copyright.getOwner() + ", " + Copyright.getAddress());
logPanel.logMessage("web: " + Copyright.getURL());
logPanel.logMessage(date);
logPanel
.statusMessage("@!@[KnowledgeFlow]|Welcome to the Weka Knowledge Flow");
logPanel.getStatusTable().addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (logPanel.getStatusTable().rowAtPoint(e.getPoint()) == 0) {
if (((e.getModifiers() & InputEvent.BUTTON1_MASK) != InputEvent.BUTTON1_MASK)
|| e.isAltDown()) {
System.gc();
Runtime currR = Runtime.getRuntime();
long freeM = currR.freeMemory();
long totalM = currR.totalMemory();
long maxM = currR.maxMemory();
logPanel
.logMessage("[KnowledgeFlow] Memory (free/total/max.) in bytes: "
+ String.format("%,d", freeM) + " / "
+ String.format("%,d", totalM) + " / "
+ String.format("%,d", maxM));
logPanel
.statusMessage("@!@[KnowledgeFlow]|Memory (free/total/max.) in bytes: "
+ String.format("%,d", freeM)
+ " / "
+ String.format("%,d", totalM)
+ " / "
+ String.format("%,d", maxM));
}
}
}
});
}
private Image loadImage(String path) {
Image pic = null;
// Modified by Zerbetto
// java.net.URL imageURL = ClassLoader.getSystemResource(path);
java.net.URL imageURL = this.getClass().getClassLoader().getResource(path);
// end modifications
if (imageURL == null) {
weka.core.logging.Logger.log(weka.core.logging.Logger.Level.WARNING,
"Unable to load " + path);
} else {
pic = Toolkit.getDefaultToolkit().getImage(imageURL);
}
return pic;
}
protected class RunThread extends Thread {
int m_flowIndex;
boolean m_sequential;
boolean m_wasUserStopped = false;
public RunThread(boolean sequential) {
m_sequential = sequential;
}
@Override
public void run() {
m_flowIndex = m_mainKFPerspective.getCurrentTabIndex();
String flowName = m_mainKFPerspective.getTabTitle(m_flowIndex);
m_mainKFPerspective.setExecuting(true);
m_mainKFPerspective.getLogPanel(m_flowIndex).clearStatus();
m_mainKFPerspective.getLogPanel(m_flowIndex).statusMessage(
"@!@[KnowledgeFlow]|Executing...");
FlowRunner runner = new FlowRunner(false, false);
runner.setStartSequentially(m_sequential);
runner.setEnvironment(m_flowEnvironment);
runner.setLog(m_logPanel);
Vector<Object> comps = BeanInstance.getBeanInstances(m_flowIndex);
runner.setFlows(comps);
try {
runner.run();
runner.waitUntilFinished();
} catch (InterruptedException ie) {
} catch (Exception ex) {
m_logPanel.logMessage("An error occurred while running the flow: "
+ ex.getMessage());
} finally {
if (m_flowIndex >= m_mainKFPerspective.getNumTabs() - 1
|| !m_mainKFPerspective.getTabTitle(m_flowIndex).equals(flowName)) {
// try and find which index our flow is at (user must have closed some
// other tabs at lower indexes than us)!
for (int i = 0; i < m_mainKFPerspective.getNumTabs(); i++) {
String tabT = m_mainKFPerspective.getTabTitle(i);
if (tabT != null && tabT.equals(flowName)) {
m_flowIndex = i;
break;
}
}
}
m_mainKFPerspective.setExecuting(m_flowIndex, false);
m_mainKFPerspective.setExecutionThread(m_flowIndex, null);
if (m_wasUserStopped) {
// TODO global Stop message to the status area
KFLogPanel lp = m_mainKFPerspective.getLogPanel(m_flowIndex);
lp.setMessageOnAll(false, "Stopped.");
} else {
m_mainKFPerspective.getLogPanel(m_flowIndex).statusMessage(
"@!@[KnowledgeFlow]|OK.");
}
}
}
public void stopAllFlows() {
Vector<Object> components = BeanInstance.getBeanInstances(m_flowIndex);
if (components != null) {
for (int i = 0; i < components.size(); i++) {
Object temp = ((BeanInstance) components.elementAt(i)).getBean();
if (temp instanceof BeanCommon) {
((BeanCommon) temp).stop();
}
}
m_wasUserStopped = true;
}
}
}
/**
* Run all start-points in a layout in parallel or sequentially. Order of
* execution is arbitrary if the user has not prefixed the names of the start
* points with "<num> :" in order to specify the order. In both parallel and
* sequential mode, a start point can be ommitted from exectution by prefixing
* its name with "! :".
*
* @param sequential true if the flow layout is to have its start points run
* sequentially rather than in parallel
*
*/
private void runFlow(final boolean sequential) {
if (m_mainKFPerspective.getNumTabs() > 0) {
RunThread runThread = new RunThread(sequential);
m_mainKFPerspective.setExecutionThread(runThread);
runThread.start();
}
}
private void stopFlow() {
if (m_mainKFPerspective.getCurrentTabIndex() >= 0) {
RunThread running = m_mainKFPerspective.getExecutionThread();
if (running != null) {
running.stopAllFlows();
}
/*
* Vector components =
* BeanInstance.getBeanInstances(m_mainKFPerspective.getCurrentTabIndex
* ());
*
* if (components != null) { for (int i = 0; i < components.size(); i++) {
* Object temp = ((BeanInstance) components.elementAt(i)).getBean();
*
* if (temp instanceof BeanCommon) { ((BeanCommon) temp).stop(); } } }
*/
}
}
private void processPackage(String tempBeanCompName,
weka.gui.HierarchyPropertyParser hpp, DefaultMutableTreeNode parentNode,
Map<String, DefaultMutableTreeNode> nodeTextIndex) {
if (hpp.isLeafReached()) {
// instantiate a bean and add it to the holderPanel
// System.err.println("Would add "+hpp.fullValue());
/*
* String algName = hpp.fullValue(); JPanel tempBean =
* instantiateToolBarBean(true, tempBeanCompName, algName); if (tempBean
* != null && holderPanel != null) { holderPanel.add(tempBean); }
*/
hpp.goToParent();
return;
}
String[] children = hpp.childrenValues();
for (String element : children) {
hpp.goToChild(element);
DefaultMutableTreeNode child = null;
if (hpp.isLeafReached()) {
String algName = hpp.fullValue();
Object visibleCheck = instantiateBean(true, tempBeanCompName, algName);
if (visibleCheck != null) {
if (visibleCheck instanceof BeanContextChild) {
m_bcSupport.add(visibleCheck);
}
ImageIcon scaledForTree = null;
if (visibleCheck instanceof Visible) {
BeanVisual bv = ((Visible) visibleCheck).getVisual();
if (bv != null) {
scaledForTree = new ImageIcon(bv.scale(0.33));
// m_iconLookup.put(algName, scaledForTree);
}
}
// try and get a tool tip
String toolTip = "";
try {
Object wrappedA = WekaPackageClassLoaderManager.objectForName(algName);
// Object wrappedA = Class.forName(algName).newInstance();
toolTip = getGlobalInfo(wrappedA);
} catch (Exception ex) {
}
JTreeLeafDetails leafData = new JTreeLeafDetails(tempBeanCompName,
algName, scaledForTree);
if (toolTip != null && toolTip.length() > 0) {
leafData.setToolTipText(toolTip);
}
child = new InvisibleNode(leafData);
nodeTextIndex.put(algName.toLowerCase() + " "
+ (toolTip != null ? toolTip.toLowerCase() : ""), child);
}
} else {
child = new InvisibleNode(element);
}
if (child != null) {
parentNode.add(child);
}
processPackage(tempBeanCompName, hpp, child, nodeTextIndex);
}
hpp.goToParent();
}
private Object instantiateBean(boolean wekawrapper, String tempBeanCompName,
String algName) {
Object tempBean;
if (wekawrapper) {
try {
// modifications by Zerbetto
// tempBean = Beans.instantiate(null, tempBeanCompName);
tempBean = WekaPackageClassLoaderManager.objectForName(tempBeanCompName);
//tempBean = Beans.instantiate(this.getClass().getClassLoader(),
// tempBeanCompName);
// end modifications by Zerbetto
} catch (Exception ex) {
weka.core.logging.Logger.log(weka.core.logging.Logger.Level.WARNING,
"[KnowledgeFlow] Failed to instantiate :"
+ tempBeanCompName + "KnowledgeFlowApp.instantiateBean()");
return null;
}
if (tempBean instanceof WekaWrapper) {
// algName = (String)tempBarSpecs.elementAt(j);
Class<?> c = null;
try {
c = WekaPackageClassLoaderManager.forName(algName);
// c = Class.forName(algName);
// check for ignore
for (Annotation a : c.getAnnotations()) {
if (a instanceof KFIgnore) {
return null;
}
}
} catch (Exception ex) {
weka.core.logging.Logger.log(weka.core.logging.Logger.Level.WARNING,
"[KnowledgeFlow] Can't find class called: "
+ algName);
return null;
}
try {
Object o = c.newInstance();
((WekaWrapper) tempBean).setWrappedAlgorithm(o);
} catch (Exception ex) {
weka.core.logging.Logger.log(weka.core.logging.Logger.Level.WARNING,
"[KnowledgeFlow] Failed to configure "
+ tempBeanCompName + " with " + algName);
return null;
}
}
} else {
try {
// modifications by Zerbetto
// tempBean = Beans.instantiate(null, tempBeanCompName);
tempBean = WekaPackageClassLoaderManager.objectForName(tempBeanCompName);
//tempBean = Beans.instantiate(this.getClass().getClassLoader(),
// tempBeanCompName);
// end modifications
} catch (Exception ex) {
ex.printStackTrace();
weka.core.logging.Logger.log(weka.core.logging.Logger.Level.WARNING,
"[KnowledgeFlow] Failed to instantiate :"
+ tempBeanCompName + "KnowledgeFlowApp.instantiateBean()");
return null;
}
}
return tempBean;
}
/**
* Pop up a help window
*/
private void popupHelp() {
final JButton tempB = m_helpB;
try {
tempB.setEnabled(false);
// Modified by Zerbetto
// InputStream inR =
// ClassLoader.
// getSystemResourceAsStream("weka/gui/beans/README_KnowledgeFlow");
InputStream inR = this.getClass().getClassLoader()
.getResourceAsStream("weka/gui/beans/README_KnowledgeFlow");
// end modifications
StringBuffer helpHolder = new StringBuffer();
LineNumberReader lnr = new LineNumberReader(new InputStreamReader(inR));
String line;
while ((line = lnr.readLine()) != null) {
helpHolder.append(line + "\n");
}
lnr.close();
final javax.swing.JFrame jf = new javax.swing.JFrame();
jf.getContentPane().setLayout(new java.awt.BorderLayout());
final JTextArea ta = new JTextArea(helpHolder.toString());
ta.setFont(new Font("Monospaced", Font.PLAIN, 12));
ta.setEditable(false);
final JScrollPane sp = new JScrollPane(ta);
jf.getContentPane().add(sp, java.awt.BorderLayout.CENTER);
jf.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
tempB.setEnabled(true);
jf.dispose();
}
});
jf.setSize(600, 600);
jf.setVisible(true);
} catch (Exception ex) {
tempB.setEnabled(true);
}
}
public void closeAllTabs() {
for (int i = m_mainKFPerspective.getNumTabs() - 1; i >= 0; i--) {
m_mainKFPerspective.removeTab(i);
}
}
public void clearLayout() {
stopFlow(); // try and stop any running components
if (m_mainKFPerspective.getNumTabs() == 0 || getAllowMultipleTabs()) {
m_mainKFPerspective.addTab("Untitled" + m_untitledCount++);
}
if (!getAllowMultipleTabs()) {
BeanConnection.setConnections(new Vector<BeanConnection>(),
m_mainKFPerspective.getCurrentTabIndex());
BeanInstance.setBeanInstances(new Vector<Object>(), m_mainKFPerspective
.getBeanLayout(m_mainKFPerspective.getCurrentTabIndex()),
m_mainKFPerspective.getCurrentTabIndex());
}
/*
* BeanInstance.reset(m_beanLayout); BeanConnection.reset();
* m_beanLayout.revalidate(); m_beanLayout.repaint();
* m_logPanel.clearStatus();
* m_logPanel.statusMessage("[KnowledgeFlow]|Welcome to the Weka Knowledge Flow"
* );
*/
}
/**
* Pops up the menu for selecting template layouts
*/
private void createTemplateMenuPopup() {
PopupMenu templatesMenu = new PopupMenu();
// MenuItem addToUserTabItem = new MenuItem("Add to user tab");
for (int i = 0; i < BeansProperties.TEMPLATE_PATHS.size(); i++) {
String mE = BeansProperties.TEMPLATE_DESCRIPTIONS.get(i);
final String path = BeansProperties.TEMPLATE_PATHS.get(i);
MenuItem m = new MenuItem(mE);
m.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ee) {
try {
ClassLoader resourceClassLoader = WekaPackageClassLoaderManager.getWekaPackageClassLoaderManager().findClassloaderForResource(path);
InputStream inR = resourceClassLoader.getResourceAsStream(path);
//InputStream inR = this.getClass().getClassLoader()
// .getResourceAsStream(path);
m_mainKFPerspective.addTab("Untitled" + m_untitledCount++);
XMLBeans xml = new XMLBeans(m_beanLayout, m_bcSupport,
m_mainKFPerspective.getCurrentTabIndex());
InputStreamReader isr = new InputStreamReader(inR);
@SuppressWarnings("unchecked")
Vector<Vector<?>> v = (Vector<Vector<?>>) xml.read(isr);
@SuppressWarnings("unchecked")
Vector<Object> beans = (Vector<Object>) v
.get(XMLBeans.INDEX_BEANINSTANCES);
@SuppressWarnings("unchecked")
Vector<BeanConnection> connections = (Vector<BeanConnection>) v
.get(XMLBeans.INDEX_BEANCONNECTIONS);
isr.close();
integrateFlow(beans, connections, false, false);
notifyIsDirty();
revalidate();
} catch (Exception ex) {
m_mainKFPerspective.getCurrentLogPanel().logMessage(
"Problem loading template: " + ex.getMessage());
}
}
});
templatesMenu.add(m);
}
m_templatesB.add(templatesMenu);
templatesMenu.show(m_templatesB, 0, 0);
}
/**
* Popup a context sensitive menu for the bean component
*
* @param pt holds the panel coordinates for the component
* @param bi the bean component over which the user right clicked the mouse
* @param x the x coordinate at which to popup the menu
* @param y the y coordinate at which to popup the menu
*
* Modified by Zerbetto: javax.swing.JPopupMenu transformed into
* java.awt.PopupMenu
*
*/
private void doPopup(Point pt, final BeanInstance bi, int x, int y) {
final JComponent bc = (JComponent) bi.getBean();
final int xx = x;
final int yy = y;
int menuItemCount = 0;
// modifications by Zerbetto
PopupMenu beanContextMenu = new PopupMenu();
// JPopupMenu beanContextMenu = new JPopupMenu();
// beanContextMenu.insert(new JLabel("Edit",
// SwingConstants.CENTER),
// menuItemCount);
boolean executing = m_mainKFPerspective.getExecuting();
MenuItem edit = new MenuItem("Edit:");
edit.setEnabled(false);
beanContextMenu.insert(edit, menuItemCount);
menuItemCount++;
if (m_mainKFPerspective.getSelectedBeans().size() > 0) {
MenuItem copyItem = new MenuItem("Copy");
copyItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
copyToClipboard();
m_mainKFPerspective.setSelectedBeans(new Vector<Object>());
}
});
beanContextMenu.add(copyItem);
copyItem.setEnabled(!executing);
menuItemCount++;
}
if (bc instanceof MetaBean) {
// JMenuItem ungroupItem = new JMenuItem("Ungroup");
MenuItem ungroupItem = new MenuItem("Ungroup");
ungroupItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// ungroup
bi.removeBean(m_beanLayout, m_mainKFPerspective.getCurrentTabIndex());
Vector<Object> group = ((MetaBean) bc).getBeansInSubFlow();
Vector<BeanConnection> associatedConnections = ((MetaBean) bc)
.getAssociatedConnections();
((MetaBean) bc).restoreBeans(xx, yy);
for (int i = 0; i < group.size(); i++) {
BeanInstance tbi = (BeanInstance) group.elementAt(i);
addComponent(tbi, false);
tbi.addBean(m_beanLayout, m_mainKFPerspective.getCurrentTabIndex());
}
for (int i = 0; i < associatedConnections.size(); i++) {
BeanConnection tbc = associatedConnections.elementAt(i);
tbc.setHidden(false);
}
m_beanLayout.repaint();
m_mainKFPerspective.setEditedStatus(true);
notifyIsDirty();
}
});
ungroupItem.setEnabled(!executing);
beanContextMenu.add(ungroupItem);
menuItemCount++;
// Add to user tab
// JMenuItem addToUserTabItem = new JMenuItem("Add to user tab");
MenuItem addToUserTabItem = new MenuItem("Add to user tab");
addToUserTabItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// addToUserToolBar((MetaBean) bi.getBean(), true);
// addToUserTreeNode((MetaBean) bi.getBean(), true);
addToUserTreeNode(bi, true);
notifyIsDirty();
}
});
addToUserTabItem.setEnabled(!executing);
beanContextMenu.add(addToUserTabItem);
menuItemCount++;
}
// JMenuItem deleteItem = new JMenuItem("Delete");
MenuItem deleteItem = new MenuItem("Delete");
deleteItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
BeanConnection.removeConnections(bi,
m_mainKFPerspective.getCurrentTabIndex());
bi.removeBean(m_beanLayout, m_mainKFPerspective.getCurrentTabIndex());
if (bc instanceof BeanCommon) {
String key = ((BeanCommon) bc).getCustomName() + "$" + bc.hashCode();
m_logPanel.statusMessage(key + "|remove");
}
// delete any that have been actively selected
if (m_mainKFPerspective.getSelectedBeans().size() > 0) {
deleteSelectedBeans();
}
revalidate();
m_mainKFPerspective.setEditedStatus(true);
notifyIsDirty();
m_selectAllB.setEnabled(BeanInstance.getBeanInstances(
m_mainKFPerspective.getCurrentTabIndex()).size() > 0);
}
});
deleteItem.setEnabled(!executing);
if (bc instanceof BeanCommon) {
if (((BeanCommon) bc).isBusy()) {
deleteItem.setEnabled(false);
}
}
beanContextMenu.add(deleteItem);
menuItemCount++;
if (bc instanceof BeanCommon) {
MenuItem nameItem = new MenuItem("Set name");
nameItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String oldName = ((BeanCommon) bc).getCustomName();
String name = JOptionPane.showInputDialog(KnowledgeFlowApp.this,
"Enter a name for this component", oldName);
if (name != null) {
((BeanCommon) bc).setCustomName(name);
m_mainKFPerspective.setEditedStatus(true);
}
}
});
if (bc instanceof BeanCommon) {
if (((BeanCommon) bc).isBusy()) {
nameItem.setEnabled(false);
}
}
nameItem.setEnabled(!executing);
beanContextMenu.add(nameItem);
menuItemCount++;
}
try {
// BeanInfo [] compInfo = null;
// JComponent [] associatedBeans = null;
Vector<BeanInfo> compInfo = new Vector<BeanInfo>(1);
Vector<Object> associatedBeans = null;
if (bc instanceof MetaBean) {
compInfo = ((MetaBean) bc).getBeanInfoSubFlow();
associatedBeans = ((MetaBean) bc).getBeansInSubFlow();
((MetaBean) bc).getBeansInOutputs();
((MetaBean) bc).getBeanInfoOutputs();
} else {
compInfo.add(Introspector.getBeanInfo(bc.getClass()));
}
final Vector<Object> tempAssociatedBeans = associatedBeans;
if (compInfo == null) {
weka.core.logging.Logger.log(weka.core.logging.Logger.Level.WARNING,
"[KnowledgeFlow] Error in doPopup()");
} else {
// System.err.println("Got bean info");
for (int zz = 0; zz < compInfo.size(); zz++) {
final int tt = zz;
final Class<?> custClass = compInfo.elementAt(zz).getBeanDescriptor()
.getCustomizerClass();
if (custClass != null) {
// System.err.println("Got customizer class");
// popupCustomizer(custClass, bc);
// JMenuItem custItem = null;
MenuItem custItem = null;
boolean customizationEnabled = !executing;
if (!(bc instanceof MetaBean)) {
// custItem = new JMenuItem("Configure...");
custItem = new MenuItem("Configure...");
if (bc instanceof BeanCommon) {
customizationEnabled = (!executing && !((BeanCommon) bc)
.isBusy());
}
} else {
String custName = custClass.getName();
BeanInstance tbi = (BeanInstance) associatedBeans.elementAt(zz);
if (tbi.getBean() instanceof BeanCommon) {
custName = ((BeanCommon) tbi.getBean()).getCustomName();
} else {
if (tbi.getBean() instanceof WekaWrapper) {
custName = ((WekaWrapper) tbi.getBean())
.getWrappedAlgorithm().getClass().getName();
} else {
custName = custName.substring(0,
custName.indexOf("Customizer"));
}
custName = custName.substring(custName.lastIndexOf('.') + 1,
custName.length());
}
// custItem = new JMenuItem("Configure: "+ custName);
custItem = new MenuItem("Configure: " + custName);
if (tbi.getBean() instanceof BeanCommon) {
customizationEnabled = (!executing && !((BeanCommon) tbi
.getBean()).isBusy());
}
}
custItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (bc instanceof MetaBean) {
popupCustomizer(custClass,
(JComponent) ((BeanInstance) tempAssociatedBeans
.elementAt(tt)).getBean());
} else {
popupCustomizer(custClass, bc);
}
notifyIsDirty();
}
});
custItem.setEnabled(customizationEnabled);
beanContextMenu.add(custItem);
menuItemCount++;
} else {
weka.core.logging.Logger.log(weka.core.logging.Logger.Level.INFO,
"[KnowledgeFlow] No customizer class");
}
}
Vector<EventSetDescriptor[]> esdV = new Vector<EventSetDescriptor[]>();
// for (int i = 0; i < compInfoOutputs.size(); i++) {
for (int i = 0; i < compInfo.size(); i++) {
EventSetDescriptor[] temp =
// ((BeanInfo)
// compInfoOutputs.elementAt(i)).getEventSetDescriptors();
compInfo.elementAt(i).getEventSetDescriptors();
if ((temp != null) && (temp.length > 0)) {
esdV.add(temp);
}
}
// EventSetDescriptor [] esds = compInfo.getEventSetDescriptors();
// if (esds != null && esds.length > 0) {
if (esdV.size() > 0) {
// beanContextMenu.insert(new JLabel("Connections",
// SwingConstants.CENTER),
// menuItemCount);
MenuItem connections = new MenuItem("Connections:");
connections.setEnabled(false);
beanContextMenu.insert(connections, menuItemCount);
menuItemCount++;
}
// final Vector finalOutputs = outputBeans;
final Vector<Object> finalOutputs = associatedBeans;
for (int j = 0; j < esdV.size(); j++) {
final int fj = j;
String sourceBeanName = "";
if (bc instanceof MetaBean) {
// Object sourceBean = ((BeanInstance)
// outputBeans.elementAt(j)).getBean();
Object sourceBean = ((BeanInstance) associatedBeans.elementAt(j))
.getBean();
if (sourceBean instanceof BeanCommon) {
sourceBeanName = ((BeanCommon) sourceBean).getCustomName();
} else {
if (sourceBean instanceof WekaWrapper) {
sourceBeanName = ((WekaWrapper) sourceBean)
.getWrappedAlgorithm().getClass().getName();
} else {
sourceBeanName = sourceBean.getClass().getName();
}
sourceBeanName = sourceBeanName.substring(
sourceBeanName.lastIndexOf('.') + 1, sourceBeanName.length());
}
sourceBeanName += ": ";
}
EventSetDescriptor[] esds = esdV.elementAt(j);
for (final EventSetDescriptor esd : esds) {
// System.err.println(esds[i].getName());
// add each event name to the menu
// JMenuItem evntItem = new JMenuItem(sourceBeanName
// +esds[i].getName());
MenuItem evntItem = new MenuItem(sourceBeanName + esd.getName());
// Check EventConstraints (if any) here
boolean ok = true;
evntItem.setEnabled(!executing);
if (bc instanceof EventConstraints) {
ok = ((EventConstraints) bc).eventGeneratable(esd.getName());
}
if (ok) {
evntItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
connectComponents(
esd,
(bc instanceof MetaBean) ? ((BeanInstance) finalOutputs
.elementAt(fj)) : bi, xx, yy);
notifyIsDirty();
}
});
} else {
evntItem.setEnabled(false);
}
beanContextMenu.add(evntItem);
menuItemCount++;
}
}
}
} catch (IntrospectionException ie) {
ie.printStackTrace();
}
// System.err.println("Just before look for other options");
// now look for other options for this bean
if (bc instanceof UserRequestAcceptor || bc instanceof Startable) {
Enumeration<String> req = null;
if (bc instanceof UserRequestAcceptor) {
req = ((UserRequestAcceptor) bc).enumerateRequests();
}
if (/* (bc instanceof Startable) || */(req != null && req
.hasMoreElements())) {
// beanContextMenu.insert(new JLabel("Actions",
// SwingConstants.CENTER),
// menuItemCount);
MenuItem actions = new MenuItem("Actions:");
actions.setEnabled(false);
beanContextMenu.insert(actions, menuItemCount);
menuItemCount++;
}
/*
* if (bc instanceof Startable) { String tempS =
* ((Startable)bc).getStartMessage(); insertUserOrStartableMenuItem(bc,
* true, tempS, beanContextMenu); }
*/
while (req != null && req.hasMoreElements()) {
String tempS = req.nextElement();
insertUserOrStartableMenuItem(bc, false, tempS, beanContextMenu);
menuItemCount++;
}
}
// Send to perspective menu item?
if (bc instanceof weka.gui.beans.Loader && m_perspectives.size() > 1
&& m_perspectiveDataLoadThread == null) {
final weka.core.converters.Loader theLoader =
((weka.gui.beans.Loader) bc)
.getLoader();
boolean ok = true;
if (theLoader instanceof FileSourcedConverter) {
String fileName = ((FileSourcedConverter) theLoader).retrieveFile()
.getPath();
Environment env = m_mainKFPerspective.getEnvironmentSettings();
try {
fileName = env.substitute(fileName);
} catch (Exception ex) {
}
File tempF = new File(fileName);
String fileNameFixedPathSep = fileName.replace(File.separatorChar, '/');
if (!tempF.isFile()
&& this.getClass().getClassLoader().getResource(fileNameFixedPathSep) == null) {
ok = false;
}
}
if (ok) {
beanContextMenu.addSeparator();
menuItemCount++;
if (m_perspectives.size() > 2) {
MenuItem sendToAllPerspectives = new MenuItem(
"Send to all perspectives");
menuItemCount++;
sendToAllPerspectives.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
loadDataAndSendToPerspective(theLoader, 0, true);
}
});
beanContextMenu.add(sendToAllPerspectives);
}
Menu sendToPerspective = new Menu("Send to perspective...");
beanContextMenu.add(sendToPerspective);
menuItemCount++;
for (int i = 1; i < m_perspectives.size(); i++) {
final int pIndex = i;
if (m_perspectives.get(i).acceptsInstances()) {
String pName = m_perspectives.get(i).getPerspectiveTitle();
MenuItem pI = new MenuItem(pName);
pI.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
loadDataAndSendToPerspective(theLoader, pIndex, false);
}
});
sendToPerspective.add(pI);
}
}
}
}
// System.err.println("Just before showing menu");
// popup the menu
if (menuItemCount > 0) {
// beanContextMenu.show(m_beanLayout, x, y);
double z = m_layoutZoom / 100.0;
double px = x * z;
double py = y * z;
m_beanLayout.add(beanContextMenu);
// beanContextMenu.show(m_beanLayout, x, y);
beanContextMenu.show(m_beanLayout, (int) px, (int) py);
}
}
private synchronized void loadDataAndSendToPerspective(
final weka.core.converters.Loader loader, final int perspectiveIndex,
final boolean sendToAll) {
if (m_perspectiveDataLoadThread == null) {
m_perspectiveDataLoadThread = new Thread() {
@Override
public void run() {
try {
Environment env = m_mainKFPerspective.getEnvironmentSettings();
if (loader instanceof EnvironmentHandler) {
((EnvironmentHandler) loader).setEnvironment(env);
}
loader.reset();
m_logPanel
.statusMessage("@!@[KnowledgeFlow]|Sending data to perspective(s)...");
Instances data = loader.getDataSet();
if (data != null) {
// make sure the perspective toolbar is visible!!
if (!m_configAndPerspectivesVisible) {
KnowledgeFlowApp.this.add(m_configAndPerspectives,
BorderLayout.NORTH);
m_configAndPerspectivesVisible = true;
}
// need to disable all the perspective buttons
for (int i = 0; i < m_perspectives.size(); i++) {
m_perspectiveToolBar.getComponent(i).setEnabled(false);
}
if (sendToAll) {
for (int i = 1; i < m_perspectives.size(); i++) {
if (m_perspectives.get(i).acceptsInstances()) {
m_perspectives.get(i).setInstances(data);
}
}
} else {
KFPerspective currentP = (KFPerspective) m_perspectiveHolder
.getComponent(0);
if (currentP != m_perspectives.get(perspectiveIndex)) {
m_perspectives.get(perspectiveIndex).setInstances(data);
currentP.setActive(false);
m_perspectiveHolder.remove(0);
m_perspectiveHolder.add(
(JComponent) m_perspectives.get(perspectiveIndex),
BorderLayout.CENTER);
m_perspectives.get(perspectiveIndex).setActive(true);
((JToggleButton) m_perspectiveToolBar
.getComponent(perspectiveIndex)).setSelected(true);
// KnowledgeFlowApp.this.invalidate();
KnowledgeFlowApp.this.revalidate();
KnowledgeFlowApp.this.repaint();
notifyIsDirty();
}
}
}
} catch (Exception ex) {
weka.core.logging.Logger.log(
weka.core.logging.Logger.Level.WARNING,
"[KnowledgeFlow] problem loading data for "
+ "perspective(s) : " + ex.getMessage());
ex.printStackTrace();
} finally {
// re-enable all the perspective buttons
for (int i = 0; i < m_perspectives.size(); i++) {
m_perspectiveToolBar.getComponent(i).setEnabled(true);
}
m_perspectiveDataLoadThread = null;
m_logPanel.statusMessage("@!@[KnowledgeFlow]|OK");
}
}
};
m_perspectiveDataLoadThread.setPriority(Thread.MIN_PRIORITY);
m_perspectiveDataLoadThread.start();
}
}
private void insertUserOrStartableMenuItem(final JComponent bc,
final boolean startable, String tempS, PopupMenu beanContextMenu) {
boolean disabled = false;
boolean confirmRequest = false;
// check to see if this item is currently disabled
if (tempS.charAt(0) == '$') {
tempS = tempS.substring(1, tempS.length());
disabled = true;
}
// check to see if this item requires confirmation
if (tempS.charAt(0) == '?') {
tempS = tempS.substring(1, tempS.length());
confirmRequest = true;
}
final String tempS2 = tempS;
// JMenuItem custItem = new JMenuItem(tempS2);
MenuItem custItem = new MenuItem(tempS2);
if (confirmRequest) {
custItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//
int result = JOptionPane.showConfirmDialog(KnowledgeFlowApp.this,
tempS2, "Confirm action", JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.YES_OPTION) {
Thread startPointThread = new Thread() {
@Override
public void run() {
try {
if (startable) {
((Startable) bc).start();
} else if (bc instanceof UserRequestAcceptor) {
((UserRequestAcceptor) bc).performRequest(tempS2);
}
notifyIsDirty();
} catch (Exception ex) {
ex.printStackTrace();
}
}
};
startPointThread.setPriority(Thread.MIN_PRIORITY);
startPointThread.start();
}
}
});
} else {
custItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Thread startPointThread = new Thread() {
@Override
public void run() {
try {
if (startable) {
((Startable) bc).start();
} else if (bc instanceof UserRequestAcceptor) {
((UserRequestAcceptor) bc).performRequest(tempS2);
}
notifyIsDirty();
} catch (Exception ex) {
ex.printStackTrace();
}
}
};
startPointThread.setPriority(Thread.MIN_PRIORITY);
startPointThread.start();
}
});
}
if (disabled) {
custItem.setEnabled(false);
}
beanContextMenu.add(custItem);
}
/**
* Tells us about the modified status of a particular object - typically a
* customizer that is editing a flow component. Allows us to set the modified
* flag for the current flow.
*/
@Override
public void setModifiedStatus(Object source, boolean modified) {
if (source instanceof BeanCustomizer && modified) {
m_mainKFPerspective.setEditedStatus(modified);
}
}
/**
* Popup the customizer for this bean
*
* @param custClass the class of the customizer
* @param bc the bean to be customized
*/
private void popupCustomizer(Class<?> custClass, JComponent bc) {
try {
// instantiate
final Object customizer = custClass.newInstance();
// set environment **before** setting object!!
if (customizer instanceof EnvironmentHandler) {
((EnvironmentHandler) customizer).setEnvironment(m_flowEnvironment);
}
if (customizer instanceof BeanCustomizer) {
((BeanCustomizer) customizer).setModifiedListener(this);
}
((Customizer) customizer).setObject(bc);
// final javax.swing.JFrame jf = new javax.swing.JFrame();
final JDialog d = new JDialog(
(java.awt.Frame) KnowledgeFlowApp.this.getTopLevelAncestor(),
ModalityType.DOCUMENT_MODAL);
d.setLayout(new BorderLayout());
d.getContentPane().add((JComponent) customizer, BorderLayout.CENTER);
// jf.getContentPane().setLayout(new BorderLayout());
// jf.getContentPane().add((JComponent)customizer, BorderLayout.CENTER);
if (customizer instanceof CustomizerCloseRequester) {
((CustomizerCloseRequester) customizer).setParentWindow(d);
}
d.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
if (customizer instanceof CustomizerClosingListener) {
((CustomizerClosingListener) customizer).customizerClosing();
}
d.dispose();
}
});
// jf.pack();
// jf.setVisible(true);
d.pack();
d.setLocationRelativeTo(KnowledgeFlowApp.this);
d.setVisible(true);
} catch (Exception ex) {
ex.printStackTrace();
}
}
private void addToUserTreeNode(BeanInstance meta, boolean installListener) {
DefaultTreeModel model = (DefaultTreeModel) m_componentTree.getModel();
DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
if (m_userCompNode == null) {
m_userCompNode = new InvisibleNode("User");
model.insertNodeInto(m_userCompNode, root, 0);
}
Vector<Object> beanHolder = new Vector<Object>();
beanHolder.add(meta);
try {
StringBuffer serialized = copyToBuffer(beanHolder);
String displayName = "";
ImageIcon scaledIcon = null;
//
if (meta.getBean() instanceof Visible) {
// ((Visible)copy).getVisual().scale(3);
scaledIcon = new ImageIcon(((Visible) meta.getBean()).getVisual()
.scale(0.33));
displayName = ((Visible) meta.getBean()).getVisual().getText();
}
Vector<Object> metaDetails = new Vector<Object>();
metaDetails.add(displayName);
metaDetails.add(serialized);
metaDetails.add(scaledIcon);
SerializedObject so = new SerializedObject(metaDetails);
@SuppressWarnings("unchecked")
Vector<Object> copy = (Vector<Object>) so.getObject();
JTreeLeafDetails metaLeaf = new JTreeLeafDetails(displayName, copy,
scaledIcon);
DefaultMutableTreeNode newUserComp = new InvisibleNode(metaLeaf);
model.insertNodeInto(newUserComp, m_userCompNode, 0);
// add to the list of user components
m_userComponents.add(copy);
if (installListener && m_firstUserComponentOpp) {
try {
installWindowListenerForSavingUserStuff();
m_firstUserComponentOpp = false;
} catch (Exception ex) {
ex.printStackTrace();
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
/*
* java.awt.Color bckC = getBackground(); Vector beans =
* BeanInstance.getBeanInstances(m_mainKFPerspective.getCurrentTabIndex());
* detachFromLayout(beans);
*/
// Disconnect any beans connected to the inputs or outputs
// of this MetaBean (prevents serialization of the entire
// KnowledgeFlow!!)
/*
* Vector tempRemovedConnections = new Vector(); Vector allConnections =
* BeanConnection.getConnections(m_mainKFPerspective.getCurrentTabIndex());
* Vector inputs = bean.getInputs(); Vector outputs = bean.getOutputs();
* Vector allComps = bean.getSubFlow();
*
* for (int i = 0; i < inputs.size(); i++) { BeanInstance temp =
* (BeanInstance)inputs.elementAt(i); // is this input a target for some
* event? for (int j = 0; j < allConnections.size(); j++) { BeanConnection
* tempC = (BeanConnection)allConnections.elementAt(j); if
* (tempC.getTarget() == temp) { tempRemovedConnections.add(tempC); }
*
* // also check to see if this input is a source for // some target that is
* *not* in the subFlow if (tempC.getSource() == temp &&
* !bean.subFlowContains(tempC.getTarget())) {
* tempRemovedConnections.add(tempC); } } }
*
* for (int i = 0; i < outputs.size(); i++) { BeanInstance temp =
* (BeanInstance)outputs.elementAt(i); // is this output a source for some
* target? for (int j = 0; j < allConnections.size(); j++) { BeanConnection
* tempC = (BeanConnection)allConnections.elementAt(j); if
* (tempC.getSource() == temp) { tempRemovedConnections.add(tempC); } } }
*
*
* for (int i = 0; i < tempRemovedConnections.size(); i++) { BeanConnection
* temp = (BeanConnection)tempRemovedConnections.elementAt(i);
* temp.remove(m_mainKFPerspective.getCurrentTabIndex()); }
*
* MetaBean copy = copyMetaBean(bean, true);
*
* String displayName =""; ImageIcon scaledIcon = null; // if (copy
* instanceof Visible) { //((Visible)copy).getVisual().scale(3); scaledIcon
* = new ImageIcon(((Visible)copy).getVisual().scale(0.33)); displayName =
* ((Visible)copy).getVisual().getText(); }
*
* JTreeLeafDetails metaLeaf = new JTreeLeafDetails(displayName, copy,
* scaledIcon); DefaultMutableTreeNode newUserComp = new
* DefaultMutableTreeNode(metaLeaf); model.insertNodeInto(newUserComp,
* m_userCompNode, 0);
*
* // add to the list of user components m_userComponents.add(copy);
*
* if (installListener && m_firstUserComponentOpp) { try {
* installWindowListenerForSavingUserBeans(); m_firstUserComponentOpp =
* false; } catch (Exception ex) { ex.printStackTrace(); } }
*
* // Now reinstate any deleted connections to the original MetaBean for
* (int i = 0; i < tempRemovedConnections.size(); i++) { BeanConnection temp
* = (BeanConnection)tempRemovedConnections.elementAt(i); BeanConnection
* newC = new BeanConnection(temp.getSource(), temp.getTarget(),
* temp.getSourceEventSetDescriptor(),
* m_mainKFPerspective.getCurrentTabIndex()); }
*/
/*
* for (int i = 0; i < beans.size(); i++) { BeanInstance tempB =
* (BeanInstance)beans.elementAt(i); if (tempB.getBean() instanceof Visible)
* { ((Visible)(tempB.getBean())).getVisual().
* addPropertyChangeListener(KnowledgeFlowApp.this);
*
* if (tempB.getBean() instanceof MetaBean) { ((MetaBean)tempB.getBean()).
* addPropertyChangeListenersSubFlow(KnowledgeFlowApp.this); } // Restore
* the default background colour ((Visible)(tempB.getBean())).getVisual().
* setBackground(bckC); ((JComponent)(tempB.getBean())).setBackground(bckC);
* } }
*/
}
/**
* Set the contents of the "paste" buffer and enable the paste from cliboard
* toolbar button
*
* @param b the buffer to use
*/
public void setPasteBuffer(StringBuffer b) {
m_pasteBuffer = b;
if (m_pasteBuffer != null && m_pasteBuffer.length() > 0) {
m_pasteB.setEnabled(true);
}
}
/**
* Get the contents of the paste buffer
*
* @return the contents of the paste buffer
*/
public StringBuffer getPasteBuffer() {
return m_pasteBuffer;
}
/**
* Utility routine that serializes the supplied Vector of BeanInstances to XML
*
* @param selectedBeans the vector of BeanInstances to serialize
* @return a StringBuffer containing the serialized vector
* @throws Exception if a problem occurs
*/
public StringBuffer copyToBuffer(Vector<Object> selectedBeans)
throws Exception {
Vector<BeanConnection> associatedConnections = BeanConnection
.getConnections(m_mainKFPerspective.getCurrentTabIndex());
/*
* BeanConnection.associatedConnections(selectedBeans,
* m_mainKFPerspective.getCurrentTabIndex());
*/
// xml serialize to a string and store in the
// clipboard variable
Vector<Vector<?>> v = new Vector<Vector<?>>();
v.setSize(2);
v.set(XMLBeans.INDEX_BEANINSTANCES, selectedBeans);
v.set(XMLBeans.INDEX_BEANCONNECTIONS, associatedConnections);
XMLBeans xml = new XMLBeans(m_beanLayout, m_bcSupport,
m_mainKFPerspective.getCurrentTabIndex());
java.io.StringWriter sw = new java.io.StringWriter();
xml.write(sw, v);
return sw.getBuffer();
// System.out.println(m_pasteBuffer.toString());
}
private boolean copyToClipboard() {
Vector<Object> selectedBeans = m_mainKFPerspective.getSelectedBeans();
if (selectedBeans == null || selectedBeans.size() == 0) {
return false;
}
// m_mainKFPerspective.setSelectedBeans(new Vector());
try {
m_pasteBuffer = copyToBuffer(selectedBeans);
} catch (Exception ex) {
m_logPanel.logMessage("[KnowledgeFlow] problem copying beans: "
+ ex.getMessage());
ex.printStackTrace();
return false;
}
m_pasteB.setEnabled(true);
revalidate();
repaint();
notifyIsDirty();
return true;
}
protected boolean pasteFromBuffer(int x, int y, StringBuffer pasteBuffer,
boolean addUndoPoint) {
if (addUndoPoint) {
addUndoPoint();
}
java.io.StringReader sr = new java.io.StringReader(pasteBuffer.toString());
try {
XMLBeans xml = new XMLBeans(m_beanLayout, m_bcSupport,
m_mainKFPerspective.getCurrentTabIndex());
@SuppressWarnings("unchecked")
Vector<Vector<?>> v = (Vector<Vector<?>>) xml.read(sr);
@SuppressWarnings("unchecked")
Vector<Object> beans = (Vector<Object>) v
.get(XMLBeans.INDEX_BEANINSTANCES);
@SuppressWarnings("unchecked")
Vector<BeanConnection> connections = (Vector<BeanConnection>) v
.get(XMLBeans.INDEX_BEANCONNECTIONS);
for (int i = 0; i < beans.size(); i++) {
BeanInstance b = (BeanInstance) beans.get(i);
if (b.getBean() instanceof MetaBean) {
Vector<Object> subFlow = ((MetaBean) b.getBean()).getSubFlow();
for (int j = 0; j < subFlow.size(); j++) {
BeanInstance subB = (BeanInstance) subFlow.get(j);
subB.removeBean(m_beanLayout,
m_mainKFPerspective.getCurrentTabIndex());
if (subB.getBean() instanceof Visible) {
((Visible) subB.getBean()).getVisual()
.removePropertyChangeListener(this);
}
}
}
}
// adjust beans coords with respect to x, y. Look for
// the smallest x and the smallest y (top left corner of the bounding)
// box.
int minX = Integer.MAX_VALUE;
int minY = Integer.MAX_VALUE;
boolean adjust = false;
for (int i = 0; i < beans.size(); i++) {
BeanInstance b = (BeanInstance) beans.get(i);
if (b.getX() < minX) {
minX = b.getX();
adjust = true;
}
if (b.getY() < minY) {
minY = b.getY();
adjust = true;
}
}
if (adjust) {
int deltaX = x - minX;
int deltaY = y - minY;
for (int i = 0; i < beans.size(); i++) {
BeanInstance b = (BeanInstance) beans.get(i);
/*
* b.setX(b.getX() + deltaX); b.setY(b.getY() + deltaY);
*/
b.setXY(b.getX() + deltaX, b.getY() + deltaY);
}
}
// integrate these beans
integrateFlow(beans, connections, false, false);
for (int i = 0; i < beans.size(); i++) {
checkForDuplicateName((BeanInstance) beans.get(i));
}
setEnvironment();
notifyIsDirty();
m_mainKFPerspective.setSelectedBeans(beans);
} catch (Exception e) {
m_logPanel.logMessage("[KnowledgeFlow] problem pasting beans: "
+ e.getMessage());
e.printStackTrace();
}
revalidate();
notifyIsDirty();
return true;
}
private boolean pasteFromClipboard(int x, int y, StringBuffer pasteBuffer,
boolean addUndoPoint) {
return pasteFromBuffer(x, y, pasteBuffer, addUndoPoint);
}
private void deleteSelectedBeans() {
Vector<Object> v = m_mainKFPerspective.getSelectedBeans();
if (v.size() > 0) {
m_mainKFPerspective.setSelectedBeans(new Vector<Object>());
}
addUndoPoint();
for (int i = 0; i < v.size(); i++) {
BeanInstance b = (BeanInstance) v.get(i);
BeanConnection.removeConnections(b,
m_mainKFPerspective.getCurrentTabIndex());
b.removeBean(m_beanLayout, m_mainKFPerspective.getCurrentTabIndex());
if (b instanceof BeanCommon) {
String key = ((BeanCommon) b).getCustomName() + "$" + b.hashCode();
m_logPanel.statusMessage(key + "|remove");
}
}
m_mainKFPerspective.setSelectedBeans(new Vector<Object>());
revalidate();
notifyIsDirty();
m_selectAllB.setEnabled(BeanInstance.getBeanInstances(
m_mainKFPerspective.getCurrentTabIndex()).size() > 0);
}
private void addUndoPoint() {
try {
Stack<File> undo = m_mainKFPerspective.getUndoBuffer();
File tempFile = File.createTempFile("knowledgeFlow", FILE_EXTENSION_XML);
tempFile.deleteOnExit();
if (saveLayout(tempFile, m_mainKFPerspective.getCurrentTabIndex(), true)) {
undo.push(tempFile);
// keep no more than 20 undo points
if (undo.size() > 20) {
undo.remove(0);
}
m_undoB.setEnabled(true);
}
} catch (Exception ex) {
m_logPanel
.logMessage("[KnowledgeFlow] a problem occurred while trying to "
+ "create a undo point : " + ex.getMessage());
}
}
private boolean groupable(Vector<Object> selected, Vector<Object> inputs,
Vector<Object> outputs) {
boolean groupable = true;
// screen the inputs and outputs
if (inputs.size() == 0 || outputs.size() == 0) {
return false;
}
// dissallow MetaBeans in the selected set (for the
// time being).
for (int i = 0; i < selected.size(); i++) {
BeanInstance temp = (BeanInstance) selected.elementAt(i);
if (temp.getBean() instanceof MetaBean) {
groupable = false;
return false;
}
}
// show connector dots for input beans
for (int i = 0; i < inputs.size(); i++) {
BeanInstance temp = (BeanInstance) inputs.elementAt(i);
if (temp.getBean() instanceof Visible) {
((Visible) temp.getBean()).getVisual().setDisplayConnectors(true,
java.awt.Color.red);
}
}
// show connector dots for output beans
for (int i = 0; i < outputs.size(); i++) {
BeanInstance temp = (BeanInstance) outputs.elementAt(i);
if (temp.getBean() instanceof Visible) {
((Visible) temp.getBean()).getVisual().setDisplayConnectors(true,
java.awt.Color.green);
}
}
return groupable;
}
// right click over empty canvas (not on a bean)
private void rightClickCanvasPopup(final int x, final int y) {
Vector<BeanConnection> closestConnections = BeanConnection
.getClosestConnections(new Point(x, y), 10,
m_mainKFPerspective.getCurrentTabIndex());
PopupMenu rightClickMenu = new PopupMenu();
int menuItemCount = 0;
if (m_mainKFPerspective.getSelectedBeans().size() > 0
|| closestConnections.size() > 0
|| (m_pasteBuffer != null && m_pasteBuffer.length() > 0)) {
if (m_mainKFPerspective.getSelectedBeans().size() > 0) {
MenuItem snapItem = new MenuItem("Snap selected to grid");
snapItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
snapSelectedToGrid();
}
});
rightClickMenu.add(snapItem);
menuItemCount++;
MenuItem copyItem = new MenuItem("Copy selected");
copyItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
copyToClipboard();
m_mainKFPerspective.setSelectedBeans(new Vector<Object>());
}
});
rightClickMenu.add(copyItem);
menuItemCount++;
MenuItem cutItem = new MenuItem("Cut selected");
cutItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// only delete if our copy was successful!
if (copyToClipboard()) {
deleteSelectedBeans();
}
}
});
rightClickMenu.add(cutItem);
menuItemCount++;
MenuItem deleteSelected = new MenuItem("Delete selected");
deleteSelected.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
deleteSelectedBeans();
}
});
rightClickMenu.add(deleteSelected);
menuItemCount++;
// Able to group selected subflow?
final Vector<Object> selected = m_mainKFPerspective.getSelectedBeans();
// check if sub flow is valid
final Vector<Object> inputs = BeanConnection.inputs(selected,
m_mainKFPerspective.getCurrentTabIndex());
final Vector<Object> outputs = BeanConnection.outputs(selected,
m_mainKFPerspective.getCurrentTabIndex());
boolean groupable = groupable(selected, inputs, outputs);
if (groupable) {
MenuItem groupItem = new MenuItem("Group selected");
groupItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
groupSubFlow(selected, inputs, outputs);
}
});
rightClickMenu.add(groupItem);
menuItemCount++;
}
}
if (m_pasteBuffer != null && m_pasteBuffer.length() > 0) {
rightClickMenu.addSeparator();
menuItemCount++;
MenuItem pasteItem = new MenuItem("Paste");
pasteItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// deserialize, integerate and
// position at x, y
pasteFromClipboard(x, y, m_pasteBuffer, true);
}
});
rightClickMenu.add(pasteItem);
menuItemCount++;
}
if (closestConnections.size() > 0) {
rightClickMenu.addSeparator();
menuItemCount++;
MenuItem deleteConnection = new MenuItem("Delete Connection:");
deleteConnection.setEnabled(false);
rightClickMenu.insert(deleteConnection, menuItemCount);
menuItemCount++;
for (int i = 0; i < closestConnections.size(); i++) {
final BeanConnection bc = closestConnections.elementAt(i);
String connName = bc.getSourceEventSetDescriptor().getName();
// JMenuItem deleteItem = new JMenuItem(connName);
String targetName = "";
if (bc.getTarget().getBean() instanceof BeanCommon) {
targetName = ((BeanCommon) bc.getTarget().getBean())
.getCustomName();
} else {
targetName = bc.getTarget().getBean().getClass().getName();
targetName = targetName.substring(targetName.lastIndexOf('.') + 1,
targetName.length());
}
MenuItem deleteItem = new MenuItem(connName + "-->" + targetName);
deleteItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
addUndoPoint();
bc.remove(m_mainKFPerspective.getCurrentTabIndex());
m_beanLayout.revalidate();
m_beanLayout.repaint();
m_mainKFPerspective.setEditedStatus(true);
if (m_mainKFPerspective.getSelectedBeans().size() > 0) {
m_mainKFPerspective.setSelectedBeans(new Vector<Object>());
}
notifyIsDirty();
}
});
rightClickMenu.add(deleteItem);
menuItemCount++;
}
}
}
if (menuItemCount > 0) {
rightClickMenu.addSeparator();
menuItemCount++;
}
MenuItem noteItem = new MenuItem("New note");
noteItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Note n = new Note();
m_toolBarBean = n;
KnowledgeFlowApp.this.setCursor(Cursor
.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
m_mode = ADDING;
}
});
rightClickMenu.add(noteItem);
menuItemCount++;
m_beanLayout.add(rightClickMenu);
// make sure that popup location takes current scaling into account
double z = m_layoutZoom / 100.0;
double px = x * z;
double py = y * z;
rightClickMenu.show(m_beanLayout, (int) px, (int) py);
}
/**
* Initiates the connection process for two beans
*
* @param esd the EventSetDescriptor for the source bean
* @param bi the source bean
* @param x the x coordinate to start connecting from
* @param y the y coordinate to start connecting from
*/
private void connectComponents(EventSetDescriptor esd, BeanInstance bi,
int x, int y) {
// unselect any selected beans on the canvas
if (m_mainKFPerspective.getSelectedBeans(
m_mainKFPerspective.getCurrentTabIndex()).size() > 0) {
m_mainKFPerspective.setSelectedBeans(
m_mainKFPerspective.getCurrentTabIndex(), new Vector<Object>());
}
// record the event set descriptior for this event
m_sourceEventSetDescriptor = esd;
Class<?> listenerClass = esd.getListenerType(); // class of the listener
JComponent source = (JComponent) bi.getBean();
// now determine which (if any) of the other beans implement this
// listener
int targetCount = 0;
Vector<Object> beanInstances = BeanInstance
.getBeanInstances(m_mainKFPerspective.getCurrentTabIndex());
for (int i = 0; i < beanInstances.size(); i++) {
JComponent bean =
(JComponent) ((BeanInstance) beanInstances.elementAt(i))
.getBean();
boolean connectable = false;
boolean canContinue = false;
if (bean != source) {
if (bean instanceof MetaBean) {
if (((MetaBean) bean).canAcceptConnection(listenerClass)) {
canContinue = true;
}
} else if (listenerClass.isInstance(bean) && bean != source) {
canContinue = true;
}
}
if (canContinue) {
if (!(bean instanceof BeanCommon)) {
connectable = true; // assume this bean is happy to receive a
// connection
} else {
// give this bean a chance to veto any proposed connection via
// the listener interface
if (((BeanCommon) bean).
// connectionAllowed(esd.getName())) {
connectionAllowed(esd)) {
connectable = true;
}
}
if (connectable) {
if (bean instanceof Visible) {
targetCount++;
((Visible) bean).getVisual().setDisplayConnectors(true);
}
}
}
}
// have some possible beans to connect to?
if (targetCount > 0) {
// System.err.println("target count "+targetCount);
if (source instanceof Visible) {
((Visible) source).getVisual().setDisplayConnectors(true);
m_editElement = bi;
Point closest = ((Visible) source).getVisual()
.getClosestConnectorPoint(new Point(x, y));
m_startX = (int) closest.getX();
m_startY = (int) closest.getY();
m_oldX = m_startX;
m_oldY = m_startY;
Graphics2D gx = (Graphics2D) m_beanLayout.getGraphics();
gx.setXORMode(java.awt.Color.white);
gx.drawLine(m_startX, m_startY, m_startX, m_startY);
gx.dispose();
m_mode = CONNECTING;
}
}
revalidate();
repaint();
notifyIsDirty();
}
private void checkForDuplicateName(BeanInstance comp) {
if (comp.getBean() instanceof BeanCommon) {
String currentName = ((BeanCommon) comp.getBean()).getCustomName();
if (currentName != null && currentName.length() > 0) {
Vector<Object> layoutBeans = BeanInstance
.getBeanInstances(m_mainKFPerspective.getCurrentTabIndex());
boolean exactMatch = false;
int maxCopyNum = 1;
for (int i = 0; i < layoutBeans.size(); i++) {
BeanInstance b = (BeanInstance) layoutBeans.get(i);
if (b.getBean() instanceof BeanCommon) {
String compName = ((BeanCommon) b.getBean()).getCustomName();
if (currentName.equals(compName) && (b.getBean() != comp.getBean())) {
exactMatch = true;
} else {
if (compName.startsWith(currentName)) {
// see if the comparison bean has a number at the end
String num = compName.replace(currentName, "");
try {
int compNum = Integer.parseInt(num);
if (compNum > maxCopyNum) {
maxCopyNum = compNum;
}
} catch (NumberFormatException e) {
}
}
}
}
}
if (exactMatch) {
maxCopyNum++;
currentName += "" + maxCopyNum;
((BeanCommon) comp.getBean()).setCustomName(currentName);
}
}
}
}
private void addComponent(BeanInstance comp, boolean repaint) {
if (comp.getBean() instanceof Visible) {
((Visible) comp.getBean()).getVisual().addPropertyChangeListener(this);
}
if (comp.getBean() instanceof BeanCommon) {
((BeanCommon) comp.getBean()).setLog(m_logPanel);
}
if (comp.getBean() instanceof MetaBean) {
// re-align sub-beans
Vector<Object> list;
list = ((MetaBean) comp.getBean()).getInputs();
for (int i = 0; i < list.size(); i++) {
((BeanInstance) list.get(i)).setX(comp.getX());
((BeanInstance) list.get(i)).setY(comp.getY());
}
list = ((MetaBean) comp.getBean()).getOutputs();
for (int i = 0; i < list.size(); i++) {
((BeanInstance) list.get(i)).setX(comp.getX());
((BeanInstance) list.get(i)).setY(comp.getY());
}
}
if (comp.getBean() instanceof EnvironmentHandler) {
((EnvironmentHandler) comp.getBean()).setEnvironment(m_flowEnvironment);
}
// check for a duplicate name
checkForDuplicateName(comp);
KnowledgeFlowApp.this.setCursor(Cursor
.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
if (repaint) {
m_beanLayout.repaint();
}
m_pointerB.setSelected(true);
m_mode = NONE;
m_selectAllB.setEnabled(BeanInstance.getBeanInstances(
m_mainKFPerspective.getCurrentTabIndex()).size() > 0);
}
private void addComponent(int x, int y) {
if (m_toolBarBean instanceof MetaBean) {
// need to add the MetaBean's internal connections
// to BeanConnection's vector
Vector<BeanConnection> associatedConnections = ((MetaBean) m_toolBarBean)
.getAssociatedConnections();
BeanConnection.getConnections(m_mainKFPerspective.getCurrentTabIndex())
.addAll(associatedConnections);
// ((MetaBean)m_toolBarBean).setXDrop(x);
// ((MetaBean)m_toolBarBean).setYDrop(y);
((MetaBean) m_toolBarBean)
.addPropertyChangeListenersSubFlow(KnowledgeFlowApp.this);
}
if (m_toolBarBean instanceof BeanContextChild) {
m_bcSupport.add(m_toolBarBean);
}
BeanInstance bi = new BeanInstance(m_beanLayout, m_toolBarBean, x, y,
m_mainKFPerspective.getCurrentTabIndex());
// addBean((JComponent)bi.getBean());
m_toolBarBean = null;
addComponent(bi, true);
}
private void highlightSubFlow(int startX, int startY, int endX, int endY) {
java.awt.Rectangle r = new java.awt.Rectangle((startX < endX) ? startX
: endX, (startY < endY) ? startY : endY, Math.abs(startX - endX),
Math.abs(startY - endY));
// System.err.println(r);
Vector<Object> selected = BeanInstance.findInstances(r,
m_mainKFPerspective.getCurrentTabIndex());
// show connector dots for selected beans
/*
* for (int i = 0; i < selected.size(); i++) { BeanInstance temp =
* (BeanInstance)selected.elementAt(i); if (temp.getBean() instanceof
* Visible) {
* ((Visible)temp.getBean()).getVisual().setDisplayConnectors(true); } }
*/
m_mainKFPerspective.setSelectedBeans(selected);
}
private void groupSubFlow(Vector<Object> selected, Vector<Object> inputs,
Vector<Object> outputs) {
int upperLeftX = Integer.MAX_VALUE;
int upperLeftY = Integer.MAX_VALUE;
int lowerRightX = Integer.MIN_VALUE;
int lowerRightY = Integer.MIN_VALUE;
for (int i = 0; i < selected.size(); i++) {
BeanInstance b = (BeanInstance) selected.get(i);
if (b.getX() < upperLeftX) {
upperLeftX = b.getX();
}
if (b.getY() < upperLeftY) {
upperLeftY = b.getY();
}
if (b.getX() > lowerRightX) {
// ImageIcon ic = ((Visible)b.getBean()).getVisual().getStaticIcon();
// lowerRightX = (b.getX() + ic.getIconWidth());
lowerRightX = b.getX();
}
if (b.getY() > lowerRightY) {
// ImageIcon ic = ((Visible)b.getBean()).getVisual().getStaticIcon();
// lowerRightY = (b.getY() + ic.getIconHeight());
lowerRightY = b.getY();
}
}
int bx = upperLeftX + ((lowerRightX - upperLeftX) / 2);
int by = upperLeftY + ((lowerRightY - upperLeftY) / 2);
new java.awt.Rectangle(upperLeftX, upperLeftY, lowerRightX, lowerRightY);
/*
* BufferedImage subFlowPreview = null; try { subFlowPreview =
* createImage(m_beanLayout, r); } catch (IOException ex) {
* ex.printStackTrace(); // drop through quietly }
*/
// Confirmation pop-up
int result = JOptionPane.showConfirmDialog(KnowledgeFlowApp.this,
"Group this sub-flow?", "Group Components", JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.YES_OPTION) {
Vector<BeanConnection> associatedConnections = BeanConnection
.associatedConnections(selected,
m_mainKFPerspective.getCurrentTabIndex());
String name = JOptionPane.showInputDialog(KnowledgeFlowApp.this,
"Enter a name for this group", "MyGroup");
if (name != null) {
MetaBean group = new MetaBean();
// group.setXCreate(bx); group.setYCreate(by);
// group.setXDrop(bx); group.setYDrop(by);
group.setSubFlow(selected);
group.setAssociatedConnections(associatedConnections);
group.setInputs(inputs);
group.setOutputs(outputs);
// group.setSubFlowPreview(new ImageIcon(subFlowPreview));
if (name.length() > 0) {
// group.getVisual().setText(name);
group.setCustomName(name);
}
// if (group instanceof BeanContextChild) {
// m_bcSupport.add(group);
// }
// int bx = (int)r.getCenterX() -
// group.getVisual().m_icon.getIconWidth();
// int by = (int)r.getCenterY() -
// group.getVisual().m_icon.getIconHeight();
/*
* BeanInstance bi = new BeanInstance(m_beanLayout, group,
* (int)r.getX()+(int)(r.getWidth()/2),
* (int)r.getY()+(int)(r.getHeight()/2),
* m_mainKFPerspective.getCurrentTabIndex());
*/
Dimension d = group.getPreferredSize();
;
int dx = (int) (d.getWidth() / 2);
int dy = (int) (d.getHeight() / 2);
BeanInstance bi = new BeanInstance(m_beanLayout, group, bx + dx, by
+ dy, m_mainKFPerspective.getCurrentTabIndex());
for (int i = 0; i < selected.size(); i++) {
BeanInstance temp = (BeanInstance) selected.elementAt(i);
temp.removeBean(m_beanLayout,
m_mainKFPerspective.getCurrentTabIndex());
if (temp.getBean() instanceof Visible) {
((Visible) temp.getBean()).getVisual()
.removePropertyChangeListener(this);
}
}
for (int i = 0; i < associatedConnections.size(); i++) {
BeanConnection temp = associatedConnections.elementAt(i);
temp.setHidden(true);
}
group.shiftBeans(bi, true);
addComponent(bi, true);
}
}
for (int i = 0; i < selected.size(); i++) {
BeanInstance temp = (BeanInstance) selected.elementAt(i);
if (temp.getBean() instanceof Visible) {
((Visible) temp.getBean()).getVisual().setDisplayConnectors(false);
}
}
m_mainKFPerspective.setSelectedBeans(new Vector<Object>());
revalidate();
notifyIsDirty();
}
/**
* Accept property change events
*
* @param e a <code>PropertyChangeEvent</code> value
*/
@Override
public void propertyChange(PropertyChangeEvent e) {
revalidate();
m_beanLayout.repaint();
}
/**
* Load a pre-saved layout
*/
private void loadLayout() {
m_loadB.setEnabled(false);
m_saveB.setEnabled(false);
m_playB.setEnabled(false);
m_playBB.setEnabled(false);
int returnVal = m_FileChooser.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
// stopFlow();
// determine filename
File oFile = m_FileChooser.getSelectedFile();
// set internal flow directory environment variable
// add extension if necessary
if (m_FileChooser.getFileFilter() == m_KfFilter) {
if (!oFile.getName().toLowerCase().endsWith(FILE_EXTENSION)) {
oFile = new File(oFile.getParent(), oFile.getName() + FILE_EXTENSION);
}
} else if (m_FileChooser.getFileFilter() == m_KOMLFilter) {
if (!oFile.getName().toLowerCase().endsWith(KOML.FILE_EXTENSION + "kf")) {
oFile = new File(oFile.getParent(), oFile.getName()
+ KOML.FILE_EXTENSION + "kf");
}
} else if (m_FileChooser.getFileFilter() == m_XMLFilter) {
if (!oFile.getName().toLowerCase().endsWith(FILE_EXTENSION_XML)) {
oFile = new File(oFile.getParent(), oFile.getName()
+ FILE_EXTENSION_XML);
}
} else if (m_FileChooser.getFileFilter() == m_XStreamFilter) {
if (!oFile.getName().toLowerCase()
.endsWith(XStream.FILE_EXTENSION + "kf")) {
oFile = new File(oFile.getParent(), oFile.getName()
+ XStream.FILE_EXTENSION + "kf");
}
}
String flowName = oFile.getName();
if (flowName.lastIndexOf('.') > 0) {
flowName = flowName.substring(0, flowName.lastIndexOf('.'));
}
loadLayout(oFile, getAllowMultipleTabs());
}
m_loadB.setEnabled(true);
m_playB.setEnabled(true);
m_playBB.setEnabled(true);
m_saveB.setEnabled(true);
}
/**
* Load a layout from a file. Supports loading binary and XML serialized flow
* files
*
* @param oFile the file to load from
* @param newTab true if the loaded layout should be displayed in a new tab
*/
public void loadLayout(File oFile, boolean newTab) {
loadLayout(oFile, newTab, false);
}
/**
* Load a layout from a file
*
* @param oFile the file to load from
* @param newTab true if the loaded layout should be displayed in a new tab
* @param isUndo is this file an "undo" file?
*/
@SuppressWarnings("unchecked")
protected void loadLayout(File oFile, boolean newTab, boolean isUndo) {
// stop any running flow first (if we are loading into this tab)
if (!newTab) {
stopFlow();
}
m_loadB.setEnabled(false);
m_saveB.setEnabled(false);
m_playB.setEnabled(false);
m_playBB.setEnabled(false);
if (newTab) {
String flowName = oFile.getName();
if (flowName.lastIndexOf('.') > 0) {
flowName = flowName.substring(0, flowName.lastIndexOf('.'));
}
m_mainKFPerspective.addTab(flowName);
// m_mainKFPerspective.setActiveTab(m_mainKFPerspective.getNumTabs() - 1);
m_mainKFPerspective.setFlowFile(oFile);
m_mainKFPerspective.setEditedStatus(false);
}
if (!isUndo) {
File absolute = new File(oFile.getAbsolutePath());
// m_flowEnvironment.addVariable("Internal.knowledgeflow.directory",
// absolute.getParent());
m_mainKFPerspective.getEnvironmentSettings().addVariable(
"Internal.knowledgeflow.directory", absolute.getParent());
}
try {
Vector<Object> beans = new Vector<Object>();
Vector<BeanConnection> connections = new Vector<BeanConnection>();
// KOML?
if ((KOML.isPresent())
&& (oFile.getAbsolutePath().toLowerCase().endsWith(KOML.FILE_EXTENSION
+ "kf"))) {
Vector<Vector<?>> v = (Vector<Vector<?>>) KOML.read(oFile
.getAbsolutePath());
beans = (Vector<Object>) v.get(XMLBeans.INDEX_BEANINSTANCES);
connections = (Vector<BeanConnection>) v
.get(XMLBeans.INDEX_BEANCONNECTIONS);
} /* XStream */else if ((XStream.isPresent())
&& (oFile.getAbsolutePath().toLowerCase()
.endsWith(XStream.FILE_EXTENSION + "kf"))) {
Vector<Vector<?>> v = (Vector<Vector<?>>) XStream.read(oFile
.getAbsolutePath());
beans = (Vector<Object>) v.get(XMLBeans.INDEX_BEANINSTANCES);
connections = (Vector<BeanConnection>) v
.get(XMLBeans.INDEX_BEANCONNECTIONS);
} /* XML? */else if (oFile.getAbsolutePath().toLowerCase()
.endsWith(FILE_EXTENSION_XML)) {
XMLBeans xml = new XMLBeans(m_beanLayout, m_bcSupport,
m_mainKFPerspective.getCurrentTabIndex());
Vector<Vector<?>> v = (Vector<Vector<?>>) xml.read(oFile);
beans = (Vector<Object>) v.get(XMLBeans.INDEX_BEANINSTANCES);
connections = (Vector<BeanConnection>) v
.get(XMLBeans.INDEX_BEANCONNECTIONS);
// connections = new Vector();
} /* binary */else {
InputStream is = new FileInputStream(oFile);
ObjectInputStream ois = new ObjectInputStream(is);
beans = (Vector<Object>) ois.readObject();
connections = (Vector<BeanConnection>) ois.readObject();
ois.close();
}
integrateFlow(beans, connections, true, false);
setEnvironment();
if (newTab) {
m_logPanel.clearStatus();
m_logPanel.statusMessage("@!@[KnowledgeFlow]|Flow loaded.");
}
} catch (Exception ex) {
m_logPanel
.statusMessage("@!@[KnowledgeFlow]|Unable to load flow (see log).");
m_logPanel.logMessage("[KnowledgeFlow] Unable to load flow ("
+ ex.getMessage() + ").");
ex.printStackTrace();
}
m_loadB.setEnabled(true);
m_saveB.setEnabled(true);
m_playB.setEnabled(true);
m_playBB.setEnabled(true);
}
/**
* Load a flow file from an input stream. Only supports XML serialized flows.
*
* @param is the input stream to laod from
* @param newTab whether to open a new tab in the UI for the flow
* @param flowName the name of the flow
* @throws Exception if a problem occurs during de-serialization
*/
public void loadLayout(InputStream is, boolean newTab, String flowName)
throws Exception {
InputStreamReader isr = new InputStreamReader(is);
loadLayout(isr, newTab, flowName);
}
/**
* Load a flow file from a reader. Only supports XML serialized flows.
*
* @param reader the reader to load from
* @param newTab whether to open a new tab in the UI for the flow
* @param flowName the name of the flow
* @throws Exception if a problem occurs during de-serialization
*/
@SuppressWarnings("unchecked")
public void loadLayout(Reader reader, boolean newTab, String flowName)
throws Exception {
// stop any running flow first (if we are loading into this tab)
if (!newTab) {
stopFlow();
}
m_loadB.setEnabled(false);
m_saveB.setEnabled(false);
m_playB.setEnabled(false);
m_playBB.setEnabled(false);
if (newTab) {
m_mainKFPerspective.addTab(flowName);
m_mainKFPerspective.setEditedStatus(false);
}
XMLBeans xml = new XMLBeans(m_beanLayout, m_bcSupport,
m_mainKFPerspective.getCurrentTabIndex());
Vector<Vector<?>> v = (Vector<Vector<?>>) xml.read(reader);
Vector<Object> beans = (Vector<Object>) v.get(XMLBeans.INDEX_BEANINSTANCES);
Vector<BeanConnection> connections = (Vector<BeanConnection>) v
.get(XMLBeans.INDEX_BEANCONNECTIONS);
integrateFlow(beans, connections, true, false);
setEnvironment();
if (newTab) {
m_logPanel.clearStatus();
m_logPanel.statusMessage("@!@[KnowledgeFlow]|Flow loaded.");
}
m_loadB.setEnabled(true);
m_saveB.setEnabled(true);
m_playB.setEnabled(true);
m_playBB.setEnabled(true);
}
// Link the supplied beans into the KnowledgeFlow gui
protected void integrateFlow(Vector<Object> beans,
Vector<BeanConnection> connections, boolean replace,
boolean notReplaceAndSourcedFromBinary) {
java.awt.Color bckC = getBackground();
m_bcSupport = new BeanContextSupport();
m_bcSupport.setDesignTime(true);
// register this panel as a property change listener with each
// bean
for (int i = 0; i < beans.size(); i++) {
BeanInstance tempB = (BeanInstance) beans.elementAt(i);
if (tempB.getBean() instanceof Visible) {
((Visible) (tempB.getBean())).getVisual().addPropertyChangeListener(
this);
// A workaround to account for JPanel's with their default
// background colour not being serializable in Apple's JRE
((Visible) (tempB.getBean())).getVisual().setBackground(bckC);
((JComponent) (tempB.getBean())).setBackground(bckC);
}
if (tempB.getBean() instanceof BeanCommon) {
((BeanCommon) (tempB.getBean())).setLog(m_logPanel);
}
if (tempB.getBean() instanceof BeanContextChild) {
m_bcSupport.add(tempB.getBean());
}
}
if (replace) {
BeanInstance.setBeanInstances(beans, m_beanLayout,
m_mainKFPerspective.getCurrentTabIndex());
BeanConnection.setConnections(connections,
m_mainKFPerspective.getCurrentTabIndex());
} else if (notReplaceAndSourcedFromBinary) {
BeanInstance.appendBeans(m_beanLayout, beans,
m_mainKFPerspective.getCurrentTabIndex());
BeanConnection.appendConnections(connections,
m_mainKFPerspective.getCurrentTabIndex());
}
revalidate();
m_beanLayout.revalidate();
m_beanLayout.repaint();
notifyIsDirty();
m_selectAllB.setEnabled(BeanInstance.getBeanInstances(
m_mainKFPerspective.getCurrentTabIndex()).size() > 0);
}
/**
* Set the flow for the KnowledgeFlow to edit. Assumes that client has loaded
* a Vector of beans and a Vector of connections. the supplied beans and
* connections are deep-copied via serialization before being set in the
* layout. The beans get added to the flow at position 0.
*
* @param v a Vector containing a Vector of beans and a Vector of connections
* @exception Exception if something goes wrong
*/
@SuppressWarnings("unchecked")
public void setFlow(Vector<Vector<?>> v) throws Exception {
// Vector beansCopy = null, connectionsCopy = null;
// clearLayout();
if (getAllowMultipleTabs()) {
throw new Exception("[KnowledgeFlow] setFlow() - can only set a flow in "
+ "singe tab only mode");
}
/*
* int tabI = 0;
*
* BeanInstance.
* removeAllBeansFromContainer((JComponent)m_mainKFPerspective.
* getBeanLayout(tabI), tabI); BeanInstance.setBeanInstances(new Vector(),
* m_mainKFPerspective.getBeanLayout(tabI));
* BeanConnection.setConnections(new Vector());
*/
// m_mainKFPerspective.removeTab(0);
// m_mainKFPerspective.addTab("Untitled");
m_beanLayout.removeAll();
BeanInstance.init();
BeanConnection.init();
SerializedObject so = new SerializedObject(v);
Vector<Vector<?>> copy = (Vector<Vector<?>>) so.getObject();
Vector<Object> beans = (Vector<Object>) copy.elementAt(0);
Vector<BeanConnection> connections = (Vector<BeanConnection>) copy
.elementAt(1);
// reset environment variables
m_flowEnvironment = new Environment();
integrateFlow(beans, connections, true, false);
revalidate();
notifyIsDirty();
}
/**
* Gets the current flow being edited. The flow is returned as a single Vector
* containing two other Vectors: the beans and the connections. These two
* vectors are deep-copied via serialization before being returned.
*
* @return the current flow being edited
* @throws Exception if a problem occurs
*/
public Vector<Vector<?>> getFlow() throws Exception {
Vector<Vector<?>> v = new Vector<Vector<?>>();
Vector<Object> beans = BeanInstance.getBeanInstances(m_mainKFPerspective
.getCurrentTabIndex());
Vector<BeanConnection> connections = BeanConnection
.getConnections(m_mainKFPerspective.getCurrentTabIndex());
detachFromLayout(beans);
v.add(beans);
v.add(connections);
SerializedObject so = new SerializedObject(v);
@SuppressWarnings("unchecked")
Vector<Vector<?>> copy = (Vector<Vector<?>>) so.getObject();
// tempWrite(beans, connections);
integrateFlow(beans, connections, true, false);
return copy;
}
/**
* Returns the current flow being edited in XML format.
*
* @return the current flow as an XML string
* @throws Exception if a problem occurs
*/
public String getFlowXML() throws Exception {
Vector<Object> beans = BeanInstance.getBeanInstances(m_mainKFPerspective
.getCurrentTabIndex());
StringBuffer buff = copyToBuffer(beans);
return buff.toString();
}
/**
* Utility method to create an image of a region of the given component
*
* @param component the component to create an image of
* @param region the region of the component to put into the image
* @return the image
* @throws IOException
*/
protected static BufferedImage createImage(JComponent component,
Rectangle region) throws IOException {
boolean opaqueValue = component.isOpaque();
component.setOpaque(true);
BufferedImage image = new BufferedImage(region.width, region.height,
BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = image.createGraphics();
g2d.translate(-region.getX(), -region.getY());
// g2d.setClip( region );
component.paint(g2d);
g2d.dispose();
component.setOpaque(opaqueValue);
return image;
}
// Remove this panel as a property changle listener from
// each bean
private void detachFromLayout(Vector<Object> beans) {
for (int i = 0; i < beans.size(); i++) {
BeanInstance tempB = (BeanInstance) beans.elementAt(i);
if (tempB.getBean() instanceof Visible) {
((Visible) (tempB.getBean())).getVisual().removePropertyChangeListener(
this);
if (tempB.getBean() instanceof MetaBean) {
((MetaBean) tempB.getBean())
.removePropertyChangeListenersSubFlow(this);
}
// A workaround to account for JPanel's with their default
// background colour not being serializable in Apple's JRE.
// JComponents are rendered with a funky stripy background
// under OS X using java.awt.TexturePaint - unfortunately
// TexturePaint doesn't implement Serializable.
((Visible) (tempB.getBean())).getVisual().setBackground(
java.awt.Color.white);
((JComponent) (tempB.getBean())).setBackground(java.awt.Color.white);
}
}
}
public void saveLayout(File toFile, int tabIndex) {
saveLayout(toFile, tabIndex, false);
}
protected boolean saveLayout(File sFile, int tabIndex, boolean isUndoPoint) {
java.awt.Color bckC = getBackground();
Vector<Object> beans = BeanInstance.getBeanInstances(tabIndex);
detachFromLayout(beans);
detachFromLayout(beans);
// now serialize components vector and connections vector
try {
// KOML?
if ((KOML.isPresent())
&& (sFile.getAbsolutePath().toLowerCase().endsWith(KOML.FILE_EXTENSION
+ "kf"))) {
Vector<Vector<?>> v = new Vector<Vector<?>>();
v.setSize(2);
v.set(XMLBeans.INDEX_BEANINSTANCES, beans);
v.set(XMLBeans.INDEX_BEANCONNECTIONS,
BeanConnection.getConnections(tabIndex));
KOML.write(sFile.getAbsolutePath(), v);
} /* XStream */else if ((XStream.isPresent())
&& (sFile.getAbsolutePath().toLowerCase()
.endsWith(XStream.FILE_EXTENSION + "kf"))) {
Vector<Vector<?>> v = new Vector<Vector<?>>();
v.setSize(2);
v.set(XMLBeans.INDEX_BEANINSTANCES, beans);
v.set(XMLBeans.INDEX_BEANCONNECTIONS,
BeanConnection.getConnections(tabIndex));
XStream.write(sFile.getAbsolutePath(), v);
} /* XML? */else if (sFile.getAbsolutePath().toLowerCase()
.endsWith(FILE_EXTENSION_XML)) {
Vector<Vector<?>> v = new Vector<Vector<?>>();
v.setSize(2);
v.set(XMLBeans.INDEX_BEANINSTANCES, beans);
v.set(XMLBeans.INDEX_BEANCONNECTIONS,
BeanConnection.getConnections(tabIndex));
XMLBeans xml = new XMLBeans(m_beanLayout, m_bcSupport, tabIndex);
// XML flows are tagged as encoded with UTF-8
BufferedWriter br = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(sFile), "UTF-8"));
xml.write(br, v);
} /* binary */else {
OutputStream os = new FileOutputStream(sFile);
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(beans);
oos.writeObject(BeanConnection.getConnections(tabIndex));
oos.flush();
oos.close();
}
} catch (Exception ex) {
m_logPanel
.statusMessage("@!@[KnowledgeFlow]|Unable to save flow (see log).");
m_logPanel.logMessage("[KnowledgeFlow] Unable to save flow ("
+ ex.getMessage() + ").");
ex.printStackTrace();
return false;
} finally {
// restore this panel as a property change listener in the beans
for (int i = 0; i < beans.size(); i++) {
BeanInstance tempB = (BeanInstance) beans.elementAt(i);
if (tempB.getBean() instanceof Visible) {
((Visible) (tempB.getBean())).getVisual().addPropertyChangeListener(
this);
if (tempB.getBean() instanceof MetaBean) {
((MetaBean) tempB.getBean())
.addPropertyChangeListenersSubFlow(this);
}
// Restore the default background colour
((Visible) (tempB.getBean())).getVisual().setBackground(bckC);
((JComponent) (tempB.getBean())).setBackground(bckC);
}
}
if (!isUndoPoint) {
Environment e = m_mainKFPerspective.getEnvironmentSettings(tabIndex);
e.addVariable("Internal.knowledgeflow.directory",
new File(sFile.getAbsolutePath()).getParent());
m_mainKFPerspective.setEditedStatus(tabIndex, false);
String tabTitle = sFile.getName();
tabTitle = tabTitle.substring(0, tabTitle.lastIndexOf('.'));
m_mainKFPerspective.setTabTitle(tabIndex, tabTitle);
}
}
return true;
}
/**
* Serialize the layout to a file
*/
private void saveLayout(int tabIndex, boolean showDialog) {
getBackground();
File sFile = m_mainKFPerspective.getFlowFile(tabIndex);
int returnVal = JFileChooser.APPROVE_OPTION;
boolean shownDialog = false;
if (showDialog || sFile.getName().equals("-NONE-")) {
returnVal = m_FileChooser.showSaveDialog(this);
shownDialog = true;
}
if (returnVal == JFileChooser.APPROVE_OPTION) {
// temporarily remove this panel as a property changle listener from
// each bean
Vector<Object> beans = BeanInstance.getBeanInstances(tabIndex);
detachFromLayout(beans);
// determine filename (if necessary)
if (shownDialog) {
sFile = m_FileChooser.getSelectedFile();
}
// add extension if necessary
if (m_FileChooser.getFileFilter() == m_KfFilter) {
if (!sFile.getName().toLowerCase().endsWith(FILE_EXTENSION)) {
sFile = new File(sFile.getParent(), sFile.getName() + FILE_EXTENSION);
}
} else if (m_FileChooser.getFileFilter() == m_KOMLFilter) {
if (!sFile.getName().toLowerCase().endsWith(KOML.FILE_EXTENSION + "kf")) {
sFile = new File(sFile.getParent(), sFile.getName()
+ KOML.FILE_EXTENSION + "kf");
}
} else if (m_FileChooser.getFileFilter() == m_XStreamFilter) {
if (!sFile.getName().toLowerCase()
.endsWith(XStream.FILE_EXTENSION + "kf")) {
sFile = new File(sFile.getParent(), sFile.getName()
+ XStream.FILE_EXTENSION + "kf");
}
} else if (m_FileChooser.getFileFilter() == m_XMLFilter) {
if (!sFile.getName().toLowerCase().endsWith(FILE_EXTENSION_XML)) {
sFile = new File(sFile.getParent(), sFile.getName()
+ FILE_EXTENSION_XML);
}
}
saveLayout(sFile, m_mainKFPerspective.getCurrentTabIndex(), false);
m_mainKFPerspective.setFlowFile(tabIndex, sFile);
}
}
/**
* Save the knowledge flow into the OutputStream passed at input. Only
* supports saving the layout data (no trained models) to XML.
*
* @param out the output stream to save the layout in
*/
public void saveLayout(OutputStream out, int tabIndex) {
// temporarily remove this panel as a property changle listener from
// each bean
Vector<Object> beans = BeanInstance.getBeanInstances(tabIndex);
for (int i = 0; i < beans.size(); i++) {
BeanInstance tempB = (BeanInstance) beans.elementAt(i);
if (tempB.getBean() instanceof Visible) {
((Visible) (tempB.getBean())).getVisual().removePropertyChangeListener(
this);
if (tempB.getBean() instanceof MetaBean) {
((MetaBean) tempB.getBean())
.removePropertyChangeListenersSubFlow(this);
}
}
}
// now serialize components vector and connections vector
try {
Vector<Vector<?>> v = new Vector<Vector<?>>();
v.setSize(2);
v.set(XMLBeans.INDEX_BEANINSTANCES, beans);
v.set(XMLBeans.INDEX_BEANCONNECTIONS,
BeanConnection.getConnections(tabIndex));
XMLBeans xml = new XMLBeans(m_beanLayout, m_bcSupport, tabIndex);
xml.write(out, v);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
// restore this panel as a property change listener in the beans
for (int i = 0; i < beans.size(); i++) {
BeanInstance tempB = (BeanInstance) beans.elementAt(i);
if (tempB.getBean() instanceof Visible) {
((Visible) (tempB.getBean())).getVisual().addPropertyChangeListener(
this);
if (tempB.getBean() instanceof MetaBean) {
((MetaBean) tempB.getBean())
.addPropertyChangeListenersSubFlow(this);
}
}
}
}
}
@SuppressWarnings("unchecked")
private void loadUserComponents() {
Vector<Vector<Object>> tempV = null;
// String ext = "";
/*
* if (m_UserComponentsInXML) ext = USERCOMPONENTS_XML_EXTENSION;
*/
File sFile = new File(weka.core.WekaPackageManager.WEKA_HOME.getPath()
+ File.separator + "knowledgeFlow" + File.separator + "userComponents");
/*
* new File(System.getProperty("user.home") +File.separator +
* ".knowledgeFlow" +File.separator + "userComponents" +ext);
*/
if (sFile.exists()) {
try {
/*
* if (m_UserComponentsInXML) { XMLBeans xml = new
* XMLBeans(m_beanLayout, m_bcSupport, XMLBeans.DATATYPE_USERCOMPONENTS,
* 0); tempV = (Vector) xml.read(sFile); } else {
*/
InputStream is = new FileInputStream(sFile);
ObjectInputStream ois = new ObjectInputStream(is);
tempV = (Vector<Vector<Object>>) ois.readObject();
ois.close();
// }
} catch (Exception ex) {
weka.core.logging.Logger.log(weka.core.logging.Logger.Level.WARNING,
"[KnowledgeFlow] Problem reading user components.");
ex.printStackTrace();
return;
}
if (tempV.size() > 0) {
DefaultTreeModel model = (DefaultTreeModel) m_componentTree.getModel();
DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
if (m_userCompNode == null) {
m_userCompNode = new InvisibleNode("User");
model.insertNodeInto(m_userCompNode, root, 0);
}
// add the components
for (int i = 0; i < tempV.size(); i++) {
Vector<Object> tempB = tempV.elementAt(i);
String displayName = (String) tempB.get(0);
tempB.get(1);
ImageIcon scaledIcon = (ImageIcon) tempB.get(2);
JTreeLeafDetails treeLeaf = new JTreeLeafDetails(displayName, tempB,
scaledIcon);
DefaultMutableTreeNode newUserComp = new InvisibleNode(treeLeaf);
model.insertNodeInto(newUserComp, m_userCompNode, 0);
// add to the list of user components
m_userComponents.add(tempB);
// addToUserToolBar(tempB, false);
// addToUserTreeNode(tempB, false);
}
}
}
}
private void installWindowListenerForSavingUserStuff() {
((java.awt.Window) getTopLevelAncestor())
.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
weka.core.logging.Logger.log(weka.core.logging.Logger.Level.INFO,
"[KnowledgeFlow] Saving user components....");
File sFile = new File(WekaPackageManager.WEKA_HOME.getPath()
+ File.separator + "knowledgeFlow");
if (!sFile.exists()) {
if (!sFile.mkdir()) {
weka.core.logging.Logger.log(
weka.core.logging.Logger.Level.WARNING,
"[KnowledgeFlow] Unable to create \""
+ sFile.getPath() + "\" directory");
}
}
try {
String ext = "";
/*
* if (m_UserComponentsInXML) ext = USERCOMPONENTS_XML_EXTENSION;
*/
File sFile2 = new File(sFile.getAbsolutePath() + File.separator
+ "userComponents" + ext);
/*
* if (m_UserComponentsInXML) { XMLBeans xml = new
* XMLBeans(m_beanLayout, m_bcSupport,
* XMLBeans.DATATYPE_USERCOMPONENTS,
* m_mainKFPerspective.getCurrentTabIndex()); xml.write(sFile2,
* m_userComponents); } else {
*/
OutputStream os = new FileOutputStream(sFile2);
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(m_userComponents);
oos.flush();
oos.close();
// }
} catch (Exception ex) {
weka.core.logging.Logger.log(
weka.core.logging.Logger.Level.WARNING,
"[KnowledgeFlow] Unable to save user components");
ex.printStackTrace();
}
// if (VISIBLE_PERSPECTIVES.size() > 0) {
weka.core.logging.Logger.log(weka.core.logging.Logger.Level.INFO,
"Saving preferences for selected perspectives...");
sFile = new File(weka.core.WekaPackageManager.PROPERTIES_DIR
.toString() + File.separator + "VisiblePerspectives.props");
try {
FileWriter f = new FileWriter(sFile);
f.write("weka.gui.beans.KnowledgeFlow.SelectedPerspectives=");
int i = 0;
for (String p : BeansProperties.VISIBLE_PERSPECTIVES) {
if (i > 0) {
f.write(",");
}
f.write(p);
i++;
}
f.write("\n");
f.write("weka.gui.beans.KnowledgeFlow.PerspectiveToolBarVisisble="
+ ((m_configAndPerspectivesVisible) ? "yes" : "no"));
f.write("\n");
f.close();
} catch (Exception ex) {
weka.core.logging.Logger.log(
weka.core.logging.Logger.Level.WARNING,
"[KnowledgeFlow] Unable to save user perspectives preferences");
ex.printStackTrace();
}
// }
}
});
}
/**
* Utility method for grabbing the global info help (if it exists) from an
* arbitrary object
*
* @param tempBean the object to grab global info from
* @return the global help info or null if global info does not exist
*/
public static String getGlobalInfo(Object tempBean) {
return Utils.getGlobalInfo(tempBean, true);
}
/**
* variable for the KnowLedgeFlow class which would be set to null by the
* memory monitoring thread to free up some memory if we running out of
* memory.
*/
private static KnowledgeFlowApp m_knowledgeFlow;
/** for monitoring the Memory consumption */
private static Memory m_Memory = new Memory(true);
// list of things to be notified when the startup process of
// the KnowledgeFlow is complete
public static Vector<StartUpListener> s_startupListeners =
new Vector<StartUpListener>();
// modifications by Zerbetto
// If showFileMenu is true, the file menu (open file, new file, save file
// buttons) is showed
private boolean m_showFileMenu = true;
/**
* Create the singleton instance of the KnowledgeFlow
*
* @param args can contain a file argument for loading a flow layout (format:
* "file=[path to layout file]") Modified by Zerbetto: you can
* specify the path of a knowledge flow layout file at input
*/
public static void createSingleton(String[] args) {
// modifications by Zerbetto 05-12-2007
String fileName = null;
boolean showFileMenu = true;
if ((args != null) && (args.length > 0)) {
for (String arg : args) {
if (arg.startsWith("file=")) {
fileName = arg.substring("file=".length());
} else if (arg.startsWith("showFileMenu=")) {
showFileMenu = Boolean.parseBoolean(arg.substring("showFileMenu="
.length()));
}
}
}
if (m_knowledgeFlow == null) {
m_knowledgeFlow = new KnowledgeFlowApp(showFileMenu);
}
// end modifications by Zerbetto
// notify listeners (if any)
for (int i = 0; i < s_startupListeners.size(); i++) {
s_startupListeners.elementAt(i).startUpComplete();
}
// modifications by Zerbetto 05-12-2007
if (fileName != null) {
m_knowledgeFlow.loadInitialLayout(fileName);
}
// end modifications
}
public static void disposeSingleton() {
m_knowledgeFlow = null;
}
/**
* Return the singleton instance of the KnowledgeFlow
*
* @return the singleton instance
*/
public static KnowledgeFlowApp getSingleton() {
return m_knowledgeFlow;
}
/**
* Add a listener to be notified when startup is complete
*
* @param s a listener to add
*/
public static void addStartupListener(StartUpListener s) {
s_startupListeners.add(s);
}
/**
* Loads the specified file at input
*
* Added by Zerbetto
*/
// modifications by Zerbetto 05-12-2007
private void loadInitialLayout(String fileName) {
File oFile = new File(fileName);
if (oFile.exists() && oFile.isFile()) {
m_FileChooser.setSelectedFile(oFile);
int index = fileName.lastIndexOf('.');
if (index != -1) {
String extension = fileName.substring(index);
if (FILE_EXTENSION_XML.equalsIgnoreCase(extension)) {
m_FileChooser.setFileFilter(m_knowledgeFlow.m_XMLFilter);
} else if (FILE_EXTENSION.equalsIgnoreCase(extension)) {
m_FileChooser.setFileFilter(m_knowledgeFlow.m_KfFilter);
}
}
} else {
weka.core.logging.Logger.log(weka.core.logging.Logger.Level.WARNING,
"[KnowledgeFlow] File '" + fileName
+ "' does not exists.");
}
loadLayout(oFile, true);
}
public void setAllowMultipleTabs(boolean multiple) {
m_allowMultipleTabs = multiple;
if (!multiple) {
m_newB.setEnabled(false);
if (m_configAndPerspectives != null) {
remove(m_configAndPerspectives);
}
}
}
public boolean getAllowMultipleTabs() {
return m_allowMultipleTabs;
}
// end modifications
/**
* Notifies to the parent swt that the layout is dirty
*
* Added by Zerbetto
*/
private void notifyIsDirty() {
// this.firePropertyChange(new Integer(IEditorPart.PROP_DIRTY).toString(),
// null, null);
this.firePropertyChange("PROP_DIRTY", null, null);
}
/**
* Main method.
*
* @param args a <code>String[]</code> value
*/
public static void main(String[] args) {
LookAndFeel.setLookAndFeel();
try {
// uncomment to disable the memory management:
// m_Memory.setEnabled(false);
final javax.swing.JFrame jf = new javax.swing.JFrame();
jf.getContentPane().setLayout(new java.awt.BorderLayout());
// final KnowledgeFlowApp tm = new KnowledgeFlowApp();
// m_knowledgeFlow = new KnowledgeFlowApp(true);
for (int i = 0; i < args.length; i++) {
if (args[i].toLowerCase().endsWith(".kf")
|| args[i].toLowerCase().endsWith(".kfml")) {
args[i] = "file=" + args[i];
}
}
KnowledgeFlowApp.createSingleton(args);
Image icon = Toolkit.getDefaultToolkit().getImage(
m_knowledgeFlow.getClass().getClassLoader()
.getResource("weka/gui/weka_icon_new_48.png"));
jf.setIconImage(icon);
jf.getContentPane().add(m_knowledgeFlow, java.awt.BorderLayout.CENTER);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setSize(1024, 768);
jf.setVisible(true);
Thread memMonitor = new Thread() {
@SuppressWarnings("static-access")
@Override
public void run() {
while (true) {
// try {
// System.out.println("Before sleeping");
// this.sleep(10);
if (m_Memory.isOutOfMemory()) {
// clean up
jf.dispose();
m_knowledgeFlow = null;
System.gc();
// display error
System.err.println("\n[KnowledgeFlow] displayed message:");
m_Memory.showOutOfMemory();
System.err.println("\nexiting");
System.exit(-1);
}
// } catch (InterruptedException ex) {
// ex.printStackTrace();
// }
}
}
};
memMonitor.setPriority(Thread.NORM_PRIORITY);
memMonitor.start();
} catch (Exception ex) {
ex.printStackTrace();
System.err.println(ex.getMessage());
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.