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/simplecli/Cls.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * Cls.java * Copyright (C) 2018 University of Waikato, Hamilton, NZ */ package weka.gui.simplecli; /** * Clears the output area. * * @author FracPete (fracpete at waikato dot ac dot nz) */ public class Cls extends AbstractCommand { /** * Returns the name of the command. * * @return the name */ @Override public String getName() { return "cls"; } /** * Returns the help string (no indentation). * * @return the help */ @Override public String getHelp() { return "Clears the output area."; } /** * Returns the one-liner help string for the parameters. * * @return the help, empty if none available */ public String getParameterHelp() { return ""; } /** * Executes the command with the given parameters. * * @param params the parameters for the command * @throws Exception if command fails */ @Override protected void doExecute(String[] params) throws Exception { // Clear the text area m_Owner.getOutputArea().setText(""); } }
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/simplecli/Echo.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * Echo.java * Copyright (C) 2018 University of Waikato, Hamilton, NZ */ package weka.gui.simplecli; /** * Outputs a message. * * @author FracPete (fracpete at waikato dot ac dot nz) */ public class Echo extends AbstractCommand { /** * Returns the name of the command. * * @return the name */ @Override public String getName() { return "echo"; } /** * Returns the help string (no indentation). * * @return the help */ @Override public String getHelp() { return "Outputs a message."; } /** * Returns the one-liner help string for the parameters. * * @return the help, empty if none available */ public String getParameterHelp() { return "msg"; } /** * Executes the command with the given parameters. * * @param params the parameters for the command * @throws Exception if command fails */ @Override protected void doExecute(String[] params) throws Exception { if (params.length > 0) System.out.println(params[0]); } }
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/simplecli/Exit.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * Exit.java * Copyright (C) 2018 University of Waikato, Hamilton, NZ */ package weka.gui.simplecli; import javax.swing.JFrame; import javax.swing.JInternalFrame; import java.awt.Container; import java.awt.Frame; import java.awt.Window; import java.awt.event.WindowEvent; /** * Closes the Simple CLI window. * * @author FracPete (fracpete at waikato dot ac dot nz) */ public class Exit extends AbstractCommand { /** * Returns the name of the command. * * @return the name */ @Override public String getName() { return "exit"; } /** * Returns the help string (no indentation). * * @return the help */ @Override public String getHelp() { return "Exits the SimpleCLI program."; } /** * Returns the one-liner help string for the parameters. * * @return the help, empty if none available */ public String getParameterHelp() { return ""; } /** * Executes the command with the given parameters. * * @param params the parameters for the command * @throws Exception if command fails */ @Override protected void doExecute(String[] params) throws Exception { // Shut down // determine parent Container parent = m_Owner.getParent(); Container frame = null; boolean finished = false; while (!finished) { if ((parent instanceof JFrame) || (parent instanceof Frame) || (parent instanceof JInternalFrame)) { frame = parent; finished = true; } if (!finished) { parent = parent.getParent(); finished = (parent == null); } } // fire the frame close event if (frame != null) { if (frame instanceof JInternalFrame) { ((JInternalFrame) frame).doDefaultCloseAction(); } else { ((Window) frame).dispatchEvent(new WindowEvent((Window) frame, WindowEvent.WINDOW_CLOSING)); } } } }
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/simplecli/Help.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * Help.java * Copyright (C) 2018 University of Waikato, Hamilton, NZ */ package weka.gui.simplecli; import java.util.ArrayList; import java.util.List; /** * Outputs help for a command or for all. * * @author FracPete (fracpete at waikato dot ac dot nz) */ public class Help extends AbstractCommand { /** * Returns the name of the command. * * @return the name */ @Override public String getName() { return "help"; } /** * Returns the help string (no indentation). * * @return the help */ @Override public String getHelp() { return "Outputs the help for the specified command or, if omitted,\n" + "for all commands."; } /** * Returns the one-liner help string for the parameters. * * @return the help, empty if none available */ public String getParameterHelp() { return "[command1] [command2] [...]"; } /** * Executes the command with the given parameters. * * @param params the parameters for the command * @throws Exception if command fails */ @Override protected void doExecute(String[] params) throws Exception { List<AbstractCommand> cmds; AbstractCommand cmd; List<AbstractCommand> help; boolean all; all = false; cmds = getCommands(); // specific command? help = new ArrayList<>(); for (String param: params) { cmd = getCommand(param); if (cmd != null) { help.add(cmd); break; } else { throw new Exception("Unknown command: " + param); } } // all? if (help.isEmpty()) { all = true; help.addAll(cmds); } for (AbstractCommand c: help) { System.out.println(c.getName() + (c.getParameterHelp().isEmpty() ? "" : " " + c.getParameterHelp())); String[] lines = c.getHelp().split("\n"); for (String line: lines) System.out.println("\t" + line); System.out.println(); } // additional information if (all) { System.out.println("\nNotes:"); System.out.println("- Variables can be used anywhere using '${<name>}' with '<name>'"); System.out.println(" being the name of the variable."); System.out.println("- Environment variables can be used with '${env.<name>}', "); System.out.println(" e.g., '${env.PATH}' to retrieve the PATH variable."); } } }
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/simplecli/History.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * History.java * Copyright (C) 2018 University of Waikato, Hamilton, NZ */ package weka.gui.simplecli; /** * Prints all issued commands. * * @author FracPete (fracpete at waikato dot ac dot nz) */ public class History extends AbstractCommand { /** * Returns the name of the command. * * @return the name */ @Override public String getName() { return "history"; } /** * Returns the help string (no indentation). * * @return the help */ @Override public String getHelp() { return "Prints all issued commands."; } /** * Returns the one-liner help string for the parameters. * * @return the help, empty if none available */ public String getParameterHelp() { return ""; } /** * Executes the command with the given parameters. * * @param params the parameters for the command * @throws Exception if command fails */ @Override protected void doExecute(String[] params) throws Exception { System.out.println("Command history:"); for (int i = 0; i < m_Owner.getCommandHistory().size(); i++) { System.out.println(m_Owner.getCommandHistory().get(i)); } 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/simplecli/Java.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * Java.java * Copyright (C) 2018 University of Waikato, Hamilton, NZ */ package weka.gui.simplecli; import weka.core.OptionHandler; import weka.gui.SimpleCLIPanel.ClassRunner; import java.util.ArrayList; import java.util.List; /** * Sets a variable. * * @author FracPete (fracpete at waikato dot ac dot nz) */ public class Java extends AbstractCommand { /** * Returns the name of the command. * * @return the name */ @Override public String getName() { return "java"; } /** * Returns the help string (no indentation). * * @return the help */ @Override public String getHelp() { return "Lists the capabilities of the specified class.\n" + "If the class is a " + OptionHandler.class.getName() + " then\n" + "trailing options after the classname will be\n" + "set as well.\n"; } /** * Returns the one-liner help string for the parameters. * * @return the help, empty if none available */ public String getParameterHelp() { return "<classname> <args>"; } /** * Executes the command with the given parameters. * * @param params the parameters for the command * @throws Exception if command fails */ @Override protected void doExecute(String[] params) throws Exception { // Execute the main method of a class try { if (params.length == 0) { throw new Exception("No class name given"); } String className = params[0]; params[0] = ""; if (m_Owner.isBusy()) { throw new Exception("An object is already running, use \"kill\"" + " to stop it."); } Class<?> theClass = Class.forName(className); // some classes expect a fixed order of the args, i.e., they don't // use Utils.getOption(...) => create new array without first two // empty strings (former "java" and "<classname>") List<String> argv = new ArrayList<>(); for (int i = 1; i < params.length; i++) { argv.add(params[i]); } m_Owner.startThread(new ClassRunner(m_Owner, theClass, argv.toArray(new String[argv.size()]))); } catch (Exception e) { System.out.println(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/simplecli/Kill.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * Kill.java * Copyright (C) 2018 University of Waikato, Hamilton, NZ */ package weka.gui.simplecli; /** * Kills the running process. * * @author FracPete (fracpete at waikato dot ac dot nz) */ public class Kill extends AbstractCommand { /** * Returns the name of the command. * * @return the name */ @Override public String getName() { return "kill"; } /** * Returns the help string (no indentation). * * @return the help */ @Override public String getHelp() { return "Kills the running job, if any."; } /** * Returns the one-liner help string for the parameters. * * @return the help, empty if none available */ public String getParameterHelp() { return ""; } /** * Executes the command with the given parameters. * * @param params the parameters for the command * @throws Exception if command fails */ @Override protected void doExecute(String[] params) throws Exception { if (!m_Owner.isBusy()) { System.err.println("Nothing is currently running."); } else { System.out.println("[Kill...]"); m_Owner.stopThread(); } } }
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/simplecli/Script.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * Script.java * Copyright (C) 2018 University of Waikato, Hamilton, NZ */ package weka.gui.simplecli; import java.io.File; import java.nio.file.Files; import java.util.List; /** * Executes commands from a script file. * * @author FracPete (fracpete at waikato dot ac dot nz) */ public class Script extends AbstractCommand { /** * Returns the name of the command. * * @return the name */ @Override public String getName() { return "script"; } /** * Returns the help string (no indentation). * * @return the help */ @Override public String getHelp() { return "Executes commands from a script file."; } /** * Returns the one-liner help string for the parameters. * * @return the help, empty if none available */ public String getParameterHelp() { return "<script_file>"; } /** * Executes the command with the given parameters. * * @param params the parameters for the command * @throws Exception if command fails */ @Override protected void doExecute(String[] params) throws Exception { if (params.length == 0) { throw new Exception("No script file provided!"); } File script = new File(params[0]); if (!script.exists()) { throw new Exception("Script does not exist: " + script); } if (script.isDirectory()) { throw new Exception("Script points to a directory: " + script); } List<String> cmds = Files.readAllLines(script.toPath()); for (String cmd: cmds) { while (m_Owner.isBusy()) { try { this.wait(100); } catch (Exception e) { // ignored } } m_Owner.runCommand(cmd); } } }
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/simplecli/Set.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * Set.java * Copyright (C) 2018 University of Waikato, Hamilton, NZ */ package weka.gui.simplecli; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Sets a variable. * * @author FracPete (fracpete at waikato dot ac dot nz) */ public class Set extends AbstractCommand { /** * Returns the name of the command. * * @return the name */ @Override public String getName() { return "set"; } /** * Returns the help string (no indentation). * * @return the help */ @Override public String getHelp() { return "Sets a variable.\n" + "If no key=value pair is given all current variables are listed."; } /** * Returns the one-liner help string for the parameters. * * @return the help, empty if none available */ public String getParameterHelp() { return "[name=value]"; } /** * Executes the command with the given parameters. * * @param params the parameters for the command * @throws Exception if command fails */ @Override protected void doExecute(String[] params) throws Exception { String name; String value; List<String> names; if (params.length == 0) { names = new ArrayList<>(m_Owner.getVariables().keySet()); if (names.size() == 0) { System.out.println("No variables stored!"); } else { Collections.sort(names); for (String n: names) System.out.println(n + "=" + m_Owner.getVariables().get(n)); } return; } if (params.length != 1) throw new Exception("Expected exactly one argument: name=value"); if (!params[0].contains("=")) throw new Exception("Expected format 'name=value', encountered: " + params[0]); name = params[0].substring(0, params[0].indexOf("=")); value = params[0].substring(params[0].indexOf("=") + 1); m_Owner.getVariables().put(name, value); } }
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/simplecli/Unset.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * Unset.java * Copyright (C) 2018 University of Waikato, Hamilton, NZ */ package weka.gui.simplecli; /** * Removes a variable. * * @author FracPete (fracpete at waikato dot ac dot nz) */ public class Unset extends AbstractCommand { /** * Returns the name of the command. * * @return the name */ @Override public String getName() { return "unset"; } /** * Returns the help string (no indentation). * * @return the help */ @Override public String getHelp() { return "Removes a variable."; } /** * Returns the one-liner help string for the parameters. * * @return the help, empty if none available */ public String getParameterHelp() { return "name"; } /** * Executes the command with the given parameters. * * @param params the parameters for the command * @throws Exception if command fails */ @Override protected void doExecute(String[] params) throws Exception { if (params.length != 1) throw new Exception("Expected exactly one argument: name"); m_Owner.getVariables().remove(params[0]); } }
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/sql/ConnectionPanel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ConnectionPanel.java * Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.sql; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.HashSet; import java.util.Iterator; import javax.swing.*; import javax.swing.event.CaretEvent; import javax.swing.event.CaretListener; import weka.gui.ComponentHelper; import weka.gui.DatabaseConnectionDialog; import weka.gui.ExtensionFileFilter; import weka.gui.ListSelectorDialog; import weka.gui.sql.event.ConnectionEvent; import weka.gui.sql.event.ConnectionListener; import weka.gui.sql.event.HistoryChangedEvent; import weka.gui.sql.event.HistoryChangedListener; /** * Enables the user to insert a database URL, plus user/password to connect to * this database. * * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class ConnectionPanel extends JPanel implements CaretListener { /** for serialization. */ static final long serialVersionUID = 3499317023969723490L; /** the name of the history. */ public final static String HISTORY_NAME = "connection"; /** the parent frame. */ protected JFrame m_Parent = null; /** the database connection dialog. */ protected DatabaseConnectionDialog m_DbDialog; /** the URL to use. */ protected String m_URL = ""; /** the user to use for connecting to the DB. */ protected String m_User = ""; /** the password to use for connecting to the DB. */ protected String m_Password = ""; /** the label for the URL. */ protected JLabel m_LabelURL = new JLabel("URL "); /** the textfield for the URL. */ protected JTextField m_TextURL = new JTextField(40); /** the button for the DB-Dialog. */ protected JButton m_ButtonDatabase = new JButton( ComponentHelper.getImageIcon("user.png")); /** the button for connecting to the database. */ protected JButton m_ButtonConnect = new JButton( ComponentHelper.getImageIcon("connect.png")); /** the button for the history. */ protected JButton m_ButtonHistory = new JButton( ComponentHelper.getImageIcon("history.png")); /** the button for the setup. */ protected JButton m_ButtonSetup = new JButton( ComponentHelper.getImageIcon("properties.gif")); /** the connection listeners. */ protected HashSet<ConnectionListener> m_ConnectionListeners; /** the history listeners. */ protected HashSet<HistoryChangedListener> m_HistoryChangedListeners; /** for connecting to the database. */ protected DbUtils m_DbUtils; /** the history of connections. */ protected DefaultListModel m_History = new DefaultListModel(); /** the file chooser for the setup files. */ protected JFileChooser m_SetupFileChooser; /** * initializes the panel. * * @param parent the parent of this panel */ public ConnectionPanel(JFrame parent) { super(); m_Parent = parent; m_ConnectionListeners = new HashSet<ConnectionListener>(); m_HistoryChangedListeners = new HashSet<HistoryChangedListener>(); m_SetupFileChooser = new JFileChooser(); m_SetupFileChooser.setDialogTitle("Switch database setup"); m_SetupFileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); m_SetupFileChooser.setMultiSelectionEnabled(false); m_SetupFileChooser.setAcceptAllFileFilterUsed(true); ExtensionFileFilter filter = new ExtensionFileFilter(".props", "Properties file"); m_SetupFileChooser.addChoosableFileFilter(filter); m_SetupFileChooser.setFileFilter(filter); try { m_DbUtils = new DbUtils(); m_URL = m_DbUtils.getDatabaseURL(); m_User = m_DbUtils.getUsername(); m_Password = m_DbUtils.getPassword(); } catch (Exception e) { e.printStackTrace(); m_URL = ""; m_User = ""; m_Password = ""; } createPanel(); } /** * builds the panel with all its components. */ protected void createPanel() { JPanel panel; JPanel panel2; setLayout(new BorderLayout()); panel2 = new JPanel(new FlowLayout()); add(panel2, BorderLayout.WEST); // label m_LabelURL.setLabelFor(m_ButtonDatabase); m_LabelURL.setDisplayedMnemonic('U'); panel2.add(m_LabelURL); // editfield m_TextURL.setText(m_URL); m_TextURL.addCaretListener(this); panel2.add(m_TextURL); // buttons panel = new JPanel(new FlowLayout()); panel2.add(panel); m_ButtonDatabase.setToolTipText("Set user and password"); m_ButtonDatabase.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { showDialog(); } }); panel.add(m_ButtonDatabase); m_ButtonConnect.setToolTipText("Connect to the database"); m_ButtonConnect.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { connect(); } }); panel.add(m_ButtonConnect); m_ButtonHistory.setToolTipText("Select a previously used connection"); m_ButtonHistory.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { showHistory(); } }); panel.add(m_ButtonHistory); m_ButtonSetup.setToolTipText("Switch database setup"); m_ButtonSetup.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { switchSetup(); } }); panel.add(m_ButtonSetup); setButtons(); } /** * sets the buttons according to the connected-state. */ protected void setButtons() { boolean isEmpty; isEmpty = m_TextURL.getText().equals(""); m_ButtonConnect.setEnabled(!isEmpty); m_ButtonDatabase.setEnabled(!isEmpty); m_ButtonHistory.setEnabled(m_History.size() > 0); m_ButtonSetup.setEnabled(true); } /** * sets the parameters back to standard. */ public void clear() { setURL(m_DbUtils.getDatabaseURL()); setUser(m_DbUtils.getUsername()); setPassword(m_DbUtils.getPassword()); } /** * sets the focus in a designated control. */ public void setFocus() { m_TextURL.requestFocus(); } /** * sets the URL. * * @param url the new value of the URL */ public void setURL(String url) { m_URL = url; m_TextURL.setText(url); } /** * returns the current URL. * * @return the current URL */ public String getURL() { m_URL = m_TextURL.getText(); return m_URL; } /** * sets the User. * * @param user the new value of the User */ public void setUser(String user) { m_User = user; } /** * returns the current User. * * @return the current user */ public String getUser() { return m_User; } /** * sets the Password. * * @param pw the new value of the Password */ public void setPassword(String pw) { m_Password = pw; } /** * returns the current Password. * * @return the current password */ public String getPassword() { return m_Password; } /** * adds the given string to the history (removes duplicates). * * @param s the string to add */ protected void addHistory(String s) { if (s.equals("")) { return; } // no duplicates! if (m_History.contains(s)) { m_History.removeElement(s); } m_History.add(0, s); // send notification notifyHistoryChangedListeners(); } /** * sets the local history to the given one. * * @param history the history to use */ public void setHistory(DefaultListModel history) { int i; m_History.clear(); for (i = 0; i < history.size(); i++) { m_History.addElement(history.get(i)); } setButtons(); } /** * returns the history. * * @return the current history */ public DefaultListModel getHistory() { return m_History; } /** * displays the database dialog. */ protected void showDialog() { JFrame parent = m_Parent; if (parent == null) { Window window = SwingUtilities.getWindowAncestor(this); if (window instanceof JFrame) { parent = (JFrame)window; } } m_DbDialog = new DatabaseConnectionDialog(parent, getURL(), getUser(), false); m_DbDialog.setLocationRelativeTo(parent); m_DbDialog.setVisible(true); if (m_DbDialog.getReturnValue() == JOptionPane.OK_OPTION) { setURL(m_DbDialog.getURL()); setUser(m_DbDialog.getUsername()); setPassword(m_DbDialog.getPassword()); } setButtons(); } /** * connects to the database, notifies the listeners. */ protected void connect() { // disconnect if still connected if (m_DbUtils.isConnected()) { try { m_DbUtils.disconnectFromDatabase(); notifyConnectionListeners(ConnectionEvent.DISCONNECT); } catch (Exception e) { e.printStackTrace(); notifyConnectionListeners(ConnectionEvent.DISCONNECT, e); } } // connect try { m_DbUtils.setDatabaseURL(getURL()); m_DbUtils.setUsername(getUser()); m_DbUtils.setPassword(getPassword()); m_DbUtils.connectToDatabase(); notifyConnectionListeners(ConnectionEvent.CONNECT); // add to history addHistory(getUser() + "@" + getURL()); } catch (Exception e) { e.printStackTrace(); notifyConnectionListeners(ConnectionEvent.CONNECT, e); } setButtons(); } /** * displays the query history. */ public void showHistory() { JList list; ListSelectorDialog dialog; String tmpStr; list = new JList(m_History); dialog = new ListSelectorDialog(m_Parent, list); if (dialog.showDialog() == ListSelectorDialog.APPROVE_OPTION) { if (list.getSelectedValue() != null) { tmpStr = list.getSelectedValue().toString(); if (tmpStr.indexOf("@") > -1) { setUser(tmpStr.substring(0, tmpStr.indexOf("@"))); setURL(tmpStr.substring(tmpStr.indexOf("@") + 1)); showDialog(); } else { setUser(""); setURL(tmpStr); } } } setButtons(); } /** * Lets the user select a props file for changing the database connection * parameters. */ public void switchSetup() { int retVal; retVal = m_SetupFileChooser.showOpenDialog(this); if (retVal != JFileChooser.APPROVE_OPTION) { return; } m_DbUtils.initialize(m_SetupFileChooser.getSelectedFile()); m_URL = m_DbUtils.getDatabaseURL(); m_User = m_DbUtils.getUsername(); m_Password = m_DbUtils.getPassword(); m_TextURL.setText(m_URL); } /** * adds the given listener to the list of listeners. * * @param l the listener to add to the list */ public void addConnectionListener(ConnectionListener l) { m_ConnectionListeners.add(l); } /** * removes the given listener from the list of listeners. * * @param l the listener to remove */ public void removeConnectionListener(ConnectionListener l) { m_ConnectionListeners.remove(l); } /** * notifies the connection listeners of the event. * * @param type the type of the action, CONNECT or DISCONNECT */ protected void notifyConnectionListeners(int type) { notifyConnectionListeners(type, null); } /** * notifies the connection listeners of the event. * * @param type the type of the action, CONNECT or DISCONNECT * @param ex an optional exception that happened (indicates failure!) */ protected void notifyConnectionListeners(int type, Exception ex) { Iterator<ConnectionListener> iter; ConnectionListener l; iter = m_ConnectionListeners.iterator(); while (iter.hasNext()) { l = iter.next(); l.connectionChange(new ConnectionEvent(this, type, m_DbUtils, ex)); } } /** * adds the given listener to the list of listeners. * * @param l the listener to add to the list */ public void addHistoryChangedListener(HistoryChangedListener l) { m_HistoryChangedListeners.add(l); } /** * removes the given listener from the list of listeners. * * @param l the listener to remove */ public void removeHistoryChangedListener(HistoryChangedListener l) { m_HistoryChangedListeners.remove(l); } /** * notifies the history listeners of the event. */ protected void notifyHistoryChangedListeners() { Iterator<HistoryChangedListener> iter; HistoryChangedListener l; iter = m_HistoryChangedListeners.iterator(); while (iter.hasNext()) { l = iter.next(); l.historyChanged(new HistoryChangedEvent(this, HISTORY_NAME, getHistory())); } } /** * Called when the caret position is updated. * * @param event the event to process */ @Override public void caretUpdate(CaretEvent event) { setButtons(); } }
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/sql/DbUtils.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * DbUtils.java * Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.sql; import java.sql.Connection; import weka.core.RevisionUtils; import weka.experiment.DatabaseUtils; /** * A little bit extended DatabaseUtils class. * * @see DatabaseUtils * @see #execute(String) * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class DbUtils extends DatabaseUtils { /** for serialization. */ private static final long serialVersionUID = 103748569037426479L; /** * initializes the object. * * @throws Exception in case something goes wrong in the init of the * DatabaseUtils constructor * @see DatabaseUtils */ public DbUtils() throws Exception { super(); } /** * returns the current database connection. * * @return the current connection instance */ public Connection getConnection() { return m_Connection; } /** * Returns the revision string. * * @return the revision */ public String getRevision() { return RevisionUtils.extract("$Revision$"); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/sql/InfoPanel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * InfoPanel.java * Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.sql; import java.awt.BorderLayout; import java.awt.Dimension; 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 javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import weka.gui.ComponentHelper; /** * A simple panel for displaying information, e.g. progress information etc. * * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class InfoPanel extends JPanel { /** for serialization */ private static final long serialVersionUID = -7701133696481997973L; /** the parent of this panel */ protected JFrame m_Parent; /** the list the contains the messages */ protected JList m_Info; /** the model for the list */ protected DefaultListModel m_Model; /** the button to clear the area */ protected JButton m_ButtonClear; /** the button to copy the selected message */ protected JButton m_ButtonCopy; /** * creates the panel * @param parent the parent of this panel */ public InfoPanel(JFrame parent) { super(); m_Parent = parent; createPanel(); } /** * inserts the components into the panel */ protected void createPanel() { JPanel panel; JPanel panel2; setLayout(new BorderLayout()); setPreferredSize(new Dimension(0, 80)); // text m_Model = new DefaultListModel(); m_Info = new JList(m_Model); m_Info.setCellRenderer(new InfoPanelCellRenderer()); m_Info.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { setButtons(e); } }); add(new JScrollPane(m_Info), BorderLayout.CENTER); // clear button panel = new JPanel(new BorderLayout()); add(panel, BorderLayout.EAST); m_ButtonClear = new JButton("Clear"); m_ButtonClear.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { clear(); } }); panel.add(m_ButtonClear, BorderLayout.NORTH); // clear button panel2 = new JPanel(new BorderLayout()); panel.add(panel2, BorderLayout.CENTER); m_ButtonCopy = new JButton("Copy"); m_ButtonCopy.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { copyToClipboard(); } }); panel2.add(m_ButtonCopy, BorderLayout.NORTH); } /** * sets the state of the buttons according to the selection state of the * JList */ protected void setButtons(ListSelectionEvent e) { if ( (e == null) || (e.getSource() == m_Info) ) { m_ButtonClear.setEnabled(m_Model.getSize() > 0); m_ButtonCopy.setEnabled(m_Info.getSelectedIndices().length == 1); } } /** * sets the focus in a designated control */ public void setFocus() { m_Info.requestFocus(); } /** * clears the content of the panel */ public void clear() { m_Model.clear(); setButtons(null); } /** * copies the currently selected error message to the clipboard * * @return true if the content was copied */ public boolean copyToClipboard() { StringSelection selection; Clipboard clipboard; if (m_Info.getSelectedIndices().length != 1) return false; selection = new StringSelection(((JLabel) m_Info.getSelectedValue()).getText()); clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents(selection, selection); return true; } /** * adds the given message to the end of the list (with the associated icon * at the beginning) * @param msg the message to append to the list * @param icon the filename of the icon */ public void append(String msg, String icon) { append(new JLabel(msg, ComponentHelper.getImageIcon(icon), JLabel.LEFT)); } /** * adds the given message to the end of the list * @param msg the message to append to the list */ public void append(Object msg) { if (msg instanceof String) { append(msg.toString(), "empty_small.gif"); return; } m_Model.addElement(msg); m_Info.setSelectedIndex(m_Model.getSize() - 1); m_Info.ensureIndexIsVisible(m_Info.getSelectedIndex()); setButtons(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/sql/InfoPanelCellRenderer.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * InfoPanelCellRenderer.java * Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.sql; import java.awt.Component; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.ListCellRenderer; /** * A specialized renderer that takes care of JLabels in a JList. * * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class InfoPanelCellRenderer extends JLabel implements ListCellRenderer { /** for serialization */ private static final long serialVersionUID = -533380118807178531L; /** * the constructor */ public InfoPanelCellRenderer() { super(); setOpaque(true); } /** * Return a component that has been configured to display the specified value. * @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. */ public Component getListCellRendererComponent( JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { if (value instanceof JLabel) { setIcon(((JLabel) value).getIcon()); setText(((JLabel) value).getText()); } else { setIcon(null); setText(value.toString()); } if (isSelected) { setBackground(list.getSelectionBackground()); setForeground(list.getSelectionForeground()); } else { setBackground(list.getBackground()); setForeground(list.getForeground()); } setEnabled(list.isEnabled()); setFont(list.getFont()); return this; } }
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/sql/QueryPanel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * QueryPanel.java * Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.sql; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.ResultSet; import java.util.HashSet; import java.util.Iterator; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSpinner; import javax.swing.JTextArea; import javax.swing.SpinnerNumberModel; import javax.swing.event.CaretEvent; import javax.swing.event.CaretListener; import weka.gui.ListSelectorDialog; import weka.gui.sql.event.ConnectionEvent; import weka.gui.sql.event.ConnectionListener; import weka.gui.sql.event.HistoryChangedEvent; import weka.gui.sql.event.HistoryChangedListener; import weka.gui.sql.event.QueryExecuteEvent; import weka.gui.sql.event.QueryExecuteListener; /** * Represents a panel for entering an SQL query. * * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class QueryPanel extends JPanel implements ConnectionListener, CaretListener { /** for serialization. */ private static final long serialVersionUID = 4348967824619706636L; /** the name of the history. */ public final static String HISTORY_NAME = "query"; /** the name for the max rows in the history. */ public final static String MAX_ROWS = "max_rows"; /** the parent of this panel. */ protected JFrame m_Parent; /** the textarea for the query. */ protected JTextArea m_TextQuery; /** the execute button. */ protected JButton m_ButtonExecute = new JButton("Execute"); /** the clear button. */ protected JButton m_ButtonClear = new JButton("Clear"); /** the history button. */ protected JButton m_ButtonHistory = new JButton("History..."); /** the spinner for the maximum number of rows. */ protected JSpinner m_SpinnerMaxRows = new JSpinner(); /** the connection listeners. */ protected HashSet<QueryExecuteListener> m_QueryExecuteListeners; /** the history listeners. */ protected HashSet<HistoryChangedListener> m_HistoryChangedListeners; /** for working on the database. */ protected DbUtils m_DbUtils; /** whether we have a connection to a database or not. */ protected boolean m_Connected; /** the query history. */ protected DefaultListModel m_History = new DefaultListModel(); /** * initializes the panel. * * @param parent the parent of this panel */ public QueryPanel(JFrame parent) { super(); m_Parent = parent; m_QueryExecuteListeners = new HashSet<QueryExecuteListener>(); m_HistoryChangedListeners = new HashSet<HistoryChangedListener>(); m_DbUtils = null; m_Connected = false; createPanel(); } /** * creates the panel with all its components. */ protected void createPanel() { JPanel panel; JPanel panel2; JPanel panel3; SpinnerNumberModel model; setLayout(new BorderLayout()); // textarea m_TextQuery = new JTextArea(); m_TextQuery.addCaretListener(this); m_TextQuery.setFont(new Font("Monospaced", Font.PLAIN, m_TextQuery .getFont().getSize())); add(new JScrollPane(m_TextQuery), BorderLayout.CENTER); // buttons panel = new JPanel(new BorderLayout()); add(panel, BorderLayout.EAST); m_ButtonExecute.setMnemonic('E'); m_ButtonExecute.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { execute(); } }); panel.add(m_ButtonExecute, BorderLayout.NORTH); panel2 = new JPanel(new BorderLayout()); panel.add(panel2, BorderLayout.CENTER); m_ButtonClear.setMnemonic('r'); m_ButtonClear.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { clear(); } }); panel2.add(m_ButtonClear, BorderLayout.NORTH); panel3 = new JPanel(new BorderLayout()); panel2.add(panel3, BorderLayout.CENTER); m_ButtonHistory.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { showHistory(); } }); panel3.add(m_ButtonHistory, BorderLayout.NORTH); // limit panel3 = new JPanel(new FlowLayout()); panel3.add(new JLabel("max. rows")); panel3.add(m_SpinnerMaxRows); panel2.add(panel3, BorderLayout.SOUTH); model = (SpinnerNumberModel) m_SpinnerMaxRows.getModel(); model.setMaximum(new Integer(Integer.MAX_VALUE)); model.setMinimum(new Integer(0)); model.setValue(new Integer(100)); model.setStepSize(new Integer(100)); m_SpinnerMaxRows.setMinimumSize(new Dimension(50, m_SpinnerMaxRows .getHeight())); m_SpinnerMaxRows.setToolTipText("with 0 all rows are retrieved"); // set initial state setButtons(); } /** * sets the focus in a designated control. */ public void setFocus() { m_TextQuery.requestFocus(); } /** * sets the buttons according to the connected-state. */ protected void setButtons() { boolean isEmpty; isEmpty = m_TextQuery.getText().trim().equals(""); m_ButtonExecute.setEnabled((m_Connected) && (!isEmpty)); m_ButtonClear.setEnabled(!isEmpty); m_ButtonHistory.setEnabled(m_History.size() > 0); } /** * This method gets called when the connection is either established or * disconnected. * * @param evt the event */ @Override public void connectionChange(ConnectionEvent evt) { m_Connected = evt.isConnected(); m_DbUtils = evt.getDbUtils(); setButtons(); } /** * executes the current query. */ public void execute() { Exception ex; ResultSet rs; // not connected? if (!m_ButtonExecute.isEnabled()) { return; } // no query? if (m_TextQuery.getText().trim().equals("")) { return; } // close old resultset try { if (m_DbUtils.getResultSet() != null) { m_DbUtils.close(); } } catch (Exception e) { // ignore (if no resultset present we get an unncessary NullPointerEx.) } ex = null; rs = null; try { if (m_DbUtils.execute(getQuery())) { rs = m_DbUtils.getResultSet(); // add to history addHistory(getQuery()); } } catch (Exception e) { ex = new Exception(e.getMessage()); } notifyQueryExecuteListeners(rs, ex); setButtons(); } /** * clears the textarea. */ public void clear() { m_TextQuery.setText(""); m_SpinnerMaxRows.setValue(new Integer(100)); } /** * adds the given string to the history (removes duplicates). * * @param s the string to add */ protected void addHistory(String s) { if (s.equals("")) { return; } // no duplicates! if (m_History.contains(s)) { m_History.removeElement(s); } m_History.add(0, s); // send notification notifyHistoryChangedListeners(); } /** * sets the local history to the given one. * * @param history the history to use */ public void setHistory(DefaultListModel history) { int i; m_History.clear(); for (i = 0; i < history.size(); i++) { m_History.addElement(history.get(i)); } setButtons(); } /** * returns the history. * * @return the current history */ public DefaultListModel getHistory() { return m_History; } /** * displays the query history. */ public void showHistory() { JList list; ListSelectorDialog dialog; list = new JList(m_History); dialog = new ListSelectorDialog(m_Parent, list); if (dialog.showDialog() == ListSelectorDialog.APPROVE_OPTION) { if (list.getSelectedValue() != null) { setQuery(list.getSelectedValue().toString()); } } setButtons(); } /** * sets the query in the textarea. * * @param query the query to display */ public void setQuery(String query) { m_TextQuery.setText(query); } /** * returns the currently displayed query. * * @return the query */ public String getQuery() { return m_TextQuery.getText(); } /** * sets the maximum number of rows to display. 0 means unlimited. * * @param rows the maximum number of rows */ public void setMaxRows(int rows) { if (rows >= 0) { m_SpinnerMaxRows.setValue(new Integer(rows)); } } /** * returns the current value for the maximum number of rows. 0 means * unlimited. * * @return the maximum number of rows */ public int getMaxRows() { return ((Integer) m_SpinnerMaxRows.getValue()).intValue(); } /** * adds the given listener to the list of listeners. * * @param l the listener to add to the list */ public void addQueryExecuteListener(QueryExecuteListener l) { m_QueryExecuteListeners.add(l); } /** * removes the given listener from the list of listeners. * * @param l the listener to remove */ public void removeQueryExecuteListener(QueryExecuteListener l) { m_QueryExecuteListeners.remove(l); } /** * notifies the listeners of the event. * * @param rs the resultset * @param ex the exception */ protected void notifyQueryExecuteListeners(ResultSet rs, Exception ex) { Iterator<QueryExecuteListener> iter; QueryExecuteListener l; iter = m_QueryExecuteListeners.iterator(); while (iter.hasNext()) { l = iter.next(); l.queryExecuted(new QueryExecuteEvent(this, m_DbUtils, getQuery(), getMaxRows(), rs, ex)); } } /** * adds the given listener to the list of listeners. * * @param l the listener to add to the list */ public void addHistoryChangedListener(HistoryChangedListener l) { m_HistoryChangedListeners.add(l); } /** * removes the given listener from the list of listeners. * * @param l the listener to remove */ public void removeHistoryChangedListener(HistoryChangedListener l) { m_HistoryChangedListeners.remove(l); } /** * notifies the history listeners of the event. */ protected void notifyHistoryChangedListeners() { Iterator<HistoryChangedListener> iter; HistoryChangedListener l; iter = m_HistoryChangedListeners.iterator(); while (iter.hasNext()) { l = iter.next(); l.historyChanged(new HistoryChangedEvent(this, HISTORY_NAME, getHistory())); } } /** * Called when the caret position is updated. * * @param event the event */ @Override public void caretUpdate(CaretEvent event) { setButtons(); } }
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/sql/ResultPanel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ResultPanel.java * Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.sql; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.HashSet; import java.util.Iterator; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.JViewport; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import weka.gui.JTableHelper; import weka.gui.sql.event.QueryExecuteEvent; import weka.gui.sql.event.QueryExecuteListener; import weka.gui.sql.event.ResultChangedEvent; import weka.gui.sql.event.ResultChangedListener; /** * Represents a panel for displaying the results of a query in table format. * * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class ResultPanel extends JPanel implements QueryExecuteListener, ChangeListener { /** for serialization */ private static final long serialVersionUID = 278654800344034571L; /** the parent of this panel */ protected JFrame m_Parent; /** the result change listeners */ protected HashSet<ResultChangedListener> m_Listeners; /** the panel where to output the queries */ protected QueryPanel m_QueryPanel; /** the tabbed pane for the results */ protected JTabbedPane m_TabbedPane; /** the close button */ protected JButton m_ButtonClose = new JButton("Close"); /** the close all button */ protected JButton m_ButtonCloseAll = new JButton("Close all"); /** the button that copies the query into the QueryPanel */ protected JButton m_ButtonCopyQuery = new JButton("Re-use query"); /** the button for the optimal column width of the current table */ protected JButton m_ButtonOptWidth = new JButton("Optimal width"); /** the counter for the tab names */ protected int m_NameCounter; /** * initializes the panel * * @param parent the parent of this panel */ public ResultPanel(JFrame parent) { super(); m_Parent = parent; m_QueryPanel = null; m_NameCounter = 0; m_Listeners = new HashSet<ResultChangedListener>(); createPanel(); } /** * creates the panel with all its components */ protected void createPanel() { JPanel panel; JPanel panel2; JPanel panel3; JPanel panel4; setLayout(new BorderLayout()); setPreferredSize(new Dimension(0, 200)); // tabbed pane m_TabbedPane = new JTabbedPane(JTabbedPane.BOTTOM); m_TabbedPane.addChangeListener(this); add(m_TabbedPane, BorderLayout.CENTER); // buttons panel = new JPanel(new BorderLayout()); add(panel, BorderLayout.EAST); panel2 = new JPanel(new BorderLayout()); panel.add(panel2, BorderLayout.CENTER); panel3 = new JPanel(new BorderLayout()); panel2.add(panel3, BorderLayout.CENTER); panel4 = new JPanel(new BorderLayout()); panel3.add(panel4, BorderLayout.CENTER); m_ButtonClose.setMnemonic('l'); m_ButtonClose.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { close(); } }); panel.add(m_ButtonClose, BorderLayout.NORTH); m_ButtonCloseAll.setMnemonic('a'); m_ButtonCloseAll.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { closeAll(); } }); panel2.add(m_ButtonCloseAll, BorderLayout.NORTH); m_ButtonCopyQuery.setMnemonic('Q'); m_ButtonCopyQuery .setToolTipText("Copies the query of the currently selected tab into the query field."); m_ButtonCopyQuery.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { copyQuery(); } }); panel3.add(m_ButtonCopyQuery, BorderLayout.NORTH); m_ButtonOptWidth.setMnemonic('p'); m_ButtonOptWidth .setToolTipText("Calculates the optimal column width for the current table."); m_ButtonOptWidth.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { calcOptimalWidth(); } }); panel4.add(m_ButtonOptWidth, BorderLayout.NORTH); // dummy place holder, otherwise is the space too small for the tabbed // pane panel4.add(new JLabel(" "), BorderLayout.CENTER); panel4.add(new JLabel(" "), BorderLayout.SOUTH); // set the initial button state setButtons(); } /** * sets the parameters back to standard */ public void clear() { closeAll(); } /** * sets the focus in a designated control */ public void setFocus() { m_TabbedPane.requestFocus(); } /** * sets the state of the buttons */ protected void setButtons() { int index; index = m_TabbedPane.getSelectedIndex(); m_ButtonClose.setEnabled(index > -1); m_ButtonCloseAll.setEnabled(m_TabbedPane.getTabCount() > 0); m_ButtonCopyQuery.setEnabled(index > -1); m_ButtonOptWidth.setEnabled(index > -1); } /** * returns the next name for a tab "QueryXYZ' */ protected String getNextTabName() { m_NameCounter++; return "Query" + m_NameCounter; } /** * This method gets called when a query has been executed. */ @Override public void queryExecuted(QueryExecuteEvent evt) { ResultSetTable table; // only displayed successful queries if (evt.failed()) { return; } // DDL command like drop etc that don't create ResultSet? if (!evt.hasResult()) { return; } try { table = new ResultSetTable(evt.getDbUtils().getDatabaseURL(), evt .getDbUtils().getUsername(), evt.getDbUtils().getPassword(), evt.getQuery(), new ResultSetTableModel(evt.getResultSet(), evt.getMaxRows())); m_TabbedPane.addTab(getNextTabName(), new JScrollPane(table)); // set active tab m_TabbedPane.setSelectedIndex(m_TabbedPane.getTabCount() - 1); } catch (Exception e) { e.printStackTrace(); } // set buttons setButtons(); } /** * Invoked when the target of the listener has changed its state. */ @Override public void stateChanged(ChangeEvent e) { // in case the tabs get clicked setButtons(); // notify listeners about current query if (getCurrentTable() != null) { notifyListeners(getCurrentTable().getURL(), getCurrentTable().getUser(), getCurrentTable().getPassword(), getCurrentTable().getQuery()); } } /** * returns the currently set QueryPanel, can be NULL * * @return the current QueryPanel, possibly NULL */ public QueryPanel getQueryPanel() { return m_QueryPanel; } /** * sets the QueryPanel to use for displaying the query * * @param panel the panel used for displaying the query */ public void setQueryPanel(QueryPanel panel) { m_QueryPanel = panel; } /** * returns the table of the current tab, can be NULL * * @return the currently selected table */ protected ResultSetTable getCurrentTable() { ResultSetTable table; JScrollPane pane; JViewport port; int index; table = null; index = m_TabbedPane.getSelectedIndex(); if (index > -1) { pane = (JScrollPane) m_TabbedPane.getComponentAt(index); port = (JViewport) pane.getComponent(0); table = (ResultSetTable) port.getComponent(0); } return table; } /** * closes the current tab */ protected void close() { int index; index = m_TabbedPane.getSelectedIndex(); if (index > -1) { try { getCurrentTable().finalize(); } catch (Throwable t) { System.out.println(t); } m_TabbedPane.removeTabAt(index); } // set buttons setButtons(); } /** * closes all tabs */ protected void closeAll() { while (m_TabbedPane.getTabCount() > 0) { m_TabbedPane.setSelectedIndex(0); try { getCurrentTable().finalize(); } catch (Throwable t) { System.out.println(t); } m_TabbedPane.removeTabAt(0); } // set buttons setButtons(); } /** * copies the query of the current tab into the QueryPanel */ protected void copyQuery() { if ((getCurrentTable() != null) && (getQueryPanel() != null)) { getQueryPanel().setQuery(getCurrentTable().getQuery()); } } /** * calculates the optimal column width for the current table */ protected void calcOptimalWidth() { if (getCurrentTable() != null) { JTableHelper.setOptimalColumnWidth(getCurrentTable()); } } /** * adds the given listener to the list of listeners * * @param l the listener to add to the list */ public void addResultChangedListener(ResultChangedListener l) { m_Listeners.add(l); } /** * removes the given listener from the list of listeners * * @param l the listener to remove */ public void removeResultChangedListener(ResultChangedListener l) { m_Listeners.remove(l); } /** * notifies the listeners of the event * * @param url the database URL * @param user the user * @param pw the password * @param query the query */ protected void notifyListeners(String url, String user, String pw, String query) { Iterator<ResultChangedListener> iter; ResultChangedListener l; iter = m_Listeners.iterator(); while (iter.hasNext()) { l = iter.next(); l.resultChanged(new ResultChangedEvent(this, url, user, pw, query)); } } }
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/sql/ResultSetHelper.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ResultSetHelper.java * Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.sql; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.Types; import java.util.Vector; /** * Represents an extended JTable, containing a table model based on a ResultSet * and the corresponding query. * * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class ResultSetHelper { /** the resultset to work on. */ protected ResultSet m_ResultSet; /** whether we initialized. */ protected boolean m_Initialized = false; /** the maximum number of rows to retrieve. */ protected int m_MaxRows = 0; /** the number of columns. */ protected int m_ColumnCount = 0; /** the number of rows. */ protected int m_RowCount = 0; /** the column names. */ protected String[] m_ColumnNames = null; /** whether a column is numeric. */ protected boolean[] m_NumericColumns = null; /** the class for each column. */ protected Class<?>[] m_ColumnClasses = null; /** * initializes the helper, with unlimited number of rows. * * @param rs the resultset to work on */ public ResultSetHelper(ResultSet rs) { this(rs, 0); } /** * initializes the helper, with the given maximum number of rows (less than 1 * means unlimited). * * @param rs the resultset to work on * @param max the maximum number of rows to retrieve */ public ResultSetHelper(ResultSet rs, int max) { super(); m_ResultSet = rs; m_MaxRows = max; } /** * initializes, i.e. reads the data, etc. */ protected void initialize() { ResultSetMetaData meta; int i; if (m_Initialized) { return; } try { meta = m_ResultSet.getMetaData(); // columns names m_ColumnNames = new String[meta.getColumnCount()]; for (i = 1; i <= meta.getColumnCount(); i++) { m_ColumnNames[i - 1] = meta.getColumnLabel(i); } // numeric columns m_NumericColumns = new boolean[meta.getColumnCount()]; for (i = 1; i <= meta.getColumnCount(); i++) { m_NumericColumns[i - 1] = typeIsNumeric(meta.getColumnType(i)); } // column classes m_ColumnClasses = new Class[meta.getColumnCount()]; for (i = 1; i <= meta.getColumnCount(); i++) { try { m_ColumnClasses[i - 1] = typeToClass(meta.getColumnType(i)); } catch (Exception ex) { m_ColumnClasses[i - 1] = String.class; } } // dimensions m_ColumnCount = meta.getColumnCount(); // if the JDBC driver doesn't support scrolling we can't determine // the row count here if (m_ResultSet.getType() == ResultSet.TYPE_FORWARD_ONLY) { m_RowCount = -1; } else { m_RowCount = 0; m_ResultSet.first(); if (m_MaxRows > 0) { try { m_ResultSet.absolute(m_MaxRows); m_RowCount = m_ResultSet.getRow(); } catch (Exception ex) { // ignore it } } else { m_ResultSet.last(); m_RowCount = m_ResultSet.getRow(); } // sometimes, e.g. with a "desc <table>", we can't use absolute(int) // and getRow()??? try { if ((m_RowCount == 0) && (m_ResultSet.first())) { m_RowCount = 1; while (m_ResultSet.next()) { m_RowCount++; if (m_ResultSet.getRow() == m_MaxRows) { break; } } ; } } catch (Exception e) { // ignore it } } m_Initialized = true; } catch (Exception ex) { // ignore it } } /** * the underlying resultset. * * @return the resultset */ public ResultSet getResultSet() { return m_ResultSet; } /** * returns the number of columns in the resultset. * * @return the number of columns */ public int getColumnCount() { initialize(); return m_ColumnCount; } /** * returns the number of rows in the resultset. If -1 then the number of rows * couldn't be determined, i.e., the cursors aren't scrollable. * * @return the number of rows, -1 if it wasn't possible to determine */ public int getRowCount() { initialize(); return m_RowCount; } /** * returns an array with the names of the columns in the resultset. * * @return the column names */ public String[] getColumnNames() { initialize(); return m_ColumnNames; } /** * returns an array that indicates whether a column is numeric or nor. * * @return the numeric columns */ public boolean[] getNumericColumns() { initialize(); return m_NumericColumns; } /** * returns the classes for the columns. * * @return the column classes */ public Class<?>[] getColumnClasses() { initialize(); return m_ColumnClasses; } /** * whether a limit on the rows to retrieve was set. * * @return true if there's a limit */ public boolean hasMaxRows() { return (m_MaxRows > 0); } /** * the maximum number of rows to retrieve, less than 1 means unlimited. * * @return the maximum number of rows */ public int getMaxRows() { return m_MaxRows; } /** * returns an 2-dimensional array with the content of the resultset, the first * dimension is the row, the second the column (i.e., getCells()[y][x]). Note: * the data is not cached! It is always retrieved anew. * * @return the data */ public Object[][] getCells() { int i; int n; Vector<Object[]> result; Object[] row; int rowCount; boolean proceed; initialize(); result = new Vector<Object[]>(); try { // do know the number of rows? rowCount = getRowCount(); if (rowCount == -1) { rowCount = getMaxRows(); proceed = m_ResultSet.next(); } else { proceed = m_ResultSet.first(); } if (proceed) { i = 0; while (true) { row = new Object[getColumnCount()]; result.add(row); for (n = 0; n < getColumnCount(); n++) { try { // to get around byte arrays when using getObject(int) if (getColumnClasses()[n] == String.class) { row[n] = m_ResultSet.getString(n + 1); } else { row[n] = m_ResultSet.getObject(n + 1); } } catch (Exception e) { row[n] = null; } } // get next row, if possible if (i == rowCount - 1) { break; } else { // no more rows -> exit if (!m_ResultSet.next()) { break; } } i++; } } } catch (Exception e) { e.printStackTrace(); } return result.toArray(new Object[result.size()][getColumnCount()]); } /** * Returns the class associated with a SQL type. * * @param type the SQL type * @return the Java class corresponding with the type */ public static Class<?> typeToClass(int type) { Class<?> result; switch (type) { case Types.BIGINT: result = Long.class; break; case Types.BINARY: result = String.class; break; case Types.BIT: result = Boolean.class; break; case Types.CHAR: result = Character.class; break; case Types.DATE: result = java.sql.Date.class; break; case Types.DECIMAL: result = Double.class; break; case Types.DOUBLE: result = Double.class; break; case Types.FLOAT: result = Float.class; break; case Types.INTEGER: result = Integer.class; break; case Types.LONGVARBINARY: result = String.class; break; case Types.LONGVARCHAR: result = String.class; break; case Types.NULL: result = String.class; break; case Types.NUMERIC: result = Double.class; break; case Types.OTHER: result = String.class; break; case Types.REAL: result = Double.class; break; case Types.SMALLINT: result = Short.class; break; case Types.TIME: result = java.sql.Time.class; break; case Types.TIMESTAMP: result = java.sql.Timestamp.class; break; case Types.TINYINT: result = Short.class; break; case Types.VARBINARY: result = String.class; break; case Types.VARCHAR: result = String.class; break; default: result = null; } return result; } /** * returns whether the SQL type is numeric (and therefore the justification * should be right). * * @param type the SQL type * @return whether the given type is numeric */ public static boolean typeIsNumeric(int type) { boolean result; switch (type) { case Types.BIGINT: result = true; break; case Types.BINARY: result = false; break; case Types.BIT: result = false; break; case Types.CHAR: result = false; break; case Types.DATE: result = false; break; case Types.DECIMAL: result = true; break; case Types.DOUBLE: result = true; break; case Types.FLOAT: result = true; break; case Types.INTEGER: result = true; break; case Types.LONGVARBINARY: result = false; break; case Types.LONGVARCHAR: result = false; break; case Types.NULL: result = false; break; case Types.NUMERIC: result = true; break; case Types.OTHER: result = false; break; case Types.REAL: result = true; break; case Types.SMALLINT: result = true; break; case Types.TIME: result = false; break; case Types.TIMESTAMP: result = true; break; case Types.TINYINT: result = true; break; case Types.VARBINARY: result = false; break; case Types.VARCHAR: result = false; break; default: result = false; } 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/sql/ResultSetTable.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ResultSetTable.java * Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.sql; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.JTable; import javax.swing.table.TableColumnModel; import weka.gui.JTableHelper; /** * Represents an extended JTable, containing a table model based on a ResultSet * and the corresponding query. * * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class ResultSetTable extends JTable { /** for serialization */ private static final long serialVersionUID = -3391076671854464137L; /** the query the table model is based on */ protected String m_Query; /** the connect string with which the query was run */ protected String m_URL; /** the user that was used to connect to the DB */ protected String m_User; /** the password that was used to connect to the DB */ protected String m_Password; /** * initializes the table * @param url the database URL * @param user the database user * @param pw the database password * @param query the query */ public ResultSetTable(String url, String user, String pw, String query, ResultSetTableModel model) { super(model); m_URL = url; m_User = user; m_Password = pw; m_Query = query; setAutoResizeMode(JTable.AUTO_RESIZE_OFF); // optimal colwidths (only according to header!)/cell renderer for (int i = 0; i < getColumnCount(); i++) { JTableHelper.setOptimalHeaderWidth(this, i); getColumnModel().getColumn(i).setCellRenderer( new ResultSetTableCellRenderer()); } // double click on column displays optimal colwidth final JTable table = this; getTableHeader().addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { TableColumnModel columnModel = getColumnModel(); int viewColumn = columnModel.getColumnIndexAtX(e.getX()); int column = convertColumnIndexToModel(viewColumn); if ( (e.getButton() == MouseEvent.BUTTON1) && (e.getClickCount() == 2) && (column != -1) ) JTableHelper.setOptimalColumnWidth(table, column); } }); getTableHeader().setToolTipText("double left click on column displays the column with optimal width"); } /** * returns the database URL that produced the table model */ public String getURL() { return m_URL; } /** * returns the user that produced the table model */ public String getUser() { return m_User; } /** * returns the password that produced the table model */ public String getPassword() { return m_Password; } /** * returns the query that produced the table model */ public String getQuery() { return m_Query; } /** * frees up the memory */ public void finalize() throws Throwable { if (getModel() != null) ((ResultSetTableModel) getModel()).finalize(); super.finalize(); System.gc(); } }
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/sql/ResultSetTableCellRenderer.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ResultSetTableCellRenderer.java * Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.sql; import java.awt.Color; import java.awt.Component; import javax.swing.JTable; import javax.swing.SwingConstants; import javax.swing.UIManager; import javax.swing.table.DefaultTableCellRenderer; /** * Handles the background colors for missing values differently than the * DefaultTableCellRenderer. * * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class ResultSetTableCellRenderer extends DefaultTableCellRenderer { /** for serialization */ private static final long serialVersionUID = -8106963669703497351L; // the color for missing values private final Color missingColor; private final Color missingColorSelected; /** * initializes the Renderer with a standard color */ public ResultSetTableCellRenderer() { this(new Color(223, 223, 223), new Color(192, 192, 192)); } /** * initializes the Renderer with the given colors */ public ResultSetTableCellRenderer(Color missingColor, Color missingColorSelected) { super(); this.missingColor = missingColor; this.missingColorSelected = missingColorSelected; } /** * Returns the default table cell renderer. stuff for the header is taken from * <a href="http://www.chka.de/swing/table/faq.html">here</a> */ @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { ResultSetTableModel model; Component result; // boolean found; NOT USED result = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); if (table.getModel() instanceof ResultSetTableModel) { model = (ResultSetTableModel) table.getModel(); // normal cell if (row >= 0) { if (model.isNullAt(row, column)) { setToolTipText("NULL"); if (isSelected) { result.setBackground(missingColorSelected); } else { result.setBackground(missingColor); } } else { setToolTipText(null); if (isSelected) { result.setBackground(table.getSelectionBackground()); } else { result.setBackground(Color.WHITE); } } // alignment if (model.isNumericAt(column)) { setHorizontalAlignment(SwingConstants.RIGHT); } else { setHorizontalAlignment(SwingConstants.LEFT); } } // header else { setBorder(UIManager.getBorder("TableHeader.cellBorder")); setHorizontalAlignment(SwingConstants.CENTER); if (table.getColumnModel().getSelectionModel().isSelectedIndex(column)) { result.setBackground(UIManager.getColor("TableHeader.background") .darker()); } else { result.setBackground(UIManager.getColor("TableHeader.background")); } } } 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/sql/ResultSetTableModel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ResultSetTableModel.java * Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.sql; import java.sql.ResultSet; import java.util.HashSet; import javax.swing.event.TableModelListener; import javax.swing.table.TableModel; /** * The model for an SQL ResultSet. * * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class ResultSetTableModel implements TableModel { /** the listeners. */ protected HashSet<TableModelListener> m_Listeners; /** the data. */ protected Object[][] m_Data; /** for retrieving the data etc. */ protected ResultSetHelper m_Helper; /** * initializes the model, retrieves all rows. * * @param rs the ResultSet to get the data from */ public ResultSetTableModel(ResultSet rs) { this(rs, 0); } /** * initializes the model, retrieves only the given amount of rows (0 means * all). * * @param rs the ResultSet to get the data from * @param rows the maximum number of rows to retrieve, 0 retrieves all */ public ResultSetTableModel(ResultSet rs, int rows) { super(); m_Listeners = new HashSet<TableModelListener>(); m_Helper = new ResultSetHelper(rs, rows); m_Data = m_Helper.getCells(); } /** * adds a listener to the list that is notified each time a change to data * model occurs. * * @param l the listener to add */ @Override public void addTableModelListener(TableModelListener l) { m_Listeners.add(l); } /** * returns the most specific superclass for all the cell values in the column * (always String). * * @param columnIndex the index of the column * @return the class */ @Override public Class<?> getColumnClass(int columnIndex) { Class<?> result; result = null; if ((m_Helper.getColumnClasses() != null) && (columnIndex >= 0) && (columnIndex < getColumnCount())) { if (columnIndex == 0) { result = Integer.class; } else { result = m_Helper.getColumnClasses()[columnIndex - 1]; } } return result; } /** * returns the number of columns in the model. * * @return the number of columns */ @Override public int getColumnCount() { return m_Helper.getColumnCount() + 1; } /** * returns the name of the column at columnIndex. * * @param columnIndex the index of the column * @return the name */ @Override public String getColumnName(int columnIndex) { String result; result = ""; if ((m_Helper.getColumnNames() != null) && (columnIndex >= 0) && (columnIndex < getColumnCount())) { if (columnIndex == 0) { result = "Row"; } else { result = m_Helper.getColumnNames()[columnIndex - 1]; } } return result; } /** * returns the number of rows in the model. * * @return the number of data rows */ @Override public int getRowCount() { return m_Data.length; } /** * returns the value for the cell at columnindex and rowIndex. * * @param rowIndex the row of the cell * @param columnIndex the column of the cell * @return the data value */ @Override public Object getValueAt(int rowIndex, int columnIndex) { Object result; result = null; if ((rowIndex >= 0) && (rowIndex < getRowCount()) && (columnIndex >= 0) && (columnIndex < getColumnCount())) { if (columnIndex == 0) { result = new Integer(rowIndex + 1); } else { result = m_Data[rowIndex][columnIndex - 1]; } } return result; } /** * checks whether the value of the cell is NULL. * * @param rowIndex the row of the cell * @param columnIndex the column of the cell * @return true if the cell value is NULL */ public boolean isNullAt(int rowIndex, int columnIndex) { return (getValueAt(rowIndex, columnIndex) == null); } /** * returns whether the column at the given index is numeric. * * @param columnIndex the column to check * @return whether the column is numeric */ public boolean isNumericAt(int columnIndex) { boolean result; result = false; if ((columnIndex >= 0) && (columnIndex < getColumnCount())) { if (columnIndex == 0) { result = true; } else { if (m_Helper.getNumericColumns() == null) { result = false; } else { result = m_Helper.getNumericColumns()[columnIndex - 1]; } } } return result; } /** * returns true if the cell at rowindex and columnindexis editable. * * @param rowIndex the row of the cell * @param columnIndex the column of the cell * @return always false */ @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return false; } /** * removes a listener from the list that is notified each time a change to the * data model occurs. * * @param l the listener to remove */ @Override public void removeTableModelListener(TableModelListener l) { m_Listeners.remove(l); } /** * sets the value in the cell at columnIndex and rowIndex to aValue. Ignored. * * @param aValue the value to set - ignored * @param rowIndex the row of the cell * @param columnIndex the column of the cell */ @Override public void setValueAt(Object aValue, int rowIndex, int columnIndex) { // ignore } /** * frees up the memory. * * @throws Throwable if something goes wrong */ @Override public void finalize() throws Throwable { try { m_Helper.getResultSet().close(); m_Helper.getResultSet().getStatement().close(); m_Helper = null; } catch (Exception e) { // ignored } m_Data = null; super.finalize(); } }
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/sql/SqlViewer.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * SqlViewer.java * Copyright (C) 2005-2018 University of Waikato, Hamilton, New Zealand * */ package weka.gui.sql; import weka.core.Memory; import weka.core.WekaPackageManager; import weka.gui.LookAndFeel; import weka.gui.sql.event.ConnectionEvent; import weka.gui.sql.event.ConnectionListener; import weka.gui.sql.event.HistoryChangedEvent; import weka.gui.sql.event.HistoryChangedListener; import weka.gui.sql.event.QueryExecuteEvent; import weka.gui.sql.event.QueryExecuteListener; import weka.gui.sql.event.ResultChangedEvent; import weka.gui.sql.event.ResultChangedListener; import javax.swing.BorderFactory; import javax.swing.DefaultListModel; import javax.swing.JFrame; import javax.swing.JPanel; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.Properties; /** * Represents a little tool for querying SQL databases. * * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class SqlViewer extends JPanel implements ConnectionListener, HistoryChangedListener, QueryExecuteListener, ResultChangedListener { /** for serialization. */ private static final long serialVersionUID = -4395028775566514329L; /** the name of the history file (in the home directory). */ protected final static String HISTORY_FILE = "SqlViewerHistory.props"; /** the width property in the history file. */ public final static String WIDTH = "width"; /** the height property in the history file. */ public final static String HEIGHT = "height"; /** the parent of this panel. */ protected JFrame m_Parent; /** the connection panel. */ protected ConnectionPanel m_ConnectionPanel; /** the query panel. */ protected QueryPanel m_QueryPanel; /** the result panel. */ protected ResultPanel m_ResultPanel; /** the info panel. */ protected InfoPanel m_InfoPanel; /** the connect string with which the query was run. */ protected String m_URL; /** the user that was used to connect to the DB. */ protected String m_User; /** the password that was used to connect to the DB. */ protected String m_Password; /** the currently selected query. */ protected String m_Query; /** stores the history. */ protected Properties m_History; /** * initializes the SqlViewer. * * @param parent the parent of this panel */ public SqlViewer(JFrame parent) { super(); m_Parent = parent; m_URL = ""; m_User = ""; m_Password = ""; m_Query = ""; m_History = new Properties(); createPanel(); } /** * builds the interface. */ protected void createPanel() { JPanel panel; JPanel panel2; setLayout(new BorderLayout()); // connection m_ConnectionPanel = new ConnectionPanel(m_Parent); panel = new JPanel(new BorderLayout()); add(panel, BorderLayout.NORTH); panel.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createTitledBorder("Connection"), BorderFactory.createEmptyBorder(0, 5, 5, 5))); panel.add(m_ConnectionPanel, BorderLayout.CENTER); // query m_QueryPanel = new QueryPanel(m_Parent); panel = new JPanel(new BorderLayout()); add(panel, BorderLayout.CENTER); panel2 = new JPanel(new BorderLayout()); panel2.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createTitledBorder("Query"), BorderFactory.createEmptyBorder(0, 5, 5, 5))); panel2.add(m_QueryPanel, BorderLayout.NORTH); panel.add(panel2, BorderLayout.NORTH); // result m_ResultPanel = new ResultPanel(m_Parent); m_ResultPanel.setQueryPanel(m_QueryPanel); panel2 = new JPanel(new BorderLayout()); panel2.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createTitledBorder("Result"), BorderFactory.createEmptyBorder(0, 5, 5, 5))); panel2.add(m_ResultPanel, BorderLayout.CENTER); panel.add(panel2, BorderLayout.CENTER); // info m_InfoPanel = new InfoPanel(m_Parent); panel = new JPanel(new BorderLayout()); add(panel, BorderLayout.SOUTH); panel.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createTitledBorder("Info"), BorderFactory.createEmptyBorder(0, 5, 5, 5))); panel.add(m_InfoPanel, BorderLayout.CENTER); // listeners addConnectionListener(this); addConnectionListener(m_QueryPanel); addQueryExecuteListener(this); addQueryExecuteListener(m_ResultPanel); addResultChangedListener(this); addHistoryChangedListener(this); // history loadHistory(true); } /** * This method gets called when the connection is either established or * disconnected. * * @param evt the event */ @Override public void connectionChange(ConnectionEvent evt) { if (evt.getType() == ConnectionEvent.DISCONNECT) { m_InfoPanel.append("disconnect from: " + evt.getDbUtils().getDatabaseURL(), "information_small.gif"); } else { m_InfoPanel.append("connecting to: " + evt.getDbUtils().getDatabaseURL() + " = " + evt.isConnected(), "information_small.gif"); } // did an exception happen? if (evt.getException() != null) { m_InfoPanel.append("exception: " + evt.getException(), "error_small.gif"); } // set focus if (evt.isConnected()) { m_QueryPanel.setFocus(); } else { m_ConnectionPanel.setFocus(); } } /** * This method gets called when a query has been executed. * * @param evt the event */ @Override public void queryExecuted(QueryExecuteEvent evt) { ResultSetHelper helper; if (evt.failed()) { m_InfoPanel.append("Query:" + evt.getQuery(), "error_small.gif"); m_InfoPanel.append("exception: " + evt.getException(), "error_small.gif"); } else { m_InfoPanel.append("Query: " + evt.getQuery(), "information_small.gif"); try { if (evt.hasResult()) { helper = new ResultSetHelper(evt.getResultSet()); if ((evt.getMaxRows() > 0) && (helper.getRowCount() >= evt.getMaxRows())) { m_InfoPanel.append( helper.getRowCount() + " rows selected (" + evt.getMaxRows() + " displayed).", "information_small.gif"); } else if (helper.getRowCount() == -1) { m_InfoPanel .append( "Unknown number of rows selected (due to JDBC driver restrictions).", "information_small.gif"); } else { m_InfoPanel.append(helper.getRowCount() + " rows selected.", "information_small.gif"); } } // save max rows loadHistory(false); m_History.setProperty(QueryPanel.MAX_ROWS, Integer.toString(evt.getMaxRows())); saveHistory(); } catch (Exception e) { e.printStackTrace(); } } } /** * This method gets called when a query has been executed. * * @param evt the event */ @Override public void resultChanged(ResultChangedEvent evt) { m_URL = evt.getURL(); m_User = evt.getUser(); m_Password = evt.getPassword(); m_Query = evt.getQuery(); } /** * This method gets called when a history is modified. It saves the history * immediately to the users home directory. * * @param evt the event */ @Override public void historyChanged(HistoryChangedEvent evt) { // load history, in case some other process changed it! loadHistory(false); m_History .setProperty(evt.getHistoryName(), modelToString(evt.getHistory())); // save it saveHistory(); } /** * returns the filename of the history file. * * @return the history file */ protected String getHistoryFilename() { return WekaPackageManager.PROPERTIES_DIR.getAbsolutePath() + File.separatorChar + HISTORY_FILE; } /** * transforms the given, comma-separated string into a DefaultListModel. * * @param s the string to break up and transform into a list model * @return the generated DefaultListModel */ protected DefaultListModel stringToModel(String s) { DefaultListModel result; String tmpStr; int i; boolean quote; String[] find; String[] replace; int index; result = new DefaultListModel(); // get rid of doubled quotes, \\n, etc. find = new String[] { "\"\"", "\\n", "\\r", "\\t" }; replace = new String[] { "\"", "\n", "\r", "\t" }; for (i = 0; i < find.length; i++) { tmpStr = ""; while (s.length() > 0) { index = s.indexOf(find[i]); if (index > -1) { tmpStr += s.substring(0, index) + replace[i]; s = s.substring(index + 2); } else { tmpStr += s; s = ""; } } s = tmpStr; } quote = false; tmpStr = ""; for (i = 0; i < s.length(); i++) { if (s.charAt(i) == '"') { quote = !quote; tmpStr += "" + s.charAt(i); } else if (s.charAt(i) == ',') { if (quote) { tmpStr += "" + s.charAt(i); } else { if (tmpStr.startsWith("\"")) { tmpStr = tmpStr.substring(1, tmpStr.length() - 1); } result.addElement(tmpStr); tmpStr = ""; } } else { tmpStr += "" + s.charAt(i); } } // add last element if (!tmpStr.equals("")) { if (tmpStr.startsWith("\"")) { tmpStr = tmpStr.substring(1, tmpStr.length() - 1); } result.addElement(tmpStr); } return result; } /** * converts the given model into a comma-separated string. * * @param m the model to convert * @return the string representation of the model */ protected String modelToString(DefaultListModel m) { String result; String tmpStr; int i; int n; boolean quote; result = ""; for (i = 0; i < m.size(); i++) { if (i > 0) { result += ","; } tmpStr = m.get(i).toString(); quote = (tmpStr.indexOf(",") > -1) || (tmpStr.indexOf(" ") > -1); if (quote) { result += "\""; } for (n = 0; n < tmpStr.length(); n++) { // double quotes if (tmpStr.charAt(n) == '"') { result += "" + "\"\""; // normal character } else { result += "" + tmpStr.charAt(n); } } if (quote) { result += "\""; } } return result; } /** * loads the history properties of the SqlViewer in the user's home directory. * * @param set whether to set the read properties in the panels or not * @see #HISTORY_FILE */ protected void loadHistory(boolean set) { BufferedInputStream str; File file; int width; int height; try { file = new File(getHistoryFilename()); if (file.exists()) { str = new BufferedInputStream(new FileInputStream(getHistoryFilename())); m_History.load(str); } } catch (Exception e) { e.printStackTrace(); } // set the histories if (set) { m_ConnectionPanel.setHistory(stringToModel(m_History.getProperty( ConnectionPanel.HISTORY_NAME, ""))); m_QueryPanel.setHistory(stringToModel(m_History.getProperty( QueryPanel.HISTORY_NAME, ""))); m_QueryPanel.setMaxRows(Integer.parseInt(m_History.getProperty( QueryPanel.MAX_ROWS, "100"))); width = Integer.parseInt(m_History.getProperty(WIDTH, "0")); height = Integer.parseInt(m_History.getProperty(HEIGHT, "0")); if ((width != 0) && (height != 0)) { setPreferredSize(new Dimension(width, height)); } } } /** * saves the history properties of the SqlViewer in the user's home directory. * * @see #HISTORY_FILE */ protected void saveHistory() { BufferedOutputStream str; try { str = new BufferedOutputStream(new FileOutputStream(getHistoryFilename())); m_History.store(str, "SQL-Viewer-History"); } catch (Exception e) { e.printStackTrace(); } } /** * obtains the size of the panel and saves it in the history. * * @see #saveHistory() */ public void saveSize() { m_History.setProperty(WIDTH, "" + getSize().width); m_History.setProperty(HEIGHT, "" + getSize().height); saveHistory(); } /** * calls the clear method of all sub-panels to set back to default values and * free up memory. */ public void clear() { m_ConnectionPanel.clear(); m_QueryPanel.clear(); m_ResultPanel.clear(); m_InfoPanel.clear(); } /** * returns the database URL from the currently active tab in the ResultPanel, * otherwise an empty string. * * @see ResultPanel * @return the currently selected tab's URL */ public String getURL() { return m_URL; } /** * returns the user from the currently active tab in the ResultPanel, * otherwise an empty string. * * @see ResultPanel * @return the currently selected tab's user */ public String getUser() { return m_User; } /** * returns the password from the currently active tab in the ResultPanel, * otherwise an empty string. * * @see ResultPanel * @return the currently selected tab's password */ public String getPassword() { return m_Password; } /** * returns the query from the currently active tab in the ResultPanel, * otherwise an empty string. * * @see ResultPanel * @return the currently selected tab's query */ public String getQuery() { return m_Query; } /** * adds the given listener to the list of listeners. * * @param l the listener to add to the list */ public void addConnectionListener(ConnectionListener l) { m_ConnectionPanel.addConnectionListener(l); } /** * removes the given listener from the list of listeners. * * @param l the listener to remove */ public void removeConnectionListener(ConnectionListener l) { m_ConnectionPanel.removeConnectionListener(l); } /** * adds the given listener to the list of listeners. * * @param l the listener to add to the list */ public void addQueryExecuteListener(QueryExecuteListener l) { m_QueryPanel.addQueryExecuteListener(l); } /** * removes the given listener from the list of listeners. * * @param l the listener to remove */ public void removeQueryExecuteListener(QueryExecuteListener l) { m_QueryPanel.removeQueryExecuteListener(l); } /** * adds the given listener to the list of listeners. * * @param l the listener to add to the list */ public void addResultChangedListener(ResultChangedListener l) { m_ResultPanel.addResultChangedListener(l); } /** * removes the given listener from the list of listeners. * * @param l the listener to remove */ public void removeResultChangedListener(ResultChangedListener l) { m_ResultPanel.removeResultChangedListener(l); } /** * adds the given listener to the list of listeners. * * @param l the listener to add to the list */ public void addHistoryChangedListener(HistoryChangedListener l) { m_ConnectionPanel.addHistoryChangedListener(l); m_QueryPanel.addHistoryChangedListener(l); } /** * removes the given listener from the list of listeners. * * @param l the listener to remove */ public void removeHistoryChangedListener(HistoryChangedListener l) { m_ConnectionPanel.removeHistoryChangedListener(l); m_QueryPanel.removeHistoryChangedListener(l); } /** for monitoring the Memory consumption. */ private static Memory m_Memory = new Memory(true); /** the sql viewer. */ private static SqlViewer m_Viewer; /** * starts the SQL-Viewer interface. * * @param args the commandline arguments - ignored */ public static void main(String[] args) { weka.core.logging.Logger.log(weka.core.logging.Logger.Level.INFO, "Logging started"); LookAndFeel.setLookAndFeel(); try { // uncomment to disable the memory management: // m_Memory.setEnabled(false); final JFrame jf = new JFrame("Weka SQL-Viewer"); m_Viewer = new SqlViewer(jf); jf.getContentPane().setLayout(new BorderLayout()); jf.getContentPane().add(m_Viewer, BorderLayout.CENTER); jf.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { m_Viewer.saveSize(); jf.dispose(); System.exit(0); } }); jf.pack(); jf.setSize(800, 600); jf.setVisible(true); Thread memMonitor = new Thread() { @Override public void run() { while (true) { // try { // Thread.sleep(10); if (m_Memory.isOutOfMemory()) { // clean up jf.dispose(); m_Viewer = 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.MAX_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/sql/SqlViewerDialog.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * SqlViewerDialog.java * Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.sql; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import weka.gui.sql.event.ResultChangedEvent; import weka.gui.sql.event.ResultChangedListener; /** * A little dialog containing the SqlViewer. * * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class SqlViewerDialog extends JDialog implements ResultChangedListener { /** for serialization. */ private static final long serialVersionUID = -31619864037233099L; /** the parent frame. */ protected JFrame m_Parent; /** the SQL panel. */ protected SqlViewer m_Viewer; /** the panel for the buttons. */ protected JPanel m_PanelButtons; /** the OK button. */ protected JButton m_ButtonOK = new JButton("OK"); /** the Cancel button. */ protected JButton m_ButtonCancel = new JButton("Cancel"); /** displays the current query. */ protected JLabel m_LabelQuery = new JLabel(""); /** whether to return sparse instances or not. */ protected JCheckBox m_CheckBoxSparseData = new JCheckBox("Generate sparse data"); /** the return value. */ protected int m_ReturnValue = JOptionPane.CANCEL_OPTION; /** the connect string with which the query was run. */ protected String m_URL; /** the user that was used to connect to the DB. */ protected String m_User; /** the password that was used to connect to the DB. */ protected String m_Password; /** the currently selected query. */ protected String m_Query; /** * initializes the dialog. * * @param parent the parent frame */ public SqlViewerDialog(JFrame parent) { super(parent, "SQL-Viewer", ModalityType.DOCUMENT_MODAL); m_Parent = parent; m_URL = ""; m_User = ""; m_Password = ""; m_Query = ""; createDialog(); } /** * builds the dialog and all its components. */ protected void createDialog() { JPanel panel; JPanel panel2; final SqlViewerDialog dialog; dialog = this; setLayout(new BorderLayout()); // sql panel m_Viewer = new SqlViewer(m_Parent); add(m_Viewer, BorderLayout.CENTER); panel2 = new JPanel(new BorderLayout()); add(panel2, BorderLayout.SOUTH); // Buttons panel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); panel2.add(panel, BorderLayout.EAST); m_ButtonOK.setMnemonic('O'); panel.add(m_ButtonOK); m_ButtonOK.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent evt){ m_ReturnValue = JOptionPane.OK_OPTION; // remove listener, otherwise does the disposal of resultspanel // change the query again! m_Viewer.removeResultChangedListener(dialog); m_Viewer.saveSize(); dialog.dispose(); } }); m_ButtonCancel.setMnemonic('C'); panel.add(m_ButtonCancel); m_ButtonCancel.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent evt){ m_ReturnValue = JOptionPane.CANCEL_OPTION; // remove listener, otherwise does the disposal of resultspanel // change the query again! m_Viewer.removeResultChangedListener(dialog); m_Viewer.saveSize(); dialog.dispose(); } }); // the checkbox for sparse data panel = new JPanel(new FlowLayout(FlowLayout.LEFT)); panel2.add(panel, BorderLayout.WEST); panel.add(m_CheckBoxSparseData); m_CheckBoxSparseData.setMnemonic('s'); addWindowListener(new WindowAdapter() { /** * Invoked when a window is in the process of being closed. */ public void windowClosing(WindowEvent e) { m_Viewer.saveSize(); } }); // current Query panel = new JPanel(new FlowLayout(FlowLayout.CENTER)); panel2.add(panel, BorderLayout.CENTER); panel.add(m_LabelQuery); pack(); getRootPane().setDefaultButton(m_ButtonOK); setResizable(true); // listener m_Viewer.addResultChangedListener(this); } /** * displays the dialog if TRUE. * * @param b if true displaying the dialog, hiding otherwise */ public void setVisible(boolean b) { if (b) m_ReturnValue = JOptionPane.CANCEL_OPTION; super.setVisible(b); // free up memory if (b) m_Viewer.clear(); } /** * returns whether the user clicked OK (JOptionPane.OK_OPTION) or whether he * cancelled the dialog (JOptionPane.CANCEL_OPTION). * @return the return value * @see JOptionPane */ public int getReturnValue() { return m_ReturnValue; } /** * returns the chosen URL, if any. * * @return the URL */ public String getURL() { return m_URL; } /** * returns the chosen user, if any. * * @return the user */ public String getUser() { return m_User; } /** * returns the chosen password, if any. * * @return the password */ public String getPassword() { return m_Password; } /** * returns the chosen query, if any. * * @return the query */ public String getQuery() { return m_Query; } /** * Returns whether sparse data is generated. * * @return true if sparse data is to be generated */ public boolean getGenerateSparseData() { return m_CheckBoxSparseData.isSelected(); } /** * This method gets called when a query has been executed. * * @param evt the event */ public void resultChanged(ResultChangedEvent evt) { m_URL = evt.getURL(); m_User = evt.getUser(); m_Password = evt.getPassword(); m_Query = evt.getQuery(); m_LabelQuery.setText("Current query: " + m_Query); } /** * for testing only. * * @param args ignored */ public static void main(String[] args) { SqlViewerDialog dialog; dialog = new SqlViewerDialog(null); dialog.setDefaultCloseOperation(SqlViewerDialog.DISPOSE_ON_CLOSE); dialog.setVisible(true); System.out.println("ReturnValue = " + dialog.getReturnValue()); if (dialog.getReturnValue() == JOptionPane.OK_OPTION) { System.out.println("URL = " + dialog.getURL()); System.out.println("User = " + dialog.getUser()); System.out.println("Password = " + dialog.getPassword().replaceAll(".", "*")); System.out.println("Query = " + dialog.getQuery()); } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/sql
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/sql/event/ConnectionEvent.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ConnectionEvent.java * Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.sql.event; import java.util.EventObject; import weka.gui.sql.DbUtils; /** * An event that is generated when a connection is established or dropped. * * @see ConnectionListener * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class ConnectionEvent extends EventObject { /** for serialization */ private static final long serialVersionUID = 5420308930427835037L; /** it was a connect try */ public final static int CONNECT = 0; /** it was a disconnect */ public final static int DISCONNECT = 1; /** the type of event, CONNECT or DISCONNECT */ protected int m_Type; /** the databaseutils instance reponsible for the connection */ protected DbUtils m_DbUtils; /** a possible exception that occurred if not successful */ protected Exception m_Exception; /** * constructs the event * @param source the source that generated this event * @param type whether CONNECT or DISCONNECT happened * @param utils the DatabaseUtils isntance responsible for the * connection */ public ConnectionEvent(Object source, int type, DbUtils utils) { this(source, type, utils, null); } /** * constructs the event * @param source the source that generated this event * @param type whether CONNECT or DISCONNECT happened * @param utils the DatabaseUtils isntance responsible for the * connection * @param ex a possible exception, if not successful */ public ConnectionEvent(Object source, int type, DbUtils utils, Exception ex) { super(source); m_Type = type; m_DbUtils = utils; m_Exception = ex; } /** * returns the type of this event, CONNECT or DISCONNECT * @return the type of this event * @see #CONNECT * @see #DISCONNECT */ public int getType() { return m_Type; } /** * whether an exception happened and is stored * @return whether an exception happened */ public boolean failed() { return (getException() != null); } /** * returns whether the connection is still open. * @return whether the connection is still open */ public boolean isConnected() { return m_DbUtils.isConnected(); } /** * returns the stored exception, if any (can be NULL) */ public Exception getException() { return m_Exception; } /** * returns the DbUtils instance that is responsible for the * connect/disconnect. * @return the responsible DbUtils instance */ public DbUtils getDbUtils() { return m_DbUtils; } /** * returns the event in a string representation * @return the event in a string representation */ public String toString() { String result; result = super.toString(); result = result.substring(0, result.length() - 1); // remove "]" result += ",url=" + m_DbUtils.getDatabaseURL() + ",user=" + m_DbUtils.getUsername() + ",password=" + m_DbUtils.getPassword().replaceAll(".", "*") + ",connected=" + isConnected() + ",exception=" + getException() + "]"; return result; } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/sql
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/sql/event/ConnectionListener.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ConnectionListener.java * Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.sql.event; import java.util.EventListener; /** * A listener for connect/disconnect events. * * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public interface ConnectionListener extends EventListener { /** * This method gets called when the connection is either established * or disconnected. */ public void connectionChange(ConnectionEvent evt); }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/sql
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/sql/event/HistoryChangedEvent.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * HistoryChangedEvent.java * Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.sql.event; import java.util.EventObject; import javax.swing.DefaultListModel; /** * An event that is generated when a history is modified. * * @see HistoryChangedListener * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class HistoryChangedEvent extends EventObject { /** for serialization */ private static final long serialVersionUID = 7476087315774869973L; /** the name of the history */ protected String m_HistoryName; /** the history model */ protected DefaultListModel m_History; /** * constructs the event * @param name the name of the history * @param history the model of the history */ public HistoryChangedEvent( Object source, String name, DefaultListModel history ) { super(source); m_HistoryName = name; m_History = history; } /** * returns the name of the history */ public String getHistoryName() { return m_HistoryName; } /** * returns the history model */ public DefaultListModel getHistory() { return m_History; } /** * returns the event in a string representation * @return the event in a string representation */ public String toString() { String result; result = super.toString(); result = result.substring(0, result.length() - 1); // remove "]" result += ",name=" + getHistoryName() + ",history=" + getHistory() + "]"; return result; } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/sql
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/sql/event/HistoryChangedListener.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * HistoryChangedListener.java * Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.sql.event; import java.util.EventListener; /** * A listener for changes in a history. * * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public interface HistoryChangedListener extends EventListener { /** * This method gets called when a history is modified. */ public void historyChanged(HistoryChangedEvent evt); }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/sql
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/sql/event/QueryExecuteEvent.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * QueryExecuteEvent.java * Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.sql.event; import java.sql.ResultSet; import java.util.EventObject; import weka.gui.sql.DbUtils; /** * An event that is generated when a query is executed. * * @see QueryExecuteListener * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class QueryExecuteEvent extends EventObject { /** for serialization */ private static final long serialVersionUID = -5556385019954730740L; /** the Db utils instance for the current DB connection */ protected DbUtils m_DbUtils; /** the query that was executed */ protected String m_Query; /** the produced ResultSet, if any */ protected ResultSet m_ResultSet; /** a possible exception, if the query failed */ protected Exception m_Exception; /** the maximum number of rows to retrieve */ protected int m_MaxRows; /** * constructs the event * @param source the source that generated this event * @param utils the DbUtils instance that connected to the DB * @param query the query that is the basis for the resultset * @param rows the maximum number of rows to retrieve (0 for all) * @param rs the ResultSet that was produced (depending on the * type of SQL query it can also be NULL) * @param ex in case an exception occurred */ public QueryExecuteEvent( Object source, DbUtils utils, String query, int rows, ResultSet rs, Exception ex ) { super(source); m_DbUtils = utils; m_Query = query; m_MaxRows = rows; m_ResultSet = rs; m_Exception = ex; } /** * returns the DbUtils instance that was executed the query */ public DbUtils getDbUtils() { return m_DbUtils; } /** * returns the query that was executed */ public String getQuery() { return m_Query; } /** * returns the maximum number of rows to retrieve. 0 means all. */ public int getMaxRows() { return m_MaxRows; } /** * is TRUE in case the exception is not NULL, i.e. the query failed */ public boolean failed() { return (m_Exception != null); } /** * whether a ResultSet was produced, e.g. DDL commands like delete, drop * or update do not produce one. */ public boolean hasResult() { return (m_ResultSet != null); } /** * returns the resultset that was produced, can be null in case the query * failed */ public ResultSet getResultSet() { return m_ResultSet; } /** * returns the exception, if one happened, otherwise NULL */ public Exception getException() { return m_Exception; } /** * returns the event in a string representation * @return the event in a string representation */ public String toString() { String result; result = super.toString(); result = result.substring(0, result.length() - 1); // remove "]" result += ",query=" + getQuery() + ",maxrows=" + getMaxRows() + ",failed=" + failed() + ",exception=" + getException() + "]"; return result; } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/sql
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/sql/event/QueryExecuteListener.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * QueryExecuteListener.java * Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.sql.event; import java.util.EventListener; /** * A listener for executing queries. * * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public interface QueryExecuteListener extends EventListener { /** * This method gets called when a query has been executed. * * @param evt the event */ public void queryExecuted(QueryExecuteEvent evt); }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/sql
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/sql/event/ResultChangedEvent.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ResultChangedEvent.java * Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.sql.event; import java.util.EventObject; /** * An event that is generated when a different Result is activated in the * ResultPanel. * * @see ResultChangedListener * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class ResultChangedEvent extends EventObject { /** for serialization */ private static final long serialVersionUID = 36042516077236111L; /** the query that is associated with the active result table */ protected String m_Query; /** the connect string with which the query was run */ protected String m_URL; /** the user that was used to connect to the DB */ protected String m_User; /** the password that was used to connect to the DB */ protected String m_Password; /** * constructs the event * @param source the source that generated this event * @param url the current database url * @param user the current user * @param pw the current password * @param query the current query */ public ResultChangedEvent(Object source, String url, String user, String pw, String query ) { super(source); m_URL = url; m_User = user; m_Password = pw; m_Query = query; } /** * returns the database URL that produced the table model */ public String getURL() { return m_URL; } /** * returns the user that produced the table model */ public String getUser() { return m_User; } /** * returns the password that produced the table model */ public String getPassword() { return m_Password; } /** * returns the query that was executed */ public String getQuery() { return m_Query; } /** * returns the event in a string representation * @return the event in a string representation */ public String toString() { String result; result = super.toString(); result = result.substring(0, result.length() - 1); // remove "]" result += ",url=" + getURL() + ",user=" + getUser() + ",password=" + getPassword().replaceAll(".", "*") + ",query=" + getQuery() + "]"; return result; } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/sql
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/sql/event/ResultChangedListener.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ResultChangedListener.java * Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.sql.event; import java.util.EventListener; /** * A listener that is notified if another Result is activated in the * ResultPanel. * * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public interface ResultChangedListener extends EventListener { /** * This method gets called when a query has been executed. */ public void resultChanged(ResultChangedEvent evt); }
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/streams/InstanceCounter.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * InstanceCounter.java * Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.streams; import java.awt.Color; import javax.swing.JLabel; import javax.swing.JPanel; import weka.core.Instance; import weka.core.Instances; /** * A bean that counts instances streamed to it. * * @author Len Trigg (trigg@cs.waikato.ac.nz) * @version $Revision$ */ public class InstanceCounter extends JPanel implements InstanceListener { /** for serialization */ private static final long serialVersionUID = -6084967152645935934L; private final JLabel m_Count_Lab; private int m_Count; private boolean m_Debug; public void input(Instance instance) throws Exception { if (m_Debug) { System.err.println("InstanceCounter::input(" + instance + ")"); } m_Count++; m_Count_Lab.setText("" + m_Count + " instances"); repaint(); } public void inputFormat(Instances instanceInfo) { if (m_Debug) { System.err.println("InstanceCounter::inputFormat()"); } // Instances inputInstances = new Instances(instanceInfo,0); NOT USED m_Count = 0; m_Count_Lab.setText("" + m_Count + " instances"); } public void setDebug(boolean debug) { m_Debug = debug; } public boolean getDebug() { return m_Debug; } public InstanceCounter() { m_Count = 0; m_Count_Lab = new JLabel("no instances"); add(m_Count_Lab); // setSize(60,40); setBackground(Color.lightGray); } @Override public void instanceProduced(InstanceEvent e) { Object source = e.getSource(); if (source instanceof InstanceProducer) { try { InstanceProducer a = (InstanceProducer) source; switch (e.getID()) { case InstanceEvent.FORMAT_AVAILABLE: inputFormat(a.outputFormat()); break; case InstanceEvent.INSTANCE_AVAILABLE: input(a.outputPeek()); break; case InstanceEvent.BATCH_FINISHED: if (m_Debug) { System.err .println("InstanceCounter::instanceProduced() - End of instance batch"); } break; default: System.err .println("InstanceCounter::instanceProduced() - unknown event type"); break; } } catch (Exception ex) { System.err.println(ex.getMessage()); } } else { System.err .println("InstanceCounter::instanceProduced() - Unknown source object type"); } } }
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/streams/InstanceEvent.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * InstanceEvent.java * Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.streams; import java.util.EventObject; /** * An event encapsulating an instance stream event. * * @author Len Trigg (trigg@cs.waikato.ac.nz) * @version $Revision$ */ public class InstanceEvent extends EventObject { /** for serialization */ private static final long serialVersionUID = 3207259868110667379L; /** Specifies that the instance format is available */ public static final int FORMAT_AVAILABLE = 1; /** Specifies that an instance is available */ public static final int INSTANCE_AVAILABLE = 2; /** Specifies that the batch of instances is finished */ public static final int BATCH_FINISHED = 3; private int m_ID; /** * Constructs an InstanceEvent with the specified source object and event * type * * @param source the object generating the InstanceEvent * @param ID the type of the InstanceEvent */ public InstanceEvent(Object source, int ID) { super(source); m_ID = ID; } /** * Get the event type * * @return the event type */ public int getID() { return m_ID; } }
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/streams/InstanceJoiner.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * InstanceJoiner.java * Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.streams; import java.io.Serializable; import java.util.Vector; import weka.core.Instance; import weka.core.Instances; /** * A bean that joins two streams of instances into one. * * @author Len Trigg (trigg@cs.waikato.ac.nz) * @version $Revision$ */ public class InstanceJoiner implements Serializable, InstanceProducer, SerialInstanceListener { /** for serialization */ private static final long serialVersionUID = -6529972700291329656L; /** The listeners */ private final Vector<InstanceListener> listeners; /** Debugging mode */ private boolean b_Debug; /** The input format for instances */ protected Instances m_InputFormat; /** The current output instance */ private Instance m_OutputInstance; /** Whether the first input batch has finished */ private boolean b_FirstInputFinished; // private boolean b_SecondInputFinished; NOT USED /** Setup the initial states of the member variables */ public InstanceJoiner() { listeners = new Vector<InstanceListener>(); m_InputFormat = null; m_OutputInstance = null; b_Debug = false; b_FirstInputFinished = false; // b_SecondInputFinished = false; NOT USED } /** * Sets the format of the input instances. If the filter is able to determine * the output format before seeing any input instances, it does so here. This * default implementation assumes the output format is determined when * batchFinished() is called. * * @param instanceInfo an Instances object containing the input instance * structure (any instances contained in the object are ignored - * only the structure is required). * @return true if the outputFormat may be collected immediately */ public boolean inputFormat(Instances instanceInfo) { m_InputFormat = new Instances(instanceInfo, 0); notifyInstanceProduced(new InstanceEvent(this, InstanceEvent.FORMAT_AVAILABLE)); b_FirstInputFinished = false; // b_SecondInputFinished = false; NOT USED return true; } /** * Gets the format of the output instances. This should only be called after * input() or batchFinished() has returned true. * * @return an Instances object containing the output instance structure only. * @throws Exception if no input structure has been defined (or the output * format hasn't been determined yet) */ @Override public Instances outputFormat() throws Exception { if (m_InputFormat == null) { throw new Exception("No output format defined."); } return new Instances(m_InputFormat, 0); } public boolean input(Instance instance) throws Exception { if (m_InputFormat == null) { throw new Exception("No input instance format defined"); } if (instance != null) { m_OutputInstance = (Instance) instance.copy(); notifyInstanceProduced(new InstanceEvent(this, InstanceEvent.INSTANCE_AVAILABLE)); return true; } return false; } /** * Signify that this batch of input to the filter is finished. If the filter * requires all instances prior to filtering, output() may now be called to * retrieve the filtered instances. Any subsequent instances filtered should * be filtered based on setting obtained from the first batch (unless the * inputFormat has been re-assigned or new options have been set). This * default implementation assumes all instance processing occurs during * inputFormat() and input(). * * @throws Exception if no input structure has been defined */ public void batchFinished() throws Exception { if (m_InputFormat == null) { throw new Exception("No input instance format defined"); } notifyInstanceProduced(new InstanceEvent(this, InstanceEvent.BATCH_FINISHED)); } /** * Output an instance after filtering but do not remove from the output queue. * * @return the instance that has most recently been filtered (or null if the * queue is empty). * @throws Exception if no input structure has been defined */ @Override public Instance outputPeek() throws Exception { if (m_InputFormat == null) { throw new Exception("No output instance format defined"); } if (m_OutputInstance == null) { return null; } return (Instance) m_OutputInstance.copy(); } public void setDebug(boolean debug) { b_Debug = debug; } public boolean getDebug() { return b_Debug; } @Override public synchronized void addInstanceListener(InstanceListener ipl) { listeners.addElement(ipl); } @Override public synchronized void removeInstanceListener(InstanceListener ipl) { listeners.removeElement(ipl); } @SuppressWarnings("unchecked") protected void notifyInstanceProduced(InstanceEvent e) { if (listeners.size() > 0) { if (b_Debug) { System.err.println(this.getClass().getName() + "::notifyInstanceProduced()"); } Vector<InstanceListener> l; synchronized (this) { l = (Vector<InstanceListener>) listeners.clone(); } for (int i = 0; i < l.size(); i++) { l.elementAt(i).instanceProduced(e); } // If there are any listeners, and the event is an INSTANCE_AVAILABLE, // they should have retrieved the instance with outputPeek(); try { if (e.getID() == InstanceEvent.INSTANCE_AVAILABLE) { m_OutputInstance = null; } } catch (Exception ex) { System.err.println("Problem: notifyInstanceProduced() was\n" + "called with INSTANCE_AVAILABLE, but output()\n" + "threw an exception: " + ex.getMessage()); } } } public void instanceProduced(InstanceEvent e) { Object source = e.getSource(); if (source instanceof InstanceProducer) { try { InstanceProducer a = (InstanceProducer) source; switch (e.getID()) { case InstanceEvent.FORMAT_AVAILABLE: if (b_Debug) { System.err.println(this.getClass().getName() + "::firstInstanceProduced() - Format available"); } inputFormat(a.outputFormat()); break; case InstanceEvent.INSTANCE_AVAILABLE: if (b_Debug) { System.err.println(this.getClass().getName() + "::firstInstanceProduced() - Instance available"); } input(a.outputPeek()); break; case InstanceEvent.BATCH_FINISHED: if (b_Debug) { System.err.println(this.getClass().getName() + "::firstInstanceProduced() - End of instance batch"); } batchFinished(); b_FirstInputFinished = true; break; default: System.err.println(this.getClass().getName() + "::firstInstanceProduced() - unknown event type"); break; } } catch (Exception ex) { System.err.println(ex.getMessage()); } } else { System.err.println(this.getClass().getName() + "::firstInstanceProduced() - Unknown source object type"); } } @Override public void secondInstanceProduced(InstanceEvent e) { Object source = e.getSource(); if (source instanceof InstanceProducer) { try { if (!b_FirstInputFinished) { throw new Exception(this.getClass().getName() + "::secondInstanceProduced() - Input received from" + " second stream before first stream finished"); } InstanceProducer a = (InstanceProducer) source; switch (e.getID()) { case InstanceEvent.FORMAT_AVAILABLE: if (b_Debug) { System.err.println(this.getClass().getName() + "::secondInstanceProduced() - Format available"); } // Check the formats are compatible if (!(a.outputFormat()).equalHeaders(outputFormat())) { throw new Exception(this.getClass().getName() + "::secondInstanceProduced() - incompatible instance streams\n" + (a.outputFormat()).equalHeadersMsg(outputFormat())); } break; case InstanceEvent.INSTANCE_AVAILABLE: if (b_Debug) { System.err.println(this.getClass().getName() + "::secondInstanceProduced() - Instance available"); } input(a.outputPeek()); break; case InstanceEvent.BATCH_FINISHED: if (b_Debug) { System.err.println(this.getClass().getName() + "::secondInstanceProduced() - End of instance batch"); } batchFinished(); break; default: System.err.println(this.getClass().getName() + "::secondInstanceProduced() - unknown event type"); break; } } catch (Exception ex) { System.err.println(ex.getMessage()); } } else { System.err.println(this.getClass().getName() + "::secondInstanceProduced() - Unknown source object type"); } } }
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/streams/InstanceListener.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * InstanceListener.java * Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.streams; import java.util.EventListener; /** * An interface for objects interested in listening to streams of instances. * * @author Len Trigg (trigg@cs.waikato.ac.nz) * @version $Revision$ */ public interface InstanceListener extends EventListener { void instanceProduced(InstanceEvent e); }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/streams/InstanceLoader.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * InstanceLoader.java * Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.streams; import java.awt.BorderLayout; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.FileReader; import java.io.Reader; import java.util.Vector; import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.JTextField; import weka.core.Instance; import weka.core.Instances; /** * A bean that produces a stream of instances from a file. * * @author Len Trigg (trigg@cs.waikato.ac.nz) * @version $Revision$ */ public class InstanceLoader extends JPanel implements ActionListener, InstanceProducer { /** for serialization */ private static final long serialVersionUID = -8725567310271862492L; private final Vector<InstanceListener> m_Listeners; private Thread m_LoaderThread; private Instance m_OutputInstance; private Instances m_OutputInstances; private boolean m_Debug; private final JButton m_StartBut; private final JTextField m_FileNameTex; private class LoadThread extends Thread { private final InstanceProducer m_IP; public LoadThread(InstanceProducer ip) { m_IP = ip; } @SuppressWarnings("deprecation") @Override public void run() { try { m_StartBut.setText("Stop"); m_StartBut.setBackground(Color.red); if (m_Debug) { System.err.println("InstanceLoader::LoadThread::run()"); } // Load the instances one at a time and pass them on to the listener Reader input = new BufferedReader(new FileReader( m_FileNameTex.getText())); m_OutputInstances = new Instances(input, 1); if (m_Debug) { System.err.println("InstanceLoader::LoadThread::run()" + " - Instances opened from: " + m_FileNameTex.getText()); } InstanceEvent ie = new InstanceEvent(m_IP, InstanceEvent.FORMAT_AVAILABLE); notifyInstanceProduced(ie); while (m_OutputInstances.readInstance(input)) { if (m_LoaderThread != this) { return; } if (m_Debug) { System.err.println("InstanceLoader::LoadThread::run()" + " - read instance"); } // put the instance into a queue? m_OutputInstance = m_OutputInstances.instance(0); m_OutputInstances.delete(0); ie = new InstanceEvent(m_IP, InstanceEvent.INSTANCE_AVAILABLE); notifyInstanceProduced(ie); } ie = new InstanceEvent(m_IP, InstanceEvent.BATCH_FINISHED); notifyInstanceProduced(ie); } catch (Exception ex) { System.err.println(ex.getMessage()); } finally { m_LoaderThread = null; m_StartBut.setText("Start"); m_StartBut.setBackground(Color.green); } } } public InstanceLoader() { setLayout(new BorderLayout()); m_StartBut = new JButton("Start"); m_StartBut.setBackground(Color.green); add("West", m_StartBut); m_StartBut.addActionListener(this); m_FileNameTex = new JTextField("/home/trigg/datasets/UCI/iris.arff"); add("Center", m_FileNameTex); m_Listeners = new Vector<InstanceListener>(); // setSize(60,40); } public void setDebug(boolean debug) { m_Debug = debug; } public boolean getDebug() { return m_Debug; } public void setArffFile(String newArffFile) { m_FileNameTex.setText(newArffFile); } public String getArffFile() { return m_FileNameTex.getText(); } @Override public synchronized void addInstanceListener(InstanceListener ipl) { m_Listeners.addElement(ipl); } @Override public synchronized void removeInstanceListener(InstanceListener ipl) { m_Listeners.removeElement(ipl); } @SuppressWarnings("unchecked") protected void notifyInstanceProduced(InstanceEvent e) { if (m_Debug) { System.err.println("InstanceLoader::notifyInstanceProduced()"); } Vector<InstanceListener> l; synchronized (this) { l = (Vector<InstanceListener>) m_Listeners.clone(); } if (l.size() > 0) { for (int i = 0; i < l.size(); i++) { l.elementAt(i).instanceProduced(e); } if (e.getID() == InstanceEvent.INSTANCE_AVAILABLE) { m_OutputInstance = null; } } } @Override public Instances outputFormat() throws Exception { if (m_OutputInstances == null) { throw new Exception("No output format defined."); } return new Instances(m_OutputInstances, 0); } @Override public Instance outputPeek() throws Exception { if ((m_OutputInstances == null) || (m_OutputInstance == null)) { return null; } return (Instance) m_OutputInstance.copy(); } @Override public void actionPerformed(ActionEvent e) { Object source = e.getSource(); if (source == m_StartBut) { // load the arff file and send the instances out to the listener if (m_LoaderThread == null) { m_LoaderThread = new LoadThread(this); m_LoaderThread.setPriority(Thread.MIN_PRIORITY); m_LoaderThread.start(); } else { m_LoaderThread = 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/streams/InstanceProducer.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * InstanceProducer.java * Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.streams; import weka.core.Instance; import weka.core.Instances; /** * An interface for objects capable of producing streams of instances. * * @author Len Trigg (trigg@cs.waikato.ac.nz) * @version $Revision$ */ public interface InstanceProducer { void addInstanceListener(InstanceListener ipl); void removeInstanceListener(InstanceListener ipl); Instances outputFormat() throws Exception; Instance outputPeek() 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/streams/InstanceSavePanel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * InstanceSavePanel.java * Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.streams; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Label; import java.awt.Panel; import java.awt.TextField; import java.io.FileOutputStream; import java.io.PrintWriter; import weka.core.Instance; import weka.core.Instances; /** * A bean that saves a stream of instances to a file. * * @author Len Trigg (trigg@cs.waikato.ac.nz) * @version $Revision$ */ public class InstanceSavePanel extends Panel implements InstanceListener { /** for serialization */ private static final long serialVersionUID = -6061005366989295026L; private Label count_Lab; private int m_Count; private TextField arffFile_Tex; private boolean b_Debug; private PrintWriter outputWriter; public void input(Instance instance) throws Exception { if (b_Debug) System.err.println("InstanceSavePanel::input(" + instance +")"); m_Count++; count_Lab.setText(""+m_Count+" instances"); if (outputWriter != null) outputWriter.println(instance.toString()); } public void inputFormat(Instances instanceInfo) { if (b_Debug) System.err.println("InstanceSavePanel::inputFormat()\n" +instanceInfo.toString()); m_Count = 0; count_Lab.setText(""+m_Count+" instances"); try { outputWriter = new PrintWriter(new FileOutputStream(arffFile_Tex.getText())); outputWriter.println(instanceInfo.toString()); if (b_Debug) System.err.println("InstanceSavePanel::inputFormat() - written header"); } catch (Exception ex) { outputWriter = null; System.err.println("InstanceSavePanel::inputFormat(): "+ex.getMessage()); } } public void batchFinished() { if (b_Debug) System.err.println("InstanceSavePanel::batchFinished()"); if (outputWriter != null) outputWriter.close(); } public InstanceSavePanel() { setLayout(new BorderLayout()); arffFile_Tex = new TextField("arffoutput.arff"); add("Center", arffFile_Tex); count_Lab = new Label("0 instances"); add("East", count_Lab); // setSize(60,40); setBackground(Color.lightGray); } public void setDebug(boolean debug) { b_Debug = debug; } public boolean getDebug() { return b_Debug; } public void setArffFile(String newArffFile) { arffFile_Tex.setText(newArffFile); } public String getArffFile() { return arffFile_Tex.getText(); } public void instanceProduced(InstanceEvent e) { Object source = e.getSource(); if (source instanceof InstanceProducer) { try { InstanceProducer a = (InstanceProducer) source; switch (e.getID()) { case InstanceEvent.FORMAT_AVAILABLE: inputFormat(a.outputFormat()); break; case InstanceEvent.INSTANCE_AVAILABLE: input(a.outputPeek()); break; case InstanceEvent.BATCH_FINISHED: batchFinished(); break; default: System.err.println("InstanceSavePanel::instanceProduced() - unknown event type"); break; } } catch (Exception ex) { System.err.println(ex.getMessage()); } } else { System.err.println("InstanceSavePanel::instanceProduced() - Unknown source object type"); } } }
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/streams/InstanceTable.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * InstanceTable.java * Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.streams; import java.awt.BorderLayout; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.AbstractTableModel; import javax.swing.table.TableModel; import weka.core.Instance; import weka.core.Instances; /** * A bean that takes a stream of instances and displays in a table. * * @author Len Trigg (trigg@cs.waikato.ac.nz) * @version $Revision$ */ public class InstanceTable extends JPanel implements InstanceListener { /** for serialization */ private static final long serialVersionUID = -2462533698100834803L; private final JTable m_InstanceTable; private boolean m_Debug; // private boolean m_Clear; NOT USED // private String m_UpdateString; NOT USED private Instances m_Instances; public void inputFormat(Instances instanceInfo) { if (m_Debug) { System.err.println("InstanceTable::inputFormat()\n" + instanceInfo.toString()); } m_Instances = instanceInfo; } public void input(Instance instance) throws Exception { if (m_Debug) { System.err.println("InstanceTable::input(" + instance + ")"); } m_Instances.add(instance); } public void batchFinished() { TableModel newModel = new AbstractTableModel() { private static final long serialVersionUID = 5447106383000555291L; @Override public String getColumnName(int col) { return m_Instances.attribute(col).name(); } @Override public Class<?> getColumnClass(int col) { return "".getClass(); } @Override public int getColumnCount() { return m_Instances.numAttributes(); } @Override public int getRowCount() { return m_Instances.numInstances(); } @Override public Object getValueAt(int row, int col) { return new String(m_Instances.instance(row).toString(col)); } }; m_InstanceTable.setModel(newModel); if (m_Debug) { System.err.println("InstanceTable::batchFinished()"); } } public InstanceTable() { setLayout(new BorderLayout()); m_InstanceTable = new JTable(); add("Center", new JScrollPane(m_InstanceTable)); } public void setDebug(boolean debug) { m_Debug = debug; } public boolean getDebug() { return m_Debug; } @Override public void instanceProduced(InstanceEvent e) { Object source = e.getSource(); if (source instanceof InstanceProducer) { try { InstanceProducer a = (InstanceProducer) source; switch (e.getID()) { case InstanceEvent.FORMAT_AVAILABLE: inputFormat(a.outputFormat()); break; case InstanceEvent.INSTANCE_AVAILABLE: input(a.outputPeek()); break; case InstanceEvent.BATCH_FINISHED: batchFinished(); break; default: System.err.println("InstanceTable::instanceProduced()" + " - unknown event type"); break; } } catch (Exception ex) { System.err.println(ex.getMessage()); } } else { System.err.println("InstanceTable::instanceProduced()" + " - Unknown source object type"); } } }
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/streams/InstanceViewer.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * InstanceViewer.java * Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.streams; import java.awt.BorderLayout; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import weka.core.Instance; import weka.core.Instances; /** * This is a very simple instance viewer - just displays the dataset as * text output as it would be written to a file. A more complex viewer * might be more spreadsheet-like * * @author Len Trigg (trigg@cs.waikato.ac.nz) * @version $Revision$ */ public class InstanceViewer extends JPanel implements InstanceListener { /** for serialization */ private static final long serialVersionUID = -4925729441294121772L; private JTextArea m_OutputTex; private boolean m_Debug; private boolean m_Clear; private String m_UpdateString; private void updateOutput() { m_OutputTex.append(m_UpdateString); m_UpdateString = ""; } private void clearOutput() { m_UpdateString = ""; m_OutputTex.setText(""); } public void inputFormat(Instances instanceInfo) { if (m_Debug) { System.err.println("InstanceViewer::inputFormat()\n" + instanceInfo.toString()); } if (m_Clear) { clearOutput(); } m_UpdateString += instanceInfo.toString(); updateOutput(); } public void input(Instance instance) throws Exception { if (m_Debug) { System.err.println("InstanceViewer::input(" + instance +")"); } m_UpdateString += instance.toString() + "\n"; updateOutput(); } public void batchFinished() { updateOutput(); if (m_Debug) { System.err.println("InstanceViewer::batchFinished()"); } } public InstanceViewer() { setLayout(new BorderLayout()); m_UpdateString = ""; setClearEachDataset(true); m_OutputTex = new JTextArea(10,20); m_OutputTex.setEditable(false); add("Center", new JScrollPane(m_OutputTex)); } public void setClearEachDataset(boolean clear) { m_Clear = clear; } public boolean getClearEachDataset() { return m_Clear; } public void setDebug(boolean debug) { m_Debug = debug; } public boolean getDebug() { return m_Debug; } public void instanceProduced(InstanceEvent e) { Object source = e.getSource(); if (source instanceof InstanceProducer) { try { InstanceProducer a = (InstanceProducer) source; switch (e.getID()) { case InstanceEvent.FORMAT_AVAILABLE: inputFormat(a.outputFormat()); break; case InstanceEvent.INSTANCE_AVAILABLE: input(a.outputPeek()); break; case InstanceEvent.BATCH_FINISHED: batchFinished(); break; default: System.err.println("InstanceViewer::instanceProduced()" + " - unknown event type"); break; } } catch (Exception ex) { System.err.println(ex.getMessage()); } } else { System.err.println("InstanceViewer::instanceProduced()" + " - Unknown source object type"); } } }
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/streams/SerialInstanceListener.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * SerialInstanceListener.java * Copyright (C) 1998-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.streams; /** * Defines an interface for objects able to produce two output streams of * instances. * * @author Len Trigg (trigg@cs.waikato.ac.nz) * @version $Revision$ */ public interface SerialInstanceListener extends java.util.EventListener { void secondInstanceProduced(InstanceEvent e); }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/treevisualizer/Colors.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * Colors.java * Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.treevisualizer; /** * This class maintains a list that contains all the colornames from the * dotty standard and what color (in RGB) they represent * * @author Malcolm Ware (mfw4@cs.waikato.ac.nz) * @version $Revision$ */ public class Colors { /** The array with all the colors input */ public NamedColor[] m_cols = { new NamedColor("snow",255, 250, 250), new NamedColor("ghostwhite",248, 248, 255), new NamedColor("whitesmoke",245, 245, 245), new NamedColor("gainsboro",220, 220, 220), new NamedColor("floralwhite",255, 250, 240), new NamedColor("oldlace",253, 245, 230), new NamedColor("linen",250, 240, 230), new NamedColor("antiquewhite",250, 235, 215), new NamedColor("papayawhip",255, 239, 213), new NamedColor("blanchedalmond",255, 235, 205), new NamedColor("bisque",255, 228, 196), new NamedColor("peachpuff",255, 218, 185), new NamedColor("navajowhite",255, 222, 173), new NamedColor("moccasin",255, 228, 181), new NamedColor("cornsilk",255, 248, 220), new NamedColor("ivory",255, 255, 240), new NamedColor("lemonchiffon",255, 250, 205), new NamedColor("seashell",255, 245, 238), new NamedColor("honeydew",240, 255, 240), new NamedColor("mintcream",245, 255, 250), new NamedColor("azure",240, 255, 255), new NamedColor("aliceblue",240, 248, 255), new NamedColor("lavender",230, 230, 250), new NamedColor("lavenderblush",255, 240, 245), new NamedColor("mistyrose",255, 228, 225), new NamedColor("white",255, 255, 255), new NamedColor("black", 0, 0, 0), new NamedColor("darkslategray", 47, 79, 79), new NamedColor("dimgray",105, 105, 105), new NamedColor("slategray",112, 128, 144), new NamedColor("lightslategray",119, 136, 153), new NamedColor("gray",190, 190, 190), new NamedColor("lightgray",211, 211, 211), new NamedColor("midnightblue", 25, 25, 112), new NamedColor("navy", 0, 0, 128), new NamedColor("cornflowerblue",100, 149, 237), new NamedColor("darkslateblue", 72, 61, 139), new NamedColor("slateblue",106, 90, 205), new NamedColor("mediumslateblue",123, 104, 238), new NamedColor("lightslateblue",132, 112, 255), new NamedColor("mediumblue", 0, 0, 205), new NamedColor("royalblue", 65, 105, 225), new NamedColor("blue", 0, 0, 255), new NamedColor("dodgerblue", 30, 144, 255), new NamedColor("deepskyblue", 0, 191, 255), new NamedColor("skyblue",135, 206, 235), new NamedColor("lightskyblue",135, 206, 250), new NamedColor("steelblue", 70, 130, 180), new NamedColor("lightsteelblue",176, 196, 222), new NamedColor("lightblue",173, 216, 230), new NamedColor("powderblue",176, 224, 230), new NamedColor("paleturquoise",175, 238, 238), new NamedColor("darkturquoise", 0, 206, 209), new NamedColor("mediumturquoise", 72, 209, 204), new NamedColor("turquoise", 64, 224, 208), new NamedColor("cyan", 0, 255, 255), new NamedColor("lightcyan",224, 255, 255), new NamedColor("cadetblue", 95, 158, 160), new NamedColor("mediumaquamarine",102, 205, 170), new NamedColor("aquamarine",127, 255, 212), new NamedColor("darkgreen", 0, 100, 0), new NamedColor("darkolivegreen", 85, 107, 47), new NamedColor("darkseagreen",143, 188, 143), new NamedColor("seagreen", 46, 139, 87), new NamedColor("mediumseagreen", 60, 179, 113), new NamedColor("lightseagreen", 32, 178, 170), new NamedColor("palegreen",152, 251, 152), new NamedColor("springgreen", 0, 255, 127), new NamedColor("lawngreen",124, 252, 0), new NamedColor("green", 0, 255, 0), new NamedColor("chartreuse",127, 255, 0), new NamedColor("mediumspringgreen", 0, 250, 154), new NamedColor("greenyellow",173, 255, 47), new NamedColor("limegreen", 50, 205, 50), new NamedColor("yellowgreen",154, 205, 50), new NamedColor("forestgreen", 34, 139, 34), new NamedColor("olivedrab",107, 142, 35), new NamedColor("darkkhaki",189, 183, 107), new NamedColor("khaki",240, 230, 140), new NamedColor("palegoldenrod",238, 232, 170), new NamedColor("lightgoldenrodyellow",250, 250, 210), new NamedColor("lightyellow",255, 255, 224), new NamedColor("yellow",255, 255, 0), new NamedColor("gold",255, 215, 0), new NamedColor("lightgoldenrod",238, 221, 130), new NamedColor("goldenrod",218, 165, 32), new NamedColor("darkgoldenrod",184, 134, 11), new NamedColor("rosybrown",188, 143, 143), new NamedColor("indianred",205, 92, 92), new NamedColor("saddlebrown",139, 69, 19), new NamedColor("sienna",160, 82, 45), new NamedColor("peru",205, 133, 63), new NamedColor("burlywood",222, 184, 135), new NamedColor("beige",245, 245, 220), new NamedColor("wheat",245, 222, 179), new NamedColor("sandybrown",244, 164, 96), new NamedColor("tan",210, 180, 140), new NamedColor("chocolate",210, 105, 30), new NamedColor("firebrick",178, 34, 34), new NamedColor("brown",165, 42, 42), new NamedColor("darksalmon",233, 150, 122), new NamedColor("salmon",250, 128, 114), new NamedColor("lightsalmon",255, 160, 122), new NamedColor("orange",255, 165, 0), new NamedColor("darkorange",255, 140, 0), new NamedColor("coral",255, 127, 80), new NamedColor("lightcoral",240, 128, 128), new NamedColor("tomato",255, 99, 71), new NamedColor("orangered",255, 69, 0), new NamedColor("red",255, 0, 0), new NamedColor("hotpink",255, 105, 180), new NamedColor("deeppink",255, 20, 147), new NamedColor("pink",255, 192, 203), new NamedColor("lightpink",255, 182, 193), new NamedColor("palevioletred",219, 112, 147), new NamedColor("maroon",176, 48, 96), new NamedColor("mediumvioletred",199, 21, 133), new NamedColor("violetred",208, 32, 144), new NamedColor("magenta",255, 0, 255), new NamedColor("violet",238, 130, 238), new NamedColor("plum",221, 160, 221), new NamedColor("orchid",218, 112, 214), new NamedColor("mediumorchid",186, 85, 211), new NamedColor("darkorchid",153, 50, 204), new NamedColor("darkviolet",148, 0, 211), new NamedColor("blueviolet",138, 43, 226), new NamedColor("purple",160, 32, 240), new NamedColor("mediumpurple",147, 112, 219), new NamedColor("thistle",216, 191, 216), new NamedColor("snow1",255, 250, 250), new NamedColor("snow2",238, 233, 233), new NamedColor("snow3",205, 201, 201), new NamedColor("snow4",139, 137, 137), new NamedColor("seashell1",255, 245, 238), new NamedColor("seashell2",238, 229, 222), new NamedColor("seashell3",205, 197, 191), new NamedColor("seashell4",139, 134, 130), new NamedColor("antiquewhite1",255, 239, 219), new NamedColor("antiquewhite2",238, 223, 204), new NamedColor("antiquewhite3",205, 192, 176), new NamedColor("antiquewhite4",139, 131, 120), new NamedColor("bisque1",255, 228, 196), new NamedColor("bisque2",238, 213, 183), new NamedColor("bisque3",205, 183, 158), new NamedColor("bisque4",139, 125, 107), new NamedColor("peachpuff1",255, 218, 185), new NamedColor("peachpuff2",238, 203, 173), new NamedColor("peachpuff3",205, 175, 149), new NamedColor("peachpuff4",139, 119, 101), new NamedColor("navajowhite1",255, 222, 173), new NamedColor("navajowhite2",238, 207, 161), new NamedColor("navajowhite3",205, 179, 139), new NamedColor("navajowhite4",139, 121, 94), new NamedColor("lemonchiffon1",255, 250, 205), new NamedColor("lemonchiffon2",238, 233, 191), new NamedColor("lemonchiffon3",205, 201, 165), new NamedColor("lemonchiffon4",139, 137, 112), new NamedColor("cornsilk1",255, 248, 220), new NamedColor("cornsilk2",238, 232, 205), new NamedColor("cornsilk3",205, 200, 177), new NamedColor("cornsilk4",139, 136, 120), new NamedColor("ivory1",255, 255, 240), new NamedColor("ivory2",238, 238, 224), new NamedColor("ivory3",205, 205, 193), new NamedColor("ivory4",139, 139, 131), new NamedColor("honeydew1",240, 255, 240), new NamedColor("honeydew2",224, 238, 224), new NamedColor("honeydew3",193, 205, 193), new NamedColor("honeydew4",131, 139, 131), new NamedColor("lavenderblush1",255, 240, 245), new NamedColor("lavenderblush2",238, 224, 229), new NamedColor("lavenderblush3",205, 193, 197), new NamedColor("lavenderblush4",139, 131, 134), new NamedColor("mistyrose1",255, 228, 225), new NamedColor("mistyrose2",238, 213, 210), new NamedColor("mistyrose3",205, 183, 181), new NamedColor("mistyrose4",139, 125, 123), new NamedColor("azure1",240, 255, 255), new NamedColor("azure2",224, 238, 238), new NamedColor("azure3",193, 205, 205), new NamedColor("azure4",131, 139, 139), new NamedColor("slateblue1",131, 111, 255), new NamedColor("slateblue2",122, 103, 238), new NamedColor("slateblue3",105, 89, 205), new NamedColor("slateblue4", 71, 60, 139), new NamedColor("royalblue1", 72, 118, 255), new NamedColor("royalblue2", 67, 110, 238), new NamedColor("royalblue3", 58, 95, 205), new NamedColor("royalblue4", 39, 64, 139), new NamedColor("blue1", 0, 0, 255), new NamedColor("blue2", 0, 0, 238), new NamedColor("blue3", 0, 0, 205), new NamedColor("blue4", 0, 0, 139), new NamedColor("dodgerblue1", 30, 144, 255), new NamedColor("dodgerblue2", 28, 134, 238), new NamedColor("dodgerblue3", 24, 116, 205), new NamedColor("dodgerblue4", 16, 78, 139), new NamedColor("steelblue1", 99, 184, 255), new NamedColor("steelblue2", 92, 172, 238), new NamedColor("steelblue3", 79, 148, 205), new NamedColor("steelblue4", 54, 100, 139), new NamedColor("deepskyblue1", 0, 191, 255), new NamedColor("deepskyblue2", 0, 178, 238), new NamedColor("deepskyblue3", 0, 154, 205), new NamedColor("deepskyblue4", 0, 104, 139), new NamedColor("skyblue1",135, 206, 255), new NamedColor("skyblue2",126, 192, 238), new NamedColor("skyblue3",108, 166, 205), new NamedColor("skyblue4", 74, 112, 139), new NamedColor("lightskyblue1",176, 226, 255), new NamedColor("lightskyblue2",164, 211, 238), new NamedColor("lightskyblue3",141, 182, 205), new NamedColor("lightskyblue4", 96, 123, 139), new NamedColor("slategray1",198, 226, 255), new NamedColor("slategray2",185, 211, 238), new NamedColor("slategray3",159, 182, 205), new NamedColor("slategray4",108, 123, 139), new NamedColor("lightsteelblue1",202, 225, 255), new NamedColor("lightsteelblue2",188, 210, 238), new NamedColor("lightsteelblue3",162, 181, 205), new NamedColor("lightsteelblue4",110, 123, 139), new NamedColor("lightblue1",191, 239, 255), new NamedColor("lightblue2",178, 223, 238), new NamedColor("lightblue3",154, 192, 205), new NamedColor("lightblue4",104, 131, 139), new NamedColor("lightcyan1",224, 255, 255), new NamedColor("lightcyan2",209, 238, 238), new NamedColor("lightcyan3",180, 205, 205), new NamedColor("lightcyan4",122, 139, 139), new NamedColor("paleturquoise1",187, 255, 255), new NamedColor("paleturquoise2",174, 238, 238), new NamedColor("paleturquoise3",150, 205, 205), new NamedColor("paleturquoise4",102, 139, 139), new NamedColor("cadetblue1",152, 245, 255), new NamedColor("cadetblue2",142, 229, 238), new NamedColor("cadetblue3",122, 197, 205), new NamedColor("cadetblue4", 83, 134, 139), new NamedColor("turquoise1", 0, 245, 255), new NamedColor("turquoise2", 0, 229, 238), new NamedColor("turquoise3", 0, 197, 205), new NamedColor("turquoise4", 0, 134, 139), new NamedColor("cyan1", 0, 255, 255), new NamedColor("cyan2", 0, 238, 238), new NamedColor("cyan3", 0, 205, 205), new NamedColor("cyan4", 0, 139, 139), new NamedColor("darkslategray1",151, 255, 255), new NamedColor("darkslategray2",141, 238, 238), new NamedColor("darkslategray3",121, 205, 205), new NamedColor("darkslategray4", 82, 139, 139), new NamedColor("aquamarine1",127, 255, 212), new NamedColor("aquamarine2",118, 238, 198), new NamedColor("aquamarine3",102, 205, 170), new NamedColor("aquamarine4", 69, 139, 116), new NamedColor("darkseagreen1",193, 255, 193), new NamedColor("darkseagreen2",180, 238, 180), new NamedColor("darkseagreen3",155, 205, 155), new NamedColor("darkseagreen4",105, 139, 105), new NamedColor("seagreen1", 84, 255, 159), new NamedColor("seagreen2", 78, 238, 148), new NamedColor("seagreen3", 67, 205, 128), new NamedColor("seagreen4", 46, 139, 87), new NamedColor("palegreen1",154, 255, 154), new NamedColor("palegreen2",144, 238, 144), new NamedColor("palegreen3",124, 205, 124), new NamedColor("palegreen4", 84, 139, 84), new NamedColor("springgreen1", 0, 255, 127), new NamedColor("springgreen2", 0, 238, 118), new NamedColor("springgreen3", 0, 205, 102), new NamedColor("springgreen4", 0, 139, 69), new NamedColor("green1", 0, 255, 0), new NamedColor("green2", 0, 238, 0), new NamedColor("green3", 0, 205, 0), new NamedColor("green4", 0, 139, 0), new NamedColor("chartreuse1",127, 255, 0), new NamedColor("chartreuse2",118, 238, 0), new NamedColor("chartreuse3",102, 205, 0), new NamedColor("chartreuse4", 69, 139, 0), new NamedColor("olivedrab1",192, 255, 62), new NamedColor("olivedrab2",179, 238, 58), new NamedColor("olivedrab3",154, 205, 50), new NamedColor("olivedrab4",105, 139, 34), new NamedColor("darkolivegreen1",202, 255, 112), new NamedColor("darkolivegreen2",188, 238, 104), new NamedColor("darkolivegreen3",162, 205, 90), new NamedColor("darkolivegreen4",110, 139, 61), new NamedColor("khaki1",255, 246, 143), new NamedColor("khaki2",238, 230, 133), new NamedColor("khaki3",205, 198, 115), new NamedColor("khaki4",139, 134, 78), new NamedColor("lightgoldenrod1",255, 236, 139), new NamedColor("lightgoldenrod2",238, 220, 130), new NamedColor("lightgoldenrod3",205, 190, 112), new NamedColor("lightgoldenrod4",139, 129, 76), new NamedColor("lightyellow1",255, 255, 224), new NamedColor("lightyellow2",238, 238, 209), new NamedColor("lightyellow3",205, 205, 180), new NamedColor("lightyellow4",139, 139, 122), new NamedColor("yellow1",255, 255, 0), new NamedColor("yellow2",238, 238, 0), new NamedColor("yellow3",205, 205, 0), new NamedColor("yellow4",139, 139, 0), new NamedColor("gold1",255, 215, 0), new NamedColor("gold2",238, 201, 0), new NamedColor("gold3",205, 173, 0), new NamedColor("gold4",139, 117, 0), new NamedColor("goldenrod1",255, 193, 37), new NamedColor("goldenrod2",238, 180, 34), new NamedColor("goldenrod3",205, 155, 29), new NamedColor("goldenrod4",139, 105, 20), new NamedColor("darkgoldenrod1",255, 185, 15), new NamedColor("darkgoldenrod2",238, 173, 14), new NamedColor("darkgoldenrod3",205, 149, 12), new NamedColor("darkgoldenrod4",139, 101, 8), new NamedColor("rosybrown1",255, 193, 193), new NamedColor("rosybrown2",238, 180, 180), new NamedColor("rosybrown3",205, 155, 155), new NamedColor("rosybrown4",139, 105, 105), new NamedColor("indianred1",255, 106, 106), new NamedColor("indianred2",238, 99, 99), new NamedColor("indianred3",205, 85, 85), new NamedColor("indianred4",139, 58, 58), new NamedColor("sienna1",255, 130, 71), new NamedColor("sienna2",238, 121, 66), new NamedColor("sienna3",205, 104, 57), new NamedColor("sienna4",139, 71, 38), new NamedColor("burlywood1",255, 211, 155), new NamedColor("burlywood2",238, 197, 145), new NamedColor("burlywood3",205, 170, 125), new NamedColor("burlywood4",139, 115, 85), new NamedColor("wheat1",255, 231, 186), new NamedColor("wheat2",238, 216, 174), new NamedColor("wheat3",205, 186, 150), new NamedColor("wheat4",139, 126, 102), new NamedColor("tan1",255, 165, 79), new NamedColor("tan2",238, 154, 73), new NamedColor("tan3",205, 133, 63), new NamedColor("tan4",139, 90, 43), new NamedColor("chocolate1",255, 127, 36), new NamedColor("chocolate2",238, 118, 33), new NamedColor("chocolate3",205, 102, 29), new NamedColor("chocolate4",139, 69, 19), new NamedColor("firebrick1",255, 48, 48), new NamedColor("firebrick2",238, 44, 44), new NamedColor("firebrick3",205, 38, 38), new NamedColor("firebrick4",139, 26, 26), new NamedColor("brown1",255, 64, 64), new NamedColor("brown2",238, 59, 59), new NamedColor("brown3",205, 51, 51), new NamedColor("brown4",139, 35, 35), new NamedColor("salmon1",255, 140, 105), new NamedColor("salmon2",238, 130, 98), new NamedColor("salmon3",205, 112, 84), new NamedColor("salmon4",139, 76, 57), new NamedColor("lightsalmon1",255, 160, 122), new NamedColor("lightsalmon2",238, 149, 114), new NamedColor("lightsalmon3",205, 129, 98), new NamedColor("lightsalmon4",139, 87, 66), new NamedColor("orange1",255, 165, 0), new NamedColor("orange2",238, 154, 0), new NamedColor("orange3",205, 133, 0), new NamedColor("orange4",139, 90, 0), new NamedColor("darkorange1",255, 127, 0), new NamedColor("darkorange2",238, 118, 0), new NamedColor("darkorange3",205, 102, 0), new NamedColor("darkorange4",139, 69, 0), new NamedColor("coral1",255, 114, 86), new NamedColor("coral2",238, 106, 80), new NamedColor("coral3",205, 91, 69), new NamedColor("coral4",139, 62, 47), new NamedColor("tomato1",255, 99, 71), new NamedColor("tomato2",238, 92, 66), new NamedColor("tomato3",205, 79, 57), new NamedColor("tomato4",139, 54, 38), new NamedColor("orangered1",255, 69, 0), new NamedColor("orangered2",238, 64, 0), new NamedColor("orangered3",205, 55, 0), new NamedColor("orangered4",139, 37, 0), new NamedColor("red1",255, 0, 0), new NamedColor("red2",238, 0, 0), new NamedColor("red3",205, 0, 0), new NamedColor("red4",139, 0, 0), new NamedColor("deeppink1",255, 20, 147), new NamedColor("deeppink2",238, 18, 137), new NamedColor("deeppink3",205, 16, 118), new NamedColor("deeppink4",139, 10, 80), new NamedColor("hotpink1",255, 110, 180), new NamedColor("hotpink2",238, 106, 167), new NamedColor("hotpink3",205, 96, 144), new NamedColor("hotpink4",139, 58, 98), new NamedColor("pink1",255, 181, 197), new NamedColor("pink2",238, 169, 184), new NamedColor("pink3",205, 145, 158), new NamedColor("pink4",139, 99, 108), new NamedColor("lightpink1",255, 174, 185), new NamedColor("lightpink2",238, 162, 173), new NamedColor("lightpink3",205, 140, 149), new NamedColor("lightpink4",139, 95, 101), new NamedColor("palevioletred1",255, 130, 171), new NamedColor("palevioletred2 ",238, 121, 159), new NamedColor("palevioletred3",205, 104, 137), new NamedColor("palevioletred4",139, 71, 93), new NamedColor("maroon1",255, 52, 179), new NamedColor("maroon2",238, 48, 167), new NamedColor("maroon3",205, 41, 144), new NamedColor("maroon4",139, 28, 98), new NamedColor("violetred1",255, 62, 150), new NamedColor("violetred2",238, 58, 140), new NamedColor("violetred3",205, 50, 120), new NamedColor("violetred4",139, 34, 82), new NamedColor("magenta1",255, 0, 255), new NamedColor("magenta2",238, 0, 238), new NamedColor("magenta3",205, 0, 205), new NamedColor("magenta4",139, 0, 139), new NamedColor("orchid1",255, 131, 250), new NamedColor("orchid2",238, 122, 233), new NamedColor("orchid3",205, 105, 201), new NamedColor("orchid4",139, 71, 137), new NamedColor("plum1",255, 187, 255), new NamedColor("plum2",238, 174, 238), new NamedColor("plum3",205, 150, 205), new NamedColor("plum4",139, 102, 139), new NamedColor("mediumorchid1",224, 102, 255), new NamedColor("mediumorchid2",209, 95, 238), new NamedColor("mediumorchid3",180, 82, 205), new NamedColor("mediumorchid4",122, 55, 139), new NamedColor("darkorchid1",191, 62, 255), new NamedColor("darkorchid2",178, 58, 238), new NamedColor("darkorchid3",154, 50, 205), new NamedColor("darkorchid4",104, 34, 139), new NamedColor("purple1",155, 48, 255), new NamedColor("purple2",145, 44, 238), new NamedColor("purple3",125, 38, 205), new NamedColor("purple4", 85, 26, 139), new NamedColor("mediumpurple1",171, 130, 255), new NamedColor("mediumpurple2",159, 121, 238), new NamedColor("mediumpurple3",137, 104, 205), new NamedColor("mediumpurple4", 93, 71, 139), new NamedColor("thistle1",255, 225, 255), new NamedColor("thistle2",238, 210, 238), new NamedColor("thistle3",205, 181, 205), new NamedColor("thistle4",139, 123, 139), new NamedColor("gray0", 0, 0, 0), new NamedColor("gray1", 3, 3, 3), new NamedColor("gray2", 5, 5, 5), new NamedColor("gray3", 8, 8, 8), new NamedColor("gray4", 10, 10, 10), new NamedColor("gray5", 13, 13, 13), new NamedColor("gray6", 15, 15, 15), new NamedColor("gray7", 18, 18, 18), new NamedColor("gray8", 20, 20, 20), new NamedColor("gray9", 23, 23, 23), new NamedColor("gray10", 26, 26, 26), new NamedColor("gray11", 28, 28, 28), new NamedColor("gray12", 31, 31, 31), new NamedColor("gray13", 33, 33, 33), new NamedColor("gray14", 36, 36, 36), new NamedColor("gray15", 38, 38, 38), new NamedColor("gray16", 41, 41, 41), new NamedColor("gray17", 43, 43, 43), new NamedColor("gray18", 46, 46, 46), new NamedColor("gray19", 48, 48, 48), new NamedColor("gray20", 51, 51, 51), new NamedColor("gray21", 54, 54, 54), new NamedColor("gray22", 56, 56, 56), new NamedColor("gray23", 59, 59, 59), new NamedColor("gray24", 61, 61, 61), new NamedColor("gray25", 64, 64, 64), new NamedColor("gray26", 66, 66, 66), new NamedColor("gray27", 69, 69, 69), new NamedColor("gray28", 71, 71, 71), new NamedColor("gray29", 74, 74, 74), new NamedColor("gray30", 77, 77, 77), new NamedColor("gray31", 79, 79, 79), new NamedColor("gray32", 82, 82, 82), new NamedColor("gray33", 84, 84, 84), new NamedColor("gray34", 87, 87, 87), new NamedColor("gray35", 89, 89, 89), new NamedColor("gray36", 92, 92, 92), new NamedColor("gray37", 94, 94, 94), new NamedColor("gray38", 97, 97, 97), new NamedColor("gray39", 99, 99, 99), new NamedColor("gray40",102, 102, 102), new NamedColor("gray41",105, 105, 105), new NamedColor("gray42",107, 107, 107), new NamedColor("gray43",110, 110, 110), new NamedColor("gray44",112, 112, 112), new NamedColor("gray45",115, 115, 115), new NamedColor("gray46",117, 117, 117), new NamedColor("gray47",120, 120, 120), new NamedColor("gray48",122, 122, 122), new NamedColor("gray49",125, 125, 125), new NamedColor("gray50",127, 127, 127), new NamedColor("gray51",130, 130, 130), new NamedColor("gray52",133, 133, 133), new NamedColor("gray53",135, 135, 135), new NamedColor("gray54",138, 138, 138), new NamedColor("gray55",140, 140, 140), new NamedColor("gray56",143, 143, 143), new NamedColor("gray57",145, 145, 145), new NamedColor("gray58",148, 148, 148), new NamedColor("gray59",150, 150, 150), new NamedColor("gray60",153, 153, 153), new NamedColor("gray61",156, 156, 156), new NamedColor("gray62",158, 158, 158), new NamedColor("gray63",161, 161, 161), new NamedColor("gray64",163, 163, 163), new NamedColor("gray65",166, 166, 166), new NamedColor("gray66",168, 168, 168), new NamedColor("gray67",171, 171, 171), new NamedColor("gray68",173, 173, 173), new NamedColor("gray69",176, 176, 176), new NamedColor("gray70",179, 179, 179), new NamedColor("gray71",181, 181, 181), new NamedColor("gray72",184, 184, 184), new NamedColor("gray73",186, 186, 186), new NamedColor("gray74",189, 189, 189), new NamedColor("gray75",191, 191, 191), new NamedColor("gray76",194, 194, 194), new NamedColor("gray77",196, 196, 196), new NamedColor("gray78",199, 199, 199), new NamedColor("gray79",201, 201, 201), new NamedColor("gray80",204, 204, 204), new NamedColor("gray81",207, 207, 207), new NamedColor("gray82",209, 209, 209), new NamedColor("gray83",212, 212, 212), new NamedColor("gray84",214, 214, 214), new NamedColor("gray85",217, 217, 217), new NamedColor("gray86",219, 219, 219), new NamedColor("gray87",222, 222, 222), new NamedColor("gray88",224, 224, 224), new NamedColor("gray89",227, 227, 227), new NamedColor("gray90",229, 229, 229), new NamedColor("gray91",232, 232, 232), new NamedColor("gray92",235, 235, 235), new NamedColor("gray93",237, 237, 237), new NamedColor("gray94",240, 240, 240), new NamedColor("gray95",242, 242, 242), new NamedColor("gray96",245, 245, 245), new NamedColor("gray97",247, 247, 247), new NamedColor("gray98",250, 250, 250), new NamedColor("gray99",252, 252, 252), new NamedColor("gray100",255, 255, 255), new NamedColor("darkgray",169, 169, 169), new NamedColor("darkblue",0 , 0, 139), new NamedColor("darkcyan",0 , 139, 139), new NamedColor("darkmagenta",139, 0, 139), new NamedColor("darkred",139, 0, 0), new NamedColor("lightgreen",144, 238, 144), }; }
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/treevisualizer/Edge.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * Edge.java * Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.treevisualizer; import java.awt.Dimension; import java.awt.FontMetrics; import java.util.Vector; /** * This class is used in conjunction with the Node class to form a tree * structure. This in particular contains information about an edges in the * tree. * * @author Malcolm Ware (mfw4@cs.waikato.ac.nz) * @version $Revision$ */ public class Edge { /** The text caption for the edge. */ private final String m_label; /** * The ID string of the parent Node of this edge (used for consrtuction * purposes). */ private String m_rsource; /** * The ID string of the child Node of this edge (used for construction * purposes). */ private String m_rtarget; /** The parent Node of this edge. */ private Node m_source; /** The child Node of this edge. */ private Node m_target; /** The label broken up into lines. */ private final Vector<String> m_lines; /** * This constructs an Edge with the specified label and parent , child serial * tags. * * @param label The text caption for the edge. * @param source The ID string for this edges parent. * @param target The ID string for this edges child. */ public Edge(String label, String source, String target) { m_label = label; m_rsource = source; m_rtarget = target; m_lines = new Vector<String>(3, 2); breakupLabel(); } /** * Get the value of label. * * @return Value of label. */ public String getLabel() { return m_label; } /** * This function is called to break the label of the edge up in to seperate * lines */ private void breakupLabel() { int prev = 0, noa; for (noa = 0; noa < m_label.length(); noa++) { if (m_label.charAt(noa) == '\n') { m_lines.addElement(m_label.substring(prev, noa)); prev = noa + 1; } } m_lines.addElement(m_label.substring(prev, noa)); } /** * This will calculate how large a rectangle using the <i>FontMetrics</i> * passed that the lines of the label will take up * * @param f The size information for a particular Font * @return A Dimension containing the size and width of the text */ public Dimension stringSize(FontMetrics f) { Dimension d = new Dimension(); int old = 0; String s; int noa = 0; while ((s = getLine(noa)) != null) { noa++; old = f.stringWidth(s); if (old > d.width) { d.width = old; } } d.height = noa * f.getHeight(); return d; } /** * Returns line number <i>n</i> * * @param n The number of the line requested * @return The string for the line number or NULL if it didn't exist */ public String getLine(int n) { if (n < m_lines.size()) { return m_lines.elementAt(n); } else { return null; } } /** * Get the value of rsource. * * @return Value of rsource. */ public String getRsource() { return m_rsource; } /** * Set the value of rsource. * * @param v Value to assign to rsource. */ public void setRsource(String v) { m_rsource = v; } /** * Get the value of rtarget. * * @return Value of rtarget. */ public String getRtarget() { return m_rtarget; } /** * Set the value of rtarget. * * @param v Value to assign to rtarget. */ public void setRtarget(String v) { m_rtarget = v; } /** * Get the value of source. * * @return Value of source. */ public Node getSource() { return m_source; } /** * Set the value of source. And then call v.addChild to add the edge to the * Node. * * @param v Value to assign to source. */ public void setSource(Node v) { m_source = v; v.addChild(this); } /** * Get the value of target. * * @return Value of target. */ public Node getTarget() { return m_target; } /** * Set the value of target. And then call v.addParent to add the edge to the * Node. * * @param v Value to assign to target. */ public void setTarget(Node v) { m_target = v; v.setParent(this); } }
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/treevisualizer/NamedColor.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * NamedColor.java * Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.treevisualizer; import java.awt.Color; /** * This class contains a color name and the rgb values of that color * * @author Malcolm Ware (mfw4@cs.waikato.ac.nz) * @version $Revision$ */ public class NamedColor { /** The name of the color */ public String m_name; /** The actual color object */ public Color m_col; /** * @param n The name of the color. * @param r The red component of the color. * @param g The green component of the color. * @param b The blue component of the color. */ public NamedColor(String n,int r,int g,int b) { m_name = n; m_col = new Color(r,g,b); } }
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/treevisualizer/Node.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * Node.java * Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.treevisualizer; import java.awt.Color; import java.awt.Dimension; import java.awt.FontMetrics; import java.io.StringReader; import java.util.Vector; import weka.core.Instances; //this is a node structure that to be useful needs the Edge class as well //note i have done an unintentional naughty thing //getHeight() returns the pixel height of the node //getHeight(Node,int) returns how many levels down the tree goes //setHeight(int) is associated to the prior /** * This class records all the data about a particular node for displaying. * * @author Malcolm Ware (mfw4@cs.waikato.ac.nz) * @version $Revision$ */ public class Node { /** The fill mode for the node (not in use). */ // private int m_backstyle; //how the back color will fill NOT USED /** The shape of the node. */ private int m_shape; /** The color of the node. */ private Color m_color; /** the text for the node. */ private final String m_label; /** the text broken up into lines */ private final Vector<String> m_lines; // the coord of the left side .note all coords are // between 1-0 for scaling per Stuart's suggestion /** The center of the node (between 0 and 1). */ private double m_center; // coord of the center . main x value used /** The top of the node (between 0 and 1). */ private double m_top; // main y coord to go by /** true if this nodes descendants are visible (not in use currently). */ private boolean m_cVisible; // whether it's descendants are visible /** true if this node is visible (not currently in use). */ private boolean m_visible; // whether it's visible /** true if this is the top of the tree. ie has no parent */ private boolean m_root; // whether it is anscestor to all i.e top of tree /** * An array containing references to all the parent edges (only 1 currently). */ private final Vector<Edge> m_parent; // the edge to its parent edges(or itself // if true root) /** An array containing references to all the child edges. */ private final Vector<Edge> m_children; // a vector list of edges to the nodes // children /** The ID string for this node (used for construction purposes) */ private String m_refer; /** A String containing extra information about the node. */ private String m_data; /** * An Instances variable generated from the data. Note that if this exists * then the string shall be NULL to save space. */ private Instances m_theData; /** * This will setup all the values of the node except for its top and center. * * @param label The text for the node. * @param refer The ID string for this node. * @param backstyle The backstyle of this node. * @param shape The shape of this node. * @param color The color of this node. */ public Node(String label, String refer, int backstyle, int shape, Color color, String d) { m_label = label; // m_backstyle = backstyle; NOT USED m_shape = shape; m_color = color; m_refer = refer; m_center = 0; m_top = 0; m_cVisible = true; m_visible = true; m_root = false; m_parent = new Vector<Edge>(1, 1); m_children = new Vector<Edge>(20, 10); m_lines = new Vector<String>(4, 2); breakupLabel(); m_data = d; m_theData = null; } /** * This will return the Instances object related to this node. If it has not * been allocated then that will be done also. * * @return The Instances object. */ public Instances getInstances() { if (m_theData == null && m_data != null) { try { m_theData = new Instances(new StringReader(m_data)); } catch (Exception e) { System.out.println("Error : " + e); } m_data = null; } return m_theData; } /** * Get If this node's childs are visible. * * @return True if the childs are visible. */ public boolean getCVisible() { return m_cVisible; } /** * Recursively goes through the tree and sets all the children and the parent * to visible. * * @param r The current node to set visible. */ private void childVis(Node r) { Edge e; r.setVisible(true); if (r.getCVisible()) { for (int noa = 0; (e = r.getChild(noa)) != null; noa++) { childVis(e.getTarget()); } } } /** * Sets all the children of this node either to visible or invisible * * @param v True if the children are to be visible */ public void setCVisible(boolean v) { m_cVisible = v; if (v) { childVis(this); } else if (!v) { childInv(this); } } /** * Recursively goes through the tree and sets all the children to invisible, * Not the parent though. * * @param r The current node from whom the children are gonna be set * invisible. */ private void childInv(Node r) { Edge e; Node s; for (int noa = 0; (e = r.getChild(noa)) != null; noa++) { s = e.getTarget(); s.setVisible(false); childInv(s); } } /** * Get the value of refer. * * @return Value of refer. */ public String getRefer() { return m_refer; } /** * Set the value of refer. * * @param v Value to assign to refer. */ public void setRefer(String v) { m_refer = v; } /** * Get the value of shape. * * @return Value of shape. */ public int getShape() { return m_shape; } /** * Set the value of shape. * * @param v Value to assign to shape. */ public void setShape(int v) { m_shape = v; } /** * Get the value of color. * * @return Value of color. */ public Color getColor() { return m_color; } /** * Set the value of color. * * @param v Value to assign to color. */ public void setColor(Color v) { m_color = v; } /** * Get the value of label. * * @return Value of label. */ public String getLabel() { return m_label; } /** * This Will break the node's text up into lines. * */ private void breakupLabel() { int prev = 0, noa; for (noa = 0; noa < m_label.length(); noa++) { if (m_label.charAt(noa) == '\n') { m_lines.addElement(m_label.substring(prev, noa)); prev = noa + 1; } } m_lines.addElement(m_label.substring(prev, noa)); } /** * This will return the width and height of the rectangle that the text will * fit into. * * @param f The size info for the Font. * @return A Dimension containing the size of the text. */ public Dimension stringSize(FontMetrics f) { Dimension d = new Dimension(); int old = 0; String s; int noa = 0; while ((s = getLine(noa)) != null) { noa++; old = f.stringWidth(s); if (old > d.width) { d.width = old; } } d.height = noa * f.getHeight(); return d; } /** * Returns the text String for the specfied line. * * @param n The line wanted. * @return The String corresponding to that line. */ public String getLine(int n) { if (n < m_lines.size()) { return m_lines.elementAt(n); } else { return null; } } /** * Get the value of center. * * @return Value of center. */ public double getCenter() { return m_center; } /** * Set the value of center. * * @param v Value to assign to center. */ public void setCenter(double v) { m_center = v; } /** * Will increase or decrease the postion of center. * * @param v The amount to increase or decrease center by. */ public void adjustCenter(double v) { m_center += v; } /** * Get the value of top. * * @return Value of top. */ public double getTop() { return m_top; } /** * Set the value of top. * * @param v Value to assign to top. */ public void setTop(double v) { m_top = v; } /** * Get the value of visible. * * @return Value of visible. */ public boolean getVisible() { return m_visible; } /** * Set the value of visible. * * @param v Value to assign to visible. */ private void setVisible(boolean v) { m_visible = v; } /** * Get the value of root. * * @return True if has no parents. */ public boolean getRoot() { return m_root; } /** * Set the value of root. * * @param v Value to assign to root. */ public void setRoot(boolean v) { m_root = v; } /** * Get the parent edge. * * @param i The parent number to get. * @return The parent edge or NULL if it doesn't exist. */ public Edge getParent(int i) { if (i < m_parent.size()) { return m_parent.elementAt(i); } else { return null; } } /** * Set the value of parent. * * @param v Value to assign to parent. */ public void setParent(Edge v) { m_parent.addElement(v); } /** * Get the Edge for the child number 'i'. * * @param i The child number to get. * @return The child Edge or NULL if it doesn't exist. */ public Edge getChild(int i) { if (i < m_children.size()) { return m_children.elementAt(i); } else { return null; } } /** * Set the value of children. * * @param v Value to assign to children. */ public void addChild(Edge v) { m_children.addElement(v); } /** * Recursively finds the number of visible groups of siblings there are. * * @param r The current Node upto. * @param n The current number of groups there are. * @return The number of groups found so far. */ public static int getGCount(Node r, int n) { Edge e; if (r.getChild(0) != null && r.getCVisible()) { n++; for (int noa = 0; (e = r.getChild(noa)) != null; noa++) { n = getGCount(e.getTarget(), n); } } return n; } /** * Recursively finds the total number of groups of siblings there are. * * @param r The current Node upto. * @param n The current number of groups there are. * @return The number of groups found so far. */ public static int getTotalGCount(Node r, int n) { Edge e; if (r.getChild(0) != null) { n++; for (int noa = 0; (e = r.getChild(noa)) != null; noa++) { n = getTotalGCount(e.getTarget(), n); } } return n; } /** * Recursively finds the number of visible nodes there are (this may * accidentally count some of the invis nodes). * * @param r The current Node upto. * @param n The current number nodes there are. * @return The number of nodes found so far. */ public static int getCount(Node r, int n) { Edge e; n++; for (int noa = 0; (e = r.getChild(noa)) != null && r.getCVisible(); noa++) { n = getCount(e.getTarget(), n); } return n; } /** * Recursively finds the total number of nodes there are. * * @param r The current Node upto. * @param n The current number nodes there are. * @return The number of nodes found so far. */ public static int getTotalCount(Node r, int n) { Edge e; n++; for (int noa = 0; (e = r.getChild(noa)) != null; noa++) { n = getTotalCount(e.getTarget(), n); } return n; } /** * Recursively finds the number of visible levels there are. * * @param r The current Node upto. * @param l The curent level. * @return The max number of levels found so far. */ public static int getHeight(Node r, int l) { l++; int lev = l, temp = 0; Edge e; for (int noa = 0; (e = r.getChild(noa)) != null && r.getCVisible(); noa++) { temp = getHeight(e.getTarget(), l); if (temp > lev) { lev = temp; } } return lev; } /** * Recursively finds the total number of levels there are. * * @param r The current Node upto. * @param l The curent level. * @return The max number of levels found so far. */ public static int getTotalHeight(Node r, int l) { l++; int lev = l, temp = 0; Edge e; for (int noa = 0; (e = r.getChild(noa)) != null; noa++) { temp = getTotalHeight(e.getTarget(), l); if (temp > lev) { lev = temp; } } return lev; } }
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/treevisualizer/NodePlace.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * NodePlace.java * Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.treevisualizer; /** * This is an interface for classes that wish to take a node structure and * arrange them * * @author Malcolm F Ware (mfw4@cs.waikato.ac.nz) * @version $Revision$ */ public interface NodePlace { /** * The function to call to postion the tree that starts at Node r * * @param r The top of the tree. */ void place(Node r); }
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/treevisualizer/PlaceNode1.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * PlaceNode1.java * Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.treevisualizer; /** * This class will place the Nodes of a tree. * <p> * * It will place these nodes so that they symetrically fill each row. This is * simple to calculate but is not visually nice for most trees. * <p> * * @author Malcolm F Ware (mfw4@cs.waikato.ac.nz) * @version $Revision$ */ public class PlaceNode1 implements NodePlace { /** An array containing the spacing value for each level */ private double[] m_levels; // contains num of nodes one each level /** The number of levels in the tree */ private int m_noLevels;// contains num of levels /** * An array containing the current node place for each level to place each * node accordingly. */ private int[] m_levelNode; // contains num of node upto on particular level /** The distance between each level. */ private double m_yRatio; // for quicker running y_ratio is a constant after // being calculated /** * Call this function to have each node in the tree starting at 'r' placed in * a visual (not logical, they already are) tree position. * * @param r The top of the tree. */ @Override public void place(Node r) { /* * this is the first and most basic algorithm to write I will use this as a * reference to test the classes * * this works by counting up the nodes on each level and spacing the level * evenly so that it is all used */ /* * this loop will work by starting at the first node and systematically * going through all their children from left to right.but first it will do * a quick pass to find out the number of levels there are */ // + 1 so that no nodes are on edge of screen m_noLevels = Node.getHeight(r, 0) + 1; m_yRatio = 1 / (double) m_noLevels; m_levels = new double[m_noLevels]; m_levelNode = new int[m_noLevels]; for (int noa = 0; noa < m_noLevels; noa++) { m_levels[noa] = 1; m_levelNode[noa] = 0; } setNumOfNodes(r, 0); for (int noa = 0; noa < m_noLevels; noa++) { m_levels[noa] = 1 / m_levels[noa]; } placer(r, 0); } /** * This function finds the number of nodes on each level recursively. * * @param r The current Node upto. * @param l The current level upto. */ private void setNumOfNodes(Node r, int l) { Edge e; l++; m_levels[l]++; for (int noa = 0; (e = r.getChild(noa)) != null && r.getCVisible(); noa++) { setNumOfNodes(e.getTarget(), l); } } /** * This function goes through and sets the position of each node * * @param r The current node upto. * @param l the current level upto. */ private void placer(Node r, int l) { Edge e; l++; m_levelNode[l]++; r.setCenter(m_levelNode[l] * m_levels[l]); r.setTop(l * m_yRatio); for (int noa = 0; (e = r.getChild(noa)) != null && r.getCVisible(); noa++) { placer(e.getTarget(), 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/treevisualizer/PlaceNode2.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * PlaceNode2.java * Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.treevisualizer; import java.util.Vector; /** * This class will place the Nodes of a tree. * <p> * * It will place these nodes so that they fall at evenly below their parent. It * will then go through and look for places where nodes fall on the wrong side * of other nodes when it finds one it will trace back up the tree to find the * first common sibling group these two nodes have And it will adjust the * spacing between these two siblings so that the two nodes no longer overlap. * This is nasty to calculate with , and takes a while with the current * algorithm I am using to do this. * <p> * * * @author Malcolm Ware (mfw4@cs.waikato.ac.nz) * @version $Revision$ */ public class PlaceNode2 implements NodePlace { /** The space each row will take up. */ private double m_yRatio; /** An array that lists the groups and information about them. */ private Group[] m_groups; /** An array that lists the levels and information about them. */ private Level[] m_levels; /** The Number of groups the tree has */ private int m_groupNum; /** The number of levels the group tree has */ private int m_levelNum; /** * The Funtion to call to have the nodes arranged. * * @param r The top node of the tree to arrange. */ @Override public void place(Node r) { // note i might write count groups into the node class as well as // it may be useful too; m_groupNum = Node.getGCount(r, 0); // i could swap over to the node class // group count,but this works os i'm not gonna m_groups = new Group[m_groupNum]; for (int noa = 0; noa < m_groupNum; noa++) { m_groups[noa] = new Group(); m_groups[noa].m_gap = 3; m_groups[noa].m_start = -1; } groupBuild(r); m_levelNum = Node.getHeight(r, 0); m_yRatio = 1 / (double) (m_levelNum + 1); m_levels = new Level[m_levelNum]; for (int noa = 0; noa < m_levelNum; noa++) { m_levels[noa] = new Level(); } r.setTop(m_yRatio); yPlacer(); r.setCenter(0); xPlacer(0); // ok now i just have to untangle then scale down // note instead of starting with coords between 1 and 0 i will // use ints then scale them down // i will scale them down either by all relative to the largest // line or by each line individually untangle2(); scaleByMax(); // scaleByInd(); } /* * private void thinner() { //what this function does is it retains the * symmetry of the // parent node about the children but the children are no * longer evenly //spaced this stops children from being pushed too far to the * sides //,note this algorithm may need the method altered as it may // * require heavy optimisation to go at any decent speed * * Node r,s; Edge e; double parent_x; for (int noa = group_num - 1;noa >= * 0;noa--) { Vector shifts = new Vector(20,10); shifts.addElement(0); int * g_num = 0;//this is the offset from groups.m_start to get the right 1 r = * groups[noa].m_p; parent_x = r.getCenter(); for (int nob = 1;(e = * r.getChild(nob)) != null;nob++) { double margin; s = e.getTarget(); margin * = s_getCenter - r.getChild(nob - 1).getTarget().getCenter-1 - * shift.elementAt(nob-1); if (margin > 0) { margin = * check_down(s,g_num,margin); if (margin > 0) { shift.addElement(-margin); } * else { shift.addElement(0); } } else { shift.addElement(0); } if * (s.getChild(0) != null) { g_num++; } } } } * * * private double check_down(Node r,int gn,double m) { //note i need to know * where the children of the //other changers are to properly overlap check * //to do this i think the best way is to go up the other group //parents * line and see if it goes through the current group //this means to save time * i need to know the level that is being //worked with along with the group * * Edge e; for (int noa = 0;(e = r.getChild(noa)) != null;noa++) { * * } } */ /** * This will set initial places for the x coord of the nodes. * * @param start The `number for the first group to start on (I think). */ private void xPlacer(int start) { // this can be one of a few x_placers (the first) // it will work by placing 1 space inbetween each node // ie the first at 0 the second at 1 and so on // then it will add to this value the place of the parent // node - half of the size // i will break this up into several functions // first the gap setter; // then the shifter // it will require a vector shift function added to the node class // i will write an additional shifter for the untangler // for its particular situation Node r; Edge e; if (m_groupNum > 0) { m_groups[0].m_p.setCenter(0); for (int noa = start; noa < m_groupNum; noa++) { int nob, alter = 0; double c = m_groups[noa].m_gap; r = m_groups[noa].m_p; for (nob = 0; (e = r.getChild(nob)) != null; nob++) { if (e.getTarget().getParent(0) == e) { e.getTarget().setCenter(nob * c); } else { alter++; } } m_groups[noa].m_size = (nob - 1 - alter) * c; xShift(noa); } } } /** * This will shift a group of nodes to be aligned under their parent. * * @param n The group number to shift */ private void xShift(int n) { Edge e; Node r = m_groups[n].m_p; double h = m_groups[n].m_size / 2; double c = m_groups[n].m_p.getCenter(); double m = c - h; m_groups[n].m_left = m; m_groups[n].m_right = c + h; for (int noa = 0; (e = r.getChild(noa)) != null; noa++) { if (e.getTarget().getParent(0) == e) { e.getTarget().adjustCenter(m); } } } /** * This scales all the x values to be between 0 and 1. */ private void scaleByMax() { // ammendment to what i may have commented before // this takes the lowest x and highest x and uses that as the scaling // factor double l_x = 5000, h_x = -5000; for (int noa = 0; noa < m_groupNum; noa++) { if (l_x > m_groups[noa].m_left) { l_x = m_groups[noa].m_left; } if (h_x < m_groups[noa].m_right) { h_x = m_groups[noa].m_right; } } Edge e; Node r, s; double m_scale = h_x - l_x + 1; if (m_groupNum > 0) { r = m_groups[0].m_p; r.setCenter((r.getCenter() - l_x) / m_scale); // System.out.println("from scaler " + l_x + " " + m_scale); for (int noa = 0; noa < m_groupNum; noa++) { r = m_groups[noa].m_p; for (int nob = 0; (e = r.getChild(nob)) != null; nob++) { s = e.getTarget(); if (s.getParent(0) == e) { s.setCenter((s.getCenter() - l_x) / m_scale); } } } } } /** * This untangles the nodes so that they will will fall on the correct side of * the other nodes along their row. */ private void untangle2() { Ease a; Edge e; Node r, nf = null, ns = null, mark; int l = 0; // ,times = 0; NOT USED int f, s, tf = 0, ts = 0, pf, ps; while ((a = overlap(l)) != null) { // times++; NOT USED // System.out.println("from untang 2 " + group_num); f = a.m_place; s = a.m_place + 1; while (f != s) { a.m_lev--; tf = f; ts = s; f = m_groups[f].m_pg; s = m_groups[s].m_pg; } l = a.m_lev; pf = 0; ps = 0; r = m_groups[f].m_p; mark = m_groups[tf].m_p; nf = null; ns = null; for (int noa = 0; nf != mark; noa++) { pf++; nf = r.getChild(noa).getTarget(); } mark = m_groups[ts].m_p; for (int noa = pf; ns != mark; noa++) { ps++; // the number of gaps between the two nodes ns = r.getChild(noa).getTarget(); } // m_groups[f].gap = // Math.ceil((a.amount / (double)ps) + m_groups[f].gap); // note for this method i do not need the group gap ,but i will leave // it for the other methods; Vector<Double> o_pos = new Vector<Double>(20, 10); for (int noa = 0; (e = r.getChild(noa)) != null; noa++) { if (e.getTarget().getParent(0) == e) { Double tem = new Double(e.getTarget().getCenter()); o_pos.addElement(tem); } } pf--; double inc = a.m_amount / ps; for (int noa = 0; (e = r.getChild(noa)) != null; noa++) { ns = e.getTarget(); if (ns.getParent(0) == e) { if (noa > pf + ps) { ns.adjustCenter(a.m_amount); } else if (noa > pf) { ns.adjustCenter(inc * (noa - pf)); } } } nf = r.getChild(0).getTarget(); inc = ns.getCenter() - nf.getCenter(); m_groups[f].m_size = inc; m_groups[f].m_left = r.getCenter() - inc / 2; m_groups[f].m_right = m_groups[f].m_left + inc; inc = m_groups[f].m_left - nf.getCenter(); double shift; int g_num = 0; for (int noa = 0; (e = r.getChild(noa)) != null; noa++) { ns = e.getTarget(); if (ns.getParent(0) == e) { ns.adjustCenter(inc); shift = ns.getCenter() - o_pos.elementAt(noa).doubleValue(); if (ns.getChild(0) != null) { moveSubtree(m_groups[f].m_start + g_num, shift); g_num++; } } // ns.adjustCenter(-shift); } // zero_offset(r); // x_placer(f); } } /** * This will recursively shift a sub there to be centered about a particular * value. * * @param n The first group in the sub tree. * @param o The point to start shifting the subtree. */ private void moveSubtree(int n, double o) { Edge e; Node r = m_groups[n].m_p; for (int noa = 0; (e = r.getChild(noa)) != null; noa++) { if (e.getTarget().getParent(0) == e) { e.getTarget().adjustCenter(o); } } m_groups[n].m_left += o; m_groups[n].m_right += o; if (m_groups[n].m_start != -1) { for (int noa = m_groups[n].m_start; noa <= m_groups[n].m_end; noa++) { moveSubtree(noa, o); } } } /** * This will find an overlap and then return information about that overlap * * @param l The level to start on. * @return null if there was no overlap , otherwise an object containing the * group number that overlaps (only need one) how much they overlap * by, and the level they overlap on. */ private Ease overlap(int l) { Ease a = new Ease(); for (int noa = l; noa < m_levelNum; noa++) { for (int nob = m_levels[noa].m_start; nob < m_levels[noa].m_end; nob++) { a.m_amount = m_groups[nob].m_right - m_groups[nob + 1].m_left + 2; // System.out.println(m_groups[nob].m_right + " + " + // m_groups[nob+1].m_left + " = " + a.amount); if (a.m_amount >= 0) { a.m_amount++; a.m_lev = noa; a.m_place = nob; return a; } } } return null; } /* * private int count_m_groups(Node r,int l) { Edge e; if (r.getChild(0) != * null) { l++; } for (int noa = 0;(e = r.getChild(noa)) != null;noa++) { l = * count_groups(e.getTarget(),l); } * * return l; } */ /** * This function sets up the height of each node, and also fills the levels * array with information about what the start and end groups on that level * are. */ private void yPlacer() { // note this places the y height and sets up the levels array double changer = m_yRatio; int lev_place = 0; if (m_groupNum > 0) { m_groups[0].m_p.setTop(m_yRatio); m_levels[0].m_start = 0; for (int noa = 0; noa < m_groupNum; noa++) { if (m_groups[noa].m_p.getTop() != changer) { m_levels[lev_place].m_end = noa - 1; lev_place++; m_levels[lev_place].m_start = noa; changer = m_groups[noa].m_p.getTop(); } nodeY(m_groups[noa].m_p); } m_levels[lev_place].m_end = m_groupNum - 1; } } /** * This will set all of the children node of a particular node to their * height. * * @param r The parent node of the children to set their height. */ private void nodeY(Node r) { Edge e; double h = r.getTop() + m_yRatio; for (int noa = 0; (e = r.getChild(noa)) != null; noa++) { if (e.getTarget().getParent(0) == e) { e.getTarget().setTop(h); if (!e.getTarget().getVisible()) { // System.out.println("oh bugger"); } } } } /** * This starts to create the information about the sibling groups. As more * groups are created the for loop in this will check those groups for lower * groups. * * @param r The top node. */ private void groupBuild(Node r) { if (m_groupNum > 0) { m_groupNum = 0; m_groups[0].m_p = r; m_groupNum++; // note i need to count up the num of groups first // woe is me for (int noa = 0; noa < m_groupNum; noa++) { groupFind(m_groups[noa].m_p, noa); } } } /** * This is called to build the rest of the grouping information. * * @param r The parent of the group. * @param pg The number for the parents group. */ private void groupFind(Node r, int pg) { Edge e; boolean first = true; for (int noa = 0; (e = r.getChild(noa)) != null; noa++) { if (e.getTarget().getParent(0) == e) { if (e.getTarget().getChild(0) != null && e.getTarget().getCVisible()) { if (first) { m_groups[pg].m_start = m_groupNum; first = false; } m_groups[pg].m_end = m_groupNum; m_groups[m_groupNum].m_p = e.getTarget(); m_groups[m_groupNum].m_pg = pg; // m_groups[m_groupNum].m_id = m_groupNum; //just in case I ever need // this info NOT USED m_groupNum++; } } } } // note these three classes are only to help organise the data and are // inter related between each other and this placer class // so don't mess with them or try to use them somewhere else // (because that would be a mistake and I would pity you) /** * Inner class for containing the level data. */ private class Level { /** The number for the group on the left of this level. */ public int m_start; /** The number for the group on the right of this level. */ public int m_end; /** These two params would appear to not be used. */ // public int m_left; NOT USED // public int m_right; NOT USED } /** * Inner class for containing the grouping data. */ private class Group { /** The parent node of this group. */ public Node m_p; /** The group number for the parent of this group. */ public int m_pg; /** The gap size for the distance between the nodes in this group. */ public double m_gap; /** The leftmost position of this group. */ public double m_left; /** The rightmost position of this group. */ public double m_right; /** The size of this group. */ public double m_size; /** The start node of this group. */ public int m_start; /** The end node of this group. */ public int m_end; /** The group number for this group. (may not be used!?). */ // public int m_id; NOT USED } /** * An inner class used to report information about any tangles found. */ private class Ease { /** The number of the group on the left of the tangle. */ public int m_place; /** The distance they were tangled. */ public double m_amount; /** The level on which they were tangled. */ public int m_lev; } }
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/treevisualizer/TreeBuild.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * TreeBuild.java * Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.treevisualizer; import java.awt.Color; import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.io.StreamTokenizer; import java.util.Hashtable; import java.util.Vector; /** * This class will parse a dotty file and construct a tree structure from it * with Edge's and Node's * * @author Malcolm Ware (mfw4@cs.waikato.ac.nz) * @version $Revision$ */ public class TreeBuild { // this class will parse the tree into relevant strings // into info objects // from there it will create the nodes and edges from the info objects /** The name of the tree, Not in use. */ // private String m_graphName; NOT USED /** An array with all the nodes initially constructed into it. */ private Vector<Node> m_aNodes; /** An array with all the edges initially constructed into it. */ private Vector<Edge> m_aEdges; /** * An array containing a structure that describes the node without actually * creating it. */ private Vector<InfoObject> m_nodes; /** * An arry containing a structure that describes the edge without actually * creating it. */ private Vector<InfoObject> m_edges; /** An object setup to take graph data. */ private InfoObject m_grObj; /** An object setup to take node data. */ private InfoObject m_noObj; /** An object setup to take edge data. */ private InfoObject m_edObj; /** true if it is a digraph. (note that this can't build digraphs). */ // private boolean m_digraph; NOT USED /** The stream to parse. */ private StreamTokenizer m_st; /** A table containing all the colors. */ private final Hashtable<String, Color> m_colorTable; /** * Upon construction this will only setup the color table for quick reference * of a color. */ public TreeBuild() { m_colorTable = new Hashtable<String, Color>(); Colors ab = new Colors(); for (NamedColor m_col : ab.m_cols) { m_colorTable.put(m_col.m_name, m_col.m_col); } } /** * This will build A node structure from the dotty format passed. Don't send a * dotty format with multiple parents per node, and ensure that there is 1 and * only 1 node with no parent. * * @param t The reader with the dotty string to be read. * @return The top node of the tree structure (the last node with no parent). */ public Node create(Reader t) { m_nodes = new Vector<InfoObject>(50, 50); m_edges = new Vector<InfoObject>(50, 50); m_grObj = new InfoObject("graph"); m_noObj = new InfoObject("node"); m_edObj = new InfoObject("edge"); // m_digraph = false; NOT USED m_st = new StreamTokenizer(new BufferedReader(t)); setSyntax(); graph(); Node top = generateStructures(); return top; } /** * This will go through all the found Nodes and Edges build instances of these * and link them together. * * @return The node with no parent (the top of the tree). */ private Node generateStructures() { String id, label; // ,source,target; NOT USED Integer shape, style; // int fontsize; NOT USED Color fontcolor, color; InfoObject t; m_aNodes = new Vector<Node>(50, 50); m_aEdges = new Vector<Edge>(50, 50); for (int noa = 0; noa < m_nodes.size(); noa++) { t = m_nodes.elementAt(noa); id = t.m_id; if (t.m_label == null) { if (m_noObj.m_label == null) { label = ""; } else { label = m_noObj.m_label; } } else { label = t.m_label; } if (t.m_shape == null) { if (m_noObj.m_shape == null) { shape = new Integer(2); } else { shape = getShape(m_noObj.m_shape); } } else { shape = getShape(t.m_shape); } if (shape == null) { shape = new Integer(2); } if (t.m_style == null) { if (m_noObj.m_style == null) { style = new Integer(1); } else { style = getStyle(m_noObj.m_style); } } else { style = getStyle(t.m_style); } if (style == null) { style = new Integer(1); } /* * NOT USED if (t.m_fontSize == null) { if (m_noObj.m_fontSize == null) { * fontsize = 12; } else { fontsize = * Integer.valueOf(m_noObj.m_fontSize).intValue(); } } else { fontsize = * Integer.valueOf(t.m_fontSize).intValue(); } */ if (t.m_fontColor == null) { if (m_noObj.m_fontColor == null) { fontcolor = Color.black; } else { fontcolor = m_colorTable.get(m_noObj.m_fontColor.toLowerCase()); } } else { fontcolor = m_colorTable.get(t.m_fontColor.toLowerCase()); } if (fontcolor == null) { fontcolor = Color.black; } if (t.m_color == null) { if (m_noObj.m_color == null) { color = Color.lightGray; } else { color = m_colorTable.get(m_noObj.m_color.toLowerCase()); } } else { color = m_colorTable.get(t.m_color.toLowerCase()); } if (color == null) { color = Color.lightGray; } m_aNodes.addElement(new Node(label, id, style.intValue(), shape .intValue(), color, t.m_data)); } for (int noa = 0; noa < m_edges.size(); noa++) { t = m_edges.elementAt(noa); id = t.m_id; if (t.m_label == null) { if (m_noObj.m_label == null) { label = ""; } else { label = m_noObj.m_label; } } else { label = t.m_label; } if (t.m_shape == null) { if (m_noObj.m_shape == null) { shape = new Integer(2); } else { shape = getShape(m_noObj.m_shape); } } else { shape = getShape(t.m_shape); } if (shape == null) { shape = new Integer(2); } if (t.m_style == null) { if (m_noObj.m_style == null) { style = new Integer(1); } else { style = getStyle(m_noObj.m_style); } } else { style = getStyle(t.m_style); } if (style == null) { style = new Integer(1); } /* * NOT USED if (t.m_fontSize == null) { if (m_noObj.m_fontSize == null) { * fontsize = 12; NOT USEDa } else { fontsize = * Integer.valueOf(m_noObj.m_fontSize).intValue(); NOT USED } } else { * fontsize = Integer.valueOf(t.m_fontSize).intValue(); } */ if (t.m_fontColor == null) { if (m_noObj.m_fontColor == null) { fontcolor = Color.black; } else { fontcolor = m_colorTable.get(m_noObj.m_fontColor.toLowerCase()); } } else { fontcolor = m_colorTable.get(t.m_fontColor.toLowerCase()); } if (fontcolor == null) { fontcolor = Color.black; } if (t.m_color == null) { if (m_noObj.m_color == null) { color = Color.white; } else { color = m_colorTable.get(m_noObj.m_color.toLowerCase()); } } else { color = m_colorTable.get(t.m_color.toLowerCase()); } if (color == null) { color = Color.white; } m_aEdges.addElement(new Edge(label, t.m_source, t.m_target)); } boolean f_set, s_set; Node x, sour = null, targ = null; Edge y; for (int noa = 0; noa < m_aEdges.size(); noa++) { f_set = false; s_set = false; y = m_aEdges.elementAt(noa); for (int nob = 0; nob < m_aNodes.size(); nob++) { x = m_aNodes.elementAt(nob); if (x.getRefer().equals(y.getRtarget())) { f_set = true; targ = x; } if (x.getRefer().equals(y.getRsource())) { s_set = true; sour = x; } if (f_set == true && s_set == true) { break; } } if (targ != sour) { y.setTarget(targ); y.setSource(sour); } else { System.out.println("logic error"); } } for (int noa = 0; noa < m_aNodes.size(); noa++) { if (m_aNodes.elementAt(noa).getParent(0) == null) { sour = m_aNodes.elementAt(noa); } } return sour; } /** * This will convert the shape string to an int representing that shape. * * @param sh The name of the shape. * @return An Integer representing the shape. */ private Integer getShape(String sh) { if (sh.equalsIgnoreCase("box") || sh.equalsIgnoreCase("rectangle")) { return new Integer(1); } else if (sh.equalsIgnoreCase("oval")) { return new Integer(2); } else if (sh.equalsIgnoreCase("diamond")) { return new Integer(3); } else { return null; } } /** * Converts the string representing the fill style int oa number representing * it. * * @param sty The name of the style. * @return An Integer representing the shape. */ private Integer getStyle(String sty) { if (sty.equalsIgnoreCase("filled")) { return new Integer(1); } else { return null; } } /** * This will setup the syntax for the tokenizer so that it parses the string * properly. * */ private void setSyntax() { m_st.resetSyntax(); m_st.eolIsSignificant(false); m_st.slashStarComments(true); m_st.slashSlashComments(true); // System.out.println("slash"); m_st.whitespaceChars(0, ' '); m_st.wordChars(' ' + 1, '\u00ff'); m_st.ordinaryChar('['); m_st.ordinaryChar(']'); m_st.ordinaryChar('{'); m_st.ordinaryChar('}'); m_st.ordinaryChar('-'); m_st.ordinaryChar('>'); m_st.ordinaryChar('/'); m_st.ordinaryChar('*'); m_st.quoteChar('"'); m_st.whitespaceChars(';', ';'); m_st.ordinaryChar('='); } /** * This is the alternative syntax for the tokenizer. */ private void alterSyntax() { m_st.resetSyntax(); m_st.wordChars('\u0000', '\u00ff'); m_st.slashStarComments(false); m_st.slashSlashComments(false); m_st.ordinaryChar('\n'); m_st.ordinaryChar('\r'); } /** * This will parse the next token out of the stream and check for certain * conditions. * * @param r The error string to print out if something goes wrong. */ private void nextToken(String r) { int t = 0; try { t = m_st.nextToken(); } catch (IOException e) { } if (t == StreamTokenizer.TT_EOF) { System.out.println("eof , " + r); } else if (t == StreamTokenizer.TT_NUMBER) { System.out.println("got a number , " + r); } } /** * Parses the top of the dotty stream that has the graph information. * */ private void graph() { nextToken("expected 'digraph'"); if (m_st.sval.equalsIgnoreCase("digraph")) { // m_digraph = true; NOT USED } else { System.out.println("expected 'digraph'"); } nextToken("expected a Graph Name"); if (m_st.sval != null) { // m_graphName = m_st.sval; NOT USED } else { System.out.println("expected a Graph Name"); } nextToken("expected '{'"); if (m_st.ttype == '{') { stmtList(); } else { System.out.println("expected '{'"); } } /** * This is one of the states, this one is where new items can be defined or * the structure can end. * */ private void stmtList() { boolean flag = true; while (flag) { nextToken("expects a STMT_LIST item or '}'"); if (m_st.ttype == '}') { flag = false; } else if (m_st.sval.equalsIgnoreCase("graph") || m_st.sval.equalsIgnoreCase("node") || m_st.sval.equalsIgnoreCase("edge")) { m_st.pushBack(); attrStmt(); } else { nodeId(m_st.sval, 0); } } } /** * This will deal specifically with a new object such as graph , node , edge. * */ private void attrStmt() { nextToken("expected 'graph' or 'node' or 'edge'"); if (m_st.sval.equalsIgnoreCase("graph")) { nextToken("expected a '['"); if (m_st.ttype == '[') { attrList(m_grObj); } else { System.out.println("expected a '['"); } } else if (m_st.sval.equalsIgnoreCase("node")) { nextToken("expected a '['"); if (m_st.ttype == '[') { attrList(m_noObj); } else { System.out.println("expected a '['"); } } else if (m_st.sval.equalsIgnoreCase("edge")) { nextToken("expected a '['"); if (m_st.ttype == '[') { attrList(m_edObj); } else { System.out.println("expected a '['"); } } else { System.out.println("expected 'graph' or 'node' or 'edge'"); } } /** * Generates a new InfoObject with the specified name and either does further * processing if applicable Otherwise it is an edge and will deal with that. * * @param s The ID string. * @param t Not sure!. */ private void nodeId(String s, int t) { nextToken("error occurred in node_id"); if (m_st.ttype == '}') { // creates a node if t is zero if (t == 0) { m_nodes.addElement(new InfoObject(s)); } m_st.pushBack(); } else if (m_st.ttype == '-') { nextToken("error occurred checking for an edge"); if (m_st.ttype == '>') { edgeStmt(s); } else { System.out.println("error occurred checking for an edge"); } } else if (m_st.ttype == '[') { // creates a node if t is zero and sends it to attr if (t == 0) { m_nodes.addElement(new InfoObject(s)); attrList(m_nodes.lastElement()); } else { attrList(m_edges.lastElement()); } } else if (m_st.sval != null) { // creates a node if t is zero if (t == 0) { m_nodes.addElement(new InfoObject(s)); } m_st.pushBack(); } else { System.out.println("error occurred in node_id"); } } /** * This will get the target of the edge. * * @param i The source of the edge. */ private void edgeStmt(String i) { nextToken("error getting target of edge"); if (m_st.sval != null) { m_edges.addElement(new InfoObject("an edge ,no id")); m_edges.lastElement().m_source = i; m_edges.lastElement().m_target = m_st.sval; nodeId(m_st.sval, 1); } else { System.out.println("error getting target of edge"); } } /** * This will parse all the items in the attrib list for an object. * * @param a The object that the attribs apply to. */ private void attrList(InfoObject a) { boolean flag = true; while (flag) { nextToken("error in attr_list"); // System.out.println(st.sval); if (m_st.ttype == ']') { flag = false; } else if (m_st.sval.equalsIgnoreCase("color")) { nextToken("error getting color"); if (m_st.ttype == '=') { nextToken("error getting color"); if (m_st.sval != null) { a.m_color = m_st.sval; } else { System.out.println("error getting color"); } } else { System.out.println("error getting color"); } } else if (m_st.sval.equalsIgnoreCase("fontcolor")) { nextToken("error getting font color"); if (m_st.ttype == '=') { nextToken("error getting font color"); if (m_st.sval != null) { a.m_fontColor = m_st.sval; } else { System.out.println("error getting font color"); } } else { System.out.println("error getting font color"); } } else if (m_st.sval.equalsIgnoreCase("fontsize")) { nextToken("error getting font size"); if (m_st.ttype == '=') { nextToken("error getting font size"); if (m_st.sval != null) { } else { System.out.println("error getting font size"); } } else { System.out.println("error getting font size"); } } else if (m_st.sval.equalsIgnoreCase("label")) { nextToken("error getting label"); if (m_st.ttype == '=') { nextToken("error getting label"); if (m_st.sval != null) { a.m_label = m_st.sval; } else { System.out.println("error getting label"); } } else { System.out.println("error getting label"); } } else if (m_st.sval.equalsIgnoreCase("shape")) { nextToken("error getting shape"); if (m_st.ttype == '=') { nextToken("error getting shape"); if (m_st.sval != null) { a.m_shape = m_st.sval; } else { System.out.println("error getting shape"); } } else { System.out.println("error getting shape"); } } else if (m_st.sval.equalsIgnoreCase("style")) { nextToken("error getting style"); if (m_st.ttype == '=') { nextToken("error getting style"); if (m_st.sval != null) { a.m_style = m_st.sval; } else { System.out.println("error getting style"); } } else { System.out.println("error getting style"); } } else if (m_st.sval.equalsIgnoreCase("data")) { nextToken("error getting data"); if (m_st.ttype == '=') { // data has a special data string that can have anything // this is delimited by a single comma on an otherwise empty line alterSyntax(); a.m_data = new String(""); while (true) { nextToken("error getting data"); if (m_st.sval != null && a.m_data != null && m_st.sval.equals(",")) { break; } else if (m_st.sval != null) { a.m_data = a.m_data.concat(m_st.sval); } else if (m_st.ttype == '\r') { a.m_data = a.m_data.concat("\r"); } else if (m_st.ttype == '\n') { a.m_data = a.m_data.concat("\n"); } else { System.out.println("error getting data"); } } setSyntax(); } else { System.out.println("error getting data"); } } } } // special class for use in creating the tree /** * This is an internal class used to keep track of the info for the objects * before they are actually created. */ private class InfoObject { /** The ID string for th object. */ public String m_id; /** The color name for the object. */ public String m_color; /** The font color for the object. not in use. */ public String m_fontColor; /** The label for the object. */ public String m_label; /** The shape name of for the object. */ public String m_shape; /** The backstyle name for the object. */ public String m_style; /** The source ID of the object. */ public String m_source; /** The target ID of the object. */ public String m_target; /** The data for this object. */ public String m_data; /** * This will construct a new InfoObject with the specified ID string. */ public InfoObject(String i) { m_id = i; m_color = null; m_fontColor = null; m_label = null; m_shape = null; m_style = null; m_source = null; m_target = null; m_data = 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/treevisualizer/TreeDisplayEvent.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * TreeDisplayEvent.java * Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.treevisualizer; /** * An event containing the user selection from the tree display * * @author Malcolm Ware (mfw4@cs.waikato.ac.nz) * @version $Revision$ */ public class TreeDisplayEvent { public static final int NO_COMMAND = 0; public static final int ADD_CHILDREN = 1; public static final int REMOVE_CHILDREN = 2; /** States that the user has accepted the tree. */ public static final int ACCEPT = 3; /** Asks for another learning scheme to classify this node. */ public static final int CLASSIFY_CHILD = 4; /** Command to remove instances from this node and send them to the * VisualizePanel. */ public static final int SEND_INSTANCES = 5; /** The int representing the action. */ private int m_command; /** The id string for the node to alter. */ private String m_nodeId; /** * Constructs an event with the specified command * and what the command is applied to. * @param ar The event type. * @param id The id string for the node to perform the action on. */ public TreeDisplayEvent(int ar, String id) { m_command = 0; if (ar == 1 || ar == 2 || ar == 3 || ar == 4 || ar == 5) { //then command is good m_command = ar; } m_nodeId = id; } /** * @return The command. */ public int getCommand() { return m_command; } /** * @return The id of the node. */ public String getID() { return m_nodeId; } }
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/treevisualizer/TreeDisplayListener.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * TreeDisplayListener.java * Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.treevisualizer; //this is simply used to get some user changes from the displayer to an actual //class //that contains the actual structure of the data the displayer is displaying /** * Interface implemented by classes that wish to recieve user selection events * from a tree displayer. * * @author Malcolm Ware (mfw4@cs.waikato.ac.nz) * @version $Revision$ */ public interface TreeDisplayListener { /** * Gets called when the user selects something, in the tree display. * @param e Contains what the user selected with what it was selected for. */ void userCommand(TreeDisplayEvent 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/treevisualizer/TreeVisualizer.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * TreeVisualizer.java * Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.treevisualizer; import java.awt.Color; import java.awt.Container; import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.InputEvent; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.io.FileReader; import java.io.IOException; import java.io.StringReader; import java.util.Properties; import javax.swing.*; import weka.core.Instances; import weka.core.Utils; import weka.gui.visualize.PrintablePanel; import weka.gui.visualize.VisualizePanel; import weka.gui.visualize.VisualizeUtils; /** * Class for displaying a Node structure in Swing. * <p> * * To work this class simply create an instance of it. * <p> * * Assign it to a window or other such object. * <p> * * Resize it to the desired size. * <p> * * * When using the Displayer hold the left mouse button to drag the tree around. * <p> * * Click the left mouse button with ctrl to shrink the size of the tree by half. * <p> * * Click and drag with the left mouse button and shift to draw a box, when the * left mouse button is released the contents of the box will be magnified to * fill the screen. * <p> * <p> * * Click the right mouse button to bring up a menu. * <p> * Most options are self explanatory. * <p> * * Select Auto Scale to set the tree to it's optimal display size. * * @author Malcolm Ware (mfw4@cs.waikato.ac.nz) * @version $Revision$ */ public class TreeVisualizer extends PrintablePanel implements MouseMotionListener, MouseListener, ActionListener, ItemListener { /** for serialization */ private static final long serialVersionUID = -8668637962504080749L; /** the props file. */ public final static String PROPERTIES_FILE = "weka/gui/treevisualizer/TreeVisualizer.props"; /** The placement algorithm for the Node structure. */ private final NodePlace m_placer; /** The top Node. */ private final Node m_topNode; /** The postion of the view relative to the tree. */ private final Dimension m_viewPos; /** The size of the tree in pixels. */ private final Dimension m_viewSize; /** The font used to display the tree. */ private Font m_currentFont; /** The size information for the current font. */ private FontMetrics m_fontSize; /** The number of Nodes in the tree. */ private final int m_numNodes; /** The number of levels in the tree. */ private final int m_numLevels; /** * An array with the Nodes sorted into it and display information about the * Nodes. */ private final NodeInfo[] m_nodes; /** * An array with the Edges sorted into it and display information about the * Edges. */ private final EdgeInfo[] m_edges; /** A timer to keep the frame rate constant. */ private final Timer m_frameLimiter; /** Describes the action the user is performing. */ private int m_mouseState; /** A variable used to tag the start pos of a user action. */ private final Dimension m_oldMousePos; /** A variable used to tag the most current point of a user action. */ private final Dimension m_newMousePos; /** * A variable used to determine for the clicked method if any other mouse * state has already taken place. */ private boolean m_clickAvailable; /** A variable used to remember the desired view pos. */ private final Dimension m_nViewPos; /** A variable used to remember the desired tree size. */ private final Dimension m_nViewSize; /** The number of frames left to calculate. */ private int m_scaling; /** A right (or middle) click popup menu. */ private final JPopupMenu m_winMenu; /** An option on the win_menu */ private final JMenuItem m_topN; /** An option on the win_menu */ private final JMenuItem m_fitToScreen; /** An option on the win_menu */ private final JMenuItem m_autoScale; /** A sub group on the win_menu */ private final JMenu m_selectFont; /** A grouping for the font choices */ private final ButtonGroup m_selectFontGroup; /** A font choice. */ private final JRadioButtonMenuItem m_size24; /** A font choice. */ private final JRadioButtonMenuItem m_size22; /** A font choice. */ private final JRadioButtonMenuItem m_size20; /** A font choice. */ private final JRadioButtonMenuItem m_size18; /** A font choice. */ private final JRadioButtonMenuItem m_size16; /** A font choice. */ private final JRadioButtonMenuItem m_size14; /** A font choice. */ private final JRadioButtonMenuItem m_size12; /** A font choice. */ private final JRadioButtonMenuItem m_size10; /** A font choice. */ private final JRadioButtonMenuItem m_size8; /** A font choice. */ private final JRadioButtonMenuItem m_size6; /** A font choice. */ private final JRadioButtonMenuItem m_size4; /** A font choice. */ private final JRadioButtonMenuItem m_size2; /** A font choice. */ private final JRadioButtonMenuItem m_size1; /** An option on the win menu. */ private final JMenuItem m_accept; /** A right or middle click popup menu for nodes. */ private final JPopupMenu m_nodeMenu; /** A visualize choice for the node, may not be available. */ private final JMenuItem m_visualise; /** * An add children to Node choice, This is only available if the tree display * has a treedisplay listerner added to it. */ // private JMenuItem m_addChildren; NOT USED /** Similar to add children but now it removes children. */ private JMenuItem m_remChildren; /** Use this to have J48 classify this node. */ private JMenuItem m_classifyChild; /** Use this to dump the instances from this node to the vis panel. */ private JMenuItem m_sendInstances; /** * The subscript for the currently selected node (this is an internal thing, * so the user is unaware of this). */ private int m_focusNode; /** * The Node the user is currently focused on , this is similar to focus node * except that it is used by other classes rather than this one. */ private int m_highlightNode; /* A pointer to this tree's classifier if a classifier is using it. */ // private UserClassifier classer; private final TreeDisplayListener m_listener; // private JTextField m_searchString; NOT USED // private JDialog m_searchWin; NOT USED // private JRadioButton m_caseSen; NOT USED /** the font color. */ protected Color m_FontColor = null; /** the background color. */ protected Color m_BackgroundColor = null; /** the node color. */ protected Color m_NodeColor = null; /** the line color. */ protected Color m_LineColor = null; /** the color of the zoombox. */ protected Color m_ZoomBoxColor = null; /** the XOR color of the zoombox. */ protected Color m_ZoomBoxXORColor = null; /** whether to show the border or not. */ protected boolean m_ShowBorder = true; // ///////////////// // this is the event fireing stuff /** * Constructs Displayer to display a tree provided in a dot format. Uses the * NodePlacer to place the Nodes. * * @param tdl listener * @param dot string containing the dot representation of the tree to display * @param p the algorithm to be used to position the nodes. */ public TreeVisualizer(TreeDisplayListener tdl, String dot, NodePlace p) { super(); initialize(); // generate the node structure in here if (m_ShowBorder) { setBorder(BorderFactory.createTitledBorder("Tree View")); } m_listener = tdl; TreeBuild builder = new TreeBuild(); Node n = null; // NodePlace arrange = new PlaceNode2(); NOT USED n = builder.create(new StringReader(dot)); // System.out.println(n.getCount(n, 0)); // if the size needs to be automatically alocated I will do it here m_highlightNode = 5; m_topNode = n; m_placer = p; m_placer.place(m_topNode); m_viewPos = new Dimension(0, 0); // will be adjusted m_viewSize = new Dimension(800, 600); // I allocate this now so that // the tree will be visible // when the panel is enlarged m_nViewPos = new Dimension(0, 0); m_nViewSize = new Dimension(800, 600); m_scaling = 0; m_numNodes = Node.getCount(m_topNode, 0); // note the second // argument must be a zero, this is a // recursive function m_numLevels = Node.getHeight(m_topNode, 0); m_nodes = new NodeInfo[m_numNodes]; m_edges = new EdgeInfo[m_numNodes - 1]; arrayFill(m_topNode, m_nodes, m_edges); changeFontSize(12); m_mouseState = 0; m_oldMousePos = new Dimension(0, 0); m_newMousePos = new Dimension(0, 0); m_frameLimiter = new Timer(120, this); m_winMenu = new JPopupMenu(); m_topN = new JMenuItem("Center on Top Node"); // note to change // language change this line m_topN.setActionCommand("Center on Top Node"); // but not this one, // same for all menu items m_fitToScreen = new JMenuItem("Fit to Screen"); m_fitToScreen.setActionCommand("Fit to Screen"); // unhide = new JMenuItem("Unhide all Nodes"); m_selectFont = new JMenu("Select Font"); m_selectFont.setActionCommand("Select Font"); m_autoScale = new JMenuItem("Auto Scale"); m_autoScale.setActionCommand("Auto Scale"); m_selectFontGroup = new ButtonGroup(); m_accept = new JMenuItem("Accept The Tree"); m_accept.setActionCommand("Accept The Tree"); m_winMenu.add(m_topN); m_winMenu.addSeparator(); m_winMenu.add(m_fitToScreen); m_winMenu.add(m_autoScale); // m_winMenu.addSeparator(); // m_winMenu.add(unhide); m_winMenu.addSeparator(); m_winMenu.add(m_selectFont); if (m_listener != null) { m_winMenu.addSeparator(); m_winMenu.add(m_accept); } m_topN.addActionListener(this); m_fitToScreen.addActionListener(this); // unhide.addActionListener(this); m_autoScale.addActionListener(this); m_accept.addActionListener(this); m_size24 = new JRadioButtonMenuItem("Size 24", false);// ,select_font_group); m_size22 = new JRadioButtonMenuItem("Size 22", false);// ,select_font_group); m_size20 = new JRadioButtonMenuItem("Size 20", false);// ,select_font_group); m_size18 = new JRadioButtonMenuItem("Size 18", false);// ,select_font_group); m_size16 = new JRadioButtonMenuItem("Size 16", false);// ,select_font_group); m_size14 = new JRadioButtonMenuItem("Size 14", false);// ,select_font_group); m_size12 = new JRadioButtonMenuItem("Size 12", true);// ,select_font_group); m_size10 = new JRadioButtonMenuItem("Size 10", false);// ,select_font_group); m_size8 = new JRadioButtonMenuItem("Size 8", false);// ,select_font_group); m_size6 = new JRadioButtonMenuItem("Size 6", false);// ,select_font_group); m_size4 = new JRadioButtonMenuItem("Size 4", false);// ,select_font_group); m_size2 = new JRadioButtonMenuItem("Size 2", false);// ,select_font_group); m_size1 = new JRadioButtonMenuItem("Size 1", false);// ,select_font_group); m_size24.setActionCommand("Size 24");// ,select_font_group); m_size22.setActionCommand("Size 22");// ,select_font_group); m_size20.setActionCommand("Size 20");// ,select_font_group); m_size18.setActionCommand("Size 18");// ,select_font_group); m_size16.setActionCommand("Size 16");// ,select_font_group); m_size14.setActionCommand("Size 14");// ,select_font_group); m_size12.setActionCommand("Size 12");// ,select_font_group); m_size10.setActionCommand("Size 10");// ,select_font_group); m_size8.setActionCommand("Size 8");// ,select_font_group); m_size6.setActionCommand("Size 6");// ,select_font_group); m_size4.setActionCommand("Size 4");// ,select_font_group); m_size2.setActionCommand("Size 2");// ,select_font_group); m_size1.setActionCommand("Size 1");// ,select_font_group); m_selectFontGroup.add(m_size24); m_selectFontGroup.add(m_size22); m_selectFontGroup.add(m_size20); m_selectFontGroup.add(m_size18); m_selectFontGroup.add(m_size16); m_selectFontGroup.add(m_size14); m_selectFontGroup.add(m_size12); m_selectFontGroup.add(m_size10); m_selectFontGroup.add(m_size8); m_selectFontGroup.add(m_size6); m_selectFontGroup.add(m_size4); m_selectFontGroup.add(m_size2); m_selectFontGroup.add(m_size1); m_selectFont.add(m_size24); m_selectFont.add(m_size22); m_selectFont.add(m_size20); m_selectFont.add(m_size18); m_selectFont.add(m_size16); m_selectFont.add(m_size14); m_selectFont.add(m_size12); m_selectFont.add(m_size10); m_selectFont.add(m_size8); m_selectFont.add(m_size6); m_selectFont.add(m_size4); m_selectFont.add(m_size2); m_selectFont.add(m_size1); m_size24.addItemListener(this); m_size22.addItemListener(this); m_size20.addItemListener(this); m_size18.addItemListener(this); m_size16.addItemListener(this); m_size14.addItemListener(this); m_size12.addItemListener(this); m_size10.addItemListener(this); m_size8.addItemListener(this); m_size6.addItemListener(this); m_size4.addItemListener(this); m_size2.addItemListener(this); m_size1.addItemListener(this); /* * search_string = new JTextField(22); search_win = new JDialog(); case_sen * = new JRadioButton("Case Sensitive"); * * * * search_win.getContentPane().setLayout(null); search_win.setSize(300, * 200); * * search_win.getContentPane().add(search_string); * search_win.getContentPane().add(case_sen); * * search_string.setLocation(50, 70); case_sen.setLocation(50, 120); * case_sen.setSize(100, 24); search_string.setSize(100, 24); * //search_string.setVisible(true); //case_sen.setVisible(true); * * //search_win.setVisible(true); */ m_nodeMenu = new JPopupMenu(); /* A visualize choice for the node, may not be available. */ m_visualise = new JMenuItem("Visualize The Node"); m_visualise.setActionCommand("Visualize The Node"); m_visualise.addActionListener(this); m_nodeMenu.add(m_visualise); if (m_listener != null) { m_remChildren = new JMenuItem("Remove Child Nodes"); m_remChildren.setActionCommand("Remove Child Nodes"); m_remChildren.addActionListener(this); m_nodeMenu.add(m_remChildren); m_classifyChild = new JMenuItem("Use Classifier..."); m_classifyChild.setActionCommand("classify_child"); m_classifyChild.addActionListener(this); m_nodeMenu.add(m_classifyChild); /* * m_sendInstances = new JMenuItem("Add Instances To Viewer"); * m_sendInstances.setActionCommand("send_instances"); * m_sendInstances.addActionListener(this); * m_nodeMenu.add(m_sendInstances); */ } m_focusNode = -1; m_highlightNode = -1; addMouseMotionListener(this); addMouseListener(this); // repaint(); // frame_limiter.setInitialDelay(); m_frameLimiter.setRepeats(false); m_frameLimiter.start(); } /** * Constructs Displayer with the specified Node as the top of the tree, and * uses the NodePlacer to place the Nodes. * * @param tdl listener. * @param n the top Node of the tree to be displayed. * @param p the algorithm to be used to position the nodes. */ public TreeVisualizer(TreeDisplayListener tdl, Node n, NodePlace p) { super(); initialize(); // if the size needs to be automatically alocated I will do it here if (m_ShowBorder) { setBorder(BorderFactory.createTitledBorder("Tree View")); } m_listener = tdl; m_topNode = n; m_placer = p; m_placer.place(m_topNode); m_viewPos = new Dimension(0, 0); // will be adjusted m_viewSize = new Dimension(800, 600); // I allocate this now so that // the tree will be visible // when the panel is enlarged m_nViewPos = new Dimension(0, 0); m_nViewSize = new Dimension(800, 600); m_scaling = 0; m_numNodes = Node.getCount(m_topNode, 0); // note the second // argument must be a zero, this is a // recursive function m_numLevels = Node.getHeight(m_topNode, 0); m_nodes = new NodeInfo[m_numNodes]; m_edges = new EdgeInfo[m_numNodes - 1]; arrayFill(m_topNode, m_nodes, m_edges); changeFontSize(12); m_mouseState = 0; m_oldMousePos = new Dimension(0, 0); m_newMousePos = new Dimension(0, 0); m_frameLimiter = new Timer(120, this); m_winMenu = new JPopupMenu(); m_topN = new JMenuItem("Center on Top Node"); // note to change // language change this line m_topN.setActionCommand("Center on Top Node"); // but not this // one, same for all menu items m_fitToScreen = new JMenuItem("Fit to Screen"); m_fitToScreen.setActionCommand("Fit to Screen"); // unhide = new JMenuItem("Unhide all Nodes"); m_selectFont = new JMenu("Select Font"); m_selectFont.setActionCommand("Select Font"); m_autoScale = new JMenuItem("Auto Scale"); m_autoScale.setActionCommand("Auto Scale"); m_selectFontGroup = new ButtonGroup(); m_accept = new JMenuItem("Accept The Tree"); m_accept.setActionCommand("Accept The Tree"); m_winMenu.add(m_topN); m_winMenu.addSeparator(); m_winMenu.add(m_fitToScreen); m_winMenu.add(m_autoScale); m_winMenu.addSeparator(); // m_winMenu.add(unhide); m_winMenu.addSeparator(); m_winMenu.add(m_selectFont); m_winMenu.addSeparator(); if (m_listener != null) { m_winMenu.add(m_accept); } m_topN.addActionListener(this); m_fitToScreen.addActionListener(this); // unhide.addActionListener(this); m_autoScale.addActionListener(this); m_accept.addActionListener(this); m_size24 = new JRadioButtonMenuItem("Size 24", false);// ,select_font_group); m_size22 = new JRadioButtonMenuItem("Size 22", false);// ,select_font_group); m_size20 = new JRadioButtonMenuItem("Size 20", false);// ,select_font_group); m_size18 = new JRadioButtonMenuItem("Size 18", false);// ,select_font_group); m_size16 = new JRadioButtonMenuItem("Size 16", false);// ,select_font_group); m_size14 = new JRadioButtonMenuItem("Size 14", false);// ,select_font_group); m_size12 = new JRadioButtonMenuItem("Size 12", true);// ,select_font_group); m_size10 = new JRadioButtonMenuItem("Size 10", false);// ,select_font_group); m_size8 = new JRadioButtonMenuItem("Size 8", false);// ,select_font_group); m_size6 = new JRadioButtonMenuItem("Size 6", false);// ,select_font_group); m_size4 = new JRadioButtonMenuItem("Size 4", false);// ,select_font_group); m_size2 = new JRadioButtonMenuItem("Size 2", false);// ,select_font_group); m_size1 = new JRadioButtonMenuItem("Size 1", false);// ,select_font_group); m_size24.setActionCommand("Size 24");// ,select_font_group); m_size22.setActionCommand("Size 22");// ,select_font_group); m_size20.setActionCommand("Size 20");// ,select_font_group); m_size18.setActionCommand("Size 18");// ,select_font_group); m_size16.setActionCommand("Size 16");// ,select_font_group); m_size14.setActionCommand("Size 14");// ,select_font_group); m_size12.setActionCommand("Size 12");// ,select_font_group); m_size10.setActionCommand("Size 10");// ,select_font_group); m_size8.setActionCommand("Size 8");// ,select_font_group); m_size6.setActionCommand("Size 6");// ,select_font_group); m_size4.setActionCommand("Size 4");// ,select_font_group); m_size2.setActionCommand("Size 2");// ,select_font_group); m_size1.setActionCommand("Size 1");// ,select_font_group); m_selectFontGroup.add(m_size24); m_selectFontGroup.add(m_size22); m_selectFontGroup.add(m_size20); m_selectFontGroup.add(m_size18); m_selectFontGroup.add(m_size16); m_selectFontGroup.add(m_size14); m_selectFontGroup.add(m_size12); m_selectFontGroup.add(m_size10); m_selectFontGroup.add(m_size8); m_selectFontGroup.add(m_size6); m_selectFontGroup.add(m_size4); m_selectFontGroup.add(m_size2); m_selectFontGroup.add(m_size1); m_selectFont.add(m_size24); m_selectFont.add(m_size22); m_selectFont.add(m_size20); m_selectFont.add(m_size18); m_selectFont.add(m_size16); m_selectFont.add(m_size14); m_selectFont.add(m_size12); m_selectFont.add(m_size10); m_selectFont.add(m_size8); m_selectFont.add(m_size6); m_selectFont.add(m_size4); m_selectFont.add(m_size2); m_selectFont.add(m_size1); m_size24.addItemListener(this); m_size22.addItemListener(this); m_size20.addItemListener(this); m_size18.addItemListener(this); m_size16.addItemListener(this); m_size14.addItemListener(this); m_size12.addItemListener(this); m_size10.addItemListener(this); m_size8.addItemListener(this); m_size6.addItemListener(this); m_size4.addItemListener(this); m_size2.addItemListener(this); m_size1.addItemListener(this); /* * search_string = new JTextField(22); search_win = new JDialog(); case_sen * = new JRadioButton("Case Sensitive"); * * * * search_win.getContentPane().setLayout(null); search_win.setSize(300, * 200); * * search_win.getContentPane().add(search_string); * search_win.getContentPane().add(case_sen); * * search_string.setLocation(50, 70); case_sen.setLocation(50, 120); * case_sen.setSize(100, 24); search_string.setSize(100, 24); * //search_string.setVisible(true); //case_sen.setVisible(true); * * search_win.setVisible(true); */ m_nodeMenu = new JPopupMenu(); /* A visualize choice for the node, may not be available. */ m_visualise = new JMenuItem("Visualize The Node"); m_visualise.setActionCommand("Visualize The Node"); m_visualise.addActionListener(this); m_nodeMenu.add(m_visualise); if (m_listener != null) { m_remChildren = new JMenuItem("Remove Child Nodes"); m_remChildren.setActionCommand("Remove Child Nodes"); m_remChildren.addActionListener(this); m_nodeMenu.add(m_remChildren); m_classifyChild = new JMenuItem("Use Classifier..."); m_classifyChild.setActionCommand("classify_child"); m_classifyChild.addActionListener(this); m_nodeMenu.add(m_classifyChild); m_sendInstances = new JMenuItem("Add Instances To Viewer"); m_sendInstances.setActionCommand("send_instances"); m_sendInstances.addActionListener(this); m_nodeMenu.add(m_sendInstances); } m_focusNode = -1; m_highlightNode = -1; addMouseMotionListener(this); addMouseListener(this); // repaint(); // frame_limiter.setInitialDelay(); m_frameLimiter.setRepeats(false); m_frameLimiter.start(); } /** * Processes the color string. Returns null if empty. * * @param colorStr the string to process * @return the processed color or null */ protected Color getColor(String colorStr) { Color result; result = null; if ((colorStr != null) && (colorStr.length() > 0)) { result = VisualizeUtils.processColour(colorStr, result); } return result; } /** * Performs some initialization. */ protected void initialize() { Properties props; try { props = Utils.readProperties(PROPERTIES_FILE); } catch (Exception e) { e.printStackTrace(); props = new Properties(); } m_FontColor = getColor(props.getProperty("FontColor", "")); m_BackgroundColor = getColor(props.getProperty("BackgroundColor", "")); m_NodeColor = getColor(props.getProperty("NodeColor", "")); m_LineColor = getColor(props.getProperty("LineColor", "")); m_ZoomBoxColor = getColor(props.getProperty("ZoomBoxColor", "")); m_ZoomBoxXORColor = getColor(props.getProperty("ZoomBoxXORColor", "")); m_ShowBorder = Boolean .parseBoolean(props.getProperty("ShowBorder", "true")); } /** * Fits the tree to the current screen size. Call this after window has been * created to get the entrire tree to be in view upon launch. */ public void fitToScreen() { getScreenFit(m_viewPos, m_viewSize); repaint(); } /** * Calculates the dimensions needed to fit the entire tree into view. */ private void getScreenFit(Dimension np, Dimension ns) { int leftmost = 1000000, rightmost = -1000000; int leftCenter = 1000000, rightCenter = -1000000, rightNode = 0; int highest = -1000000, highTop = -1000000; for (int noa = 0; noa < m_numNodes; noa++) { calcScreenCoords(noa); if (m_nodes[noa].m_center - m_nodes[noa].m_side < leftmost) { leftmost = m_nodes[noa].m_center - m_nodes[noa].m_side; } if (m_nodes[noa].m_center < leftCenter) { leftCenter = m_nodes[noa].m_center; } if (m_nodes[noa].m_center + m_nodes[noa].m_side > rightmost) { rightmost = m_nodes[noa].m_center + m_nodes[noa].m_side; } if (m_nodes[noa].m_center > rightCenter) { rightCenter = m_nodes[noa].m_center; rightNode = noa; } if (m_nodes[noa].m_top + m_nodes[noa].m_height > highest) { highest = m_nodes[noa].m_top + m_nodes[noa].m_height; } if (m_nodes[noa].m_top > highTop) { highTop = m_nodes[noa].m_top; } } ns.width = getWidth(); ns.width -= leftCenter - leftmost + rightmost - rightCenter + 30; ns.height = getHeight() - highest + highTop - 40; if (m_nodes[rightNode].m_node.getCenter() != 0 && leftCenter != rightCenter) { ns.width /= m_nodes[rightNode].m_node.getCenter(); } if (ns.width < 10) { ns.width = 10; } if (ns.height < 10) { ns.height = 10; } np.width = (leftCenter - leftmost + rightmost - rightCenter) / 2 + 15; np.height = (highest - highTop) / 2 + 20; } /** * Performs the action associated with the ActionEvent. * * @param e the action event. */ @Override public void actionPerformed(ActionEvent e) { // JMenuItem m = (JMenuItem)e.getSource(); if (e.getActionCommand() == null) { if (m_scaling == 0) { repaint(); } else { animateScaling(m_nViewPos, m_nViewSize, m_scaling); } } else if (e.getActionCommand().equals("Fit to Screen")) { Dimension np = new Dimension(); Dimension ns = new Dimension(); getScreenFit(np, ns); animateScaling(np, ns, 10); } else if (e.getActionCommand().equals("Center on Top Node")) { int tpx = (int) (m_topNode.getCenter() * m_viewSize.width); // calculate // the top nodes postion but don't adjust for where int tpy = (int) (m_topNode.getTop() * m_viewSize.height); // view is Dimension np = new Dimension(getSize().width / 2 - tpx, getSize().width / 6 - tpy); animateScaling(np, m_viewSize, 10); } else if (e.getActionCommand().equals("Auto Scale")) { autoScale(); // this will figure the best scale value // keep the focus on the middle of the screen and call animate } else if (e.getActionCommand().equals("Visualize The Node")) { // send the node data to the visualizer if (m_focusNode >= 0) { Instances inst; if ((inst = m_nodes[m_focusNode].m_node.getInstances()) != null) { VisualizePanel pan = new VisualizePanel(); pan.setInstances(inst); JFrame nf = Utils.getWekaJFrame("", this); nf.getContentPane().add(pan); nf.pack(); nf.setSize(800, 600); nf.setLocationRelativeTo(SwingUtilities.getWindowAncestor(this)); nf.setVisible(true); } else { JOptionPane.showMessageDialog(this, "Sorry, there is no " + "available Instances data for " + "this Node.", "Sorry!", JOptionPane.WARNING_MESSAGE); } } else { JOptionPane.showMessageDialog(this, "Error, there is no " + "selected Node to perform " + "this operation on.", "Error!", JOptionPane.ERROR_MESSAGE); } } else if (e.getActionCommand().equals("Create Child Nodes")) { if (m_focusNode >= 0) { if (m_listener != null) { // then send message to the listener m_listener.userCommand(new TreeDisplayEvent( TreeDisplayEvent.ADD_CHILDREN, m_nodes[m_focusNode].m_node .getRefer())); } else { JOptionPane.showMessageDialog(this, "Sorry, there is no " + "available Decision Tree to " + "perform this operation on.", "Sorry!", JOptionPane.WARNING_MESSAGE); } } else { JOptionPane.showMessageDialog(this, "Error, there is no " + "selected Node to perform this " + "operation on.", "Error!", JOptionPane.ERROR_MESSAGE); } } else if (e.getActionCommand().equals("Remove Child Nodes")) { if (m_focusNode >= 0) { if (m_listener != null) { // then send message to the listener m_listener.userCommand(new TreeDisplayEvent( TreeDisplayEvent.REMOVE_CHILDREN, m_nodes[m_focusNode].m_node .getRefer())); } else { JOptionPane.showMessageDialog(this, "Sorry, there is no " + "available Decsion Tree to " + "perform this operation on.", "Sorry!", JOptionPane.WARNING_MESSAGE); } } else { JOptionPane.showMessageDialog(this, "Error, there is no " + "selected Node to perform this " + "operation on.", "Error!", JOptionPane.ERROR_MESSAGE); } } else if (e.getActionCommand().equals("classify_child")) { if (m_focusNode >= 0) { if (m_listener != null) { // then send message to the listener m_listener.userCommand(new TreeDisplayEvent( TreeDisplayEvent.CLASSIFY_CHILD, m_nodes[m_focusNode].m_node .getRefer())); } else { JOptionPane.showMessageDialog(this, "Sorry, there is no " + "available Decsion Tree to " + "perform this operation on.", "Sorry!", JOptionPane.WARNING_MESSAGE); } } else { JOptionPane.showMessageDialog(this, "Error, there is no " + "selected Node to perform this " + "operation on.", "Error!", JOptionPane.ERROR_MESSAGE); } } else if (e.getActionCommand().equals("send_instances")) { if (m_focusNode >= 0) { if (m_listener != null) { // then send message to the listener m_listener.userCommand(new TreeDisplayEvent( TreeDisplayEvent.SEND_INSTANCES, m_nodes[m_focusNode].m_node .getRefer())); } else { JOptionPane.showMessageDialog(this, "Sorry, there is no " + "available Decsion Tree to " + "perform this operation on.", "Sorry!", JOptionPane.WARNING_MESSAGE); } } else { JOptionPane.showMessageDialog(this, "Error, there is no " + "selected Node to perform this " + "operation on.", "Error!", JOptionPane.ERROR_MESSAGE); } } else if (e.getActionCommand().equals("Accept The Tree")) { if (m_listener != null) { // then send message to the listener saying that the tree is done m_listener.userCommand(new TreeDisplayEvent(TreeDisplayEvent.ACCEPT, null)); } else { JOptionPane.showMessageDialog(this, "Sorry, there is no " + "available Decision Tree to " + "perform this operation on.", "Sorry!", JOptionPane.WARNING_MESSAGE); } } } /** * Performs the action associated with the ItemEvent. * * @param e the item event. */ @Override public void itemStateChanged(ItemEvent e) { JRadioButtonMenuItem c = (JRadioButtonMenuItem) e.getSource(); if (c.getActionCommand().equals("Size 24")) { changeFontSize(24); } else if (c.getActionCommand().equals("Size 22")) { changeFontSize(22); } else if (c.getActionCommand().equals("Size 20")) { changeFontSize(20); } else if (c.getActionCommand().equals("Size 18")) { changeFontSize(18); } else if (c.getActionCommand().equals("Size 16")) { changeFontSize(16); } else if (c.getActionCommand().equals("Size 14")) { changeFontSize(14); } else if (c.getActionCommand().equals("Size 12")) { changeFontSize(12); } else if (c.getActionCommand().equals("Size 10")) { changeFontSize(10); } else if (c.getActionCommand().equals("Size 8")) { changeFontSize(8); } else if (c.getActionCommand().equals("Size 6")) { changeFontSize(6); } else if (c.getActionCommand().equals("Size 4")) { changeFontSize(4); } else if (c.getActionCommand().equals("Size 2")) { changeFontSize(2); } else if (c.getActionCommand().equals("Size 1")) { changeFontSize(1); } else if (c.getActionCommand().equals("Hide Descendants")) { // focus_node.setCVisible(!c.isSelected()); // no longer used... } } /** * Does nothing. * * @param e the mouse event. */ @Override public void mouseClicked(MouseEvent e) { // if the mouse was left clicked on // the node then if (m_clickAvailable) { // determine if the click was on a node or not int s = -1; for (int noa = 0; noa < m_numNodes; noa++) { if (m_nodes[noa].m_quad == 18) { // then is on the screen calcScreenCoords(noa); if (e.getX() <= m_nodes[noa].m_center + m_nodes[noa].m_side && e.getX() >= m_nodes[noa].m_center - m_nodes[noa].m_side && e.getY() >= m_nodes[noa].m_top && e.getY() <= m_nodes[noa].m_top + m_nodes[noa].m_height) { // then it is this node that the mouse was clicked on s = noa; } m_nodes[noa].m_top = 32000; } } m_focusNode = s; if (m_focusNode != -1) { if (m_listener != null) { // then set this to be the selected node for editing actionPerformed(new ActionEvent(this, 32000, "Create Child Nodes")); } else { // then open a visualize to display this nodes instances if possible actionPerformed(new ActionEvent(this, 32000, "Visualize The Node")); } } } } /** * Determines what action the user wants to perform. * * @param e the mouse event. */ @Override public void mousePressed(MouseEvent e) { m_frameLimiter.setRepeats(true); if ((e.getModifiers() & InputEvent.BUTTON1_MASK) != 0 && !e.isAltDown() && m_mouseState == 0 && m_scaling == 0) { // then the left mouse button has been pressed // check for modifiers if (((e.getModifiers() & InputEvent.CTRL_MASK) != 0) && ((e.getModifiers() & InputEvent.SHIFT_MASK) == 0)) { // then is in zoom out mode m_mouseState = 2; } else if (((e.getModifiers() & InputEvent.SHIFT_MASK) != 0) && ((e.getModifiers() & InputEvent.CTRL_MASK) == 0)) { // then is in zoom mode // note if both are pressed default action is to zoom out m_oldMousePos.width = e.getX(); m_oldMousePos.height = e.getY(); m_newMousePos.width = e.getX(); m_newMousePos.height = e.getY(); m_mouseState = 3; Graphics g = getGraphics(); if (m_ZoomBoxColor == null) { g.setColor(Color.black); } else { g.setColor(m_ZoomBoxColor); } if (m_ZoomBoxXORColor == null) { g.setXORMode(Color.white); } else { g.setXORMode(m_ZoomBoxXORColor); } g.drawRect(m_oldMousePos.width, m_oldMousePos.height, m_newMousePos.width - m_oldMousePos.width, m_newMousePos.height - m_oldMousePos.height); g.dispose(); } else { // no modifiers drag area around m_oldMousePos.width = e.getX(); m_oldMousePos.height = e.getY(); m_newMousePos.width = e.getX(); m_newMousePos.height = e.getY(); m_mouseState = 1; m_frameLimiter.start(); } } // pop up save dialog explicitly (is somehow overridden...) else if ((e.getButton() == MouseEvent.BUTTON1) && e.isAltDown() && e.isShiftDown() && !e.isControlDown()) { saveComponent(); } else if (m_mouseState == 0 && m_scaling == 0) { // either middle or right mouse button pushed // determine menu to use } } /** * Performs the final stages of what the user wants to perform. * * @param e the mouse event. */ @Override public void mouseReleased(MouseEvent e) { if (m_mouseState == 1) { // this is used by mouseClicked to determine if it is alright to do // something m_clickAvailable = true; // note that a standard click with the left mouse is pretty much the // only safe input left to be assigned anything. } else { m_clickAvailable = false; } if (m_mouseState == 2 && mouseInBounds(e)) { // then zoom out; m_mouseState = 0; Dimension ns = new Dimension(m_viewSize.width / 2, m_viewSize.height / 2); if (ns.width < 10) { ns.width = 10; } if (ns.height < 10) { ns.height = 10; } Dimension d = getSize(); Dimension np = new Dimension( (int) (d.width / 2 - ((double) d.width / 2 - m_viewPos.width) / 2), (int) (d.height / 2 - ((double) d.height / 2 - m_viewPos.height) / 2)); animateScaling(np, ns, 10); // view_pos.width += view_size.width / 2; // view_pos.height += view_size.height / 2; } else if (m_mouseState == 3) { // then zoom in m_mouseState = 0; Graphics g = getGraphics(); if (m_ZoomBoxColor == null) { g.setColor(Color.black); } else { g.setColor(m_ZoomBoxColor); } if (m_ZoomBoxXORColor == null) { g.setXORMode(Color.white); } else { g.setXORMode(m_ZoomBoxXORColor); } g.drawRect(m_oldMousePos.width, m_oldMousePos.height, m_newMousePos.width - m_oldMousePos.width, m_newMousePos.height - m_oldMousePos.height); g.dispose(); int cw = m_newMousePos.width - m_oldMousePos.width; int ch = m_newMousePos.height - m_oldMousePos.height; if (cw >= 1 && ch >= 1) { if (mouseInBounds(e) && (getSize().width / cw) <= 6 && (getSize().height / ch) <= 6) { // now calculate new position and size Dimension ns = new Dimension(); Dimension np = new Dimension(); double nvsw = getSize().width / (double) (cw); double nvsh = getSize().height / (double) (ch); np.width = (int) ((m_oldMousePos.width - m_viewPos.width) * -nvsw); np.height = (int) ((m_oldMousePos.height - m_viewPos.height) * -nvsh); ns.width = (int) (m_viewSize.width * nvsw); ns.height = (int) (m_viewSize.height * nvsh); animateScaling(np, ns, 10); } } } else if (m_mouseState == 0 && m_scaling == 0) { // menu m_mouseState = 0; setFont(new Font("A Name", 0, 12)); // determine if the click was on a node or not int s = -1; for (int noa = 0; noa < m_numNodes; noa++) { if (m_nodes[noa].m_quad == 18) { // then is on the screen calcScreenCoords(noa); if (e.getX() <= m_nodes[noa].m_center + m_nodes[noa].m_side && e.getX() >= m_nodes[noa].m_center - m_nodes[noa].m_side && e.getY() >= m_nodes[noa].m_top && e.getY() <= m_nodes[noa].m_top + m_nodes[noa].m_height) { // then it is this node that the mouse was clicked on s = noa; } m_nodes[noa].m_top = 32000; } } if (s == -1) { // the mouse wasn't clicked on a node m_winMenu.show(this, e.getX(), e.getY()); } else { // the mouse was clicked on a node m_focusNode = s; m_nodeMenu.show(this, e.getX(), e.getY()); } setFont(m_currentFont); } else if (m_mouseState == 1) { // dragging m_mouseState = 0; m_frameLimiter.stop(); repaint(); } } /** * Checks to see if the coordinates of the mouse lie on this JPanel. * * @param e the mouse event. * @return true if the mouse lies on this JPanel. */ private boolean mouseInBounds(MouseEvent e) { // this returns true if the mouse is currently over the canvas otherwise // false if (e.getX() < 0 || e.getY() < 0 || e.getX() > getSize().width || e.getY() > getSize().height) { return false; } return true; } /** * Performs intermediate updates to what the user wishes to do. * * @param e the mouse event. */ @Override public void mouseDragged(MouseEvent e) { // use mouse state to determine what to do to the view of the tree if (m_mouseState == 1) { // then dragging view m_oldMousePos.width = m_newMousePos.width; m_oldMousePos.height = m_newMousePos.height; m_newMousePos.width = e.getX(); m_newMousePos.height = e.getY(); m_viewPos.width += m_newMousePos.width - m_oldMousePos.width; m_viewPos.height += m_newMousePos.height - m_oldMousePos.height; } else if (m_mouseState == 3) { // then zoom box being created // redraw the zoom box Graphics g = getGraphics(); if (m_ZoomBoxColor == null) { g.setColor(Color.black); } else { g.setColor(m_ZoomBoxColor); } if (m_ZoomBoxXORColor == null) { g.setXORMode(Color.white); } else { g.setXORMode(m_ZoomBoxXORColor); } g.drawRect(m_oldMousePos.width, m_oldMousePos.height, m_newMousePos.width - m_oldMousePos.width, m_newMousePos.height - m_oldMousePos.height); m_newMousePos.width = e.getX(); m_newMousePos.height = e.getY(); g.drawRect(m_oldMousePos.width, m_oldMousePos.height, m_newMousePos.width - m_oldMousePos.width, m_newMousePos.height - m_oldMousePos.height); g.dispose(); } } /** * Does nothing. * * @param e the mouse event. */ @Override public void mouseMoved(MouseEvent e) { } /** * Does nothing. * * @param e the mouse event. */ @Override public void mouseEntered(MouseEvent e) { } /** * Does nothing. * * @param e the mouse event. */ @Override public void mouseExited(MouseEvent e) { } /** * Set the highlight for the node with the given id * * @param id the id of the node to set the highlight for */ public void setHighlight(String id) { // set the highlight for the node with the given id for (int noa = 0; noa < m_numNodes; noa++) { if (id.equals(m_nodes[noa].m_node.getRefer())) { // then highlight this node m_highlightNode = noa; } } // System.out.println("ahuh " + highlight_node + " " + // nodes[0].node.getRefer()); repaint(); } /** * Updates the screen contents. * * @param g the drawing surface. */ @Override public void paintComponent(Graphics g) { Color oldBackground = ((Graphics2D) g).getBackground(); if (m_BackgroundColor != null) { ((Graphics2D) g).setBackground(m_BackgroundColor); } g.clearRect(0, 0, getSize().width, getSize().height); ((Graphics2D) g).setBackground(oldBackground); g.setClip(3, 7, getWidth() - 6, getHeight() - 10); painter(g); g.setClip(0, 0, getWidth(), getHeight()); } /** * Draws the tree to the graphics context * * @param g the drawing surface. */ private void painter(Graphics g) { // I have moved what would normally be in the paintComponent // function to here // for now so that if I do in fact need to do double // buffering or the like it will be easier // this will go through the table of edges and draw the edge if it deems the // two nodes attached to it could cause it to cut the screen or be on it. // in the process flagging all nodes so that they can quickly be put to the // screen if they lie on it // I do it in this order because in some circumstances I have seen a line // cut through a node , to make things look better the line will // be drawn under the node // converting the screen edges to the node scale so that they // can be positioned relative to the screen // note I give a buffer around the edges of the screen. // when seeing // if a node is on screen I only bother to check the nodes top centre // if it has large enough size it may still fall onto the screen double left_clip = (double) (-m_viewPos.width - 50) / m_viewSize.width; double right_clip = (double) (getSize().width - m_viewPos.width + 50) / m_viewSize.width; double top_clip = (double) (-m_viewPos.height - 50) / m_viewSize.height; double bottom_clip = (double) (getSize().height - m_viewPos.height + 50) / m_viewSize.height; // 12 10 9 //the quadrants // 20 18 17 // 36 34 33 // first the edges must be rendered // Edge e; NOT USED Node r; // ,s; NOT USED double ncent, ntop; int row = 0, col = 0, pq, cq; for (int noa = 0; noa < m_numNodes; noa++) { r = m_nodes[noa].m_node; if (m_nodes[noa].m_change) { // then recalc row component of quadrant ntop = r.getTop(); if (ntop < top_clip) { row = 8; } else if (ntop > bottom_clip) { row = 32; } else { row = 16; } } // calc the column the node falls in for the quadrant ncent = r.getCenter(); if (ncent < left_clip) { col = 4; } else if (ncent > right_clip) { col = 1; } else { col = 2; } m_nodes[noa].m_quad = row | col; if (m_nodes[noa].m_parent >= 0) { // this will draw the edge if it should be drawn // It will do this by eliminating all edges that definitely won't enter // the screen and then draw the rest pq = m_nodes[m_edges[m_nodes[noa].m_parent].m_parent].m_quad; cq = m_nodes[noa].m_quad; // note that this will need to be altered if more than 1 parent exists if ((cq & 8) == 8) { // then child exists above screen } else if ((pq & 32) == 32) { // then parent exists below screen } else if ((cq & 4) == 4 && (pq & 4) == 4) { // then both child and parent exist to the left of the screen } else if ((cq & 1) == 1 && (pq & 1) == 1) { // then both child and parent exist to the right of the screen } else { // then draw the line drawLine(m_nodes[noa].m_parent, g); } } // now draw the nodes } for (int noa = 0; noa < m_numNodes; noa++) { if (m_nodes[noa].m_quad == 18) { // then the node is on the screen , draw it drawNode(noa, g); } } if (m_highlightNode >= 0 && m_highlightNode < m_numNodes) { // then draw outline if (m_nodes[m_highlightNode].m_quad == 18) { Color acol; if (m_NodeColor == null) { acol = m_nodes[m_highlightNode].m_node.getColor(); } else { acol = m_NodeColor; } g.setColor(new Color((acol.getRed() + 125) % 256, (acol.getGreen() + 125) % 256, (acol.getBlue() + 125) % 256)); // g.setXORMode(Color.white); if (m_nodes[m_highlightNode].m_node.getShape() == 1) { g.drawRect(m_nodes[m_highlightNode].m_center - m_nodes[m_highlightNode].m_side, m_nodes[m_highlightNode].m_top, m_nodes[m_highlightNode].m_width, m_nodes[m_highlightNode].m_height); g.drawRect(m_nodes[m_highlightNode].m_center - m_nodes[m_highlightNode].m_side + 1, m_nodes[m_highlightNode].m_top + 1, m_nodes[m_highlightNode].m_width - 2, m_nodes[m_highlightNode].m_height - 2); } else if (m_nodes[m_highlightNode].m_node.getShape() == 2) { g.drawOval(m_nodes[m_highlightNode].m_center - m_nodes[m_highlightNode].m_side, m_nodes[m_highlightNode].m_top, m_nodes[m_highlightNode].m_width, m_nodes[m_highlightNode].m_height); g.drawOval(m_nodes[m_highlightNode].m_center - m_nodes[m_highlightNode].m_side + 1, m_nodes[m_highlightNode].m_top + 1, m_nodes[m_highlightNode].m_width - 2, m_nodes[m_highlightNode].m_height - 2); } } } for (int noa = 0; noa < m_numNodes; noa++) { // this resets the coords so that next time a refresh occurs // they don't accidentally get used // I will use 32000 to signify that they are invalid, even if this // coordinate occurs it doesn't // matter as it is only for the sake of the caching m_nodes[noa].m_top = 32000; } } /** * Determines the attributes of the node and draws it. * * @param n A subscript identifying the node in <i>nodes</i> array * @param g The drawing surface */ private void drawNode(int n, Graphics g) { // this will draw a node and then print text on it if (m_NodeColor == null) { g.setColor(m_nodes[n].m_node.getColor()); } else { g.setColor(m_NodeColor); } g.setPaintMode(); calcScreenCoords(n); int x = m_nodes[n].m_center - m_nodes[n].m_side; int y = m_nodes[n].m_top; if (m_nodes[n].m_node.getShape() == 1) { g.fill3DRect(x, y, m_nodes[n].m_width, m_nodes[n].m_height, true); drawText(x, y, n, false, g); } else if (m_nodes[n].m_node.getShape() == 2) { g.fillOval(x, y, m_nodes[n].m_width, m_nodes[n].m_height); drawText(x, y + (int) (m_nodes[n].m_height * .15), n, false, g); } } /** * Determines the attributes of the edge and draws it. * * @param e A subscript identifying the edge in <i>edges</i> array. * @param g The drawing surface. */ private void drawLine(int e, Graphics g) { // this will draw a line taking in the edge number and then getting // the nodes subscript for the parent and child entries // this will draw a line that has been broken in the middle // for the edge text to be displayed // if applicable // first convert both parent and child node coords to screen coords int p = m_edges[e].m_parent; int c = m_edges[e].m_child; calcScreenCoords(c); calcScreenCoords(p); if (m_LineColor == null) { g.setColor(Color.black); } else { g.setColor(m_LineColor); } g.setPaintMode(); if (m_currentFont.getSize() < 2) { // text to small to bother cutting the edge g.drawLine(m_nodes[p].m_center, m_nodes[p].m_top + m_nodes[p].m_height, m_nodes[c].m_center, m_nodes[c].m_top); } else { // find where to cut the edge to insert text int e_width = m_nodes[c].m_center - m_nodes[p].m_center; int e_height = m_nodes[c].m_top - (m_nodes[p].m_top + m_nodes[p].m_height); int e_width2 = e_width / 2; int e_height2 = e_height / 2; int e_centerx = m_nodes[p].m_center + e_width2; int e_centery = m_nodes[p].m_top + m_nodes[p].m_height + e_height2; int e_offset = m_edges[e].m_tb; int tmp = (int) (((double) e_width / e_height) * (e_height2 - e_offset)) + m_nodes[p].m_center; // System.out.println(edges[e].m_height); // draw text now drawText(e_centerx - m_edges[e].m_side, e_centery - e_offset, e, true, g); if (tmp > (e_centerx - m_edges[e].m_side) && tmp < (e_centerx + m_edges[e].m_side)) { // then cut line on top and bottom of text g.drawLine(m_nodes[p].m_center, m_nodes[p].m_top + m_nodes[p].m_height, tmp, e_centery - e_offset); // first segment g.drawLine(e_centerx * 2 - tmp, e_centery + e_offset, m_nodes[c].m_center, m_nodes[c].m_top); // second segment } else { e_offset = m_edges[e].m_side; if (e_width < 0) { e_offset *= -1; // adjusting for direction which could otherwise // screw up the calculation } tmp = (int) (((double) e_height / e_width) * (e_width2 - e_offset)) + m_nodes[p].m_top + m_nodes[p].m_height; g.drawLine(m_nodes[p].m_center, m_nodes[p].m_top + m_nodes[p].m_height, e_centerx - e_offset, tmp); // first segment g.drawLine(e_centerx + e_offset, e_centery * 2 - tmp, m_nodes[c].m_center, m_nodes[c].m_top); // second segment } } // System.out.println("here" + nodes[p].center); } /** * Draws the text for either an Edge or a Node. * * @param x1 the left side of the text area. * @param y1 the top of the text area. * @param s A subscript identifying either a Node or Edge. * @param e_or_n Distinguishes whether it is a node or edge. * @param g The drawing surface. */ private void drawText(int x1, int y1, int s, boolean e_or_n, Graphics g) { // this function will take in the rectangle that the text should be // drawn in as well as the subscript // for either the edge or node and a boolean variable to tell which // backup color Color oldColor = g.getColor(); g.setPaintMode(); if (m_FontColor == null) { g.setColor(Color.black); } else { g.setColor(m_FontColor); } String st; if (e_or_n) { // then paint for edge Edge e = m_edges[s].m_edge; for (int noa = 0; (st = e.getLine(noa)) != null; noa++) { g.drawString(st, (m_edges[s].m_width - m_fontSize.stringWidth(st)) / 2 + x1, y1 + (noa + 1) * m_fontSize.getHeight()); } } else { // then paint for node Node e = m_nodes[s].m_node; for (int noa = 0; (st = e.getLine(noa)) != null; noa++) { g.drawString(st, (m_nodes[s].m_width - m_fontSize.stringWidth(st)) / 2 + x1, y1 + (noa + 1) * m_fontSize.getHeight()); } } // restore color g.setColor(oldColor); } /** * Converts the internal coordinates of the node found from <i>n</i> and * converts them to the actual screen coordinates. * * @param n A subscript identifying the Node. */ private void calcScreenCoords(int n) { // this converts the coordinate system the Node uses into screen coordinates // System.out.println(n + " " + view_pos.height + " " + // nodes[n].node.getCenter()); if (m_nodes[n].m_top == 32000) { m_nodes[n].m_top = ((int) (m_nodes[n].m_node.getTop() * m_viewSize.height)) + m_viewPos.height; m_nodes[n].m_center = ((int) (m_nodes[n].m_node.getCenter() * m_viewSize.width)) + m_viewPos.width; } } /** * This Calculates the minimum size of the tree which will prevent any text * overlapping and make it readable, and then set the size of the tree to * this. */ private void autoScale() { // this function will determine the smallest scale value that keeps the text // from overlapping // it will leave the view centered int dist; // Node ln,rn; NOT USED Dimension temp = new Dimension(10, 10); if (m_numNodes <= 1) { return; } // calc height needed by first node dist = (m_nodes[0].m_height + 40) * m_numLevels; if (dist > temp.height) { temp.height = dist; } for (int noa = 0; noa < m_numNodes - 1; noa++) { calcScreenCoords(noa); calcScreenCoords(noa + 1); if (m_nodes[noa + 1].m_change) { // then on a new level so don't check width this time round } else { dist = m_nodes[noa + 1].m_center - m_nodes[noa].m_center; // the distance between the node centers, along horiz if (dist <= 0) { dist = 1; } dist = ((6 + m_nodes[noa].m_side + m_nodes[noa + 1].m_side) * m_viewSize.width) / dist; // calc optimal size for width if (dist > temp.width) { temp.width = dist; } } // now calc.. minimun hieght needed by nodes dist = (m_nodes[noa + 1].m_height + 40) * m_numLevels; if (dist > temp.height) { temp.height = dist; } } int y1, y2, xa, xb; y1 = m_nodes[m_edges[0].m_parent].m_top; y2 = m_nodes[m_edges[0].m_child].m_top; dist = y2 - y1; if (dist <= 0) { dist = 1; } dist = ((60 + m_edges[0].m_height + m_nodes[m_edges[0].m_parent].m_height) * m_viewSize.height) / dist; if (dist > temp.height) { temp.height = dist; } for (int noa = 0; noa < m_numNodes - 2; noa++) { // check the edges now if (m_nodes[m_edges[noa + 1].m_child].m_change) { // then edge is on a different level , so skip this one } else { // calc the width requirements of this pair of edges xa = m_nodes[m_edges[noa].m_child].m_center - m_nodes[m_edges[noa].m_parent].m_center; xa /= 2; xa += m_nodes[m_edges[noa].m_parent].m_center; xb = m_nodes[m_edges[noa + 1].m_child].m_center - m_nodes[m_edges[noa + 1].m_parent].m_center; xb /= 2; xb += m_nodes[m_edges[noa + 1].m_parent].m_center; dist = xb - xa; if (dist <= 0) { dist = 1; } dist = ((12 + m_edges[noa].m_side + m_edges[noa + 1].m_side) * m_viewSize.width) / dist; if (dist > temp.width) { temp.width = dist; } } // now calc height need by the edges y1 = m_nodes[m_edges[noa + 1].m_parent].m_top; y2 = m_nodes[m_edges[noa + 1].m_child].m_top; dist = y2 - y1; if (dist <= 0) { dist = 1; } dist = ((60 + m_edges[noa + 1].m_height + m_nodes[m_edges[noa + 1].m_parent].m_height) * m_viewSize.height) / dist; if (dist > temp.height) { temp.height = dist; } } Dimension e = getSize(); Dimension np = new Dimension(); np.width = (int) (e.width / 2 - (((double) e.width / 2) - m_viewPos.width) / (m_viewSize.width) * temp.width); np.height = (int) (e.height / 2 - (((double) e.height / 2) - m_viewPos.height) / (m_viewSize.height) * temp.height); // animate_scaling(c_size,c_pos,25); for (int noa = 0; noa < m_numNodes; noa++) { // this resets the coords so that next time a refresh occurs they don't // accidentally get used // I will use 32000 to signify that they are invalid, even if this // coordinate occurs it doesn't // matter as it is only for the sake of the caching m_nodes[noa].m_top = 32000; } animateScaling(np, temp, 10); } /** * This will increment the size and position of the tree towards the desired * size and position a little (depending on the value of <i>frames</i>) * everytime it is called. * * @param n_pos The final position of the tree wanted. * @param n_size The final size of the tree wanted. * @param frames The number of frames that shall occur before the final size * and pos is reached. */ private void animateScaling(Dimension n_pos, Dimension n_size, int frames) { // this function will take new size and position coords , and incrementally // scale the view to these // since I will be tying it in with the framelimiter I will simply call // this function and increment it once // I will have to use a global variable since I am doing it proportionally if (frames == 0) { System.out.println("the timer didn't end in time"); m_scaling = 0; } else { if (m_scaling == 0) { // new animate session // start timer and set scaling m_frameLimiter.start(); m_nViewPos.width = n_pos.width; m_nViewPos.height = n_pos.height; m_nViewSize.width = n_size.width; m_nViewSize.height = n_size.height; m_scaling = frames; } int s_w = (n_size.width - m_viewSize.width) / frames; int s_h = (n_size.height - m_viewSize.height) / frames; int p_w = (n_pos.width - m_viewPos.width) / frames; int p_h = (n_pos.height - m_viewPos.height) / frames; m_viewSize.width += s_w; m_viewSize.height += s_h; m_viewPos.width += p_w; m_viewPos.height += p_h; repaint(); m_scaling--; if (m_scaling == 0) { // all done m_frameLimiter.stop(); } } } /** * This will change the font size for displaying the tree to the one * specified. * * @param s The new pointsize of the font. */ private void changeFontSize(int s) { // this will set up the new font that shall be used // it will also recalculate the size of the nodes as these will change as // a result of // the new font size setFont(m_currentFont = new Font("A Name", 0, s)); m_fontSize = getFontMetrics(getFont()); Dimension d; for (int noa = 0; noa < m_numNodes; noa++) { // this will set the size info for each node and edge d = m_nodes[noa].m_node.stringSize(m_fontSize); if (m_nodes[noa].m_node.getShape() == 1) { m_nodes[noa].m_height = d.height + 10; m_nodes[noa].m_width = d.width + 8; m_nodes[noa].m_side = m_nodes[noa].m_width / 2; } else if (m_nodes[noa].m_node.getShape() == 2) { m_nodes[noa].m_height = (int) ((d.height + 2) * 1.6); m_nodes[noa].m_width = (int) ((d.width + 2) * 1.6); m_nodes[noa].m_side = m_nodes[noa].m_width / 2; } if (noa < m_numNodes - 1) { // this will do the same for edges d = m_edges[noa].m_edge.stringSize(m_fontSize); m_edges[noa].m_height = d.height + 8; m_edges[noa].m_width = d.width + 8; m_edges[noa].m_side = m_edges[noa].m_width / 2; m_edges[noa].m_tb = m_edges[noa].m_height / 2; } } } /** * This will fill two arrays with the Nodes and Edges from the tree into a * particular order. * * @param t The top Node of the tree. * @param l An array that has already been allocated, to be filled. * @param k An array that has already been allocated, to be filled. */ private void arrayFill(Node t, NodeInfo[] l, EdgeInfo[] k) { // this will take the top node and the array to fill // it will go through the tree structure and and fill the array with the // nodes // from top to bottom left to right // note I do not believe this function will be able to deal with multiple // parents if (t == null || l == null) { System.exit(1); // this is just a preliminary safety check // (i shouldn' need it) } Edge e; Node r, s; l[0] = new NodeInfo(); l[0].m_node = t; l[0].m_parent = -1; l[0].m_change = true; int floater; // this will point at a node that has previously been // put in the list // all of the children that this node has shall be put in the list , // once this is done the floater shall point at the next node in the list // this will allow the nodes to be put into order from closest to top node // to furtherest from top node int free_space = 1; // the next empty array position double height = t.getTop(); // this will be used to determine if the node // has a // new height compared to the // previous one for (floater = 0; floater < free_space; floater++) { r = l[floater].m_node; for (int noa = 0; (e = r.getChild(noa)) != null; noa++) { // this loop pulls out each child of r // e points to a child edge, getTarget will return that edges child node s = e.getTarget(); l[free_space] = new NodeInfo(); l[free_space].m_node = s; l[free_space].m_parent = free_space - 1; k[free_space - 1] = new EdgeInfo(); k[free_space - 1].m_edge = e; k[free_space - 1].m_parent = floater; k[free_space - 1].m_child = free_space; // note although it's child // will always have a subscript // of 1 more , I may not nessecarily have access to that // and it will need the subscr.. for multiple parents // determine if level of node has changed from previous one if (height != s.getTop()) { l[free_space].m_change = true; height = s.getTop(); } else { l[free_space].m_change = false; } free_space++; } } } /** * Internal Class for containing display information about a Node. */ private class NodeInfo { // this class contains a pointer to the node itself along with extra // information // about the node used by the Displayer class /** The y pos of the node on screen. */ int m_top = 32000; // the main node coords calculated out /** The x pos of the node on screen. */ int m_center; // these coords will probably change each refresh // and are the positioning coords // which the rest of the offsets use /** The offset to get to the left or right of the node. */ int m_side; // these are the screen offset for the dimensions of // the node relative to the nodes // internal top and center values (after they have been converted to // screen coords /** The width of the node. */ int m_width; /** The height of the node. */ int m_height; /** * True if the node is at the start (left) of a new level (not sibling * group). */ boolean m_change; // this is quickly used to identify whether the node // has chenged height from the // previous one to help speed up the calculation of what row it lies in /** The subscript number of the Nodes parent. */ int m_parent; // this is the index of the nodes parent edge in an array /** The rough position of the node relative to the screen. */ int m_quad; // what of nine quadrants is it in /* * 12 10 9 20 18 17 //18 being the screen 36 34 33 //this arrangement uses 6 * bits, each bit represents a row or column */ /** The Node itself. */ Node m_node; } /** * Internal Class for containing display information about an Edge. */ private class EdgeInfo { // this class contains a pointer to the edge along with all the other // extra info about the edge /** The parent subscript (for a Node). */ int m_parent; // array indexs for its two connections /** The child subscript (for a Node). */ int m_child; /** The distance from the center of the text to either side. */ int m_side; // these are used to describe the dimensions of the // text /** The distance from the center of the text to top or bottom. */ int m_tb; // tb stands for top , bottom, this is simply the // distance from the middle to top bottom /** The width of the text. */ int m_width; /** The height of the text. */ int m_height; /** The Edge itself. */ Edge m_edge; } /** * Main method for testing this class. * * @param args first argument should be the name of a file that contains a * tree discription in dot format. */ public static void main(String[] args) { try { weka.core.logging.Logger.log(weka.core.logging.Logger.Level.INFO, "Logging started"); // put in the random data generator right here // this call with import java.lang gives me between 0 and 1 Math.random TreeBuild builder = new TreeBuild(); Node top = null; NodePlace arrange = new PlaceNode2(); // top = builder.create(new // StringReader("digraph atree { top [label=\"the top\"] a [label=\"the first node\"] b [label=\"the second nodes\"] c [label=\"comes off of first\"] top->a top->b b->c }")); top = builder.create(new FileReader(args[0])); // int num = Node.getCount(top,0); NOT USED // System.out.println("counter counted " + num + " nodes"); // System.out.println("there are " + num + " nodes"); TreeVisualizer a = new TreeVisualizer(null, top, arrange); a.setSize(800, 600); // a.setTree(top); JFrame f; f = new JFrame(); // a.addMouseMotionListener(a); // a.addMouseListener(a); // f.add(a); Container contentPane = f.getContentPane(); contentPane.add(a); f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); f.setSize(800, 600); f.setVisible(true); // f. // find_prop(top); // a.setTree(top,arrange);//,(num + 1000), num / 2 + 1000); } catch (IOException e) { // ignored } } }
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/visualize/AttributePanel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * AttributePanel.java * Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.visualize; import weka.core.Attribute; import weka.core.Environment; import weka.core.Instances; import weka.core.Settings; import javax.swing.JPanel; import javax.swing.JScrollPane; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.InputEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; /** * This panel displays one dimensional views of the attributes in a dataset. * Colouring is done on the basis of a column in the dataset or an auxiliary * array (useful for colouring cluster predictions). * * @author Malcolm Ware (mfw4@cs.waikato.ac.nz) * @author Mark Hall (mhall@cs.waikato.ac.nz) * @version $Revision$ */ public class AttributePanel extends JScrollPane { /** for serialization */ private static final long serialVersionUID = 3533330317806757814L; /** The instances to be plotted */ protected Instances m_plotInstances = null; /** Holds the min and max values of the colouring attributes */ protected double m_maxC; protected double m_minC; protected int m_cIndex; protected int m_xIndex; protected int m_yIndex; /** The colour map to use for colouring points */ protected ArrayList<Color> m_colorList; /** default colours for colouring discrete class */ protected Color[] m_DefaultColors = { Color.blue, Color.red, Color.green, Color.cyan, Color.pink, new Color(255, 0, 255), Color.orange, new Color(255, 0, 0), new Color(0, 255, 0), Color.white }; /** * If set, it allows this panel to avoid setting a color in the color list * that is equal to the background color */ protected Color m_backgroundColor = null; /** The list of things listening to this panel */ protected ArrayList<AttributePanelListener> m_Listeners = new ArrayList<AttributePanelListener>(); /** Holds the random height for each instance. */ protected int[] m_heights; // protected Color[] colors_array; /** * The container window for the attribute bars, and also where the X,Y or B * get printed. */ protected JPanel m_span = null; /** * The default colour to use for the background of the bars if a colour is not * defined in Visualize.props */ protected Color m_barColour = Color.black; /** * inner inner class used for plotting the points into a bar for a particular * attribute. */ protected class AttributeSpacing extends JPanel { /** for serialization */ private static final long serialVersionUID = 7220615894321679898L; /** The min and max values for this attribute. */ protected double m_maxVal; protected double m_minVal; /** The attribute itself. */ protected Attribute m_attrib; /** The index for this attribute. */ protected int m_attribIndex; /** The x position of each point. */ protected int[] m_cached; // note for m_cached, if you wanted to speed up the drawing algorithm // and save memory, the system could be setup to drop out any // of the instances not being drawn (you would need to find a new way // of matching the height however). /** * A temporary array used to strike any instances that would be drawn * redundantly. */ protected boolean[][] m_pointDrawn; /** Used to determine if the positions need to be recalculated. */ protected int m_oldWidth = -9000; /** * The container window for the attribute bars, and also where the X,Y or B * get printed. */ /** * This constructs the bar with the specified attribute and sets its index * to be used for selecting by the mouse. * * @param a The attribute this bar represents. * @param aind The index of this bar. */ public AttributeSpacing(Attribute a, int aind) { m_attrib = a; m_attribIndex = aind; this.setBackground(m_barColour); this.setPreferredSize(new Dimension(0, 20)); this.setMinimumSize(new Dimension(0, 20)); m_cached = new int[m_plotInstances.numInstances()]; // this will only get allocated if m_plotInstances != null // this is used to determine the min and max values for plotting double min = Double.POSITIVE_INFINITY; double max = Double.NEGATIVE_INFINITY; double value; if (m_plotInstances.attribute(m_attribIndex).isNominal()) { m_minVal = 0; m_maxVal = m_plotInstances.attribute(m_attribIndex).numValues() - 1; } else { for (int i = 0; i < m_plotInstances.numInstances(); i++) { if (!m_plotInstances.instance(i).isMissing(m_attribIndex)) { value = m_plotInstances.instance(i).value(m_attribIndex); if (value < min) { min = value; } if (value > max) { max = value; } } } m_minVal = min; m_maxVal = max; if (min == max) { m_maxVal += 0.05; m_minVal -= 0.05; } } this.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if ((e.getModifiers() & InputEvent.BUTTON1_MASK) == InputEvent.BUTTON1_MASK) { setX(m_attribIndex); if (m_Listeners.size() > 0) { for (int i = 0; i < m_Listeners.size(); i++) { AttributePanelListener l = (m_Listeners.get(i)); l.attributeSelectionChange(new AttributePanelEvent(true, false, m_attribIndex)); } } } else { // put it on the y axis setY(m_attribIndex); if (m_Listeners.size() > 0) { for (int i = 0; i < m_Listeners.size(); i++) { AttributePanelListener l = (m_Listeners.get(i)); l.attributeSelectionChange(new AttributePanelEvent(false, true, m_attribIndex)); } } } } }); } /** * Convert an raw x value to Panel x coordinate. * * @param val the raw x value * @return an x value for plotting in the panel. */ private double convertToPanel(double val) { double temp = (val - m_minVal) / (m_maxVal - m_minVal); double temp2 = temp * (this.getWidth() - 10); return temp2 + 4; } /** * paints all the visible instances to the panel , and recalculates their * position if need be. * * @param gx The graphics context. */ @Override public void paintComponent(Graphics gx) { setBackground(m_barColour); super.paintComponent(gx); int xp, yp, h; h = this.getWidth(); if (m_plotInstances != null && m_plotInstances.numAttributes() > 0 && m_plotInstances.numInstances() > 0) { if (m_oldWidth != h) { m_pointDrawn = new boolean[h][20]; for (int noa = 0; noa < m_plotInstances.numInstances(); noa++) { if (!m_plotInstances.instance(noa).isMissing(m_attribIndex) && !m_plotInstances.instance(noa).isMissing(m_cIndex)) { m_cached[noa] = (int) convertToPanel(m_plotInstances.instance(noa).value( m_attribIndex)); if (m_pointDrawn[m_cached[noa] % h][m_heights[noa]]) { m_cached[noa] = -9000; } else { m_pointDrawn[m_cached[noa] % h][m_heights[noa]] = true; } } else { m_cached[noa] = -9000; // this value will not happen // so it is safe } } m_oldWidth = h; } if (m_plotInstances.attribute(m_cIndex).isNominal()) { for (int noa = 0; noa < m_plotInstances.numInstances(); noa++) { if (m_cached[noa] != -9000) { xp = m_cached[noa]; yp = m_heights[noa]; if (m_plotInstances.attribute(m_attribIndex).isNominal()) { xp += (int) (Math.random() * 5) - 2; } int ci = (int) m_plotInstances.instance(noa).value(m_cIndex); gx.setColor(m_colorList.get(ci % m_colorList.size())); gx.drawRect(xp, yp, 1, 1); } } } else { double r; for (int noa = 0; noa < m_plotInstances.numInstances(); noa++) { if (m_cached[noa] != -9000) { r = (m_plotInstances.instance(noa).value(m_cIndex) - m_minC) / (m_maxC - m_minC); r = (r * 240) + 15; gx.setColor(new Color((int) r, 150, (int) (255 - r))); xp = m_cached[noa]; yp = m_heights[noa]; if (m_plotInstances.attribute(m_attribIndex).isNominal()) { xp += (int) (Math.random() * 5) - 2; } gx.drawRect(xp, yp, 1, 1); } } } } } } /** * Set the properties for the AttributePanel */ private void setProperties() { if (VisualizeUtils.VISUALIZE_PROPERTIES != null) { String thisClass = this.getClass().getName(); String barKey = thisClass + ".barColour"; String barC = VisualizeUtils.VISUALIZE_PROPERTIES.getProperty(barKey); if (barC == null) { /* * System.err.println("Warning: no configuration property found in " * +VisualizeUtils.PROPERTY_FILE +" for "+barKey); */ } else { // System.err.println("Setting attribute bar colour to: "+barC); m_barColour = VisualizeUtils.processColour(barC, m_barColour); } } } /** * Apply settings * * @param settings the settings to apply * @param ownerID the ID of owner perspective, panel. Used when looking up our * settings */ public void applySettings(Settings settings, String ownerID) { m_barColour = settings.getSetting(ownerID, VisualizeUtils.VisualizeDefaults.BAR_BACKGROUND_COLOUR_KEY, VisualizeUtils.VisualizeDefaults.BAR_BACKGROUND_COLOUR, Environment.getSystemWide()); repaint(); } public AttributePanel() { this(null); } /** * This constructs an attributePanel. */ public AttributePanel(Color background) { m_backgroundColor = background; setProperties(); this.setBackground(Color.blue); setVerticalScrollBarPolicy(VERTICAL_SCROLLBAR_ALWAYS); m_colorList = new ArrayList<Color>(10); for (int noa = m_colorList.size(); noa < 10; noa++) { Color pc = m_DefaultColors[noa % 10]; int ija = noa / 10; ija *= 2; for (int j = 0; j < ija; j++) { pc = pc.darker(); } m_colorList.add(pc); } } /** * Add a listener to the list of things listening to this panel * * @param a the listener to notify when attribute bars are clicked on */ public void addAttributePanelListener(AttributePanelListener a) { m_Listeners.add(a); } /** * Set the index of the attribute by which to colour the data. Updates the * number of entries in the colour list if there are more values for this new * attribute than previous ones. * * @param c the index of the attribute to colour on * @param h maximum value of this attribute * @param l minimum value of this attribute */ public void setCindex(int c, double h, double l) { m_cIndex = c; m_maxC = h; m_minC = l; if (m_span != null) { if (m_plotInstances.numAttributes() > 0 && m_cIndex < m_plotInstances.numAttributes()) { if (m_plotInstances.attribute(m_cIndex).isNominal()) { if (m_plotInstances.attribute(m_cIndex).numValues() > m_colorList .size()) { extendColourMap(); } } } this.repaint(); } } /** * Set the index of the attribute by which to colour the data. Updates the * number of entries in the colour list if there are more values for this new * attribute than previous ones. * * @param c the index of the attribute to colour on */ public void setCindex(int c) { m_cIndex = c; /* * m_maxC = h; m_minC = l; */ if (m_span != null) { if (m_cIndex < m_plotInstances.numAttributes() && m_plotInstances.attribute(m_cIndex).isNumeric()) { double min = Double.POSITIVE_INFINITY; double max = Double.NEGATIVE_INFINITY; double value; for (int i = 0; i < m_plotInstances.numInstances(); i++) { if (!m_plotInstances.instance(i).isMissing(m_cIndex)) { value = m_plotInstances.instance(i).value(m_cIndex); if (value < min) { min = value; } if (value > max) { max = value; } } } m_minC = min; m_maxC = max; } else { if (m_plotInstances.attribute(m_cIndex).numValues() > m_colorList .size()) { extendColourMap(); } } this.repaint(); } } /** * Adds more colours to the colour list */ private void extendColourMap() { if (m_plotInstances.attribute(m_cIndex).isNominal()) { for (int i = m_colorList.size(); i < m_plotInstances.attribute(m_cIndex) .numValues(); i++) { Color pc = m_DefaultColors[i % 10]; int ija = i / 10; ija *= 2; for (int j = 0; j < ija; j++) { pc = pc.brighter(); } if (m_backgroundColor != null) { pc = Plot2D.checkAgainstBackground(pc, m_backgroundColor); } m_colorList.add(pc); } } } /** * Sets a list of colours to use for colouring data points * * @param cols a list of java.awt.Color */ public void setColours(ArrayList<Color> cols) { m_colorList = cols; } protected void setDefaultColourList(Color[] list) { m_DefaultColors = list; } /** * This sets the instances to be drawn into the attribute panel * * @param ins The instances. */ public void setInstances(Instances ins) throws Exception { if (ins.numAttributes() > 512) { throw new Exception("Can't display more than 512 attributes!"); } if (m_span == null) { m_span = new JPanel() { private static final long serialVersionUID = 7107576557995451922L; @Override public void paintComponent(Graphics gx) { super.paintComponent(gx); gx.setColor(Color.red); if (m_yIndex != m_xIndex) { gx.drawString("X", 5, m_xIndex * 20 + 16); gx.drawString("Y", 5, m_yIndex * 20 + 16); } else { gx.drawString("B", 5, m_xIndex * 20 + 16); } } }; } m_span.removeAll(); m_plotInstances = ins; if (ins.numInstances() > 0 && ins.numAttributes() > 0) { JPanel padder = new JPanel(); JPanel padd2 = new JPanel(); /* * if (m_splitListener != null) { m_plotInstances.randomize(new Random()); * } */ m_heights = new int[ins.numInstances()]; m_cIndex = ins.numAttributes() - 1; for (int noa = 0; noa < ins.numInstances(); noa++) { m_heights[noa] = (int) (Math.random() * 19); } m_span.setPreferredSize(new Dimension(m_span.getPreferredSize().width, (m_cIndex + 1) * 20)); m_span.setMaximumSize(new Dimension(m_span.getMaximumSize().width, (m_cIndex + 1) * 20)); AttributeSpacing tmp; GridBagLayout gb = new GridBagLayout(); GridBagLayout gb2 = new GridBagLayout(); GridBagConstraints constraints = new GridBagConstraints(); padder.setLayout(gb); m_span.setLayout(gb2); constraints.anchor = GridBagConstraints.CENTER; constraints.gridx = 0; constraints.gridy = 0; constraints.weightx = 5; constraints.fill = GridBagConstraints.HORIZONTAL; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.insets = new Insets(0, 0, 0, 0); padder.add(m_span, constraints); constraints.gridx = 0; constraints.gridy = 1; constraints.weightx = 5; constraints.fill = GridBagConstraints.BOTH; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.weighty = 5; constraints.insets = new Insets(0, 0, 0, 0); padder.add(padd2, constraints); constraints.weighty = 0; setViewportView(padder); // getViewport().setLayout(null); // m_span.setMinimumSize(new Dimension(100, (m_cIndex + 1) * 24)); // m_span.setSize(100, (m_cIndex + 1) * 24); constraints.anchor = GridBagConstraints.CENTER; constraints.gridx = 0; constraints.gridy = 0; constraints.weightx = 5; constraints.fill = GridBagConstraints.HORIZONTAL; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.weighty = 5; constraints.insets = new Insets(2, 20, 2, 4); for (int noa = 0; noa < ins.numAttributes(); noa++) { tmp = new AttributeSpacing(ins.attribute(noa), noa); constraints.gridy = noa; m_span.add(tmp, constraints); } } } /** * shows which bar is the current x attribute. * * @param x The attributes index. */ public void setX(int x) { if (m_span != null) { m_xIndex = x; m_span.repaint(); } } /** * shows which bar is the current y attribute. * * @param y The attributes index. */ public void setY(int y) { if (m_span != null) { m_yIndex = y; m_span.repaint(); } } /** * Main method for testing this class. * * @param args first argument should be an arff file. Second argument can be * an optional class col */ public static void main(String[] args) { try { if (args.length < 1) { System.err.println("Usage : weka.gui.visualize.AttributePanel " + "<dataset> [class col]"); System.exit(1); } final javax.swing.JFrame jf = new javax.swing.JFrame("Weka Explorer: Attribute"); jf.setSize(100, 100); jf.getContentPane().setLayout(new BorderLayout()); final AttributePanel p2 = new AttributePanel(); p2.addAttributePanelListener(new AttributePanelListener() { @Override public void attributeSelectionChange(AttributePanelEvent e) { if (e.m_xChange) { System.err.println("X index changed to : " + e.m_indexVal); } else { System.err.println("Y index changed to : " + e.m_indexVal); } } }); jf.getContentPane().add(p2, BorderLayout.CENTER); jf.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { jf.dispose(); System.exit(0); } }); 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); i.setClassIndex(i.numAttributes() - 1); p2.setInstances(i); } if (args.length > 1) { p2.setCindex((Integer.parseInt(args[1])) - 1); } else { p2.setCindex(0); } 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/visualize/AttributePanelEvent.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * AttributePanelEvent.java * Copyright (C) 2000-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.visualize; /** * Class encapsulating a change in the AttributePanel's selected x and y * attributes. * * @author Mark Hall (mhall@cs.waikato.ac.nz) * @version $Revision$ */ public class AttributePanelEvent { /** True if the x selection changed */ public boolean m_xChange; /** True if the y selection changed */ public boolean m_yChange; /** The index for the new attribute */ public int m_indexVal; /** * Constructor * @param xChange true if a change occured to the x selection * @param yChange true if a change occured to the y selection * @param indexVal the index of the new attribute */ public AttributePanelEvent(boolean xChange, boolean yChange, int indexVal) { m_xChange = xChange; m_yChange = yChange; m_indexVal = indexVal; } }
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/visualize/AttributePanelListener.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * AttributePanelListener.java * Copyright (C) 2000-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.visualize; /** * Interface for classes that want to listen for Attribute selection * changes in the attribute panel * * @author Mark Hall (mhall@cs.waikato.ac.nz) * @version $Revision$ */ public interface AttributePanelListener { /** * Called when the user clicks on an attribute bar * @param e the event encapsulating what happened */ void attributeSelectionChange(AttributePanelEvent 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/visualize/BMPWriter.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * BMPWriter.java * Copyright (C) 2007-2012 University of Waikato, Hamilton, New Zealand */ package weka.gui.visualize; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import javax.imageio.ImageIO; import javax.swing.JComponent; /** * This class takes any JComponent and outputs it to a BMP-file. * Scaling is by default disabled, since we always take a screenshot. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class BMPWriter extends JComponentWriter { /** the background color. */ protected Color m_Background; /** * initializes the object. */ public BMPWriter() { super(); } /** * initializes the object with the given Component. * * @param c the component to print in the output format */ public BMPWriter(JComponent c) { super(c); } /** * initializes the object with the given Component and filename. * * @param c the component to print in the output format * @param f the file to store the output in */ public BMPWriter(JComponent c, File f) { super(c, f); } /** * further initialization. */ public void initialize() { super.initialize(); setScalingEnabled(false); } /** * returns the name of the writer, to display in the FileChooser. * must be overridden in the derived class. * * @return the name of the writer */ public String getDescription() { return "BMP-Image"; } /** * returns the extension (incl. ".") of the output format, to use in the * FileChooser. * * @return the file extension */ public String getExtension() { return ".bmp"; } /** * returns the current background color. * * @return the current background color */ public Color getBackground() { return m_Background; } /** * sets the background color to use in creating the BMP. * * @param c the color to use for background */ public void setBackground(Color c) { m_Background = c; } /** * generates the actual output. * * @throws Exception if something goes wrong */ public void generateOutput() throws Exception { BufferedImage bi; Graphics g; bi = new BufferedImage(getComponent().getWidth(), getComponent().getHeight(), BufferedImage.TYPE_INT_RGB); g = bi.getGraphics(); g.setPaintMode(); g.setColor(getBackground()); if (g instanceof Graphics2D) ((Graphics2D) g).scale(getXScale(), getYScale()); g.fillRect(0, 0, getComponent().getWidth(), getComponent().getHeight()); getComponent().printAll(g); ImageIO.write(bi, "bmp", getFile()); } /** * for testing only. * * @param args the commandline arguments * @throws Exception if something goes wrong */ public static void main(String[] args) throws Exception { System.out.println("building TreeVisualizer..."); weka.gui.treevisualizer.TreeBuild builder = new weka.gui.treevisualizer.TreeBuild(); weka.gui.treevisualizer.NodePlace arrange = new weka.gui.treevisualizer.PlaceNode2(); weka.gui.treevisualizer.Node top = builder.create(new java.io.StringReader("digraph atree { top [label=\"the top\"] a [label=\"the first node\"] b [label=\"the second nodes\"] c [label=\"comes off of first\"] top->a top->b b->c }")); weka.gui.treevisualizer.TreeVisualizer tv = new weka.gui.treevisualizer.TreeVisualizer(null, top, arrange); tv.setSize(800 ,600); String filename = System.getProperty("java.io.tmpdir") + File.separator + "test.bmp"; System.out.println("outputting to '" + filename + "'..."); toOutput(new BMPWriter(), tv, new File(filename)); System.out.println("done!"); } }
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/visualize/ClassPanel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ClassPanel.java * Copyright (C) 2000-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.visualize; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; 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.util.ArrayList; import javax.swing.JColorChooser; import javax.swing.JLabel; import javax.swing.JPanel; import weka.core.Instances; import weka.core.Utils; /** * This panel displays coloured labels for nominal attributes and a spectrum for * numeric attributes. It can also be told to colour on the basis of an array of * doubles (this can be useful for displaying coloured labels that correspond to * a clusterers predictions). * * @author Mark Hall (mhall@cs.waikato.ac.nz) * @author Malcolm Ware (mfw4@cs.waikato.ac.nz) * @version $Revision$ */ public class ClassPanel extends JPanel { /** for serialization */ private static final long serialVersionUID = -7969401840501661430L; /** * True when the panel has been enabled (ie after setNumeric or setNominal has * been called */ private boolean m_isEnabled = false; /** True if the colouring attribute is numeric */ private boolean m_isNumeric = false; /** The height of the spectrum for numeric class */ private final int m_spectrumHeight = 5; /** The maximum value for the colouring attribute */ private double m_maxC; /** The minimum value for the colouring attribute */ private double m_minC; /** The size of the ticks */ private final int m_tickSize = 5; /** Font metrics */ private FontMetrics m_labelMetrics = null; /** The font used in labeling */ private Font m_labelFont = null; /** The amount of space to leave either side of the legend */ private int m_HorizontalPad = 0; /** The precision with which to display real values */ private int m_precisionC; /** Field width for numeric values */ // private int m_fieldWidthC; NOT USED /** The old width. */ private int m_oldWidth = -9000; /** Instances being plotted */ private Instances m_Instances = null; /** Index of the colouring attribute */ private int m_cIndex; /** the list of colours to use for colouring nominal attribute labels */ private ArrayList<Color> m_colorList; /** * An optional list of Components that use the colour list maintained by this * class. If the user changes a colour using the colour chooser, then these * components need to be repainted in order to display the change */ private final ArrayList<Component> m_Repainters = new ArrayList<Component>(); /** * An optional list of listeners who want to know when a colour changes. * Listeners are notified via an ActionEvent */ private final ArrayList<ActionListener> m_ColourChangeListeners = new ArrayList<ActionListener>(); /** default colours for colouring discrete class */ protected Color[] m_DefaultColors = { Color.blue, Color.red, Color.green, Color.cyan, Color.pink, new Color(255, 0, 255), Color.orange, new Color(255, 0, 0), new Color(0, 255, 0), Color.white }; /** * if set, it allows this panel to steer away from setting up a color in the * color list that is equal to the background color */ protected Color m_backgroundColor = null; /** * Inner Inner class used to create labels for nominal attributes so that * there color can be changed. */ private class NomLabel extends JLabel { /** for serialization */ private static final long serialVersionUID = -4686613106474820655L; private int m_index = 0; /** * Creates a label with its name and class index value. * * @param name The name of the nominal class value. * @param id The index value for that class value. */ public NomLabel(String name, int id) { super(name); m_index = id; this.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if ((e.getModifiers() & InputEvent.BUTTON1_MASK) == InputEvent.BUTTON1_MASK) { Color tmp = JColorChooser.showDialog(ClassPanel.this, "Select new Color", m_colorList.get(m_index)); if (tmp != null) { m_colorList.set(m_index, tmp); m_oldWidth = -9000; ClassPanel.this.repaint(); if (m_Repainters.size() > 0) { for (int i = 0; i < m_Repainters.size(); i++) { (m_Repainters.get(i)).repaint(); } } if (m_ColourChangeListeners.size() > 0) { for (int i = 0; i < m_ColourChangeListeners.size(); i++) { (m_ColourChangeListeners.get(i)) .actionPerformed(new ActionEvent(this, 0, "")); } } } } } }); } } public ClassPanel() { this(null); } public ClassPanel(Color background) { m_backgroundColor = background; /** Set up some default colours */ m_colorList = new ArrayList<Color>(10); for (int noa = m_colorList.size(); noa < 10; noa++) { Color pc = m_DefaultColors[noa % 10]; int ija = noa / 10; ija *= 2; for (int j = 0; j < ija; j++) { pc = pc.darker(); } m_colorList.add(pc); } } /** * Adds a component that will need to be repainted if the user changes the * colour of a label. * * @param c the component to be repainted */ public void addRepaintNotify(Component c) { m_Repainters.add(c); } /** * Add an action listener that will be notified if the user changes the colour * of a label * * @param a an <code>ActionListener</code> value */ public void addActionListener(ActionListener a) { m_ColourChangeListeners.add(a); } /** * Set up fonts and font metrics * * @param gx the graphics context */ private void setFonts(Graphics gx) { if (m_labelMetrics == null) { m_labelFont = new Font("Monospaced", Font.PLAIN, 12); m_labelMetrics = gx.getFontMetrics(m_labelFont); int hf = m_labelMetrics.getAscent(); if (this.getHeight() < (3 * hf)) { m_labelFont = new Font("Monospaced", Font.PLAIN, 11); m_labelMetrics = gx.getFontMetrics(m_labelFont); } } gx.setFont(m_labelFont); } /** * Enables the panel * * @param e true to enable the panel */ public void setOn(boolean e) { m_isEnabled = e; } /** * Set the instances. * * @param insts the instances */ public void setInstances(Instances insts) { m_Instances = insts; } /** * Set the index of the attribute to display coloured labels for * * @param cIndex the index of the attribute to display coloured labels for */ public void setCindex(int cIndex) { if (m_Instances.numAttributes() > 0) { m_cIndex = cIndex; if (m_Instances.attribute(m_cIndex).isNumeric()) { setNumeric(); } else { if (m_Instances.attribute(m_cIndex).numValues() > m_colorList.size()) { extendColourMap(); } setNominal(); } } } /** * Extends the list of colours if a new attribute with more values than the * previous one is chosen */ private void extendColourMap() { if (m_Instances.attribute(m_cIndex).isNominal()) { for (int i = m_colorList.size(); i < m_Instances.attribute(m_cIndex) .numValues(); i++) { Color pc = m_DefaultColors[i % 10]; int ija = i / 10; ija *= 2; for (int j = 0; j < ija; j++) { pc = pc.brighter(); } if (m_backgroundColor != null) { pc = Plot2D.checkAgainstBackground(pc, m_backgroundColor); } m_colorList.add(pc); } } } protected void setDefaultColourList(Color[] list) { m_DefaultColors = list; } /** * Set a list of colours to use for colouring labels * * @param cols a list containing java.awt.Colors */ public void setColours(ArrayList<Color> cols) { m_colorList = cols; } /** * Sets the legend to be for a nominal variable */ protected void setNominal() { m_isNumeric = false; m_HorizontalPad = 0; setOn(true); m_oldWidth = -9000; this.repaint(); } /** * Sets the legend to be for a numeric variable */ protected void setNumeric() { m_isNumeric = true; /* * m_maxC = mxC; m_minC = mnC; */ double min = Double.POSITIVE_INFINITY; double max = Double.NEGATIVE_INFINITY; double value; for (int i = 0; i < m_Instances.numInstances(); i++) { if (!m_Instances.instance(i).isMissing(m_cIndex)) { value = m_Instances.instance(i).value(m_cIndex); if (value < min) { min = value; } if (value > max) { max = value; } } } // handle case where all values are missing if (min == Double.POSITIVE_INFINITY) { min = max = 0.0; } m_minC = min; m_maxC = max; int whole = (int) Math.abs(m_maxC); double decimal = Math.abs(m_maxC) - whole; int nondecimal; nondecimal = (whole > 0) ? (int) (Math.log(whole) / Math.log(10)) : 1; m_precisionC = (decimal > 0) ? (int) Math .abs(((Math.log(Math.abs(m_maxC)) / Math.log(10)))) + 2 : 1; if (m_precisionC > VisualizeUtils.MAX_PRECISION) { m_precisionC = 1; } String maxStringC = Utils.doubleToString(m_maxC, nondecimal + 1 + m_precisionC, m_precisionC); if (m_labelMetrics != null) { m_HorizontalPad = m_labelMetrics.stringWidth(maxStringC); } whole = (int) Math.abs(m_minC); decimal = Math.abs(m_minC) - whole; nondecimal = (whole > 0) ? (int) (Math.log(whole) / Math.log(10)) : 1; m_precisionC = (decimal > 0) ? (int) Math .abs(((Math.log(Math.abs(m_minC)) / Math.log(10)))) + 2 : 1; if (m_precisionC > VisualizeUtils.MAX_PRECISION) { m_precisionC = 1; } maxStringC = Utils.doubleToString(m_minC, nondecimal + 1 + m_precisionC, m_precisionC); if (m_labelMetrics != null) { if (m_labelMetrics.stringWidth(maxStringC) > m_HorizontalPad) { m_HorizontalPad = m_labelMetrics.stringWidth(maxStringC); } } setOn(true); this.repaint(); } /** * Renders the legend for a nominal colouring attribute * * @param gx the graphics context */ protected void paintNominal(Graphics gx) { setFonts(gx); int numClasses; numClasses = m_Instances.attribute(m_cIndex).numValues(); int maxLabelLen = 0; int idx = 0; int legendHeight; int w = this.getWidth(); int hf = m_labelMetrics.getAscent(); for (int i = 0; i < numClasses; i++) { if (m_Instances.attribute(m_cIndex).value(i).length() > maxLabelLen) { maxLabelLen = m_Instances.attribute(m_cIndex).value(i).length(); idx = i; } } maxLabelLen = m_labelMetrics.stringWidth(m_Instances.attribute(m_cIndex) .value(idx)); if (((w - (2 * m_HorizontalPad)) / (maxLabelLen + 5)) >= numClasses) { legendHeight = 1; } else { legendHeight = 2; } int x = m_HorizontalPad; int y = 1 + hf; int numToDo = ((legendHeight == 1) ? numClasses : (numClasses / 2)); for (int i = 0; i < numToDo; i++) { gx.setColor(m_colorList.get(i)); // can we fit the full label or will each need to be trimmed? if ((numToDo * maxLabelLen) > (w - (m_HorizontalPad * 2))) { String val; val = m_Instances.attribute(m_cIndex).value(i); int sw = m_labelMetrics.stringWidth(val); int rm = 0; // truncate string if necessary if (sw > ((w - (m_HorizontalPad * 2)) / (numToDo))) { int incr = (sw / val.length()); rm = (sw - ((w - (m_HorizontalPad * 2)) / numToDo)) / incr; if (rm <= 0) { rm = 0; } if (rm >= val.length()) { rm = val.length() - 1; } val = val.substring(0, val.length() - rm); sw = m_labelMetrics.stringWidth(val); } NomLabel jj = new NomLabel(val, i); jj.setFont(gx.getFont()); jj.setSize(m_labelMetrics.stringWidth(jj.getText()), m_labelMetrics.getAscent() + 4); this.add(jj); jj.setLocation(x, y); jj.setForeground(m_colorList.get(i % m_colorList.size())); x += sw + 2; } else { NomLabel jj; jj = new NomLabel(m_Instances.attribute(m_cIndex).value(i), i); jj.setFont(gx.getFont()); jj.setSize(m_labelMetrics.stringWidth(jj.getText()), m_labelMetrics.getAscent() + 4); this.add(jj); jj.setLocation(x, y); jj.setForeground(m_colorList.get(i % m_colorList.size())); x += ((w - (m_HorizontalPad * 2)) / numToDo); } } x = m_HorizontalPad; y = 1 + hf + 5 + hf; for (int i = numToDo; i < numClasses; i++) { gx.setColor(m_colorList.get(i)); if (((numClasses - numToDo + 1) * maxLabelLen) > (w - (m_HorizontalPad * 2))) { String val; val = m_Instances.attribute(m_cIndex).value(i); int sw = m_labelMetrics.stringWidth(val); int rm = 0; // truncate string if necessary if (sw > ((w - (m_HorizontalPad * 2)) / (numClasses - numToDo + 1))) { int incr = (sw / val.length()); rm = (sw - ((w - (m_HorizontalPad * 2)) / (numClasses - numToDo))) / incr; if (rm <= 0) { rm = 0; } if (rm >= val.length()) { rm = val.length() - 1; } val = val.substring(0, val.length() - rm); sw = m_labelMetrics.stringWidth(val); } // this is the clipped string NomLabel jj = new NomLabel(val, i); jj.setFont(gx.getFont()); jj.setSize(m_labelMetrics.stringWidth(jj.getText()), m_labelMetrics.getAscent() + 4); this.add(jj); jj.setLocation(x, y); jj.setForeground(m_colorList.get(i % m_colorList.size())); x += sw + 2; } else { // this is the full string NomLabel jj; jj = new NomLabel(m_Instances.attribute(m_cIndex).value(i), i); jj.setFont(gx.getFont()); jj.setSize(m_labelMetrics.stringWidth(jj.getText()), m_labelMetrics.getAscent() + 4); this.add(jj); jj.setLocation(x, y); jj.setForeground(m_colorList.get(i % m_colorList.size())); x += ((w - (m_HorizontalPad * 2)) / (numClasses - numToDo)); } } } /** * Renders the legend for a numeric colouring attribute * * @param gx the graphics context */ protected void paintNumeric(Graphics gx) { setFonts(gx); if (m_HorizontalPad == 0) { setCindex(m_cIndex); } int w = this.getWidth(); double rs = 15; double incr = 240.0 / (w - (m_HorizontalPad * 2)); int hf = m_labelMetrics.getAscent(); for (int i = m_HorizontalPad; i < (w - m_HorizontalPad); i++) { Color c = new Color((int) rs, 150, (int) (255 - rs)); gx.setColor(c); gx.drawLine(i, 0, i, 0 + m_spectrumHeight); rs += incr; } int whole = (int) Math.abs(m_maxC); double decimal = Math.abs(m_maxC) - whole; int nondecimal; nondecimal = (whole > 0) ? (int) (Math.log(whole) / Math.log(10)) : 1; m_precisionC = (decimal > 0) ? (int) Math .abs(((Math.log(Math.abs(m_maxC)) / Math.log(10)))) + 2 : 1; if (m_precisionC > VisualizeUtils.MAX_PRECISION) { m_precisionC = 1; } String maxStringC = Utils.doubleToString(m_maxC, nondecimal + 1 + m_precisionC, m_precisionC); int mswc = m_labelMetrics.stringWidth(maxStringC); int tmsc = mswc; if (w > (2 * tmsc)) { gx.setColor(Color.black); gx.drawLine(m_HorizontalPad, (m_spectrumHeight + 5), w - m_HorizontalPad, (m_spectrumHeight + 5)); gx.drawLine(w - m_HorizontalPad, (m_spectrumHeight + 5), w - m_HorizontalPad, (m_spectrumHeight + 5 + m_tickSize)); gx.drawString(maxStringC, (w - m_HorizontalPad) - (mswc / 2), (m_spectrumHeight + 5 + m_tickSize + hf)); gx.drawLine(m_HorizontalPad, (m_spectrumHeight + 5), m_HorizontalPad, (m_spectrumHeight + 5 + m_tickSize)); whole = (int) Math.abs(m_minC); decimal = Math.abs(m_minC) - whole; nondecimal = (whole > 0) ? (int) (Math.log(whole) / Math.log(10)) : 1; m_precisionC = (decimal > 0) ? (int) Math .abs(((Math.log(Math.abs(m_minC)) / Math.log(10)))) + 2 : 1; if (m_precisionC > VisualizeUtils.MAX_PRECISION) { m_precisionC = 1; } maxStringC = Utils.doubleToString(m_minC, nondecimal + 1 + m_precisionC, m_precisionC); mswc = m_labelMetrics.stringWidth(maxStringC); gx.drawString(maxStringC, m_HorizontalPad - (mswc / 2), (m_spectrumHeight + 5 + m_tickSize + hf)); // draw the middle value if there is space if (w > (3 * tmsc)) { double mid = m_minC + ((m_maxC - m_minC) / 2.0); gx.drawLine(m_HorizontalPad + ((w - (2 * m_HorizontalPad)) / 2), (m_spectrumHeight + 5), m_HorizontalPad + ((w - (2 * m_HorizontalPad)) / 2), (m_spectrumHeight + 5 + m_tickSize)); whole = (int) Math.abs(mid); decimal = Math.abs(mid) - whole; nondecimal = (whole > 0) ? (int) (Math.log(whole) / Math.log(10)) : 1; m_precisionC = (decimal > 0) ? (int) Math .abs(((Math.log(Math.abs(mid)) / Math.log(10)))) + 2 : 1; if (m_precisionC > VisualizeUtils.MAX_PRECISION) { m_precisionC = 1; } maxStringC = Utils.doubleToString(mid, nondecimal + 1 + m_precisionC, m_precisionC); mswc = m_labelMetrics.stringWidth(maxStringC); gx.drawString(maxStringC, m_HorizontalPad + ((w - (2 * m_HorizontalPad)) / 2) - (mswc / 2), (m_spectrumHeight + 5 + m_tickSize + hf)); } } } /** * Renders this component * * @param gx the graphics context */ @Override public void paintComponent(Graphics gx) { super.paintComponent(gx); if (m_isEnabled) { if (m_isNumeric) { m_oldWidth = -9000; // done so that if change back to nom, it will // work this.removeAll(); paintNumeric(gx); } else { if (m_Instances != null && m_Instances.numInstances() > 0 && m_Instances.numAttributes() > 0) { if (m_oldWidth != this.getWidth()) { this.removeAll(); m_oldWidth = this.getWidth(); paintNominal(gx); } } } } } /** * Main method for testing this class. * * @param args first argument must specify an arff file. Second can specify an * optional index to colour labels on */ public static void main(String[] args) { try { if (args.length < 1) { System.err.println("Usage : weka.gui.visualize.ClassPanel <dataset> " + "[class col]"); System.exit(1); } final javax.swing.JFrame jf = new javax.swing.JFrame( "Weka Explorer: Class"); jf.setSize(500, 100); jf.getContentPane().setLayout(new BorderLayout()); final ClassPanel p2 = new ClassPanel(); jf.getContentPane().add(p2, BorderLayout.CENTER); jf.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { jf.dispose(); System.exit(0); } }); 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); i.setClassIndex(i.numAttributes() - 1); p2.setInstances(i); } if (args.length > 1) { p2.setCindex((Integer.parseInt(args[1])) - 1); } else { p2.setCindex(0); } 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/visualize/InstanceInfo.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * InstanceInfo.java * Copyright (C) 2009-2012 University of Waikato, Hamilton, New Zealand */ package weka.gui.visualize; import java.util.Vector; import weka.core.Instances; /** * Interface for JFrames that display instance info. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public interface InstanceInfo { /** * Sets the text to display. * * @param text the text to display */ public void setInfoText(String text); /** * Returns the currently displayed info text. * * @return the info text */ public String getInfoText(); /** * Sets the underlying data. * * @param data the data of the info text */ public void setInfoData(Vector<Instances> data); /** * Returns the underlying data. * * @return the data of the info text, can be null */ public Vector<Instances> getInfoData(); }
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/visualize/InstanceInfoFrame.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * InstanceInfoFrame.java * Copyright (C) 2009-2012 University of Waikato, Hamilton, New Zealand */ package weka.gui.visualize; import java.awt.BorderLayout; import java.awt.Font; import java.util.Vector; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTextArea; import weka.core.Instances; /** * Frame for displaying information on the displayed data. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class InstanceInfoFrame extends JFrame implements InstanceInfo { /** for serialization. */ private static final long serialVersionUID = 4684184733677263009L; /** the underlying data. */ protected Vector<Instances> m_Data; /** the text area for displaying the info. */ protected JTextArea m_TextInfo; /** * Initializes the frame. */ public InstanceInfoFrame() { super("Weka: Instance info"); initialize(); initGUI(); initFinished(); } /** * Initializes member variables. */ protected void initialize() { m_Data = new Vector<Instances>(); } /** * Sets up the GUI components. */ protected void initGUI() { getContentPane().setLayout(new BorderLayout()); m_TextInfo = new JTextArea(); m_TextInfo.setEditable(false); m_TextInfo.setFont(new Font("Monospaced", Font.PLAIN,12)); getContentPane().add(new JScrollPane(m_TextInfo), BorderLayout.CENTER); pack(); setSize(320, 400); } /** * A hook method after initialize() and initGUI have been called. */ protected void initFinished() { } /** * Sets the text to display. * * @param text the text to display */ public void setInfoText(String text) { m_TextInfo.setText(text); } /** * Returns the currently displayed info text. * * @return the info text */ public String getInfoText() { return m_TextInfo.getText(); } /** * Sets the underlying data. * * @param data the data of the info text */ public void setInfoData(Vector<Instances> data) { m_Data = new Vector<Instances>(); if (data != null) m_Data.addAll(data); } /** * Returns the underlying data. * * @return the data of the info text, can be null */ public Vector<Instances> getInfoData() { return m_Data; } }
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/visualize/JComponentWriter.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * JComponentWriter.java * Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.visualize; import java.io.File; import javax.swing.JComponent; /** * This class takes any JComponent and outputs it to a file. Scaling is by * default enabled. Derived classes only need to override the following * methods: * <ul> * <li><code>getDescription()</code></li> * <li><code>getExtension()</code></li> * <li><code>generateOutput()</code></li> * <li><code></code></li> * </ul> * * @see #setScalingEnabled(boolean) * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public abstract class JComponentWriter { /** whether to print some debug information */ protected final static boolean DEBUG = false; /** output if we're in debug mode */ static { if (DEBUG) System.err.println(JComponentWriter.class.getName() + ": DEBUG ON"); } /** the component to print in the output format */ private JComponent component; /** the file to write the output stream to */ private File outputFile; /** the x scale factor */ protected double m_xScale; /** the y scale factor */ protected double m_yScale; /** whether scaling is enabled */ protected boolean m_ScalingEnabled; /** whether to use custom dimensions */ protected boolean m_UseCustomDimensions; /** the custom width */ protected int m_CustomWidth; /** the custom height */ protected int m_CustomHeight; /** * initializes the object */ public JComponentWriter() { this(null); } /** * initializes the object with the given Component * * @param c the component to print in the output format */ public JComponentWriter(JComponent c) { this(c, null); } /** * initializes the object with the given Component and filename * * @param c the component to print in the output format * @param f the file to store the output in */ public JComponentWriter(JComponent c, File f) { component = c; outputFile = f; initialize(); } /** * further initialization can take place here */ protected void initialize() { m_xScale = 1.0; m_yScale = 1.0; m_ScalingEnabled = true; m_UseCustomDimensions = false; m_CustomWidth = -1; m_CustomHeight = -1; } /** * sets the component to print to an output format * * @param c the component to print */ public void setComponent(JComponent c) { component = c; } /** * returns the component that is stored in the output format * * @return the component to print */ public JComponent getComponent() { return component; } /** * sets the file to store the output in * * @param f the file to store the output in */ public void setFile(File f) { outputFile = f; } /** * returns the file being used for storing the output * * @return the file to store the output in */ public File getFile() { return outputFile; } /** * returns the name of the writer, to display in the FileChooser. * must be overridden in the derived class. * * @return the name of the writer */ public abstract String getDescription(); /** * returns the extension (incl. ".") of the output format, to use in the * FileChooser. * must be overridden in the derived class. * * @return the file extension */ public abstract String getExtension(); /** * whether scaling is enabled or ignored * * @return true if scaling is enabled */ public boolean getScalingEnabled() { return m_ScalingEnabled; } /** * sets whether to enable scaling * * @param enabled whether scaling is enabled */ public void setScalingEnabled(boolean enabled) { m_ScalingEnabled = enabled; } /** * sets the scale factor - is ignored since we always create a screenshot! * @param x the scale factor for the x-axis * @param y the scale factor for the y-axis */ public void setScale(double x, double y) { if (getScalingEnabled()) { m_xScale = x; m_yScale = y; } else { m_xScale = 1.0; m_yScale = 1.0; } if (DEBUG) System.err.println("xScale = " + m_xScale + ", yScale = " + m_yScale); } /** * returns the scale factor for the x-axis * * @return the scale scale factor for the x-axis */ public double getXScale() { return m_xScale; } /** * returns the scale factor for the y-axis * * @return the scale scale factor for the y-axis */ public double getYScale() { return m_xScale; } /** * whether custom dimensions are to used for the size of the image * * @return true if custom dimensions are used */ public boolean getUseCustomDimensions() { return m_UseCustomDimensions; } /** * sets whether to use custom dimensions for the image * * @param value whether custom dimensions are used */ public void setUseCustomDimensions(boolean value) { m_UseCustomDimensions = value; } /** * sets the custom width to use * * @param value the width to use * @see #m_UseCustomDimensions */ public void setCustomWidth(int value) { m_CustomWidth = value; } /** * gets the custom width currently used * * @return the custom width currently used * @see #m_UseCustomDimensions */ public int getCustomWidth() { return m_CustomWidth; } /** * sets the custom height to use * * @param value the height to use * @see #m_UseCustomDimensions */ public void setCustomHeight(int value) { m_CustomHeight = value; } /** * gets the custom height currently used * * @return the custom height currently used * @see #m_UseCustomDimensions */ public int getCustomHeight() { return m_CustomHeight; } /** * generates the actual output * * @throws Exception if something goes wrong */ protected abstract void generateOutput() throws Exception; /** * saves the current component to the currently set file.<p> * <b>Note:</b> this method calls <code>generateOutput()</code> which needs * to be overriden in subclasses! * @throws Exception if either the file or the component is <code>null</code> */ public void toOutput() throws Exception { int oldWidth; int oldHeight; if (getFile() == null) throw new Exception("The file is not set!"); if (getComponent() == null) throw new Exception("The component is not set!"); // backup original dimensions and set custom ones if necessary oldWidth = getComponent().getWidth(); oldHeight = getComponent().getHeight(); if (getUseCustomDimensions()) getComponent().setSize(getCustomWidth(), getCustomHeight()); generateOutput(); // restore original dimensions if (getUseCustomDimensions()) getComponent().setSize(oldWidth, oldHeight); } /** * outputs the given component with the given writer in the specified file * * @param writer the writer to use * @param comp the component to output * @param file the file to store the output in * @throws Exception if component of file are <code>null</code> */ public static void toOutput(JComponentWriter writer, JComponent comp, File file) throws Exception { toOutput(writer, comp, file, -1, -1); } /** * outputs the given component with the given writer in the specified file. * If width and height are different from -1 then these sizes are used, * otherwise the current ones of the component * * @param writer the writer to use * @param comp the component to output * @param file the file to store the output in * @param width custom width, -1 uses the component's one * @param height custom height, -1 uses the component's one * @throws Exception if component or file are <code>null</code> */ public static void toOutput(JComponentWriter writer, JComponent comp, File file, int width, int height) throws Exception { writer.setComponent(comp); writer.setFile(file); // custom dimensions? if ((width != -1) && (height != -1)) { writer.setUseCustomDimensions(true); writer.setCustomWidth(width); writer.setCustomHeight(height); } writer.toOutput(); } }
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/visualize/JPEGWriter.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * JPEGWriter.java * Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.visualize; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.util.Iterator; import java.util.Locale; 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.JComponent; /** * This class takes any JComponent and outputs it to a JPEG-file. Scaling is by * default disabled, since we always take a screenshot. * * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class JPEGWriter extends JComponentWriter { /** the quality of the image. */ protected float m_Quality; /** the background color. */ protected Color m_Background; /** * initializes the object. */ public JPEGWriter() { super(); } /** * initializes the object with the given Component. * * @param c the component to print in the output format */ public JPEGWriter(JComponent c) { super(c); } /** * initializes the object with the given Component and filename. * * @param c the component to print in the output format * @param f the file to store the output in */ public JPEGWriter(JComponent c, File f) { super(c, f); m_Quality = 1.0f; m_Background = Color.WHITE; } /** * further initialization. */ @Override public void initialize() { super.initialize(); m_Quality = 1.0f; m_Background = Color.WHITE; setScalingEnabled(false); } /** * returns the name of the writer, to display in the FileChooser. must be * overridden in the derived class. * * @return the name of the writer */ @Override public String getDescription() { return "JPEG-Image"; } /** * returns the extension (incl. ".") of the output format, to use in the * FileChooser. must be overridden in the derived class. * * @return the file extension */ @Override public String getExtension() { return ".jpg"; } /** * returns the current background color. * * @return the current background color */ public Color getBackground() { return m_Background; } /** * sets the background color to use in creating the JPEG. * * @param c the color to use for background */ public void setBackground(Color c) { m_Background = c; } /** * returns the quality the JPEG will be stored in. * * @return the quality */ public float getQuality() { return m_Quality; } /** * sets the quality the JPEG is saved in. * * @param q the quality to use */ public void setQuality(float q) { m_Quality = q; } /** * generates the actual output. * * @throws Exception if something goes wrong */ @Override public void generateOutput() throws Exception { BufferedImage bi; Graphics g; ImageWriter writer; Iterator<ImageWriter> iter; ImageOutputStream ios; ImageWriteParam param; // render image bi = new BufferedImage(getComponent().getWidth(), getComponent() .getHeight(), BufferedImage.TYPE_INT_RGB); g = bi.getGraphics(); g.setPaintMode(); g.setColor(getBackground()); if (g instanceof Graphics2D) { ((Graphics2D) g).scale(getXScale(), getYScale()); } g.fillRect(0, 0, getComponent().getWidth(), getComponent().getHeight()); getComponent().printAll(g); // get jpeg writer writer = null; iter = ImageIO.getImageWritersByFormatName(getExtension().replace(".", "")); if (iter.hasNext()) { writer = iter.next(); } else { throw new Exception("No writer available for " + getDescription() + "!"); } // prepare output file ios = ImageIO.createImageOutputStream(getFile()); writer.setOutput(ios); // set the quality param = new JPEGImageWriteParam(Locale.getDefault()); param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); param.setCompressionQuality(getQuality()); // write the image writer.write(null, new IIOImage(bi, null, null), param); // cleanup ios.flush(); writer.dispose(); ios.close(); } /** * for testing only. * * @param args the commandline arguments * @throws Exception if something goes wrong */ public static void main(String[] args) throws Exception { System.out.println("building TreeVisualizer..."); weka.gui.treevisualizer.TreeBuild builder = new weka.gui.treevisualizer.TreeBuild(); weka.gui.treevisualizer.NodePlace arrange = new weka.gui.treevisualizer.PlaceNode2(); weka.gui.treevisualizer.Node top = builder .create(new java.io.StringReader( "digraph atree { top [label=\"the top\"] a [label=\"the first node\"] b [label=\"the second nodes\"] c [label=\"comes off of first\"] top->a top->b b->c }")); weka.gui.treevisualizer.TreeVisualizer tv = new weka.gui.treevisualizer.TreeVisualizer( null, top, arrange); tv.setSize(800, 600); String filename = System.getProperty("java.io.tmpdir") + File.separator + "test.jpg"; System.out.println("outputting to '" + filename + "'..."); toOutput(new JPEGWriter(), tv, new File(filename)); System.out.println("done!"); } }
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/visualize/LegendPanel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * LegendPanel.java * Copyright (C) 2000-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.visualize; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Graphics; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.InputEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; import javax.swing.JColorChooser; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import weka.core.Instances; /** * This panel displays legends for a list of plots. If a given plot has a custom * colour defined then this panel allows the colour to be changed. * * @author Mark Hall (mhall@cs.waikato.ac.nz) * @version $Revision$ */ public class LegendPanel extends JScrollPane { /** for serialization */ private static final long serialVersionUID = -1262384440543001505L; /** the list of plot elements */ protected ArrayList<PlotData2D> m_plots; /** the panel that contains the legend entries */ protected JPanel m_span = null; /** * a list of components that need to be repainted when a colour is changed */ protected ArrayList<Component> m_Repainters = new ArrayList<Component>(); /** * Inner class for handling legend entries */ protected class LegendEntry extends JPanel { /** for serialization */ private static final long serialVersionUID = 3879990289042935670L; /** the data for this legend entry */ private PlotData2D m_plotData = null; /** * the index (in the list of plots) of the data for this legend--- used to * draw the correct shape for this data */ private final int m_dataIndex; /** the text part of this legend */ private final JLabel m_legendText; /** displays the point shape associated with this legend entry */ private final JPanel m_pointShape; public LegendEntry(PlotData2D data, int dataIndex) { javax.swing.ToolTipManager.sharedInstance().setDismissDelay(5000); m_plotData = data; m_dataIndex = dataIndex; // this.setBackground(Color.black); /* * this.setPreferredSize(new Dimension(0, 20)); this.setMinimumSize(new * Dimension(0, 20)); */ if (m_plotData.m_useCustomColour) { this.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if ((e.getModifiers() & InputEvent.BUTTON1_MASK) == InputEvent.BUTTON1_MASK) { Color tmp = JColorChooser.showDialog(LegendPanel.this, "Select new Color", m_plotData.m_customColour); if (tmp != null) { m_plotData.m_customColour = tmp; m_legendText.setForeground(tmp); if (m_Repainters.size() > 0) { for (int i = 0; i < m_Repainters.size(); i++) { (m_Repainters.get(i)).repaint(); } } LegendPanel.this.repaint(); } } } }); } m_legendText = new JLabel(m_plotData.m_plotName); m_legendText.setToolTipText(m_plotData.getPlotNameHTML()); if (m_plotData.m_useCustomColour) { m_legendText.setForeground(m_plotData.m_customColour); } this.setLayout(new BorderLayout()); this.add(m_legendText, BorderLayout.CENTER); /* * GridBagLayout gb = new GridBagLayout(); GridBagConstraints constraints * = new GridBagConstraints(); constraints.fill = * GridBagConstraints.HORIZONTAL; * constraints.gridx=0;constraints.gridy=0;constraints.weightx=5; */ m_pointShape = new JPanel() { private static final long serialVersionUID = -7048435221580488238L; @Override public void paintComponent(Graphics gx) { super.paintComponent(gx); if (!m_plotData.m_useCustomColour) { gx.setColor(Color.black); } else { gx.setColor(m_plotData.m_customColour); } Plot2D.drawDataPoint(10, 10, 3, m_dataIndex, gx); } }; // m_pointShape.setBackground(Color.black); m_pointShape.setPreferredSize(new Dimension(20, 20)); m_pointShape.setMinimumSize(new Dimension(20, 20)); this.add(m_pointShape, BorderLayout.WEST); } } /** * Constructor */ public LegendPanel() { this.setBackground(Color.blue); setVerticalScrollBarPolicy(VERTICAL_SCROLLBAR_ALWAYS); } /** * Set the list of plots to generate legend entries for * * @param pl a list of plots */ public void setPlotList(ArrayList<PlotData2D> pl) { m_plots = pl; updateLegends(); } /** * Adds a component that will need to be repainted if the user changes the * colour of a label. * * @param c the component to be repainted */ public void addRepaintNotify(Component c) { m_Repainters.add(c); } /** * Redraw the panel with the legend entries */ private void updateLegends() { if (m_span == null) { m_span = new JPanel(); } JPanel padder = new JPanel(); JPanel padd2 = new JPanel(); m_span.setPreferredSize(new Dimension(m_span.getPreferredSize().width, (m_plots.size() + 1) * 20)); m_span.setMaximumSize(new Dimension(m_span.getPreferredSize().width, (m_plots.size() + 1) * 20)); LegendEntry tmp; GridBagLayout gb = new GridBagLayout(); GridBagLayout gb2 = new GridBagLayout(); GridBagConstraints constraints = new GridBagConstraints(); m_span.removeAll(); padder.setLayout(gb); m_span.setLayout(gb2); constraints.anchor = GridBagConstraints.CENTER; constraints.gridx = 0; constraints.gridy = 0; constraints.weightx = 5; constraints.fill = GridBagConstraints.HORIZONTAL; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.insets = new Insets(0, 0, 0, 0); padder.add(m_span, constraints); constraints.gridx = 0; constraints.gridy = 1; constraints.weightx = 5; constraints.fill = GridBagConstraints.BOTH; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.weighty = 5; constraints.insets = new Insets(0, 0, 0, 0); padder.add(padd2, constraints); constraints.weighty = 0; setViewportView(padder); constraints.anchor = GridBagConstraints.CENTER; constraints.gridx = 0; constraints.gridy = 0; constraints.weightx = 5; constraints.fill = GridBagConstraints.HORIZONTAL; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.weighty = 5; constraints.insets = new Insets(2, 4, 2, 4); // int numLines = // ((PlotData2D)m_plots.get(0)).getPlotName().split("<br>").length; for (int i = 0; i < m_plots.size(); i++) { tmp = new LegendEntry(m_plots.get(i), i); constraints.gridy = i; /* * constraints.gridheight = 1; if (numLines > 0) { constraints.gridheight * = (numLines + 2); } */ m_span.add(tmp, constraints); } } /** * Main method for testing this class * * @param args a list of arff files */ public static void main(String[] args) { try { if (args.length < 1) { System.err.println("Usage : weka.gui.visualize.LegendPanel " + "<dataset> [dataset2], [dataset3],..."); System.exit(1); } final javax.swing.JFrame jf = new javax.swing.JFrame( "Weka Explorer: Legend"); jf.setSize(100, 100); jf.getContentPane().setLayout(new BorderLayout()); final LegendPanel p2 = new LegendPanel(); jf.getContentPane().add(p2, BorderLayout.CENTER); jf.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { jf.dispose(); System.exit(0); } }); ArrayList<PlotData2D> plotList = new ArrayList<PlotData2D>(); for (int j = 0; j < args.length; j++) { System.err.println("Loading instances from " + args[j]); java.io.Reader r = new java.io.BufferedReader(new java.io.FileReader( args[j])); Instances i = new Instances(r); PlotData2D tmp = new PlotData2D(i); if (j != 1) { tmp.m_useCustomColour = true; tmp.m_customColour = Color.red; } tmp.setPlotName(i.relationName()); plotList.add(tmp); } p2.setPlotList(plotList); jf.setVisible(true); } catch (Exception ex) { System.err.println(ex.getMessage()); 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/visualize/MatrixPanel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * MatrixPanel.java * Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.visualize; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dialog.ModalityType; import java.awt.Dimension; import java.awt.Graphics; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Image; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Random; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSlider; import javax.swing.JSplitPane; import javax.swing.JTextField; import javax.swing.SwingUtilities; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import weka.core.Attribute; import weka.core.Environment; import weka.core.Instances; import weka.core.Settings; import weka.core.Utils; import weka.gui.ExtensionFileFilter; /** * This panel displays a plot matrix of the user selected attributes of a given * data set. * * The datapoints are coloured using a discrete colouring set if the user has * selected a nominal attribute for colouring. If the user has selected a * numeric attribute then the datapoints are coloured using a colour spectrum * ranging from blue to red (low values to high). Datapoints missing a class * value are displayed in black. * * @author Ashraf M. Kibriya (amk14@cs.waikato.ac.nz) * @version $Revision$ */ public class MatrixPanel extends JPanel { /** for serialization */ private static final long serialVersionUID = -1232642719869188740L; /** The that panel contains the actual matrix */ private final Plot m_plotsPanel; /** The panel that displays the legend of the colouring attribute */ protected final ClassPanel m_cp = new ClassPanel(); /** * The panel that contains all the buttons and tools, i.e. resize, jitter bars * and sub-sampling buttons etc on the bottom of the panel */ protected JPanel optionsPanel; /** Split pane for splitting the matrix and the buttons and bars */ protected JSplitPane jp; /** * The button that updates the display to reflect the changes made by the * user. E.g. changed attribute set for the matrix */ protected JButton m_updateBt = new JButton("Update"); /** The button to display a window to select attributes */ protected JButton m_selAttrib = new JButton("Select Attributes"); /** The dataset for which this panel will display the plot matrix for */ protected Instances m_data = null; /** The list for selecting the attributes to display the plot matrix */ protected JList m_attribList = new JList(); /** The scroll pane to scrolling the matrix */ protected final JScrollPane m_js = new JScrollPane(); /** The combo box to allow user to select the colouring attribute */ protected JComboBox m_classAttrib = new JComboBox(); /** The slider to adjust the size of the cells in the matrix */ protected JSlider m_plotSize = new JSlider(50, 200, 100); /** The slider to adjust the size of the datapoints */ protected JSlider m_pointSize = new JSlider(1, 10, 1); /** The slider to add jitter to the plots */ protected JSlider m_jitter = new JSlider(0, 20, 0); /** For adding random jitter */ private final Random rnd = new Random(); /** Array containing precalculated jitter values */ private int jitterVals[][]; /** This stores the size of the datapoint */ private int datapointSize = 1; /** The text area for percentage to resample data */ protected JTextField m_resamplePercent = new JTextField(5); /** The label for resample percentage */ protected JButton m_resampleBt = new JButton("SubSample % :"); /** Random seed for random subsample */ protected JTextField m_rseed = new JTextField(5); /** Displays the current size beside the slider bar for cell size */ private final JLabel m_plotSizeLb = new JLabel("PlotSize: [100]"); /** Displays the current size beside the slider bar for point size */ private final JLabel m_pointSizeLb = new JLabel("PointSize: [10]"); /** This array contains the indices of the attributes currently selected */ private int[] m_selectedAttribs; /** This contains the index of the currently selected colouring attribute */ private int m_classIndex; /** * This is a local array cache for all the instance values for faster * rendering */ private int[][] m_points; /** * This is an array cache for the colour of each of the instances depending on * the colouring attribute. If the colouring attribute is nominal then it * contains the index of the colour in our colour list. Otherwise, for numeric * colouring attribute, it contains the precalculated red component for each * instance's colour */ private int[] m_pointColors; /** * Contains true for each attribute value (only the selected attributes+class * attribute) that is missing, for each instance. m_missing[i][j] == true if * m_selectedAttribs[j] is missing in instance i. * m_missing[i][m_missing[].length-1] == true if class value is missing in * instance i. */ private boolean[][] m_missing; /** * This array contains for the classAttribute: <br> * m_type[0] = [type of attribute, nominal, string or numeric]<br> * m_type[1] = [number of discrete values of nominal or string attribute <br> * or same as m_type[0] for numeric attribute] */ private int[] m_type; /** Stores the maximum size for PlotSize label to keep it's size constant */ private final Dimension m_plotLBSizeD; /** Stores the maximum size for PointSize label to keep it's size constant */ private final Dimension m_pointLBSizeD; /** Contains discrete colours for colouring for nominal attributes */ private final ArrayList<Color> m_colorList = new ArrayList<Color>(); /** default colour list */ private static final Color[] m_defaultColors = { Color.blue, Color.red, Color.cyan, new Color(75, 123, 130), Color.pink, Color.green, Color.orange, new Color(255, 0, 255), new Color(255, 0, 0), new Color(0, 255, 0), Color.black }; /** color for the font used in column and row names */ private final Color fontColor = new Color(98, 101, 156); /** font used in column and row names */ private final java.awt.Font f = new java.awt.Font("Dialog", java.awt.Font.BOLD, 11); /** Settings (if available) to pass through to the VisualizePanels */ protected Settings m_settings; /** For the background of the little plots */ protected Color m_backgroundColor = Color.white; /** * ID of the owner (perspective, panel etc.) under which to lookup our * settings */ protected String m_settingsOwnerID; protected transient Image m_osi = null; protected boolean[][] m_plottedCells; protected boolean m_regenerateOSI = true; protected boolean m_clearOSIPlottedCells; protected double m_previousPercent = -1; protected JCheckBox m_fastScroll = new JCheckBox("Fast scrolling (uses more memory)"); /** * Constructor */ public MatrixPanel() { this.m_rseed.setText("1"); /** Setting up GUI **/ this.m_selAttrib.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent ae) { final JDialog jd = new JDialog((JFrame) MatrixPanel.this.getTopLevelAncestor(), "Attribute Selection Panel", ModalityType.DOCUMENT_MODAL); JPanel jp = new JPanel(); JScrollPane js = new JScrollPane(MatrixPanel.this.m_attribList); JButton okBt = new JButton("OK"); JButton cancelBt = new JButton("Cancel"); final int[] savedSelection = MatrixPanel.this.m_attribList.getSelectedIndices(); okBt.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { jd.dispose(); } }); cancelBt.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { MatrixPanel.this.m_attribList.setSelectedIndices(savedSelection); jd.dispose(); } }); jd.addWindowListener(new WindowAdapter() { @Override public void windowClosing(final WindowEvent e) { MatrixPanel.this.m_attribList.setSelectedIndices(savedSelection); jd.dispose(); } }); jp.add(okBt); jp.add(cancelBt); jd.getContentPane().add(js, BorderLayout.CENTER); jd.getContentPane().add(jp, BorderLayout.SOUTH); if (js.getPreferredSize().width < 200) { jd.setSize(250, 250); } else { jd.setSize(js.getPreferredSize().width + 10, 250); } jd.setLocation(MatrixPanel.this.m_selAttrib.getLocationOnScreen().x, MatrixPanel.this.m_selAttrib.getLocationOnScreen().y - jd.getHeight()); jd.setVisible(true); } }); this.m_updateBt.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { MatrixPanel.this.updatePanel(); } }); this.m_updateBt.setPreferredSize(this.m_selAttrib.getPreferredSize()); this.m_jitter.addChangeListener(new ChangeListener() { @Override public void stateChanged(final ChangeEvent ce) { if (MatrixPanel.this.m_fastScroll.isSelected()) { MatrixPanel.this.m_clearOSIPlottedCells = true; } } }); this.m_plotSize.addChangeListener(new ChangeListener() { @Override public void stateChanged(final ChangeEvent ce) { MatrixPanel.this.m_plotSizeLb.setText("PlotSize: [" + MatrixPanel.this.m_plotSize.getValue() + "]"); MatrixPanel.this.m_plotSizeLb.setPreferredSize(MatrixPanel.this.m_plotLBSizeD); MatrixPanel.this.m_jitter.setMaximum(MatrixPanel.this.m_plotSize.getValue() / 5); // 20% of cell Size MatrixPanel.this.m_regenerateOSI = true; } }); this.m_pointSize.addChangeListener(new ChangeListener() { @Override public void stateChanged(final ChangeEvent ce) { MatrixPanel.this.m_pointSizeLb.setText("PointSize: [" + MatrixPanel.this.m_pointSize.getValue() + "]"); MatrixPanel.this.m_pointSizeLb.setPreferredSize(MatrixPanel.this.m_pointLBSizeD); MatrixPanel.this.datapointSize = MatrixPanel.this.m_pointSize.getValue(); if (MatrixPanel.this.m_fastScroll.isSelected()) { MatrixPanel.this.m_clearOSIPlottedCells = true; } } }); this.m_resampleBt.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { JLabel rseedLb = new JLabel("Random Seed: "); JTextField rseedTxt = MatrixPanel.this.m_rseed; JLabel percentLb = new JLabel("Subsample as"); JLabel percent2Lb = new JLabel("% of input: "); final JTextField percentTxt = new JTextField(5); percentTxt.setText(MatrixPanel.this.m_resamplePercent.getText()); JButton doneBt = new JButton("Done"); final JDialog jd = new JDialog((JFrame) MatrixPanel.this.getTopLevelAncestor(), "Subsample % Panel", ModalityType.DOCUMENT_MODAL) { private static final long serialVersionUID = -269823533147146296L; @Override public void dispose() { MatrixPanel.this.m_resamplePercent.setText(percentTxt.getText()); super.dispose(); } }; jd.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); doneBt.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent ae) { jd.dispose(); } }); GridBagLayout gbl = new GridBagLayout(); GridBagConstraints gbc = new GridBagConstraints(); JPanel p1 = new JPanel(gbl); gbc.anchor = GridBagConstraints.WEST; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.insets = new Insets(0, 2, 2, 2); gbc.gridwidth = GridBagConstraints.RELATIVE; p1.add(rseedLb, gbc); gbc.weightx = 0; gbc.gridwidth = GridBagConstraints.REMAINDER; gbc.weightx = 1; p1.add(rseedTxt, gbc); gbc.insets = new Insets(8, 2, 0, 2); gbc.weightx = 0; p1.add(percentLb, gbc); gbc.insets = new Insets(0, 2, 2, 2); gbc.gridwidth = GridBagConstraints.RELATIVE; p1.add(percent2Lb, gbc); gbc.gridwidth = GridBagConstraints.REMAINDER; gbc.weightx = 1; p1.add(percentTxt, gbc); gbc.insets = new Insets(8, 2, 2, 2); JPanel p3 = new JPanel(gbl); gbc.fill = GridBagConstraints.HORIZONTAL; gbc.gridwidth = GridBagConstraints.REMAINDER; gbc.weightx = 1; gbc.weighty = 0; p3.add(p1, gbc); gbc.insets = new Insets(8, 4, 8, 4); p3.add(doneBt, gbc); jd.getContentPane().setLayout(new BorderLayout()); jd.getContentPane().add(p3, BorderLayout.NORTH); jd.pack(); jd.setLocation(MatrixPanel.this.m_resampleBt.getLocationOnScreen().x, MatrixPanel.this.m_resampleBt.getLocationOnScreen().y - jd.getHeight()); jd.setVisible(true); } }); this.optionsPanel = new JPanel(new GridBagLayout()); // all the rest of the // panels are in here. final JPanel p2 = new JPanel(new BorderLayout()); // this has class colour // panel final JPanel p3 = new JPanel(new GridBagLayout()); // this has update and // select buttons final JPanel p4 = new JPanel(new GridBagLayout()); // this has the slider // bars and combobox GridBagConstraints gbc = new GridBagConstraints(); this.m_plotLBSizeD = this.m_plotSizeLb.getPreferredSize(); this.m_pointLBSizeD = this.m_pointSizeLb.getPreferredSize(); this.m_pointSizeLb.setText("PointSize: [1]"); this.m_pointSizeLb.setPreferredSize(this.m_pointLBSizeD); this.m_resampleBt.setPreferredSize(this.m_selAttrib.getPreferredSize()); gbc.fill = GridBagConstraints.HORIZONTAL; gbc.anchor = GridBagConstraints.NORTHWEST; gbc.insets = new Insets(2, 2, 2, 2); p4.add(this.m_plotSizeLb, gbc); gbc.weightx = 1; gbc.gridwidth = GridBagConstraints.REMAINDER; p4.add(this.m_plotSize, gbc); gbc.weightx = 0; gbc.gridwidth = GridBagConstraints.RELATIVE; p4.add(this.m_pointSizeLb, gbc); gbc.weightx = 1; gbc.gridwidth = GridBagConstraints.REMAINDER; p4.add(this.m_pointSize, gbc); gbc.weightx = 0; gbc.gridwidth = GridBagConstraints.RELATIVE; p4.add(new JLabel("Jitter: "), gbc); gbc.weightx = 1; gbc.gridwidth = GridBagConstraints.REMAINDER; p4.add(this.m_jitter, gbc); p4.add(this.m_classAttrib, gbc); gbc.gridwidth = GridBagConstraints.REMAINDER; gbc.weightx = 1; gbc.fill = GridBagConstraints.NONE; p3.add(this.m_fastScroll, gbc); p3.add(this.m_updateBt, gbc); p3.add(this.m_selAttrib, gbc); gbc.gridwidth = GridBagConstraints.RELATIVE; gbc.weightx = 0; gbc.fill = GridBagConstraints.VERTICAL; gbc.anchor = GridBagConstraints.WEST; p3.add(this.m_resampleBt, gbc); gbc.gridwidth = GridBagConstraints.REMAINDER; p3.add(this.m_resamplePercent, gbc); p2.setBorder(BorderFactory.createTitledBorder("Class Colour")); p2.add(this.m_cp, BorderLayout.SOUTH); gbc.insets = new Insets(8, 5, 2, 5); gbc.anchor = GridBagConstraints.SOUTHWEST; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.weightx = 1; gbc.gridwidth = GridBagConstraints.RELATIVE; this.optionsPanel.add(p4, gbc); gbc.gridwidth = GridBagConstraints.REMAINDER; this.optionsPanel.add(p3, gbc); this.optionsPanel.add(p2, gbc); this.m_fastScroll.setSelected(false); this.m_fastScroll.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { if (!MatrixPanel.this.m_fastScroll.isSelected()) { MatrixPanel.this.m_osi = null; } else { MatrixPanel.this.m_plottedCells = new boolean[MatrixPanel.this.m_selectedAttribs.length][MatrixPanel.this.m_selectedAttribs.length]; } MatrixPanel.this.invalidate(); MatrixPanel.this.repaint(); } }); this.addComponentListener(new ComponentAdapter() { @Override public void componentResized(final ComponentEvent cv) { MatrixPanel.this.m_js.setMinimumSize(new Dimension(MatrixPanel.this.getWidth(), MatrixPanel.this.getHeight() - MatrixPanel.this.optionsPanel.getPreferredSize().height - 10)); MatrixPanel.this.jp.setDividerLocation(MatrixPanel.this.getHeight() - MatrixPanel.this.optionsPanel.getPreferredSize().height - 10); } }); this.optionsPanel.setMinimumSize(new Dimension(0, 0)); this.jp = new JSplitPane(JSplitPane.VERTICAL_SPLIT, this.m_js, this.optionsPanel); this.jp.setOneTouchExpandable(true); this.jp.setResizeWeight(1); this.setLayout(new BorderLayout()); this.add(this.jp, BorderLayout.CENTER); /** Setting up the initial color list **/ for (int i = 0; i < m_defaultColors.length; i++) { this.m_colorList.add(m_defaultColors[i]); } /** Initializing internal fields and components **/ this.m_selectedAttribs = this.m_attribList.getSelectedIndices(); this.m_plotsPanel = new Plot(); this.m_plotsPanel.setLayout(null); this.m_js.getHorizontalScrollBar().setUnitIncrement(10); this.m_js.getVerticalScrollBar().setUnitIncrement(10); this.m_js.setViewportView(this.m_plotsPanel); this.m_js.setColumnHeaderView(this.m_plotsPanel.getColHeader()); this.m_js.setRowHeaderView(this.m_plotsPanel.getRowHeader()); final JLabel lb = new JLabel(" Plot Matrix"); lb.setFont(this.f); lb.setForeground(this.fontColor); lb.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); this.m_js.setCorner(JScrollPane.UPPER_LEFT_CORNER, lb); this.m_cp.setInstances(this.m_data); this.m_cp.setBorder(BorderFactory.createEmptyBorder(15, 10, 10, 10)); this.m_cp.addRepaintNotify(this.m_plotsPanel); // m_updateBt.doClick(); //not until setting up the instances } /** * Initializes internal data fields, i.e. data values, type, missing and color * cache arrays */ public void initInternalFields() { Instances inst = this.m_data; this.m_classIndex = this.m_classAttrib.getSelectedIndex(); this.m_selectedAttribs = this.m_attribList.getSelectedIndices(); double minC = 0, maxC = 0; /** Resampling **/ double currentPercent = Double.parseDouble(this.m_resamplePercent.getText()); if (currentPercent <= 100) { if (currentPercent != this.m_previousPercent) { this.m_clearOSIPlottedCells = true; } inst = new Instances(this.m_data, 0, this.m_data.numInstances()); try { inst.randomize(new Random(Integer.parseInt(this.m_rseed.getText()))); } catch (InterruptedException e) { throw new IllegalStateException(e); } // System.err.println("gettingPercent: " + // Math.round( // Double.parseDouble(m_resamplePercent.getText()) // / 100D * m_data.numInstances() // ) // ); inst = new Instances(inst, 0, (int) Math.round(currentPercent / 100D * inst.numInstances())); this.m_previousPercent = currentPercent; } this.m_points = new int[inst.numInstances()][this.m_selectedAttribs.length]; // changed this.m_pointColors = new int[inst.numInstances()]; this.m_missing = new boolean[inst.numInstances()][this.m_selectedAttribs.length + 1]; // changed this.m_type = new int[2]; // [m_selectedAttribs.length]; //changed this.jitterVals = new int[inst.numInstances()][2]; /** * Setting up the color list for non-numeric attribute as well as jittervals **/ if (!(inst.attribute(this.m_classIndex).isNumeric())) { for (int i = this.m_colorList.size(); i < inst.attribute(this.m_classIndex).numValues() + 1; i++) { Color pc = m_defaultColors[i % 10]; int ija = i / 10; ija *= 2; for (int j = 0; j < ija; j++) { pc = pc.darker(); } this.m_colorList.add(pc); } for (int i = 0; i < inst.numInstances(); i++) { // set to black for missing class value which is last colour is default // list if (inst.instance(i).isMissing(this.m_classIndex)) { this.m_pointColors[i] = m_defaultColors.length - 1; } else { this.m_pointColors[i] = (int) inst.instance(i).value(this.m_classIndex); } this.jitterVals[i][0] = this.rnd.nextInt(this.m_jitter.getValue() + 1) - this.m_jitter.getValue() / 2; this.jitterVals[i][1] = this.rnd.nextInt(this.m_jitter.getValue() + 1) - this.m_jitter.getValue() / 2; } } /** Setting up color variations for numeric attribute as well as jittervals **/ else { for (int i = 0; i < inst.numInstances(); i++) { if (!(inst.instance(i).isMissing(this.m_classIndex))) { minC = maxC = inst.instance(i).value(this.m_classIndex); break; } } for (int i = 1; i < inst.numInstances(); i++) { if (!(inst.instance(i).isMissing(this.m_classIndex))) { if (minC > inst.instance(i).value(this.m_classIndex)) { minC = inst.instance(i).value(this.m_classIndex); } if (maxC < inst.instance(i).value(this.m_classIndex)) { maxC = inst.instance(i).value(this.m_classIndex); } } } for (int i = 0; i < inst.numInstances(); i++) { double r = (inst.instance(i).value(this.m_classIndex) - minC) / (maxC - minC); r = (r * 240) + 15; this.m_pointColors[i] = (int) r; this.jitterVals[i][0] = this.rnd.nextInt(this.m_jitter.getValue() + 1) - this.m_jitter.getValue() / 2; this.jitterVals[i][1] = this.rnd.nextInt(this.m_jitter.getValue() + 1) - this.m_jitter.getValue() / 2; } } /** Creating local cache of the data values **/ double min[] = new double[this.m_selectedAttribs.length], max = 0; // changed double ratio[] = new double[this.m_selectedAttribs.length]; // changed double cellSize = this.m_plotSize.getValue(), temp1 = 0, temp2 = 0; for (int j = 0; j < this.m_selectedAttribs.length; j++) { int i; for (i = 0; i < inst.numInstances(); i++) { min[j] = max = 0; if (!(inst.instance(i).isMissing(this.m_selectedAttribs[j]))) { min[j] = max = inst.instance(i).value(this.m_selectedAttribs[j]); break; } } for (; i < inst.numInstances(); i++) { if (!(inst.instance(i).isMissing(this.m_selectedAttribs[j]))) { if (inst.instance(i).value(this.m_selectedAttribs[j]) < min[j]) { min[j] = inst.instance(i).value(this.m_selectedAttribs[j]); } if (inst.instance(i).value(this.m_selectedAttribs[j]) > max) { max = inst.instance(i).value(this.m_selectedAttribs[j]); } } } ratio[j] = cellSize / (max - min[j]); } boolean classIndexProcessed = false; for (int j = 0; j < this.m_selectedAttribs.length; j++) { if (inst.attribute(this.m_selectedAttribs[j]).isNominal() || inst.attribute(this.m_selectedAttribs[j]).isString()) { // m_type[0][j] = 1; m_type[1][j] = // inst.attribute(m_selectedAttribs[j]).numValues(); temp1 = cellSize / inst.attribute(this.m_selectedAttribs[j]).numValues(); // m_type[1][j]; temp2 = temp1 / 2; for (int i = 0; i < inst.numInstances(); i++) { this.m_points[i][j] = (int) Math.round(temp2 + temp1 * inst.instance(i).value(this.m_selectedAttribs[j])); if (inst.instance(i).isMissing(this.m_selectedAttribs[j])) { this.m_missing[i][j] = true; // represents missing value if (this.m_selectedAttribs[j] == this.m_classIndex) { this.m_missing[i][this.m_missing[0].length - 1] = true; classIndexProcessed = true; } } } } else { // m_type[0][j] = m_type[1][j] = 0; for (int i = 0; i < inst.numInstances(); i++) { this.m_points[i][j] = (int) Math.round((inst.instance(i).value(this.m_selectedAttribs[j]) - min[j]) * ratio[j]); if (inst.instance(i).isMissing(this.m_selectedAttribs[j])) { this.m_missing[i][j] = true; // represents missing value if (this.m_selectedAttribs[j] == this.m_classIndex) { this.m_missing[i][this.m_missing[0].length - 1] = true; classIndexProcessed = true; } } } } } if (inst.attribute(this.m_classIndex).isNominal() || inst.attribute(this.m_classIndex).isString()) { this.m_type[0] = 1; this.m_type[1] = inst.attribute(this.m_classIndex).numValues(); } else { this.m_type[0] = this.m_type[1] = 0; } if (classIndexProcessed == false) { // class Index has not been processed as // class index is not among the selected // attribs for (int i = 0; i < inst.numInstances(); i++) { if (inst.instance(i).isMissing(this.m_classIndex)) { this.m_missing[i][this.m_missing[0].length - 1] = true; } } } this.m_cp.setColours(this.m_colorList); } /** * Sets up the UI's attributes lists */ public void setupAttribLists() { String[] tempAttribNames = new String[this.m_data.numAttributes()]; String type; this.m_classAttrib.removeAllItems(); for (int i = 0; i < tempAttribNames.length; i++) { type = " (" + Attribute.typeToStringShort(this.m_data.attribute(i)) + ")"; tempAttribNames[i] = new String("Colour: " + this.m_data.attribute(i).name() + " " + type); this.m_classAttrib.addItem(tempAttribNames[i]); } if (this.m_data.classIndex() == -1) { this.m_classAttrib.setSelectedIndex(tempAttribNames.length - 1); } else { this.m_classAttrib.setSelectedIndex(this.m_data.classIndex()); } this.m_attribList.setListData(tempAttribNames); this.m_attribList.setSelectionInterval(0, tempAttribNames.length - 1); } /** * Calculates the percentage to resample */ public void setPercent() { if (this.m_data.numInstances() > 700) { double percnt = 500D / this.m_data.numInstances() * 100; percnt *= 100; percnt = Math.round(percnt); percnt /= 100; this.m_resamplePercent.setText("" + percnt); } else { this.m_resamplePercent.setText("100"); } } /** * This method changes the Instances object of this class to a new one. It * also does all the necessary initializations for displaying the panel. This * must be called before trying to display the panel. * * @param newInst The new set of Instances */ public void setInstances(final Instances newInst) { this.m_osi = null; this.m_fastScroll.setSelected(false); this.m_data = newInst; this.setPercent(); this.setupAttribLists(); this.m_rseed.setText("1"); this.initInternalFields(); this.m_cp.setInstances(this.m_data); this.m_cp.setCindex(this.m_classIndex); this.m_updateBt.doClick(); } /** * Main method for testing this class */ public static void main(final String[] args) { final JFrame jf = new JFrame("Weka Explorer: MatrixPanel"); final JButton setBt = new JButton("Set Instances"); Instances data = null; try { if (args.length == 1) { data = new Instances(new BufferedReader(new FileReader(args[0]))); } else { System.out.println("Usage: MatrixPanel <arff file>"); System.exit(-1); } } catch (IOException ex) { ex.printStackTrace(); System.exit(-1); } final MatrixPanel mp = new MatrixPanel(); mp.setInstances(data); setBt.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { JFileChooser chooser = new JFileChooser(new java.io.File(System.getProperty("user.dir"))); ExtensionFileFilter myfilter = new ExtensionFileFilter("arff", "Arff data files"); chooser.setFileFilter(myfilter); int returnVal = chooser.showOpenDialog(jf); if (returnVal == JFileChooser.APPROVE_OPTION) { try { System.out.println("You chose to open this file: " + chooser.getSelectedFile().getName()); Instances in = new Instances(new FileReader(chooser.getSelectedFile().getAbsolutePath())); mp.setInstances(in); } catch (Exception ex) { ex.printStackTrace(); } } } }); // System.out.println("Loaded: "+args[0]+"\nRelation: "+data.relationName()+"\nAttributes: "+data.numAttributes()); // System.out.println("The attributes are: "); // for(int i=0; i<data.numAttributes(); i++) // System.out.println(data.attribute(i).name()); // RepaintManager.currentManager(jf.getRootPane()).setDoubleBufferingEnabled(false); jf.getContentPane().setLayout(new BorderLayout()); jf.getContentPane().add(mp, BorderLayout.CENTER); jf.getContentPane().add(setBt, BorderLayout.SOUTH); jf.getContentPane().setFont(new java.awt.Font("SansSerif", java.awt.Font.PLAIN, 11)); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jf.setSize(800, 600); jf.setVisible(true); jf.repaint(); } /** * Internal class responsible for displaying the actual matrix Requires the * internal data fields of the parent class to be properly initialized before * being created */ private class Plot extends JPanel implements MouseMotionListener, MouseListener { /** for serialization */ private static final long serialVersionUID = -1721245738439420882L; int extpad = 3, intpad = 4, cellSize = 100, cellRange = 100; java.awt.Rectangle r; java.awt.FontMetrics fm; int lastxpos, lastypos; JPanel jPlColHeader, jPlRowHeader; /** * Constructor */ public Plot() { super(); this.setToolTipText("blah"); this.addMouseMotionListener(this); this.addMouseListener(this); this.initialize(); } /** Initializes the internal fields */ public void initialize() { this.lastxpos = this.lastypos = 0; this.cellRange = this.cellSize; this.cellSize = this.cellRange + 2 * this.intpad; this.jPlColHeader = new JPanel() { private static final long serialVersionUID = -9098547751937467506L; java.awt.Rectangle r; @Override public void paint(final Graphics g) { this.r = g.getClipBounds(); g.setColor(this.getBackground()); g.fillRect(this.r.x, this.r.y, this.r.width, this.r.height); g.setFont(MatrixPanel.this.f); Plot.this.fm = g.getFontMetrics(); int xpos = 0, ypos = 0, attribWidth = 0; g.setColor(MatrixPanel.this.fontColor); xpos = Plot.this.extpad; ypos = Plot.this.extpad + Plot.this.fm.getHeight(); for (int m_selectedAttrib : MatrixPanel.this.m_selectedAttribs) { if (xpos + Plot.this.cellSize < this.r.x) { xpos += Plot.this.cellSize + Plot.this.extpad; continue; } else if (xpos > this.r.x + this.r.width) { break; } else { attribWidth = Plot.this.fm.stringWidth(MatrixPanel.this.m_data.attribute(m_selectedAttrib).name()); g.drawString(MatrixPanel.this.m_data.attribute(m_selectedAttrib).name(), (attribWidth < Plot.this.cellSize) ? (xpos + (Plot.this.cellSize / 2 - attribWidth / 2)) : xpos, ypos); } xpos += Plot.this.cellSize + Plot.this.extpad; } Plot.this.fm = null; this.r = null; } @Override public Dimension getPreferredSize() { Plot.this.fm = this.getFontMetrics(this.getFont()); return new Dimension(MatrixPanel.this.m_selectedAttribs.length * (Plot.this.cellSize + Plot.this.extpad), 2 * Plot.this.extpad + Plot.this.fm.getHeight()); } }; this.jPlRowHeader = new JPanel() { private static final long serialVersionUID = 8474957069309552844L; java.awt.Rectangle r; @Override public void paint(final Graphics g) { this.r = g.getClipBounds(); g.setColor(this.getBackground()); g.fillRect(this.r.x, this.r.y, this.r.width, this.r.height); g.setFont(MatrixPanel.this.f); Plot.this.fm = g.getFontMetrics(); int xpos = 0, ypos = 0; g.setColor(MatrixPanel.this.fontColor); xpos = Plot.this.extpad; ypos = Plot.this.extpad; for (int j = MatrixPanel.this.m_selectedAttribs.length - 1; j >= 0; j--) { if (ypos + Plot.this.cellSize < this.r.y) { ypos += Plot.this.cellSize + Plot.this.extpad; continue; } else if (ypos > this.r.y + this.r.height) { break; } else { g.drawString(MatrixPanel.this.m_data.attribute(MatrixPanel.this.m_selectedAttribs[j]).name(), xpos + Plot.this.extpad, ypos + Plot.this.cellSize / 2); } xpos = Plot.this.extpad; ypos += Plot.this.cellSize + Plot.this.extpad; } this.r = null; } @Override public Dimension getPreferredSize() { return new Dimension(100 + Plot.this.extpad, MatrixPanel.this.m_selectedAttribs.length * (Plot.this.cellSize + Plot.this.extpad)); } }; this.jPlColHeader.setFont(MatrixPanel.this.f); this.jPlRowHeader.setFont(MatrixPanel.this.f); this.setFont(MatrixPanel.this.f); } public JPanel getRowHeader() { return this.jPlRowHeader; } public JPanel getColHeader() { return this.jPlColHeader; } @Override public void mouseMoved(final MouseEvent e) { Graphics g = this.getGraphics(); int xpos = this.extpad, ypos = this.extpad; for (int j = MatrixPanel.this.m_selectedAttribs.length - 1; j >= 0; j--) { for (@SuppressWarnings("unused") int m_selectedAttrib : MatrixPanel.this.m_selectedAttribs) { if (e.getX() >= xpos && e.getX() <= xpos + this.cellSize + this.extpad) { if (e.getY() >= ypos && e.getY() <= ypos + this.cellSize + this.extpad) { if (xpos != this.lastxpos || ypos != this.lastypos) { g.setColor(Color.red); g.drawRect(xpos - 1, ypos - 1, this.cellSize + 1, this.cellSize + 1); if (this.lastxpos != 0 && this.lastypos != 0) { g.setColor(this.getBackground().darker()); g.drawRect(this.lastxpos - 1, this.lastypos - 1, this.cellSize + 1, this.cellSize + 1); } this.lastxpos = xpos; this.lastypos = ypos; } return; } } xpos += this.cellSize + this.extpad; } xpos = this.extpad; ypos += this.cellSize + this.extpad; } if (this.lastxpos != 0 && this.lastypos != 0) { g.setColor(this.getBackground().darker()); g.drawRect(this.lastxpos - 1, this.lastypos - 1, this.cellSize + 1, this.cellSize + 1); } this.lastxpos = this.lastypos = 0; } @Override public void mouseDragged(final MouseEvent e) { } @Override public void mouseClicked(final MouseEvent e) { int i = 0, j = 0, found = 0; int xpos = this.extpad, ypos = this.extpad; for (j = MatrixPanel.this.m_selectedAttribs.length - 1; j >= 0; j--) { for (i = 0; i < MatrixPanel.this.m_selectedAttribs.length; i++) { if (e.getX() >= xpos && e.getX() <= xpos + this.cellSize + this.extpad) { if (e.getY() >= ypos && e.getY() <= ypos + this.cellSize + this.extpad) { found = 1; break; } } xpos += this.cellSize + this.extpad; } if (found == 1) { break; } xpos = this.extpad; ypos += this.cellSize + this.extpad; } if (found == 0) { return; } JFrame jf = Utils.getWekaJFrame("Weka Explorer: Visualizing " + MatrixPanel.this.m_data.relationName(), this); VisualizePanel vp = new VisualizePanel(); try { PlotData2D pd = new PlotData2D(MatrixPanel.this.m_data); pd.setPlotName("Master Plot"); vp.setMasterPlot(pd); // System.out.println("x: "+i+" y: "+j); vp.setXIndex(MatrixPanel.this.m_selectedAttribs[i]); vp.setYIndex(MatrixPanel.this.m_selectedAttribs[j]); vp.m_ColourCombo.setSelectedIndex(MatrixPanel.this.m_classIndex); if (MatrixPanel.this.m_settings != null) { vp.applySettings(MatrixPanel.this.m_settings, MatrixPanel.this.m_settingsOwnerID); } } catch (Exception ex) { ex.printStackTrace(); } jf.getContentPane().add(vp); jf.pack(); jf.setSize(800, 600); jf.setLocationRelativeTo(SwingUtilities.getWindowAncestor(this)); jf.setVisible(true); } @Override public void mouseEntered(final MouseEvent e) { } @Override public void mouseExited(final MouseEvent e) { } @Override public void mousePressed(final MouseEvent e) { } @Override public void mouseReleased(final MouseEvent e) { } /** * sets the new jitter value for the plots */ public void setJitter(final int newjitter) { } /** * sets the new size for the plots */ public void setCellSize(final int newCellSize) { this.cellSize = newCellSize; this.initialize(); } /** * Returns the X and Y attributes of the plot the mouse is currently on */ @Override public String getToolTipText(final MouseEvent event) { int xpos = this.extpad, ypos = this.extpad; for (int j = MatrixPanel.this.m_selectedAttribs.length - 1; j >= 0; j--) { for (int m_selectedAttrib : MatrixPanel.this.m_selectedAttribs) { if (event.getX() >= xpos && event.getX() <= xpos + this.cellSize + this.extpad) { if (event.getY() >= ypos && event.getY() <= ypos + this.cellSize + this.extpad) { return ("X: " + MatrixPanel.this.m_data.attribute(m_selectedAttrib).name() + " Y: " + MatrixPanel.this.m_data.attribute(MatrixPanel.this.m_selectedAttribs[j]).name() + " (click to enlarge)"); } } xpos += this.cellSize + this.extpad; } xpos = this.extpad; ypos += this.cellSize + this.extpad; } return ("Matrix Panel"); } /** * Paints a single Plot at xpos, ypos. and xattrib and yattrib on X and Y * axes */ public void paintGraph(final Graphics g, final int xattrib, final int yattrib, final int xpos, final int ypos) { int x, y; g.setColor(MatrixPanel.this.m_backgroundColor.equals(Color.BLACK) ? MatrixPanel.this.m_backgroundColor.brighter().brighter() : MatrixPanel.this.m_backgroundColor.darker().darker()); g.drawRect(xpos - 1, ypos - 1, this.cellSize + 1, this.cellSize + 1); g.setColor(MatrixPanel.this.m_backgroundColor); g.fillRect(xpos, ypos, this.cellSize, this.cellSize); for (int i = 0; i < MatrixPanel.this.m_points.length; i++) { if (!(MatrixPanel.this.m_missing[i][yattrib] || MatrixPanel.this.m_missing[i][xattrib])) { if (MatrixPanel.this.m_type[0] == 0) { if (MatrixPanel.this.m_missing[i][MatrixPanel.this.m_missing[0].length - 1]) { g.setColor(m_defaultColors[m_defaultColors.length - 1]); } else { g.setColor(new Color(MatrixPanel.this.m_pointColors[i], 150, (255 - MatrixPanel.this.m_pointColors[i]))); } } else { g.setColor(MatrixPanel.this.m_colorList.get(MatrixPanel.this.m_pointColors[i])); } if (MatrixPanel.this.m_points[i][xattrib] + MatrixPanel.this.jitterVals[i][0] < 0 || MatrixPanel.this.m_points[i][xattrib] + MatrixPanel.this.jitterVals[i][0] > this.cellRange) { if (this.cellRange - MatrixPanel.this.m_points[i][yattrib] + MatrixPanel.this.jitterVals[i][1] < 0 || this.cellRange - MatrixPanel.this.m_points[i][yattrib] + MatrixPanel.this.jitterVals[i][1] > this.cellRange) { // both x and y out of range don't add jitter x = this.intpad + MatrixPanel.this.m_points[i][xattrib]; y = this.intpad + (this.cellRange - MatrixPanel.this.m_points[i][yattrib]); } else { // only x out of range x = this.intpad + MatrixPanel.this.m_points[i][xattrib]; y = this.intpad + (this.cellRange - MatrixPanel.this.m_points[i][yattrib]) + MatrixPanel.this.jitterVals[i][1]; } } else if (this.cellRange - MatrixPanel.this.m_points[i][yattrib] + MatrixPanel.this.jitterVals[i][1] < 0 || this.cellRange - MatrixPanel.this.m_points[i][yattrib] + MatrixPanel.this.jitterVals[i][1] > this.cellRange) { // only y out of range x = this.intpad + MatrixPanel.this.m_points[i][xattrib] + MatrixPanel.this.jitterVals[i][0]; y = this.intpad + (this.cellRange - MatrixPanel.this.m_points[i][yattrib]); } else { // none out of range x = this.intpad + MatrixPanel.this.m_points[i][xattrib] + MatrixPanel.this.jitterVals[i][0]; y = this.intpad + (this.cellRange - MatrixPanel.this.m_points[i][yattrib]) + MatrixPanel.this.jitterVals[i][1]; } if (MatrixPanel.this.datapointSize == 1) { g.drawLine(x + xpos, y + ypos, x + xpos, y + ypos); } else { g.drawOval(x + xpos - MatrixPanel.this.datapointSize / 2, y + ypos - MatrixPanel.this.datapointSize / 2, MatrixPanel.this.datapointSize, MatrixPanel.this.datapointSize); } } } g.setColor(MatrixPanel.this.fontColor); } private void createOSI() { int iwidth = this.getWidth(); int iheight = this.getHeight(); MatrixPanel.this.m_osi = this.createImage(iwidth, iheight); this.clearOSI(); } private void clearOSI() { if (MatrixPanel.this.m_osi == null) { return; } int iwidth = this.getWidth(); int iheight = this.getHeight(); Graphics m = MatrixPanel.this.m_osi.getGraphics(); m.setColor(this.getBackground().darker().darker()); m.fillRect(0, 0, iwidth, iheight); } /** * Paints the matrix of plots in the current visible region */ public void paintME(final Graphics g) { Graphics g2 = g; if (MatrixPanel.this.m_osi == null && MatrixPanel.this.m_fastScroll.isSelected()) { this.createOSI(); } if (MatrixPanel.this.m_osi != null && MatrixPanel.this.m_fastScroll.isSelected()) { g2 = MatrixPanel.this.m_osi.getGraphics(); } this.r = g.getClipBounds(); g.setColor(this.getBackground()); g.fillRect(this.r.x, this.r.y, this.r.width, this.r.height); g.setColor(MatrixPanel.this.fontColor); int xpos = 0, ypos = 0; xpos = this.extpad; ypos = this.extpad; for (int j = MatrixPanel.this.m_selectedAttribs.length - 1; j >= 0; j--) { if (ypos + this.cellSize < this.r.y) { ypos += this.cellSize + this.extpad; continue; } else if (ypos > this.r.y + this.r.height) { break; } else { for (int i = 0; i < MatrixPanel.this.m_selectedAttribs.length; i++) { if (xpos + this.cellSize < this.r.x) { xpos += this.cellSize + this.extpad; continue; } else if (xpos > this.r.x + this.r.width) { break; } else if (MatrixPanel.this.m_fastScroll.isSelected()) { if (!MatrixPanel.this.m_plottedCells[i][j]) { this.paintGraph(g2, i, j, xpos, ypos); // m_selectedAttribs[i], // m_selectedAttribs[j], xpos, // ypos); MatrixPanel.this.m_plottedCells[i][j] = true; } } else { this.paintGraph(g2, i, j, xpos, ypos); } xpos += this.cellSize + this.extpad; } } xpos = this.extpad; ypos += this.cellSize + this.extpad; } } /** * paints this JPanel (PlotsPanel) */ @Override public void paintComponent(final Graphics g) { this.paintME(g); if (MatrixPanel.this.m_osi != null && MatrixPanel.this.m_fastScroll.isSelected()) { g.drawImage(MatrixPanel.this.m_osi, 0, 0, this); } } } /** * Set the point size for the plots * * @param pointSize the point size to use */ public void setPointSize(final int pointSize) { if (pointSize <= this.m_pointSize.getMaximum() && pointSize > this.m_pointSize.getMinimum()) { this.m_pointSize.setValue(pointSize); } } /** * Set the plot size * * @param plotSize the plot size to use */ public void setPlotSize(final int plotSize) { if (plotSize >= this.m_plotSize.getMinimum() && plotSize <= this.m_plotSize.getMaximum()) { this.m_plotSize.setValue(plotSize); } } /** * Set the background colour for the cells in the matrix * * @param c the background colour */ public void setPlotBackgroundColour(final Color c) { this.m_backgroundColor = c; } /** * @param settings * @param ownerID */ public void applySettings(final Settings settings, final String ownerID) { this.m_settings = settings; this.m_settingsOwnerID = ownerID; this.setPointSize(settings.getSetting(ownerID, weka.gui.explorer.VisualizePanel.ScatterDefaults.POINT_SIZE_KEY, weka.gui.explorer.VisualizePanel.ScatterDefaults.POINT_SIZE, Environment.getSystemWide())); this.setPlotSize(settings.getSetting(ownerID, weka.gui.explorer.VisualizePanel.ScatterDefaults.PLOT_SIZE_KEY, weka.gui.explorer.VisualizePanel.ScatterDefaults.PLOT_SIZE, Environment.getSystemWide())); this.setPlotBackgroundColour(settings.getSetting(ownerID, VisualizeUtils.VisualizeDefaults.BACKGROUND_COLOUR_KEY, VisualizeUtils.VisualizeDefaults.BACKGROUND_COLOR, Environment.getSystemWide())); } /** * Update the display. Typically called after changing plot size, point size * etc. */ public void updatePanel() { // m_selectedAttribs = m_attribList.getSelectedIndices(); this.initInternalFields(); Plot a = this.m_plotsPanel; a.setCellSize(this.m_plotSize.getValue()); Dimension d = new Dimension((this.m_selectedAttribs.length) * (a.cellSize + a.extpad) + 2, (this.m_selectedAttribs.length) * (a.cellSize + a.extpad) + 2); // System.out.println("Size: "+a.cellSize+" Extpad: "+ // a.extpad+" selected: "+ // m_selectedAttribs.length+' '+d); a.setPreferredSize(d); a.setSize(a.getPreferredSize()); a.setJitter(this.m_jitter.getValue()); if (this.m_fastScroll.isSelected() && this.m_clearOSIPlottedCells) { this.m_plottedCells = new boolean[this.m_selectedAttribs.length][this.m_selectedAttribs.length]; this.m_clearOSIPlottedCells = false; } if (this.m_regenerateOSI) { this.m_osi = null; } this.m_js.revalidate(); this.m_cp.setColours(this.m_colorList); this.m_cp.setCindex(this.m_classIndex); this.m_regenerateOSI = false; this.repaint(); } }
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/visualize/PNGWriter.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * PNGWriter.java * Copyright (C) 2007-2012 University of Waikato, Hamilton, New Zealand */ package weka.gui.visualize; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import javax.imageio.ImageIO; import javax.swing.JComponent; /** * This class takes any JComponent and outputs it to a PNG-file. * Scaling is by default disabled, since we always take a screenshot. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class PNGWriter extends JComponentWriter { /** the background color. */ protected Color m_Background; /** * initializes the object. */ public PNGWriter() { super(); } /** * initializes the object with the given Component. * * @param c the component to print in the output format */ public PNGWriter(JComponent c) { super(c); } /** * initializes the object with the given Component and filename. * * @param c the component to print in the output format * @param f the file to store the output in */ public PNGWriter(JComponent c, File f) { super(c, f); } /** * further initialization. */ public void initialize() { super.initialize(); setScalingEnabled(false); } /** * returns the name of the writer, to display in the FileChooser. * must be overridden in the derived class. * * @return the name of the writer */ public String getDescription() { return "PNG-Image"; } /** * returns the extension (incl. ".") of the output format, to use in the * FileChooser. * * @return the file extension */ public String getExtension() { return ".png"; } /** * returns the current background color. * * @return the current background color */ public Color getBackground() { return m_Background; } /** * sets the background color to use in creating the PNG. * * @param c the color to use for background */ public void setBackground(Color c) { m_Background = c; } /** * generates the actual output. * * @throws Exception if something goes wrong */ public void generateOutput() throws Exception { BufferedImage bi; Graphics g; bi = new BufferedImage(getComponent().getWidth(), getComponent().getHeight(), BufferedImage.TYPE_INT_RGB); g = bi.getGraphics(); g.setPaintMode(); g.setColor(getBackground()); if (g instanceof Graphics2D) ((Graphics2D) g).scale(getXScale(), getYScale()); g.fillRect(0, 0, getComponent().getWidth(), getComponent().getHeight()); getComponent().printAll(g); ImageIO.write(bi, "png", getFile()); } /** * for testing only. * * @param args the commandline arguments * @throws Exception if something goes wrong */ public static void main(String[] args) throws Exception { System.out.println("building TreeVisualizer..."); weka.gui.treevisualizer.TreeBuild builder = new weka.gui.treevisualizer.TreeBuild(); weka.gui.treevisualizer.NodePlace arrange = new weka.gui.treevisualizer.PlaceNode2(); weka.gui.treevisualizer.Node top = builder.create(new java.io.StringReader("digraph atree { top [label=\"the top\"] a [label=\"the first node\"] b [label=\"the second nodes\"] c [label=\"comes off of first\"] top->a top->b b->c }")); weka.gui.treevisualizer.TreeVisualizer tv = new weka.gui.treevisualizer.TreeVisualizer(null, top, arrange); tv.setSize(800 ,600); String filename = System.getProperty("java.io.tmpdir") + File.separator + "test.png"; System.out.println("outputting to '" + filename + "'..."); toOutput(new PNGWriter(), tv, new File(filename)); System.out.println("done!"); } }
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/visualize/Plot2D.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * Plot2D.java * Copyright (C) 2000-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.visualize; import weka.core.Environment; import weka.core.Instance; import weka.core.Instances; import weka.core.Settings; import weka.core.Utils; import javax.swing.JFrame; import javax.swing.JPanel; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.event.InputEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.ArrayList; import java.util.Random; import java.util.Vector; /** * This class plots datasets in two dimensions. It can also plot classifier * errors and clusterer predictions. * * @author Mark Hall (mhall@cs.waikato.ac.nz) * @version $Revision$ */ public class Plot2D extends JPanel { /** for serialization */ private static final long serialVersionUID = -1673162410856660442L; /* constants for shape types */ public static final int MAX_SHAPES = 5; public static final int ERROR_SHAPE = 1000; public static final int MISSING_SHAPE = 2000; public static final int CONST_AUTOMATIC_SHAPE = -1; public static final int X_SHAPE = 0; public static final int PLUS_SHAPE = 1; public static final int DIAMOND_SHAPE = 2; public static final int TRIANGLEUP_SHAPE = 3; public static final int TRIANGLEDOWN_SHAPE = 4; public static final int DEFAULT_SHAPE_SIZE = 2; /** Default colour for the axis */ protected Color m_axisColour = Color.green; /** Default colour for the plot background */ protected Color m_backgroundColour = Color.black; /** The plots to display */ protected ArrayList<PlotData2D> m_plots = new ArrayList<PlotData2D>(); /** The master plot */ protected PlotData2D m_masterPlot = null; /** The name of the master plot */ protected String m_masterName = "master plot"; /** The instances to be plotted */ protected Instances m_plotInstances = null; /** * An optional "compainion" of the panel. If specified, this class will get to * do its thing with our graphics context before we do any drawing. Eg. the * visualize panel may need to draw polygons etc. before we draw plot axis and * data points */ protected Plot2DCompanion m_plotCompanion = null; /** the class for displaying instance info. */ protected Class<?> m_InstanceInfoFrameClass = null; /** For popping up text info on data points */ protected JFrame m_InstanceInfo = null; /** The list of the colors used */ protected ArrayList<Color> m_colorList; /** default colours for colouring discrete class */ protected Color[] m_DefaultColors = { Color.blue, Color.red, Color.green, Color.cyan, Color.pink, new Color(255, 0, 255), Color.orange, new Color(255, 0, 0), new Color(0, 255, 0), Color.white }; /** * Indexes of the attributes to go on the x and y axis and the attribute to * use for colouring and the current shape for drawing */ protected int m_xIndex = 0; protected int m_yIndex = 0; protected int m_cIndex = 0; protected int m_sIndex = 0; /** * Holds the min and max values of the x, y and colouring attributes over all * plots */ protected double m_maxX; protected double m_minX; protected double m_maxY; protected double m_minY; protected double m_maxC; protected double m_minC; /** Axis padding */ protected final int m_axisPad = 5; /** Tick size */ protected final int m_tickSize = 5; /** the offsets of the axes once label metrics are calculated */ protected int m_XaxisStart = 0; protected int m_YaxisStart = 0; protected int m_XaxisEnd = 0; protected int m_YaxisEnd = 0; /** * if the user resizes the window, or the attributes selected for the * attributes change, then the lookup table for points needs to be * recalculated */ protected boolean m_plotResize = true; /** if the user changes attribute assigned to an axis */ protected boolean m_axisChanged = false; /** * An array used to show if a point is hidden or not. This is used for * speeding up the drawing of the plot panel although I am not sure how much * performance this grants over not having it. */ protected int[][] m_drawnPoints; /** Font for labels */ protected Font m_labelFont; protected FontMetrics m_labelMetrics = null; /** the level of jitter */ protected int m_JitterVal = 0; /** random values for perterbing the data points */ protected Random m_JRand = new Random(0); /** Constructor */ public Plot2D() { super(); setProperties(); this.setBackground(m_backgroundColour); m_drawnPoints = new int[this.getWidth()][this.getHeight()]; /** Set up some default colours */ m_colorList = new ArrayList<Color>(10); for (int noa = m_colorList.size(); noa < 10; noa++) { Color pc = m_DefaultColors[noa % 10]; int ija = noa / 10; ija *= 2; for (int j = 0; j < ija; j++) { pc = pc.darker(); } m_colorList.add(pc); } } /** * Set the properties for Plot2D */ private void setProperties() { if (VisualizeUtils.VISUALIZE_PROPERTIES != null) { String thisClass = this.getClass().getName(); String axisKey = thisClass + ".axisColour"; String backgroundKey = thisClass + ".backgroundColour"; String axisColour = VisualizeUtils.VISUALIZE_PROPERTIES.getProperty(axisKey); if (axisColour == null) { /* * System.err.println("Warning: no configuration property found in " * +VisualizeUtils.PROPERTY_FILE +" for "+axisKey); */ } else { // System.err.println("Setting axis colour to: "+axisColour); m_axisColour = VisualizeUtils.processColour(axisColour, m_axisColour); } String backgroundColour = VisualizeUtils.VISUALIZE_PROPERTIES.getProperty(backgroundKey); if (backgroundColour == null) { /* * System.err.println("Warning: no configuration property found in " * +VisualizeUtils.PROPERTY_FILE +" for "+backgroundKey); */ } else { // System.err.println("Setting background colour to: "+backgroundColour); m_backgroundColour = VisualizeUtils.processColour(backgroundColour, m_backgroundColour); } try { m_InstanceInfoFrameClass = Class.forName(VisualizeUtils.VISUALIZE_PROPERTIES.getProperty( thisClass + ".instanceInfoFrame", "weka.gui.visualize.InstanceInfoFrame")); } catch (Exception e) { e.printStackTrace(); m_InstanceInfoFrameClass = InstanceInfoFrame.class; } } } /** * Apply settings * * @param settings the settings to apply * @param ownerID the ID of the owner perspective, panel etc. to use when * looking up our settings */ public void applySettings(Settings settings, String ownerID) { m_axisColour = settings.getSetting(ownerID, VisualizeUtils.VisualizeDefaults.AXIS_COLOUR_KEY, VisualizeUtils.VisualizeDefaults.AXIS_COLOR, Environment.getSystemWide()); m_backgroundColour = settings.getSetting(ownerID, VisualizeUtils.VisualizeDefaults.BACKGROUND_COLOUR_KEY, VisualizeUtils.VisualizeDefaults.BACKGROUND_COLOR, Environment.getSystemWide()); this.setBackground(m_backgroundColour); repaint(); } /** * Set a companion class. This is a class that might want to render something * on the plot before we do our thing. Eg, Malcolm's shape drawing stuff needs * to happen before we plot axis and points * * @param p a companion class */ public void setPlotCompanion(Plot2DCompanion p) { m_plotCompanion = p; } /** * Set level of jitter and repaint the plot using the new jitter value * * @param j the level of jitter */ public void setJitter(int j) { if (m_plotInstances.numAttributes() > 0 && m_plotInstances.numInstances() > 0) { if (j >= 0) { m_JitterVal = j; m_JRand = new Random(m_JitterVal); // if (m_pointLookup != null) { m_drawnPoints = new int[m_XaxisEnd - m_XaxisStart + 1][m_YaxisEnd - m_YaxisStart + 1]; updatePturb(); // } this.repaint(); } } } /** * Set a list of colours to use when colouring points according to class * values or cluster numbers * * @param cols the list of colours to use */ public void setColours(ArrayList<Color> cols) { m_colorList = cols; } /** * Set the index of the attribute to go on the x axis * * @param x the index of the attribute to use on the x axis */ public void setXindex(int x) { m_xIndex = x; for (int i = 0; i < m_plots.size(); i++) { m_plots.get(i).setXindex(m_xIndex); } determineBounds(); if (m_JitterVal != 0) { updatePturb(); } m_axisChanged = true; this.repaint(); } /** * Set the index of the attribute to go on the y axis * * @param y the index of the attribute to use on the y axis */ public void setYindex(int y) { m_yIndex = y; for (int i = 0; i < m_plots.size(); i++) { m_plots.get(i).setYindex(m_yIndex); } determineBounds(); if (m_JitterVal != 0) { updatePturb(); } m_axisChanged = true; this.repaint(); } /** * Set the index of the attribute to use for colouring * * @param c the index of the attribute to use for colouring */ public void setCindex(int c) { m_cIndex = c; for (int i = 0; i < m_plots.size(); i++) { m_plots.get(i).setCindex(m_cIndex); } determineBounds(); m_axisChanged = true; this.repaint(); } /** * Return the list of plots * * @return the list of plots */ public ArrayList<PlotData2D> getPlots() { return m_plots; } /** * Get the master plot * * @return the master plot */ public PlotData2D getMasterPlot() { return m_masterPlot; } /** * Return the current max value of the attribute plotted on the x axis * * @return the max x value */ public double getMaxX() { return m_maxX; } /** * Return the current max value of the attribute plotted on the y axis * * @return the max y value */ public double getMaxY() { return m_maxY; } /** * Return the current min value of the attribute plotted on the x axis * * @return the min x value */ public double getMinX() { return m_minX; } /** * Return the current min value of the attribute plotted on the y axis * * @return the min y value */ public double getMinY() { return m_minY; } /** * Return the current max value of the colouring attribute * * @return the max colour value */ public double getMaxC() { return m_maxC; } /** * Return the current min value of the colouring attribute * * @return the min colour value */ public double getMinC() { return m_minC; } /** * Sets the master plot from a set of instances * * @param inst the instances * @exception Exception if instances could not be set */ public void setInstances(Instances inst) throws Exception { // System.err.println("Setting Instances"); PlotData2D tempPlot = new PlotData2D(inst); tempPlot.setPlotName("master plot"); setMasterPlot(tempPlot); } /** * Set the master plot. * * @param master the plot to make the master plot * @exception Exception if the plot could not be set. */ public void setMasterPlot(PlotData2D master) throws Exception { if (master.m_plotInstances == null) { throw new Exception("No instances in plot data!"); } removeAllPlots(); m_masterPlot = master; m_plots.add(m_masterPlot); m_plotInstances = m_masterPlot.m_plotInstances; m_xIndex = 0; m_yIndex = 0; m_cIndex = 0; determineBounds(); } /** * Clears all plots */ public void removeAllPlots() { m_masterPlot = null; m_plotInstances = null; m_plots = new ArrayList<PlotData2D>(); m_xIndex = 0; m_yIndex = 0; m_cIndex = 0; } /** * Add a plot to the list of plots to display * * @param newPlot the new plot to add * @exception Exception if the plot could not be added */ public void addPlot(PlotData2D newPlot) throws Exception { if (newPlot.m_plotInstances == null) { throw new Exception("No instances in plot data!"); } if (m_masterPlot != null) { if (m_masterPlot.m_plotInstances.equalHeaders(newPlot.m_plotInstances) == false) { throw new Exception("Plot2D :Plot data's instances are incompatable " + " with master plot"); } } else { m_masterPlot = newPlot; m_plotInstances = m_masterPlot.m_plotInstances; } m_plots.add(newPlot); setXindex(m_xIndex); setYindex(m_yIndex); setCindex(m_cIndex); } /** * Set up fonts and font metrics * * @param gx the graphics context */ private void setFonts(Graphics gx) { if (m_labelMetrics == null) { m_labelFont = new Font("Monospaced", Font.PLAIN, 12); m_labelMetrics = gx.getFontMetrics(m_labelFont); } gx.setFont(m_labelFont); } /** * Pops up a window displaying attribute information on any instances at a * point+-plotting_point_size (in panel coordinates) * * @param x the x value of the clicked point * @param y the y value of the clicked point * @param newFrame true if instance info is to be displayed in a new frame. */ public void searchPoints(int x, int y, final boolean newFrame) { if (m_masterPlot.m_plotInstances != null) { int longest = 0; for (int j = 0; j < m_masterPlot.m_plotInstances.numAttributes(); j++) { if (m_masterPlot.m_plotInstances.attribute(j).name().length() > longest) { longest = m_masterPlot.m_plotInstances.attribute(j).name().length(); } } StringBuffer insts = new StringBuffer(); Vector<Instances> data = new Vector<Instances>(); for (int jj = 0; jj < m_plots.size(); jj++) { PlotData2D temp_plot = (m_plots.get(jj)); data.add(new Instances(temp_plot.m_plotInstances, 0)); for (int i = 0; i < temp_plot.m_plotInstances.numInstances(); i++) { if (temp_plot.m_pointLookup[i][0] != Double.NEGATIVE_INFINITY) { double px = temp_plot.m_pointLookup[i][0] + temp_plot.m_pointLookup[i][2]; double py = temp_plot.m_pointLookup[i][1] + temp_plot.m_pointLookup[i][3]; // double size = temp_plot.m_pointLookup[i][2]; double size = temp_plot.m_shapeSize[i]; if ((x >= px - size) && (x <= px + size) && (y >= py - size) && (y <= py + size)) { { data.get(jj).add( (Instance) temp_plot.m_plotInstances.instance(i).copy()); insts.append("\nPlot : " + temp_plot.m_plotName + "\nInstance: " + (i + 1) + "\n"); if (temp_plot.m_plotInstances.instance(i).weight() != 1.0) { insts.append("Weight : " + temp_plot.m_plotInstances.instance(i).weight() + "\n"); } for (int j = 0; j < temp_plot.m_plotInstances.numAttributes(); j++) { for (int k = 0; k < (longest - temp_plot.m_plotInstances .attribute(j).name().length()); k++) { insts.append(" "); } insts.append(temp_plot.m_plotInstances.attribute(j).name()); insts.append(" : "); if (temp_plot.m_plotInstances.instance(i).isMissing(j)) { insts.append("Missing"); } else if (temp_plot.m_plotInstances.attribute(j).isNominal() || temp_plot.m_plotInstances.attribute(j).isString()) { insts.append(temp_plot.m_plotInstances.attribute(j).value( (int) temp_plot.m_plotInstances.instance(i).value(j))); } else { insts .append(temp_plot.m_plotInstances.instance(i).value(j)); } insts.append("\n"); } } } } } } // remove datasets that contain no instances int i = 0; while (data.size() > i) { if (data.get(i).numInstances() == 0) { data.remove(i); } else { i++; } } if (insts.length() > 0) { // Pop up a new frame if (newFrame || m_InstanceInfo == null) { try { final JFrame jf = (JFrame) m_InstanceInfoFrameClass.newInstance(); ((InstanceInfo) jf).setInfoText(insts.toString()); ((InstanceInfo) jf).setInfoData(data); final JFrame testf = m_InstanceInfo; jf.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { if (!newFrame || testf == null) { m_InstanceInfo = null; } jf.dispose(); } }); jf.setVisible(true); if (m_InstanceInfo == null) { m_InstanceInfo = jf; } } catch (Exception e) { e.printStackTrace(); } } else { // Overwrite info in existing frame ((InstanceInfo) m_InstanceInfo).setInfoText(insts.toString()); ((InstanceInfo) m_InstanceInfo).setInfoData(data); } } } } /** * Determine the min and max values for axis and colouring attributes */ public void determineBounds() { double value; // , min, max; NOT USED // find maximums minimums over all plots m_minX = m_plots.get(0).m_minX; m_maxX = m_plots.get(0).m_maxX; m_minY = m_plots.get(0).m_minY; m_maxY = m_plots.get(0).m_maxY; m_minC = m_plots.get(0).m_minC; m_maxC = m_plots.get(0).m_maxC; for (int i = 1; i < m_plots.size(); i++) { value = m_plots.get(i).m_minX; if (value < m_minX) { m_minX = value; } value = m_plots.get(i).m_maxX; if (value > m_maxX) { m_maxX = value; } value = m_plots.get(i).m_minY; if (value < m_minY) { m_minY = value; } value = m_plots.get(i).m_maxY; if (value > m_maxY) { m_maxY = value; } value = m_plots.get(i).m_minC; if (value < m_minC) { m_minC = value; } value = m_plots.get(i).m_maxC; if (value > m_maxC) { m_maxC = value; } } fillLookup(); this.repaint(); } // to convert screen coords to attrib values // note that I use a double to avoid accuracy // headaches with ints /** * convert a Panel x coordinate to a raw x value. * * @param scx The Panel x coordinate * @return A raw x value. */ public double convertToAttribX(double scx) { double temp = m_XaxisEnd - m_XaxisStart; double temp2 = ((scx - m_XaxisStart) * (m_maxX - m_minX)) / temp; temp2 = temp2 + m_minX; return temp2; } /** * convert a Panel y coordinate to a raw y value. * * @param scy The Panel y coordinate * @return A raw y value. */ public double convertToAttribY(double scy) { double temp = m_YaxisEnd - m_YaxisStart; double temp2 = ((scy - m_YaxisEnd) * (m_maxY - m_minY)) / temp; temp2 = -(temp2 - m_minY); return temp2; } // //// /** * returns a value by which an x value can be peturbed. Makes sure that the x * value+pturb stays within the plot bounds * * @param xvalP the x coordinate to be peturbed * @param xj a random number to use in calculating a peturb value * @return a peturb value */ int pturbX(double xvalP, double xj) { int xpturb = 0; if (m_JitterVal > 0) { xpturb = (int) (m_JitterVal * (xj / 2.0)); if (((xvalP + xpturb) < m_XaxisStart) || ((xvalP + xpturb) > m_XaxisEnd)) { xpturb *= -1; } } return xpturb; } /** * Convert an raw x value to Panel x coordinate. * * @param xval the raw x value * @return an x value for plotting in the panel. */ public double convertToPanelX(double xval) { double temp = (xval - m_minX) / (m_maxX - m_minX); double temp2 = temp * (m_XaxisEnd - m_XaxisStart); temp2 = temp2 + m_XaxisStart; return temp2; } /** * returns a value by which a y value can be peturbed. Makes sure that the y * value+pturb stays within the plot bounds * * @param yvalP the y coordinate to be peturbed * @param yj a random number to use in calculating a peturb value * @return a peturb value */ int pturbY(double yvalP, double yj) { int ypturb = 0; if (m_JitterVal > 0) { ypturb = (int) (m_JitterVal * (yj / 2.0)); if (((yvalP + ypturb) < m_YaxisStart) || ((yvalP + ypturb) > m_YaxisEnd)) { ypturb *= -1; } } return ypturb; } /** * Convert an raw y value to Panel y coordinate. * * @param yval the raw y value * @return an y value for plotting in the panel. */ public double convertToPanelY(double yval) { double temp = (yval - m_minY) / (m_maxY - m_minY); double temp2 = temp * (m_YaxisEnd - m_YaxisStart); temp2 = m_YaxisEnd - temp2; return temp2; } /** * Draws an X. * * @param gx the graphics context * @param x the x coord * @param y the y coord * @param size the size of the shape */ private static void drawX(Graphics gx, double x, double y, int size) { gx.drawLine((int) (x - size), (int) (y - size), (int) (x + size), (int) (y + size)); gx.drawLine((int) (x + size), (int) (y - size), (int) (x - size), (int) (y + size)); } /** * Draws a plus. * * @param gx the graphics context * @param x the x coord * @param y the y coord * @param size the size of the shape */ private static void drawPlus(Graphics gx, double x, double y, int size) { gx.drawLine((int) (x - size), (int) (y), (int) (x + size), (int) (y)); gx.drawLine((int) (x), (int) (y - size), (int) (x), (int) (y + size)); } /** * Draws a diamond. * * @param gx the graphics context * @param x the x coord * @param y the y coord * @param size the size of the shape */ private static void drawDiamond(Graphics gx, double x, double y, int size) { gx.drawLine((int) (x - size), (int) (y), (int) (x), (int) (y - size)); gx.drawLine((int) (x), (int) (y - size), (int) (x + size), (int) (y)); gx.drawLine((int) (x + size), (int) (y), (int) (x), (int) (y + size)); gx.drawLine((int) (x), (int) (y + size), (int) (x - size), (int) (y)); } /** * Draws an triangle (point at top). * * @param gx the graphics context * @param x the x coord * @param y the y coord * @param size the size of the shape */ private static void drawTriangleUp(Graphics gx, double x, double y, int size) { gx.drawLine((int) (x), (int) (y - size), (int) (x - size), (int) (y + size)); gx.drawLine((int) (x - size), (int) (y + size), (int) (x + size), (int) (y + size)); gx.drawLine((int) (x + size), (int) (y + size), (int) (x), (int) (y - size)); } /** * Draws an triangle (point at bottom). * * @param gx the graphics context * @param x the x coord * @param y the y coord * @param size the size of the shape */ private static void drawTriangleDown(Graphics gx, double x, double y, int size) { gx.drawLine((int) (x), (int) (y + size), (int) (x - size), (int) (y - size)); gx.drawLine((int) (x - size), (int) (y - size), (int) (x + size), (int) (y - size)); gx.drawLine((int) (x + size), (int) (y - size), (int) (x), (int) (y + size)); } /** * Draws a data point at a given set of panel coordinates at a given size and * connects a line to the previous point. * * @param x the x coord * @param y the y coord * @param xprev the x coord of the previous point * @param yprev the y coord of the previous point * @param size the size of the point * @param shape the shape of the data point (square is reserved for nominal * error data points). Shapes: 0=x, 1=plus, 2=diamond, * 3=triangle(up), 4 = triangle (down). * @param gx the graphics context */ protected static void drawDataPoint(double x, double y, double xprev, double yprev, int size, int shape, Graphics gx) { drawDataPoint(x, y, size, shape, gx); // connect a line to the previous point gx.drawLine((int) x, (int) y, (int) xprev, (int) yprev); } /** * Draws a data point at a given set of panel coordinates at a given size. * * @param x the x coord * @param y the y coord * @param size the size of the point * @param shape the shape of the data point (square is reserved for nominal * error data points). Shapes: 0=x, 1=plus, 2=diamond, * 3=triangle(up), 4 = triangle (down). * @param gx the graphics context */ protected static void drawDataPoint(double x, double y, int size, int shape, Graphics gx) { Font lf = new Font("Monospaced", Font.PLAIN, 12); FontMetrics fm = gx.getFontMetrics(lf); if (size == 0) { size = 1; } if (shape != ERROR_SHAPE && shape != MISSING_SHAPE) { shape = shape % 5; } switch (shape) { case X_SHAPE: drawX(gx, x, y, size); break; case PLUS_SHAPE: drawPlus(gx, x, y, size); break; case DIAMOND_SHAPE: drawDiamond(gx, x, y, size); break; case TRIANGLEUP_SHAPE: drawTriangleUp(gx, x, y, size); break; case TRIANGLEDOWN_SHAPE: drawTriangleDown(gx, x, y, size); break; case ERROR_SHAPE: // draws the nominal error shape gx.drawRect((int) (x - size), (int) (y - size), (size * 2), (size * 2)); break; case MISSING_SHAPE: int hf = fm.getAscent(); int width = fm.stringWidth("M"); gx.drawString("M", (int) (x - (width / 2)), (int) (y + (hf / 2))); break; } } /** * Updates the perturbed values for the plots when the jitter value is changed */ private void updatePturb() { double xj = 0; double yj = 0; for (int j = 0; j < m_plots.size(); j++) { PlotData2D temp_plot = (m_plots.get(j)); for (int i = 0; i < temp_plot.m_plotInstances.numInstances(); i++) { if (temp_plot.m_plotInstances.instance(i).isMissing(m_xIndex) || temp_plot.m_plotInstances.instance(i).isMissing(m_yIndex)) { } else { if (m_JitterVal > 0) { xj = m_JRand.nextGaussian(); yj = m_JRand.nextGaussian(); } temp_plot.m_pointLookup[i][2] = pturbX(temp_plot.m_pointLookup[i][0], xj); temp_plot.m_pointLookup[i][3] = pturbY(temp_plot.m_pointLookup[i][1], yj); } } } } /** * Fills the lookup caches for the plots. Also calculates errors for numeric * predictions (if any) in plots */ private void fillLookup() { for (int j = 0; j < m_plots.size(); j++) { PlotData2D temp_plot = (m_plots.get(j)); if (temp_plot.m_plotInstances.numInstances() > 0 && temp_plot.m_plotInstances.numAttributes() > 0) { for (int i = 0; i < temp_plot.m_plotInstances.numInstances(); i++) { if (temp_plot.m_plotInstances.instance(i).isMissing(m_xIndex) || temp_plot.m_plotInstances.instance(i).isMissing(m_yIndex)) { temp_plot.m_pointLookup[i][0] = Double.NEGATIVE_INFINITY; temp_plot.m_pointLookup[i][1] = Double.NEGATIVE_INFINITY; } else { double x = convertToPanelX(temp_plot.m_plotInstances.instance(i).value( m_xIndex)); double y = convertToPanelY(temp_plot.m_plotInstances.instance(i).value( m_yIndex)); temp_plot.m_pointLookup[i][0] = x; temp_plot.m_pointLookup[i][1] = y; } } } } } /** * Draws the data points and predictions (if provided). * * @param gx the graphics context */ private void paintData(Graphics gx) { for (int j = 0; j < m_plots.size(); j++) { PlotData2D temp_plot = (m_plots.get(j)); for (int i = 0; i < temp_plot.m_plotInstances.numInstances(); i++) { if (temp_plot.m_plotInstances.instance(i).isMissing(m_xIndex) || temp_plot.m_plotInstances.instance(i).isMissing(m_yIndex)) { } else { double x = (temp_plot.m_pointLookup[i][0] + temp_plot.m_pointLookup[i][2]); double y = (temp_plot.m_pointLookup[i][1] + temp_plot.m_pointLookup[i][3]); double prevx = 0; double prevy = 0; if (i > 0) { prevx = (temp_plot.m_pointLookup[i - 1][0] + temp_plot.m_pointLookup[i - 1][2]); prevy = (temp_plot.m_pointLookup[i - 1][1] + temp_plot.m_pointLookup[i - 1][3]); } int x_range = (int) x - m_XaxisStart; int y_range = (int) y - m_YaxisStart; if (x_range >= 0 && y_range >= 0) { if (m_drawnPoints[x_range][y_range] == i || m_drawnPoints[x_range][y_range] == 0 || temp_plot.m_shapeSize[i] == temp_plot.m_alwaysDisplayPointsOfThisSize || temp_plot.m_displayAllPoints == true) { m_drawnPoints[x_range][y_range] = i; if (temp_plot.m_plotInstances.attribute(m_cIndex).isNominal()) { if (temp_plot.m_plotInstances.attribute(m_cIndex).numValues() > m_colorList .size() && !temp_plot.m_useCustomColour) { extendColourMap(temp_plot.m_plotInstances.attribute(m_cIndex) .numValues()); } Color ci; if (temp_plot.m_plotInstances.instance(i).isMissing(m_cIndex)) { ci = Color.gray; } else { int ind = (int) temp_plot.m_plotInstances.instance(i).value(m_cIndex); ci = m_colorList.get(ind); } if (!temp_plot.m_useCustomColour) { gx.setColor(ci); } else { gx.setColor(temp_plot.m_customColour); } if (temp_plot.m_plotInstances.instance(i).isMissing(m_cIndex)) { if (temp_plot.m_connectPoints[i] == true) { drawDataPoint(x, y, prevx, prevy, temp_plot.m_shapeSize[i], MISSING_SHAPE, gx); } else { drawDataPoint(x, y, temp_plot.m_shapeSize[i], MISSING_SHAPE, gx); } } else { if (temp_plot.m_shapeType[i] == CONST_AUTOMATIC_SHAPE) { if (temp_plot.m_connectPoints[i] == true) { drawDataPoint(x, y, prevx, prevy, temp_plot.m_shapeSize[i], j, gx); } else { drawDataPoint(x, y, temp_plot.m_shapeSize[i], j, gx); } } else { if (temp_plot.m_connectPoints[i] == true) { drawDataPoint(x, y, prevx, prevy, temp_plot.m_shapeSize[i], temp_plot.m_shapeType[i], gx); } else { drawDataPoint(x, y, temp_plot.m_shapeSize[i], temp_plot.m_shapeType[i], gx); } } } } else { double r; Color ci = null; if (!temp_plot.m_plotInstances.instance(i).isMissing(m_cIndex)) { r = (temp_plot.m_plotInstances.instance(i).value(m_cIndex) - m_minC) / (m_maxC - m_minC); r = (r * 240) + 15; ci = new Color((int) r, 150, (int) (255 - r)); } else { ci = Color.gray; } if (!temp_plot.m_useCustomColour) { gx.setColor(ci); } else { gx.setColor(temp_plot.m_customColour); } if (temp_plot.m_plotInstances.instance(i).isMissing(m_cIndex)) { if (temp_plot.m_connectPoints[i] == true) { drawDataPoint(x, y, prevx, prevy, temp_plot.m_shapeSize[i], MISSING_SHAPE, gx); } else { drawDataPoint(x, y, temp_plot.m_shapeSize[i], MISSING_SHAPE, gx); } } else { if (temp_plot.m_shapeType[i] == CONST_AUTOMATIC_SHAPE) { if (temp_plot.m_connectPoints[i] == true) { drawDataPoint(x, y, prevx, prevy, temp_plot.m_shapeSize[i], j, gx); } else { drawDataPoint(x, y, temp_plot.m_shapeSize[i], j, gx); } } else { if (temp_plot.m_connectPoints[i] == true) { drawDataPoint(x, y, prevx, prevy, temp_plot.m_shapeSize[i], temp_plot.m_shapeType[i], gx); } else { drawDataPoint(x, y, temp_plot.m_shapeSize[i], temp_plot.m_shapeType[i], gx); } } } } } } } } } } /* * public void determineAxisPositions(Graphics gx) { setFonts(gx); int mxs = * m_XaxisStart; int mxe = m_XaxisEnd; int mys = m_YaxisStart; int mye = * m_YaxisEnd; m_axisChanged = false; * * int h = this.getHeight(); int w = this.getWidth(); int hf = * m_labelMetrics.getAscent(); int mswx=0; int mswy=0; * * // determineBounds(); int fieldWidthX = * (int)((Math.log(m_maxX)/Math.log(10)))+1; int precisionX = 1; if * ((Math.abs(m_maxX-m_minX) < 1) && ((m_maxY-m_minX) != 0)) { precisionX = * (int)Math.abs(((Math.log(Math.abs(m_maxX-m_minX)) / Math.log(10))))+1; } * String maxStringX = Utils.doubleToString(m_maxX, fieldWidthX+1+precisionX * ,precisionX); mswx = m_labelMetrics.stringWidth(maxStringX); int * fieldWidthY = (int)((Math.log(m_maxY)/Math.log(10)))+1; int precisionY = 1; * if (Math.abs((m_maxY-m_minY)) < 1 && ((m_maxY-m_minY) != 0)) { precisionY = * (int)Math.abs(((Math.log(Math.abs(m_maxY-m_minY)) / Math.log(10))))+1; } * String maxStringY = Utils.doubleToString(m_maxY, fieldWidthY+1+precisionY * ,precisionY); String minStringY = Utils.doubleToString(m_minY, * fieldWidthY+1+precisionY ,precisionY); * * if (m_plotInstances.attribute(m_yIndex).isNumeric()) { mswy = * (m_labelMetrics.stringWidth(maxStringY) > * m_labelMetrics.stringWidth(minStringY)) ? * m_labelMetrics.stringWidth(maxStringY) : * m_labelMetrics.stringWidth(minStringY); } else { mswy = * m_labelMetrics.stringWidth("MM"); } * * m_YaxisStart = m_axisPad; m_XaxisStart = 0+m_axisPad+m_tickSize+mswy; * * m_XaxisEnd = w-m_axisPad-(mswx/2); * * m_YaxisEnd = h-m_axisPad-(2 * hf)-m_tickSize; } */ /** * Draws the axis and a spectrum if the colouring attribute is numeric * * @param gx the graphics context */ private void paintAxis(Graphics gx) { setFonts(gx); int mxs = m_XaxisStart; int mxe = m_XaxisEnd; int mys = m_YaxisStart; int mye = m_YaxisEnd; m_plotResize = false; int h = this.getHeight(); int w = this.getWidth(); int hf = m_labelMetrics.getAscent(); int mswx = 0; int mswy = 0; // determineBounds(); int precisionXmax = 1; int precisionXmin = 1; int precisionXmid = 1; /* * if ((Math.abs(m_maxX-m_minX) < 1) && ((m_maxY-m_minX) != 0)) { precisionX * = (int)Math.abs(((Math.log(Math.abs(m_maxX-m_minX)) / Math.log(10))))+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 > VisualizeUtils.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 > VisualizeUtils.MAX_PRECISION) { precisionXmin = 1; } String minStringX = Utils.doubleToString(m_minX, nondecimal + 1 + precisionXmin, precisionXmin); mswx = m_labelMetrics.stringWidth(maxStringX); int precisionYmax = 1; int precisionYmin = 1; int precisionYmid = 1; whole = (int) Math.abs(m_maxY); decimal = Math.abs(m_maxY) - whole; 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 > VisualizeUtils.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 > VisualizeUtils.MAX_PRECISION) { precisionYmin = 1; } String minStringY = Utils.doubleToString(m_minY, nondecimal + 1 + precisionYmin, precisionYmin); if (m_plotInstances.attribute(m_yIndex).isNumeric()) { mswy = (m_labelMetrics.stringWidth(maxStringY) > m_labelMetrics .stringWidth(minStringY)) ? m_labelMetrics.stringWidth(maxStringY) : m_labelMetrics.stringWidth(minStringY); mswy += m_labelMetrics.stringWidth("M"); } else { mswy = m_labelMetrics.stringWidth("MM"); } m_YaxisStart = m_axisPad; m_XaxisStart = 0 + m_axisPad + m_tickSize + mswy; m_XaxisEnd = w - m_axisPad - (mswx / 2); m_YaxisEnd = h - m_axisPad - (2 * hf) - m_tickSize; // draw axis gx.setColor(m_axisColour); if (m_plotInstances.attribute(m_xIndex).isNumeric()) { if (w > (2 * mswx)) { gx.drawString(maxStringX, m_XaxisEnd - (mswx / 2), m_YaxisEnd + hf + m_tickSize); mswx = m_labelMetrics.stringWidth(minStringX); gx.drawString(minStringX, (m_XaxisStart - (mswx / 2)), m_YaxisEnd + hf + m_tickSize); // draw the middle value if (w > (3 * mswx) && (m_plotInstances.attribute(m_xIndex).isNumeric())) { double mid = m_minX + ((m_maxX - m_minX) / 2.0); whole = (int) Math.abs(mid); decimal = Math.abs(mid) - whole; nondecimal = (whole > 0) ? (int) (Math.log(whole) / Math.log(10)) : 1; precisionXmid = (decimal > 0) ? (int) Math.abs(((Math.log(Math.abs(mid)) / Math .log(10)))) + 2 : 1; if (precisionXmid > VisualizeUtils.MAX_PRECISION) { precisionXmid = 1; } String maxString = Utils.doubleToString(mid, nondecimal + 1 + precisionXmid, precisionXmid); int sw = m_labelMetrics.stringWidth(maxString); double mx = m_XaxisStart + ((m_XaxisEnd - m_XaxisStart) / 2.0); gx.drawString(maxString, (int) (mx - ((sw) / 2.0)), m_YaxisEnd + hf + m_tickSize); gx.drawLine((int) mx, m_YaxisEnd, (int) mx, m_YaxisEnd + m_tickSize); } } } else { int numValues = m_plotInstances.attribute(m_xIndex).numValues(); int maxXStringWidth = (m_XaxisEnd - m_XaxisStart) / numValues; for (int i = 0; i < numValues; i++) { String val = m_plotInstances.attribute(m_xIndex).value(i); int sw = m_labelMetrics.stringWidth(val); int rm; // truncate string if necessary if (sw > maxXStringWidth) { int incr = (sw / val.length()); rm = (sw - maxXStringWidth) / incr; if (rm == 0) { rm = 1; } val = val.substring(0, val.length() - rm); sw = m_labelMetrics.stringWidth(val); } if (i == 0) { gx.drawString(val, (int) convertToPanelX(i), m_YaxisEnd + hf + m_tickSize); } else if (i == numValues - 1) { if ((i % 2) == 0) { gx.drawString(val, m_XaxisEnd - sw, m_YaxisEnd + hf + m_tickSize); } else { gx.drawString(val, m_XaxisEnd - sw, m_YaxisEnd + (2 * hf) + m_tickSize); } } else { if ((i % 2) == 0) { gx.drawString(val, (int) convertToPanelX(i) - (sw / 2), m_YaxisEnd + hf + m_tickSize); } else { gx.drawString(val, (int) convertToPanelX(i) - (sw / 2), m_YaxisEnd + (2 * hf) + m_tickSize); } } gx.drawLine((int) convertToPanelX(i), m_YaxisEnd, (int) convertToPanelX(i), m_YaxisEnd + m_tickSize); } } // draw the y axis if (m_plotInstances.attribute(m_yIndex).isNumeric()) { if (h > (2 * hf)) { gx.drawString(maxStringY, m_XaxisStart - mswy - m_tickSize, m_YaxisStart + (hf)); gx.drawString(minStringY, (m_XaxisStart - mswy - m_tickSize), m_YaxisEnd); // draw the middle value if (w > (3 * hf) && (m_plotInstances.attribute(m_yIndex).isNumeric())) { double mid = m_minY + ((m_maxY - m_minY) / 2.0); whole = (int) Math.abs(mid); decimal = Math.abs(mid) - whole; nondecimal = (whole > 0) ? (int) (Math.log(whole) / Math.log(10)) : 1; precisionYmid = (decimal > 0) ? (int) Math.abs(((Math.log(Math.abs(mid)) / Math .log(10)))) + 2 : 1; if (precisionYmid > VisualizeUtils.MAX_PRECISION) { precisionYmid = 1; } String maxString = Utils.doubleToString(mid, nondecimal + 1 + precisionYmid, precisionYmid); int sw = m_labelMetrics.stringWidth(maxString); double mx = m_YaxisStart + ((m_YaxisEnd - m_YaxisStart) / 2.0); gx.drawString(maxString, m_XaxisStart - sw - m_tickSize - 1, (int) (mx + ((hf) / 2.0))); gx.drawLine(m_XaxisStart - m_tickSize, (int) mx, m_XaxisStart, (int) mx); } } } else { int numValues = m_plotInstances.attribute(m_yIndex).numValues(); int div = ((numValues % 2) == 0) ? (numValues / 2) : (numValues / 2 + 1); int maxYStringHeight = (m_YaxisEnd - m_XaxisStart) / div; int sw = m_labelMetrics.stringWidth("M"); for (int i = 0; i < numValues; i++) { // can we at least print 2 characters if (maxYStringHeight >= (2 * hf)) { String val = m_plotInstances.attribute(m_yIndex).value(i); int numPrint = ((maxYStringHeight / hf) > val.length()) ? val.length() : (maxYStringHeight / hf); for (int j = 0; j < numPrint; j++) { String ll = val.substring(j, j + 1); if (val.charAt(j) == '_' || val.charAt(j) == '-') { ll = "|"; } if (i == 0) { gx.drawString(ll, m_XaxisStart - sw - m_tickSize - 1, (int) convertToPanelY(i) - ((numPrint - 1) * hf) + (j * hf) + (hf / 2)); } else if (i == (numValues - 1)) { if ((i % 2) == 0) { gx.drawString(ll, m_XaxisStart - sw - m_tickSize - 1, (int) convertToPanelY(i) + (j * hf) + (hf / 2)); } else { gx.drawString(ll, m_XaxisStart - (2 * sw) - m_tickSize - 1, (int) convertToPanelY(i) + (j * hf) + (hf / 2)); } } else { if ((i % 2) == 0) { gx.drawString(ll, m_XaxisStart - sw - m_tickSize - 1, (int) convertToPanelY(i) - (((numPrint - 1) * hf) / 2) + (j * hf) + (hf / 2)); } else { gx.drawString(ll, m_XaxisStart - (2 * sw) - m_tickSize - 1, (int) convertToPanelY(i) - (((numPrint - 1) * hf) / 2) + (j * hf) + (hf / 2)); } } } } gx.drawLine(m_XaxisStart - m_tickSize, (int) convertToPanelY(i), m_XaxisStart, (int) convertToPanelY(i)); } } gx.drawLine(m_XaxisStart, m_YaxisStart, m_XaxisStart, m_YaxisEnd); gx.drawLine(m_XaxisStart, m_YaxisEnd, m_XaxisEnd, m_YaxisEnd); if (m_XaxisStart != mxs || m_XaxisEnd != mxe || m_YaxisStart != mys || m_YaxisEnd != mye) { m_plotResize = true; } } /** * Add more colours to the colour map */ private void extendColourMap(int highest) { // System.err.println("Extending colour map"); for (int i = m_colorList.size(); i < highest; i++) { Color pc = m_DefaultColors[i % 10]; int ija = i / 10; ija *= 2; for (int j = 0; j < ija; j++) { pc = pc.brighter(); } m_colorList.add(pc); } } /** * Renders this component * * @param gx the graphics context */ @Override public void paintComponent(Graphics gx) { super.paintComponent(gx); if (m_plotInstances != null && m_plotInstances.numInstances() > 0 && m_plotInstances.numAttributes() > 0) { if (m_plotCompanion != null) { m_plotCompanion.prePlot(gx); } m_JRand = new Random(m_JitterVal); paintAxis(gx); if (m_axisChanged || m_plotResize) { int x_range = m_XaxisEnd - m_XaxisStart; int y_range = m_YaxisEnd - m_YaxisStart; if (x_range < 10) { x_range = 10; } if (y_range < 10) { y_range = 10; } m_drawnPoints = new int[x_range + 1][y_range + 1]; fillLookup(); m_plotResize = false; m_axisChanged = false; } paintData(gx); } } protected static Color checkAgainstBackground(Color c, Color background) { if (background == null) { return c; } if (c.equals(background)) { int red = c.getRed(); int blue = c.getBlue(); int green = c.getGreen(); red += (red < 128) ? (255 - red) / 2 : -(red / 2); blue += (blue < 128) ? (blue - red) / 2 : -(blue / 2); green += (green < 128) ? (255 - green) / 2 : -(green / 2); c = new Color(red, green, blue); } return c; } /** * Main method for testing this class * * @param args arguments */ public static void main(String[] args) { try { if (args.length < 1) { System.err.println("Usage : weka.gui.visualize.Plot2D " + "<dataset> [<dataset> <dataset>...]"); System.exit(1); } final javax.swing.JFrame jf = new javax.swing.JFrame("Weka Explorer: Visualize"); jf.setSize(500, 400); jf.getContentPane().setLayout(new BorderLayout()); final Plot2D p2 = new Plot2D(); jf.getContentPane().add(p2, BorderLayout.CENTER); jf.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { jf.dispose(); System.exit(0); } }); p2.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if ((e.getModifiers() & InputEvent.BUTTON1_MASK) == InputEvent.BUTTON1_MASK) { p2.searchPoints(e.getX(), e.getY(), false); } else { p2.searchPoints(e.getX(), e.getY(), true); } } }); jf.setVisible(true); if (args.length >= 1) { for (int j = 0; j < args.length; j++) { System.err.println("Loading instances from " + args[j]); java.io.Reader r = new java.io.BufferedReader(new java.io.FileReader(args[j])); Instances i = new Instances(r); i.setClassIndex(i.numAttributes() - 1); PlotData2D pd1 = new PlotData2D(i); if (j == 0) { pd1.setPlotName("Master plot"); p2.setMasterPlot(pd1); p2.setXindex(2); p2.setYindex(3); p2.setCindex(i.classIndex()); } else { pd1.setPlotName("Plot " + (j + 1)); pd1.m_useCustomColour = true; pd1.m_customColour = (j % 2 == 0) ? Color.red : Color.blue; p2.addPlot(pd1); } } } } 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/visualize/Plot2DCompanion.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * Plot2DCompanion.java * Copyright (C) 2000-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.visualize; import java.awt.Graphics; /** * Interface for classes that need to draw to the Plot2D panel *before* * Plot2D renders anything (eg. VisualizePanel may need to draw polygons * etc.) * * @author Mark Hall (mhall@cs.waikato.ac.nz) * @version $Revision$ */ public interface Plot2DCompanion { /** * Something to be drawn before the plot itself * @param gx the graphics context to render to */ void prePlot(Graphics gx); }
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/visualize/PlotData2D.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * PlotData2D.java * Copyright (C) 2000-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.visualize; import java.awt.Color; import java.io.Serializable; import java.util.ArrayList; import weka.core.Instances; import weka.filters.Filter; import weka.filters.unsupervised.attribute.Add; /** * This class is a container for plottable data. Instances form the primary * data. An optional array of classifier/clusterer predictions (associated 1 for * 1 with the instances) can also be provided. * * @author Mark Hall (mhall@cs.waikato.ac.nz) * @version $Revision$ */ public class PlotData2D implements Serializable { /** * For serialization */ private static final long serialVersionUID = -3979972167982697979L; /** The instances */ protected Instances m_plotInstances = null; /** The name of this plot */ protected String m_plotName = "new plot"; /** * The name of this plot (possibly in html) suitable for using in a tool tip * text. */ protected String m_plotNameHTML = null; /** Custom colour for this plot */ public boolean m_useCustomColour = false; public Color m_customColour = null; /** Display all points (ie. those that map to the same display coords) */ public boolean m_displayAllPoints = false; /** * If the shape size of a point equals this size then always plot it (i.e. * even if it is obscured by other points) */ public int m_alwaysDisplayPointsOfThisSize = -1; /** Panel coordinate cache for data points */ protected double[][] m_pointLookup; /** * Additional optional information to control the size of points. The default * is shape size 2 */ protected int[] m_shapeSize; /** * Additional optional information to control the point shape for this data. * Default is to allow automatic assigning of point shape on the basis of plot * number */ protected int[] m_shapeType; /** * Additional optional information to control the drawing of lines between * consecutive points. Setting an entry in the array to true indicates that * the associated point should have a line connecting it to the previous * point. */ protected boolean[] m_connectPoints; /** These are used to determine bounds */ /** The x index */ private int m_xIndex; /** The y index */ private int m_yIndex; /** The colouring index */ private int m_cIndex; /** * Holds the min and max values of the x, y and colouring attributes for this * plot */ protected double m_maxX; protected double m_minX; protected double m_maxY; protected double m_minY; protected double m_maxC; protected double m_minC; /** * Construct a new PlotData2D using the supplied instances * * @param insts the instances to use. */ public PlotData2D(Instances insts) { m_plotInstances = insts; m_xIndex = m_yIndex = m_cIndex = 0; m_pointLookup = new double[m_plotInstances.numInstances()][4]; m_shapeSize = new int[m_plotInstances.numInstances()]; m_shapeType = new int[m_plotInstances.numInstances()]; m_connectPoints = new boolean[m_plotInstances.numInstances()]; for (int i = 0; i < m_plotInstances.numInstances(); i++) { m_shapeSize[i] = Plot2D.DEFAULT_SHAPE_SIZE; // default shape size // default (automatic shape assignment) or -ve weight indicates hack to make // point invisible m_shapeType[i] = m_plotInstances.instance(i).weight() >= 0 ? Plot2D.CONST_AUTOMATIC_SHAPE : -2; } determineBounds(); } /** * Adds an instance number attribute to the plottable instances, */ public void addInstanceNumberAttribute() { String originalRelationName = m_plotInstances.relationName(); int originalClassIndex = m_plotInstances.classIndex(); try { Add addF = new Add(); addF.setAttributeName("Instance_number"); addF.setAttributeIndex("first"); addF.setInputFormat(m_plotInstances); m_plotInstances = Filter.useFilter(m_plotInstances, addF); m_plotInstances.setClassIndex(originalClassIndex + 1); for (int i = 0; i < m_plotInstances.numInstances(); i++) { m_plotInstances.instance(i).setValue(0, i); } m_plotInstances.setRelationName(originalRelationName); } catch (Exception ex) { ex.printStackTrace(); } } /** * Returns the instances for this plot * * @return the instances for this plot */ public Instances getPlotInstances() { return new Instances(m_plotInstances); } /** * Set the name of this plot * * @param name the name for this plot */ public void setPlotName(String name) { m_plotName = name; } /** * Get the name of this plot * * @return the name of this plot */ public String getPlotName() { return m_plotName; } /** * Set the plot name for use in a tool tip text. * * @param name the name of the plot for potential use in a tool tip text (may * use html). */ public void setPlotNameHTML(String name) { m_plotNameHTML = name; } /** * Get the name of the plot for use in a tool tip text. Defaults to the * standard plot name if it hasn't been set. * * @return the name of this plot (possibly in html) for use in a tool tip * text. */ public String getPlotNameHTML() { if (m_plotNameHTML == null) { return m_plotName; } return m_plotNameHTML; } /** * Set the shape type for the plot data * * @param st an array of integers corresponding to shape types (see constants * defined in Plot2D) */ public void setShapeType(int[] st) throws Exception { m_shapeType = st; if (m_shapeType.length != m_plotInstances.numInstances()) { throw new Exception("PlotData2D: Shape type array must have the same " + "number of entries as number of data points!"); } /* * for (int i = 0; i < st.length; i++) { if (m_shapeType[i] == * Plot2D.ERROR_SHAPE) { m_shapeSize[i] = 3; } } */ } /** * Get the shape types for the plot data * * @return the shape types for the plot data */ public int[] getShapeType() { return m_shapeType; } /** * Set the shape type for the plot data * * @param st a FastVector of integers corresponding to shape types (see * constants defined in Plot2D) */ public void setShapeType(ArrayList<Integer> st) throws Exception { if (st.size() != m_plotInstances.numInstances()) { throw new Exception("PlotData2D: Shape type vector must have the same " + "number of entries as number of data points!"); } m_shapeType = new int[st.size()]; for (int i = 0; i < st.size(); i++) { m_shapeType[i] = st.get(i).intValue(); /* * if (m_shapeType[i] == Plot2D.ERROR_SHAPE) { m_shapeSize[i] = 3; } */ } } /** * Set the shape sizes for the plot data * * @param ss an array of integers specifying the size of data points */ public void setShapeSize(int[] ss) throws Exception { m_shapeSize = ss; if (m_shapeType.length != m_plotInstances.numInstances()) { throw new Exception("PlotData2D: Shape size array must have the same " + "number of entries as number of data points!"); } } /** * Get the shape sizes for the plot data * * @return the shape sizes for the plot data */ public int[] getShapeSize() { return m_shapeSize; } /** * Set the shape sizes for the plot data * * @param ss a FastVector of integers specifying the size of data points */ public void setShapeSize(ArrayList<Object> ss) throws Exception { if (ss.size() != m_plotInstances.numInstances()) { throw new Exception("PlotData2D: Shape size vector must have the same " + "number of entries as number of data points!"); } // System.err.println("Setting connect points "); m_shapeSize = new int[ss.size()]; for (int i = 0; i < ss.size(); i++) { m_shapeSize[i] = ((Integer) ss.get(i)).intValue(); } } /** * Set whether consecutive points should be connected by lines * * @param cp an array of boolean specifying which points should be connected * to their preceeding neighbour. */ public void setConnectPoints(boolean[] cp) throws Exception { m_connectPoints = cp; if (m_connectPoints.length != m_plotInstances.numInstances()) { throw new Exception("PlotData2D: connect points array must have the " + "same number of entries as number of data points!"); } m_connectPoints[0] = false; } /** * Set whether consecutive points should be connected by lines * * @param cp a FastVector of boolean specifying which points should be * connected to their preceeding neighbour. */ public void setConnectPoints(ArrayList<Boolean> cp) throws Exception { if (cp.size() != m_plotInstances.numInstances()) { throw new Exception("PlotData2D: connect points array must have the " + "same number of entries as number of data points!"); } // System.err.println("Setting connect points "); m_shapeSize = new int[cp.size()]; for (int i = 0; i < cp.size(); i++) { m_connectPoints[i] = cp.get(i).booleanValue(); } m_connectPoints[0] = false; } /** * Set a custom colour to use for this plot. This overides any data index to * use for colouring. If null, then will revert back to the default (no custom * colouring). * * @param c a custom colour to use for this plot or null (default---no * colouring). */ public void setCustomColour(Color c) { m_customColour = c; if (c != null) { m_useCustomColour = true; } else { m_useCustomColour = false; } } /** * Set the x index of the data. * * @param x the x index */ public void setXindex(int x) { m_xIndex = x; determineBounds(); } /** * Set the y index of the data * * @param y the y index */ public void setYindex(int y) { m_yIndex = y; determineBounds(); } /** * Set the colouring index of the data * * @param c the colouring index */ public void setCindex(int c) { m_cIndex = c; determineBounds(); } /** * Get the currently set x index of the data * * @return the current x index */ public int getXindex() { return m_xIndex; } /** * Get the currently set y index of the data * * @return the current y index */ public int getYindex() { return m_yIndex; } /** * Get the currently set colouring index of the data * * @return the current colouring index */ public int getCindex() { return m_cIndex; } /** * Determine bounds for the current x,y and colouring indexes */ private void determineBounds() { double value, min, max; if (m_plotInstances != null && m_plotInstances.numAttributes() > 0 && m_plotInstances.numInstances() > 0) { // x bounds min = Double.POSITIVE_INFINITY; max = Double.NEGATIVE_INFINITY; if (m_plotInstances.attribute(m_xIndex).isNominal()) { m_minX = 0; m_maxX = m_plotInstances.attribute(m_xIndex).numValues() - 1; } else { for (int i = 0; i < m_plotInstances.numInstances(); i++) { if (!m_plotInstances.instance(i).isMissing(m_xIndex)) { value = m_plotInstances.instance(i).value(m_xIndex); if (value < min) { min = value; } if (value > max) { max = value; } } } // handle case where all values are missing if (min == Double.POSITIVE_INFINITY) { min = max = 0.0; } m_minX = min; m_maxX = max; if (min == max) { m_maxX += 0.05; m_minX -= 0.05; } } // y bounds min = Double.POSITIVE_INFINITY; max = Double.NEGATIVE_INFINITY; if (m_plotInstances.attribute(m_yIndex).isNominal()) { m_minY = 0; m_maxY = m_plotInstances.attribute(m_yIndex).numValues() - 1; } else { for (int i = 0; i < m_plotInstances.numInstances(); i++) { if (!m_plotInstances.instance(i).isMissing(m_yIndex)) { value = m_plotInstances.instance(i).value(m_yIndex); if (value < min) { min = value; } if (value > max) { max = value; } } } // handle case where all values are missing if (min == Double.POSITIVE_INFINITY) { min = max = 0.0; } m_minY = min; m_maxY = max; if (min == max) { m_maxY += 0.05; m_minY -= 0.05; } } // colour bounds min = Double.POSITIVE_INFINITY; max = Double.NEGATIVE_INFINITY; for (int i = 0; i < m_plotInstances.numInstances(); i++) { if (!m_plotInstances.instance(i).isMissing(m_cIndex)) { value = m_plotInstances.instance(i).value(m_cIndex); if (value < min) { min = value; } if (value > max) { max = value; } } } // handle case where all values are missing if (min == Double.POSITIVE_INFINITY) { min = max = 0.0; } m_minC = min; m_maxC = max; } } }
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/visualize/PostscriptGraphics.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * PostscriptGraphics.java * Copyright (C) 2003-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.visualize; import java.awt.AlphaComposite; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Composite; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GraphicsConfiguration; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.Image; import java.awt.Paint; import java.awt.Polygon; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.Stroke; import java.awt.Toolkit; import java.awt.font.FontRenderContext; import java.awt.font.GlyphVector; import java.awt.geom.AffineTransform; import java.awt.image.BufferedImage; import java.awt.image.BufferedImageOp; import java.awt.image.ColorModel; import java.awt.image.ImageObserver; import java.awt.image.PixelGrabber; import java.awt.image.RenderedImage; import java.awt.image.renderable.RenderableImage; import java.io.OutputStream; import java.io.PrintStream; import java.text.AttributedCharacterIterator; import java.util.Calendar; import java.util.Hashtable; import java.util.Map; /** * The PostscriptGraphics class extends the Graphics2D class to produce an * encapsulated postscript file rather than on-screen display. * <p> * Currently only a small (but useful) subset of Graphics methods have been * implemented. To handle the ability to Clone a Graphics object, the graphics * state of the eps is set from the graphics state of the local * PostscriptGraphics before output. To use, create a PostscriptGraphics object, * and pass it to the PaintComponent method of a JComponent. * <p> * If necessary additional font replacements can be inserted, since some fonts * might be displayed incorrectly. * * @see #addPSFontReplacement(String, String) * @see #m_PSFontReplacement * @author Dale Fletcher (dale@cs.waikato.ac.nz) * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class PostscriptGraphics extends Graphics2D { /** * This inner class is used to maintain the graphics states of the PostScript * file and graphics context. */ private class GraphicsState { /** The current pen color */ protected Color m_currentColor; /** The current Font */ protected Font m_currentFont; /** The current Stroke (not yet used) */ protected Stroke m_currentStroke; /** x,y Translation */ protected int m_xOffset; protected int m_yOffset; /** the scale factors */ protected double m_xScale; protected double m_yScale; /** * Create a new GraphicsState with default values. */ GraphicsState() { m_currentColor = Color.white; m_currentFont = new Font("Courier", Font.PLAIN, 11); m_currentStroke = new BasicStroke(); m_xOffset = 0; m_yOffset = 0; m_xScale = 1.0; m_yScale = 1.0; } /** * Create a new cloned GraphicsState * * @param copy The GraphicsState to clone */ GraphicsState(GraphicsState copy) { m_currentColor = copy.m_currentColor; m_currentFont = copy.m_currentFont; m_currentStroke = copy.m_currentStroke; m_xOffset = copy.m_xOffset; m_yOffset = copy.m_yOffset; m_xScale = copy.m_xScale; m_yScale = copy.m_yScale; } /* Stroke Methods */ protected Stroke getStroke() { return m_currentStroke; } protected void setStroke(Stroke s) { m_currentStroke = s; } /* Font Methods */ protected Font getFont() { return m_currentFont; } protected void setFont(Font f) { m_currentFont = f; } /* Color Methods */ protected Color getColor() { return m_currentColor; } protected void setColor(Color c) { m_currentColor = c; } /* Translation methods */ protected void setXOffset(int xo) { m_xOffset = xo; } protected void setYOffset(int yo) { m_yOffset = yo; } protected int getXOffset() { return m_xOffset; } protected int getYOffset() { return m_yOffset; } protected void setXScale(double x) { m_xScale = x; } protected void setYScale(double y) { m_yScale = y; } protected double getXScale() { return m_xScale; } protected double getYScale() { return m_yScale; } } /** The bounding box of the output */ protected Rectangle m_extent; /** The output file */ protected PrintStream m_printstream; /** The current global PostScript graphics state for all cloned objects */ protected GraphicsState m_psGraphicsState; /** The current local graphics state for this PostscriptGraphics object */ protected GraphicsState m_localGraphicsState; /** whether to print some debug information */ protected final static boolean DEBUG = false; /** the font replacement */ protected static Hashtable<String, String> m_PSFontReplacement; /** output if we're in debug mode */ static { if (DEBUG) { System.err.println(PostscriptGraphics.class.getName() + ": DEBUG ON"); } // get font replacements m_PSFontReplacement = new Hashtable<String, String>(); m_PSFontReplacement.put("SansSerif.plain", "Helvetica.plain"); // SansSerif.plain // is // displayed // as Courier // in GV??? m_PSFontReplacement.put("Dialog.plain", "Helvetica.plain"); // dialog is a // Sans Serif // font, but GV // displays it // as Courier??? m_PSFontReplacement.put("Microsoft Sans Serif", "Helvetica.plain"); // MS // Sans // Serif // is a // Sans // Serif // font // (hence // the // name!), // but // GV // displays // it as // Courier??? m_PSFontReplacement.put("MicrosoftSansSerif", "Helvetica.plain"); // MS Sans // Serif // is a // Sans // Serif // font // (hence // the // name!), // but GV // displays // it as // Courier??? } /** * Constructor Creates a new PostscriptGraphics object, given dimensions and * output file. * * @param width The width of eps in points. * @param height The height of eps in points. * @param os File to send postscript to. */ public PostscriptGraphics(int width, int height, OutputStream os) { m_extent = new Rectangle(0, 0, height, width); m_printstream = new PrintStream(os); m_localGraphicsState = new GraphicsState(); m_psGraphicsState = new GraphicsState(); Header(); } /** * Creates a new cloned PostscriptGraphics object. * * @param copy The PostscriptGraphics object to clone. */ PostscriptGraphics(PostscriptGraphics copy) { m_extent = new Rectangle(copy.m_extent); m_printstream = copy.m_printstream; m_localGraphicsState = new GraphicsState(copy.m_localGraphicsState); // create // a // local // copy // of // the // current // state m_psGraphicsState = copy.m_psGraphicsState; // link to global state of eps // file } /** * Finalizes output file. */ public void finished() { m_printstream.flush(); } /** * Output postscript header to PrintStream, including helper macros. */ private void Header() { m_printstream.println("%!PS-Adobe-3.0 EPSF-3.0"); m_printstream.println("%%BoundingBox: 0 0 " + xScale(m_extent.width) + " " + yScale(m_extent.height)); m_printstream .println("%%CreationDate: " + Calendar.getInstance().getTime()); m_printstream.println("/Oval { % x y w h filled"); m_printstream.println("gsave"); m_printstream .println("/filled exch def /h exch def /w exch def /y exch def /x exch def"); m_printstream.println("x w 2 div add y h 2 div sub translate"); m_printstream.println("1 h w div scale"); m_printstream.println("filled {0 0 moveto} if"); m_printstream.println("0 0 w 2 div 0 360 arc"); m_printstream .println("filled {closepath fill} {stroke} ifelse grestore} bind def"); m_printstream.println("/Rect { % x y w h filled"); m_printstream .println("/filled exch def /h exch def /w exch def /y exch def /x exch def"); m_printstream.println("newpath "); m_printstream.println("x y moveto"); m_printstream.println("w 0 rlineto"); m_printstream.println("0 h neg rlineto"); m_printstream.println("w neg 0 rlineto"); m_printstream.println("closepath"); m_printstream.println("filled {fill} {stroke} ifelse} bind def"); m_printstream.println("%%BeginProlog\n%%EndProlog"); m_printstream.println("%%Page 1 1"); setFont(null); // set to default setColor(null); // set to default setStroke(null); // set to default } /** * adds the PS font name to replace and its replacement in the replacement * hashtable * * @param replace the PS font name to replace * @param with the PS font name to replace the font with */ public static void addPSFontReplacement(String replace, String with) { m_PSFontReplacement.put(replace, with); } /** * Convert Java Y coordinate (0 = top) to PostScript (0 = bottom) Also apply * current Translation * * @param y Java Y coordinate * @return translated Y to postscript */ private int yTransform(int y) { return (m_extent.height - (m_localGraphicsState.getYOffset() + y)); } /** * Apply current X Translation * * @param x Java X coordinate * @return translated X to postscript */ private int xTransform(int x) { return (m_localGraphicsState.getXOffset() + x); } /** * scales the given number with the provided scale factor */ private int doScale(int number, double factor) { return (int) StrictMath.round(number * factor); } /** * scales the given x value with current x scale factor */ private int xScale(int x) { return doScale(x, m_localGraphicsState.getXScale()); } /** * scales the given y value with current y scale factor */ private int yScale(int y) { return doScale(y, m_localGraphicsState.getYScale()); } /** * Set the current eps graphics state to that of the local one */ private void setStateToLocal() { setColor(this.getColor()); setFont(this.getFont()); setStroke(this.getStroke()); } /** * returns a two hexadecimal representation of i, if shorter than 2 chars then * an additional "0" is put in front */ private String toHex(int i) { String result; result = Integer.toHexString(i); if (result.length() < 2) { result = "0" + result; } return result; } /***** overridden Graphics methods *****/ /** * Draw a filled rectangle with the background color. * * @param x starting x coord * @param y starting y coord * @param width rectangle width * @param height rectangle height */ @Override public void clearRect(int x, int y, int width, int height) { setStateToLocal(); Color saveColor = getColor(); setColor(Color.white); // background color for page m_printstream.println(xTransform(xScale(x)) + " " + yTransform(yScale(y)) + " " + xScale(width) + " " + yScale(height) + " true Rect"); setColor(saveColor); } /** * Not implemented */ @Override public void clipRect(int x, int y, int width, int height) { } /** * Not implemented */ @Override public void copyArea(int x, int y, int width, int height, int dx, int dy) { } /** * Clone a PostscriptGraphics object */ @Override public Graphics create() { if (DEBUG) { m_printstream.println("%create"); } PostscriptGraphics psg = new PostscriptGraphics(this); return (psg); } /** * Not implemented */ @Override public void dispose() { } /** * Draw an outlined rectangle with 3D effect in current pen color. (Current * implementation: draw simple outlined rectangle) * * @param x starting x coord * @param y starting y coord * @param width rectangle width * @param height rectangle height * @param raised True: appear raised, False: appear etched */ @Override public void draw3DRect(int x, int y, int width, int height, boolean raised) { drawRect(x, y, width, height); } /** * Not implemented */ @Override public void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle) { } /** * simply calls drawString(String,int,int) * * @see #drawString(String,int,int) */ @Override public void drawBytes(byte[] data, int offset, int length, int x, int y) { drawString(new String(data, offset, length), x, y); } /** * simply calls drawString(String,int,int) * * @see #drawString(String,int,int) */ @Override public void drawChars(char[] data, int offset, int length, int x, int y) { drawString(new String(data, offset, length), x, y); } /** * calls drawImage(Image,int,int,int,int,Color,ImageObserver) * * @see #drawImage(Image,int,int,int,int,Color,ImageObserver) */ @Override public boolean drawImage(Image img, int x, int y, Color bgcolor, ImageObserver observer) { return drawImage(img, x, y, img.getWidth(observer), img.getHeight(observer), bgcolor, observer); } /** * calls drawImage(Image,int,int,Color,ImageObserver) with Color.WHITE as * background color * * @see #drawImage(Image,int,int,Color,ImageObserver) * @see Color#WHITE */ @Override public boolean drawImage(Image img, int x, int y, ImageObserver observer) { return drawImage(img, x, y, Color.WHITE, observer); } /** * PS see http://astronomy.swin.edu.au/~pbourke/geomformats/postscript/ Java * http * ://show.docjava.com:8086/book/cgij/doc/ip/graphics/SimpleImageFrame.java * .html */ @Override public boolean drawImage(Image img, int x, int y, int width, int height, Color bgcolor, ImageObserver observer) { try { // get data from image int[] pixels = new int[width * height]; PixelGrabber grabber = new PixelGrabber(img, 0, 0, width, height, pixels, 0, width); grabber.grabPixels(); ColorModel model = ColorModel.getRGBdefault(); // print data to ps m_printstream.println("gsave"); m_printstream.println(xTransform(xScale(x)) + " " + (yTransform(yScale(y)) - yScale(height)) + " translate"); m_printstream.println(xScale(width) + " " + yScale(height) + " scale"); m_printstream.println(width + " " + height + " " + "8" + " [" + width + " 0 0 " + (-height) + " 0 " + height + "]"); m_printstream.println("{<"); int index; for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { index = i * width + j; m_printstream.print(toHex(model.getRed(pixels[index]))); m_printstream.print(toHex(model.getGreen(pixels[index]))); m_printstream.print(toHex(model.getBlue(pixels[index]))); } m_printstream.println(); } m_printstream.println(">}"); m_printstream.println("false 3 colorimage"); m_printstream.println("grestore"); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * calls drawImage(Image,int,int,int,int,Color,ImageObserver) with the color * WHITE as background * * @see #drawImage(Image,int,int,int,int,Color,ImageObserver) * @see Color#WHITE */ @Override public boolean drawImage(Image img, int x, int y, int width, int height, ImageObserver observer) { return drawImage(img, x, y, width, height, Color.WHITE, observer); } /** * Not implemented */ @Override public boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, Color bgcolor, ImageObserver observer) { return false; } /** * calls drawImage(Image,int,int,int,int,int,int,int,int,Color,ImageObserver) * with Color.WHITE as background color * * @see #drawImage(Image,int,int,int,int,int,int,int,int,Color,ImageObserver) */ @Override public boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, ImageObserver observer) { return drawImage(img, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2, Color.WHITE, observer); } /** * Draw a line in current pen color. * * @param x1 starting x coord * @param y1 starting y coord * @param x2 ending x coord * @param y2 ending y coord */ @Override public void drawLine(int x1, int y1, int x2, int y2) { setStateToLocal(); m_printstream.println(xTransform(xScale(x1)) + " " + yTransform(yScale(y1)) + " moveto " + xTransform(xScale(x2)) + " " + yTransform(yScale(y2)) + " lineto stroke"); } /** * Draw an Oval outline in current pen color. * * @param x x-axis center of oval * @param y y-axis center of oval * @param width oval width * @param height oval height */ @Override public void drawOval(int x, int y, int width, int height) { setStateToLocal(); m_printstream.println(xTransform(xScale(x)) + " " + yTransform(yScale(y)) + " " + xScale(width) + " " + yScale(height) + " false Oval"); } /** * Not implemented */ @Override public void drawPolygon(int[] xPoints, int[] yPoints, int nPoints) { } /** * Not implemented */ @Override public void drawPolyline(int[] xPoints, int[] yPoints, int nPoints) { } /** * Draw an outlined rectangle in current pen color. * * @param x starting x coord * @param y starting y coord * @param width rectangle width * @param height rectangle height */ @Override public void drawRect(int x, int y, int width, int height) { setStateToLocal(); m_printstream.println(xTransform(xScale(x)) + " " + yTransform(yScale(y)) + " " + xScale(width) + " " + yScale(height) + " false Rect"); } /** * Not implemented */ @Override public void drawRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) { } /** * Not implemented */ @Override public void drawString(AttributedCharacterIterator iterator, int x, int y) { } /** * Escapes brackets in the string with backslashes. * * @param s the string to escape * @return the escaped string */ protected String escape(String s) { StringBuffer result; int i; result = new StringBuffer(); for (i = 0; i < s.length(); i++) { if ((s.charAt(i) == '(') || (s.charAt(i) == ')')) { result.append('\\'); } result.append(s.charAt(i)); } return result.toString(); } /** * Draw text in current pen color. * * @param str Text to output * @param x starting x coord * @param y starting y coord */ @Override public void drawString(String str, int x, int y) { setStateToLocal(); m_printstream.println(xTransform(xScale(x)) + " " + yTransform(yScale(y)) + " moveto" + " (" + escape(str) + ") show stroke"); } /** * Draw a filled rectangle with 3D effect in current pen color. (Current * implementation: draw simple filled rectangle) * * @param x starting x coord * @param y starting y coord * @param width rectangle width * @param height rectangle height * @param raised True: appear raised, False: appear etched */ @Override public void fill3DRect(int x, int y, int width, int height, boolean raised) { fillRect(x, y, width, height); } /** * Not implemented */ @Override public void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle) { } /** * Draw a filled Oval in current pen color. * * @param x x-axis center of oval * @param y y-axis center of oval * @param width oval width * @param height oval height */ @Override public void fillOval(int x, int y, int width, int height) { setStateToLocal(); m_printstream.println(xTransform(xScale(x)) + " " + yTransform(yScale(y)) + " " + xScale(width) + " " + yScale(height) + " true Oval"); } /** * Not implemented */ @Override public void fillPolygon(int[] xPoints, int[] yPoints, int nPoints) { } /** * Not implemented */ @Override public void fillPolygon(Polygon p) { } /** * Draw a filled rectangle in current pen color. * * @param x starting x coord * @param y starting y coord * @param width rectangle width * @param height rectangle height */ @Override public void fillRect(int x, int y, int width, int height) { if (width == m_extent.width && height == m_extent.height) { clearRect(x, y, width, height); // if we're painting the entire // background, just make it white } else { if (DEBUG) { m_printstream.println("% fillRect"); } setStateToLocal(); m_printstream.println(xTransform(xScale(x)) + " " + yTransform(yScale(y)) + " " + xScale(width) + " " + yScale(height) + " true Rect"); } } /** * Not implemented */ @Override public void fillRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) { } /** * Not implemented */ @Override public void finalize() { } /** * Not implemented */ @Override public Shape getClip() { return (null); } /** * This returns the full current drawing area * * @return full drawing area */ @Override public Rectangle getClipBounds() { return (new Rectangle(0, 0, m_extent.width, m_extent.height)); } /** * This returns the full current drawing area * * @return full drawing area */ @Override public Rectangle getClipBounds(Rectangle r) { r.setBounds(0, 0, m_extent.width, m_extent.height); return r; } /** * Not implemented */ @Override public Rectangle getClipRect() { return null; } /** * Get current pen color. * * @return current pen color. */ @Override public Color getColor() { return (m_localGraphicsState.getColor()); } /** * Get current font. * * @return current font. */ @Override public Font getFont() { return (m_localGraphicsState.getFont()); } /** * Get Font metrics * * @param f Font * @return Font metrics. */ @Override @SuppressWarnings("deprecation") public FontMetrics getFontMetrics(Font f) { return (Toolkit.getDefaultToolkit().getFontMetrics(f)); } /** * Not implemented */ @Override public void setClip(int x, int y, int width, int height) { } /** * Not implemented */ @Override public void setClip(Shape clip) { } /** * Set current pen color. Default to black if null. * * @param c new pen color. */ @Override public void setColor(Color c) { if (c != null) { m_localGraphicsState.setColor(c); if (m_psGraphicsState.getColor().equals(c)) { return; } m_psGraphicsState.setColor(c); } else { m_localGraphicsState.setColor(Color.black); m_psGraphicsState.setColor(getColor()); } m_printstream.print(getColor().getRed() / 255.0); m_printstream.print(" "); m_printstream.print(getColor().getGreen() / 255.0); m_printstream.print(" "); m_printstream.print(getColor().getBlue() / 255.0); m_printstream.println(" setrgbcolor"); } /** * replaces the font (PS name) if necessary and returns the new name */ private static String replacePSFont(String font) { String result; result = font; // do we have to replace it? -> same style, size if (m_PSFontReplacement.containsKey(font)) { result = m_PSFontReplacement.get(font).toString(); if (DEBUG) { System.out.println("switched font from '" + font + "' to '" + result + "'"); } } return result; } /** * Set current font. Default to Plain Courier 11 if null. * * @param font new font. */ @Override public void setFont(Font font) { if (font != null) { m_localGraphicsState.setFont(font); if (font.getName().equals(m_psGraphicsState.getFont().getName()) && (m_psGraphicsState.getFont().getStyle() == font.getStyle()) && (m_psGraphicsState.getFont().getSize() == yScale(font.getSize()))) { return; } m_psGraphicsState.setFont(new Font(font.getName(), font.getStyle(), yScale(getFont().getSize()))); } else { m_localGraphicsState.setFont(new Font("Courier", Font.PLAIN, 11)); m_psGraphicsState.setFont(getFont()); } m_printstream.println("/(" + replacePSFont(getFont().getPSName()) + ")" + " findfont"); m_printstream.println(yScale(getFont().getSize()) + " scalefont setfont"); } /** * Not implemented */ @Override public void setPaintMode() { } /** * Not implemented */ @Override public void setXORMode(Color c1) { } /** * Translates the origin of the graphics context to the point (x, y) in the * current coordinate system. Modifies this graphics context so that its new * origin corresponds to the point (x, y) in this graphics context's original * coordinate system. All coordinates used in subsequent rendering operations * on this graphics context will be relative to this new origin. * * @param x the x coordinate. * @param y the y coordinate. */ @Override public void translate(int x, int y) { if (DEBUG) { System.out.println("translate with x = " + x + " and y = " + y); } m_localGraphicsState.setXOffset(m_localGraphicsState.getXOffset() + xScale(x)); m_localGraphicsState.setYOffset(m_localGraphicsState.getYOffset() + yScale(y)); m_psGraphicsState.setXOffset(m_psGraphicsState.getXOffset() + xScale(x)); m_psGraphicsState.setYOffset(m_psGraphicsState.getYOffset() + yScale(y)); } /***** END overridden Graphics methods *****/ /***** START overridden Graphics2D methods *****/ @Override public FontRenderContext getFontRenderContext() { return (new FontRenderContext(null, true, true)); } @Override public void clip(Shape s) { } @Override public Stroke getStroke() { return (m_localGraphicsState.getStroke()); } @Override public Color getBackground() { return (Color.white); } @Override public void setBackground(Color c) { } @Override public Composite getComposite() { return (AlphaComposite.getInstance(AlphaComposite.SRC)); } @Override public Paint getPaint() { return ((new Color(getColor().getRed(), getColor().getGreen(), getColor() .getBlue()))); } @Override public AffineTransform getTransform() { return (new AffineTransform()); } @Override public void setTransform(AffineTransform at) { } @Override public void transform(AffineTransform at) { } @Override public void shear(double d1, double d2) { } @Override public void scale(double d1, double d2) { m_localGraphicsState.setXScale(d1); m_localGraphicsState.setYScale(d2); if (DEBUG) { System.err.println("d1 = " + d1 + ", d2 = " + d2); } } @Override public void rotate(double d1, double d2, double d3) { } @Override public void rotate(double d1) { } @Override public void translate(double d1, double d2) { } @Override public RenderingHints getRenderingHints() { return (new RenderingHints(null)); } @Override public void addRenderingHints(Map<?, ?> m) { } @Override public void setRenderingHints(Map<?, ?> m) { } @Override public Object getRenderingHint(RenderingHints.Key key) { return (null); } @Override public void setRenderingHint(RenderingHints.Key key, Object o) { } @Override public void setStroke(Stroke s) { if (s != null) { m_localGraphicsState.setStroke(s); if (s.equals(m_psGraphicsState.getStroke())) { return; } m_psGraphicsState.setStroke(s); } else { m_localGraphicsState.setStroke(new BasicStroke()); m_psGraphicsState.setStroke(getStroke()); } // ouput postscript here to set stroke. } @Override public void setPaint(Paint p) { } @Override public void setComposite(Composite c) { } @Override public GraphicsConfiguration getDeviceConfiguration() { GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice gd = ge.getDefaultScreenDevice(); return (gd.getDefaultConfiguration()); } @Override public boolean hit(Rectangle r, Shape s, boolean onstroke) { return (false); } @Override public void fill(Shape s) { } @Override public void drawGlyphVector(GlyphVector gv, float f1, float f2) { } @Override public void drawString(AttributedCharacterIterator aci, float f1, float f2) { } @Override public void drawString(String str, float x, float y) { drawString(str, (int) x, (int) y); } @Override public void drawRenderableImage(RenderableImage ri, AffineTransform at) { } @Override public void drawRenderedImage(RenderedImage ri, AffineTransform af) { } @Override public void drawImage(BufferedImage bi, BufferedImageOp bio, int i1, int i2) { } @Override public boolean drawImage(Image im, AffineTransform at, ImageObserver io) { return (false); } @Override public void draw(Shape s) { } /***** END *****/ }
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/visualize/PostscriptWriter.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * PostscriptWriter.java * Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.visualize; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import javax.swing.JComponent; /** * This class takes any Component and outputs it to a Postscript file.<p> * <b>Note:</b><br> * This writer does not work with Components that rely on clipping, like e.g. * scroll lists. Here the complete list is printed, instead of only in the * borders of the scroll list (may overlap other components!). This is due to * the way, clipping is handled in Postscript. There was no easy way around * this issue. :-( * * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ * @see PostscriptGraphics */ public class PostscriptWriter extends JComponentWriter { /** * initializes the object */ public PostscriptWriter() { super(null); } /** * initializes the object with the given Component * * @param c the component to print in the output format */ public PostscriptWriter(JComponent c) { super(c); } /** * initializes the object with the given Component and filename * * @param c the component to print in the output format * @param f the file to store the output in */ public PostscriptWriter(JComponent c, File f) { super(c, f); } /** * returns the name of the writer, to display in the FileChooser. * must be overridden in the derived class. */ public String getDescription() { return "Postscript-File"; } /** * returns the extension (incl. ".") of the output format, to use in the * FileChooser. * must be overridden in the derived class. */ public String getExtension() { return ".eps"; } /** * generates the actual output * * @throws Exception if something goes wrong */ public void generateOutput() throws Exception { BufferedOutputStream ostrm; PostscriptGraphics psg; ostrm = null; try { ostrm = new BufferedOutputStream(new FileOutputStream(getFile())); psg = new PostscriptGraphics(getComponent().getHeight(), getComponent().getWidth(), ostrm); psg.setFont(getComponent().getFont()); psg.scale(getXScale(), getYScale()); getComponent().printAll(psg); psg.finished(); } catch (Exception e) { System.err.println(e); } finally { if (ostrm != null) { try { ostrm.close(); } catch (Exception e) { // Nothing to really do for error on close } } } } /** * for testing only */ public static void main(String[] args) throws Exception { System.out.println("building TreeVisualizer..."); weka.gui.treevisualizer.TreeBuild builder = new weka.gui.treevisualizer.TreeBuild(); weka.gui.treevisualizer.NodePlace arrange = new weka.gui.treevisualizer.PlaceNode2(); weka.gui.treevisualizer.Node top = builder.create(new java.io.StringReader("digraph atree { top [label=\"the top\"] a [label=\"the first node\"] b [label=\"the second nodes\"] c [label=\"comes off of first\"] top->a top->b b->c }")); weka.gui.treevisualizer.TreeVisualizer tv = new weka.gui.treevisualizer.TreeVisualizer(null, top, arrange); tv.setSize(800 ,600); String filename = System.getProperty("java.io.tmpdir") + "test.eps"; System.out.println("outputting to '" + filename + "'..."); toOutput(new PostscriptWriter(), tv, new File(filename)); System.out.println("done!"); } }
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/visualize/PrintableComponent.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * PrintableComponent.java * Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.visualize; import weka.core.PluginManager; import weka.gui.ExtensionFileFilter; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import java.awt.Dimension; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.util.Collections; import java.util.Enumeration; import java.util.Hashtable; import java.util.List; import java.util.Properties; /** * This class extends the component which is handed over in the constructor by a * print dialog. The Print dialog is accessible via Alt+Shift+LeftMouseClick. * <p> * The individual JComponentWriter-descendants can be accessed by the * <code>getWriter(String)</code> method, if the parameters need to be changed. * * @see #getWriters() * @see #getWriter(String) * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class PrintableComponent implements PrintableHandler { /** the parent component of this print dialog. */ protected JComponent m_Component; /** the filechooser for saving the panel. */ protected static JFileChooser m_FileChooserPanel; /** the checkbox for the custom dimensions. */ protected static JCheckBox m_CustomDimensionsCheckBox; /** the edit field for the custom width. */ protected static JTextField m_CustomWidthText; /** the edit field for the custom height. */ protected static JTextField m_CustomHeightText; /** the checkbox for keeping the aspect ration. */ protected static JCheckBox m_AspectRatioCheckBox; /** the title of the save dialog. */ protected String m_SaveDialogTitle = "Save as..."; /** the x scale factor. */ protected double m_xScale = 1.0; /** the y scale factor. */ protected double m_yScale = 1.0; /** the aspect ratio. */ protected double m_AspectRatio; /** whether to ignore the update of the text field (in case of "keep ratio"). */ protected boolean m_IgnoreChange; /** whether to print some debug information. */ private static final boolean DEBUG = false; /** whether the user was already asked about the tooltip behavior. */ protected static boolean m_ToolTipUserAsked = false; /** the property name for showing the tooltip. */ protected final static String PROPERTY_SHOW = "PrintableComponentToolTipShow"; /** the property name whether the user was already asked. */ protected final static String PROPERTY_USERASKED = "PrintableComponentToolTipUserAsked"; /** whether to display the tooltip or not. */ protected static boolean m_ShowToolTip = true; static { try { m_ShowToolTip = Boolean.valueOf( VisualizeUtils.VISUALIZE_PROPERTIES.getProperty(PROPERTY_SHOW, "true")) .booleanValue(); m_ToolTipUserAsked = Boolean.valueOf( VisualizeUtils.VISUALIZE_PROPERTIES.getProperty(PROPERTY_USERASKED, "false")).booleanValue(); } catch (Exception e) { // ignore exception m_ToolTipUserAsked = false; m_ShowToolTip = true; } } /** output if we're in debug mode */ static { if (DEBUG) { System.err.println(PrintablePanel.class.getName() + ": DEBUG ON"); } } /** * initializes the panel. * * @param component the component to enhance with printing functionality */ public PrintableComponent(JComponent component) { super(); m_Component = component; m_AspectRatio = Double.NaN; getComponent().addMouseListener(new PrintMouseListener(this)); getComponent().setToolTipText(getToolTipText(this)); initFileChooser(); } /** * returns the GUI component this print dialog is part of. * * @return the GUI component */ public JComponent getComponent() { return m_Component; } /** * Returns a tooltip only if the user wants it. If retrieved for the first, a * dialog pops up and asks the user whether the tooltip should always appear * or not. The weka/gui/visualize/Visualize.props is then written in the * user's home directory. * * @param component the PrintableComponent to ask for * @return null if the user doesn't want the tooltip, otherwise the text */ @SuppressWarnings("unused") public static String getToolTipText(PrintableComponent component) { String result; int retVal; Properties props; String name; Enumeration<?> names; String filename; // ToolTip is disabled for the moment... if (true) { return null; } // ask user whether the tooltip should be shown if (!m_ToolTipUserAsked) { m_ToolTipUserAsked = true; retVal = JOptionPane.showConfirmDialog(component.getComponent(), "Some panels enable the user to save the content as JPEG or EPS.\n" + "In order to see which panels support this, a tooltip can be " + "displayed. Enable tooltip?", "ToolTip for Panels...", JOptionPane.YES_NO_OPTION); m_ShowToolTip = (retVal == JOptionPane.YES_OPTION); // save props file VisualizeUtils.VISUALIZE_PROPERTIES.setProperty(PROPERTY_SHOW, "" + m_ShowToolTip); VisualizeUtils.VISUALIZE_PROPERTIES.setProperty(PROPERTY_USERASKED, "" + m_ToolTipUserAsked); try { // NOTE: properties that got inherited from another props file don't // get saved. I.e., one could overwrite the existing props // file with an (nearly) empty one. // => transfer all properties into a new one props = new Properties(); names = VisualizeUtils.VISUALIZE_PROPERTIES.propertyNames(); while (names.hasMoreElements()) { name = names.nextElement().toString(); props.setProperty(name, VisualizeUtils.VISUALIZE_PROPERTIES.getProperty(name, "")); } filename = System.getProperty("user.home") + "/Visualize.props"; props.store(new BufferedOutputStream(new FileOutputStream(filename)), null); // inform user about location of props file and name of property JOptionPane .showMessageDialog( component.getComponent(), "You can still manually enable or disable the ToolTip via the following property\n" + " " + PROPERTY_SHOW + "\n" + "in the following file\n" + " " + filename); } catch (Exception e) { JOptionPane .showMessageDialog( component.getComponent(), "Error saving the props file!\n" + e.getMessage() + "\n\n" + "Note:\n" + "If you want to disable these messages from popping up, place a file\n" + "called 'Visualize.props' either in your home directory or in the directory\n" + "you're starting Weka from and add the following lines:\n" + " " + PROPERTY_USERASKED + "=true\n" + " " + PROPERTY_SHOW + "=" + m_ShowToolTip, "Error...", JOptionPane.ERROR_MESSAGE); } } if (m_ShowToolTip) { result = "Click left mouse button while holding <alt> and <shift> to display a save dialog."; } else { result = null; } return result; } /** * initializes the filechooser, i.e. locates all the available writers in the * current package */ protected void initFileChooser() { List<String> writerNames; int i; Class<?> cls; JComponentWriter writer; JPanel accessory; JLabel label; // already initialized? if (m_FileChooserPanel != null) { return; } m_FileChooserPanel = new JFileChooser(); m_FileChooserPanel.resetChoosableFileFilters(); m_FileChooserPanel.setAcceptAllFileFilterUsed(false); // setup the accessory accessory = new JPanel(); accessory.setLayout(null); accessory.setPreferredSize(new Dimension(200, 200)); accessory.revalidate(); m_FileChooserPanel.setAccessory(accessory); m_CustomDimensionsCheckBox = new JCheckBox("Use custom dimensions"); m_CustomDimensionsCheckBox.setBounds(14, 7, 200, 21); m_CustomDimensionsCheckBox.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { boolean custom = m_CustomDimensionsCheckBox.isSelected(); m_CustomWidthText.setEnabled(custom); m_CustomHeightText.setEnabled(custom); m_AspectRatioCheckBox.setEnabled(custom); if (custom) { m_IgnoreChange = true; m_CustomWidthText.setText("" + m_Component.getWidth()); m_CustomHeightText.setText("" + m_Component.getHeight()); m_IgnoreChange = false; } else { m_IgnoreChange = true; m_CustomWidthText.setText("-1"); m_CustomHeightText.setText("-1"); m_IgnoreChange = false; } } }); accessory.add(m_CustomDimensionsCheckBox); m_CustomWidthText = new JTextField(5); m_CustomWidthText.setText("-1"); m_CustomWidthText.setEnabled(false); m_CustomWidthText.setBounds(65, 35, 50, 21); m_CustomWidthText.getDocument().addDocumentListener(new DocumentListener() { @Override public void changedUpdate(DocumentEvent e) { updateDimensions(m_CustomWidthText); } @Override public void insertUpdate(DocumentEvent e) { updateDimensions(m_CustomWidthText); } @Override public void removeUpdate(DocumentEvent e) { updateDimensions(m_CustomWidthText); } }); label = new JLabel("Width"); label.setLabelFor(m_CustomWidthText); label.setDisplayedMnemonic('W'); label.setBounds(14, 35, 50, 21); accessory.add(label); accessory.add(m_CustomWidthText); m_CustomHeightText = new JTextField(5); m_CustomHeightText.setText("-1"); m_CustomHeightText.setEnabled(false); m_CustomHeightText.setBounds(65, 63, 50, 21); m_CustomHeightText.getDocument().addDocumentListener( new DocumentListener() { @Override public void changedUpdate(DocumentEvent e) { updateDimensions(m_CustomHeightText); } @Override public void insertUpdate(DocumentEvent e) { updateDimensions(m_CustomHeightText); } @Override public void removeUpdate(DocumentEvent e) { updateDimensions(m_CustomHeightText); } }); label = new JLabel("Height"); label.setLabelFor(m_CustomHeightText); label.setDisplayedMnemonic('H'); label.setBounds(14, 63, 50, 21); accessory.add(label); accessory.add(m_CustomHeightText); m_AspectRatioCheckBox = new JCheckBox("Keep aspect ratio"); m_AspectRatioCheckBox.setBounds(14, 91, 200, 21); m_AspectRatioCheckBox.setEnabled(false); m_AspectRatioCheckBox.setSelected(true); m_AspectRatioCheckBox.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { boolean keep = m_AspectRatioCheckBox.isSelected(); if (keep) { m_IgnoreChange = true; m_CustomWidthText.setText("" + m_Component.getWidth()); m_CustomHeightText.setText("" + m_Component.getHeight()); m_IgnoreChange = false; } } }); accessory.add(m_AspectRatioCheckBox); // determine all available writers and add them to the filechooser writerNames = PluginManager.getPluginNamesOfTypeList(JComponentWriter.class .getName()); Collections.sort(writerNames); for (i = 0; i < writerNames.size(); i++) { try { cls = Class.forName(writerNames.get(i).toString()); writer = (JComponentWriter) cls.newInstance(); m_FileChooserPanel .addChoosableFileFilter(new JComponentWriterFileFilter(writer .getExtension(), writer.getDescription() + " (*" + writer.getExtension() + ")", writer)); } catch (Exception e) { System.err.println(writerNames.get(i) + ": " + e); } } // set first filter as active filter if (m_FileChooserPanel.getChoosableFileFilters().length > 0) { m_FileChooserPanel.setFileFilter(m_FileChooserPanel .getChoosableFileFilters()[0]); } } /** * updates the dimensions if necessary (i.e., if aspect ratio is to be kept). * * @param sender the JTextField which send the notification to update */ protected void updateDimensions(JTextField sender) { int newValue; int baseValue; // some sanity checks if (!m_AspectRatioCheckBox.isSelected() || m_IgnoreChange) { return; } if (!(sender instanceof JTextField) || (sender == null)) { return; } if (sender.getText().length() == 0) { return; } // is it a valid integer, greater than 0? try { baseValue = Integer.parseInt(sender.getText()); newValue = 0; if (baseValue <= 0) { return; } if (Double.isNaN(m_AspectRatio)) { m_AspectRatio = (double) getComponent().getWidth() / (double) getComponent().getHeight(); } } catch (Exception e) { // we can't parse the string! return; } // computer and update m_IgnoreChange = true; if (sender == m_CustomWidthText) { newValue = (int) ((baseValue) * (1 / m_AspectRatio)); m_CustomHeightText.setText("" + newValue); } else if (sender == m_CustomHeightText) { newValue = (int) ((baseValue) * m_AspectRatio); m_CustomWidthText.setText("" + newValue); } m_IgnoreChange = false; } /** * returns a Hashtable with the current available JComponentWriters in the * save dialog. the key of the Hashtable is the description of the writer. * * @return all currently available JComponentWriters * @see JComponentWriter#getDescription() */ @Override public Hashtable<String, JComponentWriter> getWriters() { Hashtable<String, JComponentWriter> result; int i; JComponentWriter writer; result = new Hashtable<String, JComponentWriter>(); for (i = 0; i < m_FileChooserPanel.getChoosableFileFilters().length; i++) { writer = ((JComponentWriterFileFilter) m_FileChooserPanel .getChoosableFileFilters()[i]).getWriter(); result.put(writer.getDescription(), writer); } return result; } /** * returns the JComponentWriter associated with the given name, is * <code>null</code> if not found. * * @param name the name of the writer * @return the writer associated with the given name * @see JComponentWriter#getDescription() */ @Override public JComponentWriter getWriter(String name) { return getWriters().get(name); } /** * sets the title for the save dialog. * * @param title the title of the save dialog */ @Override public void setSaveDialogTitle(String title) { m_SaveDialogTitle = title; } /** * returns the title for the save dialog. * * @return the title of the save dialog */ @Override public String getSaveDialogTitle() { return m_SaveDialogTitle; } /** * sets the scale factor. * * @param x the scale factor for the x-axis * @param y the scale factor for the y-axis */ @Override public void setScale(double x, double y) { m_xScale = x; m_yScale = y; if (DEBUG) { System.err.println("x = " + x + ", y = " + y); } } /** * returns the scale factor for the x-axis. * * @return the scale factor */ @Override public double getXScale() { return m_xScale; } /** * returns the scale factor for the y-axis. * * @return the scale factor */ @Override public double getYScale() { return m_xScale; } /** * displays a save dialog for saving the panel to a file. Fixes a bug with the * Swing JFileChooser: if you entered a new filename in the save dialog and * press Enter the <code>getSelectedFile</code> method returns * <code>null</code> instead of the filename.<br> * To solve this annoying behavior we call the save dialog once again s.t. the * filename is set. Might look a little bit strange to the user, but no * NullPointerException! ;-) */ @Override public void saveComponent() { int result; JComponentWriter writer; File file; JComponentWriterFileFilter filter; // display save dialog m_FileChooserPanel.setDialogTitle(getSaveDialogTitle()); do { result = m_FileChooserPanel.showSaveDialog(getComponent()); if (result != JFileChooser.APPROVE_OPTION) { return; } } while (m_FileChooserPanel.getSelectedFile() == null); // save the file try { filter = (JComponentWriterFileFilter) m_FileChooserPanel.getFileFilter(); file = m_FileChooserPanel.getSelectedFile(); writer = filter.getWriter(); if (!file.getAbsolutePath().toLowerCase() .endsWith(writer.getExtension().toLowerCase())) { file = new File(file.getAbsolutePath() + writer.getExtension()); } writer.setComponent(getComponent()); writer.setFile(file); writer.setScale(getXScale(), getYScale()); writer.setUseCustomDimensions(m_CustomDimensionsCheckBox.isSelected()); if (m_CustomDimensionsCheckBox.isSelected()) { writer.setCustomWidth(Integer.parseInt(m_CustomWidthText.getText())); writer.setCustomHeight(Integer.parseInt(m_CustomHeightText.getText())); } else { writer.setCustomWidth(-1); writer.setCustomHeight(-1); } writer.toOutput(); } catch (Exception e) { e.printStackTrace(); } } /** * a specialized filter that also contains the associated filter class. */ protected class JComponentWriterFileFilter extends ExtensionFileFilter { /** ID added to avoid warning */ private static final long serialVersionUID = 8540426888094207515L; /** the associated writer. */ private final JComponentWriter m_Writer; /** * Creates the ExtensionFileFilter. * * @param extension the extension of accepted files. * @param description a text description of accepted files. * @param writer the associated writer */ public JComponentWriterFileFilter(String extension, String description, JComponentWriter writer) { super(extension, description); m_Writer = writer; } /** * returns the associated writer. * * @return the writer */ public JComponentWriter getWriter() { return m_Writer; } } /** * The listener to wait for Ctrl-Shft-Left Mouse Click. */ private class PrintMouseListener extends MouseAdapter { /** the listener's component. */ private final PrintableComponent m_Component; /** * initializes the listener. * * @param component the component for which to create the listener */ public PrintMouseListener(PrintableComponent component) { m_Component = component; } /** * Invoked when the mouse has been clicked on a component. * * @param e the event */ @Override public void mouseClicked(MouseEvent e) { int modifiers = e.getModifiers(); if (((modifiers & MouseEvent.SHIFT_MASK) == MouseEvent.SHIFT_MASK) && ((modifiers & MouseEvent.ALT_MASK) == MouseEvent.ALT_MASK) && ((modifiers & MouseEvent.BUTTON1_MASK) == MouseEvent.BUTTON1_MASK)) { e.consume(); m_Component.saveComponent(); } } } }
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/visualize/PrintableHandler.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * PrintableComponent.java * Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.visualize; import java.util.Hashtable; /** * This interface is for all JComponent classes that provide the ability to * print itself to a file. * * @see PrintableComponent * @see PrintablePanel * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public interface PrintableHandler { /** * returns a Hashtable with the current available JComponentWriters in the * save dialog. the key of the Hashtable is the description of the writer. * * @return all currently available JComponentWriters * @see JComponentWriter#getDescription() */ public Hashtable<String, JComponentWriter> getWriters(); /** * returns the JComponentWriter associated with the given name, is * <code>null</code> if not found * * @return the writer associated with the given name * @see JComponentWriter#getDescription() */ public JComponentWriter getWriter(String name); /** * sets the title for the save dialog */ public void setSaveDialogTitle(String title); /** * returns the title for the save dialog */ public String getSaveDialogTitle(); /** * sets the scale factor * * @param x the scale factor for the x-axis * @param y the scale factor for the y-axis */ public void setScale(double x, double y); /** * returns the scale factor for the x-axis */ public double getXScale(); /** * returns the scale factor for the y-axis */ public double getYScale(); /** * displays a save dialog for saving the component to a file. */ public void saveComponent(); }
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/visualize/PrintablePanel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * PrintablePanel.java * Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.visualize; import java.util.Hashtable; import javax.swing.JPanel; /** * This Panel enables the user to print the panel to various file formats. The * Print dialog is accessible via Ctrl-Shft-Left Mouse Click. * <p> * The individual JComponentWriter-descendants can be accessed by the * <code>getWriter(String)</code> method, if the parameters need to be changed. * * @see #getWriters() * @see #getWriter(String) * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class PrintablePanel extends JPanel implements PrintableHandler { /** for serialization */ private static final long serialVersionUID = 6281532227633417538L; /** the class responsible for printing */ protected PrintableComponent m_Printer = null; /** * initializes the panel */ public PrintablePanel() { super(); m_Printer = new PrintableComponent(this); } /** * returns a Hashtable with the current available JComponentWriters in the * save dialog. the key of the Hashtable is the description of the writer. * * @return all currently available JComponentWriters * @see JComponentWriter#getDescription() */ @Override public Hashtable<String, JComponentWriter> getWriters() { return m_Printer.getWriters(); } /** * returns the JComponentWriter associated with the given name, is * <code>null</code> if not found * * @return the writer associated with the given name * @see JComponentWriter#getDescription() */ @Override public JComponentWriter getWriter(String name) { return m_Printer.getWriter(name); } /** * sets the title for the save dialog */ @Override public void setSaveDialogTitle(String title) { m_Printer.setSaveDialogTitle(title); } /** * returns the title for the save dialog */ @Override public String getSaveDialogTitle() { return m_Printer.getSaveDialogTitle(); } /** * sets the scale factor * * @param x the scale factor for the x-axis * @param y the scale factor for the y-axis */ @Override public void setScale(double x, double y) { m_Printer.setScale(x, y); } /** * returns the scale factor for the x-axis */ @Override public double getXScale() { return m_Printer.getXScale(); } /** * returns the scale factor for the y-axis */ @Override public double getYScale() { return m_Printer.getYScale(); } /** * displays a save dialog for saving the panel to a file. */ @Override public void saveComponent() { m_Printer.saveComponent(); } }
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/visualize/ThresholdVisualizePanel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ThresholdVisualizePanel.java * Copyright (C) 2003-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.visualize; import java.awt.BorderLayout; 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.FileReader; import java.util.ArrayList; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.border.TitledBorder; import weka.classifiers.AbstractClassifier; import weka.classifiers.Classifier; import weka.classifiers.evaluation.EvaluationUtils; import weka.classifiers.evaluation.Prediction; import weka.classifiers.evaluation.ThresholdCurve; import weka.core.Instances; import weka.core.SingleIndex; import weka.core.Utils; /** * This panel is a VisualizePanel, with the added ablility to display the area * under the ROC curve if an ROC curve is chosen. * * @author Dale Fletcher (dale@cs.waikato.ac.nz) * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class ThresholdVisualizePanel extends VisualizePanel { /** for serialization */ private static final long serialVersionUID = 3070002211779443890L; /** The string to add to the Plot Border. */ private String m_ROCString = ""; /** Original border text */ private final String m_savePanelBorderText; /** * default constructor */ public ThresholdVisualizePanel() { super(); // Save the current border text TitledBorder tb = (TitledBorder) m_plotSurround.getBorder(); m_savePanelBorderText = tb.getTitle(); } /** * Set the string with ROC area * * @param str ROC area string to add to border */ public void setROCString(String str) { m_ROCString = str; } /** * This extracts the ROC area string * * @return ROC area string */ public String getROCString() { return m_ROCString; } /** * This overloads VisualizePanel's setUpComboBoxes to add ActionListeners to * watch for when the X/Y Axis comboboxes are changed. * * @param inst a set of instances with data for plotting */ @Override public void setUpComboBoxes(Instances inst) { super.setUpComboBoxes(inst); m_XCombo.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { setBorderText(); } }); m_YCombo.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { setBorderText(); } }); // Just in case the default is ROC setBorderText(); } /** * This checks the current selected X/Y Axis comboBoxes to see if an ROC graph * is selected. If so, add the ROC area string to the plot border, otherwise * display the original border text. */ private void setBorderText() { String xs = m_XCombo.getSelectedItem().toString(); String ys = m_YCombo.getSelectedItem().toString(); if (xs.equals("X: False Positive Rate (Num)") && ys.equals("Y: True Positive Rate (Num)")) { m_plotSurround.setBorder((BorderFactory .createTitledBorder(m_savePanelBorderText + " " + m_ROCString))); } else { m_plotSurround.setBorder((BorderFactory .createTitledBorder(m_savePanelBorderText))); } } /** * displays the previously saved instances * * @param insts the instances to display * @throws Exception if display is not possible */ @Override protected void openVisibleInstances(Instances insts) throws Exception { super.openVisibleInstances(insts); setROCString("(Area under ROC = " + Utils.doubleToString(ThresholdCurve.getROCArea(insts), 4) + ")"); setBorderText(); } /** * Starts the ThresholdVisualizationPanel with parameters from the command * line. * <p/> * * Valid options are: * <p/> * -h <br/> * lists all the commandline parameters * <p/> * * -t file <br/> * Dataset to process with given classifier. * <p/> * * -W classname <br/> * Full classname of classifier to run.<br/> * Options after '--' are passed to the classifier. <br/> * (default weka.classifiers.functions.Logistic) * <p/> * * -r number <br/> * The number of runs to perform (default 2). * <p/> * * -x number <br/> * The number of Cross-validation folds (default 10). * <p/> * * -l file <br/> * Previously saved threshold curve ARFF file. * <p/> * * @param args optional commandline parameters */ public static void main(String[] args) { Instances inst; Classifier classifier; int runs; int folds; String tmpStr; boolean compute; Instances result; String[] options; SingleIndex classIndex; SingleIndex valueIndex; int seed; inst = null; classifier = null; runs = 2; folds = 10; compute = true; result = null; classIndex = null; valueIndex = null; seed = 1; try { // help? if (Utils.getFlag('h', args)) { System.out.println("\nOptions for " + ThresholdVisualizePanel.class.getName() + ":\n"); System.out.println("-h\n\tThis help."); System.out .println("-t <file>\n\tDataset to process with given classifier."); System.out .println("-c <num>\n\tThe class index. first and last are valid, too (default: last)."); System.out .println("-C <num>\n\tThe index of the class value to get the the curve for (default: first)."); System.out .println("-W <classname>\n\tFull classname of classifier to run.\n\tOptions after '--' are passed to the classifier.\n\t(default: weka.classifiers.functions.Logistic)"); System.out .println("-r <number>\n\tThe number of runs to perform (default: 1)."); System.out .println("-x <number>\n\tThe number of Cross-validation folds (default: 10)."); System.out .println("-S <number>\n\tThe seed value for randomizing the data (default: 1)."); System.out .println("-l <file>\n\tPreviously saved threshold curve ARFF file."); return; } // regular options tmpStr = Utils.getOption('l', args); if (tmpStr.length() != 0) { result = new Instances(new BufferedReader(new FileReader(tmpStr))); compute = false; } if (compute) { tmpStr = Utils.getOption('r', args); if (tmpStr.length() != 0) { runs = Integer.parseInt(tmpStr); } else { runs = 1; } tmpStr = Utils.getOption('x', args); if (tmpStr.length() != 0) { folds = Integer.parseInt(tmpStr); } else { folds = 10; } tmpStr = Utils.getOption('S', args); if (tmpStr.length() != 0) { seed = Integer.parseInt(tmpStr); } else { seed = 1; } tmpStr = Utils.getOption('t', args); if (tmpStr.length() != 0) { inst = new Instances(new BufferedReader(new FileReader(tmpStr))); inst.setClassIndex(inst.numAttributes() - 1); } tmpStr = Utils.getOption('W', args); if (tmpStr.length() != 0) { options = Utils.partitionOptions(args); } else { tmpStr = weka.classifiers.functions.Logistic.class.getName(); options = new String[0]; } classifier = AbstractClassifier.forName(tmpStr, options); tmpStr = Utils.getOption('c', args); if (tmpStr.length() != 0) { classIndex = new SingleIndex(tmpStr); } else { classIndex = new SingleIndex("last"); } tmpStr = Utils.getOption('C', args); if (tmpStr.length() != 0) { valueIndex = new SingleIndex(tmpStr); } else { valueIndex = new SingleIndex("first"); } } // compute if necessary if (compute) { if (classIndex != null) { classIndex.setUpper(inst.numAttributes() - 1); inst.setClassIndex(classIndex.getIndex()); } else { inst.setClassIndex(inst.numAttributes() - 1); } if (valueIndex != null) { valueIndex.setUpper(inst.classAttribute().numValues() - 1); } ThresholdCurve tc = new ThresholdCurve(); EvaluationUtils eu = new EvaluationUtils(); ArrayList<Prediction> predictions = new ArrayList<Prediction>(); for (int i = 0; i < runs; i++) { eu.setSeed(seed + i); predictions.addAll(eu.getCVPredictions(classifier, inst, folds)); } if (valueIndex != null) { result = tc.getCurve(predictions, valueIndex.getIndex()); } else { result = tc.getCurve(predictions); } } // setup GUI ThresholdVisualizePanel vmc = new ThresholdVisualizePanel(); vmc.setROCString("(Area under ROC = " + Utils.doubleToString(ThresholdCurve.getROCArea(result), 4) + ")"); if (compute) { vmc.setName(result.relationName() + ". (Class value " + inst.classAttribute().value(valueIndex.getIndex()) + ")"); } else { vmc.setName(result.relationName() + " (display only)"); } PlotData2D tempd = new PlotData2D(result); tempd.setPlotName(result.relationName()); tempd.addInstanceNumberAttribute(); vmc.addPlot(tempd); String plotName = vmc.getName(); final JFrame jf = new JFrame("Weka Classifier Visualize: " + plotName); jf.setSize(500, 400); jf.getContentPane().setLayout(new BorderLayout()); jf.getContentPane().add(vmc, BorderLayout.CENTER); jf.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { jf.dispose(); } }); jf.setVisible(true); } catch (Exception e) { e.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/visualize/VisualizePanel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * VisualizePanel.java * Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.visualize; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Graphics; 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.InputEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionAdapter; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.Writer; import java.util.ArrayList; import java.util.Random; import javax.swing.BorderFactory; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JSlider; import javax.swing.SwingConstants; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.filechooser.FileFilter; import weka.core.Attribute; import weka.core.Instance; import weka.core.Instances; import weka.core.Settings; import weka.gui.ExtensionFileFilter; import weka.gui.Logger; /** * This panel allows the user to visualize a dataset (and if provided) a * classifier's/clusterer's predictions in two dimensions. * * If the user selects a nominal attribute as the colouring attribute then each * point is drawn in a colour that corresponds to the discrete value of that * attribute for the instance. If the user selects a numeric attribute to colour * on, then the points are coloured using a spectrum ranging from blue to red * (low values to high). * * When a classifier's predictions are supplied they are plotted in one of two * ways (depending on whether the class is nominal or numeric).<br> * For nominal class: an error made by a classifier is plotted as a square in * the colour corresponding to the class it predicted.<br> * For numeric class: predictions are plotted as varying sized x's, where the * size of the x is related to the magnitude of the error. * * @author Mark Hall (mhall@cs.waikato.ac.nz) * @author Malcolm Ware (mfw4@cs.waikato.ac.nz) * @version $Revision$ */ public class VisualizePanel extends PrintablePanel { /** for serialization */ private static final long serialVersionUID = 240108358588153943L; /** Inner class to handle plotting */ protected class PlotPanel extends PrintablePanel implements Plot2DCompanion { /** for serialization */ private static final long serialVersionUID = -4823674171136494204L; /** The actual generic plotting panel */ protected Plot2D m_plot2D = new Plot2D(); /** The instances from the master plot */ protected Instances m_plotInstances = null; /** The master plot */ protected PlotData2D m_originalPlot = null; /** * Indexes of the attributes to go on the x and y axis and the attribute to * use for colouring and the current shape for drawing */ protected int m_xIndex = 0; protected int m_yIndex = 0; protected int m_cIndex = 0; protected int m_sIndex = 0; /** the offsets of the axes once label metrics are calculated */ /* * private int m_XaxisStart=0; NOT USED private int m_YaxisStart=0; private * int m_XaxisEnd=0; private int m_YaxisEnd=0; */ /** True if the user is currently dragging a box. */ private boolean m_createShape; /** contains all the shapes that have been drawn for these attribs */ private ArrayList<ArrayList<Double>> m_shapes; /** contains the points of the shape currently being drawn. */ private ArrayList<Double> m_shapePoints; /** contains the position of the mouse (used for rubberbanding). */ private final Dimension m_newMousePos; /** Constructor */ public PlotPanel() { this.setBackground(this.m_plot2D.getBackground()); this.setLayout(new BorderLayout()); this.add(this.m_plot2D, BorderLayout.CENTER); this.m_plot2D.setPlotCompanion(this); this.m_createShape = false; this.m_shapes = null;// // this.m_shapePoints = null; this.m_newMousePos = new Dimension(); this.addMouseListener(new MouseAdapter() { // ///// @Override public void mousePressed(final MouseEvent e) { if ((e.getModifiers() & MouseEvent.BUTTON1_MASK) == MouseEvent.BUTTON1_MASK) { // if (PlotPanel.this.m_sIndex == 0) { // do nothing it will get dealt to in the clicked method } else if (PlotPanel.this.m_sIndex == 1) { PlotPanel.this.m_createShape = true; PlotPanel.this.m_shapePoints = new ArrayList<Double>(5); PlotPanel.this.m_shapePoints.add(new Double(PlotPanel.this.m_sIndex)); PlotPanel.this.m_shapePoints.add(new Double(e.getX())); PlotPanel.this.m_shapePoints.add(new Double(e.getY())); PlotPanel.this.m_shapePoints.add(new Double(e.getX())); PlotPanel.this.m_shapePoints.add(new Double(e.getY())); // Graphics g = PlotPanel.this.getGraphics(); Graphics g = PlotPanel.this.m_plot2D.getGraphics(); g.setColor(Color.black); g.setXORMode(Color.white); g.drawRect(PlotPanel.this.m_shapePoints.get(1).intValue(), PlotPanel.this.m_shapePoints.get(2).intValue(), PlotPanel.this.m_shapePoints.get(3).intValue() - PlotPanel.this.m_shapePoints.get(1).intValue(), PlotPanel.this.m_shapePoints.get(4).intValue() - PlotPanel.this.m_shapePoints.get(2).intValue()); g.dispose(); } // System.out.println("clicked"); } // System.out.println("clicked"); } // //// @Override public void mouseClicked(final MouseEvent e) { if ((PlotPanel.this.m_sIndex == 2 || PlotPanel.this.m_sIndex == 3) && (PlotPanel.this.m_createShape || (e.getModifiers() & MouseEvent.BUTTON1_MASK) == MouseEvent.BUTTON1_MASK)) { if (PlotPanel.this.m_createShape) { // then it has been started already. Graphics g = PlotPanel.this.m_plot2D.getGraphics(); g.setColor(Color.black); g.setXORMode(Color.white); if ((e.getModifiers() & MouseEvent.BUTTON1_MASK) == MouseEvent.BUTTON1_MASK && !e.isAltDown()) { PlotPanel.this.m_shapePoints.add(new Double(PlotPanel.this.m_plot2D.convertToAttribX(e.getX()))); PlotPanel.this.m_shapePoints.add(new Double(PlotPanel.this.m_plot2D.convertToAttribY(e.getY()))); PlotPanel.this.m_newMousePos.width = e.getX(); PlotPanel.this.m_newMousePos.height = e.getY(); g.drawLine((int) Math.ceil(PlotPanel.this.m_plot2D.convertToPanelX(PlotPanel.this.m_shapePoints.get(PlotPanel.this.m_shapePoints.size() - 2).doubleValue())), (int) Math.ceil(PlotPanel.this.m_plot2D.convertToPanelY(PlotPanel.this.m_shapePoints.get(PlotPanel.this.m_shapePoints.size() - 1).doubleValue())), PlotPanel.this.m_newMousePos.width, PlotPanel.this.m_newMousePos.height); } else if (PlotPanel.this.m_sIndex == 3) { // then extend the lines to infinity // (100000 or so should be enough). // the area is selected by where the user right clicks // the mouse button PlotPanel.this.m_createShape = false; if (PlotPanel.this.m_shapePoints.size() >= 5) { double cx = Math.ceil(PlotPanel.this.m_plot2D.convertToPanelX(PlotPanel.this.m_shapePoints.get(PlotPanel.this.m_shapePoints.size() - 4).doubleValue())); double cx2 = Math.ceil(PlotPanel.this.m_plot2D.convertToPanelX(PlotPanel.this.m_shapePoints.get(PlotPanel.this.m_shapePoints.size() - 2).doubleValue())) - cx; cx2 *= 50000; double cy = Math.ceil(PlotPanel.this.m_plot2D.convertToPanelY(PlotPanel.this.m_shapePoints.get(PlotPanel.this.m_shapePoints.size() - 3).doubleValue())); double cy2 = Math.ceil(PlotPanel.this.m_plot2D.convertToPanelY(PlotPanel.this.m_shapePoints.get(PlotPanel.this.m_shapePoints.size() - 1).doubleValue())) - cy; cy2 *= 50000; double cxa = Math.ceil(PlotPanel.this.m_plot2D.convertToPanelX(PlotPanel.this.m_shapePoints.get(3).doubleValue())); double cxa2 = Math.ceil(PlotPanel.this.m_plot2D.convertToPanelX(PlotPanel.this.m_shapePoints.get(1).doubleValue())) - cxa; cxa2 *= 50000; double cya = Math.ceil(PlotPanel.this.m_plot2D.convertToPanelY(PlotPanel.this.m_shapePoints.get(4).doubleValue())); double cya2 = Math.ceil(PlotPanel.this.m_plot2D.convertToPanelY(PlotPanel.this.m_shapePoints.get(2).doubleValue())) - cya; cya2 *= 50000; PlotPanel.this.m_shapePoints.set(1, new Double(PlotPanel.this.m_plot2D.convertToAttribX(cxa2 + cxa))); PlotPanel.this.m_shapePoints.set(PlotPanel.this.m_shapePoints.size() - 1, new Double(PlotPanel.this.m_plot2D.convertToAttribY(cy2 + cy))); PlotPanel.this.m_shapePoints.set(PlotPanel.this.m_shapePoints.size() - 2, new Double(PlotPanel.this.m_plot2D.convertToAttribX(cx2 + cx))); PlotPanel.this.m_shapePoints.set(2, new Double(PlotPanel.this.m_plot2D.convertToAttribY(cya2 + cya))); // determine how infinity line should be built cy = Double.POSITIVE_INFINITY; cy2 = Double.NEGATIVE_INFINITY; if (PlotPanel.this.m_shapePoints.get(1).doubleValue() > PlotPanel.this.m_shapePoints.get(3).doubleValue()) { if (PlotPanel.this.m_shapePoints.get(2).doubleValue() == PlotPanel.this.m_shapePoints.get(4).doubleValue()) { cy = PlotPanel.this.m_shapePoints.get(2).doubleValue(); } } if (PlotPanel.this.m_shapePoints.get(PlotPanel.this.m_shapePoints.size() - 2).doubleValue() > PlotPanel.this.m_shapePoints.get(PlotPanel.this.m_shapePoints.size() - 4).doubleValue()) { if (PlotPanel.this.m_shapePoints.get(PlotPanel.this.m_shapePoints.size() - 3).doubleValue() == PlotPanel.this.m_shapePoints.get(PlotPanel.this.m_shapePoints.size() - 1).doubleValue()) { cy2 = PlotPanel.this.m_shapePoints.get(PlotPanel.this.m_shapePoints.size() - 1).doubleValue(); } } PlotPanel.this.m_shapePoints.add(new Double(cy)); PlotPanel.this.m_shapePoints.add(new Double(cy2)); if (!PlotPanel.this.inPolyline(PlotPanel.this.m_shapePoints, PlotPanel.this.m_plot2D.convertToAttribX(e.getX()), PlotPanel.this.m_plot2D.convertToAttribY(e.getY()))) { Double tmp = PlotPanel.this.m_shapePoints.get(PlotPanel.this.m_shapePoints.size() - 2); PlotPanel.this.m_shapePoints.set(PlotPanel.this.m_shapePoints.size() - 2, PlotPanel.this.m_shapePoints.get(PlotPanel.this.m_shapePoints.size() - 1)); PlotPanel.this.m_shapePoints.set(PlotPanel.this.m_shapePoints.size() - 1, tmp); } if (PlotPanel.this.m_shapes == null) { PlotPanel.this.m_shapes = new ArrayList<ArrayList<Double>>(4); } PlotPanel.this.m_shapes.add(PlotPanel.this.m_shapePoints); VisualizePanel.this.m_submit.setText("Submit"); VisualizePanel.this.m_submit.setActionCommand("Submit"); VisualizePanel.this.m_submit.setEnabled(true); } PlotPanel.this.m_shapePoints = null; PlotPanel.this.repaint(); } else { // then close the shape PlotPanel.this.m_createShape = false; if (PlotPanel.this.m_shapePoints.size() >= 7) { PlotPanel.this.m_shapePoints.add(PlotPanel.this.m_shapePoints.get(1)); PlotPanel.this.m_shapePoints.add(PlotPanel.this.m_shapePoints.get(2)); if (PlotPanel.this.m_shapes == null) { PlotPanel.this.m_shapes = new ArrayList<ArrayList<Double>>(4); } PlotPanel.this.m_shapes.add(PlotPanel.this.m_shapePoints); VisualizePanel.this.m_submit.setText("Submit"); VisualizePanel.this.m_submit.setActionCommand("Submit"); VisualizePanel.this.m_submit.setEnabled(true); } PlotPanel.this.m_shapePoints = null; PlotPanel.this.repaint(); } g.dispose(); // repaint(); } else if ((e.getModifiers() & MouseEvent.BUTTON1_MASK) == MouseEvent.BUTTON1_MASK) { // then this is the first point PlotPanel.this.m_createShape = true; PlotPanel.this.m_shapePoints = new ArrayList<Double>(17); PlotPanel.this.m_shapePoints.add(new Double(PlotPanel.this.m_sIndex)); PlotPanel.this.m_shapePoints.add(new Double(PlotPanel.this.m_plot2D.convertToAttribX(e.getX()))); // the // new // point PlotPanel.this.m_shapePoints.add(new Double(PlotPanel.this.m_plot2D.convertToAttribY(e.getY()))); PlotPanel.this.m_newMousePos.width = e.getX(); // the temp mouse point PlotPanel.this.m_newMousePos.height = e.getY(); Graphics g = PlotPanel.this.m_plot2D.getGraphics(); g.setColor(Color.black); g.setXORMode(Color.white); g.drawLine((int) Math.ceil(PlotPanel.this.m_plot2D.convertToPanelX(PlotPanel.this.m_shapePoints.get(1).doubleValue())), (int) Math.ceil(PlotPanel.this.m_plot2D.convertToPanelY(PlotPanel.this.m_shapePoints.get(2).doubleValue())), PlotPanel.this.m_newMousePos.width, PlotPanel.this.m_newMousePos.height); g.dispose(); } } else { if ((e.getModifiers() & InputEvent.BUTTON1_MASK) == InputEvent.BUTTON1_MASK) { PlotPanel.this.m_plot2D.searchPoints(e.getX(), e.getY(), false); } else { PlotPanel.this.m_plot2D.searchPoints(e.getX(), e.getY(), true); } } } // /////// @Override public void mouseReleased(final MouseEvent e) { if (PlotPanel.this.m_createShape) { if (PlotPanel.this.m_shapePoints.get(0).intValue() == 1) { PlotPanel.this.m_createShape = false; Graphics g = PlotPanel.this.m_plot2D.getGraphics(); g.setColor(Color.black); g.setXORMode(Color.white); g.drawRect(PlotPanel.this.m_shapePoints.get(1).intValue(), PlotPanel.this.m_shapePoints.get(2).intValue(), PlotPanel.this.m_shapePoints.get(3).intValue() - PlotPanel.this.m_shapePoints.get(1).intValue(), PlotPanel.this.m_shapePoints.get(4).intValue() - PlotPanel.this.m_shapePoints.get(2).intValue()); g.dispose(); if (PlotPanel.this.checkPoints(PlotPanel.this.m_shapePoints.get(1).doubleValue(), PlotPanel.this.m_shapePoints.get(2).doubleValue()) && PlotPanel.this.checkPoints(PlotPanel.this.m_shapePoints.get(3).doubleValue(), PlotPanel.this.m_shapePoints.get(4).doubleValue())) { // then the points all land on the screen // now do special check for the rectangle if (PlotPanel.this.m_shapePoints.get(1).doubleValue() < PlotPanel.this.m_shapePoints.get(3).doubleValue() && PlotPanel.this.m_shapePoints.get(2).doubleValue() < PlotPanel.this.m_shapePoints.get(4).doubleValue()) { // then the rectangle is valid if (PlotPanel.this.m_shapes == null) { PlotPanel.this.m_shapes = new ArrayList<ArrayList<Double>>(2); } PlotPanel.this.m_shapePoints.set(1, new Double(PlotPanel.this.m_plot2D.convertToAttribX(PlotPanel.this.m_shapePoints.get(1).doubleValue()))); PlotPanel.this.m_shapePoints.set(2, new Double(PlotPanel.this.m_plot2D.convertToAttribY(PlotPanel.this.m_shapePoints.get(2).doubleValue()))); PlotPanel.this.m_shapePoints.set(3, new Double(PlotPanel.this.m_plot2D.convertToAttribX(PlotPanel.this.m_shapePoints.get(3).doubleValue()))); PlotPanel.this.m_shapePoints.set(4, new Double(PlotPanel.this.m_plot2D.convertToAttribY(PlotPanel.this.m_shapePoints.get(4).doubleValue()))); PlotPanel.this.m_shapes.add(PlotPanel.this.m_shapePoints); VisualizePanel.this.m_submit.setText("Submit"); VisualizePanel.this.m_submit.setActionCommand("Submit"); VisualizePanel.this.m_submit.setEnabled(true); PlotPanel.this.repaint(); } } PlotPanel.this.m_shapePoints = null; } } } }); this.addMouseMotionListener(new MouseMotionAdapter() { @Override public void mouseDragged(final MouseEvent e) { // check if the user is dragging a box if (PlotPanel.this.m_createShape) { if (PlotPanel.this.m_shapePoints.get(0).intValue() == 1) { Graphics g = PlotPanel.this.m_plot2D.getGraphics(); g.setColor(Color.black); g.setXORMode(Color.white); g.drawRect(PlotPanel.this.m_shapePoints.get(1).intValue(), PlotPanel.this.m_shapePoints.get(2).intValue(), PlotPanel.this.m_shapePoints.get(3).intValue() - PlotPanel.this.m_shapePoints.get(1).intValue(), PlotPanel.this.m_shapePoints.get(4).intValue() - PlotPanel.this.m_shapePoints.get(2).intValue()); PlotPanel.this.m_shapePoints.set(3, new Double(e.getX())); PlotPanel.this.m_shapePoints.set(4, new Double(e.getY())); g.drawRect(PlotPanel.this.m_shapePoints.get(1).intValue(), PlotPanel.this.m_shapePoints.get(2).intValue(), PlotPanel.this.m_shapePoints.get(3).intValue() - PlotPanel.this.m_shapePoints.get(1).intValue(), PlotPanel.this.m_shapePoints.get(4).intValue() - PlotPanel.this.m_shapePoints.get(2).intValue()); g.dispose(); } } } @Override public void mouseMoved(final MouseEvent e) { if (PlotPanel.this.m_createShape) { if (PlotPanel.this.m_shapePoints.get(0).intValue() == 2 || PlotPanel.this.m_shapePoints.get(0).intValue() == 3) { Graphics g = PlotPanel.this.m_plot2D.getGraphics(); g.setColor(Color.black); g.setXORMode(Color.white); g.drawLine((int) Math.ceil(PlotPanel.this.m_plot2D.convertToPanelX(PlotPanel.this.m_shapePoints.get(PlotPanel.this.m_shapePoints.size() - 2).doubleValue())), (int) Math.ceil(PlotPanel.this.m_plot2D.convertToPanelY(PlotPanel.this.m_shapePoints.get(PlotPanel.this.m_shapePoints.size() - 1).doubleValue())), PlotPanel.this.m_newMousePos.width, PlotPanel.this.m_newMousePos.height); PlotPanel.this.m_newMousePos.width = e.getX(); PlotPanel.this.m_newMousePos.height = e.getY(); g.drawLine((int) Math.ceil(PlotPanel.this.m_plot2D.convertToPanelX(PlotPanel.this.m_shapePoints.get(PlotPanel.this.m_shapePoints.size() - 2).doubleValue())), (int) Math.ceil(PlotPanel.this.m_plot2D.convertToPanelY(PlotPanel.this.m_shapePoints.get(PlotPanel.this.m_shapePoints.size() - 1).doubleValue())), PlotPanel.this.m_newMousePos.width, PlotPanel.this.m_newMousePos.height); g.dispose(); } } } }); VisualizePanel.this.m_submit.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { if (e.getActionCommand().equals("Submit")) { if (VisualizePanel.this.m_splitListener != null && PlotPanel.this.m_shapes != null) { // then send the split to the listener Instances sub_set1 = new Instances(PlotPanel.this.m_plot2D.getMasterPlot().m_plotInstances, 500); Instances sub_set2 = new Instances(PlotPanel.this.m_plot2D.getMasterPlot().m_plotInstances, 500); if (PlotPanel.this.m_plot2D.getMasterPlot().m_plotInstances != null) { for (int noa = 0; noa < PlotPanel.this.m_plot2D.getMasterPlot().m_plotInstances.numInstances(); noa++) { if (!PlotPanel.this.m_plot2D.getMasterPlot().m_plotInstances.instance(noa).isMissing(PlotPanel.this.m_xIndex) && !PlotPanel.this.m_plot2D.getMasterPlot().m_plotInstances.instance(noa).isMissing(PlotPanel.this.m_yIndex)) { if (PlotPanel.this.inSplit(PlotPanel.this.m_plot2D.getMasterPlot().m_plotInstances.instance(noa))) { sub_set1.add(PlotPanel.this.m_plot2D.getMasterPlot().m_plotInstances.instance(noa)); } else { sub_set2.add(PlotPanel.this.m_plot2D.getMasterPlot().m_plotInstances.instance(noa)); } } } ArrayList<ArrayList<Double>> tmp = PlotPanel.this.m_shapes; PlotPanel.this.cancelShapes(); VisualizePanel.this.m_splitListener.userDataEvent(new VisualizePanelEvent(tmp, sub_set1, sub_set2, PlotPanel.this.m_xIndex, PlotPanel.this.m_yIndex)); } } else if (PlotPanel.this.m_shapes != null && PlotPanel.this.m_plot2D.getMasterPlot().m_plotInstances != null) { Instances sub_set1 = new Instances(PlotPanel.this.m_plot2D.getMasterPlot().m_plotInstances, 500); int count = 0; for (int noa = 0; noa < PlotPanel.this.m_plot2D.getMasterPlot().m_plotInstances.numInstances(); noa++) { if (PlotPanel.this.inSplit(PlotPanel.this.m_plot2D.getMasterPlot().m_plotInstances.instance(noa))) { sub_set1.add(PlotPanel.this.m_plot2D.getMasterPlot().m_plotInstances.instance(noa)); count++; } } int[] nSizes = null; int[] nTypes = null; boolean[] connect = null; int x = PlotPanel.this.m_xIndex; int y = PlotPanel.this.m_yIndex; if (PlotPanel.this.m_originalPlot == null) { // this sets these instances as the instances // to go back to. PlotPanel.this.m_originalPlot = PlotPanel.this.m_plot2D.getMasterPlot(); } if (count > 0) { nTypes = new int[count]; nSizes = new int[count]; connect = new boolean[count]; count = 0; for (int noa = 0; noa < PlotPanel.this.m_plot2D.getMasterPlot().m_plotInstances.numInstances(); noa++) { if (PlotPanel.this.inSplit(PlotPanel.this.m_plot2D.getMasterPlot().m_plotInstances.instance(noa))) { nTypes[count] = PlotPanel.this.m_plot2D.getMasterPlot().m_shapeType[noa]; nSizes[count] = PlotPanel.this.m_plot2D.getMasterPlot().m_shapeSize[noa]; connect[count] = PlotPanel.this.m_plot2D.getMasterPlot().m_connectPoints[noa]; count++; } } } PlotPanel.this.cancelShapes(); PlotData2D newPlot = new PlotData2D(sub_set1); try { newPlot.setShapeSize(nSizes); newPlot.setShapeType(nTypes); newPlot.setConnectPoints(connect); PlotPanel.this.m_plot2D.removeAllPlots(); VisualizePanel.this.addPlot(newPlot); } catch (Exception ex) { System.err.println(ex); ex.printStackTrace(); } try { VisualizePanel.this.setXIndex(x); VisualizePanel.this.setYIndex(y); } catch (Exception er) { System.out.println("Error : " + er); // System.out.println("Part of user input so had to" + // " catch here"); } } } else if (e.getActionCommand().equals("Reset")) { int x = PlotPanel.this.m_xIndex; int y = PlotPanel.this.m_yIndex; PlotPanel.this.m_plot2D.removeAllPlots(); try { VisualizePanel.this.addPlot(PlotPanel.this.m_originalPlot); } catch (Exception ex) { System.err.println(ex); ex.printStackTrace(); } try { VisualizePanel.this.setXIndex(x); VisualizePanel.this.setYIndex(y); } catch (Exception er) { System.out.println("Error : " + er); } } } }); VisualizePanel.this.m_cancel.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { PlotPanel.this.cancelShapes(); PlotPanel.this.repaint(); } }); // ////////// } /** * Apply settings * * @param settings the settings to apply * @param ownerID the ID of the owner perspective, panel etc. This key is * used when looking up our settings */ protected void applySettings(final Settings settings, final String ownerID) { this.m_plot2D.applySettings(settings, ownerID); this.setBackground(this.m_plot2D.getBackground()); this.repaint(); } /** * Removes all the plots. */ public void removeAllPlots() { this.m_plot2D.removeAllPlots(); VisualizePanel.this.m_legendPanel.setPlotList(this.m_plot2D.getPlots()); } /** * @return The FastVector containing all the shapes. */ public ArrayList<ArrayList<Double>> getShapes() { return this.m_shapes; } /** * Sets the list of shapes to empty and also cancels the current shape being * drawn (if applicable). */ public void cancelShapes() { if (VisualizePanel.this.m_splitListener == null) { VisualizePanel.this.m_submit.setText("Reset"); VisualizePanel.this.m_submit.setActionCommand("Reset"); if (this.m_originalPlot == null || this.m_originalPlot.m_plotInstances == this.m_plotInstances) { VisualizePanel.this.m_submit.setEnabled(false); } else { VisualizePanel.this.m_submit.setEnabled(true); } } else { VisualizePanel.this.m_submit.setEnabled(false); } this.m_createShape = false; this.m_shapePoints = null; this.m_shapes = null; this.repaint(); } /** * This can be used to set the shapes that should appear. * * @param v The list of shapes. */ public void setShapes(final ArrayList<ArrayList<Double>> v) { // note that this method should be fine for doubles, // but anything else that uses something other than doubles // (or uneditable objects) could have unsafe copies. if (v != null) { ArrayList<Double> temp; this.m_shapes = new ArrayList<ArrayList<Double>>(v.size()); for (int noa = 0; noa < v.size(); noa++) { temp = new ArrayList<Double>(v.get(noa).size()); this.m_shapes.add(temp); for (int nob = 0; nob < v.get(noa).size(); nob++) { temp.add(v.get(noa).get(nob)); } } } else { this.m_shapes = null; } this.repaint(); } /** * This will check the values of the screen points passed and make sure that * they land on the screen * * @param x1 The x coord. * @param y1 The y coord. * @return true if the point would land on the screen */ private boolean checkPoints(final double x1, final double y1) { if (x1 < 0 || x1 > this.getSize().width || y1 < 0 || y1 > this.getSize().height) { return false; } return true; } /** * This will check if an instance is inside or outside of the current * shapes. * * @param i The instance to check. * @return True if 'i' falls inside the shapes, false otherwise. */ public boolean inSplit(final Instance i) { // this will check if the instance lies inside the shapes or not if (this.m_shapes != null) { ArrayList<Double> stmp; double x1, y1, x2, y2; for (int noa = 0; noa < this.m_shapes.size(); noa++) { stmp = this.m_shapes.get(noa); if (stmp.get(0).intValue() == 1) { // then rectangle x1 = stmp.get(1).doubleValue(); y1 = stmp.get(2).doubleValue(); x2 = stmp.get(3).doubleValue(); y2 = stmp.get(4).doubleValue(); if (i.value(this.m_xIndex) >= x1 && i.value(this.m_xIndex) <= x2 && i.value(this.m_yIndex) <= y1 && i.value(this.m_yIndex) >= y2) { // then is inside split so return true; return true; } } else if (stmp.get(0).intValue() == 2) { // then polygon if (this.inPoly(stmp, i.value(this.m_xIndex), i.value(this.m_yIndex))) { return true; } } else if (stmp.get(0).intValue() == 3) { // then polyline if (this.inPolyline(stmp, i.value(this.m_xIndex), i.value(this.m_yIndex))) { return true; } } } } return false; } /** * Checks to see if the coordinate passed is inside the ployline passed, * Note that this is done using attribute values and not there respective * screen values. * * @param ob The polyline. * @param x The x coord. * @param y The y coord. * @return True if it falls inside the polyline, false otherwise. */ private boolean inPolyline(final ArrayList<Double> ob, final double x, final double y) { // this works similar to the inPoly below except that // the first and last lines are treated as extending infinite in one // direction and // then infinitly in the x dirction their is a line that will // normaly be infinite but // can be finite in one or both directions int countx = 0; double vecx, vecy; double change; double x1, y1, x2, y2; for (int noa = 1; noa < ob.size() - 4; noa += 2) { y1 = ob.get(noa + 1).doubleValue(); y2 = ob.get(noa + 3).doubleValue(); x1 = ob.get(noa).doubleValue(); x2 = ob.get(noa + 2).doubleValue(); // System.err.println(y1 + " " + y2 + " " + x1 + " " + x2); vecy = y2 - y1; vecx = x2 - x1; if (noa == 1 && noa == ob.size() - 6) { // then do special test first and last edge if (vecy != 0) { change = (y - y1) / vecy; if (vecx * change + x1 >= x) { // then intersection countx++; } } } else if (noa == 1) { if ((y < y2 && vecy > 0) || (y > y2 && vecy < 0)) { // now just determine intersection or not change = (y - y1) / vecy; if (vecx * change + x1 >= x) { // then intersection on horiz countx++; } } } else if (noa == ob.size() - 6) { // then do special test on last edge if ((y <= y1 && vecy < 0) || (y >= y1 && vecy > 0)) { change = (y - y1) / vecy; if (vecx * change + x1 >= x) { countx++; } } } else if ((y1 <= y && y < y2) || (y2 < y && y <= y1)) { // then continue tests. if (vecy == 0) { // then lines are parallel stop tests in // ofcourse it should never make it this far } else { change = (y - y1) / vecy; if (vecx * change + x1 >= x) { // then intersects on horiz countx++; } } } } // now check for intersection with the infinity line y1 = ob.get(ob.size() - 2).doubleValue(); y2 = ob.get(ob.size() - 1).doubleValue(); if (y1 > y2) { // then normal line if (y1 >= y && y > y2) { countx++; } } else { // then the line segment is inverted if (y1 >= y || y > y2) { countx++; } } if ((countx % 2) == 1) { return true; } else { return false; } } /** * This checks to see if The coordinate passed is inside the polygon that * was passed. * * @param ob The polygon. * @param x The x coord. * @param y The y coord. * @return True if the coordinate is in the polygon, false otherwise. */ private boolean inPoly(final ArrayList<Double> ob, final double x, final double y) { // brief on how this works // it draws a line horizontally from the point to the right (infinitly) // it then sees how many lines of the polygon intersect this, // if it is even then the point is // outside the polygon if it's odd then it's inside the polygon int count = 0; double vecx, vecy; double change; double x1, y1, x2, y2; for (int noa = 1; noa < ob.size() - 2; noa += 2) { y1 = ob.get(noa + 1).doubleValue(); y2 = ob.get(noa + 3).doubleValue(); if ((y1 <= y && y < y2) || (y2 < y && y <= y1)) { // then continue tests. vecy = y2 - y1; if (vecy == 0) { // then lines are parallel stop tests for this line } else { x1 = ob.get(noa).doubleValue(); x2 = ob.get(noa + 2).doubleValue(); vecx = x2 - x1; change = (y - y1) / vecy; if (vecx * change + x1 >= x) { // then add to count as an intersected line count++; } } } } if ((count % 2) == 1) { // then lies inside polygon // System.out.println("in"); return true; } else { // System.out.println("out"); return false; } // System.out.println("WHAT?!?!?!?!!?!??!?!"); // return false; } /** * Set level of jitter and repaint the plot using the new jitter value * * @param j the level of jitter */ public void setJitter(final int j) { this.m_plot2D.setJitter(j); } /** * Set the index of the attribute to go on the x axis * * @param x the index of the attribute to use on the x axis */ public void setXindex(final int x) { // this just ensures that the shapes get disposed of // if the attribs change if (x != this.m_xIndex) { this.cancelShapes(); } this.m_xIndex = x; this.m_plot2D.setXindex(x); if (VisualizePanel.this.m_showAttBars) { VisualizePanel.this.m_attrib.setX(x); } // this.repaint(); } /** * Set the index of the attribute to go on the y axis * * @param y the index of the attribute to use on the y axis */ public void setYindex(final int y) { // this just ensures that the shapes get disposed of // if the attribs change if (y != this.m_yIndex) { this.cancelShapes(); } this.m_yIndex = y; this.m_plot2D.setYindex(y); if (VisualizePanel.this.m_showAttBars) { VisualizePanel.this.m_attrib.setY(y); } // this.repaint(); } /** * Set the index of the attribute to use for colouring * * @param c the index of the attribute to use for colouring */ public void setCindex(final int c) { this.m_cIndex = c; this.m_plot2D.setCindex(c); if (VisualizePanel.this.m_showAttBars) { VisualizePanel.this.m_attrib.setCindex(c, this.m_plot2D.getMaxC(), this.m_plot2D.getMinC()); } VisualizePanel.this.m_classPanel.setCindex(c); this.repaint(); } /** * Set the index of the attribute to use for the shape. * * @param s the index of the attribute to use for the shape */ public void setSindex(final int s) { if (s != this.m_sIndex) { this.m_shapePoints = null; this.m_createShape = false; } this.m_sIndex = s; this.repaint(); } /** * Clears all existing plots and sets a new master plot * * @param newPlot the new master plot * @exception Exception if plot could not be added */ public void setMasterPlot(final PlotData2D newPlot) throws Exception { this.m_plot2D.removeAllPlots(); this.addPlot(newPlot); } /** * Adds a plot. If there are no plots so far this plot becomes the master * plot and, if it has a custom colour defined then the class panel is * removed. * * @param newPlot the plot to add. * @exception Exception if plot could not be added */ public void addPlot(final PlotData2D newPlot) throws Exception { if (this.m_plot2D.getPlots().size() == 0) { this.m_plot2D.addPlot(newPlot); if (VisualizePanel.this.m_plotSurround.getComponentCount() > 1 && VisualizePanel.this.m_plotSurround.getComponent(1) == VisualizePanel.this.m_attrib && VisualizePanel.this.m_showAttBars) { try { VisualizePanel.this.m_attrib.setInstances(newPlot.m_plotInstances); VisualizePanel.this.m_attrib.setCindex(0); VisualizePanel.this.m_attrib.setX(0); VisualizePanel.this.m_attrib.setY(0); } catch (Exception ex) { // more attributes than the panel can handle? // Due to hard coded constraints in GridBagLayout VisualizePanel.this.m_plotSurround.remove(VisualizePanel.this.m_attrib); System.err.println("Warning : data contains more attributes " + "than can be displayed as attribute bars."); if (VisualizePanel.this.m_Log != null) { VisualizePanel.this.m_Log.logMessage("Warning : data contains more attributes " + "than can be displayed as attribute bars."); } } } else if (VisualizePanel.this.m_showAttBars) { try { VisualizePanel.this.m_attrib.setInstances(newPlot.m_plotInstances); VisualizePanel.this.m_attrib.setCindex(0); VisualizePanel.this.m_attrib.setX(0); VisualizePanel.this.m_attrib.setY(0); GridBagConstraints constraints = new GridBagConstraints(); constraints.fill = GridBagConstraints.BOTH; constraints.insets = new Insets(0, 0, 0, 0); constraints.gridx = 4; constraints.gridy = 0; constraints.weightx = 1; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.weighty = 5; VisualizePanel.this.m_plotSurround.add(VisualizePanel.this.m_attrib, constraints); } catch (Exception ex) { System.err.println("Warning : data contains more attributes " + "than can be displayed as attribute bars."); if (VisualizePanel.this.m_Log != null) { VisualizePanel.this.m_Log.logMessage("Warning : data contains more attributes " + "than can be displayed as attribute bars."); } } } VisualizePanel.this.m_classPanel.setInstances(newPlot.m_plotInstances); this.plotReset(newPlot.m_plotInstances, newPlot.getCindex()); if (newPlot.m_useCustomColour && VisualizePanel.this.m_showClassPanel) { VisualizePanel.this.remove(VisualizePanel.this.m_classSurround); this.switchToLegend(); VisualizePanel.this.m_legendPanel.setPlotList(this.m_plot2D.getPlots()); VisualizePanel.this.m_ColourCombo.setEnabled(false); } } else { if (!newPlot.m_useCustomColour && VisualizePanel.this.m_showClassPanel) { VisualizePanel.this.add(VisualizePanel.this.m_classSurround, BorderLayout.SOUTH); VisualizePanel.this.m_ColourCombo.setEnabled(true); } if (this.m_plot2D.getPlots().size() == 1) { this.switchToLegend(); } this.m_plot2D.addPlot(newPlot); VisualizePanel.this.m_legendPanel.setPlotList(this.m_plot2D.getPlots()); } } /** * Remove the attibute panel and replace it with the legend panel */ protected void switchToLegend() { if (VisualizePanel.this.m_plotSurround.getComponentCount() > 1 && VisualizePanel.this.m_plotSurround.getComponent(1) == VisualizePanel.this.m_attrib) { VisualizePanel.this.m_plotSurround.remove(VisualizePanel.this.m_attrib); } if (VisualizePanel.this.m_plotSurround.getComponentCount() > 1 && VisualizePanel.this.m_plotSurround.getComponent(1) == VisualizePanel.this.m_legendPanel) { return; } GridBagConstraints constraints = new GridBagConstraints(); constraints.fill = GridBagConstraints.BOTH; constraints.insets = new Insets(0, 0, 0, 0); constraints.gridx = 4; constraints.gridy = 0; constraints.weightx = 1; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.weighty = 5; VisualizePanel.this.m_plotSurround.add(VisualizePanel.this.m_legendPanel, constraints); this.setSindex(0); VisualizePanel.this.m_ShapeCombo.setEnabled(false); } protected void switchToBars() { if (VisualizePanel.this.m_plotSurround.getComponentCount() > 1 && VisualizePanel.this.m_plotSurround.getComponent(1) == VisualizePanel.this.m_legendPanel) { VisualizePanel.this.m_plotSurround.remove(VisualizePanel.this.m_legendPanel); } if (VisualizePanel.this.m_plotSurround.getComponentCount() > 1 && VisualizePanel.this.m_plotSurround.getComponent(1) == VisualizePanel.this.m_attrib) { return; } if (VisualizePanel.this.m_showAttBars) { try { VisualizePanel.this.m_attrib.setInstances(this.m_plot2D.getMasterPlot().m_plotInstances); VisualizePanel.this.m_attrib.setCindex(0); VisualizePanel.this.m_attrib.setX(0); VisualizePanel.this.m_attrib.setY(0); GridBagConstraints constraints = new GridBagConstraints(); constraints.fill = GridBagConstraints.BOTH; constraints.insets = new Insets(0, 0, 0, 0); constraints.gridx = 4; constraints.gridy = 0; constraints.weightx = 1; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.weighty = 5; VisualizePanel.this.m_plotSurround.add(VisualizePanel.this.m_attrib, constraints); } catch (Exception ex) { System.err.println("Warning : data contains more attributes " + "than can be displayed as attribute bars."); if (VisualizePanel.this.m_Log != null) { VisualizePanel.this.m_Log.logMessage("Warning : data contains more attributes " + "than can be displayed as attribute bars."); } } } } /** * Reset the visualize panel's buttons and the plot panels instances * * @param inst the data * @param cIndex the color index * @throws InterruptedException */ private void plotReset(final Instances inst, final int cIndex) { if (VisualizePanel.this.m_splitListener == null) { VisualizePanel.this.m_submit.setText("Reset"); VisualizePanel.this.m_submit.setActionCommand("Reset"); // if (m_origInstances == null || m_origInstances == inst) { if (this.m_originalPlot == null || this.m_originalPlot.m_plotInstances == inst) { VisualizePanel.this.m_submit.setEnabled(false); } else { VisualizePanel.this.m_submit.setEnabled(true); } } else { VisualizePanel.this.m_submit.setEnabled(false); } this.m_plotInstances = inst; if (VisualizePanel.this.m_splitListener != null) { try { this.m_plotInstances.randomize(new Random()); } catch (InterruptedException e) { throw new IllegalStateException(e); } } this.m_xIndex = 0; this.m_yIndex = 0; this.m_cIndex = cIndex; this.cancelShapes(); } /** * Set a list of colours to use for plotting points * * @param cols a list of java.awt.Colors */ public void setColours(final ArrayList<Color> cols) { this.m_plot2D.setColours(cols); VisualizePanel.this.m_colorList = cols; } /** * This will draw the shapes created onto the panel. For best visual, this * should be the first thing to be drawn (and it currently is). * * @param gx The graphics context. */ private void drawShapes(final Graphics gx) { // FastVector tmp = m_plot.getShapes(); if (this.m_shapes != null) { ArrayList<Double> stmp; int x1, y1, x2, y2; for (int noa = 0; noa < this.m_shapes.size(); noa++) { stmp = this.m_shapes.get(noa); if (stmp.get(0).intValue() == 1) { // then rectangle x1 = (int) this.m_plot2D.convertToPanelX(stmp.get(1).doubleValue()); y1 = (int) this.m_plot2D.convertToPanelY(stmp.get(2).doubleValue()); x2 = (int) this.m_plot2D.convertToPanelX(stmp.get(3).doubleValue()); y2 = (int) this.m_plot2D.convertToPanelY(stmp.get(4).doubleValue()); gx.setColor(Color.gray); gx.fillRect(x1, y1, x2 - x1, y2 - y1); gx.setColor(Color.black); gx.drawRect(x1, y1, x2 - x1, y2 - y1); } else if (stmp.get(0).intValue() == 2) { // then polygon int[] ar1, ar2; ar1 = this.getXCoords(stmp); ar2 = this.getYCoords(stmp); gx.setColor(Color.gray); gx.fillPolygon(ar1, ar2, (stmp.size() - 1) / 2); gx.setColor(Color.black); gx.drawPolyline(ar1, ar2, (stmp.size() - 1) / 2); } else if (stmp.get(0).intValue() == 3) { // then polyline int[] ar1, ar2; ArrayList<Double> tmp = this.makePolygon(stmp); ar1 = this.getXCoords(tmp); ar2 = this.getYCoords(tmp); gx.setColor(Color.gray); gx.fillPolygon(ar1, ar2, (tmp.size() - 1) / 2); gx.setColor(Color.black); gx.drawPolyline(ar1, ar2, (tmp.size() - 1) / 2); } } } if (this.m_shapePoints != null) { // then the current image needs to be refreshed if (this.m_shapePoints.get(0).intValue() == 2 || this.m_shapePoints.get(0).intValue() == 3) { gx.setColor(Color.black); gx.setXORMode(Color.white); int[] ar1, ar2; ar1 = this.getXCoords(this.m_shapePoints); ar2 = this.getYCoords(this.m_shapePoints); gx.drawPolyline(ar1, ar2, (this.m_shapePoints.size() - 1) / 2); this.m_newMousePos.width = (int) Math.ceil(this.m_plot2D.convertToPanelX(this.m_shapePoints.get(this.m_shapePoints.size() - 2).doubleValue())); this.m_newMousePos.height = (int) Math.ceil(this.m_plot2D.convertToPanelY(this.m_shapePoints.get(this.m_shapePoints.size() - 1).doubleValue())); gx.drawLine((int) Math.ceil(this.m_plot2D.convertToPanelX(this.m_shapePoints.get(this.m_shapePoints.size() - 2).doubleValue())), (int) Math.ceil(this.m_plot2D.convertToPanelY(this.m_shapePoints.get(this.m_shapePoints.size() - 1).doubleValue())), this.m_newMousePos.width, this.m_newMousePos.height); gx.setPaintMode(); } } } /** * This is called for polylines to see where there two lines that extend to * infinity cut the border of the view. * * @param x1 an x point along the line * @param y1 the accompanying y point. * @param x2 The x coord of the end point of the line. * @param y2 The y coord of the end point of the line. * @param x 0 or the width of the border line if it has one. * @param y 0 or the height of the border line if it has one. * @param offset The offset for the border line (either for x or y dependant * on which one doesn't change). * @return double array that contains the coordinate for the point that the * polyline cuts the border (which ever side that may be). */ private double[] lineIntersect(final double x1, final double y1, final double x2, final double y2, final double x, final double y, final double offset) { // the first 4 params are thestart and end points of a line // the next param is either 0 for no change in x or change in x, // the next param is the same for y // the final 1 is the offset for either x or y (which ever has no change) double xval; double yval; double xn = -100, yn = -100; double change; if (x == 0) { if ((x1 <= offset && offset < x2) || (x1 >= offset && offset > x2)) { // then continue xval = x1 - x2; change = (offset - x2) / xval; yn = (y1 - y2) * change + y2; if (0 <= yn && yn <= y) { // then good xn = offset; } else { // no intersect xn = -100; } } } else if (y == 0) { if ((y1 <= offset && offset < y2) || (y1 >= offset && offset > y2)) { // the continue yval = (y1 - y2); change = (offset - y2) / yval; xn = (x1 - x2) * change + x2; if (0 <= xn && xn <= x) { // then good yn = offset; } else { xn = -100; } } } double[] ret = new double[2]; ret[0] = xn; ret[1] = yn; return ret; } /** * This will convert a polyline to a polygon for drawing purposes So that I * can simply use the polygon drawing function. * * @param v The polyline to convert. * @return A FastVector containing the polygon. */ private ArrayList<Double> makePolygon(final ArrayList<Double> v) { ArrayList<Double> building = new ArrayList<Double>(v.size() + 10); double x1, y1, x2, y2; int edge1 = 0, edge2 = 0; for (int noa = 0; noa < v.size() - 2; noa++) { building.add(new Double(v.get(noa).doubleValue())); } // now clip the lines double[] new_coords; // note lineIntersect , expects the values to have been converted to // screen coords // note the first point passed is the one that gets shifted. x1 = this.m_plot2D.convertToPanelX(v.get(1).doubleValue()); y1 = this.m_plot2D.convertToPanelY(v.get(2).doubleValue()); x2 = this.m_plot2D.convertToPanelX(v.get(3).doubleValue()); y2 = this.m_plot2D.convertToPanelY(v.get(4).doubleValue()); if (x1 < 0) { // test left new_coords = this.lineIntersect(x1, y1, x2, y2, 0, this.getHeight(), 0); edge1 = 0; if (new_coords[0] < 0) { // then not left if (y1 < 0) { // test top new_coords = this.lineIntersect(x1, y1, x2, y2, this.getWidth(), 0, 0); edge1 = 1; } else { // test bottom new_coords = this.lineIntersect(x1, y1, x2, y2, this.getWidth(), 0, this.getHeight()); edge1 = 3; } } } else if (x1 > this.getWidth()) { // test right new_coords = this.lineIntersect(x1, y1, x2, y2, 0, this.getHeight(), this.getWidth()); edge1 = 2; if (new_coords[0] < 0) { // then not right if (y1 < 0) { // test top new_coords = this.lineIntersect(x1, y1, x2, y2, this.getWidth(), 0, 0); edge1 = 1; } else { // test bottom new_coords = this.lineIntersect(x1, y1, x2, y2, this.getWidth(), 0, this.getHeight()); edge1 = 3; } } } else if (y1 < 0) { // test top new_coords = this.lineIntersect(x1, y1, x2, y2, this.getWidth(), 0, 0); edge1 = 1; } else { // test bottom new_coords = this.lineIntersect(x1, y1, x2, y2, this.getWidth(), 0, this.getHeight()); edge1 = 3; } building.set(1, new Double(this.m_plot2D.convertToAttribX(new_coords[0]))); building.set(2, new Double(this.m_plot2D.convertToAttribY(new_coords[1]))); x1 = this.m_plot2D.convertToPanelX(v.get(v.size() - 4).doubleValue()); y1 = this.m_plot2D.convertToPanelY(v.get(v.size() - 3).doubleValue()); x2 = this.m_plot2D.convertToPanelX(v.get(v.size() - 6).doubleValue()); y2 = this.m_plot2D.convertToPanelY(v.get(v.size() - 5).doubleValue()); if (x1 < 0) { // test left new_coords = this.lineIntersect(x1, y1, x2, y2, 0, this.getHeight(), 0); edge2 = 0; if (new_coords[0] < 0) { // then not left if (y1 < 0) { // test top new_coords = this.lineIntersect(x1, y1, x2, y2, this.getWidth(), 0, 0); edge2 = 1; } else { // test bottom new_coords = this.lineIntersect(x1, y1, x2, y2, this.getWidth(), 0, this.getHeight()); edge2 = 3; } } } else if (x1 > this.getWidth()) { // test right new_coords = this.lineIntersect(x1, y1, x2, y2, 0, this.getHeight(), this.getWidth()); edge2 = 2; if (new_coords[0] < 0) { // then not right if (y1 < 0) { // test top new_coords = this.lineIntersect(x1, y1, x2, y2, this.getWidth(), 0, 0); edge2 = 1; } else { // test bottom new_coords = this.lineIntersect(x1, y1, x2, y2, this.getWidth(), 0, this.getHeight()); edge2 = 3; } } } else if (y1 < 0) { // test top new_coords = this.lineIntersect(x1, y1, x2, y2, this.getWidth(), 0, 0); edge2 = 1; } else { // test bottom new_coords = this.lineIntersect(x1, y1, x2, y2, this.getWidth(), 0, this.getHeight()); edge2 = 3; } building.set(building.size() - 2, new Double(this.m_plot2D.convertToAttribX(new_coords[0]))); building.set(building.size() - 1, new Double(this.m_plot2D.convertToAttribY(new_coords[1]))); // trust me this complicated piece of code will // determine what points on the boundary of the view to add to the polygon int xp, yp; xp = this.getWidth() * ((edge2 & 1) ^ ((edge2 & 2) / 2)); yp = this.getHeight() * ((edge2 & 2) / 2); // System.out.println(((-1 + 4) % 4) + " hoi"); if (this.inPolyline(v, this.m_plot2D.convertToAttribX(xp), this.m_plot2D.convertToAttribY(yp))) { // then add points in a clockwise direction building.add(new Double(this.m_plot2D.convertToAttribX(xp))); building.add(new Double(this.m_plot2D.convertToAttribY(yp))); for (int noa = (edge2 + 1) % 4; noa != edge1; noa = (noa + 1) % 4) { xp = this.getWidth() * ((noa & 1) ^ ((noa & 2) / 2)); yp = this.getHeight() * ((noa & 2) / 2); building.add(new Double(this.m_plot2D.convertToAttribX(xp))); building.add(new Double(this.m_plot2D.convertToAttribY(yp))); } } else { xp = this.getWidth() * ((edge2 & 2) / 2); yp = this.getHeight() * (1 & ~((edge2 & 1) ^ ((edge2 & 2) / 2))); if (this.inPolyline(v, this.m_plot2D.convertToAttribX(xp), this.m_plot2D.convertToAttribY(yp))) { // then add points in anticlockwise direction building.add(new Double(this.m_plot2D.convertToAttribX(xp))); building.add(new Double(this.m_plot2D.convertToAttribY(yp))); for (int noa = (edge2 + 3) % 4; noa != edge1; noa = (noa + 3) % 4) { xp = this.getWidth() * ((noa & 2) / 2); yp = this.getHeight() * (1 & ~((noa & 1) ^ ((noa & 2) / 2))); building.add(new Double(this.m_plot2D.convertToAttribX(xp))); building.add(new Double(this.m_plot2D.convertToAttribY(yp))); } } } return building; } /** * This will extract from a polygon shape its x coodrdinates so that an * awt.Polygon can be created. * * @param v The polygon shape. * @return an int array containing the screen x coords for the polygon. */ private int[] getXCoords(final ArrayList<Double> v) { int cach = (v.size() - 1) / 2; int[] ar = new int[cach]; for (int noa = 0; noa < cach; noa++) { ar[noa] = (int) this.m_plot2D.convertToPanelX(v.get(noa * 2 + 1).doubleValue()); } return ar; } /** * This will extract from a polygon shape its y coordinates so that an * awt.Polygon can be created. * * @param v The polygon shape. * @return an int array containing the screen y coords for the polygon. */ private int[] getYCoords(final ArrayList<Double> v) { int cach = (v.size() - 1) / 2; int[] ar = new int[cach]; for (int noa = 0; noa < cach; noa++) { ar[noa] = (int) this.m_plot2D.convertToPanelY(v.get(noa * 2 + 2).doubleValue()); } return ar; } /** * Renders the polygons if necessary * * @param gx the graphics context */ @Override public void prePlot(final Graphics gx) { super.paintComponent(gx); if (this.m_plotInstances != null) { this.drawShapes(gx); // will be in paintComponent of ShapePlot2D } } } /** default colours for colouring discrete class */ protected Color[] m_DefaultColors = { Color.blue, Color.red, Color.green, Color.cyan, Color.pink, new Color(255, 0, 255), Color.orange, new Color(255, 0, 0), new Color(0, 255, 0), Color.white }; /** Lets the user select the attribute for the x axis */ protected JComboBox m_XCombo = new JComboBox(); /** Lets the user select the attribute for the y axis */ protected JComboBox m_YCombo = new JComboBox(); /** Lets the user select the attribute to use for colouring */ protected JComboBox m_ColourCombo = new JComboBox(); /** * Lets the user select the shape they want to create for instance selection. */ protected JComboBox m_ShapeCombo = new JComboBox(); /** Button for the user to enter the splits. */ protected JButton m_submit = new JButton("Submit"); /** Button for the user to remove all splits. */ protected JButton m_cancel = new JButton("Clear"); /** Button for the user to open the visualized set of instances */ protected JButton m_openBut = new JButton("Open"); /** Button for the user to save the visualized set of instances */ protected JButton m_saveBut = new JButton("Save"); /** Stop the combos from growing out of control */ private final Dimension COMBO_SIZE = new Dimension(250, this.m_saveBut.getPreferredSize().height); /** file chooser for saving instances */ protected JFileChooser m_FileChooser = new JFileChooser(new File(System.getProperty("user.dir"))); /** Filter to ensure only arff files are selected */ protected FileFilter m_ArffFilter = new ExtensionFileFilter(Instances.FILE_EXTENSION, "Arff data files"); /** Label for the jitter slider */ protected JLabel m_JitterLab = new JLabel("Jitter", SwingConstants.RIGHT); /** The jitter slider */ protected JSlider m_Jitter = new JSlider(0, 50, 0); /** The panel that displays the plot */ protected PlotPanel m_plot = new PlotPanel(); /** * The panel that displays the attributes , using color to represent another * attribute. */ protected AttributePanel m_attrib = new AttributePanel(this.m_plot.m_plot2D.getBackground()); /** The panel that displays legend info if there is more than one plot */ protected LegendPanel m_legendPanel = new LegendPanel(); /** Panel that surrounds the plot panel with a titled border */ protected JPanel m_plotSurround = new JPanel(); /** Panel that surrounds the class panel with a titled border */ protected JPanel m_classSurround = new JPanel(); /** * An optional listener that we will inform when ComboBox selections change */ protected ActionListener listener = null; /** * An optional listener that we will inform when the user creates a split to * seperate instances. */ protected VisualizePanelListener m_splitListener = null; /** * The name of the plot (not currently displayed, but can be used in the * containing Frame or Panel) */ protected String m_plotName = ""; /** The panel that displays the legend for the colouring attribute */ protected ClassPanel m_classPanel = new ClassPanel(this.m_plot.m_plot2D.getBackground()); /** The list of the colors used */ protected ArrayList<Color> m_colorList; /** * These hold the names of preferred columns to visualize on---if the user has * defined them in the Visualize.props file */ protected String m_preferredXDimension = null; protected String m_preferredYDimension = null; protected String m_preferredColourDimension = null; /** Show the attribute bar panel */ protected boolean m_showAttBars = true; /** Show the class panel **/ protected boolean m_showClassPanel = true; /** the logger */ protected Logger m_Log; /** * Sets the Logger to receive informational messages * * @param newLog the Logger that will now get info messages */ public void setLog(final Logger newLog) { this.m_Log = newLog; } /** * Set whether the attribute bars should be shown or not. If turned off via * this method then any setting in the properties file (if exists) is ignored. * * @param sab false if attribute bars are not to be displayed. */ public void setShowAttBars(final boolean sab) { if (!sab && this.m_showAttBars) { this.m_plotSurround.remove(this.m_attrib); } else if (sab && !this.m_showAttBars) { GridBagConstraints constraints = new GridBagConstraints(); constraints.insets = new Insets(0, 0, 0, 0); constraints.gridx = 4; constraints.gridy = 0; constraints.weightx = 1; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.weighty = 5; this.m_plotSurround.add(this.m_attrib, constraints); } this.m_showAttBars = sab; this.repaint(); } /** * Gets whether or not attribute bars are being displayed. * * @return true if attribute bars are being displayed. */ public boolean getShowAttBars() { return this.m_showAttBars; } /** * Set whether the class panel should be shown or not. * * @param scp false if class panel is not to be displayed */ public void setShowClassPanel(final boolean scp) { if (!scp && this.m_showClassPanel) { this.remove(this.m_classSurround); } else if (scp && !this.m_showClassPanel) { this.add(this.m_classSurround, BorderLayout.SOUTH); } this.m_showClassPanel = scp; this.repaint(); } /** * Gets whether or not the class panel is being displayed. * * @return true if the class panel is being displayed. */ public boolean getShowClassPanel() { return this.m_showClassPanel; } /** * This constructor allows a VisualizePanelListener to be set. * * @param ls the listener to use */ public VisualizePanel(final VisualizePanelListener ls) { this(); this.m_splitListener = ls; } /** * Set the properties for the VisualizePanel * * @param relationName the name of the relation, can be null */ private void setProperties(final String relationName) { if (VisualizeUtils.VISUALIZE_PROPERTIES != null) { String thisClass = this.getClass().getName(); if (relationName == null) { String showAttBars = thisClass + ".displayAttributeBars"; String val = VisualizeUtils.VISUALIZE_PROPERTIES.getProperty(showAttBars); if (val == null) { // System.err.println("Displaying attribute bars "); // m_showAttBars = true; } else { // only check if this hasn't been turned off programatically if (this.m_showAttBars) { if (val.compareTo("true") == 0 || val.compareTo("on") == 0) { // System.err.println("Displaying attribute bars "); this.m_showAttBars = true; } else { this.m_showAttBars = false; } } } } else { /* * System.err.println("Looking for preferred visualization dimensions for " * +relationName); */ String xcolKey = thisClass + "." + relationName + ".XDimension"; String ycolKey = thisClass + "." + relationName + ".YDimension"; String ccolKey = thisClass + "." + relationName + ".ColourDimension"; this.m_preferredXDimension = VisualizeUtils.VISUALIZE_PROPERTIES.getProperty(xcolKey); /* * if (m_preferredXDimension == null) { * System.err.println("No preferred X dimension found in " * +VisualizeUtils.PROPERTY_FILE +" for "+xcolKey); } else { * System.err.println("Setting preferred X dimension to " * +m_preferredXDimension); } */ this.m_preferredYDimension = VisualizeUtils.VISUALIZE_PROPERTIES.getProperty(ycolKey); /* * if (m_preferredYDimension == null) { * System.err.println("No preferred Y dimension found in " * +VisualizeUtils.PROPERTY_FILE +" for "+ycolKey); } else { * System.err.println("Setting preferred dimension Y to " * +m_preferredYDimension); } */ this.m_preferredColourDimension = VisualizeUtils.VISUALIZE_PROPERTIES.getProperty(ccolKey); /* * if (m_preferredColourDimension == null) { * System.err.println("No preferred Colour dimension found in " * +VisualizeUtils.PROPERTY_FILE +" for "+ycolKey); } else { * System.err.println("Setting preferred Colour dimension to " * +m_preferredColourDimension); } */ } } } /** * Apply settings * * @param settings the settings to apply * @param ownerID the ID of the owner perspective, panel etc. to use when * looking up settings */ public void applySettings(final Settings settings, final String ownerID) { this.m_plot.applySettings(settings, ownerID); this.m_attrib.applySettings(settings, ownerID); this.repaint(); } /** * Constructor */ public VisualizePanel() { super(); this.setProperties(null); this.m_FileChooser.setFileFilter(this.m_ArffFilter); this.m_FileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); this.m_XCombo.setToolTipText("Select the attribute for the x axis"); this.m_YCombo.setToolTipText("Select the attribute for the y axis"); this.m_ColourCombo.setToolTipText("Select the attribute to colour on"); this.m_ShapeCombo.setToolTipText("Select the shape to use for data selection"); this.m_XCombo.setPreferredSize(this.COMBO_SIZE); this.m_YCombo.setPreferredSize(this.COMBO_SIZE); this.m_ColourCombo.setPreferredSize(this.COMBO_SIZE); this.m_ShapeCombo.setPreferredSize(this.COMBO_SIZE); this.m_XCombo.setMaximumSize(this.COMBO_SIZE); this.m_YCombo.setMaximumSize(this.COMBO_SIZE); this.m_ColourCombo.setMaximumSize(this.COMBO_SIZE); this.m_ShapeCombo.setMaximumSize(this.COMBO_SIZE); this.m_XCombo.setMinimumSize(this.COMBO_SIZE); this.m_YCombo.setMinimumSize(this.COMBO_SIZE); this.m_ColourCombo.setMinimumSize(this.COMBO_SIZE); this.m_ShapeCombo.setMinimumSize(this.COMBO_SIZE); // //////// this.m_XCombo.setEnabled(false); this.m_YCombo.setEnabled(false); this.m_ColourCombo.setEnabled(false); this.m_ShapeCombo.setEnabled(false); // tell the class panel and the legend panel that we want to know when // colours change this.m_classPanel.addRepaintNotify(this); this.m_legendPanel.addRepaintNotify(this); // Check the default colours against the background colour of the // plot panel. If any are equal to the background colour then // change them (so they are visible :-) for (int i = 0; i < this.m_DefaultColors.length; i++) { Color c = this.m_DefaultColors[i]; if (c.equals(this.m_plot.m_plot2D.getBackground())) { int red = c.getRed(); int blue = c.getBlue(); int green = c.getGreen(); red += (red < 128) ? (255 - red) / 2 : -(red / 2); blue += (blue < 128) ? (blue - red) / 2 : -(blue / 2); green += (green < 128) ? (255 - green) / 2 : -(green / 2); this.m_DefaultColors[i] = new Color(red, green, blue); } } this.m_classPanel.setDefaultColourList(this.m_DefaultColors); this.m_attrib.setDefaultColourList(this.m_DefaultColors); this.m_colorList = new ArrayList<Color>(10); for (int noa = this.m_colorList.size(); noa < 10; noa++) { Color pc = this.m_DefaultColors[noa % 10]; int ija = noa / 10; ija *= 2; for (int j = 0; j < ija; j++) { pc = pc.darker(); } this.m_colorList.add(pc); } this.m_plot.setColours(this.m_colorList); this.m_classPanel.setColours(this.m_colorList); this.m_attrib.setColours(this.m_colorList); this.m_attrib.addAttributePanelListener(new AttributePanelListener() { @Override public void attributeSelectionChange(final AttributePanelEvent e) { if (e.m_xChange) { VisualizePanel.this.m_XCombo.setSelectedIndex(e.m_indexVal); } else { VisualizePanel.this.m_YCombo.setSelectedIndex(e.m_indexVal); } } }); this.m_XCombo.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { int selected = VisualizePanel.this.m_XCombo.getSelectedIndex(); if (selected < 0) { selected = 0; } VisualizePanel.this.m_plot.setXindex(selected); // try sending on the event if anyone is listening if (VisualizePanel.this.listener != null) { VisualizePanel.this.listener.actionPerformed(e); } } }); this.m_YCombo.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { int selected = VisualizePanel.this.m_YCombo.getSelectedIndex(); if (selected < 0) { selected = 0; } VisualizePanel.this.m_plot.setYindex(selected); // try sending on the event if anyone is listening if (VisualizePanel.this.listener != null) { VisualizePanel.this.listener.actionPerformed(e); } } }); this.m_ColourCombo.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { int selected = VisualizePanel.this.m_ColourCombo.getSelectedIndex(); if (selected < 0) { selected = 0; } VisualizePanel.this.m_plot.setCindex(selected); if (VisualizePanel.this.listener != null) { VisualizePanel.this.listener.actionPerformed(e); } } }); // ///// this.m_ShapeCombo.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { int selected = VisualizePanel.this.m_ShapeCombo.getSelectedIndex(); if (selected < 0) { selected = 0; } VisualizePanel.this.m_plot.setSindex(selected); // try sending on the event if anyone is listening if (VisualizePanel.this.listener != null) { VisualizePanel.this.listener.actionPerformed(e); } } }); // ///////////////////////////////////// this.m_Jitter.addChangeListener(new ChangeListener() { @Override public void stateChanged(final ChangeEvent e) { VisualizePanel.this.m_plot.setJitter(VisualizePanel.this.m_Jitter.getValue()); } }); this.m_openBut.setToolTipText("Loads previously saved instances from a file"); this.m_openBut.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { VisualizePanel.this.openVisibleInstances(); } }); this.m_saveBut.setEnabled(false); this.m_saveBut.setToolTipText("Save the visible instances to a file"); this.m_saveBut.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { VisualizePanel.this.saveVisibleInstances(); } }); JPanel combos = new JPanel(); GridBagLayout gb = new GridBagLayout(); GridBagConstraints constraints = new GridBagConstraints(); this.m_XCombo.setLightWeightPopupEnabled(false); this.m_YCombo.setLightWeightPopupEnabled(false); this.m_ColourCombo.setLightWeightPopupEnabled(false); this.m_ShapeCombo.setLightWeightPopupEnabled(false); combos.setBorder(BorderFactory.createEmptyBorder(10, 5, 10, 5)); combos.setLayout(gb); constraints.gridx = 0; constraints.gridy = 0; constraints.weightx = 5; constraints.fill = GridBagConstraints.HORIZONTAL; constraints.gridwidth = 2; constraints.gridheight = 1; constraints.insets = new Insets(0, 2, 0, 2); combos.add(this.m_XCombo, constraints); constraints.gridx = 2; constraints.gridy = 0; constraints.weightx = 5; constraints.gridwidth = 2; constraints.gridheight = 1; combos.add(this.m_YCombo, constraints); constraints.gridx = 0; constraints.gridy = 1; constraints.weightx = 5; constraints.gridwidth = 2; constraints.gridheight = 1; combos.add(this.m_ColourCombo, constraints); // constraints.gridx = 2; constraints.gridy = 1; constraints.weightx = 5; constraints.gridwidth = 2; constraints.gridheight = 1; combos.add(this.m_ShapeCombo, constraints); JPanel mbts = new JPanel(); mbts.setLayout(new GridLayout(1, 4)); mbts.add(this.m_submit); mbts.add(this.m_cancel); mbts.add(this.m_openBut); mbts.add(this.m_saveBut); constraints.gridx = 0; constraints.gridy = 2; constraints.weightx = 5; constraints.gridwidth = 2; constraints.gridheight = 1; combos.add(mbts, constraints); // ////////////////////////////// constraints.gridx = 2; constraints.gridy = 2; constraints.weightx = 5; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.insets = new Insets(10, 0, 0, 5); combos.add(this.m_JitterLab, constraints); constraints.gridx = 3; constraints.gridy = 2; constraints.weightx = 5; constraints.insets = new Insets(10, 0, 0, 0); combos.add(this.m_Jitter, constraints); this.m_classSurround = new JPanel(); this.m_classSurround.setBorder(BorderFactory.createTitledBorder("Class colour")); this.m_classSurround.setLayout(new BorderLayout()); this.m_classPanel.setBorder(BorderFactory.createEmptyBorder(15, 10, 10, 10)); this.m_classSurround.add(this.m_classPanel, BorderLayout.CENTER); GridBagLayout gb2 = new GridBagLayout(); this.m_plotSurround.setBorder(BorderFactory.createTitledBorder("Plot")); this.m_plotSurround.setLayout(gb2); constraints.fill = GridBagConstraints.BOTH; constraints.insets = new Insets(0, 0, 0, 10); constraints.gridx = 0; constraints.gridy = 0; constraints.weightx = 3; constraints.gridwidth = 4; constraints.gridheight = 1; constraints.weighty = 5; this.m_plotSurround.add(this.m_plot, constraints); if (this.m_showAttBars) { constraints.insets = new Insets(0, 0, 0, 0); constraints.gridx = 4; constraints.gridy = 0; constraints.weightx = 1; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.weighty = 5; this.m_plotSurround.add(this.m_attrib, constraints); } this.setLayout(new BorderLayout()); this.add(combos, BorderLayout.NORTH); this.add(this.m_plotSurround, BorderLayout.CENTER); this.add(this.m_classSurround, BorderLayout.SOUTH); String[] SNames = new String[4]; SNames[0] = "Select Instance"; SNames[1] = "Rectangle"; SNames[2] = "Polygon"; SNames[3] = "Polyline"; this.m_ShapeCombo.setModel(new DefaultComboBoxModel(SNames)); this.m_ShapeCombo.setEnabled(true); } /** * displays the previously saved instances * * @param insts the instances to display * @throws Exception if display is not possible */ protected void openVisibleInstances(final Instances insts) throws Exception { PlotData2D tempd = new PlotData2D(insts); tempd.setPlotName(insts.relationName()); tempd.addInstanceNumberAttribute(); this.m_plot.m_plot2D.removeAllPlots(); this.addPlot(tempd); // modify title Component parent = this.getParent(); while (parent != null) { if (parent instanceof JFrame) { ((JFrame) parent).setTitle("Weka Classifier Visualize: " + insts.relationName() + " (display only)"); break; } else { parent = parent.getParent(); } } } /** * Loads previously saved instances from a file */ protected void openVisibleInstances() { try { int returnVal = this.m_FileChooser.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { File sFile = this.m_FileChooser.getSelectedFile(); if (!sFile.getName().toLowerCase().endsWith(Instances.FILE_EXTENSION)) { sFile = new File(sFile.getParent(), sFile.getName() + Instances.FILE_EXTENSION); } File selected = sFile; Instances insts = new Instances(new BufferedReader(new FileReader(selected))); this.openVisibleInstances(insts); } } catch (Exception ex) { ex.printStackTrace(); this.m_plot.m_plot2D.removeAllPlots(); JOptionPane.showMessageDialog(this, ex.getMessage(), "Error loading file...", JOptionPane.ERROR_MESSAGE); } } /** * Save the currently visible set of instances to a file */ private void saveVisibleInstances() { ArrayList<PlotData2D> plots = this.m_plot.m_plot2D.getPlots(); if (plots != null) { PlotData2D master = plots.get(0); Instances saveInsts = new Instances(master.getPlotInstances()); for (int i = 1; i < plots.size(); i++) { PlotData2D temp = plots.get(i); Instances addInsts = temp.getPlotInstances(); for (int j = 0; j < addInsts.numInstances(); j++) { saveInsts.add(addInsts.instance(j)); } } try { int returnVal = this.m_FileChooser.showSaveDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { File sFile = this.m_FileChooser.getSelectedFile(); if (!sFile.getName().toLowerCase().endsWith(Instances.FILE_EXTENSION)) { sFile = new File(sFile.getParent(), sFile.getName() + Instances.FILE_EXTENSION); } File selected = sFile; Writer w = new BufferedWriter(new FileWriter(selected)); w.write(saveInsts.toString()); w.close(); } } catch (Exception ex) { ex.printStackTrace(); } } } /** * Set the index for colouring. * * @param index the index of the attribute to use for colouring * @param enableCombo false if the colouring combo box should be disabled */ public void setColourIndex(final int index, final boolean enableCombo) { if (index >= 0) { this.m_ColourCombo.setSelectedIndex(index); } else { this.m_ColourCombo.setSelectedIndex(0); } this.m_ColourCombo.setEnabled(enableCombo); } /** * Sets the index used for colouring. If this method is called then the * supplied index is used and the combo box for selecting colouring attribute * is disabled. * * @param index the index of the attribute to use for colouring */ public void setColourIndex(final int index) { this.setColourIndex(index, false); } /** * Set the index of the attribute for the x axis * * @param index the index for the x axis * @exception Exception if index is out of range. */ public void setXIndex(final int index) throws Exception { if (index >= 0 && index < this.m_XCombo.getItemCount()) { this.m_XCombo.setSelectedIndex(index); } else { throw new Exception("x index is out of range!"); } } /** * Get the index of the attribute on the x axis * * @return the index of the attribute on the x axis */ public int getXIndex() { return this.m_XCombo.getSelectedIndex(); } /** * Set the index of the attribute for the y axis * * @param index the index for the y axis * @exception Exception if index is out of range. */ public void setYIndex(final int index) throws Exception { if (index >= 0 && index < this.m_YCombo.getItemCount()) { this.m_YCombo.setSelectedIndex(index); } else { throw new Exception("y index is out of range!"); } } /** * Get the index of the attribute on the y axis * * @return the index of the attribute on the x axis */ public int getYIndex() { return this.m_YCombo.getSelectedIndex(); } /** * Get the index of the attribute selected for coloring * * @return the index of the attribute on the x axis */ public int getCIndex() { return this.m_ColourCombo.getSelectedIndex(); } /** * Get the index of the shape selected for creating splits. * * @return The index of the shape. */ public int getSIndex() { return this.m_ShapeCombo.getSelectedIndex(); } /** * Set the shape for creating splits. * * @param index The index of the shape. * @exception Exception if index is out of range. */ public void setSIndex(final int index) throws Exception { if (index >= 0 && index < this.m_ShapeCombo.getItemCount()) { this.m_ShapeCombo.setSelectedIndex(index); } else { throw new Exception("s index is out of range!"); } } /** * Add a listener for this visualize panel * * @param act an ActionListener */ public void addActionListener(final ActionListener act) { this.listener = act; } /** * Set a name for this plot * * @param plotName the name for the plot */ @Override public void setName(final String plotName) { this.m_plotName = plotName; } /** * Returns the name associated with this plot. "" is returned if no name is * set. * * @return the name of the plot */ @Override public String getName() { return this.m_plotName; } /** * Get the master plot's instances * * @return the master plot's instances */ public Instances getInstances() { return this.m_plot.m_plotInstances; } /** * Sets the Colors in use for a different attrib if it is not a nominal attrib * and or does not have more possible values then this will do nothing. * otherwise it will add default colors to see that there is a color for the * attrib to begin with. * * @param a The index of the attribute to color. * @param i The instances object that contains the attribute. */ protected void newColorAttribute(final int a, final Instances i) { if (i.attribute(a).isNominal()) { for (int noa = this.m_colorList.size(); noa < i.attribute(a).numValues(); noa++) { Color pc = this.m_DefaultColors[noa % 10]; int ija = noa / 10; ija *= 2; for (int j = 0; j < ija; j++) { pc = pc.brighter(); } this.m_colorList.add(pc); } this.m_plot.setColours(this.m_colorList); this.m_attrib.setColours(this.m_colorList); this.m_classPanel.setColours(this.m_colorList); } } /** * This will set the shapes for the instances. * * @param l A list of the shapes, providing that the objects in the lists are * non editable the data will be kept intact. */ public void setShapes(final ArrayList<ArrayList<Double>> l) { this.m_plot.setShapes(l); } /** * Tells the panel to use a new set of instances. * * @param inst a set of Instances */ public void setInstances(final Instances inst) { if (inst.numAttributes() > 0 && inst.numInstances() > 0) { this.newColorAttribute(inst.numAttributes() - 1, inst); } PlotData2D temp = new PlotData2D(inst); temp.setPlotName(inst.relationName()); try { this.setMasterPlot(temp); } catch (Exception ex) { System.err.println(ex); ex.printStackTrace(); } } /** * initializes the comboboxes based on the data * * @param inst the data to base the combobox-setup on */ public void setUpComboBoxes(final Instances inst) { this.setProperties(inst.relationName()); int prefX = -1; int prefY = -1; if (inst.numAttributes() > 1) { prefY = 1; } int prefC = -1; String[] XNames = new String[inst.numAttributes()]; String[] YNames = new String[inst.numAttributes()]; String[] CNames = new String[inst.numAttributes()]; for (int i = 0; i < XNames.length; i++) { String type = " (" + Attribute.typeToStringShort(inst.attribute(i)) + ")"; XNames[i] = "X: " + inst.attribute(i).name() + type; YNames[i] = "Y: " + inst.attribute(i).name() + type; CNames[i] = "Colour: " + inst.attribute(i).name() + type; if (this.m_preferredXDimension != null) { if (this.m_preferredXDimension.compareTo(inst.attribute(i).name()) == 0) { prefX = i; // System.err.println("Found preferred X dimension"); } } if (this.m_preferredYDimension != null) { if (this.m_preferredYDimension.compareTo(inst.attribute(i).name()) == 0) { prefY = i; // System.err.println("Found preferred Y dimension"); } } if (this.m_preferredColourDimension != null) { if (this.m_preferredColourDimension.compareTo(inst.attribute(i).name()) == 0) { prefC = i; // System.err.println("Found preferred Colour dimension"); } } } this.m_XCombo.setModel(new DefaultComboBoxModel(XNames)); this.m_YCombo.setModel(new DefaultComboBoxModel(YNames)); this.m_ColourCombo.setModel(new DefaultComboBoxModel(CNames)); // m_ShapeCombo.setModel(new DefaultComboBoxModel(SNames)); // m_ShapeCombo.setEnabled(true); this.m_XCombo.setEnabled(true); this.m_YCombo.setEnabled(true); if (this.m_splitListener == null) { this.m_ColourCombo.setEnabled(true); this.m_ColourCombo.setSelectedIndex(inst.numAttributes() - 1); } this.m_plotSurround.setBorder((BorderFactory.createTitledBorder("Plot: " + inst.relationName()))); try { if (prefX != -1) { this.setXIndex(prefX); } if (prefY != -1) { this.setYIndex(prefY); } if (prefC != -1) { this.m_ColourCombo.setSelectedIndex(prefC); } } catch (Exception ex) { System.err.println("Problem setting preferred Visualization dimensions"); } } /** * Removes all the plots. */ public void removeAllPlots() { this.m_plot.removeAllPlots(); } /** * Set the master plot for the visualize panel * * @param newPlot the new master plot * @exception Exception if the master plot could not be set */ public void setMasterPlot(final PlotData2D newPlot) throws Exception { this.m_plot.setMasterPlot(newPlot); this.setUpComboBoxes(newPlot.m_plotInstances); this.m_saveBut.setEnabled(true); this.repaint(); } /** * Set a new plot to the visualize panel * * @param newPlot the new plot to add * @exception Exception if the plot could not be added */ public void addPlot(final PlotData2D newPlot) throws Exception { this.m_plot.addPlot(newPlot); if (this.m_plot.m_plot2D.getMasterPlot() != null) { this.setUpComboBoxes(newPlot.m_plotInstances); } this.m_saveBut.setEnabled(true); this.repaint(); } /** * Returns the underlying plot panel. * * @return the plot panel */ public PlotPanel getPlotPanel() { return this.m_plot; } /** * Main method for testing this class * * @param args the commandline parameters */ public static void main(final String[] args) { try { if (args.length < 1) { System.err.println("Usage : weka.gui.visualize.VisualizePanel " + "<dataset> [<dataset> <dataset>...]"); System.exit(1); } weka.core.logging.Logger.log(weka.core.logging.Logger.Level.INFO, "Logging started"); final javax.swing.JFrame jf = new javax.swing.JFrame("Weka Explorer: Visualize"); jf.setSize(500, 400); jf.getContentPane().setLayout(new BorderLayout()); final VisualizePanel sp = new VisualizePanel(); jf.getContentPane().add(sp, 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.setVisible(true); if (args.length >= 1) { for (int j = 0; j < args.length; j++) { System.err.println("Loading instances from " + args[j]); java.io.Reader r = new java.io.BufferedReader(new java.io.FileReader(args[j])); Instances i = new Instances(r); i.setClassIndex(i.numAttributes() - 1); PlotData2D pd1 = new PlotData2D(i); if (j == 0) { pd1.setPlotName("Master plot"); sp.setMasterPlot(pd1); } else { pd1.setPlotName("Plot " + (j + 1)); pd1.m_useCustomColour = true; pd1.m_customColour = (j % 2 == 0) ? Color.red : Color.blue; sp.addPlot(pd1); } } } } 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/visualize/VisualizePanelEvent.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * VisualizePanelEvent.java * Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.visualize; import java.util.ArrayList; import weka.core.Instances; /** * This event Is fired to a listeners 'userDataEvent' function when The user on * the VisualizePanel clicks submit. It contains the attributes selected at the * time and a FastVector containing the various shapes that had been drawn into * the panel. * * @author Malcolm Ware (mfw4@cs.waikato.ac.nz) * @version $Revision$ */ public class VisualizePanelEvent { /** No longer used */ public static int NONE = 0; public static int RECTANGLE = 1; public static int OVAL = 2; public static int POLYGON = 3; public static int LINE = 4; public static int VLINE = 5; public static int HLINE = 6; /** Contains FastVectors, each one containing the points for an object. */ private final ArrayList<ArrayList<Double>> m_values; /** The instances that fall inside the shapes described in m_values. */ private final Instances m_inst; /** The instances that fall outside the shapes described in m_values. */ private final Instances m_inst2; /** The attribute along the x axis. */ private final int m_attrib1; /** The attribute along the y axis. */ private final int m_attrib2; /** * This constructor creates the event with all the parameters set. * * @param ar The list of shapes. * @param i The instances that lie in these shapes. * @param i2 The instances that lie outside these shapes. * @param at1 The attribute that was along the x axis. * @param at2 The attribute that was along the y axis. */ public VisualizePanelEvent(ArrayList<ArrayList<Double>> ar, Instances i, Instances i2, int at1, int at2) { m_values = ar; m_inst = i; m_inst2 = i2; m_attrib1 = at1; m_attrib2 = at2; } /** * @return The list of shapes. */ public ArrayList<ArrayList<Double>> getValues() { return m_values; } /** * @return The instances that lie in the shapes. */ public Instances getInstances1() { return m_inst; } /** * @return The instances that lie outside the shapes. */ public Instances getInstances2() { return m_inst2; } /** * @return The x axis attribute. */ public int getAttribute1() { return m_attrib1; } /** * @return The y axis attribute. */ public int getAttribute2() { return m_attrib2; } }
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/visualize/VisualizePanelListener.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * VisualizePanelListener.java * Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.visualize; /** * Interface implemented by a class that is interested in receiving * submited shapes from a visualize panel. * @author Malcolm Ware (mfw4@cs.waikato.ac.nz) * @version $Revision$ */ public interface VisualizePanelListener { /** * This method receives an object containing the shapes, instances * inside and outside these shapes and the attributes these shapes were * created in. * @param e The Event containing the data. */ void userDataEvent(VisualizePanelEvent 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/visualize/VisualizeUtils.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * VisualizeUtils.java * Copyright (C) 2000-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.visualize; import weka.core.Defaults; import weka.core.Settings; import weka.core.Utils; import javax.swing.JOptionPane; import java.awt.Color; import java.util.Properties; /** * This class contains utility routines for visualization * * @author Mark Hall (mhall@cs.waikato.ac.nz) * @version $Revision$ */ public class VisualizeUtils { /** The name of the properties file */ protected static String PROPERTY_FILE = "weka/gui/visualize/Visualize.props"; /** Contains the visualization properties */ protected static Properties VISUALIZE_PROPERTIES; /** Default maximum precision for the display of numeric values */ public static int MAX_PRECISION = 10; static { try { VISUALIZE_PROPERTIES = Utils.readProperties(PROPERTY_FILE); String precision = VISUALIZE_PROPERTIES.getProperty("weka.gui.visualize.precision"); if (precision == null) { /* * System.err.println("Warning: no configuration property found in" * +PROPERTY_FILE +" for weka.gui.visualize.precision. Using" * +" default instead."); */ } else { MAX_PRECISION = Integer.parseInt(precision); // System.err.println("Setting numeric precision to: "+precision); } } catch (Exception ex) { JOptionPane.showMessageDialog(null, "VisualizeUtils: Could not read a visualization configuration file.\n" + "An example file is included in the Weka distribution.\n" + "This file should be named \"" + PROPERTY_FILE + "\" and\n" + "should be placed either in your user home (which is set\n" + "to \"" + System.getProperties().getProperty("user.home") + "\")\n" + "or the directory that java was started from\n", "Plot2D", JOptionPane.ERROR_MESSAGE); } } /** * Parses a string containing either a named colour or r,g,b values. * * @param colourDef the string containing the named colour (or r,g,b) * @param defaultColour the colour to return if parsing fails * @return the Color corresponding to the string. */ public static Color processColour(String colourDef, Color defaultColour) { String colourDefBack = new String(colourDef); Color retC = defaultColour; if (colourDef.indexOf(",") >= 0) { // Looks like property value is in R, G, B format try { int index = colourDef.indexOf(","); int R = Integer.parseInt(colourDef.substring(0, index)); colourDef = colourDef.substring(index + 1, colourDef.length()); index = colourDef.indexOf(","); int G = Integer.parseInt(colourDef.substring(0, index)); colourDef = colourDef.substring(index + 1, colourDef.length()); int B = Integer.parseInt(colourDef); // System.err.println(R+" "+G+" "+B); retC = new Color(R, G, B); } catch (Exception ex) { System.err.println("VisualizeUtils: Problem parsing colour property " + "value (" + colourDefBack + ")."); } } else { // assume that the string is the name of a default Color.color if (colourDef.compareTo("black") == 0) { retC = Color.black; } else if (colourDef.compareTo("blue") == 0) { retC = Color.blue; } else if (colourDef.compareTo("cyan") == 0) { retC = Color.cyan; } else if (colourDef.compareTo("darkGray") == 0) { retC = Color.darkGray; } else if (colourDef.compareTo("gray") == 0) { retC = Color.gray; } else if (colourDef.compareTo("green") == 0) { retC = Color.green; } else if (colourDef.compareTo("lightGray") == 0) { retC = Color.lightGray; } else if (colourDef.compareTo("magenta") == 0) { retC = Color.magenta; } else if (colourDef.compareTo("orange") == 0) { retC = Color.orange; } else if (colourDef.compareTo("pink") == 0) { retC = Color.pink; } else if (colourDef.compareTo("red") == 0) { retC = Color.red; } else if (colourDef.compareTo("white") == 0) { retC = Color.white; } else if (colourDef.compareTo("yellow") == 0) { retC = Color.yellow; } else { System.err .println("VisualizeUtils: colour property name not recognized " + "(" + colourDefBack + ")."); } } return retC; } /** * Defaults for the 2D scatter plot and attribute bars */ public static class VisualizeDefaults extends Defaults { /** ID for the metastore */ public static final String ID = "weka.gui.visualize.visualizepanel"; /** Axis colour key */ public static final Settings.SettingKey AXIS_COLOUR_KEY = new Settings.SettingKey(ID + ".axisColor", "Colour of the axis", ""); /** Axis colour default */ public static final Color AXIS_COLOR = Color.GREEN; /** Scatter plot background colour key */ public static final Settings.SettingKey BACKGROUND_COLOUR_KEY = new Settings.SettingKey(ID + ".backgroundColor", "Background colour of scatter plot", ""); /** Scatter plot background colour default */ public static final Color BACKGROUND_COLOR = Color.WHITE; /** Attribute bar background colour key */ public static final Settings.SettingKey BAR_BACKGROUND_COLOUR_KEY = new Settings.SettingKey(ID + ".attributeBarBackgroundColor", "Background " + "colour for the 1-dimensional attribute bars", ""); /** Attribute bar background colour key */ public static final Color BAR_BACKGROUND_COLOUR = Color.WHITE; /** For serialization */ private static final long serialVersionUID = 4227480313375404688L; /** * Constructor */ public VisualizeDefaults() { super(ID); m_defaults.put(AXIS_COLOUR_KEY, AXIS_COLOR); m_defaults.put(BACKGROUND_COLOUR_KEY, BACKGROUND_COLOR); m_defaults.put(BAR_BACKGROUND_COLOUR_KEY, BAR_BACKGROUND_COLOUR); } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/visualize
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/visualize/plugins/AssociationRuleVisualizePlugin.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * AssociationRulesVisualizePlugin.java * Copyright (C) 2010-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.visualize.plugins; import javax.swing.JMenuItem; import weka.associations.AssociationRules; /** * Interface implemented by classes loaded dynamically to * visualize association results in the explorer. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision$ */ public interface AssociationRuleVisualizePlugin { /** * Get a JMenu or JMenuItem which contain action listeners * that perform the visualization of the association rules. * * @see NoClassDefFoundError * @see IncompatibleClassChangeError * * @param rules the association rules * @param name the name of the item (in the Explorer's history list) * @return menuitem for opening visualization(s), or null * to indicate no visualization is applicable for the input */ public JMenuItem getVisualizeMenuItem(AssociationRules rules, String name); }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/visualize
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/visualize/plugins/ErrorVisualizePlugin.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ErrorVisualizePlugin.java * Copyright (C) 2009-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.visualize.plugins; import javax.swing.JMenuItem; import weka.core.Instances; /** * Interface implemented by classes loaded dynamically to * visualize classifier errors in the explorer. * * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public interface ErrorVisualizePlugin { /** * Get a JMenu or JMenuItem which contain action listeners * that perform the visualization of the classifier errors. * <p/> * The actual class is the attribute declared as class attribute, the * predicted class values is found in the attribute prior to the class * attribute's position. In other words, if the <code>classIndex()</code> * method returns 10, then the attribute position for the predicted class * values is 9. * <p/> * Exceptions thrown because of changes in Weka since compilation need to * be caught by the implementer. * * @see NoClassDefFoundError * @see IncompatibleClassChangeError * * @param predInst the instances with the actual and predicted class values * @return menuitem for opening visualization(s), or null * to indicate no visualization is applicable for the input */ public JMenuItem getVisualizeMenuItem(Instances predInst); /** * Get the minimum version of Weka, inclusive, the class * is designed to work with. eg: <code>3.5.0</code> * * @return the minimum version */ public String getMinVersion(); /** * Get the maximum version of Weka, exclusive, the class * is designed to work with. eg: <code>3.6.0</code> * * @return the maximum version */ public String getMaxVersion(); /** * Get the specific version of Weka the class is designed for. * eg: <code>3.5.1</code> * * @return the version the plugin was designed for */ public String getDesignVersion(); }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/visualize
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/visualize/plugins/GraphVisualizePlugin.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * GraphVisualizePlugin.java * Copyright (C) 2009-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.visualize.plugins; import javax.swing.JMenuItem; /** * Interface implemented by classes loaded dynamically to * visualize graphs in the explorer. * * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public interface GraphVisualizePlugin { /** * Get a JMenu or JMenuItem which contain action listeners * that perform the visualization of the graph in XML BIF format. * Exceptions thrown because of changes in Weka since compilation need to * be caught by the implementer. * * @see NoClassDefFoundError * @see IncompatibleClassChangeError * * @param bif the graph in XML BIF format * @param name the name of the item (in the Explorer's history list) * @return menuitem for opening visualization(s), or null * to indicate no visualization is applicable for the input */ public JMenuItem getVisualizeMenuItem(String bif, String name); /** * Get the minimum version of Weka, inclusive, the class * is designed to work with. eg: <code>3.5.0</code> * * @return the minimum version */ public String getMinVersion(); /** * Get the maximum version of Weka, exclusive, the class * is designed to work with. eg: <code>3.6.0</code> * * @return the maximum version */ public String getMaxVersion(); /** * Get the specific version of Weka the class is designed for. * eg: <code>3.5.1</code> * * @return the version the plugin was designed for */ public String getDesignVersion(); }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/visualize
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/visualize/plugins/TreeVisualizePlugin.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * TreeVisualizePlugin.java * Copyright (C) 2009-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.visualize.plugins; import javax.swing.JMenuItem; /** * Interface implemented by classes loaded dynamically to * visualize classifier results in the explorer. * * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public interface TreeVisualizePlugin { /** * Get a JMenu or JMenuItem which contain action listeners * that perform the visualization of the tree in GraphViz's dotty format. * Exceptions thrown because of changes in Weka since compilation need to * be caught by the implementer. * * @see NoClassDefFoundError * @see IncompatibleClassChangeError * * @param dotty the tree in dotty format * @param name the name of the item (in the Explorer's history list) * @return menuitem for opening visualization(s), or null * to indicate no visualization is applicable for the input */ public JMenuItem getVisualizeMenuItem(String dotty, String name); /** * Get the minimum version of Weka, inclusive, the class * is designed to work with. eg: <code>3.5.0</code> * * @return the minimum version */ public String getMinVersion(); /** * Get the maximum version of Weka, exclusive, the class * is designed to work with. eg: <code>3.6.0</code> * * @return the maximum version */ public String getMaxVersion(); /** * Get the specific version of Weka the class is designed for. * eg: <code>3.5.1</code> * * @return the version the plugin was designed for */ public String getDesignVersion(); }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/visualize
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/visualize/plugins/VisualizePlugin.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * VisualizePlugin.java * Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand * Written by Jeffery Grajkowski of the AICML * */ package weka.gui.visualize.plugins; import java.util.ArrayList; import javax.swing.JMenuItem; import weka.classifiers.evaluation.Prediction; import weka.core.Attribute; /** * Interface implemented by classes loaded dynamically to visualize classifier * results in the explorer. * * @author Jeffery Grajkowski (grajkows@cs.ualberta.ca) * @version $Revision$ */ public interface VisualizePlugin { /** * Get a JMenu or JMenuItem which contain action listeners that perform the * visualization, using some but not necessarily all of the data. Exceptions * thrown because of changes in Weka since compilation need to be caught by * the implementer. * * @see NoClassDefFoundError * @see IncompatibleClassChangeError * * @param preds predictions * @param classAtt class attribute * @return menuitem for opening visualization(s), or null to indicate no * visualization is applicable for the input */ public JMenuItem getVisualizeMenuItem(ArrayList<Prediction> preds, Attribute classAtt); /** * Get the minimum version of Weka, inclusive, the class is designed to work * with. eg: <code>3.5.0</code> */ public String getMinVersion(); /** * Get the maximum version of Weka, exclusive, the class is designed to work * with. eg: <code>3.6.0</code> */ public String getMaxVersion(); /** * Get the specific version of Weka the class is designed for. eg: * <code>3.5.1</code> */ public String getDesignVersion(); }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/knowledgeflow/BaseExecutionEnvironment.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * BaseExecutionEnvironment.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.knowledgeflow; import weka.core.Defaults; import weka.core.Environment; import weka.core.Settings; import weka.core.WekaException; import weka.gui.Logger; import weka.core.PluginManager; import weka.gui.knowledgeflow.GraphicalEnvironmentCommandHandler; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; /** * Base class for execution environments * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) */ public class BaseExecutionEnvironment implements ExecutionEnvironment { /** Description of the default execution environment */ public static final String DESCRIPTION = "Default execution environment"; static { // register the default execution environment PluginManager.addPlugin(BaseExecutionEnvironment.class.getCanonicalName(), DESCRIPTION, BaseExecutionEnvironment.class.getCanonicalName()); } /** * The FlowExecutor that will be running the flow. This is not guaranteed to * be available from this class until the flow is initialized */ protected FlowExecutor m_flowExecutor; /** Whether the execution environment is headless or not */ protected boolean m_headless; /** * The handler (if any) for application-level commands in a graphical * environment */ protected GraphicalEnvironmentCommandHandler m_graphicalEnvCommandHandler; /** The environment variables to use */ protected transient Environment m_envVars = Environment.getSystemWide(); /** The knowledge flow settings to use */ protected transient Settings m_settings; /** * This is the main executor service, used by the execution environment to * invoke processIncoming() on a step when batch data is passed to it - i.e. a * step receiving data will execute in its own thread. This is not used, * however, when streaming data is processed, as it usually the case that * processing is lightweight in this case and the gains of running a separate * thread for each piece of data probably do not outweigh the overheads * involved. */ protected transient ExecutorService m_executorService; /** * An executor service that steps can use to do work in parallel (if desired) * by using {@code StepTask instances}. This executor service is intended for * high cpu load tasks, and the number of threads used by it should be kept <= * number of physical CPU cores */ protected transient ExecutorService m_clientExecutorService; /** * An executor service with a single worker thread. This is used to execute * steps that are marked with the {@code SingleThreadedExecution annotation}, * which effectively limits one object of the type in question to be executing * in the KnowledgeFlow/JVM at any one time. */ protected transient ExecutorService m_singleThreadService; /** The log */ protected transient Logger m_log; /** Log handler to wrap log in */ protected transient LogManager m_logHandler; /** The level to log at */ protected LoggingLevel m_loggingLevel = LoggingLevel.BASIC; /** * Get a description of this execution environment * * @return a description of this execution environemtn */ @Override public String getDescription() { return DESCRIPTION; } /** * Get whether this execution environment is headless * * @return true if this execution environment is headless */ @Override public boolean isHeadless() { return m_headless; } /** * Set whether this execution environment is headless * * @param headless true if the execution environment is headless */ @Override public void setHeadless(boolean headless) { m_headless = headless; } /** * Get the environment for performing commands at the application-level in a * graphical environment. * * @return the graphical environment command handler, or null if running * headless */ @Override public GraphicalEnvironmentCommandHandler getGraphicalEnvironmentCommandHandler() { return m_graphicalEnvCommandHandler; } /** * Set the environment for performing commands at the application-level in a * graphical environment. * * @handler the handler to use */ @Override public void setGraphicalEnvironmentCommandHandler( GraphicalEnvironmentCommandHandler handler) { m_graphicalEnvCommandHandler = handler; } /** * Get environment variables for this execution environment * * @return the environment variables for this execution environment */ @Override public Environment getEnvironmentVariables() { return m_envVars; } /** * Set environment variables for this execution environment * * @param env the environment variables to use */ @Override public void setEnvironmentVariables(Environment env) { m_envVars = env; } @Override public void setSettings(Settings settings) { m_settings = settings; m_logHandler.setLoggingLevel(m_settings.getSetting( KFDefaults.MAIN_PERSPECTIVE_ID, KFDefaults.LOGGING_LEVEL_KEY, KFDefaults.LOGGING_LEVEL)); } @Override public Settings getSettings() { if (m_settings == null) { m_settings = new Settings("weka", KFDefaults.APP_ID); } return m_settings; } /** * Get the log in use * * @return the log in use */ @Override public Logger getLog() { return m_log; } /** * Set the log to use * * @param log the log to use */ @Override public void setLog(Logger log) { m_log = log; if (m_logHandler == null) { m_logHandler = new LogManager(m_log); m_logHandler.m_statusMessagePrefix = "BaseExecutionEnvironment$" + hashCode() + "|"; } m_logHandler.setLog(m_log); } /** * Get the logging level in use * * @return the logging level in use */ @Override public LoggingLevel getLoggingLevel() { return m_loggingLevel; } /** * Set the logging level to use * * @param level the logging level to use */ @Override public void setLoggingLevel(LoggingLevel level) { m_loggingLevel = level; } /** * Submit a task to be run by the execution environment. The default execution * environment uses an ExecutorService to run tasks in parallel. Client steps * are free to use this service or to just do their processing locally within * their own code. * * @param stepTask the StepTask encapsulating the code to be run * @return the Future holding the status and result when complete */ @Override public <T> Future<ExecutionResult<T>> submitTask(StepTask<T> stepTask) throws WekaException { String taskType = ""; if (stepTask.getMustRunSingleThreaded()) { taskType = " (single threaded)"; } else if (stepTask.isResourceIntensive()) { taskType = " (resource intensive)"; } m_logHandler.logDebug("Submitting " + stepTask.toString() + taskType); if (stepTask.getMustRunSingleThreaded()) { return m_singleThreadService.submit(stepTask); } if (stepTask.isResourceIntensive()) { return m_clientExecutorService.submit(stepTask); } return m_executorService.submit(stepTask); } /** * The main point at which to request stop processing of a flow. This will * request the FlowExecutor to stop and then shutdown the executor service */ @Override public void stopProcessing() { if (getFlowExecutor() != null) { getFlowExecutor().stopProcessing(); } if (m_executorService != null) { m_executorService.shutdownNow(); m_executorService = null; } } /** * Gets a new instance of the default flow executor suitable for use with this * execution environment * * @return a new instance of the default flow executor suitable for use with * this execution environment */ public FlowExecutor getDefaultFlowExecutor() { return new FlowRunner(); } /** * Get the executor that will actually be responsible for running the flow. * This is not guaranteed to be available from this execution environment * until the flow is actually running (or at least initialized) * * @return the executor that will be running the flow */ public FlowExecutor getFlowExecutor() { return m_flowExecutor; } /** * Set the executor that will actually be responsible for running the flow. * This is not guaranteed to be available from this execution environment * until the flow is actually running (or at least initialized) * * @param executor the executor that will be running the flow */ public void setFlowExecutor(FlowExecutor executor) { m_flowExecutor = executor; } /** * Start the main step executor service and the high cpu load executor service * for clients to use to execute {@code StepTask} instances in this execution * environment. Client steps are free to use this service or to just do their * processing locally within their own code (in which case the main step * executor service is used). * * @param numThreadsMain the number of threads to use (level of parallelism). * <= 0 indicates no limit on parallelism * @param numThreadsHighLoad the number of threads to use for the high cpu * load executor service (executes {@code StepTask} instances) */ protected void startClientExecutionService(int numThreadsMain, int numThreadsHighLoad) { if (m_executorService != null) { m_executorService.shutdownNow(); } m_logHandler .logDebug("Requested number of threads for main step executor: " + numThreadsMain); m_logHandler .logDebug("Requested number of threads for high load executor: " + (numThreadsHighLoad > 0 ? numThreadsHighLoad : Runtime.getRuntime() .availableProcessors())); m_executorService = numThreadsMain > 0 ? Executors.newFixedThreadPool(numThreadsMain) : Executors.newCachedThreadPool(); m_clientExecutorService = numThreadsHighLoad > 0 ? Executors.newFixedThreadPool(numThreadsHighLoad) : Executors.newFixedThreadPool(Runtime.getRuntime() .availableProcessors()); m_singleThreadService = Executors.newSingleThreadExecutor(); } /** * Stop the client executor service */ protected void stopClientExecutionService() { if (m_executorService != null) { m_executorService.shutdown(); try { // try to avoid a situation where a step might not have received // data yet (and will be launching tasks on the client executor service // when it does), all preceding steps have finished, and the shutdown // monitor has polled and found all steps not busy. In this case, // both executor services will be shutdown. The main one will have // the job of executing the step in question (and will already have // a runnable for this in its queue, so this will get executed). // However, // the client executor service will (potentially) have an empty queue // as the step has not launched a task on it yet. This can lead to // a situation where the step tries to launch a task when the // client executor service has been shutdown. Blocking here at the // main executor service should avoid this situation. m_executorService.awaitTermination(5L, TimeUnit.SECONDS); } catch (InterruptedException e) { e.printStackTrace(); } } if (m_clientExecutorService != null) { m_clientExecutorService.shutdown(); } if (m_singleThreadService != null) { m_singleThreadService.shutdown(); } } /** * Launches a Step (via the startStep() method) in either than standard step * executor service or the resource intensive executor service. Does not check * that the step is actually a start point. * * @param startPoint the step to launch as a start point * @throws WekaException if a problem occurs */ protected void launchStartPoint(final StepManagerImpl startPoint) throws WekaException { String taskType = startPoint.getStepMustRunSingleThreaded() ? " (single-threaded)" : (startPoint.stepIsResourceIntensive() ? " (resource intensive)" : ""); m_logHandler.logDebug("Submitting " + startPoint.getName() + taskType); if (startPoint.getStepMustRunSingleThreaded()) { StepTask<Void> singleThreaded = new StepTask<Void>(null) { private static final long serialVersionUID = -4008646793585608806L; @Override public void process() throws Exception { startPoint.startStep(); } }; singleThreaded.setMustRunSingleThreaded(true); submitTask(singleThreaded); } else if (startPoint.stepIsResourceIntensive()) { submitTask(new StepTask<Void>(null) { /** For serialization */ private static final long serialVersionUID = -5466021103296024455L; @Override public void process() throws Exception { startPoint.startStep(); } }); } else { m_executorService.submit(new Runnable() { @Override public void run() { startPoint.startStep(); } }); } } /** * Send the supplied data to the specified step. Base implementation just * calls processIncoming() on the step directly. Subclasses may opt to do * something different (e.g. wrap data and target step to be executed, and * then execute remotely). * * @param data the data to input to the target step * @param step the step to receive data * @throws WekaException if a problem occurs */ protected void sendDataToStep(final StepManagerImpl step, final Data... data) throws WekaException { if (data != null) { if (data.length == 1 && (StepManagerImpl.connectionIsIncremental(data[0]))) { // we don't want the overhead of spinning up a thread for single // instance (streaming) connections. step.processIncoming(data[0]); } else { String taskType = step.getStepMustRunSingleThreaded() ? " (single-threaded)" : (step .stepIsResourceIntensive() ? " (resource intensive)" : ""); m_logHandler.logDebug("Submitting " + step.getName() + taskType); if (step.getStepMustRunSingleThreaded()) { m_singleThreadService.submit(new Runnable() { @Override public void run() { for (Data d : data) { step.processIncoming(d); } } }); } else if (step.stepIsResourceIntensive()) { m_clientExecutorService.submit(new Runnable() { @Override public void run() { for (Data d : data) { step.processIncoming(d); } } }); } else { m_executorService.submit(new Runnable() { @Override public void run() { for (Data d : data) { step.processIncoming(d); } } }); } } } } /** * Get default settings for the base execution environment * * @return the default settings */ @Override public Defaults getDefaultSettings() { return new BaseExecutionEnvironmentDefaults(); } /** * Defaults for the base execution environment */ public static class BaseExecutionEnvironmentDefaults extends Defaults { public static final Settings.SettingKey STEP_EXECUTOR_SERVICE_NUM_THREADS_KEY = new Settings.SettingKey(KFDefaults.APP_ID + ".stepExecutorNumThreads", "Number of threads to use in the main step executor service", ""); public static final int STEP_EXECUTOR_SERVICE_NUM_THREADS = 50; public static final Settings.SettingKey RESOURCE_INTENSIVE_EXECUTOR_SERVICE_NUM_THREADS_KEY = new Settings.SettingKey(KFDefaults.APP_ID + ".highResourceExecutorNumThreads", "Number of threads to use in the resource intensive executor service", "<html>This executor service is used for executing StepTasks and<br>" + "Steps that are marked as resource intensive. 0 = use as many<br>" + "threads as there are cpu processors.</html>"); /** Default (0) means use as many threads as there are cpu processors */ public static final int RESOURCE_INTENSIVE_EXECUTOR_SERVICE_NUM_THREADS = 0; private static final long serialVersionUID = -3386792058002464330L; public BaseExecutionEnvironmentDefaults() { super(KFDefaults.APP_ID); m_defaults.put(STEP_EXECUTOR_SERVICE_NUM_THREADS_KEY, STEP_EXECUTOR_SERVICE_NUM_THREADS); m_defaults.put(RESOURCE_INTENSIVE_EXECUTOR_SERVICE_NUM_THREADS_KEY, RESOURCE_INTENSIVE_EXECUTOR_SERVICE_NUM_THREADS); } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/knowledgeflow/CallbackNotifierDelegate.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * CallbackNotifierDelegate.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.knowledgeflow; /** * Interface to something that can notify a Step that a Task submitted by * ExecutionEnvironment.submitTask() has finished. The default implementation * notifies the Step as soon as the task has completed. Other implementations * might delay notification (e.g. if a task gets executed on a remote machine * then we will want to delay notification until receiving the result back over * the wire. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public interface CallbackNotifierDelegate { /** * Notify the supplied callback * * @param callback the callback to notify * @param taskExecuted the StepTask that was executed * @param result the ExecutionResult that was produced * @throws Exception if a problem occurs */ void notifyCallback(StepTaskCallback callback, StepTask taskExecuted, ExecutionResult result) throws Exception; }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/knowledgeflow/Data.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * Data.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.knowledgeflow; import weka.knowledgeflow.steps.Step; import java.io.Serializable; import java.util.LinkedHashMap; import java.util.Map; /** * <p>Class for encapsulating data to be transferred between Knowledge Flow steps * over a particular connection type. Typical usage involves constructing a Data * object with a given connection name and then setting one or more pieces of * "payload" data to encapsulate. Usually there is a primary payload that is * associated with the connection name itself (there is a constructor that takes * both the connection name and the primary payload data). Further auxiliary * data items can be added via the setPayloadElement() method.</p> * * <p>Standard connection types are defined as constants in the StepManager class. * There is nothing to prevent clients from using their own connection types (as * these are just string identifiers).</p> * * Typical usage in a client step (transferring an training instances object):<br> * <br> * * <pre> * Instances train = ... * Data myData = new Data(StepManager.CON_TRAININGSET, train); * getStepManager().outputData(myData); * </pre> * * @author mhall{[at]}pentaho{[dot]}com * @version $Revision: $ */ public class Data implements Serializable { /** * For serialization */ private static final long serialVersionUID = 239235113781041619L; /** The source of this data */ protected Step m_sourceStep; /** * The connection name for this Data - determines which downstream steps will * receive the data. */ protected String m_connectionName; /** The payload */ protected Map<String, Object> m_payloadMap = new LinkedHashMap<String, Object>(); /** * Empty constructor - no connection name; no payload */ public Data() { } /** * Construct a Data object with just a connection name * * @param connectionName the connection name */ public Data(String connectionName) { setConnectionName(connectionName); } /** * Construct a Data object with a connection name and a primary payload object * to associate with the connection name * * @param connectionName connection name * @param primaryPayload primary payload object (i.e. is keyed against the * connection name) */ public Data(String connectionName, Object primaryPayload) { this(connectionName); setPayloadElement(connectionName, primaryPayload); } /** * Set the source step of producing this Data object * * @param sourceStep the source step */ public void setSourceStep(Step sourceStep) { m_sourceStep = sourceStep; } /** * Get the source step producing this Data object * * @return the source step producing the data object */ public Step getSourceStep() { return m_sourceStep; } /** * Set the connection name for this Data object * * @param name the name of the connection */ public void setConnectionName(String name) { m_connectionName = name; if (StepManagerImpl.connectionIsIncremental(this)) { setPayloadElement(StepManager.CON_AUX_DATA_IS_INCREMENTAL, true); } } /** * Get the connection name associated with this Data object * * @return the connection name */ public String getConnectionName() { return m_connectionName; } /** * Get the primary payload of this data object (i.e. the data associated with * the connection name) * * @param <T> the type of the primary payload * @return the primary payload data (or null if there is no data associated * with the connection) */ @SuppressWarnings("unchecked") public <T> T getPrimaryPayload() { return (T) m_payloadMap.get(m_connectionName); } /** * Get a payload element from this Data object. Standard payload element names * (keys) can be found as constants defined in the StepManager class. * * @param name the name of the payload element to get * @return the named payload element, or null if it does not exist in this * Data object */ @SuppressWarnings("unchecked") public <T> T getPayloadElement(String name) { return (T) m_payloadMap.get(name); } /** * Get a payload element from this Data object. Standard payload element names * (keys) can be found as constants defined in the StepManager class. * * @param name the name of the payload element to get * @param defaultValue a default value if the named element does not exist * @param <T> the type of the payload element to get * @return the payload element, or the supplied default value. */ public <T> T getPayloadElement(String name, T defaultValue) { Object result = getPayloadElement(name); if (result == null) { return defaultValue; } return (T) result; } /** * Set a payload element to encapsulate in this Data object. Standard payload * element names (keys) can be found as constants defined in the StepManager * class. * * @param name the name of the payload element to encapsulate * @param value the value of the payload element */ public void setPayloadElement(String name, Object value) { m_payloadMap.put(name, value); } /** * Clear all payload elements from this Data object */ public void clearPayload() { m_payloadMap.clear(); } /** * Return true if the connection specified for this data object is incremental * * @return true if the connection for this data object is incremental */ public boolean isIncremental() { return StepManagerImpl.connectionIsIncremental(this); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/knowledgeflow/DefaultCallbackNotifierDelegate.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * DefaultCallbackNotifierDelegate.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.knowledgeflow; /** * Default implementation of a CallbackNotifierDelegate. Notifies the * callback immediately. * * @author Mark hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class DefaultCallbackNotifierDelegate implements CallbackNotifierDelegate { /** * Notifies the callback immediately * * @param callback the callback to notify * @param taskExecuted the StepTask that was executed * @param result the ExecutionResult that was produced * @throws Exception if a problem occurs */ @SuppressWarnings("unchecked") @Override public void notifyCallback(StepTaskCallback callback, StepTask taskExecuted, ExecutionResult result) throws Exception { if (result.getError() == null) { callback.taskFinished(result); } else { callback.taskFailed(taskExecuted, result); } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/knowledgeflow/DelayedCallbackNotifierDelegate.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * DelayedCallbackNotifierDelegate.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.knowledgeflow; /** * Implementation of a CallbackNotifierDelegate that stores the ExecutionResult * and only notifies the callback when the notifyNow() method is called. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) */ public class DelayedCallbackNotifierDelegate implements CallbackNotifierDelegate { /** The callback to notify */ protected StepTaskCallback m_callback; /** The task executed */ protected StepTask m_taskExecuted; /** The result produced */ protected ExecutionResult m_result; /** * Notify the callback. This implementation stores the result, and only * notifies the callback when the notifyNow() method is called. * * @param callback the callback to notify * @param taskExecuted the StepTask that was executed * @param result the ExecutionResult that was produced * @throws Exception if a problem occurs */ @Override public void notifyCallback(StepTaskCallback callback, StepTask taskExecuted, ExecutionResult result) throws Exception { // just store callback and result here m_callback = callback; m_taskExecuted = taskExecuted; m_result = result; } /** * Do the notification now * * @throws Exception if a problem occurs */ @SuppressWarnings("unchecked") public void notifyNow() throws Exception { if (m_callback != null && m_result != null) { if (m_result.getError() != null) { m_callback.taskFinished(m_result); } else { m_callback.taskFailed(m_taskExecuted, m_result); } } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/knowledgeflow/ExecutionEnvironment.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ExecutionEnvironment.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.knowledgeflow; import weka.core.Defaults; import weka.core.Environment; import weka.core.Settings; import weka.core.WekaException; import weka.gui.Logger; import weka.gui.knowledgeflow.GraphicalEnvironmentCommandHandler; import java.util.concurrent.Future; /** * Client (i.e. from the Step perspective) interface for an execution * environment. Implementations of ExecutionEnvironment need to extend * BaseExecutionEnvironment * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) */ public interface ExecutionEnvironment { /** * Get a description of this execution environment * * @return a description of this execution environment */ String getDescription(); /** * Get default settings for this ExecutionEnvironment. * * @return the default settings for this execution environment, or null if * there are no default settings. */ Defaults getDefaultSettings(); /** * Set whether this execution environment is headless * * @param headless true if the execution environment is headless */ void setHeadless(boolean headless); /** * Get whether this execution environment is headless * * @return true if this execution environment is headless */ boolean isHeadless(); /** * Set the environment for performing commands at the application-level in a * graphical environment. * * @handler the handler to use */ void setGraphicalEnvironmentCommandHandler( GraphicalEnvironmentCommandHandler handler); /** * Get the environment for performing commands at the application-level in a * graphical environment. * * @return the graphical environment command handler, or null if running * headless */ GraphicalEnvironmentCommandHandler getGraphicalEnvironmentCommandHandler(); /** * Set environment variables for this execution environment * * @param env the environment variables to use */ void setEnvironmentVariables(Environment env); /** * Get environment variables for this execution environment * * @return the environment variables for this execution environment */ Environment getEnvironmentVariables(); /** * Set knowledge flow settings for this execution environment * * @param settings the settings to use */ void setSettings(Settings settings); /** * Get knowledge flow settings for this execution environment * * @return the settings to use */ Settings getSettings(); /** * Set the log to use * * @param log the log to use */ void setLog(Logger log); /** * Get the log in use * * @return the log in use */ Logger getLog(); /** * Set the logging level to use * * @param level the logging level to use */ void setLoggingLevel(LoggingLevel level); /** * Get the logging level in use * * @return the logging level in use */ LoggingLevel getLoggingLevel(); /** * Submit a task to be run by the execution environment. Client steps are free * to use this service or to just do their processing locally within their own * code. * * @param callable the Callable encapsulating the task to be run * @return the Future holding the status and result when complete * @throws WekaException if processing fails in the case of */ <T> Future<ExecutionResult<T>> submitTask(StepTask<T> callable) throws WekaException; /** * Step/StepManager can use this to request a stop to all processing */ void stopProcessing(); }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/knowledgeflow/ExecutionFinishedCallback.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ExecutionFinishedCallback.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.knowledgeflow; /** * Callback interface for receiving notification of a flow finishing * execution * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public interface ExecutionFinishedCallback { /** * Notification of the finish of execution */ void executionFinished(); }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/knowledgeflow/ExecutionResult.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ExecutionResult.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.knowledgeflow; import java.io.Serializable; /** * Stores the result generated by a StepTask. * * @param <T> the type of the result stored * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class ExecutionResult<T> implements Serializable { /** * For serialization */ private static final long serialVersionUID = -4495164361311877942L; /** Holds any error that might have been generated */ protected Exception m_error; /** Holds the result payload */ protected T m_executionResult; /** * Set an exception, in the case that an error occurred during the * processing done by a StepTask * * @param error */ public void setError(Exception error) { m_error = error; } /** * Get the Exception generated during processing of a StepTask, or null * if the task completed successfully. * * @return the Exception generated, or null if the task completed successfully */ public Exception getError() { return m_error; } /** * Set the result generated by the StepTask * * @param result the result generated by the StepTask */ public void setResult(T result) { m_executionResult = result; } /** * Get the result generated by the StepTask * * @return the result generated by the StepTask */ public T getResult() { return m_executionResult; } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/knowledgeflow/Flow.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * Flow.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.knowledgeflow; import weka.core.WekaException; import weka.gui.ExtensionFileFilter; import weka.gui.Logger; import weka.core.PluginManager; import weka.knowledgeflow.steps.SetVariables; import javax.swing.filechooser.FileFilter; import java.io.File; import java.io.InputStream; import java.io.Reader; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; /** * Class that encapsulates the Steps involved in a Knowledge Flow process. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class Flow { /** Holds available file extensions for flow files handled */ public static final List<FileFilter> FLOW_FILE_EXTENSIONS = new ArrayList<FileFilter>(); // register default loader for JSON flow files static { PluginManager.addPlugin(FlowLoader.class.getCanonicalName(), JSONFlowLoader.class.getCanonicalName(), JSONFlowLoader.class.getCanonicalName(), true); // TODO temporary (move to a package later) PluginManager.addPlugin(FlowLoader.class.getCanonicalName(), LegacyFlowLoader.class.getCanonicalName(), LegacyFlowLoader.class.getCanonicalName(), true); Set<String> flowLoaders = PluginManager.getPluginNamesOfType(FlowLoader.class.getCanonicalName()); if (flowLoaders != null) { try { for (String f : flowLoaders) { FlowLoader fl = (FlowLoader) PluginManager.getPluginInstance( FlowLoader.class.getCanonicalName(), f); String extension = fl.getFlowFileExtension(); String description = fl.getFlowFileExtensionDescription(); FLOW_FILE_EXTENSIONS.add(new ExtensionFileFilter("." + extension, description + " (*." + extension + ")")); } } catch (Exception ex) { ex.printStackTrace(); } } } /** Holds the Steps in this Flow, keyed by step name */ protected Map<String, StepManagerImpl> m_flowSteps = new LinkedHashMap<String, StepManagerImpl>(); /** The name of this flow */ protected String m_flowName = "Untitled"; /** * Utility method to get a FlowLoader implementation suitable for loading a * flow with the supplied file extension. * * @param flowFileExtension the file extension to get a FlowLoader for * @param log the log in use * @return a FlowLoader * @throws WekaException if a problem occurs */ public static FlowLoader getFlowLoader(String flowFileExtension, Logger log) throws WekaException { Set<String> availableLoaders = PluginManager.getPluginNamesOfType(FlowLoader.class.getCanonicalName()); FlowLoader result = null; if (availableLoaders != null) { try { for (String l : availableLoaders) { FlowLoader candidate = (FlowLoader) PluginManager.getPluginInstance( FlowLoader.class.getCanonicalName(), l); if (candidate.getFlowFileExtension().equalsIgnoreCase( flowFileExtension)) { result = candidate; break; } } } catch (Exception ex) { throw new WekaException(ex); } } if (result != null) { result.setLog(log); } return result; } /** * Utility method to load a flow from a file * * @param flowFile the file to load from * @param log the log to use * @return the loaded Flow * @throws WekaException if a problem occurs */ public static Flow loadFlow(File flowFile, Logger log) throws WekaException { String extension = "kf"; if (flowFile.toString().lastIndexOf('.') > 0) { extension = flowFile.toString().substring(flowFile.toString().lastIndexOf('.') + 1, flowFile.toString().length()); } FlowLoader toUse = getFlowLoader(extension, log); if (toUse == null) { throw new WekaException("Was unable to find a loader for flow file: " + flowFile.toString()); } return toUse.readFlow(flowFile); } /** * Utility method to load a flow from the supplied input stream using the * supplied FlowLoader * * @param is the input stream to load from * @param loader the FlowLoader to use * @return the loaded Flow * @throws WekaException if a problem occurs */ public static Flow loadFlow(InputStream is, FlowLoader loader) throws WekaException { return loader.readFlow(is); } /** * Utility method to load a flow from the supplied reader using the supplied * FlowLoader * * @param r the reader to load from * @param loader the FlowLoader to use * @return the loaded flow * @throws WekaException if a problem occurs */ public static Flow loadFlow(Reader r, FlowLoader loader) throws WekaException { return loader.readFlow(r); } /** * Parse a Flow from the supplied JSON string * * @param flowJSON the JSON string to parse * @return the Flow * @throws WekaException if a problem occurs */ public static Flow JSONToFlow(String flowJSON) throws WekaException { return JSONToFlow(flowJSON, false); } /** * Parse a Flow from the supplied JSON string * * @param flowJSON the JSON string to parse * @param dontComplainAboutMissingConnections true to not raise an exception * if there are connections to non-existent Steps in the JSON flow * @return the Flow * @throws WekaException if a problem occurs */ public static Flow JSONToFlow(String flowJSON, boolean dontComplainAboutMissingConnections) throws WekaException { return JSONFlowUtils.JSONToFlow(flowJSON, dontComplainAboutMissingConnections); } /** * Save this Flow to the supplied File * * @param file the File to save to * @throws WekaException if a problem occurs */ public void saveFlow(File file) throws WekaException { JSONFlowUtils.writeFlow(this, file); } /** * Get the name of this Flow * * @return the name of this flow */ public String getFlowName() { return m_flowName; } /** * Set the name of this Flow * * @param name the name to set */ public void setFlowName(String name) { m_flowName = name; } /** * Get an ID string for this flow. The ID is made up of the FlowName + "_" + * the hashcode generated from the JSON representation of the flow. * * @return */ public String getFlowID() { String ID = getFlowName(); try { ID += "_" + toJSON().hashCode(); } catch (WekaException ex) { ex.printStackTrace(); } return ID; } /** * All all steps in the supplied list to this Flow * * @param steps a list of StepManagers for the steps to add */ public synchronized void addAll(List<StepManagerImpl> steps) { for (StepManagerImpl s : steps) { addStep(s); } } /** * Add the given Step to this flow * * @param manager the StepManager containing the Step to add */ public synchronized void addStep(StepManagerImpl manager) { // int ID = manager.getManagedStep().hashCode(); // scan for steps that already have the same name as the step being added String toAddName = manager.getManagedStep().getName(); if (toAddName != null && toAddName.length() > 0) { boolean exactMatch = false; int maxCopyNum = 1; for (Map.Entry<String, StepManagerImpl> e : m_flowSteps.entrySet()) { String compName = e.getValue().getManagedStep().getName(); if (toAddName.equals(compName)) { exactMatch = true; } else { if (compName.startsWith(toAddName)) { String num = compName.replace(toAddName, ""); try { int compNum = Integer.parseInt(num); if (compNum > maxCopyNum) { maxCopyNum = compNum; } } catch (NumberFormatException ex) { } } } } if (exactMatch) { maxCopyNum++; toAddName += "" + maxCopyNum; manager.getManagedStep().setName(toAddName); } } m_flowSteps.put(toAddName, manager); } /** * Connect the supplied source and target steps using the given * connectionType. The connection will be successful only if both source and * target are actually part of this Flow, and the target is able to accept the * connection at this time. * * @param source the StepManager for the source step * @param target the StepManager for the target step * @param connectionType the connection type to use * says it can accept the connection type at this time) * @return true if the connection was successful */ public synchronized boolean connectSteps(StepManagerImpl source, StepManagerImpl target, String connectionType) { return connectSteps(source, target, connectionType, false); } /** * Connect the supplied source and target steps using the given * connectionType. The connection will be successful only if both source and * target are actually part of this Flow, and the target is able to accept the * connection at this time. * * @param source the StepManager for the source step * @param target the StepManager for the target step * @param connectionType the connection type to use * @param force true to force the connection (i.e. even if the target step * says it can accept the connection type at this time) * @return true if the connection was successful */ public synchronized boolean connectSteps(StepManagerImpl source, StepManagerImpl target, String connectionType, boolean force) { boolean connSuccessful = false; // make sure we contain both these steps! if (findStep(source.getName()) == source && findStep(target.getName()) == target) { // this takes care of ensuring that the target can accept // the connection at this time and the creation of the // incoming connection on the target connSuccessful = source.addOutgoingConnection(connectionType, target, force); } return connSuccessful; } /** * Rename the supplied step with the supplied name * * @param step the StepManager of the Step to rename * @param newName the new name to give the step * @throws WekaException if the Step is not part of this Flow. */ public synchronized void renameStep(StepManagerImpl step, String newName) throws WekaException { renameStep(step.getName(), newName); } /** * Rename a Step. * * @param oldName the name of the Step to rename * @param newName the new name to use * @throws WekaException if the named Step is not part of this flow */ public synchronized void renameStep(String oldName, String newName) throws WekaException { if (!m_flowSteps.containsKey(oldName)) { throw new WekaException("Step " + oldName + " does not seem to be part of the flow!"); } StepManagerImpl toRename = m_flowSteps.remove(oldName); toRename.getManagedStep().setName(newName); m_flowSteps.put(newName, toRename); } /** * Remove the supplied Step from this flow * * @param manager the StepManager of the Step to remove * @throws WekaException if the step is not part of this flow */ public synchronized void removeStep(StepManagerImpl manager) throws WekaException { // int ID = manager.getManagedStep().hashCode(); if (!m_flowSteps.containsKey(manager.getManagedStep().getName())) { throw new WekaException("Step " + manager.getManagedStep().getName() + " does not seem to be part of the flow!"); } m_flowSteps.remove(manager.getManagedStep().getName()); manager.clearAllConnections(); // remove from the map & disconnect from other steps! for (Map.Entry<String, StepManagerImpl> e : m_flowSteps.entrySet()) { e.getValue().disconnectStep(manager.getManagedStep()); } } /** * Get a list of the Steps in this Flow * * @return a list of StepManagers of the steps in this flow */ public List<StepManagerImpl> getSteps() { return new ArrayList<StepManagerImpl>(m_flowSteps.values()); } /** * Get an Iterator over the Steps in this flow * * @return an Iterator over the StepManagers of the Steps in this flow */ public Iterator<StepManagerImpl> iterator() { return m_flowSteps.values().iterator(); } /** * Get the number of steps in this flow * * @return the number of steps in this flow */ public int size() { return m_flowSteps.size(); } /** * Find a Step by name * * @param stepName the name of the Step to find * @return the StepManager of the named Step, or null if the Step is not part * of this flow */ public StepManagerImpl findStep(String stepName) { return m_flowSteps.get(stepName); } /** * Get a list of potential start points in this Flow. Potential start points * are those steps that have no incoming connections. * * @return a list of potential start points */ public List<StepManagerImpl> findPotentialStartPoints() { List<StepManagerImpl> startPoints = new ArrayList<StepManagerImpl>(); // potential start points will have no incoming connections... for (Map.Entry<String, StepManagerImpl> e : m_flowSteps.entrySet()) { StepManagerImpl candidate = e.getValue(); if (candidate.getIncomingConnections().size() == 0) { startPoints.add(candidate); } } return startPoints; } /** * Initialize the flow by setting the execution environment and calling the * init() method of each step * * @param executor the flow executor being used to execute the flow * @return false if initialization failed * @throws WekaException if a problem occurs during flow initialization */ public boolean initFlow(FlowExecutor executor) throws WekaException { boolean initOK = true; // first set the execution environment for (Map.Entry<String, StepManagerImpl> s : m_flowSteps.entrySet()) { s.getValue().setExecutionEnvironment(executor.getExecutionEnvironment()); } // scan for any SetVariables steps so that we can init() those first... for (Map.Entry<String, StepManagerImpl> s : m_flowSteps.entrySet()) { if (s.getValue().getManagedStep() instanceof SetVariables) { if (!s.getValue().initStep()) { initOK = false; break; } } } if (initOK) { // now call init() on each step for (Map.Entry<String, StepManagerImpl> s : m_flowSteps.entrySet()) { if (!s.getValue().initStep()) { initOK = false; break; } } } return initOK; } /** * Return the JSON encoded version of this Flow * * @return the flow in JSON format * @throws WekaException if a problem occurs */ public String toJSON() throws WekaException { return JSONFlowUtils.flowToJSON(this); } /** * Make a copy of this Flow * * @return a copy of this Flow * @throws WekaException if a problem occurs */ public Flow copyFlow() throws WekaException { return JSONToFlow(toJSON()); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/knowledgeflow/FlowExecutor.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * FlockExecutor.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.knowledgeflow; import weka.core.Settings; import weka.core.WekaException; import weka.gui.Logger; /** * Interface to something that can execute a Knowledge Flow process * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public interface FlowExecutor { /** * Set the flow to be executed * * @param flow the flow to execute */ void setFlow(Flow flow); /** * Get the flow to be executed * * @return the flow to be executed */ Flow getFlow(); /** * Set a log to use * * @param logger the log tos use */ void setLogger(Logger logger); /** * Get the log in use * * @return the log in use */ Logger getLogger(); /** * Set the level to log at * * @param level the level to log at (logging messages at this level or below * will be displayed in the log) */ void setLoggingLevel(LoggingLevel level); /** * Get the logging level to log at * * @return the logging level to log at */ public LoggingLevel getLoggingLevel(); /** * Set the execution environment to use * * @param env the execution environment to use */ void setExecutionEnvironment(BaseExecutionEnvironment env); /** * Convenience method for applying settings - implementers should delegate the * the execution environment * * @param settings the settings to use */ void setSettings(Settings settings); /** * Convenience method for getting current settings - implementers should * delegate the the execution environment * * @return the settings in use */ Settings getSettings(); /** * Return the execution environment object for this flow executor * * @return the execution environment */ BaseExecutionEnvironment getExecutionEnvironment(); /** * Run the flow sequentially (i.e. launch start points sequentially rather * than in parallel) * * @throws WekaException if a problem occurs during execution */ void runSequentially() throws WekaException; /** * Run the flow by launching all start points in parallel * * @throws WekaException if a problem occurs during execution */ void runParallel() throws WekaException; /** * Block until all steps are no longer busy */ void waitUntilFinished(); /** * Stop all processing */ void stopProcessing(); /** * Returns true if execution was stopped via the stopProcessing() method * * @return true if execution was stopped */ boolean wasStopped(); /** * Add a callback to notify when execution finishes * * @param callback the callback to notify */ void addExecutionFinishedCallback(ExecutionFinishedCallback callback); /** * Remove a callback * * @param callback the callback to remove */ void removeExecutionFinishedCallback(ExecutionFinishedCallback callback); }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/knowledgeflow/FlowLoader.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * FlowLoader * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.knowledgeflow; import weka.core.WekaException; import weka.gui.Logger; import java.io.File; import java.io.InputStream; import java.io.Reader; /** * Interface to something that can load a Knowledge Flow * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public interface FlowLoader { /** * Set a log to use * * @param log log to use */ void setLog(Logger log); /** * Get the extension of the Knowledge Flow file format handled by this loader * * @return the flow file extension */ String getFlowFileExtension(); /** * Get a description of the flow file format handled by this loader * * @return a description of the file format handles */ String getFlowFileExtensionDescription(); /** * Load a flow from the supplied file * * @param flowFile the file to load from * @return the loaded Flow * @throws WekaException if a problem occurs */ Flow readFlow(File flowFile) throws WekaException; /** * Load a flow from the supplied input stream * * @param is the input stream to load from * @return the loaded Flow * @throws WekaException if a problem occurs */ Flow readFlow(InputStream is) throws WekaException; /** * Load a flow from the supplied reader * * @param r the reader to load from * @return the loaded Flow * @throws WekaException if a problem occurs */ Flow readFlow(Reader r) throws WekaException; }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/knowledgeflow/FlowRunner.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * FlowRunner.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.knowledgeflow; import weka.core.CommandlineRunnable; import weka.core.Environment; import weka.core.PluginManager; import weka.core.Settings; import weka.core.Utils; import weka.core.WekaException; import weka.core.WekaPackageManager; import weka.gui.Logger; import weka.gui.knowledgeflow.KnowledgeFlowApp; import weka.knowledgeflow.steps.Note; import java.io.File; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.TreeMap; /** * A FlowExecutor that can launch start points in a flow in parallel or * sequentially. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class FlowRunner implements FlowExecutor, CommandlineRunnable { /** The flow to execute */ protected Flow m_flow; /** The execution environment */ protected transient BaseExecutionEnvironment m_execEnv; /** The log to use */ protected transient Logger m_log = new SimpleLogger(); /** Local log handler for FlowRunner-specific logging */ protected transient LogManager m_logHandler; /** The level to at which to log at */ protected LoggingLevel m_loggingLevel = LoggingLevel.BASIC; /** Invoke start points sequentially? */ protected boolean m_startSequentially; /** Number of worker threads to use in the step executor service */ protected int m_numThreads = BaseExecutionEnvironment.BaseExecutionEnvironmentDefaults.STEP_EXECUTOR_SERVICE_NUM_THREADS; /** * Number of worker threads to use in the resource intensive executor service */ protected int m_resourceIntensiveNumThreads = BaseExecutionEnvironment.BaseExecutionEnvironmentDefaults.RESOURCE_INTENSIVE_EXECUTOR_SERVICE_NUM_THREADS; /** Callback to notify when execution completes */ protected List<ExecutionFinishedCallback> m_callbacks = new ArrayList<ExecutionFinishedCallback>(); /** Gets set to true if the stopProcessing() method is called */ protected boolean m_wasStopped; /** * Constructor */ public FlowRunner() { Settings settings = new Settings("weka", KFDefaults.APP_ID); settings.applyDefaults(new KFDefaults()); init(settings); } /** * Constructor */ public FlowRunner(Settings settings) { init(settings); } protected void init(Settings settings) { // TODO probably need some command line options to override settings for // logging, execution environment etc. // force the base execution environment class to be loaded so that it // registers itself with the plugin manager new BaseExecutionEnvironment(); String execName = settings.getSetting(KFDefaults.APP_ID, KnowledgeFlowApp.KnowledgeFlowGeneralDefaults.EXECUTION_ENV_KEY, KnowledgeFlowApp.KnowledgeFlowGeneralDefaults.EXECUTION_ENV); BaseExecutionEnvironment execE = null; try { execE = (BaseExecutionEnvironment) PluginManager.getPluginInstance( BaseExecutionEnvironment.class.getCanonicalName(), execName); } catch (Exception ex) { ex.printStackTrace(); } if (execE != null) { m_execEnv = execE; } else { // default execution environment is headless m_execEnv = new BaseExecutionEnvironment(); } m_execEnv.setHeadless(true); m_execEnv.setFlowExecutor(this); m_execEnv.setLog(m_log); m_execEnv.setSettings(settings); m_numThreads = settings .getSetting( KFDefaults.APP_ID, BaseExecutionEnvironment.BaseExecutionEnvironmentDefaults.STEP_EXECUTOR_SERVICE_NUM_THREADS_KEY, BaseExecutionEnvironment.BaseExecutionEnvironmentDefaults.STEP_EXECUTOR_SERVICE_NUM_THREADS); m_resourceIntensiveNumThreads = settings .getSetting( KFDefaults.APP_ID, BaseExecutionEnvironment.BaseExecutionEnvironmentDefaults.RESOURCE_INTENSIVE_EXECUTOR_SERVICE_NUM_THREADS_KEY, BaseExecutionEnvironment.BaseExecutionEnvironmentDefaults.RESOURCE_INTENSIVE_EXECUTOR_SERVICE_NUM_THREADS); } /** * Set the settings to use when executing the Flow * * @param settings the settings to use */ @Override public void setSettings(Settings settings) { init(settings); } /** * Get the settings in use when executing the Flow * * @return the settings */ @Override public Settings getSettings() { return m_execEnv.getSettings(); } /** * Main method for executing the FlowRunner * * @param args command line arguments */ public static void main(String[] args) { weka.core.logging.Logger.log(weka.core.logging.Logger.Level.INFO, "Logging started"); try { WekaPackageManager.loadPackages(false, true, false); FlowRunner fr = new FlowRunner(); fr.run(fr, args); } catch (Exception ex) { ex.printStackTrace(); } } /** * Run a FlowRunner object * * @param toRun the FlowRunner object to execute * @param args the command line arguments * @throws Exception if a problem occurs */ @Override public void run(Object toRun, String[] args) throws Exception { if (!(toRun instanceof FlowRunner)) { throw new IllegalArgumentException("Object to run is not an instance of " + "FlowRunner!"); } if (args.length < 1) { System.err.println("Usage:\n\nFlowRunner <json flow file> [-s]\n\n" + "\tUse -s to launch start points sequentially (default launches " + "in parallel)."); } else { Settings settings = new Settings("weka", KFDefaults.APP_ID); settings.loadSettings(); settings.applyDefaults(new KFDefaults()); FlowRunner fr = (FlowRunner) toRun; fr.setSettings(settings); String fileName = args[0]; args[0] = ""; fr.setLaunchStartPointsSequentially(Utils.getFlag("s", args)); Flow flowToRun = Flow.loadFlow(new File(fileName), new SimpleLogger()); fr.setFlow(flowToRun); fr.run(); fr.waitUntilFinished(); fr.m_logHandler.logLow("FlowRunner: Finished all flows."); System.exit(0); } } /** * Set a callback to notify when flow execution finishes * * @param callback the callback to notify */ @Override public void addExecutionFinishedCallback(ExecutionFinishedCallback callback) { if (!m_callbacks.contains(callback)) { m_callbacks.add(callback); } } /** * Remove a callback * * @param callback the callback to remove */ @Override public void removeExecutionFinishedCallback(ExecutionFinishedCallback callback) { m_callbacks.remove(callback); } /** * Get the flow to execute * * @return the flow to execute */ @Override public Flow getFlow() { return m_flow; } /** * Set the flow to execute * * @param flow the flow to execute */ @Override public void setFlow(Flow flow) { m_flow = flow; } /** * Get the log to use * * @return the log to use */ @Override public Logger getLogger() { return m_log; } /** * Set the log to use * * @param logger the log to use */ @Override public void setLogger(Logger logger) { m_log = logger; if (m_execEnv != null) { m_execEnv.setLog(logger); } } /** * Get the logging level to use * * @return the logging level to use */ @Override public LoggingLevel getLoggingLevel() { return m_loggingLevel; } /** * Set the logging level to use * * @param level the logging level to use */ @Override public void setLoggingLevel(LoggingLevel level) { m_loggingLevel = level; if (m_execEnv != null) { m_execEnv.setLoggingLevel(level); } } /** * Get whether to launch start points sequentially * * @return true if start points are to be launched sequentially */ public boolean getLaunchStartPointsSequentially() { return m_startSequentially; } /** * Set whether to launch start points sequentially * * @param s true if start points are to be launched sequentially */ public void setLaunchStartPointsSequentially(boolean s) { m_startSequentially = s; } @Override public BaseExecutionEnvironment getExecutionEnvironment() { return m_execEnv; } /** * Set the execution environment to use * * @param env the execution environment to use */ @Override public void setExecutionEnvironment(BaseExecutionEnvironment env) { m_execEnv = env; } /** * Execute the flow * * @throws WekaException if a problem occurs */ public void run() throws WekaException { if (m_flow == null) { throw new WekaException("No flow to execute!"); } if (m_startSequentially) { runSequentially(); } else { runParallel(); } } /** * Initialize the flow ready for execution * * @return a list of start points in the Flow * @throws WekaException if a problem occurs during initialization */ protected List<StepManagerImpl> initializeFlow() throws WekaException { m_wasStopped = false; if (m_flow == null) { m_wasStopped = true; for (ExecutionFinishedCallback c : m_callbacks) { c.executionFinished(); } throw new WekaException("No flow to execute!"); } m_logHandler = new LogManager(m_log); m_logHandler.m_statusMessagePrefix = "FlowRunner$" + hashCode() + "|"; setLoggingLevel(m_execEnv.getSettings().getSetting( KFDefaults.MAIN_PERSPECTIVE_ID, KFDefaults.LOGGING_LEVEL_KEY, LoggingLevel.BASIC, Environment.getSystemWide())); m_logHandler.setLoggingLevel(m_loggingLevel); List<StepManagerImpl> startPoints = m_flow.findPotentialStartPoints(); if (startPoints.size() == 0) { m_wasStopped = true; m_logHandler.logError("FlowRunner: there don't appear to be any " + "start points to launch!", null); for (ExecutionFinishedCallback c : m_callbacks) { c.executionFinished(); } return null; } m_wasStopped = false; m_execEnv.startClientExecutionService(m_numThreads, m_resourceIntensiveNumThreads); if (!m_flow.initFlow(this)) { m_wasStopped = true; for (ExecutionFinishedCallback c : m_callbacks) { c.executionFinished(); } throw new WekaException( "Flow did not initializeFlow properly - check log."); } return startPoints; } /** * Run the flow by launching start points sequentially. * * @throws WekaException if a problem occurs */ @Override public void runSequentially() throws WekaException { List<StepManagerImpl> startPoints = initializeFlow(); if (startPoints == null) { return; } runSequentially(startPoints); } /** * Run the flow by launching start points in parallel * * @throws WekaException if a problem occurs */ @Override public void runParallel() throws WekaException { List<StepManagerImpl> startPoints = initializeFlow(); if (startPoints == null) { return; } runParallel(startPoints); } /** * Execute the flow by launching start points sequentially * * @param startPoints the list of potential start points * @throws WekaException if a problem occurs */ protected void runSequentially(List<StepManagerImpl> startPoints) throws WekaException { m_logHandler.logDetailed("Flow runner: using execution environment - " + "" + m_execEnv.getDescription()); TreeMap<Integer, StepManagerImpl> sortedStartPoints = new TreeMap<Integer, StepManagerImpl>(); List<StepManagerImpl> unNumbered = new ArrayList<StepManagerImpl>(); for (StepManagerImpl s : startPoints) { String stepName = s.getManagedStep().getName(); if (stepName.startsWith("!")) { continue; } if (stepName.indexOf(":") > 0) { try { Integer num = Integer.parseInt(stepName.split(":")[0]); sortedStartPoints.put(num, s); } catch (NumberFormatException ex) { unNumbered.add(s); } } else { unNumbered.add(s); } } int biggest = 0; if (sortedStartPoints.size() > 0) { biggest = sortedStartPoints.lastKey(); } for (StepManagerImpl s : unNumbered) { biggest++; sortedStartPoints.put(biggest, s); } for (final StepManagerImpl stepToStart : sortedStartPoints.values()) { if (stepToStart.getManagedStep() instanceof Note) { continue; } m_logHandler.logLow("FlowRunner: Launching start point: " + stepToStart.getManagedStep().getName()); m_execEnv.launchStartPoint(stepToStart); /* * m_execEnv.submitTask(new StepTask<Void>(null) { * * /** For serialization * private static final long serialVersionUID = * -5466021103296024455L; * * @Override public void process() throws Exception { * stepToStart.startStep(); } }); */ } m_logHandler.logDebug("FlowRunner: Launching shutdown monitor"); launchExecutorShutdownThread(); } /** * Execute the flow by launching start points in parallel * * @param startPoints the list of potential start points to execute * @throws WekaException if a problem occurs */ protected void runParallel(List<StepManagerImpl> startPoints) throws WekaException { m_logHandler.logDetailed("Flow runner: using execution environment - " + "" + m_execEnv.getDescription()); for (final StepManagerImpl startP : startPoints) { if (startP.getManagedStep().getName().startsWith("!") || startP.getManagedStep() instanceof Note) { continue; } m_logHandler.logLow("FlowRunner: Launching start point: " + startP.getManagedStep().getName()); m_execEnv.launchStartPoint(startP); /* * m_execEnv.submitTask(new StepTask<Void>(null) { /** For serialization * * private static final long serialVersionUID = 663985401825979869L; * * @Override public void process() throws Exception { startP.startStep(); * } }); */ } m_logHandler.logDebug("FlowRunner: Launching shutdown monitor"); launchExecutorShutdownThread(); } /** * Launch a thread to monitor the progress of the flow, and then shutdown the * executor service once all steps have completed. */ protected void launchExecutorShutdownThread() { if (m_execEnv != null) { Thread shutdownThread = new Thread() { @Override public void run() { waitUntilFinished(); m_logHandler.logDebug("FlowRunner: Shutting down executor service"); m_execEnv.stopClientExecutionService(); for (ExecutionFinishedCallback c : m_callbacks) { c.executionFinished(); } } }; shutdownThread.start(); } } /** * Wait until all the steps are no longer busy */ @Override public void waitUntilFinished() { try { Thread.sleep(800); while (true) { boolean busy = flowBusy(); if (busy) { Thread.sleep(3000); } else { break; } } } catch (Exception ex) { m_logHandler.logDetailed("FlowRunner: Attempting to stop all steps..."); } } /** * Checks to see if any step(s) are doing work * * @return true if one or more steps in the flow are busy */ public boolean flowBusy() { boolean busy = false; Iterator<StepManagerImpl> iter = m_flow.iterator(); while (iter.hasNext()) { StepManagerImpl s = iter.next(); if (s.isStepBusy()) { m_logHandler.logDebug(s.getName() + " is still busy."); busy = true; } } return busy; } /** * Attempt to stop processing in all steps */ @Override public synchronized void stopProcessing() { Iterator<StepManagerImpl> iter = m_flow.iterator(); while (iter.hasNext()) { iter.next().stopStep(); } System.err.println("Asked all steps to stop..."); m_wasStopped = true; } /** * Returns true if execution was stopped via the stopProcessing() method * * @return true if execution was stopped. */ @Override public boolean wasStopped() { return m_wasStopped; } @Override public void preExecution() throws Exception { } @Override public void postExecution() throws Exception { } /** * A simple logging implementation that writes to standard out * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) */ public static class SimpleLogger implements weka.gui.Logger { /** The date format to use for logging */ SimpleDateFormat m_DateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); @Override public void logMessage(String lm) { System.out.println(m_DateFormat.format(new Date()) + ": " + lm); } @Override public void statusMessage(String lm) { // don't output status messages to the console } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/knowledgeflow/JSONFlowLoader.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * JSONFlowLoader.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.knowledgeflow; import weka.core.WekaException; import weka.gui.Logger; import java.io.File; import java.io.InputStream; import java.io.Reader; /** * Flow loader that wraps the routines in JSONFlowUtils * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class JSONFlowLoader implements FlowLoader { /** The log to use */ protected Logger m_log; /** The file exetension for JSON-based flows */ public static final String EXTENSION = "kf"; /** * Set a log to use * * @param log log to use */ @Override public void setLog(Logger log) { m_log = log; } /** * Get the file extension handled by this loader * * @return the file extension */ @Override public String getFlowFileExtension() { return EXTENSION; } /** * Get the description of the file format handled by this loader * * @return the description of the file format handled */ @Override public String getFlowFileExtensionDescription() { return "JSON Knowledge Flow configuration files"; } /** * Read the flow from the supplied file * * @param flowFile the file to load from * @return the Flow read * @throws WekaException if a problem occurs */ @Override public Flow readFlow(File flowFile) throws WekaException { return JSONFlowUtils.readFlow(flowFile); } /** * Read the flow from the supplied input stream * * @param is the input stream to load from * @return the Flow read * @throws WekaException */ @Override public Flow readFlow(InputStream is) throws WekaException { return JSONFlowUtils.readFlow(is); } /** * Read the flow from the supplied reader * * @param r the reader to load from * @return the Flow read * @throws WekaException if a problem occurs */ @Override public Flow readFlow(Reader r) throws WekaException { return JSONFlowUtils.readFlow(r); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/knowledgeflow/JSONFlowUtils.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * JSONFlowUtils.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.knowledgeflow; import weka.core.EnumHelper; import weka.core.Environment; import weka.core.EnvironmentHandler; import weka.core.OptionHandler; import weka.core.Settings; import weka.core.Utils; import weka.core.WekaException; import weka.core.WekaPackageClassLoaderManager; import weka.core.json.JSONNode; import weka.gui.FilePropertyMetadata; import weka.knowledgeflow.steps.ClassAssigner; import weka.knowledgeflow.steps.NotPersistable; import weka.knowledgeflow.steps.Saver; import weka.knowledgeflow.steps.Step; import weka.knowledgeflow.steps.TrainingSetMaker; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.StringReader; import java.io.Writer; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Utilities for building and saving flows from JSON data * * @author Mark Hall */ public class JSONFlowUtils { public static final String FLOW_NAME = "flow_name"; public static final String STEPS = "steps"; public static final String OPTIONHANDLER = "optionHandler"; public static final String OPTIONS = "options"; public static final String LOADER = "loader"; public static final String SAVER = "saver"; public static final String ENUM_HELPER = "enumHelper"; public static final String CLASS = "class"; public static final String PROPERTIES = "properties"; public static final String CONNECTIONS = "connections"; public static final String COORDINATES = "coordinates"; /** * Add a name,value pair to the JSON * * @param b the StringBuilder to add the pair to * @param name the name * @param value the associated value * @param comma if true postfix a comma */ protected static void addNameValue(StringBuilder b, String name, String value, boolean comma) { b.append(name).append(" : ").append(value); if (comma) { b.append(","); } } /** * Add an {@code OptionHandler} spec to the JSON * * @param propName the name to associate with the option handler * @param handler the option handler * @param json the current {@JSONNode} to add to */ protected static void addOptionHandler(String propName, OptionHandler handler, JSONNode json) { JSONNode optionNode = json.addObject(propName); optionNode.addPrimitive("type", OPTIONHANDLER); optionNode.addPrimitive(CLASS, handler.getClass().getCanonicalName()); optionNode.addPrimitive(OPTIONS, Utils.joinOptions(handler.getOptions())); } /** * Add an enum to the JSON * * @param propName the name to associate the enum with * @param ee the enum to add * @param json the current {@code JSONNode} to add to */ protected static void addEnum(String propName, Enum ee, JSONNode json) { JSONNode enumNode = json.addObject(propName); enumNode.addPrimitive("type", ENUM_HELPER); EnumHelper helper = new EnumHelper(ee); enumNode.addPrimitive(CLASS, helper.getEnumClass()); enumNode.addPrimitive("value", helper.getSelectedEnumValue()); } /** * Add a {@code weka.core.converters.Saver} to the JSON * * @param propName the name to associate the saver with * @param saver the saver to add * @param json the current {@code JSONNode} to add to */ protected static void addSaver(String propName, weka.core.converters.Saver saver, JSONNode json) { JSONNode saverNode = json.addObject(propName); saverNode.addPrimitive("type", SAVER); saverNode.addPrimitive(CLASS, saver.getClass().getCanonicalName()); String prefix = ""; String dir = ""; 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('\\', '/'); } Boolean relativeB = null; if (saver instanceof weka.core.converters.FileSourcedConverter) { relativeB = ((weka.core.converters.FileSourcedConverter) saver) .getUseRelativePath(); } saverNode.addPrimitive("filePath", ""); saverNode.addPrimitive("dir", dir); saverNode.addPrimitive("prefix", prefix); if (relativeB != null) { saverNode.addPrimitive("useRelativePath", relativeB); } if (saver instanceof OptionHandler) { String optsString = Utils.joinOptions(((OptionHandler) saver).getOptions()); saverNode.addPrimitive(OPTIONS, optsString); } } /** * Add a {@code weka.core.converters.Loader} to the JSON * * @param propName the name to associate the loader with * @param loader the loader to add * @param json the curren {@code JSONNode} to add to */ protected static void addLoader(String propName, weka.core.converters.Loader loader, JSONNode json) { JSONNode loaderNode = json.addObject(propName); loaderNode.addPrimitive("type", LOADER); loaderNode.addPrimitive("class", loader.getClass().getCanonicalName()); File file = null; if (loader instanceof weka.core.converters.AbstractFileLoader) { file = ((weka.core.converters.AbstractFileLoader) loader).retrieveFile(); } Boolean relativeB = null; if (loader instanceof weka.core.converters.FileSourcedConverter) { relativeB = ((weka.core.converters.FileSourcedConverter) loader) .getUseRelativePath(); } if (file != null && !file.isDirectory()) { String withResourceSeparators = file.getPath().replace(File.pathSeparatorChar, '/'); boolean notAbsolute = (((weka.core.converters.AbstractFileLoader) loader) .getUseRelativePath() || (loader instanceof EnvironmentHandler && Environment .containsEnvVariables(file.getPath())) || JSONFlowUtils.class.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('\\', '/'); loaderNode.addPrimitive("filePath", path); } else { loaderNode.addPrimitive("filePath", ""); } if (relativeB != null) { loaderNode.addPrimitive("useRelativePath", relativeB); } if (loader instanceof OptionHandler) { String optsString = Utils.joinOptions(((OptionHandler) loader).getOptions()); loaderNode.addPrimitive(OPTIONS, optsString); } } /** * Add a step to the JSON * * @param stepArray the {@code JSONNode} to add the step to * @param stepManager the {@code StepManager} of the step to add * @throws WekaException if a problem occurs */ protected static void addStepJSONtoFlowArray(JSONNode stepArray, StepManagerImpl stepManager) throws WekaException { JSONNode step = stepArray.addObjectArrayElement(); step.addPrimitive("class", stepManager.getManagedStep().getClass() .getCanonicalName()); // step.addPrimitive(STEP_NAME, stepManager.getManagedStep().getName()); JSONNode properties = step.addObject(PROPERTIES); try { Step theStep = stepManager.getManagedStep(); BeanInfo bi = Introspector.getBeanInfo(theStep.getClass()); PropertyDescriptor[] stepProps = bi.getPropertyDescriptors(); for (PropertyDescriptor p : stepProps) { if (p.isHidden() || p.isExpert()) { continue; } String name = p.getDisplayName(); Method getter = p.getReadMethod(); Method setter = p.getWriteMethod(); if (getter == null || setter == null) { continue; } boolean skip = false; for (Annotation a : getter.getAnnotations()) { if (a instanceof NotPersistable) { skip = true; break; } } if (skip) { continue; } Object[] args = {}; Object propValue = getter.invoke(theStep, args); if (propValue == null) { properties.addNull(name); } else if (propValue instanceof Boolean) { properties.addPrimitive(name, (Boolean) propValue); } else if (propValue instanceof Integer || propValue instanceof Long) { properties.addPrimitive(name, new Integer(((Number) propValue).intValue())); } else if (propValue instanceof Double) { properties.addPrimitive(name, (Double) propValue); } else if (propValue instanceof Number) { properties.addPrimitive(name, new Double(((Number) propValue).doubleValue())); } else if (propValue instanceof weka.core.converters.Loader) { addLoader(name, (weka.core.converters.Loader) propValue, properties); } else if (propValue instanceof weka.core.converters.Saver) { addSaver(name, (weka.core.converters.Saver) propValue, properties); } else if (propValue instanceof OptionHandler) { addOptionHandler(name, (OptionHandler) propValue, properties); } else if (propValue instanceof Enum) { addEnum(name, (Enum) propValue, properties); } else if (propValue instanceof File) { String fString = propValue.toString(); fString = fString.replace('\\', '/'); properties.addPrimitive(name, fString); } else { properties.addPrimitive(name, propValue.toString()); } } } catch (Exception ex) { throw new WekaException(ex); } JSONNode connections = step.addObject(CONNECTIONS); for (Map.Entry<String, List<StepManager>> e : stepManager.m_connectedByTypeOutgoing .entrySet()) { String connName = e.getKey(); JSONNode connTypeArray = connections.addArray(connName); for (StepManager c : e.getValue()) { connTypeArray.addArrayElement(c.getName()); } } if (stepManager.getStepVisual() != null) { String coords = "" + stepManager.getStepVisual().getX() + "," + stepManager.getStepVisual().getY(); step.addPrimitive(COORDINATES, coords); } } /** * Read a {@code weka.core.converters.Loader} from the current JSON node * * @param loaderNode the {@code JSONNode} to read the loader from * @return the instantiated loader * @throws WekaException if a problem occurs */ protected static weka.core.converters.Loader readStepPropertyLoader( JSONNode loaderNode) throws WekaException { String clazz = loaderNode.getChild(CLASS).getValue().toString(); try { weka.core.converters.Loader loader = (weka.core.converters.Loader) WekaPackageClassLoaderManager .objectForName(clazz); /* * Beans.instantiate( JSONFlowUtils.class.getClassLoader(), clazz); */ if (loader instanceof OptionHandler) { String optionString = loaderNode.getChild(OPTIONS).getValue().toString(); if (optionString != null && optionString.length() > 0) { ((OptionHandler) loader).setOptions(Utils.splitOptions(optionString)); } } if (loader instanceof weka.core.converters.AbstractFileLoader) { String filePath = loaderNode.getChild("filePath").getValue().toString(); if (filePath.length() > 0) { ((weka.core.converters.AbstractFileLoader) loader) .setSource(new File(filePath)); } } if (loader instanceof weka.core.converters.FileSourcedConverter) { Boolean relativePath = (Boolean) loaderNode.getChild("useRelativePath").getValue(); ((weka.core.converters.FileSourcedConverter) loader) .setUseRelativePath(relativePath); } return loader; } catch (Exception ex) { throw new WekaException(ex); } } /** * Read a {@code weka.core.converters.Saver} from the current JSON node * * @param saverNode the {@code JSONNode} to read from * @return an instantiated saver * @throws WekaException if a problem occurs */ protected static weka.core.converters.Saver readStepPropertySaver( JSONNode saverNode) throws WekaException { String clazz = saverNode.getChild(CLASS).getValue().toString(); try { weka.core.converters.Saver saver = (weka.core.converters.Saver) WekaPackageClassLoaderManager .objectForName(clazz); /* * Beans.instantiate( JSONFlowUtils.class.getClassLoader(), clazz); */ if (saver instanceof OptionHandler) { String optionString = saverNode.getChild(OPTIONS).getValue().toString(); if (optionString != null && optionString.length() > 0) { ((OptionHandler) saver).setOptions(Utils.splitOptions(optionString)); } } if (saver instanceof weka.core.converters.AbstractFileSaver) { String dir = saverNode.getChild("dir").getValue().toString(); String prefix = saverNode.getChild("prefix").getValue().toString(); if (dir != null && prefix != null) { ((weka.core.converters.AbstractFileSaver) saver).setDir(dir); ((weka.core.converters.AbstractFileSaver) saver) .setFilePrefix(prefix); } } if (saver instanceof weka.core.converters.FileSourcedConverter) { Boolean relativePath = (Boolean) saverNode.getChild("useRelativePath").getValue(); ((weka.core.converters.FileSourcedConverter) saver) .setUseRelativePath(relativePath); } return saver; } catch (Exception ex) { throw new WekaException(ex); } } /** * Read an {@code OptionHandler} from the current JSON node * * @param optionHNode the {@code JSONNode} to read from * @return an instantiated and configured option handler * @throws WekaException if a problem occurs */ protected static OptionHandler readStepPropertyOptionHandler( JSONNode optionHNode) throws WekaException { String clazz = optionHNode.getChild(CLASS).getValue().toString(); try { OptionHandler oh = (OptionHandler) WekaPackageClassLoaderManager.objectForName(clazz); /* * Beans.instantiate(JSONFlowUtils.class.getClassLoader(), clazz); */ String optionString = optionHNode.getChild(OPTIONS).getValue().toString(); if (optionString != null && optionString.length() > 0) { String[] options = Utils.splitOptions(optionString); oh.setOptions(options); } return oh; } catch (Exception ex) { throw new WekaException(ex); } } /** * Read an enum from the current JSON node * * @param enumNode the {@code JSONNode} to read from * @return the enum object * @throws WekaException if a problem occurs */ protected static Object readStepPropertyEnum(JSONNode enumNode) throws WekaException { EnumHelper helper = new EnumHelper(); String clazz = enumNode.getChild(CLASS).getValue().toString(); String value = enumNode.getChild("value").getValue().toString(); try { return EnumHelper.valueFromString(clazz, value); } catch (Exception ex) { throw new WekaException(ex); } } /** * Read a step property object from the current JSON node. Handles option * handlers, loaders, savers and enums. * * @param propNode the {@code JSONNode} to read from * @return a step property object * @throws Exception if a problem occurs */ protected static Object readStepObjectProperty(JSONNode propNode) throws Exception { String type = propNode.getChild("type").getValue().toString(); if (type.equals(OPTIONHANDLER)) { return readStepPropertyOptionHandler(propNode); } else if (type.equals(LOADER)) { return readStepPropertyLoader(propNode); } else if (type.equals(SAVER)) { return readStepPropertySaver(propNode); } else if (type.equals(ENUM_HELPER)) { return readStepPropertyEnum(propNode); } else { throw new WekaException("Unknown object property type: " + type); } } /** * Checks a property to see if it is tagged with the FilePropertyMetadata * class. If so, it converts the string property into an actual file property * so that the Step can be restored correctly * * @param theValue the value of the property * @param propD the PropertyDescriptor for the property * @return a File object or null if this property is not tagged as a file * property */ protected static File checkForFileProp(Object theValue, PropertyDescriptor propD) { Method writeMethod = propD.getWriteMethod(); Method readMethod = propD.getReadMethod(); if (writeMethod != null && readMethod != null) { FilePropertyMetadata fM = writeMethod.getAnnotation(FilePropertyMetadata.class); if (fM == null) { fM = readMethod.getAnnotation(FilePropertyMetadata.class); } if (fM != null) { return new File(theValue.toString()); } } return null; } /** * Read a {@code Step} from the supplied JSON node * * @param stepNode the {@code JSONNode} to read from * @param flow the {@code Flow} to add the read step to * @throws WekaException if a problem occurs */ protected static void readStep(JSONNode stepNode, Flow flow) throws WekaException { String clazz = stepNode.getChild(CLASS).getValue().toString(); Object step = null; Step theStep = null; try { step = WekaPackageClassLoaderManager.objectForName(clazz); // Beans.instantiate(JSONFlowUtils.class.getClassLoader(), clazz); if (!(step instanceof Step)) { throw new WekaException( "Instantiated a knowledge flow step that does not implement StepComponent!"); } theStep = (Step) step; JSONNode properties = stepNode.getChild(PROPERTIES); for (int i = 0; i < properties.getChildCount(); i++) { JSONNode aProp = (JSONNode) properties.getChildAt(i); Object valueToSet = null; if (aProp.isObject()) { valueToSet = readStepObjectProperty(aProp); } else if (aProp.isArray()) { // TODO } else { valueToSet = aProp.getValue(); } try { if (valueToSet != null) { PropertyDescriptor propD = new PropertyDescriptor(aProp.getName(), theStep.getClass()); File checkForFileProp = checkForFileProp(valueToSet, propD); if (checkForFileProp != null) { valueToSet = checkForFileProp; } Method writeMethod = propD.getWriteMethod(); if (writeMethod == null) { System.err .println("Unable to obtain a setter method for property '" + aProp.getName() + "' in step class '" + clazz); continue; } Object[] arguments = { valueToSet }; writeMethod.invoke(theStep, arguments); } } catch (IntrospectionException ex) { System.err.println("WARNING: Unable to set property '" + aProp.getName() + "' in step class '" + clazz + " - skipping"); } } } catch (Exception ex) { throw new WekaException(ex); } StepManagerImpl manager = new StepManagerImpl(theStep); flow.addStep(manager); // do coordinates last JSONNode coords = stepNode.getChild(COORDINATES); if (coords != null) { String[] vals = coords.getValue().toString().split(","); int x = Integer.parseInt(vals[0]); int y = Integer.parseInt(vals[1]); manager.m_x = x; manager.m_y = y; } } /** * Read step connections from the supplied JSON node * * @param step the {@code JSONNode} to read from * @param flow the flow being constructed * @throws WekaException if a problem occurs */ protected static void readConnectionsForStep(JSONNode step, Flow flow) throws WekaException { readConnectionsForStep(step, flow, false); } /** * Read step connections from the supplied JSON node * * @param step the {@code JSONNode} to read from * @param flow the flow being constructed * @param dontComplainAboutMissingConnections true if no exception should be * raised if the step named in a connection is not present in the * flow * @throws WekaException if a problem occurs */ protected static void readConnectionsForStep(JSONNode step, Flow flow, boolean dontComplainAboutMissingConnections) throws WekaException { JSONNode properties = step.getChild(PROPERTIES); String stepName = properties.getChild("name").getValue().toString(); StepManagerImpl manager = flow.findStep(stepName); JSONNode connections = step.getChild(CONNECTIONS); for (int i = 0; i < connections.getChildCount(); i++) { JSONNode conn = (JSONNode) connections.getChildAt(i); String conName = conn.getName(); if (!conn.isArray()) { throw new WekaException( "Was expecting an array of connected step names " + "for a the connection '" + conName + "'"); } for (int j = 0; j < conn.getChildCount(); j++) { JSONNode connectedStepName = (JSONNode) conn.getChildAt(j); StepManagerImpl targetManager = flow.findStep(connectedStepName.getValue().toString()); if (targetManager == null && !dontComplainAboutMissingConnections) { throw new WekaException("Could not find the target step '" + connectedStepName.getValue().toString() + "' for connection " + "'" + connectedStepName.getValue().toString()); } if (targetManager != null) { manager.addOutgoingConnection(conName, targetManager, true); } } } } /** * Serializes the supplied flow to JSON and writes out using the supplied * writer * * @param flow the {@code Flow} to serialize * @param writer the {@code Writer} to write to * @throws WekaException if a problem occurs */ public static void writeFlow(Flow flow, Writer writer) throws WekaException { try { String flowJSON = flowToJSON(flow); writer.write(flowJSON); } catch (IOException ex) { throw new WekaException(ex); } finally { try { writer.flush(); writer.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * Serializes the supplied flow to JSON and writes out using the supplied * output stream * * @param flow the {@code Flow} to serialize * @param os the {@code OutputStream} to write to * @throws WekaException if a problem occurs */ public static void writeFlow(Flow flow, OutputStream os) throws WekaException { OutputStreamWriter osw = new OutputStreamWriter(os); writeFlow(flow, osw); } /** * Serializes the supplied flow to JSON and writes it out to the supplied file * * @param flow the {@code Flow} to serialize * @param file the {@code File} to write to * @throws WekaException if a problem occurs */ public static void writeFlow(Flow flow, File file) throws WekaException { try { Writer w = new BufferedWriter(new FileWriter(file)); writeFlow(flow, w); } catch (IOException ex) { throw new WekaException(ex); } } /** * Read a flow from the supplied file * * @param file the file to read from * @return the deserialized {@code Flow} * @throws WekaException if a problem occurs */ public static Flow readFlow(File file) throws WekaException { return readFlow(file, false); } /** * Read a flow from the supplied file * * @param file the file to read from * @param dontComplainAboutMissingConnections true if no exceptions should be * raised if connections are missing in the flow * @return the deserialized Flow * @throws WekaException if a problem occurs */ public static Flow readFlow(File file, boolean dontComplainAboutMissingConnections) throws WekaException { try { Reader r = new BufferedReader(new FileReader(file)); return readFlow(r, dontComplainAboutMissingConnections); } catch (FileNotFoundException e) { throw new WekaException(e); } } /** * Read a Flow from the supplied input stream * * @param is the {@code InputStream} to read from * @return the deserialized flow * @throws WekaException if a problem occurs */ public static Flow readFlow(InputStream is) throws WekaException { return readFlow(is, false); } /** * Read a Flow from the supplied input stream * * @param is the {@code InputStream} to read from * @param dontComplainAboutMissingConnections true if no exception should be * raised if there are missing connections * @return the deserialized flow * @throws WekaException if a problem occurs */ public static Flow readFlow(InputStream is, boolean dontComplainAboutMissingConnections) throws WekaException { InputStreamReader isr = new InputStreamReader(is); return readFlow(isr, dontComplainAboutMissingConnections); } /** * Read a flow from the supplied reader * * @param sr the reader to read from * @return the deserialized flow * @throws WekaException if a problem occurs */ public static Flow readFlow(Reader sr) throws WekaException { return readFlow(sr, false); } /** * Read a flow from the supplied reader * * @param sr the reader to read from * @param dontComplainAboutMissingConnections true if no exception should be * raised if there are missing connections * @return the deserialized flow * @throws WekaException if a problem occurs */ public static Flow readFlow(Reader sr, boolean dontComplainAboutMissingConnections) throws WekaException { Flow flow = new Flow(); try { JSONNode root = JSONNode.read(sr); flow.setFlowName(root.getChild(FLOW_NAME).getValue().toString()); JSONNode stepsArray = root.getChild(STEPS); if (stepsArray == null) { throw new WekaException("Flow JSON does not contain a steps array!"); } for (int i = 0; i < stepsArray.getChildCount(); i++) { JSONNode aStep = (JSONNode) stepsArray.getChildAt(i); readStep(aStep, flow); } // now fill in the connections for (int i = 0; i < stepsArray.getChildCount(); i++) { JSONNode aStep = (JSONNode) stepsArray.getChildAt(i); readConnectionsForStep(aStep, flow, dontComplainAboutMissingConnections); } } catch (Exception ex) { throw new WekaException(ex); } finally { try { sr.close(); } catch (IOException e) { e.printStackTrace(); } } return flow; } /** * Utility routine to deserialize a flow from the supplied JSON string * * @param flowJSON the string containing a flow in JSON form * @param dontComplainAboutMissingConnections to not raise any exceptions if * there are missing connections in the flow * @return the deserialized flow * @throws WekaException if a problem occurs */ public static Flow JSONToFlow(String flowJSON, boolean dontComplainAboutMissingConnections) throws WekaException { StringReader sr = new StringReader(flowJSON); return readFlow(sr, dontComplainAboutMissingConnections); } /** * Utility routine to serialize a supplied flow to a JSON string * * @param flow the flow to serialize * @return a string containing the flow in JSON form * @throws WekaException if a problem occurs */ public static String flowToJSON(Flow flow) throws WekaException { JSONNode flowRoot = new JSONNode(); flowRoot.addPrimitive(FLOW_NAME, flow.getFlowName()); JSONNode flowArray = flowRoot.addArray(STEPS); Iterator<StepManagerImpl> iter = flow.iterator(); if (iter.hasNext()) { while (iter.hasNext()) { StepManagerImpl next = iter.next(); addStepJSONtoFlowArray(flowArray, next); } } StringBuffer b = new StringBuffer(); flowRoot.toString(b); return b.toString(); } /** * Main method for testing this class * * @param args command line arguments */ public static void main(String[] args) { try { weka.knowledgeflow.steps.Loader step = new weka.knowledgeflow.steps.Loader(); weka.core.converters.ArffLoader arffL = new weka.core.converters.ArffLoader(); arffL.setFile(new java.io.File("${user.home}/datasets/UCI/iris.arff")); step.setLoader(arffL); StepManagerImpl manager = new StepManagerImpl(step); Flow flow = new Flow(); flow.addStep(manager); TrainingSetMaker step2 = new TrainingSetMaker(); StepManagerImpl trainManager = new StepManagerImpl(step2); flow.addStep(trainManager); manager.addOutgoingConnection(StepManager.CON_DATASET, trainManager); ClassAssigner step3 = new ClassAssigner(); StepManagerImpl assignerManager = new StepManagerImpl(step3); flow.addStep(assignerManager); trainManager.addOutgoingConnection(StepManager.CON_TRAININGSET, assignerManager); Saver step4 = new Saver(); weka.core.converters.CSVSaver arffS = new weka.core.converters.CSVSaver(); arffS.setDir("."); arffS.setFilePrefix(""); step4.setSaver(arffS); StepManagerImpl saverManager = new StepManagerImpl(step4); // saverManager.setManagedStep(step3); flow.addStep(saverManager); assignerManager.addOutgoingConnection(StepManager.CON_TRAININGSET, saverManager); // Dummy steo2 = new Dummy(); // StepManager manager2 = new StepManager(); // manager2.setManagedStep(steo2); // flow.addStep(manager2); // // manager.addOutgoingConnection(StepManager.CON_DATASET, // manager2); // String json = flowToJSON(flow); // System.out.println(json); // // Flow newFlow = JSONToFlow(json); // json = flowToJSON(newFlow); // System.out.println(json); FlowRunner fr = new FlowRunner(new Settings("weka", KFDefaults.APP_ID)); fr.setFlow(flow); fr.run(); } catch (Exception ex) { ex.printStackTrace(); } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/knowledgeflow/JobEnvironment.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * JobEnvironment.java * Copyright (C) 2016 University of Waikato, Hamilton, New Zealand * */ package weka.knowledgeflow; import weka.core.Environment; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * Extended Environment with support for storing results and property values to * be set at a later date on the base schemes of WekaAlgorithmWrapper steps. The * latter is useful in the case where variables are not supported for properties * in a base scheme. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class JobEnvironment extends Environment { /** Map of non-incremental result data */ protected Map<String, LinkedHashSet<Data>> m_resultData = new ConcurrentHashMap<>(); /** * Map of properties for various base schemes owned by scheme-specific * (WekaAlgorithmWrapper) steps. Outer map is keyed by step name, inner map by * property name */ protected Map<String, Map<String, String>> m_stepProperties = new ConcurrentHashMap<>(); /** * Constructor */ public JobEnvironment() { super(); } /** * Construct a JobEnvironment by copying the contents of a standard * Environment * * @param env the Environment to copy into this JobEnvironment */ public JobEnvironment(Environment env) { super(env); if (env instanceof JobEnvironment) { m_stepProperties.putAll(((JobEnvironment) env).m_stepProperties); } } /** * Add a non-incremental data object to the result * * @param data the data to add */ public void addToResult(Data data) { if (!data.isIncremental()) { LinkedHashSet<Data> dataList = m_resultData.get(data.getConnectionName()); if (dataList == null) { dataList = new LinkedHashSet<>(); m_resultData.put(data.getConnectionName(), dataList); } dataList.add(data); } } /** * Add all the results from the supplied map to this environment's results * * @param otherResults the results to add */ public void addAllResults(Map<String, LinkedHashSet<Data>> otherResults) { for (Map.Entry<String, LinkedHashSet<Data>> e : otherResults.entrySet()) { if (!m_resultData.containsKey(e.getKey())) { m_resultData.put(e.getKey(), e.getValue()); } else { LinkedHashSet<Data> toAddTo = m_resultData.get(e.getKey()); toAddTo.addAll(e.getValue()); } } } /** * Get a list of any result data objects of the supplied connection type * * @param connName the name of the connection to get result data objects for * @return a list of result data objects for the specified connection type, or * null if none exist */ public LinkedHashSet<Data> getResultDataOfType(String connName) { LinkedHashSet<Data> results = m_resultData.remove(connName); return results; } /** * Returns true if the results contain data of a particular connection type * * @param connName the name of the connection to check for data * @return true if the results contain data of the supplied connection type */ public boolean hasResultDataOfType(String connName) { return m_resultData.containsKey(connName); } /** * Get a map of all the result data objects * * @return a map of all result data */ public Map<String, LinkedHashSet<Data>> getResultData() { return m_resultData; } public void clearResultData() { m_resultData.clear(); } /** * Get the step properties for a named step * * @param stepName the name of the step to get properties for * @return a map of properties for the named step */ public Map<String, String> getStepProperties(String stepName) { return m_stepProperties.get(stepName); } /** * Clear all step properties */ public void clearStepProperties() { m_stepProperties.clear(); } /** * Add the supplied map of step properties. The map contains properties for * various base schemes owned by scheme-specific (WekaAlgorithmWrapper) steps. * Outer map is keyed by step name, inner map by property name. * * @param propsToAdd properties to add */ public void addToStepProperties(Map<String, Map<String, String>> propsToAdd) { m_stepProperties.putAll(propsToAdd); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/knowledgeflow/KFDefaults.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * KFDefaults * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.knowledgeflow; import weka.core.Defaults; import weka.core.Settings; import javax.swing.JPanel; import java.awt.Color; /** * Default settings for the Knowledge Flow * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) */ public class KFDefaults extends Defaults { public static final String APP_NAME = "Knowledge Flow"; public static final String APP_ID = "knowledgeflow"; public static final String MAIN_PERSPECTIVE_ID = "knowledgeflow.main"; // Main perspective settings public static final Settings.SettingKey MAX_UNDO_POINTS_KEY = new Settings.SettingKey(MAIN_PERSPECTIVE_ID + ".maxUndoPoints", "Maximum undo points", "Maximum number of states to keep in the undo" + "buffer"); public static final int MAX_UNDO_POINTS = 20; public static final Settings.SettingKey LAYOUT_COLOR_KEY = new Settings.SettingKey(MAIN_PERSPECTIVE_ID + ".layoutcolor", "Layout background color", ""); private static Color JP_COLOR = new JPanel().getBackground(); public static final Color LAYOUT_COLOR = new Color(JP_COLOR.getRGB()); public static final Settings.SettingKey SHOW_GRID_KEY = new Settings.SettingKey(MAIN_PERSPECTIVE_ID + ".showgrid", "Show grid", "The snap-to-grid grid"); public static final boolean SHOW_GRID = false; public static final Settings.SettingKey GRID_COLOR_KEY = new Settings.SettingKey(MAIN_PERSPECTIVE_ID + ".gridcolor", "Grid line color", "The snap-to-grid line color"); public static final Color GRID_COLOR = Color.LIGHT_GRAY; public static final Settings.SettingKey GRID_SPACING_KEY = new Settings.SettingKey(MAIN_PERSPECTIVE_ID + ".gridSpacing", "Grid spacing", "The spacing for snap-to-grid"); public static final int GRID_SPACING = 40; public static final int SCROLL_BAR_INCREMENT_LAYOUT = 20; public static final Settings.SettingKey LAYOUT_WIDTH_KEY = new Settings.SettingKey(MAIN_PERSPECTIVE_ID + ".layoutWidth", "Layout width", "The width (in pixels) of the flow layout"); public static final Settings.SettingKey LAYOUT_HEIGHT_KEY = new Settings.SettingKey(MAIN_PERSPECTIVE_ID + ".layoutHeight", "Layout height", "The height (in pixels) of the flow layout"); public static final int LAYOUT_WIDTH = 2560; public static final int LAYOUT_HEIGHT = 1440; public static final Settings.SettingKey STEP_LABEL_FONT_SIZE_KEY = new Settings.SettingKey(MAIN_PERSPECTIVE_ID + ".stepLabelFontSize", "Font size for step/connection labels", "The point size of the font used to render " + "the names of steps and connections on the layout"); public static final int STEP_LABEL_FONT_SIZE = 9; public static final Settings.SettingKey LOGGING_LEVEL_KEY = new Settings.SettingKey(MAIN_PERSPECTIVE_ID + ".loggingLevel", "Logging level", "The logging level to use"); public static final LoggingLevel LOGGING_LEVEL = LoggingLevel.BASIC; protected static final Settings.SettingKey LOG_MESSAGE_FONT_SIZE_KEY = new Settings.SettingKey(MAIN_PERSPECTIVE_ID + ".logMessageFontSize", "Size of font for log " + "messages", "Size of font for log messages (-1 = system default)"); protected static final int LOG_MESSAGE_FONT_SIZE = -1; // Global app settings public static final Settings.SettingKey SHOW_JTREE_TIP_TEXT_KEY = new Settings.SettingKey(APP_ID + ".showGlobalInfoTipText", "Show scheme tool tips in tree view", ""); public static final boolean SHOW_JTREE_GLOBAL_INFO_TIPS = true; public static final String LAF = "javax.swing.plaf.nimbus.NimbusLookAndFeel"; protected static final Settings.SettingKey[] DEFAULT_KEYS = { MAX_UNDO_POINTS_KEY, LAYOUT_COLOR_KEY, SHOW_GRID_KEY, GRID_COLOR_KEY, GRID_SPACING_KEY, LAYOUT_WIDTH_KEY, LAYOUT_HEIGHT_KEY, STEP_LABEL_FONT_SIZE_KEY, LOGGING_LEVEL_KEY, LOG_MESSAGE_FONT_SIZE_KEY }; protected static final Object[] DEFAULT_VALUES = { MAX_UNDO_POINTS, LAYOUT_COLOR, SHOW_GRID, GRID_COLOR, GRID_SPACING, LAYOUT_WIDTH, LAYOUT_HEIGHT, STEP_LABEL_FONT_SIZE, LOGGING_LEVEL, LOG_MESSAGE_FONT_SIZE }; public KFDefaults() { super(MAIN_PERSPECTIVE_ID); for (int i = 0; i < DEFAULT_KEYS.length; i++) { m_defaults.put(DEFAULT_KEYS[i], DEFAULT_VALUES[i]); } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/knowledgeflow/LegacyFlowLoader.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * LegacyFlowLoader.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.knowledgeflow; import weka.core.WekaException; import weka.core.WekaPackageClassLoaderManager; import weka.gui.Logger; import weka.gui.beans.BeanCommon; import weka.gui.beans.BeanConnection; import weka.gui.beans.BeanInstance; import weka.core.PluginManager; import weka.gui.beans.WekaWrapper; import weka.gui.beans.xml.XMLBeans; import weka.knowledgeflow.steps.ClassAssigner; import weka.knowledgeflow.steps.ClassValuePicker; import weka.knowledgeflow.steps.Classifier; import weka.knowledgeflow.steps.ClassifierPerformanceEvaluator; import weka.knowledgeflow.steps.CrossValidationFoldMaker; import weka.knowledgeflow.steps.DataVisualizer; import weka.knowledgeflow.steps.FlowByExpression; import weka.knowledgeflow.steps.ImageSaver; import weka.knowledgeflow.steps.IncrementalClassifierEvaluator; import weka.knowledgeflow.steps.Join; import weka.knowledgeflow.steps.ModelPerformanceChart; import weka.knowledgeflow.steps.Note; import weka.knowledgeflow.steps.PredictionAppender; import weka.knowledgeflow.steps.Saver; import weka.knowledgeflow.steps.SerializedModelSaver; import weka.knowledgeflow.steps.Sorter; import weka.knowledgeflow.steps.Step; import weka.knowledgeflow.steps.StripChart; import weka.knowledgeflow.steps.SubstringLabeler; import weka.knowledgeflow.steps.SubstringReplacer; import weka.knowledgeflow.steps.TextSaver; import weka.knowledgeflow.steps.TrainTestSplitMaker; import weka.knowledgeflow.steps.WekaAlgorithmWrapper; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.lang.reflect.Method; import java.util.Set; import java.util.Vector; /** * Flow loader that reads legacy .kfml files and translates them to the new * implementation. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class LegacyFlowLoader implements FlowLoader { /** File extension for the format handled by this flow loader */ public static final String EXTENSION = "kfml"; /** Path to the steps.props file */ protected static final String STEP_LIST_PROPS = "weka/knowledgeflow/steps/steps.props"; static { // Add the built-in steps to the plugin manager try { PluginManager.addFromProperties(LegacyFlowLoader.class.getClassLoader() .getResourceAsStream(STEP_LIST_PROPS), true); } catch (Exception e) { e.printStackTrace(); } } /** Legacy beans loaded */ protected Vector<Object> m_beans; /** Legacy bean connections loaded */ protected Vector<BeanConnection> m_connections; /** Log to use */ protected LogManager m_log; /** * Constructor */ public LegacyFlowLoader() { } /** * Set the log to use * * @param log log to use */ @Override public void setLog(Logger log) { m_log = new LogManager(log, false); } /** * Get the flow file extension of the file format handled by this flow loader * * @return the file extension */ @Override public String getFlowFileExtension() { return EXTENSION; } /** * Get the description of the file format handled by this flow loader * * @return the description of the file format */ @Override public String getFlowFileExtensionDescription() { return "Legacy XML-based Knowledge Flow configuration files"; } /** * Deserialize a legacy flow from the supplied file * * @param flowFile the file to load from * @return the legacy flow translated to a new {@code Flow} object * @throws WekaException if a problem occurs */ @Override public Flow readFlow(File flowFile) throws WekaException { try { loadLegacy(new BufferedReader(new FileReader(flowFile))); } catch (Exception ex) { throw new WekaException(ex); } String name = flowFile.getName(); name = name.substring(0, name.lastIndexOf('.')); return makeFlow(name); } /** * Deserialize a legacy flow from the supplied input stream * * @param is the input stream to load from * @return the legacy flow translated to a new {@code Flow} object * @throws WekaException if a problem occurs */ @Override public Flow readFlow(InputStream is) throws WekaException { loadLegacy(new InputStreamReader(is)); return makeFlow("Untitled"); } /** * Deserialize a legacy flow from the supplied reader * * @param r the reader to load from * @return the legacy flow translated to a new {@code Flow} object * @throws WekaException if a problem occurs */ @Override public Flow readFlow(Reader r) throws WekaException { loadLegacy(r); return makeFlow("Untitled"); } /** * Makes a new {@code Flow} by translating the legacy beans and connections to * the new Step implementations * * @param name the name to use for the flow * @return a {@code Flow} object * @throws WekaException if a problem occurs */ protected Flow makeFlow(String name) throws WekaException { Flow flow = new Flow(); flow.setFlowName(name != null ? name : "Untitled"); // process beans first for (Object o : m_beans) { BeanInstance bean = (BeanInstance) o; StepManagerImpl newManager = handleStep(bean); if (newManager != null) { flow.addStep(newManager); } } // now connections for (BeanConnection conn : m_connections) { handleConnection(flow, conn); } return flow; } /** * Handles a legacy {@BeanConnection} * * @param flow the new {@code Flow} to add the translated connection to * @param conn the legacy bean connection to process */ protected void handleConnection(Flow flow, BeanConnection conn) { BeanInstance source = conn.getSource(); BeanInstance target = conn.getTarget(); if (!(source.getBean() instanceof BeanCommon) && !(target.getBean() instanceof BeanCommon)) { return; } BeanCommon sourceC = (BeanCommon) source.getBean(); BeanCommon targetC = (BeanCommon) target.getBean(); StepManagerImpl sourceNew = flow.findStep(sourceC.getCustomName()); StepManagerImpl targetNew = flow.findStep(targetC.getCustomName()); if (sourceNew == null || targetNew == null) { if (m_log != null) { m_log .logWarning("Unable to make connection in new flow between legacy " + "steps " + sourceC.getCustomName() + " and " + targetC.getCustomName() + " for connection '" + conn.getEventName()); } return; } String evntName = conn.getEventName(); flow.connectSteps(sourceNew, targetNew, evntName, true); } /** * Handles a legacy {@BeanInstance} step component * * @param bean the bean instance to process * @return a configured {@code StepManagerImpl} that is the equivalent of the * legacy bean * @throws WekaException if a problem occurs */ protected StepManagerImpl handleStep(BeanInstance bean) throws WekaException { Object comp = bean.getBean(); String name = ""; if (comp instanceof BeanCommon) { BeanCommon beanCommon = (BeanCommon) comp; name = beanCommon.getCustomName(); } int x = bean.getX(); int y = bean.getY(); Step match = findStepMatch(comp.getClass().getCanonicalName()); if (match != null) { StepManagerImpl manager = new StepManagerImpl(match); manager.m_x = x; manager.m_y = y; // copy settings... if (!(comp instanceof WekaWrapper)) { copySettingsNonWrapper(comp, match); } else { copySettingsWrapper((WekaWrapper) comp, (WekaAlgorithmWrapper) match); } if (!(match instanceof Note)) { match.setName(name); } return manager; } else { if (m_log != null) { m_log.logWarning("Unable to find an equivalent for legacy step: " + comp.getClass().getCanonicalName()); } } return null; } /** * Copy settings from a legacy {@code WekaWrapper} bean to the new * {@code WekaAlgorithmWrapper} equivalent * * @param legacy the legacy wrapper * @param current the new step equivalent * @throws WekaException if a problem occurs */ protected void copySettingsWrapper(WekaWrapper legacy, WekaAlgorithmWrapper current) throws WekaException { Object wrappedAlgo = legacy.getWrappedAlgorithm(); current.setWrappedAlgorithm(wrappedAlgo); if (legacy instanceof weka.gui.beans.Classifier && current instanceof Classifier) { ((Classifier) current).setLoadClassifierFileName(new File( ((weka.gui.beans.Classifier) legacy).getLoadClassifierFileName())); ((Classifier) current) .setUpdateIncrementalClassifier(((weka.gui.beans.Classifier) legacy) .getUpdateIncrementalClassifier()); ((Classifier) current) .setResetIncrementalClassifier(((weka.gui.beans.Classifier) legacy) .getResetIncrementalClassifier()); } else if (legacy instanceof weka.gui.beans.Saver && current instanceof Saver) { (((Saver) current)) .setRelationNameForFilename((((weka.gui.beans.Saver) legacy) .getRelationNameForFilename())); } } /** * Copy the settings from a legacy non-algorithm wrapper bean to the new step * equivalent * * @param legacy the legacy bean to copy settings from * @param current the new {@code Step} to copy to * @throws WekaException if a problem occurs */ protected void copySettingsNonWrapper(Object legacy, Step current) throws WekaException { if (current instanceof Note && legacy instanceof weka.gui.beans.Note) { ((Note) current) .setNoteText(((weka.gui.beans.Note) legacy).getNoteText()); } else if (current instanceof TrainTestSplitMaker && legacy instanceof weka.gui.beans.TrainTestSplitMaker) { ((TrainTestSplitMaker) current).setSeed("" + ((weka.gui.beans.TrainTestSplitMaker) legacy).getSeed()); ((TrainTestSplitMaker) current).setTrainPercent("" + ((weka.gui.beans.TrainTestSplitMaker) legacy).getTrainPercent()); } else if (current instanceof CrossValidationFoldMaker && legacy instanceof weka.gui.beans.CrossValidationFoldMaker) { ((CrossValidationFoldMaker) current).setSeed("" + ((weka.gui.beans.CrossValidationFoldMaker) legacy).getSeed()); ((CrossValidationFoldMaker) current).setNumFolds("" + ((weka.gui.beans.CrossValidationFoldMaker) legacy).getFolds()); ((CrossValidationFoldMaker) current) .setPreserveOrder(((weka.gui.beans.CrossValidationFoldMaker) legacy) .getPreserveOrder()); } else if (current instanceof ClassAssigner && legacy instanceof weka.gui.beans.ClassAssigner) { ((ClassAssigner) current) .setClassColumn(((weka.gui.beans.ClassAssigner) legacy) .getClassColumn()); } else if (current instanceof ClassValuePicker && legacy instanceof weka.gui.beans.ClassValuePicker) { ((ClassValuePicker) current) .setClassValue(((weka.gui.beans.ClassValuePicker) legacy) .getClassValue()); } else if (current instanceof ClassifierPerformanceEvaluator && legacy instanceof weka.gui.beans.ClassifierPerformanceEvaluator) { ((ClassifierPerformanceEvaluator) current) .setEvaluationMetricsToOutput(((weka.gui.beans.ClassifierPerformanceEvaluator) legacy) .getEvaluationMetricsToOutput()); ((ClassifierPerformanceEvaluator) current) .setErrorPlotPointSizeProportionalToMargin(((weka.gui.beans.ClassifierPerformanceEvaluator) legacy) .getErrorPlotPointSizeProportionalToMargin()); } else if (current instanceof IncrementalClassifierEvaluator && legacy instanceof weka.gui.beans.IncrementalClassifierEvaluator) { ((IncrementalClassifierEvaluator) current) .setChartingEvalWindowSize(((weka.gui.beans.IncrementalClassifierEvaluator) legacy) .getChartingEvalWindowSize()); ((IncrementalClassifierEvaluator) current) .setOutputPerClassInfoRetrievalStats(((weka.gui.beans.IncrementalClassifierEvaluator) legacy) .getOutputPerClassInfoRetrievalStats()); ((IncrementalClassifierEvaluator) current) .setStatusFrequency(((weka.gui.beans.IncrementalClassifierEvaluator) legacy) .getStatusFrequency()); } else if (current instanceof PredictionAppender && legacy instanceof weka.gui.beans.PredictionAppender) { ((PredictionAppender) current) .setAppendProbabilities(((weka.gui.beans.PredictionAppender) legacy) .getAppendPredictedProbabilities()); } else if (current instanceof SerializedModelSaver && legacy instanceof weka.gui.beans.SerializedModelSaver) { ((SerializedModelSaver) current) .setFilenamePrefix(((weka.gui.beans.SerializedModelSaver) legacy) .getPrefix()); ((SerializedModelSaver) current) .setIncludeRelationNameInFilename(((weka.gui.beans.SerializedModelSaver) legacy) .getIncludeRelationName()); ((SerializedModelSaver) current) .setOutputDirectory(((weka.gui.beans.SerializedModelSaver) legacy) .getDirectory()); ((SerializedModelSaver) current) .setIncrementalSaveSchedule(((weka.gui.beans.SerializedModelSaver) legacy) .getIncrementalSaveSchedule()); } else if (current instanceof ImageSaver && legacy instanceof weka.gui.beans.ImageSaver) { ((ImageSaver) current).setFile(new File( ((weka.gui.beans.ImageSaver) legacy).getFilename())); } else if (current instanceof TextSaver && legacy instanceof weka.gui.beans.TextSaver) { ((TextSaver) current).setFile(new File( ((weka.gui.beans.TextSaver) legacy).getFilename())); ((TextSaver) current).setAppend(((weka.gui.beans.TextSaver) legacy) .getAppend()); } else if (current instanceof StripChart && legacy instanceof weka.gui.beans.StripChart) { ((StripChart) current) .setRefreshFreq(((weka.gui.beans.StripChart) legacy).getRefreshFreq()); ((StripChart) current) .setRefreshWidth(((weka.gui.beans.StripChart) legacy).getRefreshWidth()); ((StripChart) current).setXLabelFreq(((weka.gui.beans.StripChart) legacy) .getXLabelFreq()); } else if (current instanceof ModelPerformanceChart && legacy instanceof weka.gui.beans.ModelPerformanceChart) { ((ModelPerformanceChart) current) .setOffscreenAdditionalOpts(((weka.gui.beans.ModelPerformanceChart) legacy) .getOffscreenAdditionalOpts()); ((ModelPerformanceChart) current) .setOffscreenRendererName(((weka.gui.beans.ModelPerformanceChart) legacy) .getOffscreenRendererName()); ((ModelPerformanceChart) current) .setOffscreenHeight(((weka.gui.beans.ModelPerformanceChart) legacy) .getOffscreenHeight()); ((ModelPerformanceChart) current) .setOffscreenWidth(((weka.gui.beans.ModelPerformanceChart) legacy) .getOffscreenWidth()); ((ModelPerformanceChart) current) .setOffscreenXAxis(((weka.gui.beans.ModelPerformanceChart) legacy) .getOffscreenXAxis()); ((ModelPerformanceChart) current) .setOffscreenYAxis(((weka.gui.beans.ModelPerformanceChart) legacy) .getOffscreenYAxis()); } else if (current instanceof DataVisualizer && legacy instanceof weka.gui.beans.DataVisualizer) { ((DataVisualizer) current) .setOffscreenHeight(((weka.gui.beans.DataVisualizer) legacy) .getOffscreenHeight()); ((DataVisualizer) current) .setOffscreenWidth(((weka.gui.beans.DataVisualizer) legacy) .getOffscreenWidth()); ((DataVisualizer) current) .setOffscreenXAxis(((weka.gui.beans.DataVisualizer) legacy) .getOffscreenXAxis()); ((DataVisualizer) current) .setOffscreenRendererName(((weka.gui.beans.DataVisualizer) legacy) .getOffscreenRendererName()); ((DataVisualizer) current) .setOffscreenAdditionalOpts(((weka.gui.beans.DataVisualizer) legacy) .getOffscreenAdditionalOpts()); } else if (current instanceof FlowByExpression && legacy instanceof weka.gui.beans.FlowByExpression) { ((FlowByExpression) current) .setExpressionString(((weka.gui.beans.FlowByExpression) legacy) .getExpressionString()); ((FlowByExpression) current) .setTrueStepName(((weka.gui.beans.FlowByExpression) legacy) .getTrueStepName()); ((FlowByExpression) current) .setFalseStepName(((weka.gui.beans.FlowByExpression) legacy) .getFalseStepName()); } else if (current instanceof Join && legacy instanceof weka.gui.beans.Join) { ((Join) current).setKeySpec(((weka.gui.beans.Join) legacy).getKeySpec()); } else if (current instanceof Sorter && legacy instanceof weka.gui.beans.Sorter) { ((Sorter) current).setSortDetails(((weka.gui.beans.Sorter) legacy) .getSortDetails()); ((Sorter) current).setBufferSize(((weka.gui.beans.Sorter) legacy) .getBufferSize()); ((Sorter) current).setTempDirectory(new File( ((weka.gui.beans.Sorter) legacy).getTempDirectory())); } else if (current instanceof SubstringReplacer && legacy instanceof weka.gui.beans.SubstringReplacer) { ((SubstringReplacer) current) .setMatchReplaceDetails(((weka.gui.beans.SubstringReplacer) legacy) .getMatchReplaceDetails()); } else if (current instanceof SubstringLabeler && legacy instanceof weka.gui.beans.SubstringLabeler) { ((SubstringLabeler) current) .setMatchDetails(((weka.gui.beans.SubstringLabeler) legacy) .getMatchDetails()); ((SubstringLabeler) current) .setConsumeNonMatching(((weka.gui.beans.SubstringLabeler) legacy) .getConsumeNonMatching()); ((SubstringLabeler) current) .setMatchAttributeName(((weka.gui.beans.SubstringLabeler) legacy) .getMatchAttributeName()); ((SubstringLabeler) current) .setNominalBinary(((weka.gui.beans.SubstringLabeler) legacy) .getNominalBinary()); } else { // configure plugin steps configurePluginStep(legacy, current); } } /** * Transfer a single setting * * @param legacy the legacy bean to transfer from * @param current the new step to transfer to * @param propName the property name of the setting * @param propType the type of the setting * @throws WekaException if a problem occurs */ protected void transferSetting(Object legacy, Step current, String propName, Class propType) throws WekaException { try { Method getM = legacy.getClass().getMethod("get" + propName, new Class[] {}); Object value = getM.invoke(legacy, new Object[] {}); Method setM = current.getClass() .getMethod("set" + propName, new Class[] { propType }); setM.invoke(current, new Object[] { value }); } catch (Exception ex) { throw new WekaException(ex); } } /** * Handles configuration of settings in the case of plugin steps * * @param legacy the legacy bean to copy settings from * @param current the plugin step to copy to * @throws WekaException if a problem occurs */ protected void configurePluginStep(Object legacy, Step current) throws WekaException { if (legacy.getClass().toString().endsWith("PythonScriptExecutor") && current.getClass().toString().endsWith("PythonScriptExecutor")) { try { transferSetting(legacy, current, "Debug", Boolean.TYPE); transferSetting(legacy, current, "PythonScript", String.class); Method getM = legacy.getClass().getDeclaredMethod("getScriptFile", new Class[] {}); Object value = getM.invoke(legacy, new Object[] {}); Method setM = current.getClass().getDeclaredMethod("setScriptFile", new Class[] { File.class }); setM.invoke(current, new Object[] { new File(value.toString()) }); transferSetting(legacy, current, "VariablesToGetFromPython", String.class); } catch (Exception ex) { throw new WekaException(ex); } } else if (legacy.getClass().toString().endsWith("RScriptExecutor") && current.getClass().toString().endsWith("RScriptExecutor")) { try { transferSetting(legacy, current, "RScript", String.class); Method getM = legacy.getClass().getDeclaredMethod("getScriptFile", new Class[] {}); Object value = getM.invoke(legacy, new Object[] {}); Method setM = current.getClass().getDeclaredMethod("setScriptFile", new Class[] { File.class }); setM.invoke(current, new Object[] { new File(value.toString()) }); } catch (Exception ex) { throw new WekaException(ex); } } else if (legacy.getClass().toString().endsWith("JsonFieldExtractor") && current.getClass().toString().endsWith("JsonFieldExtractor")) { try { transferSetting(legacy, current, "PathDetails", String.class); } catch (Exception ex) { throw new WekaException(ex); } } else if (legacy.getClass().toString().endsWith("TimeSeriesForecasting") && current.getClass().toString().endsWith("TimeSeriesForecasting")) { try { transferSetting(legacy, current, "EncodedForecaster", String.class); transferSetting(legacy, current, "NumStepsToForecast", String.class); transferSetting(legacy, current, "ArtificialTimeStartOffset", String.class); transferSetting(legacy, current, "RebuildForecaster", Boolean.TYPE); Method getM = legacy.getClass().getDeclaredMethod("getFilename", new Class[] {}); Object value = getM.invoke(legacy, new Object[] {}); Method setM = current.getClass().getDeclaredMethod("setFilename", new Class[] { File.class }); setM.invoke(current, new Object[] { new File(value.toString()) }); getM = legacy.getClass() .getDeclaredMethod("getSaveFilename", new Class[] {}); value = getM.invoke(legacy, new Object[] {}); setM = current.getClass().getDeclaredMethod("setSaveFilename", new Class[] { File.class }); setM.invoke(current, new Object[] { new File(value.toString()) }); } catch (Exception ex) { throw new WekaException(ex); } } else if (legacy.getClass().toString().endsWith("GroovyComponent") && current.getClass().toString().endsWith("GroovyStep")) { transferSetting(legacy, current, "Script", String.class); } else if (legacy.getClass().getSuperclass().toString() .endsWith("AbstractSparkJob") && current.getClass().getSuperclass().toString() .endsWith("AbstractSparkJob")) { transferSetting(legacy, current, "JobOptions", String.class); } else if (legacy.getClass().getSuperclass().toString() .endsWith("AbstractHadoopJob")) { transferSetting(legacy, current, "JobOptions", String.class); } } /** * Attempts to find a matching {@code Step} implementation for a supplied * legacy class name * * @param legacyFullyQualified the fully qualified class name of the legacy * bean to find a match for * @return an instantiated {@code Step} that is equivalent to the legacy one * @throws WekaException if a match can't be found */ protected Step findStepMatch(String legacyFullyQualified) throws WekaException { String clazzNameOnly = legacyFullyQualified.substring(legacyFullyQualified.lastIndexOf('.') + 1, legacyFullyQualified.length()); // Note is a special case if (clazzNameOnly.equals("Note")) { return new Note(); } Set<String> steps = PluginManager.getPluginNamesOfType(weka.knowledgeflow.steps.Step.class .getCanonicalName()); Step result = null; if (steps != null) { for (String s : steps) { String sClazzNameOnly = s.substring(s.lastIndexOf(".") + 1); if (sClazzNameOnly.equals(clazzNameOnly)) { try { result = (Step) PluginManager.getPluginInstance( weka.knowledgeflow.steps.Step.class.getCanonicalName(), s); break; } catch (Exception ex) { throw new WekaException(ex); } } } } if (result == null) { // one more last-ditch attempt String lastDitch = "weka.knowledgeflow.steps." + clazzNameOnly; try { result = (Step) WekaPackageClassLoaderManager.objectForName(lastDitch); } catch (Exception e) { // } } return result; } /** * Load the legacy flow using the supplied reader * * @param r the reader to load from * @throws WekaException if a problem occurs */ @SuppressWarnings("unchecked") protected void loadLegacy(Reader r) throws WekaException { BeanConnection.init(); BeanInstance.init(); try { XMLBeans xml = new XMLBeans(null, null, 0); Vector<?> v = (Vector<?>) xml.read(r); m_beans = (Vector<Object>) v.get(XMLBeans.INDEX_BEANINSTANCES); m_connections = (Vector<BeanConnection>) v.get(XMLBeans.INDEX_BEANCONNECTIONS); } catch (Exception ex) { throw new WekaException(ex); } /* * m_beans = new Vector<Object>(); m_connections = new * Vector<BeanConnection>(); */ } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/knowledgeflow/LogManager.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * LogHandler.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.knowledgeflow; import weka.core.LogHandler; import weka.core.OptionHandler; import weka.core.Utils; import weka.gui.Logger; import weka.knowledgeflow.steps.Step; import weka.knowledgeflow.steps.WekaAlgorithmWrapper; import java.io.PrintWriter; import java.io.StringWriter; /** * Class that wraps a {@code weka.gui.Logger} and filters log messages according * to the set logging level. Note that warnings and errors reported via the * logWarning() and logError() methods will always be output regardless of the * logging level set. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class LogManager implements LogHandler { /** Prefix to use for status messages */ protected String m_statusMessagePrefix = ""; /** The log to use */ protected Logger m_log; /** True if status messages should be output as well as log messages */ protected boolean m_status; /** * The level at which to report messages to the log. Messages at this level or * higher will be reported to the log/status. Note that warnings and errors * and errors reported via the logWarning() and logError() methods will always * be output, regardless of the logging level set */ protected LoggingLevel m_levelToLogAt = LoggingLevel.BASIC; /** * Constructor that takes a {@code Step}. Uses the log from the step * * @param source the source {@code Step} */ public LogManager(Step source) { m_status = true; String prefix = (source != null ? source.getName() : "Unknown") + "$"; prefix += (source != null ? source.hashCode() : 1) + "|"; if (source instanceof WekaAlgorithmWrapper) { Object wrappedAlgo = ((WekaAlgorithmWrapper) source).getWrappedAlgorithm(); if (wrappedAlgo instanceof OptionHandler) { prefix += Utils.joinOptions(((OptionHandler) wrappedAlgo).getOptions()) + "|"; } } m_statusMessagePrefix = prefix; if (source != null) { m_log = ((StepManagerImpl) source.getStepManager()).getLog(); setLoggingLevel(((StepManagerImpl) source.getStepManager()) .getLoggingLevel()); } } /** * Constructor that takes a log * * @param log the log to wrap */ public LogManager(Logger log) { this(log, true); } /** * Constructor that takes a log * * @param log the log to wrap * @param status true if warning and error messages should be output to the * status area as well as to the log */ public LogManager(Logger log, boolean status) { m_log = log; m_status = status; } /** * Utility method to convert a stack trace to a String * * @param throwable the {@code Throwable} to convert to a stack trace string * @return the string containing the stack trace */ public static String stackTraceToString(Throwable throwable) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); throwable.printStackTrace(pw); return sw.toString(); } /** * Set the log wrap * * @param log the log to wrap */ public void setLog(Logger log) { m_log = log; } /** * Get the wrapped log * * @return the wrapped log */ public Logger getLog() { return m_log; } /** * Get the logging level in use * * @return */ public LoggingLevel getLoggingLevel() { return m_levelToLogAt; } /** * Set the logging level to use * * @param level the level to use */ public void setLoggingLevel(LoggingLevel level) { m_levelToLogAt = level; } /** * Log at the low level * * @param message the message to log */ public void logLow(String message) { log(message, LoggingLevel.LOW); } /** * Log at the basic level * * @param message the message to log */ public void logBasic(String message) { log(message, LoggingLevel.BASIC); } /** * Log at the detailed level * * @param message the message to log */ public void logDetailed(String message) { log(message, LoggingLevel.DETAILED); } /** * Log at the debugging level * * @param message the message to log */ public void logDebug(String message) { log(message, LoggingLevel.DEBUGGING); } /** * Log a warning * * @param message the message to log */ public void logWarning(String message) { log(message, LoggingLevel.WARNING); if (m_status) { statusMessage("WARNING: " + message); } } /** * Log an error * * @param message the message to log * @param cause the cause of the error */ public void logError(String message, Exception cause) { log(message, LoggingLevel.ERROR, cause); if (m_status) { statusMessage("ERROR: " + message); } } /** * Output a status message * * @param message the status message */ public void statusMessage(String message) { if (m_log != null) { m_log.statusMessage(statusMessagePrefix() + message); } } /** * Log a message at the supplied level * * @param message the message to log * @param messageLevel the level to log at */ public void log(String message, LoggingLevel messageLevel) { log(message, messageLevel, null); } /** * Log a message at the supplied level * * @param message the message to log * @param messageLevel the level to log at * @param cause an optional exception for error level messages */ protected void log(String message, LoggingLevel messageLevel, Throwable cause) { if (messageLevel == LoggingLevel.WARNING || messageLevel == LoggingLevel.ERROR || messageLevel.ordinal() <= m_levelToLogAt.ordinal()) { String logMessage = "[" + messageLevel.toString() + "] " + statusMessagePrefix() + message; if (cause != null) { logMessage += "\n" + stackTraceToString(cause); } if (m_log != null) { m_log.logMessage(logMessage); if (messageLevel == LoggingLevel.ERROR || messageLevel == LoggingLevel.WARNING) { statusMessage(messageLevel.toString() + " (see log for details)"); } } else { System.err.println(logMessage); } } } private String statusMessagePrefix() { return m_statusMessagePrefix; } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/knowledgeflow/LoggingLevel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * LoggingLevel.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.knowledgeflow; /** * Enum for different logging levels * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public enum LoggingLevel { NONE("None"), LOW("Low"), BASIC("Basic"), DETAILED("Detailed"), DEBUGGING( "Debugging"), WARNING("WARNING"), ERROR("ERROR"); /** The name of this logging level */ private final String m_name; /** * Constructor * * @param name the name of this logging level */ LoggingLevel(String name) { m_name = name; } /** * Return LoggingLevel given its name as a string * * @param s the string containing the name of the logging level * @return the LoggingLevel (or LoggingLevel.BASIC if the string could * not be matched) */ public static LoggingLevel stringToLevel(String s) { LoggingLevel ret = LoggingLevel.BASIC; for (LoggingLevel l : LoggingLevel.values()) { if (l.toString().equals(s)) { ret = l; } } return ret; } /** * String representation * * @return the string representation of this logging level */ @Override public String toString() { return m_name; } }