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/Loader.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * Loader.java * Copyright (C) 2002-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.EventSetDescriptor; import java.beans.beancontext.BeanContext; import java.io.File; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectStreamException; import java.util.Vector; import javax.swing.JButton; import weka.core.Environment; import weka.core.EnvironmentHandler; import weka.core.Instance; import weka.core.Instances; import weka.core.OptionHandler; import weka.core.SerializedObject; import weka.core.Utils; import weka.core.converters.ArffLoader; import weka.core.converters.DatabaseLoader; import weka.core.converters.FileSourcedConverter; import weka.core.converters.Loader.StructureNotReadyException; import weka.gui.Logger; /** * Loads data sets using weka.core.converter classes * * @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a> * @version $Revision$ * @since 1.0 * @see AbstractDataSource * @see UserRequestAcceptor */ public class Loader extends AbstractDataSource implements Startable, WekaWrapper, EventConstraints, BeanCommon, EnvironmentHandler, StructureProducer { /** for serialization */ private static final long serialVersionUID = 1993738191961163027L; /** * Holds the instances loaded */ private transient Instances m_dataSet; /** * Holds the format of the last loaded data set */ private transient Instances m_dataFormat; /** * Global info for the wrapped loader (if it exists). */ protected String m_globalInfo; /** * Thread for doing IO in */ private LoadThread m_ioThread; private static int IDLE = 0; private static int BATCH_LOADING = 1; private static int INCREMENTAL_LOADING = 2; private int m_state = IDLE; /** * Loader */ private weka.core.converters.Loader m_Loader = new ArffLoader(); private final InstanceEvent m_ie = new InstanceEvent(this); /** * Keep track of how many listeners for different types of events there are. */ private int m_instanceEventTargets = 0; private int m_dataSetEventTargets = 0; /** Flag indicating that a database has already been configured */ private boolean m_dbSet = false; /** * Logging */ protected transient Logger m_log; /** * The environment variables. */ protected transient Environment m_env; /** * Asked to stop? */ protected boolean m_stopped = false; private class LoadThread extends Thread { private final DataSource m_DP; private StreamThroughput m_throughput; private StreamThroughput m_flowThroughput; public LoadThread(final DataSource dp) { this.m_DP = dp; } @SuppressWarnings("deprecation") @Override public void run() { String stm = Loader.this.getCustomName() + "$" + this.hashCode() + 99 + "| - overall flow throughput -|"; try { Loader.this.m_visual.setAnimated(); // m_visual.setText("Loading..."); boolean instanceGeneration = true; // determine if we are going to produce data set or instance events /* * for (int i = 0; i < m_listeners.size(); i++) { if * (m_listeners.elementAt(i) instanceof DataSourceListener) { * instanceGeneration = false; break; } } */ if (Loader.this.m_dataSetEventTargets > 0) { instanceGeneration = false; Loader.this.m_state = BATCH_LOADING; } // Set environment variables if (Loader.this.m_Loader instanceof EnvironmentHandler && Loader.this.m_env != null) { ((EnvironmentHandler) Loader.this.m_Loader).setEnvironment(Loader.this.m_env); } String msg = Loader.this.statusMessagePrefix(); if (Loader.this.m_Loader instanceof FileSourcedConverter) { msg += "Loading " + ((FileSourcedConverter) Loader.this.m_Loader).retrieveFile().getName(); } else { msg += "Loading..."; } if (Loader.this.m_log != null) { Loader.this.m_log.statusMessage(msg); } if (instanceGeneration) { this.m_throughput = new StreamThroughput(Loader.this.statusMessagePrefix()); this.m_flowThroughput = new StreamThroughput(stm, "Starting flow...", Loader.this.m_log); Loader.this.m_state = INCREMENTAL_LOADING; // boolean start = true; Instance nextInstance = null; // load and pass on the structure first Instances structure = null; Instances structureCopy = null; Instances currentStructure = null; boolean stringAttsPresent = false; try { Loader.this.m_Loader.reset(); Loader.this.m_Loader.setRetrieval(weka.core.converters.Loader.INCREMENTAL); // System.err.println("NOTIFYING STRUCTURE AVAIL"); structure = Loader.this.m_Loader.getStructure(); if (structure.checkForStringAttributes()) { structureCopy = (Instances) (new SerializedObject(structure).getObject()); stringAttsPresent = true; } currentStructure = structure; Loader.this.m_ie.m_formatNotificationOnly = false; Loader.this.notifyStructureAvailable(structure); } catch (IOException e) { if (Loader.this.m_log != null) { Loader.this.m_log.statusMessage(Loader.this.statusMessagePrefix() + "ERROR (See log for details"); Loader.this.m_log.logMessage("[Loader] " + Loader.this.statusMessagePrefix() + " " + e.getMessage()); } e.printStackTrace(); } try { nextInstance = Loader.this.m_Loader.getNextInstance(structure); } catch (IOException e) { if (Loader.this.m_log != null) { Loader.this.m_log.statusMessage(Loader.this.statusMessagePrefix() + "ERROR (See log for details"); Loader.this.m_log.logMessage("[Loader] " + Loader.this.statusMessagePrefix() + " " + e.getMessage()); } e.printStackTrace(); } while (nextInstance != null) { if (Loader.this.m_stopped) { break; } this.m_throughput.updateStart(); this.m_flowThroughput.updateStart(); // nextInstance.setDataset(structure); // format.add(nextInstance); /* * InstanceEvent ie = (start) ? new InstanceEvent(m_DP, * nextInstance, InstanceEvent.FORMAT_AVAILABLE) : new * InstanceEvent(m_DP, nextInstance, * InstanceEvent.INSTANCE_AVAILABLE); */ // if (start) { // m_ie.setStatus(InstanceEvent.FORMAT_AVAILABLE); // } else { Loader.this.m_ie.setStatus(InstanceEvent.INSTANCE_AVAILABLE); // } Loader.this.m_ie.setInstance(nextInstance); // start = false; // System.err.println(z); // a little jiggery pokery to ensure that our // one instance lookahead to determine whether // this instance is the end of the batch doesn't // clobber any string values in the current // instance, if the loader is loading them // incrementally (i.e. only retaining one // value in the header at any one time). if (stringAttsPresent) { if (currentStructure == structure) { currentStructure = structureCopy; } else { currentStructure = structure; } } nextInstance = Loader.this.m_Loader.getNextInstance(currentStructure); if (nextInstance == null) { Loader.this.m_ie.setStatus(InstanceEvent.BATCH_FINISHED); } this.m_throughput.updateEnd(Loader.this.m_log); Loader.this.notifyInstanceLoaded(Loader.this.m_ie); this.m_flowThroughput.updateEnd(Loader.this.m_log); } Loader.this.m_visual.setStatic(); // m_visual.setText(structure.relationName()); } else { Loader.this.m_Loader.reset(); Loader.this.m_Loader.setRetrieval(weka.core.converters.Loader.BATCH); Loader.this.m_dataSet = Loader.this.m_Loader.getDataSet(); Loader.this.m_visual.setStatic(); if (Loader.this.m_log != null) { Loader.this.m_log.logMessage("[Loader] " + Loader.this.statusMessagePrefix() + " loaded " + Loader.this.m_dataSet.relationName()); } // m_visual.setText(m_dataSet.relationName()); Loader.this.notifyDataSetLoaded(new DataSetEvent(this.m_DP, Loader.this.m_dataSet)); } } catch (Exception ex) { if (Loader.this.m_log != null) { Loader.this.m_log.statusMessage(Loader.this.statusMessagePrefix() + "ERROR (See log for details"); Loader.this.m_log.logMessage("[Loader] " + Loader.this.statusMessagePrefix() + " " + ex.getMessage()); } ex.printStackTrace(); } finally { if (Thread.currentThread().isInterrupted()) { if (Loader.this.m_log != null) { Loader.this.m_log.logMessage("[Loader] " + Loader.this.statusMessagePrefix() + " loading interrupted!"); } } Loader.this.m_ioThread = null; // m_visual.setText("Finished"); // m_visual.setIcon(m_inactive.getVisual()); Loader.this.m_visual.setStatic(); Loader.this.m_state = IDLE; Loader.this.m_stopped = false; if (Loader.this.m_log != null) { if (this.m_throughput != null) { String finalMessage = this.m_throughput.finished() + " (read speed); "; this.m_flowThroughput.finished(Loader.this.m_log); Loader.this.m_log.statusMessage(stm + "remove"); int flowSpeed = this.m_flowThroughput.getAverageInstancesPerSecond(); finalMessage += ("" + flowSpeed + " insts/sec (flow throughput)"); Loader.this.m_log.statusMessage(Loader.this.statusMessagePrefix() + finalMessage); } else { Loader.this.m_log.statusMessage(Loader.this.statusMessagePrefix() + "Finished."); } } Loader.this.block(false); } } } /** * Global info (if it exists) for the wrapped loader * * @return the global info */ public String globalInfo() { return this.m_globalInfo; } public Loader() { super(); this.setLoader(this.m_Loader); this.appearanceFinal(); } public void setDB(final boolean flag) { this.m_dbSet = flag; if (this.m_dbSet) { try { this.newStructure(); } catch (Exception e) { e.printStackTrace(); } } } protected void appearanceFinal() { this.removeAll(); this.setLayout(new BorderLayout()); JButton goButton = new JButton("Start..."); this.add(goButton, BorderLayout.CENTER); goButton.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { Loader.this.startLoading(); } }); } protected void appearanceDesign() { this.removeAll(); this.setLayout(new BorderLayout()); this.add(this.m_visual, BorderLayout.CENTER); } /** * Set a bean context for this bean * * @param bc a <code>BeanContext</code> value */ @Override public void setBeanContext(final BeanContext bc) { super.setBeanContext(bc); if (this.m_design) { this.appearanceDesign(); } else { this.appearanceFinal(); } } /** * Set the loader to use * * @param loader a <code>weka.core.converters.Loader</code> value */ public void setLoader(final weka.core.converters.Loader loader) { boolean loadImages = true; if (loader.getClass().getName().compareTo(this.m_Loader.getClass().getName()) == 0) { loadImages = false; } this.m_Loader = loader; String loaderName = loader.getClass().toString(); loaderName = loaderName.substring(loaderName.lastIndexOf('.') + 1, loaderName.length()); if (loadImages) { if (this.m_Loader instanceof Visible) { this.m_visual = ((Visible) this.m_Loader).getVisual(); } else { if (!this.m_visual.loadIcons(BeanVisual.ICON_PATH + loaderName + ".gif", BeanVisual.ICON_PATH + loaderName + "_animated.gif")) { this.useDefaultVisual(); } } } this.m_visual.setText(loaderName); // get global info this.m_globalInfo = KnowledgeFlowApp.getGlobalInfo(this.m_Loader); } protected void newFileSelected() throws Exception { if (!(this.m_Loader instanceof DatabaseLoader)) { this.newStructure(true); /* * // try to load structure (if possible) and notify any listeners * * // Set environment variables if (m_Loader instanceof EnvironmentHandler * && m_env != null) { try { * ((EnvironmentHandler)m_Loader).setEnvironment(m_env); }catch (Exception * ex) { } } m_dataFormat = m_Loader.getStructure(); // * System.err.println(m_dataFormat); System.out.println( * "[Loader] Notifying listeners of instance structure avail."); * notifyStructureAvailable(m_dataFormat); */ } } protected void newStructure(final boolean... notificationOnly) throws Exception { if (notificationOnly != null && notificationOnly.length > 0) { // If incremental then specify whether this FORMAT_AVAILABLE // event is actually the start of stream processing or just // due to a file/source change this.m_ie.m_formatNotificationOnly = notificationOnly[0]; } else { this.m_ie.m_formatNotificationOnly = false; } try { this.m_Loader.reset(); // Set environment variables if (this.m_Loader instanceof EnvironmentHandler && this.m_env != null) { try { ((EnvironmentHandler) this.m_Loader).setEnvironment(this.m_env); } catch (Exception ex) { } } this.m_dataFormat = this.m_Loader.getStructure(); System.out.println("[Loader] Notifying listeners of instance structure avail."); this.notifyStructureAvailable(this.m_dataFormat); } catch (StructureNotReadyException e) { if (this.m_log != null) { this.m_log.statusMessage(this.statusMessagePrefix() + "WARNING: " + e.getMessage()); this.m_log.logMessage("[Loader] " + this.statusMessagePrefix() + " " + e.getMessage()); } } } /** * 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(final String eventName) { if (!eventName.equals("dataSet") && !eventName.equals("instance")) { return null; } if (this.m_dataSetEventTargets > 0 && !eventName.equals("dataSet")) { return null; } if (this.m_dataSetEventTargets == 0 && !eventName.equals("instance")) { return null; } try { this.newStructure(); } catch (Exception ex) { // ex.printStackTrace(); System.err.println("[KnowledgeFlow/Loader] Warning: " + ex.getMessage()); this.m_dataFormat = null; } return this.m_dataFormat; } /** * Get the loader * * @return a <code>weka.core.converters.Loader</code> value */ public weka.core.converters.Loader getLoader() { return this.m_Loader; } /** * Set the loader * * @param algorithm a Loader * @exception IllegalArgumentException if an error occurs */ @Override public void setWrappedAlgorithm(final Object algorithm) { if (!(algorithm instanceof weka.core.converters.Loader)) { throw new IllegalArgumentException(algorithm.getClass() + " : incorrect " + "type of algorithm (Loader)"); } this.setLoader((weka.core.converters.Loader) algorithm); } /** * Get the loader * * @return a Loader */ @Override public Object getWrappedAlgorithm() { return this.getLoader(); } /** * Notify all listeners that the structure of a data set is available. * * @param structure an <code>Instances</code> value */ protected void notifyStructureAvailable(final Instances structure) { if (this.m_dataSetEventTargets > 0 && structure != null) { DataSetEvent dse = new DataSetEvent(this, structure); this.notifyDataSetLoaded(dse); } else if (this.m_instanceEventTargets > 0 && structure != null) { this.m_ie.setStructure(structure); this.notifyInstanceLoaded(this.m_ie); } } /** * Notify all Data source listeners that a data set has been loaded * * @param e a <code>DataSetEvent</code> value */ @SuppressWarnings("unchecked") protected void notifyDataSetLoaded(final DataSetEvent e) { Vector<DataSourceListener> l; synchronized (this) { l = (Vector<DataSourceListener>) this.m_listeners.clone(); } if (l.size() > 0) { for (int i = 0; i < l.size(); i++) { l.elementAt(i).acceptDataSet(e); } this.m_dataSet = null; } } /** * Notify all instance listeners that a new instance is available * * @param e an <code>InstanceEvent</code> value */ @SuppressWarnings("unchecked") protected void notifyInstanceLoaded(final InstanceEvent e) { Vector<InstanceListener> l; synchronized (this) { l = (Vector<InstanceListener>) this.m_listeners.clone(); } if (l.size() > 0) { for (int i = 0; i < l.size(); i++) { l.elementAt(i).acceptInstance(e); } this.m_dataSet = null; } } /** * Start loading data */ public void startLoading() { if (this.m_ioThread == null) { // m_visual.setText(m_dataSetFile.getName()); this.m_state = BATCH_LOADING; this.m_stopped = false; this.m_ioThread = new LoadThread(Loader.this); this.m_ioThread.setPriority(Thread.MIN_PRIORITY); this.m_ioThread.start(); } else { this.m_ioThread = null; this.m_state = IDLE; } } /** * Get a list of user requests * * @return an <code>Enumeration</code> value */ /* * public Enumeration enumerateRequests() { Vector newVector = new Vector(0); * boolean ok = true; if (m_ioThread == null) { if (m_Loader instanceof * FileSourcedConverter) { String temp = ((FileSourcedConverter) * m_Loader).retrieveFile().getPath(); Environment env = (m_env == null) ? * Environment.getSystemWide() : m_env; try { temp = env.substitute(temp); } * catch (Exception ex) {} File tempF = new File(temp); if (!tempF.isFile()) { * ok = false; } } String entry = "Start loading"; if (!ok) { entry = * "$"+entry; } newVector.addElement(entry); } return newVector.elements(); } */ /** * Perform the named request * * @param request a <code>String</code> value * @exception IllegalArgumentException if an error occurs */ /* * public void performRequest(String request) { if * (request.compareTo("Start loading") == 0) { startLoading(); } else { throw * new IllegalArgumentException(request + " not supported (Loader)"); } } */ /** * Start loading * * @exception Exception if something goes wrong */ @Override public void start() throws Exception { this.startLoading(); this.block(true); } /** * Gets a string that describes the start action. The KnowledgeFlow uses this * in the popup contextual menu for the component. The string can be proceeded * by a '$' character to indicate that the component can't be started at * present. * * @return a string describing the start action. */ @Override public String getStartMessage() { boolean ok = true; String entry = "Start loading"; if (this.m_ioThread == null) { if (this.m_Loader instanceof FileSourcedConverter) { String temp = ((FileSourcedConverter) this.m_Loader).retrieveFile().getPath(); Environment env = (this.m_env == null) ? Environment.getSystemWide() : this.m_env; try { temp = env.substitute(temp); } catch (Exception ex) { } File tempF = new File(temp); // forward slashes are platform independent for resources read from the // classpath String tempFixedPathSepForResource = temp.replace(File.separatorChar, '/'); if (!tempF.isFile() && this.getClass().getClassLoader().getResource(tempFixedPathSepForResource) == null) { ok = false; } } if (!ok) { entry = "$" + entry; } } return entry; } /** * 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(final boolean tf) { if (tf) { try { // only block if thread is still doing something useful! if (this.m_ioThread.isAlive() && this.m_state != IDLE) { this.wait(); } } catch (InterruptedException ex) { } } else { this.notifyAll(); } } /** * Returns true if the named event can be generated at this time * * @param eventName the event * @return a <code>boolean</code> value */ @Override public boolean eventGeneratable(final String eventName) { if (eventName.compareTo("instance") == 0) { if (!(this.m_Loader instanceof weka.core.converters.IncrementalConverter)) { return false; } if (this.m_dataSetEventTargets > 0) { return false; } /* * for (int i = 0; i < m_listeners.size(); i++) { if * (m_listeners.elementAt(i) instanceof DataSourceListener) { return * false; } } */ } if (eventName.compareTo("dataSet") == 0) { if (!(this.m_Loader instanceof weka.core.converters.BatchConverter)) { return false; } if (this.m_instanceEventTargets > 0) { return false; } /* * for (int i = 0; i < m_listeners.size(); i++) { if * (m_listeners.elementAt(i) instanceof InstanceListener) { return false; * } } */ } return true; } /** * Add a listener * * @param dsl a <code>DataSourceListener</code> value */ @Override public synchronized void addDataSourceListener(final DataSourceListener dsl) { super.addDataSourceListener(dsl); this.m_dataSetEventTargets++; // pass on any current instance format try { if ((this.m_Loader instanceof DatabaseLoader && this.m_dbSet && this.m_dataFormat == null) || (!(this.m_Loader instanceof DatabaseLoader) && this.m_dataFormat == null)) { this.m_dataFormat = this.m_Loader.getStructure(); this.m_dbSet = false; } } catch (Exception ex) { } this.notifyStructureAvailable(this.m_dataFormat); } /** * Remove a listener * * @param dsl a <code>DataSourceListener</code> value */ @Override public synchronized void removeDataSourceListener(final DataSourceListener dsl) { super.removeDataSourceListener(dsl); this.m_dataSetEventTargets--; } /** * Add an instance listener * * @param dsl a <code>InstanceListener</code> value */ @Override public synchronized void addInstanceListener(final InstanceListener dsl) { super.addInstanceListener(dsl); this.m_instanceEventTargets++; try { if ((this.m_Loader instanceof DatabaseLoader && this.m_dbSet && this.m_dataFormat == null) || (!(this.m_Loader instanceof DatabaseLoader) && this.m_dataFormat == null)) { this.m_dataFormat = this.m_Loader.getStructure(); this.m_dbSet = false; } } catch (Exception ex) { } // pass on any current instance format this.m_ie.m_formatNotificationOnly = true; this.notifyStructureAvailable(this.m_dataFormat); } /** * Remove an instance listener * * @param dsl a <code>InstanceListener</code> value */ @Override public synchronized void removeInstanceListener(final InstanceListener dsl) { super.removeInstanceListener(dsl); this.m_instanceEventTargets--; } public static void main(final String[] args) { try { final javax.swing.JFrame jf = new javax.swing.JFrame(); jf.getContentPane().setLayout(new java.awt.BorderLayout()); final Loader tv = new Loader(); jf.getContentPane().add(tv, java.awt.BorderLayout.CENTER); jf.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(final java.awt.event.WindowEvent e) { jf.dispose(); System.exit(0); } }); jf.setSize(800, 600); jf.setVisible(true); } catch (Exception ex) { ex.printStackTrace(); } } private Object readResolve() throws ObjectStreamException { // try and reset the Loader if (this.m_Loader != null) { try { this.m_Loader.reset(); } catch (Exception ex) { } } return this; } /** * 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(); } /** * Set a logger * * @param logger a <code>weka.gui.Logger</code> value */ @Override public void setLog(final Logger logger) { this.m_log = logger; } /** * Set environment variables to use. * * @param env the environment variables to use */ @Override public void setEnvironment(final Environment env) { this.m_env = env; } /** * Returns true if, at this time, the object will accept a connection via the * supplied EventSetDescriptor. Always returns false for loader. * * @param esd the EventSetDescriptor * @return true if the object will accept a connection */ @Override public boolean connectionAllowed(final EventSetDescriptor esd) { return false; } /** * 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) { return false; } /** * Notify this object that it has been registered as a listener with a source * for receiving 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) { // this should never get called for us. } /** * 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 should never get called for us. } /** * Stop any loading action. */ @Override public void stop() { this.m_stopped = 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() { return (this.m_ioThread != null); } private String statusMessagePrefix() { return this.getCustomName() + "$" + this.hashCode() + "|" + ((this.m_Loader instanceof OptionHandler) ? Utils.joinOptions(((OptionHandler) this.m_Loader).getOptions()) + "|" : ""); } // Custom de-serialization in order to set default // environment variables on de-serialization private void readObject(final ObjectInputStream aStream) throws IOException, ClassNotFoundException { aStream.defaultReadObject(); // set a default environment to use this.m_env = Environment.getSystemWide(); } }
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/LoaderBeanInfo.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * LoaderBeanInfo.java * Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.beans; import java.beans.BeanDescriptor; /** * Bean info class for the loader bean * * @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a> * @version $Revision$ */ public class LoaderBeanInfo extends AbstractDataSourceBeanInfo { /** * Get the bean descriptor for this bean * * @return a <code>BeanDescriptor</code> value */ public BeanDescriptor getBeanDescriptor() { return new BeanDescriptor(weka.gui.beans.Loader.class, LoaderCustomizer.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/LoaderCustomizer.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * LoaderCustomizer.java * Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.beans; import java.awt.BorderLayout; import java.awt.Dialog.ModalityType; import java.awt.FlowLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.File; import java.util.Arrays; import javax.swing.*; import weka.core.Environment; import weka.core.EnvironmentHandler; import weka.core.converters.DatabaseConverter; import weka.core.converters.DatabaseLoader; import weka.core.converters.FileSourcedConverter; import weka.gui.ExtensionFileFilter; import weka.gui.GenericObjectEditor; import weka.gui.PropertySheetPanel; /** * GUI Customizer for the loader bean * * @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a> * @version $Revision$ */ public class LoaderCustomizer extends JPanel implements BeanCustomizer, CustomizerCloseRequester, EnvironmentHandler { /** for serialization */ private static final long serialVersionUID = 6990446313118930298L; static { GenericObjectEditor.registerEditors(); } private final PropertyChangeSupport m_pcSupport = new PropertyChangeSupport( this); private weka.gui.beans.Loader m_dsLoader; private final PropertySheetPanel m_LoaderEditor = new PropertySheetPanel(); private final JFileChooser m_fileChooser = new JFileChooser(new File( System.getProperty("user.dir"))); /* * private JDialog m_chooserDialog = new * JDialog((JFrame)getTopLevelAncestor(), true); */ private Window m_parentWindow; private JDialog m_fileChooserFrame; private EnvironmentField m_dbaseURLText; private EnvironmentField m_userNameText; private EnvironmentField m_queryText; private EnvironmentField m_keyText; private JPasswordField m_passwordText; // private JCheckBox m_relativeFilePath; NOT USED private EnvironmentField m_fileText; private Environment m_env = Environment.getSystemWide(); private FileEnvironmentField m_dbProps; private ModifyListener m_modifyListener; private weka.core.converters.Loader m_backup = null; public LoaderCustomizer() { /* * m_fileEditor.addPropertyChangeListener(new PropertyChangeListener() { * public void propertyChange(PropertyChangeEvent e) { if (m_dsLoader != * null) { m_dsLoader.setDataSetFile((File)m_fileEditor.getValue()); } } }); */ /* * try { m_LoaderEditor.addPropertyChangeListener( new * PropertyChangeListener() { public void propertyChange(PropertyChangeEvent * e) { repaint(); if (m_dsLoader != null) { * //System.err.println("Property change!!"); * m_dsLoader.setLoader(m_dsLoader.getLoader()); } } }); repaint(); } catch * (Exception ex) { ex.printStackTrace(); } */ setLayout(new BorderLayout()); // add(m_fileEditor.getCustomEditor(), BorderLayout.CENTER); // add(m_LoaderEditor, BorderLayout.CENTER); m_fileChooser.setDialogType(JFileChooser.OPEN_DIALOG); m_fileChooser.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals(JFileChooser.APPROVE_SELECTION)) { try { File selectedFile = m_fileChooser.getSelectedFile(); /* * EnvironmentField ef = m_environmentFields.get(0); * ef.setText(selectedFile.toString()); */ m_fileText.setText(selectedFile.toString()); /* * ((FileSourcedConverter)m_dsLoader.getLoader()). * setFile(selectedFile); // tell the loader that a new file has * been selected so // that it can attempt to load the header * //m_dsLoader.setLoader(m_dsLoader.getLoader()); * m_dsLoader.newFileSelected(); */ } catch (Exception ex) { ex.printStackTrace(); } } // closing if (m_fileChooserFrame != null) { m_fileChooserFrame.dispose(); } } }); } @Override public void setParentWindow(Window parent) { m_parentWindow = parent; } private void setUpOther() { removeAll(); add(m_LoaderEditor, BorderLayout.CENTER); JPanel buttonsP = new JPanel(); buttonsP.setLayout(new FlowLayout()); JButton ok, cancel; buttonsP.add(ok = new JButton("OK")); buttonsP.add(cancel = new JButton("Cancel")); ok.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { // 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_LoaderEditor.closingOK(); // make sure that the beans.Loader passes any changed structure // downstream try { m_dsLoader.newStructure(true); } catch (Exception e) { e.printStackTrace(); } if (m_parentWindow != null) { m_parentWindow.dispose(); } } }); cancel.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { // 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_LoaderEditor.closingCancel(); if (m_parentWindow != null) { m_parentWindow.dispose(); } } }); add(buttonsP, BorderLayout.SOUTH); validate(); repaint(); } /** Sets up a customizer window for a Database Connection */ private void setUpDatabase() { removeAll(); JPanel db = new JPanel(); GridBagLayout gbLayout = new GridBagLayout(); // db.setLayout(new GridLayout(6, 1)); db.setLayout(gbLayout); JLabel urlLab = new JLabel("Database URL", SwingConstants.RIGHT); urlLab.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0)); GridBagConstraints gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 0; gbConstraints.gridx = 0; gbLayout.setConstraints(urlLab, gbConstraints); db.add(urlLab); m_dbaseURLText = new EnvironmentField(); m_dbaseURLText.setEnvironment(m_env); /* * int width = m_dbaseURLText.getPreferredSize().width; int height = * m_dbaseURLText.getPreferredSize().height; * m_dbaseURLText.setMinimumSize(new Dimension(width * 2, height)); * m_dbaseURLText.setPreferredSize(new Dimension(width * 2, height)); */ m_dbaseURLText.setText(((DatabaseConverter) m_dsLoader.getLoader()) .getUrl()); gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 0; gbConstraints.gridx = 1; gbConstraints.weightx = 5; gbLayout.setConstraints(m_dbaseURLText, gbConstraints); db.add(m_dbaseURLText); JLabel userLab = new JLabel("Username", SwingConstants.RIGHT); userLab.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0)); gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 1; gbConstraints.gridx = 0; gbLayout.setConstraints(userLab, gbConstraints); db.add(userLab); m_userNameText = new EnvironmentField(); m_userNameText.setEnvironment(m_env); /* * m_userNameText.setMinimumSize(new Dimension(width * 2, height)); * m_userNameText.setPreferredSize(new Dimension(width * 2, height)); */ m_userNameText.setText(((DatabaseConverter) m_dsLoader.getLoader()) .getUser()); gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 1; gbConstraints.gridx = 1; gbLayout.setConstraints(m_userNameText, gbConstraints); db.add(m_userNameText); JLabel passwordLab = new JLabel("Password ", SwingConstants.RIGHT); passwordLab.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0)); gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 2; gbConstraints.gridx = 0; gbLayout.setConstraints(passwordLab, gbConstraints); db.add(passwordLab); m_passwordText = new JPasswordField(); m_passwordText.setText(((DatabaseLoader) m_dsLoader.getLoader()) .getPassword()); JPanel passwordHolder = new JPanel(); passwordHolder.setLayout(new BorderLayout()); passwordHolder.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); // passwordHolder.add(passwordLab, BorderLayout.WEST); passwordHolder.add(m_passwordText, BorderLayout.CENTER); /* * passwordHolder.setMinimumSize(new Dimension(width * 2, height)); * passwordHolder.setPreferredSize(new Dimension(width * 2, height)); */ gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 2; gbConstraints.gridx = 1; gbLayout.setConstraints(passwordHolder, gbConstraints); db.add(passwordHolder); JLabel queryLab = new JLabel("Query", SwingConstants.RIGHT); queryLab.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0)); gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 3; gbConstraints.gridx = 0; gbLayout.setConstraints(queryLab, gbConstraints); db.add(queryLab); m_queryText = new EnvironmentField(); m_queryText.setEnvironment(m_env); /* * m_queryText.setMinimumSize(new Dimension(width * 2, height)); * m_queryText.setPreferredSize(new Dimension(width * 2, height)); */ m_queryText.setText(((DatabaseLoader) m_dsLoader.getLoader()).getQuery()); gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 3; gbConstraints.gridx = 1; gbLayout.setConstraints(m_queryText, gbConstraints); db.add(m_queryText); JLabel keyLab = new JLabel("Key columns", SwingConstants.RIGHT); keyLab.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0)); gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 4; gbConstraints.gridx = 0; gbLayout.setConstraints(keyLab, gbConstraints); db.add(keyLab); m_keyText = new EnvironmentField(); m_keyText.setEnvironment(m_env); /* * m_keyText.setMinimumSize(new Dimension(width * 2, height)); * m_keyText.setPreferredSize(new Dimension(width * 2, height)); */ m_keyText.setText(((DatabaseLoader) m_dsLoader.getLoader()).getKeys()); gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 4; gbConstraints.gridx = 1; gbLayout.setConstraints(m_keyText, gbConstraints); db.add(m_keyText); JLabel propsLab = new JLabel("DB config props", SwingConstants.RIGHT); propsLab .setToolTipText("The custom properties that the user can use to override the default ones."); propsLab.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0)); gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 5; gbConstraints.gridx = 0; gbLayout.setConstraints(propsLab, gbConstraints); db.add(propsLab); m_dbProps = new FileEnvironmentField(); m_dbProps.setEnvironment(m_env); m_dbProps.resetFileFilters(); m_dbProps.addFileFilter(new ExtensionFileFilter(".props", "DatabaseUtils property file (*.props)")); gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 5; gbConstraints.gridx = 1; gbLayout.setConstraints(m_dbProps, gbConstraints); db.add(m_dbProps); File toSet = ((DatabaseLoader) m_dsLoader.getLoader()).getCustomPropsFile(); if (toSet != null) { m_dbProps.setText(toSet.getPath()); } JButton loadPropsBut = new JButton("Load"); loadPropsBut.setToolTipText("Load config"); gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 5; gbConstraints.gridx = 2; gbLayout.setConstraints(loadPropsBut, gbConstraints); db.add(loadPropsBut); loadPropsBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (m_dbProps.getText() != null && m_dbProps.getText().length() > 0) { String propsS = m_dbProps.getText(); try { propsS = m_env.substitute(propsS); } catch (Exception ex) { } File propsFile = new File(propsS); if (propsFile.exists()) { ((DatabaseLoader) m_dsLoader.getLoader()) .setCustomPropsFile(propsFile); ((DatabaseLoader) m_dsLoader.getLoader()).resetOptions(); m_dbaseURLText.setText(((DatabaseLoader) m_dsLoader.getLoader()) .getUrl()); } } } }); JPanel buttonsP = new JPanel(); buttonsP.setLayout(new FlowLayout()); JButton ok, cancel; buttonsP.add(ok = new JButton("OK")); buttonsP.add(cancel = new JButton("Cancel")); ok.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { /* * ((DatabaseLoader)m_dsLoader.getLoader()).resetStructure(); * ((DatabaseConverter * )m_dsLoader.getLoader()).setUrl(m_dbaseURLText.getText()); * ((DatabaseConverter * )m_dsLoader.getLoader()).setUser(m_userNameText.getText()); * ((DatabaseConverter)m_dsLoader.getLoader()).setPassword(new * String(m_passwordText.getPassword())); * ((DatabaseLoader)m_dsLoader.getLoader * ()).setQuery(m_queryText.getText()); * ((DatabaseLoader)m_dsLoader.getLoader * ()).setKeys(m_keyText.getText()); */ if (resetAndUpdateDatabaseLoaderIfChanged()) { try { // m_dsLoader.notifyStructureAvailable(((DatabaseLoader)m_dsLoader.getLoader()).getStructure()); // database connection has been configured m_dsLoader.setDB(true); } catch (Exception ex) { } } if (m_parentWindow != null) { m_parentWindow.dispose(); } } }); cancel.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { if (m_backup != null) { m_dsLoader.setLoader(m_backup); } if (m_parentWindow != null) { m_parentWindow.dispose(); } } }); JPanel holderP = new JPanel(); holderP.setLayout(new BorderLayout()); holderP.add(db, BorderLayout.NORTH); holderP.add(buttonsP, BorderLayout.SOUTH); // db.add(buttonsP); JPanel about = m_LoaderEditor.getAboutPanel(); if (about != null) { add(about, BorderLayout.NORTH); } add(holderP, BorderLayout.SOUTH); } private boolean resetAndUpdateDatabaseLoaderIfChanged() { DatabaseLoader dbl = (DatabaseLoader) m_dsLoader.getLoader(); String url = dbl.getUrl(); String user = dbl.getUser(); String password = dbl.getPassword(); String query = dbl.getQuery(); String keys = dbl.getKeys(); File propsFile = dbl.getCustomPropsFile(); boolean update = (!url.equals(m_dbaseURLText.getText()) || !user.equals(m_userNameText.getText()) || !Arrays.equals(password.toCharArray(), m_passwordText.getPassword()) || !query.equalsIgnoreCase(m_queryText.getText()) || !keys .equals(m_keyText.getText())); if (propsFile != null && m_dbProps.getText().length() > 0) { update = (update || !propsFile.toString().equals(m_dbProps.getText())); } else { update = (update || m_dbProps.getText().length() > 0); } if (update) { dbl.resetStructure(); dbl.setUrl(m_dbaseURLText.getText()); dbl.setUser(m_userNameText.getText()); dbl.setPassword(new String(m_passwordText.getPassword())); dbl.setQuery(m_queryText.getText()); dbl.setKeys(m_keyText.getText()); if (m_dbProps.getText() != null && m_dbProps.getText().length() > 0) { dbl.setCustomPropsFile(new File(m_dbProps.getText())); } } return update; } public void setUpFile() { removeAll(); boolean currentFileIsDir = false; File tmp = ((FileSourcedConverter) m_dsLoader.getLoader()).retrieveFile(); String tmpString = tmp.toString(); if (Environment.containsEnvVariables(tmpString)) { try { tmpString = m_env.substitute(tmpString); } catch (Exception ex) { // ignore } } File tmp2 = new File((new File(tmpString)).getAbsolutePath()); if (tmp2.isDirectory()) { m_fileChooser.setCurrentDirectory(tmp2); currentFileIsDir = true; } else { m_fileChooser.setSelectedFile(tmp2); } FileSourcedConverter loader = (FileSourcedConverter) m_dsLoader.getLoader(); String[] ext = loader.getFileExtensions(); ExtensionFileFilter firstFilter = null; for (int i = 0; i < ext.length; i++) { ExtensionFileFilter ff = new ExtensionFileFilter(ext[i], loader.getFileDescription() + " (*" + ext[i] + ")"); if (i == 0) { firstFilter = ff; } m_fileChooser.addChoosableFileFilter(ff); } if (firstFilter != null) { m_fileChooser.setFileFilter(firstFilter); } JPanel about = m_LoaderEditor.getAboutPanel(); JPanel northPanel = new JPanel(); northPanel.setLayout(new BorderLayout()); if (about != null) { northPanel.add(about, BorderLayout.NORTH); } add(northPanel, BorderLayout.NORTH); final EnvironmentField ef = new EnvironmentField(); JPanel efHolder = new JPanel(); efHolder.setLayout(new BorderLayout()); ef.setEnvironment(m_env); /* * int width = ef.getPreferredSize().width; int height = * ef.getPreferredSize().height; // ef.setMinimumSize(new Dimension(width * * 2, height)); ef.setPreferredSize(new Dimension(width * 2, height)); */ m_fileText = ef; // only set the text on the EnvironmentField if the current file is not a // directory if (!currentFileIsDir) { ef.setText(tmp.toString()); } efHolder.add(ef, BorderLayout.CENTER); JButton browseBut = new JButton("Browse..."); browseBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { // final JFrame jf = new JFrame("Choose file"); final JDialog jf = new JDialog((JDialog) LoaderCustomizer.this .getTopLevelAncestor(), "Choose file", ModalityType.DOCUMENT_MODAL); jf.setLayout(new BorderLayout()); // jf.getContentPane().setLayout(new BorderLayout()); jf.getContentPane().add(m_fileChooser, BorderLayout.CENTER); m_fileChooserFrame = jf; jf.pack(); jf.setLocationRelativeTo(SwingUtilities.getWindowAncestor(LoaderCustomizer.this)); jf.setVisible(true); } catch (Exception ex) { ex.printStackTrace(); } } }); JPanel bP = new JPanel(); bP.setLayout(new BorderLayout()); bP.setBorder(BorderFactory.createEmptyBorder(5, 0, 5, 5)); bP.add(browseBut, BorderLayout.CENTER); efHolder.add(bP, BorderLayout.EAST); JPanel alignedP = new JPanel(); alignedP.setBorder(BorderFactory.createTitledBorder("File")); alignedP.setLayout(new BorderLayout()); JLabel efLab = new JLabel("Filename", SwingConstants.RIGHT); efLab.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0)); alignedP.add(efLab, BorderLayout.WEST); alignedP.add(efHolder, BorderLayout.CENTER); northPanel.add(alignedP, BorderLayout.SOUTH); JPanel butHolder = new JPanel(); // butHolder.setLayout(new GridLayout(1,2)); butHolder.setLayout(new FlowLayout()); JButton OKBut = new JButton("OK"); OKBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { ((FileSourcedConverter) m_dsLoader.getLoader()).setFile(new File(ef .getText())); // tell the loader that a new file has been selected so // that it can attempt to load the header // m_dsLoader.setLoader(m_dsLoader.getLoader()); m_dsLoader.newFileSelected(); } catch (Exception ex) { ex.printStackTrace(); } if (m_modifyListener != null) { m_modifyListener.setModifiedStatus(LoaderCustomizer.this, true); } m_parentWindow.dispose(); } }); JButton CancelBut = new JButton("Cancel"); CancelBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (m_modifyListener != null) { m_modifyListener.setModifiedStatus(LoaderCustomizer.this, false); } if (m_backup != null) { m_dsLoader.setLoader(m_backup); } m_parentWindow.dispose(); } }); butHolder.add(OKBut); butHolder.add(CancelBut); JPanel optionsHolder = new JPanel(); optionsHolder.setLayout(new BorderLayout()); optionsHolder.setBorder(BorderFactory.createTitledBorder("Other options")); optionsHolder.add(m_LoaderEditor, BorderLayout.SOUTH); JScrollPane scroller = new JScrollPane(optionsHolder); add(scroller, BorderLayout.CENTER); add(butHolder, BorderLayout.SOUTH); } /** * Set the loader to be customized * * @param object a weka.gui.beans.Loader */ @Override public void setObject(Object object) { m_dsLoader = (weka.gui.beans.Loader) object; try { m_backup = (weka.core.converters.Loader) GenericObjectEditor .makeCopy(m_dsLoader.getLoader()); } catch (Exception ex) { // ignore } m_LoaderEditor.setTarget(m_dsLoader.getLoader()); // m_fileEditor.setValue(m_dsLoader.getDataSetFile()); m_LoaderEditor.setEnvironment(m_env); if (m_dsLoader.getLoader() instanceof FileSourcedConverter) { setUpFile(); } else { if (m_dsLoader.getLoader() instanceof DatabaseConverter) { setUpDatabase(); } else { setUpOther(); } } } @Override public void setEnvironment(Environment env) { m_env = env; } /** * 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; } }
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/LogPanel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * LogPanel * Copyright (C) 2008-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.beans; import weka.gui.Logger; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.JTable; import javax.swing.SwingUtilities; import javax.swing.Timer; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableCellRenderer; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.DecimalFormat; import java.util.HashMap; import java.util.Iterator; /** * Class for displaying a status area (made up of a variable number of lines) * and a log area. * * @author mhall (mhall{[at]}pentaho{[dot]}com) * @version $Revision$ */ public class LogPanel extends JPanel implements Logger { /** Added ID to avoid warning */ private static final long serialVersionUID = 6583097154513435548L; /** * Holds the index (line number) in the JTable of each component being * tracked. */ protected HashMap<String, Integer> m_tableIndexes = new HashMap<String, Integer>(); /** * Holds the timers associated with each component being tracked. */ private final HashMap<String, Timer> m_timers = new HashMap<String, Timer>(); /** * The table model for the JTable used in the status area */ private final DefaultTableModel m_tableModel; /** * The table for the status area */ private JTable m_table; /** * Tabbed pane to hold both the status and the log */ private final JTabbedPane m_tabs = new JTabbedPane(); /** * For formatting timer digits */ private final DecimalFormat m_formatter = new DecimalFormat("00"); /** * The log panel to delegate log messages to. */ private final weka.gui.LogPanel m_logPanel = new weka.gui.LogPanel(null, false, true, false); public LogPanel() { String[] columnNames = { "Component", "Parameters", "Time", "Status" }; m_tableModel = new DefaultTableModel(columnNames, 0); // JTable with error/warning indication for rows. m_table = new JTable() { /** Added ID to avoid warning */ private static final long serialVersionUID = 5883722364387855125L; @Override public Class<?> getColumnClass(int column) { return getValueAt(0, column).getClass(); } @Override public Component prepareRenderer(TableCellRenderer renderer, int row, int column) { Component c = super.prepareRenderer(renderer, row, column); if (!c.getBackground().equals(getSelectionBackground())) { String type = (String) getModel().getValueAt(row, 3); Color backgroundIndicator = null; if (type.startsWith("ERROR")) { backgroundIndicator = Color.RED; } else if (type.startsWith("WARNING")) { backgroundIndicator = Color.YELLOW; } else if (type.startsWith("INTERRUPTED")) { backgroundIndicator = Color.MAGENTA; } c.setBackground(backgroundIndicator); } return c; } }; m_table.setModel(m_tableModel); m_table.getColumnModel().getColumn(0).setPreferredWidth(100); m_table.getColumnModel().getColumn(1).setPreferredWidth(150); m_table.getColumnModel().getColumn(2).setPreferredWidth(40); m_table.getColumnModel().getColumn(3).setPreferredWidth(350); m_table.setShowVerticalLines(true); JPanel statusPan = new JPanel(); statusPan.setLayout(new BorderLayout()); statusPan.add(new JScrollPane(m_table), BorderLayout.CENTER); m_tabs.addTab("Status", statusPan); m_tabs.addTab("Log", m_logPanel); setLayout(new BorderLayout()); add(m_tabs, BorderLayout.CENTER); } /** * Clear the status area. */ public void clearStatus() { // stop any running timers Iterator<Timer> i = m_timers.values().iterator(); while (i.hasNext()) { i.next().stop(); } // clear the map entries m_timers.clear(); m_tableIndexes.clear(); // clear the rows from the table while (m_tableModel.getRowCount() > 0) { m_tableModel.removeRow(0); } } /** * The JTable used for the status messages (in case clients want to attach * listeners etc.) * * @return the JTable used for the status messages. */ public JTable getStatusTable() { return m_table; } /** * Sends the supplied message to the log area. These message will typically * have the current timestamp prepended, and be viewable as a history. * * @param message the log message */ @Override public synchronized void logMessage(String message) { // delegate to the weka.gui.LogPanel m_logPanel.logMessage(message); } /** * Sends the supplied message to the status area. These messages are typically * one-line status messages to inform the user of progress during processing * (i.e. it doesn't matter if the user doesn't happen to look at each * message). These messages have the following format: * * <Component name (needs to be unique)>|<Parameter string (optional)|<Status * message> * * @param message the status message. */ @Override public synchronized void statusMessage(String message) { boolean hasDelimiters = (message.indexOf('|') > 0); String stepName = ""; String stepHash = ""; String stepParameters = ""; String stepStatus = ""; boolean noTimer = false; if (!hasDelimiters) { stepName = "Unknown"; stepHash = "Unknown"; stepStatus = message; } else { // Extract the fields of the status message stepHash = message.substring(0, message.indexOf('|')); message = message.substring(message.indexOf('|') + 1, message.length()); // See if there is a unique object ID in the stepHash string if (stepHash.indexOf('$') > 0) { // Extract the step name stepName = stepHash.substring(0, stepHash.indexOf('$')); } else { stepName = stepHash; } if (stepName.startsWith("@!@")) { noTimer = true; stepName = stepName.substring(3, stepName.length()); } // See if there are any step parameters to extract if (message.indexOf('|') >= 0) { stepParameters = message.substring(0, message.indexOf('|')); stepStatus = message.substring(message.indexOf('|') + 1, message.length()); } else { // set the status message to the remainder stepStatus = message; } } // Now see if this step is in the hashmap if (m_tableIndexes.containsKey(stepHash)) { // Get the row number and update the table model... final Integer rowNum = m_tableIndexes.get(stepHash); if (stepStatus.equalsIgnoreCase("remove") || stepStatus.equalsIgnoreCase("remove.")) { // m_tableModel.fireTableDataChanged(); m_tableIndexes.remove(stepHash); Timer t = m_timers.get(stepHash); if (t != null) { t.stop(); m_timers.remove(stepHash); } // now need to decrement all the row indexes of // any rows greater than this one Iterator<String> i = m_tableIndexes.keySet().iterator(); while (i.hasNext()) { String nextKey = i.next(); int index = m_tableIndexes.get(nextKey).intValue(); if (index > rowNum.intValue()) { index--; // System.err.println("*** " + nextKey + " needs decrementing to " + // index); m_tableIndexes.put(nextKey, index); // System.err.println("new index " + // m_rows.get(nextKey).intValue()); } } // Remove the entry... if (!SwingUtilities.isEventDispatchThread()) { try { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { m_tableModel.removeRow(rowNum); } }); } catch (Exception ex) { ex.printStackTrace(); } } else { m_tableModel.removeRow(rowNum); } } else { final String stepNameCopy = stepName; final String stepStatusCopy = stepStatus; final String stepParametersCopy = stepParameters; if (!SwingUtilities.isEventDispatchThread()) { try { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { String currentStatus = m_tableModel.getValueAt(rowNum.intValue(), 3).toString(); if (currentStatus.startsWith("INTERRUPTED") || currentStatus.startsWith("ERROR")) { // leave these in place until the status area is cleared. return; } // ERROR overrides INTERRUPTED if (!(stepStatusCopy.startsWith("INTERRUPTED") && ((String) m_tableModel .getValueAt(rowNum.intValue(), 3)).startsWith("ERROR"))) { m_tableModel.setValueAt(stepNameCopy, rowNum.intValue(), 0); m_tableModel.setValueAt(stepParametersCopy, rowNum.intValue(), 1); m_tableModel.setValueAt( m_table.getValueAt(rowNum.intValue(), 2), rowNum.intValue(), 2); m_tableModel.setValueAt(stepStatusCopy, rowNum.intValue(), 3); } } }); } catch (Exception ex) { ex.printStackTrace(); } } else { String currentStatus = m_tableModel.getValueAt(rowNum.intValue(), 3).toString(); if (currentStatus.startsWith("INTERRUPTED") || currentStatus.startsWith("ERROR")) { // leave these in place until the status area is cleared. return; } if (!(stepStatusCopy.startsWith("INTERRUPTED") && ((String) m_tableModel .getValueAt(rowNum.intValue(), 3)).startsWith("ERROR"))) { m_tableModel.setValueAt(stepNameCopy, rowNum.intValue(), 0); m_tableModel.setValueAt(stepParametersCopy, rowNum.intValue(), 1); m_tableModel.setValueAt(m_table.getValueAt(rowNum.intValue(), 2), rowNum.intValue(), 2); if (m_table.getValueAt(rowNum.intValue(), 3) != null && !m_table.getValueAt(rowNum.intValue(), 3).toString() .toLowerCase() .startsWith("finished")) { m_tableModel.setValueAt(stepStatusCopy, rowNum.intValue(), 3); } } } if (stepStatus.startsWith("ERROR") || stepStatus.startsWith("INTERRUPTED") || stepStatus.toLowerCase().startsWith("finished") || // stepStatus.toLowerCase().startsWith("finished.") || stepStatus.toLowerCase().startsWith("done") || // stepStatus.toLowerCase().startsWith("done.") || stepStatus.equalsIgnoreCase("stopped") || stepStatus.equalsIgnoreCase("stopped.")) { // stop the timer. Timer t = m_timers.get(stepHash); if (t != null) { t.stop(); } } else if (m_timers.get(stepHash) != null && !m_timers.get(stepHash).isRunning()) { // need to create a new one in order to reset the // elapsed time. installTimer(stepHash); } // m_tableModel.fireTableCellUpdated(rowNum.intValue(), 3); } } else if (!stepStatus.equalsIgnoreCase("Remove") && !stepStatus.equalsIgnoreCase("Remove.")) { // Add this one to the hash map int numKeys = m_tableIndexes.keySet().size(); m_tableIndexes.put(stepHash, numKeys); // Now add a row to the table model final Object[] newRow = new Object[4]; newRow[0] = stepName; newRow[1] = stepParameters; newRow[2] = "-"; newRow[3] = stepStatus; final String stepHashCopy = stepHash; try { if (!SwingUtilities.isEventDispatchThread()) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { m_tableModel.addRow(newRow); // m_tableModel.fireTableDataChanged(); } }); } else { m_tableModel.addRow(newRow); } if (!noTimer && !stepStatus.toLowerCase().startsWith("finished") && !stepStatus.toLowerCase().startsWith("done")) { installTimer(stepHashCopy); } } catch (Exception ex) { ex.printStackTrace(); } } } private void installTimer(final String stepHash) { final long startTime = System.currentTimeMillis(); Timer newTimer = new Timer(1000, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { synchronized (LogPanel.this) { if (m_tableIndexes.containsKey(stepHash)) { final Integer rn = m_tableIndexes.get(stepHash); long elapsed = System.currentTimeMillis() - startTime; long seconds = elapsed / 1000; long minutes = seconds / 60; final long hours = minutes / 60; seconds = seconds - (minutes * 60); minutes = minutes - (hours * 60); final long seconds2 = seconds; final long minutes2 = minutes; if (!SwingUtilities.isEventDispatchThread()) { try { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { m_tableModel.setValueAt( "" + m_formatter.format(hours) + ":" + m_formatter.format(minutes2) + ":" + m_formatter.format(seconds2), rn.intValue(), 2); } }); } catch (Exception ex) { ex.printStackTrace(); } } else { m_tableModel.setValueAt( "" + m_formatter.format(hours) + ":" + m_formatter.format(minutes2) + ":" + m_formatter.format(seconds2), rn.intValue(), 2); } } } } }); m_timers.put(stepHash, newTimer); newTimer.start(); } /** * Set the size of the font used in the log message area. <= 0 will use the * default for JTextArea. * * @param size the size of the font to use in the log message area */ public void setLoggingFontSize(int size) { m_logPanel.setLoggingFontSize(size); } /** * Main method to test this class. * * @param args any arguments (unused) */ public static void main(String[] args) { try { final javax.swing.JFrame jf = new javax.swing.JFrame("Status/Log Panel"); jf.getContentPane().setLayout(new BorderLayout()); final LogPanel lp = new LogPanel(); jf.getContentPane().add(lp, BorderLayout.CENTER); jf.getContentPane().add(lp, BorderLayout.CENTER); 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); lp.statusMessage("Step 1|Some options here|A status message"); lp.statusMessage("Step 2$hashkey|Status message: no options"); Thread.sleep(3000); lp.statusMessage("Step 2$hashkey|Funky Chickens!!!"); Thread.sleep(3000); lp.statusMessage("Step 1|Some options here|finished"); // lp.statusMessage("Step 1|Some options here|back again!"); Thread.sleep(3000); lp.statusMessage("Step 2$hashkey|ERROR! More Funky Chickens!!!"); Thread.sleep(3000); lp.statusMessage("Step 2$hashkey|WARNING - now a warning..."); Thread.sleep(3000); lp.statusMessage("Step 2$hashkey|Back to normal."); Thread.sleep(3000); lp.statusMessage("Step 2$hashkey|INTERRUPTED."); } 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/LogWriter.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * LogWriter.java * Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.beans; /** * Interface to be implemented by classes that should be able to write their * own output to the Weka logger. This is useful, for example, for filters * that provide detailed processing instructions. * * @author Carsten Pohle (cp AT cpohle de) * @version $Revision$ */ public interface LogWriter { /** * Set a logger * * @param logger a <code>weka.gui.Logger</code> value */ void setLog(weka.gui.Logger logger); }
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/MetaBean.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * MetaBean.java * Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.beans; import java.awt.BorderLayout; import java.awt.Point; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.beans.BeanInfo; import java.beans.EventSetDescriptor; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyChangeListener; import java.io.Serializable; import java.util.Enumeration; import java.util.Set; import java.util.TreeMap; import java.util.Vector; import javax.swing.ImageIcon; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JWindow; import weka.gui.Logger; /** * A meta bean that encapsulates several other regular beans, useful for * grouping large KnowledgeFlows. * * * @author Mark Hall (mhall at cs dot waikato dot ac dot nz) * @version $Revision$ */ public class MetaBean extends JPanel implements BeanCommon, Visible, EventConstraints, Serializable, UserRequestAcceptor, Startable { /** for serialization */ private static final long serialVersionUID = -6582768902038027077L; protected BeanVisual m_visual = new BeanVisual("Group", BeanVisual.ICON_PATH + "DiamondPlain.gif", BeanVisual.ICON_PATH + "DiamondPlain.gif"); private transient Logger m_log = null; private transient JWindow m_previewWindow = null; private transient javax.swing.Timer m_previewTimer = null; protected Vector<Object> m_subFlow = new Vector<Object>(); protected Vector<Object> m_inputs = new Vector<Object>(); protected Vector<Object> m_outputs = new Vector<Object>(); // the internal connections for the grouping protected Vector<BeanConnection> m_associatedConnections = new Vector<BeanConnection>(); // Holds a preview image of the encapsulated sub-flow protected ImageIcon m_subFlowPreview = null; // offset from where originally grouped if the meta bean // dropped onto the canvas from the user toolbar protected int m_xCreate = 0; protected int m_yCreate = 0; protected int m_xDrop = 0; protected int m_yDrop = 0; public MetaBean() { 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(); } public void setAssociatedConnections(Vector<BeanConnection> ac) { m_associatedConnections = ac; } public Vector<BeanConnection> getAssociatedConnections() { return m_associatedConnections; } public void setSubFlow(Vector<Object> sub) { m_subFlow = sub; } public Vector<Object> getSubFlow() { return m_subFlow; } public void setInputs(Vector<Object> inputs) { m_inputs = inputs; } public Vector<Object> getInputs() { return m_inputs; } public void setOutputs(Vector<Object> outputs) { m_outputs = outputs; } public Vector<Object> getOutputs() { return m_outputs; } private Vector<Object> getBeans(Vector<Object> beans, int type) { Vector<Object> comps = new Vector<Object>(); for (int i = 0; i < beans.size(); i++) { BeanInstance temp = (BeanInstance) beans.elementAt(i); // need to check for sub MetaBean! if (temp.getBean() instanceof MetaBean) { switch (type) { case 0: comps.addAll(((MetaBean) temp.getBean()).getBeansInSubFlow()); break; case 1: comps.addAll(((MetaBean) temp.getBean()).getBeansInInputs()); break; case 2: comps.addAll(((MetaBean) temp.getBean()).getBeansInOutputs()); break; } } else { comps.add(temp); } } return comps; } private boolean beanSetContains(Vector<Object> set, BeanInstance toCheck) { boolean ok = false; for (int i = 0; i < set.size(); i++) { BeanInstance temp = (BeanInstance) set.elementAt(i); if (toCheck == temp) { ok = true; break; } } return ok; } public boolean subFlowContains(BeanInstance toCheck) { return beanSetContains(m_subFlow, toCheck); } public boolean inputsContains(BeanInstance toCheck) { return beanSetContains(m_inputs, toCheck); } public boolean outputsContains(BeanInstance toCheck) { return beanSetContains(m_outputs, toCheck); } /** * Return all the beans in the sub flow * * @return a Vector of all the beans in the sub flow */ public Vector<Object> getBeansInSubFlow() { return getBeans(m_subFlow, 0); } /** * Return all the beans in the inputs * * @return a Vector of all the beans in the inputs */ public Vector<Object> getBeansInInputs() { return getBeans(m_inputs, 1); } /** * Return all the beans in the outputs * * @return a Vector of all the beans in the outputs */ public Vector<Object> getBeansInOutputs() { return getBeans(m_outputs, 2); } private Vector<BeanInfo> getBeanInfos(Vector<Object> beans, int type) { Vector<BeanInfo> infos = new Vector<BeanInfo>(); for (int i = 0; i < beans.size(); i++) { BeanInstance temp = (BeanInstance) beans.elementAt(i); if (temp.getBean() instanceof MetaBean) { switch (type) { case 0: infos.addAll(((MetaBean) temp.getBean()).getBeanInfoSubFlow()); break; case 1: infos.addAll(((MetaBean) temp.getBean()).getBeanInfoInputs()); break; case 2: infos.addAll(((MetaBean) temp.getBean()).getBeanInfoOutputs()); } } else { try { infos.add(Introspector.getBeanInfo(temp.getBean().getClass())); } catch (IntrospectionException ex) { ex.printStackTrace(); } } } return infos; } public Vector<BeanInfo> getBeanInfoSubFlow() { return getBeanInfos(m_subFlow, 0); } public Vector<BeanInfo> getBeanInfoInputs() { return getBeanInfos(m_inputs, 1); } public Vector<BeanInfo> getBeanInfoOutputs() { return getBeanInfos(m_outputs, 2); } // stores the original position of the beans // when this group is created. Used // to restore their locations if the group is ungrouped. private Vector<Point> m_originalCoords; /** * returns the vector containing the original coordinates (instances of class * Point) for the inputs * * @return the containing the coord Points of the original inputs */ public Vector<Point> getOriginalCoords() { return m_originalCoords; } /** * sets the vector containing the original coordinates (instances of class * Point) for the inputs * * @param value the vector containing the points of the coords of the original * inputs */ public void setOriginalCoords(Vector<Point> value) { m_originalCoords = value; } /** * Move coords of all inputs and outputs of this meta bean to the coords of * the supplied BeanInstance. Typically the supplied BeanInstance is the * BeanInstance that encapsulates this meta bean; the result in this case is * that all inputs and outputs are shifted so that their coords coincide with * the meta bean and all connections to them appear (visually) to go to/from * the meta bean. * * @param toShiftTo the BeanInstance whos coordinates will be used. * @param save true if coordinates are to be saved. */ public void shiftBeans(BeanInstance toShiftTo, boolean save) { if (save) { m_originalCoords = new Vector<Point>(); } int targetX = toShiftTo.getX(); int targetY = toShiftTo.getY(); for (int i = 0; i < m_subFlow.size(); i++) { BeanInstance temp = (BeanInstance) m_subFlow.elementAt(i); if (save) { // save offsets from this point Point p = new Point(temp.getX() - targetX, temp.getY() - targetY); m_originalCoords.add(p); } temp.setX(targetX); temp.setY(targetY); } } public void restoreBeans(int x, int y) { for (int i = 0; i < m_subFlow.size(); i++) { BeanInstance temp = (BeanInstance) m_subFlow.elementAt(i); Point p = m_originalCoords.elementAt(i); JComponent c = (JComponent) temp.getBean(); c.getPreferredSize(); temp.setX(x + (int) p.getX());// + (m_xDrop - m_xCreate)); temp.setY(y + (int) p.getY());// + (m_yDrop - m_yCreate)); } } /** * 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) { for (int i = 0; i < m_subFlow.size(); i++) { BeanInstance output = (BeanInstance) m_subFlow.elementAt(i); if (output.getBean() instanceof EventConstraints) { if (((EventConstraints) output.getBean()).eventGeneratable(eventName)) { return true; } } } return false; } /** * Returns true if, at this time, the object will accept a connection with * respect to the supplied EventSetDescriptor * * @param esd the EventSetDescriptor * @return true if the object will accept a connection */ @Override public boolean connectionAllowed(EventSetDescriptor esd) { Vector<BeanInstance> targets = getSuitableTargets(esd); for (int i = 0; i < targets.size(); i++) { BeanInstance input = targets.elementAt(i); if (input.getBean() instanceof BeanCommon) { // if (((BeanCommon)input.getBean()).connectionAllowed(esd.getName())) { if (((BeanCommon) input.getBean()).connectionAllowed(esd)) { return true; } } else { return true; } } return false; } @Override public boolean connectionAllowed(String eventName) { return false; } /** * Notify this object that it has been registered as a listener with a source * with respect to the named event. This is just a dummy method in this class * to satisfy the interface. Specific code in BeanConnection takes care of * this method for MetaBeans * * @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) { } /** * Notify this object that it has been deregistered as a listener with a * source with respect to the supplied event name. This is just a dummy method * in this class to satisfy the interface. Specific code in BeanConnection * takes care of this method for MetaBeans * * @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) { } /** * Stop all encapsulated beans */ @Override public void stop() { for (int i = 0; i < m_subFlow.size(); i++) { Object temp = m_subFlow.elementAt(i); if (temp instanceof BeanCommon) { ((BeanCommon) temp).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() { boolean result = false; for (int i = 0; i < m_subFlow.size(); i++) { Object temp = m_subFlow.elementAt(i); if (temp instanceof BeanCommon) { if (((BeanCommon) temp).isBusy()) { result = true; break; } } } return result; } /** * 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 + "DiamondPlain.gif", BeanVisual.ICON_PATH + "DiamondPlain.gif"); } @Override public String getStartMessage() { String message = "Start loading"; for (int i = 0; i < m_subFlow.size(); i++) { BeanInstance temp = (BeanInstance) m_subFlow.elementAt(i); if (temp.getBean() instanceof Startable) { String s = ((Startable) temp.getBean()).getStartMessage(); if (s.startsWith("$")) { message = "$" + message; break; } } } return message; } @Override public void start() { TreeMap<Integer, Startable> startables = new TreeMap<Integer, Startable>(); for (int i = 0; i < m_subFlow.size(); i++) { BeanInstance temp = (BeanInstance) m_subFlow.elementAt(i); if (temp.getBean() instanceof Startable) { Startable s = (Startable) temp.getBean(); String beanName = s.getClass().getName(); String customName = beanName; boolean ok = false; Integer position = null; boolean launch = true; // String beanName = s.getClass().getName(); if (s instanceof BeanCommon) { 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(statusMessagePrefix() + "adding start point " + beanName + " to the execution list (position " + position + ")"); } startables.put(position, s); } } } } if (startables.size() > 0) { if (m_log != null) { m_log.logMessage(statusMessagePrefix() + "Starting " + startables.size() + " sub-flow start points sequentially."); } Set<Integer> s = startables.keySet(); for (Integer i : s) { try { Startable startPoint = startables.get(i); String bN = startPoint.getClass().getName(); if (startPoint instanceof BeanCommon) { bN = ((BeanCommon) startPoint).getCustomName(); } if (m_log != null) { m_log.statusMessage(statusMessagePrefix() + "Starting sub-flow start point: " + bN); m_log.logMessage(statusMessagePrefix() + "Starting sub-flow start point: " + bN); } startPoint.start(); Thread.sleep(500); while (isBusy()) { Thread.sleep(2000); } } catch (Exception ex) { if (m_log != null) { m_log.logMessage(statusMessagePrefix() + "A problem occurred when launching start points in sub-flow: " + ex.getMessage()); } stop(); if (m_log != null) { m_log.statusMessage(statusMessagePrefix() + "ERROR (see log for details)"); } } } if (m_log != null) { m_log.statusMessage(statusMessagePrefix() + "Finished."); } } } /** * 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>(); if (m_subFlowPreview != null) { String text = "Show preview"; if (m_previewWindow != null) { text = "$" + text; } newVector.addElement(text); } for (int i = 0; i < m_subFlow.size(); i++) { BeanInstance temp = (BeanInstance) m_subFlow.elementAt(i); if (temp.getBean() instanceof UserRequestAcceptor) { String prefix = ""; if ((temp.getBean() instanceof BeanCommon)) { prefix = ((BeanCommon) temp.getBean()).getCustomName(); } else { prefix = temp.getBean().getClass().getName(); prefix = prefix.substring(prefix.lastIndexOf('.') + 1, prefix.length()); } prefix = "" + (i + 1) + ": (" + prefix + ")"; Enumeration<String> en = ((UserRequestAcceptor) temp.getBean()) .enumerateRequests(); while (en.hasMoreElements()) { String req = en.nextElement(); if (req.charAt(0) == '$') { prefix = '$' + prefix; req = req.substring(1, req.length()); } if (req.charAt(0) == '?') { prefix = '?' + prefix; req = req.substring(1, req.length()); } newVector.add(prefix + " " + req); } } else if (temp.getBean() instanceof Startable) { String prefix = ""; if ((temp.getBean() instanceof BeanCommon)) { prefix = ((BeanCommon) temp.getBean()).getCustomName(); } else { prefix = temp.getBean().getClass().getName(); prefix = prefix.substring(prefix.lastIndexOf('.') + 1, prefix.length()); } prefix = "" + (i + 1) + ": (" + prefix + ")"; String startMessage = ((Startable) temp.getBean()).getStartMessage(); if (startMessage.charAt(0) == '$') { prefix = '$' + prefix; startMessage = startMessage.substring(1, startMessage.length()); } newVector.add(prefix + " " + startMessage); } } return newVector.elements(); } public void setSubFlowPreview(ImageIcon sfp) { m_subFlowPreview = sfp; } private void showPreview() { if (m_previewWindow == null) { JLabel jl = new JLabel(m_subFlowPreview); // Dimension d = jl.getPreferredSize(); jl.setLocation(0, 0); m_previewWindow = new JWindow(); // popup.getContentPane().setLayout(null); m_previewWindow.getContentPane().add(jl); m_previewWindow.validate(); m_previewWindow.setSize(m_subFlowPreview.getIconWidth(), m_subFlowPreview.getIconHeight()); m_previewWindow.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { m_previewWindow.dispose(); m_previewWindow = null; } }); m_previewWindow.setLocation(getParent().getLocationOnScreen().x + getX() + getWidth() / 2 - m_subFlowPreview.getIconWidth() / 2, getParent().getLocationOnScreen().y + getY() + getHeight() / 2 - m_subFlowPreview.getIconHeight() / 2); // popup.pack(); m_previewWindow.setVisible(true); m_previewTimer = new javax.swing.Timer(8000, new java.awt.event.ActionListener() { @Override public void actionPerformed(java.awt.event.ActionEvent e) { if (m_previewWindow != null) { m_previewWindow.dispose(); m_previewWindow = null; m_previewTimer = null; } } }); m_previewTimer.setRepeats(false); m_previewTimer.start(); } } /** * 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("Show preview") == 0) { showPreview(); return; } // first grab the index if any if (request.indexOf(":") < 0) { return; } String tempI = request.substring(0, request.indexOf(':')); int index = Integer.parseInt(tempI); index--; String req = request.substring(request.indexOf(')') + 1, request.length()) .trim(); Object target = ((BeanInstance) m_subFlow.elementAt(index)).getBean(); if (target instanceof Startable && req.equals(((Startable) target).getStartMessage())) { try { ((Startable) target).start(); } catch (Exception ex) { if (m_log != null) { String compName = (target instanceof BeanCommon) ? ((BeanCommon) target) .getCustomName() : ""; m_log.logMessage("Problem starting subcomponent " + compName); } } } else { ((UserRequestAcceptor) target).performRequest(req); } } /** * Set a logger * * @param logger a <code>Logger</code> value */ @Override public void setLog(Logger logger) { m_log = logger; } public void removePropertyChangeListenersSubFlow(PropertyChangeListener pcl) { for (int i = 0; i < m_subFlow.size(); i++) { BeanInstance temp = (BeanInstance) m_subFlow.elementAt(i); if (temp.getBean() instanceof Visible) { ((Visible) (temp.getBean())).getVisual().removePropertyChangeListener( pcl); } if (temp.getBean() instanceof MetaBean) { ((MetaBean) temp.getBean()).removePropertyChangeListenersSubFlow(pcl); } } } public void addPropertyChangeListenersSubFlow(PropertyChangeListener pcl) { for (int i = 0; i < m_subFlow.size(); i++) { BeanInstance temp = (BeanInstance) m_subFlow.elementAt(i); if (temp.getBean() instanceof Visible) { ((Visible) (temp.getBean())).getVisual().addPropertyChangeListener(pcl); } if (temp.getBean() instanceof MetaBean) { ((MetaBean) temp.getBean()).addPropertyChangeListenersSubFlow(pcl); } } } /** * Checks to see if any of the inputs to this group implements the supplied * listener class * * @param listenerClass the listener to check for */ public boolean canAcceptConnection(Class<?> listenerClass) { for (int i = 0; i < m_inputs.size(); i++) { BeanInstance input = (BeanInstance) m_inputs.elementAt(i); if (listenerClass.isInstance(input.getBean())) { return true; } } return false; } /** * Return a list of input beans capable of receiving the supplied event * * @param esd the event in question * @return a vector of beans capable of handling the event */ public Vector<BeanInstance> getSuitableTargets(EventSetDescriptor esd) { Class<?> listenerClass = esd.getListenerType(); // class of the listener Vector<BeanInstance> targets = new Vector<BeanInstance>(); for (int i = 0; i < m_inputs.size(); i++) { BeanInstance input = (BeanInstance) m_inputs.elementAt(i); if (listenerClass.isInstance(input.getBean())) { targets.add(input); } } return targets; } private String statusMessagePrefix() { return getCustomName() + "$" + MetaBean.this.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/ModelPerformanceChart.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ModelPerformanceChart.java * Copyright (C) 2004-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.beans; 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.PluginManager; import weka.gui.Logger; import weka.gui.visualize.PlotData2D; import weka.gui.visualize.VisualizePanel; import javax.swing.JFrame; import javax.swing.JPanel; 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 can be used for displaying threshold curves (e.g. ROC curves) and * scheme error plots * * @author Mark Hall * @version $Revision$ */ public class ModelPerformanceChart extends JPanel implements ThresholdDataListener, VisualizableErrorListener, Visible, UserRequestAcceptor, EventConstraints, Serializable, BeanContextChild, HeadlessEventCollector, BeanCommon, EnvironmentHandler { /** for serialization */ private static final long serialVersionUID = -4602034200071195924L; protected BeanVisual m_visual = new BeanVisual("ModelPerformanceChart", BeanVisual.ICON_PATH + "ModelPerformanceChart.gif", BeanVisual.ICON_PATH + "ModelPerformanceChart_animated.gif"); protected transient PlotData2D m_masterPlot; /** For rendering plots to encapsulate in ImageEvents */ protected transient List<Instances> m_offscreenPlotData; protected transient List<String> m_thresholdSeriesTitles; 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"; protected transient JFrame m_popupFrame; protected boolean m_framePoppedUp = false; /** 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>(); /** * 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 transient VisualizePanel m_visPanel; /** * The environment variables. */ protected transient Environment m_env; /** * BeanContextChild support */ protected BeanContextChildSupport m_bcSupport = new BeanContextChildSupport( this); public ModelPerformanceChart() { useDefaultVisual(); 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)."; } protected void appearanceDesign() { removeAll(); setLayout(new BorderLayout()); add(m_visual, BorderLayout.CENTER); } protected void appearanceFinal() { removeAll(); setLayout(new BorderLayout()); setUpFinal(); } protected void setUpFinal() { if (m_visPanel == null) { m_visPanel = new VisualizePanel(); } add(m_visPanel, BorderLayout.CENTER); } 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(); } } } } /** * Display a threshold curve. * * @param e a ThresholdDataEvent */ @Override public synchronized void acceptDataSet(ThresholdDataEvent e) { if (m_env == null) { m_env = Environment.getSystemWide(); } if (!GraphicsEnvironment.isHeadless()) { if (m_visPanel == null) { m_visPanel = new VisualizePanel(); } if (m_masterPlot == null) { m_masterPlot = e.getDataSet(); } try { // check for compatable data sets if (!m_masterPlot.getPlotInstances().relationName() .equals(e.getDataSet().getPlotInstances().relationName())) { // if not equal then remove all plots and set as new master plot m_masterPlot = e.getDataSet(); m_visPanel.setMasterPlot(m_masterPlot); m_visPanel.validate(); m_visPanel.repaint(); } else { // add as new plot m_visPanel.addPlot(e.getDataSet()); m_visPanel.validate(); m_visPanel.repaint(); } m_visPanel.setXIndex(4); m_visPanel.setYIndex(5); } catch (Exception ex) { System.err .println("Problem setting up visualization (ModelPerformanceChart)"); ex.printStackTrace(); } } else { m_headlessEvents.add(e); } if (m_imageListeners.size() > 0 && !m_processingHeadlessEvents) { // configure the renderer (if necessary) setupOffscreenRenderer(); if (m_offscreenPlotData == null || !m_offscreenPlotData.get(0).relationName() .equals(e.getDataSet().getPlotInstances().relationName())) { m_offscreenPlotData = new ArrayList<Instances>(); m_thresholdSeriesTitles = new ArrayList<String>(); } m_offscreenPlotData.add(e.getDataSet().getPlotInstances()); m_thresholdSeriesTitles.add(e.getDataSet().getPlotName()); List<String> options = new ArrayList<String>(); String additional = "-color=/last"; if (m_additionalOptions != null && m_additionalOptions.length() > 0) { additional = m_additionalOptions; try { additional = m_env.substitute(additional); } catch (Exception ex) { } } String[] optsParts = additional.split(","); for (String p : optsParts) { options.add(p.trim()); } String xAxis = "False Positive Rate"; if (m_xAxis != null && m_xAxis.length() > 0) { xAxis = m_xAxis; try { xAxis = m_env.substitute(xAxis); } catch (Exception ex) { } } String yAxis = "True Positive Rate"; if (m_yAxis != null && m_yAxis.length() > 0) { 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 { List<Instances> series = new ArrayList<Instances>(); for (int i = 0; i < m_offscreenPlotData.size(); i++) { Instances temp = new Instances(m_offscreenPlotData.get(i)); // set relation name to scheme name temp.setRelationName(m_thresholdSeriesTitles.get(i)); series.add(temp); } BufferedImage osi = m_offscreenRenderer.renderXYLineChart(defWidth, defHeight, series, xAxis, yAxis, options); ImageEvent ie = new ImageEvent(this, osi); notifyImageListeners(ie); } catch (Exception e1) { e1.printStackTrace(); } } } /** * Display a scheme error plot. * * @param e a VisualizableErrorEvent */ @Override public synchronized void acceptDataSet(VisualizableErrorEvent e) { if (m_env == null) { m_env = Environment.getSystemWide(); } if (!GraphicsEnvironment.isHeadless()) { if (m_visPanel == null) { m_visPanel = new VisualizePanel(); } m_masterPlot = e.getDataSet(); try { m_visPanel.setMasterPlot(m_masterPlot); } catch (Exception ex) { System.err .println("Problem setting up visualization (ModelPerformanceChart)"); ex.printStackTrace(); } m_visPanel.validate(); m_visPanel.repaint(); } else { m_headlessEvents = new ArrayList<EventObject>(); m_headlessEvents.add(e); } if (m_imageListeners.size() > 0 && !m_processingHeadlessEvents) { // configure the renderer (if necessary) setupOffscreenRenderer(); m_offscreenPlotData = new ArrayList<Instances>(); Instances predictedI = e.getDataSet().getPlotInstances(); if (predictedI.classAttribute().isNominal()) { // split the classes out into individual series. // add a new attribute to hold point sizes - correctly // classified instances get default point size (2); // misclassified instances get point size (5). // WekaOffscreenChartRenderer can take advantage of this // information - other plugin renderers may or may not // be able to use it ArrayList<Attribute> atts = new ArrayList<Attribute>(); for (int i = 0; i < predictedI.numAttributes(); i++) { atts.add((Attribute) predictedI.attribute(i).copy()); } atts.add(new Attribute("@@size@@")); Instances newInsts = new Instances(predictedI.relationName(), atts, predictedI.numInstances()); newInsts.setClassIndex(predictedI.classIndex()); for (int i = 0; i < predictedI.numInstances(); i++) { double[] vals = new double[newInsts.numAttributes()]; for (int j = 0; j < predictedI.numAttributes(); j++) { vals[j] = predictedI.instance(i).value(j); } vals[vals.length - 1] = 2; // default shape size Instance ni = new DenseInstance(1.0, vals); newInsts.add(ni); } // predicted class attribute is always actualClassIndex - 1 Instances[] classes = new Instances[newInsts.numClasses()]; for (int i = 0; i < newInsts.numClasses(); i++) { classes[i] = new Instances(newInsts, 0); classes[i].setRelationName(newInsts.classAttribute().value(i)); } Instances errors = new Instances(newInsts, 0); int actualClass = newInsts.classIndex(); for (int i = 0; i < newInsts.numInstances(); i++) { Instance current = newInsts.instance(i); classes[(int) current.classValue()].add((Instance) current.copy()); if (current.value(actualClass) != current.value(actualClass - 1)) { Instance toAdd = (Instance) current.copy(); // larger shape for an error toAdd.setValue(toAdd.numAttributes() - 1, 5); // swap predicted and actual class value so // that the color plotted for the error series // is that of the predicted class double actualClassV = toAdd.value(actualClass); double predictedClassV = toAdd.value(actualClass - 1); toAdd.setValue(actualClass, predictedClassV); toAdd.setValue(actualClass - 1, actualClassV); errors.add(toAdd); } } errors.setRelationName("Errors"); m_offscreenPlotData.add(errors); for (Instances classe : classes) { m_offscreenPlotData.add(classe); } } else { // numeric class - have to make a new set of instances // with the point sizes added as an additional attribute ArrayList<Attribute> atts = new ArrayList<Attribute>(); for (int i = 0; i < predictedI.numAttributes(); i++) { atts.add((Attribute) predictedI.attribute(i).copy()); } atts.add(new Attribute("@@size@@")); Instances newInsts = new Instances(predictedI.relationName(), atts, predictedI.numInstances()); int[] shapeSizes = e.getDataSet().getShapeSize(); for (int i = 0; i < predictedI.numInstances(); i++) { double[] vals = new double[newInsts.numAttributes()]; for (int j = 0; j < predictedI.numAttributes(); j++) { vals[j] = predictedI.instance(i).value(j); } vals[vals.length - 1] = shapeSizes[i]; Instance ni = new DenseInstance(1.0, vals); newInsts.add(ni); } newInsts.setRelationName(predictedI.classAttribute().name()); m_offscreenPlotData.add(newInsts); } List<String> options = new ArrayList<String>(); String additional = "-color=" + predictedI.classAttribute().name() + ",-hasErrors"; if (m_additionalOptions != null && m_additionalOptions.length() > 0) { additional += "," + m_additionalOptions; try { additional = m_env.substitute(additional); } catch (Exception ex) { } } String[] optionsParts = additional.split(","); for (String p : optionsParts) { options.add(p.trim()); } // if (predictedI.classAttribute().isNumeric()) { options.add("-shapeSize=@@size@@"); // } 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 text listeners of a TextEvent * * @param te a <code>ImageEvent</code> value */ @SuppressWarnings("unchecked") private 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 (!GraphicsEnvironment.isHeadless()) { m_processingHeadlessEvents = true; for (EventObject e : headless) { if (e instanceof ThresholdDataEvent) { acceptDataSet((ThresholdDataEvent) e); } else if (e instanceof VisualizableErrorEvent) { acceptDataSet((VisualizableErrorEvent) 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 + "ModelPerformanceChart.gif", BeanVisual.ICON_PATH + "ModelPerformanceChart_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_masterPlot != null) { newVector.addElement("Show chart"); newVector.addElement("?Clear all plots"); } 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 { 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; } /** * 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 chart") == 0) { try { // popup visualize panel if (!m_framePoppedUp) { m_framePoppedUp = true; final javax.swing.JFrame jf = new javax.swing.JFrame( "Model Performance Chart"); jf.setSize(800, 600); jf.getContentPane().setLayout(new BorderLayout()); jf.getContentPane().add(m_visPanel, 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 if (request.equals("Clear all plots")) { m_visPanel.removeAllPlots(); m_visPanel.validate(); m_visPanel.repaint(); m_visPanel = null; m_masterPlot = null; m_offscreenPlotData = null; } else { throw new IllegalArgumentException(request + " not supported (Model Performance Chart)"); } } public static void main(String[] args) { try { if (args.length != 1) { System.err.println("Usage: ModelPerformanceChart <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 ModelPerformanceChart as = new ModelPerformanceChart(); PlotData2D pd = new PlotData2D(inst); pd.setPlotName(inst.relationName()); ThresholdDataEvent roc = new ThresholdDataEvent(as, pd); as.acceptDataSet(roc); 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()); } } /** * 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(); } /** * 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; } /** * 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 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("thresholdData") || eventName.equals("visualizableError"); } /** * 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("thresholdData") || ((EventConstraints) o).eventGeneratable("visualizableError")) { ok = true; break; } } } return ok; } @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; } }
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/ModelPerformanceChartBeanInfo.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ModelPerformanceChartBeanInfo.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; /** * Bean info class for the model performance chart * * @author Mark Hall * @version $Revision$ */ public class ModelPerformanceChartBeanInfo 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(ModelPerformanceChart.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.ModelPerformanceChart.class, ModelPerformanceChartCustomizer.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/ModelPerformanceChartCustomizer.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ModelPerformanceChartCustomizer.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 model performance chart. 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 ModelPerformanceChartCustomizer extends JPanel implements BeanCustomizer, EnvironmentHandler, CustomizerClosingListener, CustomizerCloseRequester { /** * For serialization */ private static final long serialVersionUID = 27802741348090392L; private ModelPerformanceChart m_modelPC; 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 ModelPerformanceChartCustomizer() { 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_modelPC = (ModelPerformanceChart)object; m_rendererNameBack = m_modelPC.getOffscreenRendererName(); m_xAxisBack = m_modelPC.getOffscreenXAxis(); m_yAxisBack = m_modelPC.getOffscreenYAxis(); m_widthBack = m_modelPC.getOffscreenWidth(); m_heightBack = m_modelPC.getOffscreenHeight(); m_optsBack = m_modelPC.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_modelPC.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_modelPC.setOffscreenXAxis(m_xAxis.getText()); m_modelPC.setOffscreenYAxis(m_yAxis.getText()); m_modelPC.setOffscreenWidth(m_width.getText()); m_modelPC.setOffscreenHeight(m_height.getText()); m_modelPC.setOffscreenAdditionalOpts(m_opts.getText()); m_modelPC.setOffscreenRendererName(m_rendererCombo. getSelectedItem().toString()); if (m_modifyListener != null) { m_modifyListener. setModifiedStatus(ModelPerformanceChartCustomizer.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_modelPC.setOffscreenXAxis(m_xAxisBack); m_modelPC.setOffscreenYAxis(m_yAxisBack); m_modelPC.setOffscreenWidth(m_widthBack); m_modelPC.setOffscreenHeight(m_heightBack); m_modelPC.setOffscreenAdditionalOpts(m_optsBack); m_modelPC.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/Note.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * Note.java * Copyright (C) 2011-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.beans; import java.awt.BorderLayout; import java.awt.Color; import javax.swing.BorderFactory; import javax.swing.JLabel; import javax.swing.JPanel; /** * Simple bean for displaying a textual note on the layout. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision$ * */ public class Note extends JPanel { /** * For serialization */ private static final long serialVersionUID = -7272355421198069040L; /** The note text */ protected String m_noteText = "New note"; /** The label that displays the note text */ protected JLabel m_label = new JLabel(); /** Adjustment for the font size */ protected int m_fontSizeAdjust = -1; /** * Constructor */ public Note() { setLayout(new BorderLayout()); // setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED)); setBorder(new ShadowBorder(2, Color.GRAY)); m_label.setText(convertToHTML(m_noteText)); m_label.setOpaque(true); m_label.setBackground(Color.YELLOW); JPanel holder = new JPanel(); holder.setLayout(new BorderLayout()); holder.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2)); holder.setOpaque(true); holder.setBackground(Color.YELLOW); holder.add(m_label, BorderLayout.CENTER); add(holder, BorderLayout.CENTER); } public void setHighlighted(boolean highlighted) { if (highlighted) { setBorder(BorderFactory.createMatteBorder(2, 2, 2, 2, Color.BLUE)); } else { //setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED)); setBorder(new ShadowBorder(2, Color.GRAY)); } revalidate(); } private String convertToHTML(String text) { String htmlString = m_noteText.replace("\n", "<br>"); htmlString = "<html><font size=" + m_fontSizeAdjust + ">" + htmlString + "</font>" + "</html>"; return htmlString; } /** * Set the text to display * * @param noteText the text to display in the note. */ public void setNoteText(String noteText) { m_noteText = noteText; m_label.setText(convertToHTML(m_noteText)); } /** * Get the note text * * @return the note text */ public String getNoteText() { return m_noteText; } /** * set the font size adjustment * * @param adjust the font size adjustment */ public void setFontSizeAdjust(int adjust) { m_fontSizeAdjust = adjust; } /** * Get the font size adjustment * * @return the font size adjustment */ public int getFontSizeAdjust() { return m_fontSizeAdjust; } /** * Decrease the font size by one */ public void decreaseFontSize() { m_fontSizeAdjust--; } /** * Increase the font size by one */ public void increaseFontSize() { m_fontSizeAdjust++; } }
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/NoteBeanInfo.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * NoteBeanInfo.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; /** * Bean info class for the Note bean. Suppresses all events. Returns the * customizer class. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision$ * */ public class NoteBeanInfo extends SimpleBeanInfo { public EventSetDescriptor[] getEventSetDescriptors() { EventSetDescriptor[] esds = {}; return esds; } public BeanDescriptor getBeanDescriptor() { return new BeanDescriptor(weka.gui.beans.Note.class, weka.gui.beans.NoteCustomizer.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/NoteCustomizer.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * NoteCustomizer.java * Copyright (C) 2011-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.beans; import java.awt.BorderLayout; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; /** * Customizer for the note component. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision$ * */ public class NoteCustomizer extends JPanel implements BeanCustomizer, CustomizerCloseRequester, CustomizerClosingListener { /** * for serialization */ private static final long serialVersionUID = 995648616684953391L; /** the parent window */ protected Window m_parentWindow; /** the note to be edited */ protected Note m_note; /** text area for displaying the note's text */ protected JTextArea m_textArea = new JTextArea(5, 20); /** * Listener that wants to know the the modified status of the object that * we're customizing */ private ModifyListener m_modifyListener; /** * Constructs a new note customizer */ public NoteCustomizer() { setLayout(new BorderLayout()); m_textArea.setLineWrap(true); JScrollPane sc = new JScrollPane(m_textArea); add(sc, BorderLayout.CENTER); JButton okBut = new JButton("OK"); add(okBut, BorderLayout.SOUTH); okBut.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { customizerClosing(); if (m_parentWindow != null) { m_parentWindow.dispose(); } } }); } @Override public void setParentWindow(Window parent) { // TODO Auto-generated method stub m_parentWindow = parent; } @Override public void setObject(Object ob) { // TODO Auto-generated method stub m_note = (Note)ob; m_textArea.setText(m_note.getNoteText()); m_textArea.selectAll(); } @Override public void customizerClosing() { if (m_note != null) { m_note.setNoteText(m_textArea.getText()); if (m_modifyListener != null) { m_modifyListener.setModifiedStatus(NoteCustomizer.this, true); } } } @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/OffscreenChartRenderer.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * OffscreenChartRenderer.java * Copyright (C) 2011-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.beans; import java.awt.image.BufferedImage; import java.util.List; import weka.core.Instances; /** * Interface to something that can render certain types of charts * in headless mode. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision$ */ public interface OffscreenChartRenderer { /** * The name of this off screen renderer * * @return the name of this off screen renderer */ String rendererName(); /** * Gets a short list of additional options (if any), * suitable for displaying in a tip text, in HTML form * * @return additional options description in simple HTML form */ String optionsTipTextHTML(); /** * Render an XY line chart * * @param width the width of the resulting chart in pixels * @param height the height of the resulting chart in pixels * @param series a list of Instances - one for each series to be plotted * @param xAxis the name of the attribute for the x-axis (all series Instances * are expected to have an attribute of the same type with this name) * @param yAxis the name of the attribute for the y-axis (all series Instances * are expected to have an attribute of the same type with this name) * @param optionalArgs optional arguments to the renderer (may be null) * * @return a BufferedImage containing the chart * @throws Exception if there is a problem rendering the chart */ BufferedImage renderXYLineChart(int width, int height, List<Instances> series, String xAxis, String yAxis, List<String> optionalArgs) throws Exception; /** * Render an XY scatter plot * * @param width the width of the resulting chart in pixels * @param height the height of the resulting chart in pixels * @param series a list of Instances - one for each series to be plotted * @param xAxis the name of the attribute for the x-axis (all series Instances * are expected to have an attribute of the same type with this name) * @param yAxis the name of the attribute for the y-axis (all series Instances * are expected to have an attribute of the same type with this name) * @param optionalArgs optional arguments to the renderer (may be null) * * @return a BufferedImage containing the chart * @throws Exception if there is a problem rendering the chart */ BufferedImage renderXYScatterPlot(int width, int height, List<Instances> series, String xAxis, String yAxis, List<String> optionalArgs) throws Exception; /** * Render histogram(s) (numeric attribute) or bar chart(s) (nominal attribute). * Some implementations may not be able to render more than one histogram/pie * on the same chart - the implementation can either throw an exception or * just process the first series in this case. * * @param width the width of the resulting chart in pixels * @param height the height of the resulting chart in pixels * @param series a list of Instances - one for each series to be plotted * @param attsToPlot the name of the attribute to plot (the attribute, with the, * same type, must be present in each series) * @param optionalArgs optional arguments to the renderer (may be null) * * @return a BufferedImage containing the chart * @throws Exception if there is a problem rendering the chart */ BufferedImage renderHistogram(int width, int height, List<Instances> series, String attsToPlot, List<String> optionalArgs) throws Exception; }
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/PluginManager.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * PluginManager.java * Copyright (C) 2011-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.beans; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; /** * Class that manages a global map of plugins. The knowledge flow uses this to * manage plugins other than step components and perspectives. Is general * purpose, so can be used by other Weka components. Provides static methods for * registering and instantiating plugins. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision$ * @deprecated Use weka.core.PluginManager instead */ @Deprecated public class PluginManager { /** * Add the supplied list of fully qualified class names to the disabled list * * @param classnames a list of class names to add */ public static synchronized void addToDisabledList(List<String> classnames) { weka.core.PluginManager.addToDisabledList(classnames); } /** * Add the supplied fully qualified class name to the list of disabled plugins * * @param classname the fully qualified name of a class to add */ public static synchronized void addToDisabledList(String classname) { weka.core.PluginManager.addToDisabledList(classname); } /** * Remove the supplied list of fully qualified class names to the disabled * list * * @param classnames a list of class names to remove */ public static synchronized void removeFromDisabledList(List<String> classnames) { weka.core.PluginManager.removeFromDisabledList(classnames); } /** * Remove the supplied fully qualified class name from the list of disabled * plugins * * @param classname the fully qualified name of a class to remove */ public static synchronized void removeFromDisabledList(String classname) { weka.core.PluginManager.removeFromDisabledList(classname); } /** * Returns true if the supplied fully qualified class name is in the disabled * list * * @param classname the name of the class to check * @return true if the supplied class name is in the disabled list */ public static boolean isInDisabledList(String classname) { return weka.core.PluginManager.isInDisabledList(classname); } /** * Add all key value pairs from the supplied property file * * @param propsFile the properties file to add * @throws Exception if a problem occurs */ public static synchronized void addFromProperties(File propsFile) throws Exception { weka.core.PluginManager.addFromProperties(propsFile); } /** * Add all key value pairs from the supplied property file * * @param propsFile the properties file to add * @param maintainInsertionOrder true if the order of insertion of * implementations is to be preserved (rather than sorted order) * @throws Exception if a problem occurs */ public static synchronized void addFromProperties(File propsFile, boolean maintainInsertionOrder) throws Exception { weka.core.PluginManager .addFromProperties(propsFile, maintainInsertionOrder); } /** * Add all key value pairs from the supplied properties stream * * @param propsStream an input stream to a properties file * @throws Exception if a problem occurs */ public static synchronized void addFromProperties(InputStream propsStream) throws Exception { weka.core.PluginManager.addFromProperties(propsStream); } /** * Add all key value pairs from the supplied properties stream * * @param propsStream an input stream to a properties file * @param maintainInsertionOrder true if the order of insertion of * implementations is to be preserved (rather than sorted order) * @throws Exception if a problem occurs */ public static synchronized void addFromProperties(InputStream propsStream, boolean maintainInsertionOrder) throws Exception { weka.core.PluginManager.addFromProperties(propsStream, maintainInsertionOrder); } /** * Add all key value pairs from the supplied properties object * * @param props a Properties object * @throws Exception if a problem occurs */ public static synchronized void addFromProperties(Properties props) throws Exception { weka.core.PluginManager.addFromProperties(props); } /** * Add all key value pairs from the supplied properties object * * @param props a Properties object * @param maintainInsertionOrder true if the order of insertion of * implementations is to be preserved (rather than sorted order) * @throws Exception if a problem occurs */ public static synchronized void addFromProperties(Properties props, boolean maintainInsertionOrder) throws Exception { weka.core.PluginManager.addFromProperties(props, maintainInsertionOrder); } /** * Add a resource. * * @param resourceGroupID the ID of the group under which the resource should * be stored * @param resourceDescription the description/ID of the resource * @param resourcePath the path to the resource */ public static synchronized void addPluginResource(String resourceGroupID, String resourceDescription, String resourcePath) { weka.core.PluginManager.addPlugin(resourceGroupID, resourceDescription, resourcePath); } /** * Get an input stream for a named resource under a given resource group ID. * * @param resourceGroupID the group ID that the resource falls under * @param resourceDescription the description/ID of the resource * @return an InputStream for the resource * @throws IOException if the group ID or resource description/ID are not * known to the PluginManager, or a problem occurs while trying to * open an input stream */ public static InputStream getPluginResourceAsStream(String resourceGroupID, String resourceDescription) throws IOException { return weka.core.PluginManager.getPluginResourceAsStream(resourceGroupID, resourceDescription); } /** * Get the number of resources available under a given resource group ID. * * @param resourceGroupID the group ID of the resources * @return the number of resources registered under the supplied group ID */ public static int numResourcesForWithGroupID(String resourceGroupID) { return weka.core.PluginManager.numResourcesForWithGroupID(resourceGroupID); } /** * Get a map of resources (description,path) registered under a given resource * group ID. * * @param resourceGroupID the group ID of the resources to get * @return a map of resources registered under the supplied group ID, or null * if the resourceGroupID is not known to the plugin manager */ public static Map<String, String> getResourcesWithGroupID( String resourceGroupID) { return weka.core.PluginManager.getResourcesWithGroupID(resourceGroupID); } /** * Get a set of names of plugins that implement the supplied interface. * * @param interfaceName the fully qualified name of the interface to list * plugins for * * @return a set of names of plugins */ public static Set<String> getPluginNamesOfType(String interfaceName) { return weka.core.PluginManager.getPluginNamesOfType(interfaceName); } /** * Add a plugin. * * @param interfaceName the fully qualified interface name that the plugin * implements * * @param name the name/short description of the plugin * @param concreteType the fully qualified class name of the actual concrete * implementation */ public static void addPlugin(String interfaceName, String name, String concreteType) { weka.core.PluginManager.addPlugin(interfaceName, name, concreteType); } /** * Add a plugin. * * @param interfaceName the fully qualified interface name that the plugin * implements * * @param name the name/short description of the plugin * @param concreteType the fully qualified class name of the actual concrete * implementation * @param maintainInsertionOrder true if the order of insertion of * implementations is to be preserved (rather than sorted order) */ public static void addPlugin(String interfaceName, String name, String concreteType, boolean maintainInsertionOrder) { weka.core.PluginManager.addPlugin(interfaceName, name, concreteType, maintainInsertionOrder); } /** * Remove plugins of a specific type. * * @param interfaceName the fully qualified interface name that the plugins to * be remove implement * @param names a list of named plugins to remove */ public static void removePlugins(String interfaceName, List<String> names) { for (String name : names) { weka.core.PluginManager.removePlugins(interfaceName, names); } } /** * Remove a plugin. * * @param interfaceName the fully qualified interface name that the plugin * implements * * @param name the name/short description of the plugin */ public static void removePlugin(String interfaceName, String name) { weka.core.PluginManager.removePlugin(interfaceName, name); } /** * Get an instance of a concrete implementation of a plugin type * * @param interfaceType the fully qualified interface name of the plugin type * @param name the name/short description of the plugin to get * @return the concrete plugin or null if the plugin is disabled * @throws Exception if the plugin can't be found or instantiated */ public static Object getPluginInstance(String interfaceType, String name) throws Exception { return weka.core.PluginManager.getPluginInstance(interfaceType, name); } }
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/PredictionAppender.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * PredictionAppender.java * Copyright (C) 2003-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.List; import java.util.Vector; import javax.swing.JPanel; import weka.clusterers.DensityBasedClusterer; import weka.core.DenseInstance; import weka.core.Instance; import weka.core.Instances; /** * Bean that can can accept batch or incremental classifier events and produce * dataset or instance events which contain instances with predictions appended. * * @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a> * @version $Revision$ */ public class PredictionAppender extends JPanel implements DataSource, TrainingSetProducer, TestSetProducer, Visible, BeanCommon, EventConstraints, BatchClassifierListener, IncrementalClassifierListener, BatchClustererListener, Serializable { /** for serialization */ private static final long serialVersionUID = -2987740065058976673L; /** * Objects listenening for dataset events */ protected Vector<DataSourceListener> m_dataSourceListeners = new Vector<DataSourceListener>(); /** * Objects listening for instances events */ protected Vector<InstanceListener> m_instanceListeners = new Vector<InstanceListener>(); /** * Objects listening for training set events */ protected Vector<TrainingSetListener> m_trainingSetListeners = new Vector<TrainingSetListener>();; /** * Objects listening for test set events */ protected Vector<TestSetListener> m_testSetListeners = new Vector<TestSetListener>(); /** * Non null if this object is a target for any events. */ protected Object m_listenee = null; /** * Format of instances to be produced. */ protected Instances m_format; protected BeanVisual m_visual = new BeanVisual("PredictionAppender", BeanVisual.ICON_PATH + "PredictionAppender.gif", BeanVisual.ICON_PATH + "PredictionAppender_animated.gif"); /** * Append classifier's predicted probabilities (if the class is discrete and * the classifier is a distribution classifier) */ protected boolean m_appendProbabilities; protected transient weka.gui.Logger m_logger; protected transient List<Integer> m_stringAttIndexes; /** * Global description of this bean * * @return a <code>String</code> value */ public String globalInfo() { return "Accepts batch or incremental classifier events and " + "produces a new data set with classifier predictions appended."; } /** * Creates a new <code>PredictionAppender</code> instance. */ public PredictionAppender() { 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(); } /** * Return a tip text suitable for displaying in a GUI * * @return a <code>String</code> value */ public String appendPredictedProbabilitiesTipText() { return "append probabilities rather than labels for discrete class " + "predictions"; } /** * Return true if predicted probabilities are to be appended rather than class * value * * @return a <code>boolean</code> value */ public boolean getAppendPredictedProbabilities() { return m_appendProbabilities; } /** * Set whether to append predicted probabilities rather than class value (for * discrete class data sets) * * @param ap a <code>boolean</code> value */ public void setAppendPredictedProbabilities(boolean ap) { m_appendProbabilities = ap; } /** * Add a training set listener * * @param tsl a <code>TrainingSetListener</code> value */ @Override public void addTrainingSetListener(TrainingSetListener tsl) { // TODO Auto-generated method stub m_trainingSetListeners.addElement(tsl); // pass on any format that we might have determined so far if (m_format != null) { TrainingSetEvent e = new TrainingSetEvent(this, m_format); tsl.acceptTrainingSet(e); } } /** * Remove a training set listener * * @param tsl a <code>TrainingSetListener</code> value */ @Override public void removeTrainingSetListener(TrainingSetListener tsl) { m_trainingSetListeners.removeElement(tsl); } /** * Add a test set listener * * @param tsl a <code>TestSetListener</code> value */ @Override public void addTestSetListener(TestSetListener tsl) { m_testSetListeners.addElement(tsl); // pass on any format that we might have determined so far if (m_format != null) { TestSetEvent e = new TestSetEvent(this, m_format); tsl.acceptTestSet(e); } } /** * Remove a test set listener * * @param tsl a <code>TestSetListener</code> value */ @Override public void removeTestSetListener(TestSetListener tsl) { m_testSetListeners.removeElement(tsl); } /** * Add a datasource listener * * @param dsl a <code>DataSourceListener</code> value */ @Override public synchronized void addDataSourceListener(DataSourceListener dsl) { m_dataSourceListeners.addElement(dsl); // pass on any format that we might have determined so far if (m_format != null) { DataSetEvent e = new DataSetEvent(this, m_format); dsl.acceptDataSet(e); } } /** * Remove a datasource listener * * @param dsl a <code>DataSourceListener</code> value */ @Override public synchronized void removeDataSourceListener(DataSourceListener dsl) { m_dataSourceListeners.remove(dsl); } /** * Add an instance listener * * @param dsl a <code>InstanceListener</code> value */ @Override public synchronized void addInstanceListener(InstanceListener dsl) { m_instanceListeners.addElement(dsl); // pass on any format that we might have determined so far if (m_format != null) { InstanceEvent e = new InstanceEvent(this, m_format); dsl.acceptInstance(e); } } /** * Remove an instance listener * * @param dsl a <code>InstanceListener</code> value */ @Override public synchronized void removeInstanceListener(InstanceListener dsl) { m_instanceListeners.remove(dsl); } /** * Set the visual for this data source * * @param newVisual a <code>BeanVisual</code> value */ @Override public void setVisual(BeanVisual newVisual) { m_visual = newVisual; } /** * Get the visual being used by this data source. * */ @Override public BeanVisual getVisual() { return m_visual; } /** * Use the default images for a data source * */ @Override public void useDefaultVisual() { m_visual.loadIcons(BeanVisual.ICON_PATH + "PredictionAppender.gif", BeanVisual.ICON_PATH + "PredictionAppender_animated.gif"); } protected InstanceEvent m_instanceEvent; protected transient StreamThroughput m_throughput; /** * Accept and process an incremental classifier event * * @param e an <code>IncrementalClassifierEvent</code> value */ @Override public void acceptClassifier(IncrementalClassifierEvent e) { weka.classifiers.Classifier classifier = e.getClassifier(); Instance currentI = e.getCurrentInstance(); int status = e.getStatus(); int oldNumAtts = 0; if (status == IncrementalClassifierEvent.NEW_BATCH) { oldNumAtts = e.getStructure().numAttributes(); m_throughput = new StreamThroughput(statusMessagePrefix()); } else { if (currentI != null) { oldNumAtts = currentI.dataset().numAttributes(); } } if (status == IncrementalClassifierEvent.NEW_BATCH) { m_instanceEvent = new InstanceEvent(this, null, 0); // create new header structure Instances oldStructure = new Instances(e.getStructure(), 0); // String relationNameModifier = oldStructure.relationName() // +"_with predictions"; // check for string attributes m_stringAttIndexes = new ArrayList<Integer>(); for (int i = 0; i < e.getStructure().numAttributes(); i++) { if (e.getStructure().attribute(i).isString()) { m_stringAttIndexes.add(new Integer(i)); } } String relationNameModifier = "_with predictions"; // +"_with predictions"; if (!m_appendProbabilities || oldStructure.classAttribute().isNumeric()) { try { m_format = makeDataSetClass(oldStructure, oldStructure, classifier, relationNameModifier); } catch (Exception ex) { ex.printStackTrace(); return; } } else if (m_appendProbabilities) { try { m_format = makeDataSetProbabilities(oldStructure, oldStructure, classifier, relationNameModifier); } catch (Exception ex) { ex.printStackTrace(); return; } } // Pass on the structure m_instanceEvent.setStructure(m_format); notifyInstanceAvailable(m_instanceEvent); return; } if (currentI != null) { m_throughput.updateStart(); double[] instanceVals = new double[m_format.numAttributes()]; Instance newInst = null; try { // process the actual instance for (int i = 0; i < oldNumAtts; i++) { instanceVals[i] = currentI.value(i); } if (!m_appendProbabilities || currentI.dataset().classAttribute().isNumeric()) { double predClass = classifier.classifyInstance(currentI); instanceVals[instanceVals.length - 1] = predClass; } else if (m_appendProbabilities) { double[] preds = classifier.distributionForInstance(currentI); for (int i = oldNumAtts; i < instanceVals.length; i++) { instanceVals[i] = preds[i - oldNumAtts]; } } } catch (Exception ex) { ex.printStackTrace(); return; } finally { newInst = new DenseInstance(currentI.weight(), instanceVals); newInst.setDataset(m_format); // check for string attributes if (m_stringAttIndexes != null) { for (int i = 0; i < m_stringAttIndexes.size(); i++) { int index = m_stringAttIndexes.get(i); m_format.attribute(m_stringAttIndexes.get(i)).setStringValue( currentI.stringValue(index)); } } m_instanceEvent.setInstance(newInst); m_instanceEvent.setStatus(status); m_throughput.updateEnd(m_logger); // notify listeners notifyInstanceAvailable(m_instanceEvent); } } else { m_instanceEvent.setInstance(null); // end of stream // notify listeners notifyInstanceAvailable(m_instanceEvent); } if (status == IncrementalClassifierEvent.BATCH_FINISHED || currentI == null) { // clean up // m_incrementalStructure = null; m_instanceEvent = null; m_throughput.finished(m_logger); } } /** * Accept and process a batch classifier event * * @param e a <code>BatchClassifierEvent</code> value */ @Override public void acceptClassifier(BatchClassifierEvent e) { if (m_dataSourceListeners.size() > 0 || m_trainingSetListeners.size() > 0 || m_testSetListeners.size() > 0) { if (e.getTestSet() == null) { // can't append predictions return; } if ((e.getTestSet().isStructureOnly() || e.getTestSet().getDataSet() .numInstances() == 0) && e.getTestSet().getDataSet().classIndex() < 0) { return; // don't do anything or make a fuss if there is no class set in // a structure only data set } if (e.getTestSet().getDataSet().classIndex() < 0) { if (m_logger != null) { m_logger.logMessage("[PredictionAppender] " + statusMessagePrefix() + "No class attribute set in the data!"); m_logger.statusMessage(statusMessagePrefix() + "ERROR: Can't append probablities - see log."); } stop(); return; } Instances testSet = e.getTestSet().getDataSet(); Instances trainSet = e.getTrainSet().getDataSet(); int setNum = e.getSetNumber(); int maxNum = e.getMaxSetNumber(); weka.classifiers.Classifier classifier = e.getClassifier(); String relationNameModifier = "_set_" + e.getSetNumber() + "_of_" + e.getMaxSetNumber(); if (!m_appendProbabilities || testSet.classAttribute().isNumeric()) { try { Instances newTestSetInstances = makeDataSetClass(testSet, trainSet, classifier, relationNameModifier); Instances newTrainingSetInstances = makeDataSetClass(trainSet, trainSet, classifier, relationNameModifier); if (m_trainingSetListeners.size() > 0) { TrainingSetEvent tse = new TrainingSetEvent(this, new Instances(newTrainingSetInstances, 0)); tse.m_setNumber = setNum; tse.m_maxSetNumber = maxNum; notifyTrainingSetAvailable(tse); // fill in predicted values for (int i = 0; i < trainSet.numInstances(); i++) { double predClass = classifier.classifyInstance(trainSet.instance(i)); newTrainingSetInstances.instance(i).setValue( newTrainingSetInstances.numAttributes() - 1, predClass); } tse = new TrainingSetEvent(this, newTrainingSetInstances); tse.m_setNumber = setNum; tse.m_maxSetNumber = maxNum; notifyTrainingSetAvailable(tse); } if (m_testSetListeners.size() > 0) { TestSetEvent tse = new TestSetEvent(this, new Instances(newTestSetInstances, 0)); tse.m_setNumber = setNum; tse.m_maxSetNumber = maxNum; notifyTestSetAvailable(tse); } if (m_dataSourceListeners.size() > 0) { notifyDataSetAvailable(new DataSetEvent(this, new Instances( newTestSetInstances, 0))); } if (e.getTestSet().isStructureOnly()) { m_format = newTestSetInstances; } if (m_dataSourceListeners.size() > 0 || m_testSetListeners.size() > 0) { // fill in predicted values for (int i = 0; i < testSet.numInstances(); i++) { Instance tempInst = testSet.instance(i); // if the class value is missing, then copy the instance // and set the data set to the training data. This is // just in case this test data was loaded from a CSV file // with all missing values for a nominal class (in this // case we have no information on the legal class values // in the test data) if (tempInst.isMissing(tempInst.classIndex()) && !(classifier instanceof weka.classifiers.misc.InputMappedClassifier)) { tempInst = (Instance) testSet.instance(i).copy(); tempInst.setDataset(trainSet); } double predClass = classifier.classifyInstance(tempInst); newTestSetInstances.instance(i).setValue( newTestSetInstances.numAttributes() - 1, predClass); } } // notify listeners if (m_testSetListeners.size() > 0) { TestSetEvent tse = new TestSetEvent(this, newTestSetInstances); tse.m_setNumber = setNum; tse.m_maxSetNumber = maxNum; notifyTestSetAvailable(tse); } if (m_dataSourceListeners.size() > 0) { notifyDataSetAvailable(new DataSetEvent(this, newTestSetInstances)); } return; } catch (Exception ex) { ex.printStackTrace(); } } if (m_appendProbabilities) { try { Instances newTestSetInstances = makeDataSetProbabilities(testSet, trainSet, classifier, relationNameModifier); Instances newTrainingSetInstances = makeDataSetProbabilities(trainSet, trainSet, classifier, relationNameModifier); if (m_trainingSetListeners.size() > 0) { TrainingSetEvent tse = new TrainingSetEvent(this, new Instances(newTrainingSetInstances, 0)); tse.m_setNumber = setNum; tse.m_maxSetNumber = maxNum; notifyTrainingSetAvailable(tse); // fill in predicted probabilities for (int i = 0; i < trainSet.numInstances(); i++) { double[] preds = classifier.distributionForInstance(trainSet.instance(i)); for (int j = 0; j < trainSet.classAttribute().numValues(); j++) { newTrainingSetInstances.instance(i).setValue( trainSet.numAttributes() + j, preds[j]); } } tse = new TrainingSetEvent(this, newTrainingSetInstances); tse.m_setNumber = setNum; tse.m_maxSetNumber = maxNum; notifyTrainingSetAvailable(tse); } if (m_testSetListeners.size() > 0) { TestSetEvent tse = new TestSetEvent(this, new Instances(newTestSetInstances, 0)); tse.m_setNumber = setNum; tse.m_maxSetNumber = maxNum; notifyTestSetAvailable(tse); } if (m_dataSourceListeners.size() > 0) { notifyDataSetAvailable(new DataSetEvent(this, new Instances( newTestSetInstances, 0))); } if (e.getTestSet().isStructureOnly()) { m_format = newTestSetInstances; } if (m_dataSourceListeners.size() > 0 || m_testSetListeners.size() > 0) { // fill in predicted probabilities for (int i = 0; i < testSet.numInstances(); i++) { Instance tempInst = testSet.instance(i); // if the class value is missing, then copy the instance // and set the data set to the training data. This is // just in case this test data was loaded from a CSV file // with all missing values for a nominal class (in this // case we have no information on the legal class values // in the test data) if (tempInst.isMissing(tempInst.classIndex()) && !(classifier instanceof weka.classifiers.misc.InputMappedClassifier)) { tempInst = (Instance) testSet.instance(i).copy(); tempInst.setDataset(trainSet); } double[] preds = classifier.distributionForInstance(tempInst); for (int j = 0; j < tempInst.classAttribute().numValues(); j++) { newTestSetInstances.instance(i).setValue( testSet.numAttributes() + j, preds[j]); } } } // notify listeners if (m_testSetListeners.size() > 0) { TestSetEvent tse = new TestSetEvent(this, newTestSetInstances); tse.m_setNumber = setNum; tse.m_maxSetNumber = maxNum; notifyTestSetAvailable(tse); } if (m_dataSourceListeners.size() > 0) { notifyDataSetAvailable(new DataSetEvent(this, newTestSetInstances)); } } catch (Exception ex) { ex.printStackTrace(); } } } } /** * Accept and process a batch clusterer event * * @param e a <code>BatchClassifierEvent</code> value */ @Override public void acceptClusterer(BatchClustererEvent e) { if (m_dataSourceListeners.size() > 0 || m_trainingSetListeners.size() > 0 || m_testSetListeners.size() > 0) { if (e.getTestSet().isStructureOnly()) { return; } Instances testSet = e.getTestSet().getDataSet(); weka.clusterers.Clusterer clusterer = e.getClusterer(); String test; if (e.getTestOrTrain() == 0) { test = "test"; } else { test = "training"; } String relationNameModifier = "_" + test + "_" + e.getSetNumber() + "_of_" + e.getMaxSetNumber(); if (!m_appendProbabilities || !(clusterer instanceof DensityBasedClusterer)) { if (m_appendProbabilities && !(clusterer instanceof DensityBasedClusterer)) { System.err .println("Only density based clusterers can append probabilities. Instead cluster will be assigned for each instance."); if (m_logger != null) { m_logger .logMessage("[PredictionAppender] " + statusMessagePrefix() + " Only density based clusterers can " + "append probabilities. Instead cluster will be assigned for each " + "instance."); m_logger .statusMessage(statusMessagePrefix() + "WARNING: Only density based clusterers can append probabilities. " + "Instead cluster will be assigned for each instance."); } } try { Instances newInstances = makeClusterDataSetClass(testSet, clusterer, relationNameModifier); // data source listeners get both train and test sets if (m_dataSourceListeners.size() > 0) { notifyDataSetAvailable(new DataSetEvent(this, new Instances( newInstances, 0))); } if (m_trainingSetListeners.size() > 0 && e.getTestOrTrain() > 0) { TrainingSetEvent tse = new TrainingSetEvent(this, new Instances(newInstances, 0)); tse.m_setNumber = e.getSetNumber(); tse.m_maxSetNumber = e.getMaxSetNumber(); notifyTrainingSetAvailable(tse); } if (m_testSetListeners.size() > 0 && e.getTestOrTrain() == 0) { TestSetEvent tse = new TestSetEvent(this, new Instances(newInstances, 0)); tse.m_setNumber = e.getSetNumber(); tse.m_maxSetNumber = e.getMaxSetNumber(); notifyTestSetAvailable(tse); } // fill in predicted values for (int i = 0; i < testSet.numInstances(); i++) { double predCluster = clusterer.clusterInstance(testSet.instance(i)); newInstances.instance(i).setValue(newInstances.numAttributes() - 1, predCluster); } // notify listeners if (m_dataSourceListeners.size() > 0) { notifyDataSetAvailable(new DataSetEvent(this, newInstances)); } if (m_trainingSetListeners.size() > 0 && e.getTestOrTrain() > 0) { TrainingSetEvent tse = new TrainingSetEvent(this, newInstances); tse.m_setNumber = e.getSetNumber(); tse.m_maxSetNumber = e.getMaxSetNumber(); notifyTrainingSetAvailable(tse); } if (m_testSetListeners.size() > 0 && e.getTestOrTrain() == 0) { TestSetEvent tse = new TestSetEvent(this, newInstances); tse.m_setNumber = e.getSetNumber(); tse.m_maxSetNumber = e.getMaxSetNumber(); notifyTestSetAvailable(tse); } return; } catch (Exception ex) { ex.printStackTrace(); } } else { try { Instances newInstances = makeClusterDataSetProbabilities(testSet, clusterer, relationNameModifier); notifyDataSetAvailable(new DataSetEvent(this, new Instances( newInstances, 0))); // fill in predicted probabilities for (int i = 0; i < testSet.numInstances(); i++) { double[] probs = clusterer.distributionForInstance(testSet.instance(i)); for (int j = 0; j < clusterer.numberOfClusters(); j++) { newInstances.instance(i).setValue(testSet.numAttributes() + j, probs[j]); } } // notify listeners notifyDataSetAvailable(new DataSetEvent(this, newInstances)); } catch (Exception ex) { ex.printStackTrace(); } } } } private Instances makeDataSetProbabilities(Instances insts, Instances format, weka.classifiers.Classifier classifier, String relationNameModifier) throws Exception { // adjust structure for InputMappedClassifier (if necessary) if (classifier instanceof weka.classifiers.misc.InputMappedClassifier) { format = ((weka.classifiers.misc.InputMappedClassifier) classifier) .getModelHeader(new Instances(format, 0)); } String classifierName = classifier.getClass().getName(); classifierName = classifierName.substring(classifierName.lastIndexOf('.') + 1, classifierName.length()); Instances newInstances = new Instances(insts); for (int i = 0; i < format.classAttribute().numValues(); i++) { weka.filters.unsupervised.attribute.Add addF = new weka.filters.unsupervised.attribute.Add(); addF.setAttributeIndex("last"); addF.setAttributeName(classifierName + "_prob_" + format.classAttribute().value(i)); addF.setInputFormat(newInstances); newInstances = weka.filters.Filter.useFilter(newInstances, addF); } newInstances.setRelationName(insts.relationName() + relationNameModifier); return newInstances; } private Instances makeDataSetClass(Instances insts, Instances structure, weka.classifiers.Classifier classifier, String relationNameModifier) throws Exception { // adjust structure for InputMappedClassifier (if necessary) if (classifier instanceof weka.classifiers.misc.InputMappedClassifier) { structure = ((weka.classifiers.misc.InputMappedClassifier) classifier) .getModelHeader(new Instances(structure, 0)); } weka.filters.unsupervised.attribute.Add addF = new weka.filters.unsupervised.attribute.Add(); addF.setAttributeIndex("last"); String classifierName = classifier.getClass().getName(); classifierName = classifierName.substring(classifierName.lastIndexOf('.') + 1, classifierName.length()); addF.setAttributeName("class_predicted_by: " + classifierName); if (structure.classAttribute().isNominal()) { String classLabels = ""; Enumeration<Object> enu = structure.classAttribute().enumerateValues(); classLabels += (String) enu.nextElement(); while (enu.hasMoreElements()) { classLabels += "," + (String) enu.nextElement(); } addF.setNominalLabels(classLabels); } addF.setInputFormat(insts); Instances newInstances = weka.filters.Filter.useFilter(insts, addF); newInstances.setRelationName(insts.relationName() + relationNameModifier); return newInstances; } private Instances makeClusterDataSetProbabilities(Instances format, weka.clusterers.Clusterer clusterer, String relationNameModifier) throws Exception { Instances newInstances = new Instances(format); for (int i = 0; i < clusterer.numberOfClusters(); i++) { weka.filters.unsupervised.attribute.Add addF = new weka.filters.unsupervised.attribute.Add(); addF.setAttributeIndex("last"); addF.setAttributeName("prob_cluster" + i); addF.setInputFormat(newInstances); newInstances = weka.filters.Filter.useFilter(newInstances, addF); } newInstances.setRelationName(format.relationName() + relationNameModifier); return newInstances; } private Instances makeClusterDataSetClass(Instances format, weka.clusterers.Clusterer clusterer, String relationNameModifier) throws Exception { weka.filters.unsupervised.attribute.Add addF = new weka.filters.unsupervised.attribute.Add(); addF.setAttributeIndex("last"); String clustererName = clusterer.getClass().getName(); clustererName = clustererName.substring(clustererName.lastIndexOf('.') + 1, clustererName.length()); addF.setAttributeName("assigned_cluster: " + clustererName); // if (format.classAttribute().isNominal()) { String clusterLabels = "0"; /* * Enumeration enu = format.classAttribute().enumerateValues(); * clusterLabels += (String)enu.nextElement(); while (enu.hasMoreElements()) * { clusterLabels += ","+(String)enu.nextElement(); } */ for (int i = 1; i <= clusterer.numberOfClusters() - 1; i++) { clusterLabels += "," + i; } addF.setNominalLabels(clusterLabels); // } addF.setInputFormat(format); Instances newInstances = weka.filters.Filter.useFilter(format, addF); newInstances.setRelationName(format.relationName() + relationNameModifier); return newInstances; } /** * Notify all instance listeners that an instance is available * * @param e an <code>InstanceEvent</code> value */ @SuppressWarnings("unchecked") protected void notifyInstanceAvailable(InstanceEvent e) { Vector<InstanceListener> l; synchronized (this) { l = (Vector<InstanceListener>) m_instanceListeners.clone(); } if (l.size() > 0) { for (int i = 0; i < l.size(); i++) { l.elementAt(i).acceptInstance(e); } } } /** * Notify all Data source listeners that a data set is available * * @param e a <code>DataSetEvent</code> value */ @SuppressWarnings("unchecked") protected void notifyDataSetAvailable(DataSetEvent e) { Vector<DataSourceListener> l; synchronized (this) { l = (Vector<DataSourceListener>) m_dataSourceListeners.clone(); } if (l.size() > 0) { for (int i = 0; i < l.size(); i++) { l.elementAt(i).acceptDataSet(e); } } } /** * Notify all test set listeners that a test set is available * * @param e a <code>TestSetEvent</code> value */ @SuppressWarnings("unchecked") protected void notifyTestSetAvailable(TestSetEvent e) { Vector<TestSetListener> l; synchronized (this) { l = (Vector<TestSetListener>) m_testSetListeners.clone(); } if (l.size() > 0) { for (int i = 0; i < l.size(); i++) { l.elementAt(i).acceptTestSet(e); } } } /** * Notify all test set listeners that a test set is available * * @param e a <code>TestSetEvent</code> value */ @SuppressWarnings("unchecked") protected void notifyTrainingSetAvailable(TrainingSetEvent e) { Vector<TrainingSetListener> l; synchronized (this) { l = (Vector<TrainingSetListener>) m_trainingSetListeners.clone(); } if (l.size() > 0) { for (int i = 0; i < l.size(); i++) { l.elementAt(i).acceptTrainingSet(e); } } } /** * Set a logger * * @param logger a <code>weka.gui.Logger</code> value */ @Override public void setLog(weka.gui.Logger logger) { m_logger = logger; } @Override public void stop() { // tell the listenee (upstream bean) to stop if (m_listenee instanceof 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; } /** * Returns true if, at this time, the object will accept a connection * according to the supplied event name * * @param eventName the event * @return true if the object will accept a connection */ @Override public boolean connectionAllowed(String eventName) { return (m_listenee == null); } /** * 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_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 name * @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_listenee == source) { m_listenee = null; m_format = null; // assume any calculated instance format if now invalid } } /** * 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 (eventName.equals("instance")) { if (!((EventConstraints) m_listenee) .eventGeneratable("incrementalClassifier")) { return false; } } if (eventName.equals("dataSet") || eventName.equals("trainingSet") || eventName.equals("testSet")) { if (((EventConstraints) m_listenee).eventGeneratable("batchClassifier")) { return true; } if (((EventConstraints) m_listenee).eventGeneratable("batchClusterer")) { return true; } 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/PredictionAppenderBeanInfo.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * PredictionAppenderBeanInfo.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.PropertyDescriptor; import java.beans.SimpleBeanInfo; /** * Bean info class for PredictionAppender. * * @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a> * @version $Revision$ * @since 1.0 * @see SimpleBeanInfo */ public class PredictionAppenderBeanInfo extends SimpleBeanInfo { /** * Get the event set descriptors pertinent to data sources * * @return an <code>EventSetDescriptor[]</code> value */ public EventSetDescriptor [] getEventSetDescriptors() { try { EventSetDescriptor [] esds = { new EventSetDescriptor(PredictionAppender.class, "dataSet", DataSourceListener.class, "acceptDataSet"), new EventSetDescriptor(PredictionAppender.class, "instance", InstanceListener.class, "acceptInstance"), new EventSetDescriptor(PredictionAppender.class, "trainingSet", TrainingSetListener.class, "acceptTrainingSet"), new EventSetDescriptor(PredictionAppender.class, "testSet", TestSetListener.class, "acceptTestSet") }; return esds; } catch (Exception ex) { ex.printStackTrace(); } return null; } /** * Return the property descriptors for this bean * * @return a <code>PropertyDescriptor[]</code> value */ public PropertyDescriptor[] getPropertyDescriptors() { try { PropertyDescriptor p1; p1 = new PropertyDescriptor("appendPredictedProbabilities", PredictionAppender.class); PropertyDescriptor [] pds = { p1 }; 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.PredictionAppender.class, PredictionAppenderCustomizer.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/PredictionAppenderCustomizer.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * PredictionAppenderCustomizer.java * Copyright (C) 2003-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.beans; import weka.gui.PropertySheetPanel; import javax.swing.JButton; import javax.swing.JPanel; 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; /** * GUI Customizer for the prediction appender bean * * @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a> * @version $Revision$ */ public class PredictionAppenderCustomizer extends JPanel implements BeanCustomizer, CustomizerCloseRequester, CustomizerClosingListener { /** for serialization */ private static final long serialVersionUID = 6884933202506331888L; private PropertyChangeSupport m_pcSupport = new PropertyChangeSupport(this); private PropertySheetPanel m_paEditor = new PropertySheetPanel(); private PredictionAppender m_appender; private boolean m_appendProbsBackup; private ModifyListener m_modifyListener; private Window m_parent; public PredictionAppenderCustomizer() { setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 5, 5, 5)); setLayout(new BorderLayout()); add(m_paEditor, BorderLayout.CENTER); add(new javax.swing.JLabel("PredcitionAppenderCustomizer"), 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) { m_modifyListener.setModifiedStatus(PredictionAppenderCustomizer.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 PredictionAppender object */ public void setObject(Object object) { m_appender = ((PredictionAppender)object); m_paEditor.setTarget(m_appender); m_appendProbsBackup = m_appender.getAppendPredictedProbabilities(); } /** * 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 value m_appender.setAppendPredictedProbabilities(m_appendProbsBackup); } }
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/SQLViewerPerspective.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * SQLViewerPerspective.java * Copyright (C) 2011-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.beans; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.beans.beancontext.BeanContextSupport; import javax.swing.*; import weka.core.Instances; import weka.core.converters.DatabaseLoader; import weka.gui.beans.KnowledgeFlowApp.MainKFPerspective; import weka.gui.sql.SqlViewer; import weka.gui.sql.event.ConnectionEvent; import weka.gui.sql.event.ConnectionListener; /** * Simple Knowledge Flow perspective that wraps the SqlViewer class * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision$ */ public class SQLViewerPerspective extends JPanel implements KnowledgeFlowApp.KFPerspective { /** * For serialization */ private static final long serialVersionUID = 3684166225482042972L; protected MainKFPerspective m_mainPerspective; protected SqlViewer m_viewer; protected JButton m_newFlowBut; /** * Constructor */ public SQLViewerPerspective() { setLayout(new BorderLayout()); m_viewer = new SqlViewer(null); add(m_viewer, BorderLayout.CENTER); m_newFlowBut = new JButton("New Flow"); m_newFlowBut.setToolTipText("Set up a new Knowledge Flow with the " + "current connection and query"); JPanel butHolder = new JPanel(); butHolder.add(m_newFlowBut); add(butHolder, BorderLayout.SOUTH); m_newFlowBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (m_mainPerspective != null) { newFlow(); } } }); m_newFlowBut.setEnabled(false); m_viewer.addConnectionListener(new ConnectionListener() { @Override public void connectionChange(ConnectionEvent evt) { if (evt.getType() == ConnectionEvent.DISCONNECT) { m_newFlowBut.setEnabled(false); } else { m_newFlowBut.setEnabled(true); } } }); } protected void newFlow() { m_newFlowBut.setEnabled(false); String user = m_viewer.getUser(); String password = m_viewer.getPassword(); String uRL = m_viewer.getURL(); String query = m_viewer.getQuery(); if (query == null) { query = ""; } try { DatabaseLoader dbl = new DatabaseLoader(); dbl.setUser(user); dbl.setPassword(password); dbl.setUrl(uRL); dbl.setQuery(query); BeanContextSupport bc = new BeanContextSupport(); bc.setDesignTime(true); Loader loaderComp = new Loader(); bc.add(loaderComp); loaderComp.setLoader(dbl); KnowledgeFlowApp singleton = KnowledgeFlowApp.getSingleton(); m_mainPerspective.addTab("DBSource"); // The process of creating a BeanInstance integrates will result // in it integrating itself into the flow in the specified tab new BeanInstance(m_mainPerspective.getBeanLayout(m_mainPerspective .getNumTabs() - 1), loaderComp, 50, 50, m_mainPerspective.getNumTabs() - 1); // Vector<Object> beans = BeanInstance.getBeanInstances(m_mainPerspective // .getNumTabs() - 1); // Vector<BeanConnection> connections = BeanConnection // .getConnections(m_mainPerspective.getNumTabs() - 1); // singleton.integrateFlow(beans, connections, true, false); singleton.setActivePerspective(0); // switch back to the main perspective m_newFlowBut.setEnabled(true); } catch (Exception ex) { ex.printStackTrace(); } } /** * Set instances (if the perspective accepts them) * * @param insts the instances */ @Override public void setInstances(Instances insts) throws Exception { // nothing to do - we don't take instances } /** * Returns true if this perspective accepts instances * * @return true if this perspective can accept instances */ @Override public boolean acceptsInstances() { return false; } /** * Get the title of this perspective * * @return the title of this perspective */ @Override public String getPerspectiveTitle() { return "SQL Viewer"; } /** * Get the tool tip text for this perspective. * * @return the tool tip text for this perspective */ @Override public String getPerspectiveTipText() { return "Explore database tables with SQL"; } /** * 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/database.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) { // nothing to do } /** * 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) { // nothing to do } /** * 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(MainKFPerspective main) { // nothing to do (could potentially create a new flow in // the knowledge flow with a configured DatabaseLoader). m_mainPerspective = main; } /** * Main method for testing this class * * @param args command line arguments */ public static void main(String[] args) { final javax.swing.JFrame jf = new javax.swing.JFrame(); jf.getContentPane().setLayout(new java.awt.BorderLayout()); SQLViewerPerspective p = new SQLViewerPerspective(); jf.getContentPane().add(p, 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); } }
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/Saver.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * Saver.java * Copyright (C) 2004-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.beans; import java.io.IOException; import java.io.ObjectInputStream; import weka.core.Environment; import weka.core.EnvironmentHandler; import weka.core.Instances; import weka.core.OptionHandler; import weka.core.SerializedObject; import weka.core.Utils; import weka.core.converters.ArffSaver; import weka.core.converters.DatabaseConverter; import weka.core.converters.DatabaseSaver; /** * Saves data sets using weka.core.converter classes * * @author <a href="mailto:mutter@cs.waikato.ac.nz">Stefan Mutter</a> * @version $Revision$ * */ public class Saver extends AbstractDataSink implements WekaWrapper, EnvironmentHandler { /** for serialization */ private static final long serialVersionUID = 5371716690308950755L; /** * Holds the instances to be saved */ private Instances m_dataSet; /** * Holds the structure */ private Instances m_structure; /** * Global info for the wrapped loader (if it exists). */ protected String m_globalInfo; /** * Thread for doing IO in */ private transient SaveBatchThread m_ioThread; /** * Saver */ private weka.core.converters.Saver m_Saver = new ArffSaver(); private weka.core.converters.Saver m_SaverTemplate = this.m_Saver; /** * The relation name that becomes part of the file name */ private String m_fileName; /** * Flag indicating that instances will be saved to database. Used because * structure information can only be sent after a database has been * configured. */ private boolean m_isDBSaver; /** * For file-based savers - if true (default), relation name is used as the * primary part of the filename. If false, then the prefix is used as the * filename. Useful for preventing filenames from getting too long when there * are many filters in a flow. */ private boolean m_relationNameForFilename = true; /** * Count for structure available messages */ private int m_count; /** * The environment variables. */ protected transient Environment m_env; private weka.core.converters.Saver makeCopy() throws Exception { return (weka.core.converters.Saver) new SerializedObject(this.m_SaverTemplate).getObject(); } private class SaveBatchThread extends Thread { public SaveBatchThread(final DataSink ds) { } @SuppressWarnings("deprecation") @Override public void run() { try { Saver.this.m_visual.setAnimated(); Saver.this.m_Saver.setInstances(Saver.this.m_dataSet); if (Saver.this.m_logger != null) { Saver.this.m_logger.statusMessage(Saver.this.statusMessagePrefix() + "Saving " + Saver.this.m_dataSet.relationName() + "..."); } Saver.this.m_Saver.writeBatch(); if (Saver.this.m_logger != null) { Saver.this.m_logger.logMessage("[Saver] " + Saver.this.statusMessagePrefix() + "Save successful."); } } catch (Exception ex) { if (Saver.this.m_logger != null) { Saver.this.m_logger.statusMessage(Saver.this.statusMessagePrefix() + "ERROR (See log for details)"); Saver.this.m_logger.logMessage("[Saver] " + Saver.this.statusMessagePrefix() + " problem saving. " + ex.getMessage()); } ex.printStackTrace(); } finally { if (Thread.currentThread().isInterrupted()) { if (Saver.this.m_logger != null) { Saver.this.m_logger.logMessage("[Saver] " + Saver.this.statusMessagePrefix() + " Saving interrupted!!"); } } if (Saver.this.m_logger != null) { Saver.this.m_logger.statusMessage(Saver.this.statusMessagePrefix() + "Finished."); } Saver.this.block(false); Saver.this.m_visual.setStatic(); Saver.this.m_ioThread = null; } } } /** * 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(final boolean tf) { if (tf) { try { if (this.m_ioThread.isAlive()) { this.wait(); } } catch (InterruptedException ex) { } } else { this.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 (this.m_ioThread != null); } /** * Global info (if it exists) for the wrapped loader * * @return the global info */ public String globalInfo() { return this.m_globalInfo; } /** Contsructor */ public Saver() { super(); this.setSaverTemplate(this.m_Saver); this.m_fileName = ""; this.m_dataSet = null; this.m_count = 0; } /** * 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(); } /** * Set environment variables to use. * * @param env the environment variables to use */ @Override public void setEnvironment(final Environment env) { this.m_env = env; } /** * Pass the environment variables on the the wrapped saver */ private void passEnvOnToSaver() { // set environment variables if (this.m_SaverTemplate instanceof EnvironmentHandler && this.m_env != null) { ((EnvironmentHandler) this.m_Saver).setEnvironment(this.m_env); } } /** * Set the loader to use * * @param saver a Saver */ public void setSaverTemplate(final weka.core.converters.Saver saver) { boolean loadImages = true; if (saver.getClass().getName().compareTo(this.m_SaverTemplate.getClass().getName()) == 0) { loadImages = false; } this.m_SaverTemplate = saver; String saverName = saver.getClass().toString(); saverName = saverName.substring(saverName.lastIndexOf('.') + 1, saverName.length()); if (loadImages) { if (!this.m_visual.loadIcons(BeanVisual.ICON_PATH + saverName + ".gif", BeanVisual.ICON_PATH + saverName + "_animated.gif")) { this.useDefaultVisual(); } } this.m_visual.setText(saverName); // get global info this.m_globalInfo = KnowledgeFlowApp.getGlobalInfo(this.m_SaverTemplate); if (this.m_SaverTemplate instanceof DatabaseConverter) { this.m_isDBSaver = true; } else { this.m_isDBSaver = false; } } /** * makes sure that the filename is valid, i.e., replaces slashes, backslashes * and colons with underscores ("_"). Also try to prevent filename from * becoming insanely long by removing package part of class names. * * @param filename the filename to cleanse * @return the cleansed filename */ protected String sanitizeFilename(String filename) { filename = filename.replaceAll("\\\\", "_").replaceAll(":", "_").replaceAll("/", "_"); filename = Utils.removeSubstring(filename, "weka.filters.supervised.instance."); filename = Utils.removeSubstring(filename, "weka.filters.supervised.attribute."); filename = Utils.removeSubstring(filename, "weka.filters.unsupervised.instance."); filename = Utils.removeSubstring(filename, "weka.filters.unsupervised.attribute."); filename = Utils.removeSubstring(filename, "weka.clusterers."); filename = Utils.removeSubstring(filename, "weka.associations."); filename = Utils.removeSubstring(filename, "weka.attributeSelection."); filename = Utils.removeSubstring(filename, "weka.estimators."); filename = Utils.removeSubstring(filename, "weka.datagenerators."); if (!this.m_isDBSaver && !this.m_relationNameForFilename) { filename = ""; try { if (this.m_Saver.filePrefix().equals("")) { this.m_Saver.setFilePrefix("no-name"); } } catch (Exception ex) { System.err.println(ex); } } return filename; } /** * Method reacts to a dataset event and starts the writing process in batch * mode * * @param e a dataset event */ @Override public synchronized void acceptDataSet(final DataSetEvent e) { try { this.m_Saver = this.makeCopy(); } catch (Exception ex) { if (this.m_logger != null) { this.m_logger.statusMessage(this.statusMessagePrefix() + "ERROR (See log for details)"); this.m_logger.logMessage("[Saver] " + this.statusMessagePrefix() + " unable to copy saver. " + ex.getMessage()); } } this.passEnvOnToSaver(); this.m_fileName = this.sanitizeFilename(e.getDataSet().relationName()); this.m_dataSet = e.getDataSet(); if (e.isStructureOnly() && this.m_isDBSaver && ((DatabaseSaver) this.m_SaverTemplate).getRelationForTableName()) {// ((DatabaseSaver) this.m_Saver).setTableName(this.m_fileName); } if (!e.isStructureOnly()) { if (!this.m_isDBSaver) { try { this.m_Saver.setDirAndPrefix(this.m_fileName, ""); } catch (Exception ex) { System.out.println(ex); } } this.saveBatch(); System.out.println("...relation " + this.m_fileName + " saved."); } } /** * Method reacts to a threshold data event ans starts the writing process in * batch mode. * * @param e threshold data event. */ @Override public synchronized void acceptDataSet(final ThresholdDataEvent e) { try { this.m_Saver = this.makeCopy(); } catch (Exception ex) { if (this.m_logger != null) { this.m_logger.statusMessage(this.statusMessagePrefix() + "ERROR (See log for details)"); this.m_logger.logMessage("[Saver] " + this.statusMessagePrefix() + " unable to copy saver. " + ex.getMessage()); } } this.passEnvOnToSaver(); this.m_fileName = this.sanitizeFilename(e.getDataSet().getPlotInstances().relationName()); this.m_dataSet = e.getDataSet().getPlotInstances(); if (this.m_isDBSaver && ((DatabaseSaver) this.m_SaverTemplate).getRelationForTableName()) {// ((DatabaseSaver) this.m_Saver).setTableName(this.m_fileName); ((DatabaseSaver) this.m_Saver).setRelationForTableName(false); } if (!this.m_isDBSaver) { try { this.m_Saver.setDirAndPrefix(this.m_fileName, ""); } catch (Exception ex) { System.out.println(ex); } } this.saveBatch(); System.out.println("...relation " + this.m_fileName + " saved."); } /** * Method reacts to a test set event and starts the writing process in batch * mode * * @param e test set event */ @Override public synchronized void acceptTestSet(final TestSetEvent e) { try { this.m_Saver = this.makeCopy(); } catch (Exception ex) { if (this.m_logger != null) { this.m_logger.statusMessage(this.statusMessagePrefix() + "ERROR (See log for details)"); this.m_logger.logMessage("[Saver] " + this.statusMessagePrefix() + " unable to copy saver. " + ex.getMessage()); } } this.passEnvOnToSaver(); this.m_fileName = this.sanitizeFilename(e.getTestSet().relationName()); this.m_dataSet = e.getTestSet(); if (e.isStructureOnly() && this.m_isDBSaver && ((DatabaseSaver) this.m_SaverTemplate).getRelationForTableName()) { ((DatabaseSaver) this.m_Saver).setTableName(this.m_fileName); } if (!e.isStructureOnly()) { if (!this.m_isDBSaver) { try { this.m_Saver.setDirAndPrefix(this.m_fileName, "_test_" + e.getSetNumber() + "_of_" + e.getMaxSetNumber()); } catch (Exception ex) { System.out.println(ex); } } else { ((DatabaseSaver) this.m_Saver).setRelationForTableName(false); String setName = ((DatabaseSaver) this.m_Saver).getTableName(); setName = setName.replaceFirst("_[tT][eE][sS][tT]_[0-9]+_[oO][fF]_[0-9]+", ""); ((DatabaseSaver) this.m_Saver).setTableName(setName + "_test_" + e.getSetNumber() + "_of_" + e.getMaxSetNumber()); } this.saveBatch(); System.out.println("... test set " + e.getSetNumber() + " of " + e.getMaxSetNumber() + " for relation " + this.m_fileName + " saved."); } } /** * Method reacts to a training set event and starts the writing process in * batch mode * * @param e a training set event */ @Override public synchronized void acceptTrainingSet(final TrainingSetEvent e) { try { this.m_Saver = this.makeCopy(); } catch (Exception ex) { if (this.m_logger != null) { this.m_logger.statusMessage(this.statusMessagePrefix() + "ERROR (See log for details)"); this.m_logger.logMessage("[Saver] " + this.statusMessagePrefix() + " unable to copy saver. " + ex.getMessage()); } } this.passEnvOnToSaver(); this.m_fileName = this.sanitizeFilename(e.getTrainingSet().relationName()); this.m_dataSet = e.getTrainingSet(); if (e.isStructureOnly() && this.m_isDBSaver && ((DatabaseSaver) this.m_SaverTemplate).getRelationForTableName()) { ((DatabaseSaver) this.m_Saver).setTableName(this.m_fileName); } if (!e.isStructureOnly()) { if (!this.m_isDBSaver) { try { this.m_Saver.setDirAndPrefix(this.m_fileName, "_training_" + e.getSetNumber() + "_of_" + e.getMaxSetNumber()); } catch (Exception ex) { System.out.println(ex); } } else { ((DatabaseSaver) this.m_Saver).setRelationForTableName(false); String setName = ((DatabaseSaver) this.m_Saver).getTableName(); setName = setName.replaceFirst("_[tT][rR][aA][iI][nN][iI][nN][gG]_[0-9]+_[oO][fF]_[0-9]+", ""); ((DatabaseSaver) this.m_Saver).setTableName(setName + "_training_" + e.getSetNumber() + "_of_" + e.getMaxSetNumber()); } this.saveBatch(); System.out.println("... training set " + e.getSetNumber() + " of " + e.getMaxSetNumber() + " for relation " + this.m_fileName + " saved."); } } /** Saves instances in batch mode */ public synchronized void saveBatch() { this.m_Saver.setRetrieval(weka.core.converters.Saver.BATCH); /* * String visText = this.getName(); try { visText = (m_fileName.length() > * 0) ? m_fileName : m_Saver.filePrefix(); } catch (Exception ex) { } * m_visual.setText(visText); */ this.m_ioThread = new SaveBatchThread(Saver.this); this.m_ioThread.setPriority(Thread.MIN_PRIORITY); this.m_ioThread.start(); this.block(true); } protected transient StreamThroughput m_throughput; /** * Methods reacts to instance events and saves instances incrementally. If the * instance to save is null, the file is closed and the saving process is * ended. * * @param e instance event * @throws InterruptedException */ @SuppressWarnings("deprecation") @Override public synchronized void acceptInstance(final InstanceEvent e) { if (e.getStatus() == InstanceEvent.FORMAT_AVAILABLE) { this.m_throughput = new StreamThroughput(this.statusMessagePrefix()); // start of a new stream try { this.m_Saver = this.makeCopy(); } catch (Exception ex) { if (this.m_logger != null) { this.m_logger.statusMessage(this.statusMessagePrefix() + "ERROR (See log for details)"); this.m_logger.logMessage("[Saver] " + this.statusMessagePrefix() + " unable to copy saver. " + ex.getMessage()); } } this.m_Saver.setRetrieval(weka.core.converters.Saver.INCREMENTAL); this.m_structure = e.getStructure(); this.m_fileName = this.sanitizeFilename(this.m_structure.relationName()); try { this.m_Saver.setInstances(this.m_structure); } catch (InterruptedException e1) { e1.printStackTrace(); return; } if (this.m_isDBSaver) { if (((DatabaseSaver) this.m_SaverTemplate).getRelationForTableName()) { ((DatabaseSaver) this.m_Saver).setTableName(this.m_fileName); ((DatabaseSaver) this.m_Saver).setRelationForTableName(false); } } } if (e.getStatus() == InstanceEvent.INSTANCE_AVAILABLE) { this.m_visual.setAnimated(); this.m_throughput.updateStart(); if (this.m_count == 0) { this.passEnvOnToSaver(); if (!this.m_isDBSaver) { try { this.m_Saver.setDirAndPrefix(this.m_fileName, ""); } catch (Exception ex) { System.out.println(ex); this.m_visual.setStatic(); } } this.m_count++; } try { /* * String visText = this.getName(); visText = (m_fileName.length() > 0) * ? m_fileName : m_Saver.filePrefix(); m_visual.setText(m_fileName); */ this.m_Saver.writeIncremental(e.getInstance()); this.m_throughput.updateEnd(this.m_logger); } catch (Exception ex) { this.m_visual.setStatic(); System.err.println("Instance " + e.getInstance() + " could not been saved"); ex.printStackTrace(); } } if (e.getStatus() == InstanceEvent.BATCH_FINISHED) { try { if (this.m_count == 0) { this.passEnvOnToSaver(); if (!this.m_isDBSaver) { try { this.m_Saver.setDirAndPrefix(this.m_fileName, ""); } catch (Exception ex) { System.out.println(ex); this.m_visual.setStatic(); } } this.m_count++; } this.m_Saver.writeIncremental(e.getInstance()); if (e.getInstance() != null) { this.m_throughput.updateStart(); this.m_Saver.writeIncremental(null); this.m_throughput.updateEnd(this.m_logger); } // m_firstNotice = true; this.m_visual.setStatic(); // System.out.println("...relation " + m_fileName + " saved."); /* * String visText = this.getName(); visText = (m_fileName.length() > 0) * ? m_fileName : m_Saver.filePrefix(); m_visual.setText(visText); */ this.m_count = 0; this.m_throughput.finished(this.m_logger); } catch (Exception ex) { this.m_visual.setStatic(); System.err.println("File could not have been closed."); ex.printStackTrace(); } } } /** * Get the saver * * @return a <code>weka.core.converters.Saver</code> value */ public weka.core.converters.Saver getSaverTemplate() { return this.m_SaverTemplate; } /** * Set the saver * * @param algorithm a Saver */ @Override public void setWrappedAlgorithm(final Object algorithm) { if (!(algorithm instanceof weka.core.converters.Saver)) { throw new IllegalArgumentException(algorithm.getClass() + " : incorrect " + "type of algorithm (Loader)"); } this.setSaverTemplate((weka.core.converters.Saver) algorithm); } /** * Get the saver * * @return a Saver */ @Override public Object getWrappedAlgorithm() { return this.getSaverTemplate(); } /** * Set whether to use the relation name as the primary part of the filename. * If false, then the prefix becomes the filename. * * @param r true if the relation name is to be part of the filename. */ public void setRelationNameForFilename(final boolean r) { this.m_relationNameForFilename = r; } /** * Get whether the relation name is the primary part of the filename. * * @return true if the relation name is part of the filename. */ public boolean getRelationNameForFilename() { return this.m_relationNameForFilename; } /** Stops the bean */ @SuppressWarnings("deprecation") @Override public void stop() { // tell the listenee (upstream bean) to stop if (this.m_listenee instanceof BeanCommon) { ((BeanCommon) this.m_listenee).stop(); } // stop the io thread if (this.m_ioThread != null) { this.m_ioThread.interrupt(); this.m_ioThread.stop(); this.m_ioThread = null; } this.m_count = 0; this.m_visual.setStatic(); } private String statusMessagePrefix() { return this.getCustomName() + "$" + this.hashCode() + "|" + ((this.m_Saver instanceof OptionHandler) ? Utils.joinOptions(((OptionHandler) this.m_Saver).getOptions()) + "|" : ""); } // Custom de-serialization in order to set default // environment variables on de-serialization private void readObject(final ObjectInputStream aStream) throws IOException, ClassNotFoundException { aStream.defaultReadObject(); // set a default environment to use this.m_env = Environment.getSystemWide(); } /** * The main method for testing * * @param args */ public static void main(final String[] args) { try { final javax.swing.JFrame jf = new javax.swing.JFrame(); jf.getContentPane().setLayout(new java.awt.BorderLayout()); final Saver tv = new Saver(); jf.getContentPane().add(tv, java.awt.BorderLayout.CENTER); jf.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(final java.awt.event.WindowEvent e) { jf.dispose(); System.exit(0); } }); jf.setSize(800, 600); 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/SaverBeanInfo.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * SaverBeanInfo.java * Copyright (C) 2004-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.beans; import java.beans.BeanDescriptor; /** * Bean info class for the saver bean * * @author <a href="mailto:mutter@cs.waikato.ac.nz">Stefan Mutter</a> * @version $Revision$ */ public class SaverBeanInfo extends AbstractDataSinkBeanInfo { /** * Get the bean descriptor for this bean * * @return a <code>BeanDescriptor</code> value */ public BeanDescriptor getBeanDescriptor() { return new BeanDescriptor(weka.gui.beans.Saver.class, SaverCustomizer.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/SaverCustomizer.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * SaverCustomizer.java * Copyright (C) 2004-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.beans; import java.awt.BorderLayout; import java.awt.Dialog.ModalityType; import java.awt.FlowLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.File; import java.io.IOException; import javax.swing.*; import javax.swing.filechooser.FileFilter; import weka.core.Environment; import weka.core.EnvironmentHandler; import weka.core.converters.DatabaseConverter; import weka.core.converters.DatabaseSaver; import weka.core.converters.FileSourcedConverter; import weka.gui.ExtensionFileFilter; import weka.gui.GenericObjectEditor; import weka.gui.PropertySheetPanel; /** * GUI Customizer for the saver bean * * @author <a href="mailto:mutter@cs.waikato.ac.nz">Stefan Mutter</a> * @version $Revision$ */ public class SaverCustomizer extends JPanel implements BeanCustomizer, CustomizerCloseRequester, EnvironmentHandler { /** for serialization */ private static final long serialVersionUID = -4874208115942078471L; static { GenericObjectEditor.registerEditors(); } private PropertyChangeSupport m_pcSupport = new PropertyChangeSupport(this); private weka.gui.beans.Saver m_dsSaver; private PropertySheetPanel m_SaverEditor = new PropertySheetPanel(); private JFileChooser m_fileChooser = new JFileChooser(new File(System.getProperty("user.dir"))); private Window m_parentWindow; private JDialog m_fileChooserFrame; private EnvironmentField m_dbaseURLText; private EnvironmentField m_userNameText; private JPasswordField m_passwordText; private EnvironmentField m_tableText; private JCheckBox m_truncateBox; private JCheckBox m_idBox; private JCheckBox m_tabBox; private EnvironmentField m_prefixText; private JCheckBox m_relativeFilePath; private JCheckBox m_relationNameForFilename; private Environment m_env = Environment.getSystemWide(); private EnvironmentField m_directoryText; private FileEnvironmentField m_dbProps; private ModifyListener m_modifyListener; /** Constructor */ public SaverCustomizer() { setLayout(new BorderLayout()); m_fileChooser.setDialogType(JFileChooser.SAVE_DIALOG); m_fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); m_fileChooser.setApproveButtonText("Select directory"); m_fileChooser.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals(JFileChooser.APPROVE_SELECTION)) { try { File selectedFile = m_fileChooser.getSelectedFile(); m_directoryText.setText(selectedFile.toString()); /* (m_dsSaver.getSaver()).setFilePrefix(m_prefixText.getText()); (m_dsSaver.getSaver()).setDir(m_fileChooser.getSelectedFile().getPath()); m_dsSaver. setRelationNameForFilename(m_relationNameForFilename.isSelected()); */ } catch (Exception ex) { ex.printStackTrace(); } } // closing if (m_fileChooserFrame != null) { m_fileChooserFrame.dispose(); } } }); } public void setParentWindow(Window parent) { m_parentWindow = parent; } /** Sets up dialog for saving instances in other data sinks then files * To be extended. */ private void setUpOther() { removeAll(); add(m_SaverEditor, BorderLayout.CENTER); JPanel buttonsP = new JPanel(); buttonsP.setLayout(new FlowLayout()); JButton ok,cancel; buttonsP.add(ok = new JButton("OK")); buttonsP.add(cancel=new JButton("Cancel")); ok.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent evt){ // 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_SaverEditor.closingOK(); if (m_parentWindow != null) { m_parentWindow.dispose(); } } }); cancel.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent evt){ // 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_SaverEditor.closingCancel(); if (m_parentWindow != null) { m_parentWindow.dispose(); } } }); add(buttonsP, BorderLayout.SOUTH); validate(); repaint(); } /** Sets up the dialog for saving to a database*/ private void setUpDatabase() { removeAll(); JPanel db = new JPanel(); GridBagLayout gbLayout = new GridBagLayout(); db.setLayout(gbLayout); JLabel dbaseURLLab = new JLabel(" Database URL", SwingConstants.RIGHT); dbaseURLLab.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0)); GridBagConstraints gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 0; gbConstraints.gridx = 0; gbLayout.setConstraints(dbaseURLLab, gbConstraints); db.add(dbaseURLLab); m_dbaseURLText = new EnvironmentField(); m_dbaseURLText.setEnvironment(m_env); /* int width = m_dbaseURLText.getPreferredSize().width; int height = m_dbaseURLText.getPreferredSize().height; m_dbaseURLText.setMinimumSize(new Dimension(width * 2, height)); m_dbaseURLText.setPreferredSize(new Dimension(width * 2, height)); */ m_dbaseURLText.setText(((DatabaseConverter)m_dsSaver.getSaverTemplate()).getUrl()); gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 0; gbConstraints.gridx = 1; gbConstraints.weightx = 5; gbLayout.setConstraints(m_dbaseURLText, gbConstraints); db.add(m_dbaseURLText); JLabel userLab = new JLabel("Username", SwingConstants.RIGHT); userLab.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0)); gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 1; gbConstraints.gridx = 0; gbLayout.setConstraints(userLab, gbConstraints); db.add(userLab); m_userNameText = new EnvironmentField(); m_userNameText.setEnvironment(m_env); /* m_userNameText.setMinimumSize(new Dimension(width * 2, height)); m_userNameText.setPreferredSize(new Dimension(width * 2, height)); */ m_userNameText.setText(((DatabaseConverter)m_dsSaver.getSaverTemplate()).getUser()); gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 1; gbConstraints.gridx = 1; gbLayout.setConstraints(m_userNameText, gbConstraints); db.add(m_userNameText); JLabel passwordLab = new JLabel("Password ", SwingConstants.RIGHT); passwordLab.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0)); gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 2; gbConstraints.gridx = 0; gbLayout.setConstraints(passwordLab, gbConstraints); db.add(passwordLab); m_passwordText = new JPasswordField(); m_passwordText.setText(((DatabaseSaver)m_dsSaver.getSaverTemplate()).getPassword()); JPanel passwordHolder = new JPanel(); passwordHolder.setLayout(new BorderLayout()); passwordHolder.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); passwordHolder.add(m_passwordText, BorderLayout.CENTER); /*passwordHolder.setMinimumSize(new Dimension(width * 2, height)); passwordHolder.setPreferredSize(new Dimension(width * 2, height)); */ gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 2; gbConstraints.gridx = 1; gbLayout.setConstraints(passwordHolder, gbConstraints); db.add(passwordHolder); JLabel tableLab = new JLabel("Table Name", SwingConstants.RIGHT); tableLab.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0)); gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 3; gbConstraints.gridx = 0; gbLayout.setConstraints(tableLab, gbConstraints); db.add(tableLab); m_tableText = new EnvironmentField(); m_tableText.setEnvironment(m_env); /* m_tableText.setMinimumSize(new Dimension(width * 2, height)); m_tableText.setPreferredSize(new Dimension(width * 2, height)); */ m_tableText.setEnabled(!((DatabaseSaver)m_dsSaver.getSaverTemplate()).getRelationForTableName()); m_tableText.setText(((DatabaseSaver)m_dsSaver.getSaverTemplate()).getTableName()); gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 3; gbConstraints.gridx = 1; gbLayout.setConstraints(m_tableText, gbConstraints); db.add(m_tableText); JLabel tabLab = new JLabel("Use relation name", SwingConstants.RIGHT); tabLab.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0)); gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 4; gbConstraints.gridx = 0; gbLayout.setConstraints(tabLab, gbConstraints); db.add(tabLab); m_tabBox = new JCheckBox(); m_tabBox.setSelected(((DatabaseSaver)m_dsSaver.getSaverTemplate()).getRelationForTableName()); m_tabBox.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ m_tableText.setEnabled(!m_tabBox.isSelected()); } }); gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 4; gbConstraints.gridx = 1; gbLayout.setConstraints(m_tabBox, gbConstraints); db.add(m_tabBox); JLabel truncLab = new JLabel("Truncate table", SwingConstants.RIGHT); truncLab.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0)); gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 5; gbConstraints.gridx = 0; gbLayout.setConstraints(truncLab, gbConstraints); db.add(truncLab); m_truncateBox = new JCheckBox(); m_truncateBox.setSelected(((DatabaseSaver)m_dsSaver.getSaverTemplate()).getTruncate()); gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 5; gbConstraints.gridx = 1; gbLayout.setConstraints(m_truncateBox, gbConstraints); db.add(m_truncateBox); JLabel idLab = new JLabel("Automatic primary key", SwingConstants.RIGHT); idLab.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0)); gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 6; gbConstraints.gridx = 0; gbLayout.setConstraints(idLab, gbConstraints); db.add(idLab); m_idBox = new JCheckBox(); m_idBox.setSelected(((DatabaseSaver)m_dsSaver.getSaverTemplate()).getAutoKeyGeneration()); gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 6; gbConstraints.gridx = 1; gbLayout.setConstraints(m_idBox, gbConstraints); db.add(m_idBox); JLabel propsLab = new JLabel("DB config props", SwingConstants.RIGHT); propsLab.setToolTipText("The custom properties that the user can use to override the default ones."); propsLab.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0)); gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 7; gbConstraints.gridx = 0; gbLayout.setConstraints(propsLab, gbConstraints); db.add(propsLab); m_dbProps = new FileEnvironmentField(); m_dbProps.setEnvironment(m_env); m_dbProps.resetFileFilters(); m_dbProps.addFileFilter(new ExtensionFileFilter(".props" , "DatabaseUtils property file (*.props)")); gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 7; gbConstraints.gridx = 1; gbLayout.setConstraints(m_dbProps, gbConstraints); db.add(m_dbProps); File toSet = ((DatabaseSaver)m_dsSaver.getSaverTemplate()).getCustomPropsFile(); if (toSet != null) { m_dbProps.setText(toSet.getPath()); } JButton loadPropsBut = new JButton("Load"); loadPropsBut.setToolTipText("Load config"); gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 7; gbConstraints.gridx = 2; gbLayout.setConstraints(loadPropsBut, gbConstraints); db.add(loadPropsBut); loadPropsBut.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (m_dbProps.getText() != null && m_dbProps.getText().length() > 0) { String propsS = m_dbProps.getText(); try { propsS = m_env.substitute(propsS); } catch (Exception ex) { } File propsFile = new File(propsS); if (propsFile.exists()) { ((DatabaseSaver)m_dsSaver.getSaverTemplate()).setCustomPropsFile(propsFile); ((DatabaseSaver)m_dsSaver.getSaverTemplate()).resetOptions(); m_dbaseURLText.setText(((DatabaseConverter)m_dsSaver.getSaverTemplate()).getUrl()); } } } }); JPanel buttonsP = new JPanel(); buttonsP.setLayout(new FlowLayout()); JButton ok,cancel; buttonsP.add(ok = new JButton("OK")); buttonsP.add(cancel=new JButton("Cancel")); ok.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent evt){ if (m_dbProps.getText().length() > 0) { ((DatabaseSaver)m_dsSaver.getSaverTemplate()). setCustomPropsFile(new File(m_dbProps.getText())); } ((DatabaseSaver)m_dsSaver.getSaverTemplate()).resetStructure(); ((DatabaseSaver)m_dsSaver.getSaverTemplate()).resetOptions(); ((DatabaseConverter)m_dsSaver.getSaverTemplate()).setUrl(m_dbaseURLText.getText()); ((DatabaseConverter)m_dsSaver.getSaverTemplate()).setUser(m_userNameText.getText()); ((DatabaseConverter)m_dsSaver.getSaverTemplate()).setPassword(new String(m_passwordText.getPassword())); if(!m_tabBox.isSelected()) { ((DatabaseSaver)m_dsSaver.getSaverTemplate()).setTableName(m_tableText.getText()); } ((DatabaseSaver)m_dsSaver.getSaverTemplate()).setTruncate(m_truncateBox.isSelected()); ((DatabaseSaver)m_dsSaver.getSaverTemplate()).setAutoKeyGeneration(m_idBox.isSelected()); ((DatabaseSaver)m_dsSaver.getSaverTemplate()).setRelationForTableName(m_tabBox.isSelected()); if (m_modifyListener != null) { m_modifyListener.setModifiedStatus(SaverCustomizer.this, true); } if (m_parentWindow != null) { m_parentWindow.dispose(); } } }); cancel.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent evt){ if (m_modifyListener != null) { m_modifyListener.setModifiedStatus(SaverCustomizer.this, false); } if (m_parentWindow != null) { m_parentWindow.dispose(); } } }); JPanel holderP = new JPanel(); holderP.setLayout(new BorderLayout()); holderP.add(db, BorderLayout.NORTH); holderP.add(buttonsP, BorderLayout.SOUTH); // db.add(buttonsP); JPanel about = m_SaverEditor.getAboutPanel(); if (about != null) { add(about, BorderLayout.NORTH); } add(holderP,BorderLayout.SOUTH); } /** Sets up dialog for saving instances in a file */ public void setUpFile() { removeAll(); m_fileChooser.setFileFilter(new FileFilter() { public boolean accept(File f) { return f.isDirectory(); } public String getDescription() { return "Directory"; } }); m_fileChooser.setAcceptAllFileFilterUsed(false); try{ if(!(((m_dsSaver.getSaverTemplate()).retrieveDir()).equals(""))) { String dirStr = m_dsSaver.getSaverTemplate().retrieveDir(); if (Environment.containsEnvVariables(dirStr)) { try { dirStr = m_env.substitute(dirStr); } catch (Exception ex) { // ignore } } File tmp = new File(dirStr); tmp = new File(tmp.getAbsolutePath()); m_fileChooser.setCurrentDirectory(tmp); } } catch(Exception ex) { System.out.println(ex); } JPanel innerPanel = new JPanel(); innerPanel.setLayout(new BorderLayout()); JPanel alignedP = new JPanel(); GridBagLayout gbLayout = new GridBagLayout(); alignedP.setLayout(gbLayout); final JLabel prefixLab = new JLabel("Prefix for file name", SwingConstants.RIGHT); prefixLab.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0)); GridBagConstraints gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 0; gbConstraints.gridx = 0; gbLayout.setConstraints(prefixLab, gbConstraints); alignedP.add(prefixLab); m_prefixText = new EnvironmentField(); m_prefixText.setEnvironment(m_env); m_prefixText.setToolTipText("Prefix for file name " + "(or filename itself if relation name is not used)"); /* int width = m_prefixText.getPreferredSize().width; int height = m_prefixText.getPreferredSize().height; m_prefixText.setMinimumSize(new Dimension(width * 2, height)); m_prefixText.setPreferredSize(new Dimension(width * 2, height)); */ gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 0; gbConstraints.gridx = 1; gbLayout.setConstraints(m_prefixText, gbConstraints); alignedP.add(m_prefixText); try{ // m_prefixText = new JTextField(m_dsSaver.getSaver().filePrefix(),25); m_prefixText.setText(m_dsSaver.getSaverTemplate().filePrefix()); /* final JLabel prefixLab = new JLabel(" Prefix for file name:", SwingConstants.LEFT); */ JLabel relationLab = new JLabel("Relation name for filename", SwingConstants.RIGHT); relationLab.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0)); gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 1; gbConstraints.gridx = 0; gbLayout.setConstraints(relationLab, gbConstraints); alignedP.add(relationLab); m_relationNameForFilename = new JCheckBox(); m_relationNameForFilename.setSelected(m_dsSaver.getRelationNameForFilename()); if (m_dsSaver.getRelationNameForFilename()) { prefixLab.setText("Prefix for file name"); } else { prefixLab.setText("File name"); } m_relationNameForFilename.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (m_relationNameForFilename.isSelected()) { prefixLab.setText("Prefix for file name"); // m_fileChooser.setApproveButtonText("Select directory and prefix"); } else { prefixLab.setText("File name"); // m_fileChooser.setApproveButtonText("Select directory and filename"); } } }); gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 1; gbConstraints.gridx = 1; gbConstraints.weightx = 5; gbLayout.setConstraints(m_relationNameForFilename, gbConstraints); alignedP.add(m_relationNameForFilename); } catch(Exception ex){ } //innerPanel.add(m_SaverEditor, BorderLayout.SOUTH); JPanel about = m_SaverEditor.getAboutPanel(); if (about != null) { innerPanel.add(about, BorderLayout.NORTH); } add(innerPanel, BorderLayout.NORTH); // add(m_fileChooser, BorderLayout.CENTER); JLabel directoryLab = new JLabel("Directory", SwingConstants.RIGHT); directoryLab.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0)); gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 2; gbConstraints.gridx = 0; gbLayout.setConstraints(directoryLab, gbConstraints); alignedP.add(directoryLab); m_directoryText = new EnvironmentField(); // m_directoryText.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); m_directoryText.setEnvironment(m_env); /* width = m_directoryText.getPreferredSize().width; height = m_directoryText.getPreferredSize().height; m_directoryText.setMinimumSize(new Dimension(width * 2, height)); m_directoryText.setPreferredSize(new Dimension(width * 2, height)); */ try { m_directoryText.setText(m_dsSaver.getSaverTemplate().retrieveDir()); } catch (IOException ex) { // ignore } JButton browseBut = new JButton("Browse..."); browseBut.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { //final JFrame jf = new JFrame("Choose directory"); final JDialog jf = new JDialog((JDialog)SaverCustomizer.this.getTopLevelAncestor(), "Choose directory", ModalityType.DOCUMENT_MODAL); jf.setLayout(new BorderLayout()); jf.getContentPane().add(m_fileChooser, BorderLayout.CENTER); m_fileChooserFrame = jf; jf.pack(); jf.setLocationRelativeTo(SwingUtilities.getWindowAncestor(SaverCustomizer.this)); jf.setVisible(true); } catch (Exception ex) { ex.printStackTrace(); } } }); JPanel efHolder = new JPanel(); efHolder.setLayout(new BorderLayout()); JPanel bP = new JPanel(); bP.setLayout(new BorderLayout()); bP.setBorder(BorderFactory.createEmptyBorder(5,0,5,5)); bP.add(browseBut, BorderLayout.CENTER); efHolder.add(m_directoryText, BorderLayout.CENTER); efHolder.add(bP, BorderLayout.EAST); //efHolder.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 2; gbConstraints.gridx = 1; gbLayout.setConstraints(efHolder, gbConstraints); alignedP.add(efHolder); JLabel relativeLab = new JLabel("Use relative file paths", SwingConstants.RIGHT); relativeLab.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0)); gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 3; gbConstraints.gridx = 0; gbLayout.setConstraints(relativeLab, gbConstraints); alignedP.add(relativeLab); m_relativeFilePath = new JCheckBox(); m_relativeFilePath. setSelected(((FileSourcedConverter)m_dsSaver.getSaverTemplate()).getUseRelativePath()); m_relativeFilePath.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { ((FileSourcedConverter)m_dsSaver.getSaverTemplate()). setUseRelativePath(m_relativeFilePath.isSelected()); } }); gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 3; gbConstraints.gridx = 1; gbLayout.setConstraints(m_relativeFilePath, gbConstraints); alignedP.add(m_relativeFilePath); JButton OKBut = new JButton("OK"); OKBut.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { (m_dsSaver.getSaverTemplate()).setFilePrefix(m_prefixText.getText()); (m_dsSaver.getSaverTemplate()).setDir(m_directoryText.getText()); m_dsSaver. setRelationNameForFilename(m_relationNameForFilename.isSelected()); } catch (Exception ex) { ex.printStackTrace(); } if (m_modifyListener != null) { m_modifyListener.setModifiedStatus(SaverCustomizer.this, true); } m_parentWindow.dispose(); } }); JButton CancelBut = new JButton("Cancel"); CancelBut.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (m_modifyListener != null) { m_modifyListener.setModifiedStatus(SaverCustomizer.this, false); } m_parentWindow.dispose(); } }); JPanel butHolder = new JPanel(); butHolder.setLayout(new FlowLayout()); butHolder.add(OKBut); butHolder.add(CancelBut); JPanel holder2 = new JPanel(); holder2.setLayout(new BorderLayout()); holder2.add(alignedP, BorderLayout.NORTH); JPanel optionsHolder = new JPanel(); optionsHolder.setLayout(new BorderLayout()); optionsHolder.setBorder(BorderFactory.createTitledBorder("Other options")); optionsHolder.add(m_SaverEditor, BorderLayout.SOUTH); JScrollPane scroller = new JScrollPane(optionsHolder); //holder2.add(scroller, BorderLayout.CENTER); //holder2.add(butHolder, BorderLayout.SOUTH); innerPanel.add(holder2, BorderLayout.SOUTH); add(scroller, BorderLayout.CENTER); add(butHolder, BorderLayout.SOUTH); } /** * Set the saver to be customized * * @param object a weka.gui.beans.Saver */ public void setObject(Object object) { m_dsSaver = (weka.gui.beans.Saver)object; m_SaverEditor.setTarget(m_dsSaver.getSaverTemplate()); if(m_dsSaver.getSaverTemplate() instanceof DatabaseConverter){ setUpDatabase(); } else{ if (m_dsSaver.getSaverTemplate() instanceof FileSourcedConverter) { setUpFile(); } else { setUpOther(); } } } /** * 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); } /* (non-Javadoc) * @see weka.core.EnvironmentHandler#setEnvironment(weka.core.Environment) */ public void setEnvironment(Environment env) { m_env = env; } @Override public void setModifiedListener(ModifyListener l) { // TODO Auto-generated method stub 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/ScatterPlotMatrix.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ScatterPlotMatrix.java * Copyright (C) 2003-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.beans; import java.awt.BorderLayout; import java.awt.GraphicsEnvironment; import javax.swing.Icon; import weka.core.Instances; import weka.gui.visualize.MatrixPanel; /** * Bean that encapsulates weka.gui.visualize.MatrixPanel for displaying a * scatter plot matrix. * * @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a> * @version $Revision$ */ public class ScatterPlotMatrix extends DataVisualizer implements KnowledgeFlowApp.KFPerspective { /** for serialization */ private static final long serialVersionUID = -657856527563507491L; protected MatrixPanel m_matrixPanel; public ScatterPlotMatrix() { java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment(); if (!GraphicsEnvironment.isHeadless()) { appearanceFinal(); } } /** * Global info for this bean * * @return a <code>String</code> value */ @Override public String globalInfo() { return "Visualize incoming data/training/test sets in a scatter " + "plot matrix."; } @Override protected void appearanceDesign() { m_matrixPanel = null; removeAll(); m_visual = new BeanVisual("ScatterPlotMatrix", BeanVisual.ICON_PATH + "ScatterPlotMatrix.gif", BeanVisual.ICON_PATH + "ScatterPlotMatrix_animated.gif"); setLayout(new BorderLayout()); add(m_visual, BorderLayout.CENTER); } @Override protected void appearanceFinal() { removeAll(); setLayout(new BorderLayout()); setUpFinal(); } @Override protected void setUpFinal() { if (m_matrixPanel == null) { m_matrixPanel = new MatrixPanel(); } add(m_matrixPanel, BorderLayout.CENTER); } /** * 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; m_matrixPanel.setInstances(m_visualizeDataSet); } /** * 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 "Scatter plot matrix"; } /** * Get the tool tip text for this perspective. * * @return the tool tip text for this perspective */ @Override public String getPerspectiveTipText() { return "Scatter plot matrix"; } /** * 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/application_view_tile.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) { } /** * 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) { } /** * 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 (request.compareTo("Show plot") == 0) { try { // popup matrix panel if (!m_framePoppedUp) { m_framePoppedUp = true; final MatrixPanel vis = new MatrixPanel(); vis.setInstances(m_visualizeDataSet); final javax.swing.JFrame jf = new javax.swing.JFrame("Visualize"); jf.setSize(800, 600); 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.setVisible(true); m_popupFrame = jf; } else { m_popupFrame.toFront(); } } catch (Exception ex) { ex.printStackTrace(); m_framePoppedUp = false; } } else { throw new IllegalArgumentException(request + " not supported (ScatterPlotMatrix)"); } } public static void main(String[] args) { try { if (args.length != 1) { System.err.println("Usage: ScatterPlotMatrix <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 ScatterPlotMatrix as = new ScatterPlotMatrix(); 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()); } } }
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/ScatterPlotMatrixBeanInfo.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ScatterPlotMatrixBeanInfo.java * Copyright (C) 2003-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.beans; import java.beans.EventSetDescriptor; import java.beans.SimpleBeanInfo; /** * Bean info class for the scatter plot matrix bean * * @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a> * @version $Revision$ */ public class ScatterPlotMatrixBeanInfo 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/SerializedModelSaver.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * SerializedModelSaver.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.io.BufferedOutputStream; import java.io.File; 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.Vector; import javax.swing.JPanel; import weka.classifiers.UpdateableBatchProcessor; import weka.core.Environment; import weka.core.EnvironmentHandler; import weka.core.Instances; import weka.core.Tag; import weka.core.Utils; import weka.core.xml.KOML; import weka.core.xml.XStream; /** * A bean that saves serialized models * * @author Mark Hall (mhall{[at]}pentaho{[dot]}org * @version $Revision$ */ @KFStep(category = "DataSinks", toolTipText = "Save a batch or incremental model to file") public class SerializedModelSaver extends JPanel implements BeanCommon, Visible, BatchClassifierListener, IncrementalClassifierListener, BatchClustererListener, EnvironmentHandler, Serializable { /** for serialization */ private static final long serialVersionUID = 3956528599473814287L; /** * 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 prefix for the file name (model + training set info will be appended) */ private String m_filenamePrefix = ""; /** Counter for use when processing incremental classifier events */ protected transient int m_counter; /** * How often to save an incremental classifier (<= 0 means only at the end of * the stream) */ protected int m_incrementalSaveSchedule = 0; /** * The directory to hold the saved model(s) */ private File m_directory = new File(System.getProperty("user.dir")); /** * File format stuff */ private Tag m_fileFormat; public final static int BINARY = 0; public final static int KOMLV = 1; public final static int XSTREAM = 2; /** the extension for serialized models (binary Java serialization) */ public final static String FILE_EXTENSION = "model"; /** * relative path for the directory (relative to the user.dir (startup * directory))? */ private boolean m_useRelativePath = false; /** include relation name in filename */ private boolean m_includeRelationName = false; /** * Available file formats. Reflection is used to check if classes are * available for deep object serialization to XML */ public static ArrayList<Tag> s_fileFormatsAvailable; static { s_fileFormatsAvailable = new ArrayList<Tag>(); s_fileFormatsAvailable.add(new Tag(BINARY, "Binary serialized model file (*" + FILE_EXTENSION + ")", "", false)); if (KOML.isPresent()) { s_fileFormatsAvailable.add(new Tag(KOMLV, "XML serialized model file (*" + KOML.FILE_EXTENSION + FILE_EXTENSION + ")", "", false)); } if (XStream.isPresent()) { s_fileFormatsAvailable.add(new Tag(XSTREAM, "XML serialized model file (*" + XStream.FILE_EXTENSION + FILE_EXTENSION + ")", "", false)); } } /** * The environment variables. */ protected transient Environment m_env; /** * Constructor. */ public SerializedModelSaver() { useDefaultVisual(); setLayout(new BorderLayout()); add(m_visual, BorderLayout.CENTER); m_fileFormat = s_fileFormatsAvailable.get(0); m_env = Environment.getSystemWide(); } /** * 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(); } /** * Use the default images for this bean. * */ @Override public void useDefaultVisual() { m_visual.loadIcons(BeanVisual.ICON_PATH + "SerializedModelSaver.gif", BeanVisual.ICON_PATH + "SerializedModelSaver_animated.gif"); m_visual.setText("SerializedModelSaver"); } /** * Set the visual for this data source. * * @param newVisual a <code>BeanVisual</code> value */ @Override public void setVisual(BeanVisual newVisual) { m_visual = newVisual; } /** * Get the visual being used by this data source. * */ @Override public BeanVisual getVisual() { return m_visual; } /** * Returns true if, at this time, the object will accept a connection * according to the supplied EventSetDescriptor. * * @param esd the EventSetDescriptor * @return true if the object will accept a connection */ @Override public boolean connectionAllowed(EventSetDescriptor esd) { return connectionAllowed(esd.getName()); } /** * Returns true if, at this time, the object will accept a connection * according to the supplied event name. * * @param eventName the event * @return true if the object will accept a connection */ @Override public boolean connectionAllowed(String eventName) { return (m_listenee == null); } /** * Notify this object that it has been registered as a listener with a source * with respect to the supplied event name. * * @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_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 synchronized void disconnectionNotification(String eventName, Object source) { if (m_listenee == source) { m_listenee = null; } } /** * Set a log for this bean. * * @param logger a <code>weka.gui.Logger</code> value */ @Override public void setLog(weka.gui.Logger logger) { m_logger = logger; } /** * Stop any processing that the bean might be doing. */ @Override public void stop() { // tell the listenee (upstream bean) to stop if (m_listenee instanceof BeanCommon) { ((BeanCommon) m_listenee).stop(); } } /** * Returns true if. at this time, the bean is busy with some (i.e. perhaps a * worker thread is performing some calculation). * * @return true if the bean is busy. */ @Override public boolean isBusy() { return false; } /** * makes sure that the filename is valid, i.e., replaces slashes, backslashes * and colons with underscores ("_"). * * @param filename the filename to cleanse * @return the cleansed filename */ protected String sanitizeFilename(String filename) { return filename.replaceAll("\\\\", "_").replaceAll(":", "_") .replaceAll("/", "_"); } /** * Accept and save a batch trained clusterer. * * @param ce a <code>BatchClassifierEvent</code> value */ @Override public void acceptClusterer(BatchClustererEvent ce) { if (ce.getTestSet() == null || ce.getTestOrTrain() == BatchClustererEvent.TEST || ce.getTestSet().isStructureOnly()) { return; } Instances trainHeader = new Instances(ce.getTestSet().getDataSet(), 0); String titleString = ce.getClusterer().getClass().getName(); titleString = titleString.substring(titleString.lastIndexOf('.') + 1, titleString.length()); String prefix = ""; String relationName = (m_includeRelationName) ? trainHeader.relationName() : ""; try { prefix = m_env.substitute(m_filenamePrefix); } catch (Exception ex) { stop(); // stop all processing String message = "[SerializedModelSaver] " + statusMessagePrefix() + " Can't save model. Reason: " + ex.getMessage(); if (m_logger != null) { m_logger.logMessage(message); m_logger.statusMessage(statusMessagePrefix() + "ERROR (See log for details)"); } else { System.err.println(message); } return; } String fileName = "" + prefix + relationName + titleString + "_" + ce.getSetNumber() + "_" + ce.getMaxSetNumber(); fileName = sanitizeFilename(fileName); String dirName = m_directory.getPath(); try { dirName = m_env.substitute(dirName); } catch (Exception ex) { String message = "[SerializedModelSaver] " + statusMessagePrefix() + " Can't save model. Reason: " + ex.getMessage(); if (m_logger != null) { m_logger.logMessage(message); m_logger.statusMessage(statusMessagePrefix() + "ERROR (See log for details)"); } else { System.err.println(message); } return; } File tempFile = new File(dirName); fileName = tempFile.getAbsolutePath() + File.separator + fileName; saveModel(fileName, trainHeader, ce.getClusterer()); } /** * Accept and save an incrementally trained classifier. * * @param ce the BatchClassifierEvent containing the classifier */ @Override public void acceptClassifier(final IncrementalClassifierEvent ce) { if (ce.getStatus() == IncrementalClassifierEvent.BATCH_FINISHED || (m_incrementalSaveSchedule > 0 && (m_counter % m_incrementalSaveSchedule == 0) && m_counter > 0)) { // Only save model when the end of the stream is reached or according // to our save schedule (if set) Instances header = ce.getStructure(); String titleString = ce.getClassifier().getClass().getName(); titleString = titleString.substring(titleString.lastIndexOf('.') + 1, titleString.length()); String prefix = ""; String relationName = (m_includeRelationName) ? header.relationName() : ""; try { prefix = m_env.substitute(m_filenamePrefix); } catch (Exception ex) { String message = "[SerializedModelSaver] " + statusMessagePrefix() + " Can't save model. Reason: " + ex.getMessage(); if (m_logger != null) { m_logger.logMessage(message); m_logger.statusMessage(statusMessagePrefix() + "ERROR (See log for details)"); } else { System.err.println(message); } return; } String fileName = "" + prefix + relationName + titleString; fileName = sanitizeFilename(fileName); String dirName = m_directory.getPath(); try { dirName = m_env.substitute(dirName); } catch (Exception ex) { String message = "[SerializedModelSaver] " + statusMessagePrefix() + " Can't save model. Reason: " + ex.getMessage(); if (m_logger != null) { m_logger.logMessage(message); m_logger.statusMessage(statusMessagePrefix() + "ERROR (See log for details)"); } else { System.err.println(message); } return; } File tempFile = new File(dirName); fileName = tempFile.getAbsolutePath() + File.separator + fileName; saveModel(fileName, header, ce.getClassifier()); } else if (ce.getStatus() == IncrementalClassifierEvent.NEW_BATCH) { m_counter = 0; } m_counter++; } /** * Accept and save a batch trained classifier. * * @param ce the BatchClassifierEvent containing the classifier */ @Override public void acceptClassifier(final BatchClassifierEvent ce) { if (ce.getTrainSet() == null || ce.getTrainSet().isStructureOnly()) { return; } Instances trainHeader = ce.getTrainSet().getDataSet().stringFreeStructure(); // adjust for InputMappedClassifier (if necessary) if (ce.getClassifier() instanceof weka.classifiers.misc.InputMappedClassifier) { try { trainHeader = ((weka.classifiers.misc.InputMappedClassifier) ce .getClassifier()).getModelHeader(trainHeader); } catch (Exception e) { e.printStackTrace(); } } String titleString = ce.getClassifier().getClass().getName(); titleString = titleString.substring(titleString.lastIndexOf('.') + 1, titleString.length()); String prefix = ""; String relationName = (m_includeRelationName) ? trainHeader.relationName() : ""; try { prefix = m_env.substitute(m_filenamePrefix); } catch (Exception ex) { String message = "[SerializedModelSaver] " + statusMessagePrefix() + " Can't save model. Reason: " + ex.getMessage(); if (m_logger != null) { m_logger.logMessage(message); m_logger.statusMessage(statusMessagePrefix() + "ERROR (See log for details)"); } else { System.err.println(message); } return; } String fileName = "" + prefix + relationName + titleString + "_" + ce.getSetNumber() + "_" + ce.getMaxSetNumber(); fileName = sanitizeFilename(fileName); String dirName = m_directory.getPath(); try { dirName = m_env.substitute(dirName); } catch (Exception ex) { String message = "[SerializedModelSaver] " + statusMessagePrefix() + " Can't save model. Reason: " + ex.getMessage(); if (m_logger != null) { m_logger.logMessage(message); m_logger.statusMessage(statusMessagePrefix() + "ERROR (See log for details)"); } else { System.err.println(message); } return; } File tempFile = new File(dirName); fileName = tempFile.getAbsolutePath() + File.separator + fileName; saveModel(fileName, trainHeader, ce.getClassifier()); } /** * Helper routine to actually save the models. */ private void saveModel(String fileName, Instances trainHeader, Object model) { m_fileFormat = validateFileFormat(m_fileFormat); if (m_fileFormat == null) { // default to binary if validation fails m_fileFormat = s_fileFormatsAvailable.get(0); } if (model instanceof UpdateableBatchProcessor) { // make sure model cleans up before saving try { ((UpdateableBatchProcessor) model).batchFinished(); } catch (Exception ex) { System.err.println("[SerializedModelSaver] Problem saving model"); if (m_logger != null) { m_logger.logMessage("[SerializedModelSaver] " + statusMessagePrefix() + " Problem saving model. Reason: " + ex.getMessage()); m_logger.statusMessage(statusMessagePrefix() + "ERROR (See log for details)"); } } } m_logger.logMessage("[SerializedModelSaver] " + statusMessagePrefix() + " Saving model " + model.getClass().getName()); try { switch (m_fileFormat.getID()) { case KOMLV: fileName = fileName + KOML.FILE_EXTENSION + FILE_EXTENSION; saveKOML(new File(fileName), model, trainHeader); break; case XSTREAM: fileName = fileName + XStream.FILE_EXTENSION + FILE_EXTENSION; saveXStream(new File(fileName), model, trainHeader); break; default: fileName = fileName + "." + FILE_EXTENSION; saveBinary(new File(fileName), model, trainHeader); break; } } catch (Exception ex) { System.err.println("[SerializedModelSaver] Problem saving model"); if (m_logger != null) { m_logger.logMessage("[SerializedModelSaver] " + statusMessagePrefix() + " Problem saving model. Reason: " + ex.getMessage()); m_logger.statusMessage(statusMessagePrefix() + "ERROR (See log for details)"); } } } /** * Save a model in binary form. * * @param saveTo the file name to save to * @param model the model to save * @param header the header of the data that was used to train the model * (optional) */ public static void saveBinary(File saveTo, Object model, Instances header) throws IOException { ObjectOutputStream os = new ObjectOutputStream(new BufferedOutputStream( new FileOutputStream(saveTo))); os.writeObject(model); // now the header if (header != null) { os.writeObject(header); } os.close(); } /** * Save a model in KOML deep object serialized XML form. * * @param saveTo the file name to save to * @param model the model to save * @param header the header of the data that was used to train the model * (optional) */ public static void saveKOML(File saveTo, Object model, Instances header) throws Exception { Vector<Object> v = new Vector<Object>(); v.add(model); if (header != null) { v.add(header); } v.trimToSize(); KOML.write(saveTo.getAbsolutePath(), v); } /** * Save a model in XStream deep object serialized XML form. * * @param saveTo the file name to save to * @param model the model to save * @param header the header of the data that was used to train the model * (optional) */ public static void saveXStream(File saveTo, Object model, Instances header) throws Exception { Vector<Object> v = new Vector<Object>(); v.add(model); if (header != null) { v.add(header); } v.trimToSize(); XStream.write(saveTo.getAbsolutePath(), v); } /** * Get the directory that the model(s) will be saved into * * @return the directory to save to */ public File getDirectory() { return m_directory; } /** * Set the directory that the model(s) will be saved into. * * @param d the directory to save to */ public void setDirectory(File d) { m_directory = d; if (m_useRelativePath) { try { m_directory = Utils.convertToRelativePath(m_directory); } catch (Exception ex) { } } } /** * Set whether to use relative paths for the directory. I.e. relative to the * startup (user.dir) directory * * @param rp true if relative paths are to be used */ public void setUseRelativePath(boolean rp) { m_useRelativePath = rp; } /** * Get whether to use relative paths for the directory. I.e. relative to the * startup (user.dir) directory * * @return true if relative paths are to be used */ public boolean getUseRelativePath() { return m_useRelativePath; } /** * Set whether the relation name of the training data used to create the model * should be included as part of the filename for the serialized model. * * @param rn true if the relation name should be included in the file name */ public void setIncludeRelationName(boolean rn) { m_includeRelationName = rn; } /** * Get whether the relation name of the training data used to create the model * is to be included in the filename of the serialized model. * * @return true if the relation name is to be included in the file name */ public boolean getIncludeRelationName() { return m_includeRelationName; } /** * Get the prefix to prepend to the model file names. * * @return the prefix to prepend */ public String getPrefix() { return m_filenamePrefix; } /** * Set the prefix to prepend to the model file names. * * @param p the prefix to prepend */ public void setPrefix(String p) { m_filenamePrefix = p; } /** * Set how often to save incremental models. <= 0 means only at the end of the * stream * * @param s how often to save (after every s instances) */ public void setIncrementalSaveSchedule(int s) { m_incrementalSaveSchedule = s; } /** * Get how often to save incremental models. <= 0 means only at the end of the * stream * * @return how often to save (after every s instances) */ public int getIncrementalSaveSchedule() { return m_incrementalSaveSchedule; } /** * Global info for this bean. Gets displayed in the GUI. * * @return information about this bean. */ public String globalInfo() { return "Save trained models to serialized object files."; } /** * Set the file format to use for saving. * * @param ff the file format to use */ public void setFileFormat(Tag ff) { m_fileFormat = ff; } /** * Get the file format to use for saving. * * @return the file format to use */ public Tag getFileFormat() { return m_fileFormat; } /** * Validate the file format. After this bean is deserialized, classes for XML * serialization may not be in the classpath any more. * * @param ff the current file format to validate */ public Tag validateFileFormat(Tag ff) { Tag r = ff; if (ff.getID() == BINARY) { return ff; } if (ff.getID() == KOMLV && !KOML.isPresent()) { r = null; } if (ff.getID() == XSTREAM && !XStream.isPresent()) { r = null; } return r; } private String statusMessagePrefix() { return getCustomName() + "$" + hashCode() + "|"; } /** * Set environment variables to use. * * @param env the environment variables to use */ @Override public void setEnvironment(Environment env) { m_env = env; } // Custom de-serialization in order to set default // environment variables on de-serialization private void readObject(ObjectInputStream aStream) throws IOException, ClassNotFoundException { aStream.defaultReadObject(); // set a default environment to use m_env = Environment.getSystemWide(); } }
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/SerializedModelSaverBeanInfo.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * SerializedModelSaverBeanInfo.java * Copyright (C) 2008-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 serialized model saver bean * * @author Mark Hall (mhall{[at]}pentaho{[dot]}org * @version $Revision$ */ public class SerializedModelSaverBeanInfo 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.SerializedModelSaver.class, SerializedModelSaverCustomizer.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/SerializedModelSaverCustomizer.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * SerializedModelSaverCustomizer.java * Copyright (C) 2008-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.beans; import java.awt.BorderLayout; import java.awt.Dialog.ModalityType; import java.awt.FlowLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.File; import javax.swing.*; import javax.swing.filechooser.FileFilter; import weka.core.Environment; import weka.core.EnvironmentHandler; import weka.core.Tag; import weka.gui.GenericObjectEditor; import weka.gui.PropertySheetPanel; /** * GUI Customizer for the SerializedModelSaver bean * * @author Mark Hall (mhall{[at]}pentaho{[dot]}org * @version $Revision$ */ public class SerializedModelSaverCustomizer extends JPanel implements BeanCustomizer, CustomizerCloseRequester, CustomizerClosingListener, EnvironmentHandler { /** for serialization */ private static final long serialVersionUID = -4874208115942078471L; static { GenericObjectEditor.registerEditors(); } private final PropertyChangeSupport m_pcSupport = new PropertyChangeSupport(this); private weka.gui.beans.SerializedModelSaver m_smSaver; private final PropertySheetPanel m_SaverEditor = new PropertySheetPanel(); private final JFileChooser m_fileChooser = new JFileChooser(new File( System.getProperty("user.dir"))); private Window m_parentWindow; private JDialog m_fileChooserFrame; // private JTextField m_prefixText; private EnvironmentField m_prefixText; private JTextField m_incrementalSaveSchedule; private JComboBox m_fileFormatBox; private JCheckBox m_relativeFilePath; private JCheckBox m_includeRelationName; private Environment m_env = Environment.getSystemWide(); private EnvironmentField m_directoryText; private ModifyListener m_modifyListener; private String m_prefixBackup; private File m_directoryBackup; private boolean m_relativeBackup; private boolean m_relationBackup; private Tag m_formatBackup; /** Constructor */ public SerializedModelSaverCustomizer() { /* * try { m_SaverEditor.addPropertyChangeListener( new * PropertyChangeListener() { public void propertyChange(PropertyChangeEvent * e) { repaint(); if (m_smSaver != null) { * System.err.println("Property change!!"); // * m_smSaver.setSaver(m_smSaver.getSaver()); } } }); repaint(); } catch * (Exception ex) { ex.printStackTrace(); } */ setLayout(new BorderLayout()); m_fileChooser.setDialogType(JFileChooser.SAVE_DIALOG); m_fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); m_fileChooser.setApproveButtonText("Select directory and prefix"); m_fileChooser.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals(JFileChooser.APPROVE_SELECTION)) { try { m_smSaver.setPrefix(m_prefixText.getText()); // m_smSaver.setDirectory(m_fileChooser.getSelectedFile()); File selectedFile = m_fileChooser.getSelectedFile(); m_directoryText.setText(selectedFile.toString()); } catch (Exception ex) { ex.printStackTrace(); } } // closing if (m_parentWindow != null) { m_fileChooserFrame.dispose(); } } }); } @Override public void setParentWindow(Window parent) { m_parentWindow = parent; } /** Sets up dialog for saving models to a file */ public void setUpFile() { removeAll(); m_fileChooser.setFileFilter(new FileFilter() { @Override public boolean accept(File f) { return f.isDirectory(); } @Override public String getDescription() { return "Directory"; } }); m_fileChooser.setAcceptAllFileFilterUsed(false); try { if (!m_smSaver.getDirectory().getPath().equals("")) { // File tmp = m_smSaver.getDirectory(); String dirStr = m_smSaver.getDirectory().toString(); if (Environment.containsEnvVariables(dirStr)) { try { dirStr = m_env.substitute(dirStr); } catch (Exception ex) { // ignore } } File tmp = new File(dirStr); ; tmp = new File(tmp.getAbsolutePath()); m_fileChooser.setCurrentDirectory(tmp); } } catch (Exception ex) { System.out.println(ex); } JPanel innerPanel = new JPanel(); innerPanel.setLayout(new BorderLayout()); JPanel alignedP = new JPanel(); GridBagLayout gbLayout = new GridBagLayout(); alignedP.setLayout(gbLayout); JLabel prefixLab = new JLabel("Prefix for file name", SwingConstants.RIGHT); prefixLab.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0)); GridBagConstraints gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 0; gbConstraints.gridx = 0; gbLayout.setConstraints(prefixLab, gbConstraints); alignedP.add(prefixLab); // m_prefixText = new JTextField(m_smSaver.getPrefix(), 25); m_prefixText = new EnvironmentField(); m_prefixText.setEnvironment(m_env); /* * int width = m_prefixText.getPreferredSize().width; int height = * m_prefixText.getPreferredSize().height; m_prefixText.setMinimumSize(new * Dimension(width * 2, height)); m_prefixText.setPreferredSize(new * Dimension(width * 2, height)); */ m_prefixText.setText(m_smSaver.getPrefix()); gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 0; gbConstraints.gridx = 1; gbLayout.setConstraints(m_prefixText, gbConstraints); alignedP.add(m_prefixText); JLabel ffLab = new JLabel("File format", SwingConstants.RIGHT); ffLab.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0)); gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 1; gbConstraints.gridx = 0; gbLayout.setConstraints(ffLab, gbConstraints); alignedP.add(ffLab); setUpFileFormatComboBox(); m_fileFormatBox.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5)); gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 1; gbConstraints.gridx = 1; gbLayout.setConstraints(m_fileFormatBox, gbConstraints); alignedP.add(m_fileFormatBox); JPanel about = m_SaverEditor.getAboutPanel(); if (about != null) { innerPanel.add(about, BorderLayout.NORTH); } add(innerPanel, BorderLayout.NORTH); JLabel directoryLab = new JLabel("Directory", SwingConstants.RIGHT); directoryLab.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0)); gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 2; gbConstraints.gridx = 0; gbLayout.setConstraints(directoryLab, gbConstraints); alignedP.add(directoryLab); m_directoryText = new EnvironmentField(); m_directoryText.setEnvironment(m_env); /* * width = m_directoryText.getPreferredSize().width; height = * m_directoryText.getPreferredSize().height; * m_directoryText.setMinimumSize(new Dimension(width * 2, height)); * m_directoryText.setPreferredSize(new Dimension(width * 2, height)); */ m_directoryText.setText(m_smSaver.getDirectory().toString()); JButton browseBut = new JButton("Browse..."); browseBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { // final JFrame jf = new JFrame("Choose directory"); final JDialog jf = new JDialog((JDialog) SerializedModelSaverCustomizer.this .getTopLevelAncestor(), "Choose directory", ModalityType.DOCUMENT_MODAL); jf.getContentPane().setLayout(new BorderLayout()); jf.getContentPane().add(m_fileChooser, BorderLayout.CENTER); m_fileChooserFrame = jf; jf.pack(); jf.setLocationRelativeTo(SwingUtilities.getWindowAncestor(SerializedModelSaverCustomizer.this)); jf.setVisible(true); } catch (Exception ex) { ex.printStackTrace(); } } }); JPanel efHolder = new JPanel(); efHolder.setLayout(new BorderLayout()); JPanel bP = new JPanel(); bP.setLayout(new BorderLayout()); bP.setBorder(BorderFactory.createEmptyBorder(5, 0, 5, 5)); bP.add(browseBut, BorderLayout.CENTER); efHolder.add(bP, BorderLayout.EAST); efHolder.add(m_directoryText, BorderLayout.CENTER); gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 2; gbConstraints.gridx = 1; gbConstraints.weightx = 5; // make sure that extra horizontal space gets // allocated to this column gbLayout.setConstraints(efHolder, gbConstraints); alignedP.add(efHolder); JLabel saveSchedule = new JLabel("Incremental classifier save schedule", SwingConstants.RIGHT); saveSchedule.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0)); gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 3; gbConstraints.gridx = 0; gbLayout.setConstraints(saveSchedule, gbConstraints); alignedP.add(saveSchedule); saveSchedule.setToolTipText("How often to save incremental models " + "(<=0 means only at the end of the stream)"); m_incrementalSaveSchedule = new JTextField("" + m_smSaver.getIncrementalSaveSchedule(), 5); gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 3; gbConstraints.gridx = 1; gbLayout.setConstraints(m_incrementalSaveSchedule, gbConstraints); alignedP.add(m_incrementalSaveSchedule); m_incrementalSaveSchedule .setToolTipText("How often to save incremental models " + "(<=0 means only at the end of the stream)"); JLabel relativeLab = new JLabel("Use relative file paths", SwingConstants.RIGHT); relativeLab.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0)); gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 4; gbConstraints.gridx = 0; gbLayout.setConstraints(relativeLab, gbConstraints); alignedP.add(relativeLab); m_relativeFilePath = new JCheckBox(); m_relativeFilePath. setSelected(m_smSaver.getUseRelativePath()); /* * m_relativeFilePath.addActionListener(new ActionListener() { public void * actionPerformed(ActionEvent e) { * m_smSaver.setUseRelativePath(m_relativeFilePath.isSelected()); } }); */ gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 4; gbConstraints.gridx = 1; gbLayout.setConstraints(m_relativeFilePath, gbConstraints); alignedP.add(m_relativeFilePath); JLabel relationLab = new JLabel("Include relation name in file name", SwingConstants.RIGHT); relationLab.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0)); gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 5; gbConstraints.gridx = 0; gbLayout.setConstraints(relationLab, gbConstraints); alignedP.add(relationLab); m_includeRelationName = new JCheckBox(); m_includeRelationName .setToolTipText("Include the relation name of the training data used " + "to create the model in the file name."); m_includeRelationName.setSelected(m_smSaver.getIncludeRelationName()); gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.EAST; gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.gridy = 5; gbConstraints.gridx = 1; gbLayout.setConstraints(m_includeRelationName, gbConstraints); alignedP.add(m_includeRelationName); JButton OKBut = new JButton("OK"); OKBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { m_smSaver.setPrefix(m_prefixText.getText()); m_smSaver.setDirectory(new File(m_directoryText.getText())); m_smSaver. setIncludeRelationName(m_includeRelationName.isSelected()); m_smSaver.setUseRelativePath(m_relativeFilePath.isSelected()); String schedule = m_incrementalSaveSchedule.getText(); if (schedule != null && schedule.length() > 0) { try { m_smSaver.setIncrementalSaveSchedule(Integer .parseInt(m_incrementalSaveSchedule.getText())); } catch (NumberFormatException ex) { // ignore } } Tag selected = (Tag) m_fileFormatBox.getSelectedItem(); if (selected != null) { m_smSaver.setFileFormat(selected); } } catch (Exception ex) { ex.printStackTrace(); } if (m_modifyListener != null) { m_modifyListener.setModifiedStatus( SerializedModelSaverCustomizer.this, true); } m_parentWindow.dispose(); } }); JButton CancelBut = new JButton("Cancel"); CancelBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { customizerClosing(); m_parentWindow.dispose(); } }); JPanel butHolder = new JPanel(); butHolder.setLayout(new FlowLayout()); butHolder.add(OKBut); butHolder.add(CancelBut); JPanel holderPanel = new JPanel(); holderPanel.setLayout(new BorderLayout()); holderPanel.add(alignedP, BorderLayout.NORTH); holderPanel.add(butHolder, BorderLayout.SOUTH); add(holderPanel, BorderLayout.SOUTH); } /** * Set the model saver to be customized * * @param object a weka.gui.beans.SerializedModelSaver */ @Override public void setObject(Object object) { m_smSaver = (weka.gui.beans.SerializedModelSaver) object; m_SaverEditor.setTarget(m_smSaver); m_prefixBackup = m_smSaver.getPrefix(); m_directoryBackup = m_smSaver.getDirectory(); m_relationBackup = m_smSaver.getIncludeRelationName(); m_relativeBackup = m_smSaver.getUseRelativePath(); m_formatBackup = m_smSaver.getFileFormat(); setUpFile(); } private void setUpFileFormatComboBox() { m_fileFormatBox = new JComboBox(); for (int i = 0; i < SerializedModelSaver.s_fileFormatsAvailable.size(); i++) { Tag temp = SerializedModelSaver.s_fileFormatsAvailable.get(i); m_fileFormatBox.addItem(temp); } Tag result = m_smSaver.validateFileFormat(m_smSaver.getFileFormat()); if (result == null) { m_fileFormatBox.setSelectedIndex(0); } else { m_fileFormatBox.setSelectedItem(result); } /* * m_fileFormatBox.addActionListener(new ActionListener() { public void * actionPerformed(ActionEvent e) { Tag selected = * (Tag)m_fileFormatBox.getSelectedItem(); if (selected != null) { * m_smSaver.setFileFormat(selected); } } }); */ } /** * 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); } /* * (non-Javadoc) * * @see weka.core.EnvironmentHandler#setEnvironment(weka.core.Environment) */ @Override public void setEnvironment(Environment env) { m_env = env; } @Override public void setModifiedListener(ModifyListener l) { m_modifyListener = l; } @Override public void customizerClosing() { // restore backup (when window is closed with close widget or // cancel button is pressed) m_smSaver.setPrefix(m_prefixBackup); m_smSaver.setDirectory(m_directoryBackup); m_smSaver.setUseRelativePath(m_relativeBackup); m_smSaver.setIncludeRelationName(m_relationBackup); m_smSaver.setFileFormat(m_formatBackup); } }
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/ShadowBorder.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ShadowBorder.java * Copyright (C) 2011-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.beans; import java.awt.Color; import java.awt.Component; import java.awt.Graphics; import java.awt.Insets; import javax.swing.border.AbstractBorder; public class ShadowBorder extends AbstractBorder { /** * For serialization */ private static final long serialVersionUID = -2117842133475125463L; /** The width in pixels of the drop shadow */ private int m_width = 3; /** the color of the drop shadow */ private Color m_color = Color.BLACK; /** * Constructor. Drop shadow with default width of 2 pixels and black color. */ public ShadowBorder() { this(2); } /** * Constructor. Drop shadow, default shadow color is black. * @param width the width of the shadow. */ public ShadowBorder(int width) { this( width, Color.BLACK ); } /** * Constructor. Drop shadow, width and color are adjustable. * * @param width the width of the shadow. * @param color the color of the shadow. */ public ShadowBorder(int width, Color color) { m_width = width; m_color = color; } /** * Returns a new Insets instance where the top and left are 1, * the bottom and right fields are the border width + 1. * * @param c the component for which this border insets value applies * @return a new Insets object initialized as stated above. */ public Insets getBorderInsets(Component c) { return new Insets(1, 1, m_width + 1, m_width + 1); } /** * Reinitializes the <code>insets</code> parameter with this ShadowBorder's * current Insets. * * @param c the component for which this border insets value applies * @param insets the object to be reinitialized * @return the given <code>insets</code> object */ public Insets getBorderInsets(Component c, Insets insets) { insets.top = 1; insets.left = 1; insets.bottom = m_width + 1; insets.right = m_width + 1; return insets; } /** * This implementation always returns true. * * @return true */ public boolean isBorderOpaque() { return true; } /** * Paints the drop shadow border around the given component. * * @param c - the component for which this border is being painted * @param g - the paint graphics * @param x - the x position of the painted border * @param y - the y position of the painted border * @param width - the width of the painted border * @param height - the height of the painted border */ public void paintBorder( Component c, Graphics g, int x, int y, int width, int height ) { Color old_color = g.getColor(); int x1, y1, x2, y2; g.setColor(m_color); // outline g.drawRect(x, y, width - m_width - 1, height - m_width - 1); // the drop shadow for (int i = 0; i <= m_width; i++) { // bottom shadow x1 = x + m_width; y1 = y + height - i; x2 = x + width; y2 = y1; g.drawLine( x1, y1, x2, y2 ); // right shadow x1 = x + width - m_width + i; y1 = y + m_width; x2 = x1; y2 = y + height; g.drawLine( x1, y1, x2, y2 ); } // fill in the corner rectangles with the background color of the parent // container if (c.getParent() != null) { g.setColor( c.getParent().getBackground() ); for ( int i = 0; i <= m_width; i++ ) { x1 = x; y1 = y + height - i; x2 = x + m_width; y2 = y1; g.drawLine( x1, y1, x2, y2 ); x1 = x + width - m_width; y1 = y + i; x2 = x + width ; y2 = y1; g.drawLine( x1, y1, x2, y2 ); } // add some slightly darker colored triangles g.setColor(g.getColor().darker()); for ( int i = 0; i < m_width; i++ ) { // bottom left triangle x1 = x + i + 1; y1 = y + height - m_width + i; x2 = x + m_width; y2 = y1; g.drawLine( x1, y1, x2, y2 ); // top right triangle x1 = x + width - m_width; y1 = y + i + 1; x2 = x1 + i ; y2 = y1; g.drawLine( x1, y1, x2, y2 ); } } g.setColor( old_color ); } }
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/Sorter.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * Sorter.java * Copyright (C) 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.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import javax.swing.JPanel; import weka.core.Attribute; import weka.core.Environment; import weka.core.EnvironmentHandler; import weka.core.Instance; import weka.core.Instances; import weka.gui.Logger; /** * <!-- globalinfo-start --> Sorts incoming instances in ascending or descending * order according to the values of user specified attributes. Instances can be * sorted according to multiple attributes (defined in order). Handles data sets * larger than can be fit into main memory via instance connections and * specifying the in-memory buffer size. Implements a merge-sort by writing the * sorted in-memory buffer to a file when full and then interleaving instances * from the disk based file(s) when the incoming stream has finished. * <p/> * <!-- globalinfo-end --> * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision$ */ @KFStep(category = "Tools", toolTipText = "Sort instances in ascending or descending order") public class Sorter extends JPanel implements BeanCommon, Visible, Serializable, DataSource, DataSourceListener, TrainingSetListener, TestSetListener, InstanceListener, EventConstraints, StructureProducer, EnvironmentHandler { /** For serialization */ private static final long serialVersionUID = 4978227384322482115L; /** Logging */ protected transient Logger m_log; /** Step talking to us */ protected Object m_listenee; /** The type of the incoming connection */ protected String m_connectionType; /** For printing status updates in incremental mode */ protected InstanceEvent m_ie = new InstanceEvent(this); /** True if we are busy */ protected boolean m_busy; /** True if a stop has been requested */ protected AtomicBoolean m_stopRequested; /** Holds the internal textual description of the sort definitions */ protected String m_sortDetails; /** Environment variables */ protected transient Environment m_env; /** Comparator that applies the sort rules */ protected transient SortComparator m_sortComparator; /** In memory buffer for incremental operation */ protected transient List<InstanceHolder> m_incrementalBuffer; /** List of sorted temp files for incremental operation */ protected transient List<File> m_bufferFiles; /** Size of the in-memory buffer */ protected String m_bufferSize = "10000"; /** Size of the in-memory buffer after resolving any environment vars */ protected int m_bufferSizeI = 10000; /** Holds indexes of string attributes, keyed by attribute name */ protected Map<String, Integer> m_stringAttIndexes; /** * The directory to hold the temp files - if not set the system tmp directory * is used */ protected String m_tempDirectory = ""; protected transient int m_streamCounter = 0; /** format of instances for current incoming connection (if any) */ private Instances m_connectedFormat; /** * Default visual for data sources */ protected BeanVisual m_visual = new BeanVisual("Sorter", BeanVisual.ICON_PATH + "Sorter.gif", BeanVisual.ICON_PATH + "Sorter_animated.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>(); /** * Inner class that holds instances and the index of the temp file that holds * them (if operating in incremental mode) */ protected static class InstanceHolder implements Serializable { /** For serialization */ private static final long serialVersionUID = -3985730394250172995L; /** The instance */ protected Instance m_instance; /** index into the list of files on disk */ protected int m_fileNumber; /** * 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; } /** * Comparator that applies the sort rules */ protected static class SortComparator implements Comparator<InstanceHolder> { protected List<SortRule> m_sortRules; public SortComparator(List<SortRule> sortRules) { m_sortRules = sortRules; } @Override public int compare(InstanceHolder o1, InstanceHolder o2) { int cmp = 0; for (SortRule sr : m_sortRules) { cmp = sr.compare(o1, o2); if (cmp != 0) { return cmp; } } return 0; } } /** * Implements a sorting rule based on a single attribute */ protected static class SortRule implements Comparator<InstanceHolder> { protected String m_attributeNameOrIndex; protected Attribute m_attribute; protected boolean m_descending; public SortRule(String att, boolean descending) { m_attributeNameOrIndex = att; m_descending = descending; } public SortRule() { } public SortRule(String setup) { parseFromInternal(setup); } protected void parseFromInternal(String setup) { String[] parts = setup.split("@@SR@@"); if (parts.length != 2) { throw new IllegalArgumentException("Malformed sort rule: " + setup); } m_attributeNameOrIndex = parts[0].trim(); m_descending = parts[1].equalsIgnoreCase("Y"); } protected String toStringInternal() { return m_attributeNameOrIndex + "@@SR@@" + (m_descending ? "Y" : "N"); } @Override public String toString() { StringBuffer res = new StringBuffer(); res.append("Attribute: " + m_attributeNameOrIndex + " - sort " + (m_descending ? "descending" : "ascending")); return res.toString(); } public void setAttribute(String att) { m_attributeNameOrIndex = att; } public String getAttribute() { return m_attributeNameOrIndex; } public void setDescending(boolean d) { m_descending = d; } public boolean getDescending() { return m_descending; } public void init(Environment env, Instances structure) { String attNameI = m_attributeNameOrIndex; try { attNameI = env.substitute(attNameI); } catch (Exception ex) { } if (attNameI.equalsIgnoreCase("/first")) { m_attribute = structure.attribute(0); } else if (attNameI.equalsIgnoreCase("/last")) { m_attribute = structure.attribute(structure.numAttributes() - 1); } else { // try actual attribute name m_attribute = structure.attribute(attNameI); if (m_attribute == null) { // try as an index try { int index = Integer.parseInt(attNameI); m_attribute = structure.attribute(index); } catch (NumberFormatException n) { throw new IllegalArgumentException("Unable to locate attribute " + attNameI + " as either a named attribute or as a valid " + "attribute index"); } } } } @Override public int compare(InstanceHolder o1, InstanceHolder o2) { // both missing is equal if (o1.m_instance.isMissing(m_attribute) && o2.m_instance.isMissing(m_attribute)) { return 0; } // one missing - missing instances should all be at the end // regardless of whether order is ascending or descending if (o1.m_instance.isMissing(m_attribute)) { return 1; } if (o2.m_instance.isMissing(m_attribute)) { return -1; } int cmp = 0; if (!m_attribute.isString() && !m_attribute.isRelationValued()) { double val1 = o1.m_instance.value(m_attribute); double val2 = o2.m_instance.value(m_attribute); cmp = Double.compare(val1, val2); } else if (m_attribute.isString()) { String val1 = o1.m_stringVals.get(m_attribute.name()); String val2 = o2.m_stringVals.get(m_attribute.name()); /* * String val1 = o1.stringValue(m_attribute); String val2 = * o2.stringValue(m_attribute); */ // TODO case insensitive? cmp = val1.compareTo(val2); } else { throw new IllegalArgumentException("Can't sort according to " + "relation-valued attribute values!"); } if (m_descending) { return -cmp; } return cmp; } } /** * Constructs a new Sorter */ public Sorter() { useDefaultVisual(); setLayout(new BorderLayout()); add(m_visual, BorderLayout.CENTER); m_env = Environment.getSystemWide(); m_stopRequested = new AtomicBoolean(false); } /** * Help information suitable for displaying in the GUI. * * @return a description of this component */ public String globalInfo() { return "Sorts incoming instances in ascending or descending order " + "according to the values of user specified attributes. Instances " + "can be sorted according to multiple attributes (defined in order). " + "Handles data sets larger than can be fit into main memory via " + "instance connections and specifying the in-memory buffer size. Implements " + "a merge-sort by writing the sorted in-memory buffer to a file when full " + "and then interleaving instances from the disk based file(s) when the " + "incoming stream has finished."; } /** * 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 (m_listenee == null) { return false; } if (!eventName.equals("instance") && !eventName.equals("dataSet")) { return false; } if (m_listenee instanceof DataSource) { if (m_listenee instanceof EventConstraints) { EventConstraints ec = (EventConstraints) m_listenee; return ec.eventGeneratable(eventName); } } if (m_listenee instanceof TrainingSetProducer) { if (m_listenee instanceof EventConstraints) { EventConstraints ec = (EventConstraints) m_listenee; if (!eventName.equals("dataSet")) { return false; } if (!ec.eventGeneratable("trainingSet")) { return false; } } } if (m_listenee instanceof TestSetProducer) { if (m_listenee instanceof EventConstraints) { EventConstraints ec = (EventConstraints) m_listenee; if (!eventName.equals("dataSet")) { return false; } if (!ec.eventGeneratable("testSet")) { return false; } } } return true; } private void copyStringAttVals(InstanceHolder holder) { for (String attName : m_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); } } /** * Accept and process an instance event * * @param e an <code>InstanceEvent</code> value */ @Override public void acceptInstance(InstanceEvent e) { if (e.getStatus() == InstanceEvent.FORMAT_AVAILABLE) { m_connectedFormat = e.getStructure(); m_stopRequested.set(false); try { init(new Instances(e.getStructure(), 0)); } catch (IllegalArgumentException ex) { if (m_log != null) { String message = "ERROR: There is a problem with the incoming instance structure"; // m_log.statusMessage(statusMessagePrefix() + message // + " - see log for details"); // m_log.logMessage(statusMessagePrefix() + message + " :" // + ex.getMessage()); stopWithErrorMessage(message, ex); // m_busy = false; return; } } String buffSize = m_bufferSize; try { buffSize = m_env.substitute(buffSize); m_bufferSizeI = Integer.parseInt(buffSize); } catch (Exception ex) { ex.printStackTrace(); } m_incrementalBuffer = new ArrayList<InstanceHolder>(m_bufferSizeI); m_bufferFiles = new ArrayList<File>(); m_streamCounter = 0; return; } m_busy = true; if (e.getInstance() != null) { if (m_streamCounter == 0) { if (m_log != null) { m_log.statusMessage(statusMessagePrefix() + "Starting streaming sort..."); m_log.logMessage("[Sorter] " + statusMessagePrefix() + " Using streaming buffer size: " + m_bufferSizeI); } } InstanceHolder tempH = new InstanceHolder(); tempH.m_instance = e.getInstance(); tempH.m_fileNumber = -1; // unused here if (m_stringAttIndexes != null) { copyStringAttVals(tempH); } m_incrementalBuffer.add(tempH); m_streamCounter++; } if (e.getInstance() == null || e.getStatus() == InstanceEvent.BATCH_FINISHED) { emitBufferedInstances(); // thread will set busy to false and report done status when // complete return; } else if (m_incrementalBuffer.size() == m_bufferSizeI) { // time to sort and write this to a temp file try { sortBuffer(true); } catch (Exception ex) { String msg = statusMessagePrefix() + "ERROR: unable to write to temp file."; // if (m_log != null) { // m_log.statusMessage(msg); // m_log.logMessage("[" + getCustomName() + "] " + msg); // } stopWithErrorMessage(msg, ex); // ex.printStackTrace(); m_busy = false; return; } } m_busy = false; } /** * Performs the merge stage of the merge sort by opening all temp files and * interleaving the instances. */ protected void emitBufferedInstances() { Thread t = new Thread() { @Override public void run() { int mergeCount = 0; if (m_incrementalBuffer.size() > 0 && !m_stopRequested.get()) { try { sortBuffer(false); } catch (Exception ex) { } if (m_bufferFiles.size() == 0) { // we only have the in memory buffer... if (m_stopRequested.get()) { m_busy = false; return; } String msg = statusMessagePrefix() + "Emitting in memory buffer...."; if (m_log != null) { m_log.statusMessage(msg); m_log.logMessage("[" + getCustomName() + "] " + msg); } Instances newHeader = new Instances( m_incrementalBuffer.get(0).m_instance.dataset(), 0); m_ie.setStructure(newHeader); notifyInstanceListeners(m_ie); for (int i = 0; i < m_incrementalBuffer.size(); i++) { InstanceHolder currentH = m_incrementalBuffer.get(i); currentH.m_instance.setDataset(newHeader); if (m_stringAttIndexes != null) { for (String attName : m_stringAttIndexes.keySet()) { boolean setValToZero = (newHeader.attribute(attName) .numValues() > 0); String valToSetInHeader = currentH.m_stringVals.get(attName); newHeader.attribute(attName).setStringValue(valToSetInHeader); if (setValToZero) { currentH.m_instance.setValue(newHeader.attribute(attName), 0); } } } if (m_stopRequested.get()) { m_busy = false; return; } m_ie.setInstance(currentH.m_instance); m_ie.setStatus(InstanceEvent.INSTANCE_AVAILABLE); if (i == m_incrementalBuffer.size() - 1) { m_ie.setStatus(InstanceEvent.BATCH_FINISHED); } notifyInstanceListeners(m_ie); } msg = statusMessagePrefix() + "Finished."; if (m_log != null) { m_log.statusMessage(msg); m_log.logMessage("[" + getCustomName() + "] " + msg); } m_busy = false; return; } } List<ObjectInputStream> inputStreams = new ArrayList<ObjectInputStream>(); // for the interleaving part of the merge sort List<InstanceHolder> merger = new ArrayList<InstanceHolder>(); Instances tempHeader = new Instances(m_connectedFormat, 0); m_ie.setStructure(tempHeader); notifyInstanceListeners(m_ie); // add an instance from the in-memory buffer first if (m_incrementalBuffer.size() > 0) { InstanceHolder tempH = m_incrementalBuffer.remove(0); merger.add(tempH); } if (m_stopRequested.get()) { m_busy = false; return; } if (m_bufferFiles.size() > 0) { String msg = statusMessagePrefix() + "Merging temp files..."; if (m_log != null) { m_log.statusMessage(msg); m_log.logMessage("[" + getCustomName() + "] " + msg); } } // open all temp buffer files and read one instance from each for (int i = 0; i < m_bufferFiles.size(); i++) { ObjectInputStream ois = null; try { FileInputStream fis = new FileInputStream(m_bufferFiles.get(i)); // GZIPInputStream giz = new GZIPInputStream(fis); BufferedInputStream bis = new BufferedInputStream(fis, 50000); ois = new ObjectInputStream(bis); InstanceHolder tempH = (InstanceHolder) ois.readObject(); if (tempH != null) { inputStreams.add(ois); tempH.m_fileNumber = i; merger.add(tempH); } else { // no instances?!?? ois.close(); } } catch (Exception ex) { ex.printStackTrace(); if (ois != null) { try { ois.close(); } catch (Exception e) { } } } } Collections.sort(merger, m_sortComparator); do { if (m_stopRequested.get()) { m_busy = false; break; } InstanceHolder holder = merger.remove(0); holder.m_instance.setDataset(tempHeader); if (m_stringAttIndexes != null) { for (String attName : m_stringAttIndexes.keySet()) { boolean setValToZero = (tempHeader.attribute(attName).numValues() > 1); String valToSetInHeader = holder.m_stringVals.get(attName); tempHeader.attribute(attName).setStringValue(valToSetInHeader); if (setValToZero) { holder.m_instance.setValue(tempHeader.attribute(attName), 0); } } } if (m_stopRequested.get()) { m_busy = false; break; } m_ie.setInstance(holder.m_instance); m_ie.setStatus(InstanceEvent.INSTANCE_AVAILABLE); mergeCount++; notifyInstanceListeners(m_ie); if (mergeCount % m_bufferSizeI == 0 && m_log != null) { String msg = statusMessagePrefix() + "Merged " + mergeCount + " instances"; if (m_log != null) { m_log.statusMessage(msg); } } int smallest = holder.m_fileNumber; // now get another instance from the source of "smallest" InstanceHolder nextH = null; if (smallest == -1) { if (m_incrementalBuffer.size() > 0) { nextH = m_incrementalBuffer.remove(0); nextH.m_fileNumber = -1; } } else { ObjectInputStream tis = inputStreams.get(smallest); try { InstanceHolder tempH = (InstanceHolder) tis.readObject(); if (tempH != null) { nextH = tempH; nextH.m_fileNumber = smallest; } else { throw new Exception("end of buffer"); } } catch (Exception ex) { // EOF try { if (m_log != null) { String msg = statusMessagePrefix() + "Closing temp file"; m_log.statusMessage(msg); } tis.close(); } catch (Exception e) { } File file = m_bufferFiles.remove(smallest); file.delete(); inputStreams.remove(smallest); // update file numbers for (InstanceHolder h : merger) { if (h.m_fileNumber != -1 && h.m_fileNumber > smallest) { h.m_fileNumber--; } } } } if (nextH != null) { // find the correct position (i.e. interleave) for this new Instance int index = Collections.binarySearch(merger, nextH, m_sortComparator); if (index < 0) { merger.add(index * -1 - 1, nextH); } else { merger.add(index, nextH); } nextH = null; } } while (merger.size() > 0 && !m_stopRequested.get()); if (!m_stopRequested.get()) { // signal the end of the stream m_ie.setInstance(null); m_ie.setStatus(InstanceEvent.BATCH_FINISHED); notifyInstanceListeners(m_ie); String msg = statusMessagePrefix() + "Finished."; if (m_log != null) { m_log.statusMessage(msg); m_log.logMessage("[" + getCustomName() + "] " + msg); } m_busy = false; } else { // try and close any input streams... for (ObjectInputStream is : inputStreams) { try { is.close(); } catch (Exception ex) { } } m_busy = false; } } }; t.setPriority(Thread.MIN_PRIORITY); t.start(); } /** * Sorts the in-memory buffer * * @param write whether to write the sorted buffer to a temp file * @throws Exception if a problem occurs */ protected void sortBuffer(boolean write) throws Exception { String msg = statusMessagePrefix() + "Sorting in memory buffer...."; if (m_log != null) { m_log.statusMessage(msg); m_log.logMessage("[" + getCustomName() + "] " + msg); } Collections.sort(m_incrementalBuffer, m_sortComparator); if (!write) { return; } String tmpDir = m_tempDirectory; File tempFile = File.createTempFile("Sorter", ".tmp"); if (tmpDir != null && tmpDir.length() > 0) { try { tmpDir = m_env.substitute(tmpDir); File tempDir = new File(tmpDir); if (tempDir.exists() && tempDir.canWrite()) { String filename = tempFile.getName(); File newFile = new File(tmpDir + File.separator + filename); tempFile = newFile; tempFile.deleteOnExit(); } } catch (Exception ex) { } } if (!m_stopRequested.get()) { m_bufferFiles.add(tempFile); FileOutputStream fos = new FileOutputStream(tempFile); // GZIPOutputStream gzo = new GZIPOutputStream(fos); BufferedOutputStream bos = new BufferedOutputStream(fos, 50000); ObjectOutputStream oos = new ObjectOutputStream(bos); msg = statusMessagePrefix() + "Writing buffer to temp file " + m_bufferFiles.size() + "..."; if (m_log != null) { m_log.statusMessage(msg); m_log.logMessage("[" + getCustomName() + "] " + msg); } for (int i = 0; i < m_incrementalBuffer.size(); i++) { InstanceHolder temp = m_incrementalBuffer.get(i); temp.m_instance.setDataset(null); oos.writeObject(temp); if (i % (m_bufferSizeI / 10) == 0) { oos.reset(); } } bos.flush(); oos.close(); } m_incrementalBuffer.clear(); } /** * Accept and process a test set event * * @param e a <code>TestSetEvent</code> value */ @Override public void acceptTestSet(TestSetEvent e) { Instances test = e.getTestSet(); DataSetEvent d = new DataSetEvent(this, test); acceptDataSet(d); } /** * Accept and process a training set event * * @param e a <code>TrainingSetEvent</code> value */ @Override public void acceptTrainingSet(TrainingSetEvent e) { Instances train = e.getTrainingSet(); DataSetEvent d = new DataSetEvent(this, train); acceptDataSet(d); } protected void init(Instances structure) { List<SortRule> sortRules = new ArrayList<SortRule>(); if (m_sortDetails != null && m_sortDetails.length() > 0) { String[] sortParts = m_sortDetails.split("@@sort-rule@@"); for (String s : sortParts) { SortRule r = new SortRule(s.trim()); r.init(m_env, structure); sortRules.add(r); } m_sortComparator = new SortComparator(sortRules); } // check for string attributes m_stringAttIndexes = new HashMap<String, Integer>(); for (int i = 0; i < structure.numAttributes(); i++) { if (structure.attribute(i).isString()) { m_stringAttIndexes.put(structure.attribute(i).name(), new Integer(i)); } } if (m_stringAttIndexes.size() == 0) { m_stringAttIndexes = null; } } /** * Get the size of the in-memory buffer * * @return the size of the in-memory buffer */ public String getBufferSize() { return m_bufferSize; } /** * Set the size of the in-memory buffer * * @param buffSize the size of the in-memory buffer */ public void setBufferSize(String buffSize) { m_bufferSize = buffSize; } /** * Set the directory to use for temporary files during incremental operation * * @param tempDir the temp dir to use */ public void setTempDirectory(String tempDir) { m_tempDirectory = tempDir; } /** * Get the directory to use for temporary files during incremental operation * * @return the temp dir to use */ public String getTempDirectory() { return m_tempDirectory; } /** * Set the sort rules to use * * @param sortDetails the sort rules in internal string representation */ public void setSortDetails(String sortDetails) { m_sortDetails = sortDetails; } /** * Get the sort rules to use * * @return the sort rules in internal string representation */ public String getSortDetails() { return m_sortDetails; } /** * Accept and process a data set event * * @param e a <code>DataSetEvent</code> value */ @Override public void acceptDataSet(DataSetEvent e) { m_busy = true; m_stopRequested.set(false); if (m_log != null && e.getDataSet().numInstances() > 0) { m_log.statusMessage(statusMessagePrefix() + "Sorting batch..."); } if (e.isStructureOnly()) { // nothing to sort! // just notify listeners of structure DataSetEvent d = new DataSetEvent(this, e.getDataSet()); notifyDataListeners(d); m_busy = false; return; } try { init(new Instances(e.getDataSet(), 0)); } catch (IllegalArgumentException ex) { if (m_log != null) { String message = "ERROR: There is a problem with the incoming instance structure"; // m_log.statusMessage(statusMessagePrefix() + message // + " - see log for details"); // m_log.logMessage(statusMessagePrefix() + message + " :" // + ex.getMessage()); stopWithErrorMessage(message, ex); m_busy = false; return; } } List<InstanceHolder> instances = new ArrayList<InstanceHolder>(); for (int i = 0; i < e.getDataSet().numInstances(); i++) { InstanceHolder h = new InstanceHolder(); h.m_instance = e.getDataSet().instance(i); instances.add(h); } Collections.sort(instances, m_sortComparator); Instances output = new Instances(e.getDataSet(), 0); for (int i = 0; i < instances.size(); i++) { output.add(instances.get(i).m_instance); } DataSetEvent d = new DataSetEvent(this, output); notifyDataListeners(d); if (m_log != null) { m_log.statusMessage(statusMessagePrefix() + "Finished."); } m_busy = false; } /** * Add a datasource listener * * @param dsl the datasource listener to add */ @Override public void addDataSourceListener(DataSourceListener dsl) { m_dataListeners.add(dsl); } /** * Remove a datasource listener * * @param dsl the datasource 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 representation */ @Override public void useDefaultVisual() { m_visual.loadIcons(BeanVisual.ICON_PATH + "Sorter.gif", BeanVisual.ICON_PATH + "Sorter_animated.gif"); m_visual.setText("Sorter"); } /** * Set a new visual representation * * @param newVisual a <code>BeanVisual</code> value */ @Override public void setVisual(BeanVisual newVisual) { m_visual = newVisual; } /** * Get the visual representation * * @return a <code>BeanVisual</code> value */ @Override public BeanVisual getVisual() { return m_visual; } /** * 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(); } /** * Stop any processing that the bean might be doing. */ @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; m_stopRequested.set(true); } /** * Stops the step (and upstream ones) and then prints an error message and * optional exception message * * @param error the error message to print * @param ex the optional exception */ protected void stopWithErrorMessage(String error, Exception ex) { stop(); if (m_log != null) { m_log.statusMessage(statusMessagePrefix() + error + " - see log for details"); m_log.logMessage(statusMessagePrefix() + error + (ex != null ? " " + ex.getMessage() : "")); } } /** * 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_busy; } /** * Set a logger * * @param logger a <code>weka.gui.Logger</code> value */ @Override public void setLog(Logger logger) { 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(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) { if (!eventName.equals("instance") && !eventName.equals("dataSet") && !eventName.equals("trainingSet") && !eventName.equals("testSet")) { return false; } if (m_listenee != null) { return false; } return true; } /** * Notify this object that it has been registered as a listener with a source * for receiving 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; m_connectionType = eventName; } } /** * 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 (source == m_listenee) { m_listenee = null; } } @SuppressWarnings("unchecked") private void notifyInstanceListeners(InstanceEvent e) { List<InstanceListener> l; synchronized (this) { l = (List<InstanceListener>) m_instanceListeners.clone(); } if (l.size() > 0) { for (InstanceListener il : l) { il.acceptInstance(e); } } } @SuppressWarnings("unchecked") private void notifyDataListeners(DataSetEvent e) { List<DataSourceListener> l; synchronized (this) { l = (List<DataSourceListener>) m_dataListeners.clone(); } if (l.size() > 0) { for (DataSourceListener ds : l) { ds.acceptDataSet(e); } } } 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_dataListeners.size() == 0) { return null; } if (eventName.equals("instance") && m_instanceListeners.size() == 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; } /** * Set 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/SorterBeanInfo.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * SorterBeanInfo.java * Copyright (C) 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 Sorter step * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision$ */ public class SorterBeanInfo extends SimpleBeanInfo { /** * Returns the event set descriptors * * @return an <code>EventSetDescriptor[]</code> value */ 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 */ public BeanDescriptor getBeanDescriptor() { return new BeanDescriptor(Sorter.class, SorterCustomizer.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/SorterCustomizer.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * SorterCustomizer.java * Copyright (C) 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.KeyAdapter; import java.awt.event.KeyEvent; import javax.swing.BorderFactory; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextField; 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 for the Sorter step * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision$ * */ public class SorterCustomizer extends JPanel implements BeanCustomizer, EnvironmentHandler, CustomizerCloseRequester { /** For serialization */ private static final long serialVersionUID = -4860246697276275408L; /** The Sorter we are editing */ protected Sorter m_sorter; protected Environment m_env = Environment.getSystemWide(); protected ModifyListener m_modifyL = null; protected JComboBox m_attCombo = new JComboBox(); protected JComboBox m_descending = new JComboBox(); protected EnvironmentField m_buffSize; protected FileEnvironmentField m_tempDir; protected Window m_parent; protected JList m_list = new JList(); protected DefaultListModel m_listModel; protected JButton m_newBut = new JButton("New"); protected JButton m_deleteBut = new JButton("Delete"); protected JButton m_upBut = new JButton("Move up"); protected JButton m_downBut = new JButton("Move down"); protected PropertySheetPanel m_tempEditor = new PropertySheetPanel(); /** * Constructor */ public SorterCustomizer() { 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,2)); JPanel attListP = new JPanel(); attListP.setLayout(new BorderLayout()); attListP.setBorder(BorderFactory.createTitledBorder("Sort on attribute")); attListP.add(m_attCombo, BorderLayout.CENTER); m_attCombo.setEditable(true); //m_attCombo.setFocusable(); //m_attCombo.getEditor().getEditorComponent().setFocusable(true); m_attCombo.setToolTipText("<html>Accepts an attribute name, index or <br> " + "the special string \"/first\" and \"/last\"</html>"); m_descending.addItem("No"); m_descending.addItem("Yes"); JPanel descendingP = new JPanel(); descendingP.setLayout(new BorderLayout()); descendingP.setBorder(BorderFactory.createTitledBorder("Sort descending")); descendingP.add(m_descending, BorderLayout.CENTER); fieldHolder.add(attListP); fieldHolder.add(descendingP); controlHolder.add(fieldHolder, BorderLayout.NORTH); JPanel otherControls = new JPanel(); otherControls.setLayout(new GridLayout(0,2)); JLabel bufferSizeLab = new JLabel("Size of in-mem streaming buffer", SwingConstants.RIGHT); bufferSizeLab.setToolTipText("<html>Number of instances to sort in memory " + "<br>before writing to a temp file " + "<br>(instance connections only).</html>"); otherControls.add(bufferSizeLab); m_buffSize = new EnvironmentField(m_env); otherControls.add(m_buffSize); JLabel tempDirLab = new JLabel("Directory for temp files", SwingConstants.RIGHT); tempDirLab.setToolTipText("Will use system tmp dir if left blank"); otherControls.add(tempDirLab); m_tempDir = new FileEnvironmentField("", m_env, JFileChooser.OPEN_DIALOG, true); m_tempDir.resetFileFilters(); otherControls.add(m_tempDir); controlHolder.add(otherControls, BorderLayout.SOUTH); aboutAndControlHolder.add(controlHolder, BorderLayout.SOUTH); JPanel aboutP = m_tempEditor.getAboutPanel(); aboutAndControlHolder.add(aboutP, BorderLayout.NORTH); add(aboutAndControlHolder, BorderLayout.NORTH); m_list.setVisibleRowCount(5); m_deleteBut.setEnabled(false); JPanel listPanel = new JPanel(); listPanel.setLayout(new BorderLayout()); JPanel butHolder = new JPanel(); butHolder.setLayout(new GridLayout(1, 0)); butHolder.add(m_newBut); butHolder.add(m_deleteBut); butHolder.add(m_upBut); butHolder.add(m_downBut); m_upBut.setEnabled(false); m_downBut.setEnabled(false); listPanel.add(butHolder, BorderLayout.NORTH); JScrollPane js = new JScrollPane(m_list); js.setBorder(BorderFactory. createTitledBorder("Sort-by list (rows applied in order)")); listPanel.add(js, BorderLayout.CENTER); add(listPanel, BorderLayout.CENTER); addButtons(); m_list.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { if (!m_deleteBut.isEnabled()) { m_deleteBut.setEnabled(true); } Object entry = m_list.getSelectedValue(); if (entry != null) { Sorter.SortRule m = (Sorter.SortRule)entry; m_attCombo.setSelectedItem(m.getAttribute()); if (m.getDescending()) { m_descending.setSelectedIndex(1); } else { m_descending.setSelectedIndex(0); } } } } }); m_newBut.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Sorter.SortRule m = new Sorter.SortRule(); String att = (m_attCombo.getSelectedItem() != null) ? m_attCombo.getSelectedItem().toString() : ""; m.setAttribute(att); m.setDescending(m_descending.getSelectedIndex() == 1); m_listModel.addElement(m); if (m_listModel.size() > 1) { m_upBut.setEnabled(true); m_downBut.setEnabled(true); } m_list.setSelectedIndex(m_listModel.size() - 1); } }); m_deleteBut.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int selected = m_list.getSelectedIndex(); if (selected >= 0) { m_listModel.removeElementAt(selected); if (m_listModel.size() <= 1) { m_upBut.setEnabled(false); m_downBut.setEnabled(false); } } } }); m_upBut.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JListHelper.moveUp(m_list); } }); m_downBut.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JListHelper.moveDown(m_list); } }); m_attCombo.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() { public void keyReleased(KeyEvent e) { Object m = m_list.getSelectedValue(); String text = ""; if (m_attCombo.getSelectedItem() != null) { text = m_attCombo.getSelectedItem().toString(); } java.awt.Component theEditor = m_attCombo.getEditor().getEditorComponent(); if (theEditor instanceof JTextField) { text = ((JTextField)theEditor).getText(); } if (m != null) { ((Sorter.SortRule)m). setAttribute(text); m_list.repaint(); } } }); m_attCombo.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Object m = m_list.getSelectedValue(); Object selected = m_attCombo.getSelectedItem(); if (m != null && selected != null) { ((Sorter.SortRule)m). setAttribute(selected.toString()); m_list.repaint(); } } }); m_descending.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Object m = m_list.getSelectedValue(); if (m != null) { ((Sorter.SortRule)m).setDescending(m_descending.getSelectedIndex() == 1); m_list.repaint(); } } }); } 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) { closingOK(); m_parent.dispose(); } }); cancelBut.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { closingCancel(); m_parent.dispose(); } }); } /** * Handle a closing event under an OK condition */ protected void closingOK() { StringBuffer buff = new StringBuffer(); for (int i = 0; i < m_listModel.size(); i++) { Sorter.SortRule m = (Sorter.SortRule)m_listModel.elementAt(i); buff.append(m.toStringInternal()); if (i < m_listModel.size() - 1) { buff.append("@@sort-rule@@"); } } if (m_sorter.getSortDetails() != null) { if (!m_sorter.getSortDetails().equals(buff.toString())) { m_modifyL.setModifiedStatus(SorterCustomizer.this, true); } } else { m_modifyL.setModifiedStatus(SorterCustomizer.this, true); } m_sorter.setSortDetails(buff.toString()); if (m_buffSize.getText() != null && m_buffSize.getText().length() > 0) { if (m_sorter.getBufferSize() != null && !m_sorter.getBufferSize().equals(m_buffSize.getText())) { m_modifyL.setModifiedStatus(SorterCustomizer.this, true); } m_sorter.setBufferSize(m_buffSize.getText()); } if (m_tempDir.getText() != null && m_tempDir.getText().length() > 0) { if (m_sorter.getTempDirectory() != null && !m_sorter.getTempDirectory().equals(m_tempDir.getText())) { m_modifyL.setModifiedStatus(SorterCustomizer.this, true); } m_sorter.setTempDirectory(m_tempDir.getText()); } } /** * Handle a closing event under a CANCEL condition */ protected void closingCancel() { // nothing to do } /** * Initialize widgets with values from Sorter */ protected void initialize() { if (m_sorter.getBufferSize() != null && m_sorter.getBufferSize().length() > 0) { m_buffSize.setText(m_sorter.getBufferSize()); } if (m_sorter.getTempDirectory() != null && m_sorter.getTempDirectory().length() > 0) { m_tempDir.setText(m_sorter.getTempDirectory()); } String sString = m_sorter.getSortDetails(); m_listModel = new DefaultListModel(); m_list.setModel(m_listModel); if (sString != null && sString.length() > 0) { String[] parts = sString.split("@@sort-rule@@"); if (parts.length > 0) { m_upBut.setEnabled(true); m_downBut.setEnabled(true); for (String sPart : parts) { Sorter.SortRule s = new Sorter.SortRule(sPart); m_listModel.addElement(s); } } m_list.repaint(); } // try and set up attribute combo if (m_sorter.getConnectedFormat() != null) { Instances incoming = m_sorter.getConnectedFormat(); m_attCombo.removeAllItems(); for (int i = 0; i < incoming.numAttributes(); i++) { m_attCombo.addItem(incoming.attribute(i).name()); } } } /** * Set the object to edit */ public void setObject(Object o) { if (o instanceof Sorter) { m_sorter = (Sorter)o; m_tempEditor.setTarget(o); setup(); initialize(); } } /** * Set the parent window for this dialog * * @param parent the parent window */ public void setParentWindow(Window parent) { m_parent = parent; } /** * Set environment variables to use * * @param env the environment variables to use */ public void setEnvironment(Environment env) { m_env = env; } /** * The modify listener interested in any chages we might make */ public void setModifiedListener(ModifyListener l) { m_modifyL = 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/StartUpListener.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * StartUpListener.java * Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.beans; import java.util.EventListener; /** * Interface to something that can be notified of a successful startup * * @author Mark Hall * @version $Revision$ */ public interface StartUpListener extends EventListener { void startUpComplete(); }
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/Startable.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * Startable.java * Copyright (C) 2008-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.beans; /** * Interface to something that is a start point for a flow and * can be launched programatically. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}org) * @version $Revision$ * @since 1.0 */ public interface Startable { /** * Start the flow running * * @exception Exception if something goes wrong */ void start() throws Exception; /** * Gets a string that describes the start action. The * KnowledgeFlow uses this in the popup contextual menu * for the component. The string can be proceeded by * a '$' character to indicate that the component can't * be started at present. * * @return a string describing the start action. */ String getStartMessage(); }
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/StreamThroughput.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * StreamThroughput.java * Copyright (C) 2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.beans; import java.io.Serializable; import weka.gui.Logger; /** * Class for measuring throughput of an incremental Knowledge Flow step. Typical * usage is to construct a StreamThroughput object at the start of the stream * (i.e. FORMAT_AVAILABLE event) and then for each instance received call * updateStart() just before processing the instance and then updateEnd() just * after. If updateEnd() is called *before* sending any event to downstream * step(s) then throughput just with respect to work done by the step will be * measured. * * Elapsed time to process each instance (along with the number of instances) is * accumulated over the sample time period. Instances per second is computed at * the end of each sample period and added to a running total. Average * instances/sec is reported to the status area of the log. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision$ */ public class StreamThroughput implements Serializable { /** * For serialization */ private static final long serialVersionUID = 2820675210555581676L; protected transient int m_avInstsPerSec = 0; protected transient double m_startTime; protected transient int m_instanceCount; protected transient int m_sampleCount; protected transient String m_statusMessagePrefix = ""; /** * sample period over which to count instances processed and instances/sec * throughput */ protected transient int m_sampleTime = 2000; protected transient double m_cumulativeTime; protected transient int m_numSamples; /** * Construct a new StreamThroughput * * @param statusMessagePrefix the unique identifier of the Knowledge Flow * component being measured. This enables the correct line in the * status area to be updated. See any Knowledge Flow step for an * example. */ public StreamThroughput(String statusMessagePrefix) { m_instanceCount = 0; m_sampleCount = 0; m_numSamples = 0; m_cumulativeTime = 0; m_startTime = System.currentTimeMillis(); m_statusMessagePrefix = statusMessagePrefix; } /** * Construct a new StreamThroughput * * @param statusMessagePrefix the unique identifier of the Knowledge Flow * component being measured. This enables the correct line in the * status area to be updated. See any Knowledge Flow step for an * example. * @param initialMessage an initial message to print to the status area for * this step on construction * @param log the log to write status updates to */ public StreamThroughput(String statusMessagePrefix, String initialMessage, Logger log) { this(statusMessagePrefix); if (log != null) { log.statusMessage(m_statusMessagePrefix + initialMessage); } } /** * Set the sampling period (in milliseconds) to compute througput over * * @param period the sampling period in milliseconds */ public void setSamplePeriod(int period) { m_sampleTime = period; } protected transient double m_updateStart; /** * Register a throughput measurement start point */ public void updateStart() { m_updateStart = System.currentTimeMillis(); } /** * Register a throughput measurement end point. Collects counts and * statistics. Will update the status area for the KF step in question if the * sample period has elapsed. * * @param log the log to write status updates to */ public void updateEnd(Logger log) { m_instanceCount++; m_sampleCount++; double end = System.currentTimeMillis(); double temp = end - m_updateStart; m_cumulativeTime += temp; boolean toFastToMeasure = false; if ((end - m_startTime) >= m_sampleTime) { computeUpdate(end); if (log != null) { log.statusMessage(m_statusMessagePrefix + "Processed " + m_instanceCount + " insts @ " + m_avInstsPerSec / m_numSamples + " insts/sec" + (toFastToMeasure ? "*" : "")); } m_sampleCount = 0; m_cumulativeTime = 0; m_startTime = System.currentTimeMillis(); } } protected boolean computeUpdate(double end) { boolean toFastToMeasure = false; int instsPerSec = 0; if (m_cumulativeTime == 0) { // all single instance updates have taken < 1 millisecond each! // the best we can do is compute the insts/sec based on the total // number of instances processed in the elapsed sample time // (rather than using the total number processed and the actual // cumulative elapsed processing time). This is going to be closer // to the throughput for the entire flow rather than for the component // itself double sampleTime = (end - m_startTime); instsPerSec = (int) (m_sampleCount / (sampleTime / 1000.0)); toFastToMeasure = true; } else { instsPerSec = (int) (m_sampleCount / (m_cumulativeTime / 1000.0)); } m_numSamples++; m_avInstsPerSec += instsPerSec; return toFastToMeasure; } /** * Get the average instances per second * * @return the average instances per second processed */ public int getAverageInstancesPerSecond() { int nS = m_numSamples > 0 ? m_numSamples : 1; return m_avInstsPerSec / nS; } /** * Register the end of measurement. Writes a "Finished" update (that includes * the final throughput info) to the status area of the log. * * @param log the log to write to * @return the message written to the status area. */ public String finished(Logger log) { if (m_avInstsPerSec == 0) { computeUpdate(System.currentTimeMillis()); } int nS = m_numSamples > 0 ? m_numSamples : 1; String msg = "Finished - " + m_instanceCount + " insts @ " + m_avInstsPerSec / nS + " insts/sec"; if (log != null) { log.statusMessage(m_statusMessagePrefix + msg); } return msg; } /** * Register the end of measurement. Does not write a "Finished" update to the * log * * @return a message that contains the final throughput info. */ public String finished() { if (m_avInstsPerSec == 0) { computeUpdate(System.currentTimeMillis()); } int nS = m_numSamples > 0 ? m_numSamples : 1; String msg = "Finished - " + m_instanceCount + " insts @ " + m_avInstsPerSec / nS + " insts/sec"; return msg; } }
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/StripChart.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * StripChart.java * Copyright (C) 2002-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.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Image; import java.beans.EventSetDescriptor; import java.io.IOException; import java.io.ObjectInputStream; import java.util.Enumeration; import java.util.LinkedList; import java.util.Random; import java.util.Vector; import javax.swing.*; import javax.swing.border.TitledBorder; import weka.core.Instance; import weka.core.Instances; import weka.core.Utils; import weka.gui.visualize.PrintableComponent; import weka.gui.visualize.VisualizeUtils; /** * Bean that can display a horizontally scrolling strip chart. Can display * multiple plots simultaneously * * @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a> * @version $Revision$ */ public class StripChart extends JPanel implements ChartListener, InstanceListener, Visible, BeanCommon, UserRequestAcceptor { /** for serialization */ private static final long serialVersionUID = 1483649041577695019L; /** default colours for colouring lines */ protected Color[] m_colorList = { Color.green, Color.red, Color.blue, Color.cyan, Color.pink, new Color(255, 0, 255), Color.orange, new Color(255, 0, 0), new Color(0, 255, 0), Color.white }; /** the background color. */ protected Color m_BackgroundColor; /** the color of the legend panel's border. */ protected Color m_LegendPanelBorderColor; /** * Class providing a panel for the plot. */ private class StripPlotter extends JPanel { /** for serialization. */ private static final long serialVersionUID = -7056271598761675879L; @Override public void paintComponent(Graphics g) { super.paintComponent(g); if (m_osi != null) { g.drawImage(m_osi, 0, 0, this); } } } private transient JFrame m_outputFrame = null; private transient StripPlotter m_plotPanel = null; /** * The off screen image for rendering to. */ private transient Image m_osi = null; /** * Width and height of the off screen image. */ private int m_iheight; private int m_iwidth; /** * Max value for the y axis. */ private double m_max = 1; /** * Min value for the y axis. */ private double m_min = 0; /** * Scale update requested. */ private boolean m_yScaleUpdate = false; private double m_oldMax; private double m_oldMin; private final Font m_labelFont = new Font("Monospaced", Font.PLAIN, 10); private FontMetrics m_labelMetrics; // private int m_plotCount = 0; private Vector<String> m_legendText = new Vector<String>(); /** * Class providing a panel for displaying the y axis. */ private class ScalePanel extends JPanel { /** for serialization. */ private static final long serialVersionUID = 6416998474984829434L; @Override public void paintComponent(Graphics gx) { super.paintComponent(gx); if (m_labelMetrics == null) { m_labelMetrics = gx.getFontMetrics(m_labelFont); } gx.setFont(m_labelFont); int hf = m_labelMetrics.getAscent(); String temp = "" + m_max; gx.setColor(m_colorList[m_colorList.length - 1]); gx.drawString(temp, 1, hf - 2); temp = "" + (m_min + ((m_max - m_min) / 2.0)); gx.drawString(temp, 1, (this.getHeight() / 2) + (hf / 2)); temp = "" + m_min; gx.drawString(temp, 1, this.getHeight() - 1); } }; /** the scale. */ private final ScalePanel m_scalePanel = new ScalePanel(); /** * Class providing a panel for the legend. */ private class LegendPanel extends JPanel { /** for serialization. */ private static final long serialVersionUID = 7713986576833797583L; @Override public void paintComponent(Graphics gx) { super.paintComponent(gx); if (m_labelMetrics == null) { m_labelMetrics = gx.getFontMetrics(m_labelFont); } int hf = m_labelMetrics.getAscent(); int x = 10; int y = hf + 15; gx.setFont(m_labelFont); for (int i = 0; i < m_legendText.size(); i++) { String temp = m_legendText.elementAt(i); gx.setColor(m_colorList[(i % m_colorList.length)]); gx.drawString(temp, x, y); y += hf; } StripChart.this.revalidate(); } }; /** the legend. */ private final LegendPanel m_legendPanel = new LegendPanel(); /** * Holds the data to be plotted. Entries in the list are arrays of y points. */ private LinkedList<double[]> m_dataList = new LinkedList<double[]>(); // private double [] m_dataPoint = new double[1]; private double[] m_previousY = new double[1]; private transient Thread m_updateHandler; protected BeanVisual m_visual = new BeanVisual("StripChart", BeanVisual.ICON_PATH + "StripChart.gif", BeanVisual.ICON_PATH + "StripChart_animated.gif"); private Object m_listenee = null; /** * Print x axis labels every m_xValFreq points */ private int m_xValFreq = 500; private int m_xCount = 0; /** * Shift the plot by this many pixels every time a point is plotted */ private int m_refreshWidth = 1; private int m_userRefreshWidth = 1; /** * Plot every m_refreshFrequency'th point */ private int m_refreshFrequency = 5; /** the class responsible for printing */ protected PrintableComponent m_Printer = null; public StripChart() { // m_plotPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5)); setLayout(new BorderLayout()); add(m_visual, BorderLayout.CENTER); // start a thread to handle plot updates initPlot(); } /** * 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 "Visualize incremental classifier performance as a scrolling plot."; } /** * GUI Tip text * * @return a <code>String</code> value */ public String xLabelFreqTipText() { return "Show x axis labels this often"; } /** * Set the frequency for printing x label values * * @param freq an <code>int</code> value */ public void setXLabelFreq(int freq) { m_xValFreq = freq; if (getGraphics() != null) { setRefreshGap(); } } /** * Get the frequency by which x axis values are printed * * @return an <code>int</code> value */ public int getXLabelFreq() { return m_xValFreq; } /** * GUI Tip text * * @return a <code>String</code> value */ public String refreshFreqTipText() { return "Plot every x'th data point"; } /** * Set how often (in x axis points) to refresh the display * * @param freq an <code>int</code> value */ public void setRefreshFreq(int freq) { m_refreshFrequency = freq; if (getGraphics() != null) { setRefreshGap(); } } /** * Get the refresh frequency * * @return an <code>int</code> value */ public int getRefreshFreq() { return m_refreshFrequency; } /** * GUI Tip text * * @return a <code>String</code> value */ public String refreshWidthTipText() { return "The number of pixels to shift the plot by every time a point" + " is plotted."; } /** * Set how many pixels to shift the plot by every time a point is plotted * * @param width the number of pixels to shift the plot by */ public void setRefreshWidth(int width) { if (width > 0) { m_userRefreshWidth = width; } } /** * Get how many pixels to shift the plot by every time a point is plotted * * @return the number of pixels to shift the plot by */ public int getRefreshWidth() { return m_userRefreshWidth; } private void setRefreshGap() { m_refreshWidth = m_userRefreshWidth; if (m_labelMetrics == null) { getGraphics().setFont(m_labelFont); m_labelMetrics = getGraphics().getFontMetrics(m_labelFont); } int refWidth = m_labelMetrics.stringWidth("99000"); // compute how often x label will be rendered int z = (getXLabelFreq() / getRefreshFreq()); if (z < 1) { z = 1; } if (z * m_refreshWidth < refWidth + 5) { m_refreshWidth *= (((refWidth + 5) / z) + 1); } } /** * Provide some necessary initialization after object has been 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(); initPlot(); // startHandler(); } catch (Exception ex) { ex.printStackTrace(); } } /** * Loads properties from properties file. * * @see KnowledgeFlowApp#BEAN_PROPERTIES */ private void setProperties() { String key; String color; // background color key = this.getClass().getName() + ".backgroundColour"; color = BeansProperties.BEAN_PROPERTIES.getProperty(key); m_BackgroundColor = Color.BLACK; if (color != null) { m_BackgroundColor = VisualizeUtils .processColour(color, m_BackgroundColor); } // legend color (border) key = m_legendPanel.getClass().getName() + ".borderColour"; color = BeansProperties.BEAN_PROPERTIES.getProperty(key); m_LegendPanelBorderColor = Color.BLUE; if (color != null) { m_LegendPanelBorderColor = VisualizeUtils.processColour(color, m_LegendPanelBorderColor); } } private void initPlot() { setProperties(); m_plotPanel = new StripPlotter(); m_plotPanel.setBackground(m_BackgroundColor); m_scalePanel.setBackground(m_BackgroundColor); m_legendPanel.setBackground(m_BackgroundColor); m_xCount = 0; } private void startHandler() { if (m_updateHandler == null) { m_updateHandler = new Thread() { private double[] dataPoint; @Override public void run() { while (true) { if (m_outputFrame != null) { synchronized (m_dataList) { while (m_dataList.isEmpty()) { // while (m_dataList.empty()) { try { m_dataList.wait(); } catch (InterruptedException ex) { return; } } dataPoint = m_dataList.remove(0); // dataPoint = (double [])m_dataList.pop(); } if (m_outputFrame != null) { StripChart.this.updateChart(dataPoint); } } } } }; // m_updateHandler.setPriority(Thread.MIN_PRIORITY); m_updateHandler.start(); } } /** * Popup the chart panel */ public void showChart() { if (m_outputFrame == null) { m_outputFrame = Utils.getWekaJFrame("Strip Chart", m_visual); m_outputFrame.getContentPane().setLayout(new BorderLayout()); JPanel panel = new JPanel(new BorderLayout()); new PrintableComponent(panel); m_outputFrame.getContentPane().add(panel, BorderLayout.CENTER); panel.add(m_legendPanel, BorderLayout.WEST); panel.add(m_plotPanel, BorderLayout.CENTER); panel.add(m_scalePanel, BorderLayout.EAST); m_legendPanel.setMinimumSize(new Dimension(100, getHeight())); m_legendPanel.setPreferredSize(new Dimension(100, getHeight())); m_scalePanel.setMinimumSize(new Dimension(30, getHeight())); m_scalePanel.setPreferredSize(new Dimension(30, getHeight())); Font lf = new Font("Monospaced", Font.PLAIN, 12); m_legendPanel.setBorder(BorderFactory.createTitledBorder( BorderFactory.createEtchedBorder(Color.gray, Color.darkGray), "Legend", TitledBorder.CENTER, TitledBorder.DEFAULT_POSITION, lf, m_LegendPanelBorderColor)); m_outputFrame.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { if (m_updateHandler != null) { System.err.println("Interrupting"); m_updateHandler.interrupt(); m_updateHandler = null; } synchronized (m_dataList) { m_dataList = new LinkedList<double[]>(); } m_outputFrame.dispose(); m_outputFrame = null; } }); m_outputFrame.pack(); m_outputFrame.setSize(600, 150); m_outputFrame.setResizable(false); m_outputFrame.setLocationRelativeTo(SwingUtilities.getWindowAncestor(m_visual)); m_outputFrame.setVisible(true); m_outputFrame.setAlwaysOnTop(true); // m_outputFrame.setLocationByPlatform(true); int iwidth = m_plotPanel.getWidth(); int iheight = m_plotPanel.getHeight(); m_osi = m_plotPanel.createImage(iwidth, iheight); Graphics m = m_osi.getGraphics(); m.setColor(m_BackgroundColor); m.fillRect(0, 0, iwidth, iheight); m_previousY[0] = -1; setRefreshGap(); if (m_updateHandler == null) { System.err.println("Starting handler"); startHandler(); } } else { m_outputFrame.toFront(); } } private int convertToPanelY(double yval) { int height = m_plotPanel.getHeight(); double temp = (yval - m_min) / (m_max - m_min); temp = temp * height; temp = height - temp; return (int) temp; } /** * Update the plot * * @param dataPoint contains y values to plot */ protected void updateChart(double[] dataPoint) { if (m_previousY[0] == -1) { int iw = m_plotPanel.getWidth(); int ih = m_plotPanel.getHeight(); m_osi = m_plotPanel.createImage(iw, ih); Graphics m = m_osi.getGraphics(); m.setColor(m_BackgroundColor); m.fillRect(0, 0, iw, ih); m_previousY[0] = convertToPanelY(0); m_iheight = ih; m_iwidth = iw; } if (dataPoint.length - 1 != m_previousY.length) { m_previousY = new double[dataPoint.length - 1]; // m_plotCount = 0; for (int i = 0; i < dataPoint.length - 1; i++) { m_previousY[i] = convertToPanelY(0); } } Graphics osg = m_osi.getGraphics(); Graphics g = m_plotPanel.getGraphics(); osg.copyArea(m_refreshWidth, 0, m_iwidth - m_refreshWidth, m_iheight, -m_refreshWidth, 0); osg.setColor(m_BackgroundColor); osg.fillRect(m_iwidth - m_refreshWidth, 0, m_iwidth, m_iheight); // paint the old scale onto the plot if a scale update has occured if (m_yScaleUpdate) { String maxVal = numToString(m_oldMax); String minVal = numToString(m_oldMin); String midVal = numToString((m_oldMax - m_oldMin) / 2.0); if (m_labelMetrics == null) { m_labelMetrics = g.getFontMetrics(m_labelFont); } osg.setFont(m_labelFont); int wmx = m_labelMetrics.stringWidth(maxVal); int wmn = m_labelMetrics.stringWidth(minVal); int wmd = m_labelMetrics.stringWidth(midVal); int hf = m_labelMetrics.getAscent(); osg.setColor(m_colorList[m_colorList.length - 1]); osg.drawString(maxVal, m_iwidth - wmx, hf - 2); osg.drawString(midVal, m_iwidth - wmd, (m_iheight / 2) + (hf / 2)); osg.drawString(minVal, m_iwidth - wmn, m_iheight - 1); m_yScaleUpdate = false; } double pos; for (int i = 0; i < dataPoint.length - 1; i++) { if (Utils.isMissingValue(dataPoint[i])) { continue; } osg.setColor(m_colorList[(i % m_colorList.length)]); pos = convertToPanelY(dataPoint[i]); osg.drawLine(m_iwidth - m_refreshWidth, (int) m_previousY[i], m_iwidth - 1, (int) pos); m_previousY[i] = pos; if (dataPoint[dataPoint.length - 1] % m_xValFreq == 0) { // draw the actual y value onto the plot for this curve String val = numToString(dataPoint[i]); if (m_labelMetrics == null) { m_labelMetrics = g.getFontMetrics(m_labelFont); } int hf = m_labelMetrics.getAscent(); if (pos - hf < 0) { pos += hf; } int w = m_labelMetrics.stringWidth(val); osg.setFont(m_labelFont); osg.drawString(val, m_iwidth - w, (int) pos); } } // last element in the data point array contains the data point number if (dataPoint[dataPoint.length - 1] % m_xValFreq == 0) { String xVal = "" + (int) dataPoint[dataPoint.length - 1]; osg.setColor(m_colorList[m_colorList.length - 1]); int w = m_labelMetrics.stringWidth(xVal); osg.setFont(m_labelFont); osg.drawString(xVal, m_iwidth - w, m_iheight - 1); } g.drawImage(m_osi, 0, 0, m_plotPanel); // System.err.println("Finished"); // m_plotCount++; } private static String numToString(double num) { int precision = 1; int whole = (int) Math.abs(num); double decimal = Math.abs(num) - whole; int nondecimal; nondecimal = (whole > 0) ? (int) (Math.log(whole) / Math.log(10)) : 1; precision = (decimal > 0) ? (int) Math.abs(((Math.log(Math.abs(num)) / Math .log(10)))) + 2 : 1; if (precision > 5) { precision = 1; } String numString = weka.core.Utils.doubleToString(num, nondecimal + 1 + precision, precision); return numString; } ChartEvent m_ce = new ChartEvent(this); double[] m_dataPoint = null; @Override public void acceptInstance(InstanceEvent e) { if (e.getStatus() == InstanceEvent.FORMAT_AVAILABLE) { Instances structure = e.getStructure(); m_legendText = new Vector<String>(); m_max = 1.0; m_min = 0; int i = 0; for (i = 0; i < structure.numAttributes(); i++) { if (i > 10) { i--; break; } m_legendText.addElement(structure.attribute(i).name()); m_legendPanel.repaint(); m_scalePanel.repaint(); } m_dataPoint = new double[i]; m_xCount = 0; return; } // process data point Instance inst = e.getInstance(); for (int i = 0; i < m_dataPoint.length; i++) { if (!inst.isMissing(i)) { m_dataPoint[i] = inst.value(i); } } acceptDataPoint(m_dataPoint); m_xCount++; } /** * Accept a data point (encapsulated in a chart event) to plot * * @param e a <code>ChartEvent</code> value */ @Override public void acceptDataPoint(ChartEvent e) { if (e.getReset()) { m_xCount = 0; m_max = 1; m_min = 0; } if (m_outputFrame != null) { boolean refresh = false; if (e.getLegendText() != null & e.getLegendText() != m_legendText) { m_legendText = e.getLegendText(); refresh = true; } if (e.getMin() != m_min || e.getMax() != m_max) { m_oldMax = m_max; m_oldMin = m_min; m_max = e.getMax(); m_min = e.getMin(); refresh = true; m_yScaleUpdate = true; } if (refresh) { m_legendPanel.repaint(); m_scalePanel.repaint(); } acceptDataPoint(e.getDataPoint()); } m_xCount++; } /** * Accept a data point to plot * * @param dataPoint a <code>double[]</code> value */ public void acceptDataPoint(double[] dataPoint) { if (m_outputFrame != null && (m_xCount % m_refreshFrequency == 0)) { double[] dp = new double[dataPoint.length + 1]; dp[dp.length - 1] = m_xCount; System.arraycopy(dataPoint, 0, dp, 0, dataPoint.length); // check for out of scale values for (double element : dataPoint) { if (element < m_min) { m_oldMin = m_min; m_min = element; m_yScaleUpdate = true; } if (element > m_max) { m_oldMax = m_max; m_max = element; m_yScaleUpdate = true; } } if (m_yScaleUpdate) { m_scalePanel.repaint(); m_yScaleUpdate = false; } synchronized (m_dataList) { m_dataList.add(m_dataList.size(), dp); // m_dataList.push(dp); m_dataList.notifyAll(); /* * if (m_dataList.size() != 0) { * System.err.println("***** "+m_dataList.size()); } */ // System.err.println(m_xCount); } } } /** * 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 for this bean */ @Override public void useDefaultVisual() { m_visual.loadIcons(BeanVisual.ICON_PATH + "StripChart.gif", BeanVisual.ICON_PATH + "StripChart_animated.gif"); } /** * Stop any processing that the bean might be doing. */ @Override public void stop() { // tell the listenee (upstream bean) to stop if (m_listenee instanceof BeanCommon) { ((BeanCommon) m_listenee).stop(); } } /** * 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_updateHandler != null); return false; } /** * Set a logger * * @param logger a <code>weka.gui.Logger</code> value */ @Override public void setLog(weka.gui.Logger logger) { } /** * 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) { if (m_listenee == null) { return true; } return false; } /** * 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 * 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; } } /** * 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_listenee = null; } /** * Describe <code>enumerateRequests</code> method here. * * @return an <code>Enumeration</code> value */ @Override public Enumeration<String> enumerateRequests() { Vector<String> newVector = new Vector<String>(0); newVector.addElement("Show chart"); return newVector.elements(); } /** * 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 chart") == 0) { showChart(); } else { throw new IllegalArgumentException(request + " not supported (StripChart)"); } } /** * Tests out the StripChart from the command line * * @param args ignored */ public static void main(String[] args) { try { final javax.swing.JFrame jf = new javax.swing.JFrame( "Weka Knowledge Flow : StripChart"); jf.getContentPane().setLayout(new BorderLayout()); final StripChart jd = new StripChart(); jf.getContentPane().add(jd, BorderLayout.CENTER); 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); jd.showChart(); Random r = new Random(1); for (int i = 0; i < 1020; i++) { double[] pos = new double[1]; pos[0] = r.nextDouble(); jd.acceptDataPoint(pos); } System.err.println("Done sending data"); } 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/StripChartBeanInfo.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * StripChartBeanInfo.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 strip chart bean * * @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a> * @version $Revision$ */ public class StripChartBeanInfo 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 property descriptors for this bean * * @return a <code>PropertyDescriptor[]</code> value */ public PropertyDescriptor[] getPropertyDescriptors() { try { PropertyDescriptor p1; PropertyDescriptor p2; PropertyDescriptor p3; p1 = new PropertyDescriptor("xLabelFreq", StripChart.class); p2 = new PropertyDescriptor("refreshFreq", StripChart.class); p3 = new PropertyDescriptor("refreshWidth", StripChart.class); PropertyDescriptor [] pds = { p1, p2, p3 }; return pds; } 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.StripChart.class, StripChartCustomizer.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/StripChartCustomizer.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * StripChartCustomizer.java * Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.beans; import java.awt.BorderLayout; import java.beans.Customizer; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import javax.swing.JPanel; import weka.gui.PropertySheetPanel; /** * GUI Customizer for the strip chart bean * * @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a> * @version $Revision$ */ public class StripChartCustomizer extends JPanel implements Customizer { /** for serialization */ private static final long serialVersionUID = 7441741530975984608L; private PropertyChangeSupport m_pcSupport = new PropertyChangeSupport(this); private PropertySheetPanel m_cvEditor = new PropertySheetPanel(); public StripChartCustomizer() { setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 5, 5, 5)); setLayout(new BorderLayout()); add(m_cvEditor, BorderLayout.CENTER); add(new javax.swing.JLabel("StripChartCustomizer"), BorderLayout.NORTH); } /** * Set the StripChart object to be customized * * @param object a StripChart */ public void setObject(Object object) { m_cvEditor.setTarget((StripChart)object); } /** * 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); } }
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/StructureProducer.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * StructureProducer.java * Copyright (C) 2011-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.beans; import weka.core.Instances; /** * Interface for something that can describe the structure of what * is encapsulated in a named event type as an empty set of * Instances (i.e. attribute information only). For example, * batchAssociationRulesEvent can be described as LHS (String), RHS (String) * and a number of metrics (Numeric); dataSetEvent, instanceEvent, * trainingSetEvent etc. are all straightforward, since they already * encapsulate instances; textEvent can be described in terms of * the title (String) and the body (String) of the text. Sometimes * it is not possible to know the structure of the encapsulated output * in advance (e.g. certain filters may not know how many attributes * will be produced until the input data arrives), in this case * any implementing class can return null to indicate this. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision$ * */ public interface StructureProducer { /** * 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. */ public Instances getStructure(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/SubstringLabeler.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * SubstringLabeler.java * Copyright (C) 2011-2013 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 javax.swing.JPanel; import weka.core.Environment; import weka.core.EnvironmentHandler; import weka.core.Instance; import weka.core.Instances; import weka.filters.unsupervised.attribute.Add; import weka.gui.Logger; /** * A bean that finds matches in string attribute values (using either substring * or regular expression matches) and labels the instance (sets the value of a * new attribute) according to the supplied label for the matching rule. The new * label attribute can be either multivalued nominal (if each match rule * specified has an explicit label associated with it) or, binary * numeric/nominal to indicate that one of the match rules has matched or not * matched. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision$ * */ @KFStep(category = "Tools", toolTipText = "Label instances according to substring matches in String attributes") public class SubstringLabeler extends JPanel implements BeanCommon, Visible, Serializable, InstanceListener, TrainingSetListener, TestSetListener, DataSourceListener, EventConstraints, EnvironmentHandler, DataSource { /** * For serialization */ private static final long serialVersionUID = 6297059699297260134L; /** Environment variables */ protected transient Environment m_env; /** Internally encoded list of match rules */ protected String m_matchDetails = ""; /** Encapsulates our match rules */ protected transient SubstringLabelerRules m_matches; /** Logging */ protected transient Logger m_log; /** Busy indicator */ protected transient boolean m_busy; /** Component talking to us */ protected Object m_listenee; /** Downstream steps listening to instance events */ protected ArrayList<InstanceListener> m_instanceListeners = new ArrayList<InstanceListener>(); /** Downstream steps listening to data set events */ protected ArrayList<DataSourceListener> m_dataListeners = new ArrayList<DataSourceListener>(); /** * Whether to make the binary match/non-match attribute a nominal (rather than * numeric) binary attribute. */ protected boolean m_nominalBinary; /** * For multi-valued labeled rules, whether or not to consume non-matching * instances or output them with missing value for the match attribute. */ protected boolean m_consumeNonMatchingInstances; /** Add filter for adding the new attribute */ protected Add m_addFilter; /** Name of the new attribute */ protected String m_attName = "Match"; /** The output structure */ // protected Instances m_outputStructure; /** Instance event to use */ protected InstanceEvent m_ie = new InstanceEvent(this); /** * Default visual filters */ protected BeanVisual m_visual = new BeanVisual("SubstringLabeler", BeanVisual.ICON_PATH + "DefaultFilter.gif", BeanVisual.ICON_PATH + "DefaultFilter_animated.gif"); /** * Constructor */ public SubstringLabeler() { useDefaultVisual(); setLayout(new BorderLayout()); add(m_visual, BorderLayout.CENTER); m_env = Environment.getSystemWide(); } /** * Help information suitable for displaying in the GUI. * * @return a description of this component */ public String globalInfo() { return "Matches substrings in String attributes using " + "either literal or regular expression matches. " + "The value of a new attribute is set to reflect" + " the status of the match. The new attribute can " + "be either binary (in which case values indicate " + "match or no match) or multi-valued nominal, " + "in which case a label must be associated with each " + "distinct matching rule. In the case of labeled matches, " + "the user can opt to have non matching instances output " + "with missing value set for the new attribute or not" + " output at all (i.e. consumed by the step)."; } /** * Set internally encoded list of match rules * * @param details the list of match rules */ public void setMatchDetails(String details) { m_matchDetails = details; } /** * Get the internally encoded list of match rules * * @return the match rules */ public String getMatchDetails() { return m_matchDetails; } /** * Set whether the new attribute created should be a nominal binary attribute * rather than a numeric binary attribute. * * @param nom true if the attribute should be a nominal binary one */ public void setNominalBinary(boolean nom) { m_nominalBinary = nom; } /** * Get whether the new attribute created should be a nominal binary attribute * rather than a numeric binary attribute. * * @return true if the attribute should be a nominal binary one */ public boolean getNominalBinary() { return m_nominalBinary; } /** * Set whether instances that do not match any of the rules should be * "consumed" rather than output with a missing value set for the new * attribute. * * @param consume true if non matching instances should be consumed by the * component. */ public void setConsumeNonMatching(boolean consume) { m_consumeNonMatchingInstances = consume; } /** * Get whether instances that do not match any of the rules should be * "consumed" rather than output with a missing value set for the new * attribute. * * @return true if non matching instances should be consumed by the component. */ public boolean getConsumeNonMatching() { return m_consumeNonMatchingInstances; } public void setMatchAttributeName(String name) { m_attName = name; } public String getMatchAttributeName() { return m_attName; } /** * Add a datasource listener * * @param dsl the datasource listener to add */ @Override public void addDataSourceListener(DataSourceListener dsl) { m_dataListeners.add(dsl); } /** * Remove a datasource listener * * @param dsl the datasource 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); } /** * Set environment variables to use */ @Override public void setEnvironment(Environment env) { m_env = env; } /** * 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 (m_listenee == null) { return false; } if (!eventName.equals("instance") && !eventName.equals("dataSet")) { return false; } if (m_listenee instanceof DataSource) { if (m_listenee instanceof EventConstraints) { EventConstraints ec = (EventConstraints) m_listenee; return ec.eventGeneratable(eventName); } } if (m_listenee instanceof TrainingSetProducer) { if (m_listenee instanceof EventConstraints) { EventConstraints ec = (EventConstraints) m_listenee; if (!eventName.equals("dataSet")) { return false; } if (!ec.eventGeneratable("trainingSet")) { return false; } } } if (m_listenee instanceof TestSetProducer) { if (m_listenee instanceof EventConstraints) { EventConstraints ec = (EventConstraints) m_listenee; if (!eventName.equals("dataSet")) { return false; } if (!ec.eventGeneratable("testSet")) { return false; } } } return true; } /** * Use the default visual representation */ @Override public void useDefaultVisual() { m_visual.loadIcons(BeanVisual.ICON_PATH + "DefaultFilter.gif", BeanVisual.ICON_PATH + "DefaultFilter_animated.gif"); m_visual.setText("SubstringLabeler"); } /** * Set a new visual representation * * @param newVisual a <code>BeanVisual</code> value */ @Override public void setVisual(BeanVisual newVisual) { m_visual = newVisual; } /** * Get the visual representation * * @return a <code>BeanVisual</code> value */ @Override public BeanVisual getVisual() { return m_visual; } /** * 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(); } /** * Stop any processing that the bean might be doing. */ @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; } /** * 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_busy; } /** * Set a logger * * @param logger a <code>weka.gui.Logger</code> value */ @Override public void setLog(Logger logger) { 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(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) { if (!eventName.equals("instance") && !eventName.equals("dataSet") && !eventName.equals("trainingSet") && !eventName.equals("testSet")) { return false; } if (m_listenee != null) { return false; } return true; } /** * Notify this object that it has been registered as a listener with a source * for receiving 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; } } /** * 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 (source == m_listenee) { m_listenee = null; } } /** * Make the output instances structure * * @param inputStructure the incoming instances structure * @throws Exception if a problem occurs */ protected void makeOutputStructure(Instances inputStructure) throws Exception { m_matches = new SubstringLabelerRules(m_matchDetails, m_attName, getConsumeNonMatching(), getNominalBinary(), inputStructure, statusMessagePrefix(), m_log, m_env); // m_matches.makeOutputStructure(); } protected transient StreamThroughput m_throughput; /** * Accept and process an instance event * * @param e the instance event to process */ @Override public void acceptInstance(InstanceEvent e) { m_busy = true; if (e.getStatus() == InstanceEvent.FORMAT_AVAILABLE) { m_throughput = new StreamThroughput(statusMessagePrefix()); Instances structure = e.getStructure(); try { makeOutputStructure(structure); } catch (Exception ex) { String msg = statusMessagePrefix() + "ERROR: unable to create output instances structure."; if (m_log != null) { m_log.statusMessage(msg); m_log.logMessage("[SubstringLabeler] " + ex.getMessage()); } stop(); ex.printStackTrace(); m_busy = false; return; } if (!e.m_formatNotificationOnly) { if (m_log != null) { m_log.statusMessage(statusMessagePrefix() + "Processing stream..."); } } m_ie.setStructure(m_matches.getOutputStructure()); m_ie.m_formatNotificationOnly = e.m_formatNotificationOnly; notifyInstanceListeners(m_ie); } else { Instance inst = e.getInstance(); Instance out = null; if (inst != null) { m_throughput.updateStart(); try { out = m_matches.makeOutputInstance(inst, false); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } m_throughput.updateEnd(m_log); } if (inst == null || out != null || e.getStatus() == InstanceEvent.BATCH_FINISHED) { // consumed // notify listeners m_ie.setInstance(out); m_ie.setStatus(e.getStatus()); notifyInstanceListeners(m_ie); } if (e.getStatus() == InstanceEvent.BATCH_FINISHED || inst == null) { // we're done m_throughput.finished(m_log); } } m_busy = false; } /** * Accept and process a data set event * * @param e the data set event to process */ @Override public void acceptDataSet(DataSetEvent e) { m_busy = true; if (m_log != null) { m_log.statusMessage(statusMessagePrefix() + "Processing batch..."); } try { makeOutputStructure(new Instances(e.getDataSet(), 0)); } catch (Exception ex) { String msg = statusMessagePrefix() + "ERROR: unable to create output instances structure."; if (m_log != null) { m_log.statusMessage(msg); m_log.logMessage("[SubstringLabeler] " + ex.getMessage()); } stop(); ex.printStackTrace(); m_busy = false; return; } Instances toProcess = e.getDataSet(); for (int i = 0; i < toProcess.numInstances(); i++) { Instance current = toProcess.instance(i); Instance result = null; try { result = m_matches.makeOutputInstance(current, true); } catch (Exception ex) { ex.printStackTrace(); } if (result != null) { // m_outputStructure.add(result); m_matches.getOutputStructure().add(result); } } if (m_log != null) { m_log.statusMessage(statusMessagePrefix() + "Finished."); } // notify listeners DataSetEvent d = new DataSetEvent(this, m_matches.getOutputStructure()); notifyDataListeners(d); m_busy = false; } /** * Accept and process a test set event * * @param e the test set event to process */ @Override public void acceptTestSet(TestSetEvent e) { Instances test = e.getTestSet(); DataSetEvent d = new DataSetEvent(this, test); acceptDataSet(d); } /** * Accept and process a training set event * * @parame e the training set event to process */ @Override public void acceptTrainingSet(TrainingSetEvent e) { Instances train = e.getTrainingSet(); DataSetEvent d = new DataSetEvent(this, train); acceptDataSet(d); } @SuppressWarnings("unchecked") private void notifyDataListeners(DataSetEvent e) { List<DataSourceListener> l; synchronized (this) { l = (List<DataSourceListener>) m_dataListeners.clone(); } if (l.size() > 0) { for (DataSourceListener ds : l) { ds.acceptDataSet(e); } } } @SuppressWarnings("unchecked") private void notifyInstanceListeners(InstanceEvent e) { List<InstanceListener> l; synchronized (this) { l = (List<InstanceListener>) m_instanceListeners.clone(); } if (l.size() > 0) { for (InstanceListener il : l) { il.acceptInstance(e); } } } protected 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/SubstringLabelerBeanInfo.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * SubstringLabelerBeanInfo.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; /** * Bean info class for the substring labeler bean * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision$ */ public class SubstringLabelerBeanInfo extends SimpleBeanInfo { /** * Returns the event set descriptors * * @return an <code>EventSetDescriptor[]</code> value */ 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 */ public BeanDescriptor getBeanDescriptor() { return new BeanDescriptor(SubstringLabeler.class, SubstringLabelerCustomizer.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/SubstringLabelerCustomizer.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * SubstringLabelerCustomizer.java * Copyright (C) 2011-2013 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.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.BorderFactory; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JCheckBox; 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.gui.JListHelper; import weka.gui.PropertySheetPanel; /** * Customizer class for the Substring labeler step * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision$ */ public class SubstringLabelerCustomizer extends JPanel implements EnvironmentHandler, BeanCustomizer, CustomizerCloseRequester { /** For serialization */ private static final long serialVersionUID = 7636584212353183751L; protected Environment m_env = Environment.getSystemWide(); protected ModifyListener m_modifyL = null; protected SubstringLabeler m_labeler; protected EnvironmentField m_matchAttNameField; protected EnvironmentField m_attListField; protected EnvironmentField m_matchField; protected EnvironmentField m_labelField; protected JCheckBox m_regexCheck = new JCheckBox(); protected JCheckBox m_ignoreCaseCheck = new JCheckBox(); protected JCheckBox m_nominalBinaryCheck = new JCheckBox(); protected JCheckBox m_consumeNonMatchingCheck = new JCheckBox(); protected JList m_list = new JList(); protected DefaultListModel m_listModel; protected JButton m_newBut = new JButton("New"); protected JButton m_deleteBut = new JButton("Delete"); protected JButton m_upBut = new JButton("Move up"); protected JButton m_downBut = new JButton("Move down"); protected Window m_parent; protected PropertySheetPanel m_tempEditor = new PropertySheetPanel(); public SubstringLabelerCustomizer() { 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(); JPanel attListP = new JPanel(); attListP.setLayout(new BorderLayout()); attListP.setBorder(BorderFactory.createTitledBorder("Apply to attributes")); m_attListField = new EnvironmentField(m_env); attListP.add(m_attListField, BorderLayout.CENTER); attListP .setToolTipText("<html>Accepts a range of indexes (e.g. '1,2,6-10')<br> " + "or a comma-separated list of named attributes</html>"); JPanel matchP = new JPanel(); matchP.setLayout(new BorderLayout()); matchP.setBorder(BorderFactory.createTitledBorder("Match")); m_matchField = new EnvironmentField(m_env); matchP.add(m_matchField, BorderLayout.CENTER); JPanel labelP = new JPanel(); labelP.setLayout(new BorderLayout()); labelP.setBorder(BorderFactory.createTitledBorder("Label")); m_labelField = new EnvironmentField(m_env); labelP.add(m_labelField, BorderLayout.CENTER); fieldHolder.add(attListP); fieldHolder.add(matchP); fieldHolder.add(labelP); controlHolder.add(fieldHolder, BorderLayout.NORTH); JPanel checkHolder = new JPanel(); checkHolder.setLayout(new GridLayout(0, 2)); JLabel attNameLab = new JLabel("Name of label attribute", SwingConstants.RIGHT); checkHolder.add(attNameLab); m_matchAttNameField = new EnvironmentField(m_env); m_matchAttNameField.setText(m_labeler.getMatchAttributeName()); checkHolder.add(m_matchAttNameField); JLabel regexLab = new JLabel("Match using a regular expression", SwingConstants.RIGHT); regexLab .setToolTipText("Use a regular expression rather than literal match"); checkHolder.add(regexLab); checkHolder.add(m_regexCheck); JLabel caseLab = new JLabel("Ignore case when matching", SwingConstants.RIGHT); checkHolder.add(caseLab); checkHolder.add(m_ignoreCaseCheck); JLabel nominalBinaryLab = new JLabel("Make binary label attribute nominal", SwingConstants.RIGHT); nominalBinaryLab .setToolTipText("<html>If the label attribute is binary (i.e. no <br>" + "explicit labels have been declared) then<br>this makes the resulting " + "attribute nominal<br>rather than numeric.</html>"); checkHolder.add(nominalBinaryLab); checkHolder.add(m_nominalBinaryCheck); m_nominalBinaryCheck.setSelected(m_labeler.getNominalBinary()); JLabel consumeNonMatchLab = new JLabel("Consume non-matching instances", SwingConstants.RIGHT); consumeNonMatchLab .setToolTipText("<html>When explicit labels have been defined, consume " + "<br>(rather than output with missing value) instances</html>"); checkHolder.add(consumeNonMatchLab); checkHolder.add(m_consumeNonMatchingCheck); m_consumeNonMatchingCheck.setSelected(m_labeler.getConsumeNonMatching()); controlHolder.add(checkHolder, BorderLayout.SOUTH); aboutAndControlHolder.add(controlHolder, BorderLayout.SOUTH); JPanel aboutP = m_tempEditor.getAboutPanel(); aboutAndControlHolder.add(aboutP, BorderLayout.NORTH); add(aboutAndControlHolder, BorderLayout.NORTH); m_list.setVisibleRowCount(5); m_deleteBut.setEnabled(false); JPanel listPanel = new JPanel(); listPanel.setLayout(new BorderLayout()); JPanel butHolder = new JPanel(); butHolder.setLayout(new GridLayout(1, 0)); butHolder.add(m_newBut); butHolder.add(m_deleteBut); butHolder.add(m_upBut); butHolder.add(m_downBut); m_upBut.setEnabled(false); m_downBut.setEnabled(false); listPanel.add(butHolder, BorderLayout.NORTH); JScrollPane js = new JScrollPane(m_list); js.setBorder(BorderFactory .createTitledBorder("Match-list list (rows applied in order)")); listPanel.add(js, BorderLayout.CENTER); add(listPanel, BorderLayout.CENTER); addButtons(); m_attListField.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent e) { Object m = m_list.getSelectedValue(); if (m != null) { ((SubstringLabelerRules.SubstringLabelerMatchRule) m) .setAttsToApplyTo(m_attListField.getText()); m_list.repaint(); } } }); m_matchField.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent e) { Object m = m_list.getSelectedValue(); if (m != null) { ((SubstringLabelerRules.SubstringLabelerMatchRule) m) .setMatch(m_matchField.getText()); m_list.repaint(); } } }); m_labelField.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent e) { Object m = m_list.getSelectedValue(); if (m != null) { ((SubstringLabelerRules.SubstringLabelerMatchRule) m) .setLabel(m_labelField.getText()); m_list.repaint(); } } }); m_list.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { if (!m_deleteBut.isEnabled()) { m_deleteBut.setEnabled(true); } Object entry = m_list.getSelectedValue(); if (entry != null) { SubstringLabelerRules.SubstringLabelerMatchRule m = (SubstringLabelerRules.SubstringLabelerMatchRule) entry; m_attListField.setText(m.getAttsToApplyTo()); m_matchField.setText(m.getMatch()); m_labelField.setText(m.getLabel()); m_regexCheck.setSelected(m.getRegex()); m_ignoreCaseCheck.setSelected(m.getIgnoreCase()); } } } }); m_newBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { SubstringLabelerRules.SubstringLabelerMatchRule m = new SubstringLabelerRules.SubstringLabelerMatchRule(); String atts = (m_attListField.getText() != null) ? m_attListField .getText() : ""; m.setAttsToApplyTo(atts); String match = (m_matchField.getText() != null) ? m_matchField .getText() : ""; m.setMatch(match); String label = (m_labelField.getText() != null) ? m_labelField .getText() : ""; m.setLabel(label); m.setRegex(m_regexCheck.isSelected()); m.setIgnoreCase(m_ignoreCaseCheck.isSelected()); m_listModel.addElement(m); if (m_listModel.size() > 1) { m_upBut.setEnabled(true); m_downBut.setEnabled(true); } m_list.setSelectedIndex(m_listModel.size() - 1); } }); m_deleteBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int selected = m_list.getSelectedIndex(); if (selected >= 0) { m_listModel.removeElementAt(selected); if (m_listModel.size() <= 1) { m_upBut.setEnabled(false); m_downBut.setEnabled(false); } } } }); m_upBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JListHelper.moveUp(m_list); } }); m_downBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JListHelper.moveDown(m_list); } }); m_regexCheck.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Object m = m_list.getSelectedValue(); if (m != null) { ((SubstringLabelerRules.SubstringLabelerMatchRule) m) .setRegex(m_regexCheck.isSelected()); m_list.repaint(); } } }); m_ignoreCaseCheck.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Object m = m_list.getSelectedValue(); if (m != null) { ((SubstringLabelerRules.SubstringLabelerMatchRule) m) .setIgnoreCase(m_ignoreCaseCheck.isSelected()); m_list.repaint(); } } }); } 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(); } }); } protected void initialize() { String mString = m_labeler.getMatchDetails(); m_listModel = new DefaultListModel(); m_list.setModel(m_listModel); if (mString != null && mString.length() > 0) { String[] parts = mString.split("@@match-rule@@"); if (parts.length > 0) { m_upBut.setEnabled(true); m_downBut.setEnabled(true); for (String mPart : parts) { SubstringLabelerRules.SubstringLabelerMatchRule m = new SubstringLabelerRules.SubstringLabelerMatchRule( mPart); m_listModel.addElement(m); } m_list.repaint(); } } } /** * Set the SubstringLabeler to edit * * @param o the SubtringLabeler to edit */ @Override public void setObject(Object o) { if (o instanceof SubstringLabeler) { m_labeler = (SubstringLabeler) o; m_tempEditor.setTarget(o); setup(); initialize(); } } /** * Set a reference to the parent window/dialog containing this panel * * @param parent the parent window */ @Override public void setParentWindow(Window parent) { m_parent = parent; } /** * Set a listener interested in knowing if the object being edited has * changed. * * @param l the interested listener */ @Override public void setModifiedListener(ModifyListener l) { m_modifyL = l; } /** * Set environment variables to use * * @param env */ @Override public void setEnvironment(Environment env) { m_env = env; } /** * Handle a closing event under an OK condition */ protected void closingOK() { StringBuffer buff = new StringBuffer(); for (int i = 0; i < m_listModel.size(); i++) { SubstringLabelerRules.SubstringLabelerMatchRule m = (SubstringLabelerRules.SubstringLabelerMatchRule) m_listModel .elementAt(i); buff.append(m.toStringInternal()); if (i < m_listModel.size() - 1) { buff.append("@@match-rule@@"); } } m_labeler.setMatchDetails(buff.toString()); m_labeler.setNominalBinary(m_nominalBinaryCheck.isSelected()); m_labeler.setConsumeNonMatching(m_consumeNonMatchingCheck.isSelected()); m_labeler.setMatchAttributeName(m_matchAttNameField.getText()); if (m_modifyL != null) { m_modifyL.setModifiedStatus(SubstringLabelerCustomizer.this, true); } } /** * Handle a closing event under a CANCEL condition */ protected 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/SubstringLabelerRules.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * Matches.java * Copyright (C) 2011-2013 University of Waikato, Hamilton, New Zealand * */ package weka.gui.beans; import java.io.Serializable; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.Vector; import java.util.regex.Pattern; 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.core.Utils; import weka.gui.Logger; /** * Manages a list of match rules for labeling strings. Also has methods for * determining the output structure with respect to a set of rules and for * constructing output instances that have been labeled according to the rules. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision$ */ public class SubstringLabelerRules implements EnvironmentHandler, Serializable { /** Separator for match rules in the internal representation */ public static final String MATCH_RULE_SEPARATOR = "@@match-rule@@"; private static final long serialVersionUID = 1392983905562573599L; /** The list of rules */ protected List<SubstringLabelerMatchRule> m_matchRules; /** True if the rules have user supplied labels */ protected boolean m_hasLabels; /** * True if non matching instances should be "consumed" - i.e no output * instance created */ protected boolean m_consumeNonMatching; /** The input structure */ protected Instances m_inputStructure; /** The output structure */ protected Instances m_outputStructure; /** The name of the new "label" attribute */ protected String m_attName = "newAtt"; /** An optional prefix for status log messages */ protected String m_statusMessagePrefix = ""; /** * If not multiple labels then should new att be a nominal rather than numeric * binary one? */ protected boolean m_nominalBinary; protected boolean m_voteLabels = true; /** Environment variables */ protected transient Environment m_env = Environment.getSystemWide(); /** * Constructor * * @param matchDetails the internally encoded match details string * @param newAttName the name of the new attribute that will be the label * @param consumeNonMatching true if non-matching instances should be consumed * @param nominalBinary true if, in the case where no user labels have been * supplied, the new attribute should be a nominal binary one rather * than numeric * @param inputStructure the incoming instances structure * @param statusMessagePrefix an optional status message prefix string for * logging * @param log the log to use (may be null) * @param env environment variables */ public SubstringLabelerRules(String matchDetails, String newAttName, boolean consumeNonMatching, boolean nominalBinary, Instances inputStructure, String statusMessagePrefix, Logger log, Environment env) throws Exception { m_matchRules = matchRulesFromInternal(matchDetails, inputStructure, statusMessagePrefix, log, env); m_inputStructure = new Instances(inputStructure, 0); m_attName = newAttName; m_statusMessagePrefix = statusMessagePrefix; m_consumeNonMatching = consumeNonMatching; m_nominalBinary = nominalBinary; m_env = env; makeOutputStructure(); } /** * Constructor. Sets consume non matching to false and nominal binary to * false. Initializes with system-wide environment variables. Initializes with * no status message prefix and no log. * * @param matchDetails the internally encoded match details string. * @param newAttName the name of the new attribute that will be the label * @param inputStructure the incoming instances structure */ public SubstringLabelerRules(String matchDetails, String newAttName, Instances inputStructure) throws Exception { this(matchDetails, newAttName, false, false, inputStructure, "", null, Environment.getSystemWide()); } /** * Set whether to consume non matching instances. If false, then they will be * passed through unaltered. * * @param n true then non-matching instances will be consumed (and only * matching, and thus labelled, instances will be output) */ public void setConsumeNonMatching(boolean n) { m_consumeNonMatching = n; } /** * Get whether to consume non matching instances. If false, then they will be * passed through unaltered. * * @return true then non-matching instances will be consumed (and only * matching, and thus labelled, instances will be output) */ public boolean getConsumeNonMatching() { return m_consumeNonMatching; } /** * Set whether to create a nominal binary attribute in the case when the user * has not supplied an explicit label to use for each rule. If no labels are * provided, then the output attribute is a binary indicator one (i.e. a rule * matched or it didn't). This option allows that binary indicator to be coded * as nominal rather than numeric * * @param n true if a binary indicator attribute should be nominal rather than * numeric */ public void setNominalBinary(boolean n) { m_nominalBinary = n; } /** * Get whether to create a nominal binary attribute in the case when the user * has not supplied an explicit label to use for each rule. If no labels are * provided, then the output attribute is a binary indicator one (i.e. a rule * matched or it didn't). This option allows that binary indicator to be coded * as nominal rather than numeric * * @return true if a binary indicator attribute should be nominal rather than * numeric */ public boolean getNominalBinary() { return m_nominalBinary; } /** * Get the output structure * * @return the structure of the output instances */ public Instances getOutputStructure() { return m_outputStructure; } /** * Get the input structure * * @return the structure of the input instances */ public Instances getInputStructure() { return m_inputStructure; } /** * Set the name to use for the new attribute that is added * * @param newName the name to use */ public void setNewAttributeName(String newName) { m_attName = newName; } /** * Get the name to use for the new attribute that is added * * @return the name to use */ public String getNewAttributeName() { return m_attName; } @Override public void setEnvironment(Environment env) { m_env = env; } /** * Get a list of match rules from an internally encoded match specification * * @param matchDetails the internally encoded specification of the match rules * @param inputStructure the input instances structure * @param statusMessagePrefix an optional status message prefix for logging * @param log the log to use * @param env environment variables * @return a list of match rules */ public static List<SubstringLabelerMatchRule> matchRulesFromInternal( String matchDetails, Instances inputStructure, String statusMessagePrefix, Logger log, Environment env) { List<SubstringLabelerMatchRule> matchRules = new ArrayList<SubstringLabelerMatchRule>(); String[] matchParts = matchDetails.split(MATCH_RULE_SEPARATOR); for (String p : matchParts) { SubstringLabelerMatchRule m = new SubstringLabelerMatchRule(p.trim()); m.m_statusMessagePrefix = statusMessagePrefix == null ? "" : statusMessagePrefix; m.m_logger = log; m.init(env, inputStructure); matchRules.add(m); } return matchRules; } /** * Make the output instances structure * * @throws Exception if a problem occurs */ protected void makeOutputStructure() throws Exception { // m_matchRules = new ArrayList<Match>(); if (m_matchRules.size() > 0) { int labelCount = 0; // StringBuffer labelList = new StringBuffer(); HashSet<String> uniqueLabels = new HashSet<String>(); Vector<String> labelVec = new Vector<String>(); for (SubstringLabelerMatchRule m : m_matchRules) { if (m.getLabel() != null && m.getLabel().length() > 0) { if (!uniqueLabels.contains(m.getLabel())) { /* * if (labelCount > 0) { labelList.append(","); } */ // labelList.append(m.getLabel()); uniqueLabels.add(m.getLabel()); labelVec.addElement(m.getLabel()); } labelCount++; } } if (labelCount > 0) { if (labelCount == m_matchRules.size()) { m_hasLabels = true; } else { throw new Exception("Can't have only some rules with a label!"); } } m_outputStructure = (Instances) (new SerializedObject(m_inputStructure).getObject()); Attribute newAtt = null; if (m_hasLabels) { newAtt = new Attribute(m_attName, labelVec); } else if (m_nominalBinary) { labelVec.addElement("0"); labelVec.addElement("1"); newAtt = new Attribute(m_attName, labelVec); } else { newAtt = new Attribute(m_attName); } m_outputStructure.insertAttributeAt(newAtt, m_outputStructure.numAttributes()); /* * // make the output structure m_addFilter = new Add(); * m_addFilter.setAttributeName(m_attName); if (m_hasLabels) { * m_addFilter.setNominalLabels(labelList.toString()); } else if * (getNominalBinary()) { m_addFilter.setNominalLabels("0,1"); } * m_addFilter.setInputFormat(inputStructure); m_outputStructure = * Filter.useFilter(inputStructure, m_addFilter); */ return; } m_outputStructure = new Instances(m_inputStructure); } /** * Process and input instance and return an output instance * * @param inputI the incoming instance * @param batch whether this is being processed as part of a batch of * instances * * @throws Exception if the output structure has not yet been determined * @return the output instance */ public Instance makeOutputInstance(Instance inputI, boolean batch) throws Exception { if (m_outputStructure == null) { throw new Exception("OutputStructure has not been determined!"); } int newAttIndex = m_outputStructure.numAttributes() - 1; Instance result = inputI; if (m_matchRules.size() > 0) { String label = null; int[] labelVotes = new int[m_matchRules.size()]; int index = 0; for (SubstringLabelerMatchRule m : m_matchRules) { label = m.apply(inputI); if (label != null) { if (m_voteLabels) { labelVotes[index]++; } else { break; } } index++; } if (m_voteLabels && Utils.sum(labelVotes) > 0) { int maxIndex = Utils.maxIndex(labelVotes); label = m_matchRules.get(maxIndex).getLabel(); } double[] vals = new double[m_outputStructure.numAttributes()]; for (int i = 0; i < inputI.numAttributes(); i++) { if (!inputI.attribute(i).isString()) { vals[i] = inputI.value(i); } else { if (!batch) { vals[i] = 0; String v = inputI.stringValue(i); m_outputStructure.attribute(i).setStringValue(v); } else { String v = inputI.stringValue(i); vals[i] = m_outputStructure.attribute(i).addStringValue(v); } } } if (label != null) { if (m_hasLabels) { vals[newAttIndex] = m_outputStructure.attribute(m_attName).indexOfValue(label); } else { vals[newAttIndex] = 1; } } else { // non match if (m_hasLabels) { if (!getConsumeNonMatching()) { vals[newAttIndex] = Utils.missingValue(); } else { return null; } } else { vals[newAttIndex] = 0; } } result = new DenseInstance(1.0, vals); result.setDataset(m_outputStructure); } return result; } /** * Inner class encapsulating the logic for matching * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) */ public static class SubstringLabelerMatchRule implements Serializable { /** Separator for parts of the match specification */ public static final String MATCH_PART_SEPARATOR = "@@MR@@"; private static final long serialVersionUID = 6518104085439241523L; /** The substring literal/regex to use for matching */ protected String m_match = ""; /** The label (if any) for this rule */ protected String m_label = ""; /** True if a regular expression match is to be used */ protected boolean m_regex; /** True if case should be ignored when matching */ protected boolean m_ignoreCase; /** Precompiled regex pattern */ protected Pattern m_regexPattern; /** The attributes to apply the match-replace rule to */ protected String m_attsToApplyTo = ""; /** Resolved match string */ protected String m_matchS; /** Resolved label string */ protected String m_labelS; /** Attributes to apply to */ protected int[] m_selectedAtts; /** Status message prefix */ protected String m_statusMessagePrefix; /** Logger to use */ protected Logger m_logger; /** * Constructor */ public SubstringLabelerMatchRule() { } /** * Constructor * * @param setup an internally encoded representation of all the match * information for this rule */ public SubstringLabelerMatchRule(String setup) { parseFromInternal(setup); } /** * Constructor * * @param match the match string * @param regex true if this is a regular expression match * @param ignoreCase true if case is to be ignored * @param selectedAtts the attributes to apply the rule to */ public SubstringLabelerMatchRule(String match, boolean regex, boolean ignoreCase, String selectedAtts) { m_match = match; m_regex = regex; m_ignoreCase = ignoreCase; m_attsToApplyTo = selectedAtts; } /** * Parses from the internal representation * * @param setup */ protected void parseFromInternal(String setup) { String[] parts = setup.split(MATCH_PART_SEPARATOR); if (parts.length < 4 || parts.length > 5) { throw new IllegalArgumentException("Malformed match definition: " + setup); } m_attsToApplyTo = parts[0].trim(); m_regex = parts[1].trim().toLowerCase().equals("t"); m_ignoreCase = parts[2].trim().toLowerCase().equals("t"); m_match = parts[3].trim(); if (m_match == null || m_match.length() == 0) { throw new IllegalArgumentException("Must provide something to match!"); } if (parts.length == 5) { m_label = parts[4].trim(); } } /** * Set the string/regex to use for matching * * @param match the match string */ public void setMatch(String match) { m_match = match; } /** * Get the string/regex to use for matching * * @return the match string */ public String getMatch() { return m_match; } /** * Set the label to assign if this rule matches, or empty string if binary * flag attribute is being created. * * @param label the label string or empty string */ public void setLabel(String label) { m_label = label; } /** * Get the label to assign if this rule matches, or empty string if binary * flag attribute is being created. * * @return the label string or empty string */ public String getLabel() { return m_label; } /** * Set whether this is a regular expression match or not * * @param regex true if this is a regular expression match */ public void setRegex(boolean regex) { m_regex = regex; } /** * Get whether this is a regular expression match or not * * @return true if this is a regular expression match */ public boolean getRegex() { return m_regex; } /** * Set whether to ignore case when matching * * @param ignore true if case is to be ignored */ public void setIgnoreCase(boolean ignore) { m_ignoreCase = ignore; } /** * Get whether to ignore case when matching * * @return true if case is to be ignored */ public boolean getIgnoreCase() { return m_ignoreCase; } /** * Set the attributes to apply the rule to * * @param a the attributes to apply the rule to. */ public void setAttsToApplyTo(String a) { m_attsToApplyTo = a; } /** * Get the attributes to apply the rule to * * @return the attributes to apply the rule to. */ public String getAttsToApplyTo() { return m_attsToApplyTo; } /** * Initialize this match rule by substituting any environment variables in * the attributes, match and label strings. Sets up the attribute indices to * apply to and validates that the selected attributes are all String * attributes * * @param env the environment variables * @param structure the structure of the incoming instances */ public void init(Environment env, Instances structure) { m_matchS = m_match; m_labelS = m_label; String attsToApplyToS = m_attsToApplyTo; try { m_matchS = env.substitute(m_matchS); m_labelS = env.substitute(m_labelS); attsToApplyToS = env.substitute(attsToApplyToS); } catch (Exception ex) { } if (m_regex) { String match = m_matchS; if (m_ignoreCase) { match = match.toLowerCase(); } // precompile regular expression for speed m_regexPattern = Pattern.compile(match); } // Try a range first for the attributes String tempRangeS = attsToApplyToS; tempRangeS = tempRangeS.replace("/first", "first").replace("/last", "last"); Range tempR = new Range(); tempR.setRanges(attsToApplyToS); try { tempR.setUpper(structure.numAttributes() - 1); m_selectedAtts = tempR.getSelection(); } catch (IllegalArgumentException ex) { // probably contains attribute names then m_selectedAtts = null; } if (m_selectedAtts == null) { // parse the comma separated list of attribute names Set<Integer> indexes = new HashSet<Integer>(); String[] attParts = m_attsToApplyTo.split(","); for (String att : attParts) { att = att.trim(); if (att.toLowerCase().equals("/first")) { indexes.add(0); } else if (att.toLowerCase().equals("/last")) { indexes.add((structure.numAttributes() - 1)); } else { // try and find attribute if (structure.attribute(att) != null) { indexes.add(new Integer(structure.attribute(att).index())); } else { if (m_logger != null) { String msg = m_statusMessagePrefix + "Can't find attribute '" + att + "in the incoming instances - ignoring"; m_logger.logMessage(msg); } } } } m_selectedAtts = new int[indexes.size()]; int c = 0; for (Integer i : indexes) { m_selectedAtts[c++] = i.intValue(); } } // validate the types of the selected atts Set<Integer> indexes = new HashSet<Integer>(); for (int m_selectedAtt : m_selectedAtts) { if (structure.attribute(m_selectedAtt).isString()) { indexes.add(m_selectedAtt); } else { if (m_logger != null) { String msg = m_statusMessagePrefix + "Attribute '" + structure.attribute(m_selectedAtt).name() + "is not a string attribute - " + "ignoring"; m_logger.logMessage(msg); } } } // final array m_selectedAtts = new int[indexes.size()]; int c = 0; for (Integer i : indexes) { m_selectedAtts[c++] = i.intValue(); } } /** * Apply this rule to the supplied instance * * @param inst the instance to apply to * * @return the label (or empty string) if this rule matches (empty string is * used to indicate a match in the case that a binary flag attribute * is being created), or null if the rule doesn't match. */ public String apply(Instance inst) { for (int i = 0; i < m_selectedAtts.length; i++) { if (!inst.isMissing(m_selectedAtts[i])) { String value = inst.stringValue(m_selectedAtts[i]); String result = apply(value); if (result != null) { // first match is good enough return result; } } } return null; } /** * Apply this rule to the supplied string * * @param source the string to apply to * @return the label (or empty string) if this rule matches (empty string is * used to indicate a match in the case that a binary flag attribute * is being created), or null if the rule doesn't match. */ protected String apply(String source) { String result = source; String match = m_matchS; boolean ruleMatches = false; if (m_ignoreCase) { result = result.toLowerCase(); match = match.toLowerCase(); } if (result != null && result.length() > 0) { if (m_regex) { if (m_regexPattern.matcher(result).matches()) { // if (result.matches(match)) { ruleMatches = true; } } else { ruleMatches = (result.indexOf(match) >= 0); } } return (ruleMatches) ? m_label : null; } /** * Return a textual description of this match rule * * @return a textual description of this match rule */ @Override public String toString() { // return a nicely formatted string for display // that shows all the details StringBuffer buff = new StringBuffer(); buff.append((m_regex) ? "Regex: " : "Substring: "); buff.append(m_match).append(" "); buff.append((m_ignoreCase) ? "[ignore case]" : "").append(" "); if (m_label != null && m_label.length() > 0) { buff.append("Label: ").append(m_label).append(" "); } buff.append("[Atts: " + m_attsToApplyTo + "]"); return buff.toString(); } /** * Get the internal representation of this rule * * @return a string formatted in the internal representation */ public String toStringInternal() { // return a string in internal format that is // easy to parse all the data out of StringBuffer buff = new StringBuffer(); buff.append(m_attsToApplyTo).append(MATCH_PART_SEPARATOR); buff.append((m_regex) ? "t" : "f").append(MATCH_PART_SEPARATOR); buff.append((m_ignoreCase) ? "t" : "f").append(MATCH_PART_SEPARATOR); buff.append(m_match).append(MATCH_PART_SEPARATOR); buff.append(m_label); return buff.toString(); } } }
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/SubstringReplacer.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * SubstringReplacer.java * Copyright (C) 2011-2013 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 javax.swing.JPanel; import weka.core.Environment; import weka.core.EnvironmentHandler; import weka.core.Instance; import weka.core.Instances; import weka.gui.Logger; /** * A bean that can replace substrings in the values of string attributes. * Multiple match and replace "rules" can be specified - these get applied in * the order that they are defined. Each rule can be applied to one or more * user-specified input String attributes. Attributes can be specified using * either a range list (e.g 1,2-10,last) or by a comma separated list of * attribute names (where "/first" and "/last" are special strings indicating * the first and last attribute respectively). * * Matching can be by string literal or by regular expression. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision$ */ @KFStep(category = "Tools", toolTipText = "Replace substrings in String attributes") public class SubstringReplacer extends JPanel implements BeanCommon, Visible, Serializable, InstanceListener, EventConstraints, EnvironmentHandler, DataSource { /** For serialization */ private static final long serialVersionUID = 5636877747903965818L; /** Environment variables */ protected transient Environment m_env; /** Internally encoded list of match-replace rules */ protected String m_matchReplaceDetails = ""; /** Temporary list of match-replace rules */ // protected transient List<SubstringReplacerMatchRule> m_mr; protected transient SubstringReplacerRules m_mr; /** Logging */ protected transient Logger m_log; /** Busy indicator */ protected transient boolean m_busy; /** Component sending us instances */ protected Object m_listenee; /** Downstream steps listening to instance events */ protected ArrayList<InstanceListener> m_instanceListeners = new ArrayList<InstanceListener>(); /** Instance event to use */ protected InstanceEvent m_ie = new InstanceEvent(this); /** * Default visual filters */ protected BeanVisual m_visual = new BeanVisual("SubstringReplacer", BeanVisual.ICON_PATH + "DefaultFilter.gif", BeanVisual.ICON_PATH + "DefaultFilter_animated.gif"); /** * Constructs a new SubstringReplacer */ public SubstringReplacer() { useDefaultVisual(); setLayout(new BorderLayout()); add(m_visual, BorderLayout.CENTER); m_env = Environment.getSystemWide(); } /** * About information * * @return about information */ public String globalInfo() { return "Replaces substrings in String attribute values " + "using either literal match and replace or " + "regular expression matching. The attributes" + "to apply the match and replace rules to " + "can be selected via a range string (e.g " + "1-5,6,last) or by a comma separated list " + "of attribute names (/first and /last can be" + " used to indicate the first and last attribute " + "respectively)"; } /** * Set internally encoded list of match-replace rules * * @param details the list of match-replace rules */ public void setMatchReplaceDetails(String details) { m_matchReplaceDetails = details; } /** * Get the internally encoded list of match-replace rules * * @return the match-replace rules */ public String getMatchReplaceDetails() { return m_matchReplaceDetails; } /** * 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 (m_listenee == null) { return false; } if (!eventName.equals("instance")) { return false; } if (m_listenee instanceof EventConstraints) { if (!((EventConstraints) m_listenee).eventGeneratable(eventName)) { return false; } } return true; } protected transient StreamThroughput m_throughput; /** * Accept and process an instance event * * @param e an <code>InstanceEvent</code> value */ @Override public synchronized void acceptInstance(InstanceEvent e) { m_busy = true; if (e.getStatus() == InstanceEvent.FORMAT_AVAILABLE) { m_throughput = new StreamThroughput(statusMessagePrefix()); Instances structure = e.getStructure(); m_mr = new SubstringReplacerRules(m_matchReplaceDetails, structure, statusMessagePrefix(), m_log, m_env); // m_mr = new ArrayList<SubstringReplacerMatchRule>(); // if (m_matchReplaceDetails != null && m_matchReplaceDetails.length() > // 0) { // // String[] mrParts = m_matchReplaceDetails.split("@@match-replace@@"); // for (String p : mrParts) { // SubstringReplacerMatchRule mr = new SubstringReplacerMatchRule( // p.trim()); // mr.m_statusMessagePrefix = statusMessagePrefix(); // mr.m_logger = m_log; // mr.init(m_env, structure); // m_mr.add(mr); // } // } if (!e.m_formatNotificationOnly) { if (m_log != null) { m_log.statusMessage(statusMessagePrefix() + "Processing stream..."); } } // pass structure on downstream m_ie.setStructure(structure); m_ie.m_formatNotificationOnly = e.m_formatNotificationOnly; notifyInstanceListeners(m_ie); } else { Instance inst = e.getInstance(); // System.err.println("got : " + inst.toString()); if (inst != null) { m_throughput.updateStart(); inst = m_mr.makeOutputInstance(inst); // m_mr.applyRules(inst); // for (SubstringReplacerMatchRule mr : m_mr) { // mr.apply(inst); // } m_throughput.updateEnd(m_log); } // notify listeners m_ie.setInstance(inst); m_ie.setStatus(e.getStatus()); notifyInstanceListeners(m_ie); if (e.getStatus() == InstanceEvent.BATCH_FINISHED || inst == null) { // we're done m_throughput.finished(m_log); } } m_busy = false; } /** * Use the default visual representation */ @Override public void useDefaultVisual() { m_visual.loadIcons(BeanVisual.ICON_PATH + "DefaultFilter.gif", BeanVisual.ICON_PATH + "DefaultFilter_animated.gif"); m_visual.setText("SubstringReplacer"); } /** * Set a new visual representation * * @param newVisual a <code>BeanVisual</code> value */ @Override public void setVisual(BeanVisual newVisual) { m_visual = newVisual; } /** * Get the visual representation * * @return a <code>BeanVisual</code> value */ @Override public BeanVisual getVisual() { return m_visual; } /** * 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(); } /** * Stop any processing that the bean might be doing. */ @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; } /** * 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_busy; } /** * Set a logger * * @param logger a <code>weka.gui.Logger</code> value */ @Override public void setLog(Logger logger) { 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(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) { if (!eventName.equals("instance")) { return false; } if (m_listenee != null) { 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(String eventName, Object source) { if (connectionAllowed(eventName)) { m_listenee = 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) { if (source == m_listenee) { m_listenee = null; } } /** * Set environment variables to use */ @Override public void setEnvironment(Environment env) { m_env = env; } protected String statusMessagePrefix() { return getCustomName() + "$" + hashCode() + "|"; } @SuppressWarnings("unchecked") private void notifyInstanceListeners(InstanceEvent e) { List<InstanceListener> l; synchronized (this) { l = (List<InstanceListener>) m_instanceListeners.clone(); } if (l.size() > 0) { for (InstanceListener il : l) { il.acceptInstance(e); } } } /** * Add an instance listener * * @param tsl an <code>InstanceListener</code> value */ @Override public synchronized void addInstanceListener(InstanceListener tsl) { m_instanceListeners.add(tsl); } /** * Remove an instance listener * * @param tsl an <code>InstanceListener</code> value */ @Override public synchronized void removeInstanceListener(InstanceListener tsl) { m_instanceListeners.remove(tsl); } /** * Add a data source listener * * @param dsl a <code>DataSourceListener</code> value */ @Override public void addDataSourceListener(DataSourceListener dsl) { } /** * Remove a data source listener * * @param dsl a <code>DataSourceListener</code> value */ @Override public void removeDataSourceListener(DataSourceListener 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/SubstringReplacerBeanInfo.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * SubstringLabelerBeanInfo.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; /** * Bean info class for the substring replacer * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision$ */ public class SubstringReplacerBeanInfo extends SimpleBeanInfo { /** * Returns the event set descriptors * * @return an <code>EventSetDescriptor[]</code> value */ public EventSetDescriptor [] getEventSetDescriptors() { try { EventSetDescriptor [] esds = { new EventSetDescriptor(DataSource.class, "instance", InstanceListener.class, "acceptInstance") }; 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(SubstringReplacer.class, SubstringReplacerCustomizer.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/SubstringReplacerCustomizer.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * SubstringReplacerCustomizer.java * Copyright (C) 2011 Pentaho Corporation */ 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.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.BorderFactory; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JCheckBox; 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.gui.JListHelper; import weka.gui.PropertySheetPanel; /** * Customizer for the SubstringReplacer * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision$ */ public class SubstringReplacerCustomizer extends JPanel implements EnvironmentHandler, BeanCustomizer, CustomizerCloseRequester { /** * For serialization */ private static final long serialVersionUID = -1245155414691393809L; protected Environment m_env = Environment.getSystemWide(); protected ModifyListener m_modifyL = null; protected SubstringReplacer m_replacer; protected EnvironmentField m_attListField; protected EnvironmentField m_matchField; protected EnvironmentField m_replaceField; protected JCheckBox m_regexCheck = new JCheckBox(); protected JCheckBox m_ignoreCaseCheck = new JCheckBox(); protected JList m_list = new JList(); protected DefaultListModel m_listModel; protected JButton m_newBut = new JButton("New"); protected JButton m_deleteBut = new JButton("Delete"); protected JButton m_upBut = new JButton("Move up"); protected JButton m_downBut = new JButton("Move down"); protected Window m_parent; protected PropertySheetPanel m_tempEditor = new PropertySheetPanel(); /** * Constructor */ public SubstringReplacerCustomizer() { 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(); JPanel attListP = new JPanel(); attListP.setLayout(new BorderLayout()); attListP.setBorder(BorderFactory.createTitledBorder("Apply to attributes")); m_attListField = new EnvironmentField(m_env); attListP.add(m_attListField, BorderLayout.CENTER); attListP .setToolTipText("<html>Accepts a range of indexes (e.g. '1,2,6-10')<br> " + "or a comma-separated list of named attributes</html>"); JPanel matchP = new JPanel(); matchP.setLayout(new BorderLayout()); matchP.setBorder(BorderFactory.createTitledBorder("Match")); m_matchField = new EnvironmentField(m_env); matchP.add(m_matchField, BorderLayout.CENTER); JPanel replaceP = new JPanel(); replaceP.setLayout(new BorderLayout()); replaceP.setBorder(BorderFactory.createTitledBorder("Replace")); m_replaceField = new EnvironmentField(m_env); replaceP.add(m_replaceField, BorderLayout.CENTER); fieldHolder.add(attListP); fieldHolder.add(matchP); fieldHolder.add(replaceP); controlHolder.add(fieldHolder, BorderLayout.NORTH); JPanel checkHolder = new JPanel(); checkHolder.setLayout(new GridLayout(0, 2)); JLabel regexLab = new JLabel("Match using a regular expression", SwingConstants.RIGHT); regexLab .setToolTipText("Use a regular expression rather than literal match"); checkHolder.add(regexLab); checkHolder.add(m_regexCheck); JLabel caseLab = new JLabel("Ignore case when matching", SwingConstants.RIGHT); checkHolder.add(caseLab); checkHolder.add(m_ignoreCaseCheck); controlHolder.add(checkHolder, BorderLayout.SOUTH); aboutAndControlHolder.add(controlHolder, BorderLayout.SOUTH); JPanel aboutP = m_tempEditor.getAboutPanel(); aboutAndControlHolder.add(aboutP, BorderLayout.NORTH); add(aboutAndControlHolder, BorderLayout.NORTH); m_list.setVisibleRowCount(5); m_deleteBut.setEnabled(false); JPanel listPanel = new JPanel(); listPanel.setLayout(new BorderLayout()); JPanel butHolder = new JPanel(); butHolder.setLayout(new GridLayout(1, 0)); butHolder.add(m_newBut); butHolder.add(m_deleteBut); butHolder.add(m_upBut); butHolder.add(m_downBut); m_upBut.setEnabled(false); m_downBut.setEnabled(false); listPanel.add(butHolder, BorderLayout.NORTH); JScrollPane js = new JScrollPane(m_list); js.setBorder(BorderFactory .createTitledBorder("Match-replace list (rows applied in order)")); listPanel.add(js, BorderLayout.CENTER); add(listPanel, BorderLayout.CENTER); addButtons(); m_attListField.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent e) { Object mr = m_list.getSelectedValue(); if (mr != null) { ((SubstringReplacerRules.SubstringReplacerMatchRule) mr) .setAttsToApplyTo(m_attListField.getText()); m_list.repaint(); } } }); m_matchField.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent e) { Object mr = m_list.getSelectedValue(); if (mr != null) { ((SubstringReplacerRules.SubstringReplacerMatchRule) mr) .setMatch(m_matchField.getText()); m_list.repaint(); } } }); m_replaceField.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent e) { Object mr = m_list.getSelectedValue(); if (mr != null) { ((SubstringReplacerRules.SubstringReplacerMatchRule) mr) .setReplace(m_replaceField.getText()); m_list.repaint(); } } }); m_list.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { if (!m_deleteBut.isEnabled()) { m_deleteBut.setEnabled(true); } Object entry = m_list.getSelectedValue(); if (entry != null) { SubstringReplacerRules.SubstringReplacerMatchRule mr = (SubstringReplacerRules.SubstringReplacerMatchRule) entry; m_attListField.setText(mr.getAttsToApplyTo()); m_matchField.setText(mr.getMatch()); m_replaceField.setText(mr.getReplace()); m_regexCheck.setSelected(mr.getRegex()); m_ignoreCaseCheck.setSelected(mr.getIgnoreCase()); } } } }); m_newBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { SubstringReplacerRules.SubstringReplacerMatchRule mr = new SubstringReplacerRules.SubstringReplacerMatchRule(); String atts = (m_attListField.getText() != null) ? m_attListField .getText() : ""; mr.setAttsToApplyTo(atts); String match = (m_matchField.getText() != null) ? m_matchField .getText() : ""; mr.setMatch(match); String replace = (m_replaceField.getText() != null) ? m_replaceField .getText() : ""; mr.setReplace(replace); mr.setRegex(m_regexCheck.isSelected()); mr.setIgnoreCase(m_ignoreCaseCheck.isSelected()); m_listModel.addElement(mr); if (m_listModel.size() > 1) { m_upBut.setEnabled(true); m_downBut.setEnabled(true); } m_list.setSelectedIndex(m_listModel.size() - 1); } }); m_deleteBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int selected = m_list.getSelectedIndex(); if (selected >= 0) { m_listModel.removeElementAt(selected); if (m_listModel.size() <= 1) { m_upBut.setEnabled(false); m_downBut.setEnabled(false); } } } }); m_upBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JListHelper.moveUp(m_list); } }); m_downBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JListHelper.moveDown(m_list); } }); m_regexCheck.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Object mr = m_list.getSelectedValue(); if (mr != null) { ((SubstringReplacerRules.SubstringReplacerMatchRule) mr) .setRegex(m_regexCheck.isSelected()); m_list.repaint(); } } }); m_ignoreCaseCheck.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Object mr = m_list.getSelectedValue(); if (mr != null) { ((SubstringReplacerRules.SubstringReplacerMatchRule) mr) .setIgnoreCase(m_ignoreCaseCheck.isSelected()); m_list.repaint(); } } }); } 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(); } }); } /** * Set environment variables to use * * @param env */ @Override public void setEnvironment(Environment env) { m_env = env; } protected void initialize() { String mrString = m_replacer.getMatchReplaceDetails(); m_listModel = new DefaultListModel(); m_list.setModel(m_listModel); if (mrString != null && mrString.length() > 0) { String[] parts = mrString.split("@@match-replace@@"); if (parts.length > 0) { m_upBut.setEnabled(true); m_downBut.setEnabled(true); for (String mrPart : parts) { SubstringReplacerRules.SubstringReplacerMatchRule mr = new SubstringReplacerRules.SubstringReplacerMatchRule( mrPart); m_listModel.addElement(mr); } m_list.repaint(); } } } /** * Set the SubstringReplacer to edit * * @param o the SubtringReplacer to edit */ @Override public void setObject(Object o) { if (o instanceof SubstringReplacer) { m_replacer = (SubstringReplacer) o; m_tempEditor.setTarget(o); setup(); initialize(); } } /** * Set a listener interested in knowing if the object being edited has * changed. * * @param l the interested listener */ @Override public void setModifiedListener(ModifyListener l) { m_modifyL = l; } /** * Handle a closing event under an OK condition */ protected void closingOK() { StringBuffer buff = new StringBuffer(); for (int i = 0; i < m_listModel.size(); i++) { SubstringReplacerRules.SubstringReplacerMatchRule mr = (SubstringReplacerRules.SubstringReplacerMatchRule) m_listModel .elementAt(i); buff.append(mr.toStringInternal()); if (i < m_listModel.size() - 1) { buff.append("@@match-replace@@"); } } m_replacer.setMatchReplaceDetails(buff.toString()); if (m_modifyL != null) { m_modifyL.setModifiedStatus(SubstringReplacerCustomizer.this, true); } } /** * Handle a closing event under a CANCEL condition */ protected void closingCancel() { // nothing to do } /** * Set a reference to the parent window/dialog containing this panel * * @param parent the parent window */ @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/SubstringReplacerRules.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * SubstringReplacerRules.java * Copyright (C) 2011-2013 University of Waikato, Hamilton, New Zealand * */ package weka.gui.beans; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.regex.Pattern; import java.io.Serializable; 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.gui.Logger; /** * Manages a list of match and replace rules for replacing values in string * attributes * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision$ */ public class SubstringReplacerRules implements EnvironmentHandler, Serializable { private static final long serialVersionUID = -7151320452496749698L; /** Environment variables */ protected transient Environment m_env = Environment.getSystemWide(); protected List<SubstringReplacerMatchRule> m_matchRules; /** The input structure */ protected Instances m_inputStructure; /** The output structure */ protected Instances m_outputStructure; /** An optional prefix for status log messages */ protected String m_statusMessagePrefix = ""; @Override public void setEnvironment(Environment env) { m_env = env; } /** * Constructor * * @param matchDetails the internally encoded match details string * @param inputStructure the incoming instances structure * @param statusMessagePrefix an optional status message prefix string for * logging * @param log the log to use (may be null) * @param env environment variables */ public SubstringReplacerRules(String matchDetails, Instances inputStructure, String statusMessagePrefix, Logger log, Environment env) { m_matchRules = matchRulesFromInternal(matchDetails, inputStructure, statusMessagePrefix, log, env); m_inputStructure = new Instances(inputStructure); m_outputStructure = new Instances(inputStructure).stringFreeStructure(); m_env = env; m_statusMessagePrefix = statusMessagePrefix; } /** * Constructor. Initializes with system-wide environment variables and uses no * status message and no log. * * @param matchDetails the internally encoded match details string * @param inputStructure the incoming instances structure */ public SubstringReplacerRules(String matchDetails, Instances inputStructure) { this(matchDetails, inputStructure, "", null, Environment.getSystemWide()); } /** * Get a list of match rules from an internally encoded match specification * * @param matchReplaceDetails the internally encoded specification of the * match rules * @param inputStructure the input instances structure * @param statusMessagePrefix an optional status message prefix for logging * @param log the log to use * @param env environment variables * @return a list of match rules */ public static List<SubstringReplacerMatchRule> matchRulesFromInternal( String matchReplaceDetails, Instances inputStructure, String statusMessagePrefix, Logger log, Environment env) { List<SubstringReplacerMatchRule> matchRules = new ArrayList<SubstringReplacerMatchRule>(); String[] mrParts = matchReplaceDetails.split("@@match-replace@@"); for (String p : mrParts) { SubstringReplacerMatchRule mr = new SubstringReplacerMatchRule(p.trim()); mr.m_statusMessagePrefix = statusMessagePrefix; mr.m_logger = log; mr.init(env, inputStructure); matchRules.add(mr); } return matchRules; } public void applyRules(Instance inst) { for (SubstringReplacerMatchRule mr : m_matchRules) { mr.apply(inst); } } /** * Make an output instance given an input one * * @param inputI the input instance to process * @return the output instance with substrings replaced */ public Instance makeOutputInstance(Instance inputI) { double[] vals = new double[m_outputStructure.numAttributes()]; String[] stringVals = new String[m_outputStructure.numAttributes()]; for (int i = 0; i < inputI.numAttributes(); i++) { if (inputI.attribute(i).isString() && !inputI.isMissing(i)) { stringVals[i] = inputI.stringValue(i); } else { vals[i] = inputI.value(i); } } for (SubstringReplacerMatchRule mr : m_matchRules) { mr.apply(stringVals); } for (int i = 0; i < m_outputStructure.numAttributes(); i++) { if (m_outputStructure.attribute(i).isString() && stringVals[i] != null) { m_outputStructure.attribute(i).setStringValue(stringVals[i]); } } Instance result = new DenseInstance(inputI.weight(), vals); result.setDataset(m_outputStructure); return result; } /** * Inner class encapsulating the logic for matching and replacing. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) */ public static class SubstringReplacerMatchRule implements Serializable { private static final long serialVersionUID = 5792838913737819728L; /** The substring literal/regex to use for matching */ protected String m_match = ""; /** The string to replace with */ protected String m_replace = ""; /** True if a regular expression match is to be used */ protected boolean m_regex; /** Precompiled regex */ protected Pattern m_regexPattern; /** True if case should be ignored when matching */ protected boolean m_ignoreCase; /** The attributes to apply the match-replace rule to */ protected String m_attsToApplyTo = ""; protected String m_matchS; protected String m_replaceS; protected int[] m_selectedAtts; protected String m_statusMessagePrefix; protected Logger m_logger; /** * Constructor */ public SubstringReplacerMatchRule() { } /** * Constructor * * @param setup an internally encoded representation of all the match and * replace information for this rule */ public SubstringReplacerMatchRule(String setup) { parseFromInternal(setup); } /** * Constructor * * @param match the match string * @param replace the replace string * @param regex true if this is a regular expression match * @param ignoreCase true if case is to be ignored * @param selectedAtts the attributes to apply the rule to */ public SubstringReplacerMatchRule(String match, String replace, boolean regex, boolean ignoreCase, String selectedAtts) { m_match = match; m_replace = replace; m_regex = regex; m_ignoreCase = ignoreCase; m_attsToApplyTo = selectedAtts; } protected void parseFromInternal(String setup) { String[] parts = setup.split("@@MR@@"); if (parts.length < 4 || parts.length > 5) { throw new IllegalArgumentException( "Malformed match-replace definition: " + setup); } m_attsToApplyTo = parts[0].trim(); m_regex = parts[1].trim().toLowerCase().equals("t"); m_ignoreCase = parts[2].trim().toLowerCase().equals("t"); m_match = parts[3].trim(); if (m_match == null || m_match.length() == 0) { throw new IllegalArgumentException("Must provide something to match!"); } if (parts.length == 5) { m_replace = parts[4]; } } /** * Set the string/regex to use for matching * * @param match the match string */ public void setMatch(String match) { m_match = match; } /** * Get the string/regex to use for matching * * @return the match string */ public String getMatch() { return m_match; } /** * Set the replace string * * @param replace the replace string */ public void setReplace(String replace) { m_replace = replace; } /** * Get the replace string * * @return the replace string */ public String getReplace() { return m_replace; } /** * Set whether this is a regular expression match or not * * @param regex true if this is a regular expression match */ public void setRegex(boolean regex) { m_regex = regex; } /** * Get whether this is a regular expression match or not * * @return true if this is a regular expression match */ public boolean getRegex() { return m_regex; } /** * Set whether to ignore case when matching * * @param ignore true if case is to be ignored */ public void setIgnoreCase(boolean ignore) { m_ignoreCase = ignore; } /** * Get whether to ignore case when matching * * @return true if case is to be ignored */ public boolean getIgnoreCase() { return m_ignoreCase; } /** * Set the attributes to apply the rule to * * @param a the attributes to apply the rule to. */ public void setAttsToApplyTo(String a) { m_attsToApplyTo = a; } /** * Get the attributes to apply the rule to * * @return the attributes to apply the rule to. */ public String getAttsToApplyTo() { return m_attsToApplyTo; } /** * Initialize this match replace rule by substituting any environment * variables in the attributes, match and replace strings. Sets up the * attribute indices to apply to and validates that the selected attributes * are all String attributes * * @param env the environment variables * @param structure the structure of the incoming instances */ public void init(Environment env, Instances structure) { m_matchS = m_match; m_replaceS = m_replace; String attsToApplyToS = m_attsToApplyTo; try { m_matchS = env.substitute(m_matchS); m_replaceS = env.substitute(m_replace); attsToApplyToS = env.substitute(attsToApplyToS); } catch (Exception ex) { } if (m_regex) { String match = m_matchS; if (m_ignoreCase) { match = match.toLowerCase(); } // precompile regular expression for speed m_regexPattern = Pattern.compile(match); } // Try a range first for the attributes String tempRangeS = attsToApplyToS; tempRangeS = tempRangeS.replace("/first", "first").replace("/last", "last"); Range tempR = new Range(); tempR.setRanges(attsToApplyToS); try { tempR.setUpper(structure.numAttributes() - 1); m_selectedAtts = tempR.getSelection(); } catch (IllegalArgumentException ex) { // probably contains attribute names then m_selectedAtts = null; } if (m_selectedAtts == null) { // parse the comma separated list of attribute names Set<Integer> indexes = new HashSet<Integer>(); String[] attParts = m_attsToApplyTo.split(","); for (String att : attParts) { att = att.trim(); if (att.toLowerCase().equals("/first")) { indexes.add(0); } else if (att.toLowerCase().equals("/last")) { indexes.add((structure.numAttributes() - 1)); } else { // try and find attribute if (structure.attribute(att) != null) { indexes.add(new Integer(structure.attribute(att).index())); } else { if (m_logger != null) { String msg = m_statusMessagePrefix + "Can't find attribute '" + att + "in the incoming instances - ignoring"; m_logger.logMessage(msg); } } } } m_selectedAtts = new int[indexes.size()]; int c = 0; for (Integer i : indexes) { m_selectedAtts[c++] = i.intValue(); } } // validate the types of the selected atts Set<Integer> indexes = new HashSet<Integer>(); for (int m_selectedAtt : m_selectedAtts) { if (structure.attribute(m_selectedAtt).isString()) { indexes.add(m_selectedAtt); } else { if (m_logger != null) { String msg = m_statusMessagePrefix + "Attribute '" + structure.attribute(m_selectedAtt).name() + "is not a string attribute - " + "ignoring"; m_logger.logMessage(msg); } } } // final array m_selectedAtts = new int[indexes.size()]; int c = 0; for (Integer i : indexes) { m_selectedAtts[c++] = i.intValue(); } } /** * Apply this rule to the supplied instance * * @param inst the instance to apply to */ public void apply(Instance inst) { for (int i = 0; i < m_selectedAtts.length; i++) { int numStringVals = inst.attribute(m_selectedAtts[i]).numValues(); if (!inst.isMissing(m_selectedAtts[i])) { String value = inst.stringValue(m_selectedAtts[i]); value = apply(value); inst.dataset().attribute(m_selectedAtts[i]).setStringValue(value); // only set the index to zero if there were more than 1 string values // for this string attribute (meaning that although the data is // streaming // in, the user has opted to retain all string values in the header. // We // only operate in pure streaming - one string value in memory at any // one time - mode). // this check saves time (no new attribute vector created) if there is // only one value (i.e. index is already zero). if (numStringVals > 1) { inst.setValue(m_selectedAtts[i], 0); } } } } /** * Apply this rule to the supplied array of strings. This array is expected * to contain string values from an instance at the same index that they * occur in the original instance. Null elements indicate non-string or * missing values from the original instance * * @param stringVals an array of strings containing string values from an * input instance */ public void apply(String[] stringVals) { for (int i = 0; i < m_selectedAtts.length; i++) { if (stringVals[m_selectedAtts[i]] != null) { stringVals[m_selectedAtts[i]] = apply(stringVals[m_selectedAtts[i]]); } } } /** * Apply this rule to the supplied string * * @param source the string to apply to * @return the source string with any matching substrings replaced. */ protected String apply(String source) { String result = source; String match = m_matchS; if (m_ignoreCase) { result = result.toLowerCase(); match = match.toLowerCase(); } if (result != null && result.length() > 0) { if (m_regex) { // result = result.replaceAll(match, m_replaceS); result = m_regexPattern.matcher(result).replaceAll(m_replaceS); } else { result = result.replace(match, m_replaceS); } } return result; } /** * Return a textual description of this rule * * @return textual description of this rule */ @Override public String toString() { // return a nicely formatted string for display // that shows all the details StringBuffer buff = new StringBuffer(); buff.append((m_regex) ? "Regex: " : "Substring: "); buff.append(m_match).append(" --> ").append(m_replace).append(" "); buff.append((m_ignoreCase) ? "[ignore case]" : "").append(" "); buff.append("[Atts: " + m_attsToApplyTo + "]"); return buff.toString(); } /** * Return the internally encoded representation of this rule * * @return the internally (parseable) representation of this rule */ public String toStringInternal() { // return a string in internal format that is // easy to parse all the data out of StringBuffer buff = new StringBuffer(); buff.append(m_attsToApplyTo).append("@@MR@@"); buff.append((m_regex) ? "t" : "f").append("@@MR@@"); buff.append((m_ignoreCase) ? "t" : "f").append("@@MR@@"); buff.append(m_match).append("@@MR@@"); buff.append(m_replace); return buff.toString(); } } }
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/TestSetEvent.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * TestSetEvent.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 test set * * @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a> * @version $Revision$ */ public class TestSetEvent extends EventObject { /** for serialization */ private static final long serialVersionUID = 8780718708498854231L; /** * The test set instances */ protected Instances m_testSet; private boolean m_structureOnly; /** * What run number is this training set from. */ protected int m_runNumber = 1; /** * Maximum number of runs. */ protected int m_maxRunNumber = 1; /** * what number is this test set (ie fold 2 of 10 folds) */ protected int m_setNumber; /** * Maximum number of sets (ie 10 in a 10 fold) */ protected int m_maxSetNumber; /** * Creates a new <code>TestSetEvent</code> * * @param source the source of the event * @param testSet the test instances */ public TestSetEvent(Object source, Instances testSet) { super(source); m_testSet = testSet; if (m_testSet != null && m_testSet.numInstances() == 0) { m_structureOnly = true; } } /** * Creates a new <code>TestSetEvent</code> * * @param source the source of the event * @param testSet the test instances * @param setNum the number of the test set * @param maxSetNum the maximum number of sets */ public TestSetEvent(Object source, Instances testSet, int setNum, int maxSetNum) { this(source, testSet); m_setNumber = setNum; m_maxSetNumber = maxSetNum; } /** * Creates a new <code>TestSetEvent</code> * * @param source the source of the event * @param testSet the test instances * @param runNum the run number that the test set belongs to * @param maxRunNum the maximum run number * @param setNum the number of the test set * @param maxSetNum the maximum number of sets */ public TestSetEvent(Object source, Instances testSet, int runNum, int maxRunNum, int setNum, int maxSetNum) { this(source, testSet, setNum, maxSetNum); m_runNumber = runNum; m_maxRunNumber = maxRunNum; } /** * Get the test set instances * * @return an <code>Instances</code> value */ public Instances getTestSet() { return m_testSet; } /** * Get the run number that this training set belongs to. * * @return the run number for this training set. */ public int getRunNumber() { return m_runNumber; } /** * Get the maximum number of runs. * * @return return the maximum number of runs. */ public int getMaxRunNumber() { return m_maxRunNumber; } /** * Get the test set number (eg. fold 2 of a 10 fold split) * * @return an <code>int</code> value */ public int getSetNumber() { return m_setNumber; } /** * Get the maximum set number * * @return an <code>int</code> value */ public int getMaxSetNumber() { return m_maxSetNumber; } /** * 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/TestSetListener.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * TestSetListener.java * Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.beans; import java.util.EventListener; /** * Interface to something that can accpet test set events * * @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a> * @version $Revision$ */ public interface TestSetListener extends EventListener { /** * Accept and process a test set event * * @param e a <code>TestSetEvent</code> value */ void acceptTestSet(TestSetEvent 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/TestSetMaker.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * TestSetMaker.java * Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.beans; import java.io.Serializable; import java.util.Vector; import weka.core.Instances; /** * Bean that accepts data sets and produces test sets * * @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a> * @version $Revision$ */ public class TestSetMaker extends AbstractTestSetProducer implements DataSourceListener, TrainingSetListener, EventConstraints, Serializable, StructureProducer { /** for serialization */ private static final long serialVersionUID = -8473882857628061841L; protected boolean m_receivedStopNotification = false; /** * 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("dataSet")) { return null; } if (m_listenee == null) { return null; } if (m_listenee != null && m_listenee instanceof StructureProducer) { return ((StructureProducer) m_listenee).getStructure("dataSet"); } return null; } public TestSetMaker() { m_visual.loadIcons(BeanVisual.ICON_PATH + "TestSetMaker.gif", BeanVisual.ICON_PATH + "TestSetMaker_animated.gif"); m_visual.setText("TestSetMaker"); } /** * 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 "Designate an incoming data set as a test set."; } /** * Accepts and processes a data set event * * @param e a <code>DataSetEvent</code> value */ @Override public void acceptDataSet(DataSetEvent e) { m_receivedStopNotification = false; TestSetEvent tse = new TestSetEvent(this, e.getDataSet()); tse.m_setNumber = 1; tse.m_maxSetNumber = 1; notifyTestSetProduced(tse); } @Override public void acceptTrainingSet(TrainingSetEvent e) { m_receivedStopNotification = false; TestSetEvent tse = new TestSetEvent(this, e.getTrainingSet()); tse.m_setNumber = 1; tse.m_maxSetNumber = 1; notifyTestSetProduced(tse); } /** * Tells all listeners that a test set is available * * @param tse a <code>TestSetEvent</code> value */ @SuppressWarnings("unchecked") protected void notifyTestSetProduced(TestSetEvent tse) { Vector<TestSetListener> l; synchronized (this) { l = (Vector<TestSetListener>) m_listeners.clone(); } if (l.size() > 0) { for (int i = 0; i < l.size(); i++) { if (m_receivedStopNotification) { if (m_logger != null) { m_logger.logMessage("[TestSetMaker] " + statusMessagePrefix() + " stopping."); m_logger.statusMessage(statusMessagePrefix() + "INTERRUPTED"); } m_receivedStopNotification = false; break; } l.elementAt(i).acceptTestSet(tse); } } } @Override public void stop() { // do something m_receivedStopNotification = true; // tell the listenee (upstream bean) to stop if (m_listenee instanceof 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; } /** * 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("dataSet")) { 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/TestSetMakerBeanInfo.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * TestSetMakerBeanInfo.java * Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.beans; /** * Bean info class for the test set maker bean. Essentially just hides * gui related properties * * @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a> * @version $Revision$ */ public class TestSetMakerBeanInfo extends AbstractTestSetProducerBeanInfo { }
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/TestSetProducer.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * TestSetProducer.java * Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.beans; /** * Interface to something that can produce test sets * * @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a> * @version $Revision$ */ public interface TestSetProducer { /** * Add a listener for test set events * * @param tsl a <code>TestSetListener</code> value */ void addTestSetListener(TestSetListener tsl); /** * Remove a listener for test set events * * @param tsl a <code>TestSetListener</code> value */ void removeTestSetListener(TestSetListener tsl); }
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/TextEvent.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * TextEvent.java * Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.beans; import java.util.EventObject; /** * Event that encapsulates some textual information * * @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a> * @version $Revision$ */ public class TextEvent extends EventObject { /** for serialization */ private static final long serialVersionUID = 4196810607402973744L; /** * The text */ protected String m_text; /** * The title for the text. Could be used in a list component */ protected String m_textTitle; /** * Creates a new <code>TextEvent</code> instance. * * @param source an <code>Object</code> value * @param text a <code>String</code> value */ public TextEvent(Object source, String text, String textTitle) { super(source); m_text = text; m_textTitle = textTitle; } /** * Describe <code>getText</code> method here. * * @return a <code>String</code> value */ public String getText() { return m_text; } /** * Describe <code>getTextTitle</code> method here. * * @return a <code>String</code> value */ public String getTextTitle() { return m_textTitle; } }
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/TextListener.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * TextListener.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 TextEvent * * @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a> * @version $Revision$ * @since 1.0 * @see EventListener */ public interface TextListener extends EventListener { /** * Accept and process a text event * * @param e a <code>TextEvent</code> value */ void acceptText(TextEvent 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/TextSaver.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * TextSaver.java * * Copyright (C) 2012 University of Waikato, Hamilton, New Zealand */ package weka.gui.beans; import java.awt.BorderLayout; import java.beans.EventSetDescriptor; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Serializable; import javax.swing.JPanel; import weka.core.Environment; import weka.core.EnvironmentHandler; import weka.gui.Logger; /** * Simple component to save the text carried in text events out to a file * * @author thuvh (thuvh87{[at]}gmail{[dot]}com) * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision$ */ @KFStep(category = "DataSinks", toolTipText = "Save text output to a file") public class TextSaver extends JPanel implements TextListener, BeanCommon, Visible, Serializable, EnvironmentHandler { /** * For serialization */ private static final long serialVersionUID = 6363577506969809332L; /** * Default visual for data sources */ protected BeanVisual m_visual = new BeanVisual("TextSaver", BeanVisual.ICON_PATH + "DefaultText.gif", BeanVisual.ICON_PATH + "DefaultText_animated.gif"); /** * 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; /** Whether to append to the file or not */ protected boolean m_append = true; /** * Global info for this bean * * @return a <code>String</code> value */ public String globalInfo() { return "Save/append static text to a file."; } /** * Default constructors a new TextSaver */ public TextSaver() { 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; } public void setAppend(boolean append) { m_append = append; } public boolean getAppend() { return m_append; } /** * Set environment variables to use * * @param env the environment variables to use */ @Override public void setEnvironment(Environment env) { m_env = env; } @Override public void useDefaultVisual() { m_visual.loadIcons(BeanVisual.ICON_PATH + "DefaultText.gif", BeanVisual.ICON_PATH + "DefaultText_animated.gif"); m_visual.setText("TextSaver"); } @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) { } /** * Accept and process an TextEvent * * @param textEvent the TextEvent to process */ @Override public synchronized void acceptText(TextEvent textEvent) { String content = textEvent.getText(); 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 .txt if necessary if (filename.toLowerCase().indexOf(".txt") < 0) { filename += ".txt"; } File file = new File(filename); if (!file.isDirectory()) { BufferedWriter writer = null; try { writer = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(file, m_append), "utf-8")); writer.write(content); writer.close(); } catch (IOException e) { if (m_logger != null) { m_logger.statusMessage(statusMessagePrefix() + "WARNING: " + "an error occurred whilte trying to write text (see log)"); m_logger.logMessage("[" + getCustomName() + "] " + "an error occurred whilte trying to write text: " + e.getMessage()); } else { e.printStackTrace(); } } } else { String message = "Can't write text 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 text because no file 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/TextSaverBeanInfo.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * TextSaverBeanInfo.java * * Copyright (C) 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 serialized model saver bean * * @author (thuvh87{[at]}gmail{[dot]}com) * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision$ */ public class TextSaverBeanInfo 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; } /** * Get BeanDescriptor for this bean * * @return an <code>BeanDescriptor</code> value */ @Override public BeanDescriptor getBeanDescriptor() { return new BeanDescriptor(weka.gui.beans.TextSaver.class, TextSaverCustomizer.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/TextSaverCustomizer.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * TextSaverCustomizer.java * * Copyright (C) 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.JCheckBox; import javax.swing.JFileChooser; import javax.swing.JPanel; import javax.swing.JTextArea; import weka.core.Environment; import weka.core.EnvironmentHandler; /** * Customizer for the TextSaver component. * * @author thuvh (thuvh87{[at]}gmail{[dot]}com) * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision$ */ public class TextSaverCustomizer extends JPanel implements BeanCustomizer, EnvironmentHandler, CustomizerClosingListener, CustomizerCloseRequester { /** * For serialization */ private static final long serialVersionUID = -1012433373647714743L; private TextSaver m_textSaver; private FileEnvironmentField m_fileEditor; private final JCheckBox m_append = new JCheckBox("Append to file"); private Environment m_env = Environment.getSystemWide(); private ModifyListener m_modifyListener; private Window m_parent; private String m_fileBackup; /** * Default Constructor */ public TextSaverCustomizer() { setLayout(new BorderLayout()); } /** * Set the TextSaver object to customize. * * @param object the TextSaver to customize */ @Override public void setObject(Object object) { m_textSaver = (TextSaver) object; m_fileBackup = m_textSaver.getFilename(); m_append.setSelected(m_textSaver.getAppend()); 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(); JPanel temp = new JPanel(); temp.setLayout(new GridLayout(2, 0)); temp.add(m_fileEditor); temp.add(m_append); holder.add(temp, BorderLayout.SOUTH); String globalInfo = m_textSaver.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_textSaver.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() { @Override public void actionPerformed(ActionEvent e) { m_textSaver.setFilename(m_fileEditor.getText()); m_textSaver.setAppend(m_append.isSelected()); if (m_modifyListener != null) { m_modifyListener.setModifiedStatus(TextSaverCustomizer.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 environment variables to use * * @param env the environment variables to use */ @Override public void setEnvironment(Environment env) { m_env = env; } /** * Set a listener interested in whether we've modified the TextSaver that * we're customizing * * @param l the listener */ @Override public void setModifiedListener(ModifyListener l) { m_modifyListener = l; } /** * Set the parent window of this dialog * * @param parent the parent window */ @Override 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 TextSaver to its previous state. */ @Override public void customizerClosing() { m_textSaver.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/TextViewer.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * TextViewer.java * Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.beans; import java.awt.BorderLayout; import java.awt.Font; import java.awt.GraphicsEnvironment; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.InputEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; 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.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Enumeration; import java.util.EventObject; import java.util.List; import java.util.Vector; import javax.swing.*; import weka.core.Utils; import weka.gui.Logger; import weka.gui.ResultHistoryPanel; import weka.gui.SaveBuffer; /** * Bean that collects and displays pieces of text * * @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a> * @version $Revision$ */ public class TextViewer extends JPanel implements TextListener, DataSourceListener, TrainingSetListener, TestSetListener, Visible, UserRequestAcceptor, BeanContextChild, BeanCommon, EventConstraints, HeadlessEventCollector { /** for serialization */ private static final long serialVersionUID = 104838186352536832L; protected BeanVisual m_visual; private transient JFrame m_resultsFrame = null; protected List<EventObject> m_headlessEvents; /** * Output area for a piece of text */ private transient JTextArea m_outText = null;// = new JTextArea(20, 80); /** * List of text revieved so far */ protected transient ResultHistoryPanel m_history; /** * 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); /** * Objects listening for text events */ private final Vector<TextListener> m_textListeners = new Vector<TextListener>(); public TextViewer() { java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment(); if (!GraphicsEnvironment.isHeadless()) { appearanceFinal(); } else { m_headlessEvents = new ArrayList<EventObject>(); } } protected void appearanceDesign() { setUpResultHistory(); removeAll(); if (m_visual == null) { m_visual = new BeanVisual("TextViewer", BeanVisual.ICON_PATH + "DefaultText.gif", BeanVisual.ICON_PATH + "DefaultText_animated.gif"); } setLayout(new BorderLayout()); add(m_visual, BorderLayout.CENTER); } protected void appearanceFinal() { removeAll(); setLayout(new BorderLayout()); setUpFinal(); } protected void setUpFinal() { setUpResultHistory(); JPanel holder = new JPanel(); holder.setLayout(new BorderLayout()); JScrollPane js = new JScrollPane(m_outText); js.setBorder(BorderFactory.createTitledBorder("Text")); holder.add(js, BorderLayout.CENTER); holder.add(m_history, BorderLayout.WEST); add(holder, BorderLayout.CENTER); } /** * Global info for this bean * * @return a <code>String</code> value */ public String globalInfo() { return "General purpose text display."; } private void setUpResultHistory() { java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment(); if (!GraphicsEnvironment.isHeadless()) { if (m_outText == null) { m_outText = new JTextArea(20, 80); m_history = new ResultHistoryPanel(m_outText); } m_outText.setEditable(false); m_outText.setFont(new Font("Monospaced", Font.PLAIN, 12)); m_outText.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); m_history.setBorder(BorderFactory.createTitledBorder("Result list")); m_history.setHandleRightClicks(false); m_history.getList().addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (((e.getModifiers() & InputEvent.BUTTON1_MASK) != InputEvent.BUTTON1_MASK) || e.isAltDown()) { int index = m_history.getList().locationToIndex(e.getPoint()); if (index != -1) { String name = m_history.getNameAtIndex(index); visualize(name, e.getX(), e.getY()); } else { visualize(null, e.getX(), e.getY()); } } } }); } } /** * Handles constructing a popup menu with visualization options. * * @param name the name of the result history list entry clicked on by the * user * @param x the x coordinate for popping up the menu * @param y the y coordinate for popping up the menu */ protected void visualize(String name, int x, int y) { final JPanel panel = this; final String selectedName = name; JPopupMenu resultListMenu = new JPopupMenu(); JMenuItem visMainBuffer = new JMenuItem("View in main window"); if (selectedName != null) { visMainBuffer.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m_history.setSingle(selectedName); } }); } else { visMainBuffer.setEnabled(false); } resultListMenu.add(visMainBuffer); JMenuItem visSepBuffer = new JMenuItem("View in separate window"); if (selectedName != null) { visSepBuffer.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m_history.openFrame(selectedName); } }); } else { visSepBuffer.setEnabled(false); } resultListMenu.add(visSepBuffer); JMenuItem saveOutput = new JMenuItem("Save result buffer"); if (selectedName != null) { saveOutput.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { SaveBuffer m_SaveOut = new SaveBuffer(null, panel); StringBuffer sb = m_history.getNamedBuffer(selectedName); if (sb != null) { m_SaveOut.save(sb); } } }); } else { saveOutput.setEnabled(false); } resultListMenu.add(saveOutput); JMenuItem deleteOutput = new JMenuItem("Delete result buffer"); if (selectedName != null) { deleteOutput.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m_history.removeResult(selectedName); } }); } else { deleteOutput.setEnabled(false); } resultListMenu.add(deleteOutput); resultListMenu.show(m_history.getList(), x, y); } /** * Accept a data set for displaying as text * * @param e a <code>DataSetEvent</code> value */ @Override public synchronized void acceptDataSet(DataSetEvent e) { TextEvent nt = new TextEvent(e.getSource(), e.getDataSet().toString(), e.getDataSet() .relationName()); acceptText(nt); } /** * Accept a training set for displaying as text * * @param e a <code>TrainingSetEvent</code> value */ @Override public synchronized void acceptTrainingSet(TrainingSetEvent e) { TextEvent nt = new TextEvent(e.getSource(), e.getTrainingSet().toString(), e .getTrainingSet().relationName()); acceptText(nt); } /** * Accept a test set for displaying as text * * @param e a <code>TestSetEvent</code> value */ @Override public synchronized void acceptTestSet(TestSetEvent e) { TextEvent nt = new TextEvent(e.getSource(), e.getTestSet().toString(), e.getTestSet() .relationName()); acceptText(nt); } /** * Accept some text * * @param e a <code>TextEvent</code> value */ @Override public synchronized void acceptText(TextEvent e) { if (m_outText == null) { setUpResultHistory(); } StringBuffer result = new StringBuffer(); result.append(e.getText()); // m_resultsString.append(e.getText()); // m_outText.setText(m_resultsString.toString()); String name = (new SimpleDateFormat("HH:mm:ss - ")).format(new Date()); name += e.getTextTitle(); if (m_outText != null) { // see if there is an entry with this name already in the list - // could happen if two items with the same name arrive at the same second int mod = 2; String nameOrig = new String(name); while (m_history.getNamedBuffer(name) != null) { name = new String(nameOrig + "" + mod); mod++; } m_history.addResult(name, result); m_history.setSingle(name); } if (m_headlessEvents != null) { m_headlessEvents.add(e); } // pass on the event to any listeners notifyTextListeners(e); } /** * 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()) { for (EventObject e : headless) { if (e instanceof TextEvent) { acceptText((TextEvent) e); } } } } /** * Describe <code>setVisual</code> method here. * * @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 for this bean */ @Override public void useDefaultVisual() { m_visual.loadIcons(BeanVisual.ICON_PATH + "DefaultText.gif", BeanVisual.ICON_PATH + "DefaultText_animated.gif"); } /** * Popup a component to display the selected text */ public void showResults() { if (m_resultsFrame == null) { if (m_outText == null) { setUpResultHistory(); } m_resultsFrame = Utils.getWekaJFrame("Text Viewer", m_visual); m_resultsFrame.getContentPane().setLayout(new BorderLayout()); final JScrollPane js = new JScrollPane(m_outText); js.setBorder(BorderFactory.createTitledBorder("Text")); JSplitPane p2 = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, m_history, js); m_resultsFrame.getContentPane().add(p2, BorderLayout.CENTER); // m_resultsFrame.getContentPane().add(js, BorderLayout.CENTER); // m_resultsFrame.getContentPane().add(m_history, BorderLayout.WEST); 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(); } } /** * Get a list 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"); newVector.addElement("?Clear 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 if (request.compareTo("Clear results") == 0) { m_outText.setText(""); m_history.clearResults(); } else { throw new IllegalArgumentException(request + " not supported (TextViewer)"); } } /** * 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(); } } } /** * 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); } } } /** * 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; } /** * 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) { } /** * 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(); } /** * 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 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(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 */ @Override public void disconnectionNotification(String eventName, Object source) { } /** * 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.equals("text")) { return true; } return false; } /** * 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); } public static void main(String[] args) { try { final javax.swing.JFrame jf = new javax.swing.JFrame(); jf.getContentPane().setLayout(new java.awt.BorderLayout()); final TextViewer tv = new TextViewer(); tv.acceptText(new TextEvent(tv, "Here is some test text from the main " + "method of this class.", "The Title")); jf.getContentPane().add(tv, 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(); } } }
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/TextViewerBeanInfo.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * TextViewerBeanInfo.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 text viewer * * @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a> * @version $Revision$ */ public class TextViewerBeanInfo extends SimpleBeanInfo { /** * Get the event set descriptors for this bean * * @return an <code>EventSetDescriptor[]</code> value */ public EventSetDescriptor [] getEventSetDescriptors() { try { EventSetDescriptor [] esds = { new EventSetDescriptor(TextViewer.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/ThresholdDataEvent.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ThresholdDataEvent.java * Copyright (C) 2003-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.beans; import java.util.EventObject; import weka.core.Attribute; import weka.gui.visualize.PlotData2D; /** * Event encapsulating classifier performance data based on * varying a threshold over the classifier's predicted probabilities * * @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a> * @version $Revision$ * @see EventObject */ public class ThresholdDataEvent extends EventObject { /** for serialization */ private static final long serialVersionUID = -8309334224492439644L; private PlotData2D m_dataSet; private Attribute m_classAttribute; public ThresholdDataEvent(Object source, PlotData2D dataSet) { this(source, dataSet, null); } public ThresholdDataEvent(Object source, PlotData2D dataSet, Attribute classAtt) { super(source); m_dataSet = dataSet; m_classAttribute = classAtt; } /** * Return the instances of the data set * * @return an <code>Instances</code> value */ public PlotData2D getDataSet() { return m_dataSet; } /** * Return the class attribute for which the threshold data was generated * for. * * @return the class attribute for the threshold data or null if not set. */ public Attribute getClassAttribute() { return m_classAttribute; } }
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/ThresholdDataListener.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ThresholdDataListener.java * Copyright (C) 2003-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.beans; import java.util.EventListener; /** * Interface to something that can accept ThresholdDataEvents * * @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a> * @version $Revision$ * @since 1.0 * @see EventListener */ public interface ThresholdDataListener extends EventListener { void 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/TrainTestSplitMaker.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * TrainTestSplitMaker.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 that accepts data sets, training sets, test sets and produces both a * training and test set by randomly spliting the data * * @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a> * @version $Revision$ */ public class TrainTestSplitMaker extends AbstractTrainAndTestSetProducer implements DataSourceListener, TrainingSetListener, TestSetListener, UserRequestAcceptor, EventConstraints, Serializable, StructureProducer { /** for serialization */ private static final long serialVersionUID = 7390064039444605943L; private double m_trainPercentage = 66; private int m_randomSeed = 1; private Thread m_splitThread = null; private boolean m_dataProvider = false; private boolean m_trainingProvider = false; private boolean m_testProvider = false; public TrainTestSplitMaker() { m_visual.loadIcons(BeanVisual.ICON_PATH + "TrainTestSplitMaker.gif", BeanVisual.ICON_PATH + "TrainTestSplittMaker_animated.gif"); m_visual.setText("TrainTestSplitMaker"); } 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 separate train and test sets."; } /** * Tip text info for this property * * @return a <code>String</code> value */ public String trainPercentTipText() { return "The percentage of data to go into the training set"; } /** * Set the percentage of data to be in the training portion of the split * * @param newTrainPercent an <code>int</code> value */ public void setTrainPercent(double newTrainPercent) { m_trainPercentage = newTrainPercent; } /** * Get the percentage of the data that will be in the training portion of the * split * * @return an <code>int</code> value */ public double getTrainPercent() { return m_trainPercentage; } /** * Tip text for this property * * @return a <code>String</code> value */ public String seedTipText() { return "The randomization seed"; } /** * Set the random seed * * @param newSeed an <code>int</code> value */ public void setSeed(int newSeed) { m_randomSeed = newSeed; } /** * Get the value of the random seed * * @return an <code>int</code> value */ public int getSeed() { return m_randomSeed; } /** * 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 (m_splitThread == null) { final Instances dataSet = new Instances(e.getDataSet()); m_splitThread = new Thread() { @Override @SuppressWarnings("deprecation") public void run() { try { dataSet.randomize(new Random(m_randomSeed)); int trainSize = (int) Math.round(dataSet.numInstances() * m_trainPercentage / 100); int testSize = dataSet.numInstances() - trainSize; Instances train = new Instances(dataSet, 0, trainSize); Instances test = new Instances(dataSet, trainSize, testSize); TrainingSetEvent tse = new TrainingSetEvent( TrainTestSplitMaker.this, train); tse.m_setNumber = 1; tse.m_maxSetNumber = 1; if (m_splitThread != null) { notifyTrainingSetProduced(tse); } // inform all test set listeners TestSetEvent teste = new TestSetEvent(TrainTestSplitMaker.this, test); teste.m_setNumber = 1; teste.m_maxSetNumber = 1; if (m_splitThread != null) { notifyTestSetProduced(teste); } else { if (m_logger != null) { m_logger.logMessage("[TrainTestSplitMaker] " + statusMessagePrefix() + " Split has been canceled!"); m_logger.statusMessage(statusMessagePrefix() + "INTERRUPTED"); } } } catch (Exception ex) { stop(); // stop all processing if (m_logger != null) { m_logger.statusMessage(statusMessagePrefix() + "ERROR (See log for details)"); m_logger.logMessage("[TrainTestSplitMaker] " + statusMessagePrefix() + " problem during split creation. " + ex.getMessage()); } ex.printStackTrace(); } finally { if (isInterrupted()) { if (m_logger != null) { m_logger.logMessage("[TrainTestSplitMaker] " + statusMessagePrefix() + " Split has been canceled!"); m_logger.statusMessage(statusMessagePrefix() + "INTERRUPTED"); } } block(false); } } }; m_splitThread.setPriority(Thread.MIN_PRIORITY); m_splitThread.start(); // if (m_splitThread.isAlive()) { block(true); // } m_splitThread = null; } } /** * Notify test set listeners that a test set is available * * @param tse a <code>TestSetEvent</code> value */ @SuppressWarnings("unchecked") protected 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_splitThread == null) { break; } // System.err.println("Notifying test listeners " // +"(Train - test split maker)"); l.elementAt(i).acceptTestSet(tse); } } } /** * Notify training set listeners that a training set is available * * @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_splitThread == null) { break; } // System.err.println("Notifying training listeners " // +"(Train - test split fold maker)"); l.elementAt(i).acceptTrainingSet(tse); } } } /** * Function used to stop code that calls acceptDataSet. This is needed as * split 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 that the thread is still alive before blocking if (m_splitThread.isAlive()) { wait(); } } catch (InterruptedException ex) { } } else { notifyAll(); } } /** * Stop processing */ @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(); } // stop the split thread if (m_splitThread != null) { Thread temp = m_splitThread; m_splitThread = null; temp.interrupt(); temp.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_splitThread != null); } /** * Get list of user requests * * @return an <code>Enumeration</code> value */ @Override public Enumeration<String> enumerateRequests() { Vector<String> newVector = new Vector<String>(0); if (m_splitThread != 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 (TrainTestSplitMaker)"); } } /** * 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; } 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/TrainTestSplitMakerBeanInfo.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * TrainTestSplitMakerBeanInfo.java * Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.beans; import java.beans.BeanDescriptor; import java.beans.PropertyDescriptor; /** * Bean info class for the train test split maker bean * * @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a> * @version $Revision$ * @since 1.0 * @see AbstractTrainAndTestSetProducerBeanInfo */ public class TrainTestSplitMakerBeanInfo extends AbstractTrainAndTestSetProducerBeanInfo { /** * Get the property descriptors for this bean * * @return a <code>PropertyDescriptor[]</code> value */ public PropertyDescriptor[] getPropertyDescriptors() { try { PropertyDescriptor p1; PropertyDescriptor p2; p1 = new PropertyDescriptor("trainPercent", TrainTestSplitMaker.class); p2 = new PropertyDescriptor("seed", TrainTestSplitMaker.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 */ public BeanDescriptor getBeanDescriptor() { return new BeanDescriptor(weka.gui.beans.TrainTestSplitMaker.class, TrainTestSplitMakerCustomizer.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/TrainTestSplitMakerCustomizer.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * TrainTestSplitMakerCustomizer.java * Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.beans; import java.awt.BorderLayout; import java.beans.Customizer; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import javax.swing.JPanel; import weka.gui.PropertySheetPanel; /** * GUI customizer for the train test split maker bean * * @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a> * @version $Revision$ */ public class TrainTestSplitMakerCustomizer extends JPanel implements Customizer { /** for serialization */ private static final long serialVersionUID = -1684662340241807260L; private PropertyChangeSupport m_pcSupport = new PropertyChangeSupport(this); private PropertySheetPanel m_splitEditor = new PropertySheetPanel(); public TrainTestSplitMakerCustomizer() { setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 5, 5, 5)); setLayout(new BorderLayout()); add(m_splitEditor, BorderLayout.CENTER); add(new javax.swing.JLabel("TrainTestSplitMakerCustomizer"), BorderLayout.NORTH); } /** * Set the TrainTestSplitMaker to be customized * * @param object an <code>Object</code> value */ public void setObject(Object object) { m_splitEditor.setTarget((TrainTestSplitMaker)object); } /** * 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); } }
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/TrainingSetEvent.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * TrainingSetEvent.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 training set * * @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a> * @version $Revision$ */ public class TrainingSetEvent extends EventObject { /** for serialization */ private static final long serialVersionUID = 5872343811810872662L; /** * The training instances */ protected Instances m_trainingSet; private boolean m_structureOnly; /** * What run number is this training set from. */ protected int m_runNumber = 1; /** * Maximum number of runs. */ protected int m_maxRunNumber = 1; /** * what number is this training set (ie fold 2 of 10 folds) */ protected int m_setNumber; /** * Maximum number of sets (ie 10 in a 10 fold) */ protected int m_maxSetNumber; /** * Creates a new <code>TrainingSetEvent</code> * * @param source the source of the event * @param trainSet the training instances */ public TrainingSetEvent(Object source, Instances trainSet) { super(source); m_trainingSet = trainSet; if (m_trainingSet != null && m_trainingSet.numInstances() == 0) { m_structureOnly = true; } } /** * Creates a new <code>TrainingSetEvent</code> * * @param source the source of the event * @param trainSet the training instances * @param setNum the number of the training set * @param maxSetNum the maximum number of sets */ public TrainingSetEvent(Object source, Instances trainSet, int setNum, int maxSetNum) { this(source, trainSet); m_setNumber = setNum; m_maxSetNumber = maxSetNum; } /** * Creates a new <code>TrainingSetEvent</code> * * @param source the source of the event * @param trainSet the training instances * @param runNum the run number that the training set belongs to * @param maxRunNum the maximum run number * @param setNum the number of the training set * @param maxSetNum the maximum number of sets */ public TrainingSetEvent(Object source, Instances trainSet, int runNum, int maxRunNum, int setNum, int maxSetNum) { this(source, trainSet, setNum, maxSetNum); m_runNumber = runNum; m_maxRunNumber = maxRunNum; } /** * Get the training instances * * @return an <code>Instances</code> value */ public Instances getTrainingSet() { return m_trainingSet; } /** * Get the run number that this training set belongs to. * * @return the run number for this training set. */ public int getRunNumber() { return m_runNumber; } /** * Get the maximum number of runs. * * @return return the maximum number of runs. */ public int getMaxRunNumber() { return m_maxRunNumber; } /** * Get the set number (eg. fold 2 of a 10 fold split) * * @return an <code>int</code> value */ public int getSetNumber() { return m_setNumber; } /** * Get the maximum set number * * @return an <code>int</code> value */ public int getMaxSetNumber() { return m_maxSetNumber; } /** * 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/TrainingSetListener.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * TrainingSetListener.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 and process training set events * * @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a> * @version $Revision$ */ public interface TrainingSetListener extends EventListener { /** * Accept and process a training set * * @param e a <code>TrainingSetEvent</code> value */ void acceptTrainingSet(TrainingSetEvent 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/TrainingSetMaker.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * TrainingSetMaker.java * Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.beans; import java.io.Serializable; import java.util.Vector; import weka.core.Instances; /** * Bean that accepts a data sets and produces a training set * * @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a> * @version $Revision$ */ public class TrainingSetMaker extends AbstractTrainingSetProducer implements DataSourceListener, TestSetListener, EventConstraints, Serializable, StructureProducer { /** for serialization */ private static final long serialVersionUID = -6152577265471535786L; protected boolean m_receivedStopNotification = false; public TrainingSetMaker() { m_visual.loadIcons(BeanVisual.ICON_PATH + "TrainingSetMaker.gif", BeanVisual.ICON_PATH + "TrainingSetMaker_animated.gif"); m_visual.setText("TrainingSetMaker"); } /** * 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("dataSet")) { return null; } if (m_listenee == null) { return null; } if (m_listenee != null && m_listenee instanceof StructureProducer) { return ((StructureProducer) m_listenee).getStructure("dataSet"); } return null; } /** * 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 "Designate an incoming data set as a training set."; } /** * Accept a data set * * @param e a <code>DataSetEvent</code> value */ @Override public void acceptDataSet(DataSetEvent e) { m_receivedStopNotification = false; TrainingSetEvent tse = new TrainingSetEvent(this, e.getDataSet()); tse.m_setNumber = 1; tse.m_maxSetNumber = 1; notifyTrainingSetProduced(tse); } @Override public void acceptTestSet(TestSetEvent e) { m_receivedStopNotification = false; TrainingSetEvent tse = new TrainingSetEvent(this, e.getTestSet()); tse.m_setNumber = 1; tse.m_maxSetNumber = 1; notifyTrainingSetProduced(tse); } /** * Inform training set listeners that a training set is available * * @param tse a <code>TrainingSetEvent</code> value */ @SuppressWarnings("unchecked") protected void notifyTrainingSetProduced(TrainingSetEvent tse) { Vector<TrainingSetListener> l; synchronized (this) { l = (Vector<TrainingSetListener>) m_listeners.clone(); } if (l.size() > 0) { for (int i = 0; i < l.size(); i++) { if (m_receivedStopNotification) { if (m_logger != null) { m_logger.logMessage("T[rainingSetMaker] " + statusMessagePrefix() + " stopping."); m_logger.statusMessage(statusMessagePrefix() + "INTERRUPTED"); } m_receivedStopNotification = false; break; } System.err.println("Notifying listeners (training set maker)"); l.elementAt(i).acceptTrainingSet(tse); } } } /** * Stop any action */ @Override public void stop() { m_receivedStopNotification = true; // 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; } /** * 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("dataSet")) { 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/TrainingSetMakerBeanInfo.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * TrainingSetMakerBeanInfo.java * Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.beans; /** * Bean info class for the training set maker bean * * @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a> * @version $Revision$ */ public class TrainingSetMakerBeanInfo extends AbstractTrainingSetProducerBeanInfo { }
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/TrainingSetProducer.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * TrainingSetProducer.java * Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.beans; /** * Interface to something that can produce a training set * * @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a> * @version $Revision$ */ public interface TrainingSetProducer { /** * Add a training set listener * * @param tsl a <code>TrainingSetListener</code> value */ void addTrainingSetListener(TrainingSetListener tsl); /** * Remove a training set listener * * @param tsl a <code>TrainingSetListener</code> value */ void removeTrainingSetListener(TrainingSetListener tsl); }
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/UserRequestAcceptor.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * UserRequestAcceptor.java * Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.beans; import java.util.Enumeration; /** * Interface to something that can accept requests from a user to perform some * action * * @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a> * @version $Revision$ * @since 1.0 */ public interface UserRequestAcceptor { /** * Get a list of performable requests * * @return an <code>Enumeration</code> value */ Enumeration<String> enumerateRequests(); /** * Perform the named request * * @param requestName a <code>String</code> value * @exception IllegalArgumentException if an error occurs */ void performRequest(String requestName); }
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/Visible.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * Visible.java * Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.beans; /** * Interface to something that has a visible (via BeanVisual) reprentation * * @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a> * @version $Revision$ * @since 1.0 */ public interface Visible { /** * Use the default visual representation */ void useDefaultVisual(); /** * Set a new visual representation * * @param newVisual a <code>BeanVisual</code> value */ void setVisual(BeanVisual newVisual); /** * Get the visual representation * * @return a <code>BeanVisual</code> value */ BeanVisual getVisual(); }
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/VisualizableErrorEvent.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * VisualizableErrorEvent.java * Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.beans; import java.util.EventObject; import weka.gui.visualize.PlotData2D; /** * Event encapsulating error information for a learning scheme * that can be visualized in the DataVisualizer * * @author Mark Hall * @version $Revision$ * @see EventObject */ public class VisualizableErrorEvent extends EventObject { /** for serialization */ private static final long serialVersionUID = -5811819270887223400L; private PlotData2D m_dataSet; public VisualizableErrorEvent(Object source, PlotData2D dataSet) { super(source); m_dataSet = dataSet; } /** * Return the instances of the data set * * @return an <code>Instances</code> value */ public PlotData2D getDataSet() { return m_dataSet; } }
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/VisualizableErrorListener.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * VisualizableErrorListener.java * Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.beans; import java.util.EventListener; /** * Interface to something that can accept VisualizableErrorEvents * * @author Mark Hall * @version $Revision$ * @since 1.0 * @see EventListener */ public interface VisualizableErrorListener extends EventListener { void acceptDataSet(VisualizableErrorEvent 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/WekaOffscreenChartRenderer.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * WekaOffscreenChartRenderer.java * Copyright (C) 2011-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.beans; import java.awt.image.BufferedImage; import java.util.List; import weka.core.Instance; import weka.core.Instances; import weka.gui.AttributeVisualizationPanel; import weka.gui.visualize.Plot2D; import weka.gui.visualize.PlotData2D; /** * Default OffscreenChartRenderer that uses Weka's built-in chart and graph * classes. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision$ */ public class WekaOffscreenChartRenderer extends AbstractOffscreenChartRenderer { /** * The name of this off screen renderer * * @return the name of this off screen renderer */ public String rendererName() { return "Weka Chart Renderer"; } /** * Gets a short list of additional options (if any), * suitable for displaying in a tip text, in HTML form * * @return additional options description in simple HTML form */ public String optionsTipTextHTML() { return "<html><ul><li>-title=[chart title]</li>" + "<li>-color=[coloring/class attribute name]</li></html>"; } /** * Render an XY line chart * * @param width the width of the resulting chart in pixels * @param height the height of the resulting chart in pixels * @param series a list of Instances - one for each series to be plotted * @param xAxis the name of the attribute for the x-axis (all series Instances * are expected to have an attribute of the same type with this name) * @param yAxis the name of the attribute for the y-axis (all series Instances * are expected to have an attribute of the same type with this name) * @param optionalArgs optional arguments to the renderer (may be null) * * @return a BufferedImage containing the chart * @throws Exception if there is a problem rendering the chart */ public BufferedImage renderXYLineChart(int width, int height, List<Instances> series, String xAxis, String yAxis, List<String> optionalArgs) throws Exception { BufferedImage osi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); String plotTitle = "Line chart"; String userTitle = getOption(optionalArgs, "-title"); plotTitle = (userTitle != null) ? userTitle : plotTitle; Plot2D offScreenPlot = new Plot2D(); offScreenPlot.setSize(width, height); // master plot PlotData2D master = new PlotData2D(series.get(0)); master.setPlotName(plotTitle); boolean[] connectPoints = new boolean[series.get(0).numInstances()]; for (int i = 0; i < connectPoints.length; i++) { connectPoints[i] = true; } master.setConnectPoints(connectPoints); offScreenPlot.setMasterPlot(master); // find x and y axis Instances masterInstances = series.get(0); int xAx = getIndexOfAttribute(masterInstances, xAxis); int yAx = getIndexOfAttribute(masterInstances, yAxis); if (xAx < 0) { xAx = 0; } if (yAx < 0) { yAx = 0; } // plotting axes and color offScreenPlot.setXindex(xAx); offScreenPlot.setYindex(yAx); offScreenPlot.setCindex(masterInstances.numAttributes() - 1); String colorAtt = getOption(optionalArgs, "-color"); int tempC = getIndexOfAttribute(masterInstances, colorAtt); if (tempC >= 0) { offScreenPlot.setCindex(tempC); } // additional plots if (series.size() > 1) { for (Instances plotI : series) { PlotData2D plotD = new PlotData2D(plotI); connectPoints = new boolean[plotI.numInstances()]; for (int i = 0; i < connectPoints.length; i++) { connectPoints[i] = true; } plotD.setConnectPoints(connectPoints); offScreenPlot.addPlot(plotD); } } // render java.awt.Graphics g = osi.getGraphics(); offScreenPlot.paintComponent(g); return osi; } /** * Render an XY scatter plot * * @param width the width of the resulting chart in pixels * @param height the height of the resulting chart in pixels * @param series a list of Instances - one for each series to be plotted * @param xAxis the name of the attribute for the x-axis (all series Instances * are expected to have an attribute of the same type with this name) * @param yAxis the name of the attribute for the y-axis (all series Instances * are expected to have an attribute of the same type with this name) * @param optionalArgs optional arguments to the renderer (may be null) * * @return a BufferedImage containing the chart * @throws Exception if there is a problem rendering the chart */ public BufferedImage renderXYScatterPlot(int width, int height, List<Instances> series, String xAxis, String yAxis, List<String> optionalArgs) throws Exception { BufferedImage osi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); String plotTitle = "Scatter plot"; String userTitle = getOption(optionalArgs, "-title"); plotTitle = (userTitle != null) ? userTitle : plotTitle; Plot2D offScreenPlot = new Plot2D(); offScreenPlot.setSize(width, height); // master plot PlotData2D master = new PlotData2D(series.get(0)); master.setPlotName(plotTitle); master.m_displayAllPoints = true; offScreenPlot.setMasterPlot(master); Instances masterInstances = series.get(0); int xAx = getIndexOfAttribute(masterInstances, xAxis); int yAx = getIndexOfAttribute(masterInstances, yAxis); if (xAx < 0) { xAx = 0; } if (yAx < 0) { yAx = 0; } // plotting axes and color offScreenPlot.setXindex(xAx); offScreenPlot.setYindex(yAx); offScreenPlot.setCindex(masterInstances.numAttributes() - 1); String colorAtt = getOption(optionalArgs, "-color"); int tempC = getIndexOfAttribute(masterInstances, colorAtt); if (tempC >= 0) { offScreenPlot.setCindex(tempC); } String hasErrors = getOption(optionalArgs, "-hasErrors"); // master plot is the error cases if (hasErrors != null) { int[] plotShapes = new int[masterInstances.numInstances()]; for (int i = 0; i < plotShapes.length; i++) { plotShapes[i] = Plot2D.ERROR_SHAPE; } master.setShapeType(plotShapes); } // look for an additional attribute that stores the // shape sizes String shapeSize = getOption(optionalArgs, "-shapeSize"); if (shapeSize != null && shapeSize.length() > 0) { int shapeSizeI = getIndexOfAttribute(masterInstances, shapeSize); if (shapeSizeI >= 0) { int[] plotSizes = new int[masterInstances.numInstances()]; for (int i = 0; i < masterInstances.numInstances(); i++) { plotSizes[i] = (int)masterInstances.instance(i).value(shapeSizeI); } master.setShapeSize(plotSizes); } } // additional plots if (series.size() > 1) { for (Instances plotI : series) { PlotData2D plotD = new PlotData2D(plotI); plotD.m_displayAllPoints = true; offScreenPlot.addPlot(plotD); if (shapeSize != null && shapeSize.length() > 0) { int shapeSizeI = getIndexOfAttribute(plotI, shapeSize); if (shapeSizeI >= 0) { int[] plotSizes = new int[plotI.numInstances()]; for (int i = 0; i < plotI.numInstances(); i++) { plotSizes[i] = (int)plotI.instance(i).value(shapeSizeI); } plotD.setShapeSize(plotSizes); } } // all other plots will have x shape if master plot are errors if (hasErrors != null) { int[] plotShapes = new int[plotI.numInstances()]; for (int i = 0; i < plotShapes.length; i++) { plotShapes[i] = Plot2D.X_SHAPE; } plotD.setShapeType(plotShapes); } } } // render java.awt.Graphics g = osi.getGraphics(); offScreenPlot.paintComponent(g); return osi; } /** * Render histogram(s) (numeric attribute) or pie chart (nominal attribute). * Some implementations may not be able to render more than one histogram/pie * on the same chart - the implementation can either throw an exception or * just process the first series in this case. * * This Default implementation uses Weka's built in VisualizeAttributePanel * to render with and, as such, can only render histograms. It produces * histograms for both numeric and nominal attributes. * * @param width the width of the resulting chart in pixels * @param height the height of the resulting chart in pixels * @param series a list of Instances - one for each series to be plotted * @param attsToPlot the attribute to plot * corresponding to the Instances in the series list * @param optionalArgs optional arguments to the renderer (may be null) * * @return a BufferedImage containing the chart * @throws Exception if there is a problem rendering the chart */ public BufferedImage renderHistogram(int width, int height, List<Instances> series, String attToPlot, List<String> optionalArgs) throws Exception { BufferedImage osi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); // we can only handle one series per plot so merge all series together Instances toPlot = new Instances(series.get(0)); for (int i = 1; i < series.size(); i++) { Instances additional = series.get(i); for (Instance temp : additional) { toPlot.add(temp); } } int attIndex = getIndexOfAttribute(toPlot, attToPlot); if (attIndex < 0) { attIndex = 0; } String colorAtt = getOption(optionalArgs, "-color"); int tempC = getIndexOfAttribute(toPlot, colorAtt); AttributeVisualizationPanel offScreenPlot = new AttributeVisualizationPanel(); offScreenPlot.setSize(width, height); offScreenPlot.setInstances(toPlot); offScreenPlot.setAttribute(attIndex); if (tempC >= 0) { offScreenPlot.setColoringIndex(tempC); } // render java.awt.Graphics g = osi.getGraphics(); offScreenPlot.paintComponent(g); // wait a little while so that the calculation thread can complete Thread.sleep(2000); offScreenPlot.paintComponent(g); // offScreenPlot.setAttribute(attIndex); return osi; } }
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/WekaWrapper.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * WekaWrapper.java * Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.beans; /** * Interface to something that can wrap around a class of Weka * algorithms (classifiers, filters etc). Typically implemented * by a bean for handling classes of Weka algorithms. * * @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a> * @version $Revision$ * @since 1.0 */ public interface WekaWrapper { /** * Set the algorithm. * * @param algorithm an <code>Object</code> value * @exception IllegalArgumentException if the supplied object is * not of the class of algorithms handled by this wrapper. */ void setWrappedAlgorithm(Object algorithm); /** * Get the algorithm * * @return an <code>Object</code> value */ Object getWrappedAlgorithm(); }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/beans/xml/XMLBeans.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * XMLBeans.java * Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand */ package weka.gui.beans.xml; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Point; import java.beans.BeanInfo; import java.beans.EventSetDescriptor; import java.beans.Introspector; import java.beans.beancontext.BeanContextSupport; import java.io.File; import java.util.Enumeration; import java.util.Hashtable; import java.util.StringTokenizer; import java.util.Vector; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.plaf.ColorUIResource; import javax.swing.plaf.FontUIResource; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import weka.core.Environment; import weka.core.EnvironmentHandler; import weka.core.WekaPackageClassLoaderManager; import weka.core.converters.ConverterUtils; import weka.core.xml.XMLBasicSerialization; import weka.core.xml.XMLDocument; import weka.gui.beans.BeanCommon; import weka.gui.beans.BeanConnection; import weka.gui.beans.BeanInstance; import weka.gui.beans.BeanVisual; import weka.gui.beans.MetaBean; import weka.gui.beans.Visible; /** * This class serializes and deserializes a KnowledgeFlow setup to and fro XML. <br> * * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class XMLBeans extends XMLBasicSerialization { /** the value of the id property */ public final static String VAL_ID = "id"; /** the value of the x property */ public final static String VAL_X = "x"; /** the value of the y property */ public final static String VAL_Y = "y"; /** the value of the bean property */ public final static String VAL_BEAN = "bean"; /** the value of the customName property */ public final static String VAL_CUSTOM_NAME = "custom_name"; /** the value of the source property */ public final static String VAL_SOURCEID = "source_id"; /** the value of the target property */ public final static String VAL_TARGETID = "target_id"; /** the value of the eventname property */ public final static String VAL_EVENTNAME = "eventname"; /** the value of the hidden property */ public final static String VAL_HIDDEN = "hidden"; /** the value of the file property */ public final static String VAL_FILE = "file"; /** the value of the dir property */ public final static String VAL_DIR = "dir"; /** the value of the prefix property */ public final static String VAL_PREFIX = "prefix"; public final static String VAL_RELATIVE_PATH = "useRelativePath"; /** the value of the options property */ public final static String VAL_OPTIONS = "options"; /** the value of the saver property */ public final static String VAL_SAVER = "wrappedAlgorithm"; /** the value of the loader property */ public final static String VAL_LOADER = "wrappedAlgorithm"; /** the value of the text property */ public final static String VAL_TEXT = "text"; /** the value of the beanContext property */ public final static String VAL_BEANCONTEXT = "beanContext"; /** the value of the width property */ public final static String VAL_WIDTH = "width"; /** the value of the height property */ public final static String VAL_HEIGHT = "height"; /** the value of the red property */ public final static String VAL_RED = "red"; /** the value of the green property */ public final static String VAL_GREEN = "green"; /** the value of the blue property */ public final static String VAL_BLUE = "blue"; /** the value of the value property */ public final static String VAL_NAME = "name"; /** the value of the style property */ public final static String VAL_STYLE = "style"; /** the value of the location property */ public final static String VAL_LOCATION = "location"; /** the value of the size property */ public final static String VAL_SIZE = "size"; /** the value of the color property */ public final static String VAL_COLOR = "color"; /** the value of the font property */ public final static String VAL_FONT = "font"; /** the value of the iconpath property */ public final static String VAL_ICONPATH = "iconPath"; /** the value of the animatedIconPath property */ public final static String VAL_ANIMATEDICONPATH = "animatedIconPath"; /** the value of the associatedConnections property */ public final static String VAL_ASSOCIATEDCONNECTIONS = "associatedConnections"; /** the value of the input property */ public final static String VAL_INPUTS = "inputs"; /** the value of the input id property */ public final static String VAL_INPUTSID = "inputs_id"; /** the value of the outputs id property */ public final static String VAL_OUTPUTS = "outputs"; /** the value of the outputs property */ public final static String VAL_OUTPUTSID = "outputs_id"; /** the value of the subFlow property */ public final static String VAL_SUBFLOW = "subFlow"; /** the value of the originalCoords property */ public final static String VAL_ORIGINALCOORDS = "originalCoords"; /** the value of the relationNameForFilename property (Saver) */ public final static String VAL_RELATIONNAMEFORFILENAME = "relationNameForFilename"; /** * the index in the Vector, where the BeanInstances are stored (Instances and * Connections are stored in a Vector and then serialized) */ public final static int INDEX_BEANINSTANCES = 0; /** * the index in the Vector, where the BeanConnections are stored (Instances * and Connections are stored in a Vector and then serialized) */ public final static int INDEX_BEANCONNECTIONS = 1; /** the component that manages the layout of the beans */ protected JComponent m_BeanLayout; /** keeps track of the BeanInstances read so far, used for the BeanConnections */ protected Vector<Object> m_BeanInstances; /** keeps track of the BeanInstances read so far, used for the BeanConnections */ protected Vector<Integer> m_BeanInstancesID; /** whether to ignore the BeanConnection */ protected boolean m_IgnoreBeanConnections; /** the current MetaBean (for the BeanConnections) */ protected MetaBean m_CurrentMetaBean; /** the identifier for regular BeanConnections */ protected final static String REGULAR_CONNECTION = "regular_connection"; /** * the relation between Bean and connection, MetaBean BeanConnections are * stored under the reference of the MetaBean, regular connections are stored * under REGULAR_CONNECTION. The relation has the following format (is a * string): sourcePos,targetPos,event,hidden * * @see #REGULAR_CONNECTION */ protected Hashtable<Object, Vector<String>> m_BeanConnectionRelation; /** * the data that is about to be read/written contains a complete layout * * @see #m_DataType */ public final static int DATATYPE_LAYOUT = 0; /** * the data that is about to be read/written contains user-components, i.e., * Metabeans * * @see #m_DataType */ public final static int DATATYPE_USERCOMPONENTS = 1; /** * the type of data that is be read/written * * @see #DATATYPE_LAYOUT * @see #DATATYPE_USERCOMPONENTS */ protected int m_DataType = DATATYPE_LAYOUT; /** * the beancontext to use for loading from XML and the beancontext is null in * the bean */ protected BeanContextSupport m_BeanContextSupport = null; /** * The index of the vector of bean instances or connections to use. this * corresponds to a tab in the main KnowledgeFlow UI */ protected int m_vectorIndex = 0; /** * initializes the serialization for layouts * * @param layout the component that manages the layout * @param context the bean context support to use * @param tab the index of the vector of bean instances or connections to use * (this corresponds to a visible tab in the main KnowledgeFlow UI) * @throws Exception if initialization fails */ public XMLBeans(JComponent layout, BeanContextSupport context, int tab) throws Exception { this(layout, context, DATATYPE_LAYOUT, tab); } /** * initializes the serialization for different types of data * * @param layout the component that manages the layout * @param context the bean context support to use * @param datatype the type of data to read/write * @throws Exception if initialization fails */ public XMLBeans(JComponent layout, BeanContextSupport context, int datatype, int tab) throws Exception { super(); m_vectorIndex = tab; m_BeanLayout = layout; m_BeanContextSupport = context; setDataType(datatype); } /** * sets what kind of data is to be read/written * * @param value the type of data * @see #m_DataType */ public void setDataType(int value) { if (value == DATATYPE_LAYOUT) { m_DataType = value; } else if (value == DATATYPE_USERCOMPONENTS) { m_DataType = value; } else { System.out.println("DataType '" + value + "' is unknown!"); } } /** * returns the type of data that is to be read/written * * @return the type of data * @see #m_DataType */ public int getDataType() { return m_DataType; } /** * generates internally a new XML document and clears also the IgnoreList and * the mappings for the Read/Write-Methods * * @throws Exception if something goes wrong */ @Override public void clear() throws Exception { Vector<String> classnames; int i; super.clear(); // ignore: suppress unnecessary GUI stuff // needs to be checked for new Java versions (might introduce new // properties) // - works with Java 1.5 m_Properties.addIgnored("UI"); m_Properties.addIgnored("actionMap"); m_Properties.addIgnored("alignmentX"); m_Properties.addIgnored("alignmentY"); m_Properties.addIgnored("autoscrolls"); m_Properties.addIgnored("background"); m_Properties.addIgnored("border"); m_Properties.addIgnored("componentPopupMenu"); m_Properties.addIgnored("debugGraphicsOptions"); m_Properties.addIgnored("doubleBuffered"); m_Properties.addIgnored("enabled"); m_Properties.addIgnored("focusCycleRoot"); m_Properties.addIgnored("focusTraversalPolicy"); m_Properties.addIgnored("focusTraversalPolicyProvider"); m_Properties.addIgnored("focusable"); m_Properties.addIgnored("font"); m_Properties.addIgnored("foreground"); m_Properties.addIgnored("inheritsPopupMenu"); m_Properties.addIgnored("inputVerifier"); m_Properties.addIgnored("layout"); m_Properties.addIgnored("locale"); m_Properties.addIgnored("maximumSize"); m_Properties.addIgnored("minimumSize"); m_Properties.addIgnored("nextFocusableComponent"); m_Properties.addIgnored("opaque"); m_Properties.addIgnored("preferredSize"); m_Properties.addIgnored("requestFocusEnabled"); m_Properties.addIgnored("toolTipText"); m_Properties.addIgnored("transferHandler"); m_Properties.addIgnored("verifyInputWhenFocusTarget"); m_Properties.addIgnored("visible"); // special ignore m_Properties.addIgnored("size"); // otherwise you get an endless loop with // Dimension! m_Properties.addIgnored("location"); // otherwise you get an endless loop // with Point! // allow m_Properties.addAllowed(weka.gui.beans.BeanInstance.class, "x"); m_Properties.addAllowed(weka.gui.beans.BeanInstance.class, "y"); m_Properties.addAllowed(weka.gui.beans.BeanInstance.class, "bean"); m_Properties.addAllowed(weka.gui.beans.Saver.class, "wrappedAlgorithm"); m_Properties.addAllowed(weka.gui.beans.Loader.class, "wrappedAlgorithm"); m_Properties.addAllowed(weka.gui.beans.Saver.class, "relationNameForFilename"); if (getDataType() == DATATYPE_LAYOUT) { m_Properties.addAllowed(weka.gui.beans.Loader.class, "beanContext"); } else { m_Properties.addIgnored(weka.gui.beans.Loader.class, "beanContext"); // TODO: // more // classes??? } m_Properties.addAllowed(weka.gui.beans.Filter.class, "filter"); m_Properties.addAllowed(weka.gui.beans.Associator.class, "associator"); m_Properties .addAllowed(weka.gui.beans.Classifier.class, "wrappedAlgorithm"); m_Properties.addAllowed(weka.gui.beans.Clusterer.class, "wrappedAlgorithm"); m_Properties.addAllowed(weka.gui.beans.Classifier.class, "executionSlots"); m_Properties.addAllowed(weka.gui.beans.Classifier.class, "blockOnLastFold"); m_Properties.addAllowed(weka.gui.beans.Classifier.class, "resetIncrementalClassifier"); m_Properties.addAllowed(weka.gui.beans.Classifier.class, "updateIncrementalClassifier"); m_Properties.addAllowed(weka.gui.beans.Classifier.class, "loadClassifierFileName"); m_Properties.addAllowed(weka.classifiers.Classifier.class, "debug"); m_Properties.addAllowed(weka.classifiers.Classifier.class, "options"); m_Properties.addAllowed(weka.associations.Associator.class, "options"); m_Properties.addAllowed(weka.clusterers.Clusterer.class, "options"); m_Properties.addAllowed(weka.filters.Filter.class, "options"); m_Properties.addAllowed(weka.core.converters.Saver.class, "options"); m_Properties.addAllowed(weka.core.converters.Loader.class, "options"); m_Properties .addAllowed(weka.core.converters.DatabaseSaver.class, "options"); m_Properties.addAllowed(weka.core.converters.DatabaseLoader.class, "options"); m_Properties.addAllowed(weka.core.converters.TextDirectoryLoader.class, "options"); // we assume that classes implementing SplitEvaluator also implement // OptionHandler m_Properties.addAllowed(weka.experiment.SplitEvaluator.class, "options"); // we assume that classes implementing ResultProducer also implement // OptionHandler m_Properties.addAllowed(weka.experiment.ResultProducer.class, "options"); // read/write methods m_CustomMethods.register(this, Color.class, "Color"); m_CustomMethods.register(this, Dimension.class, "Dimension"); m_CustomMethods.register(this, Font.class, "Font"); m_CustomMethods.register(this, Point.class, "Point"); m_CustomMethods.register(this, ColorUIResource.class, "ColorUIResource"); m_CustomMethods.register(this, FontUIResource.class, "FontUIResource"); m_CustomMethods.register(this, weka.gui.beans.BeanInstance.class, "BeanInstance"); m_CustomMethods.register(this, weka.gui.beans.BeanConnection.class, "BeanConnection"); m_CustomMethods.register(this, weka.gui.beans.BeanVisual.class, "BeanVisual"); m_CustomMethods.register(this, weka.gui.beans.Saver.class, "BeanSaver"); m_CustomMethods.register(this, weka.gui.beans.MetaBean.class, "MetaBean"); classnames = ConverterUtils.getFileLoaders(); for (i = 0; i < classnames.size(); i++) { m_CustomMethods .register(this, WekaPackageClassLoaderManager.forName(classnames.get(i)), "Loader"); } classnames = ConverterUtils.getFileSavers(); for (i = 0; i < classnames.size(); i++) { m_CustomMethods.register(this, WekaPackageClassLoaderManager.forName(classnames.get(i)), "Saver"); } // other variables m_BeanInstances = null; m_BeanInstancesID = null; m_CurrentMetaBean = null; m_IgnoreBeanConnections = true; m_BeanConnectionRelation = null; } /** * traverses over all BeanInstances (or MetaBeans) and stores them in a vector * (recurses into MetaBeans, since the sub-BeanInstances are not visible) * * @param list the BeanInstances/MetaBeans to traverse */ protected void addBeanInstances(Vector<Object> list) { int i; BeanInstance beaninst; for (i = 0; i < list.size(); i++) { if (list.get(i) instanceof BeanInstance) { beaninst = (BeanInstance) list.get(i); m_BeanInstancesID.add(new Integer(m_BeanInstances.size())); m_BeanInstances.add(beaninst); if (beaninst.getBean() instanceof MetaBean) { addBeanInstances(((MetaBean) beaninst.getBean()).getBeansInSubFlow()); } } else if (list.get(i) instanceof MetaBean) { addBeanInstances(((MetaBean) list.get(i)).getBeansInSubFlow()); } else { System.out .println("addBeanInstances does not support Vectors of class '" + list.get(i) + "'!"); } } } /** * enables derived classes to due some pre-processing on the objects, that's * about to be serialized. Right now it only returns the object. * * @param o the object that is serialized into XML * @return the possibly altered object * @throws Exception if post-processing fails */ @Override @SuppressWarnings("unchecked") protected Object writePreProcess(Object o) throws Exception { o = super.writePreProcess(o); // gather all BeanInstances, also the ones in MetaBeans m_BeanInstances = new Vector<Object>(); m_BeanInstancesID = new Vector<Integer>(); switch (getDataType()) { case DATATYPE_LAYOUT: addBeanInstances(BeanInstance.getBeanInstances(m_vectorIndex)); break; case DATATYPE_USERCOMPONENTS: addBeanInstances((Vector<Object>) o); break; default: System.out.println("writePreProcess: data type '" + getDataType() + "' is not recognized!"); break; } return o; } /** * enables derived classes to add other properties to the DOM tree, e.g. ones * that do not apply to the get/set convention of beans. only implemented with * empty method body. * * @param o the object that is serialized into XML * @throws Exception if post-processing fails */ @Override protected void writePostProcess(Object o) throws Exception { Element root; NodeList list; Element conns; Element child; int i; // since not all BeanConnections get saved to XML (e.g., MetaBeans in the // UserToolBar) if one saves a layout, the numbering in the Vector of the // BeanConnections is not correct. The "name" attribute of the nodes has // to be modified if (getDataType() == DATATYPE_LAYOUT) { root = m_Document.getDocument().getDocumentElement(); conns = (Element) root.getChildNodes().item(INDEX_BEANCONNECTIONS); list = conns.getChildNodes(); for (i = 0; i < list.getLength(); i++) { child = (Element) list.item(i); child.setAttribute(ATT_NAME, "" + i); } } } /** * additional pre-processing can happen in derived classes before the actual * reading from XML (working on the raw XML). right now it does nothing with * the document, only empties the help-vector for the BeanInstances and reads * the IDs for the BeanInstances, s.t. the correct references can be set again * * @param document the document to pre-process * @return the processed object * @throws Exception if post-processing fails * @see #m_BeanInstances */ @Override protected Document readPreProcess(Document document) throws Exception { NodeList list; int i; Element node; String clsName; Vector<Element> children; int id; int n; Element child; m_BeanInstances = new Vector<Object>(); m_BeanInstancesID = new Vector<Integer>(); // get all BeanInstance nodes list = document.getElementsByTagName("*"); clsName = BeanInstance.class.getName(); for (i = 0; i < list.getLength(); i++) { node = (Element) list.item(i); // is it a BeanInstance? if (node.getAttribute(ATT_CLASS).equals(clsName)) { children = XMLDocument.getChildTags(node); id = m_BeanInstancesID.size(); // get id-tag (if available) for (n = 0; n < children.size(); n++) { child = children.get(n); if (child.getAttribute(ATT_NAME).equals(VAL_ID)) { id = readIntFromXML(child); } } m_BeanInstancesID.add(new Integer(id)); } } m_BeanInstances.setSize(m_BeanInstancesID.size()); // set MetaBean to null m_CurrentMetaBean = null; // no BeanConnections -> see readPostProcess(Object) m_IgnoreBeanConnections = true; // reset BeanConnection-Relations m_BeanConnectionRelation = new Hashtable<Object, Vector<String>>(); return document; } /** * puts the given BeanConnection onto the next null in the given Vector, or at * the end of the list, if no null is found. (during the de-serializing, no * BeanConnections are set, only nulls) * * @param conn the connection to add to the list * @param list the list to add the BeanConnection to */ protected void setBeanConnection(BeanConnection conn, Vector<BeanConnection> list) { int i; boolean added; added = false; for (i = 0; i < list.size(); i++) { if (list.get(i) == null) { list.set(i, conn); added = true; break; } } if (!added) { list.add(conn); } } /** * generates a connection based on the given parameters * * @param sourcePos the source position in the m_BeanInstances vector * @param targetPos the target position in the m_BeanInstances vector * @param event the name of the event, i.e., the connection * @param hidden true if the connection is hidden * @return the generated BeanConnection * @throws Exception if something goes wrong */ protected BeanConnection createBeanConnection(int sourcePos, int targetPos, String event, boolean hidden) throws Exception { BeanConnection result; BeanInfo compInfo; EventSetDescriptor[] esds; int i; BeanInstance instSource; BeanInstance instTarget; result = null; // was there a connection? if ((sourcePos == -1) || (targetPos == -1)) { return result; } instSource = (BeanInstance) m_BeanInstances.get(sourcePos); instTarget = (BeanInstance) m_BeanInstances.get(targetPos); compInfo = Introspector.getBeanInfo(((BeanInstance) m_BeanInstances .get(sourcePos)).getBean().getClass()); esds = compInfo.getEventSetDescriptors(); for (i = 0; i < esds.length; i++) { if (esds[i].getName().equals(event)) { result = new BeanConnection(instSource, instTarget, esds[i], m_vectorIndex); result.setHidden(hidden); break; } } return result; } /** * rebuilds all the connections for a certain key in the hashtable. for the * ones being part of a MetaBean, no new instance is built, but only the * reference to the actual BeanConnection set. * * @param deserialized the deserialized knowledgeflow * @param key the key of the hashtable to rebuild all connections for * @throws Exception if something goes wrong */ @SuppressWarnings("unchecked") protected void rebuildBeanConnections(Vector<Vector<?>> deserialized, Object key) throws Exception { int i; int n; int sourcePos; int targetPos; String event; boolean hidden; Vector<String> conns; BeanConnection conn; StringTokenizer tok; Vector<BeanConnection> beanconns; conns = m_BeanConnectionRelation.get(key); // no connections? if (conns == null) { return; } for (n = 0; n < conns.size(); n++) { tok = new StringTokenizer(conns.get(n).toString(), ","); conn = null; sourcePos = Integer.parseInt(tok.nextToken()); targetPos = Integer.parseInt(tok.nextToken()); event = tok.nextToken(); hidden = stringToBoolean(tok.nextToken()); // regular connection? -> new instance // or MetaBean from user toolbar if ((!(key instanceof MetaBean)) || (getDataType() == DATATYPE_USERCOMPONENTS)) { conn = createBeanConnection(sourcePos, targetPos, event, hidden); } // MetaBean? -> find BeanConnection else { beanconns = BeanConnection.getConnections(m_vectorIndex); for (i = 0; i < beanconns.size(); i++) { conn = beanconns.get(i); if ((conn.getSource() == m_BeanInstances.get(sourcePos)) && (conn.getTarget() == m_BeanInstances.get(targetPos)) && (conn.getEventName().equals(event))) { break; } conn = null; } } // add the connection to the corresponding list/MetaBean if (key instanceof MetaBean) { setBeanConnection(conn, ((MetaBean) key).getAssociatedConnections()); } else { setBeanConnection(conn, (Vector<BeanConnection>) deserialized.get(INDEX_BEANCONNECTIONS)); } } } /** * removes the given meta beans from the layout, since they're only listed in * the user toolbar * * @param metabeans the list of MetaBeans in the user toolbar */ protected void removeUserToolBarBeans(Vector<?> metabeans) { int i; int n; MetaBean meta; Vector<Object> subflow; BeanInstance beaninst; for (i = 0; i < metabeans.size(); i++) { meta = (MetaBean) metabeans.get(i); subflow = meta.getSubFlow(); for (n = 0; n < subflow.size(); n++) { beaninst = (BeanInstance) subflow.get(n); beaninst.removeBean(m_BeanLayout); } } } /** * additional post-processing can happen in derived classes after reading from * XML. re-builds the BeanConnections. * * @param o the object to perform some additional processing on * @return the processed object * @throws Exception if post-processing fails */ @SuppressWarnings("unchecked") @Override protected Object readPostProcess(Object o) throws Exception { Enumeration<Object> enm; Vector<Vector<?>> deserialized; Object key; deserialized = (Vector<Vector<?>>) super.readPostProcess(o); // rebuild the actual connections rebuildBeanConnections(deserialized, REGULAR_CONNECTION); // rebuild the references in the MetaBeans enm = m_BeanConnectionRelation.keys(); while (enm.hasMoreElements()) { key = enm.nextElement(); // skip the regular connections if (!(key instanceof MetaBean)) { continue; } rebuildBeanConnections(deserialized, key); } // remove MetaBean and subflow from BeanInstance (not part of the flow!) if (getDataType() == DATATYPE_USERCOMPONENTS) { removeUserToolBarBeans(deserialized); } return deserialized; } /** * returns the relation for the given MetaBean, for the regular connections, * null has to be used * * @param meta the MetaBean (or null for regular connections) to retrieve the * connections for * @return the associated connections * @see #REGULAR_CONNECTION */ protected Vector<String> getBeanConnectionRelation(MetaBean meta) { Vector<String> result; Object key; if (meta == null) { key = REGULAR_CONNECTION; } else { key = meta; } // not yet in there? if (!m_BeanConnectionRelation.containsKey(key)) { m_BeanConnectionRelation.put(key, new Vector<String>()); } result = m_BeanConnectionRelation.get(key); return result; } /** * adds the given connection-relation for the specified MetaBean (or null in * case of regular connections) * * @param meta the MetaBean (or null for regular connections) to add the * relationship for * @param connection the connection relation to add */ protected void addBeanConnectionRelation(MetaBean meta, String connection) { Vector<String> relations; Object key; relations = getBeanConnectionRelation(meta); // add relation relations.add(connection); // update if (meta == null) { key = REGULAR_CONNECTION; } else { key = meta; } m_BeanConnectionRelation.put(key, relations); } /** * adds the given Color to a DOM structure. * * @param parent the parent of this object, e.g. the class this object is a * member of * @param o the Object to describe in XML * @param name the name of the object * @return the node that was created * @throws Exception if the DOM creation fails */ public Element writeColor(Element parent, Object o, String name) throws Exception { Element node; Color color; // for debugging only if (DEBUG) { trace(new Throwable(), name); } m_CurrentNode = parent; color = (Color) o; node = addElement(parent, name, color.getClass().getName(), false); writeIntToXML(node, color.getRed(), VAL_RED); writeIntToXML(node, color.getGreen(), VAL_GREEN); writeIntToXML(node, color.getBlue(), VAL_BLUE); return node; } /** * builds the Color from the given DOM node. * * @param node the associated XML node * @return the instance created from the XML description * @throws Exception if instantiation fails */ public Object readColor(Element node) throws Exception { Object result; Vector<Element> children; Element child; int i; int red; int green; int blue; String name; // for debugging only if (DEBUG) { trace(new Throwable(), node.getAttribute(ATT_NAME)); } m_CurrentNode = node; result = null; children = XMLDocument.getChildTags(node); red = 0; green = 0; blue = 0; for (i = 0; i < children.size(); i++) { child = children.get(i); name = child.getAttribute(ATT_NAME); if (name.equals(VAL_RED)) { red = readIntFromXML(child); } else if (name.equals(VAL_GREEN)) { green = readIntFromXML(child); } else if (name.equals(VAL_BLUE)) { blue = readIntFromXML(child); } else { System.out.println("WARNING: '" + name + "' is not a recognized name for " + node.getAttribute(ATT_NAME) + "!"); } } result = new Color(red, green, blue); return result; } /** * adds the given Dimension to a DOM structure. * * @param parent the parent of this object, e.g. the class this object is a * member of * @param o the Object to describe in XML * @param name the name of the object * @return the node that was created * @throws Exception if the DOM creation fails */ public Element writeDimension(Element parent, Object o, String name) throws Exception { Element node; Dimension dim; // for debugging only if (DEBUG) { trace(new Throwable(), name); } m_CurrentNode = parent; dim = (Dimension) o; node = addElement(parent, name, dim.getClass().getName(), false); writeDoubleToXML(node, dim.getWidth(), VAL_WIDTH); writeDoubleToXML(node, dim.getHeight(), VAL_HEIGHT); return node; } /** * builds the Dimension from the given DOM node. * * @param node the associated XML node * @return the instance created from the XML description * @throws Exception if instantiation fails */ public Object readDimension(Element node) throws Exception { Object result; Vector<Element> children; Element child; int i; double width; double height; String name; // for debugging only if (DEBUG) { trace(new Throwable(), node.getAttribute(ATT_NAME)); } m_CurrentNode = node; result = null; children = XMLDocument.getChildTags(node); width = 0; height = 0; for (i = 0; i < children.size(); i++) { child = children.get(i); name = child.getAttribute(ATT_NAME); if (name.equals(VAL_WIDTH)) { width = readDoubleFromXML(child); } else if (name.equals(VAL_HEIGHT)) { height = readDoubleFromXML(child); } else { System.out.println("WARNING: '" + name + "' is not a recognized name for " + node.getAttribute(ATT_NAME) + "!"); } } result = new Dimension(); ((Dimension) result).setSize(width, height); return result; } /** * adds the given Font to a DOM structure. * * @param parent the parent of this object, e.g. the class this object is a * member of * @param o the Object to describe in XML * @param name the name of the object * @return the node that was created * @throws Exception if the DOM creation fails */ public Element writeFont(Element parent, Object o, String name) throws Exception { Element node; Font font; // for debugging only if (DEBUG) { trace(new Throwable(), name); } m_CurrentNode = parent; font = (Font) o; node = addElement(parent, name, font.getClass().getName(), false); invokeWriteToXML(node, font.getName(), VAL_NAME); writeIntToXML(node, font.getStyle(), VAL_STYLE); writeIntToXML(node, font.getSize(), VAL_SIZE); return node; } /** * builds the Font from the given DOM node. * * @param node the associated XML node * @return the instance created from the XML description * @throws Exception if instantiation fails */ public Object readFont(Element node) throws Exception { Object result; Vector<Element> children; Element child; int i; int style; int size; String name; String fontname; // for debugging only if (DEBUG) { trace(new Throwable(), node.getAttribute(ATT_NAME)); } m_CurrentNode = node; result = null; children = XMLDocument.getChildTags(node); fontname = ""; style = 0; size = 0; for (i = 0; i < children.size(); i++) { child = children.get(i); name = child.getAttribute(ATT_NAME); if (name.equals(VAL_NAME)) { name = (String) invokeReadFromXML(child); } else if (name.equals(VAL_STYLE)) { style = readIntFromXML(child); } else if (name.equals(VAL_SIZE)) { size = readIntFromXML(child); } else { System.out.println("WARNING: '" + name + "' is not a recognized name for " + node.getAttribute(ATT_NAME) + "!"); } } result = new Font(fontname, style, size); return result; } /** * adds the given Point to a DOM structure. * * @param parent the parent of this object, e.g. the class this object is a * member of * @param o the Object to describe in XML * @param name the name of the object * @return the node that was created * @throws Exception if the DOM creation fails */ public Element writePoint(Element parent, Object o, String name) throws Exception { Element node; Point p; // for debugging only if (DEBUG) { trace(new Throwable(), name); } m_CurrentNode = parent; p = (Point) o; node = addElement(parent, name, p.getClass().getName(), false); writeDoubleToXML(node, p.getX(), VAL_X); writeDoubleToXML(node, p.getY(), VAL_Y); return node; } /** * builds the Point from the given DOM node. * * @param node the associated XML node * @return the instance created from the XML description * @throws Exception if instantiation fails */ public Object readPoint(Element node) throws Exception { Object result; Vector<Element> children; Element child; int i; double x; double y; String name; // for debugging only if (DEBUG) { trace(new Throwable(), node.getAttribute(ATT_NAME)); } m_CurrentNode = node; result = null; children = XMLDocument.getChildTags(node); x = 0; y = 0; for (i = 0; i < children.size(); i++) { child = children.get(i); name = child.getAttribute(ATT_NAME); if (name.equals(VAL_X)) { x = readDoubleFromXML(child); } else if (name.equals(VAL_Y)) { y = readDoubleFromXML(child); } else { System.out.println("WARNING: '" + name + "' is not a recognized name for " + node.getAttribute(ATT_NAME) + "!"); } } result = new Point(); ((Point) result).setLocation(x, y); return result; } /** * adds the given ColorUIResource to a DOM structure. * * @param parent the parent of this object, e.g. the class this object is a * member of * @param o the Object to describe in XML * @param name the name of the object * @return the node that was created * @throws Exception if the DOM creation fails */ public Element writeColorUIResource(Element parent, Object o, String name) throws Exception { Element node; ColorUIResource resource; // for debugging only if (DEBUG) { trace(new Throwable(), name); } m_CurrentNode = parent; resource = (ColorUIResource) o; node = addElement(parent, name, resource.getClass().getName(), false); invokeWriteToXML(node, new Color(resource.getRGB()), VAL_COLOR); return node; } /** * builds the ColorUIResource from the given DOM node. * * @param node the associated XML node * @return the instance created from the XML description * @throws Exception if instantiation fails */ public Object readColorUIResource(Element node) throws Exception { Object result; Vector<Element> children; Element child; int i; String name; Color color; // for debugging only if (DEBUG) { trace(new Throwable(), node.getAttribute(ATT_NAME)); } m_CurrentNode = node; result = null; children = XMLDocument.getChildTags(node); color = null; for (i = 0; i < children.size(); i++) { child = children.get(i); name = child.getAttribute(ATT_NAME); if (name.equals(VAL_COLOR)) { color = (Color) invokeReadFromXML(child); } else { System.out.println("WARNING: '" + name + "' is not a recognized name for " + node.getAttribute(ATT_NAME) + "!"); } } result = new ColorUIResource(color); return result; } /** * adds the given FontUIResource to a DOM structure. * * @param parent the parent of this object, e.g. the class this object is a * member of * @param o the Object to describe in XML * @param name the name of the object * @return the node that was created * @throws Exception if the DOM creation fails */ public Element writeFontUIResource(Element parent, Object o, String name) throws Exception { Element node; FontUIResource resource; // for debugging only if (DEBUG) { trace(new Throwable(), name); } m_CurrentNode = parent; resource = (FontUIResource) o; node = addElement(parent, name, resource.getClass().getName(), false); invokeWriteToXML(node, new Font(resource.getName(), resource.getStyle(), resource.getSize()), VAL_COLOR); return node; } /** * builds the FontUIResource from the given DOM node. * * @param node the associated XML node * @return the instance created from the XML description * @throws Exception if instantiation fails */ public Object readFontUIResource(Element node) throws Exception { Object result; Vector<Element> children; Element child; int i; String name; Font font; // for debugging only if (DEBUG) { trace(new Throwable(), node.getAttribute(ATT_NAME)); } m_CurrentNode = node; result = null; children = XMLDocument.getChildTags(node); font = null; for (i = 0; i < children.size(); i++) { child = children.get(i); name = child.getAttribute(ATT_NAME); if (name.equals(VAL_FONT)) { font = (Font) invokeReadFromXML(child); } else { System.out.println("WARNING: '" + name + "' is not a recognized name for " + node.getAttribute(ATT_NAME) + "!"); } } result = new FontUIResource(font); return result; } /** * adds the given BeanInstance to a DOM structure. * * @param parent the parent of this object, e.g. the class this object is a * member of * @param o the Object to describe in XML * @param name the name of the object * @return the node that was created * @throws Exception if the DOM creation fails */ public Element writeBeanInstance(Element parent, Object o, String name) throws Exception { Element node; BeanInstance beaninst; // for debugging only if (DEBUG) { trace(new Throwable(), name); } m_CurrentNode = parent; beaninst = (BeanInstance) o; node = addElement(parent, name, beaninst.getClass().getName(), false); writeIntToXML(node, m_BeanInstances.indexOf(beaninst), VAL_ID); int w = beaninst.getWidth() / 2; int h = beaninst.getHeight() / 2; // If a bean instance doesn't have dimensions (0 widht/height) then it means // that it hasn't been rendered (yet). In this case we'll // use half the known width/height of the icons so that the // position does not change if (w == 0 && h == 0) { w = 28; h = 28; } writeIntToXML(node, beaninst.getX() + w, VAL_X); // x is thought to be in // the center? writeIntToXML(node, beaninst.getY() + h, VAL_Y); // y is thought to be in // the center? if (beaninst.getBean() instanceof BeanCommon) { // write the custom name of this bean String custName = ((BeanCommon) beaninst.getBean()).getCustomName(); invokeWriteToXML(node, custName, VAL_CUSTOM_NAME); } invokeWriteToXML(node, beaninst.getBean(), VAL_BEAN); return node; } /** * builds the BeanInstance from the given DOM node. * * @param node the associated XML node * @return the instance created from the XML description * @throws Exception if instantiation fails */ public Object readBeanInstance(Element node) throws Exception { Object result; Vector<Element> children; Element child; String name; int i; int x; int y; int id; Object bean; BeanVisual visual; BeanInstance beaninst; // for debugging only if (DEBUG) { trace(new Throwable(), node.getAttribute(ATT_NAME)); } m_CurrentNode = node; result = null; children = XMLDocument.getChildTags(node); id = -1; x = 0; y = 0; bean = null; String customName = null; for (i = 0; i < children.size(); i++) { child = children.get(i); name = child.getAttribute(ATT_NAME); if (name.equals(VAL_ID)) { id = readIntFromXML(child); } else if (name.equals(VAL_X)) { x = readIntFromXML(child); } else if (name.equals(VAL_Y)) { y = readIntFromXML(child); } else if (name.equals(VAL_CUSTOM_NAME)) { customName = (String) invokeReadFromXML(child); } else if (name.equals(VAL_BEAN)) { bean = invokeReadFromXML(child); } else { System.out.println("WARNING: '" + name + "' is not a recognized name for " + node.getAttribute(ATT_NAME) + "!"); } } result = new BeanInstance(m_BeanLayout, bean, x, y, m_vectorIndex); beaninst = (BeanInstance) result; // set parent of BeanVisual if (beaninst.getBean() instanceof weka.gui.beans.Visible) { visual = ((Visible) beaninst.getBean()).getVisual(); visual.setSize(visual.getPreferredSize()); if (visual.getParent() == null) { ((JPanel) beaninst.getBean()).add(visual); } } if (beaninst.getBean() instanceof BeanCommon && customName != null) { ((BeanCommon) beaninst.getBean()).setCustomName(customName); } // no IDs -> get next null position if (id == -1) { for (i = 0; i < m_BeanInstances.size(); i++) { if (m_BeanInstances.get(i) == null) { id = m_BeanInstancesID.get(i).intValue(); break; } } } // get position for id i = m_BeanInstancesID.indexOf(new Integer(id)); // keep track of the BeanInstances for reading the connections later on m_BeanInstances.set(i, result); // no current MetaBean m_CurrentMetaBean = null; return result; } /** * adds the given BeanConncetion to a DOM structure. * * @param parent the parent of this object, e.g. the class this object is a * member of * @param o the Object to describe in XML * @param name the name of the object * @return the node that was created * @throws Exception if the DOM creation fails */ public Element writeBeanConnection(Element parent, Object o, String name) throws Exception { Element node; BeanConnection beanconn; int source; int target; int sourcePos; int targetPos; // for debugging only if (DEBUG) { trace(new Throwable(), name); } m_CurrentNode = parent; beanconn = (BeanConnection) o; node = null; // get position sourcePos = m_BeanInstances.indexOf(beanconn.getSource()); targetPos = m_BeanInstances.indexOf(beanconn.getTarget()); // get id (if Connection is from a Bean in the UserToolBar, it's not listed! // -> ignore it) if ((sourcePos > -1) && (targetPos > -1)) { source = m_BeanInstancesID.get(sourcePos).intValue(); target = m_BeanInstancesID.get(targetPos).intValue(); } else { source = -1; target = -1; } // connection exists in the layout? if ((source > -1) && (target > -1)) { node = addElement(parent, name, beanconn.getClass().getName(), false); writeIntToXML(node, source, VAL_SOURCEID); writeIntToXML(node, target, VAL_TARGETID); invokeWriteToXML(node, beanconn.getEventName(), VAL_EVENTNAME); writeBooleanToXML(node, beanconn.isHidden(), VAL_HIDDEN); } return node; } /** * builds the BeanConnection from the given DOM node. * * @param node the associated XML node * @return the instance created from the XML description * @throws Exception if instantiation fails */ public Object readBeanConnection(Element node) throws Exception { Object result; Vector<Element> children; Element child; String name; int i; int source; int target; int sourcePos; int targetPos; String event; boolean hidden; // for debugging only if (DEBUG) { trace(new Throwable(), node.getAttribute(ATT_NAME)); } m_CurrentNode = node; result = null; children = XMLDocument.getChildTags(node); source = 0; target = 0; event = ""; hidden = false; for (i = 0; i < children.size(); i++) { child = children.get(i); name = child.getAttribute(ATT_NAME); if (name.equals(VAL_SOURCEID)) { source = readIntFromXML(child); } else if (name.equals(VAL_TARGETID)) { target = readIntFromXML(child); } else if (name.equals(VAL_EVENTNAME)) { event = (String) invokeReadFromXML(child); } else if (name.equals(VAL_HIDDEN)) { hidden = readBooleanFromXML(child); } else { System.out.println("WARNING: '" + name + "' is not a recognized name for " + node.getAttribute(ATT_NAME) + "!"); } } // get position of id sourcePos = m_BeanInstancesID.indexOf(new Integer(source)); targetPos = m_BeanInstancesID.indexOf(new Integer(target)); // do we currently ignore the connections? // Note: necessary because of the MetaBeans if (m_IgnoreBeanConnections) { addBeanConnectionRelation(m_CurrentMetaBean, sourcePos + "," + targetPos + "," + event + "," + hidden); return result; } // generate it normally result = createBeanConnection(sourcePos, targetPos, event, hidden); return result; } /** * adds the given Loader (a bean) to a DOM structure. * * @param parent the parent of this object, e.g. the class this object is a * member of * @param o the Object to describe in XML * @param name the name of the object * @return the node that was created * @throws Exception if the DOM creation fails */ public Element writeBeanLoader(Element parent, Object o, String name) throws Exception { Element node; weka.gui.beans.Loader loader; // for debugging only if (DEBUG) { trace(new Throwable(), name); } m_CurrentNode = parent; loader = (weka.gui.beans.Loader) o; node = addElement(parent, name, loader.getClass().getName(), false); invokeWriteToXML(node, loader.getLoader(), VAL_LOADER); invokeWriteToXML(node, loader.getBeanContext(), VAL_BEANCONTEXT); return node; } /** * adds the given Saver (a bean) to a DOM structure. * * @param parent the parent of this object, e.g. the class this object is a * member of * @param o the Object to describe in XML * @param name the name of the object * @return the node that was created * @throws Exception if the DOM creation fails */ public Element writeBeanSaver(Element parent, Object o, String name) throws Exception { Element node; weka.gui.beans.Saver saver; // for debugging only if (DEBUG) { trace(new Throwable(), name); } m_CurrentNode = parent; saver = (weka.gui.beans.Saver) o; node = addElement(parent, name, saver.getClass().getName(), false); invokeWriteToXML(node, saver.getRelationNameForFilename(), VAL_RELATIONNAMEFORFILENAME); invokeWriteToXML(node, saver.getSaverTemplate(), VAL_SAVER); return node; } /** * adds the given Loader to a DOM structure. * * @param parent the parent of this object, e.g. the class this object is a * member of * @param o the Object to describe in XML * @param name the name of the object * @return the node that was created * @throws Exception if the DOM creation fails */ public Element writeLoader(Element parent, Object o, String name) throws Exception { Element node; weka.core.converters.Loader loader; File file; boolean known; // for debugging only if (DEBUG) { trace(new Throwable(), name); } m_CurrentNode = parent; loader = (weka.core.converters.Loader) o; node = addElement(parent, name, loader.getClass().getName(), false); known = true; file = null; // file if (loader instanceof weka.core.converters.AbstractFileLoader) { file = ((weka.core.converters.AbstractFileLoader) loader).retrieveFile(); } else { known = false; } if (!known) { System.out.println("WARNING: unknown loader class '" + loader.getClass().getName() + "' - cannot retrieve file!"); } Boolean relativeB = null; if (loader instanceof weka.core.converters.FileSourcedConverter) { boolean relative = ((weka.core.converters.FileSourcedConverter) loader) .getUseRelativePath(); relativeB = new Boolean(relative); } // only save it, if it's a real file! if ((file == null) || (file.isDirectory())) { invokeWriteToXML(node, "", VAL_FILE); } else { String withResourceSeparators = file.getPath().replace( File.pathSeparatorChar, '/'); boolean notAbsolute = (((weka.core.converters.AbstractFileLoader) loader) .getUseRelativePath() || (loader instanceof EnvironmentHandler && Environment .containsEnvVariables(file.getPath())) || this.getClass().getClassLoader().getResource(withResourceSeparators) != null || !file .exists()); String path = (notAbsolute) ? file.getPath() : file.getAbsolutePath(); // Replace any windows file separators with forward slashes (Java under // windows can // read paths with forward slashes (apparantly) path = path.replace('\\', '/'); invokeWriteToXML(node, path, VAL_FILE); } if (relativeB != null) { invokeWriteToXML(node, relativeB.toString(), VAL_RELATIVE_PATH); } if (loader instanceof weka.core.OptionHandler) { String[] opts = ((weka.core.OptionHandler) loader).getOptions(); invokeWriteToXML(node, opts, VAL_OPTIONS); } return node; } /** * builds the Loader from the given DOM node. * * @param node the associated XML node * @return the instance created from the XML description * @throws Exception if instantiation fails */ public Object readLoader(Element node) throws Exception { Object result; Vector<Element> children; Element child; int i; String name; String file; File fl; // for debugging only if (DEBUG) { trace(new Throwable(), node.getAttribute(ATT_NAME)); } m_CurrentNode = node; result = Class.forName(node.getAttribute(ATT_CLASS)).newInstance(); children = XMLDocument.getChildTags(node); file = ""; Object relativeB = null; boolean relative = false; for (i = 0; i < children.size(); i++) { child = children.get(i); name = child.getAttribute(ATT_NAME); if (name.equals(VAL_FILE)) { file = (String) invokeReadFromXML(child); } else if (name.equals(VAL_RELATIVE_PATH)) { relativeB = readFromXML(child); if (relativeB instanceof Boolean) { relative = ((Boolean) relativeB).booleanValue(); } } else { readFromXML(result, name, child); } } if (result instanceof weka.core.converters.FileSourcedConverter) { ((weka.core.converters.FileSourcedConverter) result) .setUseRelativePath(relative); } if (file.equals("")) { file = null; } // set file only, if it exists if (file != null) { String tempFile = file; boolean containsEnv = false; containsEnv = Environment.containsEnvVariables(file); fl = new File(file); // only test for existence if the path does not contain environment vars // (trust that after they are resolved that everything is hunky dory). // Also // don't test if the file can be found as a resource in the classath if (containsEnv || fl.exists() || this.getClass().getClassLoader().getResource(file) != null) { ((weka.core.converters.AbstractFileLoader) result).setSource(new File( file)); } else { System.out.println("WARNING: The file '" + tempFile + "' does not exist!"); } } return result; } /** * adds the given Saver to a DOM structure. * * @param parent the parent of this object, e.g. the class this object is a * member of * @param o the Object to describe in XML * @param name the name of the object * @return the node that was created * @throws Exception if the DOM creation fails */ public Element writeSaver(Element parent, Object o, String name) throws Exception { Element node; weka.core.converters.Saver saver; String prefix; String dir; boolean known; // for debugging only if (DEBUG) { trace(new Throwable(), name); } m_CurrentNode = parent; saver = (weka.core.converters.Saver) o; node = addElement(parent, name, saver.getClass().getName(), false); known = true; prefix = ""; dir = ""; // file if (saver instanceof weka.core.converters.AbstractFileSaver) { ((weka.core.converters.AbstractFileSaver) saver).retrieveFile(); prefix = ((weka.core.converters.AbstractFileSaver) saver).filePrefix(); dir = ((weka.core.converters.AbstractFileSaver) saver).retrieveDir(); // Replace any windows file separators with forward slashes (Java under // windows can // read paths with forward slashes (apparantly) dir = dir.replace('\\', '/'); } else { known = false; } if (!known) { System.out.println("WARNING: unknown saver class '" + saver.getClass().getName() + "' - cannot retrieve file!"); } Boolean relativeB = null; if (saver instanceof weka.core.converters.FileSourcedConverter) { boolean relative = ((weka.core.converters.FileSourcedConverter) saver) .getUseRelativePath(); relativeB = new Boolean(relative); } // if ( (file == null) || (file.isDirectory()) ) { invokeWriteToXML(node, "", VAL_FILE); invokeWriteToXML(node, dir, VAL_DIR); invokeWriteToXML(node, prefix, VAL_PREFIX); /* * } else { String path = (((weka.core.converters.FileSourcedConverter) * saver).getUseRelativePath()) ? file.getPath() : file.getAbsolutePath(); * // Replace any windows file separators with forward slashes (Java under * windows can // read paths with forward slashes (apparantly) path = * path.replace('\\', '/'); invokeWriteToXML(node, path, VAL_FILE); * invokeWriteToXML(node, dir, VAL_DIR); invokeWriteToXML(node, prefix, * VAL_PREFIX); } */ if (relativeB != null) { invokeWriteToXML(node, relativeB.toString(), VAL_RELATIVE_PATH); } if (saver instanceof weka.core.OptionHandler) { String[] opts = ((weka.core.OptionHandler) saver).getOptions(); invokeWriteToXML(node, opts, VAL_OPTIONS); } return node; } /** * builds the Saver from the given DOM node. * * @param node the associated XML node * @return the instance created from the XML description * @throws Exception if instantiation fails */ public Object readSaver(Element node) throws Exception { Object result; Vector<Element> children; Element child; int i; String name; String file; String dir; String prefix; // for debugging only if (DEBUG) { trace(new Throwable(), node.getAttribute(ATT_NAME)); } m_CurrentNode = node; result = Class.forName(node.getAttribute(ATT_CLASS)).newInstance(); children = XMLDocument.getChildTags(node); file = null; dir = null; prefix = null; Object relativeB = null; boolean relative = false; for (i = 0; i < children.size(); i++) { child = children.get(i); name = child.getAttribute(ATT_NAME); if (name.equals(VAL_FILE)) { file = (String) invokeReadFromXML(child); } else if (name.equals(VAL_DIR)) { dir = (String) invokeReadFromXML(child); } else if (name.equals(VAL_PREFIX)) { prefix = (String) invokeReadFromXML(child); } else if (name.equals(VAL_RELATIVE_PATH)) { relativeB = readFromXML(child); if (relativeB instanceof Boolean) { relative = ((Boolean) relativeB).booleanValue(); } } else { readFromXML(result, name, child); } } if ((file != null) && (file.length() == 0)) { file = null; } // savers only get directory and prefix, not file (KnowledgeFlow sets the // file/destination based on the relation, dir and prefix) if ((dir != null) && (prefix != null)) { ((weka.core.converters.AbstractFileSaver) result).setDir(dir); ((weka.core.converters.AbstractFileSaver) result).setFilePrefix(prefix); } if (result instanceof weka.core.converters.FileSourcedConverter) { ((weka.core.converters.FileSourcedConverter) result) .setUseRelativePath(relative); } return result; } /** * adds the given BeanVisual to a DOM structure. * * @param parent the parent of this object, e.g. the class this object is a * member of * @param o the Object to describe in XML * @param name the name of the object * @return the node that was created * @throws Exception if the DOM creation fails */ public Element writeBeanVisual(Element parent, Object o, String name) throws Exception { Element node; BeanVisual visual; // for debugging only if (DEBUG) { trace(new Throwable(), name); } m_CurrentNode = parent; visual = (BeanVisual) o; node = writeToXML(parent, o, name); // add icon paths invokeWriteToXML(node, visual.getIconPath(), VAL_ICONPATH); invokeWriteToXML(node, visual.getAnimatedIconPath(), VAL_ANIMATEDICONPATH); return node; } /** * builds the BeanVisual from the given DOM node. * * @param node the associated XML node * @return the instance created from the XML description * @throws Exception if instantiation fails */ public Object readBeanVisual(Element node) throws Exception { Object result; Vector<Element> children; Element child; int i; String name; String text; String iconPath; String animIconPath; // for debugging only if (DEBUG) { trace(new Throwable(), node.getAttribute(ATT_NAME)); } m_CurrentNode = node; result = null; children = XMLDocument.getChildTags(node); text = ""; iconPath = ""; animIconPath = ""; // find text for (i = 0; i < children.size(); i++) { child = children.get(i); name = child.getAttribute(ATT_NAME); if (name.equals(VAL_TEXT)) { text = (String) invokeReadFromXML(child); } else if (name.equals(VAL_ICONPATH)) { iconPath = (String) invokeReadFromXML(child); } else if (name.equals(VAL_ANIMATEDICONPATH)) { animIconPath = (String) invokeReadFromXML(child); } } result = new BeanVisual(text, iconPath, animIconPath); // set rest of properties for (i = 0; i < children.size(); i++) { readFromXML(result, node.getAttribute(ATT_NAME), children.get(i)); } return result; } /** * returns the IDs for the given BeanInstances, i.e., the stored IDs in * m_BeanInstancesID, based on m_BeanInstances * * @param beans the beans to retrieve the IDs for * @return the IDs for the given BeanInstances * @see #m_BeanInstances * @see #m_BeanInstancesID */ protected Vector<Integer> getIDsForBeanInstances(Vector<Object> beans) { Vector<Integer> result; int i; int pos; result = new Vector<Integer>(); for (i = 0; i < beans.size(); i++) { pos = m_BeanInstances.indexOf(beans.get(i)); result.add(m_BeanInstancesID.get(pos)); } return result; } /** * adds the given MetaBean to a DOM structure. * * @param parent the parent of this object, e.g. the class this object is a * member of * @param o the Object to describe in XML * @param name the name of the object * @return the node that was created * @throws Exception if the DOM creation fails */ public Element writeMetaBean(Element parent, Object o, String name) throws Exception { Element node; MetaBean meta; // for debugging only if (DEBUG) { trace(new Throwable(), name); } m_CurrentNode = parent; meta = (MetaBean) o; node = writeToXML(parent, o, name); invokeWriteToXML(node, getIDsForBeanInstances(meta.getBeansInInputs()), VAL_INPUTSID); invokeWriteToXML(node, getIDsForBeanInstances(meta.getBeansInOutputs()), VAL_OUTPUTSID); return node; } /** * returns a vector with references to BeanInstances according to the IDs in * the given Vector. * * @param ids contains the IDs of the BeanInstances * @return the corresponding BeanInstances * @see #m_BeanInstances * @see #m_BeanInstancesID */ protected Vector<Object> getBeanInstancesForIDs(Vector<Integer> ids) { Vector<Object> result; int i; int pos; result = new Vector<Object>(); for (i = 0; i < ids.size(); i++) { pos = m_BeanInstancesID.indexOf(ids.get(i)); result.add(m_BeanInstances.get(pos)); } return result; } /** * builds the MetaBean from the given DOM node. * * @param node the associated XML node * @return the instance created from the XML description * @throws Exception if instantiation fails */ @SuppressWarnings("unchecked") public Object readMetaBean(Element node) throws Exception { Object result; Vector<Element> children; Element child; int i; String name; Vector<Integer> inputs; Vector<Integer> outputs; Vector<Point> coords; MetaBean bean; // for debugging only if (DEBUG) { trace(new Throwable(), node.getAttribute(ATT_NAME)); } m_CurrentNode = node; result = new MetaBean(); children = XMLDocument.getChildTags(node); inputs = new Vector<Integer>(); outputs = new Vector<Integer>(); coords = new Vector<Point>(); // the current MetaBean m_CurrentMetaBean = (MetaBean) result; for (i = 0; i < children.size(); i++) { child = children.get(i); name = child.getAttribute(ATT_NAME); if (name.equals(VAL_ASSOCIATEDCONNECTIONS)) { ((MetaBean) result) .setAssociatedConnections((Vector<BeanConnection>) invokeReadFromXML(child)); } else if (name.equals(VAL_INPUTSID)) { inputs = (Vector<Integer>) invokeReadFromXML(child); } else if (name.equals(VAL_OUTPUTSID)) { outputs = (Vector<Integer>) invokeReadFromXML(child); } else if (name.equals(VAL_SUBFLOW)) { ((MetaBean) result) .setSubFlow((Vector<Object>) invokeReadFromXML(child)); } else if (name.equals(VAL_ORIGINALCOORDS)) { coords = (Vector<Point>) invokeReadFromXML(child); } else if (name.equals(VAL_INPUTS)) { System.out.println("INFO: '" + name + "' will be restored later."); } else if (name.equals(VAL_OUTPUTS)) { System.out.println("INFO: '" + name + "' will be restored later."); } else { readFromXML(result, name, child); } } bean = (MetaBean) result; // set inputs and outputs, after the beans have been instantiated bean.setInputs(getBeanInstancesForIDs(inputs)); bean.setOutputs(getBeanInstancesForIDs(outputs)); bean.setOriginalCoords(coords); return result; } }
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/boundaryvisualizer/BoundaryPanel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * BoundaryPanel.java * Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.boundaryvisualizer; 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.RenderingHints; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.ObjectInputStream; import java.util.ArrayList; import java.util.Iterator; import java.util.Locale; import java.util.Random; import java.util.Vector; import javax.imageio.IIOImage; import javax.imageio.ImageIO; import javax.imageio.ImageWriteParam; import javax.imageio.ImageWriter; import javax.imageio.plugins.jpeg.JPEGImageWriteParam; import javax.imageio.stream.ImageOutputStream; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.ToolTipManager; import weka.classifiers.AbstractClassifier; import weka.classifiers.Classifier; import weka.core.DenseInstance; import weka.core.Instance; import weka.core.Instances; import weka.core.Utils; /** * BoundaryPanel. A class to handle the plotting operations associated with * generating a 2D picture of a classifier's decision boundaries. * * @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a> * @version $Revision$ * @since 1.0 * @see JPanel */ public class BoundaryPanel extends JPanel { /** for serialization */ private static final long serialVersionUID = -8499445518744770458L; /** default colours for classes */ public static final Color[] DEFAULT_COLORS = { Color.red, Color.green, Color.blue, new Color(0, 255, 255), // cyan new Color(255, 0, 255), // pink new Color(255, 255, 0), // yellow new Color(255, 255, 255), // white new Color(0, 0, 0) }; /** * The distance we can click away from a point in the GUI and still remove it. */ public static final double REMOVE_POINT_RADIUS = 7.0; protected ArrayList<Color> m_Colors = new ArrayList<Color>(); /** training data */ protected Instances m_trainingData; /** distribution classifier to use */ protected Classifier m_classifier; /** data generator to use */ protected DataGenerator m_dataGenerator; /** index of the class attribute */ private int m_classIndex = -1; // attributes for visualizing on protected int m_xAttribute; protected int m_yAttribute; // min, max and ranges of these attributes protected double m_minX; protected double m_minY; protected double m_maxX; protected double m_maxY; private double m_rangeX; private double m_rangeY; // pixel width and height in terms of attribute values protected double m_pixHeight; protected double m_pixWidth; /** used for offscreen drawing */ protected Image m_osi = null; // width and height of the display area protected int m_panelWidth; protected int m_panelHeight; // number of samples to take from each region in the fixed dimensions protected int m_numOfSamplesPerRegion = 2; // number of samples per kernel = base ^ (# non-fixed dimensions) protected int m_numOfSamplesPerGenerator; protected double m_samplesBase = 2.0; /** listeners to be notified when plot is complete */ private final Vector<ActionListener> m_listeners = new Vector<ActionListener>(); /** * small inner class for rendering the bitmap on to */ private class PlotPanel extends JPanel { /** for serialization */ private static final long serialVersionUID = 743629498352235060L; public PlotPanel() { this.setToolTipText(""); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); if (m_osi != null) { g.drawImage(m_osi, 0, 0, this); } } @Override public String getToolTipText(MouseEvent event) { if (m_probabilityCache == null) { return null; } if (m_probabilityCache[event.getY()][event.getX()] == null) { return null; } String pVec = "(X: " + Utils.doubleToString(convertFromPanelX(event.getX()), 2) + " Y: " + Utils.doubleToString(convertFromPanelY(event.getY()), 2) + ") "; // construct a string holding the probability vector for (int i = 0; i < m_trainingData.classAttribute().numValues(); i++) { pVec += Utils.doubleToString( m_probabilityCache[event.getY()][event.getX()][i], 3) + " "; } return pVec; } } /** the actual plotting area */ private final PlotPanel m_plotPanel = new PlotPanel(); /** thread for running the plotting operation in */ private Thread m_plotThread = null; /** Stop the plotting thread */ protected boolean m_stopPlotting = false; /** Stop any replotting threads */ protected boolean m_stopReplotting = false; // Used by replotting threads to pause and resume the main plot thread private final Double m_dummy = new Double(1.0); private boolean m_pausePlotting = false; /** what size of tile is currently being plotted */ private int m_size = 1; /** is the main plot thread performing the initial coarse tiling */ private boolean m_initialTiling; /** A random number generator */ private Random m_random = null; /** cache of probabilities for fast replotting */ protected double[][][] m_probabilityCache; /** plot the training data */ protected boolean m_plotTrainingData = true; /** * Creates a new <code>BoundaryPanel</code> instance. * * @param panelWidth the width in pixels of the panel * @param panelHeight the height in pixels of the panel */ public BoundaryPanel(int panelWidth, int panelHeight) { ToolTipManager.sharedInstance().setDismissDelay(Integer.MAX_VALUE); m_panelWidth = panelWidth; m_panelHeight = panelHeight; setLayout(new BorderLayout()); m_plotPanel.setMinimumSize(new Dimension(m_panelWidth, m_panelHeight)); m_plotPanel.setPreferredSize(new Dimension(m_panelWidth, m_panelHeight)); m_plotPanel.setMaximumSize(new Dimension(m_panelWidth, m_panelHeight)); add(m_plotPanel, BorderLayout.CENTER); setPreferredSize(m_plotPanel.getPreferredSize()); setMaximumSize(m_plotPanel.getMaximumSize()); setMinimumSize(m_plotPanel.getMinimumSize()); m_random = new Random(1); for (Color element : DEFAULT_COLORS) { m_Colors.add(new Color(element.getRed(), element.getGreen(), element .getBlue())); } m_probabilityCache = new double[m_panelHeight][m_panelWidth][]; } /** * Set the number of points to uniformly sample from a region (fixed * dimensions). * * @param num an <code>int</code> value */ public void setNumSamplesPerRegion(int num) { m_numOfSamplesPerRegion = num; } /** * Get the number of points to sample from a region (fixed dimensions). * * @return an <code>int</code> value */ public int getNumSamplesPerRegion() { return m_numOfSamplesPerRegion; } /** * Set the base for computing the number of samples to obtain from each * generator. number of samples = base ^ (# non fixed dimensions) * * @param ksb a <code>double</code> value */ public void setGeneratorSamplesBase(double ksb) { m_samplesBase = ksb; } /** * Get the base used for computing the number of samples to obtain from each * generator * * @return a <code>double</code> value */ public double getGeneratorSamplesBase() { return m_samplesBase; } /** * Set up the off screen bitmap for rendering to */ protected void initialize() { int iwidth = m_plotPanel.getWidth(); int iheight = m_plotPanel.getHeight(); // System.err.println(iwidth+" "+iheight); m_osi = m_plotPanel.createImage(iwidth, iheight); Graphics m = m_osi.getGraphics(); m.fillRect(0, 0, iwidth, iheight); } /** * Stop the plotting thread */ public void stopPlotting() { m_stopPlotting = true; try { m_plotThread.join(100); } catch (Exception e) { } ; } /** * Set up the bounds of our graphic based by finding the smallest reasonable * area in the instance space to surround our data points. */ public void computeMinMaxAtts() { m_minX = Double.MAX_VALUE; m_minY = Double.MAX_VALUE; m_maxX = Double.MIN_VALUE; m_maxY = Double.MIN_VALUE; boolean allPointsLessThanOne = true; if (m_trainingData.numInstances() == 0) { m_minX = m_minY = 0.0; m_maxX = m_maxY = 1.0; } else { for (int i = 0; i < m_trainingData.numInstances(); i++) { Instance inst = m_trainingData.instance(i); double x = inst.value(m_xAttribute); double y = inst.value(m_yAttribute); if (!Utils.isMissingValue(x) && !Utils.isMissingValue(y)) { if (x < m_minX) { m_minX = x; } if (x > m_maxX) { m_maxX = x; } if (y < m_minY) { m_minY = y; } if (y > m_maxY) { m_maxY = y; } if (x > 1.0 || y > 1.0) { allPointsLessThanOne = false; } } } } if (m_minX == m_maxX) { m_minX = 0; } if (m_minY == m_maxY) { m_minY = 0; } if (m_minX == Double.MAX_VALUE) { m_minX = 0; } if (m_minY == Double.MAX_VALUE) { m_minY = 0; } if (m_maxX == Double.MIN_VALUE) { m_maxX = 1; } if (m_maxY == Double.MIN_VALUE) { m_maxY = 1; } if (allPointsLessThanOne) { // m_minX = m_minY = 0.0; m_maxX = m_maxY = 1.0; } m_rangeX = (m_maxX - m_minX); m_rangeY = (m_maxY - m_minY); m_pixWidth = m_rangeX / m_panelWidth; m_pixHeight = m_rangeY / m_panelHeight; } /** * Return a random x attribute value contained within the pix'th horizontal * pixel * * @param pix the horizontal pixel number * @return a value in attribute space */ private double getRandomX(int pix) { double minPix = m_minX + (pix * m_pixWidth); return minPix + m_random.nextDouble() * m_pixWidth; } /** * Return a random y attribute value contained within the pix'th vertical * pixel * * @param pix the vertical pixel number * @return a value in attribute space */ private double getRandomY(int pix) { double minPix = m_minY + (pix * m_pixHeight); return minPix + m_random.nextDouble() * m_pixHeight; } /** * Start the plotting thread * * @exception Exception if an error occurs */ public void start() throws Exception { m_numOfSamplesPerGenerator = (int) Math.pow(m_samplesBase, m_trainingData.numAttributes() - 3); m_stopReplotting = true; if (m_trainingData == null) { throw new Exception("No training data set (BoundaryPanel)"); } if (m_classifier == null) { throw new Exception("No classifier set (BoundaryPanel)"); } if (m_dataGenerator == null) { throw new Exception("No data generator set (BoundaryPanel)"); } if (m_trainingData.attribute(m_xAttribute).isNominal() || m_trainingData.attribute(m_yAttribute).isNominal()) { throw new Exception("Visualization dimensions must be numeric " + "(BoundaryPanel)"); } computeMinMaxAtts(); startPlotThread(); /* * if (m_plotThread == null) { m_plotThread = new PlotThread(); * m_plotThread.setPriority(Thread.MIN_PRIORITY); m_plotThread.start(); } */ } // Thread for main plotting operation protected class PlotThread extends Thread { double[] m_weightingAttsValues; boolean[] m_attsToWeightOn; double[] m_vals; double[] m_dist; Instance m_predInst; @Override @SuppressWarnings("unchecked") public void run() { m_stopPlotting = false; try { initialize(); repaint(); // train the classifier m_probabilityCache = new double[m_panelHeight][m_panelWidth][]; m_classifier.buildClassifier(m_trainingData); // build DataGenerator m_attsToWeightOn = new boolean[m_trainingData.numAttributes()]; m_attsToWeightOn[m_xAttribute] = true; m_attsToWeightOn[m_yAttribute] = true; m_dataGenerator.setWeightingDimensions(m_attsToWeightOn); m_dataGenerator.buildGenerator(m_trainingData); // generate samples m_weightingAttsValues = new double[m_attsToWeightOn.length]; m_vals = new double[m_trainingData.numAttributes()]; m_predInst = new DenseInstance(1.0, m_vals); m_predInst.setDataset(m_trainingData); m_size = 1 << 4; // Current sample region size m_initialTiling = true; // Display the initial coarse image tiling. abortInitial: for (int i = 0; i <= m_panelHeight; i += m_size) { for (int j = 0; j <= m_panelWidth; j += m_size) { if (m_stopPlotting) { break abortInitial; } if (m_pausePlotting) { synchronized (m_dummy) { try { m_dummy.wait(); } catch (InterruptedException ex) { m_pausePlotting = false; } } } plotPoint(j, i, m_size, m_size, calculateRegionProbs(j, i), (j == 0)); } } if (!m_stopPlotting) { m_initialTiling = false; } // Sampling and gridding loop int size2 = m_size / 2; abortPlot: while (m_size > 1) { // Subdivide down to the pixel level for (int i = 0; i <= m_panelHeight; i += m_size) { for (int j = 0; j <= m_panelWidth; j += m_size) { if (m_stopPlotting) { break abortPlot; } if (m_pausePlotting) { synchronized (m_dummy) { try { m_dummy.wait(); } catch (InterruptedException ex) { m_pausePlotting = false; } } } boolean update = (j == 0 && i % 2 == 0); // Draw the three new subpixel regions plotPoint(j, i + size2, size2, size2, calculateRegionProbs(j, i + size2), update); plotPoint(j + size2, i + size2, size2, size2, calculateRegionProbs(j + size2, i + size2), update); plotPoint(j + size2, i, size2, size2, calculateRegionProbs(j + size2, i), update); } } // The new region edge length is half the old edge length m_size = size2; size2 = size2 / 2; } update(); /* * // Old method without sampling. abortPlot: for (int i = 0; i < * m_panelHeight; i++) { for (int j = 0; j < m_panelWidth; j++) { if * (m_stopPlotting) { break abortPlot; } plotPoint(j, i, * calculateRegionProbs(j, i), (j == 0)); } } */ if (m_plotTrainingData) { plotTrainingData(); } } catch (Exception ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(null, "Error while plotting: \"" + ex.getMessage() + "\""); } finally { m_plotThread = null; // notify any listeners that we are finished Vector<ActionListener> l; ActionEvent e = new ActionEvent(this, 0, ""); synchronized (this) { l = (Vector<ActionListener>) m_listeners.clone(); } for (int i = 0; i < l.size(); i++) { ActionListener al = l.elementAt(i); al.actionPerformed(e); } } } private double[] calculateRegionProbs(int j, int i) throws Exception { double[] sumOfProbsForRegion = new double[m_trainingData.classAttribute() .numValues()]; double sumOfSums = 0; for (int u = 0; u < m_numOfSamplesPerRegion; u++) { double[] sumOfProbsForLocation = new double[m_trainingData .classAttribute().numValues()]; m_weightingAttsValues[m_xAttribute] = getRandomX(j); m_weightingAttsValues[m_yAttribute] = getRandomY(m_panelHeight - i - 1); m_dataGenerator.setWeightingValues(m_weightingAttsValues); double[] weights = m_dataGenerator.getWeights(); double sumOfWeights = Utils.sum(weights); sumOfSums += sumOfWeights; int[] indices = Utils.sort(weights); // Prune 1% of weight mass int[] newIndices = new int[indices.length]; double sumSoFar = 0; double criticalMass = 0.99 * sumOfWeights; int index = weights.length - 1; int counter = 0; for (int z = weights.length - 1; z >= 0; z--) { newIndices[index--] = indices[z]; sumSoFar += weights[indices[z]]; counter++; if (sumSoFar > criticalMass) { break; } } indices = new int[counter]; System.arraycopy(newIndices, index + 1, indices, 0, counter); for (int z = 0; z < m_numOfSamplesPerGenerator; z++) { m_dataGenerator.setWeightingValues(m_weightingAttsValues); double[][] values = m_dataGenerator.generateInstances(indices); for (int q = 0; q < values.length; q++) { if (values[q] != null) { System.arraycopy(values[q], 0, m_vals, 0, m_vals.length); m_vals[m_xAttribute] = m_weightingAttsValues[m_xAttribute]; m_vals[m_yAttribute] = m_weightingAttsValues[m_yAttribute]; // classify the instance m_dist = m_classifier.distributionForInstance(m_predInst); for (int k = 0; k < sumOfProbsForLocation.length; k++) { sumOfProbsForLocation[k] += (m_dist[k] * weights[q]); } } } } for (int k = 0; k < sumOfProbsForRegion.length; k++) { sumOfProbsForRegion[k] += (sumOfProbsForLocation[k] / m_numOfSamplesPerGenerator); } } // average if (sumOfSums > 0) { Utils.normalize(sumOfProbsForRegion, sumOfSums); } else { throw new Exception("Arithmetic underflow. Please increase value of kernel bandwidth parameter (k)."); } // cache if ((i < m_panelHeight) && (j < m_panelWidth)) { m_probabilityCache[i][j] = new double[sumOfProbsForRegion.length]; System.arraycopy(sumOfProbsForRegion, 0, m_probabilityCache[i][j], 0, sumOfProbsForRegion.length); } return sumOfProbsForRegion; } } /** * Render the training points on-screen. */ public void plotTrainingData() { Graphics2D osg = (Graphics2D) m_osi.getGraphics(); Graphics g = m_plotPanel.getGraphics(); osg.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); double xval = 0; double yval = 0; for (int i = 0; i < m_trainingData.numInstances(); i++) { if (!m_trainingData.instance(i).isMissing(m_xAttribute) && !m_trainingData.instance(i).isMissing(m_yAttribute)) { if (m_trainingData.instance(i).isMissing(m_classIndex)) { continue; // don't plot if class is missing. TODO could we plot it // differently instead? } xval = m_trainingData.instance(i).value(m_xAttribute); yval = m_trainingData.instance(i).value(m_yAttribute); int panelX = convertToPanelX(xval); int panelY = convertToPanelY(yval); Color ColorToPlotWith = (m_Colors.get((int) m_trainingData.instance(i) .value(m_classIndex) % m_Colors.size())); if (ColorToPlotWith.equals(Color.white)) { osg.setColor(Color.black); } else { osg.setColor(Color.white); } osg.fillOval(panelX - 3, panelY - 3, 7, 7); osg.setColor(ColorToPlotWith); osg.fillOval(panelX - 2, panelY - 2, 5, 5); } } g.drawImage(m_osi, 0, 0, m_plotPanel); } /** * Convert an X coordinate from the instance space to the panel space. */ private int convertToPanelX(double xval) { double temp = (xval - m_minX) / m_rangeX; temp = temp * m_panelWidth; return (int) temp; } /** * Convert a Y coordinate from the instance space to the panel space. */ private int convertToPanelY(double yval) { double temp = (yval - m_minY) / m_rangeY; temp = temp * m_panelHeight; temp = m_panelHeight - temp; return (int) temp; } /** * Convert an X coordinate from the panel space to the instance space. */ private double convertFromPanelX(double pX) { pX /= m_panelWidth; pX *= m_rangeX; return pX + m_minX; } /** * Convert a Y coordinate from the panel space to the instance space. */ private double convertFromPanelY(double pY) { pY = m_panelHeight - pY; pY /= m_panelHeight; pY *= m_rangeY; return pY + m_minY; } /** * Plot a point in our visualization on-screen. */ protected void plotPoint(int x, int y, double[] probs, boolean update) { plotPoint(x, y, 1, 1, probs, update); } /** * Plot a point in our visualization on-screen. */ private void plotPoint(int x, int y, int width, int height, double[] probs, boolean update) { // draw a progress line Graphics osg = m_osi.getGraphics(); if (update) { osg.setXORMode(Color.white); osg.drawLine(0, y, m_panelWidth - 1, y); update(); osg.drawLine(0, y, m_panelWidth - 1, y); } // plot the point osg.setPaintMode(); float[] colVal = new float[3]; float[] tempCols = new float[3]; for (int k = 0; k < probs.length; k++) { Color curr = m_Colors.get(k % m_Colors.size()); curr.getRGBColorComponents(tempCols); for (int z = 0; z < 3; z++) { colVal[z] += probs[k] * tempCols[z]; } } for (int z = 0; z < 3; z++) { if (colVal[z] < 0) { colVal[z] = 0; } else if (colVal[z] > 1) { colVal[z] = 1; } } osg.setColor(new Color(colVal[0], colVal[1], colVal[2])); osg.fillRect(x, y, width, height); } /** * Update the rendered image. */ private void update() { Graphics g = m_plotPanel.getGraphics(); g.drawImage(m_osi, 0, 0, m_plotPanel); } /** * Set the training data to use * * @param trainingData the training data * @exception Exception if an error occurs */ public void setTrainingData(Instances trainingData) throws Exception { m_trainingData = trainingData; if (m_trainingData.classIndex() < 0) { throw new Exception("No class attribute set (BoundaryPanel)"); } m_classIndex = m_trainingData.classIndex(); } /** * Adds a training instance to the visualization dataset. */ public void addTrainingInstance(Instance instance) { if (m_trainingData == null) { // TODO System.err .println("Trying to add to a null training set (BoundaryPanel)"); } else { m_trainingData.add(instance); } } /** * Register a listener to be notified when plotting completes * * @param newListener the listener to add */ public void addActionListener(ActionListener newListener) { m_listeners.add(newListener); } /** * Remove a listener * * @param removeListener the listener to remove */ public void removeActionListener(ActionListener removeListener) { m_listeners.removeElement(removeListener); } /** * Set the classifier to use. * * @param classifier the classifier to use */ public void setClassifier(Classifier classifier) { m_classifier = classifier; } /** * Set the data generator to use for generating new instances * * @param dataGenerator the data generator to use */ public void setDataGenerator(DataGenerator dataGenerator) { m_dataGenerator = dataGenerator; } /** * Set the x attribute index * * @param xatt index of the attribute to use on the x axis * @exception Exception if an error occurs */ public void setXAttribute(int xatt) throws Exception { if (m_trainingData == null) { throw new Exception("No training data set (BoundaryPanel)"); } if (xatt < 0 || xatt > m_trainingData.numAttributes()) { throw new Exception("X attribute out of range (BoundaryPanel)"); } if (m_trainingData.attribute(xatt).isNominal()) { throw new Exception("Visualization dimensions must be numeric " + "(BoundaryPanel)"); } /* * if (m_trainingData.numDistinctValues(xatt) < 2) { throw new * Exception("Too few distinct values for X attribute " +"(BoundaryPanel)"); * } */// removed by jimmy. TESTING! m_xAttribute = xatt; } /** * Set the y attribute index * * @param yatt index of the attribute to use on the y axis * @exception Exception if an error occurs */ public void setYAttribute(int yatt) throws Exception { if (m_trainingData == null) { throw new Exception("No training data set (BoundaryPanel)"); } if (yatt < 0 || yatt > m_trainingData.numAttributes()) { throw new Exception("X attribute out of range (BoundaryPanel)"); } if (m_trainingData.attribute(yatt).isNominal()) { throw new Exception("Visualization dimensions must be numeric " + "(BoundaryPanel)"); } /* * if (m_trainingData.numDistinctValues(yatt) < 2) { throw new * Exception("Too few distinct values for Y attribute " +"(BoundaryPanel)"); * } */// removed by jimmy. TESTING! m_yAttribute = yatt; } /** * Set a vector of Color objects for the classes * * @param colors a <code>FastVector</code> value */ public void setColors(ArrayList<Color> colors) { synchronized (m_Colors) { m_Colors = colors; } // replot(); //commented by jimmy update(); // added by jimmy } /** * Set whether to superimpose the training data plot * * @param pg a <code>boolean</code> value */ public void setPlotTrainingData(boolean pg) { m_plotTrainingData = pg; } /** * Returns true if training data is to be superimposed * * @return a <code>boolean</code> value */ public boolean getPlotTrainingData() { return m_plotTrainingData; } /** * Get the current vector of Color objects used for the classes * * @return a <code>FastVector</code> value */ public ArrayList<Color> getColors() { return m_Colors; } /** * Quickly replot the display using cached probability estimates */ public void replot() { if (m_probabilityCache[0][0] == null) { return; } m_stopReplotting = true; m_pausePlotting = true; // wait 300 ms to give any other replot threads a chance to halt try { Thread.sleep(300); } catch (Exception ex) { } final Thread replotThread = new Thread() { @Override public void run() { m_stopReplotting = false; int size2 = m_size / 2; finishedReplot: for (int i = 0; i < m_panelHeight; i += m_size) { for (int j = 0; j < m_panelWidth; j += m_size) { if (m_probabilityCache[i][j] == null || m_stopReplotting) { break finishedReplot; } boolean update = (j == 0 && i % 2 == 0); if (i < m_panelHeight && j < m_panelWidth) { // Draw the three new subpixel regions or single course tiling if (m_initialTiling || m_size == 1) { if (m_probabilityCache[i][j] == null) { break finishedReplot; } plotPoint(j, i, m_size, m_size, m_probabilityCache[i][j], update); } else { if (m_probabilityCache[i + size2][j] == null) { break finishedReplot; } plotPoint(j, i + size2, size2, size2, m_probabilityCache[i + size2][j], update); if (m_probabilityCache[i + size2][j + size2] == null) { break finishedReplot; } plotPoint(j + size2, i + size2, size2, size2, m_probabilityCache[i + size2][j + size2], update); if (m_probabilityCache[i][j + size2] == null) { break finishedReplot; } plotPoint(j + size2, i, size2, size2, m_probabilityCache[i + size2][j], update); } } } } update(); if (m_plotTrainingData) { plotTrainingData(); } m_pausePlotting = false; if (!m_stopPlotting) { synchronized (m_dummy) { m_dummy.notifyAll(); } } } }; replotThread.start(); } protected void saveImage(String fileName) { BufferedImage bi; Graphics2D gr2; ImageWriter writer; Iterator<ImageWriter> iter; ImageOutputStream ios; ImageWriteParam param; try { // render image bi = new BufferedImage(m_panelWidth, m_panelHeight, BufferedImage.TYPE_INT_RGB); gr2 = bi.createGraphics(); gr2.drawImage(m_osi, 0, 0, m_panelWidth, m_panelHeight, null); // get jpeg writer writer = null; iter = ImageIO.getImageWritersByFormatName("jpg"); if (iter.hasNext()) { writer = iter.next(); } else { throw new Exception("No JPEG writer available!"); } // prepare output file ios = ImageIO.createImageOutputStream(new File(fileName)); writer.setOutput(ios); // set the quality param = new JPEGImageWriteParam(Locale.getDefault()); param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); param.setCompressionQuality(1.0f); // write the image writer.write(null, new IIOImage(bi, null, null), param); // cleanup ios.flush(); writer.dispose(); ios.close(); } catch (Exception e) { e.printStackTrace(); } } /** * Adds a training instance to our dataset, based on the coordinates of the * mouse on the panel. This method sets the x and y attributes and the class * (as defined by classAttIndex), and sets all other values as Missing. * * @param mouseX the x coordinate of the mouse, in pixels. * @param mouseY the y coordinate of the mouse, in pixels. * @param classAttIndex the index of the attribute that is currently selected * as the class attribute. * @param classValue the value to set the class to in our new point. */ public void addTrainingInstanceFromMouseLocation(int mouseX, int mouseY, int classAttIndex, double classValue) { // convert to coordinates in the training instance space. double x = convertFromPanelX(mouseX); double y = convertFromPanelY(mouseY); // build the training instance Instance newInstance = new DenseInstance(m_trainingData.numAttributes()); for (int i = 0; i < newInstance.numAttributes(); i++) { if (i == classAttIndex) { newInstance.setValue(i, classValue); } else if (i == m_xAttribute) { newInstance.setValue(i, x); } else if (i == m_yAttribute) { newInstance.setValue(i, y); } else { newInstance.setMissing(i); } } // add it to our data set. addTrainingInstance(newInstance); } /** * Deletes all training instances from our dataset. */ public void removeAllInstances() { if (m_trainingData != null) { m_trainingData.delete(); try { initialize(); } catch (Exception e) { } ; } } /** * Removes a single training instance from our dataset, if there is one that * is close enough to the specified mouse location. */ public void removeTrainingInstanceFromMouseLocation(int mouseX, int mouseY) { // convert to coordinates in the training instance space. double x = convertFromPanelX(mouseX); double y = convertFromPanelY(mouseY); int bestIndex = -1; double bestDistanceBetween = Integer.MAX_VALUE; // find the closest point. for (int i = 0; i < m_trainingData.numInstances(); i++) { Instance current = m_trainingData.instance(i); double distanceBetween = (current.value(m_xAttribute) - x) * (current.value(m_xAttribute) - x) + (current.value(m_yAttribute) - y) * (current.value(m_yAttribute) - y); // won't bother to sqrt, just used // square values. if (distanceBetween < bestDistanceBetween) { bestIndex = i; bestDistanceBetween = distanceBetween; } } if (bestIndex == -1) { return; } Instance best = m_trainingData.instance(bestIndex); double panelDistance = (convertToPanelX(best.value(m_xAttribute)) - mouseX) * (convertToPanelX(best.value(m_xAttribute)) - mouseX) + (convertToPanelY(best.value(m_yAttribute)) - mouseY) * (convertToPanelY(best.value(m_yAttribute)) - mouseY); if (panelDistance < REMOVE_POINT_RADIUS * REMOVE_POINT_RADIUS) {// the best // point is // close // enough. // (using // squared // distances) m_trainingData.delete(bestIndex); } } /** * Starts the plotting thread. Will also create it if necessary. */ public void startPlotThread() { if (m_plotThread == null) { // jimmy m_plotThread = new PlotThread(); m_plotThread.setPriority(Thread.MIN_PRIORITY); m_plotThread.start(); } } /** * Adds a mouse listener. */ @Override public void addMouseListener(MouseListener l) { m_plotPanel.addMouseListener(l); } /** * Gets the minimum x-coordinate bound, in training-instance units (not mouse * coordinates). */ public double getMinXBound() { return m_minX; } /** * Gets the minimum y-coordinate bound, in training-instance units (not mouse * coordinates). */ public double getMinYBound() { return m_minY; } /** * Gets the maximum x-coordinate bound, in training-instance units (not mouse * coordinates). */ public double getMaxXBound() { return m_maxX; } /** * Gets the maximum x-coordinate bound, in training-instance units (not mouse * coordinates). */ public double getMaxYBound() { return m_maxY; } /** * Main method for testing this class * * @param args a <code>String[]</code> value */ public static void main(String[] args) { try { if (args.length < 8) { System.err.println("Usage : BoundaryPanel <dataset> " + "<class col> <xAtt> <yAtt> " + "<base> <# loc/pixel> <kernel bandwidth> " + "<display width> " + "<display height> <classifier " + "[classifier options]>"); System.exit(1); } final javax.swing.JFrame jf = new javax.swing.JFrame( "Weka classification boundary visualizer"); jf.getContentPane().setLayout(new BorderLayout()); System.err.println("Loading instances from : " + args[0]); java.io.Reader r = new java.io.BufferedReader(new java.io.FileReader( args[0])); final Instances i = new Instances(r); i.setClassIndex(Integer.parseInt(args[1])); // bv.setClassifier(new Logistic()); final int xatt = Integer.parseInt(args[2]); final int yatt = Integer.parseInt(args[3]); int base = Integer.parseInt(args[4]); int loc = Integer.parseInt(args[5]); int bandWidth = Integer.parseInt(args[6]); int panelWidth = Integer.parseInt(args[7]); int panelHeight = Integer.parseInt(args[8]); final String classifierName = args[9]; final BoundaryPanel bv = new BoundaryPanel(panelWidth, panelHeight); bv.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String classifierNameNew = classifierName.substring( classifierName.lastIndexOf('.') + 1, classifierName.length()); bv.saveImage(classifierNameNew + "_" + i.relationName() + "_X" + xatt + "_Y" + yatt + ".jpg"); } }); jf.getContentPane().add(bv, BorderLayout.CENTER); jf.setSize(bv.getMinimumSize()); // jf.setSize(200,200); 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); // bv.initialize(); bv.repaint(); String[] argsR = null; if (args.length > 10) { argsR = new String[args.length - 10]; for (int j = 10; j < args.length; j++) { argsR[j - 10] = args[j]; } } Classifier c = AbstractClassifier.forName(args[9], argsR); KDDataGenerator dataGen = new KDDataGenerator(); dataGen.setKernelBandwidth(bandWidth); bv.setDataGenerator(dataGen); bv.setNumSamplesPerRegion(loc); bv.setGeneratorSamplesBase(base); bv.setClassifier(c); bv.setTrainingData(i); bv.setXAttribute(xatt); bv.setYAttribute(yatt); try { // try and load a color map if one exists FileInputStream fis = new FileInputStream("colors.ser"); ObjectInputStream ois = new ObjectInputStream(fis); @SuppressWarnings("unchecked") ArrayList<Color> colors = (ArrayList<Color>) ois.readObject(); bv.setColors(colors); ois.close(); } catch (Exception ex) { System.err.println("No color map file"); } bv.start(); } 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/boundaryvisualizer/BoundaryPanelDistributed.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * BoundaryPanelDistrubuted.java * Copyright (C) 2003-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.boundaryvisualizer; import java.awt.BorderLayout; import java.awt.Color; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileReader; import java.io.ObjectInputStream; import java.rmi.Naming; import java.util.ArrayList; import java.util.Vector; import weka.classifiers.AbstractClassifier; import weka.classifiers.Classifier; import weka.core.Instances; import weka.core.Utils; import weka.experiment.Compute; import weka.experiment.RemoteExperimentEvent; import weka.experiment.RemoteExperimentListener; import weka.experiment.TaskStatusInfo; /** * This class extends BoundaryPanel with code for distributing the processing * necessary to create a visualization among a list of remote machines. * Specifically, a visualization is broken down and processed row by row using * the available remote computers. * * @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a> * @version $Revision$ * @since 1.0 * @see BoundaryPanel */ public class BoundaryPanelDistributed extends BoundaryPanel { /** for serialization */ private static final long serialVersionUID = -1743284397893937776L; /** a list of RemoteExperimentListeners */ protected Vector<RemoteExperimentListener> m_listeners = new Vector<RemoteExperimentListener>(); /** Holds the names of machines with remoteEngine servers running */ protected Vector<String> m_remoteHosts = new Vector<String>(); /** The queue of available hosts */ private weka.core.Queue m_remoteHostsQueue = new weka.core.Queue(); /** The status of each of the remote hosts */ private int[] m_remoteHostsStatus; /** The number of times tasks have failed on each remote host */ private int[] m_remoteHostFailureCounts; protected static final int AVAILABLE = 0; protected static final int IN_USE = 1; protected static final int CONNECTION_FAILED = 2; protected static final int SOME_OTHER_FAILURE = 3; protected static final int MAX_FAILURES = 3; /** * Set to true if MAX_FAILURES exceeded on all hosts or connections fail on * all hosts or user aborts plotting */ private boolean m_plottingAborted = false; /** The number of hosts removed due to exceeding max failures */ private int m_removedHosts; /** The count of failed sub-tasks */ private int m_failedCount; /** The queue of sub-tasks waiting to be processed */ private weka.core.Queue m_subExpQueue = new weka.core.Queue(); /** number of seconds between polling server */ private final int m_minTaskPollTime = 1000; private int[] m_hostPollingTime; /** * Creates a new <code>BoundaryPanelDistributed</code> instance. * * @param panelWidth width of the display * @param panelHeight height of the display */ public BoundaryPanelDistributed(int panelWidth, int panelHeight) { super(panelWidth, panelHeight); } /** * Set a list of host names of machines to distribute processing to * * @param remHosts a Vector of host names (Strings) */ public void setRemoteHosts(Vector<String> remHosts) { m_remoteHosts = remHosts; } /** * Add an object to the list of those interested in recieving update * information from the RemoteExperiment * * @param r a listener */ public void addRemoteExperimentListener(RemoteExperimentListener r) { m_listeners.addElement(r); } @Override protected void initialize() { super.initialize(); m_plottingAborted = false; m_failedCount = 0; // initialize all remote hosts to available m_remoteHostsStatus = new int[m_remoteHosts.size()]; m_remoteHostFailureCounts = new int[m_remoteHosts.size()]; m_remoteHostsQueue = new weka.core.Queue(); if (m_remoteHosts.size() == 0) { System.err.println("No hosts specified!"); System.exit(1); } // prime the hosts queue m_hostPollingTime = new int[m_remoteHosts.size()]; for (int i = 0; i < m_remoteHosts.size(); i++) { m_remoteHostsQueue.push(new Integer(i)); m_hostPollingTime[i] = m_minTaskPollTime; } // set up sub taskss (just holds the row numbers to be processed m_subExpQueue = new weka.core.Queue(); for (int i = 0; i < m_panelHeight; i++) { m_subExpQueue.push(new Integer(i)); } try { // need to build classifier and data generator m_classifier.buildClassifier(m_trainingData); } catch (Exception ex) { ex.printStackTrace(); System.exit(1); } boolean[] attsToWeightOn; // build DataGenerator attsToWeightOn = new boolean[m_trainingData.numAttributes()]; attsToWeightOn[m_xAttribute] = true; attsToWeightOn[m_yAttribute] = true; m_dataGenerator.setWeightingDimensions(attsToWeightOn); try { m_dataGenerator.buildGenerator(m_trainingData); } catch (Exception ex) { ex.printStackTrace(); System.exit(1); } } /** * Start processing * * @exception Exception if an error occurs */ @Override public void start() throws Exception { // done in the sub task /* * m_numOfSamplesPerGenerator = (int)Math.pow(m_samplesBase, * m_trainingData.numAttributes()-3); */ m_stopReplotting = true; if (m_trainingData == null) { throw new Exception("No training data set (BoundaryPanel)"); } if (m_classifier == null) { throw new Exception("No classifier set (BoundaryPanel)"); } if (m_dataGenerator == null) { throw new Exception("No data generator set (BoundaryPanel)"); } if (m_trainingData.attribute(m_xAttribute).isNominal() || m_trainingData.attribute(m_yAttribute).isNominal()) { throw new Exception("Visualization dimensions must be numeric " + "(BoundaryPanel)"); } computeMinMaxAtts(); initialize(); // launch tasks on all available hosts int totalHosts = m_remoteHostsQueue.size(); for (int i = 0; i < totalHosts; i++) { availableHost(-1); Thread.sleep(70); } } /** * Push a host back onto the list of available hosts and launch a waiting Task * (if any). * * @param hostNum the number of the host to return to the queue. -1 if no host * to return. */ protected synchronized void availableHost(int hostNum) { if (hostNum >= 0) { if (m_remoteHostFailureCounts[hostNum] < MAX_FAILURES) { m_remoteHostsQueue.push(new Integer(hostNum)); } else { notifyListeners(false, true, false, "Max failures exceeded for host " + (m_remoteHosts.elementAt(hostNum)) + ". Removed from host list."); m_removedHosts++; } } // check for all sub exp complete or all hosts failed or failed count // exceeded if (m_failedCount == (MAX_FAILURES * m_remoteHosts.size())) { m_plottingAborted = true; notifyListeners(false, true, true, "Plotting aborted! Max failures " + "exceeded on all remote hosts."); return; } /* * System.err.println("--------------"); * System.err.println("exp q :"+m_subExpQueue.size()); * System.err.println("host list size "+m_remoteHosts.size()); * System.err.println("actual host list size "+m_remoteHostsQueue.size()); * System.err.println("removed hosts "+m_removedHosts); */ if (m_subExpQueue.size() == 0 && (m_remoteHosts.size() == (m_remoteHostsQueue.size() + m_removedHosts))) { if (m_plotTrainingData) { plotTrainingData(); } notifyListeners(false, true, true, "Plotting completed successfully."); return; } if (checkForAllFailedHosts()) { return; } if (m_plottingAborted && (m_remoteHostsQueue.size() + m_removedHosts) == m_remoteHosts.size()) { notifyListeners(false, true, true, "Plotting aborted. All remote tasks " + "finished."); } if (!m_subExpQueue.empty() && !m_plottingAborted) { if (!m_remoteHostsQueue.empty()) { int availHost, waitingTask; try { availHost = ((Integer) m_remoteHostsQueue.pop()).intValue(); waitingTask = ((Integer) m_subExpQueue.pop()).intValue(); launchNext(waitingTask, availHost); } catch (Exception ex) { ex.printStackTrace(); } } } } /** * Inform all listeners of progress * * @param status true if this is a status type of message * @param log true if this is a log type of message * @param finished true if the remote task has finished * @param message the message. */ private synchronized void notifyListeners(boolean status, boolean log, boolean finished, String message) { if (m_listeners.size() > 0) { for (int i = 0; i < m_listeners.size(); i++) { RemoteExperimentListener r = (m_listeners.elementAt(i)); r.remoteExperimentStatus(new RemoteExperimentEvent(status, log, finished, message)); } } else { System.err.println(message); } } /** * Check to see if we have failed to connect to all hosts */ private boolean checkForAllFailedHosts() { boolean allbad = true; for (int m_remoteHostsStatu : m_remoteHostsStatus) { if (m_remoteHostsStatu != CONNECTION_FAILED) { allbad = false; break; } } if (allbad) { m_plottingAborted = true; notifyListeners(false, true, true, "Plotting aborted! All connections " + "to remote hosts failed."); } return allbad; } /** * Increment the number of successfully completed sub experiments */ protected synchronized void incrementFinished() { } /** * Increment the overall number of failures and the number of failures for a * particular host * * @param hostNum the index of the host to increment failure count */ protected synchronized void incrementFailed(int hostNum) { m_failedCount++; m_remoteHostFailureCounts[hostNum]++; } /** * Push an experiment back on the queue of waiting experiments * * @param expNum the index of the experiment to push onto the queue */ protected synchronized void waitingTask(int expNum) { m_subExpQueue.push(new Integer(expNum)); } protected void launchNext(final int wtask, final int ah) { Thread subTaskThread; subTaskThread = new Thread() { @Override public void run() { m_remoteHostsStatus[ah] = IN_USE; // m_subExpComplete[wtask] = TaskStatusInfo.PROCESSING; RemoteBoundaryVisualizerSubTask vSubTask = new RemoteBoundaryVisualizerSubTask(); vSubTask.setXAttribute(m_xAttribute); vSubTask.setYAttribute(m_yAttribute); vSubTask.setRowNumber(wtask); vSubTask.setPanelWidth(m_panelWidth); vSubTask.setPanelHeight(m_panelHeight); vSubTask.setPixHeight(m_pixHeight); vSubTask.setPixWidth(m_pixWidth); vSubTask.setClassifier(m_classifier); vSubTask.setDataGenerator(m_dataGenerator); vSubTask.setInstances(m_trainingData); vSubTask.setMinMaxX(m_minX, m_maxX); vSubTask.setMinMaxY(m_minY, m_maxY); vSubTask.setNumSamplesPerRegion(m_numOfSamplesPerRegion); vSubTask.setGeneratorSamplesBase(m_samplesBase); try { String name = "//" + (m_remoteHosts.elementAt(ah)) + "/RemoteEngine"; Compute comp = (Compute) Naming.lookup(name); // assess the status of the sub-exp notifyListeners(false, true, false, "Starting row " + wtask + " on host " + (m_remoteHosts.elementAt(ah))); Object subTaskId = comp.executeTask(vSubTask); boolean finished = false; TaskStatusInfo is = null; long startTime = System.currentTimeMillis(); while (!finished) { try { Thread.sleep(Math.max(m_minTaskPollTime, m_hostPollingTime[ah])); TaskStatusInfo cs = (TaskStatusInfo) comp.checkStatus(subTaskId); if (cs.getExecutionStatus() == TaskStatusInfo.FINISHED) { // push host back onto queue and try launching any waiting // sub-experiments long runTime = System.currentTimeMillis() - startTime; runTime /= 4; if (runTime < 1000) { runTime = 1000; } m_hostPollingTime[ah] = (int) runTime; // Extract the row from the result RemoteResult rr = (RemoteResult) cs.getTaskResult(); double[][] probs = rr.getProbabilities(); for (int i = 0; i < m_panelWidth; i++) { m_probabilityCache[wtask][i] = probs[i]; if (i < m_panelWidth - 1) { plotPoint(i, wtask, probs[i], false); } else { plotPoint(i, wtask, probs[i], true); } } notifyListeners(false, true, false, cs.getStatusMessage()); m_remoteHostsStatus[ah] = AVAILABLE; incrementFinished(); availableHost(ah); finished = true; } else if (cs.getExecutionStatus() == TaskStatusInfo.FAILED) { // a non connection related error---possibly host doesn't have // access to data sets or security policy is not set up // correctly or classifier(s) failed for some reason notifyListeners(false, true, false, cs.getStatusMessage()); m_remoteHostsStatus[ah] = SOME_OTHER_FAILURE; // m_subExpComplete[wexp] = TaskStatusInfo.FAILED; notifyListeners(false, true, false, "Row " + wtask + " " + cs.getStatusMessage() + ". Scheduling for execution on another host."); incrementFailed(ah); // push experiment back onto queue waitingTask(wtask); // push host back onto queue and try launching any waiting // Tasks. Host is pushed back on the queue as the // failure may be temporary. availableHost(ah); finished = true; } else { if (is == null) { is = cs; notifyListeners(false, true, false, cs.getStatusMessage()); } else { RemoteResult rr = (RemoteResult) cs.getTaskResult(); if (rr != null) { int percentComplete = rr.getPercentCompleted(); String timeRemaining = ""; if (percentComplete > 0 && percentComplete < 100) { double timeSoFar = (double) System.currentTimeMillis() - (double) startTime; double timeToGo = ((100.0 - percentComplete) / percentComplete) * timeSoFar; if (timeToGo < m_hostPollingTime[ah]) { m_hostPollingTime[ah] = (int) timeToGo; } String units = "seconds"; timeToGo /= 1000.0; if (timeToGo > 60) { units = "minutes"; timeToGo /= 60.0; } if (timeToGo > 60) { units = "hours"; timeToGo /= 60.0; } timeRemaining = " (approx. time remaining " + Utils.doubleToString(timeToGo, 1) + " " + units + ")"; } if (percentComplete < 25 /* && minTaskPollTime < 30000 */) { if (percentComplete > 0) { m_hostPollingTime[ah] = (int) ((25.0 / percentComplete) * m_hostPollingTime[ah]); } else { m_hostPollingTime[ah] *= 2; } if (m_hostPollingTime[ah] > 60000) { m_hostPollingTime[ah] = 60000; } } notifyListeners(false, true, false, "Row " + wtask + " " + percentComplete + "% complete" + timeRemaining + "."); } else { notifyListeners(false, true, false, "Row " + wtask + " queued on " + (m_remoteHosts.elementAt(ah))); if (m_hostPollingTime[ah] < 60000) { m_hostPollingTime[ah] *= 2; } } is = cs; } } } catch (InterruptedException ie) { ie.printStackTrace(); } } } catch (Exception ce) { m_remoteHostsStatus[ah] = CONNECTION_FAILED; m_removedHosts++; System.err.println(ce); ce.printStackTrace(); notifyListeners(false, true, false, "Connection to " + (m_remoteHosts.elementAt(ah)) + " failed. Scheduling row " + wtask + " for execution on another host."); checkForAllFailedHosts(); waitingTask(wtask); } finally { if (isInterrupted()) { System.err.println("Sub exp Interupted!"); } } } }; subTaskThread.setPriority(Thread.MIN_PRIORITY); subTaskThread.start(); } /** * Main method for testing this class * * @param args a <code>String[]</code> value */ public static void main(String[] args) { try { if (args.length < 8) { System.err.println("Usage : BoundaryPanelDistributed <dataset> " + "<class col> <xAtt> <yAtt> " + "<base> <# loc/pixel> <kernel bandwidth> " + "<display width> " + "<display height> <classifier " + "[classifier options]>"); System.exit(1); } Vector<String> hostNames = new Vector<String>(); // try loading hosts file try { BufferedReader br = new BufferedReader(new FileReader("hosts.vis")); String hostName = br.readLine(); while (hostName != null) { System.out.println("Adding host " + hostName); hostNames.add(hostName); hostName = br.readLine(); } br.close(); } catch (Exception ex) { System.err.println("No hosts.vis file - create this file in " + "the current directory with one host name " + "per line, or use BoundaryPanel instead."); System.exit(1); } final javax.swing.JFrame jf = new javax.swing.JFrame( "Weka classification boundary visualizer"); jf.getContentPane().setLayout(new BorderLayout()); System.err.println("Loading instances from : " + args[0]); java.io.Reader r = new java.io.BufferedReader(new java.io.FileReader( args[0])); final Instances i = new Instances(r); i.setClassIndex(Integer.parseInt(args[1])); // bv.setClassifier(new Logistic()); final int xatt = Integer.parseInt(args[2]); final int yatt = Integer.parseInt(args[3]); int base = Integer.parseInt(args[4]); int loc = Integer.parseInt(args[5]); int bandWidth = Integer.parseInt(args[6]); int panelWidth = Integer.parseInt(args[7]); int panelHeight = Integer.parseInt(args[8]); final String classifierName = args[9]; final BoundaryPanelDistributed bv = new BoundaryPanelDistributed( panelWidth, panelHeight); bv.addRemoteExperimentListener(new RemoteExperimentListener() { @Override public void remoteExperimentStatus(RemoteExperimentEvent e) { if (e.m_experimentFinished) { String classifierNameNew = classifierName.substring( classifierName.lastIndexOf('.') + 1, classifierName.length()); bv.saveImage(classifierNameNew + "_" + i.relationName() + "_X" + xatt + "_Y" + yatt + ".jpg"); } else { System.err.println(e.m_messageString); } } }); bv.setRemoteHosts(hostNames); jf.getContentPane().add(bv, BorderLayout.CENTER); jf.setSize(bv.getMinimumSize()); // jf.setSize(200,200); 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); // bv.initialize(); bv.repaint(); String[] argsR = null; if (args.length > 10) { argsR = new String[args.length - 10]; for (int j = 10; j < args.length; j++) { argsR[j - 10] = args[j]; } } Classifier c = AbstractClassifier.forName(args[9], argsR); KDDataGenerator dataGen = new KDDataGenerator(); dataGen.setKernelBandwidth(bandWidth); bv.setDataGenerator(dataGen); bv.setNumSamplesPerRegion(loc); bv.setGeneratorSamplesBase(base); bv.setClassifier(c); bv.setTrainingData(i); bv.setXAttribute(xatt); bv.setYAttribute(yatt); try { // try and load a color map if one exists FileInputStream fis = new FileInputStream("colors.ser"); ObjectInputStream ois = new ObjectInputStream(fis); @SuppressWarnings("unchecked") ArrayList<Color> colors = (ArrayList<Color>) ois.readObject(); bv.setColors(colors); ois.close(); } catch (Exception ex) { System.err.println("No color map file"); } bv.start(); } 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/boundaryvisualizer/BoundaryVisualizer.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * BoundaryVisualizer.java * Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.boundaryvisualizer; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import java.io.FileOutputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.Vector; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.ButtonGroup; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JTextField; import weka.classifiers.AbstractClassifier; import weka.classifiers.Classifier; import weka.core.Attribute; import weka.core.Instances; import weka.core.TechnicalInformation; import weka.core.TechnicalInformation.Field; import weka.core.TechnicalInformation.Type; import weka.core.TechnicalInformationHandler; import weka.core.Utils; import weka.gui.ExtensionFileFilter; import weka.gui.GenericObjectEditor; import weka.gui.PropertyPanel; import weka.gui.visualize.ClassPanel; /** * BoundaryVisualizer. Allows the visualization of classifier decision * boundaries in two dimensions. A supplied classifier is first trained on * supplied training data, then a data generator (currently using kernels) is * used to generate new instances at points fixed in the two visualization * dimensions but random in the other dimensions. These instances are classified * by the classifier and plotted as points with colour corresponding to the * probability distribution predicted by the classifier. At present, 2 * 2^(# * non-fixed dimensions) points are generated from each kernel per pixel in the * display. In practice, fewer points than this are actually classified because * kernels are weighted (on a per-pixel basis) according to the fixexd * dimensions and kernels corresponding to the lowest 1% of the weight mass are * discarded. Predicted probability distributions are weighted (acording to the * fixed visualization dimensions) and averaged to produce an RGB value for the * pixel. For more information, see * <p> * * Eibe Frank and Mark Hall (2003). Visualizing Class Probability Estimators. * Working Paper 02/03, Department of Computer Science, University of Waikato. * * @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a> * @version $Revision$ * @since 1.0 * @see JPanel */ public class BoundaryVisualizer extends JPanel implements TechnicalInformationHandler { /** for serialization */ private static final long serialVersionUID = 3933877580074013208L; /** * Inner class to handle rendering the axis * * @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a> * @version $Revision$ * @since 1.0 * @see JPanel */ private class AxisPanel extends JPanel { /** for serialization */ private static final long serialVersionUID = -7421022416674492712L; private static final int MAX_PRECISION = 10; private boolean m_vertical = false; private final int PAD = 5; private FontMetrics m_fontMetrics; private int m_fontHeight; public AxisPanel(boolean vertical) { m_vertical = vertical; this.setBackground(Color.black); // Graphics g = this.getGraphics(); String fontFamily = this.getFont().getFamily(); Font newFont = new Font(fontFamily, Font.PLAIN, 10); this.setFont(newFont); } @Override public Dimension getPreferredSize() { if (m_fontMetrics == null) { Graphics g = this.getGraphics(); m_fontMetrics = g.getFontMetrics(); m_fontHeight = m_fontMetrics.getHeight(); } if (!m_vertical) { return new Dimension(this.getSize().width, PAD + 2 + m_fontHeight); } return new Dimension(50, this.getSize().height); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); this.setBackground(Color.black); if (m_fontMetrics == null) { m_fontMetrics = g.getFontMetrics(); m_fontHeight = m_fontMetrics.getHeight(); } Dimension d = this.getSize(); Dimension d2 = m_boundaryPanel.getSize(); g.setColor(Color.gray); int hf = m_fontMetrics.getAscent(); if (!m_vertical) { g.drawLine(d.width, PAD, d.width - d2.width, PAD); // try and draw some scale values if (getInstances() != null) { int precisionXmax = 1; int precisionXmin = 1; int whole = (int) Math.abs(m_maxX); double decimal = Math.abs(m_maxX) - whole; int nondecimal; nondecimal = (whole > 0) ? (int) (Math.log(whole) / Math.log(10)) : 1; precisionXmax = (decimal > 0) ? (int) Math.abs(((Math.log(Math .abs(m_maxX)) / Math.log(10)))) + 2 : 1; if (precisionXmax > MAX_PRECISION) { precisionXmax = 1; } String maxStringX = Utils.doubleToString(m_maxX, nondecimal + 1 + precisionXmax, precisionXmax); whole = (int) Math.abs(m_minX); decimal = Math.abs(m_minX) - whole; nondecimal = (whole > 0) ? (int) (Math.log(whole) / Math.log(10)) : 1; precisionXmin = (decimal > 0) ? (int) Math.abs(((Math.log(Math .abs(m_minX)) / Math.log(10)))) + 2 : 1; if (precisionXmin > MAX_PRECISION) { precisionXmin = 1; } String minStringX = Utils.doubleToString(m_minX, nondecimal + 1 + precisionXmin, precisionXmin); g.drawString(minStringX, d.width - d2.width, PAD + hf + 2); int maxWidth = m_fontMetrics.stringWidth(maxStringX); g.drawString(maxStringX, d.width - maxWidth, PAD + hf + 2); } } else { g.drawLine(d.width - PAD, 0, d.width - PAD, d2.height); // try and draw some scale values if (getInstances() != null) { int precisionYmax = 1; int precisionYmin = 1; int whole = (int) Math.abs(m_maxY); double decimal = Math.abs(m_maxY) - whole; int nondecimal; nondecimal = (whole > 0) ? (int) (Math.log(whole) / Math.log(10)) : 1; precisionYmax = (decimal > 0) ? (int) Math.abs(((Math.log(Math .abs(m_maxY)) / Math.log(10)))) + 2 : 1; if (precisionYmax > MAX_PRECISION) { precisionYmax = 1; } String maxStringY = Utils.doubleToString(m_maxY, nondecimal + 1 + precisionYmax, precisionYmax); whole = (int) Math.abs(m_minY); decimal = Math.abs(m_minY) - whole; nondecimal = (whole > 0) ? (int) (Math.log(whole) / Math.log(10)) : 1; precisionYmin = (decimal > 0) ? (int) Math.abs(((Math.log(Math .abs(m_minY)) / Math.log(10)))) + 2 : 1; if (precisionYmin > MAX_PRECISION) { precisionYmin = 1; } String minStringY = Utils.doubleToString(m_minY, nondecimal + 1 + precisionYmin, precisionYmin); int maxWidth = m_fontMetrics.stringWidth(minStringY); g.drawString(minStringY, d.width - PAD - maxWidth - 2, d2.height); maxWidth = m_fontMetrics.stringWidth(maxStringY); g.drawString(maxStringY, d.width - PAD - maxWidth - 2, hf); } } } } /** the number of visualizer windows we have open. */ protected static int m_WindowCount = 0; /** whether the exit if there are no more windows open */ protected static boolean m_ExitIfNoWindowsOpen = true; /** the training instances */ private Instances m_trainingInstances; /** the classifier to use */ private Classifier m_classifier; // plot area dimensions protected int m_plotAreaWidth = 384; // protected int m_plotAreaHeight = 384; protected int m_plotAreaHeight = 384; /** the plotting panel */ protected BoundaryPanel m_boundaryPanel; // combo boxes for selecting the class attribute, class values (for // colouring pixels), and visualization attributes protected JComboBox m_classAttBox = new JComboBox(); protected JComboBox m_xAttBox = new JComboBox(); protected JComboBox m_yAttBox = new JComboBox(); protected Dimension COMBO_SIZE = new Dimension( (int) (m_plotAreaWidth * 0.75), m_classAttBox.getPreferredSize().height); protected JButton m_startBut = new JButton("Start"); protected JCheckBox m_plotTrainingData = new JCheckBox("Plot training data"); protected JPanel m_controlPanel; protected ClassPanel m_classPanel = new ClassPanel(); // separate panels for rendering axis information private AxisPanel m_xAxisPanel; private AxisPanel m_yAxisPanel; // min and max values for visualization dimensions private double m_maxX; private double m_maxY; private double m_minX; private double m_minY; private int m_xIndex; private int m_yIndex; /* Kernel density estimator/generator */ private KDDataGenerator m_dataGenerator; /* number of samples per pixel (fixed dimensions only) */ private int m_numberOfSamplesFromEachRegion; /** base for sampling in the non-fixed dimensions */ private int m_generatorSamplesBase; /** Set the kernel bandwidth to cover this many nearest neighbours */ private int m_kernelBandwidth; private final JTextField m_regionSamplesText = new JTextField("" + 0); private final JTextField m_generatorSamplesText = new JTextField("" + 0); private final JTextField m_kernelBandwidthText = new JTextField("" + 3 + " "); // jimmy protected GenericObjectEditor m_classifierEditor = new GenericObjectEditor(); // the // widget // to // select // the // classifier protected PropertyPanel m_ClassifierPanel = new PropertyPanel( m_classifierEditor); /** The file chooser for selecting arff files */ protected JFileChooser m_FileChooser = new JFileChooser(new File( System.getProperty("user.dir"))); protected ExtensionFileFilter m_arffFileFilter = new ExtensionFileFilter( Instances.FILE_EXTENSION, "Arff data files"); protected JLabel dataFileLabel = new JLabel(); // stores the name of the data // file (currently stores // relation name rather than // filename) protected JPanel m_addRemovePointsPanel = new JPanel(); // a panel which // contains the // controls to add and // remove points protected JComboBox m_classValueSelector = new JComboBox(); // a widget to // select the // class // attribute. protected JRadioButton m_addPointsButton = new JRadioButton(); // when this is // selected, // clicking on // the // BoundaryPanel // will add // points. protected JRadioButton m_removePointsButton = new JRadioButton(); // when this // is // selected, // clicking // on the // BoundaryPanel // will // remove // points. protected ButtonGroup m_addRemovePointsButtonGroup = new ButtonGroup(); protected JButton removeAllButton = new JButton("Remove all"); // button to // remove all // points protected JButton chooseButton = new JButton("Open File"); // button to choose // a data file /* Register the property editors we need */ static { GenericObjectEditor.registerEditors(); } /** * Returns a string describing this tool * * @return a description of the tool suitable for displaying in various Weka * GUIs */ public String globalInfo() { return "Class for visualizing class probability estimates.\n\n" + "For more information, see\n\n" + getTechnicalInformation().toString(); } /** * Returns an instance of a TechnicalInformation object, containing detailed * information about the technical background of this class, e.g., paper * reference or book this class is based on. * * @return the technical information about this class */ @Override public TechnicalInformation getTechnicalInformation() { TechnicalInformation result; result = new TechnicalInformation(Type.INPROCEEDINGS); result.setValue(Field.AUTHOR, "Eibe Frank and Mark Hall"); result.setValue(Field.TITLE, "Visualizing class probability estimators"); result.setValue(Field.BOOKTITLE, "European Conference on Principles and Practice of " + "Knowledge Discovery in Databases"); result.setValue(Field.YEAR, "2003"); result.setValue(Field.PAGES, "168-169"); result.setValue(Field.PUBLISHER, "Springer-Verlag"); result.setValue(Field.ADDRESS, "Cavtat-Dubrovnik"); return result; } /** * Creates a new <code>BoundaryVisualizer</code> instance. */ public BoundaryVisualizer() { setLayout(new BorderLayout()); m_classAttBox.setMinimumSize(COMBO_SIZE); m_classAttBox.setPreferredSize(COMBO_SIZE); m_classAttBox.setMaximumSize(COMBO_SIZE); m_classAttBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (m_classAttBox.getItemCount() != 0) { try { m_classPanel.setCindex(m_classAttBox.getSelectedIndex()); plotTrainingData(); System.err.println("Here in class att box listener"); } catch (Exception ex) { ex.printStackTrace(); } // set up the add points selector combo box. -jimmy setUpClassValueSelectorCB(); } } }); m_xAttBox.setMinimumSize(COMBO_SIZE); m_xAttBox.setPreferredSize(COMBO_SIZE); m_xAttBox.setMaximumSize(COMBO_SIZE); m_yAttBox.setMinimumSize(COMBO_SIZE); m_yAttBox.setPreferredSize(COMBO_SIZE); m_yAttBox.setMaximumSize(COMBO_SIZE); m_classPanel.setMinimumSize(new Dimension((int) COMBO_SIZE.getWidth() * 2, (int) COMBO_SIZE.getHeight() * 2)); m_classPanel.setPreferredSize(new Dimension( (int) COMBO_SIZE.getWidth() * 2, (int) COMBO_SIZE.getHeight() * 2)); m_controlPanel = new JPanel(); m_controlPanel.setLayout(new BorderLayout()); // jimmy JPanel dataChooseHolder = new JPanel(new BorderLayout()); dataChooseHolder.setBorder(BorderFactory.createTitledBorder("Dataset")); dataChooseHolder.add(dataFileLabel, BorderLayout.WEST); m_FileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); m_FileChooser.addChoosableFileFilter(m_arffFileFilter); chooseButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { setInstancesFromFileQ(); int classIndex = m_classAttBox.getSelectedIndex(); if (m_trainingInstances != null && m_classifier != null && (m_trainingInstances.attribute(classIndex).isNominal())) { m_startBut.setEnabled(true); // plotTrainingData(); } } catch (Exception ex) { ex.printStackTrace(System.out); System.err.println("exception"); } } }); dataChooseHolder.add(chooseButton, BorderLayout.EAST); JPanel classifierHolder = new JPanel(); classifierHolder.setBorder(BorderFactory.createTitledBorder("Classifier")); classifierHolder.setLayout(new BorderLayout()); m_classifierEditor.setClassType(weka.classifiers.Classifier.class); m_classifierEditor.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { m_classifier = (Classifier) m_classifierEditor.getValue(); try { int classIndex = m_classAttBox.getSelectedIndex(); if (m_trainingInstances != null && m_classifier != null && (m_trainingInstances.attribute(classIndex).isNominal())) { m_startBut.setEnabled(true); } } catch (Exception ex) { } ; } }); classifierHolder.add(m_ClassifierPanel, BorderLayout.CENTER); JPanel cHolder = new JPanel(); cHolder.setBorder(BorderFactory.createTitledBorder("Class Attribute")); cHolder.add(m_classAttBox); JPanel vAttHolder = new JPanel(); vAttHolder.setLayout(new GridLayout(2, 1)); vAttHolder.setBorder(BorderFactory .createTitledBorder("Visualization Attributes")); vAttHolder.add(m_xAttBox); vAttHolder.add(m_yAttBox); JPanel colOne = new JPanel(); colOne.setLayout(new BorderLayout()); colOne.add(dataChooseHolder, BorderLayout.NORTH); // jimmy colOne.add(cHolder, BorderLayout.CENTER); // colOne.add(vAttHolder, BorderLayout.SOUTH); JPanel tempPanel = new JPanel(); tempPanel.setBorder(BorderFactory.createTitledBorder("Sampling control")); tempPanel.setLayout(new GridLayout(3, 1)); JPanel colTwo = new JPanel(); colTwo.setLayout(new BorderLayout()); JPanel gsP = new JPanel(); gsP.setLayout(new BorderLayout()); gsP.add(new JLabel(" Base for sampling (r)"), BorderLayout.CENTER); gsP.add(m_generatorSamplesText, BorderLayout.WEST); tempPanel.add(gsP); JPanel rsP = new JPanel(); rsP.setLayout(new BorderLayout()); rsP.add(new JLabel(" Num. locations per pixel"), BorderLayout.CENTER); rsP.add(m_regionSamplesText, BorderLayout.WEST); tempPanel.add(rsP); JPanel ksP = new JPanel(); ksP.setLayout(new BorderLayout()); ksP.add(new JLabel(" Kernel bandwidth (k)"), BorderLayout.CENTER); ksP.add(m_kernelBandwidthText, BorderLayout.WEST); tempPanel.add(ksP); colTwo.add(classifierHolder, BorderLayout.NORTH);// jimmy // colTwo.add(tempPanel, BorderLayout.CENTER); colTwo.add(vAttHolder, BorderLayout.CENTER); JPanel startPanel = new JPanel(); startPanel.setBorder(BorderFactory.createTitledBorder("Plotting")); startPanel.setLayout(new BorderLayout()); startPanel.add(m_startBut, BorderLayout.CENTER); startPanel.add(m_plotTrainingData, BorderLayout.WEST); // colTwo.add(startPanel, BorderLayout.SOUTH); m_controlPanel.add(colOne, BorderLayout.WEST); m_controlPanel.add(colTwo, BorderLayout.CENTER); JPanel classHolder = new JPanel(); classHolder.setLayout(new BorderLayout()); // jimmy classHolder.setBorder(BorderFactory.createTitledBorder("Class color")); classHolder.add(m_classPanel, BorderLayout.CENTER); m_controlPanel.add(classHolder, BorderLayout.SOUTH); JPanel aboutAndControlP = new JPanel(); aboutAndControlP.setLayout(new BorderLayout()); aboutAndControlP.add(m_controlPanel, BorderLayout.SOUTH); weka.gui.PropertySheetPanel psp = new weka.gui.PropertySheetPanel(); psp.setTarget(BoundaryVisualizer.this); JPanel aboutPanel = psp.getAboutPanel(); aboutAndControlP.add(aboutPanel, BorderLayout.NORTH); add(aboutAndControlP, BorderLayout.NORTH); // classHolder.add(newWindowButton, BorderLayout.EAST); // set up the add-remove points widgets m_addRemovePointsPanel.setBorder(BorderFactory .createTitledBorder("Add / remove data points")); m_addRemovePointsPanel.setLayout(new GridBagLayout()); GridBagConstraints constraints = new GridBagConstraints(); constraints.weightx = 1.0; constraints.weighty = 1.0; constraints.gridx = 0; constraints.gridy = 0; constraints.fill = GridBagConstraints.BOTH; m_addRemovePointsPanel.add(m_addPointsButton); constraints.gridx = 1; m_addRemovePointsPanel.add(new JLabel("Add points"), constraints); constraints.gridx = 2; m_addRemovePointsPanel.add(m_classValueSelector); constraints.gridx = 0; constraints.gridy = 1; m_addRemovePointsPanel.add(m_removePointsButton, constraints); constraints.gridx = 1; m_addRemovePointsPanel.add(new JLabel("Remove points"), constraints); removeAllButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (m_trainingInstances != null) { if (m_startBut.getText().equals("Stop")) { return; } m_boundaryPanel.removeAllInstances(); computeBounds(); m_xAxisPanel.repaint(0, 0, 0, m_xAxisPanel.getWidth(), m_xAxisPanel.getHeight()); m_yAxisPanel.repaint(0, 0, 0, m_yAxisPanel.getWidth(), m_yAxisPanel.getHeight()); try { m_boundaryPanel.plotTrainingData(); } catch (Exception ex) { } } } }); constraints.gridx = 2; m_addRemovePointsPanel.add(removeAllButton, constraints); // m_addRemovePointsPanel.add(addPointsFrame, BorderLayout.NORTH); // m_addRemovePointsPanel.add(removePointsFrame, BorderLayout.CENTER); // m_addRemovePointsPanel.add(removeAllButton, BorderLayout.SOUTH); m_addRemovePointsButtonGroup.add(m_addPointsButton); m_addRemovePointsButtonGroup.add(m_removePointsButton); m_addPointsButton.setSelected(true); // classHolder.add(m_addRemovePointsPanel, BorderLayout.SOUTH); m_boundaryPanel = new BoundaryPanel(m_plotAreaWidth, m_plotAreaHeight); m_numberOfSamplesFromEachRegion = m_boundaryPanel.getNumSamplesPerRegion(); m_regionSamplesText.setText("" + m_numberOfSamplesFromEachRegion + " "); m_generatorSamplesBase = (int) m_boundaryPanel.getGeneratorSamplesBase(); m_generatorSamplesText.setText("" + m_generatorSamplesBase + " "); m_dataGenerator = new KDDataGenerator(); m_kernelBandwidth = m_dataGenerator.getKernelBandwidth(); m_kernelBandwidthText.setText("" + m_kernelBandwidth + " "); m_boundaryPanel.setDataGenerator(m_dataGenerator); JPanel gfxPanel = new JPanel(); gfxPanel.setLayout(new BorderLayout()); gfxPanel.setBorder(BorderFactory.createEtchedBorder()); // add(gfxPanel, BorderLayout.CENTER); // gfxPanel.add(m_addRemovePointsPanel, BorderLayout.NORTH); gfxPanel.add(m_boundaryPanel, BorderLayout.CENTER); m_xAxisPanel = new AxisPanel(false); gfxPanel.add(m_xAxisPanel, BorderLayout.SOUTH); m_yAxisPanel = new AxisPanel(true); gfxPanel.add(m_yAxisPanel, BorderLayout.WEST); JPanel containerPanel = new JPanel(); containerPanel.setLayout(new BorderLayout()); containerPanel.add(gfxPanel, BorderLayout.CENTER); add(containerPanel, BorderLayout.WEST); JPanel rightHandToolsPanel = new JPanel(); // this panel contains the // widgets to the right of the // BoundaryPanel. rightHandToolsPanel.setLayout(new BoxLayout(rightHandToolsPanel, BoxLayout.PAGE_AXIS)); rightHandToolsPanel.add(m_addRemovePointsPanel); JButton newWindowButton = new JButton("Open a new window"); // the button // for spawning // a new window // for the // program. // newWindowButton.setMaximumSize(new Dimension(100, 100)); // newWindowButton.setPreferredSize(new Dimension(120, // m_addRemovePointsPanel.getHeight())); newWindowButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { Instances newTrainingData = null; Classifier newClassifier = null; if (m_trainingInstances != null) { newTrainingData = new Instances(m_trainingInstances); } if (m_classifier != null) { newClassifier = AbstractClassifier.makeCopy(m_classifier); } createNewVisualizerWindow(newClassifier, newTrainingData); } catch (Exception ex) { ex.printStackTrace(); } } }); JPanel newWindowHolder = new JPanel(); newWindowHolder.add(newWindowButton); rightHandToolsPanel.add(newWindowHolder); rightHandToolsPanel.add(tempPanel); rightHandToolsPanel.add(startPanel); containerPanel.add(rightHandToolsPanel, BorderLayout.EAST); /* * add(m_boundaryPanel, BorderLayout.CENTER); * * m_xAxisPanel = new AxisPanel(false); add(m_xAxisPanel, * BorderLayout.SOUTH); m_yAxisPanel = new AxisPanel(true); * add(m_yAxisPanel, BorderLayout.WEST); */ m_startBut.setEnabled(false); m_startBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (m_startBut.getText().equals("Start")) { if (m_trainingInstances != null && m_classifier != null) { try { int BPSuccessCode = setUpBoundaryPanel(); // set up the boundary // panel, find out if it // was successful or // not. if (BPSuccessCode == 1) { JOptionPane.showMessageDialog(null, "Error: Kernel Bandwidth can't be less than zero!"); } else if (BPSuccessCode == 2) { JOptionPane .showMessageDialog(null, "Error: Kernel Bandwidth must be less than the number of training instances!"); } else { m_boundaryPanel.start(); m_startBut.setText("Stop"); setControlEnabledStatus(false); } } catch (Exception ex) { ex.printStackTrace(); } } } else { m_boundaryPanel.stopPlotting(); m_startBut.setText("Start"); setControlEnabledStatus(true); } } }); m_boundaryPanel.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m_startBut.setText("Start"); setControlEnabledStatus(true); } }); m_classPanel.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { // save color vector to a file ArrayList<Color> colors = m_boundaryPanel.getColors(); FileOutputStream fos = new FileOutputStream("colors.ser"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(colors); oos.flush(); oos.close(); } catch (Exception ex) { } m_boundaryPanel.replot(); } }); // set up a mouse listener for the boundary panel. m_boundaryPanel.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { // System.err.println("boundary panel mouseClick " + e.getX() + " " + // e.getY()); if (m_trainingInstances != null) { if (m_startBut.getText().equals("Stop")) { return; } if (m_addPointsButton.isSelected()) {// we are in add mode double classVal = 0; boolean validInput = true; if (m_trainingInstances.attribute(m_classAttBox.getSelectedIndex()) .isNominal()) { classVal = m_classValueSelector.getSelectedIndex(); } else { String indexStr = ""; try { indexStr = (String) m_classValueSelector.getSelectedItem(); classVal = Double.parseDouble(indexStr); } catch (Exception ex) { if (indexStr == null) { indexStr = ""; } JOptionPane.showMessageDialog(null, "Error adding a point: \"" + indexStr + "\"" + " is not a valid class value."); validInput = false; } } // System.err.println("classVal is " + classVal); if (validInput) { m_boundaryPanel.addTrainingInstanceFromMouseLocation(e.getX(), e.getY(), m_classAttBox.getSelectedIndex(), classVal); } } else { // remove mode m_boundaryPanel.removeTrainingInstanceFromMouseLocation(e.getX(), e.getY()); } try { plotTrainingData(); } catch (Exception ex) { } // jimmy m_xAxisPanel.repaint(0, 0, 0, m_xAxisPanel.getWidth(), m_xAxisPanel.getHeight()); m_yAxisPanel.repaint(0, 0, 0, m_yAxisPanel.getWidth(), m_yAxisPanel.getHeight()); } } }); } /** * Set the enabled status of the controls * * @param status a <code>boolean</code> value */ private void setControlEnabledStatus(boolean status) { m_classAttBox.setEnabled(status); m_xAttBox.setEnabled(status); m_yAttBox.setEnabled(status); m_regionSamplesText.setEnabled(status); m_generatorSamplesText.setEnabled(status); m_kernelBandwidthText.setEnabled(status); m_plotTrainingData.setEnabled(status); removeAllButton.setEnabled(status); m_classValueSelector.setEnabled(status); m_addPointsButton.setEnabled(status); m_removePointsButton.setEnabled(status); m_FileChooser.setEnabled(status); chooseButton.setEnabled(status); } /** * Set a classifier to use * * @param newClassifier the classifier to use * @exception Exception if an error occurs */ public void setClassifier(Classifier newClassifier) throws Exception { m_classifier = newClassifier; try { int classIndex = m_classAttBox.getSelectedIndex(); if ((m_classifier != null) && (m_trainingInstances != null) && (m_trainingInstances.attribute(classIndex).isNominal())) { m_startBut.setEnabled(true); } else { m_startBut.setEnabled(false); } } catch (Exception e) { } } /** * Sets up the bounds on our x and y axes to fit the dataset. Also repaints * the x and y axes. */ private void computeBounds() { m_boundaryPanel.computeMinMaxAtts(); // delegate to the BoundaryPanel String xName = (String) m_xAttBox.getSelectedItem(); if (xName == null) { return; } xName = Utils.removeSubstring(xName, "X: "); xName = Utils.removeSubstring(xName, " (Num)"); String yName = (String) m_yAttBox.getSelectedItem(); yName = Utils.removeSubstring(yName, "Y: "); yName = Utils.removeSubstring(yName, " (Num)"); m_xIndex = -1; m_yIndex = -1; for (int i = 0; i < m_trainingInstances.numAttributes(); i++) { if (m_trainingInstances.attribute(i).name().equals(xName)) { m_xIndex = i; } if (m_trainingInstances.attribute(i).name().equals(yName)) { m_yIndex = i; } } m_minX = m_boundaryPanel.getMinXBound(); m_minY = m_boundaryPanel.getMinYBound(); m_maxX = m_boundaryPanel.getMaxXBound(); m_maxY = m_boundaryPanel.getMaxYBound(); // System.err.println("setting bounds to " + m_minX + " " + m_minY + " " + // m_maxX + " " + m_maxY); m_xAxisPanel.repaint(0, 0, 0, m_xAxisPanel.getWidth(), m_xAxisPanel.getHeight()); m_yAxisPanel.repaint(0, 0, 0, m_yAxisPanel.getWidth(), m_yAxisPanel.getHeight()); } /** * Get the training instances * * @return the training instances */ public Instances getInstances() { return m_trainingInstances; } /** * Set the training instances * * @param inst the instances to use */ public void setInstances(Instances inst) throws Exception { if (inst == null) { m_trainingInstances = inst; m_classPanel.setInstances(m_trainingInstances); return; } // count the number of numeric attributes int numCount = 0; for (int i = 0; i < inst.numAttributes(); i++) { if (inst.attribute(i).isNumeric()) { numCount++; } } if (numCount < 2) { JOptionPane.showMessageDialog(null, "We need at least two numeric " + "attributes in order to visualize!"); return; } m_trainingInstances = inst; m_classPanel.setInstances(m_trainingInstances); // setup combo boxes String[] classAttNames = new String[m_trainingInstances.numAttributes()]; final Vector<String> xAttNames = new Vector<String>(); Vector<String> yAttNames = new Vector<String>(); for (int i = 0; i < m_trainingInstances.numAttributes(); i++) { classAttNames[i] = m_trainingInstances.attribute(i).name(); String type = " (" + Attribute.typeToStringShort(m_trainingInstances.attribute(i)) + ")"; classAttNames[i] += type; if (m_trainingInstances.attribute(i).isNumeric()) { xAttNames.add("X: " + classAttNames[i]); yAttNames.add("Y: " + classAttNames[i]); } } m_classAttBox.setModel(new DefaultComboBoxModel(classAttNames)); m_xAttBox.setModel(new DefaultComboBoxModel(xAttNames)); m_yAttBox.setModel(new DefaultComboBoxModel(yAttNames)); if (xAttNames.size() > 1) { m_yAttBox.setSelectedIndex(1); } m_classAttBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { configureForClassAttribute(); } }); m_xAttBox.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { /* * if (xAttNames.size() > 1) { if (m_xAttBox.getSelectedIndex() == * m_yAttBox.getSelectedIndex()) { * m_xAttBox.setSelectedIndex((m_xAttBox.getSelectedIndex() + 1) % * xAttNames.size()); } } */ computeBounds(); repaint(); try { plotTrainingData(); } catch (Exception ex) { ex.printStackTrace(); } // jimmy } } }); m_yAttBox.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { /* * if (xAttNames.size() > 1) { if (m_yAttBox.getSelectedIndex() == * m_xAttBox.getSelectedIndex()) { * m_yAttBox.setSelectedIndex((m_yAttBox.getSelectedIndex() + 1) % * xAttNames.size()); } } */ computeBounds(); repaint(); try { plotTrainingData(); } catch (Exception ex) { ex.printStackTrace(); } } } }); if (classAttNames.length > 0) { m_classAttBox.setSelectedIndex(classAttNames.length - 1); // select last // attribute as // class by // default. // -jimmy } // set up the add points selector combo box setUpClassValueSelectorCB(); configureForClassAttribute(); m_classPanel.setCindex(m_classAttBox.getSelectedIndex()); plotTrainingData(); computeBounds(); revalidate(); repaint(); if (getTopLevelAncestor() instanceof java.awt.Window) { ((java.awt.Window) getTopLevelAncestor()).pack(); } } /** * Set up the combo box that chooses which class values to use when adding * data points. */ private void setUpClassValueSelectorCB() { m_classValueSelector.removeAllItems(); int classAttribute = m_classAttBox.getSelectedIndex(); // System.err.println(m_trainingInstances.numClasses() + " classes"); m_trainingInstances.setClassIndex(classAttribute); if (m_trainingInstances.attribute(classAttribute).isNominal()) { m_classValueSelector.setEditable(false); for (int i = 0; i < /* * m_trainingInstances.numDistinctValues(classAttribute * ) */m_trainingInstances.numClasses(); i++) { m_classValueSelector.insertItemAt( m_trainingInstances.attribute(classAttribute).value(i), i); } m_classValueSelector.setSelectedIndex(0); } else { m_classValueSelector.setEditable(true); } } /** * Set up the class values combo boxes */ private void configureForClassAttribute() { int classIndex = m_classAttBox.getSelectedIndex(); if (classIndex >= 0) { // see if this is a nominal attribute if (!m_trainingInstances.attribute(classIndex).isNominal() || m_classifier == null) { m_startBut.setEnabled(false); } else { m_startBut.setEnabled(true); } // set up class colours ArrayList<Color> colors = new ArrayList<Color>(); if (!m_trainingInstances.attribute(m_classAttBox.getSelectedIndex()) .isNominal()) // this if by jimmy { for (Color element : BoundaryPanel.DEFAULT_COLORS) { colors.add(element); } } else { for (int i = 0; i < m_trainingInstances.attribute(classIndex) .numValues(); i++) { colors.add(BoundaryPanel.DEFAULT_COLORS[i % BoundaryPanel.DEFAULT_COLORS.length]); // m_classPanel.setColours(colors); // m_boundaryPanel.setColors(colors); } } m_classPanel.setColours(colors); // jimmy m_boundaryPanel.setColors(colors); } } /** * Queries the user for a file to load instances from, then loads the * instances in a background process. This is done in the IO thread, and an * error message is popped up if the IO thread is busy. */ public void setInstancesFromFileQ() { // if (m_IOThread == null) { int returnVal = m_FileChooser.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { File selected = m_FileChooser.getSelectedFile(); try { java.io.Reader r = new java.io.BufferedReader(new java.io.FileReader( selected)); Instances i = new Instances(r); setInstances(i); // dataFileLabel.setText(selected.getName()); String relationName = i.relationName(); String truncatedN = relationName; if (relationName.length() > 25) { truncatedN = relationName.substring(0, 25) + "..."; } dataFileLabel.setText(truncatedN); dataFileLabel.setToolTipText(relationName); } catch (Exception e) { JOptionPane.showMessageDialog(this, "Can't load at this time,\n" + "currently busy with other IO", "Load Instances", JOptionPane.WARNING_MESSAGE); e.printStackTrace(); } } } /** * Sets up the BoundaryPanel object so that it is ready for plotting. * * @return an error code:<br/> * 0 - SUCCESS<br/> * 1 - ERROR - Kernel bandwidth < 0<br/> * 2 - ERROR - Kernel bandwidth >= number of training instances. */ public int setUpBoundaryPanel() throws Exception { int returner = 0; // OK code. int tempSamples = m_numberOfSamplesFromEachRegion; try { tempSamples = Integer.parseInt(m_regionSamplesText.getText().trim()); } catch (Exception ex) { m_regionSamplesText.setText("" + tempSamples); } m_numberOfSamplesFromEachRegion = tempSamples; m_boundaryPanel.setNumSamplesPerRegion(tempSamples); tempSamples = m_generatorSamplesBase; try { tempSamples = Integer.parseInt(m_generatorSamplesText.getText().trim()); } catch (Exception ex) { m_generatorSamplesText.setText("" + tempSamples); } m_generatorSamplesBase = tempSamples; m_boundaryPanel.setGeneratorSamplesBase(tempSamples); tempSamples = m_kernelBandwidth; try { tempSamples = Integer.parseInt(m_kernelBandwidthText.getText().trim()); } catch (Exception ex) { m_kernelBandwidthText.setText("" + tempSamples); } m_kernelBandwidth = tempSamples; m_dataGenerator.setKernelBandwidth(tempSamples); if (m_kernelBandwidth < 0) { returner = 1; } if (m_kernelBandwidth >= m_trainingInstances.numInstances()) { returner = 2; } m_trainingInstances.setClassIndex(m_classAttBox.getSelectedIndex()); m_boundaryPanel.setClassifier(m_classifier); m_boundaryPanel.setTrainingData(m_trainingInstances); m_boundaryPanel.setXAttribute(m_xIndex); m_boundaryPanel.setYAttribute(m_yIndex); m_boundaryPanel.setPlotTrainingData(m_plotTrainingData.isSelected()); return returner; } /** * Plots the training data on-screen. Also does all of the setup required for * this to work. */ public void plotTrainingData() throws Exception { m_boundaryPanel.initialize(); setUpBoundaryPanel(); computeBounds(); m_boundaryPanel.plotTrainingData(); } /** * Stops the plotting thread. */ public void stopPlotting() { m_boundaryPanel.stopPlotting(); } /** * Sets whether System.exit gets called when no more windows are open. * * @param value if TRUE then a System.exit call is ossued after the last * window gets closed. */ public static void setExitIfNoWindowsOpen(boolean value) { m_ExitIfNoWindowsOpen = value; } /** * Gets whether System.exit gets called after the last window gets closed * * @return TRUE if System.exit gets called after last window got closed. */ public static boolean getExitIfNoWindowsOpen() { return m_ExitIfNoWindowsOpen; } /** * Creates a new GUI window with all of the BoundaryVisualizer trappings, * * @param classifier The classifier to use in the new window. May be null. * @param instances The dataset to visualize on in the new window. May be * null. */ public static void createNewVisualizerWindow(Classifier classifier, Instances instances) throws Exception { m_WindowCount++; final javax.swing.JFrame jf = new javax.swing.JFrame( "Weka classification boundary visualizer"); jf.getContentPane().setLayout(new BorderLayout()); final BoundaryVisualizer bv = new BoundaryVisualizer(); jf.getContentPane().add(bv, BorderLayout.CENTER); jf.setSize(bv.getMinimumSize()); jf.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { m_WindowCount--; bv.stopPlotting(); jf.dispose(); if ((m_WindowCount == 0) && m_ExitIfNoWindowsOpen) { System.exit(0); } } }); jf.pack(); jf.setVisible(true); jf.setResizable(false); if (classifier == null) { bv.setClassifier(null); } else { bv.setClassifier(classifier); bv.m_classifierEditor.setValue(classifier); } if (instances == null) { bv.setInstances(null); } else { bv.setInstances(instances); try { bv.dataFileLabel.setText(instances.relationName()); bv.plotTrainingData(); bv.m_classPanel.setCindex(bv.m_classAttBox.getSelectedIndex()); bv.repaint(0, 0, 0, bv.getWidth(), bv.getHeight()); } catch (Exception ex) { } } } /** * Main method for testing this class * * @param args a <code>String[]</code> value */ public static void main(String[] args) { weka.core.logging.Logger.log(weka.core.logging.Logger.Level.INFO, "Logging started"); try { if (args.length < 2) { createNewVisualizerWindow(null, null); } else { String[] argsR = null; if (args.length > 2) { argsR = new String[args.length - 2]; for (int j = 2; j < args.length; j++) { argsR[j - 2] = args[j]; } } Classifier c = AbstractClassifier.forName(args[1], argsR); System.err.println("Loading instances from : " + args[0]); java.io.Reader r = new java.io.BufferedReader(new java.io.FileReader( args[0])); Instances i = new Instances(r); createNewVisualizerWindow(c, i); } } 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/boundaryvisualizer/DataGenerator.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * DataGenerator.java * Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.boundaryvisualizer; import weka.core.Instances; /** * Interface to something that can generate new instances based on * a set of input instances * * @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a> * @version $Revision$ * @since 1.0 */ public interface DataGenerator { /** * Build the data generator * * @param inputInstances Instances to build the generator from * @exception Exception if an error occurs */ void buildGenerator(Instances inputInstances) throws Exception; /** * Generate an instance. Should return a new Instance object * * @return an <code>Instance</code> value * @exception Exception if an error occurs */ double [][] generateInstances(int [] indices) throws Exception; /** * Get weights */ double [] getWeights() throws Exception; /** * Set the dimensions to be used in computing a weight for * each instance generated * * @param dimensions an array of booleans specifying the dimensions to * be used when computing instance weights */ void setWeightingDimensions(boolean [] dimensions); /** * Set the values of the dimensions (chosen via setWeightingDimensions) * to be used when computing instance weights * * @param vals a <code>double[]</code> value */ void setWeightingValues(double [] vals); /** * Returns the number of generating models used by this DataGenerator * * @return an <code>int</code> value */ int getNumGeneratingModels(); /** * Set a seed for random number generation (if needed). * * @param seed an <code>int</code> value */ void setSeed(int seed); }
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/boundaryvisualizer/KDDataGenerator.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * KDDataGenerator.java * Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.boundaryvisualizer; import java.io.Serializable; import java.util.Random; import weka.core.Attribute; import weka.core.Instance; import weka.core.Instances; import weka.core.Utils; /** * KDDataGenerator. Class that uses kernels to generate new random instances * based on a supplied set of instances. * * @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a> * @version $Revision$ * @since 1.0 * @see DataGenerator * @see Serializable */ public class KDDataGenerator implements DataGenerator, Serializable { /** for serialization */ private static final long serialVersionUID = -958573275606402792L; /** the instances to use */ private Instances m_instances; /** * standard deviations of the normal distributions for numeric attributes in * each KD estimator */ // private double [] m_standardDeviations; /** global means or modes to use for missing values */ private double[] m_globalMeansOrModes; /** minimum standard deviation for numeric attributes */ // private double m_minStdDev = 1e-5; NOT USED /** Laplace correction for discrete distributions */ private final double m_laplaceConst = 1.0; /** random number seed */ private int m_seed = 1; /** random number generator */ private Random m_random; /** * which dimensions to use for computing a weight for each generated instance */ private boolean[] m_weightingDimensions; /** * the values for the weighting dimensions to use for computing the weight for * the next instance to be generated */ private double[] m_weightingValues; private static double m_normConst = Math.sqrt(2 * Math.PI); /** Number of neighbours to use for kernel bandwidth */ private int m_kernelBandwidth = 3; /** * standard deviations for numeric attributes computed from the * m_kernelBandwidth nearest neighbours for each kernel. */ private double[][] m_kernelParams; /** The minimum values for numeric attributes. */ protected double[] m_Min; /** The maximum values for numeric attributes. */ protected double[] m_Max; /** * Initialize the generator using the supplied instances * * @param inputInstances the instances to use as the basis of the kernels * @throws Exception if an error occurs */ @Override public void buildGenerator(Instances inputInstances) throws Exception { m_random = new Random(m_seed); m_instances = inputInstances; // m_standardDeviations = new double[m_instances.numAttributes()]; NOT USED m_globalMeansOrModes = new double[m_instances.numAttributes()]; if (m_weightingDimensions == null) { m_weightingDimensions = new boolean[m_instances.numAttributes()]; } /* * for (int i = 0; i < m_instances.numAttributes(); i++) { if (i != * m_instances.classIndex()) { if (m_instances.attribute(i).isNumeric()) { * // global standard deviations double var = m_instances.variance(i); if * (var == 0) { var = m_minStdDev; } else { var = Math.sqrt(var); // * heuristic to take into account # instances and dimensions double adjust = * Math.pow((double) m_instances.numInstances(), 1.0 / * m_instances.numAttributes()); // double adjust = * m_instances.numInstances(); var /= adjust; } m_standardDeviations[i] = * var; } else { m_globalMeansOrModes[i] = m_instances.meanOrMode(i); } } } */ for (int i = 0; i < m_instances.numAttributes(); i++) { if (i != m_instances.classIndex()) { m_globalMeansOrModes[i] = m_instances.meanOrMode(i); } } m_kernelParams = new double[m_instances.numInstances()][m_instances .numAttributes()]; computeParams(); } @Override public double[] getWeights() { double[] weights = new double[m_instances.numInstances()]; for (int k = 0; k < m_instances.numInstances(); k++) { double weight = 1; for (int i = 0; i < m_instances.numAttributes(); i++) { if (m_weightingDimensions[i]) { double mean = 0; if (!m_instances.instance(k).isMissing(i)) { mean = m_instances.instance(k).value(i); } else { mean = m_globalMeansOrModes[i]; } double wm = 1.0; // wm = normalDens(m_weightingValues[i], mean, // m_standardDeviations[i]); wm = normalDens(m_weightingValues[i], mean, m_kernelParams[k][i]); weight *= wm; } } weights[k] = weight; } return weights; } /** * Return a cumulative distribution from a discrete distribution * * @param dist the distribution to use * @return the cumulative distribution */ private double[] computeCumulativeDistribution(double[] dist) { double[] cumDist = new double[dist.length]; double sum = 0; for (int i = 0; i < dist.length; i++) { sum += dist[i]; cumDist[i] = sum; } return cumDist; } /** * Generates a new instance using one kernel estimator. Each successive call * to this method incremets the index of the kernel to use. * * @return the new random instance * @throws Exception if an error occurs */ @Override public double[][] generateInstances(int[] indices) throws Exception { double[][] values = new double[m_instances.numInstances()][]; for (int k = 0; k < indices.length; k++) { values[indices[k]] = new double[m_instances.numAttributes()]; for (int i = 0; i < m_instances.numAttributes(); i++) { if ((!m_weightingDimensions[i]) && (i != m_instances.classIndex())) { if (m_instances.attribute(i).isNumeric()) { double mean = 0; double val = m_random.nextGaussian(); if (!m_instances.instance(indices[k]).isMissing(i)) { mean = m_instances.instance(indices[k]).value(i); } else { mean = m_globalMeansOrModes[i]; } val *= m_kernelParams[indices[k]][i]; val += mean; values[indices[k]][i] = val; } else { // nominal attribute double[] dist = new double[m_instances.attribute(i).numValues()]; for (int j = 0; j < dist.length; j++) { dist[j] = m_laplaceConst; } if (!m_instances.instance(indices[k]).isMissing(i)) { dist[(int) m_instances.instance(indices[k]).value(i)]++; } else { dist[(int) m_globalMeansOrModes[i]]++; } Utils.normalize(dist); double[] cumDist = computeCumulativeDistribution(dist); double randomVal = m_random.nextDouble(); int instVal = 0; for (int j = 0; j < cumDist.length; j++) { if (randomVal <= cumDist[j]) { instVal = j; break; } } values[indices[k]][i] = instVal; } } } } return values; } /** * Density function of normal distribution. * * @param x input value * @param mean mean of distribution * @param stdDev standard deviation of distribution */ private double normalDens(double x, double mean, double stdDev) { double diff = x - mean; return (1 / (m_normConst * stdDev)) * Math.exp(-(diff * diff / (2 * stdDev * stdDev))); } /** * Set which dimensions to use when computing a weight for the next instance * to generate * * @param dims an array of booleans indicating which dimensions to use */ @Override public void setWeightingDimensions(boolean[] dims) { m_weightingDimensions = dims; } /** * Set the values for the weighting dimensions to be used when computing the * weight for the next instance to be generated * * @param vals an array of doubles containing the values of the weighting * dimensions (corresponding to the entries that are set to true * throw setWeightingDimensions) */ @Override public void setWeightingValues(double[] vals) { m_weightingValues = vals; } /** * Return the number of kernels (there is one per training instance) * * @return the number of kernels */ @Override public int getNumGeneratingModels() { if (m_instances != null) { return m_instances.numInstances(); } return 0; } /** * Set the kernel bandwidth (number of nearest neighbours to cover) * * @param kb an <code>int</code> value */ public void setKernelBandwidth(int kb) { m_kernelBandwidth = kb; } /** * Get the kernel bandwidth * * @return an <code>int</code> value */ public int getKernelBandwidth() { return m_kernelBandwidth; } /** * Initializes a new random number generator using the supplied seed. * * @param seed an <code>int</code> value */ @Override public void setSeed(int seed) { m_seed = seed; m_random = new Random(m_seed); } /** * Calculates the distance between two instances * * @param test the first instance * @param train the second instance * @return the distance between the two given instances, between 0 and 1 */ private double distance(Instance first, Instance second) { double diff, distance = 0; for (int i = 0; i < m_instances.numAttributes(); i++) { if (i == m_instances.classIndex()) { continue; } double firstVal = m_globalMeansOrModes[i]; double secondVal = m_globalMeansOrModes[i]; switch (m_instances.attribute(i).type()) { case Attribute.NUMERIC: // If attribute is numeric if (!first.isMissing(i)) { firstVal = first.value(i); } if (!second.isMissing(i)) { secondVal = second.value(i); } diff = norm(firstVal, i) - norm(secondVal, i); break; default: diff = 0; break; } distance += diff * diff; } return Math.sqrt(distance); } /** * Normalizes a given value of a numeric attribute. * * @param x the value to be normalized * @param i the attribute's index */ private double norm(double x, int i) { if (Double.isNaN(m_Min[i]) || Utils.eq(m_Max[i], m_Min[i])) { return 0; } else { return (x - m_Min[i]) / (m_Max[i] - m_Min[i]); } } /** * Updates the minimum and maximum values for all the attributes based on a * new instance. * * @param instance the new instance */ private void updateMinMax(Instance instance) { for (int j = 0; j < m_instances.numAttributes(); j++) { if (!instance.isMissing(j)) { if (Double.isNaN(m_Min[j])) { m_Min[j] = instance.value(j); m_Max[j] = instance.value(j); } else if (instance.value(j) < m_Min[j]) { m_Min[j] = instance.value(j); } else if (instance.value(j) > m_Max[j]) { m_Max[j] = instance.value(j); } } } } private void computeParams() throws Exception { // Calculate the minimum and maximum values m_Min = new double[m_instances.numAttributes()]; m_Max = new double[m_instances.numAttributes()]; for (int i = 0; i < m_instances.numAttributes(); i++) { m_Min[i] = m_Max[i] = Double.NaN; } for (int i = 0; i < m_instances.numInstances(); i++) { updateMinMax(m_instances.instance(i)); } double[] distances = new double[m_instances.numInstances()]; for (int i = 0; i < m_instances.numInstances(); i++) { Instance current = m_instances.instance(i); for (int j = 0; j < m_instances.numInstances(); j++) { distances[j] = distance(current, m_instances.instance(j)); } int[] sorted = Utils.sort(distances); int k = m_kernelBandwidth; double bandwidth = distances[sorted[k]]; // Check for bandwidth zero if (bandwidth <= 0) { for (int j = k + 1; j < sorted.length; j++) { if (distances[sorted[j]] > bandwidth) { bandwidth = distances[sorted[j]]; break; } } if (bandwidth <= 0) { throw new Exception("All training instances coincide with " + "test instance!"); } } for (int j = 0; j < m_instances.numAttributes(); j++) { if ((m_Max[j] - m_Min[j]) > 0) { m_kernelParams[i][j] = bandwidth * (m_Max[j] - m_Min[j]); } } } } }
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/boundaryvisualizer/RemoteBoundaryVisualizerSubTask.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * RemoteBoundaryVisualizerSubTask.java * Copyright (C) 2003-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.boundaryvisualizer; import java.util.Random; import weka.classifiers.Classifier; import weka.core.DenseInstance; import weka.core.Instance; import weka.core.Instances; import weka.core.Utils; import weka.experiment.Task; import weka.experiment.TaskStatusInfo; /** * Class that encapsulates a sub task for distributed boundary visualization. * Produces probability distributions for each pixel in one row of the * visualization. * * @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a> * @version $Revision$ * @since 1.0 * @see Task */ public class RemoteBoundaryVisualizerSubTask implements Task { /** ID added to avoid warning */ private static final long serialVersionUID = -5275252329449241592L; // status information for this sub task private final TaskStatusInfo m_status = new TaskStatusInfo(); // the result of this sub task private RemoteResult m_result; // which row are we doing private int m_rowNumber; // width and height of the visualization private int m_panelHeight; private int m_panelWidth; // the classifier to use private Classifier m_classifier; // the kernel density estimator private DataGenerator m_dataGenerator; // the training data private Instances m_trainingData; // attributes for visualizing on (fixed dimensions) private int m_xAttribute; private int m_yAttribute; // pixel width and height in terms of attribute values private double m_pixHeight; private double m_pixWidth; // min, max of these attributes private double m_minX; private double m_minY; // number of samples to take from each region in the fixed dimensions private int m_numOfSamplesPerRegion = 2; // number of samples per kernel = base ^ (# non-fixed dimensions) private int m_numOfSamplesPerGenerator; private double m_samplesBase = 2.0; // A random number generator private Random m_random; private double[] m_weightingAttsValues; private boolean[] m_attsToWeightOn; private double[] m_vals; private double[] m_dist; private Instance m_predInst; /** * Set the row number for this sub task * * @param rn the row number */ public void setRowNumber(int rn) { m_rowNumber = rn; } /** * Set the width of the visualization * * @param pw the width */ public void setPanelWidth(int pw) { m_panelWidth = pw; } /** * Set the height of the visualization * * @param ph the height */ public void setPanelHeight(int ph) { m_panelHeight = ph; } /** * Set the height of a pixel * * @param ph the height of a pixel */ public void setPixHeight(double ph) { m_pixHeight = ph; } /** * Set the width of a pixel * * @param pw the width of a pixel */ public void setPixWidth(double pw) { m_pixWidth = pw; } /** * Set the classifier to use * * @param dc the classifier */ public void setClassifier(Classifier dc) { m_classifier = dc; } /** * Set the density estimator to use * * @param dg the density estimator */ public void setDataGenerator(DataGenerator dg) { m_dataGenerator = dg; } /** * Set the training data * * @param i the training data */ public void setInstances(Instances i) { m_trainingData = i; } /** * Set the minimum and maximum values of the x axis fixed dimension * * @param minx a <code>double</code> value * @param maxx a <code>double</code> value */ public void setMinMaxX(double minx, double maxx) { m_minX = minx; } /** * Set the minimum and maximum values of the y axis fixed dimension * * @param miny a <code>double</code> value * @param maxy a <code>double</code> value */ public void setMinMaxY(double miny, double maxy) { m_minY = miny; } /** * Set the x axis fixed dimension * * @param xatt an <code>int</code> value */ public void setXAttribute(int xatt) { m_xAttribute = xatt; } /** * Set the y axis fixed dimension * * @param yatt an <code>int</code> value */ public void setYAttribute(int yatt) { m_yAttribute = yatt; } /** * Set the number of points to uniformly sample from a region (fixed * dimensions). * * @param num an <code>int</code> value */ public void setNumSamplesPerRegion(int num) { m_numOfSamplesPerRegion = num; } /** * Set the base for computing the number of samples to obtain from each * generator. number of samples = base ^ (# non fixed dimensions) * * @param ksb a <code>double</code> value */ public void setGeneratorSamplesBase(double ksb) { m_samplesBase = ksb; } /** * Perform the sub task */ @Override public void execute() { m_random = new Random(m_rowNumber * 11); m_dataGenerator.setSeed(m_rowNumber * 11); m_result = new RemoteResult(m_rowNumber, m_panelWidth); m_status.setTaskResult(m_result); m_status.setExecutionStatus(TaskStatusInfo.PROCESSING); try { m_numOfSamplesPerGenerator = (int) Math.pow(m_samplesBase, m_trainingData.numAttributes() - 3); if (m_trainingData == null) { throw new Exception("No training data set (BoundaryPanel)"); } if (m_classifier == null) { throw new Exception("No classifier set (BoundaryPanel)"); } if (m_dataGenerator == null) { throw new Exception("No data generator set (BoundaryPanel)"); } if (m_trainingData.attribute(m_xAttribute).isNominal() || m_trainingData.attribute(m_yAttribute).isNominal()) { throw new Exception("Visualization dimensions must be numeric " + "(RemoteBoundaryVisualizerSubTask)"); } m_attsToWeightOn = new boolean[m_trainingData.numAttributes()]; m_attsToWeightOn[m_xAttribute] = true; m_attsToWeightOn[m_yAttribute] = true; // generate samples m_weightingAttsValues = new double[m_attsToWeightOn.length]; m_vals = new double[m_trainingData.numAttributes()]; m_predInst = new DenseInstance(1.0, m_vals); m_predInst.setDataset(m_trainingData); System.err.println("Executing row number " + m_rowNumber); for (int j = 0; j < m_panelWidth; j++) { double[] preds = calculateRegionProbs(j, m_rowNumber); m_result.setLocationProbs(j, preds); m_result .setPercentCompleted((int) (100 * ((double) j / (double) m_panelWidth))); } } catch (Exception ex) { m_status.setExecutionStatus(TaskStatusInfo.FAILED); m_status.setStatusMessage("Row " + m_rowNumber + " failed."); System.err.print(ex); return; } // finished m_status.setExecutionStatus(TaskStatusInfo.FINISHED); m_status .setStatusMessage("Row " + m_rowNumber + " completed successfully."); } private double[] calculateRegionProbs(int j, int i) throws Exception { double[] sumOfProbsForRegion = new double[m_trainingData.classAttribute() .numValues()]; for (int u = 0; u < m_numOfSamplesPerRegion; u++) { double[] sumOfProbsForLocation = new double[m_trainingData .classAttribute().numValues()]; m_weightingAttsValues[m_xAttribute] = getRandomX(j); m_weightingAttsValues[m_yAttribute] = getRandomY(m_panelHeight - i - 1); m_dataGenerator.setWeightingValues(m_weightingAttsValues); double[] weights = m_dataGenerator.getWeights(); double sumOfWeights = Utils.sum(weights); int[] indices = Utils.sort(weights); // Prune 1% of weight mass int[] newIndices = new int[indices.length]; double sumSoFar = 0; double criticalMass = 0.99 * sumOfWeights; int index = weights.length - 1; int counter = 0; for (int z = weights.length - 1; z >= 0; z--) { newIndices[index--] = indices[z]; sumSoFar += weights[indices[z]]; counter++; if (sumSoFar > criticalMass) { break; } } indices = new int[counter]; System.arraycopy(newIndices, index + 1, indices, 0, counter); for (int z = 0; z < m_numOfSamplesPerGenerator; z++) { m_dataGenerator.setWeightingValues(m_weightingAttsValues); double[][] values = m_dataGenerator.generateInstances(indices); for (int q = 0; q < values.length; q++) { if (values[q] != null) { System.arraycopy(values[q], 0, m_vals, 0, m_vals.length); m_vals[m_xAttribute] = m_weightingAttsValues[m_xAttribute]; m_vals[m_yAttribute] = m_weightingAttsValues[m_yAttribute]; // classify the instance m_dist = m_classifier.distributionForInstance(m_predInst); for (int k = 0; k < sumOfProbsForLocation.length; k++) { sumOfProbsForLocation[k] += (m_dist[k] * weights[q]); } } } } for (int k = 0; k < sumOfProbsForRegion.length; k++) { sumOfProbsForRegion[k] += (sumOfProbsForLocation[k] * sumOfWeights); } } // average Utils.normalize(sumOfProbsForRegion); // cache double[] tempDist = new double[sumOfProbsForRegion.length]; System.arraycopy(sumOfProbsForRegion, 0, tempDist, 0, sumOfProbsForRegion.length); return tempDist; } /** * Return a random x attribute value contained within the pix'th horizontal * pixel * * @param pix the horizontal pixel number * @return a value in attribute space */ private double getRandomX(int pix) { double minPix = m_minX + (pix * m_pixWidth); return minPix + m_random.nextDouble() * m_pixWidth; } /** * Return a random y attribute value contained within the pix'th vertical * pixel * * @param pix the vertical pixel number * @return a value in attribute space */ private double getRandomY(int pix) { double minPix = m_minY + (pix * m_pixHeight); return minPix + m_random.nextDouble() * m_pixHeight; } /** * Return status information for this sub task * * @return a <code>TaskStatusInfo</code> value */ @Override public TaskStatusInfo getTaskStatus() { return m_status; } }
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/boundaryvisualizer/RemoteResult.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * RemoteResult.java * Copyright (C) 2003-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.boundaryvisualizer; import java.io.Serializable; /** * Class that encapsulates a result (and progress info) for part of a * distributed boundary visualization. The result of a sub-task is the * probabilities necessary to display one row of the final visualization. * * @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a> * @version $Revision$ * @since 1.0 * @see Serializable */ public class RemoteResult implements Serializable { /** for serialization */ private static final long serialVersionUID = 1873271280044633808L; /** the row number that this result corresponds to */ // private int m_rowNumber; NOT USED /** how many pixels in a row */ // private int m_rowLength; NOT USED /** * the result - ie. the probability distributions produced by the classifier * for this row in the visualization */ private final double[][] m_probabilities; /** progress on computing this row */ private int m_percentCompleted; /** * Creates a new <code>RemoteResult</code> instance. * * @param rowNum the row number * @param rowLength the number of pixels in the row */ public RemoteResult(int rowNum, int rowLength) { m_probabilities = new double[rowLength][0]; } /** * Store the classifier's distribution for a particular pixel in the * visualization * * @param index the pixel * @param distribution the probability distribution from the classifier */ public void setLocationProbs(int index, double[] distribution) { m_probabilities[index] = distribution; } /** * Return the probability distributions for this row in the visualization * * @return the probability distributions */ public double[][] getProbabilities() { return m_probabilities; } /** * Set the progress for this row so far * * @param pc a percent completed value */ public void setPercentCompleted(int pc) { m_percentCompleted = pc; } /** * Return the progress for this row * * @return a percent completed value */ public int getPercentCompleted() { return m_percentCompleted; } }
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/experiment/AbstractSetupPanel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * AbstractSetupPanel.java * Copyright (C) 2015 University of Waikato, Hamilton, NZ */ package weka.gui.experiment; import weka.core.PluginManager; import weka.experiment.Experiment; import javax.swing.JPanel; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Ancestor for setup panels for experiments. * * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public abstract class AbstractSetupPanel extends JPanel implements Comparable<AbstractSetupPanel> { /** * Returns the name of the panel. * * @return the name */ public abstract String getName(); /** * Sets the panel used to switch between simple and advanced modes. * * @param modePanel the panel */ public abstract void setModePanel(SetupModePanel modePanel); /** * Sets the experiment to configure. * * @param exp a value of type 'Experiment' * @return true if experiment could be configured, false otherwise */ public abstract boolean setExperiment(Experiment exp); /** * Gets the currently configured experiment. * * @return the currently configured experiment. */ public abstract Experiment getExperiment(); /** * Hook method for cleaning up the interface after a switch. * <br> * Default implementation does nothing. */ public void cleanUpAfterSwitch() { } /** * Adds a PropertyChangeListener who will be notified of value changes. * * @param l a value of type 'PropertyChangeListener' */ public abstract void addPropertyChangeListener(PropertyChangeListener l); /** * Removes a PropertyChangeListener. * * @param l a value of type 'PropertyChangeListener' */ public abstract void removePropertyChangeListener(PropertyChangeListener l); /** * Uses the name for comparison. * * @param o the other panel * @return <0 , 0, >0 if name is less than, equal or greater than this one * @see #getName() */ public int compareTo(AbstractSetupPanel o) { return getName().compareTo(o.getName()); } /** * Just returns the name of the panel. * * @return the name */ public String toString() { return getName(); } /** * Returns a list of all available setup panels. * * @return the available panels */ public static AbstractSetupPanel[] getPanels() { List<AbstractSetupPanel> result; List<String> names; Class cls; AbstractSetupPanel panel; result = new ArrayList<AbstractSetupPanel>(); names = PluginManager.getPluginNamesOfTypeList(AbstractSetupPanel.class.getName()); for (String name: names) { try { cls = Class.forName(name); panel = (AbstractSetupPanel) cls.newInstance(); result.add(panel); } catch (Exception e) { System.err.println("Failed to instantiate setup panel: " + name); e.printStackTrace(); } } Collections.sort(result); return result.toArray(new AbstractSetupPanel[result.size()]); } }
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/experiment/AlgorithmListPanel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * AlgorithmListPanel.java * Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.experiment; import java.awt.BorderLayout; import java.awt.Component; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.StringSelection; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import java.lang.reflect.Array; import java.util.List; import javax.swing.BorderFactory; import javax.swing.DefaultListCellRenderer; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.filechooser.FileFilter; import weka.classifiers.Classifier; import weka.classifiers.xml.XMLClassifier; import weka.core.OptionHandler; import weka.core.SerializedObject; import weka.core.Utils; import weka.experiment.Experiment; import weka.gui.ExtensionFileFilter; import weka.gui.GenericObjectEditor; import weka.gui.JListHelper; import weka.gui.PropertyDialog; /** * This panel controls setting a list of algorithms for an experiment to iterate * over. * * @author Richard Kirkby (rkirkby@cs.waikato.ac.nz) * @version $Revision$ */ public class AlgorithmListPanel extends JPanel implements ActionListener { /** for serialization */ private static final long serialVersionUID = -7204528834764898671L; /** * Class required to show the Classifiers nicely in the list */ public class ObjectCellRenderer extends DefaultListCellRenderer { /** for serialization */ private static final long serialVersionUID = -5067138526587433808L; /** * Return a component that has been configured to display the specified * value. That component's paint method is then called to "render" the cell. * If it is necessary to compute the dimensions of a list because the list * cells do not have a fixed size, this method is called to generate a * component on which getPreferredSize can be invoked. * * @param list The JList we're painting. * @param value The value returned by list.getModel().getElementAt(index). * @param index The cells index. * @param isSelected True if the specified cell was selected. * @param cellHasFocus True if the specified cell has the focus. * @return A component whose paint() method will render the specified value. */ @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); String rep = value.getClass().getName(); int dotPos = rep.lastIndexOf('.'); if (dotPos != -1) { rep = rep.substring(dotPos + 1); } if (value instanceof OptionHandler) { rep += " " + Utils.joinOptions(((OptionHandler) value).getOptions()); } setText(rep); return c; } } /** The experiment to set the algorithm list of */ protected Experiment m_Exp; /** The component displaying the algorithm list */ protected JList<Classifier> m_List; /** Click to add an algorithm */ protected JButton m_AddBut = new JButton("Add new..."); /** Click to edit the selected algorithm */ protected JButton m_EditBut = new JButton("Edit selected..."); /** Click to remove the selected dataset from the list */ protected JButton m_DeleteBut = new JButton("Delete selected"); /** Click to edit the load the options for athe selected algorithm */ protected JButton m_LoadOptionsBut = new JButton("Load options..."); /** Click to edit the save the options from selected algorithm */ protected JButton m_SaveOptionsBut = new JButton("Save options..."); /** Click to move the selected algorithm(s) one up */ protected JButton m_UpBut = new JButton("Up"); /** Click to move the selected algorithm(s) one down */ protected JButton m_DownBut = new JButton("Down"); /** The file chooser for selecting experiments */ protected JFileChooser m_FileChooser = new JFileChooser(new File( System.getProperty("user.dir"))); /** * A filter to ensure only experiment (in XML format) files get shown in the * chooser */ protected FileFilter m_XMLFilter = new ExtensionFileFilter(".xml", "Classifier options (*.xml)"); /** Whether an algorithm is added or only edited */ protected boolean m_Editing = false; /** Lets the user configure the classifier */ protected GenericObjectEditor m_ClassifierEditor = new GenericObjectEditor( true); /** The currently displayed property dialog, if any */ protected PropertyDialog m_PD; /** The list model used */ protected DefaultListModel m_AlgorithmListModel = new DefaultListModel(); /* Register the property editors we need */ static { GenericObjectEditor.registerEditors(); } /** * Creates the algorithm list panel with the given experiment. * * @param exp a value of type 'Experiment' */ public AlgorithmListPanel(Experiment exp) { this(); setExperiment(exp); } /** * Create the algorithm list panel initially disabled. */ public AlgorithmListPanel() { final AlgorithmListPanel self = this; m_List = new JList(); MouseListener mouseListener = new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { final int index = m_List.locationToIndex(e.getPoint()); if ((e.getClickCount() == 2) && (e.getButton() == MouseEvent.BUTTON1)) { // unfortunately, locationToIndex only returns the nearest entry // and not the exact one, i.e. if there's one item in the list and // one doublelclicks somewhere in the list, this index will be // returned if (index > -1) { actionPerformed(new ActionEvent(m_EditBut, 0, "")); } } else if (e.getClickCount() == 1) { if ((e.getButton() == MouseEvent.BUTTON3) || ((e.getButton() == MouseEvent.BUTTON1) && e.isAltDown() && e .isShiftDown())) { JPopupMenu menu = new JPopupMenu(); JMenuItem item; item = new JMenuItem("Add configuration(s)..."); item.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String str = JOptionPane.showInputDialog(self, "Configuration (<classname> [<options>])"); if (str != null && str.length() > 0) { try { String[] options = Utils.splitOptions(str); String classname = options[0]; options[0] = ""; Class c = Utils.forName(Object.class, classname, null).getClass(); if (c.isArray()) { for (int i = 1; i < options.length; i++) { String[] ops = Utils.splitOptions(options[i]); String cname = ops[0]; ops[0] = ""; m_AlgorithmListModel.addElement(Utils.forName(Object.class, cname, ops)); } } else { m_AlgorithmListModel.addElement(Utils.forName(Object.class, classname, options)); } updateExperiment(); } catch (Exception ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(self, "Error parsing commandline:\n" + ex, "Error...", JOptionPane.ERROR_MESSAGE); } } } }); menu.add(item); if (m_List.getSelectedValue() != null) { menu.addSeparator(); item = new JMenuItem("Show properties..."); item.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (m_List.getSelectedValuesList().size() > 1) { JOptionPane.showMessageDialog(self, "You have selected more than one element in the list.", "Error...", JOptionPane.ERROR_MESSAGE); return; } self.actionPerformed(new ActionEvent(m_EditBut, 0, "")); } }); menu.add(item); item = new JMenuItem("Copy configuration(s) to clipboard"); item.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { List<Classifier> list = m_List.getSelectedValuesList(); Object value = null; if (list.size() > 1) { value = list.toArray(new Classifier[0]); } else { value = list.get(0); } String str = ""; if (value.getClass().isArray()) { str += value.getClass().getName(); Object[] arr = (Object[])value; for (Object v : arr) { String s = v.getClass().getName(); if (v instanceof OptionHandler) { s += " " + Utils.joinOptions(((OptionHandler) v).getOptions()); } str += " \"" + Utils.backQuoteChars(s.trim()) + "\""; } } else { str += value.getClass().getName(); if (value instanceof OptionHandler) { str += " " + Utils.joinOptions(((OptionHandler) value).getOptions()); } } StringSelection selection = new StringSelection(str.trim()); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents(selection, selection); } }); menu.add(item); item = new JMenuItem("Enter configuration..."); item.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (m_List.getSelectedValuesList().size() > 1) { JOptionPane.showMessageDialog(self, "You have selected more than one element in the list.", "Error...", JOptionPane.ERROR_MESSAGE); return; } String str = JOptionPane.showInputDialog(self, "Configuration (<classname> [<options>])"); if (str != null && str.length() > 0) { try { String[] options = Utils.splitOptions(str); String classname = options[0]; options[0] = ""; Object obj = Utils.forName(Object.class, classname, options); m_AlgorithmListModel.setElementAt(obj, index); updateExperiment(); } catch (Exception ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(self, "Error parsing commandline:\n" + ex, "Error...", JOptionPane.ERROR_MESSAGE); } } } }); menu.add(item); } menu.show(m_List, e.getX(), e.getY()); } } } }; m_List.addMouseListener(mouseListener); m_ClassifierEditor.setClassType(Classifier.class); m_ClassifierEditor.setValue(new weka.classifiers.rules.ZeroR()); m_ClassifierEditor.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent e) { repaint(); } }); ((GenericObjectEditor.GOEPanel) m_ClassifierEditor.getCustomEditor()) .addOkListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Classifier newCopy = (Classifier) copyObject(m_ClassifierEditor .getValue()); addNewAlgorithm(newCopy); } }); m_DeleteBut.setEnabled(false); m_DeleteBut.addActionListener(this); m_AddBut.setEnabled(false); m_AddBut.addActionListener(this); m_EditBut.setEnabled(false); m_EditBut.addActionListener(this); m_LoadOptionsBut.setEnabled(false); m_LoadOptionsBut.addActionListener(this); m_SaveOptionsBut.setEnabled(false); m_SaveOptionsBut.addActionListener(this); m_UpBut.setEnabled(false); m_UpBut.addActionListener(this); m_DownBut.setEnabled(false); m_DownBut.addActionListener(this); m_List.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { setButtons(e); } }); m_FileChooser.addChoosableFileFilter(m_XMLFilter); m_FileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); setLayout(new BorderLayout()); setBorder(BorderFactory.createTitledBorder("Algorithms")); JPanel topLab = new JPanel(); GridBagLayout gb = new GridBagLayout(); GridBagConstraints constraints = new GridBagConstraints(); topLab.setBorder(BorderFactory.createEmptyBorder(10, 5, 10, 5)); topLab.setLayout(gb); constraints.gridx = 0; constraints.gridy = 0; constraints.weightx = 5; constraints.fill = GridBagConstraints.HORIZONTAL; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.insets = new Insets(0, 2, 0, 2); topLab.add(m_AddBut, constraints); constraints.gridx = 1; constraints.gridy = 0; constraints.weightx = 5; constraints.gridwidth = 1; constraints.gridheight = 1; topLab.add(m_EditBut, constraints); constraints.gridx = 2; constraints.gridy = 0; constraints.weightx = 5; constraints.gridwidth = 1; constraints.gridheight = 1; topLab.add(m_DeleteBut, constraints); JPanel bottomLab = new JPanel(); gb = new GridBagLayout(); constraints = new GridBagConstraints(); bottomLab.setBorder(BorderFactory.createEmptyBorder(10, 5, 10, 5)); bottomLab.setLayout(gb); constraints.gridx = 0; constraints.gridy = 0; constraints.weightx = 5; constraints.fill = GridBagConstraints.HORIZONTAL; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.insets = new Insets(0, 2, 0, 2); bottomLab.add(m_LoadOptionsBut, constraints); constraints.gridx = 1; constraints.gridy = 0; constraints.weightx = 5; constraints.gridwidth = 1; constraints.gridheight = 1; bottomLab.add(m_SaveOptionsBut, constraints); constraints.gridx = 2; constraints.gridy = 0; constraints.weightx = 5; constraints.gridwidth = 1; constraints.gridheight = 1; bottomLab.add(m_UpBut, constraints); constraints.gridx = 3; constraints.gridy = 0; constraints.weightx = 5; constraints.gridwidth = 1; constraints.gridheight = 1; bottomLab.add(m_DownBut, constraints); add(topLab, BorderLayout.NORTH); add(new JScrollPane(m_List), BorderLayout.CENTER); add(bottomLab, BorderLayout.SOUTH); } /** * Tells the panel to act on a new experiment. * * @param exp a value of type 'Experiment' */ public void setExperiment(Experiment exp) { m_Exp = exp; m_AddBut.setEnabled(true); m_List.setModel(m_AlgorithmListModel); m_List.setCellRenderer(new ObjectCellRenderer()); m_AlgorithmListModel.removeAllElements(); if (m_Exp.getPropertyArray() instanceof Classifier[]) { Classifier[] algorithms = (Classifier[]) m_Exp.getPropertyArray(); for (Classifier algorithm : algorithms) { m_AlgorithmListModel.addElement(algorithm); } } m_EditBut.setEnabled((m_AlgorithmListModel.size() > 0)); m_DeleteBut.setEnabled((m_AlgorithmListModel.size() > 0)); m_LoadOptionsBut.setEnabled((m_AlgorithmListModel.size() > 0)); m_SaveOptionsBut.setEnabled((m_AlgorithmListModel.size() > 0)); m_UpBut.setEnabled(JListHelper.canMoveUp(m_List)); m_DownBut.setEnabled(JListHelper.canMoveDown(m_List)); } /** * Add a new algorithm to the list. * * @param newScheme the new scheme to add */ private void addNewAlgorithm(Classifier newScheme) { if (!m_Editing) { m_AlgorithmListModel.addElement(newScheme); } else { m_AlgorithmListModel.setElementAt(newScheme, m_List.getSelectedIndex()); } updateExperiment(); m_Editing = false; } /** * updates the classifiers in the experiment */ private void updateExperiment() { Classifier[] cArray = new Classifier[m_AlgorithmListModel.size()]; for (int i = 0; i < cArray.length; i++) { cArray[i] = (Classifier) m_AlgorithmListModel.elementAt(i); } m_Exp.setPropertyArray(cArray); } /** * sets the state of the buttons according to the selection state of the JList * * @param e the event */ private void setButtons(ListSelectionEvent e) { if (e.getSource() == m_List) { m_DeleteBut.setEnabled(m_List.getSelectedIndex() > -1); m_AddBut.setEnabled(true); m_EditBut.setEnabled(m_List.getSelectedIndices().length == 1); m_LoadOptionsBut.setEnabled(m_List.getSelectedIndices().length == 1); m_SaveOptionsBut.setEnabled(m_List.getSelectedIndices().length == 1); m_UpBut.setEnabled(JListHelper.canMoveUp(m_List)); m_DownBut.setEnabled(JListHelper.canMoveDown(m_List)); } } /** * Handle actions when buttons get pressed. * * @param e a value of type 'ActionEvent' */ @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == m_AddBut) { m_Editing = false; if (m_PD == null) { if (PropertyDialog.getParentDialog(this) != null) { m_PD = new PropertyDialog(PropertyDialog.getParentDialog(this), m_ClassifierEditor, -1, -1); } else { m_PD = new PropertyDialog(PropertyDialog.getParentFrame(this), m_ClassifierEditor, -1, -1); } m_PD.setVisible(true); } else { if (PropertyDialog.getParentDialog(this) != null) { m_PD.setLocationRelativeTo(PropertyDialog.getParentDialog(this)); } else { m_PD.setLocationRelativeTo(PropertyDialog.getParentFrame(this)); } m_PD.setVisible(true); } } else if (e.getSource() == m_EditBut) { if (m_List.getSelectedValue() != null) { m_ClassifierEditor.setClassType(weka.classifiers.Classifier.class); // m_PD.getEditor().setValue(m_List.getSelectedValue()); m_ClassifierEditor.setValue(m_List.getSelectedValue()); m_Editing = true; if (m_PD == null) { int x = getLocationOnScreen().x; int y = getLocationOnScreen().y; if (PropertyDialog.getParentDialog(this) != null) { m_PD = new PropertyDialog(PropertyDialog.getParentDialog(this), m_ClassifierEditor, -1, -1); } else { m_PD = new PropertyDialog(PropertyDialog.getParentFrame(this), m_ClassifierEditor, -1, -1); } m_PD.setVisible(true); } else { if (PropertyDialog.getParentDialog(this) != null) { m_PD.setLocationRelativeTo(PropertyDialog.getParentDialog(this)); } else { m_PD.setLocationRelativeTo(PropertyDialog.getParentFrame(this)); } m_PD.setVisible(true); } } } else if (e.getSource() == m_DeleteBut) { int[] selected = m_List.getSelectedIndices(); if (selected != null) { for (int i = selected.length - 1; i >= 0; i--) { int current = selected[i]; m_AlgorithmListModel.removeElementAt(current); if (m_Exp.getDatasets().size() > current) { m_List.setSelectedIndex(current); } else { m_List.setSelectedIndex(current - 1); } } } if (m_List.getSelectedIndex() == -1) { m_EditBut.setEnabled(false); m_DeleteBut.setEnabled(false); m_LoadOptionsBut.setEnabled(false); m_SaveOptionsBut.setEnabled(false); m_UpBut.setEnabled(false); m_DownBut.setEnabled(false); } updateExperiment(); } else if (e.getSource() == m_LoadOptionsBut) { if (m_List.getSelectedValue() != null) { int returnVal = m_FileChooser.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { try { File file = m_FileChooser.getSelectedFile(); if (!file.getAbsolutePath().toLowerCase().endsWith(".xml")) { file = new File(file.getAbsolutePath() + ".xml"); } XMLClassifier xmlcls = new XMLClassifier(); Classifier c = (Classifier) xmlcls.read(file); m_AlgorithmListModel.setElementAt(c, m_List.getSelectedIndex()); updateExperiment(); } catch (Exception ex) { ex.printStackTrace(); } } } } else if (e.getSource() == m_SaveOptionsBut) { if (m_List.getSelectedValue() != null) { int returnVal = m_FileChooser.showSaveDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { try { File file = m_FileChooser.getSelectedFile(); if (!file.getAbsolutePath().toLowerCase().endsWith(".xml")) { file = new File(file.getAbsolutePath() + ".xml"); } XMLClassifier xmlcls = new XMLClassifier(); xmlcls.write(file, m_List.getSelectedValue()); } catch (Exception ex) { ex.printStackTrace(); } } } } else if (e.getSource() == m_UpBut) { JListHelper.moveUp(m_List); updateExperiment(); } else if (e.getSource() == m_DownBut) { JListHelper.moveDown(m_List); updateExperiment(); } } /** * Makes a copy of an object using serialization * * @param source the object to copy * @return a copy of the source object */ protected Object copyObject(Object source) { Object result = null; try { SerializedObject so = new SerializedObject(source); result = so.getObject(); } catch (Exception ex) { System.err.println("AlgorithmListPanel: Problem copying object"); System.err.println(ex); } return result; } /** * Tests out the algorithm list panel from the command line. * * @param args ignored */ public static void main(String[] args) { try { final JFrame jf = new JFrame("Algorithm List Editor"); jf.getContentPane().setLayout(new BorderLayout()); AlgorithmListPanel dp = new AlgorithmListPanel(); jf.getContentPane().add(dp, BorderLayout.CENTER); jf.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { jf.dispose(); System.exit(0); } }); jf.pack(); jf.setVisible(true); System.err.println("Short nap"); Thread.sleep(3000); System.err.println("Done"); dp.setExperiment(new Experiment()); } 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/experiment/DatasetListPanel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * DatasetListPanel.java * Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.experiment; import java.awt.BorderLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.util.Collections; import java.util.Vector; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import weka.core.Utils; import weka.core.converters.ConverterUtils; import weka.core.converters.ConverterUtils.DataSource; import weka.core.converters.Saver; import weka.experiment.Experiment; import weka.gui.ConverterFileChooser; import weka.gui.JListHelper; import weka.gui.ViewerDialog; /** * This panel controls setting a list of datasets for an experiment to iterate * over. * * @author Len Trigg (trigg@cs.waikato.ac.nz) * @version $Revision$ */ public class DatasetListPanel extends JPanel implements ActionListener { /** for serialization. */ private static final long serialVersionUID = 7068857852794405769L; /** The experiment to set the dataset list of. */ protected Experiment m_Exp; /** The component displaying the dataset list. */ protected JList m_List; /** Click to add a dataset. */ protected JButton m_AddBut = new JButton("Add new..."); /** Click to edit the selected algorithm. */ protected JButton m_EditBut = new JButton("Edit selected..."); /** Click to remove the selected dataset from the list. */ protected JButton m_DeleteBut = new JButton("Delete selected"); /** Click to move the selected dataset(s) one up. */ protected JButton m_UpBut = new JButton("Up"); /** Click to move the selected dataset(s) one down. */ protected JButton m_DownBut = new JButton("Down"); /** Make file paths relative to the user (start) directory. */ protected JCheckBox m_relativeCheck = new JCheckBox("Use relative paths"); /** The user (start) directory. */ // protected File m_UserDir = new File(System.getProperty("user.dir")); /** The file chooser component. */ protected ConverterFileChooser m_FileChooser = new ConverterFileChooser( ExperimenterDefaults.getInitialDatasetsDirectory()); /** * Creates the dataset list panel with the given experiment. * * @param exp a value of type 'Experiment' */ public DatasetListPanel(Experiment exp) { this(); setExperiment(exp); } /** * Create the dataset list panel initially disabled. */ public DatasetListPanel() { m_List = new JList(); m_List.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { setButtons(e); } }); MouseListener mouseListener = new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { // unfortunately, locationToIndex only returns the nearest entry // and not the exact one, i.e. if there's one item in the list and // one doublelclicks somewhere in the list, this index will be // returned int index = m_List.locationToIndex(e.getPoint()); if (index > -1) { actionPerformed(new ActionEvent(m_EditBut, 0, "")); } } } }; m_List.addMouseListener(mouseListener); // m_FileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); m_FileChooser.setCoreConvertersOnly(true); m_FileChooser.setMultiSelectionEnabled(true); m_FileChooser .setFileSelectionMode(ConverterFileChooser.FILES_AND_DIRECTORIES); m_FileChooser.setAcceptAllFileFilterUsed(false); m_DeleteBut.setEnabled(false); m_DeleteBut.addActionListener(this); m_AddBut.setEnabled(false); m_AddBut.addActionListener(this); m_EditBut.setEnabled(false); m_EditBut.addActionListener(this); m_UpBut.setEnabled(false); m_UpBut.addActionListener(this); m_DownBut.setEnabled(false); m_DownBut.addActionListener(this); m_relativeCheck.setSelected(ExperimenterDefaults.getUseRelativePaths()); m_relativeCheck.setToolTipText("Store file paths relative to " + "the start directory"); setLayout(new BorderLayout()); setBorder(BorderFactory.createTitledBorder("Datasets")); JPanel topLab = new JPanel(); GridBagLayout gb = new GridBagLayout(); GridBagConstraints constraints = new GridBagConstraints(); topLab.setBorder(BorderFactory.createEmptyBorder(10, 5, 10, 5)); // topLab.setLayout(new GridLayout(1,2,5,5)); topLab.setLayout(gb); constraints.gridx = 0; constraints.gridy = 0; constraints.weightx = 5; constraints.fill = GridBagConstraints.HORIZONTAL; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.insets = new Insets(0, 2, 0, 2); topLab.add(m_AddBut, constraints); constraints.gridx = 1; constraints.gridy = 0; constraints.weightx = 5; constraints.gridwidth = 1; constraints.gridheight = 1; topLab.add(m_EditBut, constraints); constraints.gridx = 2; constraints.gridy = 0; constraints.weightx = 5; constraints.gridwidth = 1; constraints.gridheight = 1; topLab.add(m_DeleteBut, constraints); constraints.gridx = 0; constraints.gridy = 1; constraints.weightx = 5; constraints.fill = GridBagConstraints.HORIZONTAL; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.insets = new Insets(0, 2, 0, 2); topLab.add(m_relativeCheck, constraints); JPanel bottomLab = new JPanel(); gb = new GridBagLayout(); constraints = new GridBagConstraints(); bottomLab.setBorder(BorderFactory.createEmptyBorder(10, 5, 10, 5)); bottomLab.setLayout(gb); constraints.gridx = 0; constraints.gridy = 0; constraints.weightx = 5; constraints.fill = GridBagConstraints.HORIZONTAL; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.insets = new Insets(0, 2, 0, 2); bottomLab.add(m_UpBut, constraints); constraints.gridx = 1; constraints.gridy = 0; constraints.weightx = 5; constraints.gridwidth = 1; constraints.gridheight = 1; bottomLab.add(m_DownBut, constraints); add(topLab, BorderLayout.NORTH); add(new JScrollPane(m_List), BorderLayout.CENTER); add(bottomLab, BorderLayout.SOUTH); } /** * sets the state of the buttons according to the selection state of the * JList. * * @param e the event */ private void setButtons(ListSelectionEvent e) { if ((e == null) || (e.getSource() == m_List)) { m_DeleteBut.setEnabled(m_List.getSelectedIndex() > -1); m_EditBut.setEnabled(m_List.getSelectedIndices().length == 1); m_UpBut.setEnabled(JListHelper.canMoveUp(m_List)); m_DownBut.setEnabled(JListHelper.canMoveDown(m_List)); } } /** * Tells the panel to act on a new experiment. * * @param exp a value of type 'Experiment' */ public void setExperiment(Experiment exp) { m_Exp = exp; m_List.setModel(m_Exp.getDatasets()); m_AddBut.setEnabled(true); setButtons(null); } /** * Gets all the files in the given directory that match the currently selected * extension. * * @param directory the directory to get the files for * @param files the list to add the files to */ protected void getFilesRecursively(File directory, Vector<File> files) { try { String[] currentDirFiles = directory.list(); for (int i = 0; i < currentDirFiles.length; i++) { currentDirFiles[i] = directory.getCanonicalPath() + File.separator + currentDirFiles[i]; File current = new File(currentDirFiles[i]); if (m_FileChooser.getFileFilter().accept(current)) { if (current.isDirectory()) { getFilesRecursively(current, files); } else { files.addElement(current); } } } } catch (Exception e) { System.err.println("IOError occured when reading list of files"); } } /** * Handle actions when buttons get pressed. * * @param e a value of type 'ActionEvent' */ @Override public void actionPerformed(ActionEvent e) { boolean useRelativePaths = m_relativeCheck.isSelected(); if (e.getSource() == m_AddBut) { // Let the user select an arff file from a file chooser int returnVal = m_FileChooser.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { if (m_FileChooser.isMultiSelectionEnabled()) { File[] selected = m_FileChooser.getSelectedFiles(); for (File element : selected) { if (element.isDirectory()) { Vector<File> files = new Vector<File>(); getFilesRecursively(element, files); // sort the result Collections.sort(files); for (int j = 0; j < files.size(); j++) { File temp = files.elementAt(j); if (useRelativePaths) { try { temp = Utils.convertToRelativePath(temp); } catch (Exception ex) { ex.printStackTrace(); } } m_Exp.getDatasets().addElement(temp); } } else { File temp = element; if (useRelativePaths) { try { temp = Utils.convertToRelativePath(temp); } catch (Exception ex) { ex.printStackTrace(); } } m_Exp.getDatasets().addElement(temp); } } setButtons(null); } else { if (m_FileChooser.getSelectedFile().isDirectory()) { Vector<File> files = new Vector<File>(); getFilesRecursively(m_FileChooser.getSelectedFile(), files); // sort the result Collections.sort(files); for (int j = 0; j < files.size(); j++) { File temp = files.elementAt(j); if (useRelativePaths) { try { temp = Utils.convertToRelativePath(temp); } catch (Exception ex) { ex.printStackTrace(); } } m_Exp.getDatasets().addElement(temp); } } else { File temp = m_FileChooser.getSelectedFile(); if (useRelativePaths) { try { temp = Utils.convertToRelativePath(temp); } catch (Exception ex) { ex.printStackTrace(); } } m_Exp.getDatasets().addElement(temp); } setButtons(null); } } } else if (e.getSource() == m_DeleteBut) { // Delete the selected files int[] selected = m_List.getSelectedIndices(); if (selected != null) { for (int i = selected.length - 1; i >= 0; i--) { int current = selected[i]; m_Exp.getDatasets().removeElementAt(current); if (m_Exp.getDatasets().size() > current) { m_List.setSelectedIndex(current); } else { m_List.setSelectedIndex(current - 1); } } } setButtons(null); } else if (e.getSource() == m_EditBut) { // Delete the selected files int selected = m_List.getSelectedIndex(); if (selected != -1) { ViewerDialog dialog = new ViewerDialog(null); String filename = m_List.getSelectedValue().toString(); int result; try { DataSource source = new DataSource(filename); result = dialog.showDialog(source.getDataSet()); // nasty workaround for Windows regarding locked files: // if file Reader in Loader is not closed explicitly, we cannot // overwrite the file. source = null; System.gc(); // workaround end if ((result == ViewerDialog.APPROVE_OPTION) && (dialog.isChanged())) { result = JOptionPane.showConfirmDialog(this, "File was modified - save changes?"); if (result == JOptionPane.YES_OPTION) { Saver saver = ConverterUtils.getSaverForFile(filename); saver.setFile(new File(filename)); saver.setInstances(dialog.getInstances()); saver.writeBatch(); } } } catch (Exception ex) { JOptionPane.showMessageDialog(this, "Error loading file '" + filename + "':\n" + ex.toString(), "Error loading file", JOptionPane.INFORMATION_MESSAGE); } } setButtons(null); } else if (e.getSource() == m_UpBut) { JListHelper.moveUp(m_List); } else if (e.getSource() == m_DownBut) { JListHelper.moveDown(m_List); } } /** * Tests out the dataset list panel from the command line. * * @param args ignored */ public static void main(String[] args) { try { final JFrame jf = new JFrame("Dataset List Editor"); jf.getContentPane().setLayout(new BorderLayout()); DatasetListPanel dp = new DatasetListPanel(); jf.getContentPane().add(dp, BorderLayout.CENTER); jf.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { jf.dispose(); System.exit(0); } }); jf.pack(); jf.setVisible(true); System.err.println("Short nap"); Thread.sleep(3000); System.err.println("Done"); dp.setExperiment(new Experiment()); } 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/experiment/DistributeExperimentPanel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * DistributeExperimentPanel.java * Copyright (C) 2000-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.experiment; import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.BorderFactory; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JRadioButton; import weka.core.Utils; import weka.experiment.Experiment; import weka.experiment.RemoteExperiment; /** * This panel enables an experiment to be distributed to multiple hosts; * it also allows remote host names to be specified. * * @author Mark Hall (mhall@cs.waikato.ac.nz) * @version $Revision$ */ public class DistributeExperimentPanel extends JPanel { /** for serialization */ private static final long serialVersionUID = 5206721431754800278L; /** * The experiment to configure. */ RemoteExperiment m_Exp = null; /** Distribute the current experiment to remote hosts */ protected JCheckBox m_enableDistributedExperiment = new JCheckBox(); /** Popup the HostListPanel */ protected JButton m_configureHostNames = new JButton("Hosts"); /** The host list panel */ protected HostListPanel m_hostList = new HostListPanel(); /** * Split experiment up by data set. */ protected JRadioButton m_splitByDataSet = new JRadioButton("By data set"); /** * Split experiment up by run number. */ protected JRadioButton m_splitByRun = new JRadioButton("By run"); /** * Split experiment up by algorithm. */ protected JRadioButton m_splitByProperty = new JRadioButton("By property"); /** Handle radio buttons */ ActionListener m_radioListener = new ActionListener() { public void actionPerformed(ActionEvent e) { updateRadioLinks(); } }; /** * Constructor */ public DistributeExperimentPanel() { m_enableDistributedExperiment.setSelected(false); m_enableDistributedExperiment. setToolTipText("Allow this experiment to be distributed to remote hosts"); m_enableDistributedExperiment.setEnabled(false); m_configureHostNames.setEnabled(false); m_configureHostNames.setToolTipText("Edit the list of remote hosts"); m_enableDistributedExperiment.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { m_configureHostNames.setEnabled(m_enableDistributedExperiment. isSelected()); m_splitByDataSet.setEnabled(m_enableDistributedExperiment. isSelected()); m_splitByRun.setEnabled(m_enableDistributedExperiment. isSelected()); m_splitByProperty.setEnabled(m_enableDistributedExperiment. isSelected()); } }); m_configureHostNames.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { popupHostPanel(); } }); m_splitByDataSet.setToolTipText("Distribute experiment by data set"); m_splitByRun.setToolTipText("Distribute experiment by run number"); m_splitByProperty.setToolTipText("Distribute experiment by property"); m_splitByDataSet.setSelected(true); m_splitByDataSet.setEnabled(false); m_splitByRun.setEnabled(false); m_splitByProperty.setEnabled(false); m_splitByDataSet.addActionListener(m_radioListener); m_splitByRun.addActionListener(m_radioListener); m_splitByProperty.addActionListener(m_radioListener); ButtonGroup bg = new ButtonGroup(); bg.add(m_splitByDataSet); bg.add(m_splitByRun); bg.add(m_splitByProperty); JPanel rbuts = new JPanel(); rbuts.setLayout(new GridLayout(1, 2)); rbuts.add(m_splitByDataSet); rbuts.add(m_splitByRun); rbuts.add(m_splitByProperty); setLayout(new BorderLayout()); setBorder(BorderFactory.createTitledBorder("Distribute experiment")); add(m_enableDistributedExperiment, BorderLayout.WEST); add(m_configureHostNames, BorderLayout.CENTER); add(rbuts, BorderLayout.SOUTH); } /** * Creates the panel with the supplied initial experiment. * * @param exp a value of type 'Experiment' */ public DistributeExperimentPanel(Experiment exp) { this(); setExperiment(exp); } /** * Sets the experiment to be configured. * * @param exp a value of type 'Experiment' */ public void setExperiment(Experiment exp) { m_enableDistributedExperiment.setEnabled(true); m_Exp = null; if (exp instanceof RemoteExperiment) { m_Exp = (RemoteExperiment)exp; m_enableDistributedExperiment.setSelected(true); m_configureHostNames.setEnabled(true); m_hostList.setExperiment(m_Exp); m_splitByDataSet.setEnabled(true); m_splitByRun.setEnabled(true); m_splitByProperty.setEnabled(true); m_splitByDataSet.setSelected(m_Exp.getSplitByDataSet()); m_splitByRun.setSelected(!m_Exp.getSplitByDataSet() && !m_Exp.getSplitByProperty()); m_splitByProperty.setSelected(m_Exp.getSplitByProperty()); } } /** * Pop up the host list panel */ private void popupHostPanel() { try { final JFrame jf = Utils.getWekaJFrame("Edit host names", this); jf.getContentPane().setLayout(new BorderLayout()); jf.getContentPane().add(m_hostList, BorderLayout.CENTER); jf.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { jf.dispose(); } }); jf.pack(); jf.setLocationRelativeTo(this); jf.setVisible(true); } catch (Exception ex) { ex.printStackTrace(); System.err.println(ex.getMessage()); } } /** * Returns true if the distribute experiment checkbox is selected * @return true if the user has opted for distributing the experiment */ public boolean distributedExperimentSelected() { return m_enableDistributedExperiment.isSelected(); } /** * Enable objects to listen for changes to the check box * @param al an ActionListener */ public void addCheckBoxActionListener(ActionListener al) { m_enableDistributedExperiment.addActionListener(al); } /** * Updates the remote experiment when a radio button is clicked */ private void updateRadioLinks() { if (m_Exp != null) { m_Exp.setSplitByDataSet(m_splitByDataSet.isSelected()); m_Exp.setSplitByProperty(m_splitByProperty.isSelected()); } } /** * Tests out the panel from the command line. * * @param args ignored. */ public static void main(String [] args) { try { final JFrame jf = new JFrame("DistributeExperiment"); jf.getContentPane().setLayout(new BorderLayout()); jf.getContentPane().add(new DistributeExperimentPanel(new Experiment()), BorderLayout.CENTER); jf.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { jf.dispose(); System.exit(0); } }); jf.pack(); 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/experiment/Experimenter.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * Experimenter.java * Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.experiment; import weka.core.Memory; import weka.experiment.Experiment; import weka.gui.AbstractPerspective; import weka.gui.LookAndFeel; import weka.gui.PerspectiveInfo; import javax.swing.JFrame; import javax.swing.JTabbedPane; import java.awt.BorderLayout; import java.awt.Image; import java.awt.Toolkit; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; /** * The main class for the experiment environment. Lets the user create, open, * save, configure, run experiments, and analyse experimental results. * * @author Len Trigg (trigg@cs.waikato.ac.nz) * @version $Revision$ */ @PerspectiveInfo(ID = "weka.gui.experimenter", title = "Experiment", toolTipText = "Run large scale experiments", iconPath = "weka/gui/weka_icon_new_small.png") public class Experimenter extends AbstractPerspective { /** for serialization */ private static final long serialVersionUID = -5751617505738193788L; /** The panel for configuring the experiment */ protected SetupModePanel m_SetupPanel; /** The panel for running the experiment */ protected RunPanel m_RunPanel; /** The panel for analysing experimental results */ protected ResultsPanel m_ResultsPanel; /** The tabbed pane that controls which sub-pane we are working with */ protected JTabbedPane m_TabbedPane = new JTabbedPane(); /** * True if the class attribute is the first attribute for all datasets * involved in this experiment. */ protected boolean m_ClassFirst = false; /** * Creates the experiment environment gui with no initial experiment */ public Experimenter() { this(false); } /** * Creates the experiment environment gui with no initial experiment */ public Experimenter(boolean classFirst) { m_SetupPanel = new SetupModePanel(); m_ResultsPanel = new ResultsPanel(); m_RunPanel = new RunPanel(); m_RunPanel.setResultsPanel(m_ResultsPanel); m_ClassFirst = classFirst; m_TabbedPane.addTab("Setup", null, m_SetupPanel, "Set up the experiment"); m_TabbedPane.addTab("Run", null, m_RunPanel, "Run the experiment"); m_TabbedPane.addTab("Analyse", null, m_ResultsPanel, "Analyse experiment results"); m_TabbedPane.setSelectedIndex(0); m_TabbedPane.setEnabledAt(1, false); m_SetupPanel.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent e) { // System.err.println("Updated experiment"); Experiment exp = m_SetupPanel.getExperiment(); if (exp != null) { exp.classFirst(m_ClassFirst); m_RunPanel.setExperiment(exp); // m_ResultsPanel.setExperiment(exp); m_TabbedPane.setEnabledAt(1, true); } } }); setLayout(new BorderLayout()); add(m_TabbedPane, BorderLayout.CENTER); } /** * Gets called if we are running in a {@code GUIApplication}. We pass * on a reference to the main perspective to the ResultsPanel here. */ @Override public void instantiationComplete() { m_ResultsPanel .setMainPerspective(getMainApplication().getMainPerspective()); } /** * variable for the Experimenter class which would be set to null by the * memory monitoring thread to free up some memory if we running out of memory */ private static Experimenter m_experimenter; /** for monitoring the Memory consumption */ protected static Memory m_Memory = new Memory(true); /** * Tests out the experiment environment. * * @param args ignored. */ public static void main(String[] args) { weka.core.logging.Logger.log(weka.core.logging.Logger.Level.INFO, "Logging started"); // make sure that packages are loaded and the GenericPropertiesCreator // executes to populate the lists correctly weka.gui.GenericObjectEditor.determineClasses(); LookAndFeel.setLookAndFeel(); try { // uncomment to disable the memory management: // m_Memory.setEnabled(false); boolean classFirst = false; if (args.length > 0) { classFirst = args[0].equals("CLASS_FIRST"); } m_experimenter = new Experimenter(classFirst); final JFrame jf = new JFrame("Weka Experiment Environment"); jf.getContentPane().setLayout(new BorderLayout()); jf.getContentPane().add(m_experimenter, BorderLayout.CENTER); jf.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { jf.dispose(); System.exit(0); } }); jf.pack(); jf.setSize(800, 600); jf.setVisible(true); Image icon = Toolkit.getDefaultToolkit().getImage( m_experimenter.getClass().getClassLoader() .getResource("weka/gui/weka_icon_new_48.png")); jf.setIconImage(icon); Thread memMonitor = new Thread() { @Override public void run() { while (true) { // try { // Thread.sleep(10); if (m_Memory.isOutOfMemory()) { // clean up jf.dispose(); m_experimenter = null; System.gc(); // display error System.err.println("\ndisplayed 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()); } } }
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/experiment/ExperimenterDefaults.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ExperimenterDefaults.java * Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.experiment; import weka.core.Utils; import weka.experiment.PairedCorrectedTTester; import weka.experiment.ResultMatrix; import weka.experiment.ResultMatrixPlainText; import weka.experiment.Tester; import java.io.File; import java.io.Serializable; import java.util.Collections; import java.util.Enumeration; import java.util.Properties; import java.util.Vector; /** * This class offers get methods for the default Experimenter settings in the * props file <code>weka/gui/experiment/Experimenter.props</code>. * * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ * @see #PROPERTY_FILE */ public class ExperimenterDefaults implements Serializable { /** for serialization. */ static final long serialVersionUID = -2835933184632147981L; /** The name of the properties file. */ public final static String PROPERTY_FILE = "weka/gui/experiment/Experimenter.props"; /** Properties associated with the experimenter options. */ protected static Properties PROPERTIES; static { try { PROPERTIES = Utils.readProperties(PROPERTY_FILE); } catch (Exception e) { System.err.println("Problem reading properties. Fix before continuing."); e.printStackTrace(); PROPERTIES = new Properties(); } } /** * returns the value for the specified property, if non-existent then the * default value. * * @param property the property to retrieve the value for * @param defaultValue the default value for the property * @return the value of the specified property */ public static String get(String property, String defaultValue) { return PROPERTIES.getProperty(property, defaultValue); } /** * returns the associated properties file. * * @return the props file */ public final static Properties getProperties() { return PROPERTIES; } /** * returns the class name of the default setup panel. * * @return the class name */ public final static String getSetupPanel() { return get("SetupPanel", SimpleSetupPanel.class.getName()); } /** * returns the default experiment extension. * * @return the extension (incl. dot) */ public final static String getExtension() { return get("Extension", ".exp"); } /** * returns the default destination. * * @return the destination */ public final static String getDestination() { return get("Destination", "ARFF file"); } /** * returns the default experiment type. * * @return the type */ public final static String getExperimentType() { return get("ExperimentType", "Cross-validation"); } /** * whether classification or regression is used. * * @return true if classification */ public final static boolean getUseClassification() { return Boolean.valueOf(get("UseClassification", "true")).booleanValue(); } /** * returns the number of folds used for cross-validation. * * @return the number of folds */ public final static int getFolds() { return Integer.parseInt(get("Folds", "10")); } /** * returns the training percentage in case of splits. * * @return the percentage (0-100) */ public final static double getTrainPercentage() { return Integer.parseInt(get("TrainPercentage", "66")); } /** * returns the number of repetitions to use. * * @return the repetitions/runs */ public final static int getRepetitions() { return Integer.parseInt(get("Repetitions", "10")); } /** * whether datasets or algorithms are iterated first. * * @return true if datasets are iterated first */ public final static boolean getDatasetsFirst() { return Boolean.valueOf(get("DatasetsFirst", "true")).booleanValue(); } /** * returns the initial directory for the datasets (if empty, it returns the * user's home directory). * * @return the directory */ public final static File getInitialDatasetsDirectory() { String dir; dir = get("InitialDatasetsDirectory", ""); if (dir.equals("")) { dir = System.getProperty("user.dir"); } return new File(dir); } /** * whether relative paths are used by default. * * @return true if relative paths are used */ public final static boolean getUseRelativePaths() { return Boolean.valueOf(get("UseRelativePaths", "false")).booleanValue(); } /** * returns the display name of the preferred Tester algorithm. * * @return the display name * @see Tester * @see PairedCorrectedTTester */ public final static String getTester() { return get("Tester", new PairedCorrectedTTester().getDisplayName()); } /** * the comma-separated list of attribute names that identify a row. * * @return the attribute list */ public final static String getRow() { return get("Row", "Key_Dataset"); } /** * the comma-separated list of attribute names that identify a column. * * @return the attribute list */ public final static String getColumn() { return get("Column", "Key_Scheme,Key_Scheme_options,Key_Scheme_version_ID"); } /** * returns the name of the field used for comparison. * * @return the comparison field */ public final static String getComparisonField() { return get("ComparisonField", "percent_correct"); } /** * returns the default significance. * * @return the significance (0.0-1.0) */ public final static double getSignificance() { return Double.parseDouble(get("Significance", "0.05")); } /** * returns the default sorting (empty string means none). * * @return the sorting field */ public final static String getSorting() { return get("Sorting", ""); } /** * returns whether StdDevs are shown by default. * * @return true if stddevs are shown */ public final static boolean getShowStdDevs() { return Boolean.valueOf(get("ShowStdDev", "false")).booleanValue(); } /** * returns whether the Average is shown by default. * * @return true if the average is shown */ public final static boolean getShowAverage() { return Boolean.valueOf(get("ShowAverage", "false")).booleanValue(); } /** * returns the default precision for the mean. * * @return the decimals of the mean */ public final static int getMeanPrecision() { return Integer.parseInt(get("MeanPrecision", "2")); } /** * returns the default precision for the stddevs. * * @return the decimals of the stddevs */ public final static int getStdDevPrecision() { return Integer.parseInt(get("StdDevPrecision", "2")); } /** * returns the classname (and optional options) of the ResultMatrix class, * responsible for the output format. * * @return the classname and options * @see ResultMatrix * @see ResultMatrixPlainText */ public final static ResultMatrix getOutputFormat() { ResultMatrix result; try { String[] options = Utils .splitOptions(get( "OutputFormat", ResultMatrix.class.getName() + " -col-name-width 0 -row-name-width 25 -mean-width 0 -stddev-width 0 -sig-width 0 -count-width 5 -print-col-names -print-row-names -enum-col-names")); String classname = options[0]; options[0] = ""; result = (ResultMatrix) Utils.forName(ResultMatrix.class, classname, options); } catch (Exception e) { e.printStackTrace(); result = new ResultMatrixPlainText(); } // override with other default properties result.setMeanPrec(getMeanPrecision()); result.setStdDevPrec(getStdDevPrecision()); result.setShowAverage(getShowAverage()); result.setShowStdDev(getShowStdDevs()); result.setRemoveFilterName(getRemoveFilterClassnames()); return result; } /** * whether the filter classnames in the dataset names are removed by default. * * @return true if filter names are removed */ public final static boolean getRemoveFilterClassnames() { return Boolean.valueOf(get("RemoveFilterClassnames", "false")) .booleanValue(); } /** * only for testing - prints the content of the props file. * * @param args commandline parameters - ignored */ public static void main(String[] args) { Enumeration<?> names; String name; Vector<String> sorted; System.out.println("\nExperimenter defaults:"); names = PROPERTIES.propertyNames(); // sort names sorted = new Vector<String>(); while (names.hasMoreElements()) { sorted.add(names.nextElement().toString()); } Collections.sort(sorted); names = sorted.elements(); // output while (names.hasMoreElements()) { name = names.nextElement().toString(); System.out.println("- " + name + ": " + PROPERTIES.getProperty(name, "")); } System.out.println(); } }
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/experiment/GeneratorPropertyIteratorPanel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * GeneratorPropertyIteratorPanel.java * Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.experiment; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyDescriptor; import java.lang.reflect.Array; import java.util.ArrayList; import javax.swing.BorderFactory; import javax.swing.ComboBoxModel; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JPanel; import weka.experiment.Experiment; import weka.experiment.PropertyNode; import weka.gui.GenericArrayEditor; import weka.gui.PropertySelectorDialog; /** * This panel controls setting a list of values for an arbitrary resultgenerator * property for an experiment to iterate over. * * @author Len Trigg (trigg@cs.waikato.ac.nz) * @version $Revision$ */ public class GeneratorPropertyIteratorPanel extends JPanel implements ActionListener { /** for serialization */ private static final long serialVersionUID = -6026938995241632139L; /** Click to select the property to iterate over */ protected JButton m_ConfigureBut = new JButton("Select property..."); /** Controls whether the custom iterator is used or not */ protected JComboBox m_StatusBox = new JComboBox(); /** Allows editing of the custom property values */ protected GenericArrayEditor m_ArrayEditor = new GenericArrayEditor(); /** The experiment this all applies to */ protected Experiment m_Exp; /** * Listeners who want to be notified about editing status of this panel */ protected ArrayList<ActionListener> m_Listeners = new ArrayList<ActionListener>(); /** * Creates the property iterator panel initially disabled. */ public GeneratorPropertyIteratorPanel() { String[] options = { "Disabled", "Enabled" }; ComboBoxModel cbm = new DefaultComboBoxModel(options); m_StatusBox.setModel(cbm); m_StatusBox.setSelectedIndex(0); m_StatusBox.addActionListener(this); m_StatusBox.setEnabled(false); m_ConfigureBut.setEnabled(false); m_ConfigureBut.addActionListener(this); JPanel buttons = new JPanel(); GridBagLayout gb = new GridBagLayout(); GridBagConstraints constraints = new GridBagConstraints(); buttons.setBorder(BorderFactory.createEmptyBorder(10, 5, 10, 5)); // buttons.setLayout(new GridLayout(1, 2)); buttons.setLayout(gb); constraints.gridx = 0; constraints.gridy = 0; constraints.weightx = 5; constraints.fill = GridBagConstraints.HORIZONTAL; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.insets = new Insets(0, 2, 0, 2); buttons.add(m_StatusBox, constraints); constraints.gridx = 1; constraints.gridy = 0; constraints.weightx = 5; constraints.gridwidth = 1; constraints.gridheight = 1; buttons.add(m_ConfigureBut, constraints); buttons.setMaximumSize(new Dimension(buttons.getMaximumSize().width, buttons.getMinimumSize().height)); setBorder(BorderFactory.createTitledBorder("Generator properties")); setLayout(new BorderLayout()); add(buttons, BorderLayout.NORTH); // add(Box.createHorizontalGlue()); ((JComponent) m_ArrayEditor.getCustomEditor()).setBorder(BorderFactory .createEtchedBorder()); m_ArrayEditor.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent e) { System.err.println("Updating experiment property iterator array"); m_Exp.setPropertyArray(m_ArrayEditor.getValue()); } }); add(m_ArrayEditor.getCustomEditor(), BorderLayout.CENTER); } /** * Creates the property iterator panel and sets the experiment. * * @param exp a value of type 'Experiment' */ public GeneratorPropertyIteratorPanel(Experiment exp) { this(); setExperiment(exp); } /** * Returns true if the editor is currently in an active status---that is the * array is active and able to be edited. * * @return true if editor is active */ public boolean getEditorActive() { if (m_StatusBox.getSelectedIndex() == 0) { return false; } return true; } /** * Sets the experiment which will have the custom properties edited. * * @param exp a value of type 'Experiment' */ public void setExperiment(Experiment exp) { m_Exp = exp; m_StatusBox.setEnabled(true); m_ArrayEditor.setValue(m_Exp.getPropertyArray()); if (m_Exp.getPropertyArray() == null) { m_StatusBox.setSelectedIndex(0); m_ConfigureBut.setEnabled(false); } else { m_StatusBox.setSelectedIndex(m_Exp.getUsePropertyIterator() ? 1 : 0); m_ConfigureBut.setEnabled(m_Exp.getUsePropertyIterator()); } validate(); } /** * Gets the user to select a property of the current resultproducer. * * @return APPROVE_OPTION if the selection went OK, otherwise the selection * was cancelled. */ protected int selectProperty() { final PropertySelectorDialog jd = new PropertySelectorDialog(null, m_Exp.getResultProducer()); jd.setLocationRelativeTo(this); int result = jd.showDialog(); if (result == PropertySelectorDialog.APPROVE_OPTION) { System.err.println("Property Selected"); PropertyNode[] path = jd.getPath(); Object value = path[path.length - 1].value; PropertyDescriptor property = path[path.length - 1].property; // Make an array containing the propertyValue Class<?> propertyClass = property.getPropertyType(); m_Exp.setPropertyPath(path); m_Exp.setPropertyArray(Array.newInstance(propertyClass, 1)); Array.set(m_Exp.getPropertyArray(), 0, value); // Pass it to the arrayeditor m_ArrayEditor.setValue(m_Exp.getPropertyArray()); m_ArrayEditor.getCustomEditor().repaint(); System.err.println("Set new array to array editor"); } else { System.err.println("Cancelled"); } return result; } /** * Handles the various button clicking type activities. * * @param e a value of type 'ActionEvent' */ @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == m_ConfigureBut) { selectProperty(); } else if (e.getSource() == m_StatusBox) { // notify any listeners for (int i = 0; i < m_Listeners.size(); i++) { ActionListener temp = (m_Listeners.get(i)); temp.actionPerformed(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "Editor status change")); } // Toggles whether the custom property is used if (m_StatusBox.getSelectedIndex() == 0) { m_Exp.setUsePropertyIterator(false); m_ConfigureBut.setEnabled(false); m_ArrayEditor.getCustomEditor().setEnabled(false); m_ArrayEditor.setValue(null); validate(); } else { if (m_Exp.getPropertyArray() == null) { selectProperty(); } if (m_Exp.getPropertyArray() == null) { m_StatusBox.setSelectedIndex(0); } else { m_Exp.setUsePropertyIterator(true); m_ConfigureBut.setEnabled(true); m_ArrayEditor.getCustomEditor().setEnabled(true); } validate(); } } } /** * Add a listener interested in kowing about editor status changes * * @param newA an listener to add */ public void addActionListener(ActionListener newA) { m_Listeners.add(newA); } /** * Tests out the panel from the command line. * * @param args ignored. */ public static void main(String[] args) { try { final JFrame jf = new JFrame("Generator Property Iterator"); jf.getContentPane().setLayout(new BorderLayout()); GeneratorPropertyIteratorPanel gp = new GeneratorPropertyIteratorPanel(); jf.getContentPane().add(gp, BorderLayout.CENTER); jf.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { jf.dispose(); System.exit(0); } }); jf.pack(); jf.setVisible(true); System.err.println("Short nap"); Thread.sleep(3000); System.err.println("Done"); gp.setExperiment(new Experiment()); } 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/experiment/HostListPanel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * HostListPanel.java * Copyright (C) 2000-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.experiment; import java.awt.BorderLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.BorderFactory; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextField; import weka.experiment.RemoteExperiment; /** * This panel controls setting a list of hosts for a RemoteExperiment to * use. * * @author Mark Hall (mhall@cs.waikato.ac.nz) * @version $Revision$ */ public class HostListPanel extends JPanel implements ActionListener { /** for serialization */ private static final long serialVersionUID = 7182791134585882197L; /** The remote experiment to set the host list of */ protected RemoteExperiment m_Exp; /** The component displaying the host list */ protected JList m_List; /** Click to remove the selected host from the list */ protected JButton m_DeleteBut = new JButton("Delete selected"); /** The field with which to enter host names */ protected JTextField m_HostField = new JTextField(25); /** * Creates the host list panel with the given experiment. * * @param exp a value of type 'Experiment' */ public HostListPanel(RemoteExperiment exp) { this(); setExperiment(exp); } /** * Create the host list panel initially disabled. */ public HostListPanel() { m_List = new JList(); m_List.setModel(new DefaultListModel()); m_DeleteBut.setEnabled(false); m_DeleteBut.addActionListener(this); m_HostField.addActionListener(this); setLayout(new BorderLayout()); setBorder(BorderFactory.createTitledBorder("Hosts")); JPanel topLab = new JPanel(); GridBagLayout gb = new GridBagLayout(); GridBagConstraints constraints = new GridBagConstraints(); topLab.setBorder(BorderFactory.createEmptyBorder(10, 5, 10, 5)); // topLab.setLayout(new GridLayout(1,2,5,5)); topLab.setLayout(gb); constraints.gridx=0;constraints.gridy=0;constraints.weightx=5; constraints.fill = GridBagConstraints.HORIZONTAL; constraints.gridwidth=1;constraints.gridheight=1; constraints.insets = new Insets(0,2,0,2); topLab.add(m_DeleteBut,constraints); constraints.gridx=1;constraints.gridy=0;constraints.weightx=5; constraints.gridwidth=1;constraints.gridheight=1; topLab.add(m_HostField,constraints); add(topLab, BorderLayout.NORTH); add(new JScrollPane(m_List), BorderLayout.CENTER); } /** * Tells the panel to act on a new experiment. * * @param exp a value of type 'Experiment' */ public void setExperiment(RemoteExperiment exp) { m_Exp = exp; m_List.setModel(m_Exp.getRemoteHosts()); if (((DefaultListModel)m_List.getModel()).size() > 0) { m_DeleteBut.setEnabled(true); } } /** * Handle actions when text is entered into the host field or the * delete button is pressed. * * @param e a value of type 'ActionEvent' */ public void actionPerformed(ActionEvent e) { if (e.getSource() == m_HostField) { ((DefaultListModel)m_List.getModel()) .addElement(m_HostField.getText()); m_DeleteBut.setEnabled(true); } else if (e.getSource() == m_DeleteBut) { int [] selected = m_List.getSelectedIndices(); if (selected != null) { for (int i = selected.length - 1; i >= 0; i--) { int current = selected[i]; ((DefaultListModel)m_List.getModel()).removeElementAt(current); if (((DefaultListModel)m_List.getModel()).size() > current) { m_List.setSelectedIndex(current); } else { m_List.setSelectedIndex(current - 1); } } } if (((DefaultListModel)m_List.getModel()).size() == 0) { m_DeleteBut.setEnabled(false); } } } /** * Tests out the host list panel from the command line. * * @param args ignored */ public static void main(String [] args) { try { final JFrame jf = new JFrame("Host List Editor"); jf.getContentPane().setLayout(new BorderLayout()); HostListPanel dp = new HostListPanel(); jf.getContentPane().add(dp, BorderLayout.CENTER); jf.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { jf.dispose(); System.exit(0); } }); jf.pack(); jf.setVisible(true); /* System.err.println("Short nap"); Thread.currentThread().sleep(3000); System.err.println("Done"); */ // dp.setExperiment(new Experiment()); } 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/experiment/OutputFormatDialog.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * OutputFormatDialog.java * Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.experiment; import weka.core.PluginManager; import weka.experiment.ResultMatrix; import weka.experiment.ResultMatrixPlainText; import weka.gui.GenericObjectEditor; import weka.gui.PropertyPanel; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSpinner; import javax.swing.SpinnerNumberModel; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Frame; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.List; import java.util.Vector; /** * A dialog for setting various output format parameters. * * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class OutputFormatDialog extends JDialog { /** for serialization. */ private static final long serialVersionUID = 2169792738187807378L; /** Signifies an OK property selection. */ public static final int APPROVE_OPTION = 0; /** Signifies a cancelled property selection. */ public static final int CANCEL_OPTION = 1; /** the result of the user's action, either OK or CANCEL. */ protected int m_Result; /** the different classes for outputting the comparison tables. */ protected Vector<Class<?>> m_OutputFormatClasses; /** the different names of matrices for outputting the comparison tables. */ protected Vector<String> m_OutputFormatNames; /** Lets the user configure the result matrix. */ protected GenericObjectEditor m_ResultMatrixEditor; /** the panel for the GOE. */ protected PropertyPanel m_ResultMatrixPanel; /** the label for the GOE. */ protected JLabel m_ResultMatrixLabel; /** the current result matrix. */ protected ResultMatrix m_ResultMatrix; /** lets the user choose the format for the output. */ protected JComboBox m_OutputFormatComboBox; /** the label for the format. */ protected JLabel m_OutputFormatLabel; /** the spinner to choose the precision for the mean from. */ protected JSpinner m_MeanPrecSpinner; /** the label for the mean precision. */ protected JLabel m_MeanPrecLabel; /** the spinner to choose the precision for the std. deviation from */ protected JSpinner m_StdDevPrecSpinner; /** the label for the std dev precision. */ protected JLabel m_StdDevPrecLabel; /** the checkbox for outputting the average. */ protected JCheckBox m_ShowAverageCheckBox; /** the label for showing the average. */ protected JLabel m_ShowAverageLabel; /** the checkbox for the removing of filter classnames. */ protected JCheckBox m_RemoveFilterNameCheckBox; /** the label for the removing the filter classnames. */ protected JLabel m_RemoveFilterNameLabel; /** Click to activate the current set parameters. */ protected JButton m_OkButton; /** Click to cancel the dialog. */ protected JButton m_CancelButton; /** whether to ignore updates in the GUI momentarily. */ protected boolean m_IgnoreChanges; /** * initializes the dialog with the given parent frame. * * @param parent the parent of this dialog */ public OutputFormatDialog(Frame parent) { super(parent, "Output Format...", ModalityType.DOCUMENT_MODAL); m_IgnoreChanges = true; initialize(); initGUI(); m_IgnoreChanges = false; } /** * initializes the member variables. */ protected void initialize() { List<String> classes; int i; Class<?> cls; ResultMatrix matrix; m_Result = CANCEL_OPTION; if (m_OutputFormatClasses == null) { classes = PluginManager.getPluginNamesOfTypeList(ResultMatrix.class.getName()); // set names and classes m_OutputFormatClasses = new Vector<Class<?>>(); m_OutputFormatNames = new Vector<String>(); for (i = 0; i < classes.size(); i++) { try { cls = Class.forName(classes.get(i).toString()); matrix = (ResultMatrix) cls.newInstance(); m_OutputFormatClasses.add(cls); m_OutputFormatNames.add(matrix.getDisplayName()); } catch (Exception e) { e.printStackTrace(); } } } } /** * performs the creation of the dialog and all its components. */ protected void initGUI() { JPanel panel; SpinnerNumberModel model; JPanel panel2; getContentPane().setLayout(new BorderLayout()); panel = new JPanel(new GridLayout(6, 1)); panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); getContentPane().add(panel, BorderLayout.CENTER); // mean precision m_MeanPrecSpinner = new JSpinner(); m_MeanPrecSpinner.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { getData(); } }); model = (SpinnerNumberModel) m_MeanPrecSpinner.getModel(); model.setMaximum(new Integer(20)); model.setMinimum(new Integer(0)); m_MeanPrecLabel = new JLabel("Mean Precision"); m_MeanPrecLabel.setDisplayedMnemonic('M'); m_MeanPrecLabel.setLabelFor(m_MeanPrecSpinner); panel2 = new JPanel(new FlowLayout(FlowLayout.LEFT)); panel2.add(m_MeanPrecLabel); panel2.add(m_MeanPrecSpinner); panel.add(panel2); // stddev precision m_StdDevPrecSpinner = new JSpinner(); m_StdDevPrecSpinner.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { getData(); } }); model = (SpinnerNumberModel) m_StdDevPrecSpinner.getModel(); model.setMaximum(new Integer(20)); model.setMinimum(new Integer(0)); m_StdDevPrecLabel = new JLabel("StdDev. Precision"); m_StdDevPrecLabel.setDisplayedMnemonic('S'); m_StdDevPrecLabel.setLabelFor(m_StdDevPrecSpinner); panel2 = new JPanel(new FlowLayout(FlowLayout.LEFT)); panel2.add(m_StdDevPrecLabel); panel2.add(m_StdDevPrecSpinner); panel.add(panel2); // Format m_OutputFormatComboBox = new JComboBox(m_OutputFormatNames); m_OutputFormatComboBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { getData(); } }); m_OutputFormatLabel = new JLabel("Output Format"); m_OutputFormatLabel.setDisplayedMnemonic('F'); m_OutputFormatLabel.setLabelFor(m_OutputFormatComboBox); panel2 = new JPanel(new FlowLayout(FlowLayout.LEFT)); panel2.add(m_OutputFormatLabel); panel2.add(m_OutputFormatComboBox); panel.add(panel2); // Average m_ShowAverageCheckBox = new JCheckBox(""); m_ShowAverageCheckBox.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { getData(); } }); m_ShowAverageLabel = new JLabel("Show Average"); m_ShowAverageLabel.setDisplayedMnemonic('A'); m_ShowAverageLabel.setLabelFor(m_ShowAverageCheckBox); panel2 = new JPanel(new FlowLayout(FlowLayout.LEFT)); panel2.add(m_ShowAverageLabel); panel2.add(m_ShowAverageCheckBox); panel.add(panel2); // Remove filter classname m_RemoveFilterNameCheckBox = new JCheckBox(""); m_RemoveFilterNameCheckBox.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { getData(); } }); m_RemoveFilterNameLabel = new JLabel("Remove filter classnames"); m_RemoveFilterNameLabel.setDisplayedMnemonic('R'); m_RemoveFilterNameLabel.setLabelFor(m_RemoveFilterNameCheckBox); panel2 = new JPanel(new FlowLayout(FlowLayout.LEFT)); panel2.add(m_RemoveFilterNameLabel); panel2.add(m_RemoveFilterNameCheckBox); panel.add(panel2); // Advanced setup m_ResultMatrix = ExperimenterDefaults.getOutputFormat(); m_ResultMatrixEditor = new GenericObjectEditor(true); m_ResultMatrixEditor.setClassType(ResultMatrix.class); m_ResultMatrixEditor.setValue(m_ResultMatrix); m_ResultMatrixEditor .addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent e) { // user selected different class? if (!m_ResultMatrix.getClass().equals( m_ResultMatrixEditor.getValue().getClass())) { // if it's the preferred class, then automaticallly use the // Experimenter defaults if (m_ResultMatrixEditor.getValue().getClass() .equals(ExperimenterDefaults.getOutputFormat().getClass())) { m_ResultMatrix = ExperimenterDefaults.getOutputFormat(); m_ResultMatrixEditor.setValue(ExperimenterDefaults .getOutputFormat()); } else { m_ResultMatrix = (ResultMatrix) m_ResultMatrixEditor.getValue(); } setData(); } repaint(); } }); ((GenericObjectEditor.GOEPanel) m_ResultMatrixEditor.getCustomEditor()) .addOkListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m_ResultMatrix = (ResultMatrix) m_ResultMatrixEditor.getValue(); setData(); } }); m_ResultMatrixPanel = new PropertyPanel(m_ResultMatrixEditor, false); m_ResultMatrixLabel = new JLabel("Advanced setup"); panel2 = new JPanel(new FlowLayout(FlowLayout.LEFT)); panel2.add(m_ResultMatrixLabel); panel2.add(m_ResultMatrixPanel); panel.add(panel2); // Buttons panel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); getContentPane().add(panel, BorderLayout.SOUTH); m_CancelButton = new JButton("Cancel"); m_CancelButton.setMnemonic('C'); m_CancelButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m_Result = CANCEL_OPTION; setVisible(false); } }); m_OkButton = new JButton("OK"); m_OkButton.setMnemonic('O'); m_OkButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { getData(); m_Result = APPROVE_OPTION; setVisible(false); } }); panel.add(m_OkButton); panel.add(m_CancelButton); // default button getRootPane().setDefaultButton(m_OkButton); // initial layout (to get widths and heights) pack(); // adjust dimensions m_MeanPrecLabel.setPreferredSize(new Dimension(m_RemoveFilterNameLabel .getWidth(), m_MeanPrecLabel.getHeight())); m_MeanPrecSpinner.setPreferredSize(new Dimension(m_MeanPrecSpinner .getWidth() * 3, m_MeanPrecSpinner.getHeight())); m_StdDevPrecLabel.setPreferredSize(new Dimension(m_RemoveFilterNameLabel .getWidth(), m_StdDevPrecLabel.getHeight())); m_StdDevPrecSpinner.setPreferredSize(new Dimension(m_StdDevPrecSpinner .getWidth() * 3, m_StdDevPrecSpinner.getHeight())); m_OutputFormatLabel.setPreferredSize(new Dimension(m_RemoveFilterNameLabel .getWidth(), m_OutputFormatLabel.getHeight())); m_ShowAverageLabel.setPreferredSize(new Dimension(m_RemoveFilterNameLabel .getWidth(), m_ShowAverageLabel.getHeight())); m_ResultMatrixLabel.setPreferredSize(new Dimension(m_RemoveFilterNameLabel .getWidth(), m_ResultMatrixLabel.getHeight())); m_ResultMatrixPanel.setPreferredSize(new Dimension( (int) (m_ResultMatrixPanel.getWidth() * 1.5), m_ResultMatrixPanel .getHeight())); // final layout pack(); } /** * initializes the GUI components with the data. */ private void setData() { m_IgnoreChanges = true; // Precision m_MeanPrecSpinner.setValue(m_ResultMatrix.getMeanPrec()); m_StdDevPrecSpinner.setValue(m_ResultMatrix.getStdDevPrec()); // format for (int i = 0; i < m_OutputFormatClasses.size(); i++) { if (m_OutputFormatClasses.get(i).equals(m_ResultMatrix.getClass())) { m_OutputFormatComboBox.setSelectedItem(m_OutputFormatNames.get(i)); break; } } // average m_ShowAverageCheckBox.setSelected(m_ResultMatrix.getShowAverage()); // filter names m_RemoveFilterNameCheckBox .setSelected(m_ResultMatrix.getRemoveFilterName()); // GOE m_ResultMatrixEditor.setValue(m_ResultMatrix); m_IgnoreChanges = false; } /** * gets the data from GUI components. */ private void getData() { if (m_IgnoreChanges) { return; } // format try { if (!m_ResultMatrix.getClass().equals( m_OutputFormatClasses.get(m_OutputFormatComboBox.getSelectedIndex()))) { if (m_OutputFormatClasses .get(m_OutputFormatComboBox.getSelectedIndex()).equals( ExperimenterDefaults.getOutputFormat().getClass())) { m_ResultMatrix = ExperimenterDefaults.getOutputFormat(); } else { m_ResultMatrix = (ResultMatrix) m_OutputFormatClasses.get( m_OutputFormatComboBox.getSelectedIndex()).newInstance(); } } } catch (Exception e) { e.printStackTrace(); m_ResultMatrix = new ResultMatrixPlainText(); } // Precision m_ResultMatrix.setMeanPrec(Integer.parseInt(m_MeanPrecSpinner.getValue() .toString())); m_ResultMatrix.setStdDevPrec(Integer.parseInt(m_StdDevPrecSpinner .getValue().toString())); // average m_ResultMatrix.setShowAverage(m_ShowAverageCheckBox.isSelected()); // filter names m_ResultMatrix.setRemoveFilterName(m_RemoveFilterNameCheckBox.isSelected()); // update GOE m_ResultMatrixEditor.setValue(m_ResultMatrix); } /** * Sets the matrix to use as initial selected output format. * * @param matrix the matrix to use as initial selected output format */ public void setResultMatrix(ResultMatrix matrix) { m_ResultMatrix = matrix; setData(); } /** * Gets the currently selected output format result matrix. * * @return the currently selected matrix to use as output */ public ResultMatrix getResultMatrix() { return m_ResultMatrix; } /** * sets the class of the chosen result matrix. */ protected void setFormat() { for (int i = 0; i < m_OutputFormatClasses.size(); i++) { if (m_OutputFormatNames.get(i).equals( m_OutputFormatComboBox.getItemAt(i).toString())) { m_OutputFormatComboBox.setSelectedIndex(i); break; } } } /** * the result from the last display of the dialog, the same is returned from * <code>showDialog</code>. * * @return the result from the last display of the dialog; either * APPROVE_OPTION, or CANCEL_OPTION * @see #showDialog() */ public int getResult() { return m_Result; } /** * Pops up the modal dialog and waits for cancel or a selection. * * @return either APPROVE_OPTION, or CANCEL_OPTION */ public int showDialog() { m_Result = CANCEL_OPTION; setData(); setVisible(true); return m_Result; } /** * for testing only. * * @param args ignored */ public static void main(String[] args) { OutputFormatDialog dialog; dialog = new OutputFormatDialog(null); if (dialog.showDialog() == APPROVE_OPTION) { System.out.println("Accepted"); } else { System.out.println("Aborted"); } } }
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/experiment/ResultsPanel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ResultsPanel.java * Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.experiment; import weka.core.*; import weka.core.converters.CSVLoader; import weka.experiment.CSVResultListener; import weka.experiment.DatabaseResultListener; import weka.experiment.Experiment; import weka.experiment.InstanceQuery; import weka.experiment.PairedCorrectedTTester; import weka.experiment.ResultMatrix; import weka.experiment.ResultMatrixPlainText; import weka.experiment.Tester; import weka.gui.DatabaseConnectionDialog; import weka.gui.ExtensionFileFilter; import weka.gui.ListSelectorDialog; import weka.gui.Perspective; import weka.gui.PropertyDialog; import weka.gui.ResultHistoryPanel; import weka.gui.SaveBuffer; import weka.gui.explorer.Explorer; import javax.swing.BorderFactory; import javax.swing.DefaultComboBoxModel; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.ListSelectionModel; import javax.swing.SwingConstants; import javax.swing.SwingUtilities; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.Reader; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.StringTokenizer; import java.util.Vector; /** * This panel controls simple analysis of experimental results. * * @author Len Trigg (trigg@cs.waikato.ac.nz) * @version $Revision$ */ public class ResultsPanel extends JPanel { /** for serialization. */ private static final long serialVersionUID = -4913007978534178569L; /** Message shown when no experimental results have been loaded. */ protected static final String NO_SOURCE = "No source"; /** Click to load results from a file. */ protected JButton m_FromFileBut = new JButton("File..."); /** Click to load results from a database. */ protected JButton m_FromDBaseBut = new JButton("Database..."); /** Click to get results from the destination given in the experiment. */ protected JButton m_FromExpBut = new JButton("Experiment"); /** Displays a message about the current result set. */ protected JLabel m_FromLab = new JLabel(NO_SOURCE); /** * This is needed to get around a bug in Swing <= 1.1 -- Once everyone is * using Swing 1.1.1 or higher just remove this variable and use the no-arg * constructor to DefaultComboBoxModel. */ private static String[] FOR_JFC_1_1_DCBM_BUG = { "" }; /** The model embedded in m_DatasetCombo. */ protected DefaultComboBoxModel m_DatasetModel = new DefaultComboBoxModel( FOR_JFC_1_1_DCBM_BUG); /** The model embedded in m_CompareCombo. */ protected DefaultComboBoxModel m_CompareModel = new DefaultComboBoxModel( FOR_JFC_1_1_DCBM_BUG); /** The model embedded in m_SortCombo. */ protected DefaultComboBoxModel m_SortModel = new DefaultComboBoxModel( FOR_JFC_1_1_DCBM_BUG); /** The model embedded in m_TestsList. */ protected DefaultListModel m_TestsModel = new DefaultListModel(); /** The model embedded in m_DisplayedList. */ protected DefaultListModel m_DisplayedModel = new DefaultListModel(); /** Displays the currently selected Tester-Class. */ protected JLabel m_TesterClassesLabel = new JLabel("Testing with", SwingConstants.RIGHT); /** * If running in the Workbench (or other {@code GUIApplication}) this will * hold a reference to the main perspective. Otherwise it will be null */ protected Perspective m_mainPerspective; /** * Contains all the available classes implementing the Tester-Interface (the * display names). * * @see Tester */ protected DefaultComboBoxModel m_TesterClassesModel = new DefaultComboBoxModel(FOR_JFC_1_1_DCBM_BUG); /** * Contains all the available classes implementing the Tester-Interface (the * actual Classes). * * @see Tester */ protected static Vector<Class<?>> m_Testers = null; /** * Lists all the available classes implementing the Tester-Interface. * * @see Tester */ protected JComboBox m_TesterClasses; /** Label for the dataset and result key buttons. */ protected JLabel m_DatasetAndResultKeysLabel = new JLabel( "Select rows and cols", SwingConstants.RIGHT); /** the panel encapsulating the Rows/Columns/Swap buttons. */ protected JPanel m_PanelDatasetResultKeys = new JPanel(new GridLayout(1, 3)); /** Click to edit the columns used to determine the scheme. */ protected JButton m_DatasetKeyBut = new JButton("Rows"); /** Stores the list of attributes for selecting the scheme columns. */ protected DefaultListModel m_DatasetKeyModel = new DefaultListModel(); /** Displays the list of selected columns determining the scheme. */ protected JList m_DatasetKeyList = new JList(m_DatasetKeyModel); /** Click to edit the columns used to determine the scheme. */ protected JButton m_ResultKeyBut = new JButton("Cols"); /** For swapping rows and columns. */ protected JButton m_SwapDatasetKeyAndResultKeyBut = new JButton("Swap"); /** Stores the list of attributes for selecting the scheme columns. */ protected DefaultListModel m_ResultKeyModel = new DefaultListModel(); /** Displays the list of selected columns determining the scheme. */ protected JList m_ResultKeyList = new JList(m_ResultKeyModel); /** Lets the user select which scheme to base comparisons against. */ protected JButton m_TestsButton = new JButton("Select"); /** Lets the user select which schemes are compared to base. */ protected JButton m_DisplayedButton = new JButton("Select"); /** Holds the list of schemes to base the test against. */ protected JList m_TestsList = new JList(m_TestsModel); /** Holds the list of schemes to display. */ protected JList m_DisplayedList = new JList(m_DisplayedModel); /** Lets the user select which performance measure to analyze. */ protected JComboBox m_CompareCombo = new JComboBox(m_CompareModel); /** Lets the user select which column to use for sorting. */ protected JComboBox m_SortCombo = new JComboBox(m_SortModel); /** Lets the user edit the test significance. */ protected JTextField m_SigTex = new JTextField("" + ExperimenterDefaults.getSignificance()); /** * Lets the user select whether standard deviations are to be output or not. */ protected JCheckBox m_ShowStdDevs = new JCheckBox(""); /** lets the user choose the format for the output. */ protected JButton m_OutputFormatButton = new JButton("Select"); /** Click to load the results instances into the Explorer */ protected JButton m_Explorer = new JButton("Open Explorer..."); /** Click to start the test. */ protected JButton m_PerformBut = new JButton("Perform test"); /** Click to save test output to a file. */ protected JButton m_SaveOutBut = new JButton("Save output"); /** The buffer saving object for saving output. */ SaveBuffer m_SaveOut = new SaveBuffer(null, this); /** Displays the output of tests. */ protected JTextArea m_OutText = new JTextArea(); /** A panel controlling results viewing. */ protected ResultHistoryPanel m_History = new ResultHistoryPanel(m_OutText); /** The file chooser for selecting result files. */ protected JFileChooser m_FileChooser = new JFileChooser(new File( System.getProperty("user.dir"))); // File filters for various file types. /** CSV file filter. */ protected ExtensionFileFilter m_csvFileFilter = new ExtensionFileFilter( CSVLoader.FILE_EXTENSION, "CSV data files"); /** ARFF file filter. */ protected ExtensionFileFilter m_arffFileFilter = new ExtensionFileFilter( Instances.FILE_EXTENSION, "Arff data files"); /** The PairedTTester object. */ protected Tester m_TTester = new PairedCorrectedTTester(); /** The instances we're extracting results from. */ protected Instances m_Instances; /** Does any database querying for us. */ protected InstanceQuery m_InstanceQuery; /** A thread to load results instances from a file or database. */ protected Thread m_LoadThread; /** An experiment (used for identifying a result source) -- optional. */ protected Experiment m_Exp; /** the size for a combobox. */ private final Dimension COMBO_SIZE = new Dimension(210, m_ResultKeyBut.getPreferredSize().height); /** the initial result matrix. */ protected ResultMatrix m_ResultMatrix = new ResultMatrixPlainText(); /** * Creates the results panel with no initial experiment. */ public ResultsPanel() { List<String> classes = PluginManager.getPluginNamesOfTypeList(Tester.class.getName()); // set names and classes m_Testers = new Vector<Class<?>>(); m_TesterClassesModel = new DefaultComboBoxModel(); for (int i = 0; i < classes.size(); i++) { try { Class<?> cls = Class.forName(classes.get(i).toString()); Tester tester = (Tester) cls.newInstance(); m_Testers.add(cls); m_TesterClassesModel.addElement(tester.getDisplayName()); } catch (Exception e) { e.printStackTrace(); } } m_TesterClasses = new JComboBox(m_TesterClassesModel); // defaults m_TTester.setSignificanceLevel(ExperimenterDefaults.getSignificance()); m_TTester.setShowStdDevs(ExperimenterDefaults.getShowStdDevs()); m_ResultMatrix = ExperimenterDefaults.getOutputFormat(); m_ResultMatrix.setShowStdDev(ExperimenterDefaults.getShowStdDevs()); m_ResultMatrix.setMeanPrec(ExperimenterDefaults.getMeanPrecision()); m_ResultMatrix.setStdDevPrec(ExperimenterDefaults.getStdDevPrecision()); m_ResultMatrix.setRemoveFilterName(ExperimenterDefaults .getRemoveFilterClassnames()); m_ResultMatrix.setShowAverage(ExperimenterDefaults.getShowAverage()); // Create/Configure/Connect components m_FileChooser.addChoosableFileFilter(m_csvFileFilter); m_FileChooser.addChoosableFileFilter(m_arffFileFilter); m_FileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); m_FromExpBut.setEnabled(false); m_FromExpBut.setMnemonic('E'); m_FromExpBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (m_LoadThread == null) { m_LoadThread = new Thread() { @Override public void run() { setInstancesFromExp(m_Exp); m_LoadThread = null; } }; m_LoadThread.start(); } } }); m_FromDBaseBut.setMnemonic('D'); m_FromDBaseBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (m_LoadThread == null) { m_LoadThread = new Thread() { @Override public void run() { setInstancesFromDBaseQuery(); m_LoadThread = null; } }; m_LoadThread.start(); } } }); m_FromFileBut.setMnemonic('F'); m_FromFileBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int returnVal = m_FileChooser.showOpenDialog(ResultsPanel.this); if (returnVal == JFileChooser.APPROVE_OPTION) { final File selected = m_FileChooser.getSelectedFile(); if (m_LoadThread == null) { m_LoadThread = new Thread() { @Override public void run() { setInstancesFromFile(selected); m_LoadThread = null; } }; m_LoadThread.start(); } } } }); setComboSizes(); m_TesterClasses.setEnabled(false); m_DatasetKeyBut.setEnabled(false); m_DatasetKeyBut .setToolTipText("For selecting the keys that are shown as rows."); m_DatasetKeyBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { setDatasetKeyFromDialog(); } }); m_DatasetKeyList .setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); m_ResultKeyBut.setEnabled(false); m_ResultKeyBut .setToolTipText("For selecting the keys that are shown as columns."); m_ResultKeyBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { setResultKeyFromDialog(); } }); m_ResultKeyList .setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); m_SwapDatasetKeyAndResultKeyBut.setEnabled(false); m_SwapDatasetKeyAndResultKeyBut .setToolTipText("Swaps the keys for selecting rows and columns."); m_SwapDatasetKeyAndResultKeyBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { swapDatasetKeyAndResultKey(); } }); m_CompareCombo.setEnabled(false); m_SortCombo.setEnabled(false); m_SigTex.setEnabled(false); m_TestsButton.setEnabled(false); m_TestsButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { setTestBaseFromDialog(); } }); m_DisplayedButton.setEnabled(false); m_DisplayedButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { setDisplayedFromDialog(); } }); m_ShowStdDevs.setEnabled(false); m_ShowStdDevs.setSelected(ExperimenterDefaults.getShowStdDevs()); m_OutputFormatButton.setEnabled(false); m_OutputFormatButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { setOutputFormatFromDialog(); } }); m_Explorer.setEnabled(false); m_Explorer.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { openExplorer(); } }); m_PerformBut.setEnabled(false); m_PerformBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { performTest(); m_SaveOutBut.setEnabled(true); } }); m_PerformBut.setToolTipText(m_TTester.getToolTipText()); m_SaveOutBut.setEnabled(false); m_SaveOutBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { saveBuffer(); } }); m_OutText.setFont(new Font("Monospaced", Font.PLAIN, 12)); m_OutText.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); m_OutText.setEditable(false); m_History.setBorder(BorderFactory.createTitledBorder("Result list")); // Set up the GUI layout JPanel sourceAndButsHolder = new JPanel(); sourceAndButsHolder.setLayout(new BorderLayout()); JPanel p1 = new JPanel(); p1.setBorder(BorderFactory.createTitledBorder("Source")); sourceAndButsHolder.add(p1, BorderLayout.NORTH); JPanel p2 = new JPanel(); GridBagLayout gb = new GridBagLayout(); GridBagConstraints constraints = new GridBagConstraints(); p2.setBorder(BorderFactory.createEmptyBorder(5, 5, 10, 5)); // p2.setLayout(new GridLayout(1, 3)); p2.setLayout(gb); constraints.gridx = 0; constraints.gridy = 0; constraints.weightx = 5; constraints.fill = GridBagConstraints.HORIZONTAL; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.insets = new Insets(0, 2, 0, 2); p2.add(m_FromFileBut, constraints); constraints.gridx = 1; constraints.gridy = 0; constraints.weightx = 5; constraints.gridwidth = 1; constraints.gridheight = 1; p2.add(m_FromDBaseBut, constraints); constraints.gridx = 2; constraints.gridy = 0; constraints.weightx = 5; constraints.gridwidth = 1; constraints.gridheight = 1; p2.add(m_FromExpBut, constraints); p1.setLayout(new BorderLayout()); p1.add(m_FromLab, BorderLayout.CENTER); p1.add(p2, BorderLayout.EAST); JPanel newButHolder = new JPanel(); newButHolder.setLayout(new BorderLayout()); newButHolder.setBorder(BorderFactory.createTitledBorder("Actions")); sourceAndButsHolder.add(newButHolder, BorderLayout.SOUTH); JPanel p3 = new JPanel(); p3.setBorder(BorderFactory.createTitledBorder("Configure test")); GridBagLayout gbL = new GridBagLayout(); p3.setLayout(gbL); int y = 0; GridBagConstraints gbC = new GridBagConstraints(); gbC.anchor = GridBagConstraints.EAST; gbC.gridy = y; gbC.gridx = 0; gbC.insets = new Insets(2, 10, 2, 10); gbL.setConstraints(m_TesterClassesLabel, gbC); m_TesterClassesLabel.setDisplayedMnemonic('w'); m_TesterClassesLabel.setLabelFor(m_TesterClasses); p3.add(m_TesterClassesLabel); gbC = new GridBagConstraints(); gbC.gridy = y; gbC.gridx = 1; gbC.weightx = 100; gbC.insets = new Insets(5, 0, 5, 0); gbC.fill = GridBagConstraints.HORIZONTAL; gbL.setConstraints(m_TesterClasses, gbC); p3.add(m_TesterClasses); m_TesterClasses.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { setTester(); } }); setSelectedItem(m_TesterClasses, ExperimenterDefaults.getTester()); y++; gbC = new GridBagConstraints(); gbC.anchor = GridBagConstraints.EAST; gbC.gridy = y; gbC.gridx = 0; gbC.insets = new Insets(2, 10, 2, 10); gbL.setConstraints(m_DatasetAndResultKeysLabel, gbC); m_DatasetAndResultKeysLabel.setDisplayedMnemonic('R'); m_DatasetAndResultKeysLabel.setLabelFor(m_DatasetKeyBut); p3.add(m_DatasetAndResultKeysLabel); m_PanelDatasetResultKeys.add(m_DatasetKeyBut); m_PanelDatasetResultKeys.add(m_ResultKeyBut); m_PanelDatasetResultKeys.add(m_SwapDatasetKeyAndResultKeyBut); gbC = new GridBagConstraints(); gbC.fill = GridBagConstraints.HORIZONTAL; gbC.gridy = y; gbC.gridx = 1; gbC.weightx = 100; gbC.insets = new Insets(5, 0, 5, 0); gbL.setConstraints(m_PanelDatasetResultKeys, gbC); p3.add(m_PanelDatasetResultKeys); y++; JLabel lab = new JLabel("Comparison field", SwingConstants.RIGHT); lab.setDisplayedMnemonic('m'); lab.setLabelFor(m_CompareCombo); gbC = new GridBagConstraints(); gbC.anchor = GridBagConstraints.EAST; gbC.gridy = y; gbC.gridx = 0; gbC.insets = new Insets(2, 10, 2, 10); gbL.setConstraints(lab, gbC); p3.add(lab); gbC = new GridBagConstraints(); gbC.gridy = y; gbC.gridx = 1; gbC.weightx = 100; gbC.insets = new Insets(5, 0, 5, 0); gbC.fill = GridBagConstraints.HORIZONTAL; gbL.setConstraints(m_CompareCombo, gbC); p3.add(m_CompareCombo); y++; lab = new JLabel("Significance", SwingConstants.RIGHT); lab.setDisplayedMnemonic('g'); lab.setLabelFor(m_SigTex); gbC = new GridBagConstraints(); gbC.anchor = GridBagConstraints.EAST; gbC.gridy = y; gbC.gridx = 0; gbC.insets = new Insets(2, 10, 2, 10); gbL.setConstraints(lab, gbC); p3.add(lab); gbC = new GridBagConstraints(); gbC.fill = GridBagConstraints.HORIZONTAL; gbC.gridy = y; gbC.gridx = 1; gbC.weightx = 100; gbL.setConstraints(m_SigTex, gbC); p3.add(m_SigTex); y++; lab = new JLabel("Sorting (asc.) by", SwingConstants.RIGHT); lab.setDisplayedMnemonic('S'); lab.setLabelFor(m_SortCombo); gbC = new GridBagConstraints(); gbC.anchor = GridBagConstraints.EAST; gbC.gridy = y; gbC.gridx = 0; gbC.insets = new Insets(2, 10, 2, 10); gbL.setConstraints(lab, gbC); p3.add(lab); gbC = new GridBagConstraints(); gbC.anchor = GridBagConstraints.WEST; gbC.fill = GridBagConstraints.HORIZONTAL; gbC.gridy = y; gbC.gridx = 1; gbC.weightx = 100; gbC.insets = new Insets(5, 0, 5, 0); gbL.setConstraints(m_SortCombo, gbC); p3.add(m_SortCombo); y++; lab = new JLabel("Test base", SwingConstants.RIGHT); lab.setDisplayedMnemonic('b'); lab.setLabelFor(m_TestsButton); gbC = new GridBagConstraints(); gbC.anchor = GridBagConstraints.EAST; gbC.gridy = y; gbC.gridx = 0; gbC.insets = new Insets(2, 10, 2, 10); gbL.setConstraints(lab, gbC); p3.add(lab); gbC = new GridBagConstraints(); gbC.fill = GridBagConstraints.HORIZONTAL; gbC.gridy = y; gbC.gridx = 1; gbC.weightx = 100; gbC.insets = new Insets(5, 0, 5, 0); gbL.setConstraints(m_TestsButton, gbC); p3.add(m_TestsButton); y++; lab = new JLabel("Displayed Columns", SwingConstants.RIGHT); lab.setDisplayedMnemonic('i'); lab.setLabelFor(m_DisplayedButton); gbC = new GridBagConstraints(); gbC.anchor = GridBagConstraints.EAST; gbC.gridy = y; gbC.gridx = 0; gbC.insets = new Insets(2, 10, 2, 10); gbL.setConstraints(lab, gbC); p3.add(lab); gbC = new GridBagConstraints(); gbC.fill = GridBagConstraints.HORIZONTAL; gbC.gridy = y; gbC.gridx = 1; gbC.weightx = 100; gbC.insets = new Insets(5, 0, 5, 0); gbL.setConstraints(m_DisplayedButton, gbC); p3.add(m_DisplayedButton); y++; lab = new JLabel("Show std. deviations", SwingConstants.RIGHT); lab.setDisplayedMnemonic('a'); lab.setLabelFor(m_ShowStdDevs); gbC = new GridBagConstraints(); gbC.anchor = GridBagConstraints.EAST; gbC.gridy = y; gbC.gridx = 0; gbC.insets = new Insets(2, 10, 2, 10); gbL.setConstraints(lab, gbC); p3.add(lab); gbC = new GridBagConstraints(); gbC.anchor = GridBagConstraints.WEST; gbC.gridy = y; gbC.gridx = 1; gbC.weightx = 100; gbC.insets = new Insets(5, 0, 5, 0); gbL.setConstraints(m_ShowStdDevs, gbC); p3.add(m_ShowStdDevs); y++; lab = new JLabel("Output Format", SwingConstants.RIGHT); lab.setDisplayedMnemonic('O'); lab.setLabelFor(m_OutputFormatButton); gbC = new GridBagConstraints(); gbC.anchor = GridBagConstraints.EAST; gbC.gridy = y; gbC.gridx = 0; gbC.insets = new Insets(2, 10, 2, 10); gbL.setConstraints(lab, gbC); p3.add(lab); gbC = new GridBagConstraints(); gbC.anchor = GridBagConstraints.WEST; gbC.fill = GridBagConstraints.HORIZONTAL; gbC.gridy = y; gbC.gridx = 1; gbC.weightx = 100; gbC.insets = new Insets(5, 0, 5, 0); gbL.setConstraints(m_OutputFormatButton, gbC); p3.add(m_OutputFormatButton); JPanel output = new JPanel(); output.setLayout(new BorderLayout()); output.setBorder(BorderFactory.createTitledBorder("Test output")); output.add(new JScrollPane(m_OutText), BorderLayout.CENTER); JPanel mondo = new JPanel(); gbL = new GridBagLayout(); mondo.setLayout(gbL); gbC = new GridBagConstraints(); // gbC.anchor = GridBagConstraints.WEST; // gbC.fill = GridBagConstraints.HORIZONTAL; gbC.gridy = 0; gbC.gridx = 0; gbL.setConstraints(p3, gbC); mondo.add(p3); JPanel bts = new JPanel(); m_PerformBut.setMnemonic('t'); m_SaveOutBut.setMnemonic('S'); bts.setLayout(new GridLayout(1, 3, 5, 5)); bts.add(m_PerformBut); bts.add(m_SaveOutBut); bts.add(m_Explorer); newButHolder.add(bts, BorderLayout.WEST); /* * gbC = new GridBagConstraints(); gbC.anchor = GridBagConstraints.NORTH; * gbC.fill = GridBagConstraints.HORIZONTAL; gbC.gridy = 1; gbC.gridx = 0; * gbC.insets = new Insets(5, 5, 5, 5); gbL.setConstraints(bts, gbC); * mondo.add(bts); */ gbC = new GridBagConstraints(); // gbC.anchor = GridBagConstraints.NORTH; gbC.fill = GridBagConstraints.BOTH; gbC.gridy = 2; gbC.gridx = 0; gbC.weightx = 0; gbC.weighty = 100; gbL.setConstraints(m_History, gbC); mondo.add(m_History); /* * gbC = new GridBagConstraints(); gbC.fill = GridBagConstraints.BOTH; * gbC.gridy = 0; gbC.gridx = 1; gbC.gridheight = 3; gbC.weightx = 100; * gbC.weighty = 100; gbL.setConstraints(output, gbC); */ // mondo.add(output); JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, mondo, output); splitPane.setOneTouchExpandable(true); // splitPane.setDividerLocation(100); setLayout(new BorderLayout()); add(sourceAndButsHolder, BorderLayout.NORTH); // add(mondo , BorderLayout.CENTER); add(splitPane, BorderLayout.CENTER); } /** * Set the main perspective (if running in a {@code GUIApplication}). * * @param mainPerspective the main perspective of the application */ protected void setMainPerspective(Perspective mainPerspective) { m_mainPerspective = mainPerspective; if (m_mainPerspective.acceptsInstances()) { m_Explorer.setText("Send to " + mainPerspective.getPerspectiveTitle()); } } /** * Sets the combo-boxes to a fixed size so they don't take up too much room * that would be better devoted to the test output box. */ protected void setComboSizes() { m_TesterClasses.setPreferredSize(COMBO_SIZE); m_PanelDatasetResultKeys.setPreferredSize(COMBO_SIZE); m_CompareCombo.setPreferredSize(COMBO_SIZE); m_SigTex.setPreferredSize(COMBO_SIZE); m_SortCombo.setPreferredSize(COMBO_SIZE); m_TesterClasses.setMaximumSize(COMBO_SIZE); m_PanelDatasetResultKeys.setMaximumSize(COMBO_SIZE); m_CompareCombo.setMaximumSize(COMBO_SIZE); m_SigTex.setMaximumSize(COMBO_SIZE); m_SortCombo.setMaximumSize(COMBO_SIZE); m_TesterClasses.setMinimumSize(COMBO_SIZE); m_PanelDatasetResultKeys.setMinimumSize(COMBO_SIZE); m_CompareCombo.setMinimumSize(COMBO_SIZE); m_SigTex.setMinimumSize(COMBO_SIZE); m_SortCombo.setMinimumSize(COMBO_SIZE); } /** * Tells the panel to use a new experiment. * * @param exp a value of type 'Experiment' */ public void setExperiment(Experiment exp) { m_Exp = exp; m_FromExpBut.setEnabled(exp != null); } /** * Queries the user enough to make a database query to retrieve experiment * results. */ protected void setInstancesFromDBaseQuery() { try { if (m_InstanceQuery == null) { m_InstanceQuery = new InstanceQuery(); } String dbaseURL = m_InstanceQuery.getDatabaseURL(); String username = m_InstanceQuery.getUsername(); String passwd = m_InstanceQuery.getPassword(); /* * dbaseURL = (String) JOptionPane.showInputDialog(this, * "Enter the database URL", "Query Database", JOptionPane.PLAIN_MESSAGE, * null, null, dbaseURL); */ DatabaseConnectionDialog dbd = new DatabaseConnectionDialog((Frame)SwingUtilities.getWindowAncestor(ResultsPanel.this), dbaseURL, username); dbd.setLocationRelativeTo(SwingUtilities.getWindowAncestor(ResultsPanel.this)); dbd.setVisible(true); // if (dbaseURL == null) { if (dbd.getReturnValue() == JOptionPane.CLOSED_OPTION) { m_FromLab.setText("Cancelled"); return; } dbaseURL = dbd.getURL(); username = dbd.getUsername(); passwd = dbd.getPassword(); m_InstanceQuery.setDatabaseURL(dbaseURL); m_InstanceQuery.setUsername(username); m_InstanceQuery.setPassword(passwd); m_InstanceQuery.setDebug(dbd.getDebug()); m_InstanceQuery.connectToDatabase(); if (!m_InstanceQuery.experimentIndexExists()) { System.err.println("not found"); m_FromLab.setText("No experiment index"); m_InstanceQuery.disconnectFromDatabase(); return; } System.err.println("found"); m_FromLab.setText("Getting experiment index"); Instances index = m_InstanceQuery.retrieveInstances("SELECT * FROM " + InstanceQuery.EXP_INDEX_TABLE); if (index.numInstances() == 0) { m_FromLab.setText("No experiments available"); m_InstanceQuery.disconnectFromDatabase(); return; } m_FromLab.setText("Got experiment index"); DefaultListModel lm = new DefaultListModel(); for (int i = 0; i < index.numInstances(); i++) { lm.addElement(index.instance(i).toString()); } JList jl = new JList(lm); jl.setSelectedIndex(0); int result; // display dialog only if there's not just one result! if (jl.getModel().getSize() != 1) { ListSelectorDialog jd = new ListSelectorDialog(SwingUtilities.getWindowAncestor(this), jl); result = jd.showDialog(); } else { result = ListSelectorDialog.APPROVE_OPTION; } if (result != ListSelectorDialog.APPROVE_OPTION) { m_FromLab.setText("Cancelled"); m_InstanceQuery.disconnectFromDatabase(); return; } Instance selInst = index.instance(jl.getSelectedIndex()); Attribute tableAttr = index.attribute(InstanceQuery.EXP_RESULT_COL); String table = InstanceQuery.EXP_RESULT_PREFIX + selInst.toString(tableAttr); setInstancesFromDatabaseTable(table); } catch (Exception ex) { // 1. print complete stacktrace ex.printStackTrace(); // 2. print message in panel m_FromLab.setText("Problem reading database: '" + ex.getMessage() + "'"); } } /** * Examines the supplied experiment to determine the results destination and * attempts to load the results. * * @param exp a value of type 'Experiment' */ protected void setInstancesFromExp(Experiment exp) { if ((exp.getResultListener() instanceof CSVResultListener)) { File resultFile = ((CSVResultListener) exp.getResultListener()).getOutputFile(); if ((resultFile == null)) { m_FromLab.setText("No result file"); } else { setInstancesFromFile(resultFile); } } else if (exp.getResultListener() instanceof DatabaseResultListener) { String dbaseURL = ((DatabaseResultListener) exp.getResultListener()).getDatabaseURL(); try { if (m_InstanceQuery == null) { m_InstanceQuery = new InstanceQuery(); } m_InstanceQuery.setDatabaseURL(dbaseURL); m_InstanceQuery.connectToDatabase(); String tableName = m_InstanceQuery.getResultsTableName(exp.getResultProducer()); setInstancesFromDatabaseTable(tableName); } catch (Exception ex) { m_FromLab.setText("Problem reading database"); } } else { m_FromLab.setText("Can't get results from experiment"); } } /** * Queries a database to load results from the specified table name. The * database connection must have already made by m_InstanceQuery. * * @param tableName the name of the table containing results to retrieve. */ protected void setInstancesFromDatabaseTable(String tableName) { try { m_FromLab.setText("Reading from database, please wait..."); final Instances i = m_InstanceQuery.retrieveInstances("SELECT * FROM " + tableName); SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { setInstances(i); } }); m_InstanceQuery.disconnectFromDatabase(); } catch (Exception ex) { m_FromLab.setText(ex.getMessage()); } } /** * Loads results from a set of instances contained in the supplied file. * * @param f a value of type 'File' */ protected void setInstancesFromFile(File f) { String fileType = f.getName(); try { m_FromLab.setText("Reading from file..."); if (f.getName().toLowerCase().endsWith(Instances.FILE_EXTENSION)) { fileType = "arff"; Reader r = new BufferedReader(new FileReader(f)); setInstances(new Instances(r)); r.close(); } else if (f.getName().toLowerCase().endsWith(CSVLoader.FILE_EXTENSION)) { fileType = "csv"; CSVLoader cnv = new CSVLoader(); cnv.setSource(f); Instances inst = cnv.getDataSet(); setInstances(inst); } else { throw new Exception("Unrecognized file type"); } } catch (Exception ex) { m_FromLab.setText("File '" + f.getName() + "' not recognised as an " + fileType + " file."); if (JOptionPane.showOptionDialog(ResultsPanel.this, "File '" + f.getName() + "' not recognised as an " + fileType + " file.\n" + "Reason:\n" + ex.getMessage(), "Load Instances", 0, JOptionPane.ERROR_MESSAGE, null, new String[] { "OK" }, null) == 1) { } } } /** * Returns a vector with column names of the dataset, listed in "list". If a * column cannot be found or the list is empty the ones from the default list * are returned. * * @param list comma-separated list of attribute names * @param defaultList the default list of attribute names * @param inst the instances to get the attribute names from * @return a vector containing attribute names */ protected Vector<String> determineColumnNames(String list, String defaultList, Instances inst) { Vector<String> result; Vector<String> atts; StringTokenizer tok; int i; String item; // get attribute names atts = new Vector<String>(); for (i = 0; i < inst.numAttributes(); i++) { atts.add(inst.attribute(i).name().toLowerCase()); } // process list result = new Vector<String>(); tok = new StringTokenizer(list, ","); while (tok.hasMoreTokens()) { item = tok.nextToken().toLowerCase(); if (atts.contains(item)) { result.add(item); } else { result.clear(); break; } } // do we have to return defaults? if (result.size() == 0) { tok = new StringTokenizer(defaultList, ","); while (tok.hasMoreTokens()) { result.add(tok.nextToken().toLowerCase()); } } return result; } /** * Sets up the panel with a new set of instances, attempting to guess the * correct settings for various columns. * * @param newInstances the new set of results. */ public void setInstances(Instances newInstances) { m_Instances = newInstances; m_TTester.setInstances(m_Instances); m_FromLab.setText("Got " + m_Instances.numInstances() + " results"); // setup row and column names Vector<String> rows = determineColumnNames(ExperimenterDefaults.getRow(), "Key_Dataset", m_Instances); Vector<String> cols = determineColumnNames(ExperimenterDefaults.getColumn(), "Key_Scheme,Key_Scheme_options,Key_Scheme_version_ID", m_Instances); // Do other stuff m_DatasetKeyModel.removeAllElements(); m_ResultKeyModel.removeAllElements(); m_CompareModel.removeAllElements(); m_SortModel.removeAllElements(); m_SortModel.addElement("<default>"); m_TTester.setSortColumn(-1); String selectedList = ""; String selectedListDataset = ""; boolean comparisonFieldSet = false; for (int i = 0; i < m_Instances.numAttributes(); i++) { String name = m_Instances.attribute(i).name(); if (name.toLowerCase().startsWith("key_", 0)) { m_DatasetKeyModel.addElement(name.substring(4)); m_ResultKeyModel.addElement(name.substring(4)); m_CompareModel.addElement(name.substring(4)); } else { m_DatasetKeyModel.addElement(name); m_ResultKeyModel.addElement(name); m_CompareModel.addElement(name); if (m_Instances.attribute(i).isNumeric()) { m_SortModel.addElement(name); } } if (rows.contains(name.toLowerCase())) { m_DatasetKeyList.addSelectionInterval(i, i); selectedListDataset += "," + (i + 1); } else if (name.toLowerCase().equals("key_run")) { m_TTester.setRunColumn(i); } else if (name.toLowerCase().equals("key_fold")) { m_TTester.setFoldColumn(i); } else if (cols.contains(name.toLowerCase())) { m_ResultKeyList.addSelectionInterval(i, i); selectedList += "," + (i + 1); } else if (name.toLowerCase().indexOf( ExperimenterDefaults.getComparisonField()) != -1) { m_CompareCombo.setSelectedIndex(i); comparisonFieldSet = true; // break; } else if ((name.toLowerCase().indexOf("root_relative_squared_error") != -1) && (!comparisonFieldSet)) { m_CompareCombo.setSelectedIndex(i); comparisonFieldSet = true; } } m_TesterClasses.setEnabled(true); m_DatasetKeyBut.setEnabled(true); m_ResultKeyBut.setEnabled(true); m_SwapDatasetKeyAndResultKeyBut.setEnabled(true); m_CompareCombo.setEnabled(true); m_SortCombo.setEnabled(true); if (ExperimenterDefaults.getSorting().length() != 0) { setSelectedItem(m_SortCombo, ExperimenterDefaults.getSorting()); } Range generatorRange = new Range(); if (selectedList.length() != 0) { try { generatorRange.setRanges(selectedList); } catch (Exception ex) { ex.printStackTrace(); System.err.println(ex.getMessage()); } } m_TTester.setResultsetKeyColumns(generatorRange); generatorRange = new Range(); if (selectedListDataset.length() != 0) { try { generatorRange.setRanges(selectedListDataset); } catch (Exception ex) { ex.printStackTrace(); System.err.println(ex.getMessage()); } } m_TTester.setDatasetKeyColumns(generatorRange); m_SigTex.setEnabled(true); setTTester(); } /** * Sets the selected item of an combobox, since using setSelectedItem(...) * doesn't work, if one checks object references! * * @param cb the combobox to set the item for * @param item the item to set active */ protected void setSelectedItem(JComboBox cb, String item) { int i; for (i = 0; i < cb.getItemCount(); i++) { if (cb.getItemAt(i).toString().equals(item)) { cb.setSelectedIndex(i); break; } } } /** * Updates the test chooser with possible tests. */ protected void setTTester() { // default is to display all columns m_TTester.setDisplayedResultsets(null); String name = (new SimpleDateFormat("HH:mm:ss - ")).format(new Date()) + "Available resultsets"; StringBuffer outBuff = new StringBuffer(); outBuff .append("Available resultsets\n" + m_TTester.resultsetKey() + "\n\n"); m_History.addResult(name, outBuff); m_History.setSingle(name); m_TestsModel.removeAllElements(); for (int i = 0; i < m_TTester.getNumResultsets(); i++) { String tname = m_TTester.getResultsetName(i); /* * if (tname.length() > 20) { tname = tname.substring(0, 20); } */ m_TestsModel.addElement(tname); } m_DisplayedModel.removeAllElements(); for (int i = 0; i < m_TestsModel.size(); i++) { m_DisplayedModel.addElement(m_TestsModel.elementAt(i)); } m_TestsModel.addElement("Summary"); m_TestsModel.addElement("Ranking"); m_TestsList.setSelectedIndex(0); m_DisplayedList.setSelectionInterval(0, m_DisplayedModel.size() - 1); m_TestsButton.setEnabled(true); m_DisplayedButton.setEnabled(true); m_ShowStdDevs.setEnabled(true); m_OutputFormatButton.setEnabled(true); m_PerformBut.setEnabled(true); m_Explorer.setEnabled(true); } /** * Carries out a t-test using the current configuration. */ protected void performTest() { String sigStr = m_SigTex.getText(); if (sigStr.length() != 0) { m_TTester.setSignificanceLevel((new Double(sigStr)).doubleValue()); } else { m_TTester.setSignificanceLevel(ExperimenterDefaults.getSignificance()); } // Carry out the test chosen and biff the results to the output area m_TTester.setShowStdDevs(m_ShowStdDevs.isSelected()); if (m_Instances.attribute(m_SortCombo.getSelectedItem().toString()) != null) { m_TTester.setSortColumn(m_Instances.attribute( m_SortCombo.getSelectedItem().toString()).index()); } else { m_TTester.setSortColumn(-1); } int compareCol = m_CompareCombo.getSelectedIndex(); int tType = m_TestsList.getSelectedIndex(); m_TTester.setResultMatrix(m_ResultMatrix); String name = (new SimpleDateFormat("HH:mm:ss - ")).format(new Date()) + (String) m_CompareCombo.getSelectedItem() + " - " + (String) m_TestsList.getSelectedValue(); StringBuffer outBuff = new StringBuffer(); outBuff.append(m_TTester.header(compareCol)); outBuff.append("\n"); m_History.addResult(name, outBuff); m_History.setSingle(name); m_TTester.setDisplayedResultsets(m_DisplayedList.getSelectedIndices()); try { if (tType < m_TTester.getNumResultsets()) { outBuff.append(m_TTester.multiResultsetFull(tType, compareCol)); } else if (tType == m_TTester.getNumResultsets()) { outBuff.append(m_TTester.multiResultsetSummary(compareCol)); } else { outBuff.append(m_TTester.multiResultsetRanking(compareCol)); } outBuff.append("\n"); } catch (Exception ex) { outBuff.append(ex.getMessage() + "\n"); } m_History.updateResult(name); } public void setResultKeyFromDialog() { ListSelectorDialog jd = new ListSelectorDialog(SwingUtilities.getWindowAncestor(this), m_ResultKeyList); // Open the dialog int result = jd.showDialog(); // If accepted, update the ttester if (result == ListSelectorDialog.APPROVE_OPTION) { int[] selected = m_ResultKeyList.getSelectedIndices(); String selectedList = ""; for (int element : selected) { selectedList += "," + (element + 1); } Range generatorRange = new Range(); if (selectedList.length() != 0) { try { generatorRange.setRanges(selectedList); } catch (Exception ex) { ex.printStackTrace(); System.err.println(ex.getMessage()); } } m_TTester.setResultsetKeyColumns(generatorRange); setTTester(); } } public void setDatasetKeyFromDialog() { ListSelectorDialog jd = new ListSelectorDialog(SwingUtilities.getWindowAncestor(this), m_DatasetKeyList); // Open the dialog int result = jd.showDialog(); // If accepted, update the ttester if (result == ListSelectorDialog.APPROVE_OPTION) { int[] selected = m_DatasetKeyList.getSelectedIndices(); String selectedList = ""; for (int element : selected) { selectedList += "," + (element + 1); } Range generatorRange = new Range(); if (selectedList.length() != 0) { try { generatorRange.setRanges(selectedList); } catch (Exception ex) { ex.printStackTrace(); System.err.println(ex.getMessage()); } } m_TTester.setDatasetKeyColumns(generatorRange); setTTester(); } } /** * Swaps the keys for dataset and result. */ protected void swapDatasetKeyAndResultKey() { int[] tmpSelected; Range tmpRange; // lists tmpSelected = m_DatasetKeyList.getSelectedIndices(); m_DatasetKeyList.setSelectedIndices(m_ResultKeyList.getSelectedIndices()); m_ResultKeyList.setSelectedIndices(tmpSelected); // tester tmpRange = m_TTester.getDatasetKeyColumns(); m_TTester.setDatasetKeyColumns(m_TTester.getResultsetKeyColumns()); m_TTester.setResultsetKeyColumns(tmpRange); setTTester(); } public void setTestBaseFromDialog() { ListSelectorDialog jd = new ListSelectorDialog(SwingUtilities.getWindowAncestor(this), m_TestsList); // Open the dialog jd.showDialog(); } public void setDisplayedFromDialog() { ListSelectorDialog jd = new ListSelectorDialog(SwingUtilities.getWindowAncestor(this), m_DisplayedList); // Open the dialog jd.showDialog(); } /** * displays the Dialog for the output format and sets the chosen settings, if * the user approves. */ public void setOutputFormatFromDialog() { OutputFormatDialog dialog = new OutputFormatDialog(PropertyDialog.getParentFrame(this)); m_ResultMatrix.setShowStdDev(m_ShowStdDevs.isSelected()); dialog.setResultMatrix(m_ResultMatrix); dialog.setLocationRelativeTo(this); if (dialog.showDialog() == OutputFormatDialog.APPROVE_OPTION) { m_ResultMatrix = dialog.getResultMatrix(); m_ShowStdDevs.setSelected(m_ResultMatrix.getShowStdDev()); } } /** * Save the currently selected result buffer to a file. */ protected void saveBuffer() { StringBuffer sb = m_History.getSelectedBuffer(); if (sb != null) { if (m_SaveOut.save(sb)) { JOptionPane.showMessageDialog(this, "File saved", "Results", JOptionPane.INFORMATION_MESSAGE); } } else { m_SaveOutBut.setEnabled(false); } } /** * sets the currently selected Tester-Class. */ protected void setTester() { Tester tester; Tester t; int i; if (m_TesterClasses.getSelectedItem() == null) { return; } tester = null; // find display name try { for (i = 0; i < m_Testers.size(); i++) { t = (Tester) ((Class<?>) m_Testers.get(i)).newInstance(); if (t.getDisplayName().equals(m_TesterClasses.getSelectedItem())) { tester = t; break; } } } catch (Exception e) { e.printStackTrace(); } if (tester == null) { tester = new PairedCorrectedTTester(); // default m_TesterClasses.setSelectedItem(tester.getDisplayName()); } tester.assign(m_TTester); m_TTester = tester; m_PerformBut.setToolTipText(m_TTester.getToolTipText()); System.out.println("Tester set to: " + m_TTester.getClass().getName()); } protected synchronized void openExplorer() { if (m_Instances != null) { if (m_mainPerspective == null || !m_mainPerspective.acceptsInstances()) { Explorer exp = new Explorer(); exp.getPreprocessPanel().setInstances(m_Instances); final JFrame jf = Utils.getWekaJFrame("Weka Explorer", this); jf.getContentPane().setLayout(new BorderLayout()); jf.getContentPane().add(exp, BorderLayout.CENTER); jf.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { jf.dispose(); } }); jf.pack(); jf.setSize(1024, 768); jf.setLocationRelativeTo(SwingUtilities.getWindowAncestor(this)); jf.setVisible(true); } else { m_mainPerspective.setInstances(m_Instances); m_mainPerspective.getMainApplication().getPerspectiveManager() .setActivePerspective(m_mainPerspective.getPerspectiveID()); } } } /** * Tests out the results panel from the command line. * * @param args ignored */ public static void main(String[] args) { try { final JFrame jf = new JFrame("Weka Experiment: Results Analysis"); jf.getContentPane().setLayout(new BorderLayout()); final ResultsPanel sp = new ResultsPanel(); // sp.setBorder(BorderFactory.createTitledBorder("Setup")); jf.getContentPane().add(sp, BorderLayout.CENTER); jf.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { jf.dispose(); System.exit(0); } }); jf.pack(); jf.setSize(700, 550); 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/experiment/RunNumberPanel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * RunNumberPanel.java * Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.experiment; import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.SwingConstants; import weka.experiment.Experiment; /** * This panel controls configuration of lower and upper run numbers * in an experiment. * * @author Len Trigg (trigg@cs.waikato.ac.nz) * @version $Revision$ */ public class RunNumberPanel extends JPanel { /** for serialization */ private static final long serialVersionUID = -1644336658426067852L; /** Configures the lower run number */ protected JTextField m_LowerText = new JTextField("1"); /** Configures the upper run number */ protected JTextField m_UpperText = new JTextField("10"); /** The experiment being configured */ protected Experiment m_Exp; /** * Creates the panel with no initial experiment. */ public RunNumberPanel() { // Updates occur to the values in exp whenever enter is pressed // or the component loses focus m_LowerText.addKeyListener(new KeyAdapter() { public void keyReleased(KeyEvent e) { m_Exp.setRunLower(getLower()); } }); m_LowerText.addFocusListener(new FocusAdapter() { public void focusLost(FocusEvent e) { m_Exp.setRunLower(getLower()); } }); m_UpperText.addKeyListener(new KeyAdapter() { public void keyReleased(KeyEvent e) { m_Exp.setRunUpper(getUpper()); } }); m_UpperText.addFocusListener(new FocusAdapter() { public void focusLost(FocusEvent e) { m_Exp.setRunUpper(getUpper()); } }); m_LowerText.setEnabled(false); m_UpperText.setEnabled(false); // Set the GUI layout setLayout(new GridLayout(1,2)); setBorder(BorderFactory.createTitledBorder("Runs")); Box b1 = new Box(BoxLayout.X_AXIS); b1.add(Box.createHorizontalStrut(10)); b1.add(new JLabel("From:", SwingConstants.RIGHT)); b1.add(Box.createHorizontalStrut(5)); b1.add(m_LowerText); add(b1); Box b2 = new Box(BoxLayout.X_AXIS); b2.add(Box.createHorizontalStrut(10)); b2.add(new JLabel("To:", SwingConstants.RIGHT)); b2.add(Box.createHorizontalStrut(5)); b2.add(m_UpperText); add(b2); } /** * Creates the panel with the supplied initial experiment. * * @param exp a value of type 'Experiment' */ public RunNumberPanel(Experiment exp) { this(); setExperiment(exp); } /** * Sets the experiment to be configured. * * @param exp a value of type 'Experiment' */ public void setExperiment(Experiment exp) { m_Exp = exp; m_LowerText.setText("" + m_Exp.getRunLower()); m_UpperText.setText("" + m_Exp.getRunUpper()); m_LowerText.setEnabled(true); m_UpperText.setEnabled(true); } /** * Gets the current lower run number. * * @return the lower run number. */ public int getLower() { int result = 1; try { result = Integer.parseInt(m_LowerText.getText()); } catch (Exception ex) { } return Math.max(1, result); } /** * Gets the current upper run number. * * @return the upper run number. */ public int getUpper() { int result = 1; try { result = Integer.parseInt(m_UpperText.getText()); } catch (Exception ex) { } return Math.max(1, result); } /** * Tests out the panel from the command line. * * @param args ignored. */ public static void main(String [] args) { try { final JFrame jf = new JFrame("Dataset List Editor"); jf.getContentPane().setLayout(new BorderLayout()); jf.getContentPane().add(new RunNumberPanel(new Experiment()), BorderLayout.CENTER); jf.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { jf.dispose(); System.exit(0); } }); jf.pack(); 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/experiment/RunPanel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * RunPanel.java * Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.experiment; import java.awt.BorderLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.ObjectInputStream; import java.io.Serializable; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import weka.core.SerializedObject; import weka.core.Utils; import weka.experiment.Experiment; import weka.experiment.RemoteExperiment; import weka.experiment.RemoteExperimentEvent; import weka.experiment.RemoteExperimentListener; import weka.gui.LogPanel; /** * This panel controls the running of an experiment. * * @author Len Trigg (trigg@cs.waikato.ac.nz) * @version $Revision$ */ public class RunPanel extends JPanel implements ActionListener { /** for serialization */ private static final long serialVersionUID = 1691868018596872051L; /** The message displayed when no experiment is running */ protected static final String NOT_RUNNING = "Not running"; /** Click to start running the experiment */ protected JButton m_StartBut = new JButton("Start"); /** Click to signal the running experiment to halt */ protected JButton m_StopBut = new JButton("Stop"); protected LogPanel m_Log = new LogPanel(); /** The experiment to run */ protected Experiment m_Exp; /** The thread running the experiment */ protected Thread m_RunThread = null; /** A pointer to the results panel */ protected ResultsPanel m_ResultsPanel = null; /* * A class that handles running a copy of the experiment * in a separate thread */ class ExperimentRunner extends Thread implements Serializable { /** for serialization */ private static final long serialVersionUID = -5591889874714150118L; Experiment m_ExpCopy; public ExperimentRunner(final Experiment exp) throws Exception { // Create a full copy using serialization if (exp == null) { System.err.println("Null experiment!!!"); } else { System.err.println("Running experiment: " + exp.toString()); } System.err.println("Writing experiment copy"); SerializedObject so = new SerializedObject(exp); System.err.println("Reading experiment copy"); m_ExpCopy = (Experiment) so.getObject(); System.err.println("Made experiment copy"); } public void abortExperiment() { if (m_ExpCopy instanceof RemoteExperiment) { ((RemoteExperiment)m_ExpCopy).abortExperiment(); // m_StartBut.setEnabled(true); m_StopBut.setEnabled(false); // statusMessage(NOT_RUNNING); } } /** * Starts running the experiment. */ public void run() { m_StartBut.setEnabled(false); m_StopBut.setEnabled(true); if (m_ResultsPanel != null) { m_ResultsPanel.setExperiment(null); } try { if (m_ExpCopy instanceof RemoteExperiment) { // add a listener System.err.println("Adding a listener"); ((RemoteExperiment)m_ExpCopy). addRemoteExperimentListener(new RemoteExperimentListener() { public void remoteExperimentStatus(RemoteExperimentEvent e) { if (e.m_statusMessage) { statusMessage(e.m_messageString); } if (e.m_logMessage) { logMessage(e.m_messageString); } if (e.m_experimentFinished) { m_RunThread = null; m_StartBut.setEnabled(true); m_StopBut.setEnabled(false); statusMessage(NOT_RUNNING); } } }); } logMessage("Started"); statusMessage("Initializing..."); m_ExpCopy.initialize(); int errors = 0; if (!(m_ExpCopy instanceof RemoteExperiment)) { statusMessage("Iterating..."); while (m_RunThread != null && m_ExpCopy.hasMoreIterations()) { try { String current = "Iteration:"; if (m_ExpCopy.getUsePropertyIterator()) { int cnum = m_ExpCopy.getCurrentPropertyNumber(); String ctype = m_ExpCopy.getPropertyArray().getClass().getComponentType().getName(); int lastDot = ctype.lastIndexOf('.'); if (lastDot != -1) { ctype = ctype.substring(lastDot + 1); } String cname = " " + ctype + "=" + (cnum + 1) + ":" + m_ExpCopy.getPropertyArrayValue(cnum).getClass().getName(); current += cname; } String dname = ((File) m_ExpCopy.getDatasets() .elementAt(m_ExpCopy.getCurrentDatasetNumber())) .getName(); current += " Dataset=" + dname + " Run=" + (m_ExpCopy.getCurrentRunNumber()); statusMessage(current); m_ExpCopy.nextIteration(); } catch (Exception ex) { errors ++; logMessage(ex.getMessage()); ex.printStackTrace(); boolean continueAfterError = false; if (continueAfterError) { m_ExpCopy.advanceCounters(); // Try to keep plowing through } else { m_RunThread = null; } } } statusMessage("Postprocessing..."); m_ExpCopy.postProcess(); if (m_RunThread == null) { logMessage("Interrupted"); } else { logMessage("Finished"); } if (errors == 1) { logMessage("There was " + errors + " error"); } else { logMessage("There were " + errors + " errors"); } statusMessage(NOT_RUNNING); } else { statusMessage("Remote experiment running..."); ((RemoteExperiment)m_ExpCopy).runExperiment(); } } catch (Exception ex) { ex.printStackTrace(); System.err.println(ex.getMessage()); statusMessage(ex.getMessage()); } finally { if (m_ResultsPanel != null) { m_ResultsPanel.setExperiment(m_ExpCopy); } if (!(m_ExpCopy instanceof RemoteExperiment)) { m_RunThread = null; m_StartBut.setEnabled(true); m_StopBut.setEnabled(false); System.err.println("Done..."); } } } } /** * Sets the pointer to the results panel. */ public void setResultsPanel(ResultsPanel rp) { m_ResultsPanel = rp; } /** * Creates the run panel with no initial experiment. */ public RunPanel() { m_StartBut.addActionListener(this); m_StopBut.addActionListener(this); m_StartBut.setEnabled(false); m_StopBut.setEnabled(false); m_StartBut.setMnemonic('S'); m_StopBut.setMnemonic('t'); m_Log.statusMessage(NOT_RUNNING); // Set the GUI layout JPanel controls = new JPanel(); GridBagLayout gb = new GridBagLayout(); GridBagConstraints constraints = new GridBagConstraints(); controls.setBorder(BorderFactory.createEmptyBorder(10, 5, 10, 5)); // controls.setLayout(new GridLayout(1,2)); controls.setLayout(gb); constraints.gridx=0;constraints.gridy=0;constraints.weightx=5; constraints.fill = GridBagConstraints.HORIZONTAL; constraints.gridwidth=1;constraints.gridheight=1; constraints.insets = new Insets(0,2,0,2); controls.add(m_StartBut,constraints); constraints.gridx=1;constraints.gridy=0;constraints.weightx=5; constraints.gridwidth=1;constraints.gridheight=1; controls.add(m_StopBut,constraints); setLayout(new BorderLayout()); add(controls, BorderLayout.NORTH); add(m_Log, BorderLayout.CENTER); } /** * Creates the panel with the supplied initial experiment. * * @param exp a value of type 'Experiment' */ public RunPanel(Experiment exp) { this(); setExperiment(exp); } /** * Sets the experiment the panel operates on. * * @param exp a value of type 'Experiment' */ public void setExperiment(Experiment exp) { m_Exp = exp; m_StartBut.setEnabled(m_RunThread == null); m_StopBut.setEnabled(m_RunThread != null); } /** * Controls starting and stopping the experiment. * * @param e a value of type 'ActionEvent' */ public void actionPerformed(ActionEvent e) { if (e.getSource() == m_StartBut) { if (m_RunThread == null) { boolean proceed = true; if (Experimenter.m_Memory.memoryIsLow()) { proceed = Experimenter.m_Memory.showMemoryIsLow(); } if (proceed) { try { m_RunThread = new ExperimentRunner(m_Exp); m_RunThread.setPriority(Thread.MIN_PRIORITY); // UI has most priority m_RunThread.start(); } catch (Exception ex) { ex.printStackTrace(); logMessage("Problem creating experiment copy to run: " + ex.getMessage()); } } } } else if (e.getSource() == m_StopBut) { m_StopBut.setEnabled(false); logMessage("User aborting experiment. "); if (m_Exp instanceof RemoteExperiment) { logMessage("Waiting for remote tasks to " +"complete..."); } ((ExperimentRunner)m_RunThread).abortExperiment(); // m_RunThread.stop() ?? m_RunThread = null; } } /** * Sends the supplied message to the log panel log area. * * @param message the message to log */ protected void logMessage(String message) { m_Log.logMessage(message); } /** * Sends the supplied message to the log panel status line. * * @param message the status message */ protected void statusMessage(String message) { m_Log.statusMessage(message); } /** * Tests out the run panel from the command line. * * @param args may contain options specifying an experiment to run. */ public static void main(String [] args) { try { boolean readExp = Utils.getFlag('l', args); final String expFile = Utils.getOption('f', args); if (readExp && (expFile.length() == 0)) { throw new Exception("A filename must be given with the -f option"); } Experiment exp = null; if (readExp) { FileInputStream fi = new FileInputStream(expFile); ObjectInputStream oi = new ObjectInputStream( new BufferedInputStream(fi)); Object to = oi.readObject(); if (to instanceof RemoteExperiment) { exp = (RemoteExperiment)to; } else { exp = (Experiment)to; } oi.close(); } else { exp = new Experiment(); } System.err.println("Initial Experiment:\n" + exp.toString()); final JFrame jf = new JFrame("Run Weka Experiment"); jf.getContentPane().setLayout(new BorderLayout()); final RunPanel sp = new RunPanel(exp); //sp.setBorder(BorderFactory.createTitledBorder("Setup")); jf.getContentPane().add(sp, BorderLayout.CENTER); jf.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.err.println("\nExperiment Configuration\n" + sp.m_Exp.toString()); jf.dispose(); System.exit(0); } }); jf.pack(); 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/experiment/SetupModePanel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * SetupModePanel.java * Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.experiment; import weka.experiment.Experiment; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.beans.PropertyChangeListener; /** * This panel switches between simple and advanced experiment setup panels. * * @author Richard Kirkby (rkirkby@cs.waikato.ac.nz) * @version $Revision$ */ public class SetupModePanel extends JPanel { /** for serialization */ private static final long serialVersionUID = -3758035565520727822L; /** the available panels. */ protected AbstractSetupPanel[] m_Panels = AbstractSetupPanel.getPanels(); /** the combobox with all available setup panels. */ protected JComboBox m_ComboBoxPanels; /** The simple setup panel */ protected AbstractSetupPanel m_defaultPanel = null; /** The advanced setup panel */ protected AbstractSetupPanel m_advancedPanel = null; /** the current panel. */ protected AbstractSetupPanel m_CurrentPanel; /** * Creates the setup panel with no initial experiment. */ public SetupModePanel() { // no panels discovered? if (m_Panels.length == 0) { System.err.println("No experimenter setup panels discovered? Using fallback (simple, advanced)."); m_Panels = new AbstractSetupPanel[]{ new SetupPanel(), new SimpleSetupPanel() }; } for (AbstractSetupPanel panel: m_Panels) { if (panel.getClass().getName().equals(ExperimenterDefaults.getSetupPanel())) m_defaultPanel = panel; if (panel instanceof SetupPanel) m_advancedPanel = panel; panel.setModePanel(this); } // fallback on simple setup panel if (m_defaultPanel == null) { for (AbstractSetupPanel panel: m_Panels) { if (panel instanceof SimpleSetupPanel) m_defaultPanel = panel; } } m_CurrentPanel = m_defaultPanel; m_ComboBoxPanels = new JComboBox(m_Panels); m_ComboBoxPanels.setSelectedItem(m_defaultPanel); m_ComboBoxPanels.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (m_ComboBoxPanels.getSelectedIndex() == -1) return; AbstractSetupPanel panel = (AbstractSetupPanel) m_ComboBoxPanels.getSelectedItem(); switchTo(panel, null); } }); JPanel switchPanel = new JPanel(); switchPanel.setLayout(new FlowLayout(FlowLayout.LEFT)); switchPanel.add(new JLabel("Experiment Configuration Mode")); switchPanel.add(m_ComboBoxPanels); setLayout(new BorderLayout()); add(switchPanel, BorderLayout.NORTH); add(m_defaultPanel, BorderLayout.CENTER); } /** * Switches to the advanced panel. * * @param exp the experiment to configure */ public void switchToAdvanced(Experiment exp) { switchTo(m_advancedPanel, exp); m_ComboBoxPanels.setSelectedItem(m_advancedPanel); } /** * Switches to the specified panel. Switching from advanced panel to simple panel without conversion * is not permitted by this method. * * @param panel the panel to switch to * @param exp the experiment to configure */ public void switchTo(AbstractSetupPanel panel, Experiment exp) { if (exp == null) exp = m_CurrentPanel.getExperiment(); if (exp != null) { if (!panel.setExperiment(exp)) { m_ComboBoxPanels.setSelectedItem(m_CurrentPanel); return; } } remove(m_CurrentPanel); m_CurrentPanel.cleanUpAfterSwitch(); add(panel, BorderLayout.CENTER); validate(); repaint(); m_CurrentPanel = panel; } /** * Adds a PropertyChangeListener who will be notified of value changes. * * @param l a value of type 'PropertyChangeListener' */ public void addPropertyChangeListener(PropertyChangeListener l) { if (m_Panels != null) { for (AbstractSetupPanel panel : m_Panels) panel.addPropertyChangeListener(l); } } /** * Removes a PropertyChangeListener who will be notified of value changes. * * @param l a value of type 'PropertyChangeListener' */ public void removePropertyChangeListener(PropertyChangeListener l) { if (m_Panels != null) { for (AbstractSetupPanel panel : m_Panels) panel.removePropertyChangeListener(l); } } /** * Gets the currently configured experiment. * * @return the currently configured experiment. */ public Experiment getExperiment() { return m_CurrentPanel.getExperiment(); } }
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/experiment/SetupPanel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * SetupPanel.java * Copyright (C) 1999-2015 University of Waikato, Hamilton, New Zealand * */ package weka.gui.experiment; import weka.core.SerializationHelper; import weka.core.Utils; import weka.core.xml.KOML; import weka.experiment.Experiment; import weka.experiment.PropertyNode; import weka.experiment.RemoteExperiment; import weka.experiment.ResultListener; import weka.experiment.ResultProducer; import weka.gui.ExtensionFileFilter; import weka.gui.GenericObjectEditor; import weka.gui.PropertyPanel; import javax.swing.BorderFactory; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.filechooser.FileFilter; import java.awt.BorderLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.GridLayout; import java.awt.Insets; 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.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; 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; /** * This panel controls the configuration of an experiment. * <p> * If <a href="http://koala.ilog.fr/XML/serialization/" target="_blank">KOML</a> * is in the classpath the experiments can also be saved to XML instead of a * binary format. * * @author Len Trigg (trigg@cs.waikato.ac.nz) * @author Mark Hall (mhall@cs.waikato.ac.nz) * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class SetupPanel extends AbstractSetupPanel { /** for serialization */ private static final long serialVersionUID = 6552671886903170033L; /** The experiment being configured */ protected Experiment m_Exp; /** The panel which switched between simple and advanced setup modes */ protected SetupModePanel m_modePanel = null; /** Click to load an experiment */ protected JButton m_OpenBut = new JButton("Open..."); /** Click to save an experiment */ protected JButton m_SaveBut = new JButton("Save..."); /** Click to create a new experiment with default settings */ protected JButton m_NewBut = new JButton("New"); /** A filter to ensure only experiment files get shown in the chooser */ protected FileFilter m_ExpFilter = new ExtensionFileFilter( Experiment.FILE_EXTENSION, "Experiment configuration files (*" + Experiment.FILE_EXTENSION + ")"); /** * A filter to ensure only experiment (in KOML format) files get shown in the * chooser */ protected FileFilter m_KOMLFilter = new ExtensionFileFilter( KOML.FILE_EXTENSION, "Experiment configuration files (*" + KOML.FILE_EXTENSION + ")"); /** * A filter to ensure only experiment (in XML format) files get shown in the * chooser */ protected FileFilter m_XMLFilter = new ExtensionFileFilter(".xml", "Experiment configuration files (*.xml)"); /** The file chooser for selecting experiments */ protected JFileChooser m_FileChooser = new JFileChooser(new File( System.getProperty("user.dir"))); /** The ResultProducer editor */ protected GenericObjectEditor m_RPEditor = new GenericObjectEditor(); /** The panel to contain the ResultProducer editor */ protected PropertyPanel m_RPEditorPanel = new PropertyPanel(m_RPEditor); /** The ResultListener editor */ protected GenericObjectEditor m_RLEditor = new GenericObjectEditor(); /** The panel to contain the ResultListener editor */ protected PropertyPanel m_RLEditorPanel = new PropertyPanel(m_RLEditor); /** The panel that configures iteration on custom resultproducer property */ protected GeneratorPropertyIteratorPanel m_GeneratorPropertyPanel = new GeneratorPropertyIteratorPanel(); /** The panel for configuring run numbers */ protected RunNumberPanel m_RunNumberPanel = new RunNumberPanel(); /** The panel for enabling a distributed experiment */ protected DistributeExperimentPanel m_DistributeExperimentPanel = new DistributeExperimentPanel(); /** The panel for configuring selected datasets */ protected DatasetListPanel m_DatasetListPanel = new DatasetListPanel(); /** A button for bringing up the notes */ protected JButton m_NotesButton = new JButton("Notes"); /** Frame for the notes */ protected JFrame m_NotesFrame = new JFrame("Notes"); /** Area for user notes Default of 10 rows */ protected JTextArea m_NotesText = new JTextArea(null, 10, 0); /** * Manages sending notifications to people when we change the experiment, at * this stage, only the resultlistener so the resultpanel can update. */ protected PropertyChangeSupport m_Support = new PropertyChangeSupport(this); /** Click to advacne data set before custom generator */ protected JRadioButton m_advanceDataSetFirst = new JRadioButton( "Data sets first"); /** Click to advance custom generator before data set */ protected JRadioButton m_advanceIteratorFirst = new JRadioButton( "Custom generator first"); /** Handle radio buttons */ ActionListener m_RadioListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { updateRadioLinks(); } }; // Registers the appropriate property editors static { GenericObjectEditor.registerEditors(); } /** * Creates the setup panel with the supplied initial experiment. * * @param exp a value of type 'Experiment' */ public SetupPanel(Experiment exp) { this(); setExperiment(exp); } /** * Creates the setup panel with no initial experiment. */ public SetupPanel() { m_DistributeExperimentPanel.addCheckBoxActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (m_DistributeExperimentPanel.distributedExperimentSelected()) { if (!(m_Exp instanceof RemoteExperiment)) { try { RemoteExperiment re = new RemoteExperiment(m_Exp); setExperiment(re); } catch (Exception ex) { ex.printStackTrace(); } } } else { if (m_Exp instanceof RemoteExperiment) { setExperiment(((RemoteExperiment) m_Exp).getBaseExperiment()); } } } }); m_NewBut.setMnemonic('N'); m_NewBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { setExperiment(new Experiment()); } }); m_SaveBut.setMnemonic('S'); m_SaveBut.setEnabled(false); m_SaveBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { saveExperiment(); } }); m_OpenBut.setMnemonic('O'); m_OpenBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { openExperiment(); } }); m_FileChooser.addChoosableFileFilter(m_ExpFilter); if (KOML.isPresent()) { m_FileChooser.addChoosableFileFilter(m_KOMLFilter); } m_FileChooser.addChoosableFileFilter(m_XMLFilter); m_FileChooser.setFileFilter(m_ExpFilter); m_FileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); m_GeneratorPropertyPanel.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { updateRadioLinks(); } }); m_RPEditor.setClassType(ResultProducer.class); m_RPEditor.setEnabled(false); m_RPEditor.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent e) { m_Exp.setResultProducer((ResultProducer) m_RPEditor.getValue()); m_Exp.setUsePropertyIterator(false); m_Exp.setPropertyArray(null); m_Exp.setPropertyPath(null); m_GeneratorPropertyPanel.setExperiment(m_Exp); repaint(); } }); m_RLEditor.setClassType(ResultListener.class); m_RLEditor.setEnabled(false); m_RLEditor.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent e) { m_Exp.setResultListener((ResultListener) m_RLEditor.getValue()); m_Support.firePropertyChange("", null, null); repaint(); } }); m_NotesFrame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { m_NotesButton.setEnabled(true); } }); m_NotesFrame.getContentPane().add(new JScrollPane(m_NotesText)); m_NotesFrame.setSize(600, 400); m_NotesButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m_NotesButton.setEnabled(false); m_NotesFrame.setVisible(true); } }); m_NotesButton.setEnabled(false); m_NotesText.setEditable(true); // m_NotesText.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); m_NotesText.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { m_Exp.setNotes(m_NotesText.getText()); } }); m_NotesText.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { m_Exp.setNotes(m_NotesText.getText()); } }); // Set up the GUI layout JPanel buttons = new JPanel(); GridBagLayout gb = new GridBagLayout(); GridBagConstraints constraints = new GridBagConstraints(); buttons.setBorder(BorderFactory.createEmptyBorder(10, 5, 10, 5)); // buttons.setLayout(new GridLayout(1, 3, 5, 5)); buttons.setLayout(gb); constraints.gridx = 0; constraints.gridy = 0; constraints.weightx = 5; constraints.fill = GridBagConstraints.HORIZONTAL; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.insets = new Insets(0, 2, 0, 2); buttons.add(m_OpenBut, constraints); constraints.gridx = 1; constraints.gridy = 0; constraints.weightx = 5; constraints.gridwidth = 1; constraints.gridheight = 1; buttons.add(m_SaveBut, constraints); constraints.gridx = 2; constraints.gridy = 0; constraints.weightx = 5; constraints.gridwidth = 1; constraints.gridheight = 1; buttons.add(m_NewBut, constraints); JPanel src = new JPanel(); src.setLayout(new BorderLayout()); src.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createTitledBorder("Result generator"), BorderFactory.createEmptyBorder(0, 5, 5, 5))); src.add(m_RPEditorPanel, BorderLayout.NORTH); m_RPEditorPanel.setEnabled(false); JPanel dest = new JPanel(); dest.setLayout(new BorderLayout()); dest.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createTitledBorder("Destination"), BorderFactory.createEmptyBorder(0, 5, 5, 5))); dest.add(m_RLEditorPanel, BorderLayout.NORTH); m_RLEditorPanel.setEnabled(false); m_advanceDataSetFirst.setEnabled(false); m_advanceIteratorFirst.setEnabled(false); m_advanceDataSetFirst .setToolTipText("Advance data set before custom generator"); m_advanceIteratorFirst .setToolTipText("Advance custom generator before data set"); m_advanceDataSetFirst.setSelected(true); ButtonGroup bg = new ButtonGroup(); bg.add(m_advanceDataSetFirst); bg.add(m_advanceIteratorFirst); m_advanceDataSetFirst.addActionListener(m_RadioListener); m_advanceIteratorFirst.addActionListener(m_RadioListener); JPanel radioButs = new JPanel(); radioButs.setBorder(BorderFactory.createTitledBorder("Iteration control")); radioButs.setLayout(new GridLayout(1, 2)); radioButs.add(m_advanceDataSetFirst); radioButs.add(m_advanceIteratorFirst); JPanel simpleIterators = new JPanel(); simpleIterators.setLayout(new BorderLayout()); JPanel tmp = new JPanel(); tmp.setLayout(new GridBagLayout()); // tmp.setLayout(new GridLayout(1, 2)); constraints.gridx = 0; constraints.gridy = 0; constraints.weightx = 5; constraints.fill = GridBagConstraints.HORIZONTAL; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.insets = new Insets(0, 2, 0, 2); tmp.add(m_RunNumberPanel, constraints); constraints.gridx = 1; constraints.gridy = 0; constraints.weightx = 5; constraints.fill = GridBagConstraints.HORIZONTAL; constraints.gridwidth = 1; constraints.gridheight = 2; tmp.add(m_DistributeExperimentPanel, constraints); JPanel tmp2 = new JPanel(); // tmp2.setLayout(new GridLayout(2, 1)); tmp2.setLayout(new GridBagLayout()); constraints.gridx = 0; constraints.gridy = 0; constraints.weightx = 5; constraints.fill = GridBagConstraints.HORIZONTAL; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.insets = new Insets(0, 2, 0, 2); tmp2.add(tmp, constraints); constraints.gridx = 0; constraints.gridy = 1; constraints.weightx = 5; constraints.fill = GridBagConstraints.HORIZONTAL; constraints.gridwidth = 1; constraints.gridheight = 1; tmp2.add(radioButs, constraints); simpleIterators.add(tmp2, BorderLayout.NORTH); simpleIterators.add(m_DatasetListPanel, BorderLayout.CENTER); JPanel iterators = new JPanel(); iterators.setLayout(new GridLayout(1, 2)); iterators.add(simpleIterators); iterators.add(m_GeneratorPropertyPanel); JPanel top = new JPanel(); top.setLayout(new GridLayout(2, 1)); top.add(dest); top.add(src); JPanel notes = new JPanel(); notes.setLayout(new BorderLayout()); notes.add(m_NotesButton, BorderLayout.CENTER); JPanel p2 = new JPanel(); // p2.setLayout(new GridLayout(2, 1)); p2.setLayout(new BorderLayout()); p2.add(iterators, BorderLayout.CENTER); p2.add(notes, BorderLayout.SOUTH); JPanel p3 = new JPanel(); p3.setLayout(new BorderLayout()); p3.add(buttons, BorderLayout.NORTH); p3.add(top, BorderLayout.SOUTH); setLayout(new BorderLayout()); add(p3, BorderLayout.NORTH); add(p2, BorderLayout.CENTER); } /** * Returns the name of the panel. * * @return the name */ public String getName() { return "Advanced"; } /** * Deletes the notes frame. */ protected void removeNotesFrame() { m_NotesFrame.setVisible(false); } /** * Sets the panel used to switch between simple and advanced modes. * * @param modePanel the panel */ public void setModePanel(SetupModePanel modePanel) { m_modePanel = modePanel; } /** * Sets the experiment to configure. * * @param exp a value of type 'Experiment' */ public boolean setExperiment(Experiment exp) { boolean iteratorOn = exp.getUsePropertyIterator(); Object propArray = exp.getPropertyArray(); PropertyNode[] propPath = exp.getPropertyPath(); m_Exp = exp; m_SaveBut.setEnabled(true); m_RPEditor.setValue(m_Exp.getResultProducer()); m_RPEditor.setEnabled(true); m_RPEditorPanel.setEnabled(true); m_RPEditorPanel.repaint(); m_RLEditor.setValue(m_Exp.getResultListener()); m_RLEditor.setEnabled(true); m_RLEditorPanel.setEnabled(true); m_RLEditorPanel.repaint(); m_NotesText.setText(exp.getNotes()); m_NotesButton.setEnabled(true); m_advanceDataSetFirst.setSelected(m_Exp.getAdvanceDataSetFirst()); m_advanceIteratorFirst.setSelected(!m_Exp.getAdvanceDataSetFirst()); m_advanceDataSetFirst.setEnabled(true); m_advanceIteratorFirst.setEnabled(true); exp.setPropertyPath(propPath); exp.setPropertyArray(propArray); exp.setUsePropertyIterator(iteratorOn); m_GeneratorPropertyPanel.setExperiment(m_Exp); m_RunNumberPanel.setExperiment(m_Exp); m_DatasetListPanel.setExperiment(m_Exp); m_DistributeExperimentPanel.setExperiment(m_Exp); m_Support.firePropertyChange("", null, null); return true; } /** * Gets the currently configured experiment. * * @return the currently configured experiment. */ public Experiment getExperiment() { return m_Exp; } /** * Prompts the user to select an experiment file and loads it. */ private void openExperiment() { int returnVal = m_FileChooser.showOpenDialog(this); if (returnVal != JFileChooser.APPROVE_OPTION) { return; } File expFile = m_FileChooser.getSelectedFile(); // add extension if necessary if (m_FileChooser.getFileFilter() == m_ExpFilter) { if (!expFile.getName().toLowerCase().endsWith(Experiment.FILE_EXTENSION)) { expFile = new File(expFile.getParent(), expFile.getName() + Experiment.FILE_EXTENSION); } } else if (m_FileChooser.getFileFilter() == m_KOMLFilter) { if (!expFile.getName().toLowerCase().endsWith(KOML.FILE_EXTENSION)) { expFile = new File(expFile.getParent(), expFile.getName() + KOML.FILE_EXTENSION); } } else if (m_FileChooser.getFileFilter() == m_XMLFilter) { if (!expFile.getName().toLowerCase().endsWith(".xml")) { expFile = new File(expFile.getParent(), expFile.getName() + ".xml"); } } try { Experiment exp = Experiment.read(expFile.getAbsolutePath()); setExperiment(exp); System.err.println("Opened experiment:\n" + m_Exp); } catch (Exception ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(this, "Couldn't open experiment file:\n" + expFile + "\nReason:\n" + ex.getMessage(), "Open Experiment", JOptionPane.ERROR_MESSAGE); // Pop up error dialog } } /** * Prompts the user for a filename to save the experiment to, then saves the * experiment. */ private void saveExperiment() { int returnVal = m_FileChooser.showSaveDialog(this); if (returnVal != JFileChooser.APPROVE_OPTION) { return; } File expFile = m_FileChooser.getSelectedFile(); // add extension if necessary if (m_FileChooser.getFileFilter() == m_ExpFilter) { if (!expFile.getName().toLowerCase().endsWith(Experiment.FILE_EXTENSION)) { expFile = new File(expFile.getParent(), expFile.getName() + Experiment.FILE_EXTENSION); } } else if (m_FileChooser.getFileFilter() == m_KOMLFilter) { if (!expFile.getName().toLowerCase().endsWith(KOML.FILE_EXTENSION)) { expFile = new File(expFile.getParent(), expFile.getName() + KOML.FILE_EXTENSION); } } else if (m_FileChooser.getFileFilter() == m_XMLFilter) { if (!expFile.getName().toLowerCase().endsWith(".xml")) { expFile = new File(expFile.getParent(), expFile.getName() + ".xml"); } } try { Experiment.write(expFile.getAbsolutePath(), m_Exp); System.err.println("Saved experiment:\n" + m_Exp); } catch (Exception ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(this, "Couldn't save experiment file:\n" + expFile + "\nReason:\n" + ex.getMessage(), "Save Experiment", JOptionPane.ERROR_MESSAGE); } } /** * Adds a PropertyChangeListener who will be notified of value changes. * * @param l a value of type 'PropertyChangeListener' */ @Override public void addPropertyChangeListener(PropertyChangeListener l) { if (m_Support != null && l != null) { m_Support.addPropertyChangeListener(l); } } /** * Removes a PropertyChangeListener. * * @param l a value of type 'PropertyChangeListener' */ @Override public void removePropertyChangeListener(PropertyChangeListener l) { if (m_Support != null && l != null) { m_Support.removePropertyChangeListener(l); } } /** * Updates the primary loop iteration control of the experiment */ private void updateRadioLinks() { m_advanceDataSetFirst .setEnabled(m_GeneratorPropertyPanel.getEditorActive()); m_advanceIteratorFirst.setEnabled(m_GeneratorPropertyPanel .getEditorActive()); if (m_Exp != null) { if (!m_GeneratorPropertyPanel.getEditorActive()) { m_Exp.setAdvanceDataSetFirst(true); } else { m_Exp.setAdvanceDataSetFirst(m_advanceDataSetFirst.isSelected()); } } } /** * Tests out the experiment setup from the command line. * * @param args arguments to the program. */ public static void main(String[] args) { try { boolean readExp = Utils.getFlag('l', args); final boolean writeExp = Utils.getFlag('s', args); final String expFile = Utils.getOption('f', args); if ((readExp || writeExp) && (expFile.length() == 0)) { throw new Exception("A filename must be given with the -f option"); } Experiment exp = null; if (readExp) { FileInputStream fi = new FileInputStream(expFile); ObjectInputStream oi = SerializationHelper.getObjectInputStream(fi); /* new ObjectInputStream( new BufferedInputStream(fi)); */ exp = (Experiment) oi.readObject(); oi.close(); } else { exp = new Experiment(); } System.err.println("Initial Experiment:\n" + exp.toString()); final JFrame jf = new JFrame("Weka Experiment Setup"); jf.getContentPane().setLayout(new BorderLayout()); final SetupPanel sp = new SetupPanel(); // sp.setBorder(BorderFactory.createTitledBorder("Setup")); jf.getContentPane().add(sp, BorderLayout.CENTER); jf.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.err.println("\nFinal Experiment:\n" + sp.m_Exp.toString()); // Save the experiment to a file if (writeExp) { try { FileOutputStream fo = new FileOutputStream(expFile); ObjectOutputStream oo = new ObjectOutputStream( new BufferedOutputStream(fo)); oo.writeObject(sp.m_Exp); oo.close(); } catch (Exception ex) { ex.printStackTrace(); System.err.println("Couldn't write experiment to: " + expFile + '\n' + ex.getMessage()); } } jf.dispose(); System.exit(0); } }); jf.pack(); jf.setVisible(true); System.err.println("Short nap"); Thread.sleep(3000); System.err.println("Done"); sp.setExperiment(exp); } catch (Exception ex) { ex.printStackTrace(); System.err.println(ex.getMessage()); } } /** * Hook method for cleaning up the interface after a switch. */ public void cleanUpAfterSwitch() { removeNotesFrame(); } }
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/experiment/SimpleSetupPanel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * SimpleSetupPanel.java * Copyright (C) 2002-2015 University of Waikato, Hamilton, New Zealand * */ package weka.gui.experiment; import weka.classifiers.Classifier; import weka.core.Utils; import weka.core.xml.KOML; import weka.experiment.CSVResultListener; import weka.experiment.ClassifierSplitEvaluator; import weka.experiment.CrossValidationResultProducer; import weka.experiment.DatabaseResultListener; import weka.experiment.Experiment; import weka.experiment.InstancesResultListener; import weka.experiment.PropertyNode; import weka.experiment.RandomSplitResultProducer; import weka.experiment.RegressionSplitEvaluator; import weka.experiment.SplitEvaluator; import weka.gui.DatabaseConnectionDialog; import weka.gui.ExtensionFileFilter; import javax.swing.*; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.filechooser.FileFilter; import java.awt.*; 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.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.beans.IntrospectionException; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.beans.PropertyDescriptor; import java.io.File; /** * This panel controls the configuration of an experiment. * <p> * If <a href="http://koala.ilog.fr/XML/serialization/" target="_blank">KOML</a> * is in the classpath the experiments can also be serialized to XML instead of a * binary format. * * @author Richard kirkby (rkirkby@cs.waikato.ac.nz) * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class SimpleSetupPanel extends AbstractSetupPanel { /** for serialization */ private static final long serialVersionUID = 5257424515609176509L; /** The experiment being configured */ protected Experiment m_Exp; /** The panel which switched between simple and advanced setup modes */ protected SetupModePanel m_modePanel = null; /** The database destination URL to store results into */ protected String m_destinationDatabaseURL; /** The filename to store results into */ protected String m_destinationFilename = ""; /** The number of folds for a cross-validation experiment */ protected int m_numFolds = 10; /** The training percentage for a train/test split experiment */ protected double m_trainPercent = 66; /** The number of times to repeat the sub-experiment */ protected int m_numRepetitions = 10; /** Whether or not the user has consented for the experiment to be simplified */ protected boolean m_userHasBeenAskedAboutConversion; /** Filter for choosing CSV files */ protected ExtensionFileFilter m_csvFileFilter = new ExtensionFileFilter(".csv", "Comma separated value files"); /** FIlter for choosing ARFF files */ protected ExtensionFileFilter m_arffFileFilter = new ExtensionFileFilter(".arff", "ARFF files"); /** Click to load an experiment */ protected JButton m_OpenBut = new JButton("Open..."); /** Click to save an experiment */ protected JButton m_SaveBut = new JButton("Save..."); /** Click to create a new experiment with default settings */ protected JButton m_NewBut = new JButton("New"); /** A filter to ensure only experiment files get shown in the chooser */ protected FileFilter m_ExpFilter = new ExtensionFileFilter(Experiment.FILE_EXTENSION, "Experiment configuration files (*" + Experiment.FILE_EXTENSION + ")"); /** A filter to ensure only experiment (in KOML format) files get shown in the chooser */ protected FileFilter m_KOMLFilter = new ExtensionFileFilter(KOML.FILE_EXTENSION, "Experiment configuration files (*" + KOML.FILE_EXTENSION + ")"); /** A filter to ensure only experiment (in XML format) files get shown in the chooser */ protected FileFilter m_XMLFilter = new ExtensionFileFilter(".xml", "Experiment configuration files (*.xml)"); /** The file chooser for selecting experiments */ protected JFileChooser m_FileChooser = new JFileChooser(new File(System.getProperty("user.dir"))); /** The file chooser for selecting result destinations */ protected JFileChooser m_DestFileChooser = new JFileChooser(new File(System.getProperty("user.dir"))); /** Combo box for choosing experiment destination type */ protected JComboBox m_ResultsDestinationCBox = new JComboBox(); /** Label for destination field */ protected JLabel m_ResultsDestinationPathLabel = new JLabel("Filename:"); /** Input field for result destination path */ protected JTextField m_ResultsDestinationPathTField = new JTextField(); /** Button for browsing destination files */ protected JButton m_BrowseDestinationButton = new JButton("Browse..."); /** Combo box for choosing experiment type */ protected JComboBox m_ExperimentTypeCBox = new JComboBox(); /** Label for parameter field */ protected JLabel m_ExperimentParameterLabel = new JLabel("Number of folds:"); /** Input field for experiment parameter */ protected JTextField m_ExperimentParameterTField = new JTextField(); /** Radio button for choosing classification experiment */ protected JRadioButton m_ExpClassificationRBut = new JRadioButton("Classification"); /** Radio button for choosing regression experiment */ protected JRadioButton m_ExpRegressionRBut = new JRadioButton("Regression"); /** Input field for number of repetitions */ protected JTextField m_NumberOfRepetitionsTField = new JTextField(); /** Radio button for choosing datasets first in order of execution */ protected JRadioButton m_OrderDatasetsFirstRBut = new JRadioButton("Data sets first"); /** Radio button for choosing algorithms first in order of execution */ protected JRadioButton m_OrderAlgorithmsFirstRBut = new JRadioButton("Algorithms first"); /** The strings used to identify the combo box choices */ protected static String DEST_DATABASE_TEXT = ("JDBC database"); protected static String DEST_ARFF_TEXT = ("ARFF file"); protected static String DEST_CSV_TEXT = ("CSV file"); protected static String TYPE_CROSSVALIDATION_TEXT = ("Cross-validation"); protected static String TYPE_RANDOMSPLIT_TEXT = ("Train/Test Percentage Split (data randomized)"); protected static String TYPE_FIXEDSPLIT_TEXT = ("Train/Test Percentage Split (order preserved)"); /** The panel for configuring selected datasets */ protected DatasetListPanel m_DatasetListPanel = new DatasetListPanel(); /** The panel for configuring selected algorithms */ protected AlgorithmListPanel m_AlgorithmListPanel = new AlgorithmListPanel(); /** A button for bringing up the notes */ protected JButton m_NotesButton = new JButton("Notes"); /** Frame for the notes */ protected JFrame m_NotesFrame = Utils.getWekaJFrame("Notes", this); /** Area for user notes Default of 10 rows */ protected JTextArea m_NotesText = new JTextArea(null, 10, 0); /** * Manages sending notifications to people when we change the experiment, * at this stage, only the resultlistener so the resultpanel can update. */ protected PropertyChangeSupport m_Support = new PropertyChangeSupport(this); /** * Creates the setup panel with the supplied initial experiment. * * @param exp a value of type 'Experiment' */ public SimpleSetupPanel(Experiment exp) { this(); setExperiment(exp); } /** * Creates the setup panel with no initial experiment. */ public SimpleSetupPanel() { // everything disabled on startup m_ResultsDestinationCBox.setEnabled(false); m_ResultsDestinationPathLabel.setEnabled(false); m_ResultsDestinationPathTField.setEnabled(false); m_BrowseDestinationButton.setEnabled(false); m_ExperimentTypeCBox.setEnabled(false); m_ExperimentParameterLabel.setEnabled(false); m_ExperimentParameterTField.setEnabled(false); m_ExpClassificationRBut.setEnabled(false); m_ExpRegressionRBut.setEnabled(false); m_NumberOfRepetitionsTField.setEnabled(false); m_OrderDatasetsFirstRBut.setEnabled(false); m_OrderAlgorithmsFirstRBut.setEnabled(false); // get sensible default database address try { m_destinationDatabaseURL = (new DatabaseResultListener()).getDatabaseURL(); } catch (Exception e) {} // create action listeners m_NewBut.setMnemonic('N'); m_NewBut.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Experiment newExp = new Experiment(); CrossValidationResultProducer cvrp = new CrossValidationResultProducer(); cvrp.setNumFolds(10); cvrp.setSplitEvaluator(new ClassifierSplitEvaluator()); newExp.setResultProducer(cvrp); newExp.setPropertyArray(new Classifier[0]); newExp.setUsePropertyIterator(true); setExperiment(newExp); // defaults if (ExperimenterDefaults.getUseClassification()) m_ExpClassificationRBut.setSelected(true); else m_ExpRegressionRBut.setSelected(true); setSelectedItem( m_ResultsDestinationCBox, ExperimenterDefaults.getDestination()); destinationTypeChanged(); setSelectedItem( m_ExperimentTypeCBox, ExperimenterDefaults.getExperimentType()); m_numRepetitions = ExperimenterDefaults.getRepetitions(); m_NumberOfRepetitionsTField.setText( "" + m_numRepetitions); if (ExperimenterDefaults.getExperimentType().equals( TYPE_CROSSVALIDATION_TEXT)) { m_numFolds = ExperimenterDefaults.getFolds(); m_ExperimentParameterTField.setText( "" + m_numFolds); } else { m_trainPercent = ExperimenterDefaults.getTrainPercentage(); m_ExperimentParameterTField.setText( "" + m_trainPercent); } if (ExperimenterDefaults.getDatasetsFirst()) m_OrderDatasetsFirstRBut.setSelected(true); else m_OrderAlgorithmsFirstRBut.setSelected(true); expTypeChanged(); } }); m_SaveBut.setEnabled(false); m_SaveBut.setMnemonic('S'); m_SaveBut.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { saveExperiment(); } }); m_OpenBut.setMnemonic('O'); m_OpenBut.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { openExperiment(); } }); m_FileChooser.addChoosableFileFilter(m_ExpFilter); if (KOML.isPresent()) m_FileChooser.addChoosableFileFilter(m_KOMLFilter); m_FileChooser.addChoosableFileFilter(m_XMLFilter); if (ExperimenterDefaults.getExtension().equals(".xml")) m_FileChooser.setFileFilter(m_XMLFilter); else if (KOML.isPresent() && ExperimenterDefaults.getExtension().equals(KOML.FILE_EXTENSION)) m_FileChooser.setFileFilter(m_KOMLFilter); else m_FileChooser.setFileFilter(m_ExpFilter); m_FileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); m_DestFileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); m_BrowseDestinationButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //using this button for both browsing file & setting username/password if (m_ResultsDestinationCBox.getSelectedItem() == DEST_DATABASE_TEXT){ chooseURLUsername(); } else { chooseDestinationFile(); } } }); m_ExpClassificationRBut.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { expTypeChanged(); } }); m_ExpRegressionRBut.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { expTypeChanged(); } }); m_OrderDatasetsFirstRBut.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (m_Exp != null) { m_Exp.setAdvanceDataSetFirst(true); m_Support.firePropertyChange("", null, null); } } }); m_OrderAlgorithmsFirstRBut.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (m_Exp != null) { m_Exp.setAdvanceDataSetFirst(false); m_Support.firePropertyChange("", null, null); } } }); m_ResultsDestinationPathTField.getDocument().addDocumentListener(new DocumentListener() { public void insertUpdate(DocumentEvent e) {destinationAddressChanged();} public void removeUpdate(DocumentEvent e) {destinationAddressChanged();} public void changedUpdate(DocumentEvent e) {destinationAddressChanged();} }); m_ExperimentParameterTField.getDocument().addDocumentListener(new DocumentListener() { public void insertUpdate(DocumentEvent e) {expParamChanged();} public void removeUpdate(DocumentEvent e) {expParamChanged();} public void changedUpdate(DocumentEvent e) {expParamChanged();} }); m_NumberOfRepetitionsTField.getDocument().addDocumentListener(new DocumentListener() { public void insertUpdate(DocumentEvent e) {numRepetitionsChanged();} public void removeUpdate(DocumentEvent e) {numRepetitionsChanged();} public void changedUpdate(DocumentEvent e) {numRepetitionsChanged();} }); m_NotesFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { m_NotesButton.setEnabled(true); } }); m_NotesFrame.getContentPane().add(new JScrollPane(m_NotesText)); m_NotesFrame.pack(); m_NotesFrame.setSize(800, 600); m_NotesButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { m_NotesButton.setEnabled(false); m_NotesFrame.setIconImage(((JFrame)SwingUtilities.getWindowAncestor(SimpleSetupPanel.this)).getIconImage()); m_NotesFrame.setLocationRelativeTo(SwingUtilities.getWindowAncestor(SimpleSetupPanel.this)); m_NotesFrame.setVisible(true); } }); m_NotesButton.setEnabled(false); m_NotesText.setEditable(true); //m_NotesText.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); m_NotesText.addKeyListener(new KeyAdapter() { public void keyReleased(KeyEvent e) { m_Exp.setNotes(m_NotesText.getText()); } }); m_NotesText.addFocusListener(new FocusAdapter() { public void focusLost(FocusEvent e) { m_Exp.setNotes(m_NotesText.getText()); } }); // Set up the GUI layout JPanel buttons = new JPanel(); GridBagLayout gb = new GridBagLayout(); GridBagConstraints constraints = new GridBagConstraints(); buttons.setBorder(BorderFactory.createEmptyBorder(10, 5, 10, 5)); buttons.setLayout(gb); constraints.gridx=0;constraints.gridy=0;constraints.weightx=5; constraints.fill = GridBagConstraints.HORIZONTAL; constraints.gridwidth=1;constraints.gridheight=1; constraints.insets = new Insets(0,2,0,2); buttons.add(m_OpenBut,constraints); constraints.gridx=1;constraints.gridy=0;constraints.weightx=5; constraints.gridwidth=1;constraints.gridheight=1; buttons.add(m_SaveBut,constraints); constraints.gridx=2;constraints.gridy=0;constraints.weightx=5; constraints.gridwidth=1;constraints.gridheight=1; buttons.add(m_NewBut,constraints); JPanel destName = new JPanel(); destName.setLayout(new BorderLayout(5, 5)); destName.add(m_ResultsDestinationPathLabel, BorderLayout.WEST); destName.add(m_ResultsDestinationPathTField, BorderLayout.CENTER); m_ResultsDestinationCBox.addItem(DEST_ARFF_TEXT); m_ResultsDestinationCBox.addItem(DEST_CSV_TEXT); m_ResultsDestinationCBox.addItem(DEST_DATABASE_TEXT); m_ResultsDestinationCBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { destinationTypeChanged(); } }); JPanel destInner = new JPanel(); destInner.setLayout(new BorderLayout(5, 5)); destInner.add(m_ResultsDestinationCBox, BorderLayout.WEST); destInner.add(destName, BorderLayout.CENTER); destInner.add(m_BrowseDestinationButton, BorderLayout.EAST); JPanel dest = new JPanel(); dest.setLayout(new BorderLayout()); dest.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createTitledBorder("Results Destination"), BorderFactory.createEmptyBorder(0, 5, 5, 5) )); dest.add(destInner, BorderLayout.NORTH); JPanel expParam = new JPanel(); expParam.setLayout(new BorderLayout(5, 5)); expParam.add(m_ExperimentParameterLabel, BorderLayout.WEST); expParam.add(m_ExperimentParameterTField, BorderLayout.CENTER); ButtonGroup typeBG = new ButtonGroup(); typeBG.add(m_ExpClassificationRBut); typeBG.add(m_ExpRegressionRBut); m_ExpClassificationRBut.setSelected(true); JPanel typeRButtons = new JPanel(); typeRButtons.setLayout(new GridLayout(1,0)); typeRButtons.add(m_ExpClassificationRBut); typeRButtons.add(m_ExpRegressionRBut); m_ExperimentTypeCBox.addItem(TYPE_CROSSVALIDATION_TEXT); m_ExperimentTypeCBox.addItem(TYPE_RANDOMSPLIT_TEXT); m_ExperimentTypeCBox.addItem(TYPE_FIXEDSPLIT_TEXT); m_ExperimentTypeCBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { expTypeChanged(); } }); JPanel typeInner = new JPanel(); typeInner.setLayout(new GridLayout(0,1)); typeInner.add(m_ExperimentTypeCBox); typeInner.add(expParam); typeInner.add(typeRButtons); JPanel type = new JPanel(); type.setLayout(new BorderLayout()); type.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createTitledBorder("Experiment Type"), BorderFactory.createEmptyBorder(0, 5, 5, 5) )); type.add(typeInner, BorderLayout.NORTH); ButtonGroup iterBG = new ButtonGroup(); iterBG.add(m_OrderDatasetsFirstRBut); iterBG.add(m_OrderAlgorithmsFirstRBut); m_OrderDatasetsFirstRBut.setSelected(true); JPanel numIter = new JPanel(); numIter.setLayout(new BorderLayout(5, 5)); numIter.add(new JLabel("Number of repetitions:"), BorderLayout.WEST); numIter.add(m_NumberOfRepetitionsTField, BorderLayout.CENTER); JPanel controlInner = new JPanel(); controlInner.setLayout(new GridLayout(0,1)); controlInner.add(numIter); controlInner.add(m_OrderDatasetsFirstRBut); controlInner.add(m_OrderAlgorithmsFirstRBut); JPanel control = new JPanel(); control.setLayout(new BorderLayout()); control.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createTitledBorder("Iteration Control"), BorderFactory.createEmptyBorder(0, 5, 5, 5) )); control.add(controlInner, BorderLayout.NORTH); JPanel type_control = new JPanel(); type_control.setLayout(new GridLayout(1,0)); type_control.add(type); type_control.add(control); JPanel notes = new JPanel(); notes.setLayout(new BorderLayout()); notes.add(m_NotesButton, BorderLayout.CENTER); JPanel top1 = new JPanel(); top1.setLayout(new BorderLayout()); top1.add(dest, BorderLayout.NORTH); top1.add(type_control, BorderLayout.CENTER); JPanel top = new JPanel(); top.setLayout(new BorderLayout()); top.add(buttons, BorderLayout.NORTH); top.add(top1, BorderLayout.CENTER); JPanel datasets = new JPanel(); datasets.setLayout(new BorderLayout()); datasets.add(m_DatasetListPanel, BorderLayout.CENTER); JPanel algorithms = new JPanel(); algorithms.setLayout(new BorderLayout()); algorithms.add(m_AlgorithmListPanel, BorderLayout.CENTER); JPanel schemes = new JPanel(); schemes.setLayout(new GridLayout(1,0)); schemes.add(datasets); schemes.add(algorithms); setLayout(new BorderLayout()); add(top, BorderLayout.NORTH); add(schemes, BorderLayout.CENTER); add(notes, BorderLayout.SOUTH); } /** * Returns the name of the panel. * * @return the name */ public String getName() { return "Simple"; } /** * Sets the selected item of an combobox, since using setSelectedItem(...) * doesn't work, if one checks object references! * * @param cb the combobox to set the item for * @param item the item to set active */ protected void setSelectedItem(JComboBox cb, String item) { int i; for (i = 0; i < cb.getItemCount(); i++) { if (cb.getItemAt(i).toString().equals(item)) { cb.setSelectedIndex(i); break; } } } /** * Deletes the notes frame. */ protected void removeNotesFrame() { m_NotesFrame.setVisible(false); } /** * Gets te users consent for converting the experiment to a simpler form. * * @return true if the user has given consent, false otherwise */ private boolean userWantsToConvert() { if (m_userHasBeenAskedAboutConversion) return true; m_userHasBeenAskedAboutConversion = true; return (JOptionPane.showConfirmDialog(this, "This experiment has settings that are too advanced\n" + "to be represented in the simple setup mode.\n" + "Do you want the experiment to be converted,\n" + "losing some of the advanced settings?\n", "Confirm conversion", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE) == JOptionPane.YES_OPTION); } /** * Sets the panel used to switch between simple and advanced modes. * * @param modePanel the panel */ public void setModePanel(SetupModePanel modePanel) { m_modePanel = modePanel; } /** * Sets the experiment to configure. * * @param exp a value of type 'Experiment' * @return true if experiment could be configured, false otherwise */ public boolean setExperiment(Experiment exp) { m_userHasBeenAskedAboutConversion = false; m_Exp = null; // hold off until we are sure we want conversion m_SaveBut.setEnabled(true); if (exp.getResultListener() instanceof DatabaseResultListener) { m_ResultsDestinationCBox.setSelectedItem(DEST_DATABASE_TEXT); m_ResultsDestinationPathLabel.setText("URL:"); m_destinationDatabaseURL = ((DatabaseResultListener)exp.getResultListener()).getDatabaseURL(); m_ResultsDestinationPathTField.setText(m_destinationDatabaseURL); m_BrowseDestinationButton.setEnabled(true); } else if (exp.getResultListener() instanceof InstancesResultListener) { m_ResultsDestinationCBox.setSelectedItem(DEST_ARFF_TEXT); m_ResultsDestinationPathLabel.setText("Filename:"); m_destinationFilename = ((InstancesResultListener)exp.getResultListener()).outputFileName(); m_ResultsDestinationPathTField.setText(m_destinationFilename); m_BrowseDestinationButton.setEnabled(true); } else if (exp.getResultListener() instanceof CSVResultListener) { m_ResultsDestinationCBox.setSelectedItem(DEST_CSV_TEXT); m_ResultsDestinationPathLabel.setText("Filename:"); m_destinationFilename = ((CSVResultListener)exp.getResultListener()).outputFileName(); m_ResultsDestinationPathTField.setText(m_destinationFilename); m_BrowseDestinationButton.setEnabled(true); } else { // unrecognised result listener System.out.println("SimpleSetup incompatibility: unrecognised result destination"); if (userWantsToConvert()) { m_ResultsDestinationCBox.setSelectedItem(DEST_ARFF_TEXT); m_ResultsDestinationPathLabel.setText("Filename:"); m_destinationFilename = ""; m_ResultsDestinationPathTField.setText(m_destinationFilename); m_BrowseDestinationButton.setEnabled(true); } else { return false; } } m_ResultsDestinationCBox.setEnabled(true); m_ResultsDestinationPathLabel.setEnabled(true); m_ResultsDestinationPathTField.setEnabled(true); if (exp.getResultProducer() instanceof CrossValidationResultProducer) { CrossValidationResultProducer cvrp = (CrossValidationResultProducer) exp.getResultProducer(); m_numFolds = cvrp.getNumFolds(); m_ExperimentParameterTField.setText("" + m_numFolds); if (cvrp.getSplitEvaluator() instanceof ClassifierSplitEvaluator) { m_ExpClassificationRBut.setSelected(true); m_ExpRegressionRBut.setSelected(false); } else if (cvrp.getSplitEvaluator() instanceof RegressionSplitEvaluator) { m_ExpClassificationRBut.setSelected(false); m_ExpRegressionRBut.setSelected(true); } else { // unknown split evaluator System.out.println("SimpleSetup incompatibility: unrecognised split evaluator"); if (userWantsToConvert()) { m_ExpClassificationRBut.setSelected(true); m_ExpRegressionRBut.setSelected(false); } else { return false; } } m_ExperimentTypeCBox.setSelectedItem(TYPE_CROSSVALIDATION_TEXT); } else if (exp.getResultProducer() instanceof RandomSplitResultProducer) { RandomSplitResultProducer rsrp = (RandomSplitResultProducer) exp.getResultProducer(); if (rsrp.getRandomizeData()) { m_ExperimentTypeCBox.setSelectedItem(TYPE_RANDOMSPLIT_TEXT); } else { m_ExperimentTypeCBox.setSelectedItem(TYPE_FIXEDSPLIT_TEXT); } if (rsrp.getSplitEvaluator() instanceof ClassifierSplitEvaluator) { m_ExpClassificationRBut.setSelected(true); m_ExpRegressionRBut.setSelected(false); } else if (rsrp.getSplitEvaluator() instanceof RegressionSplitEvaluator) { m_ExpClassificationRBut.setSelected(false); m_ExpRegressionRBut.setSelected(true); } else { // unknown split evaluator System.out.println("SimpleSetup incompatibility: unrecognised split evaluator"); if (userWantsToConvert()) { m_ExpClassificationRBut.setSelected(true); m_ExpRegressionRBut.setSelected(false); } else { return false; } } m_trainPercent = rsrp.getTrainPercent(); m_ExperimentParameterTField.setText("" + m_trainPercent); } else { // unknown experiment type System.out.println("SimpleSetup incompatibility: unrecognised resultProducer"); if (userWantsToConvert()) { m_ExperimentTypeCBox.setSelectedItem(TYPE_CROSSVALIDATION_TEXT); m_ExpClassificationRBut.setSelected(true); m_ExpRegressionRBut.setSelected(false); } else { return false; } } m_ExperimentTypeCBox.setEnabled(true); m_ExperimentParameterLabel.setEnabled(true); m_ExperimentParameterTField.setEnabled(true); m_ExpClassificationRBut.setEnabled(true); m_ExpRegressionRBut.setEnabled(true); if (exp.getRunLower() == 1) { m_numRepetitions = exp.getRunUpper(); m_NumberOfRepetitionsTField.setText("" + m_numRepetitions); } else { // unsupported iterations System.out.println("SimpleSetup incompatibility: runLower is not 1"); if (userWantsToConvert()) { exp.setRunLower(1); if (m_ExperimentTypeCBox.getSelectedItem() == TYPE_FIXEDSPLIT_TEXT) { exp.setRunUpper(1); m_NumberOfRepetitionsTField.setEnabled(false); m_NumberOfRepetitionsTField.setText("1"); } else { exp.setRunUpper(10); m_numRepetitions = 10; m_NumberOfRepetitionsTField.setText("" + m_numRepetitions); } } else { return false; } } m_NumberOfRepetitionsTField.setEnabled(true); m_OrderDatasetsFirstRBut.setSelected(exp.getAdvanceDataSetFirst()); m_OrderAlgorithmsFirstRBut.setSelected(!exp.getAdvanceDataSetFirst()); m_OrderDatasetsFirstRBut.setEnabled(true); m_OrderAlgorithmsFirstRBut.setEnabled(true); m_NotesText.setText(exp.getNotes()); m_NotesButton.setEnabled(true); if (!exp.getUsePropertyIterator() || !(exp.getPropertyArray() instanceof Classifier[])) { // unknown property iteration System.out.println("SimpleSetup incompatibility: unrecognised property iteration"); if (userWantsToConvert()) { exp.setPropertyArray(new Classifier[0]); exp.setUsePropertyIterator(true); } else { return false; } } m_DatasetListPanel.setExperiment(exp); m_AlgorithmListPanel.setExperiment(exp); m_Exp = exp; expTypeChanged(); // recreate experiment m_Support.firePropertyChange("", null, null); return true; } /** * Gets the currently configured experiment. * * @return the currently configured experiment. */ public Experiment getExperiment() { return m_Exp; } /** * Prompts the user to select an experiment file and loads it. */ private void openExperiment() { int returnVal = m_FileChooser.showOpenDialog(this); if (returnVal != JFileChooser.APPROVE_OPTION) { return; } File expFile = m_FileChooser.getSelectedFile(); // add extension if necessary if (m_FileChooser.getFileFilter() == m_ExpFilter) { if (!expFile.getName().toLowerCase().endsWith(Experiment.FILE_EXTENSION)) expFile = new File(expFile.getParent(), expFile.getName() + Experiment.FILE_EXTENSION); } else if (m_FileChooser.getFileFilter() == m_KOMLFilter) { if (!expFile.getName().toLowerCase().endsWith(KOML.FILE_EXTENSION)) expFile = new File(expFile.getParent(), expFile.getName() + KOML.FILE_EXTENSION); } else if (m_FileChooser.getFileFilter() == m_XMLFilter) { if (!expFile.getName().toLowerCase().endsWith(".xml")) expFile = new File(expFile.getParent(), expFile.getName() + ".xml"); } try { Experiment exp = Experiment.read(expFile.getAbsolutePath()); if (!setExperiment(exp)) { if (m_modePanel != null) m_modePanel.switchToAdvanced(exp); } System.err.println("Opened experiment:\n" + exp); } catch (Exception ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(this, "Couldn't open experiment file:\n" + expFile + "\nReason:\n" + ex.getMessage(), "Open Experiment", JOptionPane.ERROR_MESSAGE); // Pop up error dialog } } /** * Prompts the user for a filename to save the experiment to, then saves * the experiment. */ private void saveExperiment() { int returnVal = m_FileChooser.showSaveDialog(this); if (returnVal != JFileChooser.APPROVE_OPTION) { return; } File expFile = m_FileChooser.getSelectedFile(); // add extension if necessary if (m_FileChooser.getFileFilter() == m_ExpFilter) { if (!expFile.getName().toLowerCase().endsWith(Experiment.FILE_EXTENSION)) expFile = new File(expFile.getParent(), expFile.getName() + Experiment.FILE_EXTENSION); } else if (m_FileChooser.getFileFilter() == m_KOMLFilter) { if (!expFile.getName().toLowerCase().endsWith(KOML.FILE_EXTENSION)) expFile = new File(expFile.getParent(), expFile.getName() + KOML.FILE_EXTENSION); } else if (m_FileChooser.getFileFilter() == m_XMLFilter) { if (!expFile.getName().toLowerCase().endsWith(".xml")) expFile = new File(expFile.getParent(), expFile.getName() + ".xml"); } try { Experiment.write(expFile.getAbsolutePath(), m_Exp); System.err.println("Saved experiment:\n" + m_Exp); } catch (Exception ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(this, "Couldn't save experiment file:\n" + expFile + "\nReason:\n" + ex.getMessage(), "Save Experiment", JOptionPane.ERROR_MESSAGE); } } /** * Adds a PropertyChangeListener who will be notified of value changes. * * @param l a value of type 'PropertyChangeListener' */ public void addPropertyChangeListener(PropertyChangeListener l) { if (m_Support != null && l != null) { m_Support.addPropertyChangeListener(l); } } /** * Removes a PropertyChangeListener. * * @param l a value of type 'PropertyChangeListener' */ public void removePropertyChangeListener(PropertyChangeListener l) { if (m_Support != null && l != null) { m_Support.removePropertyChangeListener(l); } } /** * Responds to a change in the destination type. */ private void destinationTypeChanged() { if (m_Exp == null) return; String str = ""; if (m_ResultsDestinationCBox.getSelectedItem() == DEST_DATABASE_TEXT) { m_ResultsDestinationPathLabel.setText("URL:"); str = m_destinationDatabaseURL; m_BrowseDestinationButton.setEnabled(true); //!!! m_BrowseDestinationButton.setText("User..."); } else { m_ResultsDestinationPathLabel.setText("Filename:"); if (m_ResultsDestinationCBox.getSelectedItem() == DEST_ARFF_TEXT) { int ind = m_destinationFilename.lastIndexOf(".csv"); if (ind > -1) { m_destinationFilename = m_destinationFilename.substring(0, ind) + ".arff"; } } if (m_ResultsDestinationCBox.getSelectedItem() == DEST_CSV_TEXT) { int ind = m_destinationFilename.lastIndexOf(".arff"); if (ind > -1) { m_destinationFilename = m_destinationFilename.substring(0, ind) + ".csv"; } } str = m_destinationFilename; if (m_ResultsDestinationCBox.getSelectedItem() == DEST_ARFF_TEXT) { int ind = str.lastIndexOf(".csv"); if (ind > -1) { str = str.substring(0, ind) + ".arff"; } } if (m_ResultsDestinationCBox.getSelectedItem() == DEST_CSV_TEXT) { int ind = str.lastIndexOf(".arff"); if (ind > -1) { str = str.substring(0, ind) + ".csv"; } } m_BrowseDestinationButton.setEnabled(true); m_BrowseDestinationButton.setText("Browse..."); } if (m_ResultsDestinationCBox.getSelectedItem() == DEST_DATABASE_TEXT) { DatabaseResultListener drl = null; try { drl = new DatabaseResultListener(); } catch (Exception e) { e.printStackTrace(); } drl.setDatabaseURL(m_destinationDatabaseURL); m_Exp.setResultListener(drl); } else { if (m_ResultsDestinationCBox.getSelectedItem() == DEST_ARFF_TEXT) { InstancesResultListener irl = new InstancesResultListener(); if (!m_destinationFilename.equals("")) { irl.setOutputFile(new File(m_destinationFilename)); } m_Exp.setResultListener(irl); } else if (m_ResultsDestinationCBox.getSelectedItem() == DEST_CSV_TEXT) { CSVResultListener crl = new CSVResultListener(); if (!m_destinationFilename.equals("")) { crl.setOutputFile(new File(m_destinationFilename)); } m_Exp.setResultListener(crl); } } m_ResultsDestinationPathTField.setText(str); m_Support.firePropertyChange("", null, null); } /** * Responds to a change in the destination address. */ private void destinationAddressChanged() { if (m_Exp == null) return; if (m_ResultsDestinationCBox.getSelectedItem() == DEST_DATABASE_TEXT) { m_destinationDatabaseURL = m_ResultsDestinationPathTField.getText(); if (m_Exp.getResultListener() instanceof DatabaseResultListener) { ((DatabaseResultListener)m_Exp.getResultListener()).setDatabaseURL(m_destinationDatabaseURL); } } else { File resultsFile = null; m_destinationFilename = m_ResultsDestinationPathTField.getText(); // Use temporary file if no file name is provided if (m_destinationFilename.equals("")) { try { if (m_ResultsDestinationCBox.getSelectedItem() == DEST_ARFF_TEXT) { resultsFile = File.createTempFile("weka_experiment", ".arff"); } if (m_ResultsDestinationCBox.getSelectedItem() == DEST_CSV_TEXT) { resultsFile = File.createTempFile("weka_experiment", ".csv"); } resultsFile.deleteOnExit(); } catch (Exception e) { System.err.println("Cannot create temp file, writing to standard out."); resultsFile = new File("-"); } } else { if (m_ResultsDestinationCBox.getSelectedItem() == DEST_ARFF_TEXT) { if (!m_destinationFilename.endsWith(".arff")) { m_destinationFilename += ".arff"; } } if (m_ResultsDestinationCBox.getSelectedItem() == DEST_CSV_TEXT) { if (!m_destinationFilename.endsWith(".csv")) { m_destinationFilename += ".csv"; } } resultsFile = new File(m_destinationFilename); } ((CSVResultListener)m_Exp.getResultListener()).setOutputFile(resultsFile); ((CSVResultListener)m_Exp.getResultListener()).setOutputFileName(m_destinationFilename); } m_Support.firePropertyChange("", null, null); } /** * Responds to a change in the experiment type. */ private void expTypeChanged() { if (m_Exp == null) return; // update parameter ui if (m_ExperimentTypeCBox.getSelectedItem() == TYPE_CROSSVALIDATION_TEXT) { m_ExperimentParameterLabel.setText("Number of folds:"); m_ExperimentParameterTField.setText("" + m_numFolds); } else { m_ExperimentParameterLabel.setText("Train percentage:"); m_ExperimentParameterTField.setText("" + m_trainPercent); } // update iteration ui if (m_ExperimentTypeCBox.getSelectedItem() == TYPE_FIXEDSPLIT_TEXT) { m_NumberOfRepetitionsTField.setEnabled(false); m_NumberOfRepetitionsTField.setText("1"); m_Exp.setRunLower(1); m_Exp.setRunUpper(1); } else { m_NumberOfRepetitionsTField.setText("" + m_numRepetitions); m_NumberOfRepetitionsTField.setEnabled(true); m_Exp.setRunLower(1); m_Exp.setRunUpper(m_numRepetitions); } SplitEvaluator se = null; Classifier sec = null; if (m_ExpClassificationRBut.isSelected()) { se = new ClassifierSplitEvaluator(); sec = ((ClassifierSplitEvaluator)se).getClassifier(); } else { se = new RegressionSplitEvaluator(); sec = ((RegressionSplitEvaluator)se).getClassifier(); } // build new ResultProducer if (m_ExperimentTypeCBox.getSelectedItem() == TYPE_CROSSVALIDATION_TEXT) { CrossValidationResultProducer cvrp = new CrossValidationResultProducer(); cvrp.setNumFolds(m_numFolds); cvrp.setSplitEvaluator(se); PropertyNode[] propertyPath = new PropertyNode[2]; try { propertyPath[0] = new PropertyNode(se, new PropertyDescriptor("splitEvaluator", CrossValidationResultProducer.class), CrossValidationResultProducer.class); propertyPath[1] = new PropertyNode(sec, new PropertyDescriptor("classifier", se.getClass()), se.getClass()); } catch (IntrospectionException e) { e.printStackTrace(); } m_Exp.setResultProducer(cvrp); m_Exp.setPropertyPath(propertyPath); } else { RandomSplitResultProducer rsrp = new RandomSplitResultProducer(); rsrp.setRandomizeData(m_ExperimentTypeCBox.getSelectedItem() == TYPE_RANDOMSPLIT_TEXT); rsrp.setTrainPercent(m_trainPercent); rsrp.setSplitEvaluator(se); PropertyNode[] propertyPath = new PropertyNode[2]; try { propertyPath[0] = new PropertyNode(se, new PropertyDescriptor("splitEvaluator", RandomSplitResultProducer.class), RandomSplitResultProducer.class); propertyPath[1] = new PropertyNode(sec, new PropertyDescriptor("classifier", se.getClass()), se.getClass()); } catch (IntrospectionException e) { e.printStackTrace(); } m_Exp.setResultProducer(rsrp); m_Exp.setPropertyPath(propertyPath); } m_Exp.setUsePropertyIterator(true); m_Support.firePropertyChange("", null, null); } /** * Responds to a change in the experiment parameter. */ private void expParamChanged() { if (m_Exp == null) return; if (m_ExperimentTypeCBox.getSelectedItem() == TYPE_CROSSVALIDATION_TEXT) { try { m_numFolds = Integer.parseInt(m_ExperimentParameterTField.getText()); } catch (NumberFormatException e) { return; } } else { try { m_trainPercent = Double.parseDouble(m_ExperimentParameterTField.getText()); } catch (NumberFormatException e) { return; } } if (m_ExperimentTypeCBox.getSelectedItem() == TYPE_CROSSVALIDATION_TEXT) { if (m_Exp.getResultProducer() instanceof CrossValidationResultProducer) { CrossValidationResultProducer cvrp = (CrossValidationResultProducer) m_Exp.getResultProducer(); cvrp.setNumFolds(m_numFolds); } else { return; } } else { if (m_Exp.getResultProducer() instanceof RandomSplitResultProducer) { RandomSplitResultProducer rsrp = (RandomSplitResultProducer) m_Exp.getResultProducer(); rsrp.setRandomizeData(m_ExperimentTypeCBox.getSelectedItem() == TYPE_RANDOMSPLIT_TEXT); rsrp.setTrainPercent(m_trainPercent); } else { //System.err.println("not rsrp"); return; } } m_Support.firePropertyChange("", null, null); } /** * Responds to a change in the number of repetitions. */ private void numRepetitionsChanged() { if (m_Exp == null || !m_NumberOfRepetitionsTField.isEnabled()) return; try { m_numRepetitions = Integer.parseInt(m_NumberOfRepetitionsTField.getText()); } catch (NumberFormatException e) { return; } m_Exp.setRunLower(1); m_Exp.setRunUpper(m_numRepetitions); m_Support.firePropertyChange("", null, null); } /** * Lets user enter username/password/URL. */ private void chooseURLUsername() { String dbaseURL=((DatabaseResultListener)m_Exp.getResultListener()).getDatabaseURL(); String username=((DatabaseResultListener)m_Exp.getResultListener()).getUsername(); DatabaseConnectionDialog dbd= new DatabaseConnectionDialog((Frame)SwingUtilities. getWindowAncestor(SimpleSetupPanel.this),dbaseURL,username); dbd.setLocationRelativeTo(SwingUtilities.getWindowAncestor(SimpleSetupPanel.this)); dbd.setVisible(true); //if (dbaseURL == null) { if (dbd.getReturnValue()==JOptionPane.CLOSED_OPTION) { return; } ((DatabaseResultListener)m_Exp.getResultListener()).setUsername(dbd.getUsername()); ((DatabaseResultListener)m_Exp.getResultListener()).setPassword(dbd.getPassword()); ((DatabaseResultListener)m_Exp.getResultListener()).setDatabaseURL(dbd.getURL()); ((DatabaseResultListener)m_Exp.getResultListener()).setDebug(dbd.getDebug()); m_ResultsDestinationPathTField.setText(dbd.getURL()); } /** * Lets user browse for a destination file.. */ private void chooseDestinationFile() { FileFilter fileFilter = null; if (m_ResultsDestinationCBox.getSelectedItem() == DEST_CSV_TEXT) { fileFilter = m_csvFileFilter; } else { fileFilter = m_arffFileFilter; } m_DestFileChooser.setFileFilter(fileFilter); int returnVal = m_DestFileChooser.showSaveDialog(this); if (returnVal != JFileChooser.APPROVE_OPTION) { return; } m_ResultsDestinationPathTField.setText(m_DestFileChooser.getSelectedFile().toString()); } /** * Hook method for cleaning up the interface after a switch. */ public void cleanUpAfterSwitch() { removeNotesFrame(); } }
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/explorer/AbstractPlotInstances.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * AbstractPlotInstances.java * Copyright (C) 2009-2013 University of Waikato, Hamilton, New Zealand */ package weka.gui.explorer; import java.io.Serializable; import java.util.Enumeration; import java.util.Vector; import weka.core.Instances; import weka.core.Option; import weka.core.OptionHandler; import weka.gui.visualize.PlotData2D; /** * Abstract superclass for generating plottable instances. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public abstract class AbstractPlotInstances implements Serializable, OptionHandler { /** for serialization. */ private static final long serialVersionUID = 2375155184845160908L; /** the full dataset. */ protected Instances m_Instances; /** the plotable instances. */ protected Instances m_PlotInstances; /** whether processing has been finished up already. */ protected boolean m_FinishUpCalled; /** * Initializes the container. */ public AbstractPlotInstances() { initialize(); } /** * Initializes the member variables. */ protected void initialize() { m_Instances = null; m_PlotInstances = null; m_FinishUpCalled = false; } /** * Returns an enumeration of all the available options. * * @return an enumeration of all available options. */ @Override public Enumeration<Option> listOptions() { return new Vector<Option>().elements(); } /** * Sets the OptionHandler's options using the given list. All options will be * set (or reset) during this call (i.e. incremental setting of options is not * possible). * * @param options the list of options as an array of strings * @throws Exception if an option is not supported */ @Override public void setOptions(String[] options) throws Exception { } /** * Gets the current option settings for the OptionHandler. * * @return the list of current option settings as an array of strings */ @Override public String[] getOptions() { return new String[0]; } /** * Sets up the structure for the plot instances. */ protected abstract void determineFormat(); /** * Sets the instances that are the basis for the plot instances. * * @param value the training data to initialize with */ public void setInstances(Instances value) { m_Instances = value; } /** * Returns the training data. * * @return the training data */ public Instances getInstances() { return m_Instances; } /** * Default implementation only ensures that a dataset has been set. */ protected void check() { if (m_Instances == null) { throw new IllegalStateException("No instances set!"); } } /** * Performs checks, sets up the structure for the plot instances. */ public void setUp() { m_FinishUpCalled = false; check(); determineFormat(); } /** * Performs optional post-processing. */ protected void finishUp() { m_FinishUpCalled = true; } /** * Returns whether all the data is available and the plot instances can be * used for plotting. * * @param setup whether to call setup as well * @return true if operational for plotting */ public boolean canPlot(boolean setup) { try { if (setup) { setUp(); } return (getPlotInstances().numInstances() > 0); } catch (Exception e) { return false; } } /** * Returns the generated plot instances. * * @return the instances to plot */ public Instances getPlotInstances() { if (!m_FinishUpCalled) { finishUp(); } return m_PlotInstances; } /** * Assembles and returns the plot. The relation name of the dataset gets added * automatically. * * @param name the name of the plot * @return the plot * @throws Exception if plot generation fails */ protected abstract PlotData2D createPlotData(String name) throws Exception; /** * Assembles and returns the plot. The relation name of the dataset gets added * automatically. * * @param name the name of the plot * @return the plot * @throws Exception if plot generation fails */ public PlotData2D getPlotData(String name) throws Exception { if (!m_FinishUpCalled) { finishUp(); } return createPlotData(name); } /** * For freeing up memory. Plot data cannot be generated after this call! */ public void cleanUp() { m_Instances = null; m_PlotInstances = null; m_FinishUpCalled = false; } }
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/explorer/AssociationsPanel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * AssociationsPanel.java * Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.explorer; import weka.associations.AssociationRules; import weka.associations.Associator; import weka.associations.FPGrowth; import weka.core.Attribute; import weka.core.Capabilities; import weka.core.CapabilitiesHandler; import weka.core.Defaults; import weka.core.Drawable; import weka.core.Environment; import weka.core.Instances; import weka.core.OptionHandler; import weka.core.PluginManager; import weka.core.Settings; import weka.core.Utils; import weka.core.WekaPackageClassLoaderManager; import weka.gui.AbstractPerspective; import weka.gui.GenericObjectEditor; import weka.gui.Logger; import weka.gui.PerspectiveInfo; import weka.gui.PropertyPanel; import weka.gui.ResultHistoryPanel; import weka.gui.SaveBuffer; import weka.gui.SysErrLog; import weka.gui.TaskLogger; import weka.gui.explorer.Explorer.CapabilitiesFilterChangeEvent; import weka.gui.explorer.Explorer.CapabilitiesFilterChangeListener; import weka.gui.explorer.Explorer.ExplorerPanel; import weka.gui.explorer.Explorer.LogHandler; import weka.gui.treevisualizer.PlaceNode2; import weka.gui.treevisualizer.TreeVisualizer; import weka.gui.visualize.plugins.AssociationRuleVisualizePlugin; import weka.gui.visualize.plugins.TreeVisualizePlugin; import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.GridLayout; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.InputEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Vector; /** * This panel allows the user to select, configure, and run a scheme that learns * associations. * * @author Eibe Frank (eibe@cs.waikato.ac.nz) * @version $Revision$ */ @PerspectiveInfo(ID = "weka.gui.explorer.associationspanel", title = "Associate", toolTipText = "Discover association rules", iconPath = "weka/gui/weka_icon_new_small.png") public class AssociationsPanel extends AbstractPerspective implements CapabilitiesFilterChangeListener, ExplorerPanel, LogHandler { /** for serialization */ static final long serialVersionUID = -6867871711865476971L; /** the parent frame */ protected Explorer m_Explorer = null; /** Lets the user configure the associator */ protected GenericObjectEditor m_AssociatorEditor = new GenericObjectEditor(); /** The panel showing the current associator selection */ protected PropertyPanel m_CEPanel = new PropertyPanel(m_AssociatorEditor); /** The output area for associations */ protected JTextArea m_OutText = new JTextArea(20, 40); /** The destination for log/status messages */ protected Logger m_Log = new SysErrLog(); /** The buffer saving object for saving output */ protected SaveBuffer m_SaveOut = new SaveBuffer(m_Log, this); /** A panel controlling results viewing */ protected ResultHistoryPanel m_History = new ResultHistoryPanel(m_OutText); /** Click to start running the associator */ protected JButton m_StartBut = new JButton("Start"); /** Click to stop a running associator */ protected JButton m_StopBut = new JButton("Stop"); /** * Whether to store any graph or xml rules output in the history list */ protected JCheckBox m_storeOutput = new JCheckBox( "Store output for visualization"); /** The main set of instances we're playing with */ protected Instances m_Instances; /** The user-supplied test set (if any) */ protected Instances m_TestInstances; /** A thread that associator runs in */ protected Thread m_RunThread; /** * Whether start-up settings have been applied (i.e. initial default * associator to use */ protected boolean m_initialSettingsSet; /* Register the property editors we need */ static { GenericObjectEditor.registerEditors(); } /** * Creates the associator panel */ public AssociationsPanel() { // Connect / configure the components m_OutText.setEditable(false); m_OutText.setFont(new Font("Monospaced", Font.PLAIN, 12)); m_OutText.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); m_OutText.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if ((e.getModifiers() & InputEvent.BUTTON1_MASK) != InputEvent.BUTTON1_MASK) { m_OutText.selectAll(); } } }); JPanel historyHolder = new JPanel(new BorderLayout()); historyHolder.setBorder(BorderFactory .createTitledBorder("Result list (right-click for options)")); historyHolder.add(m_History, BorderLayout.CENTER); m_History.setHandleRightClicks(false); // see if we can popup a menu for the selected result m_History.getList().addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (((e.getModifiers() & InputEvent.BUTTON1_MASK) != InputEvent.BUTTON1_MASK) || e.isAltDown()) { int index = m_History.getList().locationToIndex(e.getPoint()); if (index != -1) { List<String> selectedEls = (List<String>) m_History.getList().getSelectedValuesList(); historyRightClickPopup(selectedEls, e.getX(), e.getY()); } else { historyRightClickPopup(null, e.getX(), e.getY()); } } } }); m_AssociatorEditor.setClassType(Associator.class); m_AssociatorEditor.setValue(ExplorerDefaults.getAssociator()); m_AssociatorEditor.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent e) { m_StartBut.setEnabled(true); // Check capabilities Capabilities currentFilter = m_AssociatorEditor.getCapabilitiesFilter(); Associator associator = (Associator) m_AssociatorEditor.getValue(); Capabilities currentSchemeCapabilities = null; if (associator != null && currentFilter != null && (associator instanceof CapabilitiesHandler)) { currentSchemeCapabilities = ((CapabilitiesHandler) associator).getCapabilities(); if (!currentSchemeCapabilities.supportsMaybe(currentFilter) && !currentSchemeCapabilities.supports(currentFilter)) { m_StartBut.setEnabled(false); } } repaint(); } }); m_StartBut.setToolTipText("Starts the associator"); m_StopBut.setToolTipText("Stops the associator"); m_StartBut.setEnabled(false); m_StopBut.setEnabled(false); m_StartBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { boolean proceed = true; if (Explorer.m_Memory.memoryIsLow()) { proceed = Explorer.m_Memory.showMemoryIsLow(); } if (proceed) { startAssociator(); } } }); m_StopBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { stopAssociator(); } }); // check for any visualization plugins so that we // can add a checkbox for storing graphs or rules boolean showStoreOutput = (PluginManager.getPluginNamesOfTypeList(AssociationRuleVisualizePlugin.class.getName()).size() > 0 || PluginManager.getPluginNamesOfTypeList(TreeVisualizePlugin.class.getName()).size() > 0); // Layout the GUI JPanel p1 = new JPanel(); p1.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createTitledBorder("Associator"), BorderFactory.createEmptyBorder(0, 5, 5, 5))); p1.setLayout(new BorderLayout()); p1.add(m_CEPanel, BorderLayout.NORTH); JPanel buttons = new JPanel(); buttons.setLayout(new BorderLayout()); JPanel buttonsP = new JPanel(); buttonsP.setLayout(new GridLayout(1, 2)); JPanel ssButs = new JPanel(); ssButs.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); ssButs.setLayout(new GridLayout(1, 2, 5, 5)); ssButs.add(m_StartBut); ssButs.add(m_StopBut); buttonsP.add(ssButs); buttons.add(buttonsP, BorderLayout.SOUTH); if (showStoreOutput) { buttons.add(m_storeOutput, BorderLayout.NORTH); } JPanel p3 = new JPanel(); p3.setBorder(BorderFactory.createTitledBorder("Associator output")); p3.setLayout(new BorderLayout()); final JScrollPane js = new JScrollPane(m_OutText); p3.add(js, BorderLayout.CENTER); js.getViewport().addChangeListener(new ChangeListener() { private int lastHeight; @Override public void stateChanged(ChangeEvent e) { JViewport vp = (JViewport) e.getSource(); int h = vp.getViewSize().height; if (h != lastHeight) { // i.e. an addition not just a user scrolling lastHeight = h; int x = h - vp.getExtentSize().height; vp.setViewPosition(new Point(0, x)); } } }); GridBagLayout gbL = new GridBagLayout(); GridBagConstraints gbC = new GridBagConstraints(); JPanel mondo = new JPanel(); gbL = new GridBagLayout(); mondo.setLayout(gbL); gbC = new GridBagConstraints(); gbC.anchor = GridBagConstraints.NORTH; gbC.fill = GridBagConstraints.HORIZONTAL; gbC.gridy = 1; gbC.gridx = 0; gbL.setConstraints(buttons, gbC); mondo.add(buttons); gbC = new GridBagConstraints(); gbC.fill = GridBagConstraints.BOTH; gbC.gridy = 2; gbC.gridx = 0; gbC.weightx = 0; gbL.setConstraints(historyHolder, gbC); mondo.add(historyHolder); gbC = new GridBagConstraints(); gbC.fill = GridBagConstraints.BOTH; gbC.gridy = 0; gbC.gridx = 1; gbC.gridheight = 3; gbC.weightx = 100; gbC.weighty = 100; gbL.setConstraints(p3, gbC); mondo.add(p3); setLayout(new BorderLayout()); add(p1, BorderLayout.NORTH); add(mondo, BorderLayout.CENTER); } /** * Sets the Logger to receive informational messages * * @param newLog the Logger that will now get info messages */ @Override public void setLog(Logger newLog) { m_Log = newLog; } /** * Tells the panel to use a new set of instances. * * @param inst a set of Instances */ @Override public void setInstances(Instances inst) { m_Instances = inst; String[] attribNames = new String[m_Instances.numAttributes()]; for (int i = 0; i < attribNames.length; i++) { String type = "(" + Attribute.typeToStringShort(m_Instances.attribute(i)) + ") "; attribNames[i] = type + m_Instances.attribute(i).name(); } m_StartBut.setEnabled(m_RunThread == null); m_StopBut.setEnabled(m_RunThread != null); } /** * Starts running the currently configured associator with the current * settings. This is run in a separate thread, and will only start if there is * no associator already running. The associator output is sent to the results * history panel. */ protected void startAssociator() { if (m_RunThread == null) { m_StartBut.setEnabled(false); m_StopBut.setEnabled(true); m_RunThread = new Thread() { @Override public void run() { m_CEPanel.addToHistory(); // Copy the current state of things m_Log.statusMessage("Setting up..."); Instances inst = new Instances(m_Instances); String grph = null; // String xmlRules = null; AssociationRules rulesList = null; Associator associator = (Associator) m_AssociatorEditor.getValue(); StringBuffer outBuff = new StringBuffer(); String name = (new SimpleDateFormat("HH:mm:ss - ")).format(new Date()); String cname = associator.getClass().getName(); if (cname.startsWith("weka.associations.")) { name += cname.substring("weka.associations.".length()); } else { name += cname; } String cmd = m_AssociatorEditor.getValue().getClass().getName(); if (m_AssociatorEditor.getValue() instanceof OptionHandler) { cmd += " " + Utils.joinOptions(((OptionHandler) m_AssociatorEditor .getValue()).getOptions()); } try { // Output some header information m_Log.logMessage("Started " + cname); m_Log.logMessage("Command: " + cmd); if (m_Log instanceof TaskLogger) { ((TaskLogger) m_Log).taskStarted(); } outBuff.append("=== Run information ===\n\n"); outBuff.append("Scheme: " + cname); if (associator instanceof OptionHandler) { String[] o = ((OptionHandler) associator).getOptions(); outBuff.append(" " + Utils.joinOptions(o)); } outBuff.append("\n"); outBuff.append("Relation: " + inst.relationName() + '\n'); outBuff.append("Instances: " + inst.numInstances() + '\n'); outBuff.append("Attributes: " + inst.numAttributes() + '\n'); if (inst.numAttributes() < 100) { for (int i = 0; i < inst.numAttributes(); i++) { outBuff.append(" " + inst.attribute(i).name() + '\n'); } } else { outBuff.append(" [list of attributes omitted]\n"); } m_History.addResult(name, outBuff); m_History.setSingle(name); // Build the model and output it. m_Log.statusMessage("Building model on training data..."); associator.buildAssociations(inst); outBuff.append("=== Associator model (full training set) ===\n\n"); outBuff.append(associator.toString() + '\n'); m_History.updateResult(name); if (m_storeOutput.isSelected()) { if (associator instanceof Drawable) { grph = null; try { grph = ((Drawable) associator).graph(); } catch (Exception ex) { } } if (associator instanceof weka.associations.AssociationRulesProducer) { // xmlRules = null; rulesList = null; try { // xmlRules = // ((weka.associations.XMLRulesProducer)associator).xmlRules(); rulesList = ((weka.associations.AssociationRulesProducer) associator) .getAssociationRules(); } catch (Exception ex) { } } } m_Log.logMessage("Finished " + cname); m_Log.statusMessage("OK"); } catch (Exception ex) { m_Log.logMessage(ex.getMessage()); m_Log.statusMessage("See error log"); } finally { Vector<Object> visVect = new Vector<Object>(); try { // save a copy since we don't need the learned model for // anything yet. // TODO should probably add options to store full model and // save/load // models like the classifier and clusterer panels Associator configCopy = associator.getClass().newInstance(); if (configCopy instanceof OptionHandler) { ((OptionHandler) configCopy) .setOptions(((OptionHandler) associator).getOptions()); } visVect.add(configCopy); } catch (Exception ex) { ex.printStackTrace(); // just add the original if we have problems copying visVect.add(associator); } if (grph != null || rulesList != null) { if (grph != null) { visVect.add(grph); } if (rulesList != null) { visVect.add(rulesList); } } m_History.addObject(name, visVect); if (isInterrupted()) { m_Log.logMessage("Interrupted " + cname); m_Log.statusMessage("See error log"); } m_RunThread = null; m_StartBut.setEnabled(true); m_StopBut.setEnabled(false); if (m_Log instanceof TaskLogger) { ((TaskLogger) m_Log).taskFinished(); } } } }; m_RunThread.setPriority(Thread.MIN_PRIORITY); m_RunThread.start(); } } /** * Stops the currently running Associator (if any). */ @SuppressWarnings("deprecation") protected void stopAssociator() { if (m_RunThread != null) { m_RunThread.interrupt(); // This is deprecated (and theoretically the interrupt should do). m_RunThread.stop(); } } /** * Save the currently selected associator output to a file. * * @param name the name of the buffer to save */ protected void saveBuffer(String name) { StringBuffer sb = m_History.getNamedBuffer(name); if (sb != null) { if (m_SaveOut.save(sb)) { m_Log.logMessage("Save successful."); } } } /** * Pops up a TreeVisualizer for the associator from the currently selected * item in the results list * * @param dottyString the description of the tree in dotty format * @param treeName the title to assign to the display */ protected void visualizeTree(String dottyString, String treeName) { final javax.swing.JFrame jf = Utils.getWekaJFrame("Weka Associator Tree Visualizer: " + treeName, this); jf.getContentPane().setLayout(new BorderLayout()); TreeVisualizer tv = new TreeVisualizer(null, dottyString, 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(800, 600); jf.setLocationRelativeTo(SwingUtilities.getWindowAncestor(this)); jf.setVisible(true); tv.fitToScreen(); } /** * Handles constructing a popup menu with visualization options. * * @param names the names of the result history list entries clicked on by the * user * @param x the x coordinate for popping up the menu * @param y the y coordinate for popping up the menu */ @SuppressWarnings("unchecked") protected void historyRightClickPopup(List<String> names, int x, int y) { final List<String> selectedNames = names; JPopupMenu resultListMenu = new JPopupMenu(); JMenuItem visMainBuffer = new JMenuItem("View in main window"); if (selectedNames != null && selectedNames.size() == 1) { visMainBuffer.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m_History.setSingle(selectedNames.get(0)); } }); } else { visMainBuffer.setEnabled(false); } resultListMenu.add(visMainBuffer); JMenuItem visSepBuffer = new JMenuItem("View in separate window"); if (selectedNames != null && selectedNames.size() == 1) { visSepBuffer.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m_History.openFrame(selectedNames.get(0)); } }); } else { visSepBuffer.setEnabled(false); } resultListMenu.add(visSepBuffer); JMenuItem saveOutput = new JMenuItem("Save result buffer"); if (selectedNames != null && selectedNames.size() == 1) { saveOutput.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { saveBuffer(selectedNames.get(0)); } }); } else { saveOutput.setEnabled(false); } resultListMenu.add(saveOutput); JMenuItem deleteOutput = new JMenuItem("Delete result buffer(s)"); if (selectedNames != null) { deleteOutput.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m_History.removeResults(selectedNames); } }); } else { deleteOutput.setEnabled(false); } resultListMenu.add(deleteOutput); Vector<Object> visVect = null; if (selectedNames != null && selectedNames.size() == 1) { visVect = (Vector<Object>) m_History.getNamedObject(selectedNames.get(0)); } // check for the associator itself if (visVect != null) { // should be the first element Associator temp_model = null; if (visVect.get(0) instanceof Associator) { temp_model = (Associator) visVect.get(0); } final Associator model = temp_model; JMenuItem reApplyConfig = new JMenuItem("Re-apply this model's configuration"); if (model != null) { reApplyConfig.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m_AssociatorEditor.setValue(model); } }); } else { reApplyConfig.setEnabled(false); } resultListMenu.add(reApplyConfig); } // plugins JMenu visPlugins = new JMenu("Plugins"); boolean availablePlugins = false; // tree plugins if (visVect != null) { for (Object o : visVect) { if (o instanceof AssociationRules) { List<String> pluginsVector = PluginManager.getPluginNamesOfTypeList(AssociationRuleVisualizePlugin.class.getName()); for (int i = 0; i < pluginsVector.size(); i++) { String className = (pluginsVector.get(i)); try { AssociationRuleVisualizePlugin plugin = (AssociationRuleVisualizePlugin) WekaPackageClassLoaderManager.objectForName(className); //Class.forName(className).newInstance(); if (plugin == null) { continue; } availablePlugins = true; JMenuItem pluginMenuItem = plugin.getVisualizeMenuItem((AssociationRules) o, selectedNames.get(0)); if (pluginMenuItem != null) { visPlugins.add(pluginMenuItem); } } catch (Exception ex) { // ex.printStackTrace(); } } } else if (o instanceof String) { List<String> pluginsVector = PluginManager.getPluginNamesOfTypeList(TreeVisualizePlugin.class.getName()); for (int i = 0; i < pluginsVector.size(); i++) { String className = (pluginsVector.get(i)); try { TreeVisualizePlugin plugin = (TreeVisualizePlugin) WekaPackageClassLoaderManager.objectForName(className); // Class.forName(className).newInstance(); if (plugin == null) { continue; } availablePlugins = true; JMenuItem pluginMenuItem = plugin.getVisualizeMenuItem((String) o, selectedNames.get(0)); // Version version = new Version(); if (pluginMenuItem != null) { /* * if (version.compareTo(plugin.getMinVersion()) < 0) * pluginMenuItem.setText(pluginMenuItem.getText() + * " (weka outdated)"); if * (version.compareTo(plugin.getMaxVersion()) >= 0) * pluginMenuItem.setText(pluginMenuItem.getText() + * " (plugin outdated)"); */ visPlugins.add(pluginMenuItem); } } catch (Exception e) { // e.printStackTrace(); } } } } } if (availablePlugins) { resultListMenu.add(visPlugins); } resultListMenu.show(m_History.getList(), x, y); } /** * updates the capabilities filter of the GOE * * @param filter the new filter to use */ protected void updateCapabilitiesFilter(Capabilities filter) { Instances tempInst; Capabilities filterClass; if (filter == null) { m_AssociatorEditor.setCapabilitiesFilter(new Capabilities(null)); return; } if (!ExplorerDefaults.getInitGenericObjectEditorFilter()) { tempInst = new Instances(m_Instances, 0); } else { tempInst = new Instances(m_Instances); } tempInst.setClassIndex(-1); try { filterClass = Capabilities.forInstances(tempInst); } catch (Exception e) { filterClass = new Capabilities(null); } m_AssociatorEditor.setCapabilitiesFilter(filterClass); m_StartBut.setEnabled(true); // Check capabilities Capabilities currentFilter = m_AssociatorEditor.getCapabilitiesFilter(); Associator associator = (Associator) m_AssociatorEditor.getValue(); Capabilities currentSchemeCapabilities = null; if (associator != null && currentFilter != null && (associator instanceof CapabilitiesHandler)) { currentSchemeCapabilities = ((CapabilitiesHandler) associator).getCapabilities(); if (!currentSchemeCapabilities.supportsMaybe(currentFilter) && !currentSchemeCapabilities.supports(currentFilter)) { m_StartBut.setEnabled(false); } } } /** * method gets called in case of a change event * * @param e the associated change event */ @Override public void capabilitiesFilterChanged(CapabilitiesFilterChangeEvent e) { if (e.getFilter() == null) { updateCapabilitiesFilter(null); } else { updateCapabilitiesFilter((Capabilities) e.getFilter().clone()); } } /** * Sets the Explorer to use as parent frame (used for sending notifications * about changes in the data) * * @param parent the parent frame */ @Override public void setExplorer(Explorer parent) { m_Explorer = parent; } /** * returns the parent Explorer frame * * @return the parent */ @Override public Explorer getExplorer() { return m_Explorer; } /** * Returns the title for the tab in the Explorer * * @return the title of this tab */ @Override public String getTabTitle() { return "Associate"; } /** * Returns the tooltip for the tab in the Explorer * * @return the tooltip of this tab */ @Override public String getTabTitleToolTip() { return "Discover association rules"; } @Override public boolean requiresLog() { return true; } @Override public boolean acceptsInstances() { return true; } @Override public Defaults getDefaultSettings() { return new AssociationsPanelDefaults(); } @Override public boolean okToBeActive() { return m_Instances != null; } public void setActive(boolean active) { super.setActive(active); if (m_isActive) { // make sure initial settings get applied settingsChanged(); } } @Override public void settingsChanged() { if (getMainApplication() != null) { if (!m_initialSettingsSet) { m_initialSettingsSet = true; Object initialA = getMainApplication().getApplicationSettings().getSetting( getPerspectiveID(), AssociationsPanelDefaults.ASSOCIATOR_KEY, AssociationsPanelDefaults.ASSOCIATOR, Environment.getSystemWide()); m_AssociatorEditor.setValue(initialA); } Font outputFont = getMainApplication().getApplicationSettings().getSetting( getPerspectiveID(), AssociationsPanelDefaults.OUTPUT_FONT_KEY, AssociationsPanelDefaults.OUTPUT_FONT, Environment.getSystemWide()); m_OutText.setFont(outputFont); Color textColor = getMainApplication().getApplicationSettings().getSetting( getPerspectiveID(), AssociationsPanelDefaults.OUTPUT_TEXT_COLOR_KEY, AssociationsPanelDefaults.OUTPUT_TEXT_COLOR, Environment.getSystemWide()); m_OutText.setForeground(textColor); Color outputBackgroundColor = getMainApplication().getApplicationSettings().getSetting( getPerspectiveID(), AssociationsPanelDefaults.OUTPUT_BACKGROUND_COLOR_KEY, AssociationsPanelDefaults.OUTPUT_BACKGROUND_COLOR, Environment.getSystemWide()); m_OutText.setBackground(outputBackgroundColor); m_History.setBackground(outputBackgroundColor); } } /** * Default settings for the associations panel */ protected static final class AssociationsPanelDefaults extends Defaults { public static final String ID = "weka.gui.explorer.associationspanel"; protected static final Settings.SettingKey ASSOCIATOR_KEY = new Settings.SettingKey(ID + ".initialAssociator", "Initial associator", "On startup, set this associator as the default one"); protected static final Associator ASSOCIATOR = new FPGrowth(); protected static final Settings.SettingKey OUTPUT_FONT_KEY = new Settings.SettingKey(ID + ".outputFont", "Font for text output", "Font to " + "use in the output area"); protected static final Font OUTPUT_FONT = new Font("Monospaced", Font.PLAIN, 12); protected static final Settings.SettingKey OUTPUT_TEXT_COLOR_KEY = new Settings.SettingKey(ID + ".outputFontColor", "Output text color", "Color " + "of output text"); protected static final Color OUTPUT_TEXT_COLOR = Color.black; protected static final Settings.SettingKey OUTPUT_BACKGROUND_COLOR_KEY = new Settings.SettingKey(ID + ".outputBackgroundColor", "Output background color", "Output background color"); protected static final Color OUTPUT_BACKGROUND_COLOR = Color.white; private static final long serialVersionUID = 1108450683775771792L; public AssociationsPanelDefaults() { super(ID); m_defaults.put(ASSOCIATOR_KEY, ASSOCIATOR); m_defaults.put(OUTPUT_FONT_KEY, OUTPUT_FONT); m_defaults.put(OUTPUT_TEXT_COLOR_KEY, OUTPUT_TEXT_COLOR); m_defaults.put(OUTPUT_BACKGROUND_COLOR_KEY, OUTPUT_BACKGROUND_COLOR); } } /** * Tests out the Associator panel from the command line. * * @param args may optionally contain the name of a dataset to load. */ public static void main(String[] args) { try { final javax.swing.JFrame jf = new javax.swing.JFrame("Weka Explorer: Associator"); jf.getContentPane().setLayout(new BorderLayout()); final AssociationsPanel sp = new AssociationsPanel(); jf.getContentPane().add(sp, BorderLayout.CENTER); weka.gui.LogPanel lp = new weka.gui.LogPanel(); sp.setLog(lp); jf.getContentPane().add(lp, BorderLayout.SOUTH); 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); if (args.length == 1) { System.err.println("Loading instances from " + args[0]); java.io.Reader r = new java.io.BufferedReader(new java.io.FileReader(args[0])); Instances i = new Instances(r); sp.setInstances(i); } } 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/explorer/AttributeSelectionPanel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * AttributeSelectionPanel.java * Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.explorer; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.GridLayout; import java.awt.Insets; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.InputEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.BufferedWriter; import java.io.FileWriter; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Random; import java.util.Vector; import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import weka.attributeSelection.ASEvaluation; import weka.attributeSelection.ASSearch; import weka.attributeSelection.AttributeEvaluator; import weka.attributeSelection.AttributeSelection; import weka.attributeSelection.AttributeTransformer; import weka.attributeSelection.BestFirst; import weka.attributeSelection.CfsSubsetEval; import weka.attributeSelection.Ranker; import weka.core.Attribute; import weka.core.Capabilities; import weka.core.CapabilitiesHandler; import weka.core.Defaults; import weka.core.Environment; import weka.core.Instances; import weka.core.OptionHandler; import weka.core.Settings; import weka.core.Utils; import weka.gui.AbstractPerspective; import weka.gui.ExtensionFileFilter; import weka.gui.GenericObjectEditor; import weka.gui.Logger; import weka.gui.PerspectiveInfo; import weka.gui.PropertyPanel; import weka.gui.ResultHistoryPanel; import weka.gui.SaveBuffer; import weka.gui.SysErrLog; import weka.gui.TaskLogger; import weka.gui.explorer.Explorer.CapabilitiesFilterChangeEvent; import weka.gui.explorer.Explorer.CapabilitiesFilterChangeListener; import weka.gui.explorer.Explorer.ExplorerPanel; import weka.gui.explorer.Explorer.LogHandler; import weka.gui.visualize.MatrixPanel; /** * This panel allows the user to select and configure an attribute evaluator and * a search method, set the attribute of the current dataset to be used as the * class, and perform attribute selection using one of two selection modes * (select using all the training data or perform a n-fold cross validation---on * each trial selecting features using n-1 folds of the data). The results of * attribute selection runs are stored in a results history so that previous * results are accessible. * * @author Mark Hall (mhall@cs.waikato.ac.nz) * @version $Revision$ */ @PerspectiveInfo(ID = "weka.gui.explorer.attributeselectionpanel", title = "Select attributes", toolTipText = "Determine relevance of attributes", iconPath = "weka/gui/weka_icon_new_small.png") public class AttributeSelectionPanel extends AbstractPerspective implements CapabilitiesFilterChangeListener, ExplorerPanel, LogHandler { /** for serialization */ static final long serialVersionUID = 5627185966993476142L; /** the parent frame */ protected Explorer m_Explorer = null; /** Lets the user configure the attribute evaluator */ protected GenericObjectEditor m_AttributeEvaluatorEditor = new GenericObjectEditor(); /** Lets the user configure the search method */ protected GenericObjectEditor m_AttributeSearchEditor = new GenericObjectEditor(); /** The panel showing the current attribute evaluation method */ protected PropertyPanel m_AEEPanel = new PropertyPanel( m_AttributeEvaluatorEditor); /** The panel showing the current search method */ protected PropertyPanel m_ASEPanel = new PropertyPanel( m_AttributeSearchEditor); /** The output area for attribute selection results */ protected JTextArea m_OutText = new JTextArea(20, 40); /** The destination for log/status messages */ protected Logger m_Log = new SysErrLog(); /** The buffer saving object for saving output */ SaveBuffer m_SaveOut = new SaveBuffer(m_Log, this); /** A panel controlling results viewing */ protected ResultHistoryPanel m_History = new ResultHistoryPanel(m_OutText); /** Lets the user select the class column */ protected JComboBox m_ClassCombo = new JComboBox(); /** Click to set evaluation mode to cross-validation */ protected JRadioButton m_CVBut = new JRadioButton("Cross-validation"); /** Click to set test mode to test on training data */ protected JRadioButton m_TrainBut = new JRadioButton("Use full training set"); /** Label by where the cv folds are entered */ protected JLabel m_CVLab = new JLabel("Folds", SwingConstants.RIGHT); /** The field where the cv folds are entered */ protected JTextField m_CVText = new JTextField("10"); /** Label by where cv random seed is entered */ protected JLabel m_SeedLab = new JLabel("Seed", SwingConstants.RIGHT); /** The field where the seed value is entered */ protected JTextField m_SeedText = new JTextField("1"); /** * Alters the enabled/disabled status of elements associated with each radio * button */ ActionListener m_RadioListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { updateRadioLinks(); } }; /** Click to start running the attribute selector */ protected JButton m_StartBut = new JButton("Start"); /** Click to stop a running classifier */ protected JButton m_StopBut = new JButton("Stop"); /** Stop the class combo from taking up to much space */ private final Dimension COMBO_SIZE = new Dimension(150, m_StartBut.getPreferredSize().height); /** The main set of instances we're playing with */ protected Instances m_Instances; /** A thread that attribute selection runs in */ protected Thread m_RunThread; /** True if startup settings have been applied */ protected boolean m_initialSettingsSet; /* Register the property editors we need */ static { GenericObjectEditor.registerEditors(); } /** * Creates the classifier panel */ public AttributeSelectionPanel() { // Connect / configure the components m_OutText.setEditable(false); m_OutText.setFont(new Font("Monospaced", Font.PLAIN, 12)); m_OutText.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); m_OutText.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if ((e.getModifiers() & InputEvent.BUTTON1_MASK) != InputEvent.BUTTON1_MASK) { m_OutText.selectAll(); } } }); JPanel historyHolder = new JPanel(new BorderLayout()); historyHolder.setBorder(BorderFactory .createTitledBorder("Result list (right-click for options)")); historyHolder.add(m_History, BorderLayout.CENTER); m_AttributeEvaluatorEditor.setClassType(ASEvaluation.class); m_AttributeEvaluatorEditor.setValue(ExplorerDefaults.getASEvaluator()); m_AttributeEvaluatorEditor .addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent e) { if (m_AttributeEvaluatorEditor.getValue() instanceof AttributeEvaluator) { if (!(m_AttributeSearchEditor.getValue() instanceof Ranker)) { Object backup = m_AttributeEvaluatorEditor.getBackup(); int result = JOptionPane.showConfirmDialog(null, "You must use use the Ranker search method " + "in order to use\n" + m_AttributeEvaluatorEditor.getValue().getClass() .getName() + ".\nShould I select the Ranker search method for you?", "Alert!", JOptionPane.YES_NO_OPTION); if (result == JOptionPane.YES_OPTION) { m_AttributeSearchEditor.setValue(new Ranker()); } else { // restore to what was there previously (if possible) if (backup != null) { m_AttributeEvaluatorEditor.setValue(backup); } } } } else { if (m_AttributeSearchEditor.getValue() instanceof Ranker) { Object backup = m_AttributeEvaluatorEditor.getBackup(); int result = JOptionPane .showConfirmDialog( null, "You must use use a search method that explores \n" + "the space of attribute subsets (such as GreedyStepwise) in " + "order to use\n" + m_AttributeEvaluatorEditor.getValue().getClass() .getName() + ".\nShould I select the GreedyStepwise search method for " + "you?\n(you can always switch to a different method afterwards)", "Alert!", JOptionPane.YES_NO_OPTION); if (result == JOptionPane.YES_OPTION) { m_AttributeSearchEditor .setValue(new weka.attributeSelection.GreedyStepwise()); } else { // restore to what was there previously (if possible) if (backup != null) { m_AttributeEvaluatorEditor.setValue(backup); } } } } updateRadioLinks(); m_StartBut.setEnabled(true); // check capabilities... Capabilities currentFilter = m_AttributeEvaluatorEditor.getCapabilitiesFilter(); ASEvaluation evaluator = (ASEvaluation) m_AttributeEvaluatorEditor.getValue(); Capabilities currentSchemeCapabilities = null; if (evaluator != null && currentFilter != null && (evaluator instanceof CapabilitiesHandler)) { currentSchemeCapabilities = ((CapabilitiesHandler) evaluator).getCapabilities(); if (!currentSchemeCapabilities.supportsMaybe(currentFilter) && !currentSchemeCapabilities.supports(currentFilter)) { m_StartBut.setEnabled(false); } } repaint(); } }); m_AttributeSearchEditor.setClassType(ASSearch.class); m_AttributeSearchEditor.setValue(ExplorerDefaults.getASSearch()); m_AttributeSearchEditor .addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent e) { if (m_AttributeSearchEditor.getValue() instanceof Ranker) { if (!(m_AttributeEvaluatorEditor.getValue() instanceof AttributeEvaluator)) { Object backup = m_AttributeSearchEditor.getBackup(); int result = JOptionPane .showConfirmDialog( null, "You must use use an evaluator that evaluates\n" + "single attributes (such as InfoGain) in order to use\n" + "the Ranker. Should I select the InfoGain evaluator " + "for you?\n" + "(You can always switch to a different method afterwards)", "Alert!", JOptionPane.YES_NO_OPTION); if (result == JOptionPane.YES_OPTION) { m_AttributeEvaluatorEditor .setValue(new weka.attributeSelection.InfoGainAttributeEval()); } else { // restore to what was there previously (if possible) if (backup != null) { m_AttributeSearchEditor.setValue(backup); } } } } else { if (m_AttributeEvaluatorEditor.getValue() instanceof AttributeEvaluator) { Object backup = m_AttributeSearchEditor.getBackup(); int result = JOptionPane .showConfirmDialog( null, "You must use use an evaluator that evaluates\n" + "subsets of attributes (such as CFS) in order to use\n" + m_AttributeEvaluatorEditor.getValue().getClass() .getName() + ".\nShould I select the CFS subset evaluator for you?" + "\n(you can always switch to a different method afterwards)", "Alert!", JOptionPane.YES_NO_OPTION); if (result == JOptionPane.YES_OPTION) { m_AttributeEvaluatorEditor .setValue(new weka.attributeSelection.CfsSubsetEval()); } else { // restore to what was there previously (if possible) if (backup != null) { m_AttributeSearchEditor.setValue(backup); } } } } repaint(); } }); m_ClassCombo.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { updateCapabilitiesFilter(m_AttributeEvaluatorEditor .getCapabilitiesFilter()); } }); m_ClassCombo.setToolTipText("Select the attribute to use as the class"); m_TrainBut.setToolTipText("select attributes using the full training " + "dataset"); m_CVBut.setToolTipText("Perform a n-fold cross-validation"); m_StartBut.setToolTipText("Starts attribute selection"); m_StopBut.setToolTipText("Stops a attribute selection task"); m_ClassCombo.setPreferredSize(COMBO_SIZE); m_ClassCombo.setMaximumSize(COMBO_SIZE); m_ClassCombo.setMinimumSize(COMBO_SIZE); m_History.setPreferredSize(COMBO_SIZE); m_History.setMaximumSize(COMBO_SIZE); m_History.setMinimumSize(COMBO_SIZE); m_ClassCombo.setEnabled(false); m_TrainBut.setSelected(ExplorerDefaults.getASTestMode() == 0); m_CVBut.setSelected(ExplorerDefaults.getASTestMode() == 1); updateRadioLinks(); ButtonGroup bg = new ButtonGroup(); bg.add(m_TrainBut); bg.add(m_CVBut); m_TrainBut.addActionListener(m_RadioListener); m_CVBut.addActionListener(m_RadioListener); m_CVText.setText("" + ExplorerDefaults.getASCrossvalidationFolds()); m_SeedText.setText("" + ExplorerDefaults.getASRandomSeed()); m_StartBut.setEnabled(false); m_StopBut.setEnabled(false); m_StartBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { boolean proceed = true; if (Explorer.m_Memory.memoryIsLow()) { proceed = Explorer.m_Memory.showMemoryIsLow(); } if (proceed) { startAttributeSelection(); } } }); m_StopBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { stopAttributeSelection(); } }); m_History.setHandleRightClicks(false); // see if we can popup a menu for the selected result m_History.getList().addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (((e.getModifiers() & InputEvent.BUTTON1_MASK) != InputEvent.BUTTON1_MASK) || e.isAltDown()) { int index = m_History.getList().locationToIndex(e.getPoint()); if (index != -1) { List<String> selectedEls = (List<String>) m_History.getList().getSelectedValuesList(); visualize(selectedEls, e.getX(), e.getY()); } else { visualize(null, e.getX(), e.getY()); } } } }); // Layout the GUI JPanel p1 = new JPanel(); p1.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createTitledBorder("Attribute Evaluator"), BorderFactory.createEmptyBorder(0, 5, 5, 5))); p1.setLayout(new BorderLayout()); p1.add(m_AEEPanel, BorderLayout.NORTH); JPanel p1_1 = new JPanel(); p1_1.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createTitledBorder("Search Method"), BorderFactory.createEmptyBorder(0, 5, 5, 5))); p1_1.setLayout(new BorderLayout()); p1_1.add(m_ASEPanel, BorderLayout.NORTH); JPanel p_new = new JPanel(); p_new.setLayout(new BorderLayout()); p_new.add(p1, BorderLayout.NORTH); p_new.add(p1_1, BorderLayout.CENTER); JPanel p2 = new JPanel(); GridBagLayout gbL = new GridBagLayout(); p2.setLayout(gbL); p2.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createTitledBorder("Attribute Selection Mode"), BorderFactory.createEmptyBorder(0, 5, 5, 5))); GridBagConstraints gbC = new GridBagConstraints(); gbC.anchor = GridBagConstraints.WEST; gbC.gridy = 2; gbC.gridx = 0; gbL.setConstraints(m_TrainBut, gbC); p2.add(m_TrainBut); gbC = new GridBagConstraints(); gbC.anchor = GridBagConstraints.WEST; gbC.gridy = 4; gbC.gridx = 0; gbL.setConstraints(m_CVBut, gbC); p2.add(m_CVBut); gbC = new GridBagConstraints(); gbC.anchor = GridBagConstraints.EAST; gbC.fill = GridBagConstraints.HORIZONTAL; gbC.gridy = 4; gbC.gridx = 1; gbC.insets = new Insets(2, 10, 2, 10); gbL.setConstraints(m_CVLab, gbC); p2.add(m_CVLab); gbC = new GridBagConstraints(); gbC.anchor = GridBagConstraints.EAST; gbC.fill = GridBagConstraints.HORIZONTAL; gbC.gridy = 4; gbC.gridx = 2; gbC.weightx = 100; gbC.ipadx = 20; gbL.setConstraints(m_CVText, gbC); p2.add(m_CVText); gbC = new GridBagConstraints(); gbC.anchor = GridBagConstraints.EAST; gbC.fill = GridBagConstraints.HORIZONTAL; gbC.gridy = 6; gbC.gridx = 1; gbC.insets = new Insets(2, 10, 2, 10); gbL.setConstraints(m_SeedLab, gbC); p2.add(m_SeedLab); gbC = new GridBagConstraints(); gbC.anchor = GridBagConstraints.EAST; gbC.fill = GridBagConstraints.HORIZONTAL; gbC.gridy = 6; gbC.gridx = 2; gbC.weightx = 100; gbC.ipadx = 20; gbL.setConstraints(m_SeedText, gbC); p2.add(m_SeedText); JPanel buttons = new JPanel(); buttons.setLayout(new GridLayout(2, 2)); buttons.add(m_ClassCombo); m_ClassCombo.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); JPanel ssButs = new JPanel(); ssButs.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); ssButs.setLayout(new GridLayout(1, 2, 5, 5)); ssButs.add(m_StartBut); ssButs.add(m_StopBut); buttons.add(ssButs); JPanel p3 = new JPanel(); p3.setBorder(BorderFactory.createTitledBorder("Attribute selection output")); p3.setLayout(new BorderLayout()); final JScrollPane js = new JScrollPane(m_OutText); p3.add(js, BorderLayout.CENTER); js.getViewport().addChangeListener(new ChangeListener() { private int lastHeight; @Override public void stateChanged(ChangeEvent e) { JViewport vp = (JViewport) e.getSource(); int h = vp.getViewSize().height; if (h != lastHeight) { // i.e. an addition not just a user scrolling lastHeight = h; int x = h - vp.getExtentSize().height; vp.setViewPosition(new Point(0, x)); } } }); JPanel mondo = new JPanel(); gbL = new GridBagLayout(); mondo.setLayout(gbL); gbC = new GridBagConstraints(); gbC.fill = GridBagConstraints.HORIZONTAL; gbC.gridy = 0; gbC.gridx = 0; gbC.weightx = 0; gbL.setConstraints(p2, gbC); mondo.add(p2); gbC = new GridBagConstraints(); gbC.anchor = GridBagConstraints.NORTH; gbC.fill = GridBagConstraints.HORIZONTAL; gbC.gridy = 1; gbC.gridx = 0; gbC.weightx = 0; gbL.setConstraints(buttons, gbC); mondo.add(buttons); gbC = new GridBagConstraints(); gbC.fill = GridBagConstraints.BOTH; gbC.gridy = 2; gbC.gridx = 0; gbC.weightx = 0; gbC.weighty = 100; gbL.setConstraints(historyHolder, gbC); mondo.add(historyHolder); gbC = new GridBagConstraints(); gbC.fill = GridBagConstraints.BOTH; gbC.gridy = 0; gbC.gridx = 1; gbC.gridheight = 3; gbC.weightx = 100; gbC.weighty = 100; gbL.setConstraints(p3, gbC); mondo.add(p3); setLayout(new BorderLayout()); add(p_new, BorderLayout.NORTH); add(mondo, BorderLayout.CENTER); } /** * Updates the enabled status of the input fields and labels. */ protected void updateRadioLinks() { m_CVBut.setEnabled(true); m_CVText.setEnabled(m_CVBut.isSelected()); m_CVLab.setEnabled(m_CVBut.isSelected()); m_SeedText.setEnabled(m_CVBut.isSelected()); m_SeedLab.setEnabled(m_CVBut.isSelected()); if (m_AttributeEvaluatorEditor.getValue() instanceof AttributeTransformer) { m_CVBut.setSelected(false); m_CVBut.setEnabled(false); m_CVText.setEnabled(false); m_CVLab.setEnabled(false); m_SeedText.setEnabled(false); m_SeedLab.setEnabled(false); m_TrainBut.setSelected(true); } } /** * Sets the Logger to receive informational messages * * @param newLog the Logger that will now get info messages */ @Override public void setLog(Logger newLog) { m_Log = newLog; } /** * Tells the panel to use a new set of instances. * * @param inst a set of Instances */ @Override public void setInstances(Instances inst) { m_Instances = inst; String[] attribNames = new String[m_Instances.numAttributes() + 1]; attribNames[0] = "No class"; for (int i = 0; i < inst.numAttributes(); i++) { String type = "(" + Attribute.typeToStringShort(m_Instances.attribute(i)) + ") "; String attnm = m_Instances.attribute(i).name(); attribNames[i + 1] = type + attnm; } m_StartBut.setEnabled(m_RunThread == null); m_StopBut.setEnabled(m_RunThread != null); m_ClassCombo.setModel(new DefaultComboBoxModel(attribNames)); if (inst.classIndex() == -1) { m_ClassCombo.setSelectedIndex(attribNames.length - 1); } else { m_ClassCombo.setSelectedIndex(inst.classIndex()); } m_ClassCombo.setEnabled(true); } /** * Starts running the currently configured attribute evaluator and search * method. This is run in a separate thread, and will only start if there is * no attribute selection already running. The attribute selection output is * sent to the results history panel. */ protected void startAttributeSelection() { if (m_RunThread == null) { m_StartBut.setEnabled(false); m_StopBut.setEnabled(true); m_RunThread = new Thread() { @Override public void run() { m_AEEPanel.addToHistory(); m_ASEPanel.addToHistory(); // Copy the current state of things m_Log.statusMessage("Setting up..."); Instances inst = new Instances(m_Instances); int testMode = 0; int numFolds = 10; int seed = 1; int classIndex = m_ClassCombo.getSelectedIndex() - 1; ASEvaluation evaluator = (ASEvaluation) m_AttributeEvaluatorEditor.getValue(); ASSearch search = (ASSearch) m_AttributeSearchEditor.getValue(); StringBuffer outBuff = new StringBuffer(); String name = (new SimpleDateFormat("HH:mm:ss - ")).format(new Date()); String sname = search.getClass().getName(); if (sname.startsWith("weka.attributeSelection.")) { name += sname.substring("weka.attributeSelection.".length()); } else { name += sname; } String ename = evaluator.getClass().getName(); if (ename.startsWith("weka.attributeSelection.")) { name += (" + " + ename.substring("weka.attributeSelection.".length())); } else { name += (" + " + ename); } // assemble commands String cmd; String cmdFilter; String cmdClassifier; // 1. attribute selection command Vector<String> list = new Vector<String>(); list.add("-s"); if (search instanceof OptionHandler) { list.add(sname + " " + Utils.joinOptions(((OptionHandler) search).getOptions())); } else { list.add(sname); } if (evaluator instanceof OptionHandler) { String[] opt = ((OptionHandler) evaluator).getOptions(); for (String element : opt) { list.add(element); } } cmd = ename + " " + Utils.joinOptions(list.toArray(new String[list.size()])); // 2. filter command weka.filters.supervised.attribute.AttributeSelection filter = new weka.filters.supervised.attribute.AttributeSelection(); filter.setEvaluator((ASEvaluation) m_AttributeEvaluatorEditor .getValue()); filter.setSearch((ASSearch) m_AttributeSearchEditor.getValue()); cmdFilter = filter.getClass().getName() + " " + Utils.joinOptions(((OptionHandler) filter).getOptions()); // 3. meta-classifier command weka.classifiers.meta.AttributeSelectedClassifier cls = new weka.classifiers.meta.AttributeSelectedClassifier(); cls .setEvaluator((ASEvaluation) m_AttributeEvaluatorEditor.getValue()); cls.setSearch((ASSearch) m_AttributeSearchEditor.getValue()); cmdClassifier = cls.getClass().getName() + " " + Utils.joinOptions(cls.getOptions()); AttributeSelection eval = null; try { if (m_CVBut.isSelected()) { testMode = 1; numFolds = Integer.parseInt(m_CVText.getText()); seed = Integer.parseInt(m_SeedText.getText()); if (numFolds <= 1) { throw new Exception("Number of folds must be greater than 1"); } } if (classIndex >= 0) { inst.setClassIndex(classIndex); } // Output some header information m_Log.logMessage("Started " + ename); m_Log.logMessage("Command: " + cmd); m_Log.logMessage("Filter command: " + cmdFilter); m_Log.logMessage("Meta-classifier command: " + cmdClassifier); if (m_Log instanceof TaskLogger) { ((TaskLogger) m_Log).taskStarted(); } outBuff.append("=== Run information ===\n\n"); outBuff.append("Evaluator: " + ename); if (evaluator instanceof OptionHandler) { String[] o = ((OptionHandler) evaluator).getOptions(); outBuff.append(" " + Utils.joinOptions(o)); } outBuff.append("\nSearch: " + sname); if (search instanceof OptionHandler) { String[] o = ((OptionHandler) search).getOptions(); outBuff.append(" " + Utils.joinOptions(o)); } outBuff.append("\n"); outBuff.append("Relation: " + inst.relationName() + '\n'); outBuff.append("Instances: " + inst.numInstances() + '\n'); outBuff.append("Attributes: " + inst.numAttributes() + '\n'); if (inst.numAttributes() < 100) { for (int i = 0; i < inst.numAttributes(); i++) { outBuff.append(" " + inst.attribute(i).name() + '\n'); } } else { outBuff.append(" [list of attributes omitted]\n"); } outBuff.append("Evaluation mode: "); switch (testMode) { case 0: // select using all training outBuff.append("evaluate on all training data\n"); break; case 1: // CV mode outBuff.append("" + numFolds + "-fold cross-validation\n"); break; } outBuff.append("\n"); m_History.addResult(name, outBuff); m_History.setSingle(name); // Do the feature selection and output the results. m_Log.statusMessage("Doing feature selection..."); m_History.updateResult(name); eval = new AttributeSelection(); eval.setEvaluator(evaluator); eval.setSearch(search); eval.setFolds(numFolds); eval.setSeed(seed); if (testMode == 1) { eval.setXval(true); } switch (testMode) { case 0: // select using training m_Log.statusMessage("Evaluating on training data..."); eval.SelectAttributes(inst); break; case 1: // CV mode m_Log.statusMessage("Randomizing instances..."); Random random = new Random(seed); inst.randomize(random); if (inst.attribute(classIndex).isNominal()) { m_Log.statusMessage("Stratifying instances..."); inst.stratify(numFolds); } for (int fold = 0; fold < numFolds; fold++) { m_Log.statusMessage("Creating splits for fold " + (fold + 1) + "..."); Instances train = inst.trainCV(numFolds, fold, random); m_Log.statusMessage("Selecting attributes using all but fold " + (fold + 1) + "..."); eval.selectAttributesCVSplit(train); } break; default: throw new Exception("Test mode not implemented"); } if (testMode == 0) { outBuff.append(eval.toResultsString()); } else { outBuff.append(eval.CVResultsString()); } outBuff.append("\n"); m_History.updateResult(name); m_Log.logMessage("Finished " + ename + " " + sname); m_Log.statusMessage("OK"); } catch (Exception ex) { m_Log.logMessage(ex.getMessage()); m_Log.statusMessage("See error log"); } finally { ArrayList<Object> vv = new ArrayList<Object>(); Vector<Object> configHolder = new Vector<Object>(); try { ASEvaluation eval_copy = evaluator.getClass().newInstance(); if (evaluator instanceof OptionHandler) { ((OptionHandler) eval_copy) .setOptions(((OptionHandler) evaluator).getOptions()); } ASSearch search_copy = search.getClass().newInstance(); if (search instanceof OptionHandler) { ((OptionHandler) search_copy) .setOptions(((OptionHandler) search).getOptions()); } configHolder.add(eval_copy); configHolder.add(search_copy); } catch (Exception ex) { configHolder.add(evaluator); configHolder.add(search); } vv.add(configHolder); if (evaluator instanceof AttributeTransformer) { try { Instances transformed = ((AttributeTransformer) evaluator).transformedData(inst); transformed .setRelationName("AT: " + transformed.relationName()); vv.add(transformed); m_History.addObject(name, vv); } catch (Exception ex) { System.err.println(ex); ex.printStackTrace(); } } else if (testMode == 0) { try { Instances reducedInst = eval.reduceDimensionality(inst); vv.add(reducedInst); m_History.addObject(name, vv); } catch (Exception ex) { ex.printStackTrace(); } } if (isInterrupted()) { m_Log.logMessage("Interrupted " + ename + " " + sname); m_Log.statusMessage("See error log"); } m_RunThread = null; m_StartBut.setEnabled(true); m_StopBut.setEnabled(false); if (m_Log instanceof TaskLogger) { ((TaskLogger) m_Log).taskFinished(); } } } }; m_RunThread.setPriority(Thread.MIN_PRIORITY); m_RunThread.start(); } } /** * Stops the currently running attribute selection (if any). */ @SuppressWarnings("deprecation") protected void stopAttributeSelection() { if (m_RunThread != null) { m_RunThread.interrupt(); // This is deprecated (and theoretically the interrupt should do). m_RunThread.stop(); } } /** * Save the named buffer to a file. * * @param name the name of the buffer to be saved. */ protected void saveBuffer(String name) { StringBuffer sb = m_History.getNamedBuffer(name); if (sb != null) { if (m_SaveOut.save(sb)) { m_Log.logMessage("Save succesful."); } } } /** * Popup a visualize panel for viewing transformed data * * @param ti the Instances to display */ protected void visualizeTransformedData(Instances ti) { if (ti != null) { MatrixPanel mp = new MatrixPanel(); mp.setInstances(ti); String plotName = ti.relationName(); final javax.swing.JFrame jf = Utils.getWekaJFrame("Weka Attribute Selection Visualize: " + plotName, this); jf.getContentPane().setLayout(new BorderLayout()); jf.getContentPane().add(mp, BorderLayout.CENTER); jf.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { jf.dispose(); } }); jf.pack(); jf.setSize(800, 600); jf.setLocationRelativeTo(SwingUtilities.getWindowAncestor(this)); jf.setVisible(true); } } /** * Popup a SaveDialog for saving the transformed data * * @param ti the Instances to display */ protected void saveTransformedData(Instances ti) { JFileChooser fc; int retVal; BufferedWriter writer; ExtensionFileFilter filter; fc = new JFileChooser(); filter = new ExtensionFileFilter(".arff", "ARFF data files"); fc.setFileFilter(filter); retVal = fc.showSaveDialog(this); if (retVal == JFileChooser.APPROVE_OPTION) { try { writer = new BufferedWriter(new FileWriter(fc.getSelectedFile())); writer.write(ti.toString()); writer.flush(); writer.close(); } catch (Exception e) { e.printStackTrace(); m_Log.logMessage("Problem saving data: " + e.getMessage()); JOptionPane.showMessageDialog(this, "Problem saving data:\n" + e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } } } /** * Handles constructing a popup menu with visualization options * * @param names the name of the result history list entry clicked on by the * user. * @param x the x coordinate for popping up the menu * @param y the y coordinate for popping up the menu */ @SuppressWarnings("unchecked") protected void visualize(List<String> names, int x, int y) { final List<String> selectedNames = names; JPopupMenu resultListMenu = new JPopupMenu(); JMenuItem visMainBuffer = new JMenuItem("View in main window"); if (selectedNames != null && selectedNames.size() == 1) { visMainBuffer.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m_History.setSingle(selectedNames.get(0)); } }); } else { visMainBuffer.setEnabled(false); } resultListMenu.add(visMainBuffer); JMenuItem visSepBuffer = new JMenuItem("View in separate window"); if (selectedNames != null && selectedNames.size() == 1) { visSepBuffer.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m_History.openFrame(selectedNames.get(0)); } }); } else { visSepBuffer.setEnabled(false); } resultListMenu.add(visSepBuffer); JMenuItem saveOutput = new JMenuItem("Save result buffer"); if (selectedNames != null && selectedNames.size() == 1) { saveOutput.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { saveBuffer(selectedNames.get(0)); } }); } else { saveOutput.setEnabled(false); } resultListMenu.add(saveOutput); JMenuItem deleteOutput = new JMenuItem("Delete result buffer(s)"); if (selectedNames != null) { deleteOutput.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m_History.removeResults(selectedNames); } }); } else { deleteOutput.setEnabled(false); } resultListMenu.add(deleteOutput); ArrayList<Object> o = null; if (selectedNames != null && selectedNames.size() == 1) { o = (ArrayList<Object>) m_History.getNamedObject(selectedNames.get(0)); } // VisualizePanel temp_vp = null; Instances tempTransformed = null; ASEvaluation temp_eval = null; ASSearch temp_search = null; if (o != null) { for (int i = 0; i < o.size(); i++) { Object temp = o.get(i); // if (temp instanceof VisualizePanel) { if (temp instanceof Instances) { // temp_vp = (VisualizePanel)temp; tempTransformed = (Instances) temp; } if (temp instanceof Vector) { temp_eval = (ASEvaluation) ((Vector<Object>) temp).get(0); temp_search = (ASSearch) ((Vector<Object>) temp).get(1); } } } final ASEvaluation eval = temp_eval; final ASSearch search = temp_search; // final VisualizePanel vp = temp_vp; final Instances ti = tempTransformed; JMenuItem visTrans = null; if (ti != null) { if (ti.relationName().startsWith("AT:")) { visTrans = new JMenuItem("Visualize transformed data"); } else { visTrans = new JMenuItem("Visualize reduced data"); } resultListMenu.addSeparator(); } // JMenuItem visTrans = new JMenuItem("Visualize transformed data"); if (ti != null && visTrans != null) { visTrans.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { visualizeTransformedData(ti); } }); } if (visTrans != null) { resultListMenu.add(visTrans); } JMenuItem saveTrans = null; if (ti != null) { if (ti.relationName().startsWith("AT:")) { saveTrans = new JMenuItem("Save transformed data..."); } else { saveTrans = new JMenuItem("Save reduced data..."); } } if (saveTrans != null) { saveTrans.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { saveTransformedData(ti); } }); resultListMenu.add(saveTrans); } JMenuItem reApplyConfig = new JMenuItem("Re-apply attribute selection configuration"); if (eval != null && search != null) { reApplyConfig.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m_AttributeEvaluatorEditor.setValue(eval); m_AttributeSearchEditor.setValue(search); } }); } else { reApplyConfig.setEnabled(false); } resultListMenu.add(reApplyConfig); resultListMenu.show(m_History.getList(), x, y); } /** * updates the capabilities filter of the GOE * * @param filter the new filter to use */ protected void updateCapabilitiesFilter(Capabilities filter) { Instances tempInst; Capabilities filterClass; if (filter == null) { m_AttributeEvaluatorEditor.setCapabilitiesFilter(new Capabilities(null)); m_AttributeSearchEditor.setCapabilitiesFilter(new Capabilities(null)); return; } if (!ExplorerDefaults.getInitGenericObjectEditorFilter()) { tempInst = new Instances(m_Instances, 0); } else { tempInst = new Instances(m_Instances); } int clIndex = m_ClassCombo.getSelectedIndex() - 1; if (clIndex >= 0) { tempInst.setClassIndex(clIndex); } try { filterClass = Capabilities.forInstances(tempInst); } catch (Exception e) { filterClass = new Capabilities(null); } // set new filter m_AttributeEvaluatorEditor.setCapabilitiesFilter(filterClass); m_AttributeSearchEditor.setCapabilitiesFilter(filterClass); m_StartBut.setEnabled(true); // check capabilities... Capabilities currentFilter = m_AttributeEvaluatorEditor.getCapabilitiesFilter(); ASEvaluation evaluator = (ASEvaluation) m_AttributeEvaluatorEditor.getValue(); Capabilities currentSchemeCapabilities = null; if (evaluator != null && currentFilter != null && (evaluator instanceof CapabilitiesHandler)) { currentSchemeCapabilities = ((CapabilitiesHandler) evaluator).getCapabilities(); if (!currentSchemeCapabilities.supportsMaybe(currentFilter) && !currentSchemeCapabilities.supports(currentFilter)) { m_StartBut.setEnabled(false); } } } /** * method gets called in case of a change event * * @param e the associated change event */ @Override public void capabilitiesFilterChanged(CapabilitiesFilterChangeEvent e) { if (e.getFilter() == null) { updateCapabilitiesFilter(null); } else { updateCapabilitiesFilter((Capabilities) e.getFilter().clone()); } } /** * Sets the Explorer to use as parent frame (used for sending notifications * about changes in the data) * * @param parent the parent frame */ @Override public void setExplorer(Explorer parent) { m_Explorer = parent; } /** * returns the parent Explorer frame * * @return the parent */ @Override public Explorer getExplorer() { return m_Explorer; } /** * Returns the title for the tab in the Explorer * * @return the title of this tab */ @Override public String getTabTitle() { return "Select attributes"; } /** * Returns the tooltip for the tab in the Explorer * * @return the tooltip of this tab */ @Override public String getTabTitleToolTip() { return "Determine relevance of attributes"; } @Override public boolean requiresLog() { return true; } @Override public boolean acceptsInstances() { return true; } @Override public Defaults getDefaultSettings() { return new AttributeSelectionPanelDefaults(); } @Override public boolean okToBeActive() { return m_Instances != null; } @Override public void setActive(boolean active) { super.setActive(active); if (m_isActive) { // make sure initial settings get applied settingsChanged(); } } @Override public void settingsChanged() { if (getMainApplication() != null) { if (!m_initialSettingsSet) { Object initialEval = getMainApplication().getApplicationSettings().getSetting( getPerspectiveID(), AttributeSelectionPanelDefaults.EVALUATOR_KEY, AttributeSelectionPanelDefaults.EVALUATOR, Environment.getSystemWide()); m_AttributeEvaluatorEditor.setValue(initialEval); Object initialSearch = getMainApplication().getApplicationSettings() .getSetting(getPerspectiveID(), AttributeSelectionPanelDefaults.SEARCH_KEY, AttributeSelectionPanelDefaults.SEARCH, Environment.getSystemWide()); m_AttributeSearchEditor.setValue(initialSearch); TestMode initialEvalMode = getMainApplication().getApplicationSettings().getSetting( getPerspectiveID(), AttributeSelectionPanelDefaults.EVAL_MODE_KEY, AttributeSelectionPanelDefaults.EVAL_MODE, Environment.getSystemWide()); m_TrainBut.setSelected(initialEvalMode == TestMode.TRAINING_SET); m_CVBut.setSelected(initialEvalMode == TestMode.CROSS_VALIDATION); int folds = getMainApplication().getApplicationSettings().getSetting( getPerspectiveID(), AttributeSelectionPanelDefaults.FOLDS_KEY, AttributeSelectionPanelDefaults.FOLDS, Environment.getSystemWide()); m_CVText.setText("" + folds); int seed = getMainApplication().getApplicationSettings().getSetting( getPerspectiveID(), AttributeSelectionPanelDefaults.SEED_KEY, AttributeSelectionPanelDefaults.SEED, Environment.getSystemWide()); m_SeedText.setText("" + seed); updateRadioLinks(); m_initialSettingsSet = true; } Font outputFont = getMainApplication().getApplicationSettings().getSetting( getPerspectiveID(), AttributeSelectionPanelDefaults.OUTPUT_FONT_KEY, AttributeSelectionPanelDefaults.OUTPUT_FONT, Environment.getSystemWide()); m_OutText.setFont(outputFont); m_History.setFont(outputFont); Color textColor = getMainApplication().getApplicationSettings().getSetting( getPerspectiveID(), AttributeSelectionPanelDefaults.OUTPUT_TEXT_COLOR_KEY, AttributeSelectionPanelDefaults.OUTPUT_TEXT_COLOR, Environment.getSystemWide()); m_OutText.setForeground(textColor); m_History.setForeground(textColor); Color outputBackgroundColor = getMainApplication().getApplicationSettings().getSetting( getPerspectiveID(), AttributeSelectionPanelDefaults.OUTPUT_BACKGROUND_COLOR_KEY, AttributeSelectionPanelDefaults.OUTPUT_BACKGROUND_COLOR, Environment.getSystemWide()); m_OutText.setBackground(outputBackgroundColor); m_History.setBackground(outputBackgroundColor); } } public static enum TestMode { TRAINING_SET, CROSS_VALIDATION; } protected static final class AttributeSelectionPanelDefaults extends Defaults { public static final String ID = "weka.gui.explorer.attributeselectionpanel"; protected static final Settings.SettingKey EVALUATOR_KEY = new Settings.SettingKey(ID + ".initialEvaluator", "Initial evaluator", "On startup, set this evaluator as the default one"); protected static final ASEvaluation EVALUATOR = new CfsSubsetEval(); protected static final Settings.SettingKey SEARCH_KEY = new Settings.SettingKey(ID + ".initialSearch", "Initial search method", "On startup, set this search method as the default one"); protected static final ASSearch SEARCH = new BestFirst(); protected static final Settings.SettingKey EVAL_MODE_KEY = new Settings.SettingKey(ID + ".initialEvalMode", "Default evaluation mode", ""); protected static final TestMode EVAL_MODE = TestMode.TRAINING_SET; protected static final Settings.SettingKey FOLDS_KEY = new Settings.SettingKey(ID + ".xvalFolds", "Default cross-validation folds", ""); protected static final Integer FOLDS = 10; protected static final Settings.SettingKey SEED_KEY = new Settings.SettingKey(ID + ".seed", "Random seed", ""); protected static final Integer SEED = 1; protected static final Settings.SettingKey OUTPUT_FONT_KEY = new Settings.SettingKey(ID + ".outputFont", "Font for text output", "Font to " + "use in the output area"); protected static final Font OUTPUT_FONT = new Font("Monospaced", Font.PLAIN, 12); protected static final Settings.SettingKey OUTPUT_TEXT_COLOR_KEY = new Settings.SettingKey(ID + ".outputFontColor", "Output text color", "Color " + "of output text"); protected static final Color OUTPUT_TEXT_COLOR = Color.black; protected static final Settings.SettingKey OUTPUT_BACKGROUND_COLOR_KEY = new Settings.SettingKey(ID + ".outputBackgroundColor", "Output background color", "Output background color"); protected static final Color OUTPUT_BACKGROUND_COLOR = Color.white; private static final long serialVersionUID = -5413933415469545770L; public AttributeSelectionPanelDefaults() { super(ID); m_defaults.put(EVALUATOR_KEY, EVALUATOR); m_defaults.put(SEARCH_KEY, SEARCH); m_defaults.put(EVAL_MODE_KEY, EVAL_MODE); m_defaults.put(FOLDS_KEY, FOLDS); m_defaults.put(SEED_KEY, SEED); m_defaults.put(OUTPUT_FONT_KEY, OUTPUT_FONT); m_defaults.put(OUTPUT_TEXT_COLOR_KEY, OUTPUT_TEXT_COLOR); m_defaults.put(OUTPUT_BACKGROUND_COLOR_KEY, OUTPUT_BACKGROUND_COLOR); } } /** * Tests out the attribute selection panel from the command line. * * @param args may optionally contain the name of a dataset to load. */ public static void main(String[] args) { try { final javax.swing.JFrame jf = new javax.swing.JFrame("Weka Explorer: Select attributes"); jf.getContentPane().setLayout(new BorderLayout()); final AttributeSelectionPanel sp = new AttributeSelectionPanel(); jf.getContentPane().add(sp, BorderLayout.CENTER); weka.gui.LogPanel lp = new weka.gui.LogPanel(); sp.setLog(lp); jf.getContentPane().add(lp, BorderLayout.SOUTH); 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); if (args.length == 1) { System.err.println("Loading instances from " + args[0]); java.io.Reader r = new java.io.BufferedReader(new java.io.FileReader(args[0])); Instances i = new Instances(r); sp.setInstances(i); } } 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/explorer/ClassifierErrorsPlotInstances.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ClassifierErrorsPlotInstances.java * Copyright (C) 2009-2012 University of Waikato, Hamilton, New Zealand */ package weka.gui.explorer; import java.util.ArrayList; import weka.classifiers.Classifier; import weka.classifiers.Evaluation; import weka.classifiers.IntervalEstimator; import weka.classifiers.evaluation.NumericPrediction; import weka.classifiers.evaluation.Prediction; import weka.core.Attribute; import weka.core.DenseInstance; import weka.core.Instance; import weka.core.Instances; import weka.core.Utils; import weka.gui.visualize.Plot2D; import weka.gui.visualize.PlotData2D; /** * A class for generating plottable visualization errors. * <p/> * Example usage: * * <pre> * Instances train = ... // from somewhere * Instances test = ... // from somewhere * Classifier cls = ... // from somewhere * // build classifier * cls.buildClassifier(train); * // evaluate classifier and generate plot instances * ClassifierPlotInstances plotInstances = new ClassifierPlotInstances(); * plotInstances.setClassifier(cls); * plotInstances.setInstances(train); * plotInstances.setClassIndex(train.classIndex()); * plotInstances.setUp(); * Evaluation eval = new Evaluation(train); * for (int i = 0; i &lt; test.numInstances(); i++) * plotInstances.process(test.instance(i), cls, eval); * // generate visualization * VisualizePanel visPanel = new VisualizePanel(); * visPanel.addPlot(plotInstances.getPlotData("plot name")); * visPanel.setColourIndex(plotInstances.getPlotInstances().classIndex()+1); * // clean up * plotInstances.cleanUp(); * </pre> * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class ClassifierErrorsPlotInstances extends AbstractPlotInstances { /** for serialization. */ private static final long serialVersionUID = -3941976365792013279L; /** the minimum plot size for numeric errors. */ protected int m_MinimumPlotSizeNumeric; /** the maximum plot size for numeric errors. */ protected int m_MaximumPlotSizeNumeric; /** * whether to save the instances for visualization or just evaluate the * instance. */ protected boolean m_SaveForVisualization; protected boolean m_pointSizeProportionalToMargin; /** for storing the plot shapes. */ protected ArrayList<Integer> m_PlotShapes; /** for storing the plot sizes. */ protected ArrayList<Object> m_PlotSizes; /** the classifier being used. */ protected Classifier m_Classifier; /** the class index. */ protected int m_ClassIndex; /** the Evaluation object to use. */ protected Evaluation m_Evaluation; /** * Initializes the members. */ @Override protected void initialize() { super.initialize(); m_PlotShapes = new ArrayList<Integer>(); m_PlotSizes = new ArrayList<Object>(); m_Classifier = null; m_ClassIndex = -1; m_Evaluation = null; m_SaveForVisualization = true; m_MinimumPlotSizeNumeric = ExplorerDefaults .getClassifierErrorsMinimumPlotSizeNumeric(); m_MaximumPlotSizeNumeric = ExplorerDefaults .getClassifierErrorsMaximumPlotSizeNumeric(); } /** * Get the vector of plot shapes (see weka.gui.visualize.Plot2D). * * @return the vector of plot shapes. */ public ArrayList<Integer> getPlotShapes() { return m_PlotShapes; } /** * Get the vector of plot sizes (see weka.gui.visualize.Plot2D). * * @return the vector of plot sizes. */ public ArrayList<Object> getPlotSizes() { return m_PlotSizes; } /** * Set the vector of plot shapes to use; * * @param plotShapes */ public void setPlotShapes(ArrayList<Integer> plotShapes) { m_PlotShapes = plotShapes; } /** * Set the vector of plot sizes to use * * @param plotSizes the plot sizes to use */ public void setPlotSizes(ArrayList<Object> plotSizes) { m_PlotSizes = plotSizes; } /** * Sets the classifier used for making the predictions. * * @param value the classifier to use */ public void setClassifier(Classifier value) { m_Classifier = value; } /** * Returns the currently set classifier. * * @return the classifier in use */ public Classifier getClassifier() { return m_Classifier; } /** * Sets the 0-based class index. * * @param index the class index */ public void setClassIndex(int index) { m_ClassIndex = index; } /** * Returns the 0-based class index. * * @return the class index */ public int getClassIndex() { return m_ClassIndex; } /** * Sets the Evaluation object to use. * * @param value the evaluation to use */ public void setEvaluation(Evaluation value) { m_Evaluation = value; } /** * Returns the Evaluation object in use. * * @return the evaluation object */ public Evaluation getEvaluation() { return m_Evaluation; } /** * Sets whether the instances are saved for visualization or only evaluation * of the prediction is to happen. * * @param value if true then the instances will be saved */ public void setSaveForVisualization(boolean value) { m_SaveForVisualization = value; } /** * Returns whether the instances are saved for visualization for only * evaluation of the prediction is to happen. * * @return true if the instances are saved */ public boolean getSaveForVisualization() { return m_SaveForVisualization; } /** * Set whether the point size should be proportional to the prediction margin * (classification only). * * @param b true if the point size should be proportional to the margin */ public void setPointSizeProportionalToMargin(boolean b) { m_pointSizeProportionalToMargin = b; } /** * Get whether the point size should be proportional to the prediction margin * (classification only). * * @return true if the point size should be proportional to the margin */ public boolean getPointSizeProportionalToMargin() { return m_pointSizeProportionalToMargin; } /** * Checks whether classifier, class index and evaluation are provided. */ @Override protected void check() { super.check(); if (m_Classifier == null) { throw new IllegalStateException("No classifier set!"); } if (m_ClassIndex == -1) { throw new IllegalStateException("No class index set!"); } if (m_Evaluation == null) { throw new IllegalStateException("No evaluation set"); } } /** * Sets up the structure for the plot instances. Sets m_PlotInstances to null * if instances are not saved for visualization. * * @see #getSaveForVisualization() */ @Override protected void determineFormat() { ArrayList<Attribute> hv; Attribute predictedClass; Attribute classAt; Attribute margin = null; ArrayList<String> attVals; int i; if (!m_SaveForVisualization) { m_PlotInstances = null; return; } hv = new ArrayList<Attribute>(); classAt = m_Instances.attribute(m_ClassIndex); if (classAt.isNominal()) { attVals = new ArrayList<String>(); for (i = 0; i < classAt.numValues(); i++) { attVals.add(classAt.value(i)); } predictedClass = new Attribute("predicted " + classAt.name(), attVals); margin = new Attribute("prediction margin"); } else { predictedClass = new Attribute("predicted" + classAt.name()); } for (i = 0; i < m_Instances.numAttributes(); i++) { if (i == m_Instances.classIndex()) { if (classAt.isNominal()) { hv.add(margin); } hv.add(predictedClass); } hv.add((Attribute) m_Instances.attribute(i).copy()); } m_PlotInstances = new Instances(m_Instances.relationName() + "_predicted", hv, m_Instances.numInstances()); if (classAt.isNominal()) { m_PlotInstances.setClassIndex(m_ClassIndex + 2); } else { m_PlotInstances.setClassIndex(m_ClassIndex + 1); } } public void process(Instances batch, double[][] predictions, Evaluation eval) { try { for (int j = 0; j < batch.numInstances(); j++) { Instance toPredict = batch.instance(j); double[] preds = predictions[j]; double probActual = 0; double probNext = 0; double pred = 0; if (batch.classAttribute().isNominal()) { pred = (Utils.sum(preds) == 0) ? Utils.missingValue() : Utils .maxIndex(preds); probActual = (Utils.sum(preds) == 0) ? Utils.missingValue() : (!Utils .isMissingValue(toPredict.classIndex()) ? preds[(int) toPredict .classValue()] : preds[Utils.maxIndex(preds)]); for (int i = 0; i < toPredict.classAttribute().numValues(); i++) { if (i != (int) toPredict.classValue() && preds[i] > probNext) { probNext = preds[i]; } } } else { pred = preds[0]; } eval.evaluationForSingleInstance(preds, toPredict, true); if (!m_SaveForVisualization) { continue; } if (m_PlotInstances != null) { double[] values = new double[m_PlotInstances.numAttributes()]; boolean isNominal = toPredict.classAttribute().isNominal(); for (int i = 0; i < m_PlotInstances.numAttributes(); i++) { if (i < toPredict.classIndex()) { values[i] = toPredict.value(i); } else if (i == toPredict.classIndex()) { if (isNominal) { values[i] = probActual - probNext; values[i + 1] = pred; values[i + 2] = toPredict.value(i); i += 2; } else { values[i] = pred; values[i + 1] = toPredict.value(i); i++; } } else { if (isNominal) { values[i] = toPredict.value(i - 2); } else { values[i] = toPredict.value(i - 1); } } } m_PlotInstances.add(new DenseInstance(1.0, values)); if (toPredict.classAttribute().isNominal()) { if (toPredict.isMissing(toPredict.classIndex()) || Utils.isMissingValue(pred)) { m_PlotShapes.add(new Integer(Plot2D.MISSING_SHAPE)); } else if (pred != toPredict.classValue()) { // set to default error point shape m_PlotShapes.add(new Integer(Plot2D.ERROR_SHAPE)); } else { // otherwise set to constant (automatically assigned) point shape m_PlotShapes.add(new Integer(Plot2D.CONST_AUTOMATIC_SHAPE)); } if (m_pointSizeProportionalToMargin) { // margin m_PlotSizes.add(new Double(probActual - probNext)); } else { int sizeAdj = 0; if (pred != toPredict.classValue()) { sizeAdj = 1; } m_PlotSizes.add(new Integer(Plot2D.DEFAULT_SHAPE_SIZE + sizeAdj)); } } else { // store the error (to be converted to a point size later) Double errd = null; if (!toPredict.isMissing(toPredict.classIndex()) && !Utils.isMissingValue(pred)) { errd = new Double(pred - toPredict.classValue()); m_PlotShapes.add(new Integer(Plot2D.CONST_AUTOMATIC_SHAPE)); } else { // missing shape if actual class not present or prediction is // missing m_PlotShapes.add(new Integer(Plot2D.MISSING_SHAPE)); } m_PlotSizes.add(errd); } } } } catch (Exception ex) { ex.printStackTrace(); } } /** * Process a classifier's prediction for an instance and update a set of * plotting instances and additional plotting info. m_PlotShape for nominal * class datasets holds shape types (actual data points have automatic shape * type assignment; classifier error data points have box shape type). For * numeric class datasets, the actual data points are stored in * m_PlotInstances and m_PlotSize stores the error (which is later converted * to shape size values). * * @param toPredict the actual data point * @param classifier the classifier * @param eval the evaluation object to use for evaluating the classifier on * the instance to predict * @see #m_PlotShapes * @see #m_PlotSizes * @see #m_PlotInstances */ public void process(Instance toPredict, Classifier classifier, Evaluation eval) { double pred; double[] values; int i; try { pred = 0; double[] preds = null; double probActual = 0; double probNext = 0; int mappedClass = -1; Instance classMissing = (Instance) toPredict.copy(); classMissing.setDataset(toPredict.dataset()); // Only need to do this if the class is nominal, since we call // evalForSingleInstance() // which only takes a prob array if (classifier instanceof weka.classifiers.misc.InputMappedClassifier && toPredict.classAttribute().isNominal()) { toPredict = (Instance) toPredict.copy(); toPredict = ((weka.classifiers.misc.InputMappedClassifier) classifier) .constructMappedInstance(toPredict); mappedClass = ((weka.classifiers.misc.InputMappedClassifier) classifier) .getMappedClassIndex(); classMissing.setMissing(mappedClass); } else { classMissing.setClassMissing(); } if (toPredict.classAttribute().isNominal()) { preds = classifier.distributionForInstance(classMissing); pred = (Utils.sum(preds) == 0) ? Utils.missingValue() : Utils .maxIndex(preds); probActual = (Utils.sum(preds) == 0) ? Utils.missingValue() : (!Utils .isMissingValue(toPredict.classIndex()) ? preds[(int) toPredict .classValue()] : preds[Utils.maxIndex(preds)]); for (i = 0; i < toPredict.classAttribute().numValues(); i++) { if (i != (int) toPredict.classValue() && preds[i] > probNext) { probNext = preds[i]; } } eval.evaluationForSingleInstance(preds, toPredict, true); } else { // Numeric class. evalModelOnceAndRecordPrediciton() does the // InputMappedClassifier // transformation for us. pred = eval.evaluateModelOnceAndRecordPrediction(classifier, toPredict); } // if (!m_SaveForVisualization) { return; } if (m_PlotInstances != null) { boolean isNominal = toPredict.classAttribute().isNominal(); values = new double[m_PlotInstances.numAttributes()]; for (i = 0; i < m_PlotInstances.numAttributes(); i++) { if (i < toPredict.classIndex()) { values[i] = toPredict.value(i); } else if (i == toPredict.classIndex()) { if (isNominal) { values[i] = probActual - probNext; values[i + 1] = pred; values[i + 2] = toPredict.value(i); i += 2; } else { values[i] = pred; values[i + 1] = toPredict.value(i); i++; } } else { if (isNominal) { values[i] = toPredict.value(i - 2); } else { values[i] = toPredict.value(i - 1); } } } m_PlotInstances.add(new DenseInstance(1.0, values)); if (toPredict.classAttribute().isNominal()) { if (toPredict.isMissing(toPredict.classIndex()) || Utils.isMissingValue(pred)) { m_PlotShapes.add(new Integer(Plot2D.MISSING_SHAPE)); } else if (pred != toPredict.classValue()) { // set to default error point shape m_PlotShapes.add(new Integer(Plot2D.ERROR_SHAPE)); } else { // otherwise set to constant (automatically assigned) point shape m_PlotShapes.add(new Integer(Plot2D.CONST_AUTOMATIC_SHAPE)); } if (m_pointSizeProportionalToMargin) { // margin m_PlotSizes.add(new Double(probActual - probNext)); } else { int sizeAdj = 0; if (pred != toPredict.classValue()) { sizeAdj = 1; } m_PlotSizes.add(new Integer(Plot2D.DEFAULT_SHAPE_SIZE + sizeAdj)); } } else { // store the error (to be converted to a point size later) Double errd = null; if (!toPredict.isMissing(toPredict.classIndex()) && !Utils.isMissingValue(pred)) { errd = new Double(pred - toPredict.classValue()); m_PlotShapes.add(new Integer(Plot2D.CONST_AUTOMATIC_SHAPE)); } else { // missing shape if actual class not present or prediction is // missing m_PlotShapes.add(new Integer(Plot2D.MISSING_SHAPE)); } m_PlotSizes.add(errd); } } } catch (Exception ex) { ex.printStackTrace(); } } /** * Scales numeric class predictions into shape sizes for plotting in the * visualize panel. */ protected void scaleNumericPredictions() { double maxErr; double minErr; double err; int i; Double errd; double temp; maxErr = Double.NEGATIVE_INFINITY; minErr = Double.POSITIVE_INFINITY; if (m_Instances.classAttribute().isNominal()) { maxErr = 1; minErr = 0; } else { // find min/max errors for (i = 0; i < m_PlotSizes.size(); i++) { errd = (Double) m_PlotSizes.get(i); if (errd != null) { err = Math.abs(errd.doubleValue()); if (err < minErr) { minErr = err; } if (err > maxErr) { maxErr = err; } } } } // scale errors for (i = 0; i < m_PlotSizes.size(); i++) { errd = (Double) m_PlotSizes.get(i); if (errd != null) { err = Math.abs(errd.doubleValue()); if (maxErr - minErr > 0) { temp = (((err - minErr) / (maxErr - minErr)) * (m_MaximumPlotSizeNumeric - m_MinimumPlotSizeNumeric + 1)); m_PlotSizes .set(i, new Integer((int) temp) + m_MinimumPlotSizeNumeric); } else { m_PlotSizes.set(i, new Integer(m_MinimumPlotSizeNumeric)); } } else { m_PlotSizes.set(i, new Integer(m_MinimumPlotSizeNumeric)); } } } /** * Adds the prediction intervals as additional attributes at the end. Since * classifiers can returns varying number of intervals per instance, the * dataset is filled with missing values for non-existing intervals. */ protected void addPredictionIntervals() { int maxNum; int num; int i; int n; ArrayList<Prediction> preds; ArrayList<Attribute> atts; Instances data; Instance inst; Instance newInst; double[] values; double[][] predInt; // determine the maximum number of intervals maxNum = 0; preds = m_Evaluation.predictions(); for (i = 0; i < preds.size(); i++) { num = ((NumericPrediction) preds.get(i)).predictionIntervals().length; if (num > maxNum) { maxNum = num; } } // create new header atts = new ArrayList<Attribute>(); for (i = 0; i < m_PlotInstances.numAttributes(); i++) { atts.add(m_PlotInstances.attribute(i)); } for (i = 0; i < maxNum; i++) { atts .add(new Attribute("predictionInterval_" + (i + 1) + "-lowerBoundary")); atts .add(new Attribute("predictionInterval_" + (i + 1) + "-upperBoundary")); atts.add(new Attribute("predictionInterval_" + (i + 1) + "-width")); } data = new Instances(m_PlotInstances.relationName(), atts, m_PlotInstances.numInstances()); data.setClassIndex(m_PlotInstances.classIndex()); // update data for (i = 0; i < m_PlotInstances.numInstances(); i++) { inst = m_PlotInstances.instance(i); // copy old values values = new double[data.numAttributes()]; System .arraycopy(inst.toDoubleArray(), 0, values, 0, inst.numAttributes()); // add interval data predInt = ((NumericPrediction) preds.get(i)).predictionIntervals(); for (n = 0; n < maxNum; n++) { if (n < predInt.length) { values[m_PlotInstances.numAttributes() + n * 3 + 0] = predInt[n][0]; values[m_PlotInstances.numAttributes() + n * 3 + 1] = predInt[n][1]; values[m_PlotInstances.numAttributes() + n * 3 + 2] = predInt[n][1] - predInt[n][0]; } else { values[m_PlotInstances.numAttributes() + n * 3 + 0] = Utils .missingValue(); values[m_PlotInstances.numAttributes() + n * 3 + 1] = Utils .missingValue(); values[m_PlotInstances.numAttributes() + n * 3 + 2] = Utils .missingValue(); } } // create new Instance newInst = new DenseInstance(inst.weight(), values); data.add(newInst); } m_PlotInstances = data; } /** * Performs optional post-processing. * * @see #scaleNumericPredictions() * @see #addPredictionIntervals() */ @Override protected void finishUp() { super.finishUp(); if (!m_SaveForVisualization) { return; } if (m_Instances.classAttribute().isNumeric() || m_pointSizeProportionalToMargin) { scaleNumericPredictions(); // now handles point sizes based on the margin // too } if (m_Instances.attribute(m_ClassIndex).isNumeric()) { if (m_Classifier instanceof IntervalEstimator) { addPredictionIntervals(); } } } /** * Assembles and returns the plot. The relation name of the dataset gets added * automatically. * * @param name the name of the plot * @return the plot or null if plot instances weren't saved for visualization * @throws Exception if plot generation fails */ @Override protected PlotData2D createPlotData(String name) throws Exception { PlotData2D result; if (!m_SaveForVisualization) { return null; } result = new PlotData2D(m_PlotInstances); result.setShapeSize(m_PlotSizes); result.setShapeType(m_PlotShapes); result.setPlotName(name + " (" + m_Instances.relationName() + ")"); // result.addInstanceNumberAttribute(); return result; } /** * For freeing up memory. Plot data cannot be generated after this call! */ @Override public void cleanUp() { super.cleanUp(); m_Classifier = null; m_PlotShapes = null; m_PlotSizes = null; m_Evaluation = null; } }