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/explorer/ClassifierPanel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ClassifierPanel.java * Copyright (C) 1999-2013 University of Waikato, Hamilton, New Zealand * */ package weka.gui.explorer; import weka.classifiers.AbstractClassifier; import weka.classifiers.Classifier; import weka.classifiers.CostMatrix; import weka.classifiers.Evaluation; import weka.classifiers.Sourcable; import weka.classifiers.evaluation.CostCurve; import weka.classifiers.evaluation.MarginCurve; import weka.classifiers.evaluation.Prediction; import weka.classifiers.evaluation.ThresholdCurve; import weka.classifiers.evaluation.output.prediction.AbstractOutput; import weka.classifiers.evaluation.output.prediction.Null; import weka.classifiers.pmml.consumer.PMMLClassifier; import weka.classifiers.rules.ZeroR; import weka.core.Attribute; import weka.core.BatchPredictor; import weka.core.Capabilities; import weka.core.CapabilitiesHandler; import weka.core.Defaults; import weka.core.Drawable; import weka.core.Environment; import weka.core.Instance; import weka.core.Instances; import weka.core.OptionHandler; import weka.core.PluginManager; import weka.core.Range; import weka.core.SerializationHelper; import weka.core.SerializedObject; import weka.core.Settings; import weka.core.Utils; import weka.core.Version; import weka.core.WekaPackageClassLoaderManager; import weka.core.converters.ArffLoader; import weka.core.converters.ConverterUtils.DataSource; import weka.core.converters.IncrementalConverter; import weka.core.converters.Loader; import weka.core.pmml.PMMLFactory; import weka.core.pmml.PMMLModel; import weka.gui.AbstractPerspective; import weka.gui.CostMatrixEditor; import weka.gui.EvaluationMetricSelectionDialog; import weka.gui.ExtensionFileFilter; import weka.gui.GenericObjectEditor; import weka.gui.Logger; import weka.gui.Perspective; import weka.gui.PerspectiveInfo; import weka.gui.PropertyDialog; import weka.gui.PropertyPanel; import weka.gui.ResultHistoryPanel; import weka.gui.SaveBuffer; import weka.gui.SetInstancesPanel; import weka.gui.SysErrLog; import weka.gui.TaskLogger; import weka.gui.beans.CostBenefitAnalysis; import weka.gui.explorer.Explorer.CapabilitiesFilterChangeEvent; import weka.gui.explorer.Explorer.CapabilitiesFilterChangeListener; import weka.gui.explorer.Explorer.ExplorerPanel; import weka.gui.explorer.Explorer.LogHandler; import weka.gui.graphvisualizer.BIFFormatException; import weka.gui.graphvisualizer.GraphVisualizer; import weka.gui.treevisualizer.PlaceNode2; import weka.gui.treevisualizer.TreeVisualizer; import weka.gui.visualize.PlotData2D; import weka.gui.visualize.ThresholdVisualizePanel; import weka.gui.visualize.VisualizePanel; import weka.gui.visualize.plugins.ErrorVisualizePlugin; import weka.gui.visualize.plugins.GraphVisualizePlugin; import weka.gui.visualize.plugins.TreeVisualizePlugin; import weka.gui.visualize.plugins.VisualizePlugin; import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.filechooser.FileFilter; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.GridLayout; import java.awt.Insets; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.InputEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Random; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; /** * This panel allows the user to select and configure a classifier, set the * attribute of the current dataset to be used as the class, and evaluate the * classifier using a number of testing modes (test on the training data, * train/test on a percentage split, n-fold cross-validation, test on a separate * split). The results of classification runs are stored in a result history so * that previous results are accessible. * * @author Len Trigg (trigg@cs.waikato.ac.nz) * @author Mark Hall (mhall@cs.waikato.ac.nz) * @author Richard Kirkby (rkirkby@cs.waikato.ac.nz) * @version $Revision$ */ @PerspectiveInfo(ID = "weka.gui.explorer.classifierpanel", title = "Classify", toolTipText = "Classify instances", iconPath = "weka/gui/weka_icon_new_small.png") public class ClassifierPanel extends AbstractPerspective implements CapabilitiesFilterChangeListener, ExplorerPanel, LogHandler { /** for serialization. */ static final long serialVersionUID = 6959973704963624003L; /** the parent frame. */ protected Explorer m_Explorer = null; /** The filename extension that should be used for model files. */ public static String MODEL_FILE_EXTENSION = ".model"; /** The filename extension that should be used for PMML xml files. */ public static String PMML_FILE_EXTENSION = ".xml"; /** Lets the user configure the classifier. */ protected GenericObjectEditor m_ClassifierEditor = new GenericObjectEditor(); /** The panel showing the current classifier selection. */ protected PropertyPanel m_CEPanel = new PropertyPanel(m_ClassifierEditor); /** The output area for classification results. */ protected JTextArea m_OutText = new JTextArea(20, 40); /** The destination for log/status messages. */ protected Logger m_Log = new SysErrLog(); /** The buffer saving object for saving output. */ SaveBuffer m_SaveOut = new SaveBuffer(m_Log, this); /** A panel controlling results viewing. */ protected ResultHistoryPanel m_History = new ResultHistoryPanel(m_OutText); /** Lets the user select the class column. */ protected JComboBox m_ClassCombo = new JComboBox(); /** Click to set test mode to cross-validation. */ protected JRadioButton m_CVBut = new JRadioButton("Cross-validation"); /** Click to set test mode to generate a % split. */ protected JRadioButton m_PercentBut = new JRadioButton("Percentage split"); /** Click to set test mode to test on training data. */ protected JRadioButton m_TrainBut = new JRadioButton("Use training set"); /** Click to set test mode to a user-specified test set. */ protected JRadioButton m_TestSplitBut = new JRadioButton("Supplied test set"); /** * Check to save the predictions in the results list for visualizing later on. */ protected JCheckBox m_StorePredictionsBut = new JCheckBox( "Store predictions for visualization"); /** * Check to have the point size in error plots proportional to the prediction * margin (classification only) */ protected JCheckBox m_errorPlotPointSizeProportionalToMargin = new JCheckBox( "Error plot point size proportional to margin"); /** Check to output the model built from the training data. */ protected JCheckBox m_OutputModelBut = new JCheckBox("Output model"); /** Check to output the models built from the training splits. */ protected JCheckBox m_OutputModelsForTrainingSplitsBut = new JCheckBox("Output models for training splits"); /** Check to output true/false positives, precision/recall for each class. */ protected JCheckBox m_OutputPerClassBut = new JCheckBox( "Output per-class stats"); /** Check to output a confusion matrix. */ protected JCheckBox m_OutputConfusionBut = new JCheckBox( "Output confusion matrix"); /** Check to output entropy statistics. */ protected JCheckBox m_OutputEntropyBut = new JCheckBox( "Output entropy evaluation measures"); /** Lets the user configure the ClassificationOutput. */ protected GenericObjectEditor m_ClassificationOutputEditor = new GenericObjectEditor(true); /** ClassificationOutput configuration. */ protected PropertyPanel m_ClassificationOutputPanel = new PropertyPanel( m_ClassificationOutputEditor); /** the range of attributes to output. */ protected Range m_OutputAdditionalAttributesRange = null; /** Check to evaluate w.r.t a cost matrix. */ protected JCheckBox m_EvalWRTCostsBut = new JCheckBox( "Cost-sensitive evaluation"); /** for the cost matrix. */ protected JButton m_SetCostsBut = new JButton("Set..."); /** Label by where the cv folds are entered. */ protected JLabel m_CVLab = new JLabel("Folds", SwingConstants.RIGHT); /** The field where the cv folds are entered. */ protected JTextField m_CVText = new JTextField("10", 3); /** Label by where the % split is entered. */ protected JLabel m_PercentLab = new JLabel("%", SwingConstants.RIGHT); /** The field where the % split is entered. */ protected JTextField m_PercentText = new JTextField("66", 3); /** The button used to open a separate test dataset. */ protected JButton m_SetTestBut = new JButton("Set..."); /** The frame used to show the test set selection panel. */ protected JFrame m_SetTestFrame; /** The frame used to show the cost matrix editing panel. */ protected PropertyDialog m_SetCostsFrame; /** * Alters the enabled/disabled status of elements associated with each radio * button. */ ActionListener m_RadioListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { updateRadioLinks(); } }; /** Button for further output/visualize options. */ JButton m_MoreOptions = new JButton("More options..."); /** User specified random seed for cross validation or % split. */ protected JTextField m_RandomSeedText = new JTextField("1", 3); /** the label for the random seed textfield. */ protected JLabel m_RandomLab = new JLabel("Random seed for XVal / % Split", SwingConstants.RIGHT); /** Whether randomization is turned off to preserve order. */ protected JCheckBox m_PreserveOrderBut = new JCheckBox( "Preserve order for % Split"); /** * Whether to output the source code (only for classifiers importing * Sourcable). */ protected JCheckBox m_OutputSourceCode = new JCheckBox("Output source code"); /** The name of the generated class (only applicable to Sourcable schemes). */ protected JTextField m_SourceCodeClass = new JTextField("WekaClassifier", 10); /** Click to start running the classifier. */ protected JButton m_StartBut = new JButton("Start"); /** Click to stop a running classifier. */ protected JButton m_StopBut = new JButton("Stop"); /** Stop the class combo from taking up to much space. */ private final Dimension COMBO_SIZE = new Dimension(150, m_StartBut.getPreferredSize().height); /** The cost matrix editor for evaluation costs. */ protected CostMatrixEditor m_CostMatrixEditor = new CostMatrixEditor(); /** The main set of instances we're playing with. */ protected Instances m_Instances; /** The loader used to load the user-supplied test set (if any). */ protected Loader m_TestLoader; /** the class index for the supplied test set. */ protected int m_TestClassIndex = -1; /** A thread that classification runs in. */ protected Thread m_RunThread; /** The current visualization object. */ protected VisualizePanel m_CurrentVis = null; /** Filter to ensure only model files are selected. */ protected FileFilter m_ModelFilter = new ExtensionFileFilter( MODEL_FILE_EXTENSION, "Model object files"); protected FileFilter m_PMMLModelFilter = new ExtensionFileFilter( PMML_FILE_EXTENSION, "PMML model files"); /** The file chooser for selecting model files. */ protected JFileChooser m_FileChooser = new JFileChooser(new File( System.getProperty("user.dir"))); /** The user's list of selected evaluation metrics */ protected List<String> m_selectedEvalMetrics = Evaluation .getAllEvaluationMetricNames(); /** * Whether start-up settings have been applied (i.e. initial classifier to * use) */ protected boolean m_initialSettingsSet; /* Register the property editors we need */ static { GenericObjectEditor.registerEditors(); } /** * Creates the classifier panel. */ public ClassifierPanel() { m_selectedEvalMetrics.remove("Coverage"); m_selectedEvalMetrics.remove("Region size"); // Connect / configure the components m_OutText.setEditable(false); m_OutText.setFont(new Font("Monospaced", Font.PLAIN, 12)); m_OutText.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); m_OutText.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if ((e.getModifiers() & InputEvent.BUTTON1_MASK) != InputEvent.BUTTON1_MASK) { m_OutText.selectAll(); } } }); JPanel historyHolder = new JPanel(new BorderLayout()); historyHolder.setBorder(BorderFactory .createTitledBorder("Result list (right-click for options)")); historyHolder.add(m_History, BorderLayout.CENTER); m_ClassifierEditor.setClassType(Classifier.class); m_ClassifierEditor.setValue(ExplorerDefaults.getClassifier()); m_ClassifierEditor.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent e) { m_StartBut.setEnabled(true); // Check capabilities Capabilities currentFilter = m_ClassifierEditor.getCapabilitiesFilter(); Classifier classifier = (Classifier) m_ClassifierEditor.getValue(); Capabilities currentSchemeCapabilities = null; if (classifier != null && currentFilter != null && (classifier instanceof CapabilitiesHandler)) { currentSchemeCapabilities = ((CapabilitiesHandler) classifier).getCapabilities(); if (!currentSchemeCapabilities.supportsMaybe(currentFilter) && !currentSchemeCapabilities.supports(currentFilter)) { m_StartBut.setEnabled(false); } } repaint(); } }); m_ClassCombo.setToolTipText("Select the attribute to use as the class"); m_TrainBut.setToolTipText("Test on the same set that the classifier" + " is trained on"); m_CVBut.setToolTipText("Perform a n-fold cross-validation"); m_PercentBut.setToolTipText("Train on a percentage of the data and" + " test on the remainder"); m_TestSplitBut.setToolTipText("Test on a user-specified dataset"); m_StartBut.setToolTipText("Starts the classification"); m_StopBut.setToolTipText("Stops a running classification"); m_StorePredictionsBut .setToolTipText("Store predictions in the result list for later " + "visualization"); m_errorPlotPointSizeProportionalToMargin .setToolTipText("In classifier errors plots the point size will be " + "set proportional to the absolute value of the " + "prediction margin (affects classification only)"); m_OutputModelBut .setToolTipText("Output the model obtained from the full training set"); m_OutputModelsForTrainingSplitsBut .setToolTipText("Output the models obtained from the training splits"); m_OutputPerClassBut.setToolTipText("Output precision/recall & true/false" + " positives for each class"); m_OutputConfusionBut .setToolTipText("Output the matrix displaying class confusions"); m_OutputEntropyBut .setToolTipText("Output entropy-based evaluation measures"); m_EvalWRTCostsBut .setToolTipText("Evaluate errors with respect to a cost matrix"); m_RandomLab.setToolTipText("The seed value for randomization"); m_RandomSeedText.setToolTipText(m_RandomLab.getToolTipText()); m_PreserveOrderBut .setToolTipText("Preserves the order in a percentage split"); m_OutputSourceCode .setToolTipText("Whether to output the built classifier as Java source code"); m_SourceCodeClass.setToolTipText("The classname of the built classifier"); m_FileChooser.addChoosableFileFilter(m_PMMLModelFilter); m_FileChooser.setFileFilter(m_ModelFilter); m_FileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); m_ClassificationOutputEditor.setClassType(AbstractOutput.class); m_ClassificationOutputEditor.setValue(new Null()); m_StorePredictionsBut.setSelected(ExplorerDefaults .getClassifierStorePredictionsForVis()); m_OutputModelBut.setSelected(ExplorerDefaults.getClassifierOutputModel()); m_OutputModelsForTrainingSplitsBut.setSelected(ExplorerDefaults.getClassifierOutputModelsForTrainingSplits()); m_OutputPerClassBut.setSelected(ExplorerDefaults .getClassifierOutputPerClassStats()); m_OutputConfusionBut.setSelected(ExplorerDefaults .getClassifierOutputConfusionMatrix()); m_EvalWRTCostsBut.setSelected(ExplorerDefaults .getClassifierCostSensitiveEval()); m_OutputEntropyBut.setSelected(ExplorerDefaults .getClassifierOutputEntropyEvalMeasures()); m_RandomSeedText.setText("" + ExplorerDefaults.getClassifierRandomSeed()); m_PreserveOrderBut.setSelected(ExplorerDefaults .getClassifierPreserveOrder()); m_OutputSourceCode.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m_SourceCodeClass.setEnabled(m_OutputSourceCode.isSelected()); } }); m_OutputSourceCode.setSelected(ExplorerDefaults .getClassifierOutputSourceCode()); m_SourceCodeClass.setText(ExplorerDefaults.getClassifierSourceCodeClass()); m_SourceCodeClass.setEnabled(m_OutputSourceCode.isSelected()); m_ClassCombo.setEnabled(false); m_ClassCombo.setPreferredSize(COMBO_SIZE); m_ClassCombo.setMaximumSize(COMBO_SIZE); m_ClassCombo.setMinimumSize(COMBO_SIZE); m_CVBut.setSelected(true); // see "testMode" variable in startClassifier m_CVBut.setSelected(ExplorerDefaults.getClassifierTestMode() == 1); m_PercentBut.setSelected(ExplorerDefaults.getClassifierTestMode() == 2); m_TrainBut.setSelected(ExplorerDefaults.getClassifierTestMode() == 3); m_TestSplitBut.setSelected(ExplorerDefaults.getClassifierTestMode() == 4); m_PercentText.setText("" + ExplorerDefaults.getClassifierPercentageSplit()); m_CVText.setText("" + ExplorerDefaults.getClassifierCrossvalidationFolds()); updateRadioLinks(); ButtonGroup bg = new ButtonGroup(); bg.add(m_TrainBut); bg.add(m_CVBut); bg.add(m_PercentBut); bg.add(m_TestSplitBut); m_TrainBut.addActionListener(m_RadioListener); m_CVBut.addActionListener(m_RadioListener); m_PercentBut.addActionListener(m_RadioListener); m_TestSplitBut.addActionListener(m_RadioListener); m_SetTestBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { setTestSet(); } }); m_EvalWRTCostsBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m_SetCostsBut.setEnabled(m_EvalWRTCostsBut.isSelected()); if ((m_SetCostsFrame != null) && (!m_EvalWRTCostsBut.isSelected())) { m_SetCostsFrame.setVisible(false); } } }); m_CostMatrixEditor.setValue(new CostMatrix(1)); m_SetCostsBut.setEnabled(m_EvalWRTCostsBut.isSelected()); m_SetCostsBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m_SetCostsBut.setEnabled(false); if (m_SetCostsFrame == null) { if (PropertyDialog.getParentDialog(m_SetCostsBut) != null) { m_SetCostsFrame = new PropertyDialog(PropertyDialog.getParentDialog(m_SetCostsBut), m_CostMatrixEditor, -1, -1); } else { m_SetCostsFrame = new PropertyDialog(PropertyDialog.getParentFrame(m_SetCostsBut), m_CostMatrixEditor, -1, -1); } m_SetCostsFrame.setTitle("Cost Matrix Editor"); // pd.setSize(250,150); m_SetCostsFrame.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent p) { m_SetCostsBut.setEnabled(m_EvalWRTCostsBut.isSelected()); if ((m_SetCostsFrame != null) && (!m_EvalWRTCostsBut.isSelected())) { m_SetCostsFrame.setVisible(false); } } }); } // do we need to change the size of the matrix? int classIndex = m_ClassCombo.getSelectedIndex(); int numClasses = m_Instances.attribute(classIndex).numValues(); if (numClasses != ((CostMatrix) m_CostMatrixEditor.getValue()) .numColumns()) { m_CostMatrixEditor.setValue(new CostMatrix(numClasses)); } if (PropertyDialog.getParentDialog(m_SetCostsBut) != null) { m_SetCostsFrame.setLocationRelativeTo(PropertyDialog.getParentDialog(m_SetCostsBut)); } else { m_SetCostsFrame.setLocationRelativeTo(PropertyDialog.getParentFrame(m_SetCostsBut)); } m_SetCostsFrame.setVisible(true); } }); m_StartBut.setEnabled(false); m_StopBut.setEnabled(false); m_StartBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { boolean proceed = true; if (Explorer.m_Memory.memoryIsLow()) { proceed = Explorer.m_Memory.showMemoryIsLow(); } if (proceed) { startClassifier(); } } }); m_StopBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { stopClassifier(); } }); m_ClassCombo.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int selected = m_ClassCombo.getSelectedIndex(); if (selected != -1) { boolean isNominal = m_Instances.attribute(selected).isNominal(); m_OutputPerClassBut.setEnabled(isNominal); m_OutputConfusionBut.setEnabled(isNominal); } updateCapabilitiesFilter(m_ClassifierEditor.getCapabilitiesFilter()); } }); m_History.setHandleRightClicks(false); // see if we can popup a menu for the selected result m_History.getList().addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (((e.getModifiers() & InputEvent.BUTTON1_MASK) != InputEvent.BUTTON1_MASK) || e.isAltDown()) { int index = m_History.getList().locationToIndex(e.getPoint()); if (index != -1) { List<String> selectedEls = (List<String>) m_History.getList().getSelectedValuesList(); // String name = m_History.getNameAtIndex(index); visualize(selectedEls, e.getX(), e.getY()); } else { visualize(null, e.getX(), e.getY()); } } } }); m_MoreOptions.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m_MoreOptions.setEnabled(false); JPanel moreOptionsPanel = new JPanel(); moreOptionsPanel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5)); moreOptionsPanel.setLayout(new GridLayout(0, 1)); moreOptionsPanel.add(m_OutputModelBut); moreOptionsPanel.add(m_OutputModelsForTrainingSplitsBut); moreOptionsPanel.add(m_OutputPerClassBut); moreOptionsPanel.add(m_OutputEntropyBut); moreOptionsPanel.add(m_OutputConfusionBut); moreOptionsPanel.add(m_StorePredictionsBut); moreOptionsPanel.add(m_errorPlotPointSizeProportionalToMargin); JPanel classOutPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); classOutPanel.add(new JLabel("Output predictions")); classOutPanel.add(m_ClassificationOutputPanel); moreOptionsPanel.add(classOutPanel); JPanel costMatrixOption = new JPanel(new FlowLayout(FlowLayout.LEFT)); costMatrixOption.add(m_EvalWRTCostsBut); costMatrixOption.add(m_SetCostsBut); moreOptionsPanel.add(costMatrixOption); JPanel seedPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); seedPanel.add(m_RandomLab); seedPanel.add(m_RandomSeedText); moreOptionsPanel.add(seedPanel); moreOptionsPanel.add(m_PreserveOrderBut); JPanel sourcePanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); m_OutputSourceCode.setEnabled(m_ClassifierEditor.getValue() instanceof Sourcable); m_SourceCodeClass.setEnabled(m_OutputSourceCode.isEnabled() && m_OutputSourceCode.isSelected()); sourcePanel.add(m_OutputSourceCode); sourcePanel.add(m_SourceCodeClass); moreOptionsPanel.add(sourcePanel); JPanel all = new JPanel(); all.setLayout(new BorderLayout()); JButton oK = new JButton("OK"); JPanel okP = new JPanel(); okP.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); okP.setLayout(new GridLayout(1, 1, 5, 5)); okP.add(oK); all.add(moreOptionsPanel, BorderLayout.CENTER); all.add(okP, BorderLayout.SOUTH); final JDialog jd = new JDialog(PropertyDialog.getParentFrame(ClassifierPanel.this), "Classifier evaluation options"); jd.getContentPane().setLayout(new BorderLayout()); jd.getContentPane().add(all, BorderLayout.CENTER); jd.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent w) { jd.dispose(); m_MoreOptions.setEnabled(true); } }); oK.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent a) { m_MoreOptions.setEnabled(true); jd.dispose(); } }); jd.pack(); // panel height is only available now m_ClassificationOutputPanel.setPreferredSize(new Dimension(300, m_ClassificationOutputPanel.getHeight())); jd.pack(); // final List<AbstractEvaluationMetric> pluginMetrics = // AbstractEvaluationMetric // .getPluginMetrics(); final JButton editEvalMetrics = new JButton("Evaluation metrics..."); JPanel evalP = new JPanel(); evalP.setLayout(new BorderLayout()); evalP.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); evalP.add(editEvalMetrics, BorderLayout.CENTER); editEvalMetrics .setToolTipText("Enable/disable output of specific evaluation metrics"); moreOptionsPanel.add(evalP); editEvalMetrics.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { EvaluationMetricSelectionDialog esd = new EvaluationMetricSelectionDialog(jd, m_selectedEvalMetrics); esd.setLocation(m_MoreOptions.getLocationOnScreen()); esd.pack(); esd.setVisible(true); m_selectedEvalMetrics = esd.getSelectedEvalMetrics(); } }); jd.setLocation(m_MoreOptions.getLocationOnScreen()); jd.setVisible(true); } }); // Layout the GUI JPanel p1 = new JPanel(); p1.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createTitledBorder("Classifier"), BorderFactory.createEmptyBorder(0, 5, 5, 5))); p1.setLayout(new BorderLayout()); p1.add(m_CEPanel, BorderLayout.NORTH); JPanel p2 = new JPanel(); GridBagLayout gbL = new GridBagLayout(); p2.setLayout(gbL); p2.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createTitledBorder("Test options"), BorderFactory.createEmptyBorder(0, 5, 5, 5))); GridBagConstraints gbC = new GridBagConstraints(); gbC.anchor = GridBagConstraints.WEST; gbC.gridy = 0; gbC.gridx = 0; gbL.setConstraints(m_TrainBut, gbC); p2.add(m_TrainBut); gbC = new GridBagConstraints(); gbC.anchor = GridBagConstraints.WEST; gbC.gridy = 1; gbC.gridx = 0; gbL.setConstraints(m_TestSplitBut, gbC); p2.add(m_TestSplitBut); gbC = new GridBagConstraints(); gbC.anchor = GridBagConstraints.EAST; gbC.fill = GridBagConstraints.HORIZONTAL; gbC.gridy = 1; gbC.gridx = 1; gbC.gridwidth = 2; gbC.insets = new Insets(2, 10, 2, 0); gbL.setConstraints(m_SetTestBut, gbC); p2.add(m_SetTestBut); gbC = new GridBagConstraints(); gbC.anchor = GridBagConstraints.WEST; gbC.gridy = 2; gbC.gridx = 0; gbL.setConstraints(m_CVBut, gbC); p2.add(m_CVBut); gbC = new GridBagConstraints(); gbC.anchor = GridBagConstraints.EAST; gbC.fill = GridBagConstraints.HORIZONTAL; gbC.gridy = 2; gbC.gridx = 1; gbC.insets = new Insets(2, 10, 2, 10); gbL.setConstraints(m_CVLab, gbC); p2.add(m_CVLab); gbC = new GridBagConstraints(); gbC.anchor = GridBagConstraints.EAST; gbC.fill = GridBagConstraints.HORIZONTAL; gbC.gridy = 2; gbC.gridx = 2; gbC.weightx = 100; gbC.ipadx = 20; gbL.setConstraints(m_CVText, gbC); p2.add(m_CVText); gbC = new GridBagConstraints(); gbC.anchor = GridBagConstraints.WEST; gbC.gridy = 3; gbC.gridx = 0; gbL.setConstraints(m_PercentBut, gbC); p2.add(m_PercentBut); gbC = new GridBagConstraints(); gbC.anchor = GridBagConstraints.EAST; gbC.fill = GridBagConstraints.HORIZONTAL; gbC.gridy = 3; gbC.gridx = 1; gbC.insets = new Insets(2, 10, 2, 10); gbL.setConstraints(m_PercentLab, gbC); p2.add(m_PercentLab); gbC = new GridBagConstraints(); gbC.anchor = GridBagConstraints.EAST; gbC.fill = GridBagConstraints.HORIZONTAL; gbC.gridy = 3; gbC.gridx = 2; gbC.weightx = 100; gbC.ipadx = 20; gbL.setConstraints(m_PercentText, gbC); p2.add(m_PercentText); gbC = new GridBagConstraints(); gbC.anchor = GridBagConstraints.WEST; gbC.fill = GridBagConstraints.HORIZONTAL; gbC.gridy = 4; gbC.gridx = 0; gbC.weightx = 100; gbC.gridwidth = 3; gbC.insets = new Insets(3, 0, 1, 0); gbL.setConstraints(m_MoreOptions, gbC); p2.add(m_MoreOptions); // Any launcher plugins? List<String> pluginsVector = PluginManager.getPluginNamesOfTypeList(ClassifierPanelLaunchHandlerPlugin.class.getName()); JButton pluginBut = null; if (pluginsVector.size() == 1) { try { // Display as a single button String className = pluginsVector.get(0); final ClassifierPanelLaunchHandlerPlugin plugin = (ClassifierPanelLaunchHandlerPlugin) WekaPackageClassLoaderManager .objectForName(className); // (ClassifierPanelLaunchHandlerPlugin) Class.forName(className) // .newInstance(); if (plugin != null) { plugin.setClassifierPanel(this); pluginBut = new JButton(plugin.getLaunchCommand()); pluginBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { plugin.launch(); } }); } } catch (Exception ex) { ex.printStackTrace(); } } else if (pluginsVector.size() > 1) { // make a popu menu int okPluginCount = 0; final java.awt.PopupMenu pluginPopup = new java.awt.PopupMenu(); for (int i = 0; i < pluginsVector.size(); i++) { String className = (pluginsVector.get(i)); try { final ClassifierPanelLaunchHandlerPlugin plugin = (ClassifierPanelLaunchHandlerPlugin) WekaPackageClassLoaderManager .objectForName(className); // (ClassifierPanelLaunchHandlerPlugin) Class.forName(className) // .newInstance(); if (plugin == null) { continue; } okPluginCount++; plugin.setClassifierPanel(this); java.awt.MenuItem popI = new java.awt.MenuItem(plugin.getLaunchCommand()); popI.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // pluginPopup.setVisible(false); plugin.launch(); } }); pluginPopup.add(popI); } catch (Exception ex) { ex.printStackTrace(); } } if (okPluginCount > 0) { pluginBut = new JButton("Launchers..."); final JButton copyB = pluginBut; copyB.add(pluginPopup); pluginBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { pluginPopup.show(copyB, 0, 0); } }); } else { pluginBut = null; } } JPanel buttons = new JPanel(); buttons.setLayout(new GridLayout(2, 2)); buttons.add(m_ClassCombo); m_ClassCombo.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); JPanel ssButs = new JPanel(); ssButs.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); if (pluginBut == null) { ssButs.setLayout(new GridLayout(1, 2, 5, 5)); } else { ssButs.setLayout(new FlowLayout(FlowLayout.LEFT)); } ssButs.add(m_StartBut); ssButs.add(m_StopBut); if (pluginBut != null) { ssButs.add(pluginBut); } buttons.add(ssButs); JPanel p3 = new JPanel(); p3.setBorder(BorderFactory.createTitledBorder("Classifier output")); p3.setLayout(new BorderLayout()); final JScrollPane js = new JScrollPane(m_OutText); p3.add(js, BorderLayout.CENTER); js.getViewport().addChangeListener(new ChangeListener() { private int lastHeight; @Override public void stateChanged(ChangeEvent e) { JViewport vp = (JViewport) e.getSource(); int h = vp.getViewSize().height; if (h != lastHeight) { // i.e. an addition not just a user scrolling lastHeight = h; int x = h - vp.getExtentSize().height; vp.setViewPosition(new Point(0, x)); } } }); JPanel mondo = new JPanel(); gbL = new GridBagLayout(); mondo.setLayout(gbL); gbC = new GridBagConstraints(); // gbC.anchor = GridBagConstraints.WEST; gbC.fill = GridBagConstraints.HORIZONTAL; gbC.gridy = 0; gbC.gridx = 0; gbL.setConstraints(p2, gbC); mondo.add(p2); gbC = new GridBagConstraints(); gbC.anchor = GridBagConstraints.NORTH; gbC.fill = GridBagConstraints.HORIZONTAL; gbC.gridy = 1; gbC.gridx = 0; gbL.setConstraints(buttons, gbC); mondo.add(buttons); gbC = new GridBagConstraints(); // gbC.anchor = GridBagConstraints.NORTH; gbC.fill = GridBagConstraints.BOTH; gbC.gridy = 2; gbC.gridx = 0; gbC.weightx = 0; gbL.setConstraints(historyHolder, gbC); mondo.add(historyHolder); gbC = new GridBagConstraints(); gbC.fill = GridBagConstraints.BOTH; gbC.gridy = 0; gbC.gridx = 1; gbC.gridheight = 3; gbC.weightx = 100; gbC.weighty = 100; gbL.setConstraints(p3, gbC); mondo.add(p3); setLayout(new BorderLayout()); add(p1, BorderLayout.NORTH); add(mondo, BorderLayout.CENTER); } /** * Updates the enabled status of the input fields and labels. */ protected void updateRadioLinks() { m_SetTestBut.setEnabled(m_TestSplitBut.isSelected()); if ((m_SetTestFrame != null) && (!m_TestSplitBut.isSelected())) { m_SetTestFrame.setVisible(false); } m_CVText.setEnabled(m_CVBut.isSelected()); m_CVLab.setEnabled(m_CVBut.isSelected()); m_PercentText.setEnabled(m_PercentBut.isSelected()); m_PercentLab.setEnabled(m_PercentBut.isSelected()); } /** * Sets the Logger to receive informational messages. * * @param newLog the Logger that will now get info messages */ @Override public void setLog(Logger newLog) { m_Log = newLog; } /** * Tells the panel to use a new set of instances. * * @param inst a set of Instances */ @Override public void setInstances(Instances inst) { m_Instances = inst; String[] attribNames = new String[m_Instances.numAttributes()]; for (int i = 0; i < attribNames.length; i++) { String type = "(" + Attribute.typeToStringShort(m_Instances.attribute(i)) + ") "; attribNames[i] = type + m_Instances.attribute(i).name(); } m_ClassCombo.setModel(new DefaultComboBoxModel(attribNames)); if (attribNames.length > 0) { if (inst.classIndex() == -1) { m_ClassCombo.setSelectedIndex(attribNames.length - 1); } else { m_ClassCombo.setSelectedIndex(inst.classIndex()); } m_ClassCombo.setEnabled(true); m_StartBut.setEnabled(m_RunThread == null); m_StopBut.setEnabled(m_RunThread != null); } else { m_StartBut.setEnabled(false); m_StopBut.setEnabled(false); } } /** * Get the current set of instances * * @return the current set of instances */ public Instances getInstances() { return m_Instances; } /** * Sets the user test set. Information about the current test set is displayed * in an InstanceSummaryPanel and the user is given the ability to load * another set from a file or url. * */ protected void setTestSet() { if (m_SetTestFrame == null) { PreprocessPanel preprocessPanel = null; if (m_Explorer != null) { preprocessPanel = m_Explorer.getPreprocessPanel(); } else if (getMainApplication() != null) { Perspective p = getMainApplication().getPerspectiveManager().getPerspective( PreprocessPanel.PreprocessDefaults.ID); preprocessPanel = (PreprocessPanel) p; } else { throw new IllegalStateException("We don't have access to a " + "PreprocessPanel!"); } final SetInstancesPanel sp = new SetInstancesPanel(true, true, preprocessPanel.m_FileChooser); if (m_TestLoader != null) { try { if (m_TestLoader.getStructure() != null) { sp.setInstances(m_TestLoader.getStructure()); } } catch (Exception ex) { ex.printStackTrace(); } } sp.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent e) { m_TestLoader = sp.getLoader(); m_TestClassIndex = sp.getClassIndex(); } }); // Add propertychangelistener to update m_TestLoader whenever // it changes in the settestframe m_SetTestFrame = Utils.getWekaJFrame("Test Instances", this); sp.setParentFrame(m_SetTestFrame); // enable Close-Button m_SetTestFrame.getContentPane().setLayout(new BorderLayout()); m_SetTestFrame.getContentPane().add(sp, BorderLayout.CENTER); m_SetTestFrame.pack(); m_SetTestFrame.setSize(400,200); } m_SetTestFrame.setLocationRelativeTo(SwingUtilities.getWindowAncestor(this)); m_SetTestFrame.setVisible(true); } /** * outputs the header for the predictions on the data. * * @param outBuff the buffer to add the output to * @param classificationOutput for generating the classification output * @param title the title to print */ protected void printPredictionsHeader(StringBuffer outBuff, AbstractOutput classificationOutput, String title) { if (classificationOutput.generatesOutput()) { outBuff.append("=== Predictions on " + title + " ===\n\n"); } classificationOutput.printHeader(); } /** * Configures an evaluation object with respect to a classifier, cost matrix, * output and plotting. * * @param eval the Evaluation object to configure * @param classifier the Classifier being used * @param inst the Instances involved * @param costMatrix a cost matrix (if any) * @param plotInstances a ClassifierErrorsPlotInstances for visualization of * errors (can be null) * @param classificationOutput an output object for printing predictions (can * be null) * @param onlySetPriors true to only set priors * @return the configured Evaluation object * @throws Exception if a problem occurs */ public static Evaluation setupEval(Evaluation eval, Classifier classifier, Instances inst, CostMatrix costMatrix, ClassifierErrorsPlotInstances plotInstances, AbstractOutput classificationOutput, boolean onlySetPriors) throws Exception { if (classifier instanceof weka.classifiers.misc.InputMappedClassifier) { Instances mappedClassifierHeader = ((weka.classifiers.misc.InputMappedClassifier) classifier) .getModelHeader(new Instances(inst, 0)); if (classificationOutput != null) { classificationOutput.setHeader(mappedClassifierHeader); } if (!onlySetPriors) { if (costMatrix != null) { eval = new Evaluation(new Instances(mappedClassifierHeader, 0), costMatrix); } else { eval = new Evaluation(new Instances(mappedClassifierHeader, 0)); } } if (!eval.getHeader().equalHeaders(inst)) { // When the InputMappedClassifier is loading a model, // we need to make a new dataset that maps the training instances to // the structure expected by the mapped classifier - this is only // to ensure that the structure and priors computed by // evaluation object is correct with respect to the mapped classifier Instances mappedClassifierDataset = ((weka.classifiers.misc.InputMappedClassifier) classifier) .getModelHeader(new Instances(mappedClassifierHeader, 0)); for (int zz = 0; zz < inst.numInstances(); zz++) { Instance mapped = ((weka.classifiers.misc.InputMappedClassifier) classifier) .constructMappedInstance(inst.instance(zz)); mappedClassifierDataset.add(mapped); } eval.setPriors(mappedClassifierDataset); if (!onlySetPriors) { if (plotInstances != null) { plotInstances.setInstances(mappedClassifierDataset); plotInstances.setClassifier(classifier); /* * int mappedClass = * ((weka.classifiers.misc.InputMappedClassifier)classifier * ).getMappedClassIndex(); System.err.println("Mapped class index " * + mappedClass); */ plotInstances.setClassIndex(mappedClassifierDataset.classIndex()); plotInstances.setEvaluation(eval); } } } else { eval.setPriors(inst); if (!onlySetPriors) { if (plotInstances != null) { plotInstances.setInstances(inst); plotInstances.setClassifier(classifier); plotInstances.setClassIndex(inst.classIndex()); plotInstances.setEvaluation(eval); } } } } else { eval.setPriors(inst); if (!onlySetPriors) { if (plotInstances != null) { plotInstances.setInstances(inst); plotInstances.setClassifier(classifier); plotInstances.setClassIndex(inst.classIndex()); plotInstances.setEvaluation(eval); } } } return eval; } /** * Starts running the currently configured classifier with the current * settings. This is run in a separate thread, and will only start if there is * no classifier already running. The classifier output is sent to the results * history panel. */ protected void startClassifier() { if (m_RunThread == null) { synchronized (this) { m_StartBut.setEnabled(false); m_StopBut.setEnabled(true); } m_RunThread = new Thread() { @Override public void run() { m_CEPanel.addToHistory(); // Copy the current state of things m_Log.statusMessage("Setting up..."); CostMatrix costMatrix = null; Instances inst = new Instances(m_Instances); DataSource source = null; Instances userTestStructure = null; ClassifierErrorsPlotInstances plotInstances = null; // for timing long trainTimeStart = 0, trainTimeElapsed = 0; long testTimeStart = 0, testTimeElapsed = 0; try { if (m_TestLoader != null && m_TestLoader.getStructure() != null) { /* if (m_ClassifierEditor.getValue() instanceof BatchPredictor && ((BatchPredictor) m_ClassifierEditor.getValue()) .implementsMoreEfficientBatchPrediction() && m_TestLoader instanceof ArffLoader) { // we're not really streaming test instances in this case... ((ArffLoader) m_TestLoader).setRetainStringVals(true); } */ if (m_TestLoader instanceof ArffLoader && m_StorePredictionsBut.isSelected()) { ((ArffLoader) m_TestLoader).setRetainStringVals(true); } m_TestLoader.reset(); source = new DataSource(m_TestLoader); userTestStructure = source.getStructure(); userTestStructure.setClassIndex(m_TestClassIndex); } } catch (Exception ex) { ex.printStackTrace(); } if (m_EvalWRTCostsBut.isSelected()) { costMatrix = new CostMatrix((CostMatrix) m_CostMatrixEditor.getValue()); } boolean outputModel = m_OutputModelBut.isSelected(); boolean outputModelsForTrainingSplits = m_OutputModelsForTrainingSplitsBut.isSelected(); boolean outputConfusion = m_OutputConfusionBut.isSelected(); boolean outputPerClass = m_OutputPerClassBut.isSelected(); boolean outputSummary = true; boolean outputEntropy = m_OutputEntropyBut.isSelected(); boolean saveVis = m_StorePredictionsBut.isSelected(); boolean outputPredictionsText = (m_ClassificationOutputEditor.getValue().getClass() != Null.class); String grph = null; int testMode = 0; int numFolds = 10; double percent = 66; int classIndex = m_ClassCombo.getSelectedIndex(); inst.setClassIndex(classIndex); Classifier classifier = (Classifier) m_ClassifierEditor.getValue(); Classifier template = null; try { template = AbstractClassifier.makeCopy(classifier); } catch (Exception ex) { m_Log.logMessage("Problem copying classifier: " + ex.getMessage()); } Classifier fullClassifier = null; StringBuffer outBuff = new StringBuffer(); AbstractOutput classificationOutput = null; if (outputPredictionsText) { classificationOutput = (AbstractOutput) m_ClassificationOutputEditor.getValue(); Instances header = new Instances(inst, 0); header.setClassIndex(classIndex); classificationOutput.setHeader(header); classificationOutput.setBuffer(outBuff); } String name = (new SimpleDateFormat("HH:mm:ss - ")).format(new Date()); String cname = ""; String cmd = ""; Evaluation eval = null; try { if (m_CVBut.isSelected()) { testMode = 1; numFolds = Integer.parseInt(m_CVText.getText()); if (numFolds <= 1) { throw new Exception("Number of folds must be greater than 1"); } } else if (m_PercentBut.isSelected()) { testMode = 2; percent = Double.parseDouble(m_PercentText.getText()); if ((percent <= 0) || (percent >= 100)) { throw new Exception("Percentage must be between 0 and 100"); } } else if (m_TrainBut.isSelected()) { testMode = 3; } else if (m_TestSplitBut.isSelected()) { testMode = 4; // Check the test instance compatibility if (source == null) { throw new Exception("No user test set has been specified"); } if (!(classifier instanceof weka.classifiers.misc.InputMappedClassifier)) { if (!inst.equalHeaders(userTestStructure)) { boolean wrapClassifier = false; if (!Utils .getDontShowDialog("weka.gui.explorer.ClassifierPanel.AutoWrapInInputMappedClassifier")) { JCheckBox dontShow = new JCheckBox("Do not show this message again"); Object[] stuff = new Object[2]; stuff[0] = "Train and test set are not compatible.\n" + "Would you like to automatically wrap the classifier in\n" + "an \"InputMappedClassifier\" before proceeding?.\n"; stuff[1] = dontShow; int result = JOptionPane.showConfirmDialog(ClassifierPanel.this, stuff, "ClassifierPanel", JOptionPane.YES_OPTION); if (result == JOptionPane.YES_OPTION) { wrapClassifier = true; } if (dontShow.isSelected()) { String response = (wrapClassifier) ? "yes" : "no"; Utils .setDontShowDialogResponse( "weka.gui.explorer.ClassifierPanel.AutoWrapInInputMappedClassifier", response); } } else { // What did the user say - do they want to autowrap or not? String response = Utils .getDontShowDialogResponse("weka.gui.explorer.ClassifierPanel.AutoWrapInInputMappedClassifier"); if (response != null && response.equalsIgnoreCase("yes")) { wrapClassifier = true; } } if (wrapClassifier) { weka.classifiers.misc.InputMappedClassifier temp = new weka.classifiers.misc.InputMappedClassifier(); // pass on the known test structure so that we get the // correct mapping report from the toString() method // of InputMappedClassifier temp.setClassifier(classifier); temp.setTestStructure(userTestStructure); classifier = temp; } else { throw new Exception( "Train and test set are not compatible\n" + inst.equalHeadersMsg(userTestStructure)); } } } } else { throw new Exception("Unknown test mode"); } cname = classifier.getClass().getName(); if (cname.startsWith("weka.classifiers.")) { name += cname.substring("weka.classifiers.".length()); } else { name += cname; } cmd = classifier.getClass().getName(); if (classifier instanceof OptionHandler) { cmd += " " + Utils .joinOptions(((OptionHandler) classifier).getOptions()); } // set up the structure of the plottable instances for // visualization plotInstances = ExplorerDefaults.getClassifierErrorsPlotInstances(); plotInstances.setInstances(testMode == 4 ? userTestStructure : inst); plotInstances.setClassifier(classifier); plotInstances.setClassIndex(inst.classIndex()); plotInstances.setSaveForVisualization(saveVis); plotInstances .setPointSizeProportionalToMargin(m_errorPlotPointSizeProportionalToMargin .isSelected()); // Output some header information m_Log.logMessage("Started " + cname); m_Log.logMessage("Command: " + cmd); if (m_Log instanceof TaskLogger) { ((TaskLogger) m_Log).taskStarted(); } outBuff.append("=== Run information ===\n\n"); outBuff.append("Scheme: " + cname); if (classifier instanceof OptionHandler) { String[] o = ((OptionHandler) classifier).getOptions(); outBuff.append(" " + Utils.joinOptions(o)); } outBuff.append("\n"); outBuff.append("Relation: " + inst.relationName() + '\n'); outBuff.append("Instances: " + inst.numInstances() + '\n'); outBuff.append("Attributes: " + inst.numAttributes() + '\n'); if (inst.numAttributes() < 100) { for (int i = 0; i < inst.numAttributes(); i++) { outBuff.append(" " + inst.attribute(i).name() + '\n'); } } else { outBuff.append(" [list of attributes omitted]\n"); } outBuff.append("Test mode: "); switch (testMode) { case 3: // Test on training outBuff.append("evaluate on training data\n"); break; case 1: // CV mode outBuff.append("" + numFolds + "-fold cross-validation\n"); break; case 2: // Percent split outBuff.append("split " + percent + "% train, remainder test\n"); break; case 4: // Test on user split if (source.isIncremental()) { outBuff.append("user supplied test set: " + " size unknown (reading incrementally)\n"); } else { outBuff.append("user supplied test set: " + source.getDataSet().numInstances() + " instances\n"); } break; } if (costMatrix != null) { outBuff.append("Evaluation cost matrix:\n") .append(costMatrix.toString()).append("\n"); } outBuff.append("\n"); m_History.addResult(name, outBuff); m_History.setSingle(name); // Build the model and output it. if (outputModel || (testMode == 3) || (testMode == 4)) { m_Log.statusMessage("Building model on training data..."); trainTimeStart = System.currentTimeMillis(); classifier.buildClassifier(inst); trainTimeElapsed = System.currentTimeMillis() - trainTimeStart; } if (outputModel) { outBuff .append("=== Classifier model (full training set) ===\n\n"); outBuff.append(classifier.toString() + "\n"); outBuff.append("\nTime taken to build model: " + Utils.doubleToString(trainTimeElapsed / 1000.0, 2) + " seconds\n\n"); m_History.updateResult(name); if (classifier instanceof Drawable) { grph = null; try { grph = ((Drawable) classifier).graph(); } catch (Exception ex) { } } // copy full model for output SerializedObject so = new SerializedObject(classifier); fullClassifier = (Classifier) so.getObject(); } switch (testMode) { case 3: // Test on training m_Log.statusMessage("Evaluating on training data..."); eval = new Evaluation(inst, costMatrix); // make adjustments if the classifier is an InputMappedClassifier eval = setupEval(eval, classifier, inst, costMatrix, plotInstances, classificationOutput, false); eval.setMetricsToDisplay(m_selectedEvalMetrics); // plotInstances.setEvaluation(eval); plotInstances.setUp(); if (outputPredictionsText) { printPredictionsHeader(outBuff, classificationOutput, "training set"); } testTimeStart = System.currentTimeMillis(); if (classifier instanceof BatchPredictor && ((BatchPredictor) classifier) .implementsMoreEfficientBatchPrediction()) { Instances toPred = new Instances(inst); for (int i = 0; i < toPred.numInstances(); i++) { toPred.instance(i).setClassMissing(); } double[][] predictions = ((BatchPredictor) classifier) .distributionsForInstances(toPred); plotInstances.process(inst, predictions, eval); if (outputPredictionsText) { for (int jj = 0; jj < inst.numInstances(); jj++) { classificationOutput.printClassification(predictions[jj], inst.instance(jj), jj); } } } else { for (int jj = 0; jj < inst.numInstances(); jj++) { plotInstances.process(inst.instance(jj), classifier, eval); if (outputPredictionsText) { classificationOutput.printClassification(classifier, inst.instance(jj), jj); } if ((jj % 100) == 0) { m_Log .statusMessage("Evaluating on training data. Processed " + jj + " instances..."); } } } testTimeElapsed = System.currentTimeMillis() - testTimeStart; if (outputPredictionsText) { classificationOutput.printFooter(); } if (outputPredictionsText && classificationOutput.generatesOutput()) { outBuff.append("\n"); } outBuff.append("=== Evaluation on training set ===\n"); break; case 1: // CV mode m_Log.statusMessage("Randomizing instances..."); int rnd = 1; try { rnd = Integer.parseInt(m_RandomSeedText.getText().trim()); // System.err.println("Using random seed "+rnd); } catch (Exception ex) { m_Log.logMessage("Trouble parsing random seed value"); rnd = 1; } Random random = new Random(rnd); inst.randomize(random); if (inst.attribute(classIndex).isNominal()) { m_Log.statusMessage("Stratifying instances..."); inst.stratify(numFolds); } eval = new Evaluation(inst, costMatrix); // make adjustments if the classifier is an InputMappedClassifier eval = setupEval(eval, classifier, inst, costMatrix, plotInstances, classificationOutput, false); eval.setMetricsToDisplay(m_selectedEvalMetrics); // plotInstances.setEvaluation(eval); plotInstances.setUp(); if (outputPredictionsText) { printPredictionsHeader(outBuff, classificationOutput, "test data"); } // Make some splits and do a CV for (int fold = 0; fold < numFolds; fold++) { m_Log.statusMessage("Creating splits for fold " + (fold + 1) + "..."); Instances train = inst.trainCV(numFolds, fold, random); // make adjustments if the classifier is an // InputMappedClassifier eval = setupEval(eval, classifier, train, costMatrix, plotInstances, classificationOutput, true); eval.setMetricsToDisplay(m_selectedEvalMetrics); // eval.setPriors(train); m_Log.statusMessage("Building model for fold " + (fold + 1) + "..."); Classifier current = null; try { current = AbstractClassifier.makeCopy(template); } catch (Exception ex) { m_Log.logMessage("Problem copying classifier: " + ex.getMessage()); } current.buildClassifier(train); if (outputModelsForTrainingSplits) { outBuff.append("\n=== Classifier model for fold " + (fold + 1) + " ===\n\n"); outBuff.append(current.toString() + "\n"); } Instances test = inst.testCV(numFolds, fold); m_Log.statusMessage("Evaluating model for fold " + (fold + 1) + "..."); if (classifier instanceof BatchPredictor && ((BatchPredictor) classifier) .implementsMoreEfficientBatchPrediction()) { Instances toPred = new Instances(test); for (int i = 0; i < toPred.numInstances(); i++) { toPred.instance(i).setClassMissing(); } double[][] predictions = ((BatchPredictor) current) .distributionsForInstances(toPred); plotInstances.process(test, predictions, eval); if (outputPredictionsText) { for (int jj = 0; jj < test.numInstances(); jj++) { classificationOutput.printClassification(predictions[jj], test.instance(jj), jj); } } } else { for (int jj = 0; jj < test.numInstances(); jj++) { plotInstances.process(test.instance(jj), current, eval); if (outputPredictionsText) { classificationOutput.printClassification(current, test.instance(jj), jj); } } } } if (outputPredictionsText) { classificationOutput.printFooter(); } if (outputPredictionsText) { outBuff.append("\n"); } if (inst.attribute(classIndex).isNominal()) { outBuff.append("=== Stratified cross-validation ===\n"); } else { outBuff.append("=== Cross-validation ===\n"); } break; case 2: // Percent split if (!m_PreserveOrderBut.isSelected()) { m_Log.statusMessage("Randomizing instances..."); try { rnd = Integer.parseInt(m_RandomSeedText.getText().trim()); } catch (Exception ex) { m_Log.logMessage("Trouble parsing random seed value"); rnd = 1; } inst.randomize(new Random(rnd)); } int trainSize = (int) Math.round(inst.numInstances() * percent / 100); int testSize = inst.numInstances() - trainSize; Instances train = new Instances(inst, 0, trainSize); Instances test = new Instances(inst, trainSize, testSize); m_Log.statusMessage("Building model on training split (" + trainSize + " instances)..."); Classifier current = null; try { current = AbstractClassifier.makeCopy(template); } catch (Exception ex) { m_Log.logMessage("Problem copying classifier: " + ex.getMessage()); } current.buildClassifier(train); if (outputModelsForTrainingSplits) { outBuff.append("\n=== Classifier model for training split (" + trainSize + " instances) ===\n\n"); outBuff.append(current.toString() + "\n"); } eval = new Evaluation(train, costMatrix); // make adjustments if the classifier is an InputMappedClassifier eval = setupEval(eval, classifier, train, costMatrix, plotInstances, classificationOutput, false); eval.setMetricsToDisplay(m_selectedEvalMetrics); // plotInstances.setEvaluation(eval); plotInstances.setUp(); m_Log.statusMessage("Evaluating on test split..."); if (outputPredictionsText) { printPredictionsHeader(outBuff, classificationOutput, "test split"); } testTimeStart = System.currentTimeMillis(); if (classifier instanceof BatchPredictor && ((BatchPredictor) classifier) .implementsMoreEfficientBatchPrediction()) { Instances toPred = new Instances(test); for (int i = 0; i < toPred.numInstances(); i++) { toPred.instance(i).setClassMissing(); } double[][] predictions = ((BatchPredictor) current).distributionsForInstances(toPred); plotInstances.process(test, predictions, eval); if (outputPredictionsText) { for (int jj = 0; jj < test.numInstances(); jj++) { classificationOutput.printClassification(predictions[jj], test.instance(jj), jj); } } } else { for (int jj = 0; jj < test.numInstances(); jj++) { plotInstances.process(test.instance(jj), current, eval); if (outputPredictionsText) { classificationOutput.printClassification(current, test.instance(jj), jj); } if ((jj % 100) == 0) { m_Log.statusMessage("Evaluating on test split. Processed " + jj + " instances..."); } } } testTimeElapsed = System.currentTimeMillis() - testTimeStart; if (outputPredictionsText) { classificationOutput.printFooter(); } if (outputPredictionsText) { outBuff.append("\n"); } outBuff.append("=== Evaluation on test split ===\n"); break; case 4: // Test on user split m_Log.statusMessage("Evaluating on test data..."); eval = new Evaluation(inst, costMatrix); // make adjustments if the classifier is an InputMappedClassifier eval = setupEval(eval, classifier, inst, costMatrix, plotInstances, classificationOutput, false); plotInstances.setInstances(userTestStructure); eval.setMetricsToDisplay(m_selectedEvalMetrics); // plotInstances.setEvaluation(eval); plotInstances.setUp(); if (outputPredictionsText) { printPredictionsHeader(outBuff, classificationOutput, "test set"); } Instance instance; int jj = 0; Instances batchInst = null; int batchSize = 100; if (classifier instanceof BatchPredictor && ((BatchPredictor) classifier) .implementsMoreEfficientBatchPrediction()) { batchInst = new Instances(userTestStructure, 0); String batchSizeS = ((BatchPredictor) classifier).getBatchSize(); if (batchSizeS != null && batchSizeS.length() > 0) { try { batchSizeS = Environment.getSystemWide().substitute(batchSizeS); } catch (Exception ex) { } try { batchSize = Integer.parseInt(batchSizeS); } catch (NumberFormatException ex) { // just go with the default } } } testTimeStart = System.currentTimeMillis(); while (source.hasMoreElements(userTestStructure)) { instance = source.nextElement(userTestStructure); if (classifier instanceof BatchPredictor && ((BatchPredictor) classifier) .implementsMoreEfficientBatchPrediction()) { batchInst.add(instance); if (batchInst.numInstances() == batchSize) { Instances toPred = new Instances(batchInst); for (int i = 0; i < toPred.numInstances(); i++) { toPred.instance(i).setClassMissing(); } double[][] predictions = ((BatchPredictor) classifier) .distributionsForInstances(toPred); plotInstances.process(batchInst, predictions, eval); if (outputPredictionsText) { for (int kk = 0; kk < batchInst.numInstances(); kk++) { classificationOutput.printClassification( predictions[kk], batchInst.instance(kk), kk); } } jj += batchInst.numInstances(); m_Log.statusMessage("Evaluating on test data. Processed " + jj + " instances..."); batchInst.delete(); } } else { plotInstances.process(instance, classifier, eval); if (outputPredictionsText) { classificationOutput.printClassification(classifier, instance, jj); } if ((++jj % 100) == 0) { m_Log.statusMessage("Evaluating on test data. Processed " + jj + " instances..."); } } } if (classifier instanceof BatchPredictor && ((BatchPredictor) classifier) .implementsMoreEfficientBatchPrediction() && batchInst.numInstances() > 0) { // finish the last batch Instances toPred = new Instances(batchInst); for (int i = 0; i < toPred.numInstances(); i++) { toPred.instance(i).setClassMissing(); } double[][] predictions = ((BatchPredictor) classifier) .distributionsForInstances(toPred); plotInstances.process(batchInst, predictions, eval); if (outputPredictionsText) { for (int kk = 0; kk < batchInst.numInstances(); kk++) { classificationOutput.printClassification(predictions[kk], batchInst.instance(kk), kk); } } } testTimeElapsed = System.currentTimeMillis() - testTimeStart; if (outputPredictionsText) { classificationOutput.printFooter(); } if (outputPredictionsText) { outBuff.append("\n"); } outBuff.append("=== Evaluation on test set ===\n"); break; default: throw new Exception("Test mode not implemented"); } if (testMode != 1) { String mode = ""; if (testMode == 2) { mode = "test split"; } else if (testMode == 3) { mode = "training data"; } else if (testMode == 4) { mode = "supplied test set"; } outBuff.append("\nTime taken to test model on " + mode + ": " + Utils.doubleToString(testTimeElapsed / 1000.0, 2) + " seconds\n\n"); } if (outputSummary) { outBuff.append(eval.toSummaryString(outputEntropy) + "\n"); } if (inst.attribute(classIndex).isNominal()) { if (outputPerClass) { outBuff.append(eval.toClassDetailsString() + "\n"); } if (outputConfusion) { outBuff.append(eval.toMatrixString() + "\n"); } } if ((fullClassifier instanceof Sourcable) && m_OutputSourceCode.isSelected()) { outBuff.append("=== Source code ===\n\n"); outBuff.append(Evaluation.wekaStaticWrapper( ((Sourcable) fullClassifier), m_SourceCodeClass.getText())); } m_History.updateResult(name); m_Log.logMessage("Finished " + cname); m_Log.statusMessage("OK"); } catch (Exception ex) { ex.printStackTrace(); m_Log.logMessage(ex.getMessage()); JOptionPane.showMessageDialog(ClassifierPanel.this, "Problem evaluating classifier:\n" + ex.getMessage(), "Evaluate classifier", JOptionPane.ERROR_MESSAGE); m_Log.statusMessage("Problem evaluating classifier"); } finally { try { if (!saveVis && outputModel) { ArrayList<Object> vv = new ArrayList<Object>(); vv.add(fullClassifier); Instances trainHeader = new Instances(m_Instances, 0); trainHeader.setClassIndex(classIndex); vv.add(trainHeader); if (grph != null) { vv.add(grph); } m_History.addObject(name, vv); } else if (saveVis && plotInstances != null && plotInstances.canPlot(false)) { m_CurrentVis = new VisualizePanel(); if (getMainApplication() != null) { Settings settings = getMainApplication().getApplicationSettings(); m_CurrentVis.applySettings(settings, weka.gui.explorer.VisualizePanel.ScatterDefaults.ID); } m_CurrentVis.setName(name + " (" + inst.relationName() + ")"); m_CurrentVis.setLog(m_Log); m_CurrentVis.addPlot(plotInstances.getPlotData(cname)); // m_CurrentVis.setColourIndex(plotInstances.getPlotInstances().classIndex()+1); m_CurrentVis.setColourIndex(plotInstances.getPlotInstances() .classIndex()); plotInstances.cleanUp(); ArrayList<Object> vv = new ArrayList<Object>(); if (outputModel) { vv.add(fullClassifier); Instances trainHeader = new Instances(m_Instances, 0); trainHeader.setClassIndex(classIndex); vv.add(trainHeader); if (grph != null) { vv.add(grph); } } vv.add(m_CurrentVis); if ((eval != null) && (eval.predictions() != null)) { vv.add(eval.predictions()); vv.add(inst.classAttribute()); } m_History.addObject(name, vv); } } catch (Exception ex) { ex.printStackTrace(); } if (isInterrupted()) { m_Log.logMessage("Interrupted " + cname); m_Log.statusMessage("Interrupted"); } synchronized (this) { m_StartBut.setEnabled(true); m_StopBut.setEnabled(false); m_RunThread = null; } if (m_Log instanceof TaskLogger) { ((TaskLogger) m_Log).taskFinished(); } } } }; m_RunThread.setPriority(Thread.MIN_PRIORITY); m_RunThread.start(); } } /** * Handles constructing a popup menu with visualization options. * * @param names the name of the result history list entry clicked on by the * user * @param x the x coordinate for popping up the menu * @param y the y coordinate for popping up the menu */ @SuppressWarnings("unchecked") protected void visualize(List<String> names, int x, int y) { final List<String> selectedNames = names; JPopupMenu resultListMenu = new JPopupMenu(); JMenuItem visMainBuffer = new JMenuItem("View in main window"); if (selectedNames != null && selectedNames.size() == 1) { visMainBuffer.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m_History.setSingle(selectedNames.get(0)); } }); } else { visMainBuffer.setEnabled(false); } resultListMenu.add(visMainBuffer); JMenuItem visSepBuffer = new JMenuItem("View in separate window"); if (selectedNames != null && selectedNames.size() == 1) { visSepBuffer.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m_History.openFrame(selectedNames.get(0)); } }); } else { visSepBuffer.setEnabled(false); } resultListMenu.add(visSepBuffer); JMenuItem saveOutput = new JMenuItem("Save result buffer"); if (selectedNames != null && selectedNames.size() == 1) { saveOutput.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { saveBuffer(selectedNames.get(0)); } }); } else { saveOutput.setEnabled(false); } resultListMenu.add(saveOutput); JMenuItem deleteOutput = new JMenuItem("Delete result buffer(s)"); if (selectedNames != null) { deleteOutput.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m_History.removeResults(selectedNames); } }); } else { deleteOutput.setEnabled(false); } resultListMenu.add(deleteOutput); resultListMenu.addSeparator(); JMenuItem loadModel = new JMenuItem("Load model"); loadModel.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { loadClassifier(); } }); resultListMenu.add(loadModel); ArrayList<Object> o = null; if (selectedNames != null && selectedNames.size() == 1) { o = (ArrayList<Object>) m_History.getNamedObject(selectedNames.get(0)); } VisualizePanel temp_vp = null; String temp_grph = null; ArrayList<Prediction> temp_preds = null; Attribute temp_classAtt = null; Classifier temp_classifier = null; Instances temp_trainHeader = null; if (o != null) { for (int i = 0; i < o.size(); i++) { Object temp = o.get(i); if (temp instanceof Classifier) { temp_classifier = (Classifier) temp; } else if (temp instanceof Instances) { // training header temp_trainHeader = (Instances) temp; } else if (temp instanceof VisualizePanel) { // normal errors temp_vp = (VisualizePanel) temp; } else if (temp instanceof String) { // graphable output temp_grph = (String) temp; } else if (temp instanceof ArrayList<?>) { // predictions temp_preds = (ArrayList<Prediction>) temp; } else if (temp instanceof Attribute) { // class attribute temp_classAtt = (Attribute) temp; } } } final VisualizePanel vp = temp_vp; final String grph = temp_grph; final ArrayList<Prediction> preds = temp_preds; final Attribute classAtt = temp_classAtt; final Classifier classifier = temp_classifier; final Instances trainHeader = temp_trainHeader; JMenuItem saveModel = new JMenuItem("Save model"); if (classifier != null && selectedNames != null && selectedNames.size() == 1) { saveModel.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { saveClassifier(selectedNames.get(0), classifier, trainHeader); } }); } else { saveModel.setEnabled(false); } resultListMenu.add(saveModel); JMenuItem reEvaluate = new JMenuItem("Re-evaluate model on current test set"); if (classifier != null && m_TestLoader != null && selectedNames != null && selectedNames.size() == 1) { reEvaluate.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { reevaluateModel(selectedNames.get(0), classifier, trainHeader); } }); } else { reEvaluate.setEnabled(false); } resultListMenu.add(reEvaluate); JMenuItem reApplyConfig = new JMenuItem("Re-apply this model's configuration"); if (classifier != null && selectedNames != null && selectedNames.size() == 1) { reApplyConfig.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m_ClassifierEditor.setValue(classifier); } }); } else { reApplyConfig.setEnabled(false); } resultListMenu.add(reApplyConfig); resultListMenu.addSeparator(); JMenuItem visErrors = new JMenuItem("Visualize classifier errors"); if (vp != null) { if ((vp.getXIndex() == 0) && (vp.getYIndex() == 1)) { try { vp.setXIndex(vp.getInstances().classIndex()); // class vp.setYIndex(vp.getInstances().classIndex() - 1); // predicted class } catch (Exception e) { // ignored } } visErrors.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { visualizeClassifierErrors(vp); } }); } else { visErrors.setEnabled(false); } resultListMenu.add(visErrors); JMenuItem visGrph = new JMenuItem("Visualize tree"); if (grph != null) { if (((Drawable) temp_classifier).graphType() == Drawable.TREE) { visGrph.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String title; if (vp != null) { title = vp.getName(); } else { title = selectedNames.get(0); } visualizeTree(grph, title); } }); } else if (((Drawable) temp_classifier).graphType() == Drawable.BayesNet) { visGrph.setText("Visualize graph"); visGrph.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Thread th = new Thread() { @Override public void run() { visualizeBayesNet(grph, selectedNames.get(0)); } }; th.start(); } }); } else { visGrph.setEnabled(false); } } else { visGrph.setEnabled(false); } resultListMenu.add(visGrph); JMenuItem visMargin = new JMenuItem("Visualize margin curve"); if ((preds != null) && (classAtt != null) && (classAtt.isNominal())) { visMargin.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { MarginCurve tc = new MarginCurve(); Instances result = tc.getCurve(preds); VisualizePanel vmc = new VisualizePanel(); if (getMainApplication() != null) { Settings settings = getMainApplication().getApplicationSettings(); m_CurrentVis.applySettings(settings, weka.gui.explorer.VisualizePanel.ScatterDefaults.ID); } vmc.setName(result.relationName()); vmc.setLog(m_Log); PlotData2D tempd = new PlotData2D(result); tempd.setPlotName(result.relationName()); tempd.addInstanceNumberAttribute(); vmc.addPlot(tempd); visualizeClassifierErrors(vmc); } catch (Exception ex) { ex.printStackTrace(); } } }); } else { visMargin.setEnabled(false); } resultListMenu.add(visMargin); JMenu visThreshold = new JMenu("Visualize threshold curve"); if ((preds != null) && (classAtt != null) && (classAtt.isNominal())) { for (int i = 0; i < classAtt.numValues(); i++) { JMenuItem clv = new JMenuItem(classAtt.value(i)); final int classValue = i; clv.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { ThresholdCurve tc = new ThresholdCurve(); Instances result = tc.getCurve(preds, classValue); // VisualizePanel vmc = new VisualizePanel(); ThresholdVisualizePanel vmc = new ThresholdVisualizePanel(); vmc.setROCString("(Area under ROC = " + Utils.doubleToString(ThresholdCurve.getROCArea(result), 4) + ")"); vmc.setLog(m_Log); vmc.setName(result.relationName() + ". (Class value " + classAtt.value(classValue) + ")"); PlotData2D tempd = new PlotData2D(result); tempd.setPlotName(result.relationName()); tempd.addInstanceNumberAttribute(); // specify which points are connected boolean[] cp = new boolean[result.numInstances()]; for (int n = 1; n < cp.length; n++) { cp[n] = true; } tempd.setConnectPoints(cp); // add plot vmc.addPlot(tempd); visualizeClassifierErrors(vmc); } catch (Exception ex) { ex.printStackTrace(); } } }); visThreshold.add(clv); } } else { visThreshold.setEnabled(false); } resultListMenu.add(visThreshold); JMenu visCostBenefit = new JMenu("Cost/Benefit analysis"); if ((preds != null) && (classAtt != null) && (classAtt.isNominal())) { for (int i = 0; i < classAtt.numValues(); i++) { JMenuItem clv = new JMenuItem(classAtt.value(i)); final int classValue = i; clv.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { ThresholdCurve tc = new ThresholdCurve(); Instances result = tc.getCurve(preds, classValue); // Create a dummy class attribute with the chosen // class value as index 0 (if necessary). Attribute classAttToUse = classAtt; if (classValue != 0) { ArrayList<String> newNames = new ArrayList<String>(); newNames.add(classAtt.value(classValue)); for (int k = 0; k < classAtt.numValues(); k++) { if (k != classValue) { newNames.add(classAtt.value(k)); } } classAttToUse = new Attribute(classAtt.name(), newNames); } CostBenefitAnalysis cbAnalysis = new CostBenefitAnalysis(); PlotData2D tempd = new PlotData2D(result); tempd.setPlotName(result.relationName()); tempd.m_alwaysDisplayPointsOfThisSize = 10; // specify which points are connected boolean[] cp = new boolean[result.numInstances()]; for (int n = 1; n < cp.length; n++) { cp[n] = true; } tempd.setConnectPoints(cp); String windowTitle = ""; if (classifier != null) { String cname = classifier.getClass().getName(); if (cname.startsWith("weka.classifiers.")) { windowTitle = "" + cname.substring("weka.classifiers.".length()) + " "; } } windowTitle += " (class = " + classAttToUse.value(0) + ")"; // add plot cbAnalysis.setCurveData(tempd, classAttToUse); visualizeCostBenefitAnalysis(cbAnalysis, windowTitle); } catch (Exception ex) { ex.printStackTrace(); } } }); visCostBenefit.add(clv); } } else { visCostBenefit.setEnabled(false); } resultListMenu.add(visCostBenefit); JMenu visCost = new JMenu("Visualize cost curve"); if ((preds != null) && (classAtt != null) && (classAtt.isNominal())) { for (int i = 0; i < classAtt.numValues(); i++) { JMenuItem clv = new JMenuItem(classAtt.value(i)); final int classValue = i; clv.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { CostCurve cc = new CostCurve(); Instances result = cc.getCurve(preds, classValue); VisualizePanel vmc = new VisualizePanel(); if (getMainApplication() != null) { Settings settings = getMainApplication().getApplicationSettings(); m_CurrentVis.applySettings(settings, weka.gui.explorer.VisualizePanel.ScatterDefaults.ID); } vmc.setLog(m_Log); vmc.setName(result.relationName() + ". (Class value " + classAtt.value(classValue) + ")"); PlotData2D tempd = new PlotData2D(result); tempd.m_displayAllPoints = true; tempd.setPlotName(result.relationName()); boolean[] connectPoints = new boolean[result.numInstances()]; for (int jj = 1; jj < connectPoints.length; jj += 2) { connectPoints[jj] = true; } tempd.setConnectPoints(connectPoints); // tempd.addInstanceNumberAttribute(); vmc.addPlot(tempd); visualizeClassifierErrors(vmc); } catch (Exception ex) { ex.printStackTrace(); } } }); visCost.add(clv); } } else { visCost.setEnabled(false); } resultListMenu.add(visCost); // visualization plugins JMenu visPlugins = new JMenu("Plugins"); boolean availablePlugins = false; // predictions List<String> pluginsVector = PluginManager.getPluginNamesOfTypeList(VisualizePlugin.class.getName()); for (int i = 0; i < pluginsVector.size(); i++) { String className = (pluginsVector.get(i)); try { VisualizePlugin plugin = (VisualizePlugin) WekaPackageClassLoaderManager .objectForName(className); // (VisualizePlugin) Class.forName(className).newInstance(); if (plugin == null) { continue; } availablePlugins = true; JMenuItem pluginMenuItem = plugin.getVisualizeMenuItem(preds, classAtt); new Version(); if (pluginMenuItem != null) { /* * if (version.compareTo(plugin.getMinVersion()) < 0) * pluginMenuItem.setText(pluginMenuItem.getText() + * " (weka outdated)"); if (version.compareTo(plugin.getMaxVersion()) * >= 0) pluginMenuItem.setText(pluginMenuItem.getText() + * " (plugin outdated)"); */ visPlugins.add(pluginMenuItem); } } catch (Exception e) { // e.printStackTrace(); } } // errros pluginsVector = PluginManager.getPluginNamesOfTypeList(ErrorVisualizePlugin.class.getName()); for (int i = 0; i < pluginsVector.size(); i++) { String className = (pluginsVector.get(i)); try { ErrorVisualizePlugin plugin = (ErrorVisualizePlugin) WekaPackageClassLoaderManager .objectForName(className); // (ErrorVisualizePlugin) Class.forName(className).newInstance(); if (plugin == null) { continue; } availablePlugins = true; JMenuItem pluginMenuItem = plugin.getVisualizeMenuItem(vp.getInstances()); new Version(); if (pluginMenuItem != null) { /* * if (version.compareTo(plugin.getMinVersion()) < 0) * pluginMenuItem.setText(pluginMenuItem.getText() + * " (weka outdated)"); if (version.compareTo(plugin.getMaxVersion()) * >= 0) pluginMenuItem.setText(pluginMenuItem.getText() + * " (plugin outdated)"); */ visPlugins.add(pluginMenuItem); } } catch (Exception e) { // e.printStackTrace(); } } // graphs+trees if (grph != null) { // trees if (((Drawable) temp_classifier).graphType() == Drawable.TREE) { pluginsVector = PluginManager.getPluginNamesOfTypeList(TreeVisualizePlugin.class.getName()); for (int i = 0; i < pluginsVector.size(); i++) { String className = (pluginsVector.get(i)); try { TreeVisualizePlugin plugin = (TreeVisualizePlugin) WekaPackageClassLoaderManager .objectForName(className); // (TreeVisualizePlugin) Class.forName(className).newInstance(); if (plugin == null) { continue; } availablePlugins = true; JMenuItem pluginMenuItem = plugin.getVisualizeMenuItem(grph, selectedNames.get(0)); new Version(); if (pluginMenuItem != null) { /* * if (version.compareTo(plugin.getMinVersion()) < 0) * pluginMenuItem.setText(pluginMenuItem.getText() + * " (weka outdated)"); if * (version.compareTo(plugin.getMaxVersion()) >= 0) * pluginMenuItem.setText(pluginMenuItem.getText() + * " (plugin outdated)"); */ visPlugins.add(pluginMenuItem); } } catch (Exception e) { // e.printStackTrace(); } } } // graphs else { pluginsVector = PluginManager.getPluginNamesOfTypeList(GraphVisualizePlugin.class.getName()); for (int i = 0; i < pluginsVector.size(); i++) { String className = (pluginsVector.get(i)); try { GraphVisualizePlugin plugin = (GraphVisualizePlugin) WekaPackageClassLoaderManager .objectForName(className); // (GraphVisualizePlugin) Class.forName(className).newInstance(); if (plugin == null) { continue; } availablePlugins = true; JMenuItem pluginMenuItem = plugin.getVisualizeMenuItem(grph, selectedNames.get(0)); new Version(); if (pluginMenuItem != null) { /* * if (version.compareTo(plugin.getMinVersion()) < 0) * pluginMenuItem.setText(pluginMenuItem.getText() + * " (weka outdated)"); if * (version.compareTo(plugin.getMaxVersion()) >= 0) * pluginMenuItem.setText(pluginMenuItem.getText() + * " (plugin outdated)"); */ visPlugins.add(pluginMenuItem); } } catch (Exception e) { // e.printStackTrace(); } } } } if (availablePlugins) { resultListMenu.add(visPlugins); } resultListMenu.show(m_History.getList(), x, y); } /** * Pops up a TreeVisualizer for the classifier from the currently selected * item in the results list. * * @param dottyString the description of the tree in dotty format * @param treeName the title to assign to the display */ protected void visualizeTree(String dottyString, String treeName) { final javax.swing.JFrame jf = Utils.getWekaJFrame("Weka Classifier Tree Visualizer: " + treeName, this); jf.setSize(500, 400); jf.getContentPane().setLayout(new BorderLayout()); TreeVisualizer tv = new TreeVisualizer(null, dottyString, new PlaceNode2()); jf.getContentPane().add(tv, BorderLayout.CENTER); jf.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { jf.dispose(); } }); jf.pack(); jf.setSize(800, 600); jf.setLocationRelativeTo(SwingUtilities.getWindowAncestor(this)); jf.setVisible(true); tv.fitToScreen(); } /** * Pops up a GraphVisualizer for the BayesNet classifier from the currently * selected item in the results list. * * @param XMLBIF the description of the graph in XMLBIF ver. 0.3 * @param graphName the name of the graph */ protected void visualizeBayesNet(String XMLBIF, String graphName) { final javax.swing.JFrame jf = Utils.getWekaJFrame("Weka Classifier Graph Visualizer: " + graphName, this); jf.setSize(500, 400); jf.getContentPane().setLayout(new BorderLayout()); GraphVisualizer gv = new GraphVisualizer(); try { gv.readBIF(XMLBIF); } catch (BIFFormatException be) { System.err.println("unable to visualize BayesNet"); be.printStackTrace(); } gv.layoutGraph(); jf.getContentPane().add(gv, BorderLayout.CENTER); jf.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { jf.dispose(); } }); jf.pack(); jf.setSize(800, 600); jf.setLocationRelativeTo(SwingUtilities.getWindowAncestor(this)); jf.setVisible(true); } /** * Pops up the Cost/Benefit analysis panel. * * @param cb the CostBenefitAnalysis panel to pop up */ protected void visualizeCostBenefitAnalysis(CostBenefitAnalysis cb, String classifierAndRelationName) { if (cb != null) { String windowTitle = "Weka Classifier: Cost/Benefit Analysis "; if (classifierAndRelationName != null) { windowTitle += "- " + classifierAndRelationName; } final javax.swing.JFrame jf = Utils.getWekaJFrame(windowTitle, this); jf.getContentPane().setLayout(new BorderLayout()); jf.getContentPane().add(cb, BorderLayout.CENTER); jf.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { jf.dispose(); } }); jf.pack(); jf.setSize(1024, 700); jf.setLocationRelativeTo(SwingUtilities.getWindowAncestor(this)); jf.setVisible(true); } } /** * Pops up a VisualizePanel for visualizing the data and errors for the * classifier from the currently selected item in the results list. * * @param sp the VisualizePanel to pop up. */ protected void visualizeClassifierErrors(VisualizePanel sp) { if (sp != null) { String plotName = sp.getName(); final javax.swing.JFrame jf = Utils.getWekaJFrame("Weka Classifier Visualize: " + plotName, this); jf.getContentPane().setLayout(new BorderLayout()); jf.getContentPane().add(sp, BorderLayout.CENTER); jf.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { jf.dispose(); } }); jf.pack(); jf.setSize(800, 600); jf.setLocationRelativeTo(SwingUtilities.getWindowAncestor(this)); jf.setVisible(true); } } /** * Save the currently selected classifier output to a file. * * @param name the name of the buffer to save */ protected void saveBuffer(String name) { StringBuffer sb = m_History.getNamedBuffer(name); if (sb != null) { if (m_SaveOut.save(sb)) { m_Log.logMessage("Save successful."); } } } /** * Stops the currently running classifier (if any). */ @SuppressWarnings("deprecation") protected void stopClassifier() { if (m_RunThread != null) { m_RunThread.interrupt(); // This is deprecated (and theoretically the interrupt should do). m_RunThread.stop(); } } /** * Saves the currently selected classifier. * * @param name the name of the run * @param classifier the classifier to save * @param trainHeader the header of the training instances */ public void saveClassifier(String name, Classifier classifier, Instances trainHeader) { File sFile = null; boolean saveOK = true; m_FileChooser.removeChoosableFileFilter(m_PMMLModelFilter); m_FileChooser.setFileFilter(m_ModelFilter); int returnVal = m_FileChooser.showSaveDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { sFile = m_FileChooser.getSelectedFile(); if (!sFile.getName().toLowerCase().endsWith(MODEL_FILE_EXTENSION)) { sFile = new File(sFile.getParent(), sFile.getName() + MODEL_FILE_EXTENSION); } m_Log.statusMessage("Saving model to file..."); try { OutputStream os = new FileOutputStream(sFile); if (sFile.getName().endsWith(".gz")) { os = new GZIPOutputStream(os); } ObjectOutputStream objectOutputStream = new ObjectOutputStream(os); objectOutputStream.writeObject(classifier); trainHeader = trainHeader.stringFreeStructure(); if (trainHeader != null) { objectOutputStream.writeObject(trainHeader); } objectOutputStream.flush(); objectOutputStream.close(); } catch (Exception e) { JOptionPane.showMessageDialog(null, e, "Save Failed", JOptionPane.ERROR_MESSAGE); saveOK = false; } if (saveOK) { m_Log.logMessage("Saved model (" + name + ") to file '" + sFile.getName() + "'"); } m_Log.statusMessage("OK"); } } /** * Loads a classifier. */ protected void loadClassifier() { m_FileChooser.addChoosableFileFilter(m_PMMLModelFilter); m_FileChooser.setFileFilter(m_ModelFilter); int returnVal = m_FileChooser.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { File selected = m_FileChooser.getSelectedFile(); Classifier classifier = null; Instances trainHeader = null; m_Log.statusMessage("Loading model from file..."); try { InputStream is = new FileInputStream(selected); if (selected.getName().endsWith(PMML_FILE_EXTENSION)) { PMMLModel model = PMMLFactory.getPMMLModel(is, m_Log); if (model instanceof PMMLClassifier) { classifier = (PMMLClassifier) model; /* * trainHeader = ((PMMLClassifier)classifier).getMiningSchema(). * getMiningSchemaAsInstances(); */ } else { throw new Exception( "PMML model is not a classification/regression model!"); } } else { if (selected.getName().endsWith(".gz")) { is = new GZIPInputStream(is); } // ObjectInputStream objectInputStream = new ObjectInputStream(is); ObjectInputStream objectInputStream = SerializationHelper.getObjectInputStream(is); classifier = (Classifier) objectInputStream.readObject(); try { // see if we can load the header trainHeader = (Instances) objectInputStream.readObject(); } catch (Exception e) { } // don't fuss if we can't objectInputStream.close(); } } catch (Exception e) { JOptionPane.showMessageDialog(null, e, "Load Failed", JOptionPane.ERROR_MESSAGE); } m_Log.statusMessage("OK"); if (classifier != null) { m_Log.logMessage("Loaded model from file '" + selected.getName() + "'"); String name = (new SimpleDateFormat("HH:mm:ss - ")).format(new Date()); String cname = classifier.getClass().getName(); if (cname.startsWith("weka.classifiers.")) { cname = cname.substring("weka.classifiers.".length()); } name += cname + " from file '" + selected.getName() + "'"; StringBuffer outBuff = new StringBuffer(); outBuff.append("=== Model information ===\n\n"); outBuff.append("Filename: " + selected.getName() + "\n"); outBuff.append("Scheme: " + classifier.getClass().getName()); if (classifier instanceof OptionHandler) { String[] o = ((OptionHandler) classifier).getOptions(); outBuff.append(" " + Utils.joinOptions(o)); } outBuff.append("\n"); if (trainHeader != null) { outBuff.append("Relation: " + trainHeader.relationName() + '\n'); outBuff.append("Attributes: " + trainHeader.numAttributes() + '\n'); if (trainHeader.numAttributes() < 100) { for (int i = 0; i < trainHeader.numAttributes(); i++) { outBuff.append(" " + trainHeader.attribute(i).name() + '\n'); } } else { outBuff.append(" [list of attributes omitted]\n"); } } else { outBuff.append("\nTraining data unknown\n"); } outBuff.append("\n=== Classifier model ===\n\n"); outBuff.append(classifier.toString() + "\n"); m_History.addResult(name, outBuff); m_History.setSingle(name); ArrayList<Object> vv = new ArrayList<Object>(); vv.add(classifier); if (trainHeader != null) { vv.add(trainHeader); } // allow visualization of graphable classifiers String grph = null; if (classifier instanceof Drawable) { try { grph = ((Drawable) classifier).graph(); } catch (Exception ex) { } } if (grph != null) { vv.add(grph); } m_History.addObject(name, vv); } } } /** * Re-evaluates the named classifier with the current test set. Unpredictable * things will happen if the data set is not compatible with the classifier. * * @param name the name of the classifier entry * @param classifier the classifier to evaluate * @param trainHeader the header of the training set */ protected void reevaluateModel(final String name, final Classifier classifier, final Instances trainHeader) { if (m_RunThread == null) { synchronized (this) { m_StartBut.setEnabled(false); m_StopBut.setEnabled(true); } m_RunThread = new Thread() { @Override public void run() { // Copy the current state of things m_Log.statusMessage("Setting up..."); Classifier classifierToUse = classifier; StringBuffer outBuff = m_History.getNamedBuffer(name); DataSource source = null; Instances userTestStructure = null; ClassifierErrorsPlotInstances plotInstances = null; CostMatrix costMatrix = null; if (m_EvalWRTCostsBut.isSelected()) { costMatrix = new CostMatrix((CostMatrix) m_CostMatrixEditor.getValue()); } boolean outputConfusion = m_OutputConfusionBut.isSelected(); boolean outputPerClass = m_OutputPerClassBut.isSelected(); boolean outputSummary = true; boolean outputEntropy = m_OutputEntropyBut.isSelected(); boolean saveVis = m_StorePredictionsBut.isSelected(); boolean outputPredictionsText = (m_ClassificationOutputEditor.getValue().getClass() != Null.class); String grph = null; Evaluation eval = null; try { boolean incrementalLoader = (m_TestLoader instanceof IncrementalConverter); if (m_TestLoader != null && m_TestLoader.getStructure() != null) { m_TestLoader.reset(); if (classifierToUse instanceof BatchPredictor && ((BatchPredictor) classifierToUse) .implementsMoreEfficientBatchPrediction() && m_TestLoader instanceof ArffLoader) { ((ArffLoader) m_TestLoader).setRetainStringVals(true); } source = new DataSource(m_TestLoader); userTestStructure = source.getStructure(); userTestStructure.setClassIndex(m_TestClassIndex); } // Check the test instance compatibility if (source == null) { throw new Exception("No user test set has been specified"); } if (trainHeader != null) { if (!trainHeader.equalHeaders(userTestStructure)) { if (!(classifierToUse instanceof weka.classifiers.misc.InputMappedClassifier)) { boolean wrapClassifier = false; if (!Utils .getDontShowDialog("weka.gui.explorer.ClassifierPanel.AutoWrapInInputMappedClassifier")) { JCheckBox dontShow = new JCheckBox("Do not show this message again"); Object[] stuff = new Object[2]; stuff[0] = "Data used to train model and test set are not compatible.\n" + "Would you like to automatically wrap the classifier in\n" + "an \"InputMappedClassifier\" before proceeding?.\n"; stuff[1] = dontShow; int result = JOptionPane.showConfirmDialog(ClassifierPanel.this, stuff, "ClassifierPanel", JOptionPane.YES_OPTION); if (result == JOptionPane.YES_OPTION) { wrapClassifier = true; } if (dontShow.isSelected()) { String response = (wrapClassifier) ? "yes" : "no"; Utils .setDontShowDialogResponse( "weka.gui.explorer.ClassifierPanel.AutoWrapInInputMappedClassifier", response); } } else { // What did the user say - do they want to autowrap or not? String response = Utils .getDontShowDialogResponse("weka.gui.explorer.ClassifierPanel.AutoWrapInInputMappedClassifier"); if (response != null && response.equalsIgnoreCase("yes")) { wrapClassifier = true; } } if (wrapClassifier) { weka.classifiers.misc.InputMappedClassifier temp = new weka.classifiers.misc.InputMappedClassifier(); temp.setClassifier(classifierToUse); temp.setModelHeader(trainHeader); temp.setTestStructure(userTestStructure); classifierToUse = temp; } else { throw new Exception( "Train and test set are not compatible\n" + trainHeader.equalHeadersMsg(userTestStructure)); } } } } else { if (classifierToUse instanceof PMMLClassifier) { // set the class based on information in the mining schema Instances miningSchemaStructure = ((PMMLClassifier) classifierToUse).getMiningSchema() .getMiningSchemaAsInstances(); String className = miningSchemaStructure.classAttribute().name(); Attribute classMatch = userTestStructure.attribute(className); if (classMatch == null) { throw new Exception( "Can't find a match for the PMML target field " + className + " in the " + "test instances!"); } userTestStructure.setClass(classMatch); } else { userTestStructure.setClassIndex(userTestStructure .numAttributes() - 1); } } if (m_Log instanceof TaskLogger) { ((TaskLogger) m_Log).taskStarted(); } m_Log.statusMessage("Evaluating on test data..."); m_Log.logMessage("Re-evaluating classifier (" + name + ") on test set"); eval = new Evaluation(userTestStructure, costMatrix); eval.setMetricsToDisplay(m_selectedEvalMetrics); // set up the structure of the plottable instances for // visualization if selected // if (saveVis) { plotInstances = ExplorerDefaults.getClassifierErrorsPlotInstances(); plotInstances.setInstances(trainHeader != null ? trainHeader : userTestStructure); plotInstances.setClassifier(classifierToUse); plotInstances.setClassIndex(trainHeader != null ? trainHeader .classIndex() : userTestStructure.classIndex()); plotInstances.setSaveForVisualization(saveVis); plotInstances.setEvaluation(eval); outBuff.append("\n=== Re-evaluation on test set ===\n\n"); outBuff.append("User supplied test set\n"); outBuff.append("Relation: " + userTestStructure.relationName() + '\n'); if (incrementalLoader) { outBuff .append("Instances: unknown (yet). Reading incrementally\n"); } else { outBuff.append("Instances: " + source.getDataSet().numInstances() + "\n"); } outBuff.append("Attributes: " + userTestStructure.numAttributes() + "\n\n"); if (trainHeader == null && !(classifierToUse instanceof weka.classifiers.pmml.consumer.PMMLClassifier)) { outBuff .append("NOTE - if test set is not compatible then results are " + "unpredictable\n\n"); } AbstractOutput classificationOutput = null; if (outputPredictionsText) { classificationOutput = (AbstractOutput) m_ClassificationOutputEditor.getValue(); classificationOutput.setHeader(userTestStructure); classificationOutput.setBuffer(outBuff); } // make adjustments if the classifier is an InputMappedClassifier eval = setupEval(eval, classifierToUse, trainHeader != null ? trainHeader : userTestStructure, costMatrix, plotInstances, classificationOutput, false); eval.useNoPriors(); plotInstances.setUp(); if (outputPredictionsText) { printPredictionsHeader(outBuff, classificationOutput, "user test set"); } int batchSize = 100; Instances batchInst = null; if (classifierToUse instanceof BatchPredictor && ((BatchPredictor) classifierToUse) .implementsMoreEfficientBatchPrediction()) { batchInst = new Instances(userTestStructure, 0); String batchSizeS = ((BatchPredictor) classifierToUse).getBatchSize(); if (batchSizeS != null && batchSizeS.length() > 0) { try { batchSizeS = Environment.getSystemWide().substitute(batchSizeS); } catch (Exception ex) { } try { batchSize = Integer.parseInt(batchSizeS); } catch (NumberFormatException e) { // just go with the default } } } Instance instance; int jj = 0; while (source.hasMoreElements(userTestStructure)) { instance = source.nextElement(userTestStructure); if (classifierToUse instanceof BatchPredictor && ((BatchPredictor) classifierToUse) .implementsMoreEfficientBatchPrediction()) { batchInst.add(instance); if (batchInst.numInstances() == batchSize) { Instances toPred = new Instances(batchInst); for (int i = 0; i < toPred.numInstances(); i++) { toPred.instance(i).setClassMissing(); } double[][] predictions = ((BatchPredictor) classifierToUse) .distributionsForInstances(toPred); plotInstances.process(batchInst, predictions, eval); if (outputPredictionsText) { for (int kk = 0; kk < batchInst.numInstances(); kk++) { classificationOutput.printClassification(predictions[kk], batchInst.instance(kk), kk); } } jj += batchInst.numInstances(); m_Log.statusMessage("Evaluating on test data. Processed " + jj + " instances..."); batchInst.delete(); } } else { plotInstances.process(instance, classifierToUse, eval); if (outputPredictionsText) { classificationOutput.printClassification(classifierToUse, instance, jj); } } if ((++jj % 100) == 0) { m_Log.statusMessage("Evaluating on test data. Processed " + jj + " instances..."); } } if (classifierToUse instanceof BatchPredictor && ((BatchPredictor) classifierToUse) .implementsMoreEfficientBatchPrediction() && batchInst.numInstances() > 0) { // finish the last batch Instances toPred = new Instances(batchInst); for (int i = 0; i < toPred.numInstances(); i++) { toPred.instance(i).setClassMissing(); } double[][] predictions = ((BatchPredictor) classifierToUse) .distributionsForInstances(toPred); plotInstances.process(batchInst, predictions, eval); if (outputPredictionsText) { for (int kk = 0; kk < batchInst.numInstances(); kk++) { classificationOutput.printClassification(predictions[kk], batchInst.instance(kk), kk); } } } if (outputPredictionsText) { classificationOutput.printFooter(); } if (outputPredictionsText && classificationOutput.generatesOutput()) { outBuff.append("\n"); } if (outputSummary) { outBuff.append(eval.toSummaryString(outputEntropy) + "\n"); } if (userTestStructure.classAttribute().isNominal()) { if (outputPerClass) { outBuff.append(eval.toClassDetailsString() + "\n"); } if (outputConfusion) { outBuff.append(eval.toMatrixString() + "\n"); } } m_History.updateResult(name); m_Log.logMessage("Finished re-evaluation"); m_Log.statusMessage("OK"); } catch (Exception ex) { ex.printStackTrace(); m_Log.logMessage(ex.getMessage()); m_Log.statusMessage("See error log"); ex.printStackTrace(); m_Log.logMessage(ex.getMessage()); JOptionPane.showMessageDialog(ClassifierPanel.this, "Problem evaluating classifier:\n" + ex.getMessage(), "Evaluate classifier", JOptionPane.ERROR_MESSAGE); m_Log.statusMessage("Problem evaluating classifier"); } finally { try { if (classifierToUse instanceof PMMLClassifier) { // signal the end of the scoring run so // that the initialized state can be reset // (forces the field mapping to be recomputed // for the next scoring run). ((PMMLClassifier) classifierToUse).done(); } if (plotInstances != null && plotInstances.getPlotInstances() != null && plotInstances.getPlotInstances().numInstances() > 0) { m_CurrentVis = new VisualizePanel(); if (getMainApplication() != null) { Settings settings = getMainApplication().getApplicationSettings(); m_CurrentVis.applySettings(settings, weka.gui.explorer.VisualizePanel.ScatterDefaults.ID); } m_CurrentVis.setName(name + " (" + userTestStructure.relationName() + ")"); m_CurrentVis.setLog(m_Log); m_CurrentVis.addPlot(plotInstances.getPlotData(name)); // m_CurrentVis.setColourIndex(plotInstances.getPlotInstances().classIndex()+1); m_CurrentVis.setColourIndex(plotInstances.getPlotInstances() .classIndex()); plotInstances.cleanUp(); if (classifierToUse instanceof Drawable) { try { grph = ((Drawable) classifierToUse).graph(); } catch (Exception ex) { } } if (saveVis) { ArrayList<Object> vv = new ArrayList<Object>(); vv.add(classifier); if (trainHeader != null) { vv.add(trainHeader); } vv.add(m_CurrentVis); if (grph != null) { vv.add(grph); } if ((eval != null) && (eval.predictions() != null)) { vv.add(eval.predictions()); vv.add(userTestStructure.classAttribute()); } m_History.addOrOverwriteObject(name, vv); } else { ArrayList<Object> vv = new ArrayList<Object>(); vv.add(classifierToUse); if (trainHeader != null) { vv.add(trainHeader); } m_History.addOrOverwriteObject(name, vv); } } } catch (Exception ex) { ex.printStackTrace(); } if (isInterrupted()) { m_Log.logMessage("Interrupted reevaluate model"); m_Log.statusMessage("Interrupted"); } synchronized (this) { m_StartBut.setEnabled(true); m_StopBut.setEnabled(false); m_RunThread = null; } if (m_Log instanceof TaskLogger) { ((TaskLogger) m_Log).taskFinished(); } } } }; m_RunThread.setPriority(Thread.MIN_PRIORITY); m_RunThread.start(); } } /** * updates the capabilities filter of the GOE. * * @param filter the new filter to use */ protected void updateCapabilitiesFilter(Capabilities filter) { Instances tempInst; Capabilities filterClass; if (filter == null) { m_ClassifierEditor.setCapabilitiesFilter(new Capabilities(null)); return; } if (!ExplorerDefaults.getInitGenericObjectEditorFilter()) { tempInst = new Instances(m_Instances, 0); } else { tempInst = new Instances(m_Instances); } tempInst.setClassIndex(m_ClassCombo.getSelectedIndex()); try { filterClass = Capabilities.forInstances(tempInst); } catch (Exception e) { filterClass = new Capabilities(null); } // set new filter m_ClassifierEditor.setCapabilitiesFilter(filterClass); // Check capabilities m_StartBut.setEnabled(true); Capabilities currentFilter = m_ClassifierEditor.getCapabilitiesFilter(); Classifier classifier = (Classifier) m_ClassifierEditor.getValue(); Capabilities currentSchemeCapabilities = null; if (classifier != null && currentFilter != null && (classifier instanceof CapabilitiesHandler)) { currentSchemeCapabilities = ((CapabilitiesHandler) classifier).getCapabilities(); if (!currentSchemeCapabilities.supportsMaybe(currentFilter) && !currentSchemeCapabilities.supports(currentFilter)) { m_StartBut.setEnabled(false); } } } /** * method gets called in case of a change event. * * @param e the associated change event */ @Override public void capabilitiesFilterChanged(CapabilitiesFilterChangeEvent e) { if (e.getFilter() == null) { updateCapabilitiesFilter(null); } else { updateCapabilitiesFilter((Capabilities) e.getFilter().clone()); } } /** * Sets the Explorer to use as parent frame (used for sending notifications * about changes in the data). * * @param parent the parent frame */ @Override public void setExplorer(Explorer parent) { m_Explorer = parent; } /** * returns the parent Explorer frame. * * @return the parent */ @Override public Explorer getExplorer() { return m_Explorer; } /** * Returns the title for the tab in the Explorer. * * @return the title of this tab */ @Override public String getTabTitle() { return "Classify"; } /** * Returns the tooltip for the tab in the Explorer. * * @return the tooltip of this tab */ @Override public String getTabTitleToolTip() { return "Classify instances"; } @Override public boolean requiresLog() { return true; } @Override public boolean acceptsInstances() { return true; } @Override public Defaults getDefaultSettings() { return new ClassifierPanelDefaults(); } @Override public boolean okToBeActive() { return m_Instances != null; } @Override public void setActive(boolean active) { super.setActive(active); if (m_isActive) { // make sure initial settings get applied settingsChanged(); } } @Override public void settingsChanged() { if (getMainApplication() != null) { if (!m_initialSettingsSet) { Object initialC = getMainApplication().getApplicationSettings().getSetting( getPerspectiveID(), ClassifierPanelDefaults.CLASSIFIER_KEY, ClassifierPanelDefaults.CLASSIFIER, Environment.getSystemWide()); m_ClassifierEditor.setValue(initialC); TestMode initialTestMode = getMainApplication().getApplicationSettings().getSetting( getPerspectiveID(), ClassifierPanelDefaults.TEST_MODE_KEY, ClassifierPanelDefaults.TEST_MODE, Environment.getSystemWide()); m_CVBut.setSelected(initialTestMode == TestMode.CROSS_VALIDATION); m_PercentBut.setSelected(initialTestMode == TestMode.PERCENTAGE_SPLIT); m_TrainBut.setSelected(initialTestMode == TestMode.USE_TRAINING_SET); m_TestSplitBut .setSelected(initialTestMode == TestMode.SEPARATE_TEST_SET); m_CVText.setEnabled(m_CVBut.isSelected()); m_PercentText.setEnabled(m_PercentBut.isSelected()); m_CVText.setText("" + getMainApplication().getApplicationSettings().getSetting( getPerspectiveID(), ClassifierPanelDefaults.CROSS_VALIDATION_FOLDS_KEY, ClassifierPanelDefaults.CROSS_VALIDATION_FOLDS, Environment.getSystemWide())); m_PercentText.setText("" + getMainApplication().getApplicationSettings().getSetting( getPerspectiveID(), ClassifierPanelDefaults.PERCENTAGE_SPLIT_KEY, ClassifierPanelDefaults.PERCENTAGE_SPLIT, Environment.getSystemWide())); // TODO these widgets will disappear, as the "More options" dialog will // not be necessary m_OutputModelBut.setSelected(getMainApplication() .getApplicationSettings().getSetting(getPerspectiveID(), ClassifierPanelDefaults.OUTPUT_MODEL_KEY, ClassifierPanelDefaults.OUTPUT_MODEL, Environment.getSystemWide())); m_OutputModelsForTrainingSplitsBut.setSelected(getMainApplication() .getApplicationSettings().getSetting(getPerspectiveID(), ClassifierPanelDefaults.OUTPUT_MODELS_FOR_TRAINING_SPLITS_KEY, ClassifierPanelDefaults.OUTPUT_MODELS_FOR_TRAINING_SPLITS, Environment.getSystemWide())); m_OutputPerClassBut.setSelected(getMainApplication() .getApplicationSettings().getSetting(getPerspectiveID(), ClassifierPanelDefaults.OUTPUT_PER_CLASS_STATS_KEY, ClassifierPanelDefaults.OUTPUT_PER_CLASS_STATS, Environment.getSystemWide())); m_OutputEntropyBut.setSelected(getMainApplication() .getApplicationSettings().getSetting(getPerspectiveID(), ClassifierPanelDefaults.OUTPUT_ENTROPY_EVAL_METRICS_KEY, ClassifierPanelDefaults.OUTPUT_ENTROPY_EVAL_METRICS, Environment.getSystemWide())); m_OutputConfusionBut.setSelected(getMainApplication() .getApplicationSettings().getSetting(getPerspectiveID(), ClassifierPanelDefaults.OUTPUT_CONFUSION_MATRIX_KEY, ClassifierPanelDefaults.OUTPUT_CONFUSION_MATRIX, Environment.getSystemWide())); m_StorePredictionsBut.setSelected(getMainApplication() .getApplicationSettings().getSetting(getPerspectiveID(), ClassifierPanelDefaults.STORE_PREDICTIONS_FOR_VIS_KEY, ClassifierPanelDefaults.STORE_PREDICTIONS_FOR_VIS, Environment.getSystemWide())); m_errorPlotPointSizeProportionalToMargin .setSelected(getMainApplication().getApplicationSettings() .getSetting(getPerspectiveID(), ClassifierPanelDefaults.ERROR_PLOT_POINT_SIZE_PROP_TO_MARGIN_KEY, ClassifierPanelDefaults.ERROR_PLOT_POINT_SIZE_PROP_TO_MARGIN, Environment.getSystemWide())); m_RandomSeedText.setText("" + getMainApplication().getApplicationSettings().getSetting( getPerspectiveID(), ClassifierPanelDefaults.RANDOM_SEED_KEY, ClassifierPanelDefaults.RANDOM_SEED, Environment.getSystemWide())); } m_initialSettingsSet = true; Font outputFont = getMainApplication().getApplicationSettings().getSetting( getPerspectiveID(), ClassifierPanelDefaults.OUTPUT_FONT_KEY, ClassifierPanelDefaults.OUTPUT_FONT, Environment.getSystemWide()); m_OutText.setFont(outputFont); m_History.setFont(outputFont); Color textColor = getMainApplication().getApplicationSettings().getSetting( getPerspectiveID(), ClassifierPanelDefaults.OUTPUT_TEXT_COLOR_KEY, ClassifierPanelDefaults.OUTPUT_TEXT_COLOR, Environment.getSystemWide()); m_OutText.setForeground(textColor); m_History.setForeground(textColor); Color outputBackgroundColor = getMainApplication().getApplicationSettings().getSetting( getPerspectiveID(), ClassifierPanelDefaults.OUTPUT_BACKGROUND_COLOR_KEY, ClassifierPanelDefaults.OUTPUT_BACKGROUND_COLOR, Environment.getSystemWide()); m_OutText.setBackground(outputBackgroundColor); m_History.setBackground(outputBackgroundColor); } } /** * Gets whether cross-validation has been selected by the user * * @return true if cross-validation has been selected */ public boolean isSelectedCV() { return m_CVBut.isSelected(); } /** * Gets whether test on train has been selected by the user * * @return true if testing is to be done on the training set */ public boolean isSelectedTestOnTrain() { return m_TrainBut.isSelected(); } /** * Gets whether a percentage split has been selected by the user * * @return true if a percentage split has been selected */ public boolean isSelectedPercentageSplit() { return m_PercentBut.isSelected(); } /** * Gets whether a separate test set has been selected by the user * * @return true if a separate test set has been selected by the user */ public boolean isSelectedSeparateTestSet() { return m_TestSplitBut.isSelected(); } /** * Gets whether evaluation with respect to costs has been selected by the user * * @return true if eval with respect to costs */ public boolean isSelectedEvalWithRespectToCosts() { return m_EvalWRTCostsBut.isSelected(); } /** * Gets whether the user has opted to output the model * * @return true if the model is to be output */ public boolean isSelectedOutputModel() { return m_OutputModelBut.isSelected(); } /** * Gets whether the user has opted to output the models for the training splits * * @return true if the models for the training splits are to be output */ public boolean isSelectedOutputModelsForTrainingSplits() { return m_OutputModelsForTrainingSplitsBut.isSelected(); } /** * Gets whether the user has opted to output the confusion matrix * * @return true if the confusion matrix is to be output */ public boolean isSelectedOutputConfusion() { return m_OutputConfusionBut.isSelected(); } /** * Gets whether the user has opted to output per-class stats * * @return true if per-class stats are to be output */ public boolean isSelectedOutputPerClassStats() { return m_OutputPerClassBut.isSelected(); } /** * Gets whether the user has opted to output entropy metrics * * @return true if entropy metrics are to be output */ public boolean isSelectedOutputEntropy() { return m_OutputEntropyBut.isSelected(); } /** * Gets whether the user has opted to store the predictions in the history * * @return true if predictions are to be stored */ public boolean isSelectedStorePredictions() { return m_StorePredictionsBut.isSelected(); } /** * Gets whether the user has opted to output source code * * @return true if source code is to be output */ public boolean isSelectedOutputSourceCode() { return m_OutputSourceCode.isSelected(); } /** * Gets whether the user has opted to preserve order of instances in a * percentage split * * @return whether the user has opted to preserve the instance order */ public boolean isSelectedPreserveOrder() { return m_PreserveOrderBut.isSelected(); } /** * Gets the name of the source code class to be generated * * @return the name of the source code class to be generated */ public String getSourceCodeClassName() { return m_SourceCodeClass.getText(); } /** * Get the current visualization * * @return the current visualization */ public VisualizePanel getCurrentVisualization() { return m_CurrentVis; } /** * Set the current visualization * * @param current the visualization to use */ public void setCurrentVisualization(VisualizePanel current) { m_CurrentVis = current; } /** * Get the selected (0-based) class index * * @return the selected class index */ public int getSelectedClassIndex() { return m_ClassCombo.getSelectedIndex(); } /** * Get the number of cross-validation folds to use * * @return the number of cross-validation folds to use */ public int getNumCVFolds() { return Integer.parseInt(m_CVText.getText()); } /** * Get the percentage to use for percentage split evaluation * * @return the percentage to use in a percent split evaluation */ public double getPercentageSplit() { return Double.parseDouble(m_PercentText.getText()); } /** * Get the currently configured classifier from the GenericObjectEditor * * @return the currently configured classifier */ public Classifier getClassifier() { return (Classifier) m_ClassifierEditor.getValue(); } /** * Get the cost matrix (if any) * * @return the cost matrix */ public CostMatrix getCostMatrix() { return (CostMatrix) m_CostMatrixEditor.getValue(); } /** * Get the formatter for classifcation output * * @return the formatter for classification output */ public Object getClassificationOutputFormatter() { return m_ClassificationOutputEditor.getValue(); } /** * Get the result history panel * * @return the result history panel */ public ResultHistoryPanel getResultHistory() { return m_History; } /** * Get the loader object used for loading a separate test set * * @return the loader used for loading a separate test set */ public Loader getSeparateTestSetLoader() { return m_TestLoader; } /** * Get the class index specified for the separate test set * * @return the class index specified for the separate test set */ public int getSeparateTestSetClassIndex() { return m_TestClassIndex; } /** * Get the random seed * * @return the random seed */ public int getRandomSeed() { return Integer.parseInt(m_RandomSeedText.getText()); } /** * Get the log * * @return the log object */ public Logger getLog() { return m_Log; } public static enum TestMode { CROSS_VALIDATION, PERCENTAGE_SPLIT, USE_TRAINING_SET, SEPARATE_TEST_SET; } /** * Default settings for the classifier panel */ protected static final class ClassifierPanelDefaults extends Defaults { public static final String ID = "weka.gui.explorer.classifierpanel"; protected static final Settings.SettingKey CLASSIFIER_KEY = new Settings.SettingKey(ID + ".initialClassifier", "Initial classifier", "On startup, set this classifier as the default one"); protected static final Classifier CLASSIFIER = new ZeroR(); protected static final Settings.SettingKey TEST_MODE_KEY = new Settings.SettingKey(ID + ".initialTestMode", "Default test mode", ""); protected static final TestMode TEST_MODE = TestMode.CROSS_VALIDATION; protected static final Settings.SettingKey CROSS_VALIDATION_FOLDS_KEY = new Settings.SettingKey(ID + ".crossValidationFolds", "Default cross validation folds", ""); protected static final int CROSS_VALIDATION_FOLDS = 10; protected static final Settings.SettingKey PERCENTAGE_SPLIT_KEY = new Settings.SettingKey(ID + ".percentageSplit", "Default percentage split", ""); protected static final int PERCENTAGE_SPLIT = 66; protected static final Settings.SettingKey OUTPUT_MODEL_KEY = new Settings.SettingKey(ID + ".outputModel", "Output model obtained from" + " the full training set", ""); protected static final boolean OUTPUT_MODEL = true; protected static final Settings.SettingKey OUTPUT_MODELS_FOR_TRAINING_SPLITS_KEY = new Settings.SettingKey(ID + ".outputModelsForTrainingSplits", "Output models obtained from" + " the training splits", ""); protected static final boolean OUTPUT_MODELS_FOR_TRAINING_SPLITS = false; protected static final Settings.SettingKey OUTPUT_PER_CLASS_STATS_KEY = new Settings.SettingKey(ID + ".outputPerClassStats", "Output per-class statistics", ""); protected static final boolean OUTPUT_PER_CLASS_STATS = true; protected static final Settings.SettingKey OUTPUT_ENTROPY_EVAL_METRICS_KEY = new Settings.SettingKey(ID + ".outputEntropyMetrics", "Output entropy " + "evaluation metrics", ""); protected static final boolean OUTPUT_ENTROPY_EVAL_METRICS = false; protected static final Settings.SettingKey OUTPUT_CONFUSION_MATRIX_KEY = new Settings.SettingKey(ID + ".outputConfusionMatrix", "Output confusion " + "matrix", ""); protected static final boolean OUTPUT_CONFUSION_MATRIX = true; protected static final Settings.SettingKey STORE_PREDICTIONS_FOR_VIS_KEY = new Settings.SettingKey(ID + ".storePredsForVis", "Store predictions for" + " visualization", ""); protected static final boolean STORE_PREDICTIONS_FOR_VIS = true; /* * protected static final Settings.SettingKey OUTPUT_PREDICTIONS_KEY = new * Settings.SettingKey(ID + ".outputPredictions", "Output predictions", ""); * protected static final boolean OUTPUT_PREDICTIONS = false; */ protected static final Settings.SettingKey PREDICTION_FORMATTER_KEY = new Settings.SettingKey(ID + ".predictionFormatter", "Prediction formatter", ""); protected static final AbstractOutput PREDICTION_FORMATTER = new Null(); protected static final Settings.SettingKey ERROR_PLOT_POINT_SIZE_PROP_TO_MARGIN_KEY = new Settings.SettingKey( ID + ".errorPlotPointSizePropToMargin", "Error plot point size proportional to margin", "In classifier error plots the point size will be set proportional to " + "the absolute value of the prediction margin (affects classification " + "only)"); protected static final boolean ERROR_PLOT_POINT_SIZE_PROP_TO_MARGIN = false; protected static final Settings.SettingKey COST_SENSITIVE_EVALUATION_KEY = new Settings.SettingKey(ID + ".costSensitiveEval", "Cost sensitive evaluation", "Evaluate errors with respect to a cost matrix"); protected static final boolean COST_SENSITIVE_EVALUATION = false; protected static final Settings.SettingKey COST_MATRIX_KEY = new Settings.SettingKey(ID + ".costMatrix", "Cost matrix for cost sensitive " + "evaluation", ""); protected static final CostMatrix COST_MATRIX = new CostMatrix(1); protected static final Settings.SettingKey RANDOM_SEED_KEY = new Settings.SettingKey(ID + ".randomSeed", "Random seed for XVal / % Split", "The seed for randomization"); protected static final int RANDOM_SEED = 1; protected static final Settings.SettingKey PRESERVE_ORDER_FOR_PERCENT_SPLIT_KEY = new Settings.SettingKey(ID + ".preserveOrder", "Preserve order for % Split", "Preserves the order in a percentage split"); protected static final boolean PRESERVE_ORDER_FOR_PERCENT_SPLIT = false; protected static final Settings.SettingKey SOURCE_CODE_CLASS_NAME_KEY = new Settings.SettingKey(ID + ".sourceCodeClassName", "Source code class " + "name", "Default classname of a Sourcable classifier"); protected static final String SOURCE_CODE_CLASS_NAME = "WekaClassifier"; protected static final Settings.SettingKey OUTPUT_FONT_KEY = new Settings.SettingKey(ID + ".outputFont", "Font for text output", "Font to " + "use in the output area"); protected static final Font OUTPUT_FONT = new Font("Monospaced", Font.PLAIN, 12); protected static final Settings.SettingKey OUTPUT_TEXT_COLOR_KEY = new Settings.SettingKey(ID + ".outputFontColor", "Output text color", "Color " + "of output text"); protected static final Color OUTPUT_TEXT_COLOR = Color.black; protected static final Settings.SettingKey OUTPUT_BACKGROUND_COLOR_KEY = new Settings.SettingKey(ID + ".outputBackgroundColor", "Output background color", "Output background color"); protected static final Color OUTPUT_BACKGROUND_COLOR = Color.white; private static final long serialVersionUID = 7109938811150596359L; public ClassifierPanelDefaults() { super(ID); m_defaults.put(CLASSIFIER_KEY, CLASSIFIER); m_defaults.put(TEST_MODE_KEY, TEST_MODE); m_defaults.put(CROSS_VALIDATION_FOLDS_KEY, CROSS_VALIDATION_FOLDS); m_defaults.put(PERCENTAGE_SPLIT_KEY, PERCENTAGE_SPLIT); m_defaults.put(OUTPUT_MODEL_KEY, OUTPUT_MODEL); m_defaults.put(OUTPUT_MODELS_FOR_TRAINING_SPLITS_KEY, OUTPUT_MODELS_FOR_TRAINING_SPLITS); m_defaults.put(OUTPUT_PER_CLASS_STATS_KEY, OUTPUT_PER_CLASS_STATS); m_defaults.put(OUTPUT_ENTROPY_EVAL_METRICS_KEY, OUTPUT_ENTROPY_EVAL_METRICS); m_defaults.put(OUTPUT_CONFUSION_MATRIX_KEY, OUTPUT_CONFUSION_MATRIX); m_defaults.put(STORE_PREDICTIONS_FOR_VIS_KEY, STORE_PREDICTIONS_FOR_VIS); // m_defaults.put(OUTPUT_PREDICTIONS_KEY, OUTPUT_PREDICTIONS); m_defaults.put(PREDICTION_FORMATTER_KEY, PREDICTION_FORMATTER); m_defaults.put(ERROR_PLOT_POINT_SIZE_PROP_TO_MARGIN_KEY, ERROR_PLOT_POINT_SIZE_PROP_TO_MARGIN); m_defaults.put(COST_SENSITIVE_EVALUATION_KEY, COST_SENSITIVE_EVALUATION); m_defaults.put(COST_MATRIX_KEY, COST_MATRIX); m_defaults.put(RANDOM_SEED_KEY, RANDOM_SEED); m_defaults.put(PRESERVE_ORDER_FOR_PERCENT_SPLIT_KEY, PRESERVE_ORDER_FOR_PERCENT_SPLIT); m_defaults.put(SOURCE_CODE_CLASS_NAME_KEY, SOURCE_CODE_CLASS_NAME); m_defaults.put(OUTPUT_FONT_KEY, OUTPUT_FONT); m_defaults.put(OUTPUT_TEXT_COLOR_KEY, OUTPUT_TEXT_COLOR); m_defaults.put(OUTPUT_BACKGROUND_COLOR_KEY, OUTPUT_BACKGROUND_COLOR); } } /** * Tests out the classifier panel from the command line. * * @param args may optionally contain the name of a dataset to load. */ public static void main(String[] args) { try { final javax.swing.JFrame jf = new javax.swing.JFrame("Weka Explorer: Classifier"); jf.getContentPane().setLayout(new BorderLayout()); final ClassifierPanel sp = new ClassifierPanel(); jf.getContentPane().add(sp, BorderLayout.CENTER); weka.gui.LogPanel lp = new weka.gui.LogPanel(); sp.setLog(lp); jf.getContentPane().add(lp, BorderLayout.SOUTH); jf.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { jf.dispose(); System.exit(0); } }); jf.pack(); jf.setSize(800, 600); jf.setVisible(true); if (args.length == 1) { System.err.println("Loading instances from " + args[0]); java.io.Reader r = new java.io.BufferedReader(new java.io.FileReader(args[0])); Instances i = new Instances(r); sp.setInstances(i); } } catch (Exception ex) { ex.printStackTrace(); System.err.println(ex.getMessage()); } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/explorer/ClassifierPanelLaunchHandlerPlugin.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ClassifierPanelLaunchHandlerPlugin.java * Copyright (C) 2011-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.explorer; /** * Interface to plugin that can take the current state of the * Classifier panel and execute it. E.g. A plugin could be * made to train and evaluate the configured classifier on * remote machine(s).<p> * * For full access to the protected member variables in the * ClassifierPanel, an implementation will need to be packaged * in weka.gui.explorer. The ClassifierPanel looks for implementations * when it is constructed, and will provide a new button (in the case * of a single plugin) or a button that pops up a menu (in the * case of multiple plugins) in order to invoke the launch() method * on the plugin. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision$ */ public interface ClassifierPanelLaunchHandlerPlugin { /** * Allows the classifier panel to pass in a reference to * itself * * @param p the ClassifierPanel */ void setClassifierPanel(ClassifierPanel p); /** * Get the name of the launch command (to appear as * the button text or in the popup menu) * * @return the name of the launch command */ String getLaunchCommand(); /** * Gets called when the user clicks the button or selects this * plugin's entry from the popup menu. */ void launch(); }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/explorer/ClustererAssignmentsPlotInstances.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ClustererAssignmentsPlotInstances.java * Copyright (C) 2009-2012 University of Waikato, Hamilton, New Zealand */ package weka.gui.explorer; import java.util.ArrayList; import weka.clusterers.ClusterEvaluation; import weka.clusterers.Clusterer; import weka.core.Attribute; import weka.core.DenseInstance; import weka.core.Instances; import weka.core.Utils; import weka.gui.visualize.Plot2D; import weka.gui.visualize.PlotData2D; /** * A class for generating plottable cluster assignments. * <p/> * Example usage: * * <pre> * Instances train = ... // from somewhere * Instances test = ... // from somewhere * Clusterer cls = ... // from somewhere * // build and evaluate clusterer * cls.buildClusterer(train); * ClusterEvaluation eval = new ClusterEvaluation(); * eval.setClusterer(cls); * eval.evaluateClusterer(test); * // generate plot instances * ClustererPlotInstances plotInstances = new ClustererPlotInstances(); * plotInstances.setClusterer(cls); * plotInstances.setInstances(test); * plotInstances.setClusterer(cls); * plotInstances.setClusterEvaluation(eval); * plotInstances.setUp(); * // generate visualization * VisualizePanel visPanel = new VisualizePanel(); * visPanel.addPlot(plotInstances.getPlotData("plot name")); * // clean up * plotInstances.cleanUp(); * </pre> * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class ClustererAssignmentsPlotInstances extends AbstractPlotInstances { /** for serialization. */ private static final long serialVersionUID = -4748134272046520423L; /** for storing the plot shapes. */ protected int[] m_PlotShapes; /** the clusterer being used. */ protected Clusterer m_Clusterer; /** the cluster evaluation to use. */ protected ClusterEvaluation m_Evaluation; /** * Initializes the members. */ @Override protected void initialize() { super.initialize(); m_PlotShapes = null; m_Clusterer = null; m_Evaluation = null; } /** * Sets the classifier used for making the predictions. * * @param value the clusterer to use */ public void setClusterer(Clusterer value) { m_Clusterer = value; } /** * Returns the currently set clusterer. * * @return the clusterer in use */ public Clusterer getClusterer() { return m_Clusterer; } /** * Sets the cluster evaluation object to use. * * @param value the evaluation object */ public void setClusterEvaluation(ClusterEvaluation value) { m_Evaluation = value; } /** * Returns the cluster evaluation object in use. * * @return the evaluation object */ public ClusterEvaluation getClusterEvaluation() { return m_Evaluation; } /** * Checks whether clusterer and evaluation are provided. */ @Override protected void check() { super.check(); if (m_Clusterer == null) { throw new IllegalStateException("No clusterer set!"); } if (m_Evaluation == null) { throw new IllegalStateException("No cluster evaluation set!"); } } /** * Sets up the structure for the plot instances. */ @Override protected void determineFormat() { int numClusters; ArrayList<Attribute> hv; Attribute predictedCluster; ArrayList<String> clustVals; int i; numClusters = m_Evaluation.getNumClusters(); hv = new ArrayList<Attribute>(); clustVals = new ArrayList<String>(); for (i = 0; i < numClusters; i++) { clustVals.add("cluster" + /* (i+1) */i); } predictedCluster = new Attribute("Cluster", clustVals); for (i = 0; i < m_Instances.numAttributes(); i++) { hv.add((Attribute) m_Instances.attribute(i).copy()); } hv.add(predictedCluster); m_PlotInstances = new Instances(m_Instances.relationName() + "_clustered", hv, m_Instances.numInstances()); } /** * Generates the cluster assignments. * * @see #m_PlotShapes * @see #m_PlotSizes * @see #m_PlotInstances */ protected void process() { double[] clusterAssignments; int i; double[] values; int j; int[] classAssignments; clusterAssignments = m_Evaluation.getClusterAssignments(); classAssignments = null; if (m_Instances.classIndex() >= 0) { classAssignments = m_Evaluation.getClassesToClusters(); m_PlotShapes = new int[m_Instances.numInstances()]; for (i = 0; i < m_Instances.numInstances(); i++) { m_PlotShapes[i] = Plot2D.CONST_AUTOMATIC_SHAPE; } } for (i = 0; i < m_Instances.numInstances(); i++) { values = new double[m_PlotInstances.numAttributes()]; for (j = 0; j < m_Instances.numAttributes(); j++) { values[j] = m_Instances.instance(i).value(j); } if (clusterAssignments[i] < 0) { values[j] = Utils.missingValue(); } else { values[j] = clusterAssignments[i]; } m_PlotInstances.add(new DenseInstance(1.0, values)); if (m_PlotShapes != null) { if (clusterAssignments[i] >= 0) { if ((int) m_Instances.instance(i).classValue() != classAssignments[(int) clusterAssignments[i]]) { m_PlotShapes[i] = Plot2D.ERROR_SHAPE; } } else { m_PlotShapes[i] = Plot2D.MISSING_SHAPE; } } } } /** * Performs optional post-processing. */ @Override protected void finishUp() { super.finishUp(); process(); } /** * Assembles and returns the plot. The relation name of the dataset gets added * automatically. * * @param name the name of the plot * @return the plot * @throws Exception if plot generation fails */ @Override protected PlotData2D createPlotData(String name) throws Exception { PlotData2D result; result = new PlotData2D(m_PlotInstances); if (m_PlotShapes != null) { result.setShapeType(m_PlotShapes); } result.addInstanceNumberAttribute(); result.setPlotName(name + " (" + m_Instances.relationName() + ")"); return result; } /** * For freeing up memory. Plot data cannot be generated after this call! */ @Override public void cleanUp() { super.cleanUp(); m_Clusterer = null; m_Evaluation = null; m_PlotShapes = 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/explorer/ClustererPanel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ClustererPanel.java * Copyright (C) 1999-2013 University of Waikato, Hamilton, New Zealand * */ package weka.gui.explorer; import weka.clusterers.ClusterEvaluation; import weka.clusterers.Clusterer; import weka.clusterers.SimpleKMeans; import weka.core.Attribute; import weka.core.Capabilities; import weka.core.CapabilitiesHandler; import weka.core.Defaults; import weka.core.Drawable; import weka.core.Environment; import weka.core.Instances; import weka.core.OptionHandler; import weka.core.PluginManager; import weka.core.SerializationHelper; import weka.core.SerializedObject; import weka.core.Settings; import weka.core.Utils; import weka.core.Version; import weka.core.WekaPackageClassLoaderManager; import weka.filters.Filter; import weka.filters.unsupervised.attribute.Remove; import weka.gui.AbstractPerspective; import weka.gui.ExtensionFileFilter; import weka.gui.GenericObjectEditor; import weka.gui.InstancesSummaryPanel; import weka.gui.ListSelectorDialog; import weka.gui.Logger; import weka.gui.PerspectiveInfo; import weka.gui.PropertyPanel; import weka.gui.ResultHistoryPanel; import weka.gui.SaveBuffer; import weka.gui.SetInstancesPanel; import weka.gui.SysErrLog; import weka.gui.TaskLogger; import weka.gui.explorer.Explorer.CapabilitiesFilterChangeEvent; import weka.gui.explorer.Explorer.CapabilitiesFilterChangeListener; import weka.gui.explorer.Explorer.ExplorerPanel; import weka.gui.explorer.Explorer.LogHandler; import weka.gui.hierarchyvisualizer.HierarchyVisualizer; import weka.gui.treevisualizer.PlaceNode2; import weka.gui.treevisualizer.TreeVisualizer; import weka.gui.visualize.VisualizePanel; import weka.gui.visualize.plugins.TreeVisualizePlugin; import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.filechooser.FileFilter; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.GridLayout; import java.awt.Insets; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.InputEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Random; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; /** * This panel allows the user to select and configure a clusterer, and evaluate * the clusterer using a number of testing modes (test on the training data, * train/test on a percentage split, test on a separate split). The results of * clustering runs are stored in a result history so that previous results are * accessible. * * @author Mark Hall (mhall@cs.waikato.ac.nz) * @author Richard Kirkby (rkirkby@cs.waikato.ac.nz) * @version $Revision$ */ @PerspectiveInfo(ID = "weka.gui.explorer.clustererpanel", title = "Cluster", toolTipText = "Cluster instances", iconPath = "weka/gui/weka_icon_new_small.png") public class ClustererPanel extends AbstractPerspective implements CapabilitiesFilterChangeListener, ExplorerPanel, LogHandler { /** for serialization */ static final long serialVersionUID = -2474932792950820990L; /** the parent frame */ protected Explorer m_Explorer = null; /** The filename extension that should be used for model files */ public static String MODEL_FILE_EXTENSION = ".model"; /** Lets the user configure the clusterer */ protected GenericObjectEditor m_ClustererEditor = new GenericObjectEditor(); /** The panel showing the current clusterer selection */ protected PropertyPanel m_CLPanel = new PropertyPanel(m_ClustererEditor); /** The output area for classification results */ protected JTextArea m_OutText = new JTextArea(20, 40); /** The destination for log/status messages */ protected Logger m_Log = new SysErrLog(); /** The buffer saving object for saving output */ SaveBuffer m_SaveOut = new SaveBuffer(m_Log, this); /** A panel controlling results viewing */ protected ResultHistoryPanel m_History = new ResultHistoryPanel(m_OutText); /** Click to set test mode to generate a % split */ protected JRadioButton m_PercentBut = new JRadioButton("Percentage split"); /** Click to set test mode to test on training data */ protected JRadioButton m_TrainBut = new JRadioButton("Use training set"); /** Click to set test mode to a user-specified test set */ protected JRadioButton m_TestSplitBut = new JRadioButton("Supplied test set"); /** Click to set test mode to classes to clusters based evaluation */ protected JRadioButton m_ClassesToClustersBut = new JRadioButton( "Classes to clusters evaluation"); /** * Lets the user select the class column for classes to clusters based * evaluation */ protected JComboBox m_ClassCombo = new JComboBox(); /** Label by where the % split is entered */ protected JLabel m_PercentLab = new JLabel("%", SwingConstants.RIGHT); /** The field where the % split is entered */ protected JTextField m_PercentText = new JTextField("66"); /** The button used to open a separate test dataset */ protected JButton m_SetTestBut = new JButton("Set..."); /** The frame used to show the test set selection panel */ protected JFrame m_SetTestFrame; /** * The button used to popup a list for choosing attributes to ignore while * clustering */ protected JButton m_ignoreBut = new JButton("Ignore attributes"); protected DefaultListModel m_ignoreKeyModel = new DefaultListModel(); protected JList m_ignoreKeyList = new JList(m_ignoreKeyModel); // protected Remove m_ignoreFilter = null; /** * Alters the enabled/disabled status of elements associated with each radio * button */ ActionListener m_RadioListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { updateRadioLinks(); } }; /** Click to start running the clusterer */ protected JButton m_StartBut = new JButton("Start"); /** Stop the class combo from taking up to much space */ private final Dimension COMBO_SIZE = new Dimension(250, m_StartBut.getPreferredSize().height); /** Click to stop a running clusterer */ protected JButton m_StopBut = new JButton("Stop"); /** The main set of instances we're playing with */ protected Instances m_Instances; /** The user-supplied test set (if any) */ protected Instances m_TestInstances; /** The current visualization object */ protected VisualizePanel m_CurrentVis = null; /** * Check to save the predictions in the results list for visualizing later on */ protected JCheckBox m_StorePredictionsBut = new JCheckBox( "Store clusters for visualization"); /** A thread that clustering runs in */ protected Thread m_RunThread; /** The instances summary panel displayed by m_SetTestFrame */ protected InstancesSummaryPanel m_Summary; /** Filter to ensure only model files are selected */ protected FileFilter m_ModelFilter = new ExtensionFileFilter( MODEL_FILE_EXTENSION, "Model object files"); /** The file chooser for selecting model files */ protected JFileChooser m_FileChooser = new JFileChooser(new File( System.getProperty("user.dir"))); /** Whether startup settings have been applied yet or not */ protected boolean m_initialSettingsSet; /* Register the property editors we need */ static { GenericObjectEditor.registerEditors(); } /** * Creates the clusterer panel */ public ClustererPanel() { // Connect / configure the components m_OutText.setEditable(false); m_OutText.setFont(new Font("Monospaced", Font.PLAIN, 12)); m_OutText.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); m_OutText.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if ((e.getModifiers() & InputEvent.BUTTON1_MASK) != InputEvent.BUTTON1_MASK) { m_OutText.selectAll(); } } }); JPanel historyHolder = new JPanel(new BorderLayout()); historyHolder.setBorder(BorderFactory .createTitledBorder("Result list (right-click for options)")); historyHolder.add(m_History, BorderLayout.CENTER); m_ClustererEditor.setClassType(Clusterer.class); m_ClustererEditor.setValue(ExplorerDefaults.getClusterer()); m_ClustererEditor.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent e) { m_StartBut.setEnabled(true); Capabilities currentFilter = m_ClustererEditor.getCapabilitiesFilter(); Clusterer clusterer = (Clusterer) m_ClustererEditor.getValue(); Capabilities currentSchemeCapabilities = null; if (clusterer != null && currentFilter != null && (clusterer instanceof CapabilitiesHandler)) { currentSchemeCapabilities = ((CapabilitiesHandler) clusterer).getCapabilities(); if (!currentSchemeCapabilities.supportsMaybe(currentFilter) && !currentSchemeCapabilities.supports(currentFilter)) { m_StartBut.setEnabled(false); } } repaint(); } }); m_TrainBut.setToolTipText("Cluster the same set that the clusterer" + " is trained on"); m_PercentBut.setToolTipText("Train on a percentage of the data and" + " cluster the remainder"); m_TestSplitBut.setToolTipText("Cluster a user-specified dataset"); m_ClassesToClustersBut.setToolTipText("Evaluate clusters with respect to a" + " class"); m_ClassCombo.setToolTipText("Select the class attribute for class based" + " evaluation"); m_StartBut.setToolTipText("Starts the clustering"); m_StopBut.setToolTipText("Stops a running clusterer"); m_StorePredictionsBut .setToolTipText("Store predictions in the result list for later " + "visualization"); m_ignoreBut.setToolTipText("Ignore attributes during clustering"); m_FileChooser.setFileFilter(m_ModelFilter); m_FileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); m_ClassCombo.setPreferredSize(COMBO_SIZE); m_ClassCombo.setMaximumSize(COMBO_SIZE); m_ClassCombo.setMinimumSize(COMBO_SIZE); m_ClassCombo.setEnabled(false); m_PercentBut.setSelected(ExplorerDefaults.getClustererTestMode() == 2); m_TrainBut.setSelected(ExplorerDefaults.getClustererTestMode() == 3); m_TestSplitBut.setSelected(ExplorerDefaults.getClustererTestMode() == 4); m_ClassesToClustersBut .setSelected(ExplorerDefaults.getClustererTestMode() == 5); m_StorePredictionsBut.setSelected(ExplorerDefaults .getClustererStoreClustersForVis()); updateRadioLinks(); ButtonGroup bg = new ButtonGroup(); bg.add(m_TrainBut); bg.add(m_PercentBut); bg.add(m_TestSplitBut); bg.add(m_ClassesToClustersBut); m_TrainBut.addActionListener(m_RadioListener); m_PercentBut.addActionListener(m_RadioListener); m_TestSplitBut.addActionListener(m_RadioListener); m_ClassesToClustersBut.addActionListener(m_RadioListener); m_SetTestBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { setTestSet(); } }); m_StartBut.setEnabled(false); m_StopBut.setEnabled(false); m_ignoreBut.setEnabled(false); m_StartBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { boolean proceed = true; if (Explorer.m_Memory.memoryIsLow()) { proceed = Explorer.m_Memory.showMemoryIsLow(); } if (proceed) { startClusterer(); } } }); m_StopBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { stopClusterer(); } }); m_ignoreBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { setIgnoreColumns(); } }); m_History.setHandleRightClicks(false); // see if we can popup a menu for the selected result m_History.getList().addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (((e.getModifiers() & InputEvent.BUTTON1_MASK) != InputEvent.BUTTON1_MASK) || e.isAltDown()) { int index = m_History.getList().locationToIndex(e.getPoint()); if (index != -1) { List<String> selectedEls = (List<String>) m_History.getList().getSelectedValuesList(); visualizeClusterer(selectedEls, e.getX(), e.getY()); } else { visualizeClusterer(null, e.getX(), e.getY()); } } } }); m_ClassCombo.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { updateCapabilitiesFilter(m_ClustererEditor.getCapabilitiesFilter()); } }); // Layout the GUI JPanel p1 = new JPanel(); p1.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createTitledBorder("Clusterer"), BorderFactory.createEmptyBorder(0, 5, 5, 5))); p1.setLayout(new BorderLayout()); p1.add(m_CLPanel, BorderLayout.NORTH); JPanel p2 = new JPanel(); GridBagLayout gbL = new GridBagLayout(); p2.setLayout(gbL); p2.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createTitledBorder("Cluster mode"), BorderFactory.createEmptyBorder(0, 5, 5, 5))); GridBagConstraints gbC = new GridBagConstraints(); gbC.anchor = GridBagConstraints.WEST; gbC.gridy = 0; gbC.gridx = 0; gbL.setConstraints(m_TrainBut, gbC); p2.add(m_TrainBut); gbC = new GridBagConstraints(); gbC.anchor = GridBagConstraints.WEST; gbC.gridy = 1; gbC.gridx = 0; gbL.setConstraints(m_TestSplitBut, gbC); p2.add(m_TestSplitBut); gbC = new GridBagConstraints(); gbC.anchor = GridBagConstraints.EAST; gbC.fill = GridBagConstraints.HORIZONTAL; gbC.gridy = 1; gbC.gridx = 1; gbC.gridwidth = 2; gbC.insets = new Insets(2, 10, 2, 0); gbL.setConstraints(m_SetTestBut, gbC); p2.add(m_SetTestBut); gbC = new GridBagConstraints(); gbC.anchor = GridBagConstraints.WEST; gbC.gridy = 2; gbC.gridx = 0; gbL.setConstraints(m_PercentBut, gbC); p2.add(m_PercentBut); gbC = new GridBagConstraints(); gbC.anchor = GridBagConstraints.EAST; gbC.fill = GridBagConstraints.HORIZONTAL; gbC.gridy = 2; gbC.gridx = 1; gbC.insets = new Insets(2, 10, 2, 10); gbL.setConstraints(m_PercentLab, gbC); p2.add(m_PercentLab); gbC = new GridBagConstraints(); gbC.anchor = GridBagConstraints.EAST; gbC.fill = GridBagConstraints.HORIZONTAL; gbC.gridy = 2; gbC.gridx = 2; gbC.weightx = 100; gbC.ipadx = 20; gbL.setConstraints(m_PercentText, gbC); p2.add(m_PercentText); gbC = new GridBagConstraints(); gbC.anchor = GridBagConstraints.WEST; gbC.gridy = 3; gbC.gridx = 0; gbC.gridwidth = 2; gbL.setConstraints(m_ClassesToClustersBut, gbC); p2.add(m_ClassesToClustersBut); m_ClassCombo.setBorder(BorderFactory.createEmptyBorder(0, 20, 0, 0)); gbC = new GridBagConstraints(); gbC.anchor = GridBagConstraints.WEST; gbC.gridy = 4; gbC.gridx = 0; gbC.gridwidth = 2; gbL.setConstraints(m_ClassCombo, gbC); p2.add(m_ClassCombo); gbC = new GridBagConstraints(); gbC.anchor = GridBagConstraints.WEST; gbC.gridy = 5; gbC.gridx = 0; gbC.gridwidth = 2; gbL.setConstraints(m_StorePredictionsBut, gbC); p2.add(m_StorePredictionsBut); // Any launcher plugins List<String> pluginsVector = PluginManager.getPluginNamesOfTypeList(ClustererPanelLaunchHandlerPlugin.class.getName()); JButton pluginBut = null; if (pluginsVector.size() == 1) { try { // display a single button String className = pluginsVector.get(0); final ClustererPanelLaunchHandlerPlugin plugin = (ClustererPanelLaunchHandlerPlugin) WekaPackageClassLoaderManager .objectForName(className); // Class.forName(className).newInstance(); if (plugin != null) { plugin.setClustererPanel(this); pluginBut = new JButton(plugin.getLaunchCommand()); pluginBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { plugin.launch(); } }); } } catch (Exception ex) { ex.printStackTrace(); } } else if (pluginsVector.size() > 1) { // make a popup menu int okPluginCount = 0; final java.awt.PopupMenu pluginPopup = new java.awt.PopupMenu(); for (int i = 0; i < pluginsVector.size(); i++) { String className = (pluginsVector.get(i)); try { final ClustererPanelLaunchHandlerPlugin plugin = (ClustererPanelLaunchHandlerPlugin) WekaPackageClassLoaderManager .objectForName(className); // Class.forName(className).newInstance(); if (plugin == null) { continue; } okPluginCount++; plugin.setClustererPanel(this); java.awt.MenuItem popI = new java.awt.MenuItem(plugin.getLaunchCommand()); popI.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // pluginPopup.setVisible(false); plugin.launch(); } }); pluginPopup.add(popI); } catch (Exception ex) { ex.printStackTrace(); } } if (okPluginCount > 0) { pluginBut = new JButton("Launchers..."); final JButton copyB = pluginBut; copyB.add(pluginPopup); pluginBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { pluginPopup.show(copyB, 0, 0); } }); } else { pluginBut = null; } } JPanel buttons = new JPanel(); buttons.setLayout(new GridLayout(2, 1)); JPanel ssButs = new JPanel(); ssButs.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); if (pluginBut == null) { ssButs.setLayout(new GridLayout(1, 2, 5, 5)); } else { ssButs.setLayout(new FlowLayout(FlowLayout.LEFT)); } ssButs.add(m_StartBut); ssButs.add(m_StopBut); if (pluginBut != null) { ssButs.add(pluginBut); } JPanel ib = new JPanel(); ib.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); ib.setLayout(new GridLayout(1, 1, 5, 5)); ib.add(m_ignoreBut); buttons.add(ib); buttons.add(ssButs); JPanel p3 = new JPanel(); p3.setBorder(BorderFactory.createTitledBorder("Clusterer output")); p3.setLayout(new BorderLayout()); final JScrollPane js = new JScrollPane(m_OutText); p3.add(js, BorderLayout.CENTER); js.getViewport().addChangeListener(new ChangeListener() { private int lastHeight; @Override public void stateChanged(ChangeEvent e) { JViewport vp = (JViewport) e.getSource(); int h = vp.getViewSize().height; if (h != lastHeight) { // i.e. an addition not just a user scrolling lastHeight = h; int x = h - vp.getExtentSize().height; vp.setViewPosition(new Point(0, x)); } } }); JPanel mondo = new JPanel(); gbL = new GridBagLayout(); mondo.setLayout(gbL); gbC = new GridBagConstraints(); // gbC.anchor = GridBagConstraints.WEST; gbC.fill = GridBagConstraints.HORIZONTAL; gbC.gridy = 0; gbC.gridx = 0; gbL.setConstraints(p2, gbC); mondo.add(p2); gbC = new GridBagConstraints(); gbC.anchor = GridBagConstraints.NORTH; gbC.fill = GridBagConstraints.HORIZONTAL; gbC.gridy = 1; gbC.gridx = 0; gbL.setConstraints(buttons, gbC); mondo.add(buttons); gbC = new GridBagConstraints(); // gbC.anchor = GridBagConstraints.NORTH; gbC.fill = GridBagConstraints.BOTH; gbC.gridy = 2; gbC.gridx = 0; gbC.weightx = 0; gbL.setConstraints(historyHolder, gbC); mondo.add(historyHolder); gbC = new GridBagConstraints(); gbC.fill = GridBagConstraints.BOTH; gbC.gridy = 0; gbC.gridx = 1; gbC.gridheight = 3; gbC.weightx = 100; gbC.weighty = 100; gbL.setConstraints(p3, gbC); mondo.add(p3); setLayout(new BorderLayout()); add(p1, BorderLayout.NORTH); add(mondo, BorderLayout.CENTER); } /** * Updates the enabled status of the input fields and labels. */ protected void updateRadioLinks() { m_SetTestBut.setEnabled(m_TestSplitBut.isSelected()); if ((m_SetTestFrame != null) && (!m_TestSplitBut.isSelected())) { m_SetTestFrame.setVisible(false); } m_PercentText.setEnabled(m_PercentBut.isSelected()); m_PercentLab.setEnabled(m_PercentBut.isSelected()); m_ClassCombo.setEnabled(m_ClassesToClustersBut.isSelected()); updateCapabilitiesFilter(m_ClustererEditor.getCapabilitiesFilter()); } /** * Sets the Logger to receive informational messages * * @param newLog the Logger that will now get info messages */ @Override public void setLog(Logger newLog) { m_Log = newLog; } /** * Tells the panel to use a new set of instances. * * @param inst a set of Instances */ @Override public void setInstances(Instances inst) { m_Instances = inst; m_ignoreKeyModel.removeAllElements(); String[] attribNames = new String[m_Instances.numAttributes()]; for (int i = 0; i < m_Instances.numAttributes(); i++) { String name = m_Instances.attribute(i).name(); m_ignoreKeyModel.addElement(name); String type = "(" + Attribute.typeToStringShort(m_Instances.attribute(i)) + ") "; String attnm = m_Instances.attribute(i).name(); attribNames[i] = type + attnm; } m_StartBut.setEnabled(m_RunThread == null); m_StopBut.setEnabled(m_RunThread != null); m_ignoreBut.setEnabled(true); m_ClassCombo.setModel(new DefaultComboBoxModel(attribNames)); if (inst.classIndex() == -1) { m_ClassCombo.setSelectedIndex(attribNames.length - 1); } else { m_ClassCombo.setSelectedIndex(inst.classIndex()); } updateRadioLinks(); } /** * Sets the user test set. Information about the current test set is displayed * in an InstanceSummaryPanel and the user is given the ability to load * another set from a file or url. * */ protected void setTestSet() { if (m_SetTestFrame == null) { final SetInstancesPanel sp = new SetInstancesPanel(); sp.setReadIncrementally(false); m_Summary = sp.getSummary(); if (m_TestInstances != null) { sp.setInstances(m_TestInstances); } sp.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent e) { m_TestInstances = sp.getInstances(); m_TestInstances.setClassIndex(-1); // make sure that no class // attribute is set! } }); // Add propertychangelistener to update m_TestInstances whenever // it changes in the settestframe m_SetTestFrame = Utils.getWekaJFrame("Test Instances", this); sp.setParentFrame(m_SetTestFrame); // enable Close-Button m_SetTestFrame.getContentPane().setLayout(new BorderLayout()); m_SetTestFrame.getContentPane().add(sp, BorderLayout.CENTER); m_SetTestFrame.pack(); m_SetTestFrame.setSize(400,200); } m_SetTestFrame.setLocationRelativeTo(SwingUtilities.getWindowAncestor(this)); m_SetTestFrame.setVisible(true); } /** * Starts running the currently configured clusterer with the current * settings. This is run in a separate thread, and will only start if there is * no clusterer already running. The clusterer output is sent to the results * history panel. */ protected void startClusterer() { if (m_RunThread == null) { m_StartBut.setEnabled(false); m_StopBut.setEnabled(true); m_ignoreBut.setEnabled(false); m_RunThread = new Thread() { @Override public void run() { m_CLPanel.addToHistory(); // for timing long trainTimeStart = 0, trainTimeElapsed = 0; // Copy the current state of things m_Log.statusMessage("Setting up..."); Instances inst = new Instances(m_Instances); inst.setClassIndex(-1); Instances userTest = null; ClustererAssignmentsPlotInstances plotInstances = ExplorerDefaults.getClustererAssignmentsPlotInstances(); plotInstances.setClusterer((Clusterer) m_ClustererEditor.getValue()); if (m_TestInstances != null) { userTest = new Instances(m_TestInstances); } boolean saveVis = m_StorePredictionsBut.isSelected(); String grph = null; int[] ignoredAtts = null; int testMode = 0; int percent = 66; Clusterer clusterer = (Clusterer) m_ClustererEditor.getValue(); Clusterer fullClusterer = null; StringBuffer outBuff = new StringBuffer(); String name = (new SimpleDateFormat("HH:mm:ss - ")).format(new Date()); String cname = clusterer.getClass().getName(); if (cname.startsWith("weka.clusterers.")) { name += cname.substring("weka.clusterers.".length()); } else { name += cname; } String cmd = m_ClustererEditor.getValue().getClass().getName(); if (m_ClustererEditor.getValue() instanceof OptionHandler) { cmd += " " + Utils.joinOptions(((OptionHandler) m_ClustererEditor .getValue()).getOptions()); } try { m_Log.logMessage("Started " + cname); m_Log.logMessage("Command: " + cmd); if (m_Log instanceof TaskLogger) { ((TaskLogger) m_Log).taskStarted(); } if (m_PercentBut.isSelected()) { testMode = 2; percent = Integer.parseInt(m_PercentText.getText()); if ((percent <= 0) || (percent >= 100)) { throw new Exception("Percentage must be between 0 and 100"); } } else if (m_TrainBut.isSelected()) { testMode = 3; } else if (m_TestSplitBut.isSelected()) { testMode = 4; // Check the test instance compatibility if (userTest == null) { throw new Exception("No user test set has been opened"); } if (!inst.equalHeaders(userTest)) { throw new Exception("Train and test set are not compatible\n" + inst.equalHeadersMsg(userTest)); } } else if (m_ClassesToClustersBut.isSelected()) { testMode = 5; } else { throw new Exception("Unknown test mode"); } Instances trainInst = new Instances(inst); if (m_ClassesToClustersBut.isSelected()) { trainInst.setClassIndex(m_ClassCombo.getSelectedIndex()); inst.setClassIndex(m_ClassCombo.getSelectedIndex()); if (inst.classAttribute().isNumeric()) { throw new Exception("Class must be nominal for class based " + "evaluation!"); } } if (!m_ignoreKeyList.isSelectionEmpty()) { trainInst = removeIgnoreCols(trainInst); } // Output some header information outBuff.append("=== Run information ===\n\n"); outBuff.append("Scheme: " + cname); if (clusterer instanceof OptionHandler) { String[] o = ((OptionHandler) clusterer).getOptions(); outBuff.append(" " + Utils.joinOptions(o)); } outBuff.append("\n"); outBuff.append("Relation: " + inst.relationName() + '\n'); outBuff.append("Instances: " + inst.numInstances() + '\n'); outBuff.append("Attributes: " + inst.numAttributes() + '\n'); if (inst.numAttributes() < 100) { boolean[] selected = new boolean[inst.numAttributes()]; for (int i = 0; i < inst.numAttributes(); i++) { selected[i] = true; } if (!m_ignoreKeyList.isSelectionEmpty()) { int[] indices = m_ignoreKeyList.getSelectedIndices(); for (int i = 0; i < indices.length; i++) { selected[indices[i]] = false; } } if (m_ClassesToClustersBut.isSelected()) { selected[m_ClassCombo.getSelectedIndex()] = false; } for (int i = 0; i < inst.numAttributes(); i++) { if (selected[i]) { outBuff.append(" " + inst.attribute(i).name() + '\n'); } } if (!m_ignoreKeyList.isSelectionEmpty() || m_ClassesToClustersBut.isSelected()) { outBuff.append("Ignored:\n"); for (int i = 0; i < inst.numAttributes(); i++) { if (!selected[i]) { outBuff.append(" " + inst.attribute(i).name() + '\n'); } } } } else { outBuff.append(" [list of attributes omitted]\n"); } if (!m_ignoreKeyList.isSelectionEmpty()) { ignoredAtts = m_ignoreKeyList.getSelectedIndices(); } if (m_ClassesToClustersBut.isSelected()) { // add class to ignored list if (ignoredAtts == null) { ignoredAtts = new int[1]; ignoredAtts[0] = m_ClassCombo.getSelectedIndex(); } else { int[] newIgnoredAtts = new int[ignoredAtts.length + 1]; System.arraycopy(ignoredAtts, 0, newIgnoredAtts, 0, ignoredAtts.length); newIgnoredAtts[ignoredAtts.length] = m_ClassCombo.getSelectedIndex(); ignoredAtts = newIgnoredAtts; } } outBuff.append("Test mode: "); switch (testMode) { case 3: // Test on training outBuff.append("evaluate on training data\n"); break; case 2: // Percent split outBuff.append("split " + percent + "% train, remainder test\n"); break; case 4: // Test on user split outBuff.append("user supplied test set: " + userTest.numInstances() + " instances\n"); break; case 5: // Classes to clusters evaluation on training outBuff.append("Classes to clusters evaluation on training data"); break; } outBuff.append("\n"); m_History.addResult(name, outBuff); m_History.setSingle(name); // Build the model and output it. m_Log.statusMessage("Building model on training data..."); // remove the class attribute (if set) and build the clusterer trainTimeStart = System.currentTimeMillis(); clusterer.buildClusterer(removeClass(trainInst)); trainTimeElapsed = System.currentTimeMillis() - trainTimeStart; // if (testMode == 2) { outBuff .append("\n=== Clustering model (full training set) ===\n\n"); outBuff.append(clusterer.toString() + '\n'); outBuff .append("\nTime taken to build model (full training data) : " + Utils.doubleToString(trainTimeElapsed / 1000.0, 2) + " seconds\n\n"); // } m_History.updateResult(name); if (clusterer instanceof Drawable) { try { grph = ((Drawable) clusterer).graph(); } catch (Exception ex) { } } // copy full model for output SerializedObject so = new SerializedObject(clusterer); fullClusterer = (Clusterer) so.getObject(); ClusterEvaluation eval = new ClusterEvaluation(); eval.setClusterer(clusterer); switch (testMode) { case 3: case 5: // Test on training m_Log.statusMessage("Clustering training data..."); eval.evaluateClusterer(trainInst, "", false); plotInstances.setInstances(inst); plotInstances.setClusterEvaluation(eval); outBuff .append("=== Model and evaluation on training set ===\n\n"); break; case 2: // Percent split m_Log.statusMessage("Randomizing instances..."); inst.randomize(new Random(1)); trainInst.randomize(new Random(1)); int trainSize = trainInst.numInstances() * percent / 100; int testSize = trainInst.numInstances() - trainSize; Instances train = new Instances(trainInst, 0, trainSize); Instances test = new Instances(trainInst, trainSize, testSize); Instances testVis = new Instances(inst, trainSize, testSize); m_Log.statusMessage("Building model on training split..."); trainTimeStart = System.currentTimeMillis(); clusterer.buildClusterer(train); trainTimeElapsed = System.currentTimeMillis() - trainTimeStart; m_Log.statusMessage("Evaluating on test split..."); eval.evaluateClusterer(test, "", false); plotInstances.setInstances(testVis); plotInstances.setClusterEvaluation(eval); outBuff.append("=== Model and evaluation on test split ===\n"); outBuff.append(clusterer.toString() + "\n"); outBuff .append("\nTime taken to build model (percentage split) : " + Utils.doubleToString(trainTimeElapsed / 1000.0, 2) + " seconds\n\n"); break; case 4: // Test on user split m_Log.statusMessage("Evaluating on test data..."); Instances userTestT = new Instances(userTest); if (!m_ignoreKeyList.isSelectionEmpty()) { userTestT = removeIgnoreCols(userTestT); } eval.evaluateClusterer(userTestT, "", false); plotInstances.setInstances(userTest); plotInstances.setClusterEvaluation(eval); outBuff.append("=== Evaluation on test set ===\n"); break; default: throw new Exception("Test mode not implemented"); } outBuff.append(eval.clusterResultsToString()); outBuff.append("\n"); m_History.updateResult(name); m_Log.logMessage("Finished " + cname); m_Log.statusMessage("OK"); } catch (Exception ex) { ex.printStackTrace(); m_Log.logMessage(ex.getMessage()); JOptionPane.showMessageDialog(ClustererPanel.this, "Problem evaluating clusterer:\n" + ex.getMessage(), "Evaluate clusterer", JOptionPane.ERROR_MESSAGE); m_Log.statusMessage("Problem evaluating clusterer"); } finally { if ((plotInstances != null) && plotInstances.canPlot(true)) { m_CurrentVis = new VisualizePanel(); if (getMainApplication() != null) { Settings settings = getMainApplication().getApplicationSettings(); m_CurrentVis.applySettings(settings, weka.gui.explorer.VisualizePanel.ScatterDefaults.ID); } m_CurrentVis.setName(name + " (" + inst.relationName() + ")"); m_CurrentVis.setLog(m_Log); try { m_CurrentVis.addPlot(plotInstances.getPlotData(name)); } catch (Exception ex) { System.err.println(ex); } plotInstances.cleanUp(); ArrayList<Object> vv = new ArrayList<Object>(); vv.add(fullClusterer); Instances trainHeader = new Instances(m_Instances, 0); vv.add(trainHeader); if (ignoredAtts != null) { vv.add(ignoredAtts); } if (saveVis) { vv.add(m_CurrentVis); if (grph != null) { vv.add(grph); } } m_History.addObject(name, vv); } if (isInterrupted()) { m_Log.logMessage("Interrupted " + cname); m_Log.statusMessage("See error log"); } m_RunThread = null; m_StartBut.setEnabled(true); m_StopBut.setEnabled(false); m_ignoreBut.setEnabled(true); if (m_Log instanceof TaskLogger) { ((TaskLogger) m_Log).taskFinished(); } } } }; m_RunThread.setPriority(Thread.MIN_PRIORITY); m_RunThread.start(); } } private Instances removeClass(Instances inst) { Remove af = new Remove(); Instances retI = null; try { if (inst.classIndex() < 0) { retI = inst; } else { af.setAttributeIndices("" + (inst.classIndex() + 1)); af.setInvertSelection(false); af.setInputFormat(inst); retI = Filter.useFilter(inst, af); } } catch (Exception e) { e.printStackTrace(); } return retI; } private Instances removeIgnoreCols(Instances inst) { // If the user is doing classes to clusters evaluation and // they have opted to ignore the class, then unselect the class in // the ignore list if (m_ClassesToClustersBut.isSelected()) { int classIndex = m_ClassCombo.getSelectedIndex(); if (m_ignoreKeyList.isSelectedIndex(classIndex)) { m_ignoreKeyList.removeSelectionInterval(classIndex, classIndex); } } int[] selected = m_ignoreKeyList.getSelectedIndices(); Remove af = new Remove(); Instances retI = null; try { af.setAttributeIndicesArray(selected); af.setInvertSelection(false); af.setInputFormat(inst); retI = Filter.useFilter(inst, af); } catch (Exception e) { e.printStackTrace(); } return retI; } private Instances removeIgnoreCols(Instances inst, int[] toIgnore) { Remove af = new Remove(); Instances retI = null; try { af.setAttributeIndicesArray(toIgnore); af.setInvertSelection(false); af.setInputFormat(inst); retI = Filter.useFilter(inst, af); } catch (Exception e) { e.printStackTrace(); } return retI; } /** * Stops the currently running clusterer (if any). */ @SuppressWarnings("deprecation") protected void stopClusterer() { if (m_RunThread != null) { m_RunThread.interrupt(); // This is deprecated (and theoretically the interrupt should do). m_RunThread.stop(); } } /** * Pops up a TreeVisualizer for the clusterer from the currently selected item * in the results list * * @param graphString the description of the tree in dotty format * @param treeName the title to assign to the display */ protected void visualizeTree(String graphString, String treeName) { final javax.swing.JFrame jf = Utils.getWekaJFrame("Weka Cluster Tree Visualizer: " + treeName, this); jf.getContentPane().setLayout(new BorderLayout()); if (graphString.contains("digraph")) { TreeVisualizer tv = new TreeVisualizer(null, graphString, new PlaceNode2()); jf.getContentPane().add(tv, BorderLayout.CENTER); jf.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { jf.dispose(); } }); jf.pack(); jf.setSize(800, 600); jf.setLocationRelativeTo(SwingUtilities.getWindowAncestor(this)); jf.setVisible(true); tv.fitToScreen(); } else if (graphString.startsWith("Newick:")) { HierarchyVisualizer tv = new HierarchyVisualizer(graphString.substring(7)); jf.getContentPane().add(tv, BorderLayout.CENTER); jf.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { jf.dispose(); } }); jf.pack(); jf.setSize(800, 600); jf.setLocationRelativeTo(SwingUtilities.getWindowAncestor(this)); jf.setVisible(true); tv.fitToScreen(); } } /** * Pops up a visualize panel to display cluster assignments * * @param sp the visualize panel to display */ protected void visualizeClusterAssignments(VisualizePanel sp) { if (sp != null) { String plotName = sp.getName(); final javax.swing.JFrame jf = Utils.getWekaJFrame("Weka Clusterer Visualize: " + plotName, this); jf.getContentPane().setLayout(new BorderLayout()); jf.getContentPane().add(sp, BorderLayout.CENTER); jf.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { jf.dispose(); } }); jf.pack(); jf.setSize(800, 600); jf.setLocationRelativeTo(SwingUtilities.getWindowAncestor(this)); jf.setVisible(true); } } /** * Handles constructing a popup menu with visualization options * * @param names the name of the result history list entry clicked on by the * user * @param x the x coordinate for popping up the menu * @param y the y coordinate for popping up the menu */ @SuppressWarnings("unchecked") protected void visualizeClusterer(List<String> names, int x, int y) { final List<String> selectedNames = names; JPopupMenu resultListMenu = new JPopupMenu(); JMenuItem visMainBuffer = new JMenuItem("View in main window"); if (selectedNames != null && selectedNames.size() == 1) { visMainBuffer.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m_History.setSingle(selectedNames.get(0)); } }); } else { visMainBuffer.setEnabled(false); } resultListMenu.add(visMainBuffer); JMenuItem visSepBuffer = new JMenuItem("View in separate window"); if (selectedNames != null && selectedNames.size() == 1) { visSepBuffer.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m_History.openFrame(selectedNames.get(0)); } }); } else { visSepBuffer.setEnabled(false); } resultListMenu.add(visSepBuffer); JMenuItem saveOutput = new JMenuItem("Save result buffer"); if (selectedNames != null && selectedNames.size() == 1) { saveOutput.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { saveBuffer(selectedNames.get(0)); } }); } else { saveOutput.setEnabled(false); } resultListMenu.add(saveOutput); JMenuItem deleteOutput = new JMenuItem("Delete result buffer(s)"); if (selectedNames != null) { deleteOutput.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m_History.removeResults(selectedNames); } }); } else { deleteOutput.setEnabled(false); } resultListMenu.add(deleteOutput); resultListMenu.addSeparator(); JMenuItem loadModel = new JMenuItem("Load model"); loadModel.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { loadClusterer(); } }); resultListMenu.add(loadModel); ArrayList<Object> o = null; if (selectedNames != null && selectedNames.size() == 1) { o = (ArrayList<Object>) m_History.getNamedObject(selectedNames.get(0)); } VisualizePanel temp_vp = null; String temp_grph = null; Clusterer temp_clusterer = null; Instances temp_trainHeader = null; int[] temp_ignoreAtts = null; if (o != null) { for (int i = 0; i < o.size(); i++) { Object temp = o.get(i); if (temp instanceof Clusterer) { temp_clusterer = (Clusterer) temp; } else if (temp instanceof Instances) { // training header temp_trainHeader = (Instances) temp; } else if (temp instanceof int[]) { // ignored attributes temp_ignoreAtts = (int[]) temp; } else if (temp instanceof VisualizePanel) { // normal errors temp_vp = (VisualizePanel) temp; } else if (temp instanceof String) { // graphable output temp_grph = (String) temp; } } } final VisualizePanel vp = temp_vp; final String grph = temp_grph; final Clusterer clusterer = temp_clusterer; final Instances trainHeader = temp_trainHeader; final int[] ignoreAtts = temp_ignoreAtts; JMenuItem saveModel = new JMenuItem("Save model"); if (clusterer != null && selectedNames != null && selectedNames.size() == 1) { saveModel.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { saveClusterer(selectedNames.get(0), clusterer, trainHeader, ignoreAtts); } }); } else { saveModel.setEnabled(false); } resultListMenu.add(saveModel); JMenuItem reEvaluate = new JMenuItem("Re-evaluate model on current test set"); if (clusterer != null && m_TestInstances != null && selectedNames != null && selectedNames.size() == 1) { reEvaluate.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { reevaluateModel(selectedNames.get(0), clusterer, trainHeader, ignoreAtts); } }); } else { reEvaluate.setEnabled(false); } resultListMenu.add(reEvaluate); JMenuItem reApplyConfig = new JMenuItem("Re-apply this model's configuration"); if (clusterer != null) { reApplyConfig.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m_ClustererEditor.setValue(clusterer); } }); } else { reApplyConfig.setEnabled(false); } resultListMenu.add(reApplyConfig); resultListMenu.addSeparator(); JMenuItem visClusts = new JMenuItem("Visualize cluster assignments"); if (vp != null) { visClusts.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { visualizeClusterAssignments(vp); } }); } else { visClusts.setEnabled(false); } resultListMenu.add(visClusts); JMenuItem visTree = new JMenuItem("Visualize tree"); if (grph != null) { visTree.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String title; if (vp != null) { title = vp.getName(); } else { title = selectedNames.get(0); } visualizeTree(grph, title); } }); } else { visTree.setEnabled(false); } resultListMenu.add(visTree); // visualization plugins JMenu visPlugins = new JMenu("Plugins"); boolean availablePlugins = false; // trees if (grph != null) { // trees List<String> pluginsVector = PluginManager.getPluginNamesOfTypeList(TreeVisualizePlugin.class.getName()); for (int i = 0; i < pluginsVector.size(); i++) { String className = (pluginsVector.get(i)); try { TreeVisualizePlugin plugin = (TreeVisualizePlugin) WekaPackageClassLoaderManager .objectForName(className); // Class.forName(className).newInstance(); if (plugin == null) { continue; } availablePlugins = true; JMenuItem pluginMenuItem = plugin.getVisualizeMenuItem(grph, selectedNames.get(0)); Version version = new Version(); if (pluginMenuItem != null) { if (version.compareTo(plugin.getMinVersion()) < 0) { pluginMenuItem.setText(pluginMenuItem.getText() + " (weka outdated)"); } if (version.compareTo(plugin.getMaxVersion()) >= 0) { pluginMenuItem.setText(pluginMenuItem.getText() + " (plugin outdated)"); } visPlugins.add(pluginMenuItem); } } catch (Exception e) { // e.printStackTrace(); } } } if (availablePlugins) { resultListMenu.add(visPlugins); } resultListMenu.show(m_History.getList(), x, y); } /** * Save the currently selected clusterer output to a file. * * @param name the name of the buffer to save */ protected void saveBuffer(String name) { StringBuffer sb = m_History.getNamedBuffer(name); if (sb != null) { if (m_SaveOut.save(sb)) { m_Log.logMessage("Save successful."); } } } private void setIgnoreColumns() { ListSelectorDialog jd = new ListSelectorDialog(SwingUtilities.getWindowAncestor(this), m_ignoreKeyList); // Open the dialog int result = jd.showDialog(); if (result != ListSelectorDialog.APPROVE_OPTION) { // clear selected indices m_ignoreKeyList.clearSelection(); } updateCapabilitiesFilter(m_ClustererEditor.getCapabilitiesFilter()); } /** * Saves the currently selected clusterer */ protected void saveClusterer(String name, Clusterer clusterer, Instances trainHeader, int[] ignoredAtts) { File sFile = null; boolean saveOK = true; int returnVal = m_FileChooser.showSaveDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { sFile = m_FileChooser.getSelectedFile(); if (!sFile.getName().toLowerCase().endsWith(MODEL_FILE_EXTENSION)) { sFile = new File(sFile.getParent(), sFile.getName() + MODEL_FILE_EXTENSION); } m_Log.statusMessage("Saving model to file..."); try { OutputStream os = new FileOutputStream(sFile); if (sFile.getName().endsWith(".gz")) { os = new GZIPOutputStream(os); } ObjectOutputStream objectOutputStream = new ObjectOutputStream(os); objectOutputStream.writeObject(clusterer); if (trainHeader != null) { objectOutputStream.writeObject(trainHeader); } if (ignoredAtts != null) { objectOutputStream.writeObject(ignoredAtts); } objectOutputStream.flush(); objectOutputStream.close(); } catch (Exception e) { JOptionPane.showMessageDialog(null, e, "Save Failed", JOptionPane.ERROR_MESSAGE); saveOK = false; } if (saveOK) { m_Log.logMessage("Saved model (" + name + ") to file '" + sFile.getName() + "'"); } m_Log.statusMessage("OK"); } } /** * Loads a clusterer */ protected void loadClusterer() { int returnVal = m_FileChooser.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { File selected = m_FileChooser.getSelectedFile(); Clusterer clusterer = null; Instances trainHeader = null; int[] ignoredAtts = null; m_Log.statusMessage("Loading model from file..."); try { InputStream is = new FileInputStream(selected); if (selected.getName().endsWith(".gz")) { is = new GZIPInputStream(is); } // ObjectInputStream objectInputStream = new ObjectInputStream(is); ObjectInputStream objectInputStream = SerializationHelper.getObjectInputStream(is); clusterer = (Clusterer) objectInputStream.readObject(); try { // see if we can load the header & ignored attribute info trainHeader = (Instances) objectInputStream.readObject(); ignoredAtts = (int[]) objectInputStream.readObject(); } catch (Exception e) { } // don't fuss if we can't objectInputStream.close(); } catch (Exception e) { JOptionPane.showMessageDialog(null, e, "Load Failed", JOptionPane.ERROR_MESSAGE); } m_Log.statusMessage("OK"); if (clusterer != null) { m_Log.logMessage("Loaded model from file '" + selected.getName() + "'"); String name = (new SimpleDateFormat("HH:mm:ss - ")).format(new Date()); String cname = clusterer.getClass().getName(); if (cname.startsWith("weka.clusterers.")) { cname = cname.substring("weka.clusterers.".length()); } name += cname + " from file '" + selected.getName() + "'"; StringBuffer outBuff = new StringBuffer(); outBuff.append("=== Model information ===\n\n"); outBuff.append("Filename: " + selected.getName() + "\n"); outBuff.append("Scheme: " + clusterer.getClass().getName()); if (clusterer instanceof OptionHandler) { String[] o = ((OptionHandler) clusterer).getOptions(); outBuff.append(" " + Utils.joinOptions(o)); } outBuff.append("\n"); if (trainHeader != null) { outBuff.append("Relation: " + trainHeader.relationName() + '\n'); outBuff.append("Attributes: " + trainHeader.numAttributes() + '\n'); if (trainHeader.numAttributes() < 100) { boolean[] selectedAtts = new boolean[trainHeader.numAttributes()]; for (int i = 0; i < trainHeader.numAttributes(); i++) { selectedAtts[i] = true; } if (ignoredAtts != null) { for (int i = 0; i < ignoredAtts.length; i++) { selectedAtts[ignoredAtts[i]] = false; } } for (int i = 0; i < trainHeader.numAttributes(); i++) { if (selectedAtts[i]) { outBuff.append(" " + trainHeader.attribute(i).name() + '\n'); } } if (ignoredAtts != null) { outBuff.append("Ignored:\n"); for (int ignoredAtt : ignoredAtts) { outBuff.append(" " + trainHeader.attribute(ignoredAtt).name() + '\n'); } } } else { outBuff.append(" [list of attributes omitted]\n"); } } else { outBuff.append("\nTraining data unknown\n"); } outBuff.append("\n=== Clustering model ===\n\n"); outBuff.append(clusterer.toString() + "\n"); m_History.addResult(name, outBuff); m_History.setSingle(name); ArrayList<Object> vv = new ArrayList<Object>(); vv.add(clusterer); if (trainHeader != null) { vv.add(trainHeader); } if (ignoredAtts != null) { vv.add(ignoredAtts); } // allow visualization of graphable classifiers String grph = null; if (clusterer instanceof Drawable) { try { grph = ((Drawable) clusterer).graph(); } catch (Exception ex) { } } if (grph != null) { vv.add(grph); } m_History.addObject(name, vv); } } } /** * Re-evaluates the named clusterer with the current test set. Unpredictable * things will happen if the data set is not compatible with the clusterer. * * @param name the name of the clusterer entry * @param clusterer the clusterer to evaluate * @param trainHeader the header of the training set * @param ignoredAtts ignored attributes */ protected void reevaluateModel(final String name, final Clusterer clusterer, final Instances trainHeader, final int[] ignoredAtts) { if (m_RunThread == null) { m_StartBut.setEnabled(false); m_StopBut.setEnabled(true); m_ignoreBut.setEnabled(false); m_RunThread = new Thread() { @Override public void run() { // Copy the current state of things m_Log.statusMessage("Setting up..."); StringBuffer outBuff = m_History.getNamedBuffer(name); Instances userTest = null; ClustererAssignmentsPlotInstances plotInstances = ExplorerDefaults.getClustererAssignmentsPlotInstances(); plotInstances.setClusterer(clusterer); if (m_TestInstances != null) { userTest = new Instances(m_TestInstances); } boolean saveVis = m_StorePredictionsBut.isSelected(); String grph = null; try { if (userTest == null) { throw new Exception("No user test set has been opened"); } if (trainHeader != null && !trainHeader.equalHeaders(userTest)) { throw new Exception("Train and test set are not compatible\n" + trainHeader.equalHeadersMsg(userTest)); } m_Log.statusMessage("Evaluating on test data..."); m_Log.logMessage("Re-evaluating clusterer (" + name + ") on test set"); m_Log.logMessage("Started reevaluate model"); if (m_Log instanceof TaskLogger) { ((TaskLogger) m_Log).taskStarted(); } ClusterEvaluation eval = new ClusterEvaluation(); eval.setClusterer(clusterer); Instances userTestT = new Instances(userTest); if (ignoredAtts != null) { userTestT = removeIgnoreCols(userTestT, ignoredAtts); } eval.evaluateClusterer(userTestT); plotInstances.setClusterEvaluation(eval); plotInstances.setInstances(userTest); plotInstances.setUp(); outBuff.append("\n=== Re-evaluation on test set ===\n\n"); outBuff.append("User supplied test set\n"); outBuff.append("Relation: " + userTest.relationName() + '\n'); outBuff.append("Instances: " + userTest.numInstances() + '\n'); outBuff .append("Attributes: " + userTest.numAttributes() + "\n\n"); if (trainHeader == null) { outBuff .append("NOTE - if test set is not compatible then results are " + "unpredictable\n\n"); } outBuff.append(eval.clusterResultsToString()); outBuff.append("\n"); m_History.updateResult(name); m_Log.logMessage("Finished re-evaluation"); m_Log.statusMessage("OK"); } catch (Exception ex) { ex.printStackTrace(); m_Log.logMessage(ex.getMessage()); JOptionPane.showMessageDialog(ClustererPanel.this, "Problem evaluating clusterer:\n" + ex.getMessage(), "Evaluate clusterer", JOptionPane.ERROR_MESSAGE); m_Log.statusMessage("Problem evaluating clusterer"); } finally { if (plotInstances != null) { m_CurrentVis = new VisualizePanel(); if (getMainApplication() != null) { Settings settings = getMainApplication().getApplicationSettings(); m_CurrentVis.applySettings(settings, weka.gui.explorer.VisualizePanel.ScatterDefaults.ID); } m_CurrentVis.setName(name + " (" + userTest.relationName() + ")"); m_CurrentVis.setLog(m_Log); try { m_CurrentVis.addPlot(plotInstances.getPlotData(name)); } catch (Exception ex) { System.err.println(ex); } ArrayList<Object> vv = new ArrayList<Object>(); vv.add(clusterer); if (trainHeader != null) { vv.add(trainHeader); } if (ignoredAtts != null) { vv.add(ignoredAtts); } if (saveVis) { vv.add(m_CurrentVis); if (grph != null) { vv.add(grph); } } m_History.addObject(name, vv); } if (isInterrupted()) { m_Log.logMessage("Interrupted reevaluate model"); m_Log.statusMessage("See error log"); } m_RunThread = null; m_StartBut.setEnabled(true); m_StopBut.setEnabled(false); m_ignoreBut.setEnabled(true); if (m_Log instanceof TaskLogger) { ((TaskLogger) m_Log).taskFinished(); } } } }; m_RunThread.setPriority(Thread.MIN_PRIORITY); m_RunThread.start(); } } /** * updates the capabilities filter of the GOE * * @param filter the new filter to use */ protected void updateCapabilitiesFilter(Capabilities filter) { Instances tempInst; Capabilities filterClass; if (filter == null) { m_ClustererEditor.setCapabilitiesFilter(new Capabilities(null)); return; } if (!ExplorerDefaults.getInitGenericObjectEditorFilter()) { tempInst = new Instances(m_Instances, 0); } else { tempInst = new Instances(m_Instances); } tempInst.setClassIndex(-1); if (!m_ignoreKeyList.isSelectionEmpty()) { tempInst = removeIgnoreCols(tempInst); } if (m_ClassesToClustersBut.isSelected()) { // remove the class too String classSelection = m_ClassCombo.getSelectedItem().toString(); classSelection = classSelection.substring(classSelection.indexOf(")") + 1).trim(); int classIndex = tempInst.attribute(classSelection).index(); Remove rm = new Remove(); rm.setAttributeIndices("" + (classIndex + 1)); try { rm.setInputFormat(tempInst); tempInst = Filter.useFilter(tempInst, rm); } catch (Exception e) { e.printStackTrace(); } } try { filterClass = Capabilities.forInstances(tempInst); } catch (Exception e) { filterClass = new Capabilities(null); } m_ClustererEditor.setCapabilitiesFilter(filterClass); // check capabilities m_StartBut.setEnabled(true); Capabilities currentFilter = m_ClustererEditor.getCapabilitiesFilter(); Clusterer clusterer = (Clusterer) m_ClustererEditor.getValue(); Capabilities currentSchemeCapabilities = null; if (clusterer != null && currentFilter != null && (clusterer instanceof CapabilitiesHandler)) { currentSchemeCapabilities = ((CapabilitiesHandler) clusterer).getCapabilities(); if (!currentSchemeCapabilities.supportsMaybe(currentFilter) && !currentSchemeCapabilities.supports(currentFilter)) { m_StartBut.setEnabled(false); } } } /** * method gets called in case of a change event * * @param e the associated change event */ @Override public void capabilitiesFilterChanged(CapabilitiesFilterChangeEvent e) { if (e.getFilter() == null) { updateCapabilitiesFilter(null); } else { updateCapabilitiesFilter((Capabilities) e.getFilter().clone()); } } /** * Sets the Explorer to use as parent frame (used for sending notifications * about changes in the data) * * @param parent the parent frame */ @Override public void setExplorer(Explorer parent) { m_Explorer = parent; } /** * returns the parent Explorer frame * * @return the parent */ @Override public Explorer getExplorer() { return m_Explorer; } /** * Returns the title for the tab in the Explorer * * @return the title of this tab */ @Override public String getTabTitle() { return "Cluster"; } /** * Returns the tooltip for the tab in the Explorer * * @return the tooltip of this tab */ @Override public String getTabTitleToolTip() { return "Identify instance clusters"; } @Override public boolean requiresLog() { return true; } @Override public boolean acceptsInstances() { return true; } @Override public Defaults getDefaultSettings() { return new ClustererPanelDefaults(); } @Override public boolean okToBeActive() { return m_Instances != null; } @Override public void setActive(boolean active) { super.setActive(active); if (m_isActive) { settingsChanged(); } } @Override public void settingsChanged() { if (getMainApplication() != null) { if (!m_initialSettingsSet) { m_initialSettingsSet = true; Object initialC = getMainApplication().getApplicationSettings().getSetting( getPerspectiveID(), ClustererPanelDefaults.CLUSTERER_KEY, ClustererPanelDefaults.CLUSTERER, Environment.getSystemWide()); m_ClustererEditor.setValue(initialC); TestMode iniitalTestMode = getMainApplication().getApplicationSettings().getSetting( getPerspectiveID(), ClustererPanelDefaults.TEST_MODE_KEY, ClustererPanelDefaults.TEST_MODE, Environment.getSystemWide()); m_TrainBut.setSelected(iniitalTestMode == TestMode.USE_TRAINING_SET); m_PercentBut.setSelected(iniitalTestMode == TestMode.PERCENTAGE_SPLIT); m_TestSplitBut .setSelected(iniitalTestMode == TestMode.SUPPLIED_TEST_SET); m_ClassesToClustersBut .setSelected(iniitalTestMode == TestMode.CLASSES_TO_CLUSTERS_EVAL); m_StorePredictionsBut.setSelected(getMainApplication() .getApplicationSettings().getSetting(getPerspectiveID(), ClustererPanelDefaults.STORE_CLUSTERS_FOR_VIS_KEY, ClustererPanelDefaults.STORE_CLUSTERS_VIS, Environment.getSystemWide())); } Font outputFont = getMainApplication().getApplicationSettings().getSetting( getPerspectiveID(), ClustererPanelDefaults.OUTPUT_FONT_KEY, ClustererPanelDefaults.OUTPUT_FONT, Environment.getSystemWide()); m_OutText.setFont(outputFont); Color textColor = getMainApplication().getApplicationSettings() .getSetting(getPerspectiveID(), ClustererPanelDefaults.OUTPUT_TEXT_COLOR_KEY, ClustererPanelDefaults.OUTPUT_TEXT_COLOR, Environment.getSystemWide()); m_OutText.setForeground(textColor); Color outputBackgroundColor = getMainApplication().getApplicationSettings().getSetting( getPerspectiveID(), ClustererPanelDefaults.OUTPUT_BACKGROUND_COLOR_KEY, ClustererPanelDefaults.OUTPUT_BACKGROUND_COLOR, Environment.getSystemWide()); m_OutText.setBackground(outputBackgroundColor); m_History.setBackground(outputBackgroundColor); } } public static enum TestMode { PERCENTAGE_SPLIT, USE_TRAINING_SET, SUPPLIED_TEST_SET, CLASSES_TO_CLUSTERS_EVAL; } /** * Default settings for the clusterer panel */ protected static final class ClustererPanelDefaults extends Defaults { public static final String ID = "weka.gui.explorer.clustererpanel"; protected static final Settings.SettingKey CLUSTERER_KEY = new Settings.SettingKey(ID + ".initialClusterer", "Initial clusterer", "On startup, set this clusterer as the default one"); protected static final Clusterer CLUSTERER = new SimpleKMeans(); protected static final Settings.SettingKey TEST_MODE_KEY = new Settings.SettingKey(ID + ".initialTestMode", "Default test mode", ""); protected static final TestMode TEST_MODE = TestMode.USE_TRAINING_SET; protected static final Settings.SettingKey STORE_CLUSTERS_FOR_VIS_KEY = new Settings.SettingKey(ID + ".storeClusterersForVis", "Store clusters " + "for visualization", ""); protected static final boolean STORE_CLUSTERS_VIS = true; protected static final Settings.SettingKey OUTPUT_FONT_KEY = new Settings.SettingKey(ID + ".outputFont", "Font for text output", "Font to " + "use in the output area"); protected static final Font OUTPUT_FONT = new Font("Monospaced", Font.PLAIN, 12); protected static final Settings.SettingKey OUTPUT_TEXT_COLOR_KEY = new Settings.SettingKey(ID + ".outputFontColor", "Output text color", "Color " + "of output text"); protected static final Color OUTPUT_TEXT_COLOR = Color.black; protected static final Settings.SettingKey OUTPUT_BACKGROUND_COLOR_KEY = new Settings.SettingKey(ID + ".outputBackgroundColor", "Output background color", "Output background color"); protected static final Color OUTPUT_BACKGROUND_COLOR = Color.white; private static final long serialVersionUID = 2708388782229179493L; public ClustererPanelDefaults() { super(ID); m_defaults.put(CLUSTERER_KEY, CLUSTERER); m_defaults.put(TEST_MODE_KEY, TEST_MODE); m_defaults.put(STORE_CLUSTERS_FOR_VIS_KEY, STORE_CLUSTERS_VIS); m_defaults.put(OUTPUT_FONT_KEY, OUTPUT_FONT); m_defaults.put(OUTPUT_TEXT_COLOR_KEY, OUTPUT_TEXT_COLOR); m_defaults.put(OUTPUT_BACKGROUND_COLOR_KEY, OUTPUT_BACKGROUND_COLOR); } } /** * Tests out the clusterer panel from the command line. * * @param args may optionally contain the name of a dataset to load. */ public static void main(String[] args) { try { final javax.swing.JFrame jf = new javax.swing.JFrame("Weka Explorer: Cluster"); jf.getContentPane().setLayout(new BorderLayout()); final ClustererPanel sp = new ClustererPanel(); jf.getContentPane().add(sp, BorderLayout.CENTER); weka.gui.LogPanel lp = new weka.gui.LogPanel(); sp.setLog(lp); jf.getContentPane().add(lp, BorderLayout.SOUTH); jf.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { jf.dispose(); System.exit(0); } }); jf.pack(); jf.setSize(800, 600); jf.setVisible(true); if (args.length == 1) { System.err.println("Loading instances from " + args[0]); java.io.Reader r = new java.io.BufferedReader(new java.io.FileReader(args[0])); Instances i = new Instances(r); sp.setInstances(i); } } catch (Exception ex) { ex.printStackTrace(); System.err.println(ex.getMessage()); } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/explorer/ClustererPanelLaunchHandlerPlugin.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ClustererPanelLaunchHandlerPlugin.java * Copyright (C) 2011-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.explorer; /** * Interface to plugin that can take the current state of the * Clusterer panel and execute it. E.g. A plugin could be * made to train and evaluate the configured clusterer on * remote machine(s).<p> * * For full access to the protected member variables in the * ClustererPanel, an implementation will need to be packaged * in weka.gui.explorer. The ClustererPanel looks for implementations * when it is constructed, and will provide a new button (in the case * of a single plugin) or a button that pops up a menu (in the * case of multiple plugins) in order to invoke the launch() method * on the plugin. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision$ */ public interface ClustererPanelLaunchHandlerPlugin { /** * Allows the clusterer panel to pass in a reference to * itself * * @param p the ClustererPanel */ void setClustererPanel(ClustererPanel p); /** * Get the name of the launch command (to appear as * the button text or in the popup menu) * * @return the name of the launch command */ String getLaunchCommand(); /** * Gets called when the user clicks the button or selects this * plugin's entry from the popup menu. */ void launch(); }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/explorer/DataGeneratorPanel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * DataGeneratorPanel.java * Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.explorer; import java.awt.BorderLayout; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.PrintWriter; import java.io.StringReader; import java.io.StringWriter; import javax.swing.JOptionPane; import javax.swing.JPanel; import weka.core.Instances; import weka.core.OptionHandler; import weka.core.Utils; import weka.datagenerators.DataGenerator; import weka.gui.GenericObjectEditor; import weka.gui.Logger; import weka.gui.PropertyPanel; import weka.gui.SysErrLog; /** * A panel for generating artificial data via DataGenerators. * * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class DataGeneratorPanel extends JPanel { /** for serialization */ private static final long serialVersionUID = -2520408165350629380L; /** the GOE for the generators */ protected GenericObjectEditor m_GeneratorEditor = new GenericObjectEditor(); /** the generated Instances */ protected Instances m_Instances = null; /** the generated output (as text) */ protected StringWriter m_Output = new StringWriter(); /** The destination for log/status messages */ protected Logger m_Log = new SysErrLog(); /** register the classes */ static { GenericObjectEditor.registerEditors(); } /** * creates the panel */ public DataGeneratorPanel() { setLayout(new BorderLayout()); add(new PropertyPanel(m_GeneratorEditor), BorderLayout.CENTER); // editor m_GeneratorEditor.setClassType(DataGenerator.class); m_GeneratorEditor.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent e) { repaint(); } }); // set default generator setGenerator(null); } /** * Sets the Logger to receive informational messages * * @param value the Logger that will now get info messages */ public void setLog(Logger value) { m_Log = value; } /** * returns the generated instances, null if the process was cancelled. * * @return the generated Instances */ public Instances getInstances() { return m_Instances; } /** * returns the generated output as text * * @return the generated output */ public String getOutput() { return m_Output.toString(); } /** * sets the generator to use initially * * @param value the data generator to use */ public void setGenerator(DataGenerator value) { if (value != null) m_GeneratorEditor.setValue(value); else m_GeneratorEditor.setValue( new weka.datagenerators.classifiers.classification.RDG1()); } /** * returns the currently selected DataGenerator * * @return the current data generator */ public DataGenerator getGenerator() { return (DataGenerator) m_GeneratorEditor.getValue(); } /** * generates the instances, returns TRUE if successful * * stores output as a string * * @return TRUE if successful * @see #getInstances() */ public boolean execute() { return execute(true); } /** * generates the instances, returns TRUE if successful * * @param storeOutput whether to store output as string * * @return TRUE if successful * @see #getInstances() */ public boolean execute(boolean storeOutput) { boolean result = true; DataGenerator generator = (DataGenerator) m_GeneratorEditor.getValue(); String relName = generator.getRelationName(); String cname = generator.getClass().getName().replaceAll(".*\\.", ""); String cmd = generator.getClass().getName(); if (generator instanceof OptionHandler) { cmd += " " + Utils.joinOptions(((OptionHandler) generator).getOptions()); } try { m_Log.logMessage("Started " + cname); m_Log.logMessage("Command: " + cmd); m_Output = new StringWriter(); generator.setOutput(new PrintWriter(m_Output)); // define dataset format // computes actual number of examples to be produced generator.setDatasetFormat(generator.defineDataFormat()); if (storeOutput) { m_Output.append(generator.getPrologue()); } else { m_Output.append("String output of data generator has not been stored"); } if (generator.getSingleModeFlag()) { m_Instances = generator.getDatasetFormat(); for (int i = 0; i < generator.getNumExamplesAct(); i++) { m_Instances.add(generator.generateExample()); } } else { m_Instances = generator.generateExamples(); } if (storeOutput) { m_Output.append(m_Instances.toString()); m_Output.append(generator.getEpilogue()); } generator.getOutput().close(); m_Log.logMessage("Finished " + cname); } catch (Exception e) { e.printStackTrace(); JOptionPane.showMessageDialog(this, "Error generating data:\n" + e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); m_Instances = null; m_Output = new StringWriter(); result = false; } generator.setRelationName(relName); 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/explorer/Explorer.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * Explorer.java * Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.explorer; import weka.core.Capabilities; import weka.core.Copyright; import weka.core.Instances; import weka.core.Memory; import weka.core.PluginManager; import weka.core.WekaPackageClassLoaderManager; import weka.core.converters.AbstractFileLoader; import weka.core.converters.ConverterUtils; import weka.gui.LogPanel; import weka.gui.Logger; import weka.gui.LookAndFeel; import weka.gui.WekaTaskMonitor; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTabbedPane; import javax.swing.event.ChangeEvent; import java.awt.BorderLayout; import java.awt.Image; import java.awt.Toolkit; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; import java.util.EventListener; import java.util.HashSet; import java.util.Hashtable; import java.util.Vector; /** * The main class for the Weka explorer. Lets the user create, open, save, * configure, datasets, and perform ML analysis. * * @author Len Trigg (trigg@cs.waikato.ac.nz) * @version $Revision$ */ public class Explorer extends JPanel { /** for serialization */ private static final long serialVersionUID = -7674003708867909578L; /** * Interface for classes that listen for filter changes. * * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public static interface CapabilitiesFilterChangeListener extends EventListener { /** * method gets called in case of a change event * * @param e the associated change event */ public void capabilitiesFilterChanged(CapabilitiesFilterChangeEvent e); } /** * This event can be fired in case the capabilities filter got changed * * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public static class CapabilitiesFilterChangeEvent extends ChangeEvent { /** for serialization */ private static final long serialVersionUID = 1194260517270385559L; /** the capabilities filter */ protected Capabilities m_Filter; /** * Constructs a GOECapabilitiesFilterChangeEvent object. * * @param source the Object that is the source of the event * @param filter the responsible capabilities filter */ public CapabilitiesFilterChangeEvent(Object source, Capabilities filter) { super(source); m_Filter = filter; } /** * returns the associated Capabilities filter * * @return the filter */ public Capabilities getFilter() { return m_Filter; } } /** * A common interface for panels to be displayed in the Explorer * * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public static interface ExplorerPanel { /** * Sets the Explorer to use as parent frame (used for sending notifications * about changes in the data) * * @param parent the parent frame */ public void setExplorer(Explorer parent); /** * returns the parent Explorer frame * * @return the parent */ public Explorer getExplorer(); /** * Tells the panel to use a new set of instances. * * @param inst a set of Instances */ public void setInstances(Instances inst); /** * Returns the title for the tab in the Explorer * * @return the title of this tab */ public String getTabTitle(); /** * Returns the tooltip for the tab in the Explorer * * @return the tooltip of this tab */ public String getTabTitleToolTip(); } /** * A common interface for panels in the explorer that can handle logs * * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public static interface LogHandler { /** * Sets the Logger to receive informational messages * * @param newLog the Logger that will now get info messages */ public void setLog(Logger newLog); } /** The panel for preprocessing instances */ protected PreprocessPanel m_PreprocessPanel = new PreprocessPanel(); /** Contains all the additional panels apart from the pre-processing panel */ protected Vector<ExplorerPanel> m_Panels = new Vector<ExplorerPanel>(); /** The tabbed pane that controls which sub-pane we are working with */ protected JTabbedPane m_TabbedPane = new JTabbedPane(); /** The panel for log and status messages */ protected LogPanel m_LogPanel = new LogPanel(new WekaTaskMonitor()); /** the listeners that listen to filter changes */ protected HashSet<CapabilitiesFilterChangeListener> m_CapabilitiesFilterChangeListeners = new HashSet<CapabilitiesFilterChangeListener>(); /** * Creates the experiment environment gui with no initial experiment */ public Explorer() { String date = (new SimpleDateFormat("EEEE, d MMMM yyyy")) .format(new Date()); m_LogPanel.logMessage("Weka Explorer"); m_LogPanel.logMessage("(c) " + Copyright.getFromYear() + "-" + Copyright.getToYear() + " " + Copyright.getOwner() + ", " + Copyright.getAddress()); m_LogPanel.logMessage("web: " + Copyright.getURL()); m_LogPanel.logMessage("Started on " + date); m_LogPanel.statusMessage("Welcome to the Weka Explorer"); // intialize pre-processpanel m_PreprocessPanel.setLog(m_LogPanel); m_TabbedPane.addTab(m_PreprocessPanel.getTabTitle(), null, m_PreprocessPanel, m_PreprocessPanel.getTabTitleToolTip()); // initialize additional panels String[] tabs = ExplorerDefaults.getTabs(); Hashtable<String, HashSet<String>> tabOptions = new Hashtable<String, HashSet<String>>(); for (String tab : tabs) { try { // determine classname and additional options String[] optionsStr = tab.split(":"); String classname = optionsStr[0]; if (PluginManager.isInDisabledList(classname)) { continue; } HashSet<String> options = new HashSet<String>(); tabOptions.put(classname, options); for (int n = 1; n < optionsStr.length; n++) { options.add(optionsStr[n]); } // setup panel ExplorerPanel panel = (ExplorerPanel) WekaPackageClassLoaderManager.forName(classname) .newInstance(); panel.setExplorer(this); m_Panels.add(panel); if (panel instanceof LogHandler) { ((LogHandler) panel).setLog(m_LogPanel); } m_TabbedPane.addTab(panel.getTabTitle(), null, (JPanel) panel, panel.getTabTitleToolTip()); } catch (Exception e) { e.printStackTrace(); } } // setup tabbed pane m_TabbedPane.setSelectedIndex(0); for (int i = 0; i < m_Panels.size(); i++) { HashSet<String> options = tabOptions.get(m_Panels.get(i).getClass() .getName()); m_TabbedPane.setEnabledAt(i + 1, options.contains("standalone")); } // setup notification for dataset changes m_PreprocessPanel.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent e) { for (int i = 0; i < m_Panels.size(); i++) { m_Panels.get(i).setInstances(m_PreprocessPanel.getInstances()); m_TabbedPane.setEnabledAt(i + 1, true); } } }); // add listeners for changes in the capabilities m_PreprocessPanel.setExplorer(this); addCapabilitiesFilterListener(m_PreprocessPanel); for (int i = 0; i < m_Panels.size(); i++) { if (m_Panels.get(i) instanceof CapabilitiesFilterChangeListener) { addCapabilitiesFilterListener((CapabilitiesFilterChangeListener) m_Panels .get(i)); } } // add components to layout setLayout(new BorderLayout()); add(m_TabbedPane, BorderLayout.CENTER); add(m_LogPanel, BorderLayout.SOUTH); } /** * returns all the panels, apart from the PreprocessPanel * * @return the currently displayed panels w/o PreprocessPanel */ public Vector<ExplorerPanel> getPanels() { return m_Panels; } /** * returns the instance of the PreprocessPanel being used in this instance of * the Explorer * * @return the panel */ public PreprocessPanel getPreprocessPanel() { return m_PreprocessPanel; } /** * returns the tabbed pane of the Explorer * * @return the tabbed pane */ public JTabbedPane getTabbedPane() { return m_TabbedPane; } /** * adds the listener to the list of objects that listen for changes of the * CapabilitiesFilter * * @param l the listener to add * @see #m_CapabilitiesFilterChangeListeners */ public void addCapabilitiesFilterListener(CapabilitiesFilterChangeListener l) { m_CapabilitiesFilterChangeListeners.add(l); } /** * Removes the specified listener from the set of listeners if it is present. * * @param l the listener to remove * @return true if the listener was registered */ public boolean removeCapabilitiesFilterListener( CapabilitiesFilterChangeListener l) { return m_CapabilitiesFilterChangeListeners.remove(l); } /** * notifies all the listeners of a change * * @param filter the affected filter */ public void notifyCapabilitiesFilterListener(Capabilities filter) { for (CapabilitiesFilterChangeListener l : m_CapabilitiesFilterChangeListeners) { if (l == this) { continue; } l.capabilitiesFilterChanged(new CapabilitiesFilterChangeEvent(this, filter)); } } /** * variable for the Explorer class which would be set to null by the memory * monitoring thread to free up some memory if we running out of memory */ private static Explorer m_explorer; /** for monitoring the Memory consumption */ protected static Memory m_Memory = new Memory(true); /** * Tests out the explorer environment. * * @param args ignored. */ public static void main(String[] args) { weka.core.logging.Logger.log(weka.core.logging.Logger.Level.INFO, "Logging started"); LookAndFeel.setLookAndFeel(); // make sure that packages are loaded and the GenericPropertiesCreator // executes to populate the lists correctly weka.gui.GenericObjectEditor.determineClasses(); try { // uncomment to disable the memory management: // m_Memory.setEnabled(false); m_explorer = new Explorer(); final JFrame jf = new JFrame("Weka Explorer"); jf.getContentPane().setLayout(new BorderLayout()); jf.getContentPane().add(m_explorer, BorderLayout.CENTER); jf.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { jf.dispose(); System.exit(0); } }); jf.pack(); jf.setSize(800, 600); jf.setVisible(true); Image icon = Toolkit.getDefaultToolkit().getImage( m_explorer.getClass().getClassLoader() .getResource("weka/gui/weka_icon_new_48.png")); jf.setIconImage(icon); if (args.length == 1) { System.err.println("Loading instances from " + args[0]); AbstractFileLoader loader = ConverterUtils.getLoaderForFile(args[0]); loader.setFile(new File(args[0])); m_explorer.m_PreprocessPanel.setInstancesFromFile(loader); } Thread memMonitor = new Thread() { @Override public void run() { while (true) { // try { // System.out.println("Before sleeping."); // Thread.sleep(10); if (m_Memory.isOutOfMemory()) { // clean up jf.dispose(); m_explorer = 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/explorer/ExplorerDefaults.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ExplorerDefaults.java * Copyright (C) 2006-2012 University of Waikato, Hamilton, New Zealand */ package weka.gui.explorer; import java.io.Serializable; import java.util.Collections; import java.util.Enumeration; import java.util.Properties; import java.util.Vector; import weka.core.Utils; /** * This class offers get methods for the default Explorer settings in the props * file <code>weka/gui/explorer/Explorer.props</code>. * * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ * @see #PROPERTY_FILE */ public class ExplorerDefaults implements Serializable { /** for serialization. */ private static final long serialVersionUID = 4954795757927524225L; /** The name of the properties file. */ public final static String PROPERTY_FILE = "weka/gui/explorer/Explorer.props"; /** Properties associated with the explorer options. */ protected static Properties PROPERTIES; static { try { PROPERTIES = Utils.readProperties(PROPERTY_FILE); } catch (Exception e) { System.err.println("Problem reading properties. Fix before continuing."); e.printStackTrace(); PROPERTIES = new Properties(); } } /** * returns the value for the specified property, if non-existent then the * default value. * * @param property the property to retrieve the value for * @param defaultValue the default value for the property * @return the value of the specified property */ public static String get(String property, String defaultValue) { return PROPERTIES.getProperty(property, defaultValue); } public static void set(String property, String value) { PROPERTIES.setProperty(property, value); } /** * returns the associated properties file. * * @return the props file */ public final static Properties getProperties() { return PROPERTIES; } /** * Tries to instantiate the class stored for this property, optional options * will be set as well. Returns null if unsuccessful. * * @param property the property to get the object for * @param defaultValue the default object spec string * @return if successful the fully configured object, null otherwise */ protected static Object getObject(String property, String defaultValue) { return getObject(property, defaultValue, Object.class); } /** * Tries to instantiate the class stored for this property, optional options * will be set as well. Returns null if unsuccessful. * * @param property the property to get the object for * @param defaultValue the default object spec string * @param cls the class the object must be derived from * @return if successful the fully configured object, null otherwise */ protected static Object getObject(String property, String defaultValue, Class<?> cls) { Object result; String tmpStr; String[] tmpOptions; result = null; try { tmpStr = get(property, defaultValue); tmpOptions = Utils.splitOptions(tmpStr); if (tmpOptions.length != 0) { tmpStr = tmpOptions[0]; tmpOptions[0] = ""; result = Utils.forName(cls, tmpStr, tmpOptions); } } catch (Exception e) { e.printStackTrace(); result = null; } return result; } /** * returns if the GOEs in the Explorer will be initialized based on the data * that is loaded into the Explorer. * * @return true if the GOEs get initialized */ public static boolean getInitGenericObjectEditorFilter() { return Boolean.parseBoolean(get("InitGenericObjectEditorFilter", "false")); } /** * returns an array with the classnames of all the additional panels to * display as tabs in the Explorer. * * @return the classnames */ public static String[] getTabs() { String[] result; String tabs; // read and split on comma tabs = get( "Tabs", "weka.gui.explorer.ClassifierPanel,weka.gui.explorer.ClustererPanel,weka.gui.explorer.AssociationsPanel,weka.gui.explorer.AttributeSelectionPanel,weka.gui.explorer.VisualizePanel"); result = tabs.split(","); return result; } /** * Returns the initial directory for the file chooser used for opening * datasets. * <p/> * The following placeholders are recognized: * * <pre> * %t - the temp directory * %h - the user's home directory * %c - the current directory * %% - gets replaced by a single percentage sign * </pre> * * @return the default directory */ public static String getInitialDirectory() { String result; result = get("InitialDirectory", "%c"); result = result.replaceAll("%t", System.getProperty("java.io.tmpdir")); result = result.replaceAll("%h", System.getProperty("user.home")); result = result.replaceAll("%c", System.getProperty("user.dir")); result = result.replaceAll("%%", System.getProperty("%")); return result; } /** * returns the default filter (fully configured) for the preprocess panel. * * @return the default filter, null if none */ public static Object getFilter() { return getObject("Filter", "", weka.filters.Filter.class); } /** * returns the default classifier (fully configured) for the classify panel. * * @return the default classifier, ZeroR by default */ public static Object getClassifier() { Object result; result = getObject("Classifier", weka.classifiers.rules.ZeroR.class.getName(), weka.classifiers.Classifier.class); if (result == null) { result = new weka.classifiers.rules.ZeroR(); } return result; } /** * returns the default classifier test mode for the classify panel. * * @return the default test mode */ public static int getClassifierTestMode() { return Integer.parseInt(get("ClassifierTestMode", "1")); } /** * returns the default number of folds of the CV in the classify panel. * * @return the default number of folds */ public static int getClassifierCrossvalidationFolds() { return Integer.parseInt(get("ClassifierCrossvalidationFolds", "10")); } /** * returns the default classifier test mode for the classify panel (0-99). * * @return the default precentage split */ public static int getClassifierPercentageSplit() { return Integer.parseInt(get("ClassifierPercentageSplit", "66")); } /** * returns whether the built model is output. * * @return true if the built model is output */ public static boolean getClassifierOutputModel() { return Boolean.parseBoolean(get("ClassifierOutputModel", "true")); } /** * returns whether the models built for the training set are output * * @return true if the models built for the training set are output */ public static boolean getClassifierOutputModelsForTrainingSplits() { return Boolean.parseBoolean(get("ClassifierOutputModelsForTrainingSplits", "false")); } /** * returns whether additional per-class stats of the classifier are output. * * @return true if stats are output */ public static boolean getClassifierOutputPerClassStats() { return Boolean.parseBoolean(get("ClassifierOutputPerClassStats", "true")); } /** * returns whether entropy-based evaluation meastures of the classifier are * output. * * @return true if output */ public static boolean getClassifierOutputEntropyEvalMeasures() { return Boolean.parseBoolean(get("ClassifierOutputEntropyEvalMeasures", "false")); } /** * returns whether the confusion matrix for the classifier is output. * * @return true if matrix is output */ public static boolean getClassifierOutputConfusionMatrix() { return Boolean.parseBoolean(get("ClassifierOutputConfusionMatrix", "true")); } /** * returns whether the predictions of the classifier are output as well. * * @return true if predictions are output as well */ public static boolean getClassifierOutputPredictions() { return Boolean.parseBoolean(get("ClassifierOutputPredictions", "false")); } /** * returns the string with the additional indices to output alongside the * predictions. * * @return the indices, 0 if none are output */ public static String getClassifierOutputAdditionalAttributes() { return get("ClassifierOutputAdditionalAttributes", ""); } /** * returns whether the predictions of the classifier are stored for * visualization. * * @return true if predictions are stored */ public static boolean getClassifierStorePredictionsForVis() { return Boolean .parseBoolean(get("ClassifierStorePredictionsForVis", "true")); } /** * returns whether the evaluation of the classifier is done cost-sensitively. * * @return true if cost-sensitively done */ public static boolean getClassifierCostSensitiveEval() { return Boolean.parseBoolean(get("ClassifierCostSensitiveEval", "false")); } /** * returns the default random seed value for the classifier for the classify * panel. * * @return the default random seed */ public static int getClassifierRandomSeed() { return Integer.parseInt(get("ClassifierRandomSeed", "1")); } /** * returns whether the order is preserved in case of the percentage split in * the classify tab. * * @return true if order is preserved */ public static boolean getClassifierPreserveOrder() { return Boolean.parseBoolean(get("ClassifierPreserveOrder", "false")); } /** * returns whether the source of a sourcable Classifier is output in the * classify tab. * * @return true if the source code is output */ public static boolean getClassifierOutputSourceCode() { return Boolean.parseBoolean(get("ClassifierOutputSourceCode", "false")); } /** * returns the default classname for a sourcable Classifier in the classify * tab. * * @return the default classname */ public static String getClassifierSourceCodeClass() { return get("ClassifierSourceCodeClass", "Foobar"); } /** * Returns an instance of the class used for generating plot instances for * displaying the classifier errors. * * @return an instance of the class */ public static ClassifierErrorsPlotInstances getClassifierErrorsPlotInstances() { ClassifierErrorsPlotInstances result; String classname; String[] options; try { options = Utils.splitOptions(get("ClassifierErrorsPlotInstances", "weka.gui.explorer.ClassifierErrorsPlotInstances")); classname = options[0]; options[0] = ""; result = (ClassifierErrorsPlotInstances) Utils.forName( ClassifierErrorsPlotInstances.class, classname, options); } catch (Exception e) { e.printStackTrace(); result = new ClassifierErrorsPlotInstances(); } return result; } /** * Returns the minimum size in pixels for plots of plotting classifier errors * of numeric attributes. * * @return the size */ public static int getClassifierErrorsMinimumPlotSizeNumeric() { return Integer.parseInt(get("ClassifierErrorsMinimumPlotSizeNumeric", "1")); } /** * Returns the maximum size in pixels for plots of plotting classifier errors * of numeric attributes. * * @return the size */ public static int getClassifierErrorsMaximumPlotSizeNumeric() { return Integer .parseInt(get("ClassifierErrorsMaximumPlotSizeNumeric", "20")); } /** * returns the default clusterer (fully configured) for the clusterer panel. * * @return the default clusterer, EM by default */ public static Object getClusterer() { Object result; result = getObject("Clusterer", weka.clusterers.EM.class.getName(), weka.clusterers.Clusterer.class); if (result == null) { result = new weka.clusterers.EM(); } return result; } /** * returns the default cluster test mode for the cluster panel. * * @return the default test mode */ public static int getClustererTestMode() { return Integer.parseInt(get("ClustererTestMode", "3")); } /** * returns whether the clusters are storeed for visualization purposes in the * cluster panel. * * @return true if clusters are stored */ public static boolean getClustererStoreClustersForVis() { return Boolean.parseBoolean(get("ClustererStoreClustersForVis", "true")); } /** * Returns an instance of the class used for generating plot instances for * displaying the cluster assignments. * * @return an instance of the class */ public static ClustererAssignmentsPlotInstances getClustererAssignmentsPlotInstances() { ClustererAssignmentsPlotInstances result; String classname; String[] options; try { options = Utils.splitOptions(get("ClustererAssignmentsPlotInstances", "weka.gui.explorer.ClustererAssignmentsPlotInstances")); classname = options[0]; options[0] = ""; result = (ClustererAssignmentsPlotInstances) Utils.forName( ClustererAssignmentsPlotInstances.class, classname, options); } catch (Exception e) { e.printStackTrace(); result = new ClustererAssignmentsPlotInstances(); } return result; } /** * returns the default associator (fully configured) for the associations * panel. * * @return the default associator, Apriori by default */ public static Object getAssociator() { Object result; result = getObject("Associator", weka.associations.Apriori.class.getName(), weka.associations.Associator.class); if (result == null) { result = new weka.associations.Apriori(); } return result; } /** * returns the default attribute evalautor (fully configured) for the * attribute selection panel. * * @return the default attribute evaluator, CfsSubsetEval by default */ public static Object getASEvaluator() { Object result; result = getObject("ASEvaluation", weka.attributeSelection.CfsSubsetEval.class.getName(), weka.attributeSelection.ASEvaluation.class); if (result == null) { result = new weka.attributeSelection.CfsSubsetEval(); } return result; } /** * returns the default attribute selection search scheme (fully configured) * for the attribute selection panel. * * @return the default search scheme, BestFirst by default */ public static Object getASSearch() { Object result; result = getObject("ASSearch", weka.attributeSelection.BestFirst.class.getName(), weka.attributeSelection.ASSearch.class); if (result == null) { result = new weka.attributeSelection.BestFirst(); } return result; } /** * returns the default attribute selection test mode for the attribute * selection panel. * * @return the default test mode */ public static int getASTestMode() { return Integer.parseInt(get("ASTestMode", "0")); } /** * returns the default number of folds of the CV in the attribute selection * panel. * * @return the default number of folds */ public static int getASCrossvalidationFolds() { return Integer.parseInt(get("ASCrossvalidationFolds", "10")); } /** * returns the default random seed value in the attribute selection panel. * * @return the default random seed */ public static int getASRandomSeed() { return Integer.parseInt(get("ASRandomSeed", "1")); } /** * only for testing - prints the content of the props file. * * @param args commandline parameters - ignored */ public static void main(String[] args) { Enumeration<?> names; String name; Vector<String> sorted; System.out.println("\nExplorer defaults:"); names = PROPERTIES.propertyNames(); // sort names sorted = new Vector<String>(); while (names.hasMoreElements()) { sorted.add(names.nextElement().toString()); } Collections.sort(sorted); names = sorted.elements(); // output while (names.hasMoreElements()) { name = names.nextElement().toString(); System.out.println("- " + name + ": " + PROPERTIES.getProperty(name, "")); } System.out.println(); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/explorer/PreprocessPanel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * PreprocessPanel.java * Copyright (C) 2003-2013 University of Waikato, Hamilton, New Zealand * */ package weka.gui.explorer; import weka.core.Capabilities; import weka.core.CapabilitiesHandler; import weka.core.Defaults; import weka.core.Environment; import weka.core.Instances; import weka.core.OptionHandler; import weka.core.Settings; import weka.core.Utils; import weka.core.converters.AbstractFileLoader; import weka.core.converters.AbstractFileSaver; import weka.core.converters.ConverterUtils; import weka.core.converters.Loader; import weka.core.converters.SerializedInstancesLoader; import weka.core.converters.URLSourcedLoader; import weka.datagenerators.DataGenerator; import weka.experiment.InstanceQuery; import weka.filters.AllFilter; import weka.filters.Filter; import weka.filters.SupervisedFilter; import weka.filters.unsupervised.attribute.Remove; import weka.gui.AbstractPerspective; import weka.gui.AttributeSelectionPanel; import weka.gui.AttributeSummaryPanel; import weka.gui.AttributeVisualizationPanel; import weka.gui.ConverterFileChooser; import weka.gui.GenericObjectEditor; import weka.gui.InstancesSummaryPanel; import weka.gui.Logger; import weka.gui.Perspective; import weka.gui.PerspectiveInfo; import weka.gui.PropertyDialog; import weka.gui.PropertyPanel; import weka.gui.SysErrLog; import weka.gui.TaskLogger; import weka.gui.ViewerDialog; import weka.gui.WorkbenchApp; import weka.gui.explorer.Explorer.CapabilitiesFilterChangeEvent; import weka.gui.explorer.Explorer.CapabilitiesFilterChangeListener; import weka.gui.explorer.Explorer.ExplorerPanel; import weka.gui.explorer.Explorer.LogHandler; import weka.gui.sql.SqlViewerDialog; 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.JMenu; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.KeyStroke; import javax.swing.ListSelectionModel; import javax.swing.SwingUtilities; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.event.TableModelEvent; import javax.swing.event.TableModelListener; import javax.swing.filechooser.FileFilter; import javax.swing.table.TableModel; import java.awt.*; 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.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.BufferedOutputStream; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.ObjectOutputStream; import java.net.URL; import java.util.ArrayList; import java.util.List; /** * This panel controls simple preprocessing of instances. Summary information on * instances and attributes is shown. Filters may be configured to alter the set * of instances. Altered instances may also be saved. * * @author Richard Kirkby (rkirkby@cs.waikato.ac.nz) * @author Len Trigg (trigg@cs.waikato.ac.nz) * @version $Revision$ */ @PerspectiveInfo(ID = "weka.gui.explorer.preprocesspanel", title = "Preprocess", toolTipText = "Preprocess data", iconPath = "weka/gui/weka_icon_new_small.png") public class PreprocessPanel extends AbstractPerspective implements CapabilitiesFilterChangeListener, ExplorerPanel, LogHandler { /** for serialization */ private static final long serialVersionUID = 6764850273874813049L; /** Displays simple stats on the working instances */ protected InstancesSummaryPanel m_InstSummaryPanel = new InstancesSummaryPanel(); /** Click to load base instances from a file */ protected JButton m_OpenFileBut = new JButton("Open file..."); /** Click to load base instances from a URL */ protected JButton m_OpenURLBut = new JButton("Open URL..."); /** Click to load base instances from a Database */ protected JButton m_OpenDBBut = new JButton("Open DB..."); /** Click to generate artificial data */ protected JButton m_GenerateBut = new JButton("Generate..."); /** Click to revert back to the last saved point */ protected JButton m_UndoBut = new JButton("Undo"); /** Click to open the current instances in a viewer */ protected JButton m_EditBut = new JButton("Edit..."); protected JMenuItem m_EditM = new JMenuItem("Edit..."); /** For sending instances to various perspectives/tabs */ protected JMenu m_sendToPerspective; /** Click to apply filters and save the results */ protected JButton m_SaveBut = new JButton("Save..."); /** Panel to let the user toggle attributes */ protected AttributeSelectionPanel m_AttPanel = new AttributeSelectionPanel(); /** Button for removing attributes */ protected JButton m_RemoveButton = new JButton("Remove"); /** Displays summary stats on the selected attribute */ protected AttributeSummaryPanel m_AttSummaryPanel = new AttributeSummaryPanel(); /** Lets the user configure the filter */ protected GenericObjectEditor m_FilterEditor = new GenericObjectEditor(); /** Filter configuration */ protected PropertyPanel m_FilterPanel = new PropertyPanel(m_FilterEditor); /** Click to apply filters and save the results */ protected JButton m_ApplyFilterBut = new JButton("Apply"); /** Click to stop a running filter */ protected JButton m_StopBut = new JButton("Stop"); /** The file chooser for selecting data files */ protected ConverterFileChooser m_FileChooser; /** Stores the last URL that instances were loaded from */ protected String m_LastURL = "http://"; /** Stores the last sql query executed */ protected String m_SQLQ = new String("SELECT * FROM ?"); /** The working instances */ protected Instances m_Instances; /** The last generator that was selected */ protected DataGenerator m_DataGenerator = null; /** The visualization of the attribute values */ protected AttributeVisualizationPanel m_AttVisualizePanel = new AttributeVisualizationPanel(); /** Keeps track of undo points */ protected File[] m_tempUndoFiles = new File[20]; // set number of undo ops // here /** The next available slot for an undo point */ protected int m_tempUndoIndex = 0; /** * Manages sending notifications to people when we change the set of working * instances. */ protected PropertyChangeSupport m_Support = new PropertyChangeSupport(this); /** A thread for loading/saving instances from a file or URL */ protected Thread m_IOThread; /** The message logger */ protected Logger m_Log = new SysErrLog(); /** the parent frame */ protected Explorer m_Explorer = null; /** True after settings have been applied the first time */ protected boolean m_initialSettingsSet; /** Menus provided by this perspective */ protected List<JMenu> m_menus = new ArrayList<JMenu>(); /** * Creates the instances panel with no initial instances. */ public PreprocessPanel() { String initialDir = ExplorerDefaults.getInitialDirectory(); m_FileChooser = new ConverterFileChooser(new File(initialDir)); // Create/Configure/Connect components m_FilterEditor.setClassType(weka.filters.Filter.class); if (ExplorerDefaults.getFilter() != null) m_FilterEditor.setValue(ExplorerDefaults.getFilter()); m_FilterEditor.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent e) { m_ApplyFilterBut.setEnabled(getInstances() != null); Capabilities currentCapabilitiesFilter = m_FilterEditor.getCapabilitiesFilter(); Filter filter = (Filter) m_FilterEditor.getValue(); Capabilities currentFilterCapabilities = null; if (filter != null && currentCapabilitiesFilter != null && (filter instanceof CapabilitiesHandler)) { currentFilterCapabilities = ((CapabilitiesHandler) filter).getCapabilities(); if (!currentFilterCapabilities .supportsMaybe(currentCapabilitiesFilter) && !currentFilterCapabilities.supports(currentCapabilitiesFilter)) { try { filter.setInputFormat(getInstances()); } catch (Exception ex) { m_ApplyFilterBut.setEnabled(false); } } } } }); JMenu fileMenu = new JMenu(); fileMenu.setText("File"); m_menus.add(fileMenu); m_OpenFileBut.setToolTipText("Open a set of instances from a file"); JMenuItem openFileM = new JMenuItem("Open file..."); openFileM.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, InputEvent.CTRL_DOWN_MASK)); fileMenu.add(openFileM); m_OpenURLBut.setToolTipText("Open a set of instances from a URL"); JMenuItem openURLM = new JMenuItem("Open URL..."); openURLM.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_U, InputEvent.CTRL_DOWN_MASK)); fileMenu.add(openURLM); m_OpenDBBut.setToolTipText("Open a set of instances from a database"); JMenuItem openDBM = new JMenuItem("Open DB..."); openDBM.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D, InputEvent.CTRL_DOWN_MASK)); fileMenu.add(openDBM); m_GenerateBut.setToolTipText("Generates artificial data"); JMenuItem generateM = new JMenuItem("Generate..."); generateM.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G, InputEvent.CTRL_DOWN_MASK)); m_UndoBut.setToolTipText("Undo the last change to the dataset"); fileMenu.add(generateM); m_UndoBut.setEnabled(ExplorerDefaults.get("enableUndo", "true") .equalsIgnoreCase("true")); if (!m_UndoBut.isEnabled()) { m_UndoBut.setToolTipText("Undo is disabled - " + "see weka.gui.explorer.Explorer.props to enable"); } m_EditBut .setToolTipText("Open the current dataset in a Viewer for editing"); JMenu editMenu = new JMenu(); editMenu.add(m_EditM); m_EditM.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, InputEvent.CTRL_DOWN_MASK)); m_EditM.setEnabled(false); editMenu.setText("Edit"); m_menus.add(editMenu); m_SaveBut.setToolTipText("Save the working relation to a file"); m_ApplyFilterBut.setToolTipText("Apply the current filter to the data"); m_StopBut.setToolTipText("Stop the filtering process"); m_FileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); m_OpenURLBut.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { setInstancesFromURLQ(); } }); openURLM.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { setInstancesFromURLQ(); } }); m_OpenDBBut.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JFrame frame = null; Window window = SwingUtilities.getWindowAncestor(PreprocessPanel.this); if (window instanceof JFrame) { frame = (JFrame)window; } SqlViewerDialog dialog = new SqlViewerDialog(frame); dialog.pack(); dialog.setSize(800, 700); dialog.setIconImage(((Frame) SwingUtilities.getWindowAncestor(PreprocessPanel.this)).getIconImage()); dialog.setLocationRelativeTo(SwingUtilities.getWindowAncestor(PreprocessPanel.this)); dialog.setVisible(true); if (dialog.getReturnValue() == JOptionPane.OK_OPTION) setInstancesFromDBQ(dialog.getURL(), dialog.getUser(), dialog.getPassword(), dialog.getQuery(), dialog.getGenerateSparseData()); } }); m_OpenFileBut.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { setInstancesFromFileQ(); } }); openFileM.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { setInstancesFromFileQ(); } }); m_GenerateBut.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { generateInstances(); } }); generateM.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { generateInstances(); } }); m_UndoBut.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { undo(); } }); m_EditBut.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { edit(); } }); m_EditM.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { edit(); } }); m_SaveBut.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { saveWorkingInstancesToFileQ(); } }); m_ApplyFilterBut.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { applyFilter((Filter) m_FilterEditor.getValue()); } }); m_StopBut.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (m_IOThread != null) { m_IOThread.stop(); m_StopBut.setEnabled(false); m_IOThread = null; if (m_Log instanceof TaskLogger) { ((TaskLogger) m_Log).taskFinished(); } m_Log.statusMessage("Filtering process stopped prematurely"); } } }); m_AttPanel.getSelectionModel().addListSelectionListener( new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { ListSelectionModel lm = (ListSelectionModel) e.getSource(); for (int i = e.getFirstIndex(); i <= e.getLastIndex(); i++) { if (lm.isSelectedIndex(i)) { m_AttSummaryPanel.setAttribute(i); m_AttVisualizePanel.setAttribute(i); break; } } } } }); m_InstSummaryPanel.setBorder(BorderFactory .createTitledBorder("Current relation")); JPanel attStuffHolderPanel = new JPanel(); attStuffHolderPanel.setBorder(BorderFactory .createTitledBorder("Attributes")); attStuffHolderPanel.setLayout(new BorderLayout()); attStuffHolderPanel.add(m_AttPanel, BorderLayout.CENTER); m_RemoveButton.setEnabled(false); m_RemoveButton.setToolTipText("Remove selected attributes."); m_RemoveButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { Remove r = new Remove(); int[] selected = m_AttPanel.getSelectedAttributes(); if (selected.length == 0) { return; } if (selected.length == m_Instances.numAttributes()) { // Pop up an error optionpane JOptionPane.showMessageDialog(PreprocessPanel.this, "Can't remove all attributes from data!\n", "Remove Attributes", JOptionPane.ERROR_MESSAGE); m_Log.logMessage("Can't remove all attributes from data!"); m_Log.statusMessage("Problem removing attributes"); return; } r.setAttributeIndicesArray(selected); applyFilter(r); m_RemoveButton.setEnabled(false); } catch (Exception ex) { if (m_Log instanceof TaskLogger) { ((TaskLogger) m_Log).taskFinished(); } // Pop up an error optionpane JOptionPane.showMessageDialog(PreprocessPanel.this, "Problem filtering instances:\n" + ex.getMessage(), "Remove Attributes", JOptionPane.ERROR_MESSAGE); m_Log.logMessage("Problem removing attributes: " + ex.getMessage()); m_Log.statusMessage("Problem removing attributes"); ex.printStackTrace(); } } }); JPanel p1 = new JPanel(); p1.setBorder(BorderFactory.createEmptyBorder(10, 5, 10, 5)); p1.setLayout(new BorderLayout()); p1.add(m_RemoveButton, BorderLayout.CENTER); attStuffHolderPanel.add(p1, BorderLayout.SOUTH); m_AttSummaryPanel.setBorder(BorderFactory .createTitledBorder("Selected attribute")); m_UndoBut.setEnabled(false); m_EditBut.setEnabled(false); m_SaveBut.setEnabled(false); m_ApplyFilterBut.setEnabled(false); m_StopBut.setEnabled(false); // Set up the GUI layout JPanel buttons = new JPanel(); buttons.setBorder(BorderFactory.createEmptyBorder(10, 5, 10, 5)); buttons.setLayout(new GridLayout(1, 6, 5, 5)); buttons.add(m_OpenFileBut); buttons.add(m_OpenURLBut); buttons.add(m_OpenDBBut); buttons.add(m_GenerateBut); buttons.add(m_UndoBut); buttons.add(m_EditBut); buttons.add(m_SaveBut); JPanel attInfo = new JPanel(); attInfo.setLayout(new BorderLayout()); attInfo.add(attStuffHolderPanel, BorderLayout.CENTER); JPanel filter = new JPanel(); filter.setBorder(BorderFactory.createTitledBorder("Filter")); filter.setLayout(new BorderLayout()); filter.add(m_FilterPanel, BorderLayout.CENTER); JPanel ssButs = new JPanel(); ssButs.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); ssButs.setLayout(new GridLayout(1, 2, 2, 0)); ssButs.add(m_ApplyFilterBut); ssButs.add(m_StopBut); filter.add(ssButs, BorderLayout.EAST); JPanel attVis = new JPanel(); attVis.setLayout(new GridLayout(2, 1)); attVis.add(m_AttSummaryPanel); JComboBox colorBox = m_AttVisualizePanel.getColorBox(); colorBox.setToolTipText("The chosen attribute will also be used as the " + "class attribute when a filter is applied."); colorBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent ie) { if (ie.getStateChange() == ItemEvent.SELECTED) { updateCapabilitiesFilter(m_FilterEditor.getCapabilitiesFilter()); } } }); final JButton visAllBut = new JButton("Visualize All"); visAllBut.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { if (m_Instances != null) { try { final weka.gui.beans.AttributeSummarizer as = new weka.gui.beans.AttributeSummarizer(); as.setColoringIndex(m_AttVisualizePanel.getColoringIndex()); as.setInstances(m_Instances); final javax.swing.JFrame jf = Utils.getWekaJFrame("All attributes", PreprocessPanel.this); jf.getContentPane().setLayout(new java.awt.BorderLayout()); jf.getContentPane().add(as, java.awt.BorderLayout.CENTER); jf.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { visAllBut.setEnabled(true); jf.dispose(); } }); jf.pack(); jf.setSize(1000, 600); jf.setLocationRelativeTo(SwingUtilities.getWindowAncestor(PreprocessPanel.this)); jf.setVisible(true); } catch (Exception ex) { ex.printStackTrace(); } } } }); JPanel histoHolder = new JPanel(); histoHolder.setLayout(new BorderLayout()); histoHolder.add(m_AttVisualizePanel, BorderLayout.CENTER); JPanel histoControls = new JPanel(); histoControls.setLayout(new BorderLayout()); histoControls.add(colorBox, BorderLayout.CENTER); histoControls.add(visAllBut, BorderLayout.EAST); histoHolder.add(histoControls, BorderLayout.NORTH); attVis.add(histoHolder); JPanel lhs = new JPanel(); lhs.setLayout(new BorderLayout()); lhs.add(m_InstSummaryPanel, BorderLayout.NORTH); lhs.add(attInfo, BorderLayout.CENTER); JPanel rhs = new JPanel(); rhs.setLayout(new BorderLayout()); rhs.add(attVis, BorderLayout.CENTER); JPanel relation = new JPanel(); relation.setLayout(new GridLayout(1, 2)); relation.add(lhs); relation.add(rhs); JPanel middle = new JPanel(); middle.setLayout(new BorderLayout()); middle.add(filter, BorderLayout.NORTH); middle.add(relation, BorderLayout.CENTER); setLayout(new BorderLayout()); add(buttons, BorderLayout.NORTH); add(middle, BorderLayout.CENTER); } /** * We can accept instances * * @return true */ @Override public boolean acceptsInstances() { return true; } /** * We've been instantiated and now have access to the main application and * PerspectiveManager */ @Override public void instantiationComplete() { // overridden here so that we know if we're operating within // a non-legacy UI, and can thus set up our send data to perspective // menu (if necessary) boolean sendToAll = getMainApplication().getApplicationSettings().getSetting( getPerspectiveID(), PreprocessDefaults.ALWAYS_SEND_INSTANCES_TO_ALL_KEY, PreprocessDefaults.ALWAYS_SEND_INSTANCES_TO_ALL, Environment.getSystemWide()); // install a menu item to allow the user to choose to send to all or // send to a specific perspective final List<Perspective> perspectivesThatAcceptInstances = new ArrayList<Perspective>(); List<Perspective> visiblePerspectives = getMainApplication().getPerspectiveManager().getVisiblePerspectives(); for (Perspective p : visiblePerspectives) { if (p.acceptsInstances() && !p.getPerspectiveID().equals(getPerspectiveID())) { perspectivesThatAcceptInstances.add(p); } } if (perspectivesThatAcceptInstances.size() > 0) { JMenu fileMenu = m_menus.get(0); m_sendToPerspective = new JMenu(); m_sendToPerspective.setText("Send to perspective"); fileMenu.add(m_sendToPerspective); if (!sendToAll) { m_sendToPerspective.setEnabled(false); } JMenuItem sendToAllItem = new JMenuItem("All perspectives"); sendToAllItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { for (Perspective p : perspectivesThatAcceptInstances) { if (getInstances() != null && p.acceptsInstances()) { p.setInstances(getInstances()); getMainApplication().getPerspectiveManager() .setEnablePerspectiveTab(p.getPerspectiveID(), true); } } } }); m_sendToPerspective.add(sendToAllItem); for (final Perspective p : perspectivesThatAcceptInstances) { JMenuItem item = new JMenuItem(p.getPerspectiveTitle()); m_sendToPerspective.add(item); item.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (getInstances() != null) { p.setInstances(getInstances()); getMainApplication().getPerspectiveManager() .setEnablePerspectiveTab(p.getPerspectiveID(), true); getMainApplication().getPerspectiveManager() .setActivePerspective(p.getPerspectiveID()); } } }); } } } /** * Sets the Logger to receive informational messages * * @param newLog the Logger that will now get info messages */ public void setLog(Logger newLog) { m_Log = newLog; } @Override public boolean requiresLog() { return true; } /** * Tells the panel to use a new base set of instances. * * @param inst a set of Instances */ public void setInstances(Instances inst) { m_Instances = inst; try { Runnable r = new Runnable() { public void run() { boolean first = (m_AttPanel.getTableModel() == null); m_InstSummaryPanel.setInstances(m_Instances); m_AttPanel.setInstances(m_Instances); if (first) { TableModel model = m_AttPanel.getTableModel(); model.addTableModelListener(new TableModelListener() { public void tableChanged(TableModelEvent e) { if (m_AttPanel.getSelectedAttributes() != null && m_AttPanel.getSelectedAttributes().length > 0) { m_RemoveButton.setEnabled(true); } else { m_RemoveButton.setEnabled(false); } } }); } // m_RemoveButton.setEnabled(true); m_AttSummaryPanel.setInstances(m_Instances); m_AttVisualizePanel.setInstances(m_Instances); // select the first attribute in the list m_AttPanel.getSelectionModel().setSelectionInterval(0, 0); m_AttSummaryPanel.setAttribute(0); m_AttVisualizePanel.setAttribute(0); m_ApplyFilterBut.setEnabled(true); m_StopBut.setEnabled(false); m_Log.logMessage("Base relation is now " + m_Instances.relationName() + " (" + m_Instances.numInstances() + " instances)"); m_SaveBut.setEnabled(true); m_EditBut.setEnabled(true); m_EditM.setEnabled(true); m_Log.statusMessage("OK"); // Fire a propertychange event m_Support.firePropertyChange("", null, null); boolean sendToAll = getExplorer() != null || getMainApplication().getApplicationSettings().getSetting( getPerspectiveID(), PreprocessDefaults.ALWAYS_SEND_INSTANCES_TO_ALL_KEY, PreprocessDefaults.ALWAYS_SEND_INSTANCES_TO_ALL, Environment.getSystemWide()); if (m_sendToPerspective != null) { m_sendToPerspective.setEnabled(!sendToAll); } if (getMainApplication() != null) { if (sendToAll) { List<Perspective> perspectiveList = getMainApplication().getPerspectiveManager() .getVisiblePerspectives(); for (Perspective p : perspectiveList) { if (p.acceptsInstances() && !p.getPerspectiveID().equals(getPerspectiveID())) { p.setInstances(m_Instances); } } } } // notify GOEs about change if (getExplorer() != null || getMainApplication() != null) { Explorer explorer = getExplorer(); WorkbenchApp app = (WorkbenchApp) getMainApplication(); try { // get rid of old filter settings if (explorer != null) { explorer.notifyCapabilitiesFilterListener(null); } else { app.notifyCapabilitiesFilterListeners(null); // enable all perspectives if (sendToAll) { app.getPerspectiveManager().enableAllPerspectiveTabs(); } } int oldIndex = m_Instances.classIndex(); m_Instances.setClassIndex(m_AttVisualizePanel.getColorBox() .getSelectedIndex() - 1); // send new ones if (ExplorerDefaults.getInitGenericObjectEditorFilter()) { if (explorer != null) { explorer.notifyCapabilitiesFilterListener(Capabilities .forInstances(m_Instances)); } else { if (sendToAll) { app.notifyCapabilitiesFilterListeners(Capabilities .forInstances(m_Instances)); } } } else { if (explorer != null) { explorer.notifyCapabilitiesFilterListener(Capabilities .forInstances(new Instances(m_Instances, 0))); } else { if (sendToAll) { app.notifyCapabilitiesFilterListeners(Capabilities .forInstances(new Instances(m_Instances, 0))); } } } m_Instances.setClassIndex(oldIndex); } catch (Exception e) { e.printStackTrace(); m_Log.logMessage(e.toString()); } } } }; if (SwingUtilities.isEventDispatchThread()) { r.run(); } else { SwingUtilities.invokeAndWait(r); } } catch (Exception ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(this, "Problem setting base instances:\n" + ex, "Instances", JOptionPane.ERROR_MESSAGE); } } /** * Gets the working set of instances. * * @return the working instances */ public Instances getInstances() { return m_Instances; } /** * Adds a PropertyChangeListener who will be notified of value changes. * * @param l a value of type 'PropertyChangeListener' */ @Override public void addPropertyChangeListener(PropertyChangeListener l) { if (m_Support != null && l != null) { m_Support.addPropertyChangeListener(l); } } /** * Removes a PropertyChangeListener. * * @param l a value of type 'PropertyChangeListener' */ @Override public void removePropertyChangeListener(PropertyChangeListener l) { if (m_Support != null && l != null) { m_Support.removePropertyChangeListener(l); } } /** * Passes the dataset through the filter that has been configured for use. * * @param filter the filter to apply */ protected void applyFilter(final Filter filter) { if (m_IOThread == null) { m_IOThread = new Thread() { @Override public void run() { try { if (filter != null) { m_FilterPanel.addToHistory(); if (m_Log instanceof TaskLogger) { ((TaskLogger) m_Log).taskStarted(); } m_Log.statusMessage("Passing dataset through filter " + filter.getClass().getName()); String cmd = filter.getClass().getName(); if (filter instanceof OptionHandler) cmd += " " + Utils.joinOptions(((OptionHandler) filter).getOptions()); m_Log.logMessage("Command: " + cmd); int classIndex = m_AttVisualizePanel.getColoringIndex(); if ((classIndex < 0) && (filter instanceof SupervisedFilter)) { throw new IllegalArgumentException("Class (colour) needs to " + "be set for supervised " + "filter."); } Instances copy = new Instances(m_Instances); copy.setClassIndex(classIndex); m_StopBut.setEnabled(true); Filter filterCopy = Filter.makeCopy(filter); filterCopy.setInputFormat(copy); Instances newInstances = Filter.useFilter(copy, filterCopy); m_StopBut.setEnabled(false); if (newInstances == null || newInstances.numAttributes() < 1) { throw new Exception("Dataset is empty."); } m_Log.statusMessage("Saving undo information"); addUndoPoint(); m_AttVisualizePanel.setColoringIndex(copy.classIndex()); // if class was not set before, reset it again after use of filter if (m_Instances.classIndex() < 0) newInstances.setClassIndex(-1); m_Instances = newInstances; setInstances(m_Instances); if (m_Log instanceof TaskLogger) { ((TaskLogger) m_Log).taskFinished(); } } } catch (Exception ex) { if (m_Log instanceof TaskLogger) { ((TaskLogger) m_Log).taskFinished(); } // Pop up an error optionpane JOptionPane.showMessageDialog(PreprocessPanel.this, "Problem filtering instances:\n" + ex.getMessage(), "Apply Filter", JOptionPane.ERROR_MESSAGE); m_Log.logMessage("Problem filtering instances: " + ex.getMessage()); m_Log.statusMessage("Problem filtering instances"); ex.printStackTrace(); } m_IOThread = null; } }; m_IOThread.setPriority(Thread.MIN_PRIORITY); // UI has most priority m_IOThread.start(); } else { JOptionPane.showMessageDialog(this, "Can't apply filter at this time,\n" + "currently busy with other IO", "Apply Filter", JOptionPane.WARNING_MESSAGE); } } /** * Queries the user for a file to save instances as, then saves the instances * in a background process. This is done in the IO thread, and an error * message is popped up if the IO thread is busy. */ public void saveWorkingInstancesToFileQ() { if (m_IOThread == null) { m_FileChooser.setCapabilitiesFilter(m_FilterEditor .getCapabilitiesFilter()); m_FileChooser.setAcceptAllFileFilterUsed(false); int returnVal = m_FileChooser.showSaveDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { Instances inst = new Instances(m_Instances); inst.setClassIndex(m_AttVisualizePanel.getColoringIndex()); saveInstancesToFile(m_FileChooser.getSaver(), inst); } FileFilter temp = m_FileChooser.getFileFilter(); m_FileChooser.setAcceptAllFileFilterUsed(true); m_FileChooser.setFileFilter(temp); } else { JOptionPane.showMessageDialog(this, "Can't save at this time,\n" + "currently busy with other IO", "Save Instances", JOptionPane.WARNING_MESSAGE); } } /** * saves the data with the specified saver * * @param saver the saver to use for storing the data * @param inst the data to save */ public void saveInstancesToFile(final AbstractFileSaver saver, final Instances inst) { if (m_IOThread == null) { m_IOThread = new Thread() { @Override public void run() { try { m_Log.statusMessage("Saving to file..."); saver.setInstances(inst); saver.writeBatch(); m_Log.statusMessage("OK"); } catch (Exception ex) { ex.printStackTrace(); m_Log.logMessage(ex.getMessage()); } m_IOThread = null; } }; m_IOThread.setPriority(Thread.MIN_PRIORITY); // UI has most priority m_IOThread.start(); } else { JOptionPane.showMessageDialog(this, "Can't save at this time,\n" + "currently busy with other IO", "Saving instances", JOptionPane.WARNING_MESSAGE); } } /** * Queries the user for a file to load instances from, then loads the * instances in a background process. This is done in the IO thread, and an * error message is popped up if the IO thread is busy. */ public void setInstancesFromFileQ() { if (m_IOThread == null) { int returnVal = m_FileChooser.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { try { addUndoPoint(); } catch (Exception ignored) { // ignored } if (m_FileChooser.getLoader() == null) { JOptionPane.showMessageDialog(this, "Cannot determine file loader automatically, please choose one.", "Load Instances", JOptionPane.ERROR_MESSAGE); converterQuery(m_FileChooser.getSelectedFile()); } else { setInstancesFromFile(m_FileChooser.getLoader()); } } } else { JOptionPane.showMessageDialog(this, "Can't load at this time,\n" + "currently busy with other IO", "Load Instances", JOptionPane.WARNING_MESSAGE); } } /** * Loads (non-sparse) instances from an SQL query the user provided with the * SqlViewerDialog, then loads the instances in a background process. This is * done in the IO thread, and an error message is popped up if the IO thread * is busy. * * @param url the database URL * @param user the user to connect as * @param pw the password of the user * @param query the query for retrieving instances from */ public void setInstancesFromDBQ(String url, String user, String pw, String query) { setInstancesFromDBQ(url, user, pw, query, false); } /** * Loads instances from an SQL query the user provided with the * SqlViewerDialog, then loads the instances in a background process. This is * done in the IO thread, and an error message is popped up if the IO thread * is busy. * * @param url the database URL * @param user the user to connect as * @param pw the password of the user * @param query the query for retrieving instances from * @param sparse whether to create sparse or non-sparse instances */ public void setInstancesFromDBQ(String url, String user, String pw, String query, boolean sparse) { if (m_IOThread == null) { try { InstanceQuery InstQ = new InstanceQuery(); InstQ.setDatabaseURL(url); InstQ.setUsername(user); InstQ.setPassword(pw); InstQ.setQuery(query); InstQ.setSparseData(sparse); // we have to disconnect, otherwise we can't change the DB! if (InstQ.isConnected()) InstQ.disconnectFromDatabase(); InstQ.connectToDatabase(); try { addUndoPoint(); } catch (Exception ignored) { } setInstancesFromDB(InstQ); } catch (Exception ex) { JOptionPane.showMessageDialog(this, "Problem connecting to database:\n" + ex.getMessage(), "Load Instances", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(this, "Can't load at this time,\n" + "currently busy with other IO", "Load Instances", JOptionPane.WARNING_MESSAGE); } } /** * Queries the user for a URL to load instances from, then loads the instances * in a background process. This is done in the IO thread, and an error * message is popped up if the IO thread is busy. */ public void setInstancesFromURLQ() { if (m_IOThread == null) { try { String urlName = (String) JOptionPane.showInputDialog(this, "Enter the source URL", "Load Instances", JOptionPane.QUESTION_MESSAGE, null, null, m_LastURL); if (urlName != null) { m_LastURL = urlName; URL url = new URL(urlName); try { addUndoPoint(); } catch (Exception ignored) { } setInstancesFromURL(url); } } catch (Exception ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(this, "Problem with URL:\n" + ex.getMessage(), "Load Instances", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(this, "Can't load at this time,\n" + "currently busy with other IO", "Load Instances", JOptionPane.WARNING_MESSAGE); } } /** * sets Instances generated via DataGenerators (pops up a Dialog) */ public void generateInstances() { if (m_IOThread == null) { m_IOThread = new Thread() { @Override public void run() { try { // create dialog final DataGeneratorPanel generatorPanel = new DataGeneratorPanel(); final JDialog dialog = new JDialog(); final JButton generateButton = new JButton("Generate"); final JCheckBox showOutputCheckBox = new JCheckBox("Show generated data as text, incl. comments"); showOutputCheckBox.setMnemonic('S'); generatorPanel.setLog(m_Log); generatorPanel.setGenerator(m_DataGenerator); generatorPanel.setPreferredSize(new Dimension(300, (int) generatorPanel.getPreferredSize().getHeight())); generateButton.setMnemonic('G'); generateButton .setToolTipText("Generates the dataset according the settings."); generateButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { boolean showOutput = showOutputCheckBox.isSelected(); // generate generatorPanel.execute(showOutput); boolean generated = (generatorPanel.getInstances() != null); if (generated) setInstances(generatorPanel.getInstances()); // close dialog dialog.dispose(); // get last generator m_DataGenerator = generatorPanel.getGenerator(); // display output? if ((generated) && (showOutput)) showGeneratedInstances(generatorPanel.getOutput()); } }); dialog.setTitle("DataGenerator"); dialog.getContentPane().add(generatorPanel, BorderLayout.CENTER); dialog.getContentPane().add(generateButton, BorderLayout.EAST); dialog.getContentPane().add(showOutputCheckBox, BorderLayout.SOUTH); dialog.pack(); dialog.setSize(1000,130); dialog.setIconImage(((Frame) SwingUtilities.getWindowAncestor(PreprocessPanel.this)).getIconImage()); dialog.setLocationRelativeTo(SwingUtilities.getWindowAncestor(PreprocessPanel.this)); // display dialog dialog.setVisible(true); } catch (Exception ex) { ex.printStackTrace(); m_Log.logMessage(ex.getMessage()); } m_IOThread = null; } }; m_IOThread.setPriority(Thread.MIN_PRIORITY); // UI has most priority m_IOThread.start(); } else { JOptionPane.showMessageDialog(this, "Can't generate data at this time,\n" + "currently busy with other IO", "Generate Data", JOptionPane.WARNING_MESSAGE); } } /** * displays a dialog with the generated instances from the DataGenerator * * @param data the data to display */ protected void showGeneratedInstances(String data) { final JDialog dialog = new JDialog(SwingUtilities.getWindowAncestor(PreprocessPanel.this)); final JButton saveButton = new JButton("Save"); final JButton closeButton = new JButton("Close"); final JTextArea textData = new JTextArea(data); final JPanel panel = new JPanel(); panel.setLayout(new FlowLayout(FlowLayout.RIGHT)); textData.setEditable(false); textData.setFont(new Font("Monospaced", Font.PLAIN, textData.getFont() .getSize())); saveButton.setMnemonic('S'); saveButton.setToolTipText("Saves the output to a file"); saveButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { JFileChooser filechooser = new JFileChooser(); int result = filechooser.showSaveDialog(dialog); if (result == JFileChooser.APPROVE_OPTION) { try { BufferedWriter writer = new BufferedWriter(new FileWriter(filechooser.getSelectedFile())); writer.write(textData.getText()); writer.flush(); writer.close(); JOptionPane.showMessageDialog( dialog, "Output successfully saved to file '" + filechooser.getSelectedFile() + "'!", "Information", JOptionPane.INFORMATION_MESSAGE); } catch (Exception e) { e.printStackTrace(); } dialog.dispose(); } } }); closeButton.setMnemonic('C'); closeButton.setToolTipText("Closes the dialog"); closeButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { dialog.dispose(); } }); panel.add(saveButton); panel.add(closeButton); dialog.setTitle("Generated Instances (incl. comments)"); dialog.getContentPane().add(new JScrollPane(textData), BorderLayout.CENTER); dialog.getContentPane().add(panel, BorderLayout.SOUTH); dialog.pack(); // make sure, it's not bigger than 80% of the screen Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); int width = dialog.getWidth() > screen.getWidth() * 0.8 ? (int) (screen.getWidth() * 0.8) : dialog.getWidth(); int height = dialog.getHeight() > screen.getHeight() * 0.8 ? (int) (screen.getHeight() * 0.8) : dialog.getHeight(); dialog.setSize(width, height); dialog.pack(); dialog.setLocationRelativeTo(SwingUtilities.getWindowAncestor(PreprocessPanel.this)); // display dialog dialog.setVisible(true); } /** * Pops up generic object editor with list of conversion filters * * @param f the File */ private void converterQuery(final File f) { final GenericObjectEditor convEd = new GenericObjectEditor(true); try { convEd.setClassType(weka.core.converters.Loader.class); convEd.setValue(new weka.core.converters.CSVLoader()); ((GenericObjectEditor.GOEPanel) convEd.getCustomEditor()) .addOkListener(new ActionListener() { public void actionPerformed(ActionEvent e) { tryConverter((Loader) convEd.getValue(), f); } }); } catch (Exception ex) { } PropertyDialog pd; if (PropertyDialog.getParentDialog(this) != null) pd = new PropertyDialog(PropertyDialog.getParentDialog(this), convEd, -1, -1); else pd = new PropertyDialog(PropertyDialog.getParentFrame(this), convEd, -1, -1); pd.setVisible(true); } /** * Applies the selected converter * * @param cnv the converter to apply to the input file * @param f the input file */ private void tryConverter(final Loader cnv, final File f) { if (m_IOThread == null) { m_IOThread = new Thread() { @Override public void run() { try { cnv.setSource(f); Instances inst = cnv.getDataSet(); setInstances(inst); } catch (Exception ex) { m_Log.statusMessage(cnv.getClass().getName() + " failed to load " + f.getName()); JOptionPane.showMessageDialog(PreprocessPanel.this, cnv.getClass() .getName() + " failed to load '" + f.getName() + "'.\n" + "Reason:\n" + ex.getMessage(), "Convert File", JOptionPane.ERROR_MESSAGE); m_IOThread = null; converterQuery(f); } m_IOThread = null; } }; m_IOThread.setPriority(Thread.MIN_PRIORITY); // UI has most priority m_IOThread.start(); } } /** * Loads results from a set of instances retrieved with the supplied loader. * This is started in the IO thread, and a dialog is popped up if there's a * problem. * * @param loader the loader to use */ public void setInstancesFromFile(final AbstractFileLoader loader) { if (m_IOThread == null) { m_IOThread = new Thread() { @Override public void run() { try { m_Log.statusMessage("Reading from file..."); Instances inst = loader.getDataSet(); setInstances(inst); } catch (Exception ex) { m_Log.statusMessage("File '" + loader.retrieveFile() + "' not recognised as an '" + loader.getFileDescription() + "' file."); m_IOThread = null; if (JOptionPane.showOptionDialog( PreprocessPanel.this, "File '" + loader.retrieveFile() + "' not recognised as an '" + loader.getFileDescription() + "' file.\n" + "Reason:\n" + ex.getMessage(), "Load Instances", 0, JOptionPane.ERROR_MESSAGE, null, new String[] { "OK", "Use Converter" }, null) == 1) { converterQuery(loader.retrieveFile()); } } m_IOThread = null; } }; m_IOThread.setPriority(Thread.MIN_PRIORITY); // UI has most priority m_IOThread.start(); } else { JOptionPane.showMessageDialog(this, "Can't load at this time,\n" + "currently busy with other IO", "Load Instances", JOptionPane.WARNING_MESSAGE); } } /** * Loads instances from a database * * @param iq the InstanceQuery object to load from (this is assumed to have * been already connected to a valid database). */ public void setInstancesFromDB(final InstanceQuery iq) { if (m_IOThread == null) { m_IOThread = new Thread() { @Override public void run() { try { m_Log.statusMessage("Reading from database..."); final Instances i = iq.retrieveInstances(); SwingUtilities.invokeAndWait(new Runnable() { public void run() { setInstances(new Instances(i)); } }); iq.disconnectFromDatabase(); } catch (Exception ex) { m_Log.statusMessage("Problem executing DB query " + m_SQLQ); JOptionPane.showMessageDialog(PreprocessPanel.this, "Couldn't read from database:\n" + ex.getMessage(), "Load Instances", JOptionPane.ERROR_MESSAGE); } m_IOThread = null; } }; m_IOThread.setPriority(Thread.MIN_PRIORITY); // UI has most priority m_IOThread.start(); } else { JOptionPane.showMessageDialog(this, "Can't load at this time,\n" + "currently busy with other IO", "Load Instances", JOptionPane.WARNING_MESSAGE); } } /** * Loads instances from a URL. * * @param u the URL to load from. */ public void setInstancesFromURL(final URL u) { if (m_IOThread == null) { m_IOThread = new Thread() { @Override public void run() { try { m_Log.statusMessage("Reading from URL..."); AbstractFileLoader loader = ConverterUtils.getURLLoaderForFile(u.toString()); if (loader == null) throw new Exception( "No suitable URLSourcedLoader found for URL!\n" + u); ((URLSourcedLoader) loader).setURL(u.toString()); setInstances(loader.getDataSet()); } catch (Exception ex) { ex.printStackTrace(); m_Log.statusMessage("Problem reading " + u); JOptionPane.showMessageDialog(PreprocessPanel.this, "Couldn't read from URL:\n" + u + "\n" + ex.getMessage(), "Load Instances", JOptionPane.ERROR_MESSAGE); } m_IOThread = null; } }; m_IOThread.setPriority(Thread.MIN_PRIORITY); // UI has most priority m_IOThread.start(); } else { JOptionPane.showMessageDialog(this, "Can't load at this time,\n" + "currently busy with other IO", "Load Instances", JOptionPane.WARNING_MESSAGE); } } /** * Backs up the current state of the dataset, so the changes can be undone. * * @throws Exception if an error occurs */ public void addUndoPoint() throws Exception { if (!ExplorerDefaults.get("enableUndo", "true").equalsIgnoreCase("true")) { return; } if (getMainApplication() != null) { boolean undoEnabled = getMainApplication().getApplicationSettings().getSetting( getPerspectiveID(), PreprocessDefaults.ENABLE_UNDO_KEY, PreprocessDefaults.ENABLE_UNDO, Environment.getSystemWide()); if (!undoEnabled) { return; } } if (m_Instances != null) { // create temporary file File tempFile = File.createTempFile("weka", SerializedInstancesLoader.FILE_EXTENSION); tempFile.deleteOnExit(); boolean nonDefaultTmpDir = false; String dir = ""; if (getMainApplication() != null) { dir = getMainApplication() .getApplicationSettings() .getSetting(getPerspectiveID(), PreprocessDefaults.UNDO_DIR_KEY, PreprocessDefaults.UNDO_DIR).toString(); if (Environment.getSystemWide().containsEnvVariables(dir)) { dir = Environment.getSystemWide().substitute(dir); } if (!dir.equals(PreprocessDefaults.UNDO_DIR)) { nonDefaultTmpDir = true; } } else if (!ExplorerDefaults.get("undoDirectory", "%t").equalsIgnoreCase( "%t")) { nonDefaultTmpDir = true; dir = ExplorerDefaults.get("undoDirectory", "%t"); } if (nonDefaultTmpDir) { File undoDir = new File(dir); if (undoDir.exists()) { String fileName = tempFile.getName(); File newFile = new File(dir + File.separator + fileName); if (undoDir.canWrite()) { newFile.deleteOnExit(); tempFile = newFile; } else { System.err .println("Explorer: it doesn't look like we have permission" + " to write to the user-specified undo directory " + "'" + dir + "'"); } } else { System.err.println("Explorer: user-specified undo directory '" + dir + "' does not exist!"); } } ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream( tempFile))); oos.writeObject(m_Instances); oos.flush(); oos.close(); // update undo file list if (m_tempUndoFiles[m_tempUndoIndex] != null) { // remove undo points that are too old m_tempUndoFiles[m_tempUndoIndex].delete(); } m_tempUndoFiles[m_tempUndoIndex] = tempFile; if (++m_tempUndoIndex >= m_tempUndoFiles.length) { // wrap pointer around m_tempUndoIndex = 0; } m_UndoBut.setEnabled(true); } } /** * Reverts to the last backed up version of the dataset. */ public void undo() { if (--m_tempUndoIndex < 0) { // wrap pointer around m_tempUndoIndex = m_tempUndoFiles.length - 1; } if (m_tempUndoFiles[m_tempUndoIndex] != null) { // load instances from the temporary file AbstractFileLoader loader = ConverterUtils.getLoaderForFile(m_tempUndoFiles[m_tempUndoIndex]); try { loader.setFile(m_tempUndoFiles[m_tempUndoIndex]); setInstancesFromFile(loader); } catch (Exception e) { e.printStackTrace(); m_Log.logMessage(e.toString()); JOptionPane.showMessageDialog(PreprocessPanel.this, "Cannot perform undo operation!\n" + e.toString(), "Undo", JOptionPane.ERROR_MESSAGE); } // update undo file list m_tempUndoFiles[m_tempUndoIndex] = null; } // update undo button int temp = m_tempUndoIndex - 1; if (temp < 0) { temp = m_tempUndoFiles.length - 1; } m_UndoBut.setEnabled(m_tempUndoFiles[temp] != null); } /** * edits the current instances object in the viewer */ public void edit() { ViewerDialog dialog; int result; Instances copy; Instances newInstances; final int classIndex = m_AttVisualizePanel.getColoringIndex(); copy = new Instances(m_Instances); copy.setClassIndex(classIndex); dialog = new ViewerDialog(null); dialog.pack(); dialog.setSize(1000, 600); dialog.setIconImage(((Frame) SwingUtilities.getWindowAncestor(PreprocessPanel.this)).getIconImage()); dialog.setLocationRelativeTo(SwingUtilities.getWindowAncestor(PreprocessPanel.this)); result = dialog.showDialog(copy); if (result == ViewerDialog.APPROVE_OPTION) { try { addUndoPoint(); } catch (Exception e) { e.printStackTrace(); } // if class was not set before, reset it again after use of filter newInstances = dialog.getInstances(); if (m_Instances.classIndex() < 0) newInstances.setClassIndex(-1); setInstances(newInstances); } } /** * Sets the Explorer to use as parent frame (used for sending notifications * about changes in the data) * * @param parent the parent frame */ public void setExplorer(Explorer parent) { m_Explorer = parent; } /** * returns the parent Explorer frame * * @return the parent */ public Explorer getExplorer() { return m_Explorer; } /** * updates the capabilities filter of the GOE * * @param filter the new filter to use */ protected void updateCapabilitiesFilter(Capabilities filter) { Instances tempInst; Capabilities filterClass; if (filter == null) { m_FilterEditor.setCapabilitiesFilter(new Capabilities(null)); return; } if (!ExplorerDefaults.getInitGenericObjectEditorFilter()) tempInst = new Instances(m_Instances, 0); else tempInst = new Instances(m_Instances); tempInst .setClassIndex(m_AttVisualizePanel.getColorBox().getSelectedIndex() - 1); try { filterClass = Capabilities.forInstances(tempInst); } catch (Exception e) { filterClass = new Capabilities(null); } // set new filter m_FilterEditor.setCapabilitiesFilter(filterClass); // check capabilities m_ApplyFilterBut.setEnabled(true); Capabilities currentCapabilitiesFilter = m_FilterEditor.getCapabilitiesFilter(); Filter currentFilter = (Filter) m_FilterEditor.getValue(); Capabilities currentFilterCapabilities = null; if (currentFilter != null && currentCapabilitiesFilter != null && (currentFilter instanceof CapabilitiesHandler)) { currentFilterCapabilities = ((CapabilitiesHandler) currentFilter).getCapabilities(); if (!currentFilterCapabilities.supportsMaybe(currentCapabilitiesFilter) && !currentFilterCapabilities.supports(currentCapabilitiesFilter)) { try { currentFilter.setInputFormat(getInstances()); } catch (Exception ex) { m_ApplyFilterBut.setEnabled(false); } } } } /** * method gets called in case of a change event * * @param e the associated change event */ public void capabilitiesFilterChanged(CapabilitiesFilterChangeEvent e) { if (e.getFilter() == null) updateCapabilitiesFilter(null); else updateCapabilitiesFilter((Capabilities) e.getFilter().clone()); } /** * Returns the title for the tab in the Explorer * * @return the title of this tab */ public String getTabTitle() { return "Preprocess"; } /** * Returns the tooltip for the tab in the Explorer * * @return the tooltip of this tab */ public String getTabTitleToolTip() { return "Open/Edit/Save instances"; } @Override public Defaults getDefaultSettings() { return new PreprocessDefaults(); } @Override public void setActive(boolean active) { super.setActive(active); if (m_isActive) { updateSettings(); } } @Override public void settingsChanged() { updateSettings(); } protected void updateSettings() { File initialDir = getMainApplication().getApplicationSettings().getSetting( getPerspectiveID(), PreprocessDefaults.INITIAL_DIR_KEY, PreprocessDefaults.INITIAL_DIR, Environment.getSystemWide()); if (Environment.getSystemWide().containsEnvVariables(initialDir.toString())) { String initDir = initialDir.toString(); try { initDir = Environment.getSystemWide().substitute(initDir); initialDir = new File(initDir); } catch (Exception ex) { } } m_FileChooser.setCurrentDirectory(initialDir); if (!m_initialSettingsSet) { // only want to set the preferred starting filter once! Filter toUse = getMainApplication().getApplicationSettings().getSetting( getPerspectiveID(), PreprocessDefaults.FILTER_KEY, PreprocessDefaults.FILTER, Environment.getSystemWide()); m_FilterEditor.setValue(toUse); m_UndoBut.setEnabled(false); m_initialSettingsSet = true; } /* * m_UndoBut.setEnabled(getMainApplication().getApplicationSettings() * .getSetting(PreprocessDefaults.ID, PreprocessDefaults.ENABLE_UNDO_KEY, * PreprocessDefaults.ENABLE_UNDO, Environment.getSystemWide())); */ boolean sendToAll = getMainApplication().getApplicationSettings().getSetting( getPerspectiveID(), PreprocessDefaults.ALWAYS_SEND_INSTANCES_TO_ALL_KEY, PreprocessDefaults.ALWAYS_SEND_INSTANCES_TO_ALL, Environment.getSystemWide()); if (sendToAll && getInstances() != null) { // check to see if any perspectives that might now be visible need // instances to be set (assume that if they are not okToBeActive() then // they need the current set of instances List<Perspective> visiblePerspectives = getMainApplication().getPerspectiveManager().getVisiblePerspectives(); for (Perspective p : visiblePerspectives) { if (!p.okToBeActive() && p.acceptsInstances()) { p.setInstances(getInstances()); } if (p.okToBeActive()) { getMainApplication().getPerspectiveManager().setEnablePerspectiveTab( p.getPerspectiveID(), true); } } } if (m_sendToPerspective != null) { m_sendToPerspective.setEnabled(!sendToAll && getInstances() != null); } } @Override public List<JMenu> getMenus() { return m_menus; } public static class PreprocessDefaults extends Defaults { public static final String ID = "weka.gui.explorer.preprocesspanel"; public static final Settings.SettingKey INITIAL_DIR_KEY = new Settings.SettingKey(ID + ".initialDir", "Initial directory for opening datasets", ""); public static final File INITIAL_DIR = new File("${user.dir}"); public static final Settings.SettingKey UNDO_DIR_KEY = new Settings.SettingKey(ID + ".undoDir", "Directory for storing undo files", ""); public static final File UNDO_DIR = new File("${java.io.tmpdir}"); public static final Settings.SettingKey FILTER_KEY = new Settings.SettingKey(ID + ".initialFilter", "Initial filter", ""); public static final Filter FILTER = new AllFilter(); public static final Settings.SettingKey ENABLE_UNDO_KEY = new Settings.SettingKey(ID + ".enableUndo", "Enable undo", ""); public static final Boolean ENABLE_UNDO = true; public static final Settings.SettingKey ALWAYS_SEND_INSTANCES_TO_ALL_KEY = new Settings.SettingKey(ID + ".alwaysSendInstancesToAllPerspectives", "Always send instances to all perspectives", ""); public static boolean ALWAYS_SEND_INSTANCES_TO_ALL = true; public PreprocessDefaults() { super(ID); INITIAL_DIR_KEY.setMetadataElement("java.io.File.fileSelectionMode", "" + JFileChooser.DIRECTORIES_ONLY); INITIAL_DIR_KEY.setMetadataElement("java.io.File.dialogType", "" + JFileChooser.OPEN_DIALOG); UNDO_DIR_KEY.setMetadataElement("java.io.File.fileSelectionMode", "" + JFileChooser.DIRECTORIES_ONLY); UNDO_DIR_KEY.setMetadataElement("java.io.File.dialogType", "" + JFileChooser.DIRECTORIES_ONLY); m_defaults.put(INITIAL_DIR_KEY, INITIAL_DIR); m_defaults.put(UNDO_DIR_KEY, UNDO_DIR); m_defaults.put(FILTER_KEY, FILTER); m_defaults.put(ENABLE_UNDO_KEY, ENABLE_UNDO); m_defaults.put(ALWAYS_SEND_INSTANCES_TO_ALL_KEY, ALWAYS_SEND_INSTANCES_TO_ALL); } } /** * Tests out the instance-preprocessing panel from the command line. * * @param args ignored */ public static void main(String[] args) { try { final JFrame jf = new JFrame("Weka Explorer: Preprocess"); jf.getContentPane().setLayout(new BorderLayout()); final PreprocessPanel sp = new PreprocessPanel(); jf.getContentPane().add(sp, BorderLayout.CENTER); weka.gui.LogPanel lp = new weka.gui.LogPanel(); sp.setLog(lp); jf.getContentPane().add(lp, BorderLayout.SOUTH); jf.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { jf.dispose(); System.exit(0); } }); jf.pack(); jf.setSize(800, 600); jf.setVisible(true); } catch (Exception ex) { ex.printStackTrace(); System.err.println(ex.getMessage()); } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/explorer/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) 2007-2012 University of Waikato, Hamilton, New Zealand */ package weka.gui.explorer; import weka.core.Defaults; import weka.core.Instances; import weka.core.Settings; import weka.gui.AbstractPerspective; import weka.gui.PerspectiveInfo; import weka.gui.explorer.Explorer.ExplorerPanel; import weka.gui.visualize.MatrixPanel; import weka.gui.visualize.VisualizeUtils; import java.awt.BorderLayout; /** * A slightly extended MatrixPanel for better support in the Explorer. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ * @see MatrixPanel */ @PerspectiveInfo(ID = "weka.gui.workbench.visualizepanel", title = "Visualize", toolTipText = "Explore the data", iconPath = "weka/gui/weka_icon_new_small.png") public class VisualizePanel extends AbstractPerspective implements ExplorerPanel { /** for serialization */ private static final long serialVersionUID = 6084015036853918846L; /** the parent frame */ protected Explorer m_Explorer = null; protected MatrixPanel m_matrixPanel = new MatrixPanel(); /** True if a set of instances has been set on the panel */ protected boolean m_hasInstancesSet; public VisualizePanel() { setLayout(new BorderLayout()); add(m_matrixPanel, BorderLayout.CENTER); } @Override public void setInstances(Instances instances) { m_matrixPanel.setInstances(instances); m_hasInstancesSet = true; } /** * Sets the Explorer to use as parent frame (used for sending notifications * about changes in the data) * * @param parent the parent frame */ @Override public void setExplorer(Explorer parent) { m_Explorer = parent; } /** * returns the parent Explorer frame * * @return the parent */ @Override public Explorer getExplorer() { return m_Explorer; } /** * Returns the title for the tab in the Explorer * * @return the title of this tab */ @Override public String getTabTitle() { return "Visualize"; } /** * Returns the tooltip for the tab in the Explorer * * @return the tooltip of this tab */ @Override public String getTabTitleToolTip() { return "Explore the data"; } /** * This perspective processes instances * * @return true, as this perspective accepts instances */ @Override public boolean acceptsInstances() { return true; } /** * Default settings for the scatter plot * * @return default settings */ @Override public Defaults getDefaultSettings() { Defaults d = new ScatterDefaults(); d.add(new VisualizeUtils.VisualizeDefaults()); return d; } @Override public boolean okToBeActive() { return m_hasInstancesSet; } /** * Make sure current settings are applied when this panel becomes active * * @param active true if this panel is the visible (active) one */ @Override public void setActive(boolean active) { super.setActive(active); if (m_isActive) { settingsChanged(); } } @Override public void settingsChanged() { if (getMainApplication() != null) { m_matrixPanel.applySettings(m_mainApplication.getApplicationSettings(), ScatterDefaults.ID); if (m_isActive) { m_matrixPanel.updatePanel(); } } } /** * Default settings specific to the {@code MatrixPanel} that provides the * scatter plot matrix */ public static class ScatterDefaults extends Defaults { public static final String ID = "weka.gui.workbench.visualizepanel"; public static final Settings.SettingKey POINT_SIZE_KEY = new Settings.SettingKey(ID + ".pointSize", "Point size for scatter plots", ""); public static final int POINT_SIZE = 1; public static final Settings.SettingKey PLOT_SIZE_KEY = new Settings.SettingKey(ID + ".plotSize", "Size (in pixels) of the cells in the matrix", ""); public static final int PLOT_SIZE = 100; public static final long serialVersionUID = -6890761195767034507L; public ScatterDefaults() { super(ID); m_defaults.put(POINT_SIZE_KEY, POINT_SIZE); m_defaults.put(PLOT_SIZE_KEY, PLOT_SIZE); } } /** * Tests out the visualize panel from the command line. * * @param args may optionally contain the name of a dataset to load. */ public static void main(String[] args) { try { final javax.swing.JFrame jf = new javax.swing.JFrame("Weka Explorer: Visualize"); jf.getContentPane().setLayout(new BorderLayout()); final VisualizePanel sp = new VisualizePanel(); jf.getContentPane().add(sp, BorderLayout.CENTER); jf.addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent e) { jf.dispose(); System.exit(0); } }); jf.pack(); jf.setSize(800, 600); jf.setVisible(true); if (args.length == 1) { System.err.println("Loading instances from " + args[0]); java.io.Reader r = new java.io.BufferedReader(new java.io.FileReader(args[0])); Instances i = new Instances(r); sp.setInstances(i); } } catch (Exception ex) { ex.printStackTrace(); System.err.println(ex.getMessage()); } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/filters/AddUserFieldsCustomizer.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * AddUserFieldsCustomizer.java * Copyright (C) 2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.filters; import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.List; import javax.swing.BorderFactory; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import weka.core.Environment; import weka.core.EnvironmentHandler; import weka.filters.unsupervised.attribute.AddUserFields; import weka.gui.JListHelper; import weka.gui.beans.EnvironmentField; import weka.gui.beans.GOECustomizer; /** * Customizer for the AddUserFields filter. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision$ */ public class AddUserFieldsCustomizer extends JPanel implements EnvironmentHandler, GOECustomizer { /** For serialization */ private static final long serialVersionUID = -3823417827142174931L; protected ModifyListener m_modifyL = null; protected Environment m_env = Environment.getSystemWide(); /** THe filter being customized */ protected AddUserFields m_filter = null; protected EnvironmentField m_nameField; protected JComboBox m_typeField; protected EnvironmentField m_dateFormatField; protected EnvironmentField m_valueField; protected JList m_list = new JList(); protected DefaultListModel m_listModel; protected JButton m_newBut = new JButton("New"); protected JButton m_deleteBut = new JButton("Delete"); protected JButton m_upBut = new JButton("Move up"); protected JButton m_downBut = new JButton("Move down"); protected boolean m_dontShowButs = false; /** * Constructor */ public AddUserFieldsCustomizer() { setLayout(new BorderLayout()); } private void setup() { JPanel fieldHolder = new JPanel(); JPanel namePanel = new JPanel(); namePanel.setLayout(new BorderLayout()); namePanel.setBorder(BorderFactory.createTitledBorder("Attribute name")); m_nameField = new EnvironmentField(m_env); namePanel.add(m_nameField, BorderLayout.CENTER); namePanel.setToolTipText("Name of the new attribute"); JPanel typePanel = new JPanel(); typePanel.setLayout(new BorderLayout()); typePanel.setBorder(BorderFactory.createTitledBorder("Attribute type")); m_typeField = new JComboBox(); m_typeField.addItem("numeric"); m_typeField.addItem("nominal"); m_typeField.addItem("string"); m_typeField.addItem("date"); typePanel.add(m_typeField, BorderLayout.CENTER); m_typeField.setToolTipText("Attribute type"); typePanel.setToolTipText("Attribute type"); JPanel formatPanel = new JPanel(); formatPanel.setLayout(new BorderLayout()); formatPanel.setBorder(BorderFactory.createTitledBorder("Date format")); m_dateFormatField = new EnvironmentField(m_env); formatPanel.add(m_dateFormatField, BorderLayout.CENTER); formatPanel.setToolTipText("Date format (date attributes only)"); JPanel valuePanel = new JPanel(); valuePanel.setLayout(new BorderLayout()); valuePanel.setBorder(BorderFactory.createTitledBorder("Attribute value")); m_valueField = new EnvironmentField(m_env); valuePanel.add(m_valueField, BorderLayout.CENTER); valuePanel .setToolTipText("<html>Constant value (number, string or date)<br>" + "for field. Special value \"now\" can be<br>" + "used for date attributes for the current<br>" + "time stamp</html>"); fieldHolder.add(namePanel); fieldHolder.add(typePanel); fieldHolder.add(formatPanel); fieldHolder.add(valuePanel); add(fieldHolder, BorderLayout.NORTH); m_list.setVisibleRowCount(5); m_deleteBut.setEnabled(false); JPanel listPanel = new JPanel(); listPanel.setLayout(new BorderLayout()); JPanel butHolder = new JPanel(); butHolder.setLayout(new GridLayout(1, 0)); butHolder.add(m_newBut); butHolder.add(m_deleteBut); butHolder.add(m_upBut); butHolder.add(m_downBut); m_upBut.setEnabled(false); m_downBut.setEnabled(false); listPanel.add(butHolder, BorderLayout.NORTH); JScrollPane js = new JScrollPane(m_list); js.setBorder(BorderFactory .createTitledBorder("Attributes to add")); listPanel.add(js, BorderLayout.CENTER); add(listPanel, BorderLayout.CENTER); m_list.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { if (!m_deleteBut.isEnabled()) { m_deleteBut.setEnabled(true); } Object entry = m_list.getSelectedValue(); if (entry != null) { AddUserFields.AttributeSpec m = (AddUserFields.AttributeSpec) entry; m_nameField.setText(m.getName()); m_valueField.setText(m.getValue()); String type = m.getType(); String format = ""; if (type.startsWith("date") && type.indexOf(":") > 0) { format = type.substring(type.indexOf(":") + 1, type.length()); type = type.substring(0, type.indexOf(":")); } m_typeField.setSelectedItem(type.trim()); m_dateFormatField.setText(format); } } } }); m_nameField.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent e) { Object a = m_list.getSelectedValue(); if (a != null) { ((AddUserFields.AttributeSpec) a).setName(m_nameField.getText()); m_list.repaint(); } } }); m_typeField.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Object a = m_list.getSelectedValue(); if (a != null) { String type = m_typeField.getSelectedItem().toString(); if (type.startsWith("date")) { // check to see if there is a date format specified String format = m_dateFormatField.getText(); if (format != null && format.length() > 0) { type += ":" + format; } } ((AddUserFields.AttributeSpec) a).setType(type); m_list.repaint(); } } }); m_valueField.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent e) { Object a = m_list.getSelectedValue(); if (a != null) { ((AddUserFields.AttributeSpec) a).setValue(m_valueField.getText()); m_list.repaint(); } } }); m_newBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { AddUserFields.AttributeSpec a = new AddUserFields.AttributeSpec(); String name = (m_nameField.getText() != null && m_nameField.getText() .length() > 0) ? m_nameField.getText() : "newAtt"; a.setName(name); String type = m_typeField.getSelectedItem().toString(); if (type.startsWith("date")) { if (m_dateFormatField.getText() != null && m_dateFormatField.getText().length() > 0) { type += ":" + m_dateFormatField.getText(); } } a.setType(type); String value = (m_valueField.getText() != null) ? m_valueField .getText() : ""; a.setValue(value); m_listModel.addElement(a); if (m_listModel.size() > 1) { m_upBut.setEnabled(true); m_downBut.setEnabled(true); } if (m_listModel.size() > 0) { m_nameField.setEnabled(true); m_typeField.setEnabled(true); m_dateFormatField.setEnabled(true); m_valueField.setEnabled(true); } m_list.setSelectedIndex(m_listModel.size() - 1); } }); m_deleteBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int selected = m_list.getSelectedIndex(); if (selected >= 0) { m_listModel.removeElementAt(selected); if (m_listModel.size() <= 1) { m_upBut.setEnabled(false); m_downBut.setEnabled(false); } if (m_listModel.size() == 0) { m_nameField.setEnabled(false); m_typeField.setEnabled(false); m_dateFormatField.setEnabled(false); m_valueField.setEnabled(false); } } } }); m_upBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JListHelper.moveUp(m_list); } }); m_downBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JListHelper.moveDown(m_list); } }); if (m_dontShowButs) { return; } addButtons(); } private void addButtons() { JButton okBut = new JButton("OK"); JButton cancelBut = new JButton("Cancel"); JPanel butHolder = new JPanel(); butHolder.setLayout(new GridLayout(1, 2)); butHolder.add(okBut); butHolder.add(cancelBut); add(butHolder, BorderLayout.SOUTH); okBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { closingOK(); } }); cancelBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { closingCancel(); } }); } /** * Set environment variables to use * * @param env the variables to use */ @Override public void setEnvironment(Environment env) { m_env = env; } /** * Set an object that is interested in knowing when we make a change to the * object that we're editing */ @Override public void setModifiedListener(ModifyListener l) { m_modifyL = l; } /** * Initialize the GUI with settings from the filter being edited. */ protected void initialize() { List<AddUserFields.AttributeSpec> specs = m_filter.getAttributeSpecs(); m_listModel = new DefaultListModel(); m_list.setModel(m_listModel); if (specs.size() > 0) { m_upBut.setEnabled(true); m_downBut.setEnabled(true); for (AddUserFields.AttributeSpec s : specs) { AddUserFields.AttributeSpec specCopy = new AddUserFields.AttributeSpec( s.toStringInternal()); m_listModel.addElement(specCopy); } m_list.repaint(); } else { // disable editing fields until the user has clicked new m_nameField.setEnabled(false); m_typeField.setEnabled(false); m_dateFormatField.setEnabled(false); m_valueField.setEnabled(false); } } /** * Set the filter to edit. * * @param o the filter to edit */ @Override public void setObject(Object o) { if (o instanceof AddUserFields) { m_filter = (AddUserFields) o; setup(); initialize(); } } /** * Tell this customizer not to show its own OK and Cancel buttons. */ @Override public void dontShowOKCancelButtons() { m_dontShowButs = true; } /** * Actions to perform when the user has closed the dialog with the OK button. */ @Override public void closingOK() { List<AddUserFields.AttributeSpec> specs = new ArrayList<AddUserFields.AttributeSpec>(); for (int i = 0; i < m_listModel.size(); i++) { AddUserFields.AttributeSpec a = (AddUserFields.AttributeSpec) m_listModel .elementAt(i); specs.add(a); } if (m_modifyL != null) { m_modifyL.setModifiedStatus(AddUserFieldsCustomizer.this, true); } m_filter.setAttributeSpecs(specs); } /** * Actions to perform when the user has closed the dialog with the Cancel * button */ @Override public void closingCancel() { // Nothing to do } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/graphvisualizer/BIFFormatException.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * BIFFormatException.java * Copyright (C) 2003-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.graphvisualizer; /** * This is the Exception thrown by BIFParser, if there * was an error in parsing the XMLBIF string or input * stream. * * @author Ashraf M. Kibriya (amk14@cs.waikato.ac.nz) * @version $Revision$ - 24 Apr 2003 - Initial version (Ashraf M. Kibriya) */ public class BIFFormatException extends Exception { /** for serialization */ private static final long serialVersionUID = -4102518086411708140L; public BIFFormatException(String s) { super(s); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/graphvisualizer/BIFParser.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * BIFParser.java * Copyright (C) 2003-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.graphvisualizer; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.util.ArrayList; import java.util.StringTokenizer; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; /** * This class parses an inputstream or a string in XMLBIF ver. 0.3 format, and * builds the datastructures that are passed to it through the constructor. * * @author Ashraf M. Kibriya (amk14@cs.waikato.ac.nz) * @version $Revision$ - 24 Apr 2003 - Initial version (Ashraf M. * Kibriya) */ public class BIFParser implements GraphConstants { /** These holds the nodes and edges of the graph */ protected ArrayList<GraphNode> m_nodes; protected ArrayList<GraphEdge> m_edges; /** * This holds the name of the graph (i.e. the name of network tag in XMLBIF * input) */ protected String graphName; /** This holds the string to be parsed */ protected String inString; /** This holds the InputStream to be parsed */ protected InputStream inStream; /** * Constructor (if our input is a String) * * @param input the string to be parsed (should not be null) * @param nodes vector containing GraphNode objects (should be empty) * @param edges vector containing GraphEdge objects (should be empty) */ public BIFParser(String input, ArrayList<GraphNode> nodes, ArrayList<GraphEdge> edges) { m_nodes = nodes; m_edges = edges; inString = input; } /** * Constructor (if our input is an InputStream) * * @param instream the InputStream to be parsed (should not be null) * @param nodes vector containing GraphNode objects (should be empty) * @param edges vector containing GraphEdge objects (should be empty) */ public BIFParser(InputStream instream, ArrayList<GraphNode> nodes, ArrayList<GraphEdge> edges) { m_nodes = nodes; m_edges = edges; inStream = instream; } /** * This method parses the string or the InputStream that we passed in through * the constructor and builds up the m_nodes and m_edges vectors * * @exception Exception if both the inString and inStream are null, i.e. no * input has been provided * @exception BIFFormatException if there is format of the input is not * correct. The format should conform to XMLBIF version 0.3 * @exception NumberFormatException if there is an invalid char in the * probability table of a node. * @return returns the name of the graph */ public String parse() throws Exception { Document dc = null; javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory .newInstance(); dbf.setIgnoringElementContentWhitespace(true); javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder(); if (inStream != null) { dc = db.parse(inStream); } else if (inString != null) { dc = db.parse(new org.xml.sax.InputSource(new StringReader(inString))); } else { throw new Exception("No input given"); } NodeList nl = dc.getElementsByTagName("NETWORK"); if (nl.getLength() == 0) { throw new BIFFormatException("NETWORK tag not found"); } // take only the first network node NodeList templist = ((Element) nl.item(0)).getElementsByTagName("NAME"); graphName = templist.item(0).getFirstChild().getNodeValue(); // System.out.println("The name of the network is "+ // templist.item(0).getFirstChild().getNodeValue()); // Get all the variables nl = dc.getElementsByTagName("VARIABLE"); for (int i = 0; i < nl.getLength(); i++) { templist = ((Element) nl.item(i)).getElementsByTagName("NAME"); if (templist.getLength() > 1) { throw new BIFFormatException("More than one name tags found for " + "variable no. " + (i + 1)); } String nodename = templist.item(0).getFirstChild().getNodeValue(); GraphNode n = new GraphNode(nodename, nodename, GraphNode.NORMAL); m_nodes.add(n); // getting nodes position templist = ((Element) nl.item(i)).getElementsByTagName("PROPERTY"); for (int j = 0; j < templist.getLength(); j++) { if (templist.item(j).getFirstChild().getNodeValue() .startsWith("position")) { String xy = templist.item(j).getFirstChild().getNodeValue(); // System.out.println("x: "+ // xy.substring(xy.indexOf('(')+1, xy.indexOf(','))+ // " y: "+ // xy.substring(xy.indexOf(',')+1, xy.indexOf(')')) // ); n.x = Integer.parseInt(xy.substring(xy.indexOf('(') + 1, xy.indexOf(',')).trim()); n.y = Integer.parseInt(xy.substring(xy.indexOf(',') + 1, xy.indexOf(')')).trim()); break; } } // getting all the outcomes of the node templist = ((Element) nl.item(i)).getElementsByTagName("OUTCOME"); n.outcomes = new String[templist.getLength()]; for (int j = 0; j < templist.getLength(); j++) { n.outcomes[j] = templist.item(j).getFirstChild().getNodeValue(); // System.out.println("Outcome["+j+"]: "+n.outcomes[j]); } } // end for (for variables) // Get all the edges and probability tables by getting all the definitions nl = dc.getElementsByTagName("DEFINITION"); for (int i = 0; i < nl.getLength(); i++) { templist = ((Element) nl.item(i)).getElementsByTagName("FOR"); // the Label of the node the edges are coming into String nid = templist.item(0).getFirstChild().getNodeValue(); // getting the GraphNode object with the above label GraphNode n = m_nodes.get(0); for (int j = 1; j < m_nodes.size() && !n.ID.equals(nid); j++) { n = m_nodes.get(j); } templist = ((Element) nl.item(i)).getElementsByTagName("GIVEN"); int parntOutcomes = 1; // for creating the probability table later on // creating all the edges coming into the node for (int j = 0; j < templist.getLength(); j++) { nid = templist.item(j).getFirstChild().getNodeValue(); GraphNode n2 = m_nodes.get(0); for (int k = 1; k < m_nodes.size() && !n2.ID.equals(nid); k++) { n2 = m_nodes.get(k); } m_edges.add(new GraphEdge(m_nodes.indexOf(n2), m_nodes.indexOf(n), 1)); parntOutcomes *= n2.outcomes.length; } // creating the probability table for the node templist = ((Element) nl.item(i)).getElementsByTagName("TABLE"); if (templist.getLength() > 1) { throw new BIFFormatException("More than one Probability Table for " + n.ID); } String probs = templist.item(0).getFirstChild().getNodeValue(); StringTokenizer tk = new StringTokenizer(probs, " \n\t"); if (parntOutcomes * n.outcomes.length > tk.countTokens()) { throw new BIFFormatException("Probability Table for " + n.ID + " contains more values than it should"); } else if (parntOutcomes * n.outcomes.length < tk.countTokens()) { throw new BIFFormatException("Probability Table for " + n.ID + " contains less values than it should"); } else { n.probs = new double[parntOutcomes][n.outcomes.length]; for (int r = 0; r < parntOutcomes; r++) { for (int c = 0; c < n.outcomes.length; c++) { try { n.probs[r][c] = Double.parseDouble(tk.nextToken()); } catch (NumberFormatException ne) { throw ne; } } } } // end of creating probability table } // endfor (for edges) // int tmpMatrix[][] = new int[m_nodes.size()][m_nodes.size()]; // for(int i=0; i<m_edges.size(); i++) // tmpMatrix[((GraphEdge)m_edges.elementAt(i)).src] // [((GraphEdge)m_edges.elementAt(i)).dest] = // ((GraphEdge)m_edges.elementAt(i)).type; // for(int i=0; i<m_nodes.size(); i++) { // GraphNode n = (GraphNode)m_nodes.elementAt(i); // n.edges = tmpMatrix[i]; // } // Adding parents, and those edges to a node which are coming out from it int noOfEdgesOfNode[] = new int[m_nodes.size()]; int noOfPrntsOfNode[] = new int[m_nodes.size()]; for (int i = 0; i < m_edges.size(); i++) { GraphEdge e = m_edges.get(i); noOfEdgesOfNode[e.src]++; noOfPrntsOfNode[e.dest]++; } for (int i = 0; i < m_edges.size(); i++) { GraphEdge e = m_edges.get(i); GraphNode n = m_nodes.get(e.src); GraphNode n2 = m_nodes.get(e.dest); if (n.edges == null) { n.edges = new int[noOfEdgesOfNode[e.src]][2]; for (int k = 0; k < n.edges.length; k++) { n.edges[k][0] = -1; } } if (n2.prnts == null) { n2.prnts = new int[noOfPrntsOfNode[e.dest]]; for (int k = 0; k < n2.prnts.length; k++) { n2.prnts[k] = -1; } } int k = 0; while (n.edges[k][0] != -1) { k++; } n.edges[k][0] = e.dest; n.edges[k][1] = e.type; k = 0; while (n2.prnts[k] != -1) { k++; } n2.prnts[k] = e.src; } // processGraph(); // setAppropriateSize(); return graphName; } // end readBIF /** * This method writes a graph in XMLBIF ver. 0.3 format to a file. However, if * is reloaded in GraphVisualizer we would need to layout the graph again to * display it correctly. * * @param filename The name of the file to write in. (will overwrite) * @param graphName The name of the graph. (will be the name of network tag in * XMLBIF) * @param nodes Vector containing all the nodes * @param edges Vector containing all the edges */ public static void writeXMLBIF03(String filename, String graphName, ArrayList<GraphNode> nodes, ArrayList<GraphEdge> edges) { try { FileWriter outfile = new FileWriter(filename); StringBuffer text = new StringBuffer(); text.append("<?xml version=\"1.0\"?>\n"); text.append("<!-- DTD for the XMLBIF 0.3 format -->\n"); text.append("<!DOCTYPE BIF [\n"); text.append(" <!ELEMENT BIF ( NETWORK )*>\n"); text.append(" <!ATTLIST BIF VERSION CDATA #REQUIRED>\n"); text.append(" <!ELEMENT NETWORK ( NAME, ( PROPERTY | VARIABLE | DEFI" + "NITION )* )>\n"); text.append(" <!ELEMENT NAME (#PCDATA)>\n"); text.append(" <!ELEMENT VARIABLE ( NAME, ( OUTCOME | PROPERTY )* )" + " >\n"); text.append(" <!ATTLIST VARIABLE TYPE (nature|decision|utility" + ") \"nature\">\n"); text.append(" <!ELEMENT OUTCOME (#PCDATA)>\n"); text.append(" <!ELEMENT DEFINITION ( FOR | GIVEN | TABLE | PROPERTY" + " )* >\n"); text.append(" <!ELEMENT FOR (#PCDATA)>\n"); text.append(" <!ELEMENT GIVEN (#PCDATA)>\n"); text.append(" <!ELEMENT TABLE (#PCDATA)>\n"); text.append(" <!ELEMENT PROPERTY (#PCDATA)>\n"); text.append("]>\n"); text.append("\n"); text.append("\n"); text.append("<BIF VERSION=\"0.3\">\n"); text.append("<NETWORK>\n"); text.append("<NAME>" + XMLNormalize(graphName) + "</NAME>\n"); // Writing all the node names and their outcomes // If outcome is null(ie if the graph was loaded from DOT file) then // simply write TRUE for (int nodeidx = 0; nodeidx < nodes.size(); nodeidx++) { GraphNode n = nodes.get(nodeidx); if (n.nodeType != GraphNode.NORMAL) { continue; } text.append("<VARIABLE TYPE=\"nature\">\n"); text.append("\t<NAME>" + XMLNormalize(n.ID) + "</NAME>\n"); if (n.outcomes != null) { for (String outcome : n.outcomes) { text.append("\t<OUTCOME>" + XMLNormalize(outcome) + "</OUTCOME>\n"); } } else { text.append("\t<OUTCOME>true</OUTCOME>\n"); } text.append("\t<PROPERTY>position = (" + n.x + "," + n.y + ")</PROPERTY>\n"); text.append("</VARIABLE>\n"); } // Writing all the nodes definitions and their probability tables // If probability table is null then simply write 1 for all // the possible outcomes of the parents for (int nodeidx = 0; nodeidx < nodes.size(); nodeidx++) { GraphNode n = nodes.get(nodeidx); if (n.nodeType != GraphNode.NORMAL) { continue; } text.append("<DEFINITION>\n"); text.append("<FOR>" + XMLNormalize(n.ID) + "</FOR>\n"); int parntOutcomes = 1; if (n.prnts != null) { for (int prnt2 : n.prnts) { GraphNode prnt = nodes.get(prnt2); text.append("\t<GIVEN>" + XMLNormalize(prnt.ID) + "</GIVEN>\n"); if (prnt.outcomes != null) { parntOutcomes *= prnt.outcomes.length; } } } text.append("<TABLE>\n"); for (int i = 0; i < parntOutcomes; i++) { if (n.outcomes != null) { for (int outidx = 0; outidx < n.outcomes.length; outidx++) { text.append(n.probs[i][outidx] + " "); } } else { text.append("1"); } text.append('\n'); } text.append("</TABLE>\n"); text.append("</DEFINITION>\n"); } text.append("</NETWORK>\n"); text.append("</BIF>\n"); outfile.write(text.toString()); outfile.close(); } catch (IOException ex) { ex.printStackTrace(); } }// writeXMLBIF /** * XMLNormalize converts the five standard XML entities in a string g.e. the * string V&D's is returned as V&amp;D&apos;s * * @author Remco Bouckaert (rrb@xm.co.nz) * @param sStr string to normalize * @return normalized string */ private static String XMLNormalize(String sStr) { StringBuffer sStr2 = new StringBuffer(); for (int iStr = 0; iStr < sStr.length(); iStr++) { char c = sStr.charAt(iStr); switch (c) { case '&': sStr2.append("&amp;"); break; case '\'': sStr2.append("&apos;"); break; case '\"': sStr2.append("&quot;"); break; case '<': sStr2.append("&lt;"); break; case '>': sStr2.append("&gt;"); break; default: sStr2.append(c); } } return sStr2.toString(); } // XMLNormalize } // BIFParser
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/graphvisualizer/DotParser.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * DotParser.java * Copyright (C) 2003-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.graphvisualizer; import java.io.BufferedReader; import java.io.FileWriter; import java.io.IOException; import java.io.Reader; import java.io.StreamTokenizer; import java.util.ArrayList; /** * This class parses input in DOT format, and builds the datastructures that are * passed to it. It is NOT 100% compatible with the DOT format. The GraphNode * and GraphEdge classes do not have any provision for dealing with different * colours or shapes of nodes, there can however, be a different label and ID * for a node. It also does not do anything for labels for edges. However, this * class won't crash or throw an exception if it encounters any of the above * attributes of an edge or a node. This class however, won't be able to deal * with things like subgraphs and grouping of nodes. * * @author Ashraf M. Kibriya (amk14@cs.waikato.ac.nz) * @version $Revision$ - 23 Apr 2003 - Initial version (Ashraf M. * Kibriya) */ public class DotParser implements GraphConstants { /** These holds the nodes and edges of the graph */ protected ArrayList<GraphNode> m_nodes; protected ArrayList<GraphEdge> m_edges; /** This is the input containing DOT stream to be parsed */ protected Reader m_input; /** This holds the name of the graph if there is any otherwise it is null */ protected String m_graphName; /** * * Dot parser Constructor * * @param input - The input, if passing in a string then encapsulate that in * String reader object * @param nodes - Vector to put in GraphNode objects, corresponding to the * nodes parsed in from the input * @param edges - Vector to put in GraphEdge objects, corresponding to the * edges parsed in from the input */ public DotParser(Reader input, ArrayList<GraphNode> nodes, ArrayList<GraphEdge> edges) { m_nodes = nodes; m_edges = edges; m_input = input; } /** * This method parses the string or the InputStream that we passed in through * the constructor and builds up the m_nodes and m_edges vectors * * @return - returns the name of the graph */ public String parse() { StreamTokenizer tk = new StreamTokenizer(new BufferedReader(m_input)); setSyntax(tk); graph(tk); return m_graphName; } /** * This method sets the syntax of the StreamTokenizer. i.e. set the * whitespace, comment and delimit chars. * */ protected void setSyntax(StreamTokenizer tk) { tk.resetSyntax(); tk.eolIsSignificant(false); tk.slashStarComments(true); tk.slashSlashComments(true); tk.whitespaceChars(0, ' '); tk.wordChars(' ' + 1, '\u00ff'); tk.ordinaryChar('['); tk.ordinaryChar(']'); tk.ordinaryChar('{'); tk.ordinaryChar('}'); tk.ordinaryChar('-'); tk.ordinaryChar('>'); tk.ordinaryChar('/'); tk.ordinaryChar('*'); tk.quoteChar('"'); tk.whitespaceChars(';', ';'); tk.ordinaryChar('='); } /************************************************************* * * Following methods parse the DOT input and mimic the DOT language's grammar * in their structure * ************************************************************* */ protected void graph(StreamTokenizer tk) { try { tk.nextToken(); if (tk.ttype == StreamTokenizer.TT_WORD) { if (tk.sval.equalsIgnoreCase("digraph")) { tk.nextToken(); if (tk.ttype == StreamTokenizer.TT_WORD) { m_graphName = tk.sval; tk.nextToken(); } while (tk.ttype != '{') { System.err.println("Error at line " + tk.lineno() + " ignoring token " + tk.sval); tk.nextToken(); if (tk.ttype == StreamTokenizer.TT_EOF) { return; } } stmtList(tk); } else if (tk.sval.equalsIgnoreCase("graph")) { System.err.println("Error. Undirected graphs cannot be used"); } else { System.err.println("Error. Expected graph or digraph at line " + tk.lineno()); } } } catch (Exception ex) { ex.printStackTrace(); } // int tmpMatrix[][] = new int[m_nodes.size()][m_nodes.size()]; // for(int i=0; i<m_edges.size(); i++) // tmpMatrix[((GraphEdge)m_edges.get(i)).src] // [((GraphEdge)m_edges.get(i)).dest] = // ((GraphEdge)m_edges.get(i)).type; // for(int i=0; i<m_nodes.size(); i++) { // GraphNode n = (GraphNode)m_nodes.get(i); // n.edges = tmpMatrix[i]; // } // Adding parents, and those edges to a node which are coming out from it int noOfEdgesOfNode[] = new int[m_nodes.size()]; int noOfPrntsOfNode[] = new int[m_nodes.size()]; for (int i = 0; i < m_edges.size(); i++) { GraphEdge e = m_edges.get(i); noOfEdgesOfNode[e.src]++; noOfPrntsOfNode[e.dest]++; } for (int i = 0; i < m_edges.size(); i++) { GraphEdge e = m_edges.get(i); GraphNode n = m_nodes.get(e.src); GraphNode n2 = m_nodes.get(e.dest); if (n.edges == null) { n.edges = new int[noOfEdgesOfNode[e.src]][2]; for (int k = 0; k < n.edges.length; k++) { n.edges[k][1] = 0; } } if (n2.prnts == null) { n2.prnts = new int[noOfPrntsOfNode[e.dest]]; for (int k = 0; k < n2.prnts.length; k++) { n2.prnts[k] = -1; } } int k = 0; while (n.edges[k][1] != 0) { k++; } n.edges[k][0] = e.dest; n.edges[k][1] = e.type; k = 0; while (n2.prnts[k] != -1) { k++; } n2.prnts[k] = e.src; } } protected void stmtList(StreamTokenizer tk) throws Exception { tk.nextToken(); if (tk.ttype == '}' || tk.ttype == StreamTokenizer.TT_EOF) { return; } else { stmt(tk); stmtList(tk); } } protected void stmt(StreamTokenizer tk) { // tk.nextToken(); if (tk.sval.equalsIgnoreCase("graph") || tk.sval.equalsIgnoreCase("node") || tk.sval.equalsIgnoreCase("edge")) { ; // attribStmt(k); } else { try { nodeID(tk); int nodeindex = m_nodes.indexOf(new GraphNode(tk.sval, null)); tk.nextToken(); if (tk.ttype == '[') { nodeStmt(tk, nodeindex); } else if (tk.ttype == '-') { edgeStmt(tk, nodeindex); } else { System.err.println("error at lineno " + tk.lineno() + " in stmt"); } } catch (Exception ex) { System.err.println("error at lineno " + tk.lineno() + " in stmtException"); ex.printStackTrace(); } } } protected void nodeID(StreamTokenizer tk) throws Exception { if (tk.ttype == '"' || tk.ttype == StreamTokenizer.TT_WORD || (tk.ttype >= 'a' && tk.ttype <= 'z') || (tk.ttype >= 'A' && tk.ttype <= 'Z')) { if (m_nodes != null && !(m_nodes.contains(new GraphNode(tk.sval, null)))) { m_nodes.add(new GraphNode(tk.sval, tk.sval)); // System.out.println("Added node >"+tk.sval+"<"); } } else { throw new Exception(); } // tk.nextToken(); } protected void nodeStmt(StreamTokenizer tk, final int nindex) throws Exception { tk.nextToken(); GraphNode temp = m_nodes.get(nindex); if (tk.ttype == ']' || tk.ttype == StreamTokenizer.TT_EOF) { return; } else if (tk.ttype == StreamTokenizer.TT_WORD) { if (tk.sval.equalsIgnoreCase("label")) { tk.nextToken(); if (tk.ttype == '=') { tk.nextToken(); if (tk.ttype == StreamTokenizer.TT_WORD || tk.ttype == '"') { temp.lbl = tk.sval; } else { System.err.println("couldn't find label at line " + tk.lineno()); tk.pushBack(); } } else { System.err.println("couldn't find label at line " + tk.lineno()); tk.pushBack(); } } else if (tk.sval.equalsIgnoreCase("color")) { tk.nextToken(); if (tk.ttype == '=') { tk.nextToken(); if (tk.ttype == StreamTokenizer.TT_WORD || tk.ttype == '"') { ; } else { System.err.println("couldn't find color at line " + tk.lineno()); tk.pushBack(); } } else { System.err.println("couldn't find color at line " + tk.lineno()); tk.pushBack(); } } else if (tk.sval.equalsIgnoreCase("style")) { tk.nextToken(); if (tk.ttype == '=') { tk.nextToken(); if (tk.ttype == StreamTokenizer.TT_WORD || tk.ttype == '"') { ; } else { System.err.println("couldn't find style at line " + tk.lineno()); tk.pushBack(); } } else { System.err.println("couldn't find style at line " + tk.lineno()); tk.pushBack(); } } } nodeStmt(tk, nindex); } protected void edgeStmt(StreamTokenizer tk, final int nindex) throws Exception { tk.nextToken(); GraphEdge e = null; if (tk.ttype == '>') { tk.nextToken(); if (tk.ttype == '{') { while (true) { tk.nextToken(); if (tk.ttype == '}') { break; } else { nodeID(tk); e = new GraphEdge(nindex, m_nodes.indexOf(new GraphNode(tk.sval, null)), DIRECTED); if (m_edges != null && !(m_edges.contains(e))) { m_edges.add(e); // System.out.println("Added edge from "+ // ((GraphNode)(m_nodes.get(nindex))).ID+ // " to "+ // ((GraphNode)(m_nodes.get(e.dest))).ID); } } } } else { nodeID(tk); e = new GraphEdge(nindex, m_nodes.indexOf(new GraphNode(tk.sval, null)), DIRECTED); if (m_edges != null && !(m_edges.contains(e))) { m_edges.add(e); // System.out.println("Added edge from "+ // ((GraphNode)(m_nodes.get(nindex))).ID+" to "+ // ((GraphNode)(m_nodes.get(e.dest))).ID); } } } else if (tk.ttype == '-') { System.err.println("Error at line " + tk.lineno() + ". Cannot deal with undirected edges"); if (tk.ttype == StreamTokenizer.TT_WORD) { tk.pushBack(); } return; } else { System.err.println("Error at line " + tk.lineno() + " in edgeStmt"); if (tk.ttype == StreamTokenizer.TT_WORD) { tk.pushBack(); } return; } tk.nextToken(); if (tk.ttype == '[') { edgeAttrib(tk, e); } else { tk.pushBack(); } } protected void edgeAttrib(StreamTokenizer tk, final GraphEdge e) throws Exception { tk.nextToken(); if (tk.ttype == ']' || tk.ttype == StreamTokenizer.TT_EOF) { return; } else if (tk.ttype == StreamTokenizer.TT_WORD) { if (tk.sval.equalsIgnoreCase("label")) { tk.nextToken(); if (tk.ttype == '=') { tk.nextToken(); if (tk.ttype == StreamTokenizer.TT_WORD || tk.ttype == '"') { System.err.println("found label " + tk.sval);// e.lbl = tk.sval; } else { System.err.println("couldn't find label at line " + tk.lineno()); tk.pushBack(); } } else { System.err.println("couldn't find label at line " + tk.lineno()); tk.pushBack(); } } else if (tk.sval.equalsIgnoreCase("color")) { tk.nextToken(); if (tk.ttype == '=') { tk.nextToken(); if (tk.ttype == StreamTokenizer.TT_WORD || tk.ttype == '"') { ; } else { System.err.println("couldn't find color at line " + tk.lineno()); tk.pushBack(); } } else { System.err.println("couldn't find color at line " + tk.lineno()); tk.pushBack(); } } else if (tk.sval.equalsIgnoreCase("style")) { tk.nextToken(); if (tk.ttype == '=') { tk.nextToken(); if (tk.ttype == StreamTokenizer.TT_WORD || tk.ttype == '"') { ; } else { System.err.println("couldn't find style at line " + tk.lineno()); tk.pushBack(); } } else { System.err.println("couldn't find style at line " + tk.lineno()); tk.pushBack(); } } } edgeAttrib(tk, e); } /** * * This method saves a graph in a file in DOT format. However, if reloaded in * GraphVisualizer we would need to layout the graph again. * * @param filename - The name of the file to write in. (will overwrite) * @param graphName - The name of the graph * @param nodes - Vector containing all the nodes * @param edges - Vector containing all the edges */ public static void writeDOT(String filename, String graphName, ArrayList<GraphNode> nodes, ArrayList<GraphEdge> edges) { try { FileWriter os = new FileWriter(filename); os.write("digraph ", 0, ("digraph ").length()); if (graphName != null) { os.write(graphName + " ", 0, graphName.length() + 1); } os.write("{\n", 0, ("{\n").length()); GraphEdge e; for (int i = 0; i < edges.size(); i++) { e = edges.get(i); os.write(nodes.get(e.src).ID, 0, nodes.get(e.src).ID.length()); os.write("->", 0, ("->").length()); os.write(nodes.get(e.dest).ID + "\n", 0, nodes.get(e.dest).ID.length() + 1); } os.write("}\n", 0, ("}\n").length()); os.close(); } catch (IOException ex) { ex.printStackTrace(); } } } // DotParser
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/graphvisualizer/GraphConstants.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * GraphConstants.java * Copyright (C) 2003-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.graphvisualizer; /** * GraphConstants.java * * * @author Ashraf M. Kibriya (amk14@cs.waikato.ac.nz) * @version $Revision$ - 24 Apr 2003 - Initial version (Ashraf M. Kibriya) */ public interface GraphConstants { /** Types of Edges */ int DIRECTED=1, REVERSED=2, DOUBLE=3; //Node types /** SINGULAR_DUMMY node - node with only one outgoing edge * i.e. one which represents a single edge and is inserted to close a gap */ int SINGULAR_DUMMY=1; /** PLURAL_DUMMY node - node with more than one outgoing edge * i.e. which represents an edge split and is inserted to close a gap */ int PLURAL_DUMMY=2; /** NORMAL node - node actually contained in graphs description */ int NORMAL=3; } // GraphConstants
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/graphvisualizer/GraphEdge.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * GraphEdge.java * Copyright (C) 2003-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.graphvisualizer; /** * This class represents an edge in the graph * * @author Ashraf M. Kibriya (amk14@cs.waikato.ac.nz) * @version $Revision$ - 23 Apr 2003 - Initial version (Ashraf M. Kibriya) */ public class GraphEdge extends Object { /** The index of source node in Nodes vector */ public int src; /** The index of target node in Nodes vector */ public int dest; /** The type of Edge */ public int type; /** Label of source node */ public String srcLbl; /** Label of target node */ public String destLbl; public GraphEdge(int s, int d, int t) { src=s; dest=d; type=t; srcLbl = null; destLbl = null; } public GraphEdge(int s, int d, int t, String sLbl, String dLbl) { src=s; dest=d; type=t; srcLbl = sLbl; destLbl = dLbl; } public String toString() { return ("("+src+","+dest+","+type+")"); } public boolean equals(Object e) { if( e instanceof GraphEdge && ((GraphEdge)e).src==this.src && ((GraphEdge)e).dest==this.dest && ((GraphEdge)e).type==this.type) return true; else return false; } } // GraphEdge
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/graphvisualizer/GraphNode.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * GraphNode.java * Copyright (C) 2003-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.graphvisualizer; /** * This class represents a node in the Graph. * * @author Ashraf M. Kibriya (amk14@cs.waikato.ac.nz) * @version $Revision$ - 23 Apr 2003 - Initial version (Ashraf M. Kibriya) */ public class GraphNode extends Object implements GraphConstants { /** ID and label for the node */ public String ID, lbl; /** The outcomes for the given node */ public String [] outcomes; /** probability table for each outcome given outcomes of parents, if any */ public double [][] probs; //probabilities /** The x and y position of the node */ public int x=0, y=0; /** The indices of parent nodes */ public int [] prnts; //parent nodes /** The indices of nodes to which there are edges from this * node, plus the type of edge */ public int [][] edges; /** Type of node. Default is Normal node type */ public int nodeType=NORMAL; /** * Constructor * */ public GraphNode(String id, String label) { ID = id; lbl = label; nodeType=NORMAL; } /** * Constructor * */ public GraphNode(String id, String label, int type ) { ID = id; lbl = label; nodeType = type; } /** * Returns true if passed in argument is an instance * of GraphNode and is equal to this node. * Implemented to enable the use of contains method * in Vector/FastVector class. */ public boolean equals(Object n) { if(n instanceof GraphNode && ((GraphNode) n).ID.equalsIgnoreCase(this.ID)) { //System.out.println("returning true, n.ID >"+((GraphNode)n).ID+ // "< this.ID >"+this.ID+"<"); return true; } else return false; } } // GraphNode
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/graphvisualizer/GraphVisualizer.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * GraphVisualizer.java * Copyright (C) 2003-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.graphvisualizer; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Container; import java.awt.Dialog.ModalityType; import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Frame; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.LayoutManager; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionAdapter; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.util.ArrayList; import javax.swing.*; import javax.swing.table.AbstractTableModel; import weka.gui.ExtensionFileFilter; import weka.gui.visualize.PrintablePanel; /** * This class displays the graph we want to visualize. It should be sufficient * to use only this class in weka.gui.graphvisulizer package to visualize a * graph. The description of a graph should be provided as a string argument * using readBIF or readDOT method in either XMLBIF03 or DOT format. * Alternatively, an InputStream in XMLBIF03 can also be provided to another * variation of readBIF. It would be necessary in case input is in DOT format to * call the layoutGraph() method to display the graph correctly after the call * to readDOT. It is also necessary to do so if readBIF is called and the graph * description doesn't have x y positions for nodes. * <p> * The graph's data is held in two FastVectors, nodes are stored as objects of * GraphNode class and edges as objects of GraphEdge class. * <p> * The graph is displayed by positioning and drawing each node according to its * x y position and then drawing all the edges coming out of it give by its * edges[][] array, the arrow heads are ofcourse marked in the opposite(ie * original direction) or both directions if the edge is reversed or is in both * directions. The graph is centered if it is smaller than it's display area. * The edges are drawn from the bottom of the current node to the top of the * node given by edges[][] array in GraphNode class, to avoid edges crossing * over other nodes. This might need to be changed if another layout engine is * added or the current Hierarchical engine is updated to avoid such crossings * over nodes. * * @author Ashraf M. Kibriya (amk14@cs.waikato.ac.nz) * @version $Revision$ */ public class GraphVisualizer extends JPanel implements GraphConstants, LayoutCompleteEventListener { /** for serialization */ private static final long serialVersionUID = -2038911085935515624L; /** Vector containing nodes */ protected ArrayList<GraphNode> m_nodes = new ArrayList<GraphNode>(); /** Vector containing edges */ protected ArrayList<GraphEdge> m_edges = new ArrayList<GraphEdge>(); /** The current LayoutEngine */ protected LayoutEngine m_le; /** Panel actually displaying the graph */ protected GraphPanel m_gp; /** String containing graph's name */ protected String graphID; /** * Save button to save the current graph in DOT or XMLBIF format. The graph * should be layed out again to get the original form if reloaded from command * line, as the formats do not allow saving specific information for a * properly layed out graph. */ protected JButton m_jBtSave; /** path for icons */ private final String ICONPATH = "weka/gui/graphvisualizer/icons/"; private final FontMetrics fm = this.getFontMetrics(this.getFont()); private double scale = 1; // current zoom private int nodeHeight = 2 * fm.getHeight(), nodeWidth = 24; private int paddedNodeWidth = 24 + 8; /** TextField for node's width */ private final JTextField jTfNodeWidth = new JTextField(3); /** TextField for nodes height */ private final JTextField jTfNodeHeight = new JTextField(3); /** * Button for laying out the graph again, necessary after changing node's size * or some other property of the layout engine */ private final JButton jBtLayout; /** used for setting appropriate node size */ private int maxStringWidth = 0; /** used when using zoomIn and zoomOut buttons */ private final int[] zoomPercents = { 10, 25, 50, 75, 100, 125, 150, 175, 200, 225, 250, 275, 300, 350, 400, 450, 500, 550, 600, 650, 700, 800, 900, 999 }; /** this contains the m_gp GraphPanel */ JScrollPane m_js; /** * Constructor<br> * Sets up the gui and initializes all the other previously uninitialized * variables. */ public GraphVisualizer() { m_gp = new GraphPanel(); m_js = new JScrollPane(m_gp); // creating a new layout engine and adding this class as its listener // to receive layoutComplete events m_le = new HierarchicalBCEngine(m_nodes, m_edges, paddedNodeWidth, nodeHeight); m_le.addLayoutCompleteEventListener(this); m_jBtSave = new JButton(); java.net.URL tempURL = ClassLoader.getSystemResource(ICONPATH + "save.gif"); if (tempURL != null) { m_jBtSave.setIcon(new ImageIcon(tempURL)); } else { System.err.println(ICONPATH + "save.gif not found for weka.gui.graphvisualizer.Graph"); } m_jBtSave.setToolTipText("Save Graph"); m_jBtSave.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { JFileChooser fc = new JFileChooser(System.getProperty("user.dir")); ExtensionFileFilter ef1 = new ExtensionFileFilter(".dot", "DOT files"); ExtensionFileFilter ef2 = new ExtensionFileFilter(".xml", "XML BIF files"); fc.addChoosableFileFilter(ef1); fc.addChoosableFileFilter(ef2); fc.setDialogTitle("Save Graph As"); int rval = fc.showSaveDialog(GraphVisualizer.this); if (rval == JFileChooser.APPROVE_OPTION) { // System.out.println("Saving to file \""+ // f.getAbsoluteFile().toString()+"\""); if (fc.getFileFilter() == ef2) { String filename = fc.getSelectedFile().toString(); if (!filename.endsWith(".xml")) { filename = filename.concat(".xml"); } BIFParser.writeXMLBIF03(filename, graphID, m_nodes, m_edges); } else { String filename = fc.getSelectedFile().toString(); if (!filename.endsWith(".dot")) { filename = filename.concat(".dot"); } DotParser.writeDOT(filename, graphID, m_nodes, m_edges); } } } }); final JButton jBtZoomIn = new JButton(); tempURL = ClassLoader.getSystemResource(ICONPATH + "zoomin.gif"); if (tempURL != null) { jBtZoomIn.setIcon(new ImageIcon(tempURL)); } else { System.err.println(ICONPATH + "zoomin.gif not found for weka.gui.graphvisualizer.Graph"); } jBtZoomIn.setToolTipText("Zoom In"); final JButton jBtZoomOut = new JButton(); tempURL = ClassLoader.getSystemResource(ICONPATH + "zoomout.gif"); if (tempURL != null) { jBtZoomOut.setIcon(new ImageIcon(tempURL)); } else { System.err.println(ICONPATH + "zoomout.gif not found for weka.gui.graphvisualizer.Graph"); } jBtZoomOut.setToolTipText("Zoom Out"); final JTextField jTfZoom = new JTextField("100%"); jTfZoom.setMinimumSize(jTfZoom.getPreferredSize()); jTfZoom.setHorizontalAlignment(JTextField.CENTER); jTfZoom.setToolTipText("Zoom"); jTfZoom.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { JTextField jt = (JTextField) ae.getSource(); try { int i = -1; i = jt.getText().indexOf('%'); if (i == -1) { i = Integer.parseInt(jt.getText()); } else { i = Integer.parseInt(jt.getText().substring(0, i)); } if (i <= 999) { scale = i / 100D; } jt.setText((int) (scale * 100) + "%"); if (scale > 0.1) { if (!jBtZoomOut.isEnabled()) { jBtZoomOut.setEnabled(true); } } else { jBtZoomOut.setEnabled(false); } if (scale < 9.99) { if (!jBtZoomIn.isEnabled()) { jBtZoomIn.setEnabled(true); } } else { jBtZoomIn.setEnabled(false); } setAppropriateSize(); // m_gp.clearBuffer(); m_gp.repaint(); m_gp.invalidate(); m_js.revalidate(); } catch (NumberFormatException ne) { JOptionPane.showMessageDialog(GraphVisualizer.this.getParent(), "Invalid integer entered for zoom.", "Error", JOptionPane.ERROR_MESSAGE); jt.setText((scale * 100) + "%"); } } }); jBtZoomIn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { int i = 0, s = (int) (scale * 100); if (s < 300) { i = s / 25; } else if (s < 700) { i = 6 + s / 50; } else { i = 13 + s / 100; } if (s >= 999) { JButton b = (JButton) ae.getSource(); b.setEnabled(false); return; } else if (s >= 10) { if (i >= 22) { JButton b = (JButton) ae.getSource(); b.setEnabled(false); } if (s == 10 && !jBtZoomOut.isEnabled()) { jBtZoomOut.setEnabled(true); } // System.out.println("i: "+i+"Zoom is: "+zoomPercents[i+1]); jTfZoom.setText(zoomPercents[i + 1] + "%"); scale = zoomPercents[i + 1] / 100D; } else { if (!jBtZoomOut.isEnabled()) { jBtZoomOut.setEnabled(true); } // System.out.println("i: "+i+"Zoom is: "+zoomPercents[0]); jTfZoom.setText(zoomPercents[0] + "%"); scale = zoomPercents[0] / 100D; } setAppropriateSize(); m_gp.repaint(); m_gp.invalidate(); m_js.revalidate(); } }); jBtZoomOut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { int i = 0, s = (int) (scale * 100); if (s < 300) { i = (int) Math.ceil(s / 25D); } else if (s < 700) { i = 6 + (int) Math.ceil(s / 50D); } else { i = 13 + (int) Math.ceil(s / 100D); } if (s <= 10) { JButton b = (JButton) ae.getSource(); b.setEnabled(false); } else if (s < 999) { if (i <= 1) { JButton b = (JButton) ae.getSource(); b.setEnabled(false); } // System.out.println("i: "+i+"Zoom is: "+zoomPercents[i-1]); jTfZoom.setText(zoomPercents[i - 1] + "%"); scale = zoomPercents[i - 1] / 100D; } else { if (!jBtZoomIn.isEnabled()) { jBtZoomIn.setEnabled(true); } // System.out.println("i: "+i+"Zoom is: "+zoomPercents[22]); jTfZoom.setText(zoomPercents[22] + "%"); scale = zoomPercents[22] / 100D; } setAppropriateSize(); m_gp.repaint(); m_gp.invalidate(); m_js.revalidate(); } }); // This button pops out the extra controls JButton jBtExtraControls = new JButton(); tempURL = ClassLoader.getSystemResource(ICONPATH + "extra.gif"); if (tempURL != null) { jBtExtraControls.setIcon(new ImageIcon(tempURL)); } else { System.err.println(ICONPATH + "extra.gif not found for weka.gui.graphvisualizer.Graph"); } jBtExtraControls.setToolTipText("Show/Hide extra controls"); final JCheckBox jCbCustomNodeSize = new JCheckBox("Custom Node Size"); final JLabel jLbNodeWidth = new JLabel("Width"); final JLabel jLbNodeHeight = new JLabel("Height"); jTfNodeWidth.setHorizontalAlignment(JTextField.CENTER); jTfNodeWidth.setText("" + nodeWidth); jTfNodeHeight.setHorizontalAlignment(JTextField.CENTER); jTfNodeHeight.setText("" + nodeHeight); jLbNodeWidth.setEnabled(false); jTfNodeWidth.setEnabled(false); jLbNodeHeight.setEnabled(false); jTfNodeHeight.setEnabled(false); jCbCustomNodeSize.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { if (((JCheckBox) ae.getSource()).isSelected()) { jLbNodeWidth.setEnabled(true); jTfNodeWidth.setEnabled(true); jLbNodeHeight.setEnabled(true); jTfNodeHeight.setEnabled(true); } else { jLbNodeWidth.setEnabled(false); jTfNodeWidth.setEnabled(false); jLbNodeHeight.setEnabled(false); jTfNodeHeight.setEnabled(false); setAppropriateNodeSize(); } } }); jBtLayout = new JButton("Layout Graph"); jBtLayout.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { int tmpW, tmpH; if (jCbCustomNodeSize.isSelected()) { try { tmpW = Integer.parseInt(jTfNodeWidth.getText()); } catch (NumberFormatException ne) { JOptionPane.showMessageDialog(GraphVisualizer.this.getParent(), "Invalid integer entered for node width.", "Error", JOptionPane.ERROR_MESSAGE); tmpW = nodeWidth; jTfNodeWidth.setText("" + nodeWidth); } try { tmpH = Integer.parseInt(jTfNodeHeight.getText()); } catch (NumberFormatException ne) { JOptionPane.showMessageDialog(GraphVisualizer.this.getParent(), "Invalid integer entered for node height.", "Error", JOptionPane.ERROR_MESSAGE); tmpH = nodeHeight; jTfNodeWidth.setText("" + nodeHeight); } if (tmpW != nodeWidth || tmpH != nodeHeight) { nodeWidth = tmpW; paddedNodeWidth = nodeWidth + 8; nodeHeight = tmpH; } } JButton bt = (JButton) ae.getSource(); bt.setEnabled(false); m_le.setNodeSize(paddedNodeWidth, nodeHeight); m_le.layoutGraph(); } }); GridBagConstraints gbc = new GridBagConstraints(); final JPanel p = new JPanel(new GridBagLayout()); gbc.gridwidth = GridBagConstraints.REMAINDER; gbc.anchor = GridBagConstraints.NORTHWEST; gbc.fill = GridBagConstraints.NONE; p.add(m_le.getControlPanel(), gbc); gbc.gridwidth = 1; gbc.insets = new Insets(8, 0, 0, 0); gbc.anchor = GridBagConstraints.NORTHWEST; gbc.gridwidth = GridBagConstraints.REMAINDER; p.add(jCbCustomNodeSize, gbc); gbc.insets = new Insets(0, 0, 0, 0); gbc.gridwidth = GridBagConstraints.REMAINDER; Container c = new Container(); c.setLayout(new GridBagLayout()); gbc.gridwidth = GridBagConstraints.RELATIVE; c.add(jLbNodeWidth, gbc); gbc.gridwidth = GridBagConstraints.REMAINDER; c.add(jTfNodeWidth, gbc); gbc.gridwidth = GridBagConstraints.RELATIVE; c.add(jLbNodeHeight, gbc); gbc.gridwidth = GridBagConstraints.REMAINDER; c.add(jTfNodeHeight, gbc); gbc.fill = GridBagConstraints.HORIZONTAL; p.add(c, gbc); gbc.anchor = GridBagConstraints.NORTHWEST; gbc.insets = new Insets(8, 0, 0, 0); gbc.fill = GridBagConstraints.HORIZONTAL; p.add(jBtLayout, gbc); gbc.fill = GridBagConstraints.NONE; p.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createTitledBorder("ExtraControls"), BorderFactory.createEmptyBorder(4, 4, 4, 4))); p.setPreferredSize(new Dimension(0, 0)); final JToolBar jTbTools = new JToolBar(); jTbTools.setFloatable(false); jTbTools.setLayout(new GridBagLayout()); gbc.anchor = GridBagConstraints.NORTHWEST; gbc.gridwidth = GridBagConstraints.REMAINDER; gbc.insets = new Insets(0, 0, 0, 0); jTbTools.add(p, gbc); gbc.gridwidth = 1; jTbTools.add(m_jBtSave, gbc); jTbTools.addSeparator(new Dimension(2, 2)); jTbTools.add(jBtZoomIn, gbc); gbc.fill = GridBagConstraints.VERTICAL; gbc.weighty = 1; JPanel p2 = new JPanel(new BorderLayout()); p2.setPreferredSize(jTfZoom.getPreferredSize()); p2.setMinimumSize(jTfZoom.getPreferredSize()); p2.add(jTfZoom, BorderLayout.CENTER); jTbTools.add(p2, gbc); gbc.weighty = 0; gbc.fill = GridBagConstraints.NONE; jTbTools.add(jBtZoomOut, gbc); jTbTools.addSeparator(new Dimension(2, 2)); jTbTools.add(jBtExtraControls, gbc); jTbTools.addSeparator(new Dimension(4, 2)); gbc.weightx = 1; gbc.fill = GridBagConstraints.BOTH; jTbTools.add(m_le.getProgressBar(), gbc); jBtExtraControls.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { Dimension d = p.getPreferredSize(); if (d.width == 0 || d.height == 0) { LayoutManager lm = p.getLayout(); Dimension d2 = lm.preferredLayoutSize(p); p.setPreferredSize(d2); jTbTools.revalidate(); /* * // this piece of code adds in an animation // for popping out the * extra controls panel Thread th = new Thread() { int h = 0, w = 0; * LayoutManager lm = p.getLayout(); Dimension d2 = * lm.preferredLayoutSize(p); * * int tow = (int)d2.getWidth(), toh = (int)d2.getHeight(); //toh = * (int)d2.getHeight(); //tow = (int)d2.getWidth(); * * public void run() { while(h<toh || w<tow) { if((h+10)<toh) h += 10; * else if(h<toh) h = toh; if((w+10)<tow) w += 10; else if(w<tow) w = * tow; p.setPreferredSize(new Dimension(w, h)); //p.invalidate(); * jTbTools.revalidate(); //paint(Temp4.this.getGraphics()); try * {this.sleep(30);} catch(InterruptedException ie) * {ie.printStackTrace(); break;} } p.setPreferredSize(new * Dimension(tow,toh)); jTbTools.revalidate(); } }; th.start(); */ } else { p.setPreferredSize(new Dimension(0, 0)); jTbTools.revalidate(); /* * Thread th = new Thread() { int h = p.getHeight(), w = p.getWidth(); * LayoutManager lm = p.getLayout(); int tow = 0, toh = 0; * * public void run() { while(h>toh || w>tow) { if((h-10)>toh) h -= 10; * else if(h>toh) h = toh; if((w-10)>tow) w -= 10; else if(w>tow) w = * tow; * * p.setPreferredSize(new Dimension(w, h)); //p.invalidate(); * jTbTools.revalidate(); //paint(Temp4.this.getGraphics()); try * {this.sleep(30);} catch(InterruptedException ie) * {ie.printStackTrace(); break;} } p.setPreferredSize(new * Dimension(tow,toh)); jTbTools.revalidate(); } }; th.start(); */ } } }); this.setLayout(new BorderLayout()); this.add(jTbTools, BorderLayout.NORTH); this.add(m_js, BorderLayout.CENTER); } /** * This method sets the node size that is appropriate considering the maximum * label size that is present. It is used internally when custom node size * checkbox is unchecked. */ protected void setAppropriateNodeSize() { int strWidth; if (maxStringWidth == 0) { for (int i = 0; i < m_nodes.size(); i++) { strWidth = fm.stringWidth(m_nodes.get(i).lbl); if (strWidth > maxStringWidth) { maxStringWidth = strWidth; } } } nodeWidth = maxStringWidth + 4; paddedNodeWidth = nodeWidth + 8; jTfNodeWidth.setText("" + nodeWidth); nodeHeight = 2 * fm.getHeight(); jTfNodeHeight.setText("" + nodeHeight); } /** * Sets the preferred size for m_gp GraphPanel to the minimum size that is * neccessary to display the graph. */ protected void setAppropriateSize() { int maxX = 0, maxY = 0; m_gp.setScale(scale, scale); for (int i = 0; i < m_nodes.size(); i++) { GraphNode n = m_nodes.get(i); if (maxX < n.x) { maxX = n.x; } if (maxY < n.y) { maxY = n.y; } } // System.out.println("Scale: "+scale+" paddedWidth: "+paddedNodeWidth+ // " nodeHeight: "+nodeHeight+"\nmaxX: "+maxX+" maxY: "+ // maxY+" final: "+(int)((maxX+paddedNodeWidth+2)*scale)+ // ","+(int)((maxY+nodeHeight+2)*scale) ); m_gp.setPreferredSize(new Dimension( (int) ((maxX + paddedNodeWidth + 2) * scale), (int) ((maxY + nodeHeight + 2) * scale))); // System.out.println("Size set to "+this.getPreferredSize()); } /** * This method is an implementation for LayoutCompleteEventListener class. It * sets the size appropriate for m_gp GraphPanel and and revalidates it's * container JScrollPane once a LayoutCompleteEvent is received from the * LayoutEngine. */ @Override public void layoutCompleted(LayoutCompleteEvent le) { setAppropriateSize(); // m_gp.clearBuffer(); m_gp.invalidate(); m_js.revalidate(); m_gp.repaint(); jBtLayout.setEnabled(true); } /** * This method lays out the graph by calling the LayoutEngine's layoutGraph() * method. This method should be called to display the graph nicely, unless * the input XMLBIF03 already contains some layout information (ie the x,y * positions of nodes. */ public void layoutGraph() { if (m_le != null) { m_le.layoutGraph(); } } /********************************************************* * * BIF reader<br> * Reads a graph description in XMLBIF03 from a string * ********************************************************* */ public void readBIF(String instring) throws BIFFormatException { BIFParser bp = new BIFParser(instring, m_nodes, m_edges); try { graphID = bp.parse(); } catch (BIFFormatException bf) { System.out.println("BIF format error"); bf.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); return; } setAppropriateNodeSize(); if (m_le != null) { m_le.setNodeSize(paddedNodeWidth, nodeHeight); } } // end readBIF1 /** * * BIF reader<br> * Reads a graph description in XMLBIF03 from an InputStrem * * */ public void readBIF(InputStream instream) throws BIFFormatException { BIFParser bp = new BIFParser(instream, m_nodes, m_edges); try { graphID = bp.parse(); } catch (BIFFormatException bf) { System.out.println("BIF format error"); bf.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); return; } setAppropriateNodeSize(); if (m_le != null) { m_le.setNodeSize(paddedNodeWidth, nodeHeight); } setAppropriateSize(); } // end readBIF2 /********************************************************* * * Dot reader<br> * Reads a graph description in DOT format from a string * ********************************************************* */ public void readDOT(Reader input) { DotParser dp = new DotParser(input, m_nodes, m_edges); graphID = dp.parse(); setAppropriateNodeSize(); if (m_le != null) { m_le.setNodeSize(paddedNodeWidth, nodeHeight); jBtLayout.setEnabled(false); layoutGraph(); } } /** * The panel which contains the actual graph. */ private class GraphPanel extends PrintablePanel { /** for serialization */ private static final long serialVersionUID = -3562813603236753173L; public GraphPanel() { super(); this.addMouseListener(new GraphVisualizerMouseListener()); this.addMouseMotionListener(new GraphVisualizerMouseMotionListener()); this.setToolTipText(""); } @Override public String getToolTipText(MouseEvent me) { int x, y, nx, ny; Rectangle r; GraphNode n; Dimension d = m_gp.getPreferredSize(); // System.out.println("Preferred Size: "+this.getPreferredSize()+ // " Actual Size: "+this.getSize()); x = y = nx = ny = 0; if (d.width < m_gp.getWidth()) { nx = (int) ((nx + m_gp.getWidth() / 2 - d.width / 2) / scale); } if (d.height < m_gp.getHeight()) { ny = (int) ((ny + m_gp.getHeight() / 2 - d.height / 2) / scale); } r = new Rectangle(0, 0, (int) (paddedNodeWidth * scale), (int) (nodeHeight * scale)); x += me.getX(); y += me.getY(); int i; for (i = 0; i < m_nodes.size(); i++) { n = m_nodes.get(i); if (n.nodeType != NORMAL) { return null; } r.x = (int) ((nx + n.x) * scale); r.y = (int) ((ny + n.y) * scale); if (r.contains(x, y)) { if (n.probs == null) { return n.lbl; } else { return n.lbl + " (click to view the probability dist. table)"; } } } return null; } @Override public void paintComponent(Graphics gr) { Graphics2D g = (Graphics2D) gr; RenderingHints rh = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); rh.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED); g.setRenderingHints(rh); g.scale(scale, scale); Rectangle r = g.getClipBounds(); g.clearRect(r.x, r.y, r.width, r.height); // g.setColor(this.getBackground()); // g.fillRect(0, 0, width+5, height+5); int x = 0, y = 0; Dimension d = this.getPreferredSize(); // System.out.println("Preferred Size: "+this.getPreferredSize()+ // " Actual Size: "+this.getSize()); // initializing x & y to display the graph in the middle // if the display area is larger than the graph if (d.width < this.getWidth()) { x = (int) ((x + this.getWidth() / 2 - d.width / 2) / scale); } if (d.height < this.getHeight()) { y = (int) ((y + this.getHeight() / 2 - d.height / 2) / scale); } for (int index = 0; index < m_nodes.size(); index++) { GraphNode n = m_nodes.get(index); if (n.nodeType == NORMAL) { g.setColor(this.getBackground().darker().darker()); g.fillOval(x + n.x + paddedNodeWidth - nodeWidth - (paddedNodeWidth - nodeWidth) / 2, y + n.y, nodeWidth, nodeHeight); g.setColor(Color.white); // g.setColor(Color.black); // System.out.println("drawing "+ // ((GraphNode)m_nodes.get(index)).ID+ // " at "+" x: "+ (x+n.x+paddedNodeWidth/2- // fm.stringWidth( ((GraphNode)m_nodes.get(index)).ID )/2)+ // " y: "+(y+n.y+nodeHeight/2+fm.getHeight()/2-2) ); // Draw the node's label if it can fit inside the node's current // width otherwise display its ID or otherwise just display its // idx in the FastVector (to distinguish it from others) // if any can fit in node's current width if (fm.stringWidth(n.lbl) <= nodeWidth) { g.drawString(n.lbl, x + n.x + paddedNodeWidth / 2 - fm.stringWidth(n.lbl) / 2, y + n.y + nodeHeight / 2 + fm.getHeight() / 2 - 2); } else if (fm.stringWidth(n.ID) <= nodeWidth) { g.drawString(n.ID, x + n.x + paddedNodeWidth / 2 - fm.stringWidth(n.ID) / 2, y + n.y + nodeHeight / 2 + fm.getHeight() / 2 - 2); } else if (fm.stringWidth(Integer.toString(index)) <= nodeWidth) { g.drawString(Integer.toString(index), x + n.x + paddedNodeWidth / 2 - fm.stringWidth(Integer.toString(index)) / 2, y + n.y + nodeHeight / 2 + fm.getHeight() / 2 - 2); } g.setColor(Color.black); } else { // g.draw( new java.awt.geom.QuadCurve2D.Double(n.x+paddedNodeWidth/2, // n.y, // n.x+paddedNodeWidth-nodeSize // -(paddedNodeWidth-nodeSize)/2, // n.y+nodeHeight/2, // n.x+paddedNodeWidth/2, n.y+nodeHeight) ); g.drawLine(x + n.x + paddedNodeWidth / 2, y + n.y, x + n.x + paddedNodeWidth / 2, y + n.y + nodeHeight); } GraphNode n2; int x1, y1, x2, y2; // System.out.println("Drawing edges of "+n.lbl); // Drawing all the edges coming out from the node, // including reversed and double ones if (n.edges != null) { for (int[] edge : n.edges) { if (edge[1] > 0) { n2 = m_nodes.get(edge[0]); // m_nodes.get(k); // System.out.println(" -->to "+n2.lbl); x1 = n.x + paddedNodeWidth / 2; y1 = n.y + nodeHeight; x2 = n2.x + paddedNodeWidth / 2; y2 = n2.y; g.drawLine(x + x1, y + y1, x + x2, y + y2); if (edge[1] == DIRECTED) { if (n2.nodeType == GraphConstants.NORMAL) { drawArrow(g, x + x1, y + y1, x + x2, y + y2); } } else if (edge[1] == REVERSED) { if (n.nodeType == NORMAL) { drawArrow(g, x + x2, y + y2, x + x1, y + y1); } } else if (edge[1] == DOUBLE) { if (n.nodeType == NORMAL) { drawArrow(g, x + x2, y + y2, x + x1, y + y1); } if (n2.nodeType == NORMAL) { drawArrow(g, x + x1, y + y1, x + x2, y + y2); } } } } } } } /** * This method draws an arrow on a line from (x1,y1) to (x2,y2). The arrow * head is seated on (x2,y2) and is in the direction of the line. If the * arrow is needed to be drawn in the opposite direction then simply swap * the order of (x1, y1) and (x2, y2) when calling this function. */ protected void drawArrow(Graphics g, int x1, int y1, int x2, int y2) { if (x1 == x2) { if (y1 < y2) { g.drawLine(x2, y2, x2 + 4, y2 - 8); g.drawLine(x2, y2, x2 - 4, y2 - 8); } else { g.drawLine(x2, y2, x2 + 4, y2 + 8); g.drawLine(x2, y2, x2 - 4, y2 + 8); } } else { // theta=line's angle from base, beta=angle of arrow's side from line double hyp = 0, base = 0, perp = 0, theta, beta; int x3 = 0, y3 = 0; if (x2 < x1) { base = x1 - x2; hyp = Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)); theta = Math.acos(base / hyp); } else { // x1>x2 as we already checked x1==x2 before base = x1 - x2; hyp = Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)); theta = Math.acos(base / hyp); } beta = 30 * Math.PI / 180; // System.out.println("Original base "+base+" perp "+perp+" hyp "+hyp+ // "\ntheta "+theta+" beta "+beta); hyp = 8; base = Math.cos(theta - beta) * hyp; perp = Math.sin(theta - beta) * hyp; x3 = (int) (x2 + base); if (y1 < y2) { y3 = (int) (y2 - perp); } else { y3 = (int) (y2 + perp); } // System.out.println("Drawing 1 from "+x2+","+y2+" to "+x3+","+y3+ // " x1,y1 is "+x1+","+y1+" base "+base+ // " perp "+perp+" cos(theta-beta) "+ // Math.cos(theta-beta)); g.drawLine(x2, y2, x3, y3); base = Math.cos(theta + beta) * hyp; perp = Math.sin(theta + beta) * hyp; x3 = (int) (x2 + base); if (y1 < y2) { y3 = (int) (y2 - perp); } else { y3 = (int) (y2 + perp); } // System.out.println("Drawing 2 from "+x2+","+y2+" to "+x3+","+y3+ // " x1,y1 is "+x1+","+y1+" base "+base+ // " perp "+perp); g.drawLine(x2, y2, x3, y3); } } /** * This method highlights a given node and all its children and the edges * coming out of it. */ public void highLight(GraphNode n) { Graphics2D g = (Graphics2D) this.getGraphics(); RenderingHints rh = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); rh.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED); g.setRenderingHints(rh); g.setPaintMode(); g.scale(scale, scale); int x = 0, y = 0; Dimension d = this.getPreferredSize(); // System.out.println("Preferred Size: "+this.getPreferredSize()+ // " Actual Size: "+this.getSize()); // initializing x & y to display the graph in the middle // if the display area is larger than the graph if (d.width < this.getWidth()) { x = (int) ((x + this.getWidth() / 2 - d.width / 2) / scale); } if (d.height < this.getHeight()) { y = (int) ((y + this.getHeight() / 2 - d.height / 2) / scale); } // if the node is of type NORMAL only then highlight if (n.nodeType == NORMAL) { g.setXORMode(Color.green); // g.setColor(Color.green); g.fillOval(x + n.x + paddedNodeWidth - nodeWidth - (paddedNodeWidth - nodeWidth) / 2, y + n.y, nodeWidth, nodeHeight); g.setXORMode(Color.red); // Draw the node's label if it can fit inside the node's current // width otherwise display its ID or otherwise just display its // idx in the FastVector (to distinguish it from others) // if any can fit in node's current width if (fm.stringWidth(n.lbl) <= nodeWidth) { g.drawString(n.lbl, x + n.x + paddedNodeWidth / 2 - fm.stringWidth(n.lbl) / 2, y + n.y + nodeHeight / 2 + fm.getHeight() / 2 - 2); } else if (fm.stringWidth(n.ID) <= nodeWidth) { g.drawString(n.ID, x + n.x + paddedNodeWidth / 2 - fm.stringWidth(n.ID) / 2, y + n.y + nodeHeight / 2 + fm.getHeight() / 2 - 2); } else if (fm.stringWidth(Integer.toString(m_nodes.indexOf(n))) <= nodeWidth) { g.drawString( Integer.toString(m_nodes.indexOf(n)), x + n.x + paddedNodeWidth / 2 - fm.stringWidth(Integer.toString(m_nodes.indexOf(n))) / 2, y + n.y + nodeHeight / 2 + fm.getHeight() / 2 - 2); } g.setXORMode(Color.green); GraphNode n2; int x1, y1, x2, y2; // System.out.println("Drawing edges of "+n.lbl); if (n.edges != null) { // Drawing all the edges from and upward ones coming to the node for (int[] edge2 : n.edges) { if (edge2[1] == DIRECTED || edge2[1] == DOUBLE) { n2 = m_nodes.get(edge2[0]); // m_nodes.get(k); // System.out.println(" -->to "+n2.lbl); x1 = n.x + paddedNodeWidth / 2; y1 = n.y + nodeHeight; x2 = n2.x + paddedNodeWidth / 2; y2 = n2.y; g.drawLine(x + x1, y + y1, x + x2, y + y2); if (edge2[1] == DIRECTED) { if (n2.nodeType == GraphConstants.NORMAL) { drawArrow(g, x + x1, y + y1, x + x2, y + y2); } } else if (edge2[1] == DOUBLE) { if (n.nodeType == NORMAL) { drawArrow(g, x + x2, y + y2, x + x1, y + y1); } if (n2.nodeType == NORMAL) { drawArrow(g, x + x1, y + y1, x + x2, y + y2); } } if (n2.nodeType == NORMAL) { g.fillOval(x + n2.x + paddedNodeWidth - nodeWidth - (paddedNodeWidth - nodeWidth) / 2, y + n2.y, nodeWidth, nodeHeight); } // If n2 is not of NORMAL type // then carry on drawing all the edges and add all the // dummy nodes encountered in a Vector until no // more dummy nodes are found and all the child nodes(node n2) // are of type normal java.util.Vector<GraphNode> t = new java.util.Vector<GraphNode>(); while (n2.nodeType != NORMAL || t.size() > 0) { // n2.dummy==true) // { // System.out.println("in while processing "+n2.ID); if (t.size() > 0) { n2 = t.get(0); t.removeElementAt(0); } if (n2.nodeType != NORMAL) { g.drawLine(x + n2.x + paddedNodeWidth / 2, y + n2.y, x + n2.x + paddedNodeWidth / 2, y + n2.y + nodeHeight); x1 = n2.x + paddedNodeWidth / 2; y1 = n2.y + nodeHeight; // System.out.println("Drawing from "+n2.lbl); for (int[] edge : n2.edges) { // System.out.println(" to "+n2.lbl+", "+ // graphMatrix[tmpIndex][m]); if (edge[1] > 0) { GraphNode n3 = m_nodes.get(edge[0]); // m_nodes.get(m); g.drawLine(x + x1, y + y1, x + n3.x + paddedNodeWidth / 2, y + n3.y); if (n3.nodeType == NORMAL) { // !n2.dummy) g.fillOval(x + n3.x + paddedNodeWidth - nodeWidth - (paddedNodeWidth - nodeWidth) / 2, y + n3.y, nodeWidth, nodeHeight); drawArrow(g, x + x1, y + y1, x + n3.x + paddedNodeWidth / 2, y + n3.y); } // if(n3.nodeType!=n3.NORMAL) t.addElement(n3); // break; } } } } } else if (edge2[1] == -REVERSED || edge2[1] == -DOUBLE) { // Drawing all the reversed and double edges which are going // upwards in the drawing. n2 = m_nodes.get(edge2[0]); // m_nodes.get(k); // System.out.println(" -->to "+n2.lbl); x1 = n.x + paddedNodeWidth / 2; y1 = n.y; x2 = n2.x + paddedNodeWidth / 2; y2 = n2.y + nodeHeight; g.drawLine(x + x1, y + y1, x + x2, y + y2); if (edge2[1] == -DOUBLE) { drawArrow(g, x + x2, y + y2, x + x1, y + y1); if (n2.nodeType != SINGULAR_DUMMY) { drawArrow(g, x + x1, y + y1, x + x2, y + y2); } } while (n2.nodeType != NORMAL) { // n2.dummy==true) { g.drawLine(x + n2.x + paddedNodeWidth / 2, y + n2.y + nodeHeight, x + n2.x + paddedNodeWidth / 2, y + n2.y); x1 = n2.x + paddedNodeWidth / 2; y1 = n2.y; for (int[] edge : n2.edges) { if (edge[1] < 0) { n2 = m_nodes.get(edge[0]); // m_nodes.get(m); g.drawLine(x + x1, y + y1, x + n2.x + paddedNodeWidth / 2, y + n2.y + nodeHeight); if (n2.nodeType != SINGULAR_DUMMY) { drawArrow(g, x + x1, y + y1, x + n2.x + paddedNodeWidth / 2, y + n2.y + nodeHeight); } break; } } } } } } } } } /** * Table Model for the Table that shows the probability distribution for a * node */ private class GraphVisualizerTableModel extends AbstractTableModel { /** for serialization */ private static final long serialVersionUID = -4789813491347366596L; final String[] columnNames; final double[][] data; public GraphVisualizerTableModel(double[][] d, String[] c) { data = d; columnNames = c; } @Override public int getColumnCount() { return columnNames.length; } @Override public int getRowCount() { return data.length; } @Override public String getColumnName(int col) { return columnNames[col]; } @Override public Object getValueAt(int row, int col) { return new Double(data[row][col]); } /* * JTable uses this method to determine the default renderer/ editor for * each cell. */ @Override public Class<?> getColumnClass(int c) { return getValueAt(0, c).getClass(); } /* * Implemented this to make sure the table is uneditable. */ @Override public boolean isCellEditable(int row, int col) { return false; } } /** * Listener class for processing mouseClicked */ private class GraphVisualizerMouseListener extends MouseAdapter { int x, y, nx, ny; Rectangle r; /** * If the mouse is clicked on a node then this method displays a dialog box * with the probability distribution table for that node IF it exists */ @Override public void mouseClicked(MouseEvent me) { GraphNode n; Dimension d = m_gp.getPreferredSize(); // System.out.println("Preferred Size: "+this.getPreferredSize()+ // " Actual Size: "+this.getSize()); x = y = nx = ny = 0; if (d.width < m_gp.getWidth()) { nx = (int) ((nx + m_gp.getWidth() / 2 - d.width / 2) / scale); } if (d.height < m_gp.getHeight()) { ny = (int) ((ny + m_gp.getHeight() / 2 - d.height / 2) / scale); } r = new Rectangle(0, 0, (int) (paddedNodeWidth * scale), (int) (nodeHeight * scale)); x += me.getX(); y += me.getY(); int i; for (i = 0; i < m_nodes.size(); i++) { n = m_nodes.get(i); r.x = (int) ((nx + n.x) * scale); r.y = (int) ((ny + n.y) * scale); if (r.contains(x, y)) { if (n.probs == null) { return; } int noOfPrntsOutcomes = 1; if (n.prnts != null) { for (int prnt : n.prnts) { GraphNode n2 = m_nodes.get(prnt); noOfPrntsOutcomes *= n2.outcomes.length; } if (noOfPrntsOutcomes > 511) { System.err.println("Too many outcomes of parents (" + noOfPrntsOutcomes + ") can't display probabilities"); return; } } GraphVisualizerTableModel tm = new GraphVisualizerTableModel(n.probs, n.outcomes); JTable jTblProbs = new JTable(tm); // JTable(probabilities, // (Object[])n.outcomes); JScrollPane js = new JScrollPane(jTblProbs); if (n.prnts != null) { GridBagConstraints gbc = new GridBagConstraints(); JPanel jPlRowHeader = new JPanel(new GridBagLayout()); // indices of the parent nodes in the Vector int[] idx = new int[n.prnts.length]; // max length of values of each parent int[] lengths = new int[n.prnts.length]; // System.out.println("n.probs.length "+n.probs.length+ // " should be "+noOfPrntsOutcomes); // System.out.println("n.probs[0].length "+n.probs[0].length+ // " should be "+n.outcomes.length); // System.out.println("probabilities are: "); // for(int j=0; j<probabilities.length; j++) { // for(int k=0; k<probabilities[j].length; k++) // System.out.print(probabilities[j][k]+" "); // System.out.println(""); // } // Adding labels for rows gbc.anchor = GridBagConstraints.NORTHWEST; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.insets = new Insets(0, 1, 0, 0); int addNum = 0, temp = 0; boolean dark = false; while (true) { GraphNode n2; gbc.gridwidth = 1; for (int k = 0; k < n.prnts.length; k++) { n2 = m_nodes.get(n.prnts[k]); JLabel lb = new JLabel(n2.outcomes[idx[k]]); lb.setFont(new Font("Dialog", Font.PLAIN, 12)); lb.setOpaque(true); lb.setBorder(BorderFactory.createEmptyBorder(1, 2, 1, 1)); lb.setHorizontalAlignment(JLabel.CENTER); if (dark) { lb.setBackground(lb.getBackground().darker()); lb.setForeground(Color.white); } else { lb.setForeground(Color.black); } temp = lb.getPreferredSize().width; // System.out.println("Preferred width "+temp+ // " for "+n2.outcomes[idx[k]]); lb.setPreferredSize(new Dimension(temp, jTblProbs .getRowHeight())); if (lengths[k] < temp) { lengths[k] = temp; } temp = 0; if (k == n.prnts.length - 1) { gbc.gridwidth = GridBagConstraints.REMAINDER; dark = (dark == true) ? false : true; } jPlRowHeader.add(lb, gbc); addNum++; } for (int k = n.prnts.length - 1; k >= 0; k--) { n2 = m_nodes.get(n.prnts[k]); if (idx[k] == n2.outcomes.length - 1 && k != 0) { idx[k] = 0; continue; } else { idx[k]++; break; } } n2 = m_nodes.get(n.prnts[0]); if (idx[0] == n2.outcomes.length) { JLabel lb = (JLabel) jPlRowHeader.getComponent(addNum - 1); jPlRowHeader.remove(addNum - 1); lb.setPreferredSize(new Dimension(lb.getPreferredSize().width, jTblProbs.getRowHeight())); gbc.gridwidth = GridBagConstraints.REMAINDER; gbc.weighty = 1; jPlRowHeader.add(lb, gbc); gbc.weighty = 0; break; } } gbc.gridwidth = 1; // The following panel contains the names of the parents // and is displayed above the row names to identify // which value belongs to which parent JPanel jPlRowNames = new JPanel(new GridBagLayout()); for (int j = 0; j < n.prnts.length; j++) { JLabel lb2; JLabel lb1 = new JLabel(m_nodes.get(n.prnts[j]).lbl); lb1.setBorder(BorderFactory.createEmptyBorder(1, 2, 1, 1)); Dimension tempd = lb1.getPreferredSize(); // System.out.println("lengths[j]: "+lengths[j]+ // " tempd.width: "+tempd.width); if (tempd.width < lengths[j]) { lb1.setPreferredSize(new Dimension(lengths[j], tempd.height)); lb1.setHorizontalAlignment(JLabel.CENTER); lb1.setMinimumSize(new Dimension(lengths[j], tempd.height)); } else if (tempd.width > lengths[j]) { lb2 = (JLabel) jPlRowHeader.getComponent(j); lb2.setPreferredSize(new Dimension(tempd.width, lb2 .getPreferredSize().height)); } jPlRowNames.add(lb1, gbc); // System.out.println("After adding "+lb1.getPreferredSize()); } js.setRowHeaderView(jPlRowHeader); js.setCorner(JScrollPane.UPPER_LEFT_CORNER, jPlRowNames); } JDialog jd = new JDialog( (Frame) GraphVisualizer.this.getTopLevelAncestor(), "Probability Distribution Table For " + n.lbl, ModalityType.DOCUMENT_MODAL); /*jd.setLocation( GraphVisualizer.this.getLocation().x + GraphVisualizer.this.getWidth() / 2 - 250, GraphVisualizer.this.getLocation().y + GraphVisualizer.this.getHeight() / 2 - 200);*/ jd.getContentPane().setLayout(new BorderLayout()); jd.getContentPane().add(js, BorderLayout.CENTER); jd.pack(); jd.setSize(450, 350); jd.setLocationRelativeTo(SwingUtilities.getWindowAncestor(GraphVisualizer.this)); jd.setVisible(true); return; } } } } /** * private class for handling mouseMoved events to highlight nodes if the the * mouse is moved on one */ private class GraphVisualizerMouseMotionListener extends MouseMotionAdapter { int x, y, nx, ny; Rectangle r; GraphNode lastNode; @Override public void mouseMoved(MouseEvent me) { GraphNode n; Dimension d = m_gp.getPreferredSize(); // System.out.println("Preferred Size: "+this.getPreferredSize()+ // " Actual Size: "+this.getSize()); x = y = nx = ny = 0; if (d.width < m_gp.getWidth()) { nx = (int) ((nx + m_gp.getWidth() / 2 - d.width / 2) / scale); } if (d.height < m_gp.getHeight()) { ny = (int) ((ny + m_gp.getHeight() / 2 - d.height / 2) / scale); } r = new Rectangle(0, 0, (int) (paddedNodeWidth * scale), (int) (nodeHeight * scale)); x += me.getX(); y += me.getY(); int i; for (i = 0; i < m_nodes.size(); i++) { n = m_nodes.get(i); r.x = (int) ((nx + n.x) * scale); r.y = (int) ((ny + n.y) * scale); if (r.contains(x, y)) { if (n != lastNode) { m_gp.highLight(n); if (lastNode != null) { m_gp.highLight(lastNode); } lastNode = n; // lastIndex = i; } break; } } if (i == m_nodes.size() && lastNode != null) { m_gp.repaint(); // m_gp.highLight(lastNode); lastNode = null; } } } /** * Main method to load a text file with the description of a graph from the * command line */ public static void main(String[] args) { weka.core.logging.Logger.log(weka.core.logging.Logger.Level.INFO, "Logging started"); JFrame jf = new JFrame("Graph Visualizer"); GraphVisualizer g = new GraphVisualizer(); try { if (args[0].endsWith(".xml")) { // StringBuffer sb = new StringBuffer(); // FileReader infile = new FileReader(args[0]); // int i; // while( (i=infile.read())!=-1) { // sb.append((char)i); // } // System.out.println(sb.toString()); // g.readBIF(sb.toString() ); g.readBIF(new FileInputStream(args[0])); } else { // BufferedReader infile=new BufferedReader(); g.readDOT(new FileReader(args[0])); // infile); } } catch (IOException ex) { ex.printStackTrace(); } catch (BIFFormatException bf) { bf.printStackTrace(); System.exit(-1); } jf.getContentPane().add(g); // RepaintManager.currentManager(jf.getRootPane()).setDoubleBufferingEnabled(false); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jf.setSize(800, 600); // jf.pack(); jf.setVisible(true); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/graphvisualizer/HierarchicalBCEngine.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * HierarchicalBCEngine.java * Copyright (C) 2003-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.graphvisualizer; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import javax.swing.BorderFactory; import javax.swing.ButtonGroup; import javax.swing.JCheckBox; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.JRadioButton; /** * This class lays out the vertices of a graph in a hierarchy of vertical * levels, with a number of nodes in each level. The number of levels is the * depth of the deepest child reachable from some parent at level 0. It * implements a layout technique as described by K. Sugiyama, S. Tagawa, and M. * Toda. in "Methods for visual understanding of hierarchical systems", IEEE * Transactions on Systems, Man and Cybernetics, SMC-11(2):109-125, Feb. 1981. * <p> * There have been a few modifications made, however. The crossings function is * changed as it was non-linear in time complexity. Furthermore, we don't have * any interconnection matrices for each level, instead we just have one big * interconnection matrix for the whole graph and a int[][] array which stores * the vertices present in each level. * * @author Ashraf M. Kibriya (amk14@cs.waikato.ac.nz) * @version $Revision$ - 24 Apr 2003 - Initial version (Ashraf M. * Kibriya) * */ public class HierarchicalBCEngine implements GraphConstants, LayoutEngine { /** FastVector containing nodes and edges */ protected ArrayList<GraphNode> m_nodes; protected ArrayList<GraphEdge> m_edges; /** * FastVector containing listeners for layoutCompleteEvent generated by this * LayoutEngine */ protected ArrayList<LayoutCompleteEventListener> layoutCompleteListeners; /** Interconnection matrix for the graph */ protected int graphMatrix[][]; /** * Array containing the indices of nodes in each level. The nodeLevels.length * is equal to the number of levels */ protected int nodeLevels[][]; /** The nodeWidth and nodeHeight */ protected int m_nodeWidth, m_nodeHeight; /* * The following radio buttons control the way the layout is performed. If any * of the following is changed then we need to perform a complete relayout */ protected JRadioButton m_jRbNaiveLayout; protected JRadioButton m_jRbPriorityLayout; protected JRadioButton m_jRbTopdown; protected JRadioButton m_jRbBottomup; /** * controls edge concentration by concentrating multilple singular dummy child * nodes into one plural dummy child node */ protected JCheckBox m_jCbEdgeConcentration; /** * The panel containing extra options, specific to this LayoutEngine, for * greater control over layout of the graph */ protected JPanel m_controlsPanel; /** * The progress bar to show the progress of the layout process */ protected JProgressBar m_progress; /** * This tells the the LayoutGraph method if a completeReLayout should be * performed when it is called. */ protected boolean m_completeReLayout = false; /** * This contains the original size of the nodes vector when it was passed in * through the constructor, before adding all the dummy vertices */ private int origNodesSize; /** * Constructor - takes in FastVectors of nodes and edges, and the initial * width and height of a node */ public HierarchicalBCEngine(ArrayList<GraphNode> nodes, ArrayList<GraphEdge> edges, int nodeWidth, int nodeHeight) { m_nodes = nodes; m_edges = edges; m_nodeWidth = nodeWidth; m_nodeHeight = nodeHeight; makeGUIPanel(false); } /** * Constructor - takes in FastVectors of nodes and edges, the initial width * and height of a node, and a boolean value to indicate if the edges should * be concentrated. * * @param nodes - FastVector containing all the nodes * @param edges - FastVector containing all the edges * @param nodeWidth - A node's allowed width * @param nodeHeight - A node's allowed height * @param edgeConcentration - True: if want to concentrate edges, False: * otherwise */ public HierarchicalBCEngine(ArrayList<GraphNode> nodes, ArrayList<GraphEdge> edges, int nodeWidth, int nodeHeight, boolean edgeConcentration) { m_nodes = nodes; m_edges = edges; m_nodeWidth = nodeWidth; m_nodeHeight = nodeHeight; makeGUIPanel(edgeConcentration); } /** * SimpleConstructor If we want to instantiate the class first, and if * information for nodes and edges is not available. However, we would have to * manually provide all the information later on by calling setNodesEdges and * setNodeSize methods */ public HierarchicalBCEngine() { } /** * This methods makes the gui extra controls panel "m_controlsPanel" */ protected void makeGUIPanel(boolean edgeConc) { m_jRbNaiveLayout = new JRadioButton("Naive Layout"); m_jRbPriorityLayout = new JRadioButton("Priority Layout"); ButtonGroup bg = new ButtonGroup(); bg.add(m_jRbNaiveLayout); bg.add(m_jRbPriorityLayout); m_jRbPriorityLayout.setSelected(true); ActionListener a = new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { m_completeReLayout = true; } }; m_jRbTopdown = new JRadioButton("Top Down"); m_jRbBottomup = new JRadioButton("Bottom Up"); m_jRbTopdown.addActionListener(a); m_jRbBottomup.addActionListener(a); bg = new ButtonGroup(); bg.add(m_jRbTopdown); bg.add(m_jRbBottomup); m_jRbBottomup.setSelected(true); m_jCbEdgeConcentration = new JCheckBox("With Edge Concentration", edgeConc); m_jCbEdgeConcentration.setSelected(edgeConc); m_jCbEdgeConcentration.addActionListener(a); JPanel jp1 = new JPanel(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.gridwidth = GridBagConstraints.REMAINDER; gbc.anchor = GridBagConstraints.NORTHWEST; gbc.weightx = 1; gbc.fill = GridBagConstraints.HORIZONTAL; jp1.add(m_jRbNaiveLayout, gbc); jp1.add(m_jRbPriorityLayout, gbc); jp1.setBorder(BorderFactory.createTitledBorder("Layout Type")); JPanel jp2 = new JPanel(new GridBagLayout()); jp2.add(m_jRbTopdown, gbc); jp2.add(m_jRbBottomup, gbc); jp2.setBorder(BorderFactory.createTitledBorder("Layout Method")); m_progress = new JProgressBar(0, 11); m_progress.setBorderPainted(false); m_progress.setStringPainted(true); m_progress.setString(""); m_progress.setValue(0); m_controlsPanel = new JPanel(new GridBagLayout()); m_controlsPanel.add(jp1, gbc); m_controlsPanel.add(jp2, gbc); m_controlsPanel.add(m_jCbEdgeConcentration, gbc); } /** give access to set of graph nodes */ @Override public ArrayList<GraphNode> getNodes() { return m_nodes; } /** * This method returns a handle to the extra controls panel, so that the * visualizing class can add it to some of it's own gui panel. */ @Override public JPanel getControlPanel() { return m_controlsPanel; } /** * Returns a handle to the progressBar of this LayoutEngine. */ @Override public JProgressBar getProgressBar() { return m_progress; } /** * Sets the nodes and edges for this LayoutEngine. Must be used if the class * created by simple HierarchicalBCEngine() constructor. * * @param nodes - FastVector containing all the nodes * @param edges - FastVector containing all the edges */ @Override public void setNodesEdges(ArrayList<GraphNode> nodes, ArrayList<GraphEdge> edges) { m_nodes = nodes; m_edges = edges; } /** * Sets the size of a node. This method must be used if the class created by * simple HierarchicalBCEngine() constructor. * * @param nodeWidth - A node's allowed width * @param nodeHeight - A node's allowed height */ @Override public void setNodeSize(int nodeWidth, int nodeHeight) { m_nodeWidth = nodeWidth; m_nodeHeight = nodeHeight; } /** * Method to add a LayoutCompleteEventListener * * @param l - Listener to receive the LayoutCompleteEvent by this class. */ @Override public void addLayoutCompleteEventListener(LayoutCompleteEventListener l) { if (layoutCompleteListeners == null) { layoutCompleteListeners = new ArrayList<LayoutCompleteEventListener>(); } layoutCompleteListeners.add(l); } /** * Method to remove a LayoutCompleteEventListener. * * @param e - The LayoutCompleteEventListener to remove. */ @Override public void removeLayoutCompleteEventListener(LayoutCompleteEventListener e) { if (layoutCompleteListeners != null) { LayoutCompleteEventListener l; for (int i = 0; i < layoutCompleteListeners.size(); i++) { l = layoutCompleteListeners.get(i); if (l == e) { layoutCompleteListeners.remove(i); return; } } System.err.println("layoutCompleteListener to be remove not present"); } else { System.err.println("layoutCompleteListener to be remove not present"); } } /** * Fires a LayoutCompleteEvent. * * @param e - The LayoutCompleteEvent to fire */ @Override public void fireLayoutCompleteEvent(LayoutCompleteEvent e) { if (layoutCompleteListeners != null && layoutCompleteListeners.size() != 0) { LayoutCompleteEventListener l; for (int i = 0; i < layoutCompleteListeners.size(); i++) { l = layoutCompleteListeners.get(i); l.layoutCompleted(e); } } } /** * This method does a complete layout of the graph which includes removing * cycles, assigning levels to nodes, reducing edge crossings and laying out * the vertices horizontally for better visibility. The removing of cycles and * assignment of levels is only performed if hasn't been performed earlier or * if some layout option has been changed and it is necessary to do so. It is * necessary to do so, if the user selects/deselects edge concentration or * topdown/bottomup options. * <p> * The layout is performed in a separate thread and the progress bar of the * class is updated for each of the steps as the process continues. */ @Override public void layoutGraph() { // cannot perform a layout if no description of nodes and/or edges is // provided if (m_nodes == null || m_edges == null) { return; } Thread th = new Thread() { @Override public void run() { m_progress.setBorderPainted(true); if (nodeLevels == null) { makeProperHierarchy(); } else if (m_completeReLayout == true) { clearTemps_and_EdgesFromNodes(); makeProperHierarchy(); m_completeReLayout = false; } // minimizing crossings if (m_jRbTopdown.isSelected()) { int crossbefore = crossings(nodeLevels), crossafter = 0, i = 0; do { m_progress.setValue(i + 4); m_progress.setString("Minimizing Crossings: Pass" + (i + 1)); if (i != 0) { crossbefore = crossafter; } nodeLevels = minimizeCrossings(false, nodeLevels); crossafter = crossings(nodeLevels); i++; } while (crossafter < crossbefore && i < 6); } else { int crossbefore = crossings(nodeLevels), crossafter = 0, i = 0; do { m_progress.setValue(i + 4); m_progress.setString("Minimizing Crossings: Pass" + (i + 1)); if (i != 0) { crossbefore = crossafter; } nodeLevels = minimizeCrossings(true, nodeLevels); crossafter = crossings(nodeLevels); i++; } while (crossafter < crossbefore && i < 6); } // System.out.println("\nCrossings at the end "+ // crossings(nodeLevels)+ // "\n---------------------------------"); m_progress.setValue(10); m_progress.setString("Laying out vertices"); // Laying out graph if (m_jRbNaiveLayout.isSelected()) { naiveLayout(); } else { priorityLayout1(); } m_progress.setValue(11); m_progress.setString("Layout Complete"); m_progress.repaint(); fireLayoutCompleteEvent(new LayoutCompleteEvent(this)); m_progress.setValue(0); m_progress.setString(""); m_progress.setBorderPainted(false); } }; th.start(); } /** * This method removes the temporary nodes that were added to fill in the * gaps, and removes all edges from all nodes in their edges[][] array */ protected void clearTemps_and_EdgesFromNodes() { /* * System.out.println("Before............."); for(int i=0; i<m_nodes.size(); * i++) { GraphNode n = (GraphNode)m_nodes.get(i); * System.out.println("N: "+n.ID+","+i); } * System.out.println("origNodesSize: "+origNodesSize); */ int curSize = m_nodes.size(); for (int i = origNodesSize; i < curSize; i++) { m_nodes.remove(origNodesSize); } for (int j = 0; j < m_nodes.size(); j++) { m_nodes.get(j).edges = null; } nodeLevels = null; /* * System.out.println("After.............."); for(int i=0; i<m_nodes.size(); * i++) { GraphNode n = (GraphNode)m_nodes.get(i); * System.out.println("N: "+n.ID+","+i); } */ } /** * This method makes the "graphMatrix" interconnection matrix for the graph * given by m_nodes and m_edges vectors. The matix is used by other methods. */ protected void processGraph() { origNodesSize = m_nodes.size(); graphMatrix = new int[m_nodes.size()][m_nodes.size()]; /* * System.out.println("The "+m_nodes.size()+" nodes are: "); for(int i=0; * i<m_nodes.size(); i++) System.out.println((String)m_nodes.get(i)+" "); * System.out.println("\nThe "+m_edges.size()+" edges are: "); for(int i=0; * i<m_edges.size(); i++) System.out.println((GraphEdge)m_edges.get(i)); */ for (int i = 0; i < m_edges.size(); i++) { graphMatrix[m_edges.get(i).src][m_edges.get(i).dest] = m_edges.get(i).type; /* * System.out.print("\t"); for(int i=0; i<graphMatrix.length; i++) * System.out.print(((GraphNode)m_nodes.get(i)).ID+" "); * System.out.println(""); for(int i=0; i<graphMatrix.length; i++) { * GraphNode n = (GraphNode)m_nodes.get(i); System.out.print(n.ID+"\t"); * for(int j=0; j<graphMatrix[i].length; j++) * System.out.print(graphMatrix[i][j]+" "); System.out.println(""); } */ } } /* * This method makes a proper hierarchy of the graph by first removing cycles, * then assigning levels to the nodes and then removing gaps by adding dummy * vertices. */ protected void makeProperHierarchy() { processGraph(); m_progress.setValue(1); m_progress.setString("Removing Cycles"); // ****removing cycles removeCycles(); m_progress.setValue(2); m_progress.setString("Assigning levels to nodes"); // ****Assigning vertical level to each node int nodesLevel[] = new int[m_nodes.size()]; int depth = 0; for (int i = 0; i < graphMatrix.length; i++) { assignLevels(nodesLevel, depth, i, 0); } for (int i = 0; i < nodesLevel.length; i++) { if (nodesLevel[i] == 0) { int min = 65536; for (int j = 0; j < graphMatrix[i].length; j++) { if (graphMatrix[i][j] == DIRECTED) { if (min > nodesLevel[j]) { min = nodesLevel[j]; } } } // if the shallowest child of a parent has a depth greater than 1 // and it is not a lone parent with no children if (min != 65536 && min > 1) { nodesLevel[i] = min - 1; } } } // System.out.println(""); int maxLevel = 0; for (int element : nodesLevel) { if (element > maxLevel) { maxLevel = element; // System.out.println( ((GraphNode)m_nodes.get(i)).ID+" "+i+">"+ // nodesLevel[i]); } } int levelCounts[] = new int[maxLevel + 1]; for (int i = 0; i < nodesLevel.length; i++) { levelCounts[nodesLevel[i]]++; } // System.out.println("------------------------------------------"); // ****Assigning nodes to each level int levelsCounter[] = new int[maxLevel + 1]; nodeLevels = new int[maxLevel + 1][]; for (int i = 0; i < nodesLevel.length; i++) { if (nodeLevels[nodesLevel[i]] == null) { nodeLevels[nodesLevel[i]] = new int[levelCounts[nodesLevel[i]]]; } // nodeLevels[nodesLevel[i]].addElement(new Integer(i)); // System.out.println(((GraphNode)m_nodes.get(i)).ID+" "+ // nodesLevel[i]+">"+levelCounts[nodesLevel[i]]); nodeLevels[nodesLevel[i]][levelsCounter[nodesLevel[i]]++] = i; } m_progress.setValue(3); m_progress.setString("Removing gaps by adding dummy vertices"); // *Making a proper Hierarchy by putting in dummy vertices to close all gaps if (m_jCbEdgeConcentration.isSelected()) { removeGapsWithEdgeConcentration(nodesLevel); } else { removeGaps(nodesLevel); } // After assigning levels and adding dummy vertices // System.out.print("\n\t"); // for(int i=0; i<graphMatrix.length; i++) // System.out.print(((GraphNode)m_nodes.get(i)).ID+" "); // System.out.println(""); // for(int i=0; i<graphMatrix.length; i++) { // System.out.print(((GraphNode)m_nodes.get(i)).ID+"\t"); // for(int j=0; j<graphMatrix[i].length; j++) // System.out.print(graphMatrix[i][j]+" "); // System.out.println(""); // } // ****Updating edges[][] array of nodes from // ****the interconnection matrix, which will be used // ****by the Visualizer class to draw edges for (int i = 0; i < graphMatrix.length; i++) { GraphNode n = m_nodes.get(i); int sum = 0; for (int j = 0; j < graphMatrix[i].length; j++) { if (graphMatrix[i][j] != 0) { sum++; } } n.edges = new int[sum][2]; for (int j = 0, k = 0; j < graphMatrix[i].length; j++) { if (graphMatrix[i][j] != 0) { n.edges[k][0] = j; n.edges[k][1] = graphMatrix[i][j]; k++; } // n.edges = graphMatrix[i]; } } // Interconnection matrices at each level, 1 to n-1 // printMatrices(nodeLevels); } /** * This method removes gaps from the graph. It doesn't perform any * concentration. It takes as an argument of int[] of length m_nodes.size() * containing the level of each node. */ private void removeGaps(int nodesLevel[]) { int temp = m_nodes.size(); int temp2 = graphMatrix[0].length, tempCnt = 1; for (int n = 0; n < temp; n++) { for (int i = 0; i < temp2; i++) { int len = graphMatrix.length; if (graphMatrix[n][i] > 0) { if (nodesLevel[i] > nodesLevel[n] + 1) { int tempMatrix[][] = new int[graphMatrix.length + (nodesLevel[i] - nodesLevel[n] - 1)][graphMatrix.length + (nodesLevel[i] - nodesLevel[n] - 1)]; int level = nodesLevel[n] + 1; copyMatrix(graphMatrix, tempMatrix); String s1 = new String("S" + tempCnt++); m_nodes.add(new GraphNode(s1, s1, SINGULAR_DUMMY)); // true)); int temp3[] = new int[nodeLevels[level].length + 1]; // for(int j=0; j<nodeLevels[level].length; j++) // temp3[j] = nodeLevels[level][j]; System.arraycopy(nodeLevels[level], 0, temp3, 0, nodeLevels[level].length); temp3[temp3.length - 1] = m_nodes.size() - 1; nodeLevels[level] = temp3; level++; // nodeLevels[level++].addElement(new Integer(m_nodes.size()-1)); // System.out.println("len:"+len+","+nodesLevel[i]+","+ // nodesLevel[n]); int k; for (k = len; k < len + nodesLevel[i] - nodesLevel[n] - 1 - 1; k++) { String s2 = new String("S" + tempCnt); m_nodes.add(new GraphNode(s2, s2, SINGULAR_DUMMY)); // true) // ); temp3 = new int[nodeLevels[level].length + 1]; // for(int j=0; j<nodeLevels[level].length; j++) // temp3[j] = nodeLevels[level][j]; System.arraycopy(nodeLevels[level], 0, temp3, 0, nodeLevels[level].length); temp3[temp3.length - 1] = m_nodes.size() - 1; nodeLevels[level++] = temp3; // nodeLevels[level++].addElement(new Integer(m_nodes.size()-1)); tempMatrix[k][k + 1] = tempMatrix[n][i]; tempCnt++; if (k > len) { tempMatrix[k][k - 1] = -1 * tempMatrix[n][i]; } } // temp[lastTempNodeCreated][targetNode]=temp[origNode][targetNode] tempMatrix[k][i] = tempMatrix[n][i]; // System.out.println("k "+((GraphNode)m_nodes.get(k)).ID+ // " i "+((GraphNode)m_nodes.get(i)).ID+ // " n "+((GraphNode)m_nodes.get(n)).ID+ // " len "+((GraphNode)m_nodes.get(len)).ID ); // temp[origNode][firstTempNodecreated] = temp[origNode][targetNode] tempMatrix[n][len] = tempMatrix[n][i]; // temp[firstTempNodeCreated][origNode] for reverse tracing tempMatrix[len][n] = -1 * tempMatrix[n][i]; // temp[targetNode][lastTempNodecreated] for reverse tracing tempMatrix[i][k] = -1 * tempMatrix[n][i]; // temp[lastTempNodeCreated][secondlastNode] for reverse tracing // but only do this if more than 1 temp nodes are created if (k > len) { tempMatrix[k][k - 1] = -1 * tempMatrix[n][i]; } // temp[origNode][targetNode] = 0 unlinking as they have been // linked by a chain of temporary nodes now. tempMatrix[n][i] = 0; tempMatrix[i][n] = 0; graphMatrix = tempMatrix; } else { // ****Even if there is no gap just add a reference for the // ****parent to the child for reverse tracing, useful if the // ****there is a reversed edge from parent to child and therefore // ****visualizer would know to highlight this edge when // ****highlighting the child. graphMatrix[i][n] = -1 * graphMatrix[n][i]; } } } } // Interconnection matrices at each level, 1 to n-1 after minimizing edges // printMatrices(nodeLevels); } /** * This method removes gaps from the graph. It tries to minimise the number of * edges by concentrating multiple dummy nodes from the same parent and on the * same vertical level into one. It takes as an argument of int[] of length * m_nodes.size() containing the level of each node. */ private void removeGapsWithEdgeConcentration(int nodesLevel[]) { final int temp = m_nodes.size(), temp2 = graphMatrix[0].length; int tempCnt = 1; for (int n = 0; n < temp; n++) { for (int i = 0; i < temp2; i++) { if (graphMatrix[n][i] > 0) { if (nodesLevel[i] > nodesLevel[n] + 1) { // System.out.println("Processing node "+ // ((GraphNode)m_nodes.get(n)).ID+ // " for "+((GraphNode)m_nodes.get(i)).ID); int tempLevel = nodesLevel[n]; boolean tempNodePresent = false; int k = temp; int tempnode = n; while (tempLevel < nodesLevel[i] - 1) { tempNodePresent = false; for (; k < graphMatrix.length; k++) { if (graphMatrix[tempnode][k] > 0) { // System.out.println("tempnode will be true"); tempNodePresent = true; break; } } if (tempNodePresent) { tempnode = k; k = k + 1; tempLevel++; } else { if (tempnode != n) { tempnode = k - 1; } // System.out.println("breaking from loop"); break; } } if (m_nodes.get(tempnode).nodeType == SINGULAR_DUMMY) { m_nodes.get(tempnode).nodeType = PLURAL_DUMMY; } if (tempNodePresent) { // Link the last known temp node to target graphMatrix[tempnode][i] = graphMatrix[n][i]; // System.out.println("modifying "+ // ((GraphNode)nodes.get(tempnode)).ID+ // ", "+((GraphNode)nodes.get(n)).ID); // ///matrix[lastknowntempnode][source]=-original_val // ///graphMatrix[tempnode][n] = -graphMatrix[n][i]; // System.out.println("modifying "+ // ((GraphNode)nodes.get(i)).ID+ // ", "+ // ((GraphNode)nodes.get(tempnode)).ID); // and matrix[target][lastknowntempnode]=-original_val // for reverse tracing graphMatrix[i][tempnode] = -graphMatrix[n][i]; // unlink source from the target graphMatrix[n][i] = 0; graphMatrix[i][n] = 0; continue; } int len = graphMatrix.length; int tempMatrix[][] = new int[graphMatrix.length + (nodesLevel[i] - nodesLevel[tempnode] - 1)][graphMatrix.length + (nodesLevel[i] - nodesLevel[tempnode] - 1)]; int level = nodesLevel[tempnode] + 1; copyMatrix(graphMatrix, tempMatrix); String s1 = new String("S" + tempCnt++); // System.out.println("Adding dummy "+s1); m_nodes.add(new GraphNode(s1, s1, SINGULAR_DUMMY)); int temp3[] = new int[nodeLevels[level].length + 1]; System.arraycopy(nodeLevels[level], 0, temp3, 0, nodeLevels[level].length); temp3[temp3.length - 1] = m_nodes.size() - 1; nodeLevels[level] = temp3; temp3 = new int[m_nodes.size() + 1]; System.arraycopy(nodesLevel, 0, temp3, 0, nodesLevel.length); temp3[m_nodes.size() - 1] = level; nodesLevel = temp3; level++; // nodeLevels[level++].addElement(new Integer(m_nodes.size()-1)); // System.out.println("len:"+len+"("+ // ((GraphNode)m_nodes.get(len)).ID+"),"+ // nodesLevel[i]+","+nodesLevel[tempnode]); int m; for (m = len; m < len + nodesLevel[i] - nodesLevel[tempnode] - 1 - 1; m++) { String s2 = new String("S" + tempCnt++); // System.out.println("Adding dummy "+s2); m_nodes.add(new GraphNode(s2, s2, SINGULAR_DUMMY)); temp3 = new int[nodeLevels[level].length + 1]; // for(int j=0; j<nodeLevels[level].length; j++) // temp3[j] = nodeLevels[level][j]; System.arraycopy(nodeLevels[level], 0, temp3, 0, nodeLevels[level].length); temp3[temp3.length - 1] = m_nodes.size() - 1; nodeLevels[level] = temp3; temp3 = new int[m_nodes.size() + 1]; System.arraycopy(nodesLevel, 0, temp3, 0, nodesLevel.length); temp3[m_nodes.size() - 1] = level; nodesLevel = temp3; level++; // nodeLevels[level++].addElement(new Integer(m_nodes.size()-1)); // System.out.println("modifying "+ // ((GraphNode)nodes.get(m)).ID+", "+ // ((GraphNode)nodes.get(m+1)).ID); tempMatrix[m][m + 1] = tempMatrix[n][i]; // tempCnt++; if (m > len) { // System.out.println("modifying "+ // ((GraphNode)nodes.get(m)).ID+ // ", "+((GraphNode)nodes.get(m-1)).ID); tempMatrix[m][m - 1] = -1 * tempMatrix[n][i]; } } // System.out.println("m "+((GraphNode)m_nodes.get(m)).ID+ // " i "+((GraphNode)m_nodes.get(i)).ID+ // " tempnode "+((GraphNode)m_nodes.get(tempnode)).ID+ // " len "+((GraphNode)m_nodes.get(len)).ID ); // System.out.println("modifying "+ // ((GraphNode)nodes.get(m)).ID+", "+ // ((GraphNode)nodes.get(i)).ID); // temp[lastTempNodeCreated][targetNode]=temp[origNode][targetNode] tempMatrix[m][i] = tempMatrix[n][i]; // System.out.println("modifying "+ // ((GraphNode)nodes.get(tempnode)).ID+", "+ // ((GraphNode)nodes.get(len)).ID); // temp[origNode][firstTempNodecreated] = temp[origNode][targetNode] tempMatrix[tempnode][len] = tempMatrix[n][i]; // System.out.println("modifying "+ // ((GraphNode)nodes.get(len)).ID+", "+ // ((GraphNode)nodes.get(tempnode)).ID); // temp[firstTempNodeCreated][origNode] for reverse tracing tempMatrix[len][tempnode] = -1 * tempMatrix[n][i]; // System.out.println("modifying "+ // ((GraphNode)nodes.get(i)).ID+", "+ // ((GraphNode)nodes.get(m)).ID); // temp[targetNode][lastTempNodecreated] for reverse tracing tempMatrix[i][m] = -1 * tempMatrix[n][i]; if (m > len) { // System.out.println("modifying "+ // ((GraphNode)nodes.get(m)).ID+ // ", "+((GraphNode)nodes.get(m-1)).ID); // temp[lastTempNodeCreated][secondlastNode] for reverse tracing // but only do this if more than 1 temp nodes are created tempMatrix[m][m - 1] = -1 * tempMatrix[n][i]; } // temp[origNode][targetNode] = 0 unlinking as they have been tempMatrix[n][i] = 0; // linked by a chain of temporary nodes now. tempMatrix[i][n] = 0; graphMatrix = tempMatrix; } else { // System.out.println("modifying "+ // ((GraphNode)nodes.get(i)).ID+", "+ // ((GraphNode)nodes.get(n)).ID); // ****Even if there is no gap just add a reference for the // ****parent to the child for reverse tracing, useful if the // ****there is a reversed edge from parent to child and therefore // ****visualizer would know to highlight this edge when // ****highlighting the child. graphMatrix[i][n] = -1 * graphMatrix[n][i]; } } } } } /** * Returns the index of an element in a level. Must never be called with the * wrong element and the wrong level, will throw an exception otherwise. It * takes as agrument the index of the element (in the m_nodes vector) and the * level it is supposed to be in (as each level contains the indices of the * nodes present in that level). */ private int indexOfElementInLevel(int element, int level[]) throws Exception { for (int i = 0; i < level.length; i++) { if (level[i] == element) { return i; } } throw new Exception("Error. Didn't find element " + m_nodes.get(element).ID + " in level. Inspect code for " + "weka.gui.graphvisualizer.HierarchicalBCEngine"); } /** * Computes the number of edge crossings in the whole graph Takes as an * argument levels of nodes. It is essentially the same algorithm provided in * Universitat des Saarlandes technical report A03/94 by Georg Sander. */ protected int crossings(final int levels[][]) { int sum = 0; for (int i = 0; i < levels.length - 1; i++) { // System.out.println("*****************Processing level "+i+ // "*****************************"); MyList upper = new MyList(), lower = new MyList(); MyListNode lastOcrnce[] = new MyListNode[m_nodes.size()]; int edgeOcrnce[] = new int[m_nodes.size()]; for (int j = 0, uidx = 0, lidx = 0; j < (levels[i].length + levels[i + 1].length); j++) { if ((j % 2 == 0 && uidx < levels[i].length) || lidx >= levels[i + 1].length) { int k1 = 0, k2 = 0, k3 = 0; GraphNode n = m_nodes.get(levels[i][uidx]); // Deactivating and counting crossings for all edges ending in it // coming from bottom left if (lastOcrnce[levels[i][uidx]] != null) { MyListNode temp = new MyListNode(-1); temp.next = upper.first; try { do { temp = temp.next; if (levels[i][uidx] == temp.n) { k1 = k1 + 1; k3 = k3 + k2; // System.out.println("Removing from upper: "+temp.n); upper.remove(temp); } else { k2 = k2 + 1; } } while (temp != lastOcrnce[levels[i][uidx]]); } catch (NullPointerException ex) { System.out.println("levels[i][uidx]: " + levels[i][uidx] + " which is: " + m_nodes.get(levels[i][uidx]).ID + " temp: " + temp + " upper.first: " + upper.first); ex.printStackTrace(); System.exit(-1); } lastOcrnce[levels[i][uidx]] = null; sum = sum + k1 * lower.size() + k3; } // Activating all the edges going out towards the bottom // and bottom right for (int k = 0; k < n.edges.length; k++) { if (n.edges[k][1] > 0) { try { if (indexOfElementInLevel(n.edges[k][0], levels[i + 1]) >= uidx) { edgeOcrnce[n.edges[k][0]] = 1; } } catch (Exception ex) { ex.printStackTrace(); } } } for (int k = 0; k < levels[i + 1].length; k++) { if (edgeOcrnce[levels[i + 1][k]] == 1) { MyListNode temp = new MyListNode(levels[i + 1][k]); // new // MyListNode(n.edges[k][0]); lower.add(temp); lastOcrnce[levels[i + 1][k]] = temp; edgeOcrnce[levels[i + 1][k]] = 0; // System.out.println("Adding to lower: "+levels[i+1][k]+ // " which is: "+((GraphNode)m_nodes.get(levels[i+1][k])).ID+ // " first's n is: "+lower.first.n); } } uidx++; } else { int k1 = 0, k2 = 0, k3 = 0; GraphNode n = m_nodes.get(levels[i + 1][lidx]); // Deactivating and counting crossings for all edges ending in it // coming from up and upper left if (lastOcrnce[levels[i + 1][lidx]] != null) { MyListNode temp = new MyListNode(-1); temp.next = lower.first; try { do { temp = temp.next; if (levels[i + 1][lidx] == temp.n) { k1 = k1 + 1; k3 = k3 + k2; lower.remove(temp); // System.out.println("Removing from lower: "+temp.n); } else { k2 = k2 + 1; // System.out.println("temp: "+temp+" lastOcrnce: "+ // lastOcrnce[levels[i+1][lidx]]+" temp.n: "+ // temp.n+" lastOcrnce.n: "+ // lastOcrnce[levels[i+1][lidx]].n); } } while (temp != lastOcrnce[levels[i + 1][lidx]]); } catch (NullPointerException ex) { System.out.print("levels[i+1][lidx]: " + levels[i + 1][lidx] + " which is: " + m_nodes.get(levels[i + 1][lidx]).ID + " temp: " + temp); System.out.println(" lower.first: " + lower.first); ex.printStackTrace(); System.exit(-1); } lastOcrnce[levels[i + 1][lidx]] = null; sum = sum + k1 * upper.size() + k3; } // Activating all the edges going out towards the upper right for (int k = 0; k < n.edges.length; k++) { if (n.edges[k][1] < 0) { try { if (indexOfElementInLevel(n.edges[k][0], levels[i]) > lidx) { edgeOcrnce[n.edges[k][0]] = 1; } } catch (Exception ex) { ex.printStackTrace(); } } } for (int k = 0; k < levels[i].length; k++) { if (edgeOcrnce[levels[i][k]] == 1) { MyListNode temp = new MyListNode(levels[i][k]); upper.add(temp); lastOcrnce[levels[i][k]] = temp; edgeOcrnce[levels[i][k]] = 0; // System.out.println("Adding to upper: "+levels[i][k]+ // " which is : "+ // ((GraphNode)m_nodes.get(levels[i][k])).ID+ // " from node: "+n.ID+", "+k+ // " first's value: "+upper.first.n); } } lidx++; } } // System.out.println("Sum at the end is: "+sum); } return sum; } /** * The following two methods remove cycles from the graph. */ protected void removeCycles() { // visited[x]=1 is only visited AND visited[x]=2 means node is visited // and is on the current path int visited[] = new int[m_nodes.size()]; for (int i = 0; i < graphMatrix.length; i++) { if (visited[i] == 0) { removeCycles2(i, visited); visited[i] = 1; } } } /** * This method should not be called directly. It should be called only from to * call removeCycles() */ private void removeCycles2(int nindex, int visited[]) { visited[nindex] = 2; for (int i = 0; i < graphMatrix[nindex].length; i++) { if (graphMatrix[nindex][i] == DIRECTED) { if (visited[i] == 0) { removeCycles2(i, visited); visited[i] = 1; } else if (visited[i] == 2) { if (nindex == i) { graphMatrix[nindex][i] = 0; } else if (graphMatrix[i][nindex] == DIRECTED) { // System.out.println("\nFound double "+nindex+','+i); graphMatrix[i][nindex] = DOUBLE; graphMatrix[nindex][i] = -DOUBLE; } else { // System.out.println("\nReversing "+nindex+','+i); graphMatrix[i][nindex] = REVERSED; graphMatrix[nindex][i] = -REVERSED; } } } } } /** * This method assigns a vertical level to each node. See * makeProperHierarchy() to see how to use it. */ protected void assignLevels(int levels[], int depth, int i, int j) { // System.out.println(i+","+j); if (i >= graphMatrix.length) { return; } else if (j >= graphMatrix[i].length) { return; } if (graphMatrix[i][j] <= 0) { assignLevels(levels, depth, i, ++j); } else if (graphMatrix[i][j] == DIRECTED || graphMatrix[i][j] == DOUBLE) { if (depth + 1 > levels[j]) { levels[j] = depth + 1; assignLevels(levels, depth + 1, j, 0); } assignLevels(levels, depth, i, ++j); } } /** * This method minimizes the number of edge crossings using the BaryCenter * heuristics given by Sugiyama et al. 1981 This method processes the graph * topdown if reversed is false, otherwise it does bottomup. */ private int[][] minimizeCrossings(boolean reversed, int nodeLevels[][]) { // Minimizing crossings using Sugiyama's method if (reversed == false) { for (int times = 0; times < 1; times++) { int tempLevels[][] = new int[nodeLevels.length][]; // System.out.println("---------------------------------"); // System.out.println("Crossings before PHaseID: "+ // crossings(nodeLevels)); copy2DArray(nodeLevels, tempLevels); for (int i = 0; i < nodeLevels.length - 1; i++) { phaseID(i, tempLevels); } if (crossings(tempLevels) < crossings(nodeLevels)) { nodeLevels = tempLevels; } // System.out.println("\nCrossings before PHaseIU: "+ // crossings(nodeLevels)); tempLevels = new int[nodeLevels.length][]; copy2DArray(nodeLevels, tempLevels); for (int i = nodeLevels.length - 2; i >= 0; i--) { phaseIU(i, tempLevels); } if (crossings(tempLevels) < crossings(nodeLevels)) { nodeLevels = tempLevels; } // System.out.println("\nCrossings before PHaseIID: "+ // crossings(nodeLevels)); tempLevels = new int[nodeLevels.length][]; copy2DArray(nodeLevels, tempLevels); for (int i = 0; i < nodeLevels.length - 1; i++) { // Down phaseIID(i, tempLevels); } if (crossings(tempLevels) < crossings(nodeLevels)) { nodeLevels = tempLevels; // System.out.println("Crossings temp:"+crossings(tempLevels)+ // " graph:"+crossings(nodeLevels)); // printMatrices(nodeLevels); } // System.out.println("\nCrossings before PHaseIIU: "+ // crossings(nodeLevels)); tempLevels = new int[nodeLevels.length][]; copy2DArray(nodeLevels, tempLevels); for (int i = nodeLevels.length - 2; i >= 0; i--) { // Up phaseIIU(i, tempLevels); } if (crossings(tempLevels) < crossings(nodeLevels)) { nodeLevels = tempLevels; // /System.out.println("Crossings temp:"+crossings(tempLevels)+ // " graph:"+crossings(nodeLevels)); // /printMatrices(nodeLevels); // System.out.println("\nCrossings after phaseIIU: "+ // crossings(nodeLevels)); } } return nodeLevels; } else { for (int times = 0; times < 1; times++) { int tempLevels[][] = new int[nodeLevels.length][]; // System.out.println("---------------------------------"); // System.out.println("\nCrossings before PHaseIU: "+ // crossings(nodeLevels)); copy2DArray(nodeLevels, tempLevels); for (int i = nodeLevels.length - 2; i >= 0; i--) { phaseIU(i, tempLevels); } if (crossings(tempLevels) < crossings(nodeLevels)) { nodeLevels = tempLevels; // printMatrices(nodeLevels); } // System.out.println("Crossings before PHaseID: "+ // crossings(nodeLevels)); tempLevels = new int[nodeLevels.length][]; copy2DArray(nodeLevels, tempLevels); for (int i = 0; i < nodeLevels.length - 1; i++) { phaseID(i, tempLevels); } if (crossings(tempLevels) < crossings(nodeLevels)) { nodeLevels = tempLevels; // /printMatrices(nodeLevels); } // System.out.println("\nCrossings before PHaseIIU: "+ // crossings(nodeLevels)); tempLevels = new int[nodeLevels.length][]; copy2DArray(nodeLevels, tempLevels); for (int i = nodeLevels.length - 2; i >= 0; i--) { // Up phaseIIU(i, tempLevels); } if (crossings(tempLevels) < crossings(nodeLevels)) { nodeLevels = tempLevels; // printMatrices(nodeLevels); } // System.out.println("\nCrossings before PHaseIID: "+ // crossings(nodeLevels)); tempLevels = new int[nodeLevels.length][]; copy2DArray(nodeLevels, tempLevels); for (int i = 0; i < nodeLevels.length - 1; i++) { // Down phaseIID(i, tempLevels); } if (crossings(tempLevels) < crossings(nodeLevels)) { nodeLevels = tempLevels; // /printMatrices(nodeLevels); // System.out.println("\nCrossings after phaseIID: "+ // crossings(nodeLevels)); } } return nodeLevels; } } /** * See Sugiyama et al. 1981 (full reference give at top) lindex is the index * of the level we want to process. In this method we'll sort the vertices at * the level one below lindex according to their UP-barycenters (or column * barycenters). */ protected void phaseID(final int lindex, final int levels[][]) { float colBC[]; // = new float[levels[lindex+1].size()]; colBC = calcColBC(lindex, levels); // System.out.println("In ID Level"+(lindex+1)+":"); // System.out.print("\t"); // for(int i=0; i<colBC.length; i++) // {System.out.print("Col"+(i+1)+":"+colBC[i]+" "); // } // System.out.println(""); // colBC = calcColBC1(lindex, levels); // for(int i=0; i<colBC.length; i++) // {System.out.print("Col"+(i+1)+":"+colBC[i]+" "); // } // System.out.println(""); // System.out.print("\n\tNodes "); // for(int i=0; i<levels[lindex+1].length; i++) // System.out.print(levels[lindex+1][i]+" "); // System.out.println(""); // System.out.println("\nCrossings: "+crossings(levels)); // inspect(false, lindex, levels, colBC); isort(levels[lindex + 1], colBC); // combSort11(levels[lindex+1], colBC); // System.out.println("After sorting"); // System.out.print("\t"); // for(int i=0; i<colBC.length; i++) // {System.out.print("Col"+(i+1)+":"+colBC[i]+" "); // } // System.out.print("\n\tNodes "); // for(int i=0; i<levels[lindex+1].length; i++) // System.out.print(levels[lindex+1][i]+" "); // System.out.println("\nCrossings: "+crossings(levels)); // /System.out.println(""); } /** * See Sugiyama et al. 1981 (full reference give at top) lindex is the index * of the level we want to process. In this method we'll sort the vertices at * the level lindex according to their DOWN-barycenters (or row barycenters). */ public void phaseIU(final int lindex, final int levels[][]) { float rowBC[]; rowBC = calcRowBC(lindex, levels); // System.out.println("In IU Level"+(lindex+1)+":"); // System.out.print("\t"); // for(int i=0; i<rowBC.length; i++) // {System.out.print("Row"+(i+1)+":"+rowBC[i]+" "); // } // System.out.print("\n\t"); // rowBC = calcRowBC1(lindex, levels); // for(int i=0; i<rowBC.length; i++) // {System.out.print("Row"+(i+1)+":"+rowBC[i]+" "); // } // System.out.println(""); // System.out.print("\n\tNodes "); // for(int i=0; i<levels[lindex].length; i++) // System.out.print(levels[lindex][i]+" "); // System.out.println("\nCrossings: "+crossings(levels)); // inspect(true, lindex, levels, rowBC); isort(levels[lindex], rowBC); // combSort11(levels[lindex], rowBC); // System.out.println("After sorting\n\t"); // for(int i=0; i<rowBC.length; i++) // {System.out.print("Row"+(i+1)+":"+rowBC[i]+" "); // } // System.out.print("\n\tNodes "); // for(int i=0; i<levels[lindex].length; i++) // System.out.print(levels[lindex][i]+" "); // System.out.println("\nCrossings: "+crossings(levels)); } /** * See Sugiyama et al. 1981 (full reference give at top) */ public void phaseIID(final int lindex, final int levels[][]) { float colBC[]; colBC = calcColBC(lindex, levels); // System.out.println("getting into phase IID"); for (int i = 0; i < colBC.length - 1; i++) { if (colBC[i] == colBC[i + 1]) { // System.out.println("Crossings before begining of iteration: "+ // crossings(levels)); int tempLevels[][] = new int[levels.length][]; copy2DArray(levels, tempLevels); // System.out.println("Interchanging: "+ // ((GraphNode)m_nodes.get(levels[lindex+1][i])).ID+ // " & "+ // ((GraphNode)m_nodes.get(levels[lindex+1][(i+1)])).ID+ // " at level "+(lindex+1) ); int node1 = levels[lindex + 1][i]; int node2 = levels[lindex + 1][i + 1]; levels[lindex + 1][i + 1] = node1; levels[lindex + 1][i] = node2; for (int k = lindex + 1; k < levels.length - 1; k++) { phaseID(k, levels); } // System.out.println("Crossings temp:"+crossings(tempLevels)+ // " graph:"+crossings(levels)); if (crossings(levels) <= crossings(tempLevels)) { // System.out.println("Crossings temp: "+crossings(tempLevels)+ // " Crossings levels: "+crossings(levels)); copy2DArray(levels, tempLevels); } // printMatrices(levels); } else { copy2DArray(tempLevels, levels); levels[lindex + 1][i + 1] = node1; levels[lindex + 1][i] = node2; } // System.out.println("Crossings after PhaseID of phaseIID, "+ // "in iteration "+i+" of "+(colBC.length-1)+" at "+ // lindex+", levels: "+crossings(levels)+ // " temp: "+crossings(tempLevels)); // tempLevels = new int[levels.length][]; // copy2DArray(levels, tempLevels); for (int k = levels.length - 2; k >= 0; k--) { phaseIU(k, levels); } // System.out.println("Crossings temp:"+crossings(tempLevels)+ // " graph:"+crossings(levels)); // if(crossings(tempLevels)<crossings(levels)) { // System.out.println("Crossings temp: "+crossings(tempLevels)+ // " Crossings levels: "+crossings(levels)); // copy2DArray(tempLevels, levels); } //printMatrices(levels); } if (crossings(tempLevels) < crossings(levels)) { copy2DArray(tempLevels, levels); } // System.out.println("Crossings after PhaseIU of phaseIID, in"+ // " iteration "+i+" of "+(colBC.length-1)+" at " // +lindex+", levels: "+crossings(levels)+" temp: "+ // crossings(tempLevels)); // colBC = calcColBC(lindex, levels); } } } /** * See Sugiyama et al. 1981 (full reference give at top) */ public void phaseIIU(final int lindex, final int levels[][]) { float rowBC[]; rowBC = calcRowBC(lindex, levels); // System.out.println("Getting into phaseIIU"); for (int i = 0; i < rowBC.length - 1; i++) { if (rowBC[i] == rowBC[i + 1]) { // System.out.println("Crossings before begining of iteration: "+ // crossings(levels)); int tempLevels[][] = new int[levels.length][]; copy2DArray(levels, tempLevels); // System.out.println("Interchanging: "+ // ((GraphNode)m_nodes.get(levels[lindex][i])).ID+" & "+ // ((GraphNode)m_nodes.get(levels[lindex][i+1])).ID+ // " at level "+(lindex+1) ); int node1 = levels[lindex][i]; int node2 = levels[lindex][i + 1]; levels[lindex][i + 1] = node1; levels[lindex][i] = node2; for (int k = lindex - 1; k >= 0; k--) { phaseIU(k, levels); } if (crossings(levels) <= crossings(tempLevels)) { // System.out.println("Crossings temp: "+crossings(tempLevels)+ // " Crossings levels: "+crossings(levels)); copy2DArray(levels, tempLevels); } // printMatrices(levels); else { copy2DArray(tempLevels, levels); levels[lindex][i + 1] = node1; levels[lindex][i] = node2; } // System.out.println("Crossings after PhaseIU of PhaseIIU, in "+ // "iteration "+i+" of "+(rowBC.length-1)+" at " // +lindex+", levels: "+crossings(levels)+ // " temp: "+crossings(tempLevels)); // tempLevels = new int[levels.length][]; // copy2DArray(levels, tempLevels); for (int k = 0; k < levels.length - 1; k++) { phaseID(k, levels); } // if(crossings(tempLevels)<crossings(levels)) { // System.out.println("Crossings temp: "+crossings(tempLevels)+ // " Crossings levels: "+crossings(levels)); // copy2DArray(tempLevels, levels); } //printMatrices(levels); } if (crossings(tempLevels) <= crossings(levels)) { copy2DArray(tempLevels, levels); // System.out.println("Crossings after PhaseID of phaseIIU, in "+ // "iteration "+i+" of "+(rowBC.length-1)+" at " // +lindex+", levels: "+crossings(levels)+ // " temp: "+crossings(tempLevels)); // rowBC = calcRowBC(lindex, levels); } } } } /** * See Sugiyama et al. 1981 (full reference give at top) */ protected float[] calcRowBC(final int lindex, final int levels[][]) { float rowBC[] = new float[levels[lindex].length]; GraphNode n; for (int i = 0; i < levels[lindex].length; i++) { int sum = 0; n = m_nodes.get(levels[lindex][i]); for (int[] edge : n.edges) { if (edge[1] > 0) { sum++; try { rowBC[i] = rowBC[i] + indexOfElementInLevel(edge[0], levels[lindex + 1]) + 1; } catch (Exception ex) { return null; } } } if (rowBC[i] != 0) { rowBC[i] = rowBC[i] / sum; } } return rowBC; } /** * See Sugiyama et al. 1981 (full reference give at top) */ protected float[] calcColBC(final int lindex, final int levels[][]) { float colBC[] = new float[levels[lindex + 1].length]; GraphNode n; for (int i = 0; i < levels[lindex + 1].length; i++) { int sum = 0; n = m_nodes.get(levels[lindex + 1][i]); for (int[] edge : n.edges) { if (edge[1] < 1) { sum++; try { colBC[i] = colBC[i] + indexOfElementInLevel(edge[0], levels[lindex]) + 1; } catch (Exception ex) { return null; } } } if (colBC[i] != 0) { colBC[i] = colBC[i] / sum; } } return colBC; } /** * Prints out the interconnection matrix at each level. See Sugiyama et al. * 1981 (full reference give at top) */ protected void printMatrices(final int levels[][]) { int i = 0; for (i = 0; i < levels.length - 1; i++) { float rowBC[] = null; float colBC[] = null; try { rowBC = calcRowBC(i, levels); colBC = calcColBC(i, levels); } catch (NullPointerException ne) { System.out.println("i: " + i + " levels.length: " + levels.length); ne.printStackTrace(); return; } System.out.print("\nM" + (i + 1) + "\t"); for (int j = 0; j < levels[i + 1].length; j++) { System.out.print(m_nodes.get(levels[i + 1][j]).ID + " "); // ((Integer)levels[i+1].get(j)).intValue())+" "); } System.out.println(""); for (int j = 0; j < levels[i].length; j++) { System.out.print(m_nodes.get(levels[i][j]).ID + "\t"); // ((Integer)levels[i].get(j)).intValue())+"\t"); for (int k = 0; k < levels[i + 1].length; k++) { System.out.print(graphMatrix[levels[i][j]] // ((Integer)levels[i].get(j)).intValue()] [levels[i + 1][k]] + " "); // ((Integer)levels[i+1].get(k)).intValue()]+" "); } System.out.println(rowBC[j]); } System.out.print("\t"); for (int k = 0; k < levels[i + 1].length; k++) { System.out.print(colBC[k] + " "); } } System.out.println("\nAt the end i: " + i + " levels.length: " + levels.length); } /** * This methods sorts the vertices in level[] according to their barycenters * in BC[], using combsort11. It, however, doesn't touch the vertices with * barycenter equal to zero. */ /* * //This method should be removed protected static void combSort11(int * level[], float BC[]) { int switches, j, top, gap, lhold; float hold; gap = * BC.length; do { gap=(int)(gap/1.3); switch(gap) { case 0: gap = 1; break; * case 9: case 10: gap=11; break; default: break; } switches=0; top = * BC.length-gap; for(int i=0; i<top; i++) { j=i+gap; if(BC[i]==0 || BC[j]==0) * continue; if(BC[i] > BC[j]) { hold=BC[i]; BC[i]=BC[j]; BC[j]=hold; lhold = * level[i]; level[i] = level[j]; level[j] = lhold; switches++; }//endif * }//endfor }while(switches>0 || gap>1); } */ /** * This methods sorts the vertices in level[] according to their barycenters * in BC[], using insertion sort. It, however, doesn't touch the vertices with * barycenter equal to zero. */ // Both level and BC have elements in the same order protected static void isort(int level[], float BC[]) { float temp; int temp2; for (int i = 0; i < BC.length - 1; i++) { int j = i; temp = BC[j + 1]; temp2 = level[j + 1]; if (temp == 0) { continue; } int prej = j + 1; while (j > -1 && (temp < BC[j] || BC[j] == 0)) { if (BC[j] == 0) { j--; continue; } else { BC[prej] = BC[j]; level[prej] = level[j]; prej = j; j--; } } // j++; BC[prej] = temp; level[prej] = temp2; // Integer node = (Integer)level.get(i+1); // level.remove(i+1); // level.insertElementAt(node, prej); } } /** * Copies one Matrix of type int[][] to another. */ protected void copyMatrix(int from[][], int to[][]) { for (int i = 0; i < from.length; i++) { for (int j = 0; j < from[i].length; j++) { to[i][j] = from[i][j]; } } } /** * Copies one array of type int[][] to another. */ protected void copy2DArray(int from[][], int to[][]) { for (int i = 0; i < from.length; i++) { to[i] = new int[from[i].length]; System.arraycopy(from[i], 0, to[i], 0, from[i].length); // for(int j=0; j<from[i].length; j++) // to[i][j] = from[i][j]; } } /** * This method lays out the vertices horizontally, in each level. It simply * assings an x value to a vertex according to its index in the level. */ protected void naiveLayout() { /* * if(maxStringWidth==0) { int strWidth; for(int i=0; i<m_nodes.size(); i++) * { strWidth = m_fm.stringWidth(((GraphNode)m_nodes.get(i)).lbl); * if(strWidth>maxStringWidth) maxStringWidth=strWidth; } * * if(m_nodeSize<maxStringWidth) {m_nodeSize = maxStringWidth+4; m_nodeArea * = m_nodeSize+8; } } */ if (nodeLevels == null) { makeProperHierarchy(); } // int nodeHeight = m_nodeHeight*2; //m_fm.getHeight()*2; for (int i = 0, temp = 0; i < nodeLevels.length; i++) { for (int j = 0; j < nodeLevels[i].length; j++) { temp = nodeLevels[i][j]; // horPositions[temp]=j; GraphNode n = m_nodes.get(temp); n.x = j * m_nodeWidth; // horPositions[temp]*m_nodeWidth; n.y = i * 3 * m_nodeHeight; } } // setAppropriateSize(); } protected int uConnectivity(int lindex, int eindex) { int n = 0; for (int i = 0; i < nodeLevels[lindex - 1].length; i++) { if (graphMatrix[nodeLevels[lindex - 1][i]][nodeLevels[lindex][eindex]] > 0) { n++; } } return n; } protected int lConnectivity(int lindex, int eindex) { int n = 0; for (int i = 0; i < nodeLevels[lindex + 1].length; i++) { if (graphMatrix[nodeLevels[lindex][eindex]][nodeLevels[lindex + 1][i]] > 0) { n++; } } return n; } protected int uBCenter(int lindex, int eindex, int horPositions[]) { int sum = 0; for (int i = 0; i < nodeLevels[lindex - 1].length; i++) { if (graphMatrix[nodeLevels[lindex - 1][i]][nodeLevels[lindex][eindex]] > 0) { sum = sum + (horPositions[nodeLevels[lindex - 1][i]]); } } if (sum != 0) { // To avoid 0/0 // System.out.println("uBC Result: "+sum+"/"+ // uConnectivity(lindex,eindex)+ // " = "+(sum/uConnectivity(lindex,eindex)) ); sum = sum / uConnectivity(lindex, eindex); } return sum; } protected int lBCenter(int lindex, int eindex, int horPositions[]) { int sum = 0; for (int i = 0; i < nodeLevels[lindex + 1].length; i++) { if (graphMatrix[nodeLevels[lindex][eindex]][nodeLevels[lindex + 1][i]] > 0) { sum = sum + (horPositions[nodeLevels[lindex + 1][i]]); } } if (sum != 0) { sum = sum / lConnectivity(lindex, eindex); // lConectivity; } return sum; } /** * This method lays out the vertices horizontally, in each level. See Sugiyama * et al. 1981 for full reference. */ protected void priorityLayout1() { int[] horPositions = new int[m_nodes.size()]; int maxCount = 0; for (int i = 0; i < nodeLevels.length; i++) { int count = 0; for (int j = 0; j < nodeLevels[i].length; j++) { horPositions[nodeLevels[i][j]] = j; count++; } if (count > maxCount) { maxCount = count; } } // fireLayoutCompleteEvent( new LayoutCompleteEvent(this) ); int priorities[], BC[]; // System.out.println("********Going from 2 to n********"); for (int i = 1; i < nodeLevels.length; i++) { priorities = new int[nodeLevels[i].length]; BC = new int[nodeLevels[i].length]; for (int j = 0; j < nodeLevels[i].length; j++) { if (m_nodes.get(nodeLevels[i][j]).ID.startsWith("S")) { priorities[j] = maxCount + 1; } else { priorities[j] = uConnectivity(i, j); } BC[j] = uBCenter(i, j, horPositions); } // for(int j=0; j<nodeLevels[i].length; j++) // System.out.println("Level: "+(i+1)+" Node: " // +((GraphNode)m_nodes.get(nodeLevels[i][j])).ID // +" uConnectivity: "+priorities[j]+" uBC: "+BC[j]+" position: " // +horPositions[nodeLevels[i][j]]); priorityLayout2(nodeLevels[i], priorities, BC, horPositions); // repaint // try { // tempMethod(horPositions); // fireLayoutCompleteEvent( new LayoutCompleteEvent(this) ); // Thread.sleep(1000); // } catch(InterruptedException ie) { ie.printStackTrace(); } // for(int j=0; j<nodeLevels[i].length; j++) // System.out.println("Level: "+(i+1)+" Node: " // +((GraphNode)m_nodes.get(nodeLevels[i][j])).ID // +" uConnectivity: "+priorities[j]+" uBC: "+BC[j]+" position: " // +horPositions[nodeLevels[i][j]]); } // System.out.println("********Going from n-1 to 1********"); for (int i = nodeLevels.length - 2; i >= 0; i--) { priorities = new int[nodeLevels[i].length]; BC = new int[nodeLevels[i].length]; for (int j = 0; j < nodeLevels[i].length; j++) { if (m_nodes.get(nodeLevels[i][j]).ID.startsWith("S")) { priorities[j] = maxCount + 1; } else { priorities[j] = lConnectivity(i, j); } BC[j] = lBCenter(i, j, horPositions); // , priorities[j]); } priorityLayout2(nodeLevels[i], priorities, BC, horPositions); // repaint(); // try { // tempMethod(horPositions); // fireLayoutCompleteEvent( new LayoutCompleteEvent(this) ); // Thread.sleep(1000); // } catch(InterruptedException ie) { ie.printStackTrace(); } // for(int j=0; j<nodeLevels[i].length; j++) // System.out.println("Level: "+(i+1)+" Node: " // +((GraphNode)m_nodes.get(nodeLevels[i][j])).ID // +" lConnectivity: "+priorities[j]+" lBC: "+BC[j]+" position: " // +horPositions[nodeLevels[i][j]]); } // System.out.println("********Going from 2 to n again********"); for (int i = 2; i < nodeLevels.length; i++) { priorities = new int[nodeLevels[i].length]; BC = new int[nodeLevels[i].length]; for (int j = 0; j < nodeLevels[i].length; j++) { if (m_nodes.get(nodeLevels[i][j]).ID.startsWith("S")) { priorities[j] = maxCount + 1; } else { priorities[j] = uConnectivity(i, j); } BC[j] = uBCenter(i, j, horPositions); } // for(int j=0; j<nodeLevels[i].length; j++) // System.out.println("Level: "+(i+1)+" Node: " // +((GraphNode)m_nodes.get(nodeLevels[i][j])).ID // +" uConnectivity: "+priorities[j]+" uBC: "+BC[j]+" position: " // +horPositions[nodeLevels[i][j]]); priorityLayout2(nodeLevels[i], priorities, BC, horPositions); // repaint(); // try { // tempMethod(horPositions); // fireLayoutCompleteEvent( new LayoutCompleteEvent(this) ); // Thread.sleep(1000); // } catch(InterruptedException ie) { ie.printStackTrace(); } // for(int j=0; j<nodeLevels[i].length; j++) // System.out.println("Level: "+(i+1)+" Node: " // +((GraphNode)m_nodes.get(nodeLevels[i][j])).ID // +" uConnectivity: "+priorities[j]+" uBC: "+BC[j]+" position: " // +horPositions[nodeLevels[i][j]]); } int minPosition = horPositions[0]; for (int horPosition : horPositions) { if (horPosition < minPosition) { minPosition = horPosition; } } if (minPosition < 0) { minPosition = minPosition * -1; for (int i = 0; i < horPositions.length; i++) { // System.out.print(horPositions[i]); horPositions[i] += minPosition; // System.out.println(">"+horPositions[i]); } } // int nodeHeight = m_nodeHeight*2; //m_fm.getHeight()*2; for (int i = 0, temp = 0; i < nodeLevels.length; i++) { for (int j = 0; j < nodeLevels[i].length; j++) { temp = nodeLevels[i][j]; // horPositions[temp]=j; GraphNode n = m_nodes.get(temp); n.x = horPositions[temp] * m_nodeWidth; n.y = i * 3 * m_nodeHeight; } } // setAppropriateSize(); } /** * This method is used by priorityLayout1(). It should not be called directly. * This method does the actual moving of the vertices in each level based on * their priorities and barycenters. */ private void priorityLayout2(int level[], int priorities[], int bCenters[], int horPositions[]) { int descOrder[] = new int[priorities.length]; // Getting the indices of priorities in descending order descOrder[0] = 0; for (int i = 0; i < priorities.length - 1; i++) { int j = i; int temp = i + 1; while (j > -1 && priorities[descOrder[j]] < priorities[temp]) { descOrder[j + 1] = descOrder[j]; j--; } j++; descOrder[j] = temp; } // System.out.println("\nPriorities:"); // for(int i=0; i<priorities.length; i++) // System.out.print(priorities[i]+" "); // System.out.println("\nDescOrder:"); // for(int i=0; i<descOrder.length; i++) // System.out.print(descOrder[i]+" "); for (int k = 0; k < descOrder.length; k++) { for (int i = 0; i < descOrder.length; i++) { int leftCount = 0, rightCount = 0, leftNodes[], rightNodes[]; for (int j = 0; j < priorities.length; j++) { if (horPositions[level[descOrder[i]]] > horPositions[level[j]]) { leftCount++; } else if (horPositions[level[descOrder[i]]] < horPositions[level[j]]) { rightCount++; } } leftNodes = new int[leftCount]; rightNodes = new int[rightCount]; for (int j = 0, l = 0, r = 0; j < priorities.length; j++) { if (horPositions[level[descOrder[i]]] > horPositions[level[j]]) { leftNodes[l++] = j; } else if (horPositions[level[descOrder[i]]] < horPositions[level[j]]) { rightNodes[r++] = j; } } // ****Moving left while (Math.abs(horPositions[level[descOrder[i]]] - 1 - bCenters[descOrder[i]]) < Math .abs(horPositions[level[descOrder[i]]] - bCenters[descOrder[i]])) { // ****Checking if it can be moved to left int temp = horPositions[level[descOrder[i]]]; boolean cantMove = false; for (int j = leftNodes.length - 1; j >= 0; j--) { if (temp - horPositions[level[leftNodes[j]]] > 1) { break; } else if (priorities[descOrder[i]] <= priorities[leftNodes[j]]) { cantMove = true; break; } else { temp = horPositions[level[leftNodes[j]]]; } } // if(horPositions[level[descOrder[i]]]-1== // horPositions[level[leftNodes[j]]]) // cantMove = true; if (cantMove) { break; } temp = horPositions[level[descOrder[i]]] - 1; // ****moving other vertices to left for (int j = leftNodes.length - 1; j >= 0; j--) { if (temp == horPositions[level[leftNodes[j]]]) { // System.out.println("Moving "+ // ((Node)m_nodes.get(level[leftNodes[j]])).ID+" from " // +horPositions[level[leftNodes[j]]]+" to " // +(horPositions[level[leftNodes[j]]]-1) ); horPositions[level[leftNodes[j]]] = temp = horPositions[level[leftNodes[j]]] - 1; } } // System.out.println("Moving main "+ // ((GraphNode)m_nodes.get(level[descOrder[i]])).ID+" from " // +horPositions[level[descOrder[i]]]+" to " // +(horPositions[level[descOrder[i]]]-1)); horPositions[level[descOrder[i]]] = horPositions[level[descOrder[i]]] - 1; } // ****Moving right while (Math.abs(horPositions[level[descOrder[i]]] + 1 - bCenters[descOrder[i]]) < Math .abs(horPositions[level[descOrder[i]]] - bCenters[descOrder[i]])) { // ****checking if the vertex can be moved int temp = horPositions[level[descOrder[i]]]; boolean cantMove = false; for (int rightNode : rightNodes) { if (horPositions[level[rightNode]] - temp > 1) { break; } else if (priorities[descOrder[i]] <= priorities[rightNode]) { cantMove = true; break; } else { temp = horPositions[level[rightNode]]; } } // if(horPositions[level[descOrder[i]]]-1== // horPositions[level[leftNodes[j]]]) // cantMove = true; if (cantMove) { break; } temp = horPositions[level[descOrder[i]]] + 1; // ****moving other vertices to left for (int j = 0; j < rightNodes.length; j++) { if (temp == horPositions[level[rightNodes[j]]]) { // System.out.println("Moving "+ // (Node)m_nodes.get(level[rightNodes[j]])).ID+" from " // +horPositions[level[rightNodes[j]]]+" to " // +(horPositions[level[rightNodes[j]]]+1) ); horPositions[level[rightNodes[j]]] = temp = horPositions[level[rightNodes[j]]] + 1; } } // System.out.println("Moving main "+ // ((GraphNode)m_nodes.get(level[descOrder[i]])).ID+" from " // +horPositions[level[descOrder[i]]]+" to " // +(horPositions[level[descOrder[i]]]+1)); horPositions[level[descOrder[i]]] = horPositions[level[descOrder[i]]] + 1; } } } } /** * The following classes implement a double linked list to be used in the * crossings function. */ private class MyList { int size; MyListNode first = null; MyListNode last = null; public void add(MyListNode n) { if (first == null) { first = last = n; } else if (last.next == null) { last.next = n; last.next.previous = last; last = last.next; } else { System.err.println("Error shouldn't be in here. Check MyList code"); size--; } size++; } public void remove(MyListNode n) { if (n.previous != null) { n.previous.next = n.next; } if (n.next != null) { n.next.previous = n.previous; } if (last == n) { last = n.previous; } if (first == n) { first = n.next; } size--; } public int size() { return size; } } private class MyListNode { int n; MyListNode next, previous; public MyListNode(int i) { n = i; next = null; previous = null; } } } // HierarchicalBCEngine
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/graphvisualizer/LayoutCompleteEvent.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * LayoutCompleteEvent.java * Copyright (C) 2003-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.graphvisualizer; import java.util.EventObject; /** * This is an event which is fired by a LayoutEngine once * a LayoutEngine finishes laying out the graph, so * that the Visualizer can repaint the screen to show * the changes. * * @author Ashraf M. Kibriya (amk14@cs.waikato.ac.nz) * @version $Revision$ - 24 Apr 2003 - Initial version (Ashraf M. Kibriya) */ public class LayoutCompleteEvent extends EventObject { /** for serialization */ private static final long serialVersionUID = 6172467234026258427L; public LayoutCompleteEvent(Object source) { super(source); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/graphvisualizer/LayoutCompleteEventListener.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * LayoutCompleteEventListener.java * Copyright (C) 2003-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.graphvisualizer; /** * This interface should be implemented by any class * which needs to receive LayoutCompleteEvents from * the LayoutEngine. Typically this would be implemented * by the Visualization class. * * @author Ashraf M. Kibriya (amk14@cs.waikato.ac.nz) * @version $Revision$ - 24 Apr 2003 - Initial version (Ashraf M. Kibriya) */ public interface LayoutCompleteEventListener { void layoutCompleted(LayoutCompleteEvent le); }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/graphvisualizer/LayoutEngine.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * LayoutEngine.java * Copyright (C) 2003-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.graphvisualizer; import java.util.ArrayList; import javax.swing.JPanel; import javax.swing.JProgressBar; /** * This interface class has been added to facilitate the addition of other * layout engines to this package. Any class that wants to lay out a graph * should implement this interface. * * @author Ashraf M. Kibriya (amk14@cs.waikato.ac.nz) * @version $Revision$ - 24 Apr 2003 - Initial version (Ashraf M. * Kibriya) */ public interface LayoutEngine { /** * This method lays out the graph for better visualization */ void layoutGraph(); /** * This method sets the nodes and edges vectors of the LayoutEngine */ void setNodesEdges(ArrayList<GraphNode> nodes, ArrayList<GraphEdge> edges); /** * This method sets the allowed size of the node */ void setNodeSize(int nodeWidth, int nodeHeight); /** give access to set of graph nodes */ ArrayList<GraphNode> getNodes(); /** * This method returns the extra controls panel for the LayoutEngine, if there * is any. */ JPanel getControlPanel(); /** * This method returns the progress bar for the LayoutEngine, which shows the * progress of the layout process, if it takes a while to layout the graph */ JProgressBar getProgressBar(); /** * This method adds a LayoutCompleteEventListener to the LayoutEngine. * * @param e - The LayoutCompleteEventListener to add */ void addLayoutCompleteEventListener(LayoutCompleteEventListener e); /** * This method removes a LayoutCompleteEventListener from the LayoutEngine. * * @param e - The LayoutCompleteEventListener to remove. */ void removeLayoutCompleteEventListener(LayoutCompleteEventListener e); /** * This fires a LayoutCompleteEvent once a layout has been completed. */ void fireLayoutCompleteEvent(LayoutCompleteEvent 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/hierarchyvisualizer/HierarchyVisualizer.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * HierarchicalClusterer.java * Copyright (C) 2009-2012 University of Waikato, Hamilton, New Zealand */ package weka.gui.hierarchyvisualizer; /** * Shows cluster trees represented in Newick format as dendrograms. * * @author Remco Bouckaert (rrb@xm.co.nz, remco@cs.waikato.ac.nz) * @version $Revision$ */ import java.awt.Color; import java.awt.Container; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import javax.swing.JFrame; import weka.gui.visualize.PrintablePanel; public class HierarchyVisualizer extends PrintablePanel implements ComponentListener { private static final long serialVersionUID = 1L; String m_sNewick; Node m_tree; int m_nLeafs; double m_fHeight; double m_fScaleX = 10; double m_fScaleY = 10; public HierarchyVisualizer(String sNewick) { try { parseNewick(sNewick); } catch (Exception e) { e.printStackTrace(); // System.exit(0); } addComponentListener(this); } // c'tor int positionLeafs(Node node, int nPosX) { if (node.isLeaf()) { node.m_fPosX = nPosX + 0.5; nPosX++; return nPosX; } else { for (int i = 0; i < node.m_children.length; i++) { nPosX = positionLeafs(node.m_children[i], nPosX); } } return nPosX; } double positionRest(Node node) { if (node.isLeaf()) { return node.m_fPosX; } else { double fPosX = 0; for (int i = 0; i < node.m_children.length; i++) { fPosX += positionRest(node.m_children[i]); } fPosX /= node.m_children.length; node.m_fPosX = fPosX; return fPosX; } } double positionHeight(Node node, double fOffSet) { if (node.isLeaf()) { node.m_fPosY = fOffSet + node.m_fLength; return node.m_fPosY; } else { double fPosY = fOffSet + node.m_fLength; double fYMax = 0; for (int i = 0; i < node.m_children.length; i++) { fYMax = Math.max(fYMax, positionHeight(node.m_children[i], fPosY)); } node.m_fPosY = fPosY; return fYMax; } } //Vector<String> m_sMetaDataNames; /** class for nodes in building tree data structure **/ class Node { double m_fLength = -1; double m_fPosX = 0; double m_fPosY = 0; String m_sLabel; //Vector<String> m_sMetaDataValues; String m_sMetaData; /** list of children of this node **/ Node[] m_children; /** parent node in the tree, null if root **/ Node m_Parent = null; Node getParent() { return m_Parent; } void setParent(Node parent) { m_Parent = parent; } /** check if current node is root node **/ boolean isRoot() { return m_Parent == null; } boolean isLeaf() { return m_children == null; } /** return nr of children **/ int getChildCount() { // } if (m_children == null) {return 0;} return m_children.length; } Node getChild(int iChild) { return m_children[iChild]; } /** count number of nodes in tree, starting with current node **/ int getNodeCount() { if (m_children == null) { return 1; } int n = 1; for (int i = 0; i < m_children.length; i++) { n += m_children[i].getNodeCount(); } return n; } public String toString() { StringBuffer buf = new StringBuffer(); if (m_children != null) { buf.append("("); for (int i = 0; i < m_children.length-1; i++) { buf.append(m_children[i].toString()); buf.append(','); } buf.append(m_children[m_children.length - 1].toString()); buf.append(")"); } else { buf.append(m_sLabel); } if (m_sMetaData != null) { buf.append('['); buf.append(m_sMetaData); buf.append(']'); } buf.append(":" + m_fLength); return buf.toString(); } double draw(Graphics g) { if (isLeaf()) { int x = (int)(m_fPosX * m_fScaleX); int y = (int)(m_fPosY * m_fScaleY); g.drawString(m_sLabel, x, y); g.drawLine((int)(m_fPosX * m_fScaleX), (int)(m_fPosY * m_fScaleY), (int)(m_fPosX * m_fScaleX), (int)((m_fPosY - m_fLength) * m_fScaleY)); } else { double fPosX1 = Double.MAX_VALUE; double fPosX2 = -Double.MAX_VALUE; for (int i = 0; i < m_children.length; i++) { double f = m_children[i].draw(g); if (f < fPosX1) {fPosX1 = f;} if (f > fPosX2) {fPosX2 = f;} } g.drawLine((int)(m_fPosX * m_fScaleX), (int)(m_fPosY * m_fScaleY), (int)(m_fPosX * m_fScaleX), (int)((m_fPosY - m_fLength) * m_fScaleY)); g.drawLine((int)(fPosX1 * m_fScaleX), (int)(m_fPosY * m_fScaleY), (int)(fPosX2 * m_fScaleX), (int)(m_fPosY* m_fScaleY)); } return m_fPosX; } } // class Node /** helper method for parsing Newick tree **/ int nextNode(String sStr, int i) { int nBraces = 0; char c = sStr.charAt(i); do { i++; if (i < sStr.length()) { c = sStr.charAt(i); // skip meta data block if (c == '[') { while (i < sStr.length() && sStr.charAt(i)!=']') { i++; } i++; if(i < sStr.length()) { c = sStr.charAt(i); } } switch (c) { case '(': nBraces++; break; case ')': nBraces--; break; default: break; } } } while (i < sStr.length() && (nBraces > 0 || (c != ','&&c != ')'&&c != '('))); if (i >= sStr.length() || nBraces < 0) { return -1; } else if (sStr.charAt(i) == ')') { i++; if (sStr.charAt(i) == '[') { while (i < sStr.length() && sStr.charAt(i)!=']') { i++; } i++; if (i >= sStr.length()) { return -1; } } if (sStr.charAt(i) == ':') { i++; c = sStr.charAt(i); while (i < sStr.length() && (c=='.' || Character.isDigit(c)) || c=='-') { i++; if (i < sStr.length()) { c = sStr.charAt(i); } } } } return i; } /** * convert string containing Newick tree into tree datastructure but only in * the limited format as contained in m_sTrees * * @param sNewick * @return tree consisting of a Node */ void parseNewick(String sNewick) throws Exception { m_sNewick = sNewick; int i = m_sNewick.indexOf('('); if (i > 0) { m_sNewick = m_sNewick.substring(i); } System.err.println(m_sNewick); m_tree = parseNewick2(m_sNewick); System.err.println(m_tree.toString()); m_nLeafs = positionLeafs(m_tree, 0); positionRest(m_tree); m_fHeight = positionHeight(m_tree, 0); } Node parseNewick2(String sStr) throws Exception { // System.out.println(sStr); if (sStr == null || sStr.length() == 0) { return null; } Node node = new Node(); if (sStr.startsWith("(")) { int i1 = nextNode(sStr, 0); int i2 = nextNode(sStr, i1); node.m_children = new Node[2]; node.m_children[0] = parseNewick2(sStr.substring(1, i1)); node.m_children[0].m_Parent = node; String sStr2 = sStr.substring(i1+1, (i2>0?i2:sStr.length())); node.m_children[1] = parseNewick2(sStr2); node.m_children[1].m_Parent = node; if (sStr.lastIndexOf('[') > sStr.lastIndexOf(')')) { sStr = sStr.substring(sStr.lastIndexOf('[')); i2 = sStr.indexOf(']'); if (i2 < 0) { throw new Exception("unbalanced square bracket found:" + sStr); } sStr2 = sStr.substring(1, i2); node.m_sMetaData = sStr2; } if (sStr.lastIndexOf(':') > sStr.lastIndexOf(')')) { sStr = sStr.substring(sStr.lastIndexOf(':')); sStr = sStr.replaceAll("[,\\):]", ""); node.m_fLength = new Double(sStr); } else { node.m_fLength = 1; } } else { // it is a leaf if (sStr.contains("[")) { // grab metadata int i1 = sStr.indexOf('['); int i2 = sStr.indexOf(']'); if (i2 < 0) { throw new Exception("unbalanced square bracket found:" + sStr); } String sStr2 = sStr.substring(i1+1, i2); sStr = sStr.substring(0, i1) +sStr.substring(i2+1); node.m_sMetaData = sStr2; } if (sStr.indexOf(')') >= 0) { sStr = sStr.substring(0, sStr.indexOf(')')); } sStr = sStr.replaceFirst("[,\\)]", ""); // System.out.println("parsing <<"+sStr+">>"); if (sStr.length() > 0) { if (sStr.indexOf(':') >= 0) { int iColon = sStr.indexOf(':'); node.m_sLabel = sStr.substring(0, iColon); if (sStr.indexOf(':', iColon+1) >= 0) { int iColon2 = sStr.indexOf(':', iColon+1); node.m_fLength = new Double(sStr.substring(iColon+1, iColon2)); m_fTmpLength = new Double(sStr.substring(iColon2+1)); } else { node.m_fLength = new Double(sStr.substring(iColon+1)); } } else { node.m_sLabel = sStr; node.m_fLength = 1; } } else { return null; } } return node; } double m_fTmpLength; /** * Fits the tree to the current screen size. Call this after window has been * created to get the entire tree to be in view upon launch. */ public void fitToScreen() { m_fScaleX = 10; int nW = getWidth(); if (m_nLeafs > 0) { m_fScaleX = nW / m_nLeafs; } m_fScaleY = 10; int nH = getHeight(); if (m_fHeight > 0) { m_fScaleY = (nH - 10) / m_fHeight; } repaint(); } /** * Updates the screen contents. * * @param g * the drawing surface. */ public void paintComponent(Graphics g) { Color oldBackground = ((Graphics2D) g).getBackground(); // if (m_BackgroundColor != null) ((Graphics2D) g).setBackground(Color.WHITE); g.clearRect(0, 0, getSize().width, getSize().height); ((Graphics2D) g).setBackground(oldBackground); g.setClip(3, 7, getWidth() - 6, getHeight() - 10); m_tree.draw(g); g.setClip(0, 0, getWidth(), getHeight()); } public void componentHidden(ComponentEvent e) {} public void componentMoved(ComponentEvent e) {} public void componentResized(ComponentEvent e) { fitToScreen(); } public void componentShown(ComponentEvent e) {} /** * Main method for testing this class. */ public static void main(String[] args) { //HierarchyVisualizer a = new HierarchyVisualizer("((((human:2.0,(chimp:1.0,bonobo:1.0):1.0):1.0,gorilla:3.0):1.0,siamang:4.0):1.0,orangutan:5.0)"); //HierarchyVisualizer a = new HierarchyVisualizer("(((human:2.0,(chimp:1.0,bonobo:1.0):1.0):1.0,gorilla:3.0):1.0,siamang:4.0)"); //HierarchyVisualizer a = new HierarchyVisualizer(" (((5[theta=0.121335,lxg=0.122437]:0.00742795,3[theta=0.0972485,lxg=0.152762]:0.00742795)[theta=0.490359,lxg=0.0746703]:0.0183076,((2[theta=0.0866056,lxg=0.2295]:0.00993801,4[theta=0.135512,lxg=0.146674]:0.00993801)[theta=0.897783,lxg=0.0200762]:0.00901206,1[theta=0.200265,lxg=0.18925]:0.0189501)[theta=0.0946195,lxg=0.143427]:0.00678551)[theta=0.185562,lxg=0.139681]:0.0129598,(7[theta=0.176022,lxg=0.364039]:0.0320395,((0[theta=0.224286,lxg=0.156485]:0.0175487,8[theta=0.223313,lxg=0.157166]:0.0175487)[theta=0.631287,lxg=0.024042]:0.00758871,6[theta=0.337871,lxg=0.148799]:0.0251374)[theta=0.33847,lxg=0.040784]:0.00690208)[theta=0.209238,lxg=0.0636202]:0.00665587)[theta=0.560453,lxg=-0.138086]:0.01"); //HierarchyVisualizer a = new HierarchyVisualizer(" ((5[theta=0.121335,lxg=0.122437]:0.00742795,3[theta=0.0972485,lxg=0.152762]:0.00742795)[theta=0.490359,lxg=0.0746703]:0.0183076,2[theta=0.0866056,lxg=0.2295]:0.00993801)[theta=0.897783,lxg=0.0200762]:0.00901206"); HierarchyVisualizer a = new HierarchyVisualizer("((1:0.4,2:0.6):-0.4,3:0.4)"); a.setSize(800 ,600); JFrame f; f = new JFrame(); Container contentPane = f.getContentPane(); contentPane.add(a); f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); f.setSize(800,600); f.setVisible(true); a.fitToScreen(); } } // class HierarchyVisualizer
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow/AbstractGraphicalCommand.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * AbstractGraphicalCommand.java * Copyright (C) 2016 University of Waikato, Hamilton, New Zealand * */ package weka.gui.knowledgeflow; import weka.core.WekaException; /** * Base class for a graphical command * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public abstract class AbstractGraphicalCommand { /** A reference to the graphical environment */ protected Object m_graphicalEnv; /** Set a reference to the graphical environment */ public void setGraphicalEnvironment(Object env) { m_graphicalEnv = env; } /** * Get the name of this command * * @return the name of this command */ public abstract String getCommandName(); /** * Get a description of this command * * @return a description of this command */ public abstract String getCommandDescription(); /** * Perform the command * * @param commandArgs arguments to the command * @param <T> the return type * @return the result, or null if the command does not return a result * @throws WekaException if a problem occurs */ public abstract <T> T performCommand(Object... commandArgs) throws WekaException; }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow/AttributeSummaryPerspective.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * AttributeSummaryPerspective.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.gui.knowledgeflow; import weka.core.Attribute; import weka.core.Defaults; import weka.core.Environment; import weka.core.Instances; import weka.core.Settings; import weka.gui.AbstractPerspective; import weka.gui.AttributeVisualizationPanel; import weka.gui.PerspectiveInfo; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.List; import java.util.Vector; /** * Knowledge Flow perspective that provides a matrix of * AttributeVisualizationPanels * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ @PerspectiveInfo(ID = AttributeSummaryPerspective.AttDefaults.ID, title = "Attribute summary", toolTipText = "Histogram summary charts", iconPath = "weka/gui/knowledgeflow/icons/chart_bar.png") public class AttributeSummaryPerspective extends AbstractPerspective { private static final long serialVersionUID = 6697308901346612850L; /** The dataset being visualized */ protected Instances m_visualizeDataSet; /** Holds the grid of attribute histogram panels */ protected transient List<AttributeVisualizationPanel> m_plots; /** Index on which to color the plots */ protected int m_coloringIndex = -1; /** * Constructor */ public AttributeSummaryPerspective() { setLayout(new BorderLayout()); } /** * Setup the panel using the supplied settings * * @param settings the settings to use */ protected void setup(Settings settings) { removeAll(); if (m_visualizeDataSet == null) { return; } JScrollPane hp = makePanel(settings == null ? m_mainApplication.getApplicationSettings() : settings); add(hp, BorderLayout.CENTER); Vector<String> atts = new Vector<String>(); for (int i = 0; i < m_visualizeDataSet.numAttributes(); i++) { atts.add("(" + Attribute.typeToStringShort(m_visualizeDataSet.attribute(i)) + ") " + m_visualizeDataSet.attribute(i).name()); } final JComboBox<String> classCombo = new JComboBox<String>(); classCombo.setModel(new DefaultComboBoxModel<String>(atts)); if (atts.size() > 0) { if (m_visualizeDataSet.classIndex() < 0) { classCombo.setSelectedIndex(atts.size() - 1); } else { classCombo.setSelectedIndex(m_visualizeDataSet.classIndex()); } classCombo.setEnabled(true); for (int i = 0; i < m_plots.size(); i++) { m_plots.get(i).setColoringIndex(classCombo.getSelectedIndex()); } } JPanel comboHolder = new JPanel(); comboHolder.setLayout(new BorderLayout()); JPanel tempHolder = new JPanel(); tempHolder.setLayout(new BorderLayout()); tempHolder.add(new JLabel("Class: "), BorderLayout.WEST); tempHolder.add(classCombo, BorderLayout.EAST); comboHolder.add(tempHolder, BorderLayout.WEST); add(comboHolder, BorderLayout.NORTH); classCombo.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int selected = classCombo.getSelectedIndex(); if (selected >= 0) { for (int i = 0; i < m_plots.size(); i++) { m_plots.get(i).setColoringIndex(selected); } } } }); } /** * Makes the scrollable panel containing the grid of attribute * visualizations * * @param settings the settings to use * @return the configured panel */ private JScrollPane makePanel(Settings settings) { String fontFamily = this.getFont().getFamily(); Font newFont = new Font(fontFamily, Font.PLAIN, 10); JPanel hp = new JPanel(); hp.setFont(newFont); int gridWidth = settings.getSetting(AttDefaults.ID, AttDefaults.GRID_WIDTH_KEY, AttDefaults.GRID_WIDTH, Environment.getSystemWide()); int maxPlots = settings.getSetting(AttDefaults.ID, AttDefaults.MAX_PLOTS_KEY, AttDefaults.MAX_PLOTS, Environment.getSystemWide()); int numPlots = Math.min(m_visualizeDataSet.numAttributes(), maxPlots); int gridHeight = numPlots / gridWidth; if (numPlots % gridWidth != 0) { gridHeight++; } hp.setLayout(new GridLayout(gridHeight, 4)); m_plots = new ArrayList<AttributeVisualizationPanel>(); for (int i = 0; i < numPlots; i++) { JPanel temp = new JPanel(); temp.setLayout(new BorderLayout()); temp.setBorder(BorderFactory.createTitledBorder(m_visualizeDataSet .attribute(i).name())); AttributeVisualizationPanel ap = new AttributeVisualizationPanel(); m_plots.add(ap); ap.setInstances(m_visualizeDataSet); if (m_coloringIndex < 0 && m_visualizeDataSet.classIndex() >= 0) { ap.setColoringIndex(m_visualizeDataSet.classIndex()); } else { ap.setColoringIndex(m_coloringIndex); } temp.add(ap, BorderLayout.CENTER); ap.setAttribute(i); hp.add(temp); } Dimension d = new Dimension(830, gridHeight * 100); hp.setMinimumSize(d); hp.setMaximumSize(d); hp.setPreferredSize(d); JScrollPane scroller = new JScrollPane(hp); return scroller; } /** * Get the default settings for this perspective * * @return the default settings for this perspective */ @Override public Defaults getDefaultSettings() { return new AttDefaults(); } /** * Set the instances to visualize * * @param instances the instances the instances to visualize */ @Override public void setInstances(Instances instances) { m_visualizeDataSet = instances; setup(null); } /** * Set the instances to visualize * * @param instances the instances to visualize * @param settings the settings to use */ public void setInstances(Instances instances, Settings settings) { m_visualizeDataSet = instances; setup(settings); } /** * Returns true if this perspective is OK with being an active perspective - * i.e. the user can click on this perspective at this time in the perspective * toolbar. For example, a Perspective might return false from this method if * it needs a set of instances to operate but none have been supplied yet. * * @return true if this perspective can be active at the current time */ @Override public boolean okToBeActive() { return m_visualizeDataSet != null; } /** * Returns true, as this perspective does accept instances * * @return true */ @Override public boolean acceptsInstances() { return true; } /** * Default settings for the AttributeSummaryPerspective */ public static class AttDefaults extends Defaults { public static final String ID = "attributesummary"; protected static final Settings.SettingKey GRID_WIDTH_KEY = new Settings.SettingKey("weka.knowledgeflow.attributesummary.gridWidth", "Number of plots to display horizontally", ""); protected static final int GRID_WIDTH = 4; protected static final Settings.SettingKey MAX_PLOTS_KEY = new Settings.SettingKey("weka.knowledgeflow.attributesummary.maxPlots", "Maximum number of plots to render", ""); protected static final int MAX_PLOTS = 100; private static final long serialVersionUID = -32801466385262321L; public AttDefaults() { super(ID); m_defaults.put(GRID_WIDTH_KEY, GRID_WIDTH); m_defaults.put(MAX_PLOTS_KEY, MAX_PLOTS); } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow/BaseInteractiveViewer.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * BaseInteractiveViewer.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand */ package weka.gui.knowledgeflow; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.IOException; import javax.swing.*; import weka.core.Defaults; import weka.core.Settings; import weka.gui.SettingsEditor; import weka.knowledgeflow.steps.Step; /** * Base class than clients can extend when implementing * {@code StepInteractiveViewer}. Provides a {@code BorderLayout} with a close * button in the south position. Also provides a {@code addButton()} method that * subclasses can call to add additional buttons to the bottom of the window. If * the subclass returns a default settings object from the * {@code getDefaultSettings()} method, then a settings button will also appear * at the bottom of the window - this will pop up a settings editor. In this * case, the subclass should also override the no-op {@code applySettings()} * method in order to apply any settings changes that the user might have made * in the settings editor. There is also a {@code closePressed()} method that is * called when the close button is pressed. Subclasses can override this method * as necessary. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public abstract class BaseInteractiveViewer extends JPanel implements StepInteractiveViewer { private static final long serialVersionUID = -1191494001428785466L; /** Holds the step that this interactive viewer relates to */ protected Step m_step; /** The close button, for closing the viewer */ protected JButton m_closeBut = new JButton("Close"); /** Holds buttons displayed at the bottom of the window */ protected JPanel m_buttonHolder = new JPanel(new GridLayout()); /** The parent window */ protected Window m_parent; /** The main Knowledge Flow perspective */ protected MainKFPerspective m_mainPerspective; /** * Constructor */ public BaseInteractiveViewer() { super(); setLayout(new BorderLayout()); JPanel tempP = new JPanel(new BorderLayout()); tempP.add(m_buttonHolder, BorderLayout.WEST); add(tempP, BorderLayout.SOUTH); m_closeBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { close(); } }); addButton(m_closeBut); if (getDefaultSettings() != null) { JButton editSettings = new JButton("Settings"); editSettings.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // popup single settings editor // String ID = getDefaultSettings().getID(); try { if (SettingsEditor.showSingleSettingsEditor(getMainKFPerspective() .getMainApplication().getApplicationSettings(), getDefaultSettings().getID(), getViewerName(), BaseInteractiveViewer.this) == JOptionPane.OK_OPTION) { applySettings(getSettings()); } } catch (IOException ex) { getMainKFPerspective().getMainApplication().showErrorDialog(ex); } } }); addButton(editSettings); } } /** * Get the settings object for the application * * @return the settings object the settings object */ @Override public Settings getSettings() { return m_mainPerspective.getMainApplication().getApplicationSettings(); } /** * No-op implementation. Subcasses should override to be notified about, and * apply, any changed settings * * @param settings the settings object that might (or might not) have been * altered by the user */ public void applySettings(Settings settings) { } /** * Set the main knowledge flow perspective. Implementations can then access * application settings if necessary * * @param perspective the main knowledge flow perspective */ @Override public void setMainKFPerspective(MainKFPerspective perspective) { m_mainPerspective = perspective; m_mainPerspective.getMainApplication().getApplicationSettings() .applyDefaults(getDefaultSettings()); } /** * Get the main knowledge flow perspective. Implementations can the access * application settings if necessary * * @return */ @Override public MainKFPerspective getMainKFPerspective() { return m_mainPerspective; } /** * Set the step that owns this viewer. Implementations may want to access data * that has been computed by the step in question. * * @param theStep the step that owns this viewer */ @Override public void setStep(Step step) { m_step = step; } /** * Get the step that owns this viewer. * * @return the {@code Step} that owns this viewer */ public Step getStep() { return m_step; } /** * Called by the KnowledgeFlow application once the enclosing JFrame is * visible */ @Override public void nowVisible() { // no-op. Subclasses to override if necessary } /** * Set the parent window for this viewer * * @param parent the parent window */ @Override public void setParentWindow(Window parent) { m_parent = parent; m_parent.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { super.windowClosing(e); closePressed(); } }); } /** * Adds a button to the bottom of the window. * * @param button the button to add. */ public void addButton(JButton button) { m_buttonHolder.add(button); } private void close() { closePressed(); if (m_parent != null) { m_parent.dispose(); } } /** * Called when the close button is pressed. Subclasses should override if they * need to do something before the window is closed */ public void closePressed() { // subclasses to override if they need to do something before // the window is closed } /** * Get default settings for the viewer. Default implementation returns null, * i.e. no default settings. Subclasses can override if they have settings * (with default values) that the user can edit. * * @return the default settings for this viewer, or null if there are no * user-editable settings */ public Defaults getDefaultSettings() { // subclasses to override if they have default settings return null; } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow/DesignPanel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * DesignPanel.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.gui.knowledgeflow; import javax.swing.*; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; import java.awt.*; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Panel that contains the tree view of steps and the search * field. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class DesignPanel extends JPanel { /** * For serialization */ private static final long serialVersionUID = 3324733191950871564L; /** * Constructor * * @param stepTree the {@code StepTree} to display */ public DesignPanel(final StepTree stepTree) { super(); setLayout(new BorderLayout()); JScrollPane treeView = new JScrollPane(stepTree); setBorder(BorderFactory.createTitledBorder("Design")); add(treeView, BorderLayout.CENTER); final JTextField searchField = new JTextField(); add(searchField, BorderLayout.NORTH); searchField.setToolTipText("Search (clear field to reset)"); searchField.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { String searchTerm = searchField.getText(); List<DefaultMutableTreeNode> nonhits = new ArrayList<DefaultMutableTreeNode>(); List<DefaultMutableTreeNode> hits = new ArrayList<DefaultMutableTreeNode>(); DefaultTreeModel model = (DefaultTreeModel) stepTree .getModel(); model.reload(); // collapse all nodes first for (Map.Entry<String, DefaultMutableTreeNode> entry : stepTree .getNodeTextIndex() .entrySet()) { if (entry.getValue() instanceof InvisibleNode) { ((InvisibleNode) entry.getValue()).setVisible(true); } if (searchTerm != null && searchTerm.length() > 0) { if (entry.getKey().contains(searchTerm.toLowerCase())) { hits.add(entry.getValue()); } else { nonhits.add(entry.getValue()); } } } if (searchTerm == null || searchTerm.length() == 0) { model.reload(); // just reset everything } // if we have some hits then set all the non-hits to invisible if (hits.size() > 0) { for (DefaultMutableTreeNode h : nonhits) { if (h instanceof InvisibleNode) { ((InvisibleNode) h).setVisible(false); } } model.reload(); // collapse all the nodes first // expand all the hits for (DefaultMutableTreeNode h : hits) { TreeNode[] path = model.getPathToRoot(h); TreePath tpath = new TreePath(path); tpath = tpath.getParentPath(); stepTree.expandPath(tpath); } } } }); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow/GOEStepEditorDialog.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * GOEStepEditorDialog.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.gui.knowledgeflow; import weka.gui.GenericObjectEditor; import weka.gui.PropertySheetPanel; import weka.knowledgeflow.StepManagerImpl; import weka.knowledgeflow.steps.Step; import weka.knowledgeflow.steps.WekaAlgorithmWrapper; import javax.swing.*; import java.awt.*; /** * A step editor dialog that uses the GOE mechanism to provide property editors. * This class is used for editing a Step if it does not supply a custom editor. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class GOEStepEditorDialog extends StepEditorDialog { /** For serialization */ private static final long serialVersionUID = -2500973437145276268L; /** The {@code StepManager} for the step being edited */ protected StepManagerImpl m_manager; /** Holds a copy of the step (for restoring after cancel) */ protected Step m_stepOriginal; /** * Main editor for the step - used for editing properties of the step or * properties of a wrapped algorithm (if the step is a subclass of * {@code WekaAlgorithmWrapper}. */ protected PropertySheetPanel m_editor = new PropertySheetPanel(); /** * Secondary editor. Used for additional properties that belong to a Step that * extends {@code WekaAlgorithmWrapper} */ protected PropertySheetPanel m_secondaryEditor; /** The main holder panel */ protected JPanel m_editorHolder = new JPanel(); /** The panel that contains the main editor */ protected JPanel m_primaryEditorHolder = new JPanel(); /** * Constructor */ public GOEStepEditorDialog() { super(); } /** * Set the step to edit * * @param step the step to edit */ @Override protected void setStepToEdit(Step step) { // override (and don't call super) as // PropertySheetPanel will do a global info panel for us copyOriginal(step); addPrimaryEditorPanel(BorderLayout.NORTH); addSecondaryEditorPanel(BorderLayout.SOUTH); JScrollPane scrollPane = new JScrollPane(m_editorHolder); add(scrollPane, BorderLayout.CENTER); if (step.getDefaultSettings() != null) { addSettingsButton(); } layoutEditor(); } /** * Make a copy of the original step * * @param step the step to copy */ protected void copyOriginal(Step step) { m_manager = (StepManagerImpl) step.getStepManager(); m_stepToEdit = step; try { // copy the original config in case of cancel m_stepOriginal = (Step) GenericObjectEditor.makeCopy(step); } catch (Exception ex) { showErrorDialog(ex); } } /** * Adds the primary editor panel to the layout * * @param borderLayoutPos the position in a {@code BorderLayout} in which to * add the primary editor panel */ protected void addPrimaryEditorPanel(String borderLayoutPos) { String className = m_stepToEdit instanceof WekaAlgorithmWrapper ? ((WekaAlgorithmWrapper) m_stepToEdit) .getWrappedAlgorithm().getClass().getName() : m_stepToEdit.getClass().getName(); className = className.substring(className.lastIndexOf('.') + 1, className.length()); m_primaryEditorHolder.setLayout(new BorderLayout()); m_primaryEditorHolder.setBorder(BorderFactory.createTitledBorder(className + " options")); m_editor.setUseEnvironmentPropertyEditors(true); m_editor.setEnvironment(m_env); m_editor .setTarget(m_stepToEdit instanceof WekaAlgorithmWrapper ? ((WekaAlgorithmWrapper) m_stepToEdit) .getWrappedAlgorithm() : m_stepToEdit); m_editorHolder.setLayout(new BorderLayout()); if (m_editor.editableProperties() > 0 || m_editor.hasCustomizer()) { m_primaryEditorHolder.add(m_editor, BorderLayout.NORTH); m_editorHolder.add(m_primaryEditorHolder, borderLayoutPos); } else { JPanel about = m_editor.getAboutPanel(); m_editorHolder.add(about, borderLayoutPos); } } /** * Add the secondary editor panel * * @param borderLayoutPos the position in a {@code BorderLayout} in which to * add the secondary editor panel */ protected void addSecondaryEditorPanel(String borderLayoutPos) { if (m_stepToEdit instanceof WekaAlgorithmWrapper) { m_secondaryEditor = new PropertySheetPanel(false); m_secondaryEditor.setUseEnvironmentPropertyEditors(true); m_secondaryEditor.setBorder(BorderFactory .createTitledBorder("Additional options")); m_secondaryEditor.setEnvironment(m_env); m_secondaryEditor.setTarget(m_stepToEdit); if (m_secondaryEditor.editableProperties() > 0 || m_secondaryEditor.hasCustomizer()) { JPanel p = new JPanel(); p.setLayout(new BorderLayout()); p.add(m_secondaryEditor, BorderLayout.NORTH); m_editorHolder.add(p, borderLayoutPos); } } } /** * Called when the cancel button is pressed */ @Override protected void cancelPressed() { // restore original state if (m_stepOriginal != null && m_manager != null) { m_manager.setManagedStep(m_stepOriginal); } } /** * Called when the OK button is pressed */ @Override protected void okPressed() { if (m_editor.hasCustomizer()) { m_editor.closingOK(); } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow/GetPerspectiveNamesGraphicalCommand.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * GetPerspectiveNamesGraphicalCommand.java * Copyright (C) 2016 University of Waikato, Hamilton, New Zealand * */ package weka.gui.knowledgeflow; import weka.core.WekaException; import weka.gui.Perspective; import weka.knowledgeflow.KFDefaults; import java.util.ArrayList; import java.util.List; /** * Class implementing a command for getting the names of all visible * perspectives * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class GetPerspectiveNamesGraphicalCommand extends AbstractGraphicalCommand { /** Command ID */ public static final String GET_PERSPECTIVE_NAMES_KEY = "getPerspectiveNames"; /** The main KF perspective */ protected MainKFPerspective m_mainPerspective; /** * Set the graphical environment * * @param graphicalEnvironment the graphical environment */ @Override public void setGraphicalEnvironment(Object graphicalEnvironment) { super.setGraphicalEnvironment(graphicalEnvironment); if (graphicalEnvironment instanceof MainKFPerspective) { m_mainPerspective = (MainKFPerspective) graphicalEnvironment; } } /** * Get the name of the command * * @return the name of the command */ @Override public String getCommandName() { return GET_PERSPECTIVE_NAMES_KEY; } /** * Get the description of this command * * @return the description of this command */ @Override public String getCommandDescription() { return "Gets the names of of visible Knowledge Flow perspectives"; } /** * Execute the command * * @param commandArgs arguments to the command * @return null (no return value for this command) * @throws WekaException if a problem occurs */ @SuppressWarnings("unchecked") @Override public List<String> performCommand(Object... commandArgs) throws WekaException { if (m_mainPerspective == null) { throw new WekaException("This command cannot be applied in the " + "current graphical environment"); } List<Perspective> perspectives = m_mainPerspective.getMainApplication().getPerspectiveManager() .getVisiblePerspectives(); List<String> result = new ArrayList<>(); for (Perspective p : perspectives) { if (!p.getPerspectiveID() .equalsIgnoreCase(KFDefaults.MAIN_PERSPECTIVE_ID)) { result.add(p.getPerspectiveTitle()); } } 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/knowledgeflow/GraphicalEnvironmentCommandHandler.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * GraphicalEnvironmentCommandHandler.java * Copyright (C) 2016 University of Waikato, Hamilton, New Zealand * */ package weka.gui.knowledgeflow; import weka.core.WekaException; /** * Interface for graphical command handlers * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public interface GraphicalEnvironmentCommandHandler { /** * Attempt to perform a graphical command (if supported) in the current * graphical environment * * @param commandName the name of the command to execute * @param commandArgs the optional arguments * @return the result of performing the command, or null if the command does * not return a result * @throws WekaException if a problem occurs */ <T> T performCommand(String commandName, Object... commandArgs) throws WekaException; }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow/InvisibleNode.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * InvisibleNode.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.gui.knowledgeflow; import weka.core.WekaEnumeration; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreeNode; import java.util.Enumeration; /** * Subclass of {@code DefaultMutableTreeNode} that can hide itself in a * {@code JTree}. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class InvisibleNode extends DefaultMutableTreeNode { /** * For serialization */ private static final long serialVersionUID = -9064396835384819887L; /** True if the node is visible */ protected boolean m_isVisible; /** * Constructor */ public InvisibleNode() { this(null); } /** * Constructor for a new node that allows children and is visible * * @param userObject the user object to wrap at the node */ public InvisibleNode(Object userObject) { this(userObject, true, true); } /** * Constructor * * @param userObject the user object to wrap at the node * @param allowsChildren true if this node allows children (not a leaf) * @param isVisible true if this node is visible initially */ public InvisibleNode(Object userObject, boolean allowsChildren, boolean isVisible) { super(userObject, allowsChildren); this.m_isVisible = isVisible; } /** * Get a child node * * @param index the index of the node to get * @param filterIsActive true if the visible filter is active * @return a child node */ public TreeNode getChildAt(int index, boolean filterIsActive) { if (!filterIsActive) { return super.getChildAt(index); } if (children == null) { throw new ArrayIndexOutOfBoundsException("node has no children"); } int realIndex = -1; int visibleIndex = -1; Enumeration<TreeNode> e = new WekaEnumeration<TreeNode>(children); while (e.hasMoreElements()) { InvisibleNode node = (InvisibleNode)e.nextElement(); if (node.isVisible()) { visibleIndex++; } realIndex++; if (visibleIndex == index) { return (TreeNode) children.elementAt(realIndex); } } throw new ArrayIndexOutOfBoundsException("index unmatched"); } /** * Get the number of children nodes * * @param filterIsActive true if the visible filter is active (alters the * count according to visibility) * @return the number of child nodes */ public int getChildCount(boolean filterIsActive) { if (!filterIsActive) { return super.getChildCount(); } if (children == null) { return 0; } int count = 0; Enumeration<TreeNode> e = new WekaEnumeration<TreeNode>(children); while (e.hasMoreElements()) { InvisibleNode node = (InvisibleNode)e.nextElement(); if (node.isVisible()) { count++; } } return count; } /** * Set the visible status of this node * * @param visible true if this node should be visible */ public void setVisible(boolean visible) { this.m_isVisible = visible; } /** * Returns true if this node is visible * * @return true if this node is visible */ public boolean isVisible() { return m_isVisible; } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow/InvisibleTreeModel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * InvisibleTreeModel * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.gui.knowledgeflow; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeNode; /** * Subclass of {@code DefaultTreeModel} that contains {@code InvisibleNode}s. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class InvisibleTreeModel extends DefaultTreeModel { /** * For serialization */ private static final long serialVersionUID = 6940101211275068260L; /** True if the visibility filter is active */ protected boolean m_filterIsActive; /** * Constructor * * @param root the root of the tree */ public InvisibleTreeModel(TreeNode root) { this(root, false); } /** * Constuctor * * @param root the root of the tree * @param asksAllowsChildren asksAllowsChildren - a boolean, false if any node * can have children, true if each node is asked to see if it can * have children */ public InvisibleTreeModel(TreeNode root, boolean asksAllowsChildren) { this(root, false, false); } /** * Constructor * * @param root the root of the tree * @param asksAllowsChildren asksAllowsChildren - a boolean, false if any node * can have children, true if each node is asked to see if it can * have children * @param filterIsActive true if the visibility filter is active */ public InvisibleTreeModel(TreeNode root, boolean asksAllowsChildren, boolean filterIsActive) { super(root, asksAllowsChildren); this.m_filterIsActive = filterIsActive; } /** * Activate/deactivate the visibility filter * * @param newValue true if the visibility filter should be active */ public void activateFilter(boolean newValue) { m_filterIsActive = newValue; } /** * Return true if the visibility filter is active * * @return true if the visibility filter is active */ public boolean isActivatedFilter() { return m_filterIsActive; } @Override public Object getChild(Object parent, int index) { if (m_filterIsActive) { if (parent instanceof InvisibleNode) { return ((InvisibleNode) parent).getChildAt(index, m_filterIsActive); } } return ((TreeNode) parent).getChildAt(index); } @Override public int getChildCount(Object parent) { if (m_filterIsActive) { if (parent instanceof InvisibleNode) { return ((InvisibleNode) parent).getChildCount(m_filterIsActive); } } return ((TreeNode) parent).getChildCount(); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow/KFGUIConsts.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * KFGUIConsts.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.gui.knowledgeflow; /** * Class that holds constants that are used within the GUI side of the * Knowledge Flow. Housing them here allows classes outside of the GUI * part of the Knowledge Flow to access them without unecessary loading * of GUI-related classes. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class KFGUIConsts { /** Base path for step icons */ public static final String BASE_ICON_PATH = "weka/gui/knowledgeflow/icons/"; /** Flow file directory key */ public static final String FLOW_DIRECTORY_KEY = "Internal.knowledgeflow.directory"; /** Group identifier for built-in knowledge flow templates */ public static final String KF_BUILTIN_TEMPLATE_KEY = "weka.knowledgeflow.templates"; /** * Group identifier for plugin knowledge flow templates - packages supplying * templates should use this */ public static final String KF_PLUGIN_TEMPLATE_KEY = "weka.knowledgeflow.plugin.templates"; /** Props for templates */ protected static final String TEMPLATE_PROPERTY_FILE = "weka/gui/knowledgeflow/templates/templates.props"; /** Constant for an open dialog (same as JFileChooser.OPEN_DIALOG) */ public static final int OPEN_DIALOG = 0; /** Constant for a save dialog (same as JFileChooser.SAVE_DIALOG) */ public static final int SAVE_DIALOG = 1; }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow/KFGraphicalEnvironmentCommandHandler.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * KFGraphicalEnvironmentCommandHandler.java * Copyright (C) 2016 University of Waikato, Hamilton, New Zealand * */ package weka.gui.knowledgeflow; import weka.core.PluginManager; import weka.core.WekaException; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * Default Knowledge Flow graphical command handler * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class KFGraphicalEnvironmentCommandHandler implements GraphicalEnvironmentCommandHandler { /** The main perspective */ protected MainKFPerspective m_mainPerspective; /** All availabel commands */ protected Map<String, AbstractGraphicalCommand> m_commands = new HashMap<>(); static { // register built-in commands PluginManager.addPlugin("weka.gui.knowledgeflow.AbstractGraphicalCommand", "weka.gui.knowledgeflow.GetPerspectiveNamesGraphicalCommand", "weka.gui.knowledgeflow.GetPerspectiveNamesGraphicalCommand", true); PluginManager.addPlugin("weka.gui.knowledgeflow.AbstractGraphicalCommand", "weka.gui.knowledgeflow.SendToPerspectiveGraphicalCommand", "weka.gui.knowledgeflow.SendToPerspectiveGraphicalCommand", true); } /** * Constructor * * @param mainPerspective the main perspective of the GUI */ public KFGraphicalEnvironmentCommandHandler(MainKFPerspective mainPerspective) { m_mainPerspective = mainPerspective; // plugin commands Set<String> commands = PluginManager .getPluginNamesOfType("weka.gui.knowledgeflow.AbstractGraphicalCommand"); try { for (String commandClass : commands) { AbstractGraphicalCommand impl = (AbstractGraphicalCommand) PluginManager.getPluginInstance( "weka.gui.knowledgeflow.AbstractGraphicalCommand", commandClass); m_commands.put(impl.getCommandName(), impl); } } catch (Exception ex) { ex.printStackTrace(); } } /** * Perform a command * * @param commandName the name of the command to execute * @param commandArgs the optional arguments * @param <T> the type of the return value * @return a result, or null if the command does not return a result * @throws WekaException if a problem occurs */ @Override public <T> T performCommand(String commandName, Object... commandArgs) throws WekaException { AbstractGraphicalCommand command = m_commands.get(commandName); if (command != null) { command.setGraphicalEnvironment(m_mainPerspective); return command.performCommand(commandArgs); } else { throw new WekaException("Unknown graphical command '" + commandName + "'"); } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow/KnowledgeFlow.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * KnowledgeFlow.java * Copyright (C) 2016 University of Waikato, Hamilton, New Zealand * */ package weka.gui.knowledgeflow; import weka.core.Copyright; import weka.core.Version; import java.util.Arrays; import java.util.List; /** * Launcher class for the Weka Knowledge Flow. Displays a splash screen and * launches the actual Knowledge Flow app (KnowledgeFlowApp). * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class KnowledgeFlow { public static void main(String[] args) { List<String> message = Arrays.asList("WEKA Knowledge Flow", "Version " + Version.VERSION, "(c) " + Copyright.getFromYear() + " - " + Copyright.getToYear(), "The University of Waikato", "Hamilton, New Zealand"); weka.gui.SplashWindow.splash( ClassLoader.getSystemResource("weka/gui/weka_icon_new.png"), message); weka.gui.SplashWindow.invokeMain("weka.gui.knowledgeflow.KnowledgeFlowApp", args); weka.gui.SplashWindow.disposeSplash(); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow/KnowledgeFlowApp.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * KnowledgeFlowApp.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.gui.knowledgeflow; import weka.core.Defaults; import weka.core.Environment; import weka.core.Memory; import weka.core.PluginManager; import weka.core.Settings; import weka.gui.AbstractGUIApplication; import weka.gui.GenericObjectEditor; import weka.gui.LookAndFeel; import weka.gui.Perspective; import weka.gui.PerspectiveManager; import weka.knowledgeflow.BaseExecutionEnvironment; import weka.knowledgeflow.ExecutionEnvironment; import weka.knowledgeflow.KFDefaults; import javax.swing.*; import java.awt.*; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Set; /** * Main Knowledge Flow application class * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class KnowledgeFlowApp extends AbstractGUIApplication { private static final long serialVersionUID = -1460599392623083983L; /** for monitoring the Memory consumption */ protected static Memory m_Memory = new Memory(true); /** * variable for the KnowledgeFlowApp class which would be set to null by the * memory monitoring thread to free up some memory if we running out of memory */ protected static KnowledgeFlowApp m_kfApp; /** Settings for the Knowledge Flow */ protected Settings m_kfProperties; /** Main perspective of the Knowledge Flow */ protected MainKFPerspective m_mainPerspective; /** * Constructor */ public KnowledgeFlowApp() { this(true); } /** * Constructor * * @param layoutComponent true if the Knowledge Flow should layout the * application using the default layout - i.e. the perspectives * toolbar at the north of a {@code BorderLayout} and the * {@code PerspectiveManager} at the center */ public KnowledgeFlowApp(boolean layoutComponent) { super(layoutComponent, "weka.gui.knowledgeflow", "weka.gui.SimpleCLIPanel"); // add an initial "untitled" tab ((MainKFPerspective) m_perspectiveManager.getMainPerspective()) .addUntitledTab(); m_perspectiveManager .addSettingsMenuItemToProgramMenu(getApplicationSettings()); if (m_perspectiveManager .userRequestedPerspectiveToolbarVisibleOnStartup(getApplicationSettings())) { showPerspectivesToolBar(); } } /** * Get the name of this application * * @return the name of the application */ @Override public String getApplicationName() { return KFDefaults.APP_NAME; } /** * Get the ID of this application * * @return the ID of the application */ @Override public String getApplicationID() { return KFDefaults.APP_ID; } /** * Get the main perspective of this application * * @return the main perspective of the application */ @Override public Perspective getMainPerspective() { if (m_mainPerspective == null) { m_mainPerspective = new MainKFPerspective(); } return m_mainPerspective; } /** * Get the {@code PerspectiveManager} used by this application * * @return the {@code PerspectiveManager} */ @Override public PerspectiveManager getPerspectiveManager() { return m_perspectiveManager; } /** * Get the settings for this application * * @return the settings for this application */ @Override public Settings getApplicationSettings() { if (m_kfProperties == null) { m_kfProperties = new Settings("weka", KFDefaults.APP_ID); Defaults kfDefaults = new KnowledgeFlowGeneralDefaults(); String envName = m_kfProperties.getSetting(KFDefaults.APP_ID, KnowledgeFlowGeneralDefaults.EXECUTION_ENV_KEY, KnowledgeFlowGeneralDefaults.EXECUTION_ENV, Environment.getSystemWide()); try { ExecutionEnvironment envForDefaults = (ExecutionEnvironment) (envName .equals(BaseExecutionEnvironment.DESCRIPTION) ? new BaseExecutionEnvironment() : PluginManager.getPluginInstance( ExecutionEnvironment.class.getCanonicalName(), envName)); Defaults envDefaults = envForDefaults.getDefaultSettings(); if (envDefaults != null) { kfDefaults.add(envDefaults); } } catch (Exception ex) { ex.printStackTrace(); } m_kfProperties.applyDefaults(kfDefaults); } return m_kfProperties; } /** * Get the default settings for this application * * @return the default settings */ @Override public Defaults getApplicationDefaults() { return new KFDefaults(); } /** * Apply (changed) settings */ @Override public void settingsChanged() { boolean showTipText = getApplicationSettings().getSetting(KFDefaults.APP_ID, KFDefaults.SHOW_JTREE_TIP_TEXT_KEY, KFDefaults.SHOW_JTREE_GLOBAL_INFO_TIPS, Environment.getSystemWide()); GenericObjectEditor.setShowGlobalInfoToolTips(showTipText); m_mainPerspective.m_stepTree.setShowLeafTipText(showTipText); } /** * General default settings for the Knowledge Flow */ public static class KnowledgeFlowGeneralDefaults extends Defaults { private static final long serialVersionUID = 6957165806947500265L; public static final Settings.SettingKey LAF_KEY = new Settings.SettingKey( KFDefaults.APP_ID + ".lookAndFeel", "Look and feel for UI", "Note: a restart " + "is required for this setting ot come into effect"); public static final String LAF = ""; public static final Settings.SettingKey EXECUTION_ENV_KEY = new Settings.SettingKey(KFDefaults.APP_ID + ".exec_env", "Execution environment", "Executor for flow processes"); public static final String EXECUTION_ENV = BaseExecutionEnvironment.DESCRIPTION; public KnowledgeFlowGeneralDefaults() { super(KFDefaults.APP_ID); List<String> lafs = LookAndFeel.getAvailableLookAndFeelClasses(); lafs.add(0, "<use platform default>"); LAF_KEY.setPickList(lafs); m_defaults.put(LAF_KEY, LAF); m_defaults.put(KFDefaults.SHOW_JTREE_TIP_TEXT_KEY, KFDefaults.SHOW_JTREE_GLOBAL_INFO_TIPS); Set<String> execs = PluginManager.getPluginNamesOfType(ExecutionEnvironment.class .getCanonicalName()); List<String> execList = new LinkedList<String>(); // make sure the default is listed first execList.add(BaseExecutionEnvironment.DESCRIPTION); if (execs != null) { for (String e : execs) { if (!e.equals(BaseExecutionEnvironment.DESCRIPTION)) { execList.add(e); } } } EXECUTION_ENV_KEY.setPickList(execList); m_defaults.put(EXECUTION_ENV_KEY, EXECUTION_ENV); } } /** * Main method for launching this application * * @param args command line args */ public static void main(String[] args) { try { LookAndFeel.setLookAndFeel(KFDefaults.APP_ID, KFDefaults.APP_ID + ".lookAndFeel", KFDefaults.LAF); } catch (IOException ex) { ex.printStackTrace(); } weka.gui.GenericObjectEditor.determineClasses(); try { if (System.getProperty("os.name").contains("Mac")) { System.setProperty("apple.laf.useScreenMenuBar", "true"); } m_kfApp = new KnowledgeFlowApp(); if (args.length == 1) { File toLoad = new File(args[0]); if (toLoad.exists() && toLoad.isFile()) { ((MainKFPerspective) m_kfApp.getMainPerspective()).loadLayout(toLoad, false); } } final javax.swing.JFrame jf = new javax.swing.JFrame("Weka " + m_kfApp.getApplicationName()); jf.getContentPane().setLayout(new java.awt.BorderLayout()); Image icon = Toolkit.getDefaultToolkit().getImage( KnowledgeFlowApp.class.getClassLoader().getResource( "weka/gui/weka_icon_new_48.png")); jf.setIconImage(icon); jf.getContentPane().add(m_kfApp, BorderLayout.CENTER); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jf.pack(); m_kfApp.showMenuBar(jf); jf.setSize(1023, 768); jf.setVisible(true); // weird effect where, if there are more perspectives than would fit // in one row horizontally in the perspective manager, then the WrapLayout // does not wrap when the Frame is first pack()ed. No amount of // invalidating/revalidating/repainting components // and ancestors seems to make a difference. Resizing - even by one pixel // - // however, does force it to re-layout and wrap. Perhaps this is an OSX // bug... jf.setSize(1024, 768); Thread memMonitor = new Thread() { @Override public void run() { while (true) { // try { // System.out.println("Before sleeping."); // Thread.sleep(10); if (m_Memory.isOutOfMemory()) { // clean up jf.dispose(); m_kfApp = null; System.gc(); // display error System.err.println("\ndisplayed message:"); m_Memory.showOutOfMemory(); System.err.println("\nexiting"); System.exit(-1); } } } }; memMonitor.setPriority(Thread.MAX_PRIORITY); memMonitor.start(); } catch (Exception ex) { ex.printStackTrace(); } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow/LayoutPanel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * LayoutPanel.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.gui.knowledgeflow; import weka.core.*; import weka.core.converters.FileSourcedConverter; import weka.gui.Perspective; import weka.gui.knowledgeflow.VisibleLayout.LayoutOperation; import weka.gui.visualize.PrintablePanel; import weka.knowledgeflow.KFDefaults; import weka.knowledgeflow.StepManager; import weka.knowledgeflow.StepManagerImpl; import weka.knowledgeflow.steps.Loader; import weka.knowledgeflow.steps.Note; import javax.swing.*; import java.awt.BasicStroke; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Cursor; import java.awt.Dialog.ModalityType; import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Menu; import java.awt.MenuItem; import java.awt.Point; import java.awt.PopupMenu; import java.awt.RenderingHints; import java.awt.Stroke; 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.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Map.Entry; /** * Provides a panel just for laying out a Knowledge Flow graph. Also listens for * mouse events for editing the flow. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class LayoutPanel extends PrintablePanel { /** For serialization */ private static final long serialVersionUID = 4988098224376217099L; /** Grid spacing */ protected int m_gridSpacing; /** The flow contained in this LayoutPanel as a visible (graphical) flow */ protected VisibleLayout m_visLayout; protected int m_currentX; protected int m_currentY; protected int m_oldX; protected int m_oldY; /** Thread for loading data for perspectives */ protected Thread m_perspectiveDataLoadThread; /** * Constructor * * @param vis the {@code VisibleLayout} to display */ public LayoutPanel(VisibleLayout vis) { super(); m_visLayout = vis; setLayout(null); setupMouseListener(); setupMouseMotionListener(); m_gridSpacing = m_visLayout.getMainPerspective().getSetting(KFDefaults.GRID_SPACING_KEY, KFDefaults.GRID_SPACING); } /** * Configure mouse listener */ protected void setupMouseListener() { addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent me) { LayoutPanel.this.requestFocusInWindow(); double z = m_visLayout.getZoomSetting() / 100.0; double px = me.getX(); double py = me.getY(); py /= z; px /= z; if (m_visLayout.getMainPerspective().getPalleteSelectedStep() == null) { if (((me.getModifiers() & InputEvent.BUTTON1_MASK) == InputEvent.BUTTON1_MASK) && m_visLayout.getFlowLayoutOperation() == VisibleLayout.LayoutOperation.NONE) { StepVisual step = m_visLayout.findStep(new Point((int) px, (int) py)); if (step != null) { m_visLayout.setEditStep(step); m_oldX = (int) px; m_oldY = (int) py; m_visLayout.setFlowLayoutOperation(LayoutOperation.MOVING); } if (m_visLayout.getFlowLayoutOperation() != LayoutOperation.MOVING) { m_visLayout.setFlowLayoutOperation(LayoutOperation.SELECTING); m_oldX = (int) px; m_oldY = (int) py; m_currentX = m_oldX; m_currentY = m_oldY; Graphics2D gx = (Graphics2D) LayoutPanel.this.getGraphics(); gx.setXORMode(java.awt.Color.white); gx.dispose(); } } } } @Override public void mouseReleased(MouseEvent me) { LayoutPanel.this.requestFocusInWindow(); if (m_visLayout.getEditStep() != null && m_visLayout.getFlowLayoutOperation() == LayoutOperation.MOVING) { if (m_visLayout.getMainPerspective().getSnapToGrid()) { int x = snapToGrid(m_visLayout.getEditStep().getX()); int y = snapToGrid(m_visLayout.getEditStep().getY()); m_visLayout.getEditStep().setX(x); m_visLayout.getEditStep().setY(y); snapSelectedToGrid(); } m_visLayout.setEditStep(null); revalidate(); repaint(); m_visLayout.setFlowLayoutOperation(LayoutOperation.NONE); } if (m_visLayout.getFlowLayoutOperation() == LayoutOperation.SELECTING) { revalidate(); repaint(); m_visLayout.setFlowLayoutOperation(LayoutOperation.NONE); double z = m_visLayout.getZoomSetting() / 100.0; double px = me.getX(); double py = me.getY(); py /= z; px /= z; highlightSubFlow(m_currentX, m_currentY, (int) px, (int) py); } } @Override public void mouseClicked(MouseEvent me) { LayoutPanel.this.requestFocusInWindow(); Point p = me.getPoint(); Point np = new Point(); double z = m_visLayout.getZoomSetting() / 100.0; double px = me.getX(); double py = me.getY(); px /= z; py /= z; np.setLocation(p.getX() / z, p.getY() / z); StepVisual step = m_visLayout.findStep(np); if (m_visLayout.getFlowLayoutOperation() == LayoutOperation.ADDING || m_visLayout.getFlowLayoutOperation() == LayoutOperation.NONE) { // try and popup a context sensitive menu if we've been // clicked over a step if (step != null) { if (me.getClickCount() == 2) { if (!step.getStepManager().isStepBusy() && !m_visLayout.isExecuting()) { popupStepEditorDialog(step); } } else if ((me.getModifiers() & InputEvent.BUTTON1_MASK) != InputEvent.BUTTON1_MASK || me.isAltDown()) { stepContextualMenu(step, (int) (p.getX() / z), (int) (p.getY() / z)); return; } else { // just select this step List<StepVisual> v = m_visLayout.getSelectedSteps(); if (!me.isShiftDown()) { v = new ArrayList<StepVisual>(); } v.add(step); m_visLayout.setSelectedSteps(v); return; } } else { if ((me.getModifiers() & InputEvent.BUTTON1_MASK) != InputEvent.BUTTON1_MASK || me.isAltDown()) { if (!m_visLayout.isExecuting()) { canvasContextualMenu((int) px, (int) py); revalidate(); repaint(); m_visLayout.getMainPerspective().notifyIsDirty(); } return; } else if (m_visLayout.getMainPerspective() .getPalleteSelectedStep() != null) { // if there is a user-selected step from the design palette then // add the step // snap to grid double x = px; double y = py; if (m_visLayout.getMainPerspective().getSnapToGrid()) { x = snapToGrid((int) x); y = snapToGrid((int) y); } m_visLayout.addUndoPoint(); m_visLayout.addStep(m_visLayout.getMainPerspective() .getPalleteSelectedStep(), (int) x, (int) y); m_visLayout.getMainPerspective().clearDesignPaletteSelection(); m_visLayout.getMainPerspective().setPalleteSelectedStep(null); m_visLayout.setFlowLayoutOperation(LayoutOperation.NONE); m_visLayout.setEdited(true); } } revalidate(); repaint(); m_visLayout.getMainPerspective().notifyIsDirty(); } if (m_visLayout.getFlowLayoutOperation() == LayoutOperation.PASTING && m_visLayout.getMainPerspective().getPasteBuffer().length() > 0) { try { m_visLayout.pasteFromClipboard((int) px, (int) py); } catch (WekaException e) { m_visLayout.getMainPerspective().showErrorDialog(e); } m_visLayout.setFlowLayoutOperation(LayoutOperation.NONE); m_visLayout.getMainPerspective().setCursor( Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); return; } if (m_visLayout.getFlowLayoutOperation() == LayoutOperation.CONNECTING) { // turn off connector points and remove connecting line repaint(); for (StepVisual v : m_visLayout.getRenderGraph()) { v.setDisplayConnectors(false); } if (step != null && step.getStepManager() != m_visLayout.getEditStep() .getStepManager()) { // connection is valid because only valid connections will // have appeared in the contextual popup m_visLayout.addUndoPoint(); m_visLayout.connectSteps( m_visLayout.getEditStep().getStepManager(), step.getStepManager(), m_visLayout.getEditConnection()); m_visLayout.setEdited(true); repaint(); } m_visLayout.setFlowLayoutOperation(LayoutOperation.NONE); m_visLayout.setEditStep(null); m_visLayout.setEditConnection(null); } if (m_visLayout.getSelectedSteps().size() > 0) { m_visLayout.setSelectedSteps(new ArrayList<StepVisual>()); } } }); } /** * Configure mouse motion listener */ protected void setupMouseMotionListener() { addMouseMotionListener(new MouseMotionAdapter() { @Override public void mouseDragged(MouseEvent me) { double z = m_visLayout.getZoomSetting() / 100.0; double px = me.getX(); double py = me.getY(); px /= z; py /= z; if (m_visLayout.getEditStep() != null && m_visLayout.getFlowLayoutOperation() == LayoutOperation.MOVING) { int deltaX = (int) px - m_oldX; int deltaY = (int) py - m_oldY; m_visLayout.getEditStep().setX( m_visLayout.getEditStep().getX() + deltaX); m_visLayout.getEditStep().setY( m_visLayout.getEditStep().getY() + deltaY); for (StepVisual v : m_visLayout.getSelectedSteps()) { if (v != m_visLayout.getEditStep()) { v.setX(v.getX() + deltaX); v.setY(v.getY() + deltaY); } } repaint(); m_oldX = (int) px; m_oldY = (int) py; m_visLayout.setEdited(true); } if (m_visLayout.getFlowLayoutOperation() == LayoutOperation.SELECTING) { repaint(); m_oldX = (int) px; m_oldY = (int) py; } } @Override public void mouseMoved(MouseEvent me) { double z = m_visLayout.getZoomSetting() / 100.0; double px = me.getX(); double py = me.getY(); px /= z; py /= z; if (m_visLayout.getFlowLayoutOperation() == LayoutOperation.CONNECTING) { repaint(); m_oldX = (int) px; m_oldY = (int) py; } } }); } @Override public void paintComponent(Graphics gx) { Color backG = m_visLayout.getMainPerspective().getSetting(KFDefaults.LAYOUT_COLOR_KEY, KFDefaults.LAYOUT_COLOR); if (!backG.equals(getBackground())) { setBackground(backG); } double lz = m_visLayout.getZoomSetting() / 100.0; ((Graphics2D) gx).scale(lz, lz); if (m_visLayout.getZoomSetting() < 100) { ((Graphics2D) gx).setStroke(new BasicStroke(2)); } super.paintComponent(gx); ((Graphics2D) gx).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); ((Graphics2D) gx).setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_GASP); paintStepLabels(gx); paintConnections(gx); if (m_visLayout.getFlowLayoutOperation() == LayoutOperation.CONNECTING) { gx.drawLine(m_currentX, m_currentY, m_oldX, m_oldY); } else if (m_visLayout.getFlowLayoutOperation() == LayoutOperation.SELECTING) { gx.drawRect(m_currentX < m_oldX ? m_currentX : m_oldX, m_currentY < m_oldY ? m_currentY : m_oldY, Math.abs(m_oldX - m_currentX), Math.abs(m_oldY - m_currentY)); } if (m_visLayout.getMainPerspective().getSetting(KFDefaults.SHOW_GRID_KEY, KFDefaults.SHOW_GRID)) { Color gridColor = m_visLayout.getMainPerspective().getSetting(KFDefaults.GRID_COLOR_KEY, KFDefaults.GRID_COLOR); gx.setColor(gridColor); int gridSpacing = m_visLayout.getMainPerspective().getSetting( KFDefaults.GRID_SPACING_KEY, KFDefaults.GRID_SPACING); int layoutWidth = m_visLayout.getMainPerspective().getSetting( KFDefaults.LAYOUT_WIDTH_KEY, KFDefaults.LAYOUT_WIDTH); int layoutHeight = m_visLayout.getMainPerspective().getSetting( KFDefaults.LAYOUT_HEIGHT_KEY, KFDefaults.LAYOUT_HEIGHT); Stroke original = ((Graphics2D) gx).getStroke(); Stroke dashed = new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0, new float[] { 3 }, 0); ((Graphics2D) gx).setStroke(dashed); for (int i = gridSpacing; i < layoutWidth / lz; i += gridSpacing) { gx.drawLine(i, 0, i, (int) (layoutHeight / lz)); } for (int i = gridSpacing; i < layoutHeight / lz; i += gridSpacing) { gx.drawLine(0, i, (int) (layoutWidth / lz), i); } ((Graphics2D) gx).setStroke(original); } } @Override public void doLayout() { super.doLayout(); for (StepVisual v : m_visLayout.getRenderGraph()) { Dimension d = v.getPreferredSize(); v.setBounds(v.getX(), v.getY(), d.width, d.height); v.revalidate(); } } /** * Render the labels for each step in the layout * * @param gx the graphics context to use */ protected void paintStepLabels(Graphics gx) { gx.setFont(new Font(null, Font.PLAIN, m_visLayout.getMainPerspective() .getSetting(KFDefaults.STEP_LABEL_FONT_SIZE_KEY, KFDefaults.STEP_LABEL_FONT_SIZE))); FontMetrics fm = gx.getFontMetrics(); int hf = fm.getAscent(); for (StepVisual v : m_visLayout.getRenderGraph()) { if (!v.getDisplayStepLabel()) { continue; } int cx = v.getX(); int cy = v.getY(); int width = v.getWidth(); int height = v.getHeight(); String label = v.getStepName(); int labelwidth = fm.stringWidth(label); if (labelwidth < width) { gx.drawString(label, (cx + (width / 2)) - (labelwidth / 2), cy + height + hf + 2); } else { // split label // find mid point int mid = label.length() / 2; // look for split point closest to the mid int closest = label.length(); int closestI = -1; for (int z = 0; z < label.length(); z++) { if (label.charAt(z) < 'a') { if (Math.abs(mid - z) < closest) { closest = Math.abs(mid - z); closestI = z; } } } if (closestI != -1) { String left = label.substring(0, closestI); String right = label.substring(closestI, label.length()); if (left.length() > 1 && right.length() > 1) { gx.drawString(left, (cx + (width / 2)) - (fm.stringWidth(left) / 2), cy + height + (hf * 1) + 2); gx.drawString(right, (cx + (width / 2)) - (fm.stringWidth(right) / 2), cy + height + (hf * 2) + 2); } else { gx.drawString(label, (cx + (width / 2)) - (fm.stringWidth(label) / 2), cy + height + (hf * 1) + 2); } } else { gx.drawString(label, (cx + (width / 2)) - (fm.stringWidth(label) / 2), cy + height + (hf * 1) + 2); } } } } /** * Render the connections between steps * * @param gx the graphics object to use */ protected void paintConnections(Graphics gx) { for (StepVisual stepVis : m_visLayout.getRenderGraph()) { Map<String, List<StepManager>> outConns = stepVis.getStepManager().getOutgoingConnections(); if (outConns.size() > 0) { List<String> generatableOutputConnections = stepVis.getStepManager().getStepOutgoingConnectionTypes(); // iterate over the outgoing connections and paint // with color according to what is present in // generatableOutputConnections int count = 0; for (Entry<String, List<StepManager>> e : outConns.entrySet()) { String connName = e.getKey(); List<StepManager> connectedSteps = e.getValue(); if (connectedSteps.size() > 0) { int sX = stepVis.getX(); int sY = stepVis.getY(); int sWidth = stepVis.getWidth(); int sHeight = stepVis.getHeight(); for (StepManager target : connectedSteps) { StepManagerImpl targetI = (StepManagerImpl) target; int tX = targetI.getStepVisual().getX(); int tY = targetI.getStepVisual().getY(); int tWidth = targetI.getStepVisual().getWidth(); int tHeight = targetI.getStepVisual().getHeight(); Point bestSourcePoint = stepVis.getClosestConnectorPoint(new Point(tX + (tWidth / 2), tY + (tHeight / 2))); Point bestTargetPoint = targetI.getStepVisual().getClosestConnectorPoint( new Point(sX + (sWidth / 2), sY + (sHeight / 2))); gx.setColor(Color.red); boolean active = generatableOutputConnections == null || !generatableOutputConnections.contains(connName) ? false : true; if (!active) { gx.setColor(Color.gray); } gx.drawLine((int) bestSourcePoint.getX(), (int) bestSourcePoint.getY(), (int) bestTargetPoint.getX(), (int) bestTargetPoint.getY()); // paint an arrow head double angle; try { double a = (bestSourcePoint.getY() - bestTargetPoint.getY()) / (bestSourcePoint.getX() - bestTargetPoint.getX()); angle = Math.atan(a); } catch (Exception ex) { angle = Math.PI / 2; } Point arrowstart = new Point(bestTargetPoint.x, bestTargetPoint.y); Point arrowoffset = new Point((int) (7 * Math.cos(angle)), (int) (7 * Math.sin(angle))); Point arrowend; if (bestSourcePoint.getX() >= bestTargetPoint.getX()) { arrowend = new Point(arrowstart.x + arrowoffset.x, arrowstart.y + arrowoffset.y); } else { arrowend = new Point(arrowstart.x - arrowoffset.x, arrowstart.y - arrowoffset.y); } int xs[] = { arrowstart.x, arrowend.x + (int) (7 * Math.cos(angle + (Math.PI / 2))), arrowend.x + (int) (7 * Math.cos(angle - (Math.PI / 2))) }; int ys[] = { arrowstart.y, arrowend.y + (int) (7 * Math.sin(angle + (Math.PI / 2))), arrowend.y + (int) (7 * Math.sin(angle - (Math.PI / 2))) }; gx.fillPolygon(xs, ys, 3); // paint the connection name int midx = (int) bestSourcePoint.getX(); midx += (int) ((bestTargetPoint.getX() - bestSourcePoint.getX()) / 2); int midy = (int) bestSourcePoint.getY(); midy += (int) ((bestTargetPoint.getY() - bestSourcePoint.getY()) / 2) - 2; gx.setColor((active) ? Color.blue : Color.gray); // check to see if there is more than one connection // between the source and target if (m_visLayout.previousConn(outConns, targetI, count)) { midy -= 15; } gx.drawString(connName, midx, midy); } } count++; } } } } /** * Popup a contextual menu on the canvas that provides options for cutting, * pasting, deleting selected steps etc. * * @param x the x coordinate to pop up at * @param y the y coordinate to pop up at */ protected void canvasContextualMenu(final int x, final int y) { Map<String, List<StepManagerImpl[]>> closestConnections = m_visLayout.findClosestConnections(new Point(x, y), 10); PopupMenu contextualMenu = new PopupMenu(); int menuItemCount = 0; if (m_visLayout.getSelectedSteps().size() > 0) { MenuItem snapItem = new MenuItem("Snap selected to grid"); snapItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { snapSelectedToGrid(); } }); contextualMenu.add(snapItem); menuItemCount++; MenuItem copyItem = new MenuItem("Copy selected"); copyItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { m_visLayout.copySelectedStepsToClipboard(); m_visLayout.setSelectedSteps(new ArrayList<StepVisual>()); } catch (WekaException ex) { m_visLayout.getMainPerspective().showErrorDialog(ex); } } }); contextualMenu.add(copyItem); menuItemCount++; MenuItem cutItem = new MenuItem("Cut selected"); cutItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { m_visLayout.copySelectedStepsToClipboard(); m_visLayout.removeSelectedSteps(); } catch (WekaException ex) { m_visLayout.getMainPerspective().showErrorDialog(ex); } } }); contextualMenu.add(cutItem); menuItemCount++; MenuItem deleteSelected = new MenuItem("Delete selected"); deleteSelected.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { m_visLayout.removeSelectedSteps(); } catch (WekaException ex) { m_visLayout.getMainPerspective().showErrorDialog(ex); } } }); contextualMenu.add(deleteSelected); menuItemCount++; } if (m_visLayout.getMainPerspective().getPasteBuffer() != null && m_visLayout.getMainPerspective().getPasteBuffer().length() > 0) { contextualMenu.addSeparator(); menuItemCount++; MenuItem pasteItem = new MenuItem("Paste"); pasteItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { m_visLayout.pasteFromClipboard(x, y); } catch (WekaException ex) { m_visLayout.getMainPerspective().showErrorDialog(ex); } } }); contextualMenu.add(pasteItem); menuItemCount++; } if (closestConnections.size() > 0) { contextualMenu.addSeparator(); menuItemCount++; MenuItem deleteConnection = new MenuItem("Delete connection:"); deleteConnection.setEnabled(false); contextualMenu.insert(deleteConnection, menuItemCount++); for (Map.Entry<String, List<StepManagerImpl[]>> e : closestConnections .entrySet()) { final String connName = e.getKey(); for (StepManagerImpl[] cons : e.getValue()) { final StepManagerImpl source = cons[0]; final StepManagerImpl target = cons[1]; MenuItem deleteItem = new MenuItem(connName + "-->" + target.getName()); deleteItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m_visLayout.addUndoPoint(); source.disconnectStepWithConnection(target.getManagedStep(), connName); target.disconnectStepWithConnection(source.getManagedStep(), connName); if (m_visLayout.getSelectedSteps().size() > 0) { m_visLayout.setSelectedSteps(new ArrayList<StepVisual>()); } m_visLayout.setEdited(true); revalidate(); repaint(); m_visLayout.getMainPerspective().notifyIsDirty(); } }); contextualMenu.add(deleteItem); menuItemCount++; } } } if (menuItemCount > 0) { contextualMenu.addSeparator(); menuItemCount++; } MenuItem noteItem = new MenuItem("New note"); noteItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { initiateAddNote(); } }); contextualMenu.add(noteItem); this.add(contextualMenu); // make sure that popup location takes current scaling into account double z = m_visLayout.getZoomSetting() / 100.0; double px = x * z; double py = y * z; contextualMenu.show(this, (int) px, (int) py); } /** * Initiate the process of adding a note to the canvas */ protected void initiateAddNote() { Note n = new Note(); StepManagerImpl noteManager = new StepManagerImpl(n); StepVisual noteVisual = StepVisual.createVisual(noteManager); m_visLayout.getMainPerspective().setPalleteSelectedStep( noteVisual.getStepManager()); m_visLayout.setFlowLayoutOperation(LayoutOperation.ADDING); m_visLayout.getMainPerspective().setCursor( Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR)); } /** * Popup the contextual menu for when a step is right clicked on * * @param step the step that was clicked on * @param x the x coordiante to pop up at * @param y the y coordinate to pop up at */ protected void stepContextualMenu(final StepVisual step, final int x, final int y) { PopupMenu stepContextMenu = new PopupMenu(); boolean executing = m_visLayout.isExecuting(); int menuItemCount = 0; MenuItem edit = new MenuItem("Edit:"); edit.setEnabled(false); stepContextMenu.insert(edit, menuItemCount); menuItemCount++; if (m_visLayout.getSelectedSteps().size() > 0) { MenuItem copyItem = new MenuItem("Copy"); copyItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { m_visLayout.copySelectedStepsToClipboard(); } catch (WekaException ex) { m_visLayout.getMainPerspective().showErrorDialog(ex); } m_visLayout.setSelectedSteps(new ArrayList<StepVisual>()); } }); stepContextMenu.add(copyItem); copyItem.setEnabled(!executing); menuItemCount++; } MenuItem deleteItem = new MenuItem("Delete"); deleteItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m_visLayout.addUndoPoint(); try { m_visLayout.removeStep(step); } catch (WekaException ex) { m_visLayout.getMainPerspective().showErrorDialog(ex); } // step.getStepManager().clearAllConnections(); // LayoutPanel.this.remove(step); String key = step.getStepName() + "$" + step.getStepManager().getManagedStep().hashCode(); m_visLayout.getLogPanel().statusMessage(key + "|remove"); LayoutPanel.this.revalidate(); LayoutPanel.this.repaint(); m_visLayout.setEdited(true); m_visLayout.getMainPerspective().notifyIsDirty(); m_visLayout .getMainPerspective() .getMainToolBar() .enableWidget( MainKFPerspectiveToolBar.Widgets.SELECT_ALL_BUTTON.toString(), m_visLayout.getSelectedSteps().size() > 0); } }); deleteItem.setEnabled(!executing); stepContextMenu.add(deleteItem); menuItemCount++; MenuItem nameItem = new MenuItem("Set name..."); nameItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String oldName = step.getStepName(); String name = JOptionPane.showInputDialog(m_visLayout.getMainPerspective(), "Enter a name for this step", oldName); if (name != null) { m_visLayout.renameStep(oldName, name); m_visLayout.setEdited(true); revalidate(); repaint(); } } }); nameItem.setEnabled(!executing); stepContextMenu.add(nameItem); menuItemCount++; MenuItem configItem = new MenuItem("Configure..."); configItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { popupStepEditorDialog(step); m_visLayout.getMainPerspective().notifyIsDirty(); } }); configItem.setEnabled(!executing); stepContextMenu.add(configItem); menuItemCount++; // connections List<String> outgoingConnTypes = step.getStepManager().getManagedStep().getOutgoingConnectionTypes(); if (outgoingConnTypes != null && outgoingConnTypes.size() > 0) { MenuItem connections = new MenuItem("Connections:"); connections.setEnabled(false); stepContextMenu.insert(connections, menuItemCount); menuItemCount++; for (final String connType : outgoingConnTypes) { MenuItem conItem = new MenuItem(connType); conItem.setEnabled(!executing); conItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { initiateConnection(connType, step, x, y); m_visLayout.getMainPerspective().notifyIsDirty(); } }); stepContextMenu.add(conItem); menuItemCount++; } } // Any interactive views? Map<String, String> interactiveViews = step.getStepManager().getManagedStep().getInteractiveViewers(); Map<String, StepInteractiveViewer> interactiveViewsImpls = step.getStepManager().getManagedStep().getInteractiveViewersImpls(); if (interactiveViews != null && interactiveViews.size() > 0) { MenuItem actions = new MenuItem("Actions:"); actions.setEnabled(false); stepContextMenu.insert(actions, menuItemCount++); for (Map.Entry<String, String> e : interactiveViews.entrySet()) { String command = e.getKey(); String viewerClassName = e.getValue(); addInteractiveViewMenuItem(step, e.getKey(), !executing, e.getValue(), null, stepContextMenu); menuItemCount++; } } else if (interactiveViewsImpls != null && interactiveViewsImpls.size() > 0) { MenuItem actions = new MenuItem("Actions:"); actions.setEnabled(false); stepContextMenu.insert(actions, menuItemCount++); for (Map.Entry<String, StepInteractiveViewer> e : interactiveViewsImpls .entrySet()) { String command = e.getKey(); StepInteractiveViewer impl = e.getValue(); addInteractiveViewMenuItem(step, e.getKey(), !executing, null, impl, stepContextMenu); menuItemCount++; } } // perspective stuff... final List<Perspective> perspectives = m_visLayout.getMainPerspective().getMainApplication() .getPerspectiveManager().getVisiblePerspectives(); if (perspectives.size() > 0 && step.getStepManager().getManagedStep() instanceof Loader) { final weka.core.converters.Loader theLoader = ((Loader) step.getStepManager().getManagedStep()).getLoader(); boolean ok = true; if (theLoader instanceof FileSourcedConverter) { String fileName = ((FileSourcedConverter) theLoader).retrieveFile().getPath(); fileName = m_visLayout.environmentSubstitute(fileName); File tempF = new File(fileName); String fileNameFixedPathSep = fileName.replace(File.separatorChar, '/'); if (!tempF.isFile() && this.getClass().getClassLoader().getResource(fileNameFixedPathSep) == null) { ok = false; } } if (ok) { stepContextMenu.addSeparator(); menuItemCount++; if (perspectives.size() > 1) { MenuItem sendToAllPerspectives = new MenuItem("Send to all perspectives"); menuItemCount++; sendToAllPerspectives.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { loadDataAndSendToPerspective(theLoader, perspectives, -1); } }); stepContextMenu.add(sendToAllPerspectives); } Menu sendToPerspective = new Menu("Send to perspective..."); stepContextMenu.add(sendToPerspective); menuItemCount++; for (int i = 0; i < perspectives.size(); i++) { final int pIndex = i; if (perspectives.get(i).acceptsInstances() && !perspectives.get(i).getPerspectiveID() .equalsIgnoreCase(KFDefaults.MAIN_PERSPECTIVE_ID)) { String pName = perspectives.get(i).getPerspectiveTitle(); final MenuItem pI = new MenuItem(pName); pI.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { loadDataAndSendToPerspective(theLoader, perspectives, pIndex); } }); sendToPerspective.add(pI); } } } } if (menuItemCount > 0) { // make sure that popup location takes current scaling into account double z = m_visLayout.getZoomSetting() / 100.0; double px = x * z; double py = y * z; this.add(stepContextMenu); stepContextMenu.show(this, (int) px, (int) py); } } private synchronized void loadDataAndSendToPerspective( final weka.core.converters.Loader loader, final List<Perspective> perspectives, final int perspectiveIndex) { if (m_perspectiveDataLoadThread == null) { m_perspectiveDataLoadThread = new Thread() { @Override public void run() { try { if (loader instanceof EnvironmentHandler) { ((EnvironmentHandler) loader).setEnvironment(m_visLayout .getEnvironment()); loader.reset(); } m_visLayout.getLogPanel().statusMessage( "@!@[KnowledgeFlow]|Sending data to perspective(s)..."); Instances data = loader.getDataSet(); if (data != null) { m_visLayout.getMainPerspective().getMainApplication() .showPerspectivesToolBar(); // need to disable all the perspective buttons on the toolbar /* * m_visLayout.getMainPerspective().getMainApplication() * .getPerspectiveManager().disableAllPerspectiveTabs(); */ if (perspectiveIndex < 0) { // send to all for (Perspective p : perspectives) { if (p.acceptsInstances()) { p.setInstances(data); m_visLayout.getMainPerspective().getMainApplication() .getPerspectiveManager() .setEnablePerspectiveTab(p.getPerspectiveID(), true); } } } else { perspectives.get(perspectiveIndex).setInstances(data); m_visLayout .getMainPerspective() .getMainApplication() .getPerspectiveManager() .setActivePerspective( perspectives.get(perspectiveIndex).getPerspectiveID()); m_visLayout .getMainPerspective() .getMainApplication() .getPerspectiveManager() .setEnablePerspectiveTab( perspectives.get(perspectiveIndex).getPerspectiveID(), true); } } } catch (Exception ex) { m_visLayout.getMainPerspective().showErrorDialog(ex); } finally { // re-enable the perspective buttons /* * m_visLayout.getMainPerspective().getMainApplication() * .getPerspectiveManager().enableAllPerspectiveTabs(); */ m_perspectiveDataLoadThread = null; m_visLayout.getLogPanel().statusMessage("@!@[KnowledgeFlow]|OK"); } } }; m_perspectiveDataLoadThread.setPriority(Thread.MIN_PRIORITY); m_perspectiveDataLoadThread.start(); } } /** * Initiate the process of connecting two steps. * * @param connType the type of the connection to create * @param source the source step of the connection * @param x the x coordinate at which the connection starts * @param y the y coordinate at which the connection starts */ protected void initiateConnection(String connType, StepVisual source, int x, int y) { // unselect any selected steps on the layaout if (m_visLayout.getSelectedSteps().size() > 0) { m_visLayout.setSelectedSteps(new ArrayList<StepVisual>()); } List<StepManagerImpl> connectableForConnType = m_visLayout.findStepsThatCanAcceptConnection(connType); for (StepManagerImpl sm : connectableForConnType) { sm.getStepVisual().setDisplayConnectors(true); } if (connectableForConnType.size() > 0) { source.setDisplayConnectors(true); m_visLayout.setEditStep(source); m_visLayout.setEditConnection(connType); Point closest = source.getClosestConnectorPoint(new Point(x, y)); m_currentX = (int) closest.getX(); m_currentY = (int) closest.getY(); m_oldX = m_currentX; m_oldY = m_currentY; Graphics2D gx = (Graphics2D) this.getGraphics(); gx.setXORMode(java.awt.Color.white); gx.drawLine(m_currentX, m_currentY, m_currentX, m_currentY); gx.dispose(); m_visLayout.setFlowLayoutOperation(LayoutOperation.CONNECTING); } revalidate(); repaint(); m_visLayout.getMainPerspective().notifyIsDirty(); } /** * Add a menu item to a contextual menu for accessing any interactive viewers * that a step might provide * * @param step the step in question * @param entryText the text of the menu entry * @param enabled true if the menu entry is to be enabled * @param viewerClassName the fully qualified name of the viewer that is * associated with the menu entry * @param viewerImpl an instance of the viewer itself. If null, then the fully * qualified viewer class name will be used to instantiate an * instance * @param stepContextMenu the menu to add the item to */ protected void addInteractiveViewMenuItem(final StepVisual step, String entryText, boolean enabled, final String viewerClassName, final StepInteractiveViewer viewerImpl, PopupMenu stepContextMenu) { MenuItem viewItem = new MenuItem(entryText); viewItem.setEnabled(enabled); viewItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { popupStepInteractiveViewer(step, viewerClassName, viewerImpl); } }); stepContextMenu.add(viewItem); } /** * Popup a dialog containing a particular interactive step viewer * * @param step the step that provides the viewer * @param viewerClassName the fully qualified name of the viewer * @param viewerImpl the actual instance of the viewer */ protected void popupStepInteractiveViewer(StepVisual step, String viewerClassName, StepInteractiveViewer viewerImpl) { try { Object viewer = viewerClassName != null ? WekaPackageClassLoaderManager .objectForName(viewerClassName) : viewerImpl; // viewerClassName != null ? Beans.instantiate(this.getClass() // .getClassLoader(), viewerClassName) : viewerImpl; if (!(viewer instanceof StepInteractiveViewer)) { throw new WekaException("Interactive step viewer component " + viewerClassName + " must implement StepInteractiveViewer"); } if (!(viewer instanceof JComponent)) { throw new WekaException("Interactive step viewer component " + viewerClassName + " must be a JComponent"); } String viewerName = ((StepInteractiveViewer) viewer).getViewerName(); ((StepInteractiveViewer) viewer).setStep(step.getStepManager() .getManagedStep()); ((StepInteractiveViewer) viewer).setMainKFPerspective(m_visLayout .getMainPerspective()); JFrame jf = Utils.getWekaJFrame(viewerName, this); ((StepInteractiveViewer) viewer).setParentWindow(jf); ((StepInteractiveViewer) viewer).init(); jf.setLayout(new BorderLayout()); jf.add((JComponent) viewer, BorderLayout.CENTER); jf.pack(); jf.setSize(1000, 600); jf.setLocationRelativeTo(SwingUtilities.getWindowAncestor(this)); jf.setVisible(true); ((StepInteractiveViewer) viewer).nowVisible(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { m_visLayout.getMainPerspective().showErrorDialog(e); } } /** * Popup an editor dialog for a given step * * @param step the step to popup the editor dialog for */ protected void popupStepEditorDialog(StepVisual step) { String custEditor = step.getStepManager().getManagedStep().getCustomEditorForStep(); StepEditorDialog toPopup = null; if (custEditor != null && custEditor.length() > 0) { try { Object custPanel = WekaPackageClassLoaderManager.objectForName(custEditor); // Beans.instantiate(getClass().getClassLoader(), custEditor); if (!(custPanel instanceof StepEditorDialog)) { throw new WekaException( "Custom editor must be a subclass of StepEditorDialog"); } toPopup = ((StepEditorDialog) custPanel); } catch (Exception ex) { m_visLayout.getMainPerspective().showErrorDialog(ex); ex.printStackTrace(); } } else { // create an editor based on the GenericObjectEditor toPopup = new GOEStepEditorDialog(); toPopup.setMainPerspective(m_visLayout.getMainPerspective()); } final JDialog d = new JDialog((java.awt.Frame) getTopLevelAncestor(), ModalityType.DOCUMENT_MODAL); d.setLayout(new BorderLayout()); d.getContentPane().add(toPopup, BorderLayout.CENTER); final StepEditorDialog toPopupC = toPopup; d.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { d.dispose(); } }); toPopup.setParentWindow(d); toPopup.setEnvironment(m_visLayout.getEnvironment()); toPopup.setMainPerspective(m_visLayout.getMainPerspective()); toPopup.setStepToEdit(step.getStepManager().getManagedStep()); toPopup.setClosingListener(new StepEditorDialog.ClosingListener() { @Override public void closing() { if (toPopupC.isEdited()) { m_visLayout.setEdited(true); } } }); d.pack(); d.setLocationRelativeTo(m_visLayout.getMainPerspective()); d.setVisible(true); } private int snapToGrid(int val) { int r = val % m_gridSpacing; val /= m_gridSpacing; if (r > (m_gridSpacing / 2)) { val++; } val *= m_gridSpacing; return val; } /** * Snaps selected steps to the grid */ protected void snapSelectedToGrid() { List<StepVisual> selected = m_visLayout.getSelectedSteps(); for (StepVisual s : selected) { int x = s.getX(); int y = s.getY(); s.setX(snapToGrid(x)); s.setY(snapToGrid(y)); } revalidate(); repaint(); m_visLayout.setEdited(true); m_visLayout.getMainPerspective().notifyIsDirty(); } private void highlightSubFlow(int startX, int startY, int endX, int endY) { java.awt.Rectangle r = new java.awt.Rectangle((startX < endX) ? startX : endX, (startY < endY) ? startY : endY, Math.abs(startX - endX), Math.abs(startY - endY)); List<StepVisual> selected = m_visLayout.findSteps(r); m_visLayout.setSelectedSteps(selected); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow/MainKFPerspective.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * MainKFPerspective.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.gui.knowledgeflow; import weka.core.Defaults; import weka.core.Environment; import weka.core.Instances; import weka.core.Memory; import weka.core.Settings; import weka.core.WekaException; import weka.gui.AbstractPerspective; import weka.gui.CloseableTabTitle; import weka.gui.ExtensionFileFilter; import weka.gui.GUIApplication; import weka.gui.PerspectiveInfo; import weka.gui.WorkbenchDefaults; import weka.gui.explorer.PreprocessPanel; import weka.knowledgeflow.Flow; import weka.knowledgeflow.JSONFlowLoader; import weka.knowledgeflow.JSONFlowUtils; import weka.knowledgeflow.KFDefaults; import weka.knowledgeflow.LoggingLevel; import weka.knowledgeflow.StepManagerImpl; import weka.knowledgeflow.steps.MemoryBasedDataSource; import javax.swing.JFileChooser; import javax.swing.JMenu; import javax.swing.JOptionPane; import javax.swing.JSplitPane; import javax.swing.JTabbedPane; import javax.swing.JToggleButton; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.filechooser.FileFilter; import java.awt.BorderLayout; import java.awt.Dimension; import java.io.File; import java.util.ArrayList; import java.util.List; /** * Main perspective for the Knowledge flow application * * @author Mark Hall */ @PerspectiveInfo(ID = "knowledgeflow.main", title = "Data mining processes", toolTipText = "Data mining processes", iconPath = "weka/gui/weka_icon_new_small.png") public class MainKFPerspective extends AbstractPerspective { /** * Key for the environment variable that holds the parent directory of a * loaded flow */ public static final String FLOW_PARENT_DIRECTORY_VARIABLE_KEY = "Internal.knowledgeflow.directory"; /** File extension for undo point files */ public static final String FILE_EXTENSION_JSON = ".kf"; /** For serialization */ private static final long serialVersionUID = 3986047323839299447L; /** For monitoring Memory consumption */ private static Memory m_memory = new Memory(true); /** Count for new "untitled" tabs */ protected int m_untitledCount = 1; /** Whether to allow multiple tabs */ protected boolean m_allowMultipleTabs = true; /** The current step selected from the design pallete */ protected StepManagerImpl m_palleteSelectedStep; /** Holds the tabs of the perspective */ protected JTabbedPane m_flowTabs = new JTabbedPane(); /** List of layouts - one for each tab */ protected List<VisibleLayout> m_flowGraphs = new ArrayList<VisibleLayout>(); /** The jtree holding steps */ protected StepTree m_stepTree; /** The paste buffer */ protected String m_pasteBuffer; /** The file chooser for loading layout files */ protected JFileChooser m_FileChooser = new JFileChooser(new File( System.getProperty("user.dir"))); /** * The file chooser for saving layout files (only supports saving as json .kf * files */ protected JFileChooser m_saveFileChooser = new JFileChooser(new File( System.getProperty("user.dir"))); /** Manages template flows */ protected TemplateManager m_templateManager = new TemplateManager(); /** Main toolbar */ protected MainKFPerspectiveToolBar m_mainToolBar; /** * Construct a new MainKFPerspective */ public MainKFPerspective() { m_isLoaded = true; m_isActive = true; setLayout(new BorderLayout()); m_stepTree = new StepTree(this); DesignPanel designPanel = new DesignPanel(m_stepTree); // spit pane for design panel and flow tabs JSplitPane pane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, designPanel, m_flowTabs); pane.setOneTouchExpandable(true); add(pane, BorderLayout.CENTER); Dimension d = designPanel.getPreferredSize(); d = new Dimension((int) (d.getWidth() * 1.5), (int) d.getHeight()); designPanel.setPreferredSize(d); designPanel.setMinimumSize(d); m_flowTabs.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { int selected = m_flowTabs.getSelectedIndex(); setActiveTab(selected); } }); m_mainToolBar = new MainKFPerspectiveToolBar(this); add(m_mainToolBar, BorderLayout.NORTH); FileFilter nativeF = null; for (FileFilter f : Flow.FLOW_FILE_EXTENSIONS) { m_FileChooser.addChoosableFileFilter(f); if (((ExtensionFileFilter) f).getExtensions()[0].equals("." + JSONFlowLoader.EXTENSION)) { nativeF = f; m_saveFileChooser.addChoosableFileFilter(nativeF); } } if (nativeF != null) { m_FileChooser.setFileFilter(nativeF); m_saveFileChooser.setFileFilter(nativeF); } } /** * Return the currently selected step in the design palette * * @return the step selected in the design palette, or null if no step is * selected */ public StepManagerImpl getPalleteSelectedStep() { return m_palleteSelectedStep; } /** * Set a reference to the currently selected step in the design palette * * @param stepvisual the currently selected step */ protected void setPalleteSelectedStep(StepManagerImpl stepvisual) { m_palleteSelectedStep = stepvisual; } /** * Popup an error dialog * * @param cause the exception associated with the error */ public void showErrorDialog(Exception cause) { m_mainApplication.showErrorDialog(cause); } /** * Popup an information dialog * * @param information the information to display * @param title the title for the dialog * @param isWarning true if the dialog should be a warning dialog */ public void showInfoDialog(Object information, String title, boolean isWarning) { m_mainApplication.showInfoDialog(information, title, isWarning); } /** * Set the current flow layout operation * * @param opp the operation to use */ public void setFlowLayoutOperation(VisibleLayout.LayoutOperation opp) { // pass this through to the current visible tab. Main purpose // is to allow the Design palette to cancel any current operation // when the user clicks on a step in the jtree. if (getCurrentTabIndex() < getNumTabs() && getCurrentTabIndex() >= 0) { m_flowGraphs.get(getCurrentTabIndex()).setFlowLayoutOperation(opp); } } /** * Return true if the snap-to-grid button is selected * * @return true if snap-to-grid is turned on */ public boolean getSnapToGrid() { return ((JToggleButton) m_mainToolBar .getWidget(MainKFPerspectiveToolBar.Widgets.SNAP_TO_GRID_BUTTON .toString())).isSelected(); } /** * Clear the current selection in the design palette */ public void clearDesignPaletteSelection() { m_stepTree.clearSelection(); } /** * Get the contents of the paste buffer * * @return the contents of the paste buffer (in JSON) */ public String getPasteBuffer() { return m_pasteBuffer; } /** * Set the contents of the paste buffer * * @param serializedFlow (sub-)flow in JSON */ protected void setPasteBuffer(String serializedFlow) { m_pasteBuffer = serializedFlow; } /** * Copy the supplied steps to the clipboard * * @param steps a list of steps to copy * @throws WekaException if a problem occurs */ public void copyStepsToClipboard(List<StepVisual> steps) throws WekaException { if (steps.size() > 0) { m_pasteBuffer = VisibleLayout.serializeStepsToJSON(steps, "Clipboard copy"); getMainToolBar().enableWidgets( MainKFPerspectiveToolBar.Widgets.PASTE_BUTTON.toString()); } } public void copyFlowToClipboard(Flow flow) throws WekaException { m_pasteBuffer = JSONFlowUtils.flowToJSON(flow); getMainToolBar().enableWidgets( MainKFPerspectiveToolBar.Widgets.PASTE_BUTTON.toString()); } /** * Get the template manager * * @return the template manager */ public TemplateManager getTemplateManager() { return m_templateManager; } /** * Add a new untitled tab to the UI */ public synchronized void addUntitledTab() { if (getNumTabs() == 0 || getAllowMultipleTabs()) { addTab("Untitled" + m_untitledCount++); } else { m_flowGraphs.get(getCurrentTabIndex()).stopFlow(); m_flowGraphs.get(getCurrentTabIndex()).setFlow(new Flow()); } } /** * Add a new titled tab to the UI * * @param tabTitle the title for the tab */ public synchronized void addTab(String tabTitle) { VisibleLayout newLayout = new VisibleLayout(this); m_flowGraphs.add(newLayout); m_flowTabs.add(tabTitle, newLayout); m_flowTabs.setTabComponentAt(getNumTabs() - 1, new CloseableTabTitle( m_flowTabs, "(Ctrl+W)", new CloseableTabTitle.ClosingCallback() { @Override public void tabClosing(int tabIndex) { if (getAllowMultipleTabs()) { removeTab(tabIndex); } } })); setActiveTab(getNumTabs() - 1); } /** * Set the edited status for the current (visible) tab * * @param edited true if the flow in the tab has been edited (but not saved) */ public void setCurrentTabTitleEditedStatus(boolean edited) { CloseableTabTitle current = (CloseableTabTitle) m_flowTabs.getTabComponentAt(getCurrentTabIndex()); current.setBold(edited); } /** * Get the index of the current (visible) tab * * @return the index of the visible tab */ public int getCurrentTabIndex() { return m_flowTabs.getSelectedIndex(); } /** * Get the number of open tabs * * @return the number of open tabs */ public synchronized int getNumTabs() { return m_flowTabs.getTabCount(); } /** * Get the title of the tab at the supplied index * * @param index the index of the tab to get the title for * @return the title of the tab * @throws IndexOutOfBoundsException if the index is out of range */ public synchronized String getTabTitle(int index) { if (index < getNumTabs() && index >= 0) { return m_flowTabs.getTitleAt(index); } throw new IndexOutOfBoundsException("Tab index " + index + " is out of range!"); } /** * Set the active (visible) tab * * @param tabIndex the index of the tab to make active */ public synchronized void setActiveTab(int tabIndex) { if (tabIndex < getNumTabs() && tabIndex >= 0) { m_flowTabs.setSelectedIndex(tabIndex); VisibleLayout current = getCurrentLayout(); m_mainToolBar.enableWidget( MainKFPerspectiveToolBar.Widgets.SAVE_FLOW_BUTTON.toString(), !current.isExecuting()); m_mainToolBar.enableWidget( MainKFPerspectiveToolBar.Widgets.SAVE_FLOW_AS_BUTTON.toString(), !current.isExecuting()); m_mainToolBar.enableWidget( MainKFPerspectiveToolBar.Widgets.PLAY_PARALLEL_BUTTON.toString(), !current.isExecuting()); m_mainToolBar.enableWidget( MainKFPerspectiveToolBar.Widgets.PLAY_SEQUENTIAL_BUTTON.toString(), !current.isExecuting()); m_mainToolBar.enableWidget( MainKFPerspectiveToolBar.Widgets.ZOOM_OUT_BUTTON.toString(), !current.isExecuting()); m_mainToolBar.enableWidget( MainKFPerspectiveToolBar.Widgets.ZOOM_IN_BUTTON.toString(), !current.isExecuting()); if (current.getZoomSetting() == 50) { m_mainToolBar.enableWidget( MainKFPerspectiveToolBar.Widgets.ZOOM_OUT_BUTTON.toString(), false); } if (current.getZoomSetting() == 200) { m_mainToolBar.enableWidget( MainKFPerspectiveToolBar.Widgets.ZOOM_IN_BUTTON.toString(), false); } m_mainToolBar.enableWidget( MainKFPerspectiveToolBar.Widgets.CUT_BUTTON.toString(), current .getSelectedSteps().size() > 0 && !current.isExecuting()); m_mainToolBar.enableWidget( MainKFPerspectiveToolBar.Widgets.COPY_BUTTON.toString(), current .getSelectedSteps().size() > 0 && !current.isExecuting()); m_mainToolBar.enableWidget( MainKFPerspectiveToolBar.Widgets.DELETE_BUTTON.toString(), current .getSelectedSteps().size() > 0 && !current.isExecuting()); m_mainToolBar.enableWidget( MainKFPerspectiveToolBar.Widgets.SELECT_ALL_BUTTON.toString(), current.numSteps() > 0 && !current.isExecuting()); m_mainToolBar.enableWidget( MainKFPerspectiveToolBar.Widgets.PASTE_BUTTON.toString(), getPasteBuffer() != null && getPasteBuffer().length() > 0 && !current.isExecuting()); m_mainToolBar.enableWidget( MainKFPerspectiveToolBar.Widgets.STOP_BUTTON.toString(), current.isExecuting()); m_mainToolBar.enableWidget( MainKFPerspectiveToolBar.Widgets.UNDO_BUTTON.toString(), !current.isExecuting() && current.getUndoBufferSize() > 0); m_mainToolBar.enableWidget( MainKFPerspectiveToolBar.Widgets.NEW_FLOW_BUTTON.toString(), !current.isExecuting() && getAllowMultipleTabs()); } } /** * Close all the open tabs */ public void closeAllTabs() { for (int i = 0; i < getNumTabs(); i++) { removeTab(i); } } /** * Remove/close a tab * * @param tabIndex the index of the tab to close */ public synchronized void removeTab(int tabIndex) { if (tabIndex < 0 || tabIndex >= getNumTabs()) { return; } if (m_flowGraphs.get(tabIndex).getEdited()) { String tabTitle = m_flowTabs.getTitleAt(tabIndex); String message = "\"" + tabTitle + "\" has been modified. Save changes " + "before closing?"; int result = JOptionPane.showConfirmDialog(this, message, "Save changes", JOptionPane.YES_NO_CANCEL_OPTION); if (result == JOptionPane.YES_OPTION) { saveLayout(tabIndex, false); } else if (result == JOptionPane.CANCEL_OPTION) { return; } } m_flowTabs.remove(tabIndex); m_flowGraphs.remove(tabIndex); if (getCurrentTabIndex() < 0) { m_mainToolBar.disableWidgets( MainKFPerspectiveToolBar.Widgets.SAVE_FLOW_BUTTON.toString(), MainKFPerspectiveToolBar.Widgets.SAVE_FLOW_AS_BUTTON.toString()); } } /** * Get the flow layout for the current (visible) tab * * @return the current flow layout */ public VisibleLayout getCurrentLayout() { if (getCurrentTabIndex() >= 0) { return m_flowGraphs.get(getCurrentTabIndex()); } return null; } /** * Get the flow layout at the supplied index * * @param index the index of the flow layout to get * @return the flow layout at the index * @throws IndexOutOfBoundsException if the index is out of range */ public VisibleLayout getLayoutAt(int index) { if (index >= 0 && index < m_flowGraphs.size()) { return m_flowGraphs.get(index); } throw new IndexOutOfBoundsException("Flow index " + index + " is out of range!"); } /** * Returns true if the perspective is allowing multiple tabs to be open * * @return true if multiple tabs are allowed */ public boolean getAllowMultipleTabs() { return m_allowMultipleTabs; } /** * Set whether multiple tabs are allowed * * @param allow true if multiple tabs are allowed */ public void setAllowMultipleTabs(boolean allow) { m_allowMultipleTabs = allow; } /** * Get the value of a setting for the main perspective * * @param propKey the key of the setting to get * @param defaultVal the default value to use if nothing is set yet * @param <T> the type of the setting * @return the value (or default value) for the setting */ public <T> T getSetting(Settings.SettingKey propKey, T defaultVal) { return m_mainApplication.getApplicationSettings().getSetting( getPerspectiveID(), propKey, defaultVal, null); } public void notifyIsDirty() { firePropertyChange("PROP_DIRTY", null, null); } /** * Save a particular flow layout * * @param tabIndex the index of the tab containing the flow to asave * @param showDialog true if a file dialog should be popped up */ protected void saveLayout(int tabIndex, boolean showDialog) { m_flowGraphs.get(tabIndex).saveLayout(showDialog); } /** * Load a flow layout. Prompts via a filechooser */ public void loadLayout() { File lFile = null; int returnVal = m_FileChooser.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { lFile = m_FileChooser.getSelectedFile(); loadLayout(lFile, true); } } /** * Load a flow layout. * * @param fFile the file to load * @param newTab true if the flow should be loaded into a new tab */ public void loadLayout(File fFile, boolean newTab) { File absoluteF = fFile.getAbsoluteFile(); if (!newTab) { m_flowGraphs.get(getCurrentTabIndex()).loadLayout(fFile, false); m_flowGraphs.get(getCurrentTabIndex()).getEnvironment() .addVariable(FLOW_PARENT_DIRECTORY_VARIABLE_KEY, absoluteF.getParent()); } else { String tabTitle = fFile.toString(); tabTitle = tabTitle.substring(tabTitle.lastIndexOf(File.separator) + 1, tabTitle.length()); if (tabTitle.lastIndexOf('.') > 0) { tabTitle = tabTitle.substring(0, tabTitle.lastIndexOf('.')); } addTab(tabTitle); VisibleLayout current = getCurrentLayout(); current.loadLayout(fFile, false); current.getEnvironment().addVariable(FLOW_PARENT_DIRECTORY_VARIABLE_KEY, absoluteF.getParent()); // set the enabled status of the toolbar widgets setActiveTab(getCurrentTabIndex()); } } /** * Set the title of the current (visible) tab * * @param title the tab title to use */ protected void setCurrentTabTitle(String title) { m_flowTabs.setTitleAt(getCurrentTabIndex(), title); } /** * Return true if memory is running low * * @return true if memory is running low */ public boolean isMemoryLow() { return m_memory.memoryIsLow(); } /** * Print a warning if memory is low (and show a GUI dialog if running in a * graphical environment) * * @return true if user opts to continue (in the GUI case) */ public boolean showMemoryIsLow() { return m_memory.showMemoryIsLow(); } public boolean getDebug() { return getMainApplication() .getApplicationSettings() .getSetting(getPerspectiveID(), KFDefaults.LOGGING_LEVEL_KEY, LoggingLevel.BASIC, Environment.getSystemWide()).ordinal() == LoggingLevel.DEBUGGING .ordinal(); } /** * Get the main toolbar * * @return the main toolbar */ public MainKFPerspectiveToolBar getMainToolBar() { return m_mainToolBar; } /** * Set active status of this perspective. True indicates that this perspective * is the visible active perspective in the application * * @param active true if this perspective is the active one */ @Override public void setActive(boolean active) { if (active) { // are we operating as a non-primary perspective somewhere other // than in the Knowledge Flow? if (!getMainApplication().getApplicationID().equalsIgnoreCase( KFDefaults.APP_ID)) { // check number of tabs and create a new one if none are open if (getNumTabs() == 0) { addUntitledTab(); } } } } /** * Get an ordered list of menus to appear in the main menu bar. Return null * for no menus * * @return a list of menus to appear in the main menu bar or null for no menus */ @Override public List<JMenu> getMenus() { return m_mainToolBar.getMenus(); } /** * Get the default settings for this perspective (or null if there are none) * * @return the default settings for this perspective, or null if the * perspective does not have any settings */ @Override public Defaults getDefaultSettings() { return new KFDefaults(); } /** * Returns true if this perspective is OK with being an active perspective - * i.e. the user can click on this perspective at this time in the perspective * toolbar. For example, a Perspective might return false from this method if * it needs a set of instances to operate but none have been supplied yet. * * @return true if this perspective can be active at the current time */ @Override public boolean okToBeActive() { return true; } /** * Called when the user alters settings. The settings altered by the user are * not necessarily ones related to this perspective */ @Override public void settingsChanged() { Settings settings = getMainApplication().getApplicationSettings(); int fontSize = settings.getSetting(KFDefaults.MAIN_PERSPECTIVE_ID, new Settings.SettingKey(KFDefaults.MAIN_PERSPECTIVE_ID + ".logMessageFontSize", "", ""), -1); for (VisibleLayout v : m_flowGraphs) { v.getLogPanel().setLoggingFontSize(fontSize); } } /** * Returns true if this perspective can do something meaningful with a set of * instances * * @return true if this perspective accepts instances */ @Override public boolean acceptsInstances() { // allow instances only if running in the Workbench and the user has // opted to manually send loaded instances to perspectives. This is because // we create a new flow containing a MemoryDataSource when receiving // a set of instances. The MemoryDataSource keeps a reference to the data. GUIApplication mainApp = getMainApplication(); if (mainApp.getApplicationID().equals(WorkbenchDefaults.APP_ID)) { boolean sendToAll = mainApp.getApplicationSettings().getSetting( PreprocessPanel.PreprocessDefaults.ID, PreprocessPanel.PreprocessDefaults.ALWAYS_SEND_INSTANCES_TO_ALL_KEY, PreprocessPanel.PreprocessDefaults.ALWAYS_SEND_INSTANCES_TO_ALL, Environment.getSystemWide()); return !sendToAll; } return false; } /** * Set instances (if this perspective can use them) * * @param instances the instances */ @Override public void setInstances(Instances instances) { addUntitledTab(); VisibleLayout newL = m_flowGraphs.get(m_flowGraphs.size() - 1); MemoryBasedDataSource memoryBasedDataSource = new MemoryBasedDataSource(); memoryBasedDataSource.setInstances(instances); StepManagerImpl newS = new StepManagerImpl(memoryBasedDataSource); newL.addStep(newS, 30, 30); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow/MainKFPerspectiveToolBar.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * MainKFPerspectiveToolBar.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand */ package weka.gui.knowledgeflow; import weka.core.Utils; import weka.core.WekaException; import weka.knowledgeflow.Flow; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.io.InputStream; import java.io.InputStreamReader; import java.io.LineNumberReader; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import static weka.gui.knowledgeflow.StepVisual.loadIcon; /** * Class that provides the main editing widget toolbar and menu items * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class MainKFPerspectiveToolBar extends JPanel { private static final long serialVersionUID = -157986423490835642L; /** Path to the icons for the toolbar */ public static String ICON_PATH = "weka/gui/knowledgeflow/icons/"; /** Reference to the main knowledge flow perspective */ protected MainKFPerspective m_mainPerspective; /** holds a map of widgets, keyed by widget name */ protected Map<String, JComponent> m_widgetMap = new HashMap<String, JComponent>(); /** Holds a map of top level menus */ protected Map<String, JMenu> m_menuMap = new LinkedHashMap<String, JMenu>(); /** holds a map of menu items (for widgets that have corresponding menu items) */ protected Map<String, JMenuItem> m_menuItemMap = new HashMap<String, JMenuItem>(); /** True if menu items corresponding to the toolbar widgets should be shown */ protected boolean m_showMenus; /** * Constructor * * @param mainKFPerspective the main knowledge flow perspective */ public MainKFPerspectiveToolBar(MainKFPerspective mainKFPerspective) { super(); JMenu fileMenu = new JMenu(); fileMenu.setText("File"); m_menuMap.put("File", fileMenu); JMenu editMenu = new JMenu(); editMenu.setText("Edit"); m_menuMap.put("Edit", editMenu); JMenu insertMenu = new JMenu(); insertMenu.setText("Insert"); m_menuMap.put("Insert", insertMenu); JMenu viewMenu = new JMenu(); viewMenu.setText("View"); m_menuMap.put("View", viewMenu); m_mainPerspective = mainKFPerspective; setLayout(new BorderLayout()); // set up an action for closing the current tab final Action closeAction = new AbstractAction("Close") { private static final long serialVersionUID = 4762166880144590384L; @Override public void actionPerformed(ActionEvent e) { if (m_mainPerspective.getCurrentTabIndex() >= 0) { m_mainPerspective.removeTab(m_mainPerspective.getCurrentTabIndex()); } } }; KeyStroke closeKey = KeyStroke.getKeyStroke(KeyEvent.VK_W, InputEvent.CTRL_DOWN_MASK); m_mainPerspective.getActionMap().put("Close", closeAction); m_mainPerspective.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put( closeKey, "Close"); setupLeftSideToolBar(); setupRightSideToolBar(); } private void setupLeftSideToolBar() { JToolBar fixedTools2 = new JToolBar(); fixedTools2.setOrientation(JToolBar.HORIZONTAL); fixedTools2.setFloatable(false); JButton playB = new JButton(new ImageIcon(loadIcon(ICON_PATH + "resultset_next.png") .getImage())); playB.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0)); playB .setToolTipText("Run this flow (all start points launched in parallel)"); final Action playParallelAction = new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { if (m_mainPerspective.getCurrentLayout() != null) { boolean proceed = true; if (m_mainPerspective.isMemoryLow()) { proceed = m_mainPerspective.showMemoryIsLow(); } if (proceed) { try { m_mainPerspective.getCurrentLayout().executeFlow(false); } catch (WekaException e1) { m_mainPerspective.showErrorDialog(e1); } } } } }; playB.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { playParallelAction.actionPerformed(e); } }); JButton playBB = new JButton(new ImageIcon(loadIcon(ICON_PATH + "resultset_last.png") .getImage())); playBB.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0)); playBB.setToolTipText("Run this flow (start points launched sequentially)"); final Action playSequentialAction = new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { if (m_mainPerspective.getCurrentLayout() != null) { if (!Utils .getDontShowDialog("weka.gui.knowledgeflow.SequentialRunInfo")) { JCheckBox dontShow = new JCheckBox("Do not show this message again"); Object[] stuff = new Object[2]; stuff[0] = "The order that data sources are launched in can be\n" + "specified by setting a custom name for each data source that\n" + "that includes a number. E.g. \"1:MyArffLoader\". To set a name,\n" + "right-click over a data source and select \"Set name\"\n\n" + "If the prefix is not specified, then the order of execution\n" + "will correspond to the order that the components were added\n" + "to the layout. Note that it is also possible to prevent a data\n" + "source from executing by prefixing its name with a \"!\". E.g\n" + "\"!:MyArffLoader\""; stuff[1] = dontShow; JOptionPane.showMessageDialog(m_mainPerspective, stuff, "Sequential execution information", JOptionPane.OK_OPTION); if (dontShow.isSelected()) { try { Utils .setDontShowDialog("weka.gui.knowledgeFlow.SequentialRunInfo"); } catch (Exception e1) { } } } boolean proceed = true; if (m_mainPerspective.isMemoryLow()) { proceed = m_mainPerspective.showMemoryIsLow(); } if (proceed) { try { m_mainPerspective.getCurrentLayout().executeFlow(true); } catch (WekaException e1) { m_mainPerspective.showErrorDialog(e1); } } } } }; playBB.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { playSequentialAction.actionPerformed(e); } }); JButton stopB = new JButton(new ImageIcon(loadIcon(ICON_PATH + "shape_square.png") .getImage())); stopB.setBorder(BorderFactory.createEmptyBorder(0, 8, 0, 0)); stopB.setToolTipText("Stop all execution"); final Action stopAction = new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { if (m_mainPerspective.getCurrentLayout() != null) { m_mainPerspective .getCurrentLayout() .getLogPanel() .statusMessage( "@!@[KnowledgeFlow]|Attempting to stop all components..."); m_mainPerspective.getCurrentLayout().stopFlow(); m_mainPerspective.getCurrentLayout().getLogPanel() .statusMessage("@!@[KnowledgeFlow]|OK."); } } }; stopB.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { stopAction.actionPerformed(e); } }); JButton pointerB = new JButton(new ImageIcon(loadIcon(ICON_PATH + "cursor.png").getImage())); pointerB.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0)); pointerB.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m_mainPerspective.setPalleteSelectedStep(null); m_mainPerspective.setCursor(Cursor .getPredefinedCursor(Cursor.DEFAULT_CURSOR)); m_mainPerspective.clearDesignPaletteSelection(); if (m_mainPerspective.getCurrentLayout() != null) { m_mainPerspective.getCurrentLayout().setFlowLayoutOperation( VisibleLayout.LayoutOperation.NONE); } } }); addWidgetToToolBar(fixedTools2, Widgets.POINTER_BUTTON.toString(), pointerB); addWidgetToToolBar(fixedTools2, Widgets.PLAY_PARALLEL_BUTTON.toString(), playB); addWidgetToToolBar(fixedTools2, Widgets.PLAY_SEQUENTIAL_BUTTON.toString(), playBB); addWidgetToToolBar(fixedTools2, Widgets.STOP_BUTTON.toString(), stopB); Dimension d = playB.getPreferredSize(); Dimension d2 = fixedTools2.getMinimumSize(); Dimension d3 = new Dimension(d2.width, d.height + 4); fixedTools2.setPreferredSize(d3); fixedTools2.setMaximumSize(d3); add(fixedTools2, BorderLayout.WEST); } private void setupRightSideToolBar() { JToolBar fixedTools = new JToolBar(); fixedTools.setOrientation(JToolBar.HORIZONTAL); JButton cutB = new JButton(new ImageIcon(loadIcon(ICON_PATH + "cut.png").getImage())); cutB.setBorder(BorderFactory.createEmptyBorder(0, 8, 0, 0)); cutB.setToolTipText("Cut selected (Ctrl+X)"); JButton copyB = new JButton(new ImageIcon(loadIcon(ICON_PATH + "page_copy.png") .getImage())); copyB.setBorder(BorderFactory.createEmptyBorder(0, 8, 0, 0)); copyB.setToolTipText("Copy selected (Ctrl+C)"); JButton pasteB = new JButton(new ImageIcon(loadIcon(ICON_PATH + "paste_plain.png") .getImage())); pasteB.setBorder(BorderFactory.createEmptyBorder(0, 8, 0, 0)); pasteB.setToolTipText("Paste from clipboard (Ctrl+V)"); JButton deleteB = new JButton(new ImageIcon(loadIcon(ICON_PATH + "delete.png").getImage())); deleteB.setBorder(BorderFactory.createEmptyBorder(0, 8, 0, 0)); deleteB.setToolTipText("Delete selected (DEL)"); final JToggleButton snapToGridB = new JToggleButton(new ImageIcon(loadIcon(ICON_PATH + "shape_handles.png") .getImage())); // m_snapToGridB.setBorder(BorderFactory.createEmptyBorder(0, 8, 0, 0)); snapToGridB.setToolTipText("Snap to grid (Ctrl+G)"); JButton saveB = new JButton(new ImageIcon(loadIcon(ICON_PATH + "disk.png").getImage())); saveB.setBorder(BorderFactory.createEmptyBorder(0, 8, 0, 0)); saveB.setToolTipText("Save layout (Ctrl+S)"); JButton saveBB = new JButton(new ImageIcon(loadIcon(ICON_PATH + "disk_multiple.png") .getImage())); saveBB.setBorder(BorderFactory.createEmptyBorder(0, 8, 0, 0)); saveBB.setToolTipText("Save layout with new name"); JButton loadB = new JButton(new ImageIcon(loadIcon(ICON_PATH + "folder_add.png") .getImage())); loadB.setToolTipText("Open (Ctrl+O)"); loadB.setBorder(BorderFactory.createEmptyBorder(0, 8, 0, 0)); JButton newB = new JButton( new ImageIcon(loadIcon(ICON_PATH + "page_add.png").getImage())); newB.setToolTipText("New layout (Ctrl+N)"); newB.setBorder(BorderFactory.createEmptyBorder(0, 8, 0, 0)); newB.setEnabled(m_mainPerspective.getAllowMultipleTabs()); final JButton helpB = new JButton(new ImageIcon(loadIcon(ICON_PATH + "help.png").getImage())); helpB.setBorder(BorderFactory.createEmptyBorder(0, 8, 0, 0)); helpB.setToolTipText("Display help (Ctrl+H)"); JButton togglePerspectivesB = new JButton(new ImageIcon(loadIcon(ICON_PATH + "cog_go.png").getImage())); togglePerspectivesB.setBorder(BorderFactory.createEmptyBorder(0, 8, 0, 0)); togglePerspectivesB .setToolTipText("Show/hide perspectives toolbar (Ctrl+P)"); final JButton templatesB = new JButton(new ImageIcon(loadIcon( ICON_PATH + "application_view_tile.png").getImage())); templatesB.setBorder(BorderFactory.createEmptyBorder(0, 8, 0, 0)); templatesB.setToolTipText("Load a template layout"); JButton noteB = new JButton( new ImageIcon(loadIcon(ICON_PATH + "note_add.png").getImage())); noteB.setBorder(BorderFactory.createEmptyBorder(0, 8, 0, 0)); noteB.setToolTipText("Add a note to the layout (Ctrl+I)"); JButton selectAllB = new JButton(new ImageIcon(loadIcon(ICON_PATH + "shape_group.png") .getImage())); selectAllB.setBorder(BorderFactory.createEmptyBorder(0, 8, 0, 0)); selectAllB.setToolTipText("Select all (Ctrl+A)"); final JButton zoomInB = new JButton(new ImageIcon(loadIcon(ICON_PATH + "zoom_in.png").getImage())); zoomInB.setBorder(BorderFactory.createEmptyBorder(0, 8, 0, 0)); zoomInB.setToolTipText("Zoom in (Ctrl++)"); final JButton zoomOutB = new JButton( new ImageIcon(loadIcon(ICON_PATH + "zoom_out.png").getImage())); zoomOutB.setBorder(BorderFactory.createEmptyBorder(0, 8, 0, 0)); zoomOutB.setToolTipText("Zoom out (Ctrl+-)"); JButton undoB = new JButton(new ImageIcon(loadIcon(ICON_PATH + "arrow_undo.png") .getImage())); undoB.setBorder(BorderFactory.createEmptyBorder(0, 8, 0, 0)); undoB.setToolTipText("Undo (Ctrl+U)"); // actions final Action saveAction = new AbstractAction("Save") { @Override public void actionPerformed(ActionEvent e) { if (m_mainPerspective.getCurrentTabIndex() >= 0) { m_mainPerspective.saveLayout(m_mainPerspective.getCurrentTabIndex(), false); } } }; KeyStroke saveKey = KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_DOWN_MASK); m_mainPerspective.getActionMap().put("Save", saveAction); m_mainPerspective.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put( saveKey, "Save"); saveB.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { saveAction.actionPerformed(e); } }); KeyStroke saveAsKey = KeyStroke.getKeyStroke(KeyEvent.VK_Y, InputEvent.CTRL_DOWN_MASK); final Action saveAsAction = new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { m_mainPerspective.saveLayout(m_mainPerspective.getCurrentTabIndex(), true); } }; m_mainPerspective.getActionMap().put("SaveAS", saveAsAction); m_mainPerspective.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put( saveAsKey, "SaveAS"); saveBB.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { saveAsAction.actionPerformed(e); } }); final Action openAction = new AbstractAction("Open") { @Override public void actionPerformed(ActionEvent e) { m_mainPerspective.loadLayout(); } }; KeyStroke openKey = KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_DOWN_MASK); m_mainPerspective.getActionMap().put("Open", openAction); m_mainPerspective.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put( openKey, "Open"); loadB.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { openAction.actionPerformed(e); } }); final Action newAction = new AbstractAction("New") { @Override public void actionPerformed(ActionEvent e) { m_mainPerspective.addUntitledTab(); } }; KeyStroke newKey = KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.CTRL_DOWN_MASK); m_mainPerspective.getActionMap().put("New", newAction); m_mainPerspective.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put( newKey, "New"); newB.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { newAction.actionPerformed(ae); } }); final Action selectAllAction = new AbstractAction("SelectAll") { @Override public void actionPerformed(ActionEvent e) { if (m_mainPerspective.getCurrentLayout() != null && m_mainPerspective.getCurrentLayout().numSteps() > 0) { List<StepVisual> newSelected = newSelected = new ArrayList<StepVisual>(); newSelected.addAll(m_mainPerspective.getCurrentLayout() .getRenderGraph()); // toggle if (newSelected.size() == m_mainPerspective.getCurrentLayout() .getSelectedSteps().size()) { // unselect all m_mainPerspective.getCurrentLayout().setSelectedSteps( new ArrayList<StepVisual>()); } else { // select all m_mainPerspective.getCurrentLayout().setSelectedSteps(newSelected); } m_mainPerspective.revalidate(); m_mainPerspective.repaint(); m_mainPerspective.notifyIsDirty(); } } }; KeyStroke selectAllKey = KeyStroke.getKeyStroke(KeyEvent.VK_A, InputEvent.CTRL_DOWN_MASK); m_mainPerspective.getActionMap().put("SelectAll", selectAllAction); m_mainPerspective.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put( selectAllKey, "SelectAll"); selectAllB.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { selectAllAction.actionPerformed(e); } }); final Action zoomInAction = new AbstractAction("ZoomIn") { @Override public void actionPerformed(ActionEvent e) { if (m_mainPerspective.getCurrentLayout() != null) { int z = m_mainPerspective.getCurrentLayout().getZoomSetting(); z += 25; zoomOutB.setEnabled(true); if (z >= 200) { z = 200; zoomInB.setEnabled(false); } m_mainPerspective.getCurrentLayout().setZoomSetting(z); m_mainPerspective.revalidate(); m_mainPerspective.repaint(); m_mainPerspective.notifyIsDirty(); } } }; KeyStroke zoomInKey = KeyStroke.getKeyStroke(KeyEvent.VK_EQUALS, InputEvent.CTRL_DOWN_MASK); m_mainPerspective.getActionMap().put("ZoomIn", zoomInAction); m_mainPerspective.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put( zoomInKey, "ZoomIn"); zoomInB.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { zoomInAction.actionPerformed(e); } }); final Action zoomOutAction = new AbstractAction("ZoomOut") { @Override public void actionPerformed(ActionEvent e) { if (m_mainPerspective.getCurrentLayout() != null) { int z = m_mainPerspective.getCurrentLayout().getZoomSetting(); z -= 25; zoomInB.setEnabled(true); if (z <= 50) { z = 50; zoomOutB.setEnabled(false); } m_mainPerspective.getCurrentLayout().setZoomSetting(z); m_mainPerspective.revalidate(); m_mainPerspective.repaint(); m_mainPerspective.notifyIsDirty(); } } }; KeyStroke zoomOutKey = KeyStroke.getKeyStroke(KeyEvent.VK_MINUS, InputEvent.CTRL_DOWN_MASK); m_mainPerspective.getActionMap().put("ZoomOut", zoomOutAction); m_mainPerspective.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put( zoomOutKey, "ZoomOut"); zoomOutB.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { zoomOutAction.actionPerformed(e); } }); final Action cutAction = new AbstractAction("Cut") { @Override public void actionPerformed(ActionEvent e) { if (m_mainPerspective.getCurrentLayout() != null && m_mainPerspective.getCurrentLayout().getSelectedSteps().size() > 0) { try { m_mainPerspective.getCurrentLayout().copySelectedStepsToClipboard(); m_mainPerspective.getCurrentLayout().removeSelectedSteps(); } catch (WekaException e1) { m_mainPerspective.showErrorDialog(e1); } } } }; KeyStroke cutKey = KeyStroke.getKeyStroke(KeyEvent.VK_X, InputEvent.CTRL_DOWN_MASK); m_mainPerspective.getActionMap().put("Cut", cutAction); m_mainPerspective.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put( cutKey, "Cut"); cutB.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { cutAction.actionPerformed(e); } }); final Action deleteAction = new AbstractAction("Delete") { @Override public void actionPerformed(ActionEvent e) { if (m_mainPerspective.getCurrentLayout() != null) { try { m_mainPerspective.getCurrentLayout().removeSelectedSteps(); } catch (WekaException e1) { m_mainPerspective.showErrorDialog(e1); } } } }; KeyStroke deleteKey = KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0); m_mainPerspective.getActionMap().put("Delete", deleteAction); m_mainPerspective.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put( deleteKey, "Delete"); deleteB.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { deleteAction.actionPerformed(e); } }); final Action copyAction = new AbstractAction("Copy") { @Override public void actionPerformed(ActionEvent e) { if (m_mainPerspective.getCurrentLayout() != null && m_mainPerspective.getCurrentLayout().getSelectedSteps().size() > 0) { try { m_mainPerspective.getCurrentLayout().copySelectedStepsToClipboard(); m_mainPerspective.getCurrentLayout().setSelectedSteps( new ArrayList<StepVisual>()); } catch (WekaException e1) { m_mainPerspective.showErrorDialog(e1); } } } }; KeyStroke copyKey = KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.CTRL_DOWN_MASK); m_mainPerspective.getActionMap().put("Copy", copyAction); m_mainPerspective.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put( copyKey, "Copy"); copyB.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { copyAction.actionPerformed(e); } }); final Action pasteAction = new AbstractAction("Paste") { @Override public void actionPerformed(ActionEvent e) { if (m_mainPerspective.getCurrentLayout() != null && m_mainPerspective.getPasteBuffer().length() > 0) { m_mainPerspective.setCursor(Cursor .getPredefinedCursor(Cursor.CROSSHAIR_CURSOR)); m_mainPerspective.getCurrentLayout().setFlowLayoutOperation( VisibleLayout.LayoutOperation.PASTING); } } }; KeyStroke pasteKey = KeyStroke.getKeyStroke(KeyEvent.VK_V, InputEvent.CTRL_DOWN_MASK); m_mainPerspective.getActionMap().put("Paste", pasteAction); m_mainPerspective.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put( pasteKey, "Paste"); pasteB.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { pasteAction.actionPerformed(e); } }); final Action snapAction = new AbstractAction("Snap") { @Override public void actionPerformed(ActionEvent e) { // toggle first // snapToGridB.setSelected(!snapToGridB.isSelected()); if (snapToGridB.isSelected()) { if (m_mainPerspective.getCurrentLayout() != null) { m_mainPerspective.getCurrentLayout().snapSelectedToGrid(); } } } }; KeyStroke snapKey = KeyStroke.getKeyStroke(KeyEvent.VK_G, InputEvent.CTRL_DOWN_MASK); m_mainPerspective.getActionMap().put("Snap", snapAction); m_mainPerspective.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put( snapKey, "Snap"); snapToGridB.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (snapToGridB.isSelected()) { snapAction.actionPerformed(e); } } }); final Action noteAction = new AbstractAction("Note") { @Override public void actionPerformed(ActionEvent e) { if (m_mainPerspective.getCurrentLayout() != null) { m_mainPerspective.getCurrentLayout().initiateAddNote(); } } }; KeyStroke noteKey = KeyStroke.getKeyStroke(KeyEvent.VK_I, InputEvent.CTRL_DOWN_MASK); m_mainPerspective.getActionMap().put("Note", noteAction); m_mainPerspective.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put( noteKey, "Note"); noteB.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { noteAction.actionPerformed(e); } }); final Action undoAction = new AbstractAction("Undo") { @Override public void actionPerformed(ActionEvent e) { if (m_mainPerspective.getCurrentLayout() != null) { m_mainPerspective.getCurrentLayout().popAndLoadUndo(); } } }; KeyStroke undoKey = KeyStroke.getKeyStroke(KeyEvent.VK_U, InputEvent.CTRL_DOWN_MASK); m_mainPerspective.getActionMap().put("Undo", undoAction); m_mainPerspective.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put( undoKey, "Undo"); undoB.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { undoAction.actionPerformed(e); } }); final Action helpAction = new AbstractAction("Help") { @Override public void actionPerformed(ActionEvent e) { popupHelp(helpB); } }; KeyStroke helpKey = KeyStroke.getKeyStroke(KeyEvent.VK_H, InputEvent.CTRL_DOWN_MASK); m_mainPerspective.getActionMap().put("Help", helpAction); m_mainPerspective.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put( helpKey, "Help"); helpB.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { helpAction.actionPerformed(ae); } }); templatesB.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // createTemplateMenuPopup(); PopupMenu popupMenu = new PopupMenu(); List<String> builtinTemplates = m_mainPerspective.getTemplateManager() .getBuiltinTemplateDescriptions(); List<String> pluginTemplates = m_mainPerspective.getTemplateManager() .getPluginTemplateDescriptions(); for (final String desc : builtinTemplates) { MenuItem menuItem = new MenuItem(desc); menuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { Flow templateFlow = m_mainPerspective.getTemplateManager().getTemplateFlow(desc); m_mainPerspective.addTab(desc); m_mainPerspective.getCurrentLayout().setFlow(templateFlow); } catch (WekaException ex) { m_mainPerspective.showErrorDialog(ex); } } }); popupMenu.add(menuItem); } if (builtinTemplates.size() > 0 && pluginTemplates.size() > 0) { popupMenu.addSeparator(); } for (final String desc : pluginTemplates) { MenuItem menuItem = new MenuItem(desc); menuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { Flow templateFlow = m_mainPerspective.getTemplateManager().getTemplateFlow(desc); m_mainPerspective.addTab(desc); m_mainPerspective.getCurrentLayout().setFlow(templateFlow); } catch (WekaException ex) { m_mainPerspective.showErrorDialog(ex); } } }); popupMenu.add(menuItem); } templatesB.add(popupMenu); popupMenu.show(templatesB, 0, 0); } }); templatesB .setEnabled(m_mainPerspective.getTemplateManager().numTemplates() > 0); final Action togglePerspectivesAction = new AbstractAction("Toggle perspectives") { @Override public void actionPerformed(ActionEvent e) { if (!Utils .getDontShowDialog("weka.gui.knowledgeflow.PerspectiveInfo")) { JCheckBox dontShow = new JCheckBox("Do not show this message again"); Object[] stuff = new Object[2]; stuff[0] = "Perspectives are environments that take over the\n" + "Knowledge Flow UI and provide major additional functionality.\n" + "Many perspectives will operate on a set of instances. Instances\n" + "Can be sent to a perspective by placing a DataSource on the\n" + "layout canvas, configuring it and then selecting \"Send to perspective\"\n" + "from the contextual popup menu that appears when you right-click on\n" + "it. Several perspectives are built in to the Knowledge Flow, others\n" + "can be installed via the package manager.\n"; stuff[1] = dontShow; JOptionPane.showMessageDialog(m_mainPerspective, stuff, "Perspective information", JOptionPane.OK_OPTION); if (dontShow.isSelected()) { try { Utils .setDontShowDialog("weka.gui.Knowledgeflow.PerspectiveInfo"); } catch (Exception ex) { // quietly ignore } } } if (m_mainPerspective.getMainApplication() .isPerspectivesToolBarVisible()) { m_mainPerspective.getMainApplication().hidePerspectivesToolBar(); } else { m_mainPerspective.getMainApplication().showPerspectivesToolBar(); } m_mainPerspective.revalidate(); m_mainPerspective.notifyIsDirty(); } }; KeyStroke togglePerspectivesKey = KeyStroke.getKeyStroke(KeyEvent.VK_P, InputEvent.CTRL_DOWN_MASK); m_mainPerspective.getActionMap().put("Toggle perspectives", togglePerspectivesAction); m_mainPerspective.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put( togglePerspectivesKey, "Toggle perspectives"); togglePerspectivesB.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { togglePerspectivesAction.actionPerformed(e); } }); addWidgetToToolBar(fixedTools, Widgets.ZOOM_IN_BUTTON.toString(), zoomInB); addMenuItemToMenu("View", Widgets.ZOOM_IN_BUTTON.toString(), zoomInAction, zoomInKey); addWidgetToToolBar(fixedTools, Widgets.ZOOM_OUT_BUTTON.toString(), zoomOutB); addMenuItemToMenu("View", Widgets.ZOOM_OUT_BUTTON.toString(), zoomOutAction, zoomOutKey); fixedTools.addSeparator(); addWidgetToToolBar(fixedTools, Widgets.SELECT_ALL_BUTTON.toString(), selectAllB); addWidgetToToolBar(fixedTools, Widgets.CUT_BUTTON.toString(), cutB); addMenuItemToMenu("Edit", Widgets.CUT_BUTTON.toString(), cutAction, cutKey); addWidgetToToolBar(fixedTools, Widgets.COPY_BUTTON.toString(), copyB); addMenuItemToMenu("Edit", Widgets.COPY_BUTTON.toString(), copyAction, copyKey); addMenuItemToMenu("Edit", Widgets.PASTE_BUTTON.toString(), pasteAction, pasteKey); addWidgetToToolBar(fixedTools, Widgets.DELETE_BUTTON.toString(), deleteB); addMenuItemToMenu("Edit", Widgets.DELETE_BUTTON.toString(), deleteAction, deleteKey); addWidgetToToolBar(fixedTools, Widgets.PASTE_BUTTON.toString(), pasteB); addWidgetToToolBar(fixedTools, Widgets.UNDO_BUTTON.toString(), undoB); addMenuItemToMenu("Edit", Widgets.UNDO_BUTTON.toString(), undoAction, undoKey); addWidgetToToolBar(fixedTools, Widgets.NOTE_BUTTON.toString(), noteB); addMenuItemToMenu("Insert", Widgets.NOTE_BUTTON.toString(), noteAction, noteKey); fixedTools.addSeparator(); addWidgetToToolBar(fixedTools, Widgets.SNAP_TO_GRID_BUTTON.toString(), snapToGridB); fixedTools.addSeparator(); addWidgetToToolBar(fixedTools, Widgets.NEW_FLOW_BUTTON.toString(), newB); addMenuItemToMenu("File", Widgets.NEW_FLOW_BUTTON.toString(), newAction, newKey); addWidgetToToolBar(fixedTools, Widgets.SAVE_FLOW_BUTTON.toString(), saveB); addMenuItemToMenu("File", Widgets.LOAD_FLOW_BUTTON.toString(), openAction, openKey); addMenuItemToMenu("File", Widgets.SAVE_FLOW_BUTTON.toString(), saveAction, saveKey); addWidgetToToolBar(fixedTools, Widgets.SAVE_FLOW_AS_BUTTON.toString(), saveBB); addMenuItemToMenu("File", Widgets.SAVE_FLOW_AS_BUTTON.toString(), saveAction, saveAsKey); addWidgetToToolBar(fixedTools, Widgets.LOAD_FLOW_BUTTON.toString(), loadB); addWidgetToToolBar(fixedTools, Widgets.TEMPLATES_BUTTON.toString(), templatesB); fixedTools.addSeparator(); addWidgetToToolBar(fixedTools, Widgets.TOGGLE_PERSPECTIVES_BUTTON.toString(), togglePerspectivesB); addWidgetToToolBar(fixedTools, Widgets.HELP_BUTTON.toString(), helpB); Dimension d = undoB.getPreferredSize(); Dimension d2 = fixedTools.getMinimumSize(); Dimension d3 = new Dimension(d2.width, d.height + 4); fixedTools.setPreferredSize(d3); fixedTools.setMaximumSize(d3); fixedTools.setFloatable(false); add(fixedTools, BorderLayout.EAST); } /** * Add a widget to a toolbar * * @param toolBar the toolbar to add to * @param widgetName the name of the widget * @param widget the widget component itself */ protected void addWidgetToToolBar(JToolBar toolBar, String widgetName, JComponent widget) { toolBar.add(widget); m_widgetMap.put(widgetName, widget); } /** * Add a menu item to a named menu * * @param topMenu the name of the menu to add to * @param menuItem the entry text for the item itself * @param action the action associated with the menu item * @param accelerator the keystroke accelerator to associate with the item */ protected void addMenuItemToMenu(String topMenu, String menuItem, final Action action, KeyStroke accelerator) { JMenuItem newItem = m_menuItemMap.get(menuItem); if (newItem != null) { throw new IllegalArgumentException("The menu item '" + menuItem + "' already exists!"); } newItem = new JMenuItem(menuItem); if (accelerator != null) { newItem.setAccelerator(accelerator); } newItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { action.actionPerformed(e); } }); JMenu topJ = m_menuMap.get(topMenu); if (topJ == null) { topJ = new JMenu(); topJ.setText(topMenu); m_menuMap.put(topMenu, topJ); } topJ.add(newItem); m_menuItemMap.put(menuItem, newItem); } /** * Enable/disable a named widget * * @param widgetName the name of the widget to enable/disable * @param enable true if the widget should be enabled; false otherwise * @see {@code Widget} enum */ public void enableWidget(String widgetName, boolean enable) { JComponent widget = m_widgetMap.get(widgetName); if (widget != null) { widget.setEnabled(enable); } JMenuItem mI = m_menuItemMap.get(widgetName); if (mI != null) { mI.setEnabled(enable); } } public void enableWidgets(String... widgetNames) { for (String s : widgetNames) { enableWidget(s, true); } } public void disableWidgets(String... widgetNames) { for (String s : widgetNames) { enableWidget(s, false); } } private void popupHelp(final JButton helpB) { try { helpB.setEnabled(false); InputStream inR = this.getClass().getClassLoader() .getResourceAsStream("weka/gui/knowledgeflow/README_KnowledgeFlow"); StringBuilder helpHolder = new StringBuilder(); LineNumberReader lnr = new LineNumberReader(new InputStreamReader(inR)); String line; while ((line = lnr.readLine()) != null) { helpHolder.append(line + "\n"); } lnr.close(); final javax.swing.JFrame jf = new javax.swing.JFrame(); jf.getContentPane().setLayout(new java.awt.BorderLayout()); final JTextArea ta = new JTextArea(helpHolder.toString()); ta.setFont(new Font("Monospaced", Font.PLAIN, 12)); ta.setEditable(false); final JScrollPane sp = new JScrollPane(ta); jf.getContentPane().add(sp, java.awt.BorderLayout.CENTER); jf.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { helpB.setEnabled(true); jf.dispose(); } }); jf.setSize(600, 600); jf.setVisible(true); } catch (Exception ex) { ex.printStackTrace(); helpB.setEnabled(true); } } public JComponent getWidget(String widgetName) { return m_widgetMap.get(widgetName); } public JMenuItem getMenuItem(String menuItemName) { return m_menuItemMap.get(menuItemName); } /** * Enum containing all the widgets provided by the toolbar. The toString() * method provides the corresponding menu entry text for each widget. */ public enum Widgets { ZOOM_IN_BUTTON("Zoom In"), ZOOM_OUT_BUTTON("Zoom Out"), SELECT_ALL_BUTTON( "Select All"), CUT_BUTTON("Cut"), COPY_BUTTON("Copy"), DELETE_BUTTON( "Delete"), PASTE_BUTTON("Paste"), UNDO_BUTTON("Undo"), NOTE_BUTTON( "New Note"), SNAP_TO_GRID_BUTTON("Snap to Grid"), NEW_FLOW_BUTTON( "New Layout"), SAVE_FLOW_BUTTON("Save"), SAVE_FLOW_AS_BUTTON("Save As..."), LOAD_FLOW_BUTTON("Open..."), TEMPLATES_BUTTON("Template"), TOGGLE_PERSPECTIVES_BUTTON( "Toggle Perspectives"), HELP_BUTTON("help..."), POINTER_BUTTON("Pointer"), PLAY_PARALLEL_BUTTON("Launch"), PLAY_SEQUENTIAL_BUTTON("Launch Squential"), STOP_BUTTON("Stop"); String m_name; Widgets(String name) { m_name = name; } @Override public String toString() { return m_name; } } /** * Get the list of menus * * @return a list of {@code JMenu}s */ public List<JMenu> getMenus() { List<JMenu> menuList = new ArrayList<JMenu>(); for (Map.Entry<String, JMenu> e : m_menuMap.entrySet()) { menuList.add(e.getValue()); } return menuList; } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow/NoteVisual.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * NoteVisual.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.gui.knowledgeflow; import weka.knowledgeflow.StepManagerImpl; import weka.knowledgeflow.steps.Note; import javax.swing.BorderFactory; import javax.swing.JLabel; import javax.swing.JPanel; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Graphics; /** * Visual representation for the Note "step". * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class NoteVisual extends StepVisual { private static final long serialVersionUID = -3291021235652124916L; /** The label that displays the note text */ protected JLabel m_label = new JLabel(); /** Adjustment for the font size */ protected int m_fontSizeAdjust = -1; /** * Set the {@code StepManagerImpl} for the step covered by this visual * * @param manager the step manager to wrap */ @Override public void setStepManager(StepManagerImpl manager) { super.setStepManager(manager); removeAll(); setLayout(new BorderLayout()); setBorder(new ShadowBorder(2, Color.GRAY)); m_label.setText(convertToHTML(((Note) getStepManager().getManagedStep()) .getNoteText())); m_label.setOpaque(true); m_label.setBackground(Color.YELLOW); JPanel holder = new JPanel(); holder.setLayout(new BorderLayout()); holder.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2)); holder.setOpaque(true); holder.setBackground(Color.YELLOW); holder.add(m_label, BorderLayout.CENTER); add(holder, BorderLayout.CENTER); } /** * Set whether the note should appear "highlighted" (i.e. thicker border) * * @param highlighted true if the note should appear highlighted */ public void setHighlighted(boolean highlighted) { if (highlighted) { setBorder(BorderFactory.createMatteBorder(2, 2, 2, 2, Color.BLUE)); } else { // setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED)); setBorder(new ShadowBorder(2, Color.GRAY)); } revalidate(); } /** * Turn on/off the connector points * * @param dc a <code>boolean</code> value */ @Override public void setDisplayConnectors(boolean dc) { // m_visualHolder.setDisplayConnectors(dc); m_displayConnectors = dc; m_connectorColor = Color.blue; setHighlighted(dc); } /** * Turn on/off the connector points * * @param dc a <code>boolean</code> value * @param c the Color to use */ @Override public void setDisplayConnectors(boolean dc, Color c) { setDisplayConnectors(dc); m_connectorColor = c; } @Override public boolean getDisplayStepLabel() { return false; } @Override public void paintComponent(Graphics gx) { m_label.setText(convertToHTML(((Note) getStepManager().getManagedStep()) .getNoteText())); } /** * Convert plain text to HTML * * @param text the text to convert to marked up HTML * @return the marked up HTML */ private String convertToHTML(String text) { String htmlString = text.replace("\n", "<br>"); htmlString = "<html><font size=" + m_fontSizeAdjust + ">" + htmlString + "</font>" + "</html>"; return htmlString; } /** * Get the font size adjustment * * @return the font size adjustment */ public int getFontSizeAdjust() { return m_fontSizeAdjust; } /** * set the font size adjustment * * @param adjust the font size adjustment */ public void setFontSizeAdjust(int adjust) { m_fontSizeAdjust = adjust; } /** * Decrease the font size by one */ public void decreaseFontSize() { m_fontSizeAdjust--; } /** * Increase the font size by one */ public void increaseFontSize() { m_fontSizeAdjust++; } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow/SQLViewerPerspective.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * SQLViewerPerspective.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand */ package weka.gui.knowledgeflow; import weka.core.Defaults; import weka.core.converters.DatabaseLoader; import weka.gui.AbstractPerspective; import weka.gui.GUIApplication; import weka.gui.PerspectiveInfo; import weka.gui.sql.SqlViewer; import weka.gui.sql.event.ConnectionEvent; import weka.gui.sql.event.ConnectionListener; import weka.knowledgeflow.KFDefaults; import weka.knowledgeflow.StepManagerImpl; import weka.knowledgeflow.steps.Loader; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; /** * Perspective that wraps the {@code SQLViewer) component * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ @PerspectiveInfo(ID = SQLViewerPerspective.SQLDefaults.ID, title = "SQL Viewer", toolTipText = "Explore database tables with SQL", iconPath = "weka/gui/knowledgeflow/icons/database.png") public class SQLViewerPerspective extends AbstractPerspective { private static final long serialVersionUID = -4771310190331379801L; /** The wrapped SQLViewer */ protected SqlViewer m_viewer; /** Button for creating a new flow layout with a configured DBLoader step */ protected JButton m_newFlowBut; /** Reference to tne main knowledge flow perspective */ protected MainKFPerspective m_mainKFPerspective; /** Panel for holding buttons */ protected JPanel m_buttonHolder; /** * Constructor */ public SQLViewerPerspective() { setLayout(new BorderLayout()); m_viewer = new SqlViewer(null); add(m_viewer, BorderLayout.CENTER); m_newFlowBut = new JButton("New Flow"); m_newFlowBut.setToolTipText("Set up a new Knowledge Flow with the " + "current connection and query"); m_buttonHolder = new JPanel(); m_buttonHolder.add(m_newFlowBut); add(m_buttonHolder, BorderLayout.SOUTH); m_newFlowBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (m_mainKFPerspective != null) { newFlow(); } } }); m_newFlowBut.setEnabled(false); m_viewer.addConnectionListener(new ConnectionListener() { @Override public void connectionChange(ConnectionEvent evt) { if (evt.getType() == ConnectionEvent.DISCONNECT) { m_newFlowBut.setEnabled(false); } else { m_newFlowBut.setEnabled(true); } } }); } /** * Set the main application. Gives other perspectives access to information * provided by the main application * * @param application the main application */ @Override public void setMainApplication(GUIApplication application) { super.setMainApplication(application); m_mainKFPerspective = (MainKFPerspective) m_mainApplication.getPerspectiveManager() .getPerspective(KFDefaults.APP_ID); if (m_mainKFPerspective == null) { remove(m_buttonHolder); } } /** * Create a new flow in the main knowledge flow perspective with a configured * database loader step */ protected void newFlow() { m_newFlowBut.setEnabled(false); String user = m_viewer.getUser(); String password = m_viewer.getPassword(); String uRL = m_viewer.getURL(); String query = m_viewer.getQuery(); if (query == null) { query = ""; } try { DatabaseLoader dbl = new DatabaseLoader(); dbl.setUser(user); dbl.setPassword(password); dbl.setUrl(uRL); dbl.setQuery(query); Loader loaderStep = new Loader(); loaderStep.setLoader(dbl); StepManagerImpl manager = new StepManagerImpl(loaderStep); m_mainKFPerspective.addTab("DBSource"); m_mainKFPerspective.getCurrentLayout().addStep(manager, 50, 50); m_mainApplication.getPerspectiveManager().setActivePerspective( KFDefaults.APP_ID); m_newFlowBut.setEnabled(true); } catch (Exception ex) { ex.printStackTrace(); m_mainApplication.showErrorDialog(ex); } } /** * Default settings for the SQLViewer perspective */ protected static class SQLDefaults extends Defaults { public static final String ID = "sqlviewer"; private static final long serialVersionUID = 5907476861935295960L; public SQLDefaults() { super(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/knowledgeflow/ScatterPlotMatrixPerspective.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ScatterPlotMatrixPerspective.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.gui.knowledgeflow; import weka.core.Defaults; import weka.core.Instances; import weka.gui.AbstractPerspective; import weka.gui.PerspectiveInfo; import weka.gui.explorer.VisualizePanel; import weka.gui.visualize.MatrixPanel; import weka.gui.visualize.VisualizeUtils; import java.awt.BorderLayout; /** * Knowledge Flow perspective for the scatter plot matrix * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ @PerspectiveInfo(ID = "weka.gui.knowledgeflow.scatterplotmatrixperspective", title = "Scatter plot matrix", toolTipText = "Scatter plots", iconPath = "weka/gui/knowledgeflow/icons/application_view_tile.png") public class ScatterPlotMatrixPerspective extends AbstractPerspective { private static final long serialVersionUID = 5661598509822826837L; /** The actual matrix panel */ protected MatrixPanel m_matrixPanel; /** The dataset being visualized */ protected Instances m_visualizeDataSet; /** * Constructor */ public ScatterPlotMatrixPerspective() { setLayout(new BorderLayout()); m_matrixPanel = new MatrixPanel(); add(m_matrixPanel, BorderLayout.CENTER); } /** * Get default settings * * @return the default settings of this perspective */ @Override public Defaults getDefaultSettings() { // re-use explorer.VisualizePanel.ScatterDefaults, but set the ID // to be our perspective ID Defaults d = new VisualizePanel.ScatterDefaults(); d.setID(getPerspectiveID()); d.add(new VisualizeUtils.VisualizeDefaults()); return d; } /** * Returns true - we accept instances. * * @return true */ @Override public boolean acceptsInstances() { return true; } /** * Called when this perspective becomes the "active" (i.e. visible) one * * @param active true if this perspective is the active one */ @Override public void setActive(boolean active) { super.setActive(active); if (m_isActive && m_visualizeDataSet != null) { m_matrixPanel.applySettings(getMainApplication().getApplicationSettings(), getPerspectiveID()); m_matrixPanel.updatePanel(); } } /** * Set the instances to use * * @param instances the instances instances to use */ @Override public void setInstances(Instances instances) { m_visualizeDataSet = instances; m_matrixPanel.setInstances(m_visualizeDataSet); } /** * Can we be active (i.e. selected) at this point in time? True if we * have a dataset to visualize * * @return true if we have a dataset to visualize */ @Override public boolean okToBeActive() { return m_visualizeDataSet != 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/knowledgeflow/SendToPerspectiveGraphicalCommand.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * SendToPerspectiveGraphicalCommand.java * Copyright (C) 2016 University of Waikato, Hamilton, New Zealand * */ package weka.gui.knowledgeflow; import weka.core.Instances; import weka.core.WekaException; import weka.gui.Perspective; import java.util.List; /** * Class implementing sending a set of Instances to a named perspective * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class SendToPerspectiveGraphicalCommand extends AbstractGraphicalCommand { /** Command ID */ public static final String SEND_TO_PERSPECTIVE_COMMAND_KEY = "sendToPerspective"; /** The main KF perspective */ protected MainKFPerspective m_mainPerspective; /** * Set the graphical environment * * @param graphicalEnvironment the graphical environment */ @Override public void setGraphicalEnvironment(Object graphicalEnvironment) { super.setGraphicalEnvironment(graphicalEnvironment); if (graphicalEnvironment instanceof MainKFPerspective) { m_mainPerspective = (MainKFPerspective) graphicalEnvironment; } } /** * Get the name of the command * * @return the name of the command */ @Override public String getCommandName() { return SEND_TO_PERSPECTIVE_COMMAND_KEY; } /** * Get the description of this command * * @return the description of this command */ @Override public String getCommandDescription() { return "Send the supplied instances to the named perspective"; } /** * Execute the command * * @param commandArgs arguments to the command * @return null (no return value for this command) * @throws WekaException if a problem occurs */ @SuppressWarnings("unchecked") @Override public Object performCommand(Object... commandArgs) throws WekaException { if (commandArgs.length != 2 && !(commandArgs[1] instanceof Instances)) { throw new WekaException( "Was expecting two arguments: 1) perspective name, and 2) " + "argument of type weka.core.Instances"); } Instances toSend = (Instances) commandArgs[1]; String perspectiveName = commandArgs[0].toString(); List<Perspective> perspectives = m_mainPerspective.getMainApplication().getPerspectiveManager() .getVisiblePerspectives(); Perspective target = null; String targetID = null; for (Perspective p : perspectives) { if (p.acceptsInstances() && p.getPerspectiveTitle().equalsIgnoreCase(perspectiveName)) { targetID = p.getPerspectiveID(); target = p; break; } } if (target == null) { throw new WekaException("Was unable to find requested perspective"); } target.setInstances(toSend); m_mainPerspective.getMainApplication().getPerspectiveManager() .setActivePerspective(targetID); m_mainPerspective.getMainApplication().getPerspectiveManager() .setEnablePerspectiveTab(targetID, true); return null; } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow/ShadowBorder.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ShadowBorder.java * Copyright (C) 2011-2012 University of Waikato, Hamilton, New Zealand * */ package weka.gui.knowledgeflow; import javax.swing.border.AbstractBorder; import java.awt.*; /** * Border implementation that provides a drop shadow * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class ShadowBorder extends AbstractBorder { /** * For serialization */ private static final long serialVersionUID = -2117842133475125463L; /** The width in pixels of the drop shadow */ private int m_width = 3; /** the color of the drop shadow */ private Color m_color = Color.BLACK; /** * Constructor. Drop shadow with default width of 2 pixels and black color. */ public ShadowBorder() { this(2); } /** * Constructor. Drop shadow, default shadow color is black. * * @param width the width of the shadow. */ public ShadowBorder(int width) { this(width, Color.BLACK); } /** * Constructor. Drop shadow, width and color are adjustable. * * @param width the width of the shadow. * @param color the color of the shadow. */ public ShadowBorder(int width, Color color) { m_width = width; m_color = color; } /** * Returns a new Insets instance where the top and left are 1, the bottom and * right fields are the border width + 1. * * @param c the component for which this border insets value applies * @return a new Insets object initialized as stated above. */ @Override public Insets getBorderInsets(Component c) { return new Insets(1, 1, m_width + 1, m_width + 1); } /** * Reinitialies the <code>insets</code> parameter with this ShadowBorder's * current Insets. * * @param c the component for which this border insets value applies * @param insets the object to be reinitialized * @return the given <code>insets</code> object */ @Override public Insets getBorderInsets(Component c, Insets insets) { insets.top = 1; insets.left = 1; insets.bottom = m_width + 1; insets.right = m_width + 1; return insets; } /** * This implementation always returns true. * * @return true */ @Override public boolean isBorderOpaque() { return true; } /** * Paints the drop shadow border around the given component. * * @param c the component for which this border is being painted * @param g the paint graphics * @param x the x position of the painted border * @param y the y position of the painted border * @param width the width of the painted border * @param height the height of the painted border */ @Override public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { Color old_color = g.getColor(); int x1, y1, x2, y2; g.setColor(m_color); // outline g.drawRect(x, y, width - m_width - 1, height - m_width - 1); // the drop shadow for (int i = 0; i <= m_width; i++) { // bottom shadow x1 = x + m_width; y1 = y + height - i; x2 = x + width; y2 = y1; g.drawLine(x1, y1, x2, y2); // right shadow x1 = x + width - m_width + i; y1 = y + m_width; x2 = x1; y2 = y + height; g.drawLine(x1, y1, x2, y2); } // fill in the corner rectangles with the background color of the parent // container if (c.getParent() != null) { g.setColor(c.getParent().getBackground()); for (int i = 0; i <= m_width; i++) { x1 = x; y1 = y + height - i; x2 = x + m_width; y2 = y1; g.drawLine(x1, y1, x2, y2); x1 = x + width - m_width; y1 = y + i; x2 = x + width; y2 = y1; g.drawLine(x1, y1, x2, y2); } // add some slightly darker colored triangles g.setColor(g.getColor().darker()); for (int i = 0; i < m_width; i++) { // bottom left triangle x1 = x + i + 1; y1 = y + height - m_width + i; x2 = x + m_width; y2 = y1; g.drawLine(x1, y1, x2, y2); // top right triangle x1 = x + width - m_width; y1 = y + i + 1; x2 = x1 + i; y2 = y1; g.drawLine(x1, y1, x2, y2); } } g.setColor(old_color); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow/StepEditorDialog.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * StepEditorDialog.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.gui.knowledgeflow; import weka.core.Environment; import weka.core.EnvironmentHandler; import weka.core.Utils; import weka.gui.PropertyDialog; import weka.gui.SettingsEditor; import weka.knowledgeflow.steps.Step; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextPane; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Font; import java.awt.Frame; import java.awt.GridLayout; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.IOException; import java.lang.reflect.Method; /** * Base class for step editor dialogs. Clients can extend this in order to * supply their own custom dialogs. The constructor for this class provides OK * and Cancel buttons in the SOUTH location of a BorderLayout. To do meaningful * things on click of OK or Cancel, subclasses should override okPressed() * and/or cancelPressed(). If setStepToEdit() is not overridden, then this class * will also provide an "about" panel in the NORTH location of BorderLayout. * This then leaves the CENTER of the BorderLayout for custom widgets. * Subclasses should typically override the no-op layoutEditor() method to add * their widgets. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public abstract class StepEditorDialog extends JPanel implements EnvironmentHandler { /** For serialization */ private static final long serialVersionUID = -4860182109190301676L; /** True if the step's properties have been altered */ protected boolean m_isEdited; /** Environment variables */ protected Environment m_env = Environment.getSystemWide(); /** Holder for buttons */ protected JPanel m_buttonHolder = new JPanel(new GridLayout(1, 0)); /** OK button */ protected JButton m_okBut = new JButton("OK"); /** Cancel button */ protected JButton m_cancelBut = new JButton("Cancel"); /** Settings button */ protected JButton m_settingsBut = new JButton("Settings"); /** Reference to the main perspective */ protected MainKFPerspective m_mainPerspective; /** Parent window */ protected Window m_parent; /** Listener to be informed when the window closes */ protected ClosingListener m_closingListener; /** The step to edit */ protected Step m_stepToEdit; /** Buffer to hold the help text */ protected StringBuilder m_helpText = new StringBuilder(); /** About button */ protected JButton m_helpBut = new JButton("About"); /** The handler for graphical commands */ protected KFGraphicalEnvironmentCommandHandler m_commandHandler; /** * Constructor */ public StepEditorDialog() { setLayout(new BorderLayout()); m_buttonHolder.add(m_okBut); m_buttonHolder.add(m_cancelBut); add(m_buttonHolder, BorderLayout.SOUTH); m_okBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { ok(); } }); m_cancelBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { cancel(); } }); } /** * Set the main perspective * * @param main the main perspective */ protected void setMainPerspective(MainKFPerspective main) { m_mainPerspective = main; m_commandHandler = new KFGraphicalEnvironmentCommandHandler(m_mainPerspective); } /** * Get the main knowledgeflow perspective * * @return the main knowledge flow perspective */ protected MainKFPerspective getMainPerspective() { return m_mainPerspective; } /** * Get the environment for performing commands at the application-level in a * graphical environment. * * @return the graphical environment command handler. */ protected KFGraphicalEnvironmentCommandHandler getGraphicalEnvironmentCommandHandler() { return m_commandHandler; } /** * Show an error dialog * * @param cause an exception to show in the dialog */ protected void showErrorDialog(Exception cause) { m_mainPerspective.showErrorDialog(cause); } /** * Show an information dialog * * @param information the information to show * @param title the title for the dialog * @param isWarning true if this is a warning rather than general information */ protected void showInfoDialog(Object information, String title, boolean isWarning) { m_mainPerspective.showInfoDialog(information, title, isWarning); } /** * Get the step being edited * * @return */ protected Step getStepToEdit() { return m_stepToEdit; } /** * Set the step to edit * * @param step the step to edit */ protected void setStepToEdit(Step step) { m_stepToEdit = step; createAboutPanel(step); if (step.getDefaultSettings() != null) { addSettingsButton(); } layoutEditor(); } /** * Layout the editor. This is a no-op method that subclasses should override */ protected void layoutEditor() { // subclasses can override to add their // stuff to the center of the borderlayout } /** * Adds a button for popping up a settings editor. Is only visible if the step * being edited provides default settings */ protected void addSettingsButton() { getMainPerspective().getMainApplication().getApplicationSettings() .applyDefaults(getStepToEdit().getDefaultSettings()); m_buttonHolder.add(m_settingsBut); m_settingsBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { SettingsEditor.showSingleSettingsEditor(getMainPerspective() .getMainApplication().getApplicationSettings(), getStepToEdit() .getDefaultSettings().getID(), getStepToEdit().getName(), StepEditorDialog.this); } catch (IOException ex) { showErrorDialog(ex); } } }); } /** * Set the parent window of this dialog * * @param parent the parent window */ protected void setParentWindow(Window parent) { m_parent = parent; } /** * Set a closing listener * * @param c the closing listener */ protected void setClosingListener(ClosingListener c) { m_closingListener = c; } /** * Returns true if the properties of the step being edited have been changed * * @return true if the step has been edited */ protected boolean isEdited() { return m_isEdited; } /** * Set whether the step's properties have changed or not * * @param edited true if the step has been edited */ protected void setEdited(boolean edited) { m_isEdited = edited; } private void ok() { setEdited(true); okPressed(); if (m_parent != null) { m_parent.dispose(); } if (m_closingListener != null) { m_closingListener.closing(); } } /** * Called when the OK button is pressed. This is a no-op method - subclasses * should override */ protected void okPressed() { // subclasses to override } /** * Called when the Cancel button is pressed. This is a no-op method - * subclasses should override */ protected void cancelPressed() { // subclasses to override } private void cancel() { setEdited(false); cancelPressed(); if (m_parent != null) { m_parent.dispose(); } if (m_closingListener != null) { m_closingListener.closing(); } } /** * Creates an "about" panel to add to the dialog * * @param step the step from which to extract help info */ protected void createAboutPanel(Step step) { String globalFirstSentence = ""; String globalInfo = Utils.getGlobalInfo(step, false); if (globalInfo == null) { globalInfo = "No info available"; globalFirstSentence = globalInfo; } else { globalInfo = globalInfo.replace("font color=blue", "font color=black"); try { Method gI = step.getClass().getMethod("globalInfo"); String globalInfoNoHTML = gI.invoke(step).toString(); globalFirstSentence = globalInfoNoHTML.contains(".") ? globalInfoNoHTML.substring(0, globalInfoNoHTML.indexOf('.')) : globalInfoNoHTML; } catch (Exception ex) { ex.printStackTrace(); } } createAboutPanel(globalInfo, globalFirstSentence); } private void createAboutPanel(String about, String firstSentence) { JTextArea jt = new JTextArea(); m_helpText.append(about); jt.setColumns(30); // jt.setContentType("text/html"); jt.setFont(new Font("SansSerif", Font.PLAIN, 12)); jt.setEditable(false); jt.setLineWrap(true); jt.setWrapStyleWord(true); jt.setText(firstSentence); jt.setBackground(getBackground()); String className = m_stepToEdit.getClass().getName(); className = className.substring(className.lastIndexOf('.') + 1, className.length()); m_helpBut.setToolTipText("More information about " + className); final JPanel jp = new JPanel(); jp.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createTitledBorder("About"), BorderFactory.createEmptyBorder(5, 5, 5, 5))); jp.setLayout(new BorderLayout()); jp.add(new JScrollPane(jt), BorderLayout.CENTER); JPanel p2 = new JPanel(); p2.setLayout(new BorderLayout()); p2.add(m_helpBut, BorderLayout.NORTH); jp.add(p2, BorderLayout.EAST); add(jp, BorderLayout.NORTH); int preferredWidth = jt.getPreferredSize().width; jt.setSize(new Dimension(Math.min(preferredWidth, 600), Short.MAX_VALUE)); Dimension d = jt.getPreferredSize(); jt.setPreferredSize(new Dimension(Math.min(preferredWidth, 600), d.height)); m_helpBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent a) { openHelpFrame(jp); m_helpBut.setEnabled(false); } }); } private void openHelpFrame(JPanel aboutPanel) { JTextPane ta = new JTextPane(); ta.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); ta.setContentType("text/html"); // ta.setLineWrap(true); // ta.setWrapStyleWord(true); // ta.setBackground(getBackground()); ta.setEditable(false); ta.setText(m_helpText.toString()); ta.setCaretPosition(0); JDialog jdtmp; if (PropertyDialog.getParentDialog(this) != null) { jdtmp = new JDialog(PropertyDialog.getParentDialog(this), "Information"); } else if (PropertyDialog.getParentFrame(this) != null) { jdtmp = new JDialog(PropertyDialog.getParentFrame(this), "Information"); } else { jdtmp = new JDialog((Frame) null, "Information"); } final JDialog jd = jdtmp; jd.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { jd.dispose(); m_helpBut.setEnabled(true); } }); jd.getContentPane().setLayout(new BorderLayout()); jd.getContentPane().add(new JScrollPane(ta), BorderLayout.CENTER); jd.pack(); jd.setSize(400, 350); jd.setLocation(aboutPanel.getTopLevelAncestor().getLocationOnScreen().x + aboutPanel.getTopLevelAncestor().getSize().width, aboutPanel .getTopLevelAncestor().getLocationOnScreen().y); jd.setVisible(true); } /** * Get environment variables * * @return environment variables */ public Environment getEnvironment() { return m_env; } /** * Set environment variables * * @param env the environment variables to use */ @Override public void setEnvironment(Environment env) { m_env = env; } /** * Substitute the values of any environment variables present in the supplied * string * * @param source the source string to substitute vars in * @return the string with any environment variables substituted */ public String environmentSubstitute(String source) { String result = source; if (result != null) { try { result = m_env.substitute(result); } catch (Exception ex) { // ignore } } return result; } /** * Interface for those that want to be notified when this dialog closes */ public interface ClosingListener { void 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/knowledgeflow/StepInteractiveViewer.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * StepInteractiveViewer.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.gui.knowledgeflow; import weka.core.Settings; import weka.core.WekaException; import weka.knowledgeflow.steps.Step; import java.awt.*; /** * Interface for GUI interactive viewer components that can be popped up from * the contextual menu in the Knowledge Flow that appears when you right-click * over a step on the layout. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public interface StepInteractiveViewer { /** * Set the step that owns this viewer. Implementations may want to access data * that has been computed by the step in question. * * @param theStep the step that owns this viewer */ void setStep(Step theStep); /** * Set the main knowledge flow perspective. Implementations can then access * application settings if necessary * * @param perspective the main knowledge flow perspective */ void setMainKFPerspective(MainKFPerspective perspective); /** * Get the main knowledge flow perspective. Implementations can the access * application settings if necessary * * @return */ MainKFPerspective getMainKFPerspective(); /** * Get the name of this viewer * * @return the name of this viewer */ String getViewerName(); /** * Set the parent window for this viewer * * @param parent the parent window */ void setParentWindow(Window parent); /** * Get the settings object * * @return the settings object */ Settings getSettings(); /** * Initialize this viewer. The KnowledgeFlow application will call this method * after constructing the viewer and after calling setStep() and * setParentWindow(). Implementers will typically layout their view in this * method (rather than a constructor) * * @throws WekaException if the initialization fails */ void init() throws WekaException; /** * Called by the KnowledgeFlow application once the enclosing JFrame is * visible */ void nowVisible(); }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow/StepTree.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * StepTree.java * Copyright (C) 2011-2013 University of Waikato, Hamilton, New Zealand * */ package weka.gui.knowledgeflow; import weka.core.PluginManager; import weka.core.Utils; import weka.core.WekaException; import weka.core.WekaPackageClassLoaderManager; import weka.gui.GenericObjectEditor; import weka.gui.GenericPropertiesCreator; import weka.gui.HierarchyPropertyParser; import weka.gui.knowledgeflow.VisibleLayout.LayoutOperation; import weka.knowledgeflow.steps.KFStep; import weka.knowledgeflow.steps.Step; import weka.knowledgeflow.steps.WekaAlgorithmWrapper; import javax.swing.Icon; import javax.swing.JTree; import javax.swing.tree.*; import java.awt.Component; import java.awt.Cursor; import java.awt.event.InputEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.InputStream; import java.lang.annotation.Annotation; import java.util.Arrays; import java.util.Enumeration; import java.util.HashMap; import java.util.Hashtable; import java.util.LinkedHashSet; import java.util.Map; import java.util.Properties; import java.util.Set; /** * Subclass of JTree for displaying available steps. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class StepTree extends JTree { /** Property file that lists built-in steps */ protected static final String STEP_LIST_PROPS = "weka/knowledgeflow/steps/steps.props"; /** * For serialization */ private static final long serialVersionUID = 3646119269455293741L; /** Reference to the main knowledge flow perspective */ protected MainKFPerspective m_mainPerspective; /** Lookup for searching text of global info/tip texts */ protected Map<String, DefaultMutableTreeNode> m_nodeTextIndex = new HashMap<String, DefaultMutableTreeNode>(); /** * Constructor * * @param mainPerspective the main knowledge flow perspective */ public StepTree(MainKFPerspective mainPerspective) { m_mainPerspective = mainPerspective; DefaultMutableTreeNode jtreeRoot = new DefaultMutableTreeNode("Weka"); // populate tree InvisibleTreeModel model = new InvisibleTreeModel(jtreeRoot); model.activateFilter(true); this.setModel(model); setEnabled(true); setToolTipText(""); setShowsRootHandles(true); setCellRenderer(new StepIconRenderer()); DefaultTreeSelectionModel selectionModel = new DefaultTreeSelectionModel(); selectionModel.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); setSelectionModel(selectionModel); addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (((e.getModifiers() & InputEvent.BUTTON1_MASK) != InputEvent.BUTTON1_MASK) || e.isAltDown()) { m_mainPerspective.setFlowLayoutOperation(LayoutOperation.NONE); m_mainPerspective.setPalleteSelectedStep(null); m_mainPerspective.setCursor(Cursor .getPredefinedCursor(Cursor.DEFAULT_CURSOR)); StepTree.this.clearSelection(); } TreePath p = StepTree.this.getSelectionPath(); if (p != null) { if (p.getLastPathComponent() instanceof DefaultMutableTreeNode) { DefaultMutableTreeNode tNode = (DefaultMutableTreeNode) p.getLastPathComponent(); if (tNode.isLeaf()) { Object userObject = tNode.getUserObject(); if (userObject instanceof StepTreeLeafDetails) { try { StepVisual visual = ((StepTreeLeafDetails) userObject).instantiateStep(); m_mainPerspective.setCursor(Cursor .getPredefinedCursor(Cursor.CROSSHAIR_CURSOR)); if (m_mainPerspective.getDebug()) { System.err.println("Instantiated " + visual.getStepName()); } m_mainPerspective.setPalleteSelectedStep(visual .getStepManager()); } catch (Exception ex) { m_mainPerspective.showErrorDialog(ex); } } } } } } }); try { populateTree(jtreeRoot); } catch (Exception ex) { ex.printStackTrace(); } expandRow(0); setRootVisible(false); } /** * Populates the tree from the given root * * @param jtreeRoot the root to populate * @throws Exception if a problem occurs */ protected void populateTree(DefaultMutableTreeNode jtreeRoot) throws Exception { Properties GOEProps = initGOEProps(); // builtin steps don't get added to the plugin manager because, // due to the package loading process, they would get added after // any plugin steps. This would stuff up the ordering we want in // the design palette InputStream inputStream = getClass().getClassLoader().getResourceAsStream(STEP_LIST_PROPS); Properties builtinSteps = new Properties(); builtinSteps.load(inputStream); inputStream.close(); inputStream = null; String stepClassNames = builtinSteps.getProperty("weka.knowledgeflow.steps.Step"); String[] s = stepClassNames.split(","); Set<String> stepImpls = new LinkedHashSet<String>(); stepImpls.addAll(Arrays.asList(s)); populateTree(stepImpls, jtreeRoot, GOEProps); // get any plugin steps here Set<String> stepClasses = PluginManager.getPluginNamesOfType("weka.knowledgeflow.steps.Step"); if (stepClasses != null && stepClasses.size() > 0) { // filtering here because the LegacyFlowLoader adds all builtin // steps to the PluginManager. This is really only necessary if // a KnowledgeFlowApp is constructed a second time, as the first // time round StepTree gets constructed before the LegacyFlowLoader // class gets loaded into the classpath (and thus populates the // PluginManager). We can remove this filtering when LegacyFlowLoader // is no longer needed. Set<String> filteredStepClasses = new LinkedHashSet<String>(); for (String plugin : stepClasses) { if (!stepClassNames.contains(plugin)) { filteredStepClasses.add(plugin); } } populateTree(filteredStepClasses, jtreeRoot, GOEProps); } } /** * Populate the tree from the given root using a set of step classes * * @param stepClasses the set of step classes to go into the tree * @param jtreeRoot the root of the tree * @param GOEProps generic object editor properties * @throws Exception if a problem occurs */ protected void populateTree(Set<String> stepClasses, DefaultMutableTreeNode jtreeRoot, Properties GOEProps) throws Exception { for (String stepClass : stepClasses) { try { Step toAdd = // (Step) Beans.instantiate(getClass().getClassLoader(), stepClass); (Step) WekaPackageClassLoaderManager.objectForName(stepClass); // check for ignore if (toAdd.getClass().getAnnotation(StepTreeIgnore.class) != null || toAdd.getClass().getAnnotation(weka.gui.beans.KFIgnore.class) != null) { continue; } String category = getStepCategory(toAdd); DefaultMutableTreeNode targetFolder = getCategoryFolder(jtreeRoot, category); if (toAdd instanceof WekaAlgorithmWrapper) { populateForWekaWrapper(targetFolder, (WekaAlgorithmWrapper) toAdd, GOEProps); } else { StepTreeLeafDetails leafData = new StepTreeLeafDetails(toAdd); DefaultMutableTreeNode fixedLeafNode = new InvisibleNode(leafData); targetFolder.add(fixedLeafNode); String tipText = leafData.getToolTipText() != null ? leafData.getToolTipText() : ""; m_nodeTextIndex.put(stepClass.toLowerCase() + " " + tipText, fixedLeafNode); } } catch (Exception ex) { ex.printStackTrace(); } } } /** * Populates a target folder in the tree for a particular class of weka * algorithm wrapper step * * @param targetFolder the folder to populate * @param wrapper the {@code WekaAlgorithmWrapper} implementation * @param GOEProps generic object editor properties * @throws Exception if a problem occurs */ protected void populateForWekaWrapper(DefaultMutableTreeNode targetFolder, WekaAlgorithmWrapper wrapper, Properties GOEProps) throws Exception { Class wrappedAlgoClass = wrapper.getWrappedAlgorithmClass(); String implList = GOEProps.getProperty(wrappedAlgoClass.getCanonicalName()); String hppRoot = wrappedAlgoClass.getCanonicalName(); hppRoot = hppRoot.substring(0, hppRoot.lastIndexOf('.')); if (implList == null) { throw new WekaException( "Unable to get a list of weka implementations for " + "class '" + wrappedAlgoClass.getCanonicalName() + "'"); } Hashtable<String, String> roots = GenericObjectEditor.sortClassesByRoot(implList); for (Map.Entry<String, String> e : roots.entrySet()) { String classes = e.getValue(); HierarchyPropertyParser hpp = new HierarchyPropertyParser(); hpp.build(classes, ", "); hpp.goTo(hppRoot); processPackage(hpp, targetFolder, wrapper); } } /** * Processes a package from the {@code HierarchPropertyParser} * * @param hpp the property parser to use * @param parentFolder the folder to populate * @param wrapper the {@code WekaAlgorithmWrapper} implementation to use for * the class of algorithm being processed * @throws Exception if a problem occurs */ protected void processPackage(HierarchyPropertyParser hpp, DefaultMutableTreeNode parentFolder, WekaAlgorithmWrapper wrapper) throws Exception { String[] primaryPackages = hpp.childrenValues(); for (String primaryPackage : primaryPackages) { hpp.goToChild(primaryPackage); if (hpp.isLeafReached()) { String algName = hpp.fullValue(); Object wrappedA = // Beans.instantiate(this.getClass().getClassLoader(), algName); WekaPackageClassLoaderManager.objectForName(algName); if (wrappedA.getClass().getAnnotation(StepTreeIgnore.class) == null && wrappedA.getClass().getAnnotation(weka.gui.beans.KFIgnore.class) == null) { WekaAlgorithmWrapper wrapperCopy = /* * (WekaAlgorithmWrapper) Beans.instantiate(this.getClass() * .getClassLoader(), wrapper.getClass().getCanonicalName()); */ (WekaAlgorithmWrapper) wrapper.getClass().newInstance(); wrapperCopy.setWrappedAlgorithm(wrappedA); StepTreeLeafDetails leafData = new StepTreeLeafDetails(wrapperCopy); DefaultMutableTreeNode wrapperLeafNode = new InvisibleNode(leafData); parentFolder.add(wrapperLeafNode); String tipText = leafData.getToolTipText() != null ? leafData.getToolTipText() : ""; m_nodeTextIndex.put(algName.toLowerCase() + " " + tipText, wrapperLeafNode); } hpp.goToParent(); } else { DefaultMutableTreeNode firstLevelOfMainAlgoType = new InvisibleNode(primaryPackage); parentFolder.add(firstLevelOfMainAlgoType); processPackage(hpp, firstLevelOfMainAlgoType, wrapper); hpp.goToParent(); } } } /** * Get a folder for a particular category from the tree. Creates the category * folder if it doesn't already exist * * @param jtreeRoot the root of the tree * @param category the name of the category to get the folder for * @return return the folder */ protected DefaultMutableTreeNode getCategoryFolder( DefaultMutableTreeNode jtreeRoot, String category) { DefaultMutableTreeNode targetFolder = null; @SuppressWarnings("unchecked") Enumeration<TreeNode> children = jtreeRoot.children(); while (children.hasMoreElements()) { Object child = children.nextElement(); if (child instanceof DefaultMutableTreeNode) { if (((DefaultMutableTreeNode) child).getUserObject().toString() .equals(category)) { targetFolder = (DefaultMutableTreeNode) child; break; } } } if (targetFolder == null) { targetFolder = new InvisibleNode(category); jtreeRoot.add(targetFolder); } return targetFolder; } /** * Gets the category that the supplied step belongs to. Uses the info in the * {@code KFStep} annotation; otherwise the default "Plugin" category is used. * * @param toAdd the step to get the category for * @return the category name */ protected String getStepCategory(Step toAdd) { String category = "Plugin"; Annotation a = toAdd.getClass().getAnnotation(KFStep.class); if (a != null) { category = ((KFStep) a).category(); } return category; } /** * Initializes generic object editor properties * * @return a properties object * @throws Exception if a problem occurs */ protected Properties initGOEProps() throws Exception { Properties GOEProps = GenericPropertiesCreator.getGlobalOutputProperties(); if (GOEProps == null) { GenericPropertiesCreator creator = new GenericPropertiesCreator(); if (creator.useDynamic()) { creator.execute(false); GOEProps = creator.getOutputProperties(); } else { GOEProps = Utils.readProperties("weka/gui/GenericObjectEditor.props"); } } return GOEProps; } /** * Get tool tip text for the step closest to the mouse location in the * {@code StepTree}. * * @param e the {@code MouseEvent} containing the pointer location * @return the tool tip for the closest step in the tree */ @Override public String getToolTipText(MouseEvent e) { if ((getRowForLocation(e.getX(), e.getY())) == -1) { return null; } TreePath currPath = getPathForLocation(e.getX(), e.getY()); if (currPath.getLastPathComponent() instanceof DefaultMutableTreeNode) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) currPath.getLastPathComponent(); if (node.isLeaf()) { StepTreeLeafDetails leaf = (StepTreeLeafDetails) node.getUserObject(); return leaf.getToolTipText(); } } return null; } /** * Turn on or off tool tip text popups for the steps in the tree * * @param show true if tool tip text popups are to be shown */ public void setShowLeafTipText(boolean show) { DefaultMutableTreeNode root = (DefaultMutableTreeNode) getModel().getRoot(); Enumeration e = root.depthFirstEnumeration(); while (e.hasMoreElements()) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.nextElement(); if (node.isLeaf()) { ((StepTreeLeafDetails) node.getUserObject()).setShowTipTexts(show); } } } /** * Get the global info/tool tip text index * * @return the global info/tool tip text index */ protected Map<String, DefaultMutableTreeNode> getNodeTextIndex() { return m_nodeTextIndex; } protected static class StepIconRenderer extends DefaultTreeCellRenderer { /** Added ID to avoid warning. */ private static final long serialVersionUID = -4488876734500244945L; @Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus); if (leaf) { Object userO = ((DefaultMutableTreeNode) value).getUserObject(); if (userO instanceof StepTreeLeafDetails) { Icon i = ((StepTreeLeafDetails) userO).getIcon(); if (i != null) { setIcon(i); } } } 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/knowledgeflow/StepTreeIgnore.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * StepTreeIgnore.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.gui.knowledgeflow; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Marker annotation. Used to prevent the Knowledge Flow main perspective from * making a step visible in its design palette. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface StepTreeIgnore { }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow/StepTreeLeafDetails.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * StepTreeLeafDetails.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.gui.knowledgeflow; import weka.core.Utils; import weka.core.WekaPackageClassLoaderManager; import weka.knowledgeflow.StepManagerImpl; import weka.knowledgeflow.steps.KFStep; import weka.knowledgeflow.steps.Step; import weka.knowledgeflow.steps.WekaAlgorithmWrapper; import javax.swing.Icon; import java.io.Serializable; import java.lang.annotation.Annotation; /** * Maintains information about a step in the {@code StepTree} - e.g. tool tip * text, wrapped algorithm name (in the case of a {@code WekaAlgorithmWrapper}. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class StepTreeLeafDetails implements Serializable { /** * For serialization */ private static final long serialVersionUID = 6347861816716877761L; /** Class of the step stored at this leaf */ protected Class m_stepClazz; /** The name of the algorithm wrapped by a WekaAlgorithmWrapper step */ protected String m_wrappedWekaAlgoName = ""; /** * the label (usually derived from the qualified name or wrapped algorithm) * for the leaf */ protected String m_leafLabel = ""; /** icon to display at the leaf (scaled appropriately) */ protected transient Icon m_scaledIcon = null; /** tool tip text to display */ protected String m_toolTipText = null; /** If a tool tip text is set, whether to show it or not */ protected boolean m_showTipText = true; /** * Constructor * * @param step the step to wrap in this {@code StepTreeLeafDetails} instance */ public StepTreeLeafDetails(Object step) { this(step, true); } /** * Constructor * * @param step the step to wrap in this {@code StepTreeLeafDetails} instance * @param showTipText true if the tool tip text should be shown for this * instance */ public StepTreeLeafDetails(Object step, boolean showTipText) { m_stepClazz = step.getClass(); Annotation[] annotations = m_stepClazz.getAnnotations(); for (Annotation a : annotations) { if (a instanceof KFStep) { m_leafLabel = ((KFStep) a).name(); if (showTipText) { m_toolTipText = ((KFStep) a).toolTipText(); } break; } } if (step instanceof Step) { m_leafLabel = ((Step) step).getName(); } if (step instanceof WekaAlgorithmWrapper) { m_wrappedWekaAlgoName = ((WekaAlgorithmWrapper) step).getWrappedAlgorithm().getClass() .getCanonicalName(); } if (showTipText) { String globalInfo = Utils.getGlobalInfo(step, false); if (globalInfo != null) { m_toolTipText = globalInfo; } } m_scaledIcon = StepVisual.scaleIcon(StepVisual.iconForStep((Step) step), 0.33); } /** * Set whether to show tip text or not * * @param show true to show tip text */ public void setShowTipTexts(boolean show) { m_showTipText = show; } /** * Get the tool tip for this leaf * * @return the tool tip */ public String getToolTipText() { return m_showTipText ? m_toolTipText : null; } /** * Returns the leaf label * * @return the leaf label */ @Override public String toString() { return m_leafLabel; } /** * Gets the icon for this bean * * @return the icon for this bean */ protected Icon getIcon() { return m_scaledIcon; } /** * Returns true if this leaf represents a wrapped Weka algorithm (i.e. filter, * classifier, clusterer etc.). * * @return true if this leaf represents a wrapped algorithm */ public boolean isWrappedAlgorithm() { return m_wrappedWekaAlgoName != null && m_wrappedWekaAlgoName.length() > 0; } /** * Instantiate the step at this leaf and return it wrapped in a StepVisual * * @return a StepVisual instance wrapping a copy of the step at this leaf * @throws Exception if a problem occurs */ public StepVisual instantiateStep() throws Exception { Step step = null; step = /* * (Step) Beans.instantiate(this.getClass().getClassLoader(), * m_stepClazz.getCanonicalName()); */ (Step) m_stepClazz.newInstance(); StepManagerImpl manager = new StepManagerImpl(step); if (step instanceof WekaAlgorithmWrapper) { Object algo = // Beans.instantiate(this.getClass().getClassLoader(), // m_wrappedWekaAlgoName); WekaPackageClassLoaderManager.objectForName(m_wrappedWekaAlgoName); ((WekaAlgorithmWrapper) step).setWrappedAlgorithm(algo); } StepVisual visual = StepVisual.createVisual(manager); return visual; } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow/StepVisual.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * StepVisual.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.gui.knowledgeflow; import weka.core.WekaException; import weka.knowledgeflow.StepManagerImpl; import weka.knowledgeflow.steps.KFStep; import weka.knowledgeflow.steps.Note; import weka.knowledgeflow.steps.Step; import weka.knowledgeflow.steps.WekaAlgorithmWrapper; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Point; import java.awt.RenderingHints; import java.awt.Toolkit; import java.beans.Beans; import java.io.IOException; import java.io.InputStream; import java.util.Map; import java.util.Set; /** * Class for managing the appearance of a step in the GUI Knowledge Flow * environment. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class StepVisual extends JPanel { /** Standard base path for Step icons */ public static final String BASE_ICON_PATH = KFGUIConsts.BASE_ICON_PATH; /** * For serialization */ private static final long serialVersionUID = 4156046438296843760L; /** The x coordinate of the step on the graphical layout */ protected int m_x; /** The y coordinate of the step on the graphical layout */ protected int m_y; /** The icon for the step this visual represents */ protected ImageIcon m_icon; /** Whether to display connector dots */ protected boolean m_displayConnectors; /** Current connector dot colour */ protected Color m_connectorColor = Color.blue; /** * The step manager for the step this visual represents */ protected StepManagerImpl m_stepManager; /** * Private constructor. Use factory methods. */ private StepVisual(ImageIcon icon) { m_icon = icon; if (icon != null) { setLayout(new BorderLayout()); setOpaque(false); JLabel visual = new JLabel(m_icon); add(visual, BorderLayout.CENTER); Dimension d = visual.getPreferredSize(); Dimension d2 = new Dimension((int) d.getWidth() + 10, (int) d.getHeight() + 10); setMinimumSize(d2); setPreferredSize(d2); setMaximumSize(d2); } } /** * Constructor */ protected StepVisual() { this(null); } /** * Create a visual for the step managed by the supplied step manager. Uses the * icon specified by the step itself (via the {@code KFStep} annotation) * * @param stepManager the step manager for the step to create a visual wrapper * for * @return the {@code StepVisual} that wraps the step */ public static StepVisual createVisual(StepManagerImpl stepManager) { if (stepManager.getManagedStep() instanceof Note) { NoteVisual wrapper = new NoteVisual(); wrapper.setStepManager(stepManager); return wrapper; } else { ImageIcon icon = iconForStep(stepManager.getManagedStep()); return createVisual(stepManager, icon); } } /** * Create a visual for the step managed by the supplied step manager using the * supplied icon. * * @param stepManager the step manager for the step to create a visual wrapper * for * @param icon the icon to use in the visual * @return the {@code StepVisual} that wraps the step */ public static StepVisual createVisual(StepManagerImpl stepManager, ImageIcon icon) { StepVisual wrapper = new StepVisual(icon); wrapper.setStepManager(stepManager); return wrapper; } /** * Gets the icon for the supplied {@code Step}. * * @param step the step to get the icon for * @return the icon for the step */ public static ImageIcon iconForStep(Step step) { KFStep stepAnnotation = step.getClass().getAnnotation(KFStep.class); if (stepAnnotation != null && stepAnnotation.iconPath() != null && stepAnnotation.iconPath().length() > 0) { return loadIcon(step.getClass().getClassLoader(), stepAnnotation.iconPath()); } if (step instanceof WekaAlgorithmWrapper) { ImageIcon icon = loadIcon(((WekaAlgorithmWrapper) step).getWrappedAlgorithm().getClass().getClassLoader(), ((WekaAlgorithmWrapper) step).getIconPath()); if (icon == null) { // try package default for this class of wrapped algorithm icon = loadIcon(((WekaAlgorithmWrapper) step) .getDefaultPackageLevelIconPath()); } if (icon == null) { // try default for this class of wrapped algorithm icon = loadIcon(((WekaAlgorithmWrapper) step).getDefaultIconPath()); } return icon; } // TODO default icon for non-wrapped steps return null; } /** * Load an icon from the supplied path * * @param iconPath the path to load from * @return an icon */ public static ImageIcon loadIcon(String iconPath) { return loadIcon(StepVisual.class.getClassLoader(), iconPath); } /** * Load an icon from the supplied path * * @param classLoader the classloader to use for finding the resource * @param iconPath the path to load from * @return an icon */ public static ImageIcon loadIcon(ClassLoader classLoader, String iconPath) { // java.net.URL imageURL = classLoader.getResource(iconPath); InputStream imageStream = classLoader.getResourceAsStream(iconPath); // if (imageURL != null) { if (imageStream != null) { // Image pic = Toolkit.getDefaultToolkit().getImage(imageURL); try { Image pic = ImageIO.read(imageStream); return new ImageIcon(pic); } catch (IOException ex) { ex.printStackTrace(); } finally { try { imageStream.close(); } catch (IOException ex) { // ignore } } } return null; } /** * Scale the supplied icon by the given factor * * @param icon the icon to scale * @param factor the factor to scale by * @return the scaled icon */ public static ImageIcon scaleIcon(ImageIcon icon, double factor) { Image pic = icon.getImage(); double width = icon.getIconWidth(); double height = icon.getIconHeight(); width *= factor; height *= factor; pic = pic.getScaledInstance((int) width, (int) height, Image.SCALE_SMOOTH); return new ImageIcon(pic); } /** * Get the icon for this visual at the given scale factor * * @param scale the factor to scale the icon by * @return the scaled icon */ public Image getIcon(double scale) { if (scale == 1) { return m_icon.getImage(); } Image pic = m_icon.getImage(); double width = m_icon.getIconWidth(); double height = m_icon.getIconHeight(); width *= scale; height *= scale; pic = pic.getScaledInstance((int) width, (int) height, Image.SCALE_SMOOTH); return pic; } /** * Convenience method for getting the name of the step that this visual wraps * * @return the name of the step */ public String getStepName() { return m_stepManager.getManagedStep().getName(); } /** * Convenience method for setting the name of the step that this visual wraps * * @param name the name to set on the step */ public void setStepName(String name) { m_stepManager.getManagedStep().setName(name); } /** * Get the x coordinate of this step on the graphical layout * * @return the x coordinate of this step */ @Override public int getX() { return m_x; } /** * Set the x coordinate of this step on the graphical layout * * @param x the x coordinate of this step */ public void setX(int x) { m_x = x; } /** * Get the y coordinate of this step on the graphical layout * * @return the y coordinate of this step */ @Override public int getY() { return m_y; } /** * Set the y coordinate of this step on the graphical layout * * @param y the y coordinate of this step */ public void setY(int y) { m_y = y; } /** * Get the step manager for this visual * * @return the step manager */ public StepManagerImpl getStepManager() { return m_stepManager; } /** * Set the step manager for this visual * * @param manager the step manager to wrap */ public void setStepManager(StepManagerImpl manager) { m_stepManager = manager; } /** * Get the fully qualified name of the custom editor (if any) for the step * wrapped in this visual * * @return the custom editor, or null if the step does not specify one */ public String getCustomEditorForStep() { return m_stepManager.getManagedStep().getCustomEditorForStep(); } /** * Get a set of fully qualified names of interactive viewers that the wrapped * step provides. * * @return a set of fully qualified interactive viewer names, or null if the * step does not have any interactive viewers. */ public Set<String> getStepInteractiveViewActionNames() { Map<String, String> viewComps = m_stepManager.getManagedStep().getInteractiveViewers(); if (viewComps == null) { return null; } return viewComps.keySet(); } /** * Gets an instance of the named step interactive viewer component * * @param viewActionName the action/name for the viewer to get * @return the instantiated viewer component * @throws WekaException if the step does not have any interactive viewers, or * does not provide a viewer with the given action/name */ public JComponent getStepInteractiveViewComponent(String viewActionName) throws WekaException { if (m_stepManager.getManagedStep().getInteractiveViewers() == null) { throw new WekaException("Step '" + m_stepManager.getManagedStep().getName() + "' " + "does not have any interactive view components"); } String clazz = m_stepManager.getManagedStep().getInteractiveViewers() .get(viewActionName); if (clazz == null) { throw new WekaException("Step '" + m_stepManager.getManagedStep().getName() + "' " + "does not have an interactive view component called '" + viewActionName + "'"); } Object comp = null; try { comp = Beans.instantiate(this.getClass().getClassLoader(), clazz); } catch (Exception ex) { throw new WekaException(ex); } if (!(comp instanceof JComponent)) { throw new WekaException("Interactive view component '" + clazz + "' does not " + "extend JComponent"); } return (JComponent) comp; } /** * Returns the coordinates of the closest "connector" point to the supplied * point. Coordinates are in the parent containers coordinate space. * * @param pt the reference point * @return the closest connector point */ public Point getClosestConnectorPoint(Point pt) { int sourceX = getX(); int sourceY = getY(); int sourceWidth = getWidth(); int sourceHeight = getHeight(); int sourceMidX = sourceX + (sourceWidth / 2); int sourceMidY = sourceY + (sourceHeight / 2); int x = (int) pt.getX(); int y = (int) pt.getY(); Point closest = new Point(); int cx = (Math.abs(x - sourceMidX) < Math.abs(y - sourceMidY)) ? sourceMidX : ((x < sourceMidX) ? sourceX : sourceX + sourceWidth); int cy = (Math.abs(y - sourceMidY) < Math.abs(x - sourceMidX)) ? sourceMidY : ((y < sourceMidY) ? sourceY : sourceY + sourceHeight); closest.setLocation(cx, cy); return closest; } /** * Turn on/off the connector points * * @param dc a <code>boolean</code> value */ public void setDisplayConnectors(boolean dc) { // m_visualHolder.setDisplayConnectors(dc); m_displayConnectors = dc; m_connectorColor = Color.blue; repaint(); } /** * Turn on/off the connector points * * @param dc a <code>boolean</code> value * @param c the Color to use */ public void setDisplayConnectors(boolean dc, Color c) { setDisplayConnectors(dc); m_connectorColor = c; } /** * Returns true if the step label is to be displayed. Subclasses can override * to change this. * * @return true (default) if the step label is to be displayed */ public boolean getDisplayStepLabel() { return true; } @Override public void paintComponent(Graphics gx) { ((Graphics2D) gx).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); super.paintComponent(gx); if (m_displayConnectors) { gx.setColor(m_connectorColor); int midx = (int) (this.getWidth() / 2.0); int midy = (int) (this.getHeight() / 2.0); gx.fillOval(midx - 2, 0, 5, 5); gx.fillOval(midx - 2, this.getHeight() - 5, 5, 5); gx.fillOval(0, midy - 2, 5, 5); gx.fillOval(this.getWidth() - 5, midy - 2, 5, 5); } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow/TemplateManager.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * TemplateManager.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.gui.knowledgeflow; import weka.core.Utils; import weka.core.WekaException; import weka.core.PluginManager; import weka.knowledgeflow.Flow; import weka.knowledgeflow.JSONFlowLoader; import javax.swing.JOptionPane; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Properties; /** * Manages all things template-related * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class TemplateManager { // statically register templates that come with Weka static { try { Properties templateProps = Utils.readProperties(KFGUIConsts.TEMPLATE_PROPERTY_FILE); PluginManager.addFromProperties(templateProps, true); } catch (Exception ex) { JOptionPane.showMessageDialog(null, ex.getMessage(), "KnowledgeFlow", JOptionPane.ERROR_MESSAGE); ex.printStackTrace(); } } /** * Get the total number of KF templates available * * @return the total number (both builtin and plugin) KF templates available */ public int numTemplates() { return numBuiltinTemplates() + numPluginTemplates(); } /** * Get the number of builtin KF templates available * * @return the number of builtin KF templates available */ public int numBuiltinTemplates() { return PluginManager .numResourcesForWithGroupID(KFGUIConsts.KF_BUILTIN_TEMPLATE_KEY); } /** * Get the number of plugin KF templates available * * @return the number of plugin KF templates available */ public int numPluginTemplates() { return PluginManager .numResourcesForWithGroupID(KFGUIConsts.KF_PLUGIN_TEMPLATE_KEY); } /** * Get descriptions for the built-in knowledge flow templates * * @return descriptions for the built-in templates */ public List<String> getBuiltinTemplateDescriptions() { List<String> result = new ArrayList<String>(); Map<String, String> builtin = PluginManager .getResourcesWithGroupID(KFGUIConsts.KF_BUILTIN_TEMPLATE_KEY); if (builtin != null) { for (String desc : builtin.keySet()) { result.add(desc); } } return result; } /** * Get descriptions for plugin knowledge flow templates * * @return descriptions for plugin templates */ public List<String> getPluginTemplateDescriptions() { List<String> result = new ArrayList<String>(); Map<String, String> plugin = PluginManager.getResourcesWithGroupID(KFGUIConsts.KF_PLUGIN_TEMPLATE_KEY); if (plugin != null) { for (String desc : plugin.keySet()) { result.add(desc); } } return result; } /** * Get the flow for the supplied description * * @param flowDescription the description of the template flow to get * @return the template flow * @throws WekaException if the template does not exist */ public Flow getTemplateFlow(String flowDescription) throws WekaException { Flow result = null; try { // try builtin first... result = getBuiltinTemplateFlow(flowDescription); } catch (IOException ex) { // ignore } if (result == null) { // now try as a plugin... try { result = getPluginTemplateFlow(flowDescription); } catch (IOException ex) { throw new WekaException("The template flow '" + flowDescription + "' " + "does not seem to exist as a builtin or plugin template"); } } return result; } /** * Get the built-in template flow corresponding to the description * * @param flowDescription the description of the template flow to get * @return the flow * @throws IOException if an IO error occurs * @throws WekaException if a problem occurs */ public Flow getBuiltinTemplateFlow(String flowDescription) throws IOException, WekaException { InputStream flowStream = PluginManager.getPluginResourceAsStream( KFGUIConsts.KF_BUILTIN_TEMPLATE_KEY, flowDescription); JSONFlowLoader loader = new JSONFlowLoader(); return loader.readFlow(flowStream); } /** * Get the plugin template flow corresponding to the description * * @param flowDescription the description of the template flow to get * @return the flow * @throws IOException if an IO error occurs * @throws WekaException if a problem occurs */ public Flow getPluginTemplateFlow(String flowDescription) throws IOException, WekaException { InputStream flowStream = PluginManager.getPluginResourceAsStream( KFGUIConsts.KF_PLUGIN_TEMPLATE_KEY, flowDescription); JSONFlowLoader loader = new JSONFlowLoader(); return loader.readFlow(flowStream); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow/VisibleLayout.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * VisibleLayout.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.gui.knowledgeflow; import weka.core.Copyright; import weka.core.Environment; import weka.core.PluginManager; import weka.core.Settings; import weka.core.WekaException; import weka.gui.beans.LogPanel; import weka.knowledgeflow.BaseExecutionEnvironment; import weka.knowledgeflow.ExecutionFinishedCallback; import weka.knowledgeflow.Flow; import weka.knowledgeflow.FlowExecutor; import weka.knowledgeflow.FlowRunner; import weka.knowledgeflow.JSONFlowUtils; import weka.knowledgeflow.KFDefaults; import weka.knowledgeflow.LogManager; import weka.knowledgeflow.StepManager; import weka.knowledgeflow.StepManagerImpl; import javax.swing.*; import java.awt.*; import java.awt.event.InputEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.File; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Stack; /** * Panel that wraps a flow and makes it visible in the KnowledgeFlow, along with * it's associated log panel * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class VisibleLayout extends JPanel { /** the flow layout width */ protected static final int LAYOUT_WIDTH = 2560; /** the flow layout height */ protected static final int LAYOUT_HEIGHT = 1440; /** The scrollbar increment of the layout scrollpane */ protected static final int SCROLLBAR_INCREMENT = 50; private static final long serialVersionUID = -3644458365810712479L; protected Flow m_flow; /** The log panel to use for this layout */ protected KFLogPanel m_logPanel = new KFLogPanel(); /** Current zoom setting for this layout */ protected int m_zoomSetting = 100; /** Current path on disk for this flow */ protected File m_filePath; /** Keeps track of any highlighted steps on the canvas */ protected List<StepVisual> m_selectedSteps = new ArrayList<StepVisual>(); /** Keeps track of the undo buffer for this flow */ protected Stack<File> m_undoBuffer = new Stack<File>(); /** True if the flow has been edited, but not yet saved */ protected boolean m_hasBeenEdited; /** The flow executor used to execute the flow */ protected FlowExecutor m_flowExecutor; /** Environment variables to use */ protected Environment m_env = new Environment(); /** True if this flow is executing */ protected boolean m_isExecuting; /** A reference to the main perspective */ protected MainKFPerspective m_mainPerspective; /** The steps to be rendered on this layout */ protected List<StepVisual> m_renderGraph = new ArrayList<StepVisual>(); /** The current layout operation */ protected LayoutOperation m_userOpp = LayoutOperation.NONE; /** The panel used to render the flow */ protected LayoutPanel m_layout; /** Reference to the step being edited (if any) */ protected StepVisual m_editStep; /** * The name of the user-selected connection if the user has initiated a * connection from a source step (stored in m_editStep) */ protected String m_editConnection; /** * Constructor * * @param mainPerspective the main Knowledge Flow perspective */ public VisibleLayout(MainKFPerspective mainPerspective) { super(); setLayout(new BorderLayout()); m_flow = new Flow(); m_mainPerspective = mainPerspective; m_layout = new LayoutPanel(this); JPanel p1 = new JPanel(); p1.setLayout(new BorderLayout()); JScrollPane js = new JScrollPane(m_layout); p1.add(js, BorderLayout.CENTER); js.getVerticalScrollBar().setUnitIncrement( KFDefaults.SCROLL_BAR_INCREMENT_LAYOUT); js.getHorizontalScrollBar().setUnitIncrement( KFDefaults.SCROLL_BAR_INCREMENT_LAYOUT); m_layout.setSize(m_mainPerspective.getSetting(KFDefaults.LAYOUT_WIDTH_KEY, KFDefaults.LAYOUT_WIDTH), m_mainPerspective.getSetting( KFDefaults.LAYOUT_HEIGHT_KEY, KFDefaults.LAYOUT_HEIGHT)); Dimension d = m_layout.getPreferredSize(); m_layout.setMinimumSize(d); m_layout.setPreferredSize(d); m_logPanel = new KFLogPanel(); setUpLogPanel(m_logPanel); Dimension d2 = new Dimension(100, 170); m_logPanel.setPreferredSize(d2); m_logPanel.setMinimumSize(d2); m_filePath = new File("-NONE-"); JSplitPane p2 = new JSplitPane(JSplitPane.VERTICAL_SPLIT, p1, m_logPanel); p2.setOneTouchExpandable(true); p2.setDividerLocation(0.7); // p2.setDividerLocation(500); p2.setResizeWeight(1.0); add(p2, BorderLayout.CENTER); } /** * Get a list of the steps (wrapped in {@code StepVisual} instances) that make * up the flow rendered/edited by this panel * * @return a list of steps */ protected List<StepVisual> getRenderGraph() { return m_renderGraph; } /** * Get the main perspective that owns this layout * * @return the main perspective */ protected MainKFPerspective getMainPerspective() { return m_mainPerspective; } /** * Get the step currently being "edited". Returns null if no step is being * edited * * @return the step being edited */ protected StepVisual getEditStep() { return m_editStep; } /** * Set the step to "edit" * * @param step the step to edit */ protected void setEditStep(StepVisual step) { m_editStep = step; } /** * If the user has initiated the connection process, then this method returns * the name of the connection involved * * @return the name of the connection if the user has initiated the connection * process */ protected String getEditConnection() { return m_editConnection; } /** * Set the name of the connection involved in a connection operation * * @param connName the name of the connection */ protected void setEditConnection(String connName) { m_editConnection = connName; } /** * Get the list of selected steps. The list will be empty if there are no * selected (highlighted) steps on the canvas. * * @return the list of selected steps */ protected List<StepVisual> getSelectedSteps() { return m_selectedSteps; } /** * Set a list of steps to be considered "selected". Setting an empty list * clears any current selection. * * @param selected a list of steps to be considered as selected */ protected void setSelectedSteps(List<StepVisual> selected) { // turn off any set ones for (StepVisual s : m_selectedSteps) { s.setDisplayConnectors(false); } m_selectedSteps = selected; // highlight any new ones for (StepVisual s : m_selectedSteps) { s.setDisplayConnectors(true); } if (m_selectedSteps.size() > 0) { m_mainPerspective.getMainToolBar().enableWidgets( MainKFPerspectiveToolBar.Widgets.CUT_BUTTON.toString(), MainKFPerspectiveToolBar.Widgets.COPY_BUTTON.toString(), MainKFPerspectiveToolBar.Widgets.DELETE_BUTTON.toString()); } else { m_mainPerspective.getMainToolBar().disableWidgets( MainKFPerspectiveToolBar.Widgets.CUT_BUTTON.toString(), MainKFPerspectiveToolBar.Widgets.COPY_BUTTON.toString(), MainKFPerspectiveToolBar.Widgets.DELETE_BUTTON.toString()); } } /** * Removes the currently selected list of steps from the layout * * @throws WekaException if a problem occurs */ protected void removeSelectedSteps() throws WekaException { addUndoPoint(); for (StepVisual v : m_selectedSteps) { m_flow.removeStep(v.getStepManager()); m_renderGraph.remove(v); m_layout.remove(v); String key = v.getStepName() + "$" + v.getStepManager().getManagedStep().hashCode(); m_logPanel.statusMessage(key + "|remove"); } setSelectedSteps(new ArrayList<StepVisual>()); m_mainPerspective.getMainToolBar().disableWidgets( MainKFPerspectiveToolBar.Widgets.DELETE_BUTTON.toString()); m_mainPerspective.getMainToolBar().enableWidget( MainKFPerspectiveToolBar.Widgets.SELECT_ALL_BUTTON.toString(), m_flow.size() > 0); m_layout.repaint(); } /** * Copies the currently selected list of steps to the global clipboard * * @throws WekaException if a problem occurs */ protected void copySelectedStepsToClipboard() throws WekaException { copyStepsToClipboard(getSelectedSteps()); } /** * Copies the supplied list of steps to the global clipboard * * @param steps the steps to copy to the clipboard * @throws WekaException if a problem occurs */ protected void copyStepsToClipboard(List<StepVisual> steps) throws WekaException { m_mainPerspective.copyStepsToClipboard(steps); } /** * Pastes the contents (if any) of the global clipboard to this layout * * @param x the x coordinate to paste at * @param y the y cooridinate to paste at * @throws WekaException if a problem occurs */ protected void pasteFromClipboard(int x, int y) throws WekaException { addUndoPoint(); Flow fromPaste = Flow.JSONToFlow(m_mainPerspective.getPasteBuffer(), true); List<StepVisual> added = addAll(fromPaste.getSteps(), false); // adjust x,y coords of pasted steps. Look for the smallest // x and the smallest y (top left corner of bounding box) int minX = Integer.MAX_VALUE; int minY = Integer.MAX_VALUE; for (StepVisual v : added) { if (v.getX() < minX) { minX = v.getX(); } if (v.getY() < minY) { minY = v.getY(); } } int deltaX = x - minX; int deltaY = y - minY; for (StepVisual v : added) { v.setX(v.getX() + deltaX); v.setY(v.getY() + deltaY); } m_layout.revalidate(); m_layout.repaint(); setSelectedSteps(added); } /** * Add an undo point */ protected void addUndoPoint() { try { File tempFile = File.createTempFile("knowledgeflow", MainKFPerspective.FILE_EXTENSION_JSON); tempFile.deleteOnExit(); JSONFlowUtils.writeFlow(m_flow, tempFile); m_undoBuffer.push(tempFile); if (m_undoBuffer.size() > m_mainPerspective.getSetting( KFDefaults.MAX_UNDO_POINTS_KEY, KFDefaults.MAX_UNDO_POINTS)) { m_undoBuffer.remove(0); } m_mainPerspective.getMainToolBar().enableWidgets( MainKFPerspectiveToolBar.Widgets.UNDO_BUTTON.toString()); } catch (Exception ex) { m_logPanel .logMessage("[KnowledgeFlow] a problem occurred while trying to " + "create an undo point : " + ex.getMessage()); } } /** * Get the number of entries in the undo stack * * @return the number of entries in the undo stack */ protected int getUndoBufferSize() { return m_undoBuffer.size(); } /** * Snap the selected steps (if any) to the grid */ protected void snapSelectedToGrid() { if (m_selectedSteps.size() > 0) { m_layout.snapSelectedToGrid(); } } /** * Initiate the process of adding a note to the layout */ protected void initiateAddNote() { m_layout.initiateAddNote(); } /** * Get the flow being edited by this layout * * @return the flow being edited by this layout */ public Flow getFlow() { return m_flow; } /** * Set the flow to edit in this layout * * @param flow the flow to edit in this layout */ public void setFlow(Flow flow) { m_flow = flow; m_renderGraph.clear(); Iterator<StepManagerImpl> iter = m_flow.iterator(); m_layout.removeAll(); while (iter.hasNext()) { StepManagerImpl manager = iter.next(); StepVisual visual = StepVisual.createVisual(manager); manager.setStepVisual(visual); m_renderGraph.add(visual); m_layout.add(visual); } m_mainPerspective.getMainToolBar().enableWidget( MainKFPerspectiveToolBar.Widgets.SELECT_ALL_BUTTON.toString(), m_flow.size() > 0); m_layout.revalidate(); m_layout.repaint(); } /** * Add all the supplied steps to the flow managed by this layout * * @param steps the steps to add * @return a list of all the added steps, where each has been wrapped in an * appropriate {@code StepVisual} instance. */ protected List<StepVisual> addAll(List<StepManagerImpl> steps) { return addAll(steps, true); } /** * Add all the supplied steps to the flow managed by this layout * * @param steps the steps to add * @param revalidate true if the GUI should be repainted * @return a list of all the added steps, where each has been wrapped in an * appropriate {@code StepVisual} instance. */ protected List<StepVisual> addAll(List<StepManagerImpl> steps, boolean revalidate) { List<StepVisual> added = new ArrayList<StepVisual>(); m_flow.addAll(steps); for (StepManagerImpl s : steps) { StepVisual visual = StepVisual.createVisual(s); s.setStepVisual(visual); added.add(visual); m_renderGraph.add(visual); m_layout.add(visual); } if (revalidate) { m_layout.repaint(); } return added; } /** * Add the supplied step to the flow managed by this layout * * @param manager the {@code StepManager} instance managing the step to be * added * @param x the x coordinate to add at * @param y the y coordinate to add at */ protected void addStep(StepManagerImpl manager, int x, int y) { m_flow.addStep(manager); StepVisual visual = StepVisual.createVisual(manager); Dimension d = visual.getPreferredSize(); int dx = (int) (d.getWidth() / 2); int dy = (int) (d.getHeight() / 2); x -= dx; y -= dy; if (x >= 0 && y >= 0) { visual.setX(x); visual.setY(y); } // manager will overwrite x and y if this step has been sourced // from JSON and has valid x, y settings manager.setStepVisual(visual); m_renderGraph.add(visual); m_layout.add(visual); visual.setLocation(x, y); m_mainPerspective.setCursor(Cursor .getPredefinedCursor(Cursor.DEFAULT_CURSOR)); m_mainPerspective.getMainToolBar().enableWidget( MainKFPerspectiveToolBar.Widgets.SELECT_ALL_BUTTON.toString(), m_flow.size() > 0); } /** * Connect the supplied source step to the supplied target step using the * specified connection type * * @param source the {@code StepManager} instance managing the source step * @param target the {@code StepManager} instance managing the target step * @param connectionType the connection type to use */ public void connectSteps(StepManagerImpl source, StepManagerImpl target, String connectionType) { if (m_mainPerspective.getDebug()) { System.err.println("[KF] connecting steps: " + source.getName() + " to " + target.getName()); } boolean success = m_flow.connectSteps(source, target, connectionType); if (m_mainPerspective.getDebug()) { if (success) { System.err.println("[KF] connection successful"); } else { System.err.println("[KF] connection failed"); } } m_layout.repaint(); } /** * Rename a step * * @param oldName the old name of the step to rename * @param newName the new name to give the step */ protected void renameStep(String oldName, String newName) { try { m_flow.renameStep(oldName, newName); } catch (WekaException ex) { m_mainPerspective.showErrorDialog(ex); } } /** * Remove a step from the flow displayed/edited by this layout * * @param step the {@code StepVisual} instance wrapping the step to be removed * @throws WekaException if a problem occurs */ protected void removeStep(StepVisual step) throws WekaException { m_flow.removeStep(step.getStepManager()); m_renderGraph.remove(step); m_layout.remove(step); m_layout.repaint(); } /** * Get the number of steps in the layout * * @return the number of steps in the layout */ protected int numSteps() { return m_renderGraph.size(); } /** * Get the environment variables being used by this layout * * @return the environment variables being used by this layout */ public Environment getEnvironment() { return m_env; } /** * Set the environment variables to use with this layout * * @param env the environment variables to use */ public void setEnvironment(Environment env) { m_env = env; } public String environmentSubstitute(String source) { Environment env = m_env != null ? m_env : Environment.getSystemWide(); try { source = env.substitute(source); } catch (Exception ex) { } return source; } /** * Get the {@code FlowExecutor} being used for execution of this flow * * @return the {@code FlowExecutor} in use by this layout */ public FlowExecutor getFlowExecutor() { return m_flowExecutor; } /** * Set the {@code FlowExcecutor} to use for executing the flow * * @param executor the {@code FlowExecutor} to use for executing the flow in * this layout */ public void setFlowExecutor(FlowExecutor executor) { m_flowExecutor = executor; } /** * Get the current path (if any) of the flow being edited in this layout * * @return the current path on disk of the flow */ public File getFilePath() { return m_filePath; } /** * Set the file path for the flow being edited by this layout * * @param path the path on disk for the flow being edited */ public void setFilePath(File path) { m_filePath = path != null ? path : new File("-NONE-"); if (path != null) { File absolute = new File(path.getAbsolutePath()); getEnvironment().addVariable(KFGUIConsts.FLOW_DIRECTORY_KEY, absolute.getParent()); } } /** * Get the log panel in use by this layout * * @return the log panel */ public KFLogPanel getLogPanel() { return m_logPanel; } /** * Get the current zoom setting for this layout * * @return the current zoom setting */ public int getZoomSetting() { return m_zoomSetting; } /** * Set the current zoom setting for this layout * * @param zoom the current zoom setting */ public void setZoomSetting(int zoom) { m_zoomSetting = zoom; } /** * Get whether this flow has been altered since the last save operation * * @return true if the flow has been altered */ public boolean getEdited() { return m_hasBeenEdited; } /** * Set the edited status of this flow * * @param edited true if the flow has been altered */ public void setEdited(boolean edited) { m_hasBeenEdited = edited; // pass on the edited status so that the tab title can be made // bold if necessary m_mainPerspective.setCurrentTabTitleEditedStatus(edited); } /** * Returns true if the flow managed by this layout is currently executing * * @return true if the flow is executing */ public boolean isExecuting() { return m_isExecuting; } /** * Get the current flow edit operation * * @return the current flow edit operation */ protected LayoutOperation getFlowLayoutOperation() { return m_userOpp; } /** * Set the current flow edit operation * * @param mode the current flow edit operation */ protected void setFlowLayoutOperation(LayoutOperation mode) { m_userOpp = mode; } /** * Execute the flow managed by this layout * * @param sequential true if the flow's start points are to be launched * sequentially rather than in parallel * @throws WekaException if a problem occurs */ public synchronized void executeFlow(boolean sequential) throws WekaException { if (isExecuting()) { throw new WekaException("The flow is already executing!"); } Settings appSettings = m_mainPerspective.getMainApplication().getApplicationSettings(); if (m_flowExecutor == null) { String execName = appSettings.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) { // drop through } if (execE == null) { execE = new BaseExecutionEnvironment(); } m_flowExecutor = execE.getDefaultFlowExecutor(); /* * m_flowExecutor = new FlowRunner(m_mainPerspective.getMainApplication() * .getApplicationSettings()); */ m_flowExecutor.setLogger(m_logPanel); m_flowExecutor .addExecutionFinishedCallback(new ExecutionFinishedCallback() { @Override public void executionFinished() { m_isExecuting = false; m_logPanel.statusMessage("@!@[KnowledgeFlow]|OK."); if (m_flowExecutor.wasStopped()) { m_logPanel.setMessageOnAll(false, "Stopped."); } m_mainPerspective.getMainToolBar().enableWidgets( MainKFPerspectiveToolBar.Widgets.PLAY_PARALLEL_BUTTON.toString(), MainKFPerspectiveToolBar.Widgets.PLAY_SEQUENTIAL_BUTTON .toString()); m_mainPerspective.getMainToolBar().disableWidgets( MainKFPerspectiveToolBar.Widgets.STOP_BUTTON.toString()); } }); } m_flowExecutor.setSettings(appSettings); m_mainPerspective.getMainToolBar().disableWidgets( MainKFPerspectiveToolBar.Widgets.PLAY_PARALLEL_BUTTON.toString(), MainKFPerspectiveToolBar.Widgets.PLAY_SEQUENTIAL_BUTTON.toString()); m_mainPerspective.getMainToolBar().enableWidgets( MainKFPerspectiveToolBar.Widgets.STOP_BUTTON.toString()); m_flowExecutor.getExecutionEnvironment().setEnvironmentVariables(m_env); m_flowExecutor.getExecutionEnvironment().setHeadless(false); m_flowExecutor.getExecutionEnvironment() .setGraphicalEnvironmentCommandHandler( new KFGraphicalEnvironmentCommandHandler(m_mainPerspective)); m_isExecuting = true; // Flow toRun = m_flow.copyFlow(); m_flowExecutor.setFlow(m_flow); m_logPanel.clearStatus(); m_logPanel.statusMessage("@!@[KnowledgeFlow]|Executing..."); if (sequential) { m_flowExecutor.runSequentially(); } else { m_flowExecutor.runParallel(); } } /** * Stop the flow from executing */ public void stopFlow() { if (isExecuting()) { m_flowExecutor.stopProcessing(); } } /** * Find the first step whose bounds enclose the supplied point * * @param p the point * @return the first step in the flow whose visible bounds enclose the * supplied point, or null if no such step exists */ protected StepVisual findStep(Point p) { Rectangle tempBounds = new Rectangle(); for (StepVisual v : m_renderGraph) { tempBounds = v.getBounds(); if (tempBounds.contains(p)) { return v; } } return null; } /** * Find a list of steps that exist within the supplied bounding box * * @param boundingBox the bounding box to check * @return a list of steps that fall within the bounding box */ protected List<StepVisual> findSteps(Rectangle boundingBox) { List<StepVisual> steps = new ArrayList<StepVisual>(); for (StepVisual v : m_renderGraph) { int centerX = v.getX() + (v.getWidth() / 2); int centerY = v.getY() + (v.getHeight() / 2); if (boundingBox.contains(centerX, centerY)) { steps.add(v); } } return steps; } /** * Find a list of steps in the flow that can accept the supplied connection * type * * @param connectionName the type of connection to check for * @return a list of steps that can accept the supplied connection type */ protected List<StepManagerImpl> findStepsThatCanAcceptConnection( String connectionName) { List<StepManagerImpl> result = new ArrayList<StepManagerImpl>(); for (StepManagerImpl step : m_flow.getSteps()) { List<String> incomingConnNames = step.getManagedStep().getIncomingConnectionTypes(); if (incomingConnNames != null && incomingConnNames.contains(connectionName)) { result.add(step); } } return result; } /** * Find all connections within delta of the supplied point * * @param point the point on the canvas to find steps at * @param delta the radius around point for detecting connections * @return a map keyed by connection type name of connected steps. The value * is a list of 2 element arrays, where each array contains source and * target steps for the connection in question */ protected Map<String, List<StepManagerImpl[]>> findClosestConnections( Point point, int delta) { Map<String, List<StepManagerImpl[]>> closestConnections = new HashMap<String, List<StepManagerImpl[]>>(); for (StepManagerImpl sourceManager : m_flow.getSteps()) { for (Map.Entry<String, List<StepManager>> outCons : sourceManager .getOutgoingConnections().entrySet()) { List<StepManager> targetsOfConnType = outCons.getValue(); for (StepManager target : targetsOfConnType) { StepManagerImpl targetManager = (StepManagerImpl) target; String connName = outCons.getKey(); StepVisual sourceVisual = sourceManager.getStepVisual(); StepVisual targetVisual = targetManager.getStepVisual(); Point bestSourcePt = sourceVisual.getClosestConnectorPoint(new Point(targetVisual.getX() + targetVisual.getWidth() / 2, targetVisual.getY() + targetVisual.getHeight() / 2)); Point bestTargetPt = targetVisual.getClosestConnectorPoint(new Point(sourceVisual.getX() + sourceVisual.getWidth() / 2, sourceVisual.getY() + sourceVisual.getHeight() / 2)); int minx = (int) Math.min(bestSourcePt.getX(), bestTargetPt.getX()); int maxx = (int) Math.max(bestSourcePt.getX(), bestTargetPt.getX()); int miny = (int) Math.min(bestSourcePt.getY(), bestTargetPt.getY()); int maxy = (int) Math.max(bestSourcePt.getY(), bestTargetPt.getY()); // check to see if supplied pt is inside bounding box if (point.getX() >= minx - delta && point.getX() <= maxx + delta && point.getY() >= miny - delta && point.getY() <= maxy + delta) { // now see if the point is within delta of the line // formulate ax + by + c = 0 double a = bestSourcePt.getY() - bestTargetPt.getY(); double b = bestTargetPt.getX() - bestSourcePt.getX(); double c = (bestSourcePt.getX() * bestTargetPt.getY()) - (bestTargetPt.getX() * bestSourcePt.getY()); double distance = Math.abs((a * point.getX()) + (b * point.getY()) + c); distance /= Math.abs(Math.sqrt((a * a) + (b * b))); if (distance <= delta) { List<StepManagerImpl[]> conList = closestConnections.get(connName); if (conList == null) { conList = new ArrayList<StepManagerImpl[]>(); closestConnections.put(connName, conList); } StepManagerImpl[] conn = { sourceManager, targetManager }; conList.add(conn); } } } } } return closestConnections; } /** * Returns true if there is a previous (prior to index) connection to the * supplied target step in the supplied map of connections. * * * @param outConns the map of connections to check * @param target the target step to check for * @param index connections to the target prior to this index in the map count * @return true if a previous connection is found */ protected boolean previousConn(Map<String, List<StepManager>> outConns, StepManagerImpl target, int index) { boolean result = false; int count = 0; for (Entry<String, List<StepManager>> e : outConns.entrySet()) { List<StepManager> connectedSteps = e.getValue(); for (StepManager c : connectedSteps) { StepManagerImpl cI = (StepManagerImpl) c; if (target.getManagedStep() == cI.getManagedStep() && count < index) { result = true; break; } } if (result) { break; } count++; } return result; } private void setUpLogPanel(final LogPanel logPanel) { String date = (new SimpleDateFormat("EEEE, d MMMM yyyy")).format(new Date()); logPanel.logMessage("Weka Knowledge Flow was written by Mark Hall"); logPanel.logMessage("Weka Knowledge Flow"); logPanel.logMessage("(c) 2002-" + Copyright.getToYear() + " " + Copyright.getOwner() + ", " + Copyright.getAddress()); logPanel.logMessage("web: " + Copyright.getURL()); logPanel.logMessage(date); logPanel .statusMessage("@!@[KnowledgeFlow]|Welcome to the Weka Knowledge Flow"); logPanel.getStatusTable().addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (logPanel.getStatusTable().rowAtPoint(e.getPoint()) == 0) { if (((e.getModifiers() & InputEvent.BUTTON1_MASK) != InputEvent.BUTTON1_MASK) || e.isAltDown()) { System.gc(); Runtime currR = Runtime.getRuntime(); long freeM = currR.freeMemory(); long totalM = currR.totalMemory(); long maxM = currR.maxMemory(); logPanel .logMessage("[KnowledgeFlow] Memory (free/total/max.) in bytes: " + String.format("%,d", freeM) + " / " + String.format("%,d", totalM) + " / " + String.format("%,d", maxM)); logPanel .statusMessage("@!@[KnowledgeFlow]|Memory (free/total/max.) in bytes: " + String.format("%,d", freeM) + " / " + String.format("%,d", totalM) + " / " + String.format("%,d", maxM)); } } } }); } /** * Save the flow managed by this layout * * @param showDialog true if a file dialog should be displayed */ protected void saveLayout(boolean showDialog) { boolean shownDialog = false; int returnVal = JFileChooser.APPROVE_OPTION; File sFile = getFilePath(); if (showDialog || sFile.getName().equals("-NONE-")) { returnVal = m_mainPerspective.m_saveFileChooser.showSaveDialog(this); shownDialog = true; } if (returnVal == JFileChooser.APPROVE_OPTION) { if (shownDialog) { sFile = m_mainPerspective.m_saveFileChooser.getSelectedFile(); } // add extension if necessary if (!sFile.getName().toLowerCase().endsWith(".kf")) { sFile = new File(sFile.getParent(), sFile.getName() + ".kf"); } try { String fName = sFile.getName(); if (fName.indexOf(".") > 0) { fName = fName.substring(0, fName.lastIndexOf('.')); } m_flow.setFlowName(fName.replace(".kf", "")); m_flow.saveFlow(sFile); setFilePath(sFile); setEdited(false); m_mainPerspective.setCurrentTabTitle(fName); } catch (WekaException e) { m_mainPerspective.showErrorDialog(e); } } } /** * Pop an undo point and load the flow it encapsulates */ protected void popAndLoadUndo() { if (m_undoBuffer.size() > 0) { File undo = m_undoBuffer.pop(); if (m_undoBuffer.size() == 0) { m_mainPerspective.getMainToolBar().disableWidgets( MainKFPerspectiveToolBar.Widgets.UNDO_BUTTON.toString()); } loadLayout(undo, true); } } /** * Load a flow into this layout * * @param fFile the file containing the flow * @param isUndo true if this is an "undo" layout */ protected void loadLayout(File fFile, boolean isUndo) { stopFlow(); m_mainPerspective.getMainToolBar().disableWidgets( MainKFPerspectiveToolBar.Widgets.PLAY_PARALLEL_BUTTON.toString(), MainKFPerspectiveToolBar.Widgets.PLAY_SEQUENTIAL_BUTTON.toString(), MainKFPerspectiveToolBar.Widgets.SAVE_FLOW_BUTTON.toString(), MainKFPerspectiveToolBar.Widgets.SAVE_FLOW_AS_BUTTON.toString()); if (!isUndo) { File absolute = new File(fFile.getAbsolutePath()); getEnvironment().addVariable("Internal.knowledgeflow.directory", absolute.getParent()); } try { Flow flow = Flow.loadFlow(fFile, m_logPanel); setFlow(flow); if (!isUndo) { setFilePath(fFile); } if (!getFlow().getFlowName().equals("Untitled")) { m_mainPerspective.setCurrentTabTitle(getFlow().getFlowName()); } } catch (WekaException e) { m_logPanel .statusMessage("@!@[KnowledgeFlow]|Unable to load flow (see log)."); m_logPanel.logMessage("[KnowledgeFlow] Unable to load flow\n" + LogManager.stackTraceToString(e)); m_mainPerspective.showErrorDialog(e); } m_mainPerspective.getMainToolBar().enableWidgets( MainKFPerspectiveToolBar.Widgets.PLAY_PARALLEL_BUTTON.toString(), MainKFPerspectiveToolBar.Widgets.PLAY_SEQUENTIAL_BUTTON.toString(), MainKFPerspectiveToolBar.Widgets.SAVE_FLOW_BUTTON.toString(), MainKFPerspectiveToolBar.Widgets.SAVE_FLOW_AS_BUTTON.toString()); m_mainPerspective.getMainToolBar().enableWidget( MainKFPerspectiveToolBar.Widgets.SELECT_ALL_BUTTON.toString(), m_flow.size() > 0); } /** * Editing operations on the layout */ protected static enum LayoutOperation { NONE, MOVING, CONNECTING, ADDING, SELECTING, PASTING; } /** * Small subclass of LogPanel for use by layouts */ protected class KFLogPanel extends LogPanel { /** For serialization */ private static final long serialVersionUID = -2224509243343105276L; public synchronized void setMessageOnAll(boolean mainKFLine, String message) { for (String key : m_tableIndexes.keySet()) { if (!mainKFLine && key.equals("[KnowledgeFlow]")) { continue; } String tm = key + "|" + message; statusMessage(tm); } } } /** * Utility method to serialize a list of steps (encapsulated in StepVisuals) * to a JSON flow. * * @param steps the steps to serialize * @param name the name to set in the encapsulating Flow before serializing * @return the serialized Flow * @throws WekaException if a problem occurs */ public static String serializeStepsToJSON(List<StepVisual> steps, String name) throws WekaException { if (steps.size() > 0) { List<StepManagerImpl> toCopy = new ArrayList<StepManagerImpl>(); for (StepVisual s : steps) { toCopy.add(s.getStepManager()); } Flow temp = new Flow(); temp.setFlowName("Clipboard copy"); temp.addAll(toCopy); return JSONFlowUtils.flowToJSON(temp); } throw new WekaException("No steps to serialize!"); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow/steps/ASEvaluatorStepEditorDialog.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ASEvaluatorStepEditorDialog.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.gui.knowledgeflow.steps; import weka.gui.knowledgeflow.GOEStepEditorDialog; import weka.knowledgeflow.steps.ASEvaluator; import weka.knowledgeflow.steps.Step; import javax.swing.*; import java.awt.*; /** * Step editor dialog for the ASEvaluator step * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class ASEvaluatorStepEditorDialog extends GOEStepEditorDialog { private static final long serialVersionUID = -166234654984288982L; /** Check box for selecting whether to treat x-val folds separately or not */ protected JCheckBox m_treatXValFoldsSeparately = new JCheckBox( "Treat x-val folds separately"); /** * Set the step to edit in this dialog * * @param step the step to edit */ @Override public void setStepToEdit(Step step) { copyOriginal(step); addPrimaryEditorPanel(BorderLayout.NORTH); JPanel p = new JPanel(new BorderLayout()); p.add(m_treatXValFoldsSeparately, BorderLayout.NORTH); m_primaryEditorHolder.add(p, BorderLayout.CENTER); add(m_editorHolder, BorderLayout.CENTER); m_treatXValFoldsSeparately.setSelected(((ASEvaluator) step) .getTreatXValFoldsSeparately()); } /** * Called when the OK button is pressed */ @Override protected void okPressed() { ((ASEvaluator) m_stepToEdit) .setTreatXValFoldsSeparately(m_treatXValFoldsSeparately.isSelected()); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow/steps/AttributeSummarizerInteractiveView.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /*` * AttributeSummarizerInteractiveView.java * Copyright (C) 2002-2015 University of Waikato, Hamilton, New Zealand * */ package weka.gui.knowledgeflow.steps; import weka.core.Defaults; import weka.core.Instances; import weka.core.Settings; import weka.core.WekaException; import weka.gui.ResultHistoryPanel; import weka.gui.knowledgeflow.AttributeSummaryPerspective; import weka.gui.knowledgeflow.BaseInteractiveViewer; import weka.knowledgeflow.Data; import weka.knowledgeflow.StepManager; import weka.knowledgeflow.steps.AttributeSummarizer; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JSplitPane; import javax.swing.ListSelectionModel; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.List; /** * Interactive viewer for the AttributeSummarizer step * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class AttributeSummarizerInteractiveView extends BaseInteractiveViewer { private static final long serialVersionUID = -8080574605631027263L; /** Holds results */ protected ResultHistoryPanel m_history; /** Holds the actual visualization */ protected AttributeSummaryPerspective m_summarizer = new AttributeSummaryPerspective(); /** Button for clearing all results */ protected JButton m_clearButton = new JButton("Clear results"); /** Split pane to separate result list from visualization */ protected JSplitPane m_splitPane; /** The instances being visualized */ protected Instances m_currentInstances; /** * The name of this viewer * * @return */ @Override public String getViewerName() { return "Attribute Summarizer"; } /** * Initialize the viewer - layout widgets etc. * * @throws WekaException if a problem occurs */ @Override public void init() throws WekaException { addButton(m_clearButton); m_history = new ResultHistoryPanel(null); m_history.setBorder(BorderFactory.createTitledBorder("Result list")); m_history.setHandleRightClicks(false); m_history.setDeleteListener(new ResultHistoryPanel.RDeleteListener() { @Override public void entryDeleted(String name, int index) { ((AttributeSummarizer) getStep()).getDatasets().remove(index); } @Override public void entriesDeleted(java.util.List<String> names, java.util.List<Integer> indexes) { List<Data> ds = ((AttributeSummarizer) getStep()).getDatasets(); List<Data> toRemove = new ArrayList<Data>(); for (int i : indexes) { toRemove.add(ds.get(i)); } ds.removeAll(toRemove); } }); m_history.getList().addMouseListener( new ResultHistoryPanel.RMouseAdapter() { private static final long serialVersionUID = -5174882230278923704L; @Override public void mouseClicked(MouseEvent e) { int index = m_history.getList().locationToIndex(e.getPoint()); if (index != -1) { String name = m_history.getNameAtIndex(index); // doPopup(name); Object inst = m_history.getNamedObject(name); if (inst instanceof Instances) { m_currentInstances = (Instances) inst; m_summarizer.setInstances((Instances) inst, getSettings()); m_summarizer.repaint(); m_parent.revalidate(); } } } }); m_history.getList().getSelectionModel() .addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { ListSelectionModel lm = (ListSelectionModel) e.getSource(); for (int i = e.getFirstIndex(); i <= e.getLastIndex(); i++) { if (lm.isSelectedIndex(i)) { // m_AttSummaryPanel.setAttribute(i); if (i != -1) { String name = m_history.getNameAtIndex(i); Object inst = m_history.getNamedObject(name); if (inst != null && inst instanceof Instances) { m_currentInstances = (Instances) inst; m_summarizer.setInstances((Instances) inst, getSettings()); m_summarizer.repaint(); m_parent.revalidate(); } } break; } } } } }); m_summarizer.setPreferredSize(new Dimension(800, 600)); m_splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, m_history, m_summarizer); add(m_splitPane, BorderLayout.CENTER); boolean first = true; for (Data d : ((AttributeSummarizer) getStep()).getDatasets()) { String title = d.getPayloadElement(StepManager.CON_AUX_DATA_TEXT_TITLE).toString(); m_history.addResult(title, new StringBuffer()); Instances instances = d.getPrimaryPayload(); m_history.addObject(title, instances); if (first) { m_summarizer.setInstances(instances, getSettings()); m_summarizer.repaint(); first = false; } } m_clearButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m_history.clearResults(); ((AttributeSummarizer) getStep()).getDatasets().clear(); m_splitPane.remove(m_summarizer); } }); } /** * Get the default settings for this viewer * * @return the default settings for this viewer */ @Override public Defaults getDefaultSettings() { return new AttributeSummaryPerspective().getDefaultSettings(); } /** * Apply user-changed settings * * @param settings the settings object that might (or might not) have been */ @Override public void applySettings(Settings settings) { m_summarizer.setInstances(m_currentInstances, getSettings()); m_summarizer.repaint(); m_parent.revalidate(); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow/steps/AttributeSummarizerStepEditorDialog.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /*` * AttributeSummarizerStepEditorDialog.java * Copyright (C) 2002-2015 University of Waikato, Hamilton, New Zealand * */ package weka.gui.knowledgeflow.steps; import weka.knowledgeflow.steps.AttributeSummarizer; /** * Step editor dialog for the attribute summarizer step * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class AttributeSummarizerStepEditorDialog extends ModelPerformanceChartStepEditorDialog { private static final long serialVersionUID = -4504946065343184549L; /** * Get the offscreen renderer and options from the step being edited */ @Override protected void getCurrentSettings() { m_currentRendererName = ((AttributeSummarizer) getStepToEdit()).getOffscreenRendererName(); m_currentRendererOptions = ((AttributeSummarizer) getStepToEdit()).getOffscreenAdditionalOpts(); } /** * Called when OK is pressed */ @Override public void okPressed() { ((AttributeSummarizer) getStepToEdit()) .setOffscreenRendererName(m_offscreenSelector.getSelectedItem() .toString()); ((AttributeSummarizer) getStepToEdit()) .setOffscreenAdditionalOpts(m_rendererOptions.getText()); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow/steps/BlockStepEditorDialog.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * BlockStepEditorDialog.java * Copyright (C) 2016 University of Waikato, Hamilton, New Zealand * */ package weka.gui.knowledgeflow.steps; import weka.gui.knowledgeflow.StepEditorDialog; import weka.knowledgeflow.StepManager; import weka.knowledgeflow.StepManagerImpl; import weka.knowledgeflow.steps.Block; import javax.swing.BorderFactory; import javax.swing.JComboBox; import javax.swing.JPanel; import java.awt.BorderLayout; import java.util.List; /** * Step editor dialog for the Block step * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class BlockStepEditorDialog extends StepEditorDialog { private static final long serialVersionUID = 1183316309880876170L; /** The combo box for choosing the step to block on */ protected JComboBox<String> m_stepToBlockBox = new JComboBox<String>(); /** * Layout the component */ @Override public void layoutEditor() { m_stepToBlockBox.setEditable(true); StepManager sm = getStepToEdit().getStepManager(); List<StepManagerImpl> flowSteps = getMainPerspective().getCurrentLayout().getFlow().getSteps(); for (StepManagerImpl smi : flowSteps) { m_stepToBlockBox.addItem(smi.getName()); } JPanel p = new JPanel(new BorderLayout()); p.setBorder(BorderFactory.createTitledBorder("Choose step to wait for")); p.add(m_stepToBlockBox, BorderLayout.NORTH); add(p, BorderLayout.CENTER); String userSelected = ((Block) getStepToEdit()).getStepToWaitFor(); if (userSelected != null) { m_stepToBlockBox.setSelectedItem(userSelected); } } /** * Called when OK is pressed */ @Override public void okPressed() { String selected = (String) m_stepToBlockBox.getSelectedItem(); ((Block) getStepToEdit()).setStepToWaitFor(selected); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow/steps/BoundaryPlotterInteractiveView.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * BoundaryPlotterInteractiveView.java * Copyright (C) 2016 University of Waikato, Hamilton, New Zealand * */ package weka.gui.knowledgeflow.steps; import weka.core.WekaException; import weka.gui.ResultHistoryPanel; import weka.gui.knowledgeflow.BaseInteractiveViewer; import weka.knowledgeflow.steps.BoundaryPlotter; import javax.swing.*; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import java.util.Map; /** * Interactive viewer component for the boundary plotter step * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class BoundaryPlotterInteractiveView extends BaseInteractiveViewer implements BoundaryPlotter.RenderingUpdateListener { private static final long serialVersionUID = 5567187861739468636L; protected JButton m_clearButton = new JButton("Clear results"); /** Holds a list of plots */ protected ResultHistoryPanel m_history; /** Panel for displaying the image */ protected ImageViewerInteractiveView.ImageDisplayer m_plotter; /** * Get the name of this viewer * * @return the name of this viewer */ @Override public String getViewerName() { return "Boundary Visualizer"; } /** * Initialize/layout the viewer * * @throws WekaException if a problem occurs */ @Override public void init() throws WekaException { addButton(m_clearButton); m_plotter = new ImageViewerInteractiveView.ImageDisplayer(); m_plotter.setMinimumSize(new Dimension(810, 610)); m_plotter.setPreferredSize(new Dimension(810, 610)); m_history = new ResultHistoryPanel(null); m_history.setBorder(BorderFactory.createTitledBorder("Image list")); m_history.setHandleRightClicks(false); m_history.getList().addMouseListener( new ResultHistoryPanel.RMouseAdapter() { /** for serialization */ private static final long serialVersionUID = -4984130887963944249L; @Override public void mouseClicked(MouseEvent e) { int index = m_history.getList().locationToIndex(e.getPoint()); if (index != -1) { String name = m_history.getNameAtIndex(index); // doPopup(name); Object pic = m_history.getNamedObject(name); if (pic instanceof BufferedImage) { m_plotter.setImage((BufferedImage) pic); m_plotter.repaint(); } } } }); m_history.getList().getSelectionModel() .addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { ListSelectionModel lm = (ListSelectionModel) e.getSource(); for (int i = e.getFirstIndex(); i <= e.getLastIndex(); i++) { if (lm.isSelectedIndex(i)) { // m_AttSummaryPanel.setAttribute(i); if (i != -1) { String name = m_history.getNameAtIndex(i); Object pic = m_history.getNamedObject(name); if (pic != null && pic instanceof BufferedImage) { m_plotter.setImage((BufferedImage) pic); m_plotter.repaint(); } } break; } } } } }); ImageViewerInteractiveView.MainPanel mainPanel = new ImageViewerInteractiveView.MainPanel(m_history, m_plotter); add(mainPanel, BorderLayout.CENTER); boolean first = true; Map<String, BufferedImage> images = ((BoundaryPlotter) getStep()).getImages(); if (images != null) { for (Map.Entry<String, BufferedImage> e : images.entrySet()) { m_history.addResult(e.getKey(), new StringBuffer()); m_history.addObject(e.getKey(), e.getValue()); if (first) { m_plotter.setImage(e.getValue()); m_plotter.repaint(); first = false; } } } m_clearButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m_history.clearResults(); ((BoundaryPlotter) getStep()).getImages().clear(); m_plotter.setImage(null); m_plotter.repaint(); } }); ((BoundaryPlotter) getStep()).setRenderingListener(this); } /** * Called when there is an update to rendering of the current image */ @Override public void renderingImageUpdate() { m_plotter.repaint(); } @Override public void newPlotStarted(String description) { BufferedImage currentImage = ((BoundaryPlotter) getStep()).getCurrentImage(); if (currentImage != null) { m_history.addResult(description, new StringBuffer()); m_history.addObject(description, currentImage); m_history.setSelectedListValue(description); m_plotter.setImage(currentImage); m_plotter.repaint(); } } /** * Called when a row of the image being plotted has been completed * * @param row the index of the row that was completed */ @Override public void currentPlotRowCompleted(int row) { m_plotter.repaint(); } /** * Called when the viewer's window is closed */ @Override public void closePressed() { ((BoundaryPlotter) getStep()).removeRenderingListener(this); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow/steps/BoundaryPlotterStepEditorDialog.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * BoundaryPlotterStepEditorDialog.java * Copyright (C) 2016 University of Waikato, Hamilton, New Zealand * */ package weka.gui.knowledgeflow.steps; import weka.core.Attribute; import weka.core.Instances; import weka.core.WekaException; import weka.gui.knowledgeflow.GOEStepEditorDialog; import weka.knowledgeflow.StepManager; import weka.knowledgeflow.steps.BoundaryPlotter; import javax.swing.*; import javax.swing.border.TitledBorder; import java.awt.*; /** * Editor dialog for the boundary plotter step * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class BoundaryPlotterStepEditorDialog extends GOEStepEditorDialog { private static final long serialVersionUID = 4351742205211273840L; /** * Combo box for selecting the x attribute to plot when there is an incoming * instances structure at design time */ protected JComboBox<String> m_xCombo = new JComboBox<String>(); /** * Combo box for selecting the y attribute to plot when there is an incoming * instances structure at design time */ protected JComboBox<String> m_yCombo = new JComboBox<String>(); /** * Environment field for specifying the x attribute when there isn't incoming * instances structure at design time */ protected weka.gui.EnvironmentField m_xEnviro = new weka.gui.EnvironmentField(); /** * Environment field for specifying the y attribute when there isn't incoming * instances structure at design time */ protected weka.gui.EnvironmentField m_yEnviro = new weka.gui.EnvironmentField(); /** * Layout the editor */ @Override public void layoutEditor() { // just need to add widgets for choosing the x and y visualization // attributes m_xCombo.setEditable(true); m_yCombo.setEditable(true); BoundaryPlotter step = (BoundaryPlotter) getStepToEdit(); Instances incomingStructure = null; try { incomingStructure = step.getStepManager().getIncomingStructureForConnectionType( StepManager.CON_DATASET); if (incomingStructure == null) { incomingStructure = step.getStepManager().getIncomingStructureForConnectionType( StepManager.CON_TRAININGSET); } if (incomingStructure == null) { incomingStructure = step.getStepManager().getIncomingStructureForConnectionType( StepManager.CON_TESTSET); } if (incomingStructure == null) { incomingStructure = step.getStepManager().getIncomingStructureForConnectionType( StepManager.CON_INSTANCE); } } catch (WekaException ex) { showErrorDialog(ex); } JPanel attPan = new JPanel(new GridLayout(1, 2)); JPanel xHolder = new JPanel(new BorderLayout()); JPanel yHolder = new JPanel(new BorderLayout()); xHolder.setBorder(new TitledBorder("X axis")); yHolder.setBorder(new TitledBorder("Y axis")); attPan.add(xHolder); attPan.add(yHolder); if (incomingStructure != null) { m_xEnviro = null; m_yEnviro = null; xHolder.add(m_xCombo, BorderLayout.CENTER); yHolder.add(m_yCombo, BorderLayout.CENTER); String xAttN = step.getXAttName(); String yAttN = step.getYAttName(); // populate combos and try to match int numAdded = 0; for (int i = 0; i < incomingStructure.numAttributes(); i++) { Attribute att = incomingStructure.attribute(i); if (att.isNumeric()) { m_xCombo.addItem(att.name()); m_yCombo.addItem(att.name()); numAdded++; } } attPan.add(xHolder); attPan.add(yHolder); if (numAdded < 2) { showInfoDialog("There are not enough numeric attributes in " + "the incoming data to visualize with", "Not enough attributes " + "available", true); } else { // try to match if (xAttN != null && xAttN.length() > 0) { m_xCombo.setSelectedItem(xAttN); } if (yAttN != null && yAttN.length() > 0) { m_yCombo.setSelectedItem(yAttN); } } } else { m_xCombo = null; m_yCombo = null; xHolder.add(m_xEnviro, BorderLayout.CENTER); yHolder.add(m_yEnviro, BorderLayout.CENTER); m_xEnviro.setText(step.getXAttName()); m_yEnviro.setText(step.getYAttName()); } m_editorHolder.add(attPan, BorderLayout.SOUTH); } /** * Called when the OK button is pressed */ @Override public void okPressed() { String xName = m_xCombo != null ? m_xCombo.getSelectedItem().toString() : m_xEnviro .getText(); String yName = m_yCombo != null ? m_yCombo.getSelectedItem().toString() : m_yEnviro .getText(); ((BoundaryPlotter) getStepToEdit()).setXAttName(xName); ((BoundaryPlotter) getStepToEdit()).setYAttName(yName); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow/steps/ClassAssignerStepEditorDialog.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ClassAssignerStepEditorDialog.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.gui.knowledgeflow.steps; import weka.core.Attribute; import weka.core.Instances; import weka.core.WekaException; import weka.gui.knowledgeflow.GOEStepEditorDialog; import weka.knowledgeflow.StepManager; import weka.knowledgeflow.steps.ClassAssigner; import weka.knowledgeflow.steps.Step; import javax.swing.*; import java.awt.*; /** * Step editor dialog for the ClassAssigner step * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class ClassAssignerStepEditorDialog extends GOEStepEditorDialog { private static final long serialVersionUID = 3105898651212196539L; /** Combo box for selecting the class attribute */ protected JComboBox<String> m_classCombo = new JComboBox<String>(); /** * Set the step being edited * * @param step the step to edit */ @Override public void setStepToEdit(Step step) { copyOriginal(step); Instances incomingStructure = null; try { incomingStructure = step.getStepManager().getIncomingStructureForConnectionType( StepManager.CON_DATASET); if (incomingStructure == null) { incomingStructure = step.getStepManager().getIncomingStructureForConnectionType( StepManager.CON_TRAININGSET); } if (incomingStructure == null) { incomingStructure = step.getStepManager().getIncomingStructureForConnectionType( StepManager.CON_TESTSET); } if (incomingStructure == null) { incomingStructure = step.getStepManager().getIncomingStructureForConnectionType( StepManager.CON_INSTANCE); } } catch (WekaException ex) { showErrorDialog(ex); } if (incomingStructure != null) { m_classCombo.setEditable(true); for (int i = 0; i < incomingStructure.numAttributes(); i++) { Attribute a = incomingStructure.attribute(i); String attN = "(" + Attribute.typeToStringShort(a) + ") " + a.name(); m_classCombo.addItem(attN); } setComboToClass(incomingStructure); JPanel p = new JPanel(new BorderLayout()); p.setBorder(BorderFactory.createTitledBorder("Choose class attribute")); p.add(m_classCombo, BorderLayout.NORTH); createAboutPanel(step); add(p, BorderLayout.CENTER); } else { m_classCombo = null; super.setStepToEdit(step); } } /** * Populate the class combo box using the supplied instances structure * * @param incomingStructure the instances structure to use */ protected void setComboToClass(Instances incomingStructure) { String stepC = ((ClassAssigner) getStepToEdit()).getClassColumn(); if (stepC != null && stepC.length() > 0) { if (stepC.equalsIgnoreCase("/first")) { m_classCombo.setSelectedIndex(0); } else if (stepC.equalsIgnoreCase("/last")) { m_classCombo.setSelectedIndex(m_classCombo.getItemCount() - 1); } else { Attribute a = incomingStructure.attribute(stepC); if (a != null) { String attN = "(" + Attribute.typeToStringShort(a) + ") " + a.name(); m_classCombo.setSelectedItem(attN); } else { // try and parse as a number try { int num = Integer.parseInt(stepC); num--; if (num >= 0 && num < incomingStructure.numAttributes()) { m_classCombo.setSelectedIndex(num); } } catch (NumberFormatException e) { // just set the value as is m_classCombo.setSelectedItem(stepC); } } } } } /** * Called when the OK button is pressed */ @Override public void okPressed() { if (m_classCombo != null) { String selected = m_classCombo.getSelectedItem().toString(); selected = selected.substring(selected.indexOf(')') + 1, selected.length()).trim(); ((ClassAssigner) getStepToEdit()).setClassColumn(selected); } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow/steps/ClassValuePickerStepEditorDialog.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ClassValuePickerStepEditorDialog.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.gui.knowledgeflow.steps; import weka.core.Instances; import weka.core.WekaException; import weka.gui.EnvironmentField; import weka.gui.knowledgeflow.GOEStepEditorDialog; import weka.knowledgeflow.StepManager; import weka.knowledgeflow.steps.ClassValuePicker; import weka.knowledgeflow.steps.Step; import javax.swing.BorderFactory; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import java.awt.BorderLayout; /** * Editor dialog for the ClassValuePicker step. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class ClassValuePickerStepEditorDialog extends GOEStepEditorDialog { private static final long serialVersionUID = 7009335918650499183L; /** For displaying class values */ protected JComboBox m_classValueCombo = new EnvironmentField.WideComboBox(); /** * Set the step to edit * * @param step the step to edit */ @Override @SuppressWarnings("unchecked") public void setStepToEdit(Step step) { copyOriginal(step); Instances incomingStructure = null; try { incomingStructure = step.getStepManager() .getIncomingStructureForConnectionType(StepManager.CON_DATASET); if (incomingStructure == null) { incomingStructure = step.getStepManager() .getIncomingStructureForConnectionType(StepManager.CON_TRAININGSET); } if (incomingStructure == null) { incomingStructure = step.getStepManager() .getIncomingStructureForConnectionType(StepManager.CON_TESTSET); } if (incomingStructure == null) { incomingStructure = step.getStepManager() .getIncomingStructureForConnectionType(StepManager.CON_INSTANCE); } } catch (WekaException ex) { showErrorDialog(ex); } if (incomingStructure != null) { if (incomingStructure.classIndex() < 0) { showInfoDialog("No class attribute is set in the data", "ClassValuePicker", true); add(new JLabel("No class attribute set in data"), BorderLayout.CENTER); } else if (incomingStructure.classAttribute().isNumeric()) { showInfoDialog("Cant set class value - class is numeric!", "ClassValuePicker", true); add(new JLabel("Can't set class value - class is numeric"), BorderLayout.CENTER); } else { m_classValueCombo.setEditable(true); m_classValueCombo .setToolTipText("Class label. /first, /last and /<num> " + "can be used to specify the first, last or specific index " + "of the label to use respectively"); for (int i = 0; i < incomingStructure.classAttribute() .numValues(); i++) { m_classValueCombo .addItem(incomingStructure.classAttribute().value(i)); } String stepL = ((ClassValuePicker) getStepToEdit()).getClassValue(); if (stepL != null && stepL.length() > 0) { m_classValueCombo.setSelectedItem(stepL); } JPanel p = new JPanel(new BorderLayout()); p.setBorder(BorderFactory.createTitledBorder("Choose class value")); p.add(m_classValueCombo, BorderLayout.NORTH); createAboutPanel(step); add(p, BorderLayout.CENTER); } } else { super.setStepToEdit(step); } } /** * Called when the OK button is pressed */ @Override public void okPressed() { Object selected = m_classValueCombo.getSelectedItem(); if (selected != null) { ((ClassValuePicker) getStepToEdit()).setClassValue(selected.toString()); } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow/steps/ClassifierPerformanceEvaluatorStepEditorDialog.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ClassifierPerformanceEvaluatorStepEditorDialog.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.gui.knowledgeflow.steps; import weka.classifiers.CostMatrix; import weka.gui.CostMatrixEditor; import weka.gui.EvaluationMetricSelectionDialog; import weka.gui.PropertyDialog; import weka.gui.knowledgeflow.GOEStepEditorDialog; import weka.knowledgeflow.steps.ClassifierPerformanceEvaluator; import weka.knowledgeflow.steps.Step; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JPanel; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.List; /** * GUI step editor dialog for the ClassifierPerformanceEvaluator step * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class ClassifierPerformanceEvaluatorStepEditorDialog extends GOEStepEditorDialog { private static final long serialVersionUID = -4459460141076392499L; /** Button for popping up the evaluation metrics selector dialog */ protected JButton m_showEvalDialog = new JButton("Evaluation metrics..."); /** Checkbox for selecting cost-sensitive evaluation */ protected JCheckBox m_useCosts = new JCheckBox("Cost-sensitive evaluation"); /** Button for popping up cost editor */ protected JButton m_setCostMatrix = new JButton("Set..."); /** The cost matrix editor for evaluation costs. */ protected CostMatrixEditor m_CostMatrixEditor = new CostMatrixEditor(); /** The frame used to show the cost matrix editing panel. */ protected PropertyDialog m_SetCostsFrame; /** Holds selected evaluation metrics */ protected List<String> m_evaluationMetrics = new ArrayList<String>(); /** * Constructor */ public ClassifierPerformanceEvaluatorStepEditorDialog() { super(); } /** * Set the step to edit * * @param step the step to edit */ @Override public void setStepToEdit(Step step) { copyOriginal(step); m_CostMatrixEditor.setValue(new CostMatrix(1)); if (((ClassifierPerformanceEvaluator) getStepToEdit()) .getEvaluateWithRespectToCosts()) { String costString = ((ClassifierPerformanceEvaluator) getStepToEdit()) .getCostMatrixString(); if (costString != null && costString.length() > 0) { try { CostMatrix cm = CostMatrix.parseMatlab(costString); m_CostMatrixEditor.setValue(cm); } catch (Exception e) { showErrorDialog(e); } } } addPrimaryEditorPanel(BorderLayout.NORTH); JPanel p = new JPanel(new BorderLayout()); p.add(m_showEvalDialog, BorderLayout.NORTH); m_primaryEditorHolder.add(p, BorderLayout.CENTER); add(m_editorHolder, BorderLayout.NORTH); JPanel costP = new JPanel(); costP.add(m_useCosts); costP.add(m_setCostMatrix); m_useCosts.setSelected(((ClassifierPerformanceEvaluator) getStepToEdit()) .getEvaluateWithRespectToCosts()); m_setCostMatrix .setEnabled(((ClassifierPerformanceEvaluator) getStepToEdit()) .getEvaluateWithRespectToCosts()); p.add(costP, BorderLayout.SOUTH); String evalM = ((ClassifierPerformanceEvaluator) step).getEvaluationMetricsToOutput(); if (evalM != null && evalM.length() > 0) { String[] parts = evalM.split(","); for (String s : parts) { m_evaluationMetrics.add(s.trim()); } } m_showEvalDialog.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { EvaluationMetricSelectionDialog esd = new EvaluationMetricSelectionDialog(m_parent, m_evaluationMetrics); esd.setLocation(m_showEvalDialog.getLocationOnScreen()); esd.pack(); esd.setVisible(true); m_evaluationMetrics = esd.getSelectedEvalMetrics(); } }); m_useCosts.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m_setCostMatrix.setEnabled(m_useCosts.isSelected()); if (m_SetCostsFrame != null && !m_useCosts.isSelected()) { m_SetCostsFrame.setVisible(false); } } }); m_setCostMatrix.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m_setCostMatrix.setEnabled(false); if (m_SetCostsFrame == null) { if (PropertyDialog .getParentDialog(ClassifierPerformanceEvaluatorStepEditorDialog.this) != null) { m_SetCostsFrame = new PropertyDialog( PropertyDialog .getParentDialog(ClassifierPerformanceEvaluatorStepEditorDialog.this), m_CostMatrixEditor, -1, -1); } else { m_SetCostsFrame = new PropertyDialog( PropertyDialog .getParentFrame(ClassifierPerformanceEvaluatorStepEditorDialog.this), m_CostMatrixEditor, -1, -1); } m_SetCostsFrame.setTitle("Cost Matrix Editor"); // pd.setSize(250,150); m_SetCostsFrame.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent p) { m_setCostMatrix.setEnabled(m_useCosts.isSelected()); if ((m_SetCostsFrame != null) && !m_useCosts.isSelected()) { m_SetCostsFrame.setVisible(false); } } }); } m_SetCostsFrame.setVisible(true); } }); } /** * Called when the OK button is pressed */ @Override protected void okPressed() { StringBuilder b = new StringBuilder(); for (String s : m_evaluationMetrics) { b.append(s).append(","); } String newList = b.substring(0, b.length() - 1); ((ClassifierPerformanceEvaluator) getStepToEdit()) .setEvaluationMetricsToOutput(newList); ((ClassifierPerformanceEvaluator) getStepToEdit()) .setEvaluateWithRespectToCosts(m_useCosts.isSelected()); if (m_useCosts.isSelected()) { CostMatrix m = (CostMatrix) m_CostMatrixEditor.getValue(); ((ClassifierPerformanceEvaluator) getStepToEdit()).setCostMatrixString(m .toMatlab()); } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow/steps/CostBenefitAnalysisInteractiveView.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /*` * CostBenefitAnalysisInteractiveView.java * Copyright (C) 2002-2015 University of Waikato, Hamilton, New Zealand * */ package weka.gui.knowledgeflow.steps; import weka.core.Attribute; import weka.core.WekaException; import weka.gui.CostBenefitAnalysisPanel; import weka.gui.ResultHistoryPanel; import weka.gui.knowledgeflow.BaseInteractiveViewer; import weka.gui.visualize.PlotData2D; import weka.knowledgeflow.Data; import weka.knowledgeflow.StepManager; import weka.knowledgeflow.steps.CostBenefitAnalysis; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JSplitPane; import javax.swing.ListSelectionModel; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.List; /** * Interactive view for the CostBenefitAnalysis step * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class CostBenefitAnalysisInteractiveView extends BaseInteractiveViewer { private static final long serialVersionUID = 4624182171551712860L; /** Holds result entries */ protected ResultHistoryPanel m_history; /** Button for clearing all results */ protected JButton m_clearButton = new JButton("Clear results"); /** The actual cost benefit panel */ protected CostBenefitAnalysisPanel m_cbPanel = new CostBenefitAnalysisPanel(); /** JSplit pane for separating the result list from the visualization */ protected JSplitPane m_splitPane; /** * Get the name of this viewer * * @return the name of this viewer */ @Override public String getViewerName() { return "Cost-benefit Analysis"; } /** * Initialize and layout the viewer * * @throws WekaException if a problem occurs */ @Override public void init() throws WekaException { addButton(m_clearButton); m_history = new ResultHistoryPanel(null); m_history.setBorder(BorderFactory.createTitledBorder("Result list")); m_history.setHandleRightClicks(false); m_history.setDeleteListener(new ResultHistoryPanel.RDeleteListener() { @Override public void entryDeleted(String name, int index) { ((CostBenefitAnalysis)getStep()).getDatasets().remove(index); } @Override public void entriesDeleted(java.util.List<String> names, java.util.List<Integer> indexes) { List<Data> ds = ((CostBenefitAnalysis) getStep()).getDatasets(); List<Data> toRemove = new ArrayList<Data>(); for (int i : indexes) { toRemove.add(ds.get(i)); } ds.removeAll(toRemove); } }); m_history.getList().addMouseListener( new ResultHistoryPanel.RMouseAdapter() { private static final long serialVersionUID = -5174882230278923704L; @Override public void mouseClicked(MouseEvent e) { int index = m_history.getList().locationToIndex(e.getPoint()); if (index != -1) { String name = m_history.getNameAtIndex(index); // doPopup(name); Object data = m_history.getNamedObject(name); if (data instanceof Data) { PlotData2D threshData = ((Data) data).getPrimaryPayload(); Attribute classAtt = ((Data) data) .getPayloadElement(StepManager.CON_AUX_DATA_CLASS_ATTRIBUTE); try { m_cbPanel.setDataSet(threshData, classAtt); m_cbPanel.repaint(); } catch (Exception ex) { ex.printStackTrace(); } } } } }); m_history.getList().getSelectionModel() .addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { ListSelectionModel lm = (ListSelectionModel) e.getSource(); for (int i = e.getFirstIndex(); i <= e.getLastIndex(); i++) { if (lm.isSelectedIndex(i)) { // m_AttSummaryPanel.setAttribute(i); if (i != -1) { String name = m_history.getNameAtIndex(i); Object data = m_history.getNamedObject(name); if (data != null && data instanceof Data) { PlotData2D threshData = ((Data) data).getPrimaryPayload(); Attribute classAtt = ((Data) data) .getPayloadElement(StepManager.CON_AUX_DATA_CLASS_ATTRIBUTE); try { m_cbPanel.setDataSet(threshData, classAtt); m_cbPanel.repaint(); } catch (Exception ex) { ex.printStackTrace(); } } } break; } } } } }); m_splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, m_history, m_cbPanel); add(m_splitPane, BorderLayout.CENTER); m_cbPanel.setPreferredSize(new Dimension(1000, 600)); boolean first = true; for (Data d : ((CostBenefitAnalysis) getStep()).getDatasets()) { PlotData2D threshData = d.getPrimaryPayload(); Attribute classAtt = d.getPayloadElement(StepManager.CON_AUX_DATA_CLASS_ATTRIBUTE); String title = threshData.getPlotName(); m_history.addResult(title, new StringBuffer()); m_history.addObject(title, d); if (first) { try { m_cbPanel.setDataSet(threshData, classAtt); m_cbPanel.repaint(); first = false; } catch (Exception ex) { ex.printStackTrace(); } } } m_clearButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m_history.clearResults(); ((CostBenefitAnalysis) getStep()).getDatasets().clear(); m_splitPane.remove(m_cbPanel); m_splitPane.revalidate(); } }); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow/steps/DataGridStepEditorDialog.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * DataGridStepEditorDialog.java * Copyright (C) 2016 University of Waikato, Hamilton, New Zealand * */ package weka.gui.knowledgeflow.steps; import weka.core.Attribute; import weka.core.DenseInstance; import weka.core.Instance; import weka.core.Instances; import weka.core.Utils; import weka.gui.EnvironmentField; import weka.gui.JListHelper; import weka.gui.arffviewer.ArffPanel; import weka.gui.knowledgeflow.StepEditorDialog; import weka.knowledgeflow.steps.DataGrid; import javax.swing.BorderFactory; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.StringReader; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Step editor dialog for the data grid * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class DataGridStepEditorDialog extends StepEditorDialog { private static final long serialVersionUID = -7314471130292016602L; /** Tabbed pane for the two parts of the editor */ protected JTabbedPane m_tabbedPane = new JTabbedPane(); /** Panel for viewing/editing the instances data */ protected ArffViewerPanel m_viewerPanel = new ArffViewerPanel(); /** Field for editing an attribute name */ protected EnvironmentField m_attNameField = new EnvironmentField(); /** Combo box for selecting the type of the attribute */ protected JComboBox<String> m_attTypeField = new JComboBox<String>(); /** Field for editing nominal values/date format string */ protected EnvironmentField m_nominalOrDateFormatField = new EnvironmentField(); /** Holds the list of attribute defs */ protected JList<AttDef> m_list = new JList<AttDef>(); /** List model */ protected DefaultListModel<AttDef> m_listModel; /** Button for adding a new attribute def */ protected JButton m_newBut = new JButton("New"); /** Button for deleting an attribute def */ protected JButton m_deleteBut = new JButton("Delete"); /** Button for moving an attribute up in the list */ protected JButton m_upBut = new JButton("Move up"); /** Button for moving an attribute down in the list */ protected JButton m_downBut = new JButton("Move down"); /** The instances data from the step as a string */ protected String m_stringInstances; /** * Initialize with data from the step */ protected void initialize() { m_stringInstances = ((DataGrid) getStepToEdit()).getData(); m_listModel = new DefaultListModel<>(); m_list.setModel(m_listModel); if (m_stringInstances != null && m_stringInstances.length() > 0) { try { Instances insts = new Instances(new StringReader(m_stringInstances)); for (int i = 0; i < insts.numAttributes(); i++) { Attribute a = insts.attribute(i); String nomOrDate = ""; if (a.isNominal()) { for (int j = 0; j < a.numValues(); j++) { nomOrDate += a.value(j) + ","; } nomOrDate = nomOrDate.substring(0, nomOrDate.length() - 1); } else if (a.isDate()) { nomOrDate = a.getDateFormat(); } AttDef def = new AttDef(a.name(), a.type(), nomOrDate); m_listModel.addElement(def); } m_viewerPanel.setInstances(insts); } catch (Exception ex) { showErrorDialog(ex); } } } /** * Layout the editor */ @Override protected void layoutEditor() { initialize(); m_upBut.setEnabled(false); m_downBut.setEnabled(false); JPanel mainHolder = new JPanel(new BorderLayout()); JPanel controlHolder = new JPanel(); controlHolder.setLayout(new BorderLayout()); JPanel fieldHolder = new JPanel(); fieldHolder.setLayout(new GridLayout(1, 0)); JPanel attNameP = new JPanel(new BorderLayout()); attNameP.setBorder(BorderFactory.createTitledBorder("Attribute name")); attNameP.add(m_attNameField, BorderLayout.CENTER); JPanel attTypeP = new JPanel(new BorderLayout()); attTypeP.setBorder(BorderFactory.createTitledBorder("Attribute type")); attTypeP.add(m_attTypeField, BorderLayout.CENTER); m_attTypeField.addItem("numeric"); m_attTypeField.addItem("nominal"); m_attTypeField.addItem("date"); m_attTypeField.addItem("string"); JPanel nomDateP = new JPanel(new BorderLayout()); nomDateP.setBorder(BorderFactory .createTitledBorder("Nominal vals/date format")); nomDateP.add(m_nominalOrDateFormatField, BorderLayout.CENTER); fieldHolder.add(attNameP); fieldHolder.add(attTypeP); fieldHolder.add(nomDateP); controlHolder.add(fieldHolder, BorderLayout.NORTH); mainHolder.add(controlHolder, BorderLayout.NORTH); m_list.setVisibleRowCount(5); m_deleteBut.setEnabled(false); JPanel listPanel = new JPanel(); listPanel.setLayout(new BorderLayout()); JPanel butHolder = new JPanel(); butHolder.setLayout(new GridLayout(1, 0)); butHolder.add(m_newBut); butHolder.add(m_deleteBut); butHolder.add(m_upBut); butHolder.add(m_downBut); listPanel.add(butHolder, BorderLayout.NORTH); JScrollPane js = new JScrollPane(m_list); js.setBorder(BorderFactory.createTitledBorder("Attributes")); listPanel.add(js, BorderLayout.CENTER); mainHolder.add(listPanel, BorderLayout.CENTER); m_tabbedPane.addTab("Attribute definitions", mainHolder); m_tabbedPane.addTab("Data", m_viewerPanel); add(m_tabbedPane, BorderLayout.CENTER); m_attNameField.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { AttDef a = m_list.getSelectedValue(); if (a != null) { a.m_name = m_attNameField.getText(); m_list.repaint(); } } }); m_nominalOrDateFormatField .addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { AttDef a = m_list.getSelectedValue(); if (a != null) { a.m_nomOrDate = m_nominalOrDateFormatField.getText(); m_list.repaint(); } } }); m_attTypeField.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { AttDef a = m_list.getSelectedValue(); if (a != null) { String type = m_attTypeField.getSelectedItem().toString(); a.m_type = AttDef.attStringToType(type); m_list.repaint(); } } }); m_tabbedPane.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { if (m_tabbedPane.getSelectedIndex() == 1) { handleTabChange(); } } }); m_list.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { if (!m_deleteBut.isEnabled()) { m_deleteBut.setEnabled(true); } checkUpDown(); AttDef entry = m_list.getSelectedValue(); if (entry != null) { m_attNameField.setText(entry.m_name); m_attTypeField.setSelectedItem(Attribute.typeToString(entry.m_type)); m_nominalOrDateFormatField .setText(entry.m_nomOrDate != null ? entry.m_nomOrDate : ""); } } } }); m_newBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { AttDef def = new AttDef(m_attNameField.getText(), AttDef .attStringToType(m_attTypeField.getSelectedItem().toString()), m_nominalOrDateFormatField.getText()); m_listModel.addElement(def); m_list.setSelectedIndex(m_listModel.size() - 1); checkUpDown(); } }); m_deleteBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int selected = m_list.getSelectedIndex(); if (selected >= 0) { m_listModel.removeElementAt(selected); checkUpDown(); if (m_listModel.size() <= 1) { m_upBut.setEnabled(false); m_downBut.setEnabled(false); } } } }); m_upBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JListHelper.moveUp(m_list); checkUpDown(); } }); m_downBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JListHelper.moveDown(m_list); checkUpDown(); } }); } /** * Set the enabled state of the up and down buttons based on the * currently selected row in the table */ protected void checkUpDown() { if (m_list.getSelectedValue() != null && m_listModel.size() > 1) { m_upBut.setEnabled(m_list.getSelectedIndex() > 0); m_downBut.setEnabled(m_list.getSelectedIndex() < m_listModel.size() - 1); } } /** * Called when the OK button is pressed */ @Override public void okPressed() { Instances current = m_viewerPanel.getInstances(); if (current != null) { ((DataGrid) getStepToEdit()).setData(current.toString()); } else { ((DataGrid) getStepToEdit()).setData(""); } } /** * Called when the user changes to the data tab */ protected void handleTabChange() { // first construct empty instances from attribute definitions ArrayList<Attribute> atts = new ArrayList<Attribute>(); for (AttDef a : Collections.list(m_listModel.elements())) { if (a.m_type == Attribute.NUMERIC) { atts.add(new Attribute(a.m_name)); } else if (a.m_type == Attribute.STRING) { atts.add(new Attribute(a.m_name, (List<String>) null)); } else if (a.m_type == Attribute.DATE) { atts.add(new Attribute(a.m_name, a.m_nomOrDate)); } else if (a.m_type == Attribute.NOMINAL) { List<String> vals = new ArrayList<String>(); for (String v : a.m_nomOrDate.split(",")) { vals.add(v.trim()); } atts.add(new Attribute(a.m_name, vals)); } else if (a.m_type == Attribute.RELATIONAL) { // TODO } } Instances defInsts = new Instances("DataGrid", atts, 0); // get current editor instances Instances editInsts = m_viewerPanel.getInstances(); if (editInsts != null) { // if there is no data in the editor then just overwrite with // the current definition if (editInsts.numInstances() == 0) { m_viewerPanel.setInstances(defInsts); } else { Map<Integer, Integer> transferMap = new HashMap<>(); for (int i = 0; i < editInsts.numAttributes(); i++) { Attribute eA = editInsts.attribute(i); Attribute dA = defInsts.attribute(eA.name()); if (dA != null && dA.type() == eA.type()) { transferMap.put(i, dA.index()); } } if (transferMap.size() > 0) { Instances defCopy = new Instances(defInsts, 0); for (int i = 0; i < editInsts.numInstances(); i++) { double[] vals = new double[defCopy.numAttributes()]; Instance editInst = editInsts.instance(i); for (int j = 0; j < vals.length; j++) { vals[j] = Utils.missingValue(); } for (Map.Entry<Integer, Integer> e : transferMap.entrySet()) { if (editInst.attribute(e.getKey()).isNumeric()) { vals[e.getValue()] = editInst.value(e.getKey()); } else if (editInst.attribute(e.getKey()).isNominal()) { if (!editInst.isMissing(e.getKey())) { int defIndex = defCopy.attribute(e.getValue()).indexOfValue( editInst.stringValue(e.getKey())); vals[e.getValue()] = defIndex >= 0 ? defIndex : Utils.missingValue(); } } else if (editInst.attribute(e.getKey()).isString()) { if (!editInst.isMissing(e.getKey())) { String editVal = editInst.stringValue(e.getKey()); vals[e.getValue()] = defCopy.attribute(e.getValue()).addStringValue(editVal); } } else if (editInst.attribute(e.getKey()).isRelationValued()) { // TODO } } defCopy.add(new DenseInstance(1.0, vals)); } m_viewerPanel.setInstances(defCopy); } else { // nothing in common between the two m_viewerPanel.setInstances(defInsts); } } } else { m_viewerPanel.setInstances(defInsts); } } /** * Small holder class for attribute information */ protected static class AttDef { protected String m_name = ""; protected int m_type = Attribute.NUMERIC; protected String m_nomOrDate = ""; /** * Constructor * * @param name name of the attribute * @param type type of the attribute * @param nomOrDate nominal values or date format string */ public AttDef(String name, int type, String nomOrDate) { m_name = name; m_type = type; m_nomOrDate = nomOrDate; } /** * Creates a string representation of the attribute that * gets displayed in the list * * @return a string representation of the attribute */ public String toString() { String result = "@attribute " + m_name + " " + (m_type != Attribute.NOMINAL ? Attribute.typeToString(m_type) : " {"); if (m_type == Attribute.NOMINAL) { result += m_nomOrDate + "}"; } else if (m_type == Attribute.DATE) { result += " " + m_nomOrDate; } return result; } /** * Convert a string attribute type to the corresponding integer type code * * @param type the string attribute type * @return the integer code */ public static int attStringToType(String type) { if (type.equals("numeric")) { return Attribute.NUMERIC; } else if (type.equals("nominal")) { return Attribute.NOMINAL; } else if (type.equals("string")) { return Attribute.STRING; } else if (type.equals("date")) { return Attribute.DATE; } else if (type.equals("relational")) { return Attribute.RELATIONAL; } return Attribute.NUMERIC; } } /** * Small wrapper pane for the ArffPanel. Provides an undo and * add instance button */ protected static class ArffViewerPanel extends JPanel { private static final long serialVersionUID = 2965315087365186710L; /** Click to undo the last action */ protected JButton m_UndoButton = new JButton("Undo"); /** Click to add a new instance to the end of the dataset */ protected JButton m_addInstanceButton = new JButton("Add instance"); /** the panel to display the Instances-object */ protected ArffPanel m_ArffPanel = new ArffPanel(); /** * Constructor */ public ArffViewerPanel() { setLayout(new BorderLayout()); add(m_ArffPanel, BorderLayout.CENTER); // Buttons JPanel panel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); panel.add(m_addInstanceButton); panel.add(m_UndoButton); add(panel, BorderLayout.SOUTH); m_UndoButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { undo(); } }); m_addInstanceButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m_ArffPanel.addInstanceAtEnd(); } }); } /** * sets the instances to display */ public void setInstances(Instances inst) { m_ArffPanel.setInstances(new Instances(inst)); m_ArffPanel.setOptimalColWidths(); } /** * returns the currently displayed instances */ public Instances getInstances() { return m_ArffPanel.getInstances(); } /** * sets the state of the buttons */ protected void setButtons() { m_UndoButton.setEnabled(m_ArffPanel.canUndo()); } /** * undoes the last action */ private void undo() { m_ArffPanel.undo(); } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow/steps/DataVisualizerInteractiveView.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /*` * DataVisualizerInteractiveView.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.gui.knowledgeflow.steps; import weka.core.Defaults; import weka.core.Settings; import weka.core.WekaException; import weka.gui.ResultHistoryPanel; import weka.gui.knowledgeflow.BaseInteractiveViewer; import weka.gui.visualize.PlotData2D; import weka.gui.visualize.VisualizePanel; import weka.gui.visualize.VisualizeUtils; import weka.knowledgeflow.steps.DataVisualizer; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JSplitPane; import javax.swing.ListSelectionModel; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.List; /** * Interactive viewer for the DataVisualizer step * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class DataVisualizerInteractiveView extends BaseInteractiveViewer { private static final long serialVersionUID = 5345799787154266282L; /** Holds results */ protected ResultHistoryPanel m_history; /** The actual visualization */ protected VisualizePanel m_visPanel = new VisualizePanel(); /** Button for clearing all results */ protected JButton m_clearButton = new JButton("Clear results"); /** Split pane for separating result list from visualization */ protected JSplitPane m_splitPane; /** Curent plot data */ protected PlotData2D m_currentPlot; /** ID used for identifying settings */ protected static final String ID = "weka.gui.knowledgeflow.steps.DataVisualizerInteractiveView"; /** * Get the name of this viewer * * @return the name of this viewer */ @Override public String getViewerName() { return "Data Visualizer"; } /** * Initialize and layout the viewer * * @throws WekaException if a problem occurs */ @Override public void init() throws WekaException { addButton(m_clearButton); m_history = new ResultHistoryPanel(null); m_history.setBorder(BorderFactory.createTitledBorder("Result list")); m_history.setHandleRightClicks(false); m_history.setDeleteListener(new ResultHistoryPanel.RDeleteListener() { @Override public void entryDeleted(String name, int index) { ((DataVisualizer) getStep()).getPlots().remove(index); } @Override public void entriesDeleted(java.util.List<String> names, java.util.List<Integer> indexes) { List<PlotData2D> ds = ((DataVisualizer) getStep()).getPlots(); List<PlotData2D> toRemove = new ArrayList<PlotData2D>(); for (int i : indexes) { toRemove.add(ds.get(i)); } ds.removeAll(toRemove); } }); m_history.getList().addMouseListener( new ResultHistoryPanel.RMouseAdapter() { private static final long serialVersionUID = -5174882230278923704L; @Override public void mouseClicked(MouseEvent e) { int index = m_history.getList().locationToIndex(e.getPoint()); if (index != -1) { String name = m_history.getNameAtIndex(index); // doPopup(name); Object plotD = m_history.getNamedObject(name); if (plotD instanceof PlotData2D) { try { if (m_currentPlot != null && m_currentPlot != plotD) { m_currentPlot.setXindex(m_visPanel.getXIndex()); m_currentPlot.setYindex(m_visPanel.getYIndex()); m_currentPlot.setCindex(m_visPanel.getCIndex()); } m_currentPlot = (PlotData2D) plotD; int x = m_currentPlot.getXindex(); int y = m_currentPlot.getYindex(); int c = m_currentPlot.getCindex(); if (x == y && x == 0 && m_currentPlot.getPlotInstances().numAttributes() > 1) { y++; } m_visPanel.setMasterPlot((PlotData2D) plotD); m_visPanel.setXIndex(x); m_visPanel.setYIndex(y); m_visPanel.setColourIndex(c, true); m_visPanel.repaint(); } catch (Exception ex) { ex.printStackTrace(); } } } } }); m_history.getList().getSelectionModel() .addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { ListSelectionModel lm = (ListSelectionModel) e.getSource(); for (int i = e.getFirstIndex(); i <= e.getLastIndex(); i++) { if (lm.isSelectedIndex(i)) { // m_AttSummaryPanel.setAttribute(i); if (i != -1) { String name = m_history.getNameAtIndex(i); Object plotD = m_history.getNamedObject(name); if (plotD != null && plotD instanceof PlotData2D) { try { if (m_currentPlot != null && m_currentPlot != plotD) { m_currentPlot.setXindex(m_visPanel.getXIndex()); m_currentPlot.setYindex(m_visPanel.getYIndex()); m_currentPlot.setCindex(m_visPanel.getCIndex()); } m_currentPlot = (PlotData2D) plotD; int x = m_currentPlot.getXindex(); int y = m_currentPlot.getYindex(); int c = m_currentPlot.getCindex(); if (x == y && x == 0 && m_currentPlot.getPlotInstances().numAttributes() > 1) { y++; } m_visPanel.setMasterPlot((PlotData2D) plotD); m_visPanel.setXIndex(x); m_visPanel.setYIndex(y); m_visPanel.setColourIndex(c, true); m_visPanel.repaint(); } catch (Exception ex) { ex.printStackTrace(); } } } break; } } } } }); m_visPanel.setPreferredSize(new Dimension(800, 600)); m_splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, m_history, m_visPanel); add(m_splitPane, BorderLayout.CENTER); m_splitPane.setDividerLocation(200 + m_splitPane.getInsets().left); boolean first = true; for (PlotData2D pd : ((DataVisualizer) getStep()).getPlots()) { m_history.addResult(pd.getPlotName(), new StringBuffer()); m_history.addObject(pd.getPlotName(), pd); if (first) { try { int x = pd.getXindex(); int y = pd.getYindex(); int c = pd.getCindex(); if (x == 0 && y == 0 && pd.getPlotInstances().numAttributes() > 1) { y++; } m_visPanel.setMasterPlot(pd); m_currentPlot = pd; m_visPanel.setXIndex(x); m_visPanel.setYIndex(y); if (pd.getPlotInstances().classIndex() >= 0) { m_visPanel.setColourIndex(pd.getPlotInstances().classIndex(), true); } else { m_visPanel.setColourIndex(c, true); } m_visPanel.repaint(); first = false; } catch (Exception ex) { ex.printStackTrace(); } } applySettings(getSettings()); } m_clearButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m_history.clearResults(); ((DataVisualizer) getStep()).getPlots().clear(); m_splitPane.remove(m_visPanel); } }); } /** * Get default settings for this viewer * * @return the default settings of this viewer */ @Override public Defaults getDefaultSettings() { Defaults d = new VisualizeUtils.VisualizeDefaults(); d.setID(ID); return d; } /** * Apply any user changes in the supplied settings object * * @param settings the settings object that might (or might not) have been * altered by the user */ @Override public void applySettings(Settings settings) { m_visPanel.applySettings(settings, ID); m_visPanel.repaint(); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow/steps/DataVisualizerStepEditorDialog.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * DataVisualizerStepEditorDialog.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.gui.knowledgeflow.steps; import weka.knowledgeflow.steps.DataVisualizer; /** * Editor dialog for the DataVisualizer step * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class DataVisualizerStepEditorDialog extends ModelPerformanceChartStepEditorDialog { private static final long serialVersionUID = -6032558757326543902L; /** * Get the name of the offscreen renderer and options from the step * being edited */ @Override protected void getCurrentSettings() { m_currentRendererName = ((DataVisualizer) getStepToEdit()).getOffscreenRendererName(); m_currentRendererOptions = ((DataVisualizer) getStepToEdit()).getOffscreenAdditionalOpts(); } /** * Called when the OK button is pressed */ @Override public void okPressed() { ((DataVisualizer) getStepToEdit()) .setOffscreenRendererName(m_offscreenSelector.getSelectedItem() .toString()); ((DataVisualizer) getStepToEdit()) .setOffscreenAdditionalOpts(m_rendererOptions.getText()); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow/steps/ExecuteProcessStepEditorDialog.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ExecuteProcessStepEditorDialog.java * Copyright (C) 2017 University of Waikato, Hamilton, New Zealand * */ package weka.gui.knowledgeflow.steps; import java.awt.BorderLayout; import java.awt.GridLayout; import java.util.List; import java.util.Map; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTabbedPane; import javax.swing.JTextField; import javax.swing.SwingConstants; import weka.core.Environment; import weka.core.Instances; import weka.core.WekaException; import weka.gui.FileEnvironmentField; import weka.gui.knowledgeflow.StepEditorDialog; import weka.knowledgeflow.StepManager; import weka.knowledgeflow.steps.ExecuteProcess; /** * Step editor dialog for the ExecuteProcess step * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class ExecuteProcessStepEditorDialog extends StepEditorDialog { private static final long serialVersionUID = -7740004961609720209L; /** Panel for static commands */ protected StaticProcessPanel m_staticPanel; /** Panel for dynamic commands */ protected DynamicProcessPanel m_dynamicPanel; /** Checkbox to indicate whether dynamic commands are to be executed */ protected JCheckBox m_useDynamicCheck = new JCheckBox( "Execute dynamic commands"); /** * Checkbox to indicate whether complete command failure (vs just returning a * non-zero status) should generate an exception */ protected JCheckBox m_raiseExceptonOnCommandFailure = new JCheckBox( "Raise an exception for command failure"); /** * Layout the editor dialog */ @Override protected void layoutEditor() { ExecuteProcess executeProcess = ((ExecuteProcess) getStepToEdit()); boolean hasIncomingInstances = executeProcess.getStepManager().numIncomingConnectionsOfType( StepManager.CON_INSTANCE) > 0 || executeProcess.getStepManager().numIncomingConnectionsOfType( StepManager.CON_ENVIRONMENT) > 0; Environment env = Environment.getSystemWide(); JPanel holderP = new JPanel(new BorderLayout()); JPanel checkP = new JPanel(new BorderLayout()); holderP.add(checkP, BorderLayout.NORTH); if (hasIncomingInstances) { checkP.add(m_useDynamicCheck, BorderLayout.NORTH); m_useDynamicCheck.setSelected(executeProcess.getUseDynamic()); } else { m_useDynamicCheck = null; } checkP.add(m_raiseExceptonOnCommandFailure, BorderLayout.SOUTH); m_raiseExceptonOnCommandFailure.setSelected(executeProcess .getRaiseExceptionOnCommandFailure()); m_staticPanel = new StaticProcessPanel(executeProcess, env); if (hasIncomingInstances) { JTabbedPane tabbedPane = new JTabbedPane(); tabbedPane.add("Static", m_staticPanel); m_dynamicPanel = new DynamicProcessPanel(executeProcess); tabbedPane.add("Dynamic", m_dynamicPanel); holderP.add(tabbedPane, BorderLayout.CENTER); } else { holderP.add(m_staticPanel, BorderLayout.CENTER); } add(holderP, BorderLayout.CENTER); } /** * Executed when the OK button is pressed */ @Override protected void okPressed() { ExecuteProcess executeProcess = (ExecuteProcess) getStepToEdit(); if (m_useDynamicCheck != null && m_useDynamicCheck.isSelected()) { m_dynamicPanel.applyToStep(executeProcess); } executeProcess .setRaiseExceptionOnCommandFailure(m_raiseExceptonOnCommandFailure .isSelected()); m_staticPanel.applyToStep(executeProcess); } /** * Panel for static command configuration */ protected class StaticProcessPanel extends JPanel { private static final long serialVersionUID = -4215730214067279661L; protected JTextField m_cmdText = new JTextField(10); protected JTextField m_argsText = new JTextField(10); protected FileEnvironmentField m_workingDirField; public StaticProcessPanel(ExecuteProcess executeProcess, Environment env) { m_workingDirField = new FileEnvironmentField("", env, JFileChooser.OPEN_DIALOG, true); setLayout(new GridLayout(0, 2)); add(new JLabel("Command", SwingConstants.RIGHT)); add(m_cmdText); add(new JLabel("Arguments", SwingConstants.RIGHT)); add(m_argsText); add(new JLabel("Working directory", SwingConstants.RIGHT)); add(m_workingDirField); String cmd = executeProcess.getStaticCmd(); if (cmd != null && cmd.length() > 0) { m_cmdText.setText(cmd); } String args = executeProcess.getStaticArgs(); if (args != null && args.length() > 0) { m_argsText.setText(args); } String workingDir = executeProcess.getStaticWorkingDir(); if (workingDir != null && workingDir.length() > 0) { m_workingDirField.setCurrentDirectory(workingDir); } m_workingDirField.setEnvironment(env); } public void applyToStep(ExecuteProcess executeProcess) { executeProcess.setStaticCmd(m_cmdText.getText()); executeProcess.setStaticArgs(m_argsText.getText()); executeProcess.setStaticWorkingDir(m_workingDirField.getText()); } } /** * Panel for dynamic command configuration */ protected class DynamicProcessPanel extends JPanel { private static final long serialVersionUID = 6440523583792476595L; protected JComboBox<String> m_cmdField = new JComboBox<>(); protected JComboBox<String> m_argsField = new JComboBox<>(); protected JComboBox<String> m_workingDirField = new JComboBox<>(); public DynamicProcessPanel(ExecuteProcess executeProcess) { m_cmdField.setEditable(true); m_argsField.setEditable(true); m_workingDirField.setEditable(true); Map<String, List<StepManager>> incomingConnTypes = executeProcess.getStepManager().getIncomingConnections(); // we are guaranteed exactly one incoming connection String incomingConnType = incomingConnTypes.keySet().iterator().next(); try { Instances incomingStructure = executeProcess.outputStructureForConnectionType(incomingConnType); if (incomingStructure != null) { // add blank entries to indicate no args or working directory // necessary m_argsField.addItem(""); m_workingDirField.addItem(""); for (int i = 0; i < incomingStructure.numAttributes(); i++) { if (incomingStructure.attribute(i).isString() || incomingStructure.attribute(i).isNominal()) { m_cmdField.addItem(incomingStructure.attribute(i).name()); m_argsField.addItem(incomingStructure.attribute(i).name()); m_workingDirField.addItem(incomingStructure.attribute(i).name()); } } } String currentCmdField = executeProcess.getDynamicCmdField(); if (currentCmdField != null && currentCmdField.length() > 0) { m_cmdField.setSelectedItem(currentCmdField); } String currentArgsField = executeProcess.getDynamicArgsField(); if (currentArgsField != null && currentArgsField.length() > 0) { m_argsField.setSelectedItem(currentArgsField); } String currentWorkingDirField = executeProcess.getDynamicWorkingDirField(); if (currentWorkingDirField != null && currentWorkingDirField.length() > 0) { m_workingDirField.setSelectedItem(currentWorkingDirField); } } catch (WekaException ex) { showErrorDialog(ex); } setLayout(new GridLayout(0, 2)); add(new JLabel("Command attribute", SwingConstants.RIGHT)); add(m_cmdField); add(new JLabel("Arguments attribute", SwingConstants.RIGHT)); add(m_argsField); add(new JLabel("Working dir attribute", SwingConstants.RIGHT)); add(m_workingDirField); } public void applyToStep(ExecuteProcess executeProcess) { executeProcess .setDynamicCmdField(m_cmdField.getSelectedItem().toString()); executeProcess.setDynamicArgsField(m_argsField.getSelectedItem() .toString()); executeProcess.setDynamicWorkingDirField(m_workingDirField .getSelectedItem().toString()); executeProcess.setUseDynamic(m_useDynamicCheck.isSelected()); } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow/steps/FlowByExpressionStepEditorDialog.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * FlowByExpressionStepEditorDialog.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.gui.knowledgeflow.steps; import weka.core.Instances; import weka.core.WekaException; import weka.gui.EnvironmentField; import weka.gui.knowledgeflow.StepEditorDialog; import weka.knowledgeflow.StepManager; import weka.knowledgeflow.steps.FlowByExpression; import javax.swing.*; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.DefaultTreeSelectionModel; import javax.swing.tree.TreePath; import javax.swing.tree.TreeSelectionModel; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.List; /** * Step editor dialog for the FlowByExpression step * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class FlowByExpressionStepEditorDialog extends StepEditorDialog { private static final long serialVersionUID = 1545740909421963983L; /** Combo box for the LHS of the expression being entered */ protected JComboBox m_lhsField = new EnvironmentField.WideComboBox(); /** Combo box for choosing the operator */ protected JComboBox<String> m_operatorCombo = new JComboBox<String>(); /** Combo box for the RHS of the expression being entered */ protected JComboBox m_rhsField = new EnvironmentField.WideComboBox(); /** Check box for indicating that the RHS is the name of an attribute */ protected JCheckBox m_rhsIsAttribute = new JCheckBox("RHS is attribute"); /** Label for displaying the current expression */ protected JLabel m_expressionLab = new JLabel(); /** * Combo box for choosing the downstream step that * instances matching the expression should go to */ protected JComboBox<String> m_trueData = new JComboBox<String>(); /** * Combo box for choosing the downstream step that instances failing * to match the expression should go to */ protected JComboBox<String> m_falseData = new JComboBox<String>(); /** Holds the tree view of the expression */ protected JTree m_expressionTree; /** Root of the tree */ protected DefaultMutableTreeNode m_treeRoot; /** Button for adding a new expression node to the expression tree */ protected JButton m_addExpressionNode = new JButton("Add Expression node"); /** Button for adding a new brackets node to the expression tree */ protected JButton m_addBracketNode = new JButton("Add bracket node"); /** Button for toggling negation */ protected JButton m_toggleNegation = new JButton("Toggle negation"); /** Button for and/or */ protected JButton m_andOr = new JButton("And/Or"); /** Button for deleting a node from the expression tree */ protected JButton m_deleteNode = new JButton("Delete node"); /** * Layout the editor */ @Override @SuppressWarnings("unchecked") protected void layoutEditor() { JPanel outerP = new JPanel(new BorderLayout()); JPanel controlHolder = new JPanel(); controlHolder.setLayout(new BorderLayout()); setupTree(outerP); JPanel fieldHolder = new JPanel(); fieldHolder.setLayout(new GridLayout(0, 4)); JPanel lhsP = new JPanel(); lhsP.setLayout(new BorderLayout()); lhsP.setBorder(BorderFactory.createTitledBorder("Attribute")); // m_lhsField = new EnvironmentField(m_env); m_lhsField.setEditable(true); lhsP.add(m_lhsField, BorderLayout.CENTER); lhsP.setToolTipText("<html>Name or index of attribute. " + "also accepts<br>the special labels \"/first\" and \"/last\"" + " to indicate<br>the first and last attribute respecitively</html>"); m_lhsField.setToolTipText("<html>Name or index of attribute. " + "also accepts<br>the special labels \"/first\" and \"/last\"" + " to indicate<br>the first and last attribute respecitively</html>"); JPanel operatorP = new JPanel(); operatorP.setLayout(new BorderLayout()); operatorP.setBorder(BorderFactory.createTitledBorder("Operator")); m_operatorCombo.addItem(" = "); m_operatorCombo.addItem(" != "); m_operatorCombo.addItem(" < "); m_operatorCombo.addItem(" <= "); m_operatorCombo.addItem(" > "); m_operatorCombo.addItem(" >= "); m_operatorCombo.addItem(" isMissing "); m_operatorCombo.addItem(" contains "); m_operatorCombo.addItem(" startsWith "); m_operatorCombo.addItem(" endsWith "); m_operatorCombo.addItem(" regex "); operatorP.add(m_operatorCombo, BorderLayout.CENTER); JPanel rhsP = new JPanel(); rhsP.setLayout(new BorderLayout()); rhsP.setBorder(BorderFactory.createTitledBorder("Constant or attribute")); rhsP.setToolTipText("<html>Constant value to test/check for. If " + "testing<br>against an attribute, then this specifies" + "an attribute index or name</html>"); // m_rhsField = new EnvironmentField(m_env); m_rhsField.setEditable(true); rhsP.add(m_rhsField, BorderLayout.CENTER); fieldHolder.add(lhsP); fieldHolder.add(operatorP); fieldHolder.add(rhsP); fieldHolder.add(m_rhsIsAttribute); controlHolder.add(fieldHolder, BorderLayout.SOUTH); JPanel tempPanel = new JPanel(); tempPanel.setLayout(new BorderLayout()); JPanel expressionP = new JPanel(); expressionP.setLayout(new BorderLayout()); expressionP.setBorder(BorderFactory.createTitledBorder("Expression")); JPanel tempE = new JPanel(); tempE.setLayout(new BorderLayout()); tempE.setBorder(BorderFactory.createEmptyBorder(5, 0, 5, 0)); tempE.add(m_expressionLab, BorderLayout.CENTER); JScrollPane expressionScroller = new JScrollPane(tempE); expressionP.add(expressionScroller, BorderLayout.CENTER); tempPanel.add(expressionP, BorderLayout.SOUTH); // JPanel flowControlP = new JPanel(); flowControlP.setLayout(new GridLayout(2, 2)); flowControlP.add(new JLabel("Send true instances to node", SwingConstants.RIGHT)); flowControlP.add(m_trueData); flowControlP.add(new JLabel("Send false instances to node", SwingConstants.RIGHT)); flowControlP.add(m_falseData); tempPanel.add(flowControlP, BorderLayout.NORTH); String falseStepN = ((FlowByExpression) getStepToEdit()).getFalseStepName(); String trueStepN = ((FlowByExpression) getStepToEdit()).getTrueStepName(); List<String> connectedSteps = ((FlowByExpression) getStepToEdit()).getDownstreamStepNames(); m_trueData.addItem("<none>"); m_falseData.addItem("<none>"); for (String s : connectedSteps) { m_trueData.addItem(s); m_falseData.addItem(s); } if (falseStepN != null && falseStepN.length() > 0) { m_falseData.setSelectedItem(falseStepN); } if (trueStepN != null && trueStepN.length() > 0) { m_trueData.setSelectedItem(trueStepN); } controlHolder.add(tempPanel, BorderLayout.NORTH); outerP.add(controlHolder, BorderLayout.NORTH); add(outerP, BorderLayout.CENTER); m_rhsIsAttribute.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (m_expressionTree != null) { TreePath p = m_expressionTree.getSelectionPath(); if (p != null) { if (p.getLastPathComponent() instanceof DefaultMutableTreeNode) { DefaultMutableTreeNode tNode = (DefaultMutableTreeNode) p.getLastPathComponent(); FlowByExpression.ExpressionNode thisNode = (FlowByExpression.ExpressionNode) tNode.getUserObject(); if (thisNode instanceof FlowByExpression.ExpressionClause) { ((FlowByExpression.ExpressionClause) thisNode) .setRHSIsAnAttribute(m_rhsIsAttribute.isSelected()); DefaultTreeModel tmodel = (DefaultTreeModel) m_expressionTree.getModel(); tmodel.nodeStructureChanged(tNode); updateExpressionLabel(); } } } } } }); m_operatorCombo.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (m_operatorCombo.getSelectedIndex() > 5) { m_rhsIsAttribute.setSelected(false); m_rhsIsAttribute.setEnabled(false); } else { m_rhsIsAttribute.setEnabled(true); } if (m_expressionTree != null) { TreePath p = m_expressionTree.getSelectionPath(); if (p != null) { if (p.getLastPathComponent() instanceof DefaultMutableTreeNode) { DefaultMutableTreeNode tNode = (DefaultMutableTreeNode) p.getLastPathComponent(); FlowByExpression.ExpressionNode thisNode = (FlowByExpression.ExpressionNode) tNode.getUserObject(); if (thisNode instanceof FlowByExpression.ExpressionClause) { String selection = m_operatorCombo.getSelectedItem().toString(); FlowByExpression.ExpressionClause.ExpressionType t = FlowByExpression.ExpressionClause.ExpressionType.EQUALS; for (FlowByExpression.ExpressionClause.ExpressionType et : FlowByExpression.ExpressionClause.ExpressionType .values()) { if (et.toString().equals(selection)) { t = et; break; } } ((FlowByExpression.ExpressionClause) thisNode).setOperator(t); DefaultTreeModel tmodel = (DefaultTreeModel) m_expressionTree.getModel(); tmodel.nodeStructureChanged(tNode); updateExpressionLabel(); } } } } } }); m_lhsField.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (m_expressionTree != null) { TreePath p = m_expressionTree.getSelectionPath(); if (p != null) { if (p.getLastPathComponent() instanceof DefaultMutableTreeNode) { DefaultMutableTreeNode tNode = (DefaultMutableTreeNode) p.getLastPathComponent(); FlowByExpression.ExpressionNode thisNode = (FlowByExpression.ExpressionNode) tNode.getUserObject(); if (thisNode instanceof FlowByExpression.ExpressionClause) { Object text = m_lhsField.getSelectedItem(); if (text != null) { ((FlowByExpression.ExpressionClause) thisNode) .setLHSAttName(text.toString()); DefaultTreeModel tmodel = (DefaultTreeModel) m_expressionTree.getModel(); tmodel.nodeStructureChanged(tNode); updateExpressionLabel(); } } } } } } }); m_lhsField.getEditor().getEditorComponent() .addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { if (m_expressionTree != null) { TreePath p = m_expressionTree.getSelectionPath(); if (p != null) { if (p.getLastPathComponent() instanceof DefaultMutableTreeNode) { DefaultMutableTreeNode tNode = (DefaultMutableTreeNode) p.getLastPathComponent(); FlowByExpression.ExpressionNode thisNode = (FlowByExpression.ExpressionNode) tNode.getUserObject(); if (thisNode instanceof FlowByExpression.ExpressionClause) { String text = ""; if (m_lhsField.getSelectedItem() != null) { text = m_lhsField.getSelectedItem().toString(); } java.awt.Component theEditor = m_lhsField.getEditor().getEditorComponent(); if (theEditor instanceof JTextField) { text = ((JTextField) theEditor).getText(); } ((FlowByExpression.ExpressionClause) thisNode) .setLHSAttName(text); DefaultTreeModel tmodel = (DefaultTreeModel) m_expressionTree.getModel(); tmodel.nodeStructureChanged(tNode); updateExpressionLabel(); } } } } } }); m_rhsField.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (m_expressionTree != null) { TreePath p = m_expressionTree.getSelectionPath(); if (p != null) { if (p.getLastPathComponent() instanceof DefaultMutableTreeNode) { DefaultMutableTreeNode tNode = (DefaultMutableTreeNode) p.getLastPathComponent(); FlowByExpression.ExpressionNode thisNode = (FlowByExpression.ExpressionNode) tNode.getUserObject(); if (thisNode instanceof FlowByExpression.ExpressionClause) { Object text = m_rhsField.getSelectedItem(); if (text != null) { ((FlowByExpression.ExpressionClause) thisNode) .setRHSOperand(text.toString()); DefaultTreeModel tmodel = (DefaultTreeModel) m_expressionTree.getModel(); tmodel.nodeStructureChanged(tNode); updateExpressionLabel(); } } } } } } }); m_rhsField.getEditor().getEditorComponent() .addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { if (m_expressionTree != null) { TreePath p = m_expressionTree.getSelectionPath(); if (p != null) { if (p.getLastPathComponent() instanceof DefaultMutableTreeNode) { DefaultMutableTreeNode tNode = (DefaultMutableTreeNode) p.getLastPathComponent(); FlowByExpression.ExpressionNode thisNode = (FlowByExpression.ExpressionNode) tNode.getUserObject(); if (thisNode instanceof FlowByExpression.ExpressionClause) { String text = ""; if (m_rhsField.getSelectedItem() != null) { text = m_rhsField.getSelectedItem().toString(); } java.awt.Component theEditor = m_rhsField.getEditor().getEditorComponent(); if (theEditor instanceof JTextField) { text = ((JTextField) theEditor).getText(); } if (m_rhsField.getSelectedItem() != null) { ((FlowByExpression.ExpressionClause) thisNode) .setRHSOperand(text); DefaultTreeModel tmodel = (DefaultTreeModel) m_expressionTree.getModel(); tmodel.nodeStructureChanged(tNode); updateExpressionLabel(); } } } } } } }); try { Instances incomingStructure = getStepToEdit().getStepManager().getIncomingStructureForConnectionType( StepManager.CON_INSTANCE); if (incomingStructure == null) { incomingStructure = getStepToEdit().getStepManager() .getIncomingStructureForConnectionType(StepManager.CON_DATASET); } if (incomingStructure == null) { incomingStructure = getStepToEdit().getStepManager() .getIncomingStructureForConnectionType(StepManager.CON_TRAININGSET); } if (incomingStructure == null) { incomingStructure = getStepToEdit().getStepManager() .getIncomingStructureForConnectionType(StepManager.CON_TESTSET); } if (incomingStructure != null) { m_lhsField.removeAllItems(); m_rhsField.removeAllItems(); for (int i = 0; i < incomingStructure.numAttributes(); i++) { m_lhsField.addItem(incomingStructure.attribute(i).name()); m_rhsField.addItem(incomingStructure.attribute(i).name()); } } } catch (WekaException ex) { showErrorDialog(ex); } } private void setExpressionEditor(FlowByExpression.ExpressionClause node) { String lhs = node.getLHSAttName(); if (lhs != null) { m_lhsField.setSelectedItem(lhs); } String rhs = node.getRHSOperand(); if (rhs != null) { m_rhsField.setSelectedItem(rhs); } FlowByExpression.ExpressionClause.ExpressionType opp = node.getOperator(); int oppIndex = opp.ordinal(); m_operatorCombo.setSelectedIndex(oppIndex); m_rhsIsAttribute.setSelected(node.isRHSAnAttribute()); } private void updateExpressionLabel() { StringBuffer buff = new StringBuffer(); FlowByExpression.ExpressionNode root = (FlowByExpression.ExpressionNode) m_treeRoot.getUserObject(); root.toStringDisplay(buff); m_expressionLab.setText(buff.toString()); } private void setupTree(JPanel holder) { JPanel treeHolder = new JPanel(); treeHolder.setLayout(new BorderLayout()); treeHolder.setBorder(BorderFactory.createTitledBorder("Expression tree")); String expressionString = ((FlowByExpression) getStepToEdit()).getExpressionString(); if (expressionString == null || expressionString.length() == 0) { expressionString = "()"; } FlowByExpression.BracketNode root = new FlowByExpression.BracketNode(); root.parseFromInternal(expressionString); root.setShowAndOr(false); m_treeRoot = root.toJTree(null); DefaultTreeModel model = new DefaultTreeModel(m_treeRoot); m_expressionTree = new JTree(model); m_expressionTree.setEnabled(true); m_expressionTree.setRootVisible(true); m_expressionTree.setShowsRootHandles(true); DefaultTreeSelectionModel selectionModel = new DefaultTreeSelectionModel(); selectionModel.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); m_expressionTree.setSelectionModel(selectionModel); // add mouse listener to tree m_expressionTree.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { TreePath p = m_expressionTree.getSelectionPath(); if (p != null) { if (p.getLastPathComponent() instanceof DefaultMutableTreeNode) { DefaultMutableTreeNode tNode = (DefaultMutableTreeNode) p.getLastPathComponent(); FlowByExpression.ExpressionNode thisNode = (FlowByExpression.ExpressionNode) tNode.getUserObject(); if (thisNode instanceof FlowByExpression.ExpressionClause) { setExpressionEditor((FlowByExpression.ExpressionClause) thisNode); } } } } }); updateExpressionLabel(); JScrollPane treeView = new JScrollPane(m_expressionTree); treeHolder.add(treeView, BorderLayout.CENTER); JPanel butHolder = new JPanel(); // butHolder.setLayout(new BorderLayout()); butHolder.add(m_addExpressionNode); butHolder.add(m_addBracketNode); butHolder.add(m_toggleNegation); butHolder.add(m_andOr); butHolder.add(m_deleteNode); treeHolder.add(butHolder, BorderLayout.NORTH); holder.add(treeHolder, BorderLayout.CENTER); Dimension d = treeHolder.getPreferredSize(); treeHolder.setPreferredSize(new Dimension(d.width, d.height / 2)); m_andOr.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { TreePath p = m_expressionTree.getSelectionPath(); if (p != null) { if (p.getLastPathComponent() instanceof DefaultMutableTreeNode) { DefaultMutableTreeNode tNode = (DefaultMutableTreeNode) p.getLastPathComponent(); FlowByExpression.ExpressionNode thisNode = (FlowByExpression.ExpressionNode) tNode.getUserObject(); thisNode.setIsOr(!thisNode.isOr()); DefaultTreeModel tmodel = (DefaultTreeModel) m_expressionTree.getModel(); tmodel.nodeStructureChanged(tNode); updateExpressionLabel(); } } else { showInfoDialog( "Please select a node in the tree to alter the boolean operator of", "And/Or", false); } } }); m_toggleNegation.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { TreePath p = m_expressionTree.getSelectionPath(); if (p != null) { if (p.getLastPathComponent() instanceof DefaultMutableTreeNode) { DefaultMutableTreeNode tNode = (DefaultMutableTreeNode) p.getLastPathComponent(); FlowByExpression.ExpressionNode thisNode = (FlowByExpression.ExpressionNode) tNode.getUserObject(); thisNode.setNegated(!thisNode.isNegated()); DefaultTreeModel tmodel = (DefaultTreeModel) m_expressionTree.getModel(); tmodel.nodeStructureChanged(tNode); updateExpressionLabel(); } } else { showInfoDialog( "Please select a node in the tree to toggle its negation", "Toggle negation", false); } } }); m_deleteNode.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { TreePath p = m_expressionTree.getSelectionPath(); if (p != null) { if (p.getLastPathComponent() instanceof DefaultMutableTreeNode) { DefaultMutableTreeNode tNode = (DefaultMutableTreeNode) p.getLastPathComponent(); if (tNode == m_treeRoot) { showInfoDialog("You can't delete the root of the tree!", "Delete node", true); } else { FlowByExpression.ExpressionNode thisNode = (FlowByExpression.ExpressionNode) tNode.getUserObject(); FlowByExpression.BracketNode parentNode = (FlowByExpression.BracketNode) ((DefaultMutableTreeNode) tNode .getParent()).getUserObject(); // remove from internal tree structure parentNode.removeChild(thisNode); // remove from jtree structure DefaultTreeModel tmodel = (DefaultTreeModel) m_expressionTree.getModel(); tmodel.removeNodeFromParent(tNode); updateExpressionLabel(); } } } else { showInfoDialog("Please select a node in the tree to delete.", "Delete node", false); } } }); m_addExpressionNode.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { TreePath p = m_expressionTree.getSelectionPath(); if (p != null) { if (p.getLastPathComponent() instanceof DefaultMutableTreeNode) { DefaultMutableTreeNode tNode = (DefaultMutableTreeNode) p.getLastPathComponent(); FlowByExpression.ExpressionNode thisNode = (FlowByExpression.ExpressionNode) tNode.getUserObject(); if (thisNode instanceof FlowByExpression.BracketNode) { FlowByExpression.ExpressionClause newNode = new FlowByExpression.ExpressionClause( FlowByExpression.ExpressionClause.ExpressionType.EQUALS, "<att name>", "<value>", false, false); ((FlowByExpression.BracketNode) thisNode).addChild(newNode); DefaultMutableTreeNode childNode = new DefaultMutableTreeNode(newNode); DefaultTreeModel tmodel = (DefaultTreeModel) m_expressionTree.getModel(); tNode.add(childNode); tmodel.nodeStructureChanged(tNode); updateExpressionLabel(); } else { showInfoDialog( "An expression can only be added to a bracket node.", "Add expression", false); } } } else { showInfoDialog( "You must select a bracket node in the tree view to add a new expression to.", "Add expression", false); } } }); m_addBracketNode.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { TreePath p = m_expressionTree.getSelectionPath(); if (p != null) { if (p.getLastPathComponent() instanceof DefaultMutableTreeNode) { DefaultMutableTreeNode tNode = (DefaultMutableTreeNode) p.getLastPathComponent(); FlowByExpression.ExpressionNode thisNode = (FlowByExpression.ExpressionNode) tNode.getUserObject(); if (thisNode instanceof FlowByExpression.BracketNode) { FlowByExpression.BracketNode newNode = new FlowByExpression.BracketNode(); ((FlowByExpression.BracketNode) thisNode).addChild(newNode); DefaultMutableTreeNode childNode = new DefaultMutableTreeNode(newNode); DefaultTreeModel tmodel = (DefaultTreeModel) m_expressionTree.getModel(); tNode.add(childNode); tmodel.nodeStructureChanged(tNode); updateExpressionLabel(); } else { showInfoDialog( "An new bracket node can only be added to an existing bracket node.", "Add bracket", false); } } } else { showInfoDialog( "You must select an existing bracket node in the tree in order to add a new bracket node.", "Add bracket", false); } } }); } /** * Called when the OK button gets pressed */ @Override protected void okPressed() { if (m_treeRoot != null) { FlowByExpression.ExpressionNode en = (FlowByExpression.ExpressionNode) m_treeRoot.getUserObject(); StringBuffer buff = new StringBuffer(); en.toStringInternal(buff); ((FlowByExpression) getStepToEdit()).setExpressionString(buff.toString()); if (m_trueData.getSelectedItem() != null && m_trueData.getSelectedItem().toString().length() > 0) { ((FlowByExpression) getStepToEdit()).setTrueStepName(m_trueData .getSelectedItem().toString()); } if (m_falseData.getSelectedItem() != null && m_falseData.getSelectedItem().toString().length() > 0) { ((FlowByExpression) getStepToEdit()).setFalseStepName(m_falseData .getSelectedItem().toString()); } } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow/steps/GraphViewerInteractiveView.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /*` * GraphViewerInteractiveView.java * Copyright (C) 2002-2015 University of Waikato, Hamilton, New Zealand * */ package weka.gui.knowledgeflow.steps; import weka.core.Drawable; import weka.core.WekaException; import weka.gui.ResultHistoryPanel; import weka.gui.graphvisualizer.BIFFormatException; import weka.gui.graphvisualizer.GraphVisualizer; import weka.gui.knowledgeflow.BaseInteractiveViewer; import weka.gui.treevisualizer.PlaceNode2; import weka.gui.treevisualizer.TreeVisualizer; import weka.knowledgeflow.Data; import weka.knowledgeflow.StepManager; import weka.knowledgeflow.steps.GraphViewer; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.JSplitPane; import javax.swing.ListSelectionModel; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.List; /** * Interactive viewer for the GraphViewer step. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class GraphViewerInteractiveView extends BaseInteractiveViewer { private static final long serialVersionUID = 2109423349272114409L; /** Holds a list of results */ protected ResultHistoryPanel m_history; /** Button for clearing the results */ protected JButton m_clearButton = new JButton("Clear results"); /** Split pane for separating the results list from the visualization */ protected JSplitPane m_splitPane; /** Visualization component for trees */ protected TreeVisualizer m_treeVisualizer; /** Visualization component for graphs */ protected GraphVisualizer m_graphVisualizer; /** Holder panel for layout purposes */ JPanel m_holderPanel = new JPanel(new BorderLayout()); /** * Get the name of this viewr * * @return the name of this viewer */ @Override public String getViewerName() { return "Graph Viewer"; } /** * Initializes the viewer * * @throws WekaException if a problem occurs */ @Override public void init() throws WekaException { addButton(m_clearButton); m_history = new ResultHistoryPanel(null); m_history.setBorder( BorderFactory.createTitledBorder( "Result list" ) ); m_history.setHandleRightClicks( false ); m_history.setDeleteListener(new ResultHistoryPanel.RDeleteListener() { @Override public void entryDeleted(String name, int index) { ((GraphViewer)getStep()).getDatasets().remove(index); } @Override public void entriesDeleted(java.util.List<String> names, java.util.List<Integer> indexes) { List<Data> ds = ((GraphViewer) getStep()).getDatasets(); List<Data> toRemove = new ArrayList<Data>(); for (int i : indexes) { toRemove.add(ds.get(i)); } ds.removeAll(toRemove); } }); m_history.getList().addMouseListener( new ResultHistoryPanel.RMouseAdapter() { private static final long serialVersionUID = -5174882230278923704L; @Override public void mouseClicked( MouseEvent e ) { int index = m_history.getList().locationToIndex( e.getPoint() ); if ( index != -1 ) { String name = m_history.getNameAtIndex( index ); // doPopup(name); Object data = m_history.getNamedObject( name ); if ( data instanceof Data ) { String grphString = ( (Data) data ).getPrimaryPayload(); Integer grphType = ( (Data) data ).getPayloadElement( StepManager.CON_AUX_DATA_GRAPH_TYPE ); if ( m_treeVisualizer != null || m_graphVisualizer != null ) { m_holderPanel.remove( m_treeVisualizer != null ? m_treeVisualizer : m_graphVisualizer ); } if ( grphType == Drawable.TREE ) { m_treeVisualizer = new TreeVisualizer( null, grphString, new PlaceNode2() ); m_holderPanel.add( m_treeVisualizer, BorderLayout.CENTER ); m_splitPane.revalidate(); } else if ( grphType == Drawable.BayesNet ) { m_graphVisualizer = new GraphVisualizer(); try { m_graphVisualizer.readBIF( grphString ); } catch ( BIFFormatException ex ) { ex.printStackTrace(); } m_graphVisualizer.layoutGraph(); m_holderPanel.add( m_graphVisualizer, BorderLayout.CENTER ); m_splitPane.revalidate(); } } } } } ); m_history.getList().getSelectionModel() .addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { ListSelectionModel lm = (ListSelectionModel) e.getSource(); for (int i = e.getFirstIndex(); i <= e.getLastIndex(); i++) { if (lm.isSelectedIndex(i)) { // m_AttSummaryPanel.setAttribute(i); if (i != -1) { String name = m_history.getNameAtIndex(i); Object data = m_history.getNamedObject(name); if (data != null && data instanceof Data) { String grphString = ((Data) data).getPrimaryPayload(); Integer grphType = ((Data) data) .getPayloadElement(StepManager.CON_AUX_DATA_GRAPH_TYPE); if (m_treeVisualizer != null || m_graphVisualizer != null) { m_holderPanel .remove(m_treeVisualizer != null ? m_treeVisualizer : m_graphVisualizer); } if (grphType == Drawable.TREE) { m_treeVisualizer = new TreeVisualizer(null, grphString, new PlaceNode2()); m_holderPanel.add(m_treeVisualizer, BorderLayout.CENTER); m_splitPane.revalidate(); } else if (grphType == Drawable.BayesNet) { m_graphVisualizer = new GraphVisualizer(); try { m_graphVisualizer.readBIF(grphString); } catch (BIFFormatException ex) { ex.printStackTrace(); } m_graphVisualizer.layoutGraph(); m_holderPanel.add(m_graphVisualizer, BorderLayout.CENTER); m_splitPane.revalidate(); } } } break; } } } } }); m_splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, m_history, m_holderPanel); // m_splitPane.setLeftComponent(m_history); add(m_splitPane, BorderLayout.CENTER); m_holderPanel.setPreferredSize(new Dimension(800, 600)); m_splitPane.setDividerLocation(200 + m_splitPane.getInsets().left); boolean first = true; for (Data d : ((GraphViewer) getStep()).getDatasets()) { String title = d.getPayloadElement(StepManager.CON_AUX_DATA_GRAPH_TITLE); m_history.addResult(title, new StringBuffer()); m_history.addObject(title, d); if (first) { String grphString = d.getPrimaryPayload(); Integer grphType = d.getPayloadElement(StepManager.CON_AUX_DATA_GRAPH_TYPE); if (grphType == Drawable.TREE) { m_treeVisualizer = new TreeVisualizer(null, grphString, new PlaceNode2()); // m_splitPane.setRightComponent(m_treeVisualizer); m_holderPanel.add(m_treeVisualizer, BorderLayout.CENTER); } else if (grphType == Drawable.BayesNet) { m_graphVisualizer = new GraphVisualizer(); try { m_graphVisualizer.readBIF(grphString); } catch (BIFFormatException ex) { ex.printStackTrace(); } m_graphVisualizer.layoutGraph(); m_holderPanel.add(m_graphVisualizer, BorderLayout.CENTER); } m_splitPane.revalidate(); first = false; } } m_clearButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m_history.clearResults(); ((GraphViewer) getStep()).getDatasets().clear(); if (m_treeVisualizer != null || m_graphVisualizer != null) { m_splitPane.remove(m_holderPanel); // invalidate(); revalidate(); } } }); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow/steps/ImageViewerInteractiveView.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /*` * ImageViewerInteractiveView.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.gui.knowledgeflow.steps; import weka.core.WekaException; import weka.gui.ResultHistoryPanel; import weka.gui.knowledgeflow.BaseInteractiveViewer; import weka.gui.knowledgeflow.StepVisual; import weka.knowledgeflow.steps.ImageViewer; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JToolBar; import javax.swing.ListSelectionModel; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import java.util.List; import java.util.Map; /** * Interactive viewer for the ImageViewer step * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class ImageViewerInteractiveView extends BaseInteractiveViewer { private static final long serialVersionUID = -6652203133445653870L; /** Button for clearing the results */ protected JButton m_clearButton = new JButton("Clear results"); /** A panel for holding a list of results */ protected ResultHistoryPanel m_history; /** Panel for displaying the image */ protected ImageDisplayer m_plotter; /** * Get the name of the viewer * * @return the name of the viewer */ @Override public String getViewerName() { return "Image Viewer"; } /** * Initialize the viewer and the layout * * @throws WekaException if a problem occurs */ @Override public void init() throws WekaException { addButton(m_clearButton); m_plotter = new ImageDisplayer(); m_plotter.setMinimumSize(new Dimension(810, 610)); m_plotter.setPreferredSize( new Dimension( 810, 610 ) ); m_history = new ResultHistoryPanel(null); m_history.setBorder(BorderFactory.createTitledBorder("Image list")); m_history.setHandleRightClicks( false ); m_history.setDeleteListener(new ResultHistoryPanel.RDeleteListener() { @Override public void entryDeleted(String name, int index) { ((ImageViewer)getStep()).getImages().remove(name); } @Override public void entriesDeleted(List<String> names, List<Integer> indexes) { for (String name : names) { ((ImageViewer) getStep()).getImages().remove(name); } } }); m_history.getList().addMouseListener( new ResultHistoryPanel.RMouseAdapter() { /** for serialization */ private static final long serialVersionUID = -4984130887963944249L; @Override public void mouseClicked( MouseEvent e ) { int index = m_history.getList().locationToIndex( e.getPoint() ); if ( index != -1 ) { String name = m_history.getNameAtIndex( index ); // doPopup(name); Object pic = m_history.getNamedObject( name ); if ( pic instanceof BufferedImage ) { m_plotter.setImage( (BufferedImage) pic ); m_plotter.repaint(); } } } } ); m_history.getList().getSelectionModel() .addListSelectionListener( new ListSelectionListener() { @Override public void valueChanged( ListSelectionEvent e ) { if ( !e.getValueIsAdjusting() ) { ListSelectionModel lm = (ListSelectionModel) e.getSource(); for ( int i = e.getFirstIndex(); i <= e.getLastIndex(); i++ ) { if ( lm.isSelectedIndex( i ) ) { // m_AttSummaryPanel.setAttribute(i); if ( i != -1 ) { String name = m_history.getNameAtIndex( i ); Object pic = m_history.getNamedObject( name ); if ( pic != null && pic instanceof BufferedImage ) { m_plotter.setImage( (BufferedImage) pic ); m_plotter.repaint(); } } break; } } } } } ); MainPanel mainPanel = new MainPanel(m_history, m_plotter); add(mainPanel, BorderLayout.CENTER); boolean first = true; for (Map.Entry<String, BufferedImage> e : ((ImageViewer) getStep()) .getImages().entrySet()) { m_history.addResult(e.getKey(), new StringBuffer()); m_history.addObject(e.getKey(), e.getValue()); if (first) { m_plotter.setImage(e.getValue()); m_plotter.repaint(); first = false; } } if (m_history.getList().getModel().getSize() > 0) { m_history.getList().setSelectedIndex(0); } m_clearButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m_history.clearResults(); ((ImageViewer) getStep()).getImages().clear(); m_plotter.setImage( null ); m_plotter.repaint(); } }); } /** * Small inner class for laying out the main parts of the popup display * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) */ protected static class MainPanel extends JPanel { private static Image loadImage(String path) { Image pic = null; java.net.URL imageURL = ImageViewer.class.getClassLoader().getResource(path); // end modifications if (imageURL == null) { } else { pic = Toolkit.getDefaultToolkit().getImage(imageURL); } return pic; } /** * For serialization */ private static final long serialVersionUID = 5648976848887609072L; /** * Constructor * * @param p a {@code ResultHistoryPanel} to add * @param id the {@code ImageDisplayer} to add */ public MainPanel(ResultHistoryPanel p, final ImageDisplayer id) { super(); setLayout(new BorderLayout()); JPanel topP = new JPanel(); topP.setLayout(new BorderLayout()); JPanel holder = new JPanel(); holder.setLayout(new BorderLayout()); holder.setBorder(BorderFactory.createTitledBorder("Image")); JToolBar tools = new JToolBar(); tools.setOrientation(JToolBar.HORIZONTAL); JButton zoomInB = new JButton(new ImageIcon(loadImage(StepVisual.BASE_ICON_PATH + "zoom_in.png"))); zoomInB.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int z = id.getZoom(); z += 25; if (z >= 200) { z = 200; } id.setZoom(z); id.repaint(); } }); JButton zoomOutB = new JButton(new ImageIcon(loadImage(StepVisual.BASE_ICON_PATH + "zoom_out.png"))); zoomOutB.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int z = id.getZoom(); z -= 25; if (z <= 50) { z = 50; } id.setZoom(z); id.repaint(); } }); tools.add(zoomInB); tools.add(zoomOutB); holder.add(tools, BorderLayout.NORTH); JScrollPane js = new JScrollPane(id); holder.add(js, BorderLayout.CENTER); JSplitPane p2 = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, p, holder); p2.setDividerLocation(200 + p2.getInsets().left); topP.add(p2, BorderLayout.CENTER); // topP.add(p, BorderLayout.WEST); add(topP, BorderLayout.CENTER); } } /** * Inner class for displaying a BufferedImage. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: 10883 $ */ protected static class ImageDisplayer extends JPanel { /** For serialization */ private static final long serialVersionUID = 4161957589912537357L; /** The image to display */ private BufferedImage m_image; private int m_imageZoom = 100; /** * Set the image to display * * @param image the image to display */ public void setImage(BufferedImage image) { m_image = image; } public void setZoom(int zoom) { m_imageZoom = zoom; } public int getZoom() { return m_imageZoom; } /** * Render the image * * @param g the graphics context */ @Override public void paintComponent(Graphics g) { super.paintComponent(g); if (m_image != null) { double lz = m_imageZoom / 100.0; ((Graphics2D) g).scale(lz, lz); int plotWidth = m_image.getWidth(); int plotHeight = m_image.getHeight(); int ourWidth = getWidth(); int ourHeight = getHeight(); // center if plot is smaller than us int x = 0, y = 0; if (plotWidth < ourWidth) { x = (ourWidth - plotWidth) / 2; } if (plotHeight < ourHeight) { y = (ourHeight - plotHeight) / 2; } g.drawImage(m_image, x, y, this); setPreferredSize(new Dimension(plotWidth, plotHeight)); revalidate(); } } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow/steps/JobStepEditorDialog.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * JobStepEditorDialog.java * Copyright (C) 2016 University of Waikato, Hamilton, New Zealand * */ package weka.gui.knowledgeflow.steps; import weka.gui.knowledgeflow.GOEStepEditorDialog; import weka.knowledgeflow.Flow; import weka.knowledgeflow.JSONFlowLoader; import weka.knowledgeflow.steps.Job; import javax.swing.JButton; import javax.swing.JPanel; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; /** * Editor dialog for the Job step. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class JobStepEditorDialog extends GOEStepEditorDialog { private static final long serialVersionUID = -4921559717867446684L; /** Button for loading the sub-flow in a new tab */ protected JButton m_editSubFlow = new JButton("Edit sub-flow..."); /** * Layout the custom part of the editor */ @Override public void layoutEditor() { JPanel butHolder = new JPanel(new FlowLayout(FlowLayout.LEFT)); butHolder.add(m_editSubFlow); m_editSubFlow.setEnabled(false); m_editorHolder.add(butHolder, BorderLayout.CENTER); m_editSubFlow.setEnabled(true); m_editSubFlow.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { Flow toEdit = loadFlow(((Job) getStepToEdit()).getFlowFile().toString()); getMainPerspective().addTab(toEdit.getFlowName()); getMainPerspective().getCurrentLayout().setFlow(toEdit); if (m_parent != null) { m_parent.dispose(); } if (m_closingListener != null) { m_closingListener.closing(); } } catch (Exception ex) { showErrorDialog(ex); } } }); } protected Flow loadFlow(String toLoad) throws Exception { Flow result = null; toLoad = environmentSubstitute(toLoad); if (new File(toLoad).exists()) { result = Flow.loadFlow(new File(toLoad), null); } else { String fileNameWithCorrectSeparators = toLoad.replace(File.separatorChar, '/'); if (this.getClass().getClassLoader() .getResource(fileNameWithCorrectSeparators) != null) { result = Flow.loadFlow( this.getClass().getClassLoader() .getResourceAsStream(fileNameWithCorrectSeparators), new JSONFlowLoader()); } } return result; } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow/steps/JoinStepEditorDialog.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * JoinStepEditorDialog.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.gui.knowledgeflow.steps; import weka.core.Instances; import weka.core.WekaException; import weka.gui.EnvironmentField; import weka.gui.JListHelper; import weka.gui.knowledgeflow.StepEditorDialog; import weka.knowledgeflow.steps.Join; import javax.swing.*; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.List; /** * Step editor dialog for the Join step * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class JoinStepEditorDialog extends StepEditorDialog { private static final long serialVersionUID = -2648770811063889717L; /** Combo box for selecting a key field to add from the first instance stream */ protected JComboBox m_firstKeyFields = new EnvironmentField.WideComboBox(); /** Combo box for selecting a the key field to add from the second instance stream */ protected JComboBox m_secondKeyFields = new EnvironmentField.WideComboBox(); /** List of selected key fields for the first instance stream */ protected JList m_firstList = new JList(); /** List of selected key fields for the second instance stream */ protected JList m_secondList = new JList(); protected DefaultListModel<String> m_firstListModel; protected DefaultListModel<String> m_secondListModel; /** Add button for the first instance stream */ protected JButton m_addOneBut = new JButton("Add"); /** Delete button for the first instance stream */ protected JButton m_deleteOneBut = new JButton("Delete"); /** Move up button for the first instance stream */ protected JButton m_upOneBut = new JButton("Up"); /** Move down button for the first instance stream */ protected JButton m_downOneBut = new JButton("Down"); /** Add button for the second instance stream */ protected JButton m_addTwoBut = new JButton("Add"); /** Delete button for the second instance stream */ protected JButton m_deleteTwoBut = new JButton("Delete"); /** Move up button for the second instance stream */ protected JButton m_upTwoBut = new JButton("Up"); /** Move down button for the second instance stream */ protected JButton m_downTwoBut = new JButton("Down"); /** * Initialize the step editor dialog */ @SuppressWarnings("unchecked") protected void initialize() { m_firstListModel = new DefaultListModel<String>(); m_secondListModel = new DefaultListModel<String>(); m_firstList.setModel(m_firstListModel); m_secondList.setModel(m_secondListModel); String keySpec = ((Join) getStepToEdit()).getKeySpec(); if (keySpec != null && keySpec.length() > 0) { keySpec = environmentSubstitute(keySpec); String[] parts = keySpec.split(Join.KEY_SPEC_SEPARATOR); if (parts.length > 0) { String[] firstParts = parts[0].trim().split(","); for (String s : firstParts) { m_firstListModel.addElement(s); } } if (parts.length > 1) { String[] secondParts = parts[1].trim().split(","); for (String s : secondParts) { m_secondListModel.addElement(s); } } } } /** * Layout the editor */ @Override @SuppressWarnings("unchecked") protected void layoutEditor() { initialize(); JPanel controlHolder = new JPanel(); controlHolder.setLayout(new BorderLayout()); // input source names List<String> connected = ((Join) getStepToEdit()).getConnectedInputNames(); String firstName = connected.get(0) == null ? "<not connected>" : connected.get(0); String secondName = connected.get(1) == null ? "<not connected>" : connected.get(1); JPanel firstSourceP = new JPanel(); firstSourceP.setLayout(new BorderLayout()); firstSourceP.add(new JLabel("First input ", SwingConstants.RIGHT), BorderLayout.CENTER); firstSourceP.add(new JLabel(firstName, SwingConstants.LEFT), BorderLayout.EAST); JPanel secondSourceP = new JPanel(); secondSourceP.setLayout(new BorderLayout()); secondSourceP.add(new JLabel("Second input ", SwingConstants.RIGHT), BorderLayout.CENTER); secondSourceP.add(new JLabel(secondName, SwingConstants.LEFT), BorderLayout.EAST); JPanel sourcePHolder = new JPanel(); sourcePHolder.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5)); sourcePHolder.setLayout(new BorderLayout()); sourcePHolder.add(firstSourceP, BorderLayout.NORTH); sourcePHolder.add(secondSourceP, BorderLayout.SOUTH); controlHolder.add(sourcePHolder, BorderLayout.NORTH); m_firstList.setVisibleRowCount(5); m_secondList.setVisibleRowCount(5); m_firstKeyFields.setEditable(true); JPanel listOneP = new JPanel(); m_deleteOneBut.setEnabled(false); listOneP.setLayout(new BorderLayout()); JPanel butOneHolder = new JPanel(); butOneHolder.setLayout(new GridLayout(1, 0)); butOneHolder.add(m_addOneBut); butOneHolder.add(m_deleteOneBut); butOneHolder.add(m_upOneBut); butOneHolder.add(m_downOneBut); m_upOneBut.setEnabled(false); m_downOneBut.setEnabled(false); JPanel fieldsAndButsOne = new JPanel(); fieldsAndButsOne.setLayout(new BorderLayout()); fieldsAndButsOne.add(m_firstKeyFields, BorderLayout.NORTH); fieldsAndButsOne.add(butOneHolder, BorderLayout.SOUTH); listOneP.add(fieldsAndButsOne, BorderLayout.NORTH); JScrollPane js1 = new JScrollPane(m_firstList); js1.setBorder(BorderFactory.createTitledBorder("First input key fields")); listOneP.add(js1, BorderLayout.CENTER); controlHolder.add(listOneP, BorderLayout.WEST); m_secondKeyFields.setEditable(true); JPanel listTwoP = new JPanel(); m_deleteTwoBut.setEnabled(false); listTwoP.setLayout(new BorderLayout()); JPanel butTwoHolder = new JPanel(); butTwoHolder.setLayout(new GridLayout(1, 0)); butTwoHolder.add(m_addTwoBut); butTwoHolder.add(m_deleteTwoBut); butTwoHolder.add(m_upTwoBut); butTwoHolder.add(m_downTwoBut); m_upTwoBut.setEnabled(false); m_downTwoBut.setEnabled(false); JPanel fieldsAndButsTwo = new JPanel(); fieldsAndButsTwo.setLayout(new BorderLayout()); fieldsAndButsTwo.add(m_secondKeyFields, BorderLayout.NORTH); fieldsAndButsTwo.add(butTwoHolder, BorderLayout.SOUTH); listTwoP.add(fieldsAndButsTwo, BorderLayout.NORTH); JScrollPane js2 = new JScrollPane(m_secondList); js2.setBorder(BorderFactory.createTitledBorder("Second input key fields")); listTwoP.add(js2, BorderLayout.CENTER); controlHolder.add(listTwoP, BorderLayout.EAST); add(controlHolder, BorderLayout.CENTER); // setup incoming atts combos try { if (((Join) getStepToEdit()).getFirstInputStructure() != null) { m_firstKeyFields.removeAllItems(); Instances incoming = ((Join) getStepToEdit()).getFirstInputStructure(); for (int i = 0; i < incoming.numAttributes(); i++) { m_firstKeyFields.addItem(incoming.attribute(i).name()); } } if (((Join) getStepToEdit()).getSecondInputStructure() != null) { m_secondKeyFields.removeAllItems(); Instances incoming = ((Join) getStepToEdit()).getSecondInputStructure(); for (int i = 0; i < incoming.numAttributes(); i++) { m_secondKeyFields.addItem(incoming.attribute(i).name()); } } } catch (WekaException ex) { showErrorDialog(ex); } m_firstList.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { if (!m_deleteOneBut.isEnabled()) { m_deleteOneBut.setEnabled(true); } } } }); m_secondList.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { if (!m_deleteTwoBut.isEnabled()) { m_deleteTwoBut.setEnabled(true); } } } }); m_addOneBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (m_firstKeyFields.getSelectedItem() != null && m_firstKeyFields.getSelectedItem().toString().length() > 0) { m_firstListModel.addElement(m_firstKeyFields.getSelectedItem() .toString()); if (m_firstListModel.size() > 1) { m_upOneBut.setEnabled(true); m_downOneBut.setEnabled(true); } } } }); m_addTwoBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (m_secondKeyFields.getSelectedItem() != null && m_secondKeyFields.getSelectedItem().toString().length() > 0) { m_secondListModel.addElement(m_secondKeyFields.getSelectedItem() .toString()); if (m_secondListModel.size() > 1) { m_upTwoBut.setEnabled(true); m_downTwoBut.setEnabled(true); } } } }); m_deleteOneBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int selected = m_firstList.getSelectedIndex(); if (selected >= 0) { m_firstListModel.remove(selected); } if (m_firstListModel.size() <= 1) { m_upOneBut.setEnabled(false); m_downOneBut.setEnabled(false); } } }); m_deleteTwoBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int selected = m_secondList.getSelectedIndex(); if (selected >= 0) { m_secondListModel.remove(selected); } if (m_secondListModel.size() <= 1) { m_upTwoBut.setEnabled(false); m_downTwoBut.setEnabled(false); } } }); m_upOneBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JListHelper.moveUp(m_firstList); ; } }); m_upTwoBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JListHelper.moveUp(m_secondList); } }); m_downOneBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JListHelper.moveDown(m_firstList); } }); m_downTwoBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JListHelper.moveDown(m_secondList); ; } }); } /** * Called when the OK button is pressed */ @Override public void okPressed() { StringBuilder b = new StringBuilder(); for (int i = 0; i < m_firstListModel.size(); i++) { if (i != 0) { b.append(","); } b.append(m_firstListModel.get(i)); } b.append(Join.KEY_SPEC_SEPARATOR); for (int i = 0; i < m_secondListModel.size(); i++) { if (i != 0) { b.append(","); } b.append(m_secondListModel.get(i)); } ((Join) getStepToEdit()).setKeySpec(b.toString()); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow/steps/LoaderStepEditorDialog.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * LoaderStepEditorDialog.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.gui.knowledgeflow.steps; import weka.core.converters.FileSourcedConverter; import weka.gui.ExtensionFileFilter; import weka.gui.FileEnvironmentField; import weka.gui.knowledgeflow.GOEStepEditorDialog; import weka.knowledgeflow.steps.Loader; import weka.knowledgeflow.steps.Step; import javax.swing.JFileChooser; import javax.swing.JPanel; import java.awt.BorderLayout; import java.io.File; import java.io.IOException; /** * Provides a custom editor dialog for Loaders. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class LoaderStepEditorDialog extends GOEStepEditorDialog { private static final long serialVersionUID = -6501371943783384741L; /** Widget for specifying/choosing a file for file-based loaders */ protected FileEnvironmentField m_fileLoader; /** * Constructor */ public LoaderStepEditorDialog() { super(); } /** * Set the step to edit in this editor * * @param step the step to edit */ @Override public void setStepToEdit(Step step) { copyOriginal(step); Loader wrappedStep = (Loader) step; if (wrappedStep.getLoader() instanceof FileSourcedConverter) { setupFileLoader(wrappedStep); } else /* if (wrappedStep.getLoader() instanceof DatabaseConverter) */{ super.setStepToEdit(step); } } /** * Sets up the editor for dealing with file-based loaders * * @param wrappedStep the {@code weka.core.converters.Loader} wrapped by the * loader step */ protected void setupFileLoader(Loader wrappedStep) { addPrimaryEditorPanel(BorderLayout.NORTH); m_fileLoader = new FileEnvironmentField("Filename", JFileChooser.OPEN_DIALOG, false); m_fileLoader.setEnvironment(m_env); m_fileLoader.resetFileFilters(); FileSourcedConverter loader = ((FileSourcedConverter) ((Loader) getStepToEdit()).getLoader()); String[] ext = loader.getFileExtensions(); ExtensionFileFilter firstFilter = null; for (int i = 0; i < ext.length; i++) { ExtensionFileFilter ff = new ExtensionFileFilter(ext[i], loader.getFileDescription() + " (*" + ext[i] + ")"); if (i == 0) { firstFilter = ff; } m_fileLoader.addFileFilter(ff); } if (firstFilter != null) { m_fileLoader.setFileFilter(firstFilter); } JPanel p = new JPanel(); p.setLayout(new BorderLayout()); p.add(m_fileLoader, BorderLayout.NORTH); m_primaryEditorHolder.add(p, BorderLayout.CENTER); add(m_editorHolder, BorderLayout.CENTER); File currentFile = ((FileSourcedConverter) wrappedStep.getLoader()).retrieveFile(); m_fileLoader.setValue(currentFile); } /** * Called when the OK button is pressed */ @Override protected void okPressed() { if (((Loader) m_stepToEdit).getLoader() instanceof FileSourcedConverter) { try { ((FileSourcedConverter) ((Loader) m_stepToEdit).getLoader()) .setFile((File) m_fileLoader.getValue()); } catch (IOException e) { e.printStackTrace(); } } super.okPressed(); // just in case the loader has a customizer } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow/steps/ModelPerformanceChartInteractiveView.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /*` * ModelPerformanceChartInteractiveView.java * Copyright (C) 2002-2015 University of Waikato, Hamilton, New Zealand * */ package weka.gui.knowledgeflow.steps; import weka.core.Defaults; import weka.core.Settings; import weka.core.WekaException; import weka.gui.knowledgeflow.BaseInteractiveViewer; import weka.gui.visualize.PlotData2D; import weka.gui.visualize.VisualizePanel; import weka.gui.visualize.VisualizeUtils; import weka.knowledgeflow.steps.ModelPerformanceChart; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.List; /** * Interactive viewer for the ModelPerformanceChart step * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class ModelPerformanceChartInteractiveView extends BaseInteractiveViewer { private static final long serialVersionUID = 8818417648798221980L; /** Button for clearing results */ protected JButton m_clearButton = new JButton("Clear results"); /** The actual visualization */ protected VisualizePanel m_visPanel = new VisualizePanel(); /** ID used for identifying settings */ protected static final String ID = "weka.gui.knowledgeflow.steps.ModelPerformanceChartInteractiveView"; /** * Get the name of this viewer * * @return the name of this viewer */ @Override public String getViewerName() { return "Model Performance Chart"; } /** * Initialize and layout the viewer * * @throws WekaException if a problem occurs */ @Override public void init() throws WekaException { addButton(m_clearButton); add(m_visPanel, BorderLayout.CENTER); m_clearButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m_visPanel.removeAllPlots(); m_visPanel.validate(); m_visPanel.repaint(); // clear all plot data/offscreen plot data ((ModelPerformanceChart) getStep()).clearPlotData(); } }); List<PlotData2D> plotData = ((ModelPerformanceChart) getStep()).getPlots(); try { m_visPanel.setMasterPlot(plotData.get(0)); for (int i = 1; i < plotData.size(); i++) { m_visPanel.addPlot(plotData.get(i)); } if (((ModelPerformanceChart) getStep()).isDataIsThresholdData()) { m_visPanel.setXIndex(4); m_visPanel.setYIndex(5); } } catch (Exception ex) { throw new WekaException(ex); } m_visPanel.setPreferredSize(new Dimension(800, 600)); applySettings(getSettings()); } /** * Get default settings for this viewer * * @return the default settings of this viewer */ @Override public Defaults getDefaultSettings() { Defaults d = new VisualizeUtils.VisualizeDefaults(); d.setID(ID); return d; } /** * Apply any user changes in the supplied settings object * * @param settings the settings object that might (or might not) have been * altered by the user */ @Override public void applySettings(Settings settings) { m_visPanel.applySettings(settings, ID); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow/steps/ModelPerformanceChartStepEditorDialog.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ModelPerformanceChartStepEditorDialog.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.gui.knowledgeflow.steps; import weka.core.PluginManager; import weka.gui.EnvironmentField; import weka.gui.PropertySheetPanel; import weka.gui.beans.OffscreenChartRenderer; import weka.gui.beans.WekaOffscreenChartRenderer; import weka.gui.knowledgeflow.GOEStepEditorDialog; import weka.knowledgeflow.steps.ModelPerformanceChart; import weka.knowledgeflow.steps.Step; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Set; /** * Step editor dialog for the ModelPerformanceChart step * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class ModelPerformanceChartStepEditorDialog extends GOEStepEditorDialog { private static final long serialVersionUID = -3031265139980301695L; /** For editing the renderer options */ protected EnvironmentField m_rendererOptions = new EnvironmentField(); /** For selecting the renderer to use */ protected JComboBox<String> m_offscreenSelector = new JComboBox<String>(); /** Currently selected renderer name */ protected String m_currentRendererName; /** Current renderer options */ protected String m_currentRendererOptions; /** * Set the step to edit. Also constructs the layout of the editor based on the * step's settings * * @param step the step to edit in this editor */ @Override protected void setStepToEdit(Step step) { copyOriginal(step); createAboutPanel(step); m_editor = new PropertySheetPanel(false); m_editor.setUseEnvironmentPropertyEditors(true); m_editor.setEnvironment(m_env); m_editor.setTarget(m_stepToEdit); m_primaryEditorHolder.setLayout(new BorderLayout()); m_primaryEditorHolder.add(m_editor, BorderLayout.CENTER); GridBagLayout gbLayout = new GridBagLayout(); JPanel p = new JPanel(gbLayout); GridBagConstraints gbc = new GridBagConstraints(); gbc.anchor = GridBagConstraints.EAST; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.gridy = 0; gbc.gridx = 0; gbc.insets = new Insets(0, 5, 0, 5); JLabel renderLabel = new JLabel("Renderer", SwingConstants.RIGHT); gbLayout.setConstraints(renderLabel, gbc); p.add(renderLabel); JPanel newPanel = new JPanel(new BorderLayout()); gbc = new GridBagConstraints(); gbc.anchor = GridBagConstraints.WEST; gbc.fill = GridBagConstraints.BOTH; gbc.gridy = 0; gbc.gridx = 1; gbc.weightx = 100; newPanel.setBorder(BorderFactory.createEmptyBorder(10, 5, 0, 10)); newPanel.add(m_offscreenSelector, BorderLayout.CENTER); gbLayout.setConstraints(newPanel, gbc); p.add(newPanel); gbc = new GridBagConstraints(); gbc.anchor = GridBagConstraints.EAST; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.gridy = 1; gbc.gridx = 0; gbc.insets = new Insets(0, 5, 0, 5); final JLabel rendererOptsLabel = new JLabel("Renderer options", SwingConstants.RIGHT); gbLayout.setConstraints(rendererOptsLabel, gbc); p.add(rendererOptsLabel); newPanel = new JPanel(new BorderLayout()); gbc = new GridBagConstraints(); gbc.anchor = GridBagConstraints.WEST; gbc.fill = GridBagConstraints.BOTH; gbc.gridy = 1; gbc.gridx = 1; gbc.weightx = 100; newPanel.setBorder(BorderFactory.createEmptyBorder(10, 5, 0, 10)); newPanel.add(m_rendererOptions, BorderLayout.CENTER); gbLayout.setConstraints(newPanel, gbc); p.add(newPanel); m_primaryEditorHolder.add(p, BorderLayout.NORTH); m_editorHolder.add(m_primaryEditorHolder, BorderLayout.NORTH); add(m_editorHolder, BorderLayout.CENTER); m_offscreenSelector.addItem("Weka Chart Renderer"); Set<String> pluginRenderers = PluginManager .getPluginNamesOfType("weka.gui.beans.OffscreenChartRenderer"); if (pluginRenderers != null) { for (String plugin : pluginRenderers) { m_offscreenSelector.addItem(plugin); } } m_offscreenSelector.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { setupRendererOptsTipText(rendererOptsLabel); } }); getCurrentSettings(); m_offscreenSelector.setSelectedItem(m_currentRendererName); m_rendererOptions.setText(m_currentRendererOptions); setupRendererOptsTipText(rendererOptsLabel); } /** * Get the name of the offscreen renderer and any options for it from the step * being edited. */ protected void getCurrentSettings() { m_currentRendererName = ((ModelPerformanceChart) getStepToEdit()).getOffscreenRendererName(); m_currentRendererOptions = ((ModelPerformanceChart) getStepToEdit()).getOffscreenAdditionalOpts(); } private void setupRendererOptsTipText(JLabel optsLab) { String renderer = m_offscreenSelector.getSelectedItem().toString(); if (renderer.equalsIgnoreCase("weka chart renderer")) { // built-in renderer WekaOffscreenChartRenderer rcr = new WekaOffscreenChartRenderer(); String tipText = rcr.optionsTipTextHTML(); tipText = tipText.replace("<html>", "<html>Comma separated list of options:<br>"); optsLab.setToolTipText(tipText); } else { try { Object rendererO = PluginManager.getPluginInstance( "weka.gui.beans.OffscreenChartRenderer", renderer); if (rendererO != null) { String tipText = ((OffscreenChartRenderer) rendererO).optionsTipTextHTML(); if (tipText != null && tipText.length() > 0) { optsLab.setToolTipText(tipText); } } } catch (Exception ex) { showErrorDialog(ex); } } } /** * Stuff to do when the user accepts the current settings */ @Override protected void okPressed() { ((ModelPerformanceChart) getStepToEdit()) .setOffscreenRendererName(m_offscreenSelector.getSelectedItem() .toString()); ((ModelPerformanceChart) getStepToEdit()) .setOffscreenAdditionalOpts(m_rendererOptions.getText()); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow/steps/NoteEditorDialog.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * NoteEditorDialog.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.gui.knowledgeflow.steps; import weka.gui.knowledgeflow.StepEditorDialog; import weka.knowledgeflow.steps.Note; import weka.knowledgeflow.steps.Step; import javax.swing.*; import java.awt.*; /** * Editor dialog for Notes * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class NoteEditorDialog extends StepEditorDialog { private static final long serialVersionUID = 2358735294813135692L; /** Text area of the note */ protected JTextArea m_textArea = new JTextArea(5, 40); /** * Set the step (note) being edited * * @param step the step to edit */ @Override protected void setStepToEdit(Step step) { // override to prevent an "about" panel getting added m_stepToEdit = step; layoutEditor(); } /** * Layout the note editor */ @Override public void layoutEditor() { m_textArea.setLineWrap(true); String noteText = ((Note) getStepToEdit()).getNoteText(); m_textArea.setText(noteText); JScrollPane sc = new JScrollPane(m_textArea); JPanel holder = new JPanel(new BorderLayout()); holder.setBorder(BorderFactory.createTitledBorder("Note Editor")); holder.add(sc, BorderLayout.CENTER); add(holder, BorderLayout.CENTER); } /** * Called when the OK button is pressed */ @Override public void okPressed() { ((Note) getStepToEdit()).setNoteText(m_textArea.getText()); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow/steps/SaverStepEditorDialog.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * SaverStepEditorDialog.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.gui.knowledgeflow.steps; import weka.core.converters.FileSourcedConverter; import weka.gui.EnvironmentField; import weka.gui.FileEnvironmentField; import weka.gui.PropertySheetPanel; import weka.gui.knowledgeflow.GOEStepEditorDialog; import weka.knowledgeflow.steps.Saver; import weka.knowledgeflow.steps.Step; import javax.swing.*; import java.awt.*; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; /** * Editor dialog for the saver step * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class SaverStepEditorDialog extends GOEStepEditorDialog { private static final long serialVersionUID = -8353826767500440827L; /** * Field for specifying either the file prefix to use or the actual filename * itself */ protected EnvironmentField m_prefixOrFile; /** Field for specifying the directory to save into */ protected FileEnvironmentField m_directory; /** Label for the directory field */ protected JLabel m_dirLab = new JLabel("Directory ", SwingConstants.RIGHT); /** Label for the file/prefix field */ protected JLabel m_prefLab = new JLabel("Prefix ", SwingConstants.RIGHT); /** * Constructor */ public SaverStepEditorDialog() { super(); } /** * Set the step to edit * * @param step the step to edit */ public void setStepToEdit(Step step) { copyOriginal(step); Saver wrappedStep = (Saver) step; if (wrappedStep.getSaver() instanceof FileSourcedConverter) { setupFileSaver(wrappedStep); } else { super.setStepToEdit(step); } } /** * Setup for editing file-based savers * * @param wrappedStep the step to edit */ protected void setupFileSaver(final Saver wrappedStep) { addPrimaryEditorPanel(BorderLayout.NORTH); m_prefixOrFile = new EnvironmentField(); m_prefixOrFile.setEnvironment(m_env); m_directory = new FileEnvironmentField("", JFileChooser.SAVE_DIALOG, true); m_directory.setEnvironment(m_env); JPanel p = new JPanel(); p.setLayout(new BorderLayout()); m_secondaryEditor = new PropertySheetPanel(false); m_secondaryEditor.setEnvironment(m_env); m_secondaryEditor.setTarget(m_stepToEdit); p.add(m_secondaryEditor, BorderLayout.NORTH); JPanel tp = new JPanel(); tp.setLayout(new BorderLayout()); JPanel dp = new JPanel(); dp.setLayout(new GridLayout(0, 1)); dp.add(m_dirLab); dp.add(m_prefLab); JPanel dp2 = new JPanel(); dp2.setLayout(new GridLayout(0, 1)); dp2.add(m_directory); dp2.add(m_prefixOrFile); tp.add(dp, BorderLayout.WEST); tp.add(dp2, BorderLayout.CENTER); p.add(tp, BorderLayout.CENTER); m_primaryEditorHolder.add(p, BorderLayout.CENTER); add(m_editorHolder, BorderLayout.CENTER); if (!wrappedStep.getRelationNameForFilename()) { m_prefLab.setText("Filename"); } try { String dir = wrappedStep.getSaver().retrieveDir(); String prefixOrFile = wrappedStep.getSaver().filePrefix(); m_directory.setText(dir); m_prefixOrFile.setText(prefixOrFile); } catch (Exception e) { e.printStackTrace(); } m_secondaryEditor.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { if (wrappedStep.getRelationNameForFilename()) { if (m_prefLab.getText().startsWith("File")) { m_prefLab.setText("Prefix "); } } else { if (m_prefLab.getText().startsWith("Prefix")) { m_prefLab.setText("Filename "); } } } }); } /** * Setup for other types of savers */ protected void setupOther() { addPrimaryEditorPanel(BorderLayout.NORTH); addSecondaryEditorPanel(BorderLayout.CENTER); add(m_editorHolder, BorderLayout.CENTER); } /** * Called when the OK button is pressed */ @Override protected void okPressed() { if (((Saver) m_stepToEdit).getSaver() instanceof FileSourcedConverter) { try { ((Saver) m_stepToEdit).getSaver().setDir(m_directory.getText()); ((Saver) m_stepToEdit).getSaver().setFilePrefix( m_prefixOrFile.getText()); } catch (Exception e) { e.printStackTrace(); } } super.okPressed(); // just in case saver has a customizer } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow/steps/ScatterPlotMatrixInteractiveView.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /*` * ScatterPlotMatrixInteractiveView.java * Copyright (C) 2002-2015 University of Waikato, Hamilton, New Zealand * */ package weka.gui.knowledgeflow.steps; import weka.core.Defaults; import weka.core.Environment; import weka.core.Instances; import weka.core.Settings; import weka.core.WekaException; import weka.gui.ResultHistoryPanel; import weka.gui.explorer.VisualizePanel; import weka.gui.knowledgeflow.BaseInteractiveViewer; import weka.gui.knowledgeflow.ScatterPlotMatrixPerspective; import weka.gui.visualize.MatrixPanel; import weka.knowledgeflow.Data; import weka.knowledgeflow.StepManager; import weka.knowledgeflow.steps.ScatterPlotMatrix; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JSplitPane; import javax.swing.ListSelectionModel; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.List; /** * Interactive viewer for the ScatterPlotMatrix step * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class ScatterPlotMatrixInteractiveView extends BaseInteractiveViewer { private static final long serialVersionUID = 275603100387301133L; /** Holds a list of results */ protected ResultHistoryPanel m_history; /** The actual visualization */ protected MatrixPanel m_matrixPanel = new MatrixPanel(); /** Button for clearing the results list */ protected JButton m_clearButton = new JButton("Clear results"); /** Split pane for separating the result list and visualization */ protected JSplitPane m_splitPane; /** * Get the name of the viewer * * @return the name of the viewer */ @Override public String getViewerName() { return "Scatter Plot Matrix"; } /** * Initialize the viewer * * @throws WekaException if a problem occurs */ @Override public void init() throws WekaException { addButton(m_clearButton); m_history = new ResultHistoryPanel(null); m_history.setBorder(BorderFactory.createTitledBorder("Result list")); m_history.setHandleRightClicks(false); m_history.setDeleteListener(new ResultHistoryPanel.RDeleteListener() { @Override public void entryDeleted(String name, int index) { ((ScatterPlotMatrix) getStep()).getDatasets().remove(index); } @Override public void entriesDeleted(List<String> names, List<Integer> indexes) { List<Data> ds = ((ScatterPlotMatrix) getStep()).getDatasets(); List<Data> toRemove = new ArrayList<Data>(); for (int i : indexes) { toRemove.add(ds.get(i)); } ds.removeAll(toRemove); } }); m_history.getList().addMouseListener( new ResultHistoryPanel.RMouseAdapter() { private static final long serialVersionUID = -5174882230278923704L; @Override public void mouseClicked(MouseEvent e) { int index = m_history.getList().locationToIndex(e.getPoint()); if (index != -1) { String name = m_history.getNameAtIndex(index); // doPopup(name); Object insts = m_history.getNamedObject(name); if (insts instanceof Instances) { try { m_matrixPanel.setInstances((Instances) insts); m_matrixPanel.repaint(); } catch (Exception ex) { ex.printStackTrace(); } } } } }); m_history.getList().getSelectionModel() .addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { ListSelectionModel lm = (ListSelectionModel) e.getSource(); for (int i = e.getFirstIndex(); i <= e.getLastIndex(); i++) { if (lm.isSelectedIndex(i)) { // m_AttSummaryPanel.setAttribute(i); if (i != -1) { String name = m_history.getNameAtIndex(i); Object insts = m_history.getNamedObject(name); if (insts != null && insts instanceof Instances) { try { m_matrixPanel.setInstances((Instances) insts); m_matrixPanel.repaint(); } catch (Exception ex) { ex.printStackTrace(); } } } break; } } } } }); // JScrollPane scatterScroller = new JScrollPane( m_matrixPanel ); m_matrixPanel.setPreferredSize(new Dimension(800, 600)); m_history.setMinimumSize(new Dimension(150, 600)); m_splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, m_history, m_matrixPanel); add(m_splitPane, BorderLayout.CENTER); boolean first = true; for (Data d : ((ScatterPlotMatrix) getStep()).getDatasets()) { String title = d.getPayloadElement(StepManager.CON_AUX_DATA_TEXT_TITLE).toString(); m_history.addResult(title, new StringBuffer()); Instances instances = d.getPrimaryPayload(); m_history.addObject(title, instances); if (first) { m_matrixPanel.setInstances(instances); m_matrixPanel.repaint(); first = false; } } m_clearButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m_history.clearResults(); ((ScatterPlotMatrix) getStep()).getDatasets().clear(); m_splitPane.remove(m_matrixPanel); } }); applySettings(getSettings()); } /** * Apply any changes to the settings * * @param settings the settings object that might (or might not) have been */ @Override public void applySettings(Settings settings) { int pointSize = settings.getSetting(VisualizePanel.ScatterDefaults.ID, VisualizePanel.ScatterDefaults.POINT_SIZE_KEY, VisualizePanel.ScatterDefaults.POINT_SIZE, Environment.getSystemWide()); int plotSize = settings.getSetting(VisualizePanel.ScatterDefaults.ID, VisualizePanel.ScatterDefaults.PLOT_SIZE_KEY, VisualizePanel.ScatterDefaults.PLOT_SIZE, Environment.getSystemWide()); m_matrixPanel.setPointSize(pointSize); m_matrixPanel.setPlotSize(plotSize); m_matrixPanel.updatePanel(); } /** * Get the default settings of this viewer * * @return the default settings */ @Override public Defaults getDefaultSettings() { return new ScatterPlotMatrixPerspective().getDefaultSettings(); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow/steps/SendToPerspectiveStepEditorDialog.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * SendToPerspectiveStepEditorDialog.java * Copyright (C) 2016 University of Waikato, Hamilton, New Zealand * */ package weka.gui.knowledgeflow.steps; import weka.core.WekaException; import weka.gui.knowledgeflow.GOEStepEditorDialog; import weka.gui.knowledgeflow.GetPerspectiveNamesGraphicalCommand; import weka.knowledgeflow.steps.SendToPerspective; import weka.knowledgeflow.steps.Step; import javax.swing.BorderFactory; import javax.swing.JComboBox; import javax.swing.JPanel; import java.awt.BorderLayout; import java.util.List; /** * Dialog for the SendToPerspective step * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class SendToPerspectiveStepEditorDialog extends GOEStepEditorDialog { private static final long serialVersionUID = -8282588308511754826L; /** Combo box for selecting the perspective to send to */ protected JComboBox<String> m_perspectivesCombo = new JComboBox<>(); /** * Sets the step to edit and configures the dialog * * @param step the step to edit */ @Override public void setStepToEdit(Step step) { copyOriginal(step); try { List<String> visiblePerspectives = getGraphicalEnvironmentCommandHandler().performCommand( GetPerspectiveNamesGraphicalCommand.GET_PERSPECTIVE_NAMES_KEY); for (String s : visiblePerspectives) { m_perspectivesCombo.addItem(s); } } catch (WekaException ex) { showErrorDialog(ex); } String current = ((SendToPerspective) getStepToEdit()).getPerspectiveName(); m_perspectivesCombo.setSelectedItem(current); JPanel p = new JPanel(new BorderLayout()); p.setBorder(BorderFactory .createTitledBorder("Choose perspective to send to")); p.add(m_perspectivesCombo, BorderLayout.NORTH); createAboutPanel(step); add(p, BorderLayout.CENTER); } /** * Handle the OK button */ @Override public void okPressed() { String selectedPerspective = m_perspectivesCombo.getSelectedItem().toString(); ((SendToPerspective) getStepToEdit()) .setPerspectiveName(selectedPerspective); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow/steps/SetVariablesStepEditorDialog.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * SetVariablesStepEditorDialog.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.gui.knowledgeflow.steps; import weka.gui.InteractiveTableModel; import weka.gui.InteractiveTablePanel; import weka.gui.knowledgeflow.StepEditorDialog; import weka.knowledgeflow.steps.SetVariables; import javax.swing.BorderFactory; import javax.swing.JPanel; import javax.swing.JTabbedPane; import javax.swing.JTable; import java.awt.BorderLayout; import java.util.List; import java.util.Map; /** * Editor dialog for the {@code SetVariables} step * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class SetVariablesStepEditorDialog extends StepEditorDialog { private static final long serialVersionUID = 5747505623497131129L; /** panel for editing variables */ protected VariablesPanel m_vp; protected DynamicVariablesPanel m_dvp; @Override protected void layoutEditor() { String internalRep = ((SetVariables) getStepToEdit()).getVarsInternalRep(); String dynamicInternalRep = ((SetVariables) getStepToEdit()).getDynamicVarsInternalRep(); Map<String, String> vars = SetVariables.internalToMap(internalRep); Map<String, List<String>> dynamicVars = SetVariables.internalDynamicToMap(dynamicInternalRep); m_vp = new VariablesPanel(vars); m_dvp = new DynamicVariablesPanel(dynamicVars); JTabbedPane tabbedPane = new JTabbedPane(); tabbedPane.add("Static", m_vp); tabbedPane.add("Dynamic", m_dvp); add(tabbedPane, BorderLayout.CENTER); } @Override protected void okPressed() { String vi = m_vp.getVariablesInternal(); String dvi = m_dvp.getVariablesInternal(); ((SetVariables) getStepToEdit()).setVarsInternalRep(m_vp .getVariablesInternal()); ((SetVariables) getStepToEdit()).setDynamicVarsInternalRep(m_dvp .getVariablesInternal()); } protected static class DynamicVariablesPanel extends JPanel { private static final long serialVersionUID = -280047347103350039L; protected InteractiveTablePanel m_table = new InteractiveTablePanel( new String[] { "Attribute name/index", "Variable name", "Default value", "" }); public DynamicVariablesPanel(Map<String, List<String>> vars) { setLayout(new BorderLayout()); setBorder(BorderFactory.createTitledBorder("Variables to set from " + "incoming instances")); add(m_table, BorderLayout.CENTER); // populate table with variables int row = 0; JTable table = m_table.getTable(); for (Map.Entry<String, List<String>> e : vars.entrySet()) { String attName = e.getKey(); String varName = e.getValue().get(0); String defaultVal = e.getValue().get(1); if (attName != null && attName.length() > 0 && varName != null && varName.length() > 0) { table.getModel().setValueAt(attName, row, 0); table.getModel().setValueAt(varName, row, 1); table.getModel().setValueAt(defaultVal, row, 2); ((InteractiveTableModel) table.getModel()).addEmptyRow(); row++; } } } /** * Get the variables in internal format * * @return the variables + settings in the internal format */ public String getVariablesInternal() { StringBuilder b = new StringBuilder(); JTable table = m_table.getTable(); int numRows = table.getModel().getRowCount(); for (int i = 0; i < numRows; i++) { String attName = table.getValueAt(i, 0).toString(); String varName = table.getValueAt(i, 1).toString(); String defVal = table.getValueAt(i, 2).toString(); if (attName.trim().length() > 0 && varName.trim().length() > 0) { if (defVal.length() == 0) { defVal = " "; } b.append(attName).append(SetVariables.SEP3).append(varName) .append(SetVariables.SEP2).append(defVal); } if (i < numRows - 1) { b.append(SetVariables.SEP1); } } return b.toString(); } } /** * Panel that holds the editor for variables */ protected static class VariablesPanel extends JPanel { private static final long serialVersionUID = 5188290550108775006L; protected InteractiveTablePanel m_table = new InteractiveTablePanel( new String[] { "Variable name", "Value", "" }); public VariablesPanel(Map<String, String> vars) { setLayout(new BorderLayout()); setBorder(BorderFactory.createTitledBorder("Static variables to set")); add(m_table, BorderLayout.CENTER); // populate table with variables int row = 0; JTable table = m_table.getTable(); for (Map.Entry<String, String> e : vars.entrySet()) { String varName = e.getKey(); String varVal = e.getValue(); if (varVal != null && varVal.length() > 0) { table.getModel().setValueAt(varName, row, 0); table.getModel().setValueAt(varVal, row, 1); ((InteractiveTableModel) table.getModel()).addEmptyRow(); row++; } } } /** * Get the variables in internal format * * @return the variables + settings in the internal format */ public String getVariablesInternal() { StringBuilder b = new StringBuilder(); JTable table = m_table.getTable(); int numRows = table.getModel().getRowCount(); for (int i = 0; i < numRows; i++) { String paramName = table.getValueAt(i, 0).toString(); String paramValue = table.getValueAt(i, 1).toString(); if (paramName.length() > 0 && paramValue.length() > 0) { b.append(paramName).append(SetVariables.SEP2).append(paramValue); } if (i < numRows - 1) { b.append(SetVariables.SEP1); } } return b.toString(); } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow/steps/SorterStepEditorDialog.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * SorterStepEditorDialog.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.gui.knowledgeflow.steps; import weka.core.Instances; import weka.core.WekaException; import weka.gui.JListHelper; import weka.gui.PropertySheetPanel; import weka.gui.knowledgeflow.GOEStepEditorDialog; import weka.knowledgeflow.steps.Sorter; import weka.knowledgeflow.steps.Step; import javax.swing.*; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; /** * Step editor dialog for the Sorter step * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class SorterStepEditorDialog extends GOEStepEditorDialog { private static final long serialVersionUID = -1258170590422372948L; /** Combo box for selecting attribute to sort on */ protected JComboBox<String> m_attCombo = new JComboBox<String>(); /** Combo box for choosing to sort descending or not */ protected JComboBox<String> m_descending = new JComboBox<String>(); /** Holds the individual sorting criteria */ protected JList<Sorter.SortRule> m_list = new JList<Sorter.SortRule>(); /** List model for sort rules */ protected DefaultListModel<Sorter.SortRule> m_listModel; /** Button for creating a new rule */ protected JButton m_newBut = new JButton("New"); /** Button for deleting a selected rule */ protected JButton m_deleteBut = new JButton("Delete"); /** Button for moving a rule up in the list */ protected JButton m_upBut = new JButton("Move up"); /** Button for moving a rule down in the list */ protected JButton m_downBut = new JButton("Move down"); /** * Set the step to edit * * @param step the step to edit */ @Override protected void setStepToEdit(Step step) { copyOriginal(step); createAboutPanel(step); m_editor = new PropertySheetPanel(false); m_editor.setUseEnvironmentPropertyEditors(true); m_editor.setEnvironment(m_env); m_editor.setTarget(m_stepToEdit); m_primaryEditorHolder.setLayout(new BorderLayout()); m_primaryEditorHolder.add(m_editor, BorderLayout.CENTER); m_editorHolder.setLayout(new BorderLayout()); m_editorHolder.add(m_primaryEditorHolder, BorderLayout.NORTH); m_editorHolder.add(createSorterPanel(), BorderLayout.CENTER); add(m_editorHolder, BorderLayout.CENTER); String sString = ((Sorter) getStepToEdit()).getSortDetails(); m_listModel = new DefaultListModel<Sorter.SortRule>(); m_list.setModel(m_listModel); if (sString != null && sString.length() > 0) { String[] parts = sString.split("@@sort-rule@@"); if (parts.length > 0) { m_upBut.setEnabled(true); m_downBut.setEnabled(true); for (String sPart : parts) { Sorter.SortRule s = new Sorter.SortRule(sPart); m_listModel.addElement(s); } } m_list.repaint(); } // try to set up attribute combo if (((Sorter) getStepToEdit()).getStepManager().numIncomingConnections() > 0) { // sorter can only have a single incoming connection - get the name // of it String incomingConnName = ((Sorter) getStepToEdit()).getStepManager().getIncomingConnections() .keySet().iterator().next(); try { Instances connectedFormat = ((Sorter) getStepToEdit()).getStepManager() .getIncomingStructureForConnectionType(incomingConnName); if (connectedFormat != null) { for (int i = 0; i < connectedFormat.numAttributes(); i++) { m_attCombo.addItem(connectedFormat.attribute(i).name()); } } } catch (WekaException ex) { showErrorDialog(ex); } } } /** * Creates the sort panel * * @return a {@code JPanel} */ protected JPanel createSorterPanel() { JPanel sorterPanel = new JPanel(new BorderLayout()); JPanel fieldHolder = new JPanel(); fieldHolder.setLayout(new GridLayout(0, 2)); JPanel attListP = new JPanel(); attListP.setLayout(new BorderLayout()); attListP.setBorder(BorderFactory.createTitledBorder("Sort on attribute")); attListP.add(m_attCombo, BorderLayout.CENTER); m_attCombo.setEditable(true); m_attCombo.setToolTipText("<html>Accepts an attribute name, index or <br> " + "the special string \"/first\" and \"/last\"</html>"); m_descending.addItem("No"); m_descending.addItem("Yes"); JPanel descendingP = new JPanel(); descendingP.setLayout(new BorderLayout()); descendingP.setBorder(BorderFactory.createTitledBorder("Sort descending")); descendingP.add(m_descending, BorderLayout.CENTER); fieldHolder.add(attListP); fieldHolder.add(descendingP); sorterPanel.add(fieldHolder, BorderLayout.NORTH); m_list.setVisibleRowCount(5); m_deleteBut.setEnabled(false); JPanel listPanel = new JPanel(); listPanel.setLayout(new BorderLayout()); JPanel butHolder = new JPanel(); butHolder.setLayout(new GridLayout(1, 0)); butHolder.add(m_newBut); butHolder.add(m_deleteBut); butHolder.add(m_upBut); butHolder.add(m_downBut); m_upBut.setEnabled(false); m_downBut.setEnabled(false); listPanel.add(butHolder, BorderLayout.NORTH); JScrollPane js = new JScrollPane(m_list); js.setBorder(BorderFactory .createTitledBorder("Sort-by list (rows applied in order)")); listPanel.add(js, BorderLayout.CENTER); sorterPanel.add(listPanel, BorderLayout.CENTER); m_list.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { if (!m_deleteBut.isEnabled()) { m_deleteBut.setEnabled(true); } Object entry = m_list.getSelectedValue(); if (entry != null) { Sorter.SortRule m = (Sorter.SortRule) entry; m_attCombo.setSelectedItem(m.getAttribute()); if (m.getDescending()) { m_descending.setSelectedIndex(1); } else { m_descending.setSelectedIndex(0); } } } } }); m_newBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Sorter.SortRule m = new Sorter.SortRule(); String att = (m_attCombo.getSelectedItem() != null) ? m_attCombo.getSelectedItem() .toString() : ""; m.setAttribute(att); m.setDescending(m_descending.getSelectedIndex() == 1); m_listModel.addElement(m); if (m_listModel.size() > 1) { m_upBut.setEnabled(true); m_downBut.setEnabled(true); } m_list.setSelectedIndex(m_listModel.size() - 1); } }); m_deleteBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int selected = m_list.getSelectedIndex(); if (selected >= 0) { m_listModel.removeElementAt(selected); if (m_listModel.size() <= 1) { m_upBut.setEnabled(false); m_downBut.setEnabled(false); } } } }); m_upBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JListHelper.moveUp(m_list); } }); m_downBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JListHelper.moveDown(m_list); } }); m_attCombo.getEditor().getEditorComponent() .addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { Object m = m_list.getSelectedValue(); String text = ""; if (m_attCombo.getSelectedItem() != null) { text = m_attCombo.getSelectedItem().toString(); } java.awt.Component theEditor = m_attCombo.getEditor().getEditorComponent(); if (theEditor instanceof JTextField) { text = ((JTextField) theEditor).getText(); } if (m != null) { ((Sorter.SortRule) m).setAttribute(text); m_list.repaint(); } } }); m_attCombo.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Object m = m_list.getSelectedValue(); Object selected = m_attCombo.getSelectedItem(); if (m != null && selected != null) { ((Sorter.SortRule) m).setAttribute(selected.toString()); m_list.repaint(); } } }); m_descending.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Object m = m_list.getSelectedValue(); if (m != null) { ((Sorter.SortRule) m).setDescending(m_descending.getSelectedIndex() == 1); m_list.repaint(); } } }); return sorterPanel; } /** * Called when the OK button is pressed */ @Override public void okPressed() { StringBuilder buff = new StringBuilder(); for (int i = 0; i < m_listModel.size(); i++) { Sorter.SortRule m = (Sorter.SortRule) m_listModel.elementAt(i); buff.append(m.toStringInternal()); if (i < m_listModel.size() - 1) { buff.append("@@sort-rule@@"); } } ((Sorter) getStepToEdit()).setSortDetails(buff.toString()); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow/steps/StorePropertiesInEnvironmentStepEditorDialog.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * StorePropertiesInEnvironmentStepEditorDialog.java * Copyright (C) 2016 University of Waikato, Hamilton, New Zealand * */ package weka.gui.knowledgeflow.steps; import weka.gui.InteractiveTableModel; import weka.gui.InteractiveTablePanel; import weka.gui.knowledgeflow.StepEditorDialog; import weka.knowledgeflow.steps.StorePropertiesInEnvironment; import javax.swing.BorderFactory; import javax.swing.JPanel; import javax.swing.JTable; import java.awt.BorderLayout; import java.util.List; import java.util.Map; /** * Editor dialog for the StorePropertiesInEnvironment step. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class StorePropertiesInEnvironmentStepEditorDialog extends StepEditorDialog { private static final long serialVersionUID = 3797813883697010599L; protected DynamicPropertiesPanel m_dpp; @Override protected void layoutEditor() { String internalRep = ((StorePropertiesInEnvironment) getStepToEdit()).getPropsInternalRep(); Map<String, List<String>> props = StorePropertiesInEnvironment.internalDynamicToMap(internalRep); m_dpp = new DynamicPropertiesPanel(props); add(m_dpp, BorderLayout.CENTER); } @Override public void okPressed() { String dps = m_dpp.getPropertiesInternal(); ((StorePropertiesInEnvironment) getStepToEdit()).setPropsInternalRep(dps); } protected static class DynamicPropertiesPanel extends JPanel { private static final long serialVersionUID = 5864117781960584665L; protected InteractiveTablePanel m_table = new InteractiveTablePanel( new String[] { "Attribute name/index", "Target step", "Property name", "Default property value", "" }); public DynamicPropertiesPanel(Map<String, List<String>> props) { setLayout(new BorderLayout()); setBorder(BorderFactory.createTitledBorder("Properties to set from " + "incoming instances")); add(m_table, BorderLayout.CENTER); // populate table with variables int row = 0; JTable table = m_table.getTable(); for (Map.Entry<String, List<String>> e : props.entrySet()) { String attName = e.getKey(); String stepName = e.getValue().get(0); String propName = e.getValue().get(1); String defaultVal = e.getValue().get(2); if (stepName != null && stepName.length() > 0 && attName != null && attName.length() > 0) { table.getModel().setValueAt(attName, row, 0); table.getModel().setValueAt(stepName, row, 1); table.getModel().setValueAt(propName, row, 2); table.getModel().setValueAt(defaultVal, row, 3); ((InteractiveTableModel) table.getModel()).addEmptyRow(); row++; } } } /** * Get the variables in internal format * * @return the variables + settings in the internal format */ public String getPropertiesInternal() { StringBuilder b = new StringBuilder(); JTable table = m_table.getTable(); int numRows = table.getModel().getRowCount(); for (int i = 0; i < numRows; i++) { String attName = table.getValueAt(i, 0).toString(); String stepName = table.getValueAt(i, 1).toString(); String propName = table.getValueAt(i, 2).toString(); String defVal = table.getValueAt(i, 3).toString(); if (stepName.trim().length() > 0 && attName.trim().length() > 0) { if (propName.length() == 0) { propName = " "; } if (defVal.length() == 0) { defVal = " "; } b.append(attName).append(StorePropertiesInEnvironment.SEP2) .append(stepName).append(StorePropertiesInEnvironment.SEP2) .append(propName).append(StorePropertiesInEnvironment.SEP2) .append(defVal); } if (i < numRows - 1) { b.append(StorePropertiesInEnvironment.SEP1); } } return b.toString(); } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow/steps/StripChartInteractiveView.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * StripChartInteractiveView.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.gui.knowledgeflow.steps; import weka.core.Defaults; import weka.core.Environment; import weka.core.Settings; import weka.core.Utils; import weka.gui.knowledgeflow.BaseInteractiveViewer; import weka.gui.visualize.PrintableComponent; import weka.knowledgeflow.steps.StripChart; import javax.swing.*; import javax.swing.border.TitledBorder; import java.awt.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.ArrayList; import java.util.List; /** * Implements the actual strip chart view * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class StripChartInteractiveView extends BaseInteractiveViewer implements StripChart.PlotNotificationListener { private static final long serialVersionUID = 7697752421621805402L; /** default colours for colouring lines */ protected Color[] m_colorList = { Color.green, Color.red, new Color(6, 80, 255), Color.cyan, Color.pink, new Color(255, 0, 255), Color.orange, new Color(255, 0, 0), new Color(0, 255, 0), Color.white }; /** the background color. */ protected Color m_BackgroundColor = Color.BLACK; /** the color of the legend panel's border. */ protected Color m_LegendPanelBorderColor = new Color(253, 255, 61); protected StripPlotter m_plotPanel; /** the scale. */ protected final ScalePanel m_scalePanel = new ScalePanel(); /** * The off screen image for rendering to. */ protected transient Image m_osi = null; /** * Width and height of the off screen image. */ protected int m_iheight; protected int m_iwidth; /** * Max value for the y axis. */ protected double m_max = 1; /** * Min value for the y axis. */ protected double m_min = 0; /** * Scale update requested. */ protected boolean m_yScaleUpdate = false; protected double m_oldMax; protected double m_oldMin; /** data point count */ protected int m_xCount = 0; /** * Shift the plot by this many pixels every time a point is plotted */ private int m_refreshWidth = 1; /** Font to use on the plot */ protected final Font m_labelFont = new Font("Monospaced", Font.PLAIN, 10); /** Font metrics for string placement calculations */ protected FontMetrics m_labelMetrics; /** Holds the legend */ protected final LegendPanel m_legendPanel = new LegendPanel(); /** Holds the legend entries */ protected List<String> m_legendText = new ArrayList<String>(); /** Previous data point */ private double[] m_previousY = new double[1]; /** * Initialize the viewer */ @Override public void init() { m_plotPanel = new StripPlotter(); m_plotPanel.setBackground(m_BackgroundColor); m_scalePanel.setBackground(m_BackgroundColor); m_legendPanel.setBackground(m_BackgroundColor); m_xCount = 0; JPanel panel = new JPanel(new BorderLayout()); new PrintableComponent(panel); add(panel, BorderLayout.CENTER); panel.add(m_legendPanel, BorderLayout.WEST); panel.add(m_plotPanel, BorderLayout.CENTER); panel.add(m_scalePanel, BorderLayout.EAST); m_legendPanel.setMinimumSize(new Dimension(100, getHeight())); m_legendPanel.setPreferredSize(new Dimension(100, getHeight())); m_scalePanel.setMinimumSize(new Dimension(30, getHeight())); m_scalePanel.setPreferredSize(new Dimension(30, getHeight())); // setPreferredSize(new Dimension(600, 150)); m_parent.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { super.windowClosing(e); ((StripChart) getStep()) .removePlotNotificationListener(StripChartInteractiveView.this); } }); ((StripChart) getStep()).addPlotNotificationListener(this); applySettings(getSettings()); } /** * Called when the close button is pressed */ @Override public void closePressed() { ((StripChart) getStep()) .removePlotNotificationListener(StripChartInteractiveView.this); } /** * Called by the KnowledgeFlow application once the enclosing JFrame is * visible */ @Override public void nowVisible() { m_parent.setSize(600, 180); ((JFrame) m_parent).setResizable(false); m_parent.setAlwaysOnTop(true); m_parent.validate(); int iwidth = m_plotPanel.getWidth(); int iheight = m_plotPanel.getHeight(); m_osi = m_plotPanel.createImage(iwidth, iheight); Graphics m = m_osi.getGraphics(); m.setColor(m_BackgroundColor); m.fillRect(0, 0, iwidth, iheight); m_previousY[0] = -1; setRefreshWidth(); } private int convertToPanelY(double yval) { int height = m_plotPanel.getHeight(); double temp = (yval - m_min) / (m_max - m_min); temp = temp * height; temp = height - temp; return (int) temp; } /** * Get the name of this viewer * * @return the name of this viewer */ @Override public String getViewerName() { return "Strip Chart"; } /** * Set the entries for the legend * * @param legendEntries a list of legend entries * @param min initial minimum for the series being plotted * @param max initial maximum for the series being plotted */ @Override public void setLegend(List<String> legendEntries, double min, double max) { m_legendText = legendEntries; m_max = max; m_min = min; m_xCount = 0; m_legendPanel.repaint(); } /** * Pre-process a data point * * @param dataPoint the data point to process * @return the data point */ protected double[] preProcessDataPoint(double[] dataPoint) { // check for out of scale values for (double element : dataPoint) { if (element < m_min) { m_oldMin = m_min; m_min = element; m_yScaleUpdate = true; } if (element > m_max) { m_oldMax = m_max; m_max = element; m_yScaleUpdate = true; } } if (m_yScaleUpdate) { m_scalePanel.repaint(); m_yScaleUpdate = false; } // return dp; return dataPoint; } /** * Accept and process a data point * * @param dataPoint the data point to process */ @Override public void acceptDataPoint(double[] dataPoint) { if (m_xCount % ((StripChart) getStep()).getRefreshFreq() != 0) { m_xCount++; return; } dataPoint = preProcessDataPoint(dataPoint); if (m_previousY[0] == -1) { int iw = m_plotPanel.getWidth(); int ih = m_plotPanel.getHeight(); m_osi = m_plotPanel.createImage(iw, ih); Graphics m = m_osi.getGraphics(); m.setColor(m_BackgroundColor); m.fillRect(0, 0, iw, ih); m_previousY[0] = convertToPanelY(0); m_iheight = ih; m_iwidth = iw; } if (dataPoint.length != m_previousY.length) { m_previousY = new double[dataPoint.length]; for (int i = 0; i < dataPoint.length; i++) { m_previousY[i] = convertToPanelY(0); } } Graphics osg = m_osi.getGraphics(); Graphics g = m_plotPanel.getGraphics(); osg.copyArea(m_refreshWidth, 0, m_iwidth - m_refreshWidth, m_iheight, -m_refreshWidth, 0); osg.setColor(m_BackgroundColor); osg.fillRect(m_iwidth - m_refreshWidth, 0, m_iwidth, m_iheight); // paint the old scale onto the plot if a scale update has occurred if (m_yScaleUpdate) { String maxVal = numToString(m_oldMax); String minVal = numToString(m_oldMin); String midVal = numToString((m_oldMax - m_oldMin) / 2.0); if (m_labelMetrics == null) { m_labelMetrics = g.getFontMetrics(m_labelFont); } osg.setFont(m_labelFont); int wmx = m_labelMetrics.stringWidth(maxVal); int wmn = m_labelMetrics.stringWidth(minVal); int wmd = m_labelMetrics.stringWidth(midVal); int hf = m_labelMetrics.getAscent(); osg.setColor(m_colorList[m_colorList.length - 1]); osg.drawString(maxVal, m_iwidth - wmx, hf - 2); osg.drawString(midVal, m_iwidth - wmd, (m_iheight / 2) + (hf / 2)); osg.drawString(minVal, m_iwidth - wmn, m_iheight - 1); m_yScaleUpdate = false; } double pos; for (int i = 0; i < dataPoint.length; i++) { if (Utils.isMissingValue(dataPoint[i])) { continue; } osg.setColor(m_colorList[(i % m_colorList.length)]); pos = convertToPanelY(dataPoint[i]); osg.drawLine(m_iwidth - m_refreshWidth, (int) m_previousY[i], m_iwidth - 1, (int) pos); m_previousY[i] = pos; if (m_xCount % ((StripChart) getStep()).getXLabelFreq() == 0) { // draw the actual y value onto the plot for this curve String val = numToString(dataPoint[i]); if (m_labelMetrics == null) { m_labelMetrics = g.getFontMetrics(m_labelFont); } int hf = m_labelMetrics.getAscent(); if (pos - hf < 0) { pos += hf; } int w = m_labelMetrics.stringWidth(val); osg.setFont(m_labelFont); osg.drawString(val, m_iwidth - w, (int) pos); } } if (m_xCount % ((StripChart) getStep()).getXLabelFreq() == 0) { String xVal = "" + m_xCount; osg.setColor(m_colorList[m_colorList.length - 1]); int w = m_labelMetrics.stringWidth(xVal); osg.setFont(m_labelFont); osg.drawString(xVal, m_iwidth - w, m_iheight - 1); } g.drawImage(m_osi, 0, 0, m_plotPanel); m_xCount++; } private void setRefreshWidth() { m_refreshWidth = ((StripChart) getStep()).getRefreshWidth(); if (m_labelMetrics == null) { getGraphics().setFont(m_labelFont); m_labelMetrics = getGraphics().getFontMetrics(m_labelFont); } int refWidth = m_labelMetrics.stringWidth("99000"); // compute how often x label will be rendered int z = (((StripChart) getStep()).getXLabelFreq() / ((StripChart) getStep()) .getRefreshFreq()); if (z < 1) { z = 1; } if (z * m_refreshWidth < refWidth + 5) { m_refreshWidth *= (((refWidth + 5) / z) + 1); } } /** * Class providing a panel for the plot. */ private class StripPlotter extends JPanel { /** for serialization. */ private static final long serialVersionUID = -7056271598761675879L; @Override public void paintComponent(Graphics g) { super.paintComponent(g); if (m_osi != null) { g.drawImage(m_osi, 0, 0, this); } } } /** * Class providing a panel for displaying the y axis. */ private class ScalePanel extends JPanel { /** for serialization. */ private static final long serialVersionUID = 6416998474984829434L; @Override public void paintComponent(Graphics gx) { super.paintComponent(gx); if (m_labelMetrics == null) { m_labelMetrics = gx.getFontMetrics(m_labelFont); } gx.setFont(m_labelFont); int hf = m_labelMetrics.getAscent(); String temp = "" + m_max; gx.setColor(m_colorList[m_colorList.length - 1]); gx.drawString(temp, 1, hf - 2); temp = "" + (m_min + ((m_max - m_min) / 2.0)); gx.drawString(temp, 1, (this.getHeight() / 2) + (hf / 2)); temp = "" + m_min; gx.drawString(temp, 1, this.getHeight() - 1); } }; /** * Class providing a panel for the legend. */ protected class LegendPanel extends JPanel { /** for serialization. */ private static final long serialVersionUID = 7713986576833797583L; @Override public void paintComponent(Graphics gx) { super.paintComponent(gx); if (m_labelMetrics == null) { m_labelMetrics = gx.getFontMetrics(m_labelFont); } int hf = m_labelMetrics.getAscent(); int x = 10; int y = hf + 15; gx.setFont(m_labelFont); for (int i = 0; i < m_legendText.size(); i++) { String temp = m_legendText.get(i); gx.setColor(m_colorList[(i % m_colorList.length)]); gx.drawString(temp, x, y); y += hf; } StripChartInteractiveView.this.revalidate(); } }; private static String numToString(double num) { int precision = 1; int whole = (int) Math.abs(num); double decimal = Math.abs(num) - whole; int nondecimal; nondecimal = (whole > 0) ? (int) (Math.log(whole) / Math.log(10)) : 1; precision = (decimal > 0) ? (int) Math .abs(((Math.log(Math.abs(num)) / Math.log(10)))) + 2 : 1; if (precision > 5) { precision = 1; } String numString = weka.core.Utils .doubleToString(num, nondecimal + 1 + precision, precision); return numString; } /** * Get the default settings for this viewer * * @return the default settings for this viewer */ @Override public Defaults getDefaultSettings() { return new StripChartInteractiveViewDefaults(); } /** * Apply settings from the supplied settings object * * @param settings the settings object that might (or might not) have been */ @Override public void applySettings(Settings settings) { m_BackgroundColor = settings.getSetting(StripChartInteractiveViewDefaults.ID, StripChartInteractiveViewDefaults.BACKGROUND_COLOR_KEY, StripChartInteractiveViewDefaults.BACKGROUND_COLOR, Environment.getSystemWide()); m_plotPanel.setBackground(m_BackgroundColor); m_scalePanel.setBackground(m_BackgroundColor); m_legendPanel.setBackground(m_BackgroundColor); m_LegendPanelBorderColor = settings.getSetting(StripChartInteractiveViewDefaults.ID, StripChartInteractiveViewDefaults.LEGEND_BORDER_COLOR_KEY, StripChartInteractiveViewDefaults.LEGEND_BORDER_COLOR, Environment.getSystemWide()); Font lf = new Font("Monospaced", Font.PLAIN, 12); m_legendPanel.setBorder(BorderFactory.createTitledBorder( BorderFactory.createEtchedBorder(Color.gray, Color.darkGray), "Legend", TitledBorder.CENTER, TitledBorder.DEFAULT_POSITION, lf, m_LegendPanelBorderColor)); m_colorList[m_colorList.length - 1] = settings.getSetting(StripChartInteractiveViewDefaults.ID, StripChartInteractiveViewDefaults.X_LABEL_COLOR_KEY, StripChartInteractiveViewDefaults.X_LABEL_COLOR, Environment.getSystemWide()); } /** * Class defining default settings for this viewer */ protected static final class StripChartInteractiveViewDefaults extends Defaults { public static final String ID = "weka.gui.knowledgeflow.steps.stripchart"; protected static final Settings.SettingKey BACKGROUND_COLOR_KEY = new Settings.SettingKey(ID + ".outputBackgroundColor", "Output background color", "Output background color"); protected static final Color BACKGROUND_COLOR = Color.black; protected static final Settings.SettingKey LEGEND_BORDER_COLOR_KEY = new Settings.SettingKey(ID + ".legendBorderColor", "Legend border color", "Legend border color"); protected static final Color LEGEND_BORDER_COLOR = new Color(253, 255, 61); protected static final Settings.SettingKey X_LABEL_COLOR_KEY = new Settings.SettingKey(ID + ".xLabelColor", "Color for x label text", "Color for x label text"); protected static final Color X_LABEL_COLOR = Color.white; private static final long serialVersionUID = 2247370679260844812L; public StripChartInteractiveViewDefaults() { super(ID); m_defaults.put(BACKGROUND_COLOR_KEY, BACKGROUND_COLOR); m_defaults.put(LEGEND_BORDER_COLOR_KEY, LEGEND_BORDER_COLOR); m_defaults.put(X_LABEL_COLOR_KEY, X_LABEL_COLOR); } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow/steps/SubstringLabelerStepEditorDialog.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * SubstringLabelerStepEditorDialog.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.gui.knowledgeflow.steps; import weka.gui.EnvironmentField; import weka.gui.JListHelper; import weka.gui.beans.SubstringLabelerRules; import weka.gui.knowledgeflow.StepEditorDialog; import weka.knowledgeflow.steps.SubstringLabeler; import javax.swing.BorderFactory; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.SwingConstants; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; /** * Step editor dialog for the SubstringLabeler step * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class SubstringLabelerStepEditorDialog extends StepEditorDialog { private static final long serialVersionUID = 2386951012941540643L; /** Field for specifying the name of the new attribute to create */ protected EnvironmentField m_matchAttNameField; /** Field for specifying the attributes to match on */ protected EnvironmentField m_attListField; /** Field for specifying the string/regex to match */ protected EnvironmentField m_matchField; /** Field for specifying the label to assign if match is positive */ protected EnvironmentField m_labelField; /** Checkbox to specify that the match is a regex */ protected JCheckBox m_regexCheck = new JCheckBox(); /** Checkbox for specifying that case should be ignored when matching */ protected JCheckBox m_ignoreCaseCheck = new JCheckBox(); /** * Checkbox for making a binary label attribute into a nominal one (rather * than numeric) */ protected JCheckBox m_nominalBinaryCheck = new JCheckBox(); /** * Checkbox for specifying that non-matching instances should be consumed * rather than having the match attribute value set to missing value */ protected JCheckBox m_consumeNonMatchingCheck = new JCheckBox(); /** Holds the list of match rules */ protected JList<SubstringLabelerRules.SubstringLabelerMatchRule> m_list = new JList<SubstringLabelerRules.SubstringLabelerMatchRule>(); /** List model */ protected DefaultListModel<SubstringLabelerRules.SubstringLabelerMatchRule> m_listModel; /** Button for adding a new match rule */ protected JButton m_newBut = new JButton("New"); /** Button for deleting a match rule */ protected JButton m_deleteBut = new JButton("Delete"); /** Button for moving a match rule up in the list */ protected JButton m_upBut = new JButton("Move up"); /** Button for moving a match rule down in the list */ protected JButton m_downBut = new JButton("Move down"); /** * Initialize the dialog */ protected void initialize() { String mlString = ((SubstringLabeler) getStepToEdit()).getMatchDetails(); m_listModel = new DefaultListModel<SubstringLabelerRules.SubstringLabelerMatchRule>(); m_list.setModel(m_listModel); if (mlString != null && mlString.length() > 0) { String[] parts = mlString.split(SubstringLabelerRules.MATCH_RULE_SEPARATOR); if (parts.length > 0) { m_upBut.setEnabled(true); m_downBut.setEnabled(true); for (String mPart : parts) { SubstringLabelerRules.SubstringLabelerMatchRule m = new SubstringLabelerRules.SubstringLabelerMatchRule(mPart); m_listModel.addElement(m); } m_list.repaint(); } } } /** * Layout the editor dialog */ @Override protected void layoutEditor() { initialize(); JPanel mainHolder = new JPanel(new BorderLayout()); JPanel controlHolder = new JPanel(); controlHolder.setLayout(new BorderLayout()); JPanel fieldHolder = new JPanel(); JPanel attListP = new JPanel(); attListP.setLayout(new BorderLayout()); attListP.setBorder(BorderFactory.createTitledBorder("Apply to attributes")); m_attListField = new EnvironmentField(m_env); attListP.add(m_attListField, BorderLayout.CENTER); attListP .setToolTipText("<html>Accepts a range of indexes (e.g. '1,2,6-10')<br> " + "or a comma-separated list of named attributes</html>"); JPanel matchP = new JPanel(); matchP.setLayout(new BorderLayout()); matchP.setBorder(BorderFactory.createTitledBorder("Match")); m_matchField = new EnvironmentField(m_env); matchP.add(m_matchField, BorderLayout.CENTER); JPanel labelP = new JPanel(); labelP.setLayout(new BorderLayout()); labelP.setBorder(BorderFactory.createTitledBorder("Label")); m_labelField = new EnvironmentField(m_env); labelP.add(m_labelField, BorderLayout.CENTER); fieldHolder.add(attListP); fieldHolder.add(matchP); fieldHolder.add(labelP); controlHolder.add(fieldHolder, BorderLayout.NORTH); JPanel checkHolder = new JPanel(); checkHolder.setLayout(new GridLayout(0, 2)); JLabel attNameLab = new JLabel("Name of label attribute", SwingConstants.RIGHT); checkHolder.add(attNameLab); m_matchAttNameField = new EnvironmentField(m_env); m_matchAttNameField.setText(((SubstringLabeler) getStepToEdit()) .getMatchAttributeName()); checkHolder.add(m_matchAttNameField); JLabel regexLab = new JLabel("Match using a regular expression", SwingConstants.RIGHT); regexLab .setToolTipText("Use a regular expression rather than literal match"); checkHolder.add(regexLab); checkHolder.add(m_regexCheck); JLabel caseLab = new JLabel("Ignore case when matching", SwingConstants.RIGHT); checkHolder.add(caseLab); checkHolder.add(m_ignoreCaseCheck); JLabel nominalBinaryLab = new JLabel("Make binary label attribute nominal", SwingConstants.RIGHT); nominalBinaryLab .setToolTipText("<html>If the label attribute is binary (i.e. no <br>" + "explicit labels have been declared) then<br>this makes the resulting " + "attribute nominal<br>rather than numeric.</html>"); checkHolder.add(nominalBinaryLab); checkHolder.add(m_nominalBinaryCheck); m_nominalBinaryCheck.setSelected(((SubstringLabeler) getStepToEdit()) .getNominalBinary()); JLabel consumeNonMatchLab = new JLabel("Consume non-matching instances", SwingConstants.RIGHT); consumeNonMatchLab .setToolTipText("<html>When explicit labels have been defined, consume " + "<br>(rather than output with missing value) instances</html>"); checkHolder.add(consumeNonMatchLab); checkHolder.add(m_consumeNonMatchingCheck); m_consumeNonMatchingCheck.setSelected(((SubstringLabeler) getStepToEdit()) .getConsumeNonMatching()); controlHolder.add(checkHolder, BorderLayout.SOUTH); mainHolder.add(controlHolder, BorderLayout.NORTH); m_list.setVisibleRowCount(5); m_deleteBut.setEnabled(false); JPanel listPanel = new JPanel(); listPanel.setLayout(new BorderLayout()); JPanel butHolder = new JPanel(); butHolder.setLayout(new GridLayout(1, 0)); butHolder.add(m_newBut); butHolder.add(m_deleteBut); butHolder.add(m_upBut); butHolder.add(m_downBut); m_upBut.setEnabled(false); m_downBut.setEnabled(false); listPanel.add(butHolder, BorderLayout.NORTH); JScrollPane js = new JScrollPane(m_list); js.setBorder(BorderFactory .createTitledBorder("Match-list list (rows applied in order)")); listPanel.add(js, BorderLayout.CENTER); mainHolder.add(listPanel, BorderLayout.CENTER); add(mainHolder, BorderLayout.CENTER); m_attListField.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent e) { Object m = m_list.getSelectedValue(); if (m != null) { ((SubstringLabelerRules.SubstringLabelerMatchRule) m) .setAttsToApplyTo(m_attListField.getText()); m_list.repaint(); } } }); m_matchField.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent e) { Object m = m_list.getSelectedValue(); if (m != null) { ((SubstringLabelerRules.SubstringLabelerMatchRule) m) .setMatch(m_matchField.getText()); m_list.repaint(); } } }); m_labelField.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent e) { Object m = m_list.getSelectedValue(); if (m != null) { ((SubstringLabelerRules.SubstringLabelerMatchRule) m) .setLabel(m_labelField.getText()); m_list.repaint(); } } }); m_list.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { if (!m_deleteBut.isEnabled()) { m_deleteBut.setEnabled(true); } checkUpDown(); Object entry = m_list.getSelectedValue(); if (entry != null) { SubstringLabelerRules.SubstringLabelerMatchRule m = (SubstringLabelerRules.SubstringLabelerMatchRule) entry; m_attListField.setText(m.getAttsToApplyTo()); m_matchField.setText(m.getMatch()); m_labelField.setText(m.getLabel()); m_regexCheck.setSelected(m.getRegex()); m_ignoreCaseCheck.setSelected(m.getIgnoreCase()); } } } }); m_newBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { SubstringLabelerRules.SubstringLabelerMatchRule m = new SubstringLabelerRules.SubstringLabelerMatchRule(); String atts = (m_attListField.getText() != null) ? m_attListField.getText() : ""; m.setAttsToApplyTo(atts); String match = (m_matchField.getText() != null) ? m_matchField.getText() : ""; m.setMatch(match); String label = (m_labelField.getText() != null) ? m_labelField.getText() : ""; m.setLabel(label); m.setRegex(m_regexCheck.isSelected()); m.setIgnoreCase(m_ignoreCaseCheck.isSelected()); m_listModel.addElement(m); if (m_listModel.size() > 1) { m_upBut.setEnabled(true); m_downBut.setEnabled(true); } m_list.setSelectedIndex(m_listModel.size() - 1); checkUpDown(); } }); m_deleteBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int selected = m_list.getSelectedIndex(); if (selected >= 0) { m_listModel.removeElementAt(selected); checkUpDown(); if (m_listModel.size() <= 1) { m_upBut.setEnabled(false); m_downBut.setEnabled(false); } } } }); m_upBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JListHelper.moveUp(m_list); checkUpDown(); } }); m_downBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JListHelper.moveDown(m_list); checkUpDown(); } }); m_regexCheck.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Object m = m_list.getSelectedValue(); if (m != null) { ((SubstringLabelerRules.SubstringLabelerMatchRule) m) .setRegex(m_regexCheck.isSelected()); m_list.repaint(); } } }); m_ignoreCaseCheck.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Object m = m_list.getSelectedValue(); if (m != null) { ((SubstringLabelerRules.SubstringLabelerMatchRule) m) .setIgnoreCase(m_ignoreCaseCheck.isSelected()); m_list.repaint(); } } }); } /** * Set the enabled state of the up and down buttons based on the currently * selected row in the table */ protected void checkUpDown() { if (m_list.getSelectedValue() != null && m_listModel.size() > 1) { m_upBut.setEnabled(m_list.getSelectedIndex() > 0); m_downBut.setEnabled(m_list.getSelectedIndex() < m_listModel.size() - 1); } } /** * Called when the OK button is pressed */ @Override protected void okPressed() { StringBuilder buff = new StringBuilder(); for (int i = 0; i < m_listModel.size(); i++) { SubstringLabelerRules.SubstringLabelerMatchRule mr = (SubstringLabelerRules.SubstringLabelerMatchRule) m_listModel .elementAt(i); buff.append(mr.toStringInternal()); if (i < m_listModel.size() - 1) { buff.append(SubstringLabelerRules.MATCH_RULE_SEPARATOR); } } ((SubstringLabeler) getStepToEdit()).setMatchDetails(buff.toString()); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow/steps/SubstringReplacerStepEditorDialog.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * SubstringReplacerStepEditorDialog.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.gui.knowledgeflow.steps; import weka.gui.EnvironmentField; import weka.gui.JListHelper; import weka.gui.beans.SubstringReplacerRules; import weka.gui.knowledgeflow.StepEditorDialog; import weka.knowledgeflow.steps.SubstringReplacer; import javax.swing.BorderFactory; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.SwingConstants; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; /** * Step editor dialog for the SubstringReplacer step * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class SubstringReplacerStepEditorDialog extends StepEditorDialog { private static final long serialVersionUID = 7804721324137987443L; /** Field for specifying the attributes to match on */ protected EnvironmentField m_attListField; /** Field for specifying the string/regex to match */ protected EnvironmentField m_matchField; /** Field for specifying the value to replace a match with */ protected EnvironmentField m_replaceField; /** Checkbox to specify that the match is a regex */ protected JCheckBox m_regexCheck = new JCheckBox(); /** Checkbox for specifying that case should be ignored when matching */ protected JCheckBox m_ignoreCaseCheck = new JCheckBox(); /** Holds the list of match rules */ protected JList<SubstringReplacerRules.SubstringReplacerMatchRule> m_list = new JList<SubstringReplacerRules.SubstringReplacerMatchRule>(); /** List model */ protected DefaultListModel<SubstringReplacerRules.SubstringReplacerMatchRule> m_listModel; /** Button for adding a new match rule */ protected JButton m_newBut = new JButton("New"); /** Button for deleting a match rule */ protected JButton m_deleteBut = new JButton("Delete"); /** Button for moving a match rule up in the list */ protected JButton m_upBut = new JButton("Move up"); /** Button for moving a match rule down in the list */ protected JButton m_downBut = new JButton("Move down"); /** * Initialize the editor */ protected void initialize() { String mrString = ((SubstringReplacer) getStepToEdit()).getMatchReplaceDetails(); m_listModel = new DefaultListModel<SubstringReplacerRules.SubstringReplacerMatchRule>(); m_list.setModel(m_listModel); if (mrString != null && mrString.length() > 0) { String[] parts = mrString.split("@@match-replace@@"); if (parts.length > 0) { m_upBut.setEnabled(true); m_downBut.setEnabled(true); for (String mrPart : parts) { SubstringReplacerRules.SubstringReplacerMatchRule mr = new SubstringReplacerRules.SubstringReplacerMatchRule(mrPart); m_listModel.addElement(mr); } m_list.repaint(); } } } /** * Layout the editor dialog */ @Override protected void layoutEditor() { initialize(); JPanel mainHolder = new JPanel(new BorderLayout()); JPanel controlHolder = new JPanel(); controlHolder.setLayout(new BorderLayout()); JPanel fieldHolder = new JPanel(); JPanel attListP = new JPanel(); attListP.setLayout(new BorderLayout()); attListP.setBorder(BorderFactory.createTitledBorder("Apply to attributes")); m_attListField = new EnvironmentField(m_env); attListP.add(m_attListField, BorderLayout.CENTER); attListP .setToolTipText("<html>Accepts a range of indexes (e.g. '1,2,6-10')<br> " + "or a comma-separated list of named attributes</html>"); JPanel matchP = new JPanel(); matchP.setLayout(new BorderLayout()); matchP.setBorder(BorderFactory.createTitledBorder("Match")); m_matchField = new EnvironmentField(m_env); matchP.add(m_matchField, BorderLayout.CENTER); JPanel replaceP = new JPanel(); replaceP.setLayout(new BorderLayout()); replaceP.setBorder(BorderFactory.createTitledBorder("Replace")); m_replaceField = new EnvironmentField(m_env); replaceP.add(m_replaceField, BorderLayout.CENTER); fieldHolder.add(attListP); fieldHolder.add(matchP); fieldHolder.add(replaceP); controlHolder.add(fieldHolder, BorderLayout.NORTH); final JPanel checkHolder = new JPanel(); checkHolder.setLayout(new GridLayout(0, 2)); JLabel regexLab = new JLabel("Match using a regular expression", SwingConstants.RIGHT); regexLab .setToolTipText("Use a regular expression rather than literal match"); checkHolder.add(regexLab); checkHolder.add(m_regexCheck); JLabel caseLab = new JLabel("Ignore case when matching", SwingConstants.RIGHT); checkHolder.add(caseLab); checkHolder.add(m_ignoreCaseCheck); controlHolder.add(checkHolder, BorderLayout.SOUTH); mainHolder.add(controlHolder, BorderLayout.NORTH); m_list.setVisibleRowCount(5); m_deleteBut.setEnabled(false); JPanel listPanel = new JPanel(); listPanel.setLayout(new BorderLayout()); JPanel butHolder = new JPanel(); butHolder.setLayout(new GridLayout(1, 0)); butHolder.add(m_newBut); butHolder.add(m_deleteBut); butHolder.add(m_upBut); butHolder.add(m_downBut); m_upBut.setEnabled(false); m_downBut.setEnabled(false); listPanel.add(butHolder, BorderLayout.NORTH); JScrollPane js = new JScrollPane(m_list); js.setBorder(BorderFactory .createTitledBorder("Match-replace list (rows applied in order)")); listPanel.add(js, BorderLayout.CENTER); mainHolder.add(listPanel, BorderLayout.CENTER); add(mainHolder, BorderLayout.CENTER); m_attListField.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent e) { Object mr = m_list.getSelectedValue(); if (mr != null) { ((SubstringReplacerRules.SubstringReplacerMatchRule) mr) .setAttsToApplyTo(m_attListField.getText()); m_list.repaint(); } } }); m_matchField.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent e) { Object mr = m_list.getSelectedValue(); if (mr != null) { ((SubstringReplacerRules.SubstringReplacerMatchRule) mr) .setMatch(m_matchField.getText()); m_list.repaint(); } } }); m_replaceField.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent e) { Object mr = m_list.getSelectedValue(); if (mr != null) { ((SubstringReplacerRules.SubstringReplacerMatchRule) mr) .setReplace(m_replaceField.getText()); m_list.repaint(); } } }); m_list.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { if (!m_deleteBut.isEnabled()) { m_deleteBut.setEnabled(true); } checkUpDown(); Object entry = m_list.getSelectedValue(); if (entry != null) { SubstringReplacerRules.SubstringReplacerMatchRule mr = (SubstringReplacerRules.SubstringReplacerMatchRule) entry; m_attListField.setText(mr.getAttsToApplyTo()); m_matchField.setText(mr.getMatch()); m_replaceField.setText(mr.getReplace()); m_regexCheck.setSelected(mr.getRegex()); m_ignoreCaseCheck.setSelected(mr.getIgnoreCase()); } } } }); m_newBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { SubstringReplacerRules.SubstringReplacerMatchRule mr = new SubstringReplacerRules.SubstringReplacerMatchRule(); String atts = (m_attListField.getText() != null) ? m_attListField.getText() : ""; mr.setAttsToApplyTo(atts); String match = (m_matchField.getText() != null) ? m_matchField.getText() : ""; mr.setMatch(match); String replace = (m_replaceField.getText() != null) ? m_replaceField.getText() : ""; mr.setReplace(replace); mr.setRegex(m_regexCheck.isSelected()); mr.setIgnoreCase(m_ignoreCaseCheck.isSelected()); m_listModel.addElement(mr); if (m_listModel.size() > 1) { m_upBut.setEnabled(true); m_downBut.setEnabled(true); } m_list.setSelectedIndex(m_listModel.size() - 1); checkUpDown(); } }); m_deleteBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int selected = m_list.getSelectedIndex(); if (selected >= 0) { m_listModel.removeElementAt(selected); checkUpDown(); if (m_listModel.size() <= 1) { m_upBut.setEnabled(false); m_downBut.setEnabled(false); } } } }); m_upBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JListHelper.moveUp(m_list); checkUpDown(); } }); m_downBut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JListHelper.moveDown(m_list); checkUpDown(); } }); m_regexCheck.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Object mr = m_list.getSelectedValue(); if (mr != null) { ((SubstringReplacerRules.SubstringReplacerMatchRule) mr) .setRegex(m_regexCheck.isSelected()); m_list.repaint(); } } }); m_ignoreCaseCheck.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Object mr = m_list.getSelectedValue(); if (mr != null) { ((SubstringReplacerRules.SubstringReplacerMatchRule) mr) .setIgnoreCase(m_ignoreCaseCheck.isSelected()); m_list.repaint(); } } }); } /** * Set the enabled state of the up and down buttons based on the currently * selected row in the table */ protected void checkUpDown() { if (m_list.getSelectedValue() != null && m_listModel.size() > 1) { m_upBut.setEnabled(m_list.getSelectedIndex() > 0); m_downBut.setEnabled(m_list.getSelectedIndex() < m_listModel.size() - 1); } } /** * Called when the OK button is pressed */ @Override protected void okPressed() { StringBuilder buff = new StringBuilder(); for (int i = 0; i < m_listModel.size(); i++) { SubstringReplacerRules.SubstringReplacerMatchRule mr = (SubstringReplacerRules.SubstringReplacerMatchRule) m_listModel .elementAt(i); buff.append(mr.toStringInternal()); if (i < m_listModel.size() - 1) { buff.append("@@match-replace@@"); } } ((SubstringReplacer) getStepToEdit()).setMatchReplaceDetails(buff .toString()); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/knowledgeflow/steps/TextViewerInteractiveView.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /*` * TextViewerInteractiveView.java * Copyright (C) 2002-2015 University of Waikato, Hamilton, New Zealand * */ package weka.gui.knowledgeflow.steps; import weka.core.Defaults; import weka.core.Environment; import weka.core.Settings; import weka.gui.ResultHistoryPanel; import weka.gui.SaveBuffer; import weka.gui.knowledgeflow.BaseInteractiveViewer; import weka.knowledgeflow.steps.TextViewer; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTextArea; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.Map; /** * Interactive viewer for the TextViewer step * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class TextViewerInteractiveView extends BaseInteractiveViewer implements TextViewer.TextNotificationListener { private static final long serialVersionUID = -3164518320257969282L; /** Button for clearing the results */ protected JButton m_clearButton = new JButton("Clear results"); /** Holds the list of results */ protected ResultHistoryPanel m_history; /** The main text output area */ protected JTextArea m_outText; /** Scroll panel for the text area */ protected JScrollPane m_textScroller; /** * Initialize the viewer */ @Override public void init() { addButton(m_clearButton); m_outText = new JTextArea(20, 80); m_outText.setEditable(false); m_outText.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); m_history = new ResultHistoryPanel(m_outText); m_history.setBorder(BorderFactory.createTitledBorder("Result list")); m_history.setHandleRightClicks(false); m_history.setDeleteListener(new ResultHistoryPanel.RDeleteListener() { @Override public void entryDeleted(String name, int index) { ((TextViewer) getStep()).getResults().remove(name); } @Override public void entriesDeleted(java.util.List<String> names, java.util.List<Integer> indexes) { for (String name : names) { ((TextViewer) getStep()).getResults().remove(name); } } }); m_history.getList().addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (((e.getModifiers() & InputEvent.BUTTON1_MASK) != InputEvent.BUTTON1_MASK) || e.isAltDown()) { int index = m_history.getList().locationToIndex(e.getPoint()); if (index != -1) { String name = m_history.getNameAtIndex(index); visualize(name, e.getX(), e.getY()); } else { visualize(null, e.getX(), e.getY()); } } } }); m_textScroller = new JScrollPane(m_outText); m_textScroller.setBorder(BorderFactory.createTitledBorder("Text")); JSplitPane p2 = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, m_history, m_textScroller); add(p2, BorderLayout.CENTER); // copy all results over to the history panel. Map<String, String> runResults = ((TextViewer) getStep()).getResults(); String lastName = ""; if (runResults.size() > 0) { for (Map.Entry<String, String> e : runResults.entrySet()) { m_history .addResult(e.getKey(), new StringBuffer().append(e.getValue())); lastName = e.getKey(); } if (lastName.length() > 0) { m_history.setSingle(lastName); } } m_clearButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m_history.clearResults(); ((TextViewer) getStep()).getResults().clear(); m_outText.setText(""); } }); applySettings(getSettings()); ((TextViewer) getStep()).setTextNotificationListener(this); } /** * Called when the close button is pressed */ @Override public void closePressed() { ((TextViewer) getStep()) .removeTextNotificationListener(TextViewerInteractiveView.this); } /** * Applys settings from the supplied settings object * * @param settings the settings object that might (or might not) have been */ @Override public void applySettings(Settings settings) { m_outText.setFont(settings.getSetting(TextViewerInteractiveViewDefaults.ID, TextViewerInteractiveViewDefaults.OUTPUT_FONT_KEY, TextViewerInteractiveViewDefaults.OUTPUT_FONT, Environment.getSystemWide())); m_history.setFont(settings.getSetting(TextViewerInteractiveViewDefaults.ID, TextViewerInteractiveViewDefaults.OUTPUT_FONT_KEY, TextViewerInteractiveViewDefaults.OUTPUT_FONT, Environment.getSystemWide())); m_outText.setForeground(settings.getSetting( TextViewerInteractiveViewDefaults.ID, TextViewerInteractiveViewDefaults.OUTPUT_TEXT_COLOR_KEY, TextViewerInteractiveViewDefaults.OUTPUT_TEXT_COLOR, Environment.getSystemWide())); m_outText.setBackground(settings.getSetting( TextViewerInteractiveViewDefaults.ID, TextViewerInteractiveViewDefaults.OUTPUT_BACKGROUND_COLOR_KEY, TextViewerInteractiveViewDefaults.OUTPUT_BACKGROUND_COLOR, Environment.getSystemWide())); m_textScroller.setBackground(settings.getSetting( TextViewerInteractiveViewDefaults.ID, TextViewerInteractiveViewDefaults.OUTPUT_BACKGROUND_COLOR_KEY, TextViewerInteractiveViewDefaults.OUTPUT_BACKGROUND_COLOR, Environment.getSystemWide())); m_outText.setRows(settings.getSetting(TextViewerInteractiveViewDefaults.ID, TextViewerInteractiveViewDefaults.NUM_ROWS_KEY, TextViewerInteractiveViewDefaults.NUM_ROWS, Environment.getSystemWide())); m_outText.setColumns(settings.getSetting( TextViewerInteractiveViewDefaults.ID, TextViewerInteractiveViewDefaults.NUM_COLUMNS_KEY, TextViewerInteractiveViewDefaults.NUM_COLUMNS, Environment.getSystemWide())); m_history.setBackground(settings.getSetting( TextViewerInteractiveViewDefaults.ID, TextViewerInteractiveViewDefaults.OUTPUT_BACKGROUND_COLOR_KEY, TextViewerInteractiveViewDefaults.OUTPUT_BACKGROUND_COLOR, Environment.getSystemWide())); } /** * Get the viewer name * * @return the viewer name */ @Override public String getViewerName() { return "Text Viewer"; } /** * Handles constructing a popup menu with visualization options. * * @param name the name of the result history list entry clicked on by the * user * @param x the x coordinate for popping up the menu * @param y the y coordinate for popping up the menu */ protected void visualize(String name, int x, int y) { final JPanel panel = this; final String selectedName = name; JPopupMenu resultListMenu = new JPopupMenu(); JMenuItem visMainBuffer = new JMenuItem("View in main window"); if (selectedName != null) { visMainBuffer.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m_history.setSingle(selectedName); } }); } else { visMainBuffer.setEnabled(false); } resultListMenu.add(visMainBuffer); JMenuItem visSepBuffer = new JMenuItem("View in separate window"); if (selectedName != null) { visSepBuffer.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m_history.openFrame(selectedName); } }); } else { visSepBuffer.setEnabled(false); } resultListMenu.add(visSepBuffer); JMenuItem saveOutput = new JMenuItem("Save result buffer"); if (selectedName != null) { saveOutput.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { SaveBuffer saveOut = new SaveBuffer(null, panel); StringBuffer sb = m_history.getNamedBuffer(selectedName); if (sb != null) { saveOut.save(sb); } } }); } else { saveOutput.setEnabled(false); } resultListMenu.add(saveOutput); JMenuItem deleteOutput = new JMenuItem("Delete result buffer"); if (selectedName != null) { deleteOutput.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m_history.removeResult(selectedName); } }); } else { deleteOutput.setEnabled(false); } resultListMenu.add(deleteOutput); resultListMenu.show(m_history.getList(), x, y); } /** * Get the default settings of this viewer * * @return the default settings */ @Override public Defaults getDefaultSettings() { return new TextViewerInteractiveViewDefaults(); } /** * Accept a new text result and add it to the result list * * @param name the name of the result * @param text the text of the result */ @Override public void acceptTextResult(String name, String text) { m_history.addResult(name, new StringBuffer().append(text)); m_history.setSingle(name); } /** * Defaults for this viewer */ protected static final class TextViewerInteractiveViewDefaults extends Defaults { public static final String ID = "weka.gui.knowledgeflow.steps.textviewer"; protected static final Settings.SettingKey OUTPUT_FONT_KEY = new Settings.SettingKey(ID + ".outputFont", "Font for text output", "Font to " + "use in the output area"); protected static final Font OUTPUT_FONT = new Font("Monospaced", Font.PLAIN, 12); protected static final Settings.SettingKey OUTPUT_TEXT_COLOR_KEY = new Settings.SettingKey(ID + ".outputFontColor", "Output text color", "Color " + "of output text"); protected static final Color OUTPUT_TEXT_COLOR = Color.black; protected static final Settings.SettingKey OUTPUT_BACKGROUND_COLOR_KEY = new Settings.SettingKey(ID + ".outputBackgroundColor", "Output background color", "Output background color"); protected static final Color OUTPUT_BACKGROUND_COLOR = Color.white; protected static final Settings.SettingKey NUM_COLUMNS_KEY = new Settings.SettingKey(ID + ".numColumns", "Number of columns of text", "Number of columns of text"); protected static final int NUM_COLUMNS = 80; protected static final Settings.SettingKey NUM_ROWS_KEY = new Settings.SettingKey(ID + ".numRows", "Number of rows of text", "Number of rows of text"); protected static final int NUM_ROWS = 20; private static final long serialVersionUID = 8361658568822013306L; public TextViewerInteractiveViewDefaults() { super(ID); m_defaults.put(OUTPUT_FONT_KEY, OUTPUT_FONT); m_defaults.put(OUTPUT_TEXT_COLOR_KEY, OUTPUT_TEXT_COLOR); m_defaults.put(OUTPUT_BACKGROUND_COLOR_KEY, OUTPUT_BACKGROUND_COLOR); m_defaults.put(NUM_COLUMNS_KEY, NUM_COLUMNS); m_defaults.put(NUM_ROWS_KEY, NUM_ROWS); } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/scripting/FileScriptingPanel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * FileScriptingPanel.java * Copyright (C) 2009-2012 University of Waikato, Hamilton, New Zealand * Copyright (c) 1995 - 2008 Sun Microsystems, Inc. */ package weka.gui.scripting; import java.awt.BorderLayout; import java.awt.Dialog; import java.awt.Dimension; import java.awt.Font; import java.awt.Frame; import java.awt.event.ActionEvent; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.io.File; import java.util.HashMap; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.BorderFactory; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JInternalFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextPane; import javax.swing.KeyStroke; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.event.UndoableEditEvent; import javax.swing.event.UndoableEditListener; import javax.swing.text.DefaultEditorKit; import javax.swing.text.Document; import javax.swing.text.JTextComponent; import javax.swing.undo.CannotRedoException; import javax.swing.undo.CannotUndoException; import javax.swing.undo.UndoManager; import weka.core.Utils; import weka.gui.ComponentHelper; import weka.gui.DocumentPrinting; import weka.gui.ExtensionFileFilter; import weka.gui.PropertyDialog; import weka.gui.scripting.event.ScriptExecutionEvent; import weka.gui.scripting.event.ScriptExecutionEvent.Type; import weka.gui.scripting.event.ScriptExecutionListener; import weka.gui.scripting.event.TitleUpdatedEvent; /** * Supports loading/saving of files. * * @author fracpete (fracpete at waikato dot ac dot nz) * @author Sun Microsystems Inc (see <a href="http://java.sun.com/docs/books/tutorial/uiswing/examples/components/TextComponentDemoProject/src/components/TextComponentDemo.java">TextComponentDemo.java</a>) * @version $Revision$ */ public abstract class FileScriptingPanel extends ScriptingPanel implements ScriptExecutionListener { /** for serialization. */ private static final long serialVersionUID = 1583670545010241816L; /** * A slightly extended action class. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public abstract class BasicAction extends AbstractAction { /** for serialization. */ private static final long serialVersionUID = 2821117985661550385L; /** * Constructor for setting up an action. * * @param name the name of the action (to be displayed in menu/button) * @param icon the icon name (no path required if in weka/gui/images), can be null * @param accel the accelerator command, e.g., "ctrl N", can be null * @param mnemonic the mnemonic character */ public BasicAction(String name, String icon, String accel, Character mnemonic) { super(name); if ((icon != null) && (icon.length() > 0)) putValue(Action.SMALL_ICON, ComponentHelper.getImageIcon(icon)); if ((accel != null) && (accel.length() > 0)) putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(accel)); if (mnemonic != null) putValue(Action.MNEMONIC_KEY, new Integer(mnemonic.charValue())); } } /** * The New action. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ protected class NewAction extends BasicAction { /** for serialization. */ private static final long serialVersionUID = -8665722554539726090L; /** * Initializes the action. */ public NewAction() { super("New", "new.gif", "ctrl N", 'N'); setEnabled(true); } /** * Fired when action got executed. * * @param e the event */ public void actionPerformed(ActionEvent e) { m_Script.empty(); notifyTitleUpdatedListeners(new TitleUpdatedEvent(FileScriptingPanel.this)); } } /** * The Open action. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ protected class OpenAction extends BasicAction { /** for serialization. */ private static final long serialVersionUID = -4496148485267789162L; /** * Initializes the action. */ public OpenAction() { super("Open...", "open.gif", "ctrl O", 'O'); setEnabled(true); } /** * Fired when action got executed. * * @param e the event */ public void actionPerformed(ActionEvent e) { boolean ok; int retVal; if (!checkModified()) return; retVal = m_FileChooser.showOpenDialog(FileScriptingPanel.this); if (retVal != JFileChooser.APPROVE_OPTION) return; ok = m_Script.open(m_FileChooser.getSelectedFile()); m_TextCode.setCaretPosition(0); if (!ok) JOptionPane.showMessageDialog( FileScriptingPanel.this, "Couldn't open file '" + m_FileChooser.getSelectedFile() + "'!"); notifyTitleUpdatedListeners(new TitleUpdatedEvent(FileScriptingPanel.this)); } } /** * The Save action. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ protected class SaveAction extends BasicAction { /** for serialization. */ private static final long serialVersionUID = -74651145892063975L; /** whether to bring up the save dialog all the time. */ protected boolean m_ShowDialog; /** * Initializes the action. * * @param name the name of the action * @param showDialog whether to always show the dialog */ public SaveAction(String name, boolean showDialog) { super(name, (showDialog ? "" : "save.gif"), (showDialog ? "ctrl shift S" : "ctrl S"), (showDialog ? 'a' : 'S')); m_ShowDialog = showDialog; setEnabled(true); } /** * Fired when action got executed. * * @param e the event */ public void actionPerformed(ActionEvent e) { boolean ok; int retVal; if (m_ShowDialog || (m_Script.getFilename() == null)) { retVal = m_FileChooser.showSaveDialog(FileScriptingPanel.this); if (retVal != JFileChooser.APPROVE_OPTION) return; ok = m_Script.saveAs(m_FileChooser.getSelectedFile()); } else { ok = m_Script.save(); } if (!ok) { if (m_Script.getFilename() != null) JOptionPane.showMessageDialog( FileScriptingPanel.this, "Failed to save file '" + m_FileChooser.getSelectedFile() + "'!"); else JOptionPane.showMessageDialog( FileScriptingPanel.this, "Failed to save file!"); } else { m_SaveAction.setEnabled(false); } notifyTitleUpdatedListeners(new TitleUpdatedEvent(FileScriptingPanel.this)); } } /** * The Print action. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ protected class PrintAction extends BasicAction { /** for serialization. */ private static final long serialVersionUID = -6246539539545724632L; /** * Initializes the action. */ public PrintAction() { super("Print...", "print.gif", "ctrl P", 'P'); setEnabled(true); } /** * Fired when action got executed. * * @param e the event */ public void actionPerformed(ActionEvent e) { JTextPane pane; DocumentPrinting doc; pane = newCodePane(); pane.setText(m_TextCode.getText()); doc = new DocumentPrinting(); doc.print(pane); } } /** * The Clear output action. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ protected class ClearOutputAction extends BasicAction { /** for serialization. */ private static final long serialVersionUID = 47986890456997211L; /** * Initializes the action. */ public ClearOutputAction() { super("Clear output", "", "F2", 'C'); setEnabled(true); } /** * Fired when action got executed. * * @param e the event */ public void actionPerformed(ActionEvent e) { m_TextOutput.setText(""); } } /** * The Exit action. Sends out a WindowEvent/WINDOW_CLOSED to all * WindowListener objects of a jframe. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ protected class ExitAction extends BasicAction { /** for serialization. */ private static final long serialVersionUID = -5884709836238884180L; /** * Initializes the action. */ public ExitAction() { super("Exit", "", "", 'x'); setEnabled(true); } /** * Fired when action got executed. * * @param e the event */ public void actionPerformed(ActionEvent e) { Dialog dialog; Frame frame; JFrame jframe; JInternalFrame jintframe; int i; WindowListener[] listeners; WindowEvent event; if (!checkModified()) return; if (PropertyDialog.getParentDialog(FileScriptingPanel.this) != null) { dialog = PropertyDialog.getParentDialog(FileScriptingPanel.this); dialog.setVisible(false); } else if (PropertyDialog.getParentFrame(FileScriptingPanel.this) != null) { jintframe = PropertyDialog.getParentInternalFrame(FileScriptingPanel.this); if (jintframe != null) { jintframe.doDefaultCloseAction(); } else { frame = PropertyDialog.getParentFrame(FileScriptingPanel.this); if (frame instanceof JFrame) { jframe = (JFrame) frame; if (jframe.getDefaultCloseOperation() == JFrame.HIDE_ON_CLOSE) jframe.setVisible(false); else if (jframe.getDefaultCloseOperation() == JFrame.DISPOSE_ON_CLOSE) jframe.dispose(); else if (jframe.getDefaultCloseOperation() == JFrame.EXIT_ON_CLOSE) System.exit(0); // notify listeners listeners = jframe.getWindowListeners(); event = new WindowEvent(jframe, WindowEvent.WINDOW_CLOSED); for (i = 0; i < listeners.length; i++) listeners[i].windowClosed(event); } else { frame.dispose(); } } } } } /** * The Undo action. * * @author Sun Microsystems Inc (see <a href="http://java.sun.com/docs/books/tutorial/uiswing/examples/components/TextComponentDemoProject/src/components/TextComponentDemo.java">TextComponentDemo.java</a>) * @version $Revision$ */ protected class UndoAction extends BasicAction { /** for serialization. */ private static final long serialVersionUID = 4298096648424808522L; /** * Initializes the action. */ public UndoAction() { super("Undo", "undo.gif", "ctrl Z", 'U'); setEnabled(false); } /** * Fired when action got executed. * * @param e the event */ public void actionPerformed(ActionEvent e) { try { m_Undo.undo(); } catch (CannotUndoException ex) { System.out.println("Unable to undo: " + ex); ex.printStackTrace(); } updateUndoState(); m_RedoAction.updateRedoState(); } /** * Updates the redo state. */ protected void updateUndoState() { if (m_Undo.canUndo()) { setEnabled(true); putValue(Action.NAME, m_Undo.getUndoPresentationName()); } else { setEnabled(false); putValue(Action.NAME, "Undo"); } } } /** * The Redo action. * * @author Sun Microsystems Inc (see <a href="http://java.sun.com/docs/books/tutorial/uiswing/examples/components/TextComponentDemoProject/src/components/TextComponentDemo.java">TextComponentDemo.java</a>) * @version $Revision$ */ protected class RedoAction extends BasicAction { /** for serialization. */ private static final long serialVersionUID = 4533966901523279350L; /** * Initializes the action. */ public RedoAction() { super("Redo", "redo.gif", "ctrl Y", 'R'); setEnabled(false); } /** * Fired when action got executed. * * @param e the event */ public void actionPerformed(ActionEvent e) { try { m_Undo.redo(); } catch (CannotRedoException ex) { System.out.println("Unable to redo: " + ex); ex.printStackTrace(); } updateRedoState(); m_UndoAction.updateUndoState(); } /** * Updates the redo state. */ protected void updateRedoState() { if (m_Undo.canRedo()) { setEnabled(true); putValue(Action.NAME, m_Undo.getRedoPresentationName()); } else { setEnabled(false); putValue(Action.NAME, "Redo"); } } } /** * The Commandline args action. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ protected class CommandlineArgsAction extends BasicAction { /** for serialization. */ private static final long serialVersionUID = -3183470039010826204L; /** * Initializes the action. */ public CommandlineArgsAction() { super("Arguments...", "properties.gif", "", 'g'); setEnabled(true); } /** * Fired when action got executed. * * @param e the event */ public void actionPerformed(ActionEvent e) { String retVal; retVal = JOptionPane.showInputDialog( FileScriptingPanel.this, "Please enter the command-line arguments", Utils.joinOptions(m_Args)); if (retVal == null) return; try { m_Args = Utils.splitOptions(retVal); } catch (Exception ex) { m_Args = new String[0]; ex.printStackTrace(); JOptionPane.showMessageDialog( FileScriptingPanel.this, "Error setting command-line arguments:\n" + ex, "Error", JOptionPane.ERROR_MESSAGE); } } } /** * The Start action. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ protected class StartAction extends BasicAction { /** for serialization. */ private static final long serialVersionUID = -7936456072955996220L; /** * Initializes the action. */ public StartAction() { super((m_Script.canExecuteScripts() ? "Start" : "Start (missing classes?)"), "run.gif", "ctrl R", 'S'); setEnabled(false); } /** * Fired when action got executed. * * @param e the event */ public void actionPerformed(ActionEvent e) { if (!checkModified()) return; if (m_Script.getFilename() == null) return; try { m_Script.start(m_Args); } catch (Exception ex) { ex.printStackTrace(); JOptionPane.showMessageDialog( FileScriptingPanel.this, "Error running script:\n" + ex, "Error", JOptionPane.ERROR_MESSAGE); } } } /** * The Stop action. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ protected class StopAction extends BasicAction { /** for serialization. */ private static final long serialVersionUID = 8764023289575718872L; /** * Initializes the action. */ public StopAction() { super("Stop", "stop.gif", "ctrl shift R", 'o'); setEnabled(false); } /** * Fired when action got executed. * * @param e the event */ public void actionPerformed(ActionEvent e) { try { m_Script.stop(); } catch (Exception ex) { // ignored } } } /** * The About action. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ protected class AboutAction extends BasicAction { /** for serialization. */ private static final long serialVersionUID = -6420463480569171227L; /** * Initializes the action. */ public AboutAction() { super("About...", "", "F1", 'A'); setEnabled(true); } /** * Fired when action got executed. * * @param e the event */ public void actionPerformed(ActionEvent e) { JDialog dialog; if (PropertyDialog.getParentDialog(FileScriptingPanel.this) != null) dialog = new JDialog(PropertyDialog.getParentDialog(FileScriptingPanel.this), getName()); else dialog = new JDialog(PropertyDialog.getParentFrame(FileScriptingPanel.this), getName()); dialog.setTitle((String) getValue(Action.NAME)); dialog.getContentPane().setLayout(new BorderLayout()); dialog.getContentPane().add(getAboutPanel()); dialog.pack(); dialog.setLocationRelativeTo(FileScriptingPanel.this); dialog.setVisible(true); } } /** * This listener class listens for edits that can be undone. * * @author Sun Microsystems Inc (see <a href="http://java.sun.com/docs/books/tutorial/uiswing/examples/components/TextComponentDemoProject/src/components/TextComponentDemo.java">TextComponentDemo.java</a>) * @version $Revision$ */ protected class ScriptUndoableEditListener implements UndoableEditListener { /** * Gets called when an undoable event gets triggered. * * @param e the event */ public void undoableEditHappened(UndoableEditEvent e) { //Remember the edit and update the menus. m_Undo.addEdit(e.getEdit()); m_UndoAction.updateUndoState(); m_RedoAction.updateRedoState(); } } /** the directory with the scripting-specific images. */ public final static String IMAGES_DIR = "weka/gui/scripting/images"; /** for loading/saving file. */ protected JFileChooser m_FileChooser; /** the script. */ protected Script m_Script; /** the script area. */ protected JTextArea m_ScriptArea; /** the output area. */ protected JTextArea m_OutputArea; /** for informing the user. */ protected JLabel m_LabelInfo; /** for storing the actions under their name. */ protected HashMap<Object, Action> m_Actions; /** the new action. */ protected NewAction m_NewAction; /** the open action. */ protected OpenAction m_OpenAction; /** the Save action. */ protected SaveAction m_SaveAction; /** the Save as action. */ protected SaveAction m_SaveAsAction; /** the Print action. */ protected PrintAction m_PrintAction; /** the clear output action. */ protected ClearOutputAction m_ClearOutputAction; /** the exit action. */ protected ExitAction m_ExitAction; /** the undo action. */ protected UndoAction m_UndoAction; /** the redo action. */ protected RedoAction m_RedoAction; /** the cut action. */ protected Action m_CutAction; /** the copy action. */ protected Action m_CopyAction; /** the paste action. */ protected Action m_PasteAction; /** the start action. */ protected StartAction m_StartAction; /** the stop action. */ protected StopAction m_StopAction; /** the arguments action. */ protected CommandlineArgsAction m_ArgsAction; /** the about action. */ protected AboutAction m_AboutAction; /** the undo manager. */ protected UndoManager m_Undo; /** the text pane with the code. */ protected JTextPane m_TextCode; /** the text pane for the output. */ protected JTextPane m_TextOutput; /** the commandline arguments to use. */ protected String[] m_Args; /** * For initializing member variables. */ protected void initialize() { super.initialize(); m_FileChooser = new JFileChooser(); m_FileChooser.setAcceptAllFileFilterUsed(true); m_FileChooser.setMultiSelectionEnabled(false); m_Undo = new UndoManager(); m_Args = new String[0]; } /** * Sets up the GUI after initializing the members. */ protected void initGUI() { JPanel panel; super.initGUI(); setLayout(new BorderLayout(0, 5)); m_TextCode = newCodePane(); m_TextCode.setFont(new Font("monospaced", Font.PLAIN, 12)); m_TextCode.getDocument().addUndoableEditListener(new ScriptUndoableEditListener()); m_TextCode.getDocument().addDocumentListener(new DocumentListener() { public void changedUpdate(DocumentEvent e) { update(); } public void insertUpdate(DocumentEvent e) { update(); } public void removeUpdate(DocumentEvent e) { update(); } protected void update() { Document doc = m_TextCode.getDocument(); m_StartAction.setEnabled((doc.getLength() > 0) && m_Script.canExecuteScripts()); m_SaveAction.setEnabled(true); notifyTitleUpdatedListeners(new TitleUpdatedEvent(FileScriptingPanel.this)); } }); add(new JScrollPane(m_TextCode), BorderLayout.CENTER); panel = new JPanel(new BorderLayout(0, 5)); panel.setPreferredSize(new Dimension(50, 200)); add(panel, BorderLayout.SOUTH); m_TextOutput = new JTextPane(); panel.add(new JScrollPane(m_TextOutput), BorderLayout.CENTER); m_LabelInfo = new JLabel(" "); m_LabelInfo.setBorder(BorderFactory.createLoweredBevelBorder()); panel.add(m_LabelInfo, BorderLayout.SOUTH); } /** * Finishes up after initializing members and setting up the GUI. */ protected void initFinish() { ExtensionFileFilter[] filters; int i; super.initFinish(); m_Script = newScript(m_TextCode.getDocument()); m_Script.addScriptFinishedListener(this); filters = m_Script.getFilters(); for (i = filters.length - 1; i >= 0; i--) m_FileChooser.addChoosableFileFilter(filters[i]); m_Actions = createActionTable(m_TextCode); // file m_NewAction = new NewAction(); m_OpenAction = new OpenAction(); m_SaveAction = new SaveAction("Save", false); m_SaveAsAction = new SaveAction("Save As...", true); m_PrintAction = new PrintAction(); m_ClearOutputAction = new ClearOutputAction(); m_ExitAction = new ExitAction(); // edit m_UndoAction = new UndoAction(); m_RedoAction = new RedoAction(); m_CutAction = updateAction(m_Actions.get(DefaultEditorKit.cutAction), "Cut", "cut.gif", "ctrl X", 'C'); m_CopyAction = updateAction(m_Actions.get(DefaultEditorKit.copyAction), "Copy", "copy.gif", "ctrl C", 'o'); m_PasteAction = updateAction(m_Actions.get(DefaultEditorKit.pasteAction), "Paste", "paste.gif", "ctrl V", 'P'); // script m_StartAction = new StartAction(); m_StopAction = new StopAction(); m_ArgsAction = new CommandlineArgsAction(); // help m_AboutAction = new AboutAction(); } /** * Updates the action and returns it. * * @param action the action to update * @param name the name to be used as display, can be null * @param icon the icon to use (if located in weka/gui/images, not path required), can be null * @param accel the accelerator command to use (e.g., "ctrl N"), can be null * @param mnemonic the mnemonic character to use, can be null * @return the updated action */ protected Action updateAction(Action action, String name, String icon, String accel, Character mnemonic) { Action result; // did we already update that action for another component? if (action == null) { result = m_Actions.get(name); return result; } result = action; if ((name != null) && (name.length() > 0)) result.putValue(Action.NAME, name); if ((icon != null) && (icon.length() > 0)) result.putValue(Action.SMALL_ICON, ComponentHelper.getImageIcon(icon)); if ((accel != null) && (accel.length() > 0)) result.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(accel)); if (mnemonic != null) result.putValue(Action.MNEMONIC_KEY, new Integer(mnemonic.charValue())); return result; } /** * Creates a new JTextPane for the code. * * @return the text pane */ protected abstract JTextPane newCodePane(); /** * Returns an initialized script object. * * @param doc the document to use as basis * @return the initialized script */ protected abstract Script newScript(Document doc); /** * Gets sent when a script finishes execution. * * @param e the event */ public void scriptFinished(ScriptExecutionEvent e) { if (e.getType() == Type.FINISHED) showInfo("Script execution finished"); else if (e.getType() == Type.STOPPED) showInfo("Script execution stopped by user"); else if (e.getType() == Type.ERROR) showInfo("Script execution failed" + (e.hasAdditional() ? (": " + e.getAdditional()) : "")); if (e.getType() != Type.STARTED) { m_NewAction.setEnabled(true); m_OpenAction.setEnabled(true); m_SaveAction.setEnabled(true); m_SaveAsAction.setEnabled(true); m_CutAction.setEnabled(true); m_CopyAction.setEnabled(true); m_PasteAction.setEnabled(true); m_StartAction.setEnabled(true); m_StopAction.setEnabled(false); } else { m_NewAction.setEnabled(false); m_OpenAction.setEnabled(false); m_SaveAction.setEnabled(false); m_SaveAsAction.setEnabled(false); m_CutAction.setEnabled(false); m_CopyAction.setEnabled(false); m_PasteAction.setEnabled(false); m_StartAction.setEnabled(false); m_StopAction.setEnabled(true); } } /** * The following two methods allow us to find an * action provided by the editor kit by its name. * * @param comp the component to get the actions from * @return the relation */ protected HashMap<Object, Action> createActionTable(JTextComponent comp) { HashMap<Object, Action> result; int i; Action[] actions; Action action; result = new HashMap<Object, Action>(); actions = comp.getActions(); for (i = 0; i < actions.length; i++) { action = actions[i]; result.put(action.getValue(Action.NAME), action); } return result; } /** * Returns a panel to be displayed with the AboutAction. * * @return the panel with some information on the scripting panel */ protected abstract JPanel getAboutPanel(); /** * Returns the title (without the filename). * * @return the plain title */ public abstract String getPlainTitle(); /** * Returns the current title for the frame/dialog. * * @return the title */ public String getTitle() { String result; result = getPlainTitle(); if (m_Script.isModified()) result = "*" + result; if (m_Script.getFilename() != null) result += " [" + m_Script.getFilename() + "]"; return result; } /** * Returns the text area that is used for displaying output on stdout * and stderr. * * @return the JTextArea */ public JTextPane getOutput() { return m_TextOutput; } /** * Returns the menu bar to to be displayed in the frame. * * @return the menu bar, null if not applicable */ public JMenuBar getMenuBar() { JMenuBar result; JMenu menu; JMenuItem menuitem; result = new JMenuBar(); // File menu = new JMenu("File"); menu.setMnemonic('F'); result.add(menu); // File/New menuitem = new JMenuItem(m_NewAction); menu.add(menuitem); // File/Open menuitem = new JMenuItem(m_OpenAction); menu.addSeparator(); menu.add(menuitem); // File/Save menuitem = new JMenuItem(m_SaveAction); menu.add(menuitem); // File/SaveAs menuitem = new JMenuItem(m_SaveAsAction); menu.add(menuitem); // File/Print menuitem = new JMenuItem(m_PrintAction); menu.addSeparator(); menu.add(menuitem); // File/Clear output menuitem = new JMenuItem(m_ClearOutputAction); menu.addSeparator(); menu.add(menuitem); // File/Exit menuitem = new JMenuItem(m_ExitAction); menu.addSeparator(); menu.add(menuitem); // Edit menu = new JMenu("Edit"); menu.setMnemonic('E'); result.add(menu); // Edit/Undo menuitem = new JMenuItem(m_UndoAction); menu.add(menuitem); // Edit/Redo menuitem = new JMenuItem(m_RedoAction); menu.add(menuitem); // Edit/Cut menuitem = new JMenuItem(m_CutAction); menu.addSeparator(); menu.add(menuitem); // Edit/Copy menuitem = new JMenuItem(m_CopyAction); menu.add(menuitem); // Edit/Paste menuitem = new JMenuItem(m_PasteAction); menu.add(menuitem); // Script menu = new JMenu("Script"); menu.setMnemonic('S'); result.add(menu); // Script/Start menuitem = new JMenuItem(m_StartAction); menu.add(menuitem); // Script/Stop menuitem = new JMenuItem(m_StopAction); menu.add(menuitem); // Script/Arguments menuitem = new JMenuItem(m_ArgsAction); menu.add(menuitem); // Help menu = new JMenu("Help"); menu.setMnemonic('H'); result.add(menu); // Help/About menuitem = new JMenuItem(m_AboutAction); menu.add(menuitem); return result; } /** * Updates the info shown in the bottom panel. * * @param msg the message to display */ protected void showInfo(String msg) { if (msg == null) msg = " "; m_LabelInfo.setText(msg); } /** * Opens the specified file. * * @param file the file to open */ public void open(File file) { m_Script.open(file); } /** * Checks whether the script is modified and asks the user to save it or not. * If everything is fine and one can ignore the modified state, true is * returned. * * @return true if one can proceed */ protected boolean checkModified() { boolean result; int retVal; result = true; if (m_Script.isModified()) { retVal = JOptionPane.showConfirmDialog( FileScriptingPanel.this, "Script not saved - save it now?", "Confirm", JOptionPane.YES_NO_CANCEL_OPTION); if (retVal == JOptionPane.YES_OPTION) { if (m_Script.getFilename() != null) m_Script.save(); else m_SaveAsAction.actionPerformed(null); result = !m_Script.isModified(); } else if (retVal == JOptionPane.CANCEL_OPTION) { 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/scripting/GroovyPanel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * GroovyPanel.java * Copyright (C) 2009-2012 University of Waikato, Hamilton, New Zealand */ package weka.gui.scripting; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Font; import java.awt.GridLayout; import java.util.Properties; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextPane; import javax.swing.text.Document; import weka.core.Utils; import weka.gui.BrowserHelper; import weka.gui.ComponentHelper; import weka.gui.visualize.VisualizeUtils; /** * A scripting panel for <a href="http://groovy.codehaus.org/" target="_blank">Groovy</a>. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class GroovyPanel extends FileScriptingPanel { /** for serialization. */ private static final long serialVersionUID = -3475707604414854111L; /** the Groovy setup. */ public final static String PROPERTIES_FILE = "weka/gui/scripting/Groovy.props"; /** * Creates a new JTextPane for the code. * * @return the text pane */ protected JTextPane newCodePane() { JTextPane result; SyntaxDocument doc; Properties props; try { props = Utils.readProperties(PROPERTIES_FILE); } catch (Exception e) { e.printStackTrace(); props = new Properties(); } result = new JTextPane(); if (props.getProperty("Syntax", "false").equals("true")) { doc = new SyntaxDocument(props); result.setDocument(doc); result.setBackground(doc.getBackgroundColor()); } else { result.setForeground(VisualizeUtils.processColour(props.getProperty("ForegroundColor", "black"), Color.BLACK)); result.setBackground(VisualizeUtils.processColour(props.getProperty("BackgroundColor", "white"), Color.WHITE)); result.setFont(new Font(props.getProperty("FontName", "monospaced"), Font.PLAIN, Integer.parseInt(props.getProperty("FontSize", "12")))); } return result; } /** * Returns an icon to be used in a frame. * * @return the icon */ public ImageIcon getIcon() { return ComponentHelper.getImageIcon(IMAGES_DIR + "/groovy_small.png"); } /** * Returns a panel to be displayed with the AboutAction. * * @return the panel with some information on the scripting panel */ protected JPanel getAboutPanel() { JPanel result; JPanel panel; result = new JPanel(new BorderLayout()); result.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); // image result.add(new JLabel(ComponentHelper.getImageIcon(IMAGES_DIR + "/groovy_medium.png")), BorderLayout.CENTER); // links panel = new JPanel(new GridLayout(5, 1)); panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); result.add(panel, BorderLayout.SOUTH); panel.add(new JLabel("Groovy homepage")); panel.add(BrowserHelper.createLink("http://groovy.codehaus.org/", null)); panel.add(new JLabel(" ")); panel.add(new JLabel("Weka and Groovy")); panel.add(BrowserHelper.createLink("http://weka.wikispaces.com/Using+Weka+from+Groovy", null)); return result; } /** * Returns the title (without the filename). * * @return the plain title */ public String getPlainTitle() { return "Groovy Console"; } /** * Returns an initialized script object. * * @param doc the document to use as basis * @return the initialized script */ protected Script newScript(Document doc) { return new GroovyScript(doc); } /** * Displays the panel in a frame. * * @param args can take a file as first argument */ public static void main(String[] args) { showPanel(new GroovyPanel(), args); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/scripting/GroovyScript.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * GroovyScript.java * Copyright (C) 2009-2012 University of Waikato, Hamilton, New Zealand */ package weka.gui.scripting; import java.io.File; import javax.swing.text.Document; import weka.core.scripting.Groovy; import weka.gui.ExtensionFileFilter; /** * Represents a <a href="http://groovy.codehaus.org/" target="_blank">Groovy</a> script. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class GroovyScript extends Script { /** for serialization. */ private static final long serialVersionUID = -3708517162415549420L; /** * Executes a Groovy script in a thread. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public static class GroovyThread extends ScriptThread { /** * Initializes the thread. * * @param owner the owning script * @param args the commandline arguments */ public GroovyThread(Script owner, String[] args) { super(owner, args); } /** * Tests whether the groovy object has a certain method. * * @param groovy the Groovy object to inspect * @param name the method to look for * @return true if the object has the given method */ protected boolean hasMethod(Object groovy, String name) { boolean result; try { groovy.getClass().getMethod(name, new Class[]{String[].class}); result = true; } catch (Exception e) { result = false; } return result; } /** * Performs the actual run. */ protected void doRun() { Object groovy; groovy = Groovy.newInstance(m_Owner.getFilename(), Object.class); if (hasMethod(groovy, "run")) Groovy.invoke(groovy, "run", new Class[]{String[].class}, new Object[]{getArgs()}); else if (hasMethod(groovy, "main")) Groovy.invoke(groovy, "main", new Class[]{String[].class}, new Object[]{getArgs()}); else throw new IllegalStateException("Neither 'run' nor 'main' method found!"); } } /** * Initializes the script. */ public GroovyScript() { super(); } /** * Initializes the script. * * @param doc the document to use as basis */ public GroovyScript(Document doc) { super(doc); } /** * Initializes the script. Automatically loads the specified file, if not * null. * * @param doc the document to use as basis * @param file the file to load (if not null) */ public GroovyScript(Document doc, File file) { super(doc, file); } /** * Returns the extension filters for this type of script. * * @return the filters */ public ExtensionFileFilter[] getFilters() { ExtensionFileFilter[] result; result = new ExtensionFileFilter[1]; result[0] = new ExtensionFileFilter(getDefaultExtension(), "Groovy script (*" + getDefaultExtension() + ")"); return result; } /** * Returns the default extension. Gets automatically added to files if * their name doesn't end with this. * * @return the default extension (incl. the dot) */ public String getDefaultExtension() { return ".groovy"; } /** * Returns whether scripts can be executed, i.e., Groovy is present. * * @return true if scripts can be executed */ protected boolean canExecuteScripts() { return Groovy.isPresent(); } /** * Performs pre-execution checks. * <p/> * This method checks whether Groovy is available (throws an exception if not). * * @param args optional commandline arguments * @throws Exception if checks fail */ protected void preCheck(String[] args) throws Exception { super.preCheck(args); if (!Groovy.isPresent()) throw new Exception("Groovy classes are not present in CLASSPATH!"); } /** * Returns a new thread to execute. * * @param args optional commandline arguments * @return the new thread object */ public ScriptThread newThread(String[] args) { return new GroovyThread(this, args); } /** * Runs the script from commandline. Use "-h" to list all options. * * @param args the commandline arguments * @throws Exception if execution fails */ public static void main(String[] args) throws Exception { runScript(new GroovyScript(), args); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/scripting/JythonPanel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * JythonPanel.java * Copyright (C) 2009-2012 University of Waikato, Hamilton, New Zealand */ package weka.gui.scripting; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Font; import java.awt.GridLayout; import java.util.Properties; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextPane; import javax.swing.text.Document; import weka.core.Utils; import weka.gui.BrowserHelper; import weka.gui.ComponentHelper; import weka.gui.visualize.VisualizeUtils; /** * A scripting panel for <a href="http://www.jython.org/" target="_blank">Jython</a>. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class JythonPanel extends FileScriptingPanel { /** for serialization. */ private static final long serialVersionUID = -827358576217085413L; /** the Groovy setup. */ public final static String PROPERTIES_FILE = "weka/gui/scripting/Jython.props"; /** * Creates a new JTextPane for the code. * * @return the text pane */ protected JTextPane newCodePane() { JTextPane result; SyntaxDocument doc; Properties props; try { props = Utils.readProperties(PROPERTIES_FILE); } catch (Exception e) { e.printStackTrace(); props = new Properties(); } result = new JTextPane(); if (props.getProperty("Syntax", "false").equals("true")) { doc = new SyntaxDocument(props); result.setDocument(doc); result.setBackground(doc.getBackgroundColor()); } else { result.setForeground(VisualizeUtils.processColour(props.getProperty("ForegroundColor", "black"), Color.BLACK)); result.setBackground(VisualizeUtils.processColour(props.getProperty("BackgroundColor", "white"), Color.WHITE)); result.setFont(new Font(props.getProperty("FontName", "monospaced"), Font.PLAIN, Integer.parseInt(props.getProperty("FontSize", "12")))); } return result; } /** * Returns an icon to be used in a frame. * * @return the icon */ public ImageIcon getIcon() { return ComponentHelper.getImageIcon(IMAGES_DIR + "/jython_small.png"); } /** * Returns a panel to be displayed with the AboutAction. * * @return the panel with some information on the scripting panel */ protected JPanel getAboutPanel() { JPanel result; JPanel panel; result = new JPanel(new BorderLayout()); result.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); // image result.add(new JLabel(ComponentHelper.getImageIcon(IMAGES_DIR + "/jython_medium.png")), BorderLayout.CENTER); // links panel = new JPanel(new GridLayout(5, 1)); panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); result.add(panel, BorderLayout.SOUTH); panel.add(new JLabel("Jython homepage")); panel.add(BrowserHelper.createLink("http://www.jython.org/", null)); panel.add(new JLabel(" ")); panel.add(new JLabel("Weka and Jython")); panel.add(BrowserHelper.createLink("http://weka.wikispaces.com/Using+Weka+from+Jython", null)); return result; } /** * Returns the title (without the filename). * * @return the plain title */ public String getPlainTitle() { return "Jython Console"; } /** * Returns an initialized script object. * * @param doc the document to use as basis * @return the initialized script */ protected Script newScript(Document doc) { return new JythonScript(doc); } /** * Displays the panel in a frame. * * @param args can take a file as first argument */ public static void main(String[] args) { showPanel(new JythonPanel(), args); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/scripting/JythonScript.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * JythonScript.java * Copyright (C) 2009-2012 University of Waikato, Hamilton, New Zealand */ package weka.gui.scripting; import java.io.File; import javax.swing.text.Document; import weka.core.Utils; import weka.core.scripting.Jython; import weka.gui.ExtensionFileFilter; /** * Represents a <a href="http://www.jython.org/" target="_blank">Jython</a> * script. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class JythonScript extends Script { /** for serialization. */ private static final long serialVersionUID = 3469648507172973169L; /** * Executes a Jython script in a thread. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public static class JythonThread extends ScriptThread { /** * Initializes the thread. * * @param owner the owning script * @param args the commandline arguments */ public JythonThread(Script owner, String[] args) { super(owner, args); } /** * Performs the actual run. */ @Override protected void doRun() { Jython jython; Class<?>[] classes; Object[] params; String argv; String arg; int i; classes = new Class[] { String.class }; params = new Object[] { m_Owner.getFilename().getPath() }; argv = "sys.argv = ['" + Utils.backQuoteChars(m_Owner.getFilename().getPath()) + "'"; for (i = 0; i < getArgs().length; i++) { arg = Utils.backQuoteChars(getArgs()[i]); argv += ", '" + arg + "'"; } argv += "]"; jython = new Jython(); // set commandline parameters jython.invoke("exec", new Class[] { String.class }, new Object[] { "import sys" }); jython .invoke("exec", new Class[] { String.class }, new Object[] { argv }); jython.invoke("execfile", classes, params); } } /** * Initializes the script. */ public JythonScript() { super(); } /** * Initializes the script. * * @param doc the document to use as basis */ public JythonScript(Document doc) { super(doc); } /** * Initializes the script. Automatically loads the specified file, if not * null. * * @param doc the document to use as basis * @param file the file to load (if not null) */ public JythonScript(Document doc, File file) { super(doc, file); } /** * Returns the extension filters for this type of script. * * @return the filters */ @Override public ExtensionFileFilter[] getFilters() { ExtensionFileFilter[] result; result = new ExtensionFileFilter[1]; result[0] = new ExtensionFileFilter(getDefaultExtension(), "Jython script (*" + getDefaultExtension() + ")"); return result; } /** * Returns the default extension. Gets automatically added to files if their * name doesn't end with this. * * @return the default extension (incl. the dot) */ @Override public String getDefaultExtension() { return ".py"; } /** * Returns whether scripts can be executed, i.e., Jython is present. * * @return true if scripts can be executed */ @Override protected boolean canExecuteScripts() { return Jython.isPresent(); } /** * Performs pre-execution checks. * <p/> * This method checks whether Jython is available (throws an exception if * not). * * @param args optional commandline arguments * @throws Exception if checks fail */ @Override protected void preCheck(String[] args) throws Exception { super.preCheck(args); if (!Jython.isPresent()) { throw new Exception("Jython classes are not present in CLASSPATH!"); } } /** * Returns a new thread to execute. * * @param args optional commandline arguments * @return the new thread object */ @Override public ScriptThread newThread(String[] args) { return new JythonThread(this, args); } /** * Runs the script from commandline. Use "-h" to list all options. * * @param args the commandline arguments * @throws Exception if execution fails */ public static void main(String[] args) throws Exception { runScript(new JythonScript(), args); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/scripting/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) 2009-2012 University of Waikato, Hamilton, New Zealand */ package weka.gui.scripting; import java.io.File; import java.io.Serializable; import java.util.Enumeration; import java.util.HashSet; import java.util.Iterator; import java.util.Vector; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.text.Document; import weka.core.Option; import weka.core.OptionHandler; import weka.core.SerializedObject; import weka.core.Utils; import weka.core.WekaException; import weka.gui.ExtensionFileFilter; import weka.gui.scripting.event.ScriptExecutionEvent; import weka.gui.scripting.event.ScriptExecutionEvent.Type; import weka.gui.scripting.event.ScriptExecutionListener; /** * A simple helper class for loading, saving scripts. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public abstract class Script implements OptionHandler, Serializable { /** for serialization. */ private static final long serialVersionUID = 5053328052680586401L; /** * The Thread for running a script. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public abstract static class ScriptThread extends Thread { /** the owning script. */ protected Script m_Owner; /** commandline arguments. */ protected String[] m_Args; /** whether the thread was stopped. */ protected boolean m_Stopped; /** * Initializes the thread. * * @param owner the owning script * @param args the commandline arguments */ public ScriptThread(Script owner, String[] args) { super(); m_Owner = owner; m_Args = args.clone(); } /** * Returns the owner. * * @return the owning script */ public Script getOwner() { return m_Owner; } /** * Returns the commandline args. * * @return the arguments */ public String[] getArgs() { return m_Args; } /** * Performs the actual run. */ protected abstract void doRun(); /** * Executes the script. */ @Override public void run() { m_Stopped = false; getOwner().notifyScriptFinishedListeners( new ScriptExecutionEvent(m_Owner, Type.STARTED)); try { doRun(); if (!m_Stopped) { getOwner().notifyScriptFinishedListeners( new ScriptExecutionEvent(m_Owner, Type.FINISHED)); } } catch (Exception e) { e.printStackTrace(); getOwner().notifyScriptFinishedListeners( new ScriptExecutionEvent(m_Owner, Type.ERROR, e)); } getOwner().m_ScriptThread = null; } /** * Stops the script execution. */ @SuppressWarnings("deprecation") public void stopScript() { if (isAlive()) { m_Stopped = true; try { stop(); } catch (Exception e) { // ignored } } } } /** the backup extension. */ public final static String BACKUP_EXTENSION = ".bak"; /** the document this script is a wrapper around. */ protected Document m_Document; /** the filename of the script. */ protected File m_Filename; /** the newline used on this platform. */ protected String m_NewLine; /** whether the script is modified. */ protected boolean m_Modified; /** the current script thread. */ protected transient ScriptThread m_ScriptThread; /** optional listeners when the script finishes. */ protected HashSet<ScriptExecutionListener> m_FinishedListeners; /** * Initializes the script. */ public Script() { this(null); } /** * Initializes the script. * * @param doc the document to use as basis */ public Script(Document doc) { this(doc, null); } /** * Initializes the script. Automatically loads the specified file, if not * null. * * @param doc the document to use as basis * @param file the file to load (if not null) */ public Script(Document doc, File file) { initialize(); m_Document = doc; if (m_Document != null) { m_Document.addDocumentListener(new DocumentListener() { @Override public void changedUpdate(DocumentEvent e) { m_Modified = true; } @Override public void insertUpdate(DocumentEvent e) { m_Modified = true; } @Override public void removeUpdate(DocumentEvent e) { m_Modified = true; } }); } if (file != null) { open(file); } } /** * Initializes the script. */ protected void initialize() { m_Filename = null; m_NewLine = System.getProperty("line.separator"); m_Modified = false; m_ScriptThread = null; m_FinishedListeners = new HashSet<ScriptExecutionListener>(); } /** * Returns an enumeration describing the available options. * * @return an enumeration of all the available options */ @Override public Enumeration<Option> listOptions() { return new Vector<Option>().elements(); } /** * Parses a given list of options. * * @param options the list of options as an array of strings * @throws Exception if an option is not supported */ @Override public void setOptions(String[] options) throws Exception { } /** * Gets the current settings of the script. * * @return an array of strings suitable for passing to setOptions */ @Override public String[] getOptions() { return new String[0]; } /** * Returns the extension filters for this type of script. * * @return the filters */ public abstract ExtensionFileFilter[] getFilters(); /** * Returns the default extension. Gets automatically added to files if their * name doesn't end with this. * * @return the default extension (incl. the dot) * @see #saveAs(File) */ public abstract String getDefaultExtension(); /** * Returns the current filename. * * @return the filename, null if no file loaded/saved */ public File getFilename() { return m_Filename; } /** * Returns the new line string in use. * * @return the new line string */ public String getNewLine() { return m_NewLine; } /** * Returns whether the script is modified. * * @return true if the script is modified */ public boolean isModified() { return m_Modified; } /** * Returns the content. * * @return the content or null in case of an error */ public String getContent() { String result; if (m_Document == null) { return ""; } try { synchronized (m_Document) { result = m_Document.getText(0, m_Document.getLength()); } } catch (Exception e) { e.printStackTrace(); result = null; } return result; } /** * Sets the content. * * @param value the new content */ public void setContent(String value) { if (m_Document == null) { return; } try { m_Document.insertString(0, value, null); } catch (Exception e) { e.printStackTrace(); } } /** * Checks whether the extension of the file is a known one. * * @param file the file to check * @return true if the exetnsion is known */ protected boolean checkExtension(File file) { boolean result; int i; int n; ExtensionFileFilter[] filters; String[] exts; result = false; filters = getFilters(); for (i = 0; i < filters.length; i++) { exts = filters[i].getExtensions(); for (n = 0; n < exts.length; n++) { if (file.getName().endsWith(exts[n])) { result = true; break; } } if (result) { break; } } return result; } /** * Empties the document. */ public void empty() { if (m_Document != null) { try { m_Document.remove(0, m_Document.getLength()); } catch (Exception e) { // ignored } } m_Modified = false; m_Filename = null; } /** * Tries to open the file. * * @param file the file to open * @return true if successfully read */ public boolean open(File file) { boolean result; String content; if (m_Document == null) { return true; } // Warn if extension unwknown if (!checkExtension(file)) { System.err.println("Extension of file '" + file + "' is unknown!"); } try { // clear old content m_Document.remove(0, m_Document.getLength()); // add new content content = ScriptUtils.load(file); if (content == null) { throw new WekaException("Error reading content of file '" + file + "'!"); } m_Document.insertString(0, content, null); m_Modified = false; m_Filename = file; result = true; } catch (Exception e) { e.printStackTrace(); try { m_Document.remove(0, m_Document.getLength()); } catch (Exception ex) { // ignored } result = false; m_Filename = null; } return result; } /** * Saves the file under with the current filename. * * @return true if successfully written */ public boolean save() { if (m_Filename == null) { return false; } else { return saveAs(m_Filename); } } /** * Saves the file under with the given filename (and updates the internal * filename). * * @param file the filename to write the content to * @return true if successfully written */ public boolean saveAs(File file) { boolean result; File backupFile; if (m_Document == null) { return true; } // correct extension? if (!checkExtension(file)) { file = new File(file.getPath() + getDefaultExtension()); } // backup previous file if (file.exists()) { backupFile = new File(file.getPath() + BACKUP_EXTENSION); try { ScriptUtils.copy(file, backupFile); } catch (Exception e) { e.printStackTrace(); } } // save current content try { result = ScriptUtils.save(file, m_Document.getText(0, m_Document.getLength())); m_Filename = file; m_Modified = false; } catch (Exception e) { e.printStackTrace(); result = false; } return result; } /** * Returns whether scripts can be executed. * * @return true if scripts can be executed */ protected abstract boolean canExecuteScripts(); /** * Returns a new thread to execute. * * @param args optional commandline arguments * @return the new thread object */ public abstract ScriptThread newThread(String[] args); /** * Performs pre-execution checks: * <ul> * <li>whether a script is currently running.</li> * <li>whether script has changed and needs saving</li> * <li>whether a filename is set (= empty content)</li> * </ul> * Throws exceptions if checks not met. * * @param args optional commandline arguments * @throws Exception if checks fail */ protected void preCheck(String[] args) throws Exception { if (m_ScriptThread != null) { throw new Exception("A script is currently running!"); } if (m_Modified) { throw new Exception("The Script has been modified!"); } if (m_Filename == null) { throw new Exception("The Script contains no content?"); } } /** * Executes the script. * * @param args optional commandline arguments */ protected void execute(String[] args) { m_ScriptThread = newThread(args); try { m_ScriptThread.start(); } catch (Exception e) { e.printStackTrace(); } } /** * Executes the script. * * @param args optional commandline arguments, can be null * @throws Exception if checks or execution fail */ public void start(String[] args) throws Exception { if (args == null) { args = new String[0]; } preCheck(args); execute(args); } /** * Stops the execution of the script. */ public void stop() { if (isRunning()) { m_ScriptThread.stopScript(); m_ScriptThread = null; notifyScriptFinishedListeners(new ScriptExecutionEvent(this, Type.STOPPED)); } } /** * Executes the script without loading it first. * * @param file the script to execute * @param args the commandline parameters for the script */ public void run(File file, String[] args) { Script script; try { script = (Script) new SerializedObject(this).getObject(); script.m_Filename = file; script.m_Modified = false; script.start(args); } catch (Exception e) { e.printStackTrace(); } } /** * Returns whether the script is still running. * * @return true if the script is still running */ public boolean isRunning() { return (m_ScriptThread != null); } /** * Adds the given listener to its internal list. * * @param l the listener to add */ public void addScriptFinishedListener(ScriptExecutionListener l) { m_FinishedListeners.add(l); } /** * Removes the given listener from its internal list. * * @param l the listener to remove */ public void removeScriptFinishedListener(ScriptExecutionListener l) { m_FinishedListeners.remove(l); } /** * Notifies all listeners. * * @param e the event to send to all listeners */ protected void notifyScriptFinishedListeners(ScriptExecutionEvent e) { Iterator<ScriptExecutionListener> iter; iter = m_FinishedListeners.iterator(); while (iter.hasNext()) { iter.next().scriptFinished(e); } } /** * Returns the content as string. * * @return the current content */ @Override public String toString() { String result; try { if (m_Document == null) { result = ""; } else { result = m_Document.getText(0, m_Document.getLength()); } } catch (Exception e) { result = ""; } return result.toString(); } /** * Make up the help string giving all the command line options. * * @param script the script to include options for * @return a string detailing the valid command line options */ protected static String makeOptionString(Script script) { StringBuffer result; Enumeration<Option> enm; Option option; result = new StringBuffer(""); result.append("\nHelp requested:\n\n"); result.append("-h or -help\n"); result.append("\tDisplays this help screen.\n"); result.append("-s <file>\n"); result.append("\tThe script to execute.\n"); enm = script.listOptions(); while (enm.hasMoreElements()) { option = enm.nextElement(); result.append(option.synopsis() + '\n'); result.append(option.description() + "\n"); } result.append("\n"); result.append("Any additional options are passed on to the script as\n"); result.append("command-line parameters.\n"); result.append("\n"); return result.toString(); } /** * Runs the specified script. All options that weren't "consumed" (like "-s" * for the script filename), will be used as commandline arguments for the * actual script. * * @param script the script object to use * @param args the commandline arguments * @throws Exception if execution fails */ public static void runScript(Script script, String[] args) throws Exception { String tmpStr; File scriptFile; Vector<String> options; int i; if (Utils.getFlag('h', args) || Utils.getFlag("help", args)) { System.out.println(makeOptionString(script)); } else { // process options tmpStr = Utils.getOption('s', args); if (tmpStr.length() == 0) { throw new WekaException("No script supplied!"); } else { scriptFile = new File(tmpStr); } script.setOptions(args); // remove empty elements from array options = new Vector<String>(); for (i = 0; i < args.length; i++) { if (args[i].length() > 0) { options.add(args[i]); } } // run script script.run(scriptFile, options.toArray(new String[options.size()])); } } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/scripting/ScriptUtils.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ScriptUtils.java * Copyright (C) 2009-2012 University of Waikato, Hamilton, New Zealand */ package weka.gui.scripting; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * A helper class for Script related stuff. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class ScriptUtils { /** * Copies or moves files and directories (recursively). * If targetLocation does not exist, it will be created. * <p/> * Original code from <a href="http://www.java-tips.org/java-se-tips/java.io/how-to-copy-a-directory-from-one-location-to-another-loc.html" target="_blank">Java-Tips.org</a>. * * @param sourceLocation the source file/dir * @param targetLocation the target file/dir * @param move if true then the source files/dirs get deleted * as soon as copying finished * @throws IOException if copying/moving fails */ protected static void copyOrMove(File sourceLocation, File targetLocation, boolean move) throws IOException { String[] children; int i; InputStream in; OutputStream out; byte[] buf; int len; if (sourceLocation.isDirectory()) { if (!targetLocation.exists()) targetLocation.mkdir(); children = sourceLocation.list(); for (i = 0; i < children.length; i++) { copyOrMove( new File(sourceLocation, children[i]), new File(targetLocation, children[i]), move); } if (move) sourceLocation.delete(); } else { in = new FileInputStream(sourceLocation); // do we need to append the filename? if (targetLocation.isDirectory()) out = new FileOutputStream(targetLocation.getAbsolutePath() + File.separator + sourceLocation.getName()); else out = new FileOutputStream(targetLocation); // Copy the content from instream to outstream buf = new byte[1024]; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); if (move) sourceLocation.delete(); } } /** * Copies the file/directory (recursively). * * @param sourceLocation the source file/dir * @param targetLocation the target file/dir * @throws IOException if copying fails */ public static void copy(File sourceLocation, File targetLocation) throws IOException { copyOrMove(sourceLocation, targetLocation, false); } /** * Moves the file/directory (recursively). * * @param sourceLocation the source file/dir * @param targetLocation the target file/dir * @throws IOException if moving fails */ public static void move(File sourceLocation, File targetLocation) throws IOException { copyOrMove(sourceLocation, targetLocation, true); } /** * Saves the content to a file. * * @param file the file to save to * @param content the content to save * @return true if successfully saved */ public static boolean save(File file, String content) { boolean result; BufferedWriter writer; writer = null; try { writer = new BufferedWriter(new FileWriter(file)); writer.write(content); writer.flush(); result = true; } catch (Exception e) { e.printStackTrace(); result = false; } finally { if (writer != null) { try { writer.close(); } catch (Exception e) { // ignored } } } return result; } /** * Tries to load the file and return its content. * * @param file the file to open * @return the content, otherwise null */ public static String load(File file) { StringBuffer result; BufferedReader reader; String line; String newLine; result = new StringBuffer(); newLine = System.getProperty("line.separator"); reader = null; try { // add new content reader = new BufferedReader(new FileReader(file)); while ((line = reader.readLine()) != null) { result.append(line); result.append(newLine); } } catch (Exception e) { e.printStackTrace(); result = null; } finally { if (reader != null) { try { reader.close(); } catch (Exception e) { // ignored } } } return ((result != null) ? result.toString() : 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/scripting/ScriptingPanel.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ScriptingPanel.java * Copyright (C) 2009-2012 University of Waikato, Hamilton, New Zealand */ package weka.gui.scripting; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.io.File; import java.io.InputStreamReader; import java.io.PipedInputStream; import java.io.PipedOutputStream; import java.io.PrintStream; import java.io.Reader; import java.util.HashSet; import java.util.Iterator; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JMenuBar; import javax.swing.JPanel; import javax.swing.JTextPane; import weka.core.Tee; import weka.gui.PropertyDialog; import weka.gui.ReaderToTextPane; import weka.gui.scripting.event.TitleUpdatedEvent; import weka.gui.scripting.event.TitleUpdatedListener; /** * Abstract ancestor for scripting panels. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public abstract class ScriptingPanel extends JPanel implements TitleUpdatedListener { /** for serialization. */ private static final long serialVersionUID = 7593091442691911406L; /** The new output stream for System.out. */ protected PipedOutputStream m_POO; /** The new output stream for System.err. */ protected PipedOutputStream m_POE; /** The thread that sends output from m_POO to the output box. */ protected ReaderToTextPane m_OutRedirector; /** The thread that sends output from m_POE to the output box. */ protected ReaderToTextPane m_ErrRedirector; /** whether debug mode is on. */ protected boolean m_Debug; /** the listeners for the changes in the title. */ protected HashSet<TitleUpdatedListener> m_TitleUpdatedListeners; /** * Default constructor. */ public ScriptingPanel() { super(); initialize(); initGUI(); initFinish(); } /** * For initializing member variables. */ protected void initialize() { m_POO = new PipedOutputStream(); m_POE = new PipedOutputStream(); m_Debug = false; m_TitleUpdatedListeners = new HashSet<TitleUpdatedListener>(); } /** * Sets up the GUI after initializing the members. * The JTextArea returned via <code>getOutputArea()</code> must be setup here. * * @see #initialize() * @see #getOutput() */ protected void initGUI() { } /** * Finishes up after initializing members and setting up the GUI. * Redirects stdout and stderr using <code>getOutputArea()</code>. * * @see #initialize() * @see #initGUI() * @see #getOutput() */ protected void initFinish() { // Redirect System.out to the text area try { PipedInputStream pio = new PipedInputStream(m_POO); Tee teeOut = new Tee(System.out); System.setOut(teeOut); teeOut.add(new PrintStream(m_POO)); Reader reader = new InputStreamReader(pio); m_OutRedirector = new ReaderToTextPane(reader, getOutput(), Color.BLACK); m_OutRedirector.start(); } catch (Exception e) { System.err.println("Error redirecting stdout"); e.printStackTrace(); m_OutRedirector = null; } // Redirect System.err to the text area try { PipedInputStream pie = new PipedInputStream(m_POE); Tee teeErr = new Tee(System.err); System.setErr(teeErr); teeErr.add(new PrintStream(m_POE)); Reader reader = new InputStreamReader(pie); m_ErrRedirector = new ReaderToTextPane(reader, getOutput(), Color.RED); m_ErrRedirector.start(); } catch (Exception e) { System.err.println("Error redirecting stderr"); e.printStackTrace(); m_ErrRedirector = null; } addTitleUpdatedListener(this); } /** * Returns an icon to be used in a frame. * * @return the icon */ public abstract ImageIcon getIcon(); /** * Returns the current title for the frame/dialog. * * @return the title */ public abstract String getTitle(); /** * Returns the text area that is used for displaying output on stdout * and stderr. * * @return the JTextArea */ public abstract JTextPane getOutput(); /** * Returns the menu bar to to be displayed in the frame. * * @return the menu bar, null if not applicable */ public abstract JMenuBar getMenuBar(); /** * Turns on/off debugging mode. * * @param value if true, debug mode is turned on */ public void setDebug(boolean value) { m_Debug = value; } /** * Returns whether debugging mode is on. * * @return true if debug mode is turned on */ public boolean getDebug() { return m_Debug; } /** * Adds the listener to the internal list. * * @param l the listener to add */ public void addTitleUpdatedListener(TitleUpdatedListener l) { m_TitleUpdatedListeners.add(l); } /** * Removes the listener from the internal list. * * @param l the listener to remove */ public void removeTitleUpdatedListener(TitleUpdatedListener l) { m_TitleUpdatedListeners.remove(l); } /** * Sends the event to all listeners for title updates. * * @param e the event to send */ protected void notifyTitleUpdatedListeners(TitleUpdatedEvent e) { Iterator<TitleUpdatedListener> iter; iter = m_TitleUpdatedListeners.iterator(); while (iter.hasNext()) iter.next().titleUpdated(e); } /** * Gets called when the title of the frame/dialog needs updating. * * @param event the event that got sent */ public void titleUpdated(TitleUpdatedEvent event) { if (PropertyDialog.getParentDialog(ScriptingPanel.this) != null) PropertyDialog.getParentDialog(ScriptingPanel.this).setTitle(getTitle()); else if (PropertyDialog.getParentFrame(ScriptingPanel.this) != null) PropertyDialog.getParentFrame(ScriptingPanel.this).setTitle(getTitle()); } /** * Displays the panel in a frame. * * @param panel the panel to display * @param args currently ignored commandline parameters */ public static void showPanel(ScriptingPanel panel, String[] args) { showPanel(panel, args, 800, 600); } /** * Displays the panel in a frame. * * @param panel the panel to display * @param args currently ignored commandline parameters * @param width the width of the frame * @param height the height of the frame */ public static void showPanel(ScriptingPanel panel, String[] args, int width, int height) { try { JFrame frame = new JFrame(); frame.getContentPane().setLayout(new BorderLayout()); frame.getContentPane().add(panel, BorderLayout.CENTER); frame.setJMenuBar(panel.getMenuBar()); frame.setSize(new Dimension(width, height)); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setTitle(panel.getTitle()); frame.setIconImage(panel.getIcon().getImage()); frame.setLocationRelativeTo(null); if ((args.length > 0) && (panel instanceof FileScriptingPanel)) ((FileScriptingPanel) panel).open(new File(args[0])); frame.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/scripting/SyntaxDocument.java
// Filename: SyntaxDocument.java // http://forums.sun.com/thread.jspa?threadID=743407&messageID=9497681 // http://www.dound.com/src/MultiSyntaxDocument.java /** * (C) camickr (primary author; java sun forums user) * (C) David Underhill * (C) 2009 University of Waikato, Hamilton, New Zealand */ package weka.gui.scripting; import java.awt.Color; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Toolkit; import java.util.HashMap; import java.util.Properties; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.DefaultEditorKit; import javax.swing.text.DefaultStyledDocument; import javax.swing.text.Element; import javax.swing.text.MutableAttributeSet; import javax.swing.text.SimpleAttributeSet; import javax.swing.text.StyleConstants; import javax.swing.text.TabSet; import javax.swing.text.TabStop; import weka.gui.visualize.VisualizeUtils; /** * Highlights syntax in a DefaultStyledDocument. Allows any number of keywords * to be formatted in any number of user-defined styles. * * @author camickr (primary author; java sun forums user) * @author David Underhill * @author FracPete (fracpete at waikato dot ac dot nz) - use of a properties * file to setup syntax highlighting instead of hard-coded */ public class SyntaxDocument extends DefaultStyledDocument { /** for serialization. */ protected static final long serialVersionUID = -3642426465631271381L; /** the maximum number of tabs. */ public static final int MAX_TABS = 35; /** the font family. */ public static final String DEFAULT_FONT_FAMILY = "monospaced"; /** the font size. */ public static final int DEFAULT_FONT_SIZE = 12; /** the attribute set for normal code. */ public static final SimpleAttributeSet DEFAULT_NORMAL; /** the attribute set for comments. */ public static final SimpleAttributeSet DEFAULT_COMMENT; /** the attribute set for strings. */ public static final SimpleAttributeSet DEFAULT_STRING; /** the attribute set for keywords. */ public static final SimpleAttributeSet DEFAULT_KEYWORD; static { DEFAULT_NORMAL = new SimpleAttributeSet(); StyleConstants.setForeground(DEFAULT_NORMAL, Color.BLACK); StyleConstants.setFontFamily(DEFAULT_NORMAL, DEFAULT_FONT_FAMILY); StyleConstants.setFontSize(DEFAULT_NORMAL, DEFAULT_FONT_SIZE); DEFAULT_COMMENT = new SimpleAttributeSet(); StyleConstants.setForeground(DEFAULT_COMMENT, Color.GRAY); StyleConstants.setFontFamily(DEFAULT_COMMENT, DEFAULT_FONT_FAMILY); StyleConstants.setFontSize(DEFAULT_COMMENT, DEFAULT_FONT_SIZE); DEFAULT_STRING = new SimpleAttributeSet(); StyleConstants.setForeground(DEFAULT_STRING, Color.RED); StyleConstants.setFontFamily(DEFAULT_STRING, DEFAULT_FONT_FAMILY); StyleConstants.setFontSize(DEFAULT_STRING, DEFAULT_FONT_SIZE); // default style for new keyword types DEFAULT_KEYWORD = new SimpleAttributeSet(); StyleConstants.setForeground(DEFAULT_KEYWORD, Color.BLUE); StyleConstants.setBold(DEFAULT_KEYWORD, false); StyleConstants.setFontFamily(DEFAULT_KEYWORD, DEFAULT_FONT_FAMILY); StyleConstants.setFontSize(DEFAULT_KEYWORD, DEFAULT_FONT_SIZE); } /** * The attribute type. */ public enum ATTR_TYPE { /** normal string. */ Normal, /** a comment. */ Comment, /** a quoted string. */ Quote; } /** the document. */ protected DefaultStyledDocument m_Self; /** the root element. */ protected Element m_RootElement; /** whether we're currently in a multi-line comment. */ protected boolean m_InsideMultiLineComment; /** the keywords. */ protected HashMap<String, MutableAttributeSet> m_Keywords; /** the delimiters. */ protected String m_Delimiters; /** the quote delimiter. */ protected String m_QuoteDelimiters; /** the quote escape. */ protected String m_QuoteEscape; /** the multi-line comment start. */ protected String m_MultiLineCommentStart; /** the multi-line comment end. */ protected String m_MultiLineCommentEnd; /** the single-line comment start. */ protected String m_SingleLineCommentStart; /** the start of a block. */ protected String m_BlockStart; /** the end of a block. */ protected String m_BlockEnd; /** the font size. */ protected int m_FontSize; /** the font name. */ protected String m_FontName; /** the background color. */ protected Color m_BackgroundColor; /** the number of spaces used for indentation. */ protected String m_Indentation; /** whether to add matching brackets. */ protected boolean m_AddMatchingEndBlocks; /** whether to use blanks instead of tabs. */ protected boolean m_UseBlanks; /** whether multi-line comments are enabled. */ protected boolean m_MultiLineComment; /** whether keywords are case-sensitive. */ protected boolean m_CaseSensitive; /** * Initializes the document. * * @param props the properties to obtain the setup from */ public SyntaxDocument(Properties props) { m_Self = this; m_RootElement = m_Self.getDefaultRootElement(); m_Keywords = new HashMap<String, MutableAttributeSet>(); m_FontSize = DEFAULT_FONT_SIZE; m_FontName = DEFAULT_FONT_FAMILY; putProperty(DefaultEditorKit.EndOfLineStringProperty, "\n"); setup(props); } /** * Sets up the document according to the properties. * * @param props the properties to use */ protected void setup(Properties props) { setDelimiters(props.getProperty("Delimiters", ";:{}()[]+-/%<=>!&|^~*")); setQuoteDelimiters(props.getProperty("QuoteDelimiters", "\"\'")); setQuoteEscape(props.getProperty("QuoteEscape", "\\")); setSingleLineCommentStart(props.getProperty("SingleLineCommentStart", "//")); setMultiLineComment(props.getProperty("MultiLineComment", "false").equals( "true")); setMultiLineCommentStart(props.getProperty("MultiLineCommentStart", "/*")); setMultiLineCommentEnd(props.getProperty("MultiLineCommentEnd", "*/")); setBlockStart(props.getProperty("BlockStart", "{")); setBlockEnd(props.getProperty("BlockEnd", "}")); setAddMatchingEndBlocks(props.getProperty("AddMatchingBlockEnd", "false") .equals("true")); setUseBlanks(props.getProperty("UseBlanks", "false").equals("true")); setCaseSensitive(props.getProperty("CaseSensitive", "true").equals("true")); addKeywords(props.getProperty("Keywords", "").trim().replaceAll(" ", "") .split(","), DEFAULT_KEYWORD); setTabs(Integer.parseInt(props.getProperty("Tabs", "2"))); setAttributeColor( DEFAULT_NORMAL, VisualizeUtils.processColour( props.getProperty("ForegroundColor", "black"), Color.BLACK)); setAttributeColor(DEFAULT_COMMENT, VisualizeUtils.processColour( props.getProperty("CommentColor", "gray"), Color.GRAY)); setAttributeColor(DEFAULT_STRING, VisualizeUtils.processColour( props.getProperty("StringColor", "red"), Color.RED)); setAttributeColor(DEFAULT_KEYWORD, VisualizeUtils.processColour( props.getProperty("KeywordColor", "blue"), Color.BLUE)); setBackgroundColor(VisualizeUtils.processColour( props.getProperty("BackgroundColor", "white"), Color.WHITE)); setFontName(props.getProperty("FontName", "monospaced")); setFontSize(Integer.parseInt(props.getProperty("FontSize", "12"))); setIndentationSize(Integer.parseInt(props.getProperty("Indentation", "2"))); } /** * Sets the font of the specified attribute. * * @param attr the attribute to apply this font to (normal, comment, string) * @param style font style (Font.BOLD, Font.ITALIC, Font.PLAIN) */ public void setAttributeFont(ATTR_TYPE attr, int style) { Font f = new Font(m_FontName, style, m_FontSize); if (attr == ATTR_TYPE.Comment) { setAttributeFont(DEFAULT_COMMENT, f); } else if (attr == ATTR_TYPE.Quote) { setAttributeFont(DEFAULT_STRING, f); } else { setAttributeFont(DEFAULT_NORMAL, f); } } /** * Sets the font of the specified attribute. * * @param attr attribute to apply this font to * @param f the font to use */ public static void setAttributeFont(MutableAttributeSet attr, Font f) { StyleConstants.setBold(attr, f.isBold()); StyleConstants.setItalic(attr, f.isItalic()); StyleConstants.setFontFamily(attr, f.getFamily()); StyleConstants.setFontSize(attr, f.getSize()); } /** * Sets the foreground (font) color of the specified attribute. * * @param attr the attribute to apply this font to (normal, comment, string) * @param c the color to use */ public void setAttributeColor(ATTR_TYPE attr, Color c) { if (attr == ATTR_TYPE.Comment) { setAttributeColor(DEFAULT_COMMENT, c); } else if (attr == ATTR_TYPE.Quote) { setAttributeColor(DEFAULT_STRING, c); } else { setAttributeColor(DEFAULT_NORMAL, c); } } /** * Sets the foreground (font) color of the specified attribute. * * @param attr attribute to apply this color to * @param c the color to use */ public static void setAttributeColor(MutableAttributeSet attr, Color c) { StyleConstants.setForeground(attr, c); } /** * Associates the keywords with a particular formatting style. * * @param keywords the tokens or words to format * @param attr how to format the keywords */ public void addKeywords(String[] keywords, MutableAttributeSet attr) { int i; for (i = 0; i < keywords.length; i++) { addKeyword(keywords[i], attr); } } /** * Associates a keyword with a particular formatting style. * * @param keyword the token or word to format * @param attr how to format keyword */ public void addKeyword(String keyword, MutableAttributeSet attr) { if (m_CaseSensitive) { m_Keywords.put(keyword, attr); } else { m_Keywords.put(keyword.toLowerCase(), attr); } } /** * Gets the formatting for a keyword. * * @param keyword the token or word to stop formatting * * @return how keyword is formatted, or null if no formatting is applied to it */ public MutableAttributeSet getKeywordFormatting(String keyword) { if (m_CaseSensitive) { return m_Keywords.get(keyword); } else { return m_Keywords.get(keyword.toLowerCase()); } } /** * Removes an association between a keyword with a particular formatting * style. * * @param keyword the token or word to stop formatting */ public void removeKeyword(String keyword) { if (m_CaseSensitive) { m_Keywords.remove(keyword); } else { m_Keywords.remove(keyword.toLowerCase()); } } /** * sets the number of characters per tab. * * @param charactersPerTab the characters per tab */ public void setTabs(int charactersPerTab) { Font f = new Font(m_FontName, Font.PLAIN, m_FontSize); @SuppressWarnings("deprecation") FontMetrics fm = Toolkit.getDefaultToolkit().getFontMetrics(f); int charWidth = fm.charWidth('w'); int tabWidth = charWidth * charactersPerTab; TabStop[] tabs = new TabStop[MAX_TABS]; for (int j = 0; j < tabs.length; j++) { tabs[j] = new TabStop((j + 1) * tabWidth); } TabSet tabSet = new TabSet(tabs); SimpleAttributeSet attributes = new SimpleAttributeSet(); StyleConstants.setTabSet(attributes, tabSet); int length = getLength(); setParagraphAttributes(0, length, attributes, false); } /** * Override to apply syntax highlighting after the document has been updated. * * @param offset the offset * @param str the string to insert * @param a the attribute set, can be null * @throws BadLocationException if offset is invalid */ @Override public void insertString(int offset, String str, AttributeSet a) throws BadLocationException { if (m_AddMatchingEndBlocks && (m_BlockStart.length() > 0) && str.equals(m_BlockStart)) { str = addMatchingBlockEnd(offset); } else if (m_UseBlanks && str.equals("\t")) { str = m_Indentation; } super.insertString(offset, str, a); processChangedLines(offset, str.length()); } /** * Applies syntax highlighting after the document has been updated. * * @param offset the offset of the deletion * @param length the length of the deletion * @throws BadLocationException if offsets are invalid */ @Override public void remove(int offset, int length) throws BadLocationException { super.remove(offset, length); processChangedLines(offset, 0); } /** * Determine how many lines have been changed, then apply highlighting to each * line. * * @param offset the offset of the changed lines * @param length the length of the change * @throws BadLocationException if offset is invalid */ public void processChangedLines(int offset, int length) throws BadLocationException { String content = m_Self.getText(0, m_Self.getLength()); // The lines affected by the latest document update int startLine = m_RootElement.getElementIndex(offset); int endLine = m_RootElement.getElementIndex(offset + length); // Make sure all comment lines prior to the start line are commented // and determine if the start line is still in a multi line comment if (getMultiLineComment()) { setInsideMultiLineComment(commentLinesBefore(content, startLine)); } // Do the actual highlighting for (int i = startLine; i <= endLine; i++) { applyHighlighting(content, i); } // Resolve highlighting to the next end multi line delimiter if (isMultiLineComment()) { commentLinesAfter(content, endLine); } else { highlightLinesAfter(content, endLine); } } /** * Highlight lines when a multi line comment is still 'open' (ie. matching end * delimiter has not yet been encountered). * * @param content the content to check * @param line the line number * @return true if there are comment lines before */ protected boolean commentLinesBefore(String content, int line) { int offset = m_RootElement.getElement(line).getStartOffset(); // Start of comment not found, nothing to do int startDelimiter = -1; if (getMultiLineComment()) { startDelimiter = lastIndexOf(content, getMultiLineCommentStart(), offset - 2); } if (startDelimiter < 0) { return false; } // Matching start/end of comment found, nothing to do int endDelimiter = indexOf(content, getMultiLineCommentEnd(), startDelimiter); if (endDelimiter < offset & endDelimiter != -1) { return false; } // End of comment not found, highlight the lines m_Self.setCharacterAttributes(startDelimiter, offset - startDelimiter + 1, DEFAULT_COMMENT, false); return true; } /** * Highlight comment lines to matching end delimiter. * * @param content the content to parse * @param line the line number */ protected void commentLinesAfter(String content, int line) { int offset = m_RootElement.getElement(line).getEndOffset(); // End of comment not found, nothing to do int endDelimiter = -1; if (getMultiLineComment()) { endDelimiter = indexOf(content, getMultiLineCommentEnd(), offset); } if (endDelimiter < 0) { return; } // Matching start/end of comment found, comment the lines int startDelimiter = lastIndexOf(content, getMultiLineCommentStart(), endDelimiter); if (startDelimiter < 0 || startDelimiter <= offset) { m_Self.setCharacterAttributes(offset, endDelimiter - offset + 1, DEFAULT_COMMENT, false); } } /** * Highlight lines to start or end delimiter. * * @param content the content to parse * @param line the line number * @throws BadLocationException if offsets are wrong */ protected void highlightLinesAfter(String content, int line) throws BadLocationException { int offset = m_RootElement.getElement(line).getEndOffset(); // Start/End delimiter not found, nothing to do int startDelimiter = -1; int endDelimiter = -1; if (getMultiLineComment()) { startDelimiter = indexOf(content, getMultiLineCommentStart(), offset); endDelimiter = indexOf(content, getMultiLineCommentEnd(), offset); } if (startDelimiter < 0) { startDelimiter = content.length(); } if (endDelimiter < 0) { endDelimiter = content.length(); } int delimiter = Math.min(startDelimiter, endDelimiter); if (delimiter < offset) { return; } // Start/End delimiter found, reapply highlighting int endLine = m_RootElement.getElementIndex(delimiter); for (int i = line + 1; i < endLine; i++) { Element branch = m_RootElement.getElement(i); Element leaf = m_Self.getCharacterElement(branch.getStartOffset()); AttributeSet as = leaf.getAttributes(); if (as.isEqual(DEFAULT_COMMENT)) { applyHighlighting(content, i); } } } /** * Parse the line to determine the appropriate highlighting. * * @param content the content to parse * @param line the line number * @throws BadLocationException if offsets are invalid */ protected void applyHighlighting(String content, int line) throws BadLocationException { int startOffset = m_RootElement.getElement(line).getStartOffset(); int endOffset = m_RootElement.getElement(line).getEndOffset() - 1; int lineLength = endOffset - startOffset; int contentLength = content.length(); if (endOffset >= contentLength) { endOffset = contentLength - 1; } // check for multi line comments // (always set the comment attribute for the entire line) if (getMultiLineComment()) { if (endingMultiLineComment(content, startOffset, endOffset) || isMultiLineComment() || startingMultiLineComment(content, startOffset, endOffset)) { m_Self.setCharacterAttributes(startOffset, endOffset - startOffset + 1, DEFAULT_COMMENT, false); return; } } // set normal attributes for the line m_Self .setCharacterAttributes(startOffset, lineLength, DEFAULT_NORMAL, true); // check for single line comment int index = content.indexOf(getSingleLineCommentStart(), startOffset); if ((index > -1) && (index < endOffset)) { m_Self.setCharacterAttributes(index, endOffset - index + 1, DEFAULT_COMMENT, false); endOffset = index - 1; } // check for tokens checkForTokens(content, startOffset, endOffset); } /** * Does this line contain the start of a multi-line comment. * * @param content the content to search * @param startOffset the start of the search * @param endOffset the end of the search * @return true if it contains the start delimiter * @throws BadLocationException if offsets are invalid */ protected boolean startingMultiLineComment(String content, int startOffset, int endOffset) throws BadLocationException { if (!getMultiLineComment()) { return false; } int index = indexOf(content, getMultiLineCommentStart(), startOffset); if ((index < 0) || (index > endOffset)) { return false; } else { setInsideMultiLineComment(true); return true; } } /** * Does this line contain the end delimiter of a multi-line comment. * * @param content the content to search * @param startOffset the start of the search * @param endOffset the end of the search * @return true if the line contains the end delimiter * @throws BadLocationException if offsets are invalid */ protected boolean endingMultiLineComment(String content, int startOffset, int endOffset) throws BadLocationException { if (!getMultiLineComment()) { return false; } int index = indexOf(content, getMultiLineCommentEnd(), startOffset); if ((index < 0) || (index > endOffset)) { return false; } else { setInsideMultiLineComment(false); return true; } } /** * We have found a start delimiter and are still searching for the end * delimiter. * * @return true if currently within a multi-line comment */ protected boolean isMultiLineComment() { return m_InsideMultiLineComment; } /** * Sets whether we're currently within a multi-line comment or not. * * @param value true if currently within a multi-line comment */ protected void setInsideMultiLineComment(boolean value) { m_InsideMultiLineComment = value; } /** * Parse the line for tokens to highlight. * * @param content the content to parse * @param startOffset the start position * @param endOffset the end position */ protected void checkForTokens(String content, int startOffset, int endOffset) { while (startOffset <= endOffset) { // skip the delimiters to find the start of a new token while (isDelimiter(content.substring(startOffset, startOffset + 1))) { if (startOffset < endOffset) { startOffset++; } else { return; } } // Extract and process the entire token if (isQuoteDelimiter(content.substring(startOffset, startOffset + 1))) { startOffset = getQuoteToken(content, startOffset, endOffset); } else { startOffset = getOtherToken(content, startOffset, endOffset); } } } /** * Searches for a quote token. * * @param content the content to search * @param startOffset the start of the search * @param endOffset the end of the search * @return the new position */ protected int getQuoteToken(String content, int startOffset, int endOffset) { String quoteDelimiter = content.substring(startOffset, startOffset + 1); String escapeString = escapeQuote(quoteDelimiter); int index; int endOfQuote = startOffset; // skip over the escape quotes in this quote index = content.indexOf(escapeString, endOfQuote + 1); while ((index > -1) && (index < endOffset)) { endOfQuote = index + 1; index = content.indexOf(escapeString, endOfQuote); } // now find the matching delimiter index = content.indexOf(quoteDelimiter, endOfQuote + 1); if ((index < 0) || (index > endOffset)) { endOfQuote = endOffset; } else { endOfQuote = index; } m_Self.setCharacterAttributes(startOffset, endOfQuote - startOffset + 1, DEFAULT_STRING, false); return endOfQuote + 1; } /** * Searches for a keyword token. * * @param content the content to search in * @param startOffset the position to start the search fromm * @param endOffset the position to end the search * @return the new position */ protected int getOtherToken(String content, int startOffset, int endOffset) { int endOfToken = startOffset + 1; while (endOfToken <= endOffset) { if (isDelimiter(content.substring(endOfToken, endOfToken + 1))) { break; } endOfToken++; } String token = content.substring(startOffset, endOfToken); // see if this token has a highlighting format associated with it MutableAttributeSet attr = getKeywordFormatting(token); if (attr != null) { m_Self.setCharacterAttributes(startOffset, endOfToken - startOffset, attr, false); } return endOfToken + 1; } /** * Assume the needle will the found at the start/end of the line. * * @param content the content to search * @param needle the string to look for * @param offset the offset to start at * @return the index */ protected int indexOf(String content, String needle, int offset) { int index; while ((index = content.indexOf(needle, offset)) != -1) { String text = getLine(content, index).trim(); if (text.startsWith(needle) || text.endsWith(needle)) { break; } else { offset = index + 1; } } return index; } /** * Assume the needle will the found at the start/end of the line. * * @param content the content search * @param needle what to look for * @param offset the offset to start * @return the index */ protected int lastIndexOf(String content, String needle, int offset) { int index; while ((index = content.lastIndexOf(needle, offset)) != -1) { String text = getLine(content, index).trim(); if (text.startsWith(needle) || text.endsWith(needle)) { break; } else { offset = index - 1; } } return index; } /** * Returns the line. * * @param content the content * @param offset the offset to start at * @return the line */ protected String getLine(String content, int offset) { int line = m_RootElement.getElementIndex(offset); Element lineElement = m_RootElement.getElement(line); int start = lineElement.getStartOffset(); int end = lineElement.getEndOffset(); return content.substring(start, end - 1); } /** * Checks whether the character is a delimiter. * * @param character the character to check * @return true if a delimiter */ public boolean isDelimiter(String character) { return Character.isWhitespace(character.charAt(0)) || (m_Delimiters.indexOf(character.charAt(0)) > -1); } /** * Checks whether the character is quote delimiter. * * @param character the character to check * @return true if a quote delimiter */ public boolean isQuoteDelimiter(String character) { return (m_QuoteDelimiters.indexOf(character.charAt(0)) > -1); } /** * Escapes the quote delimiter. * * @param quoteDelimiter the string to escape * @return the escaped string */ public String escapeQuote(String quoteDelimiter) { return m_QuoteEscape + quoteDelimiter; } /** * Adds the matching block end. * * @param offset the offset * @return the string after adding the matching block end * @throws BadLocationException if the offset is invalid */ protected String addMatchingBlockEnd(int offset) throws BadLocationException { StringBuffer result; StringBuffer whiteSpace = new StringBuffer(); int line = m_RootElement.getElementIndex(offset); int i = m_RootElement.getElement(line).getStartOffset(); while (true) { String temp = m_Self.getText(i, 1); if (temp.equals(" ") || temp.equals("\t")) { whiteSpace.append(temp); i++; } else { break; } } // assemble string result = new StringBuffer(); result.append(m_BlockStart); result.append("\n"); result.append(whiteSpace.toString()); if (m_UseBlanks) { result.append(m_Indentation); } else { result.append("\t"); } result.append("\n"); result.append(whiteSpace.toString()); result.append(m_BlockEnd); return result.toString(); } /** * gets the current font size. * * @return the font size */ public int getFontSize() { return m_FontSize; } /** * sets the current font size (affects all built-in styles). * * @param fontSize the size */ public void setFontSize(int fontSize) { m_FontSize = fontSize; StyleConstants.setFontSize(DEFAULT_NORMAL, fontSize); StyleConstants.setFontSize(DEFAULT_STRING, fontSize); StyleConstants.setFontSize(DEFAULT_COMMENT, fontSize); } /** * gets the current font family. * * @return the font name */ public String getFontName() { return m_FontName; } /** * sets the current font family (affects all built-in styles). * * @param fontName the font name */ public void setFontName(String fontName) { m_FontName = fontName; StyleConstants.setFontFamily(DEFAULT_NORMAL, fontName); StyleConstants.setFontFamily(DEFAULT_STRING, fontName); StyleConstants.setFontFamily(DEFAULT_COMMENT, fontName); } /** * Sets the number of blanks to use for indentation. * * @param value the number of blanks */ public void setIndentationSize(int value) { int i; m_Indentation = ""; for (i = 0; i < value; i++) { m_Indentation += " "; } } /** * Returns the number of blanks used for indentation. * * @return the number of blanks */ public int getIndentationSize() { return m_Indentation.length(); } /** * Sets the delimiter characters to use. * * @param value the characters */ public void setDelimiters(String value) { m_Delimiters = value; } /** * Returns the delimiter characters to use. * * @return the characters */ public String getDelimiters() { return m_Delimiters; } /** * Sets the quote delimiter characters to use. * * @param value the characters */ public void setQuoteDelimiters(String value) { m_QuoteDelimiters = value; } /** * Returns the quote delimiter characters to use. * * @return the characters */ public String getQuoteDelimiters() { return m_QuoteDelimiters; } /** * Sets the character to use for escaping a quote character. * * @param value the character */ public void setQuoteEscape(String value) { m_QuoteEscape = value; } /** * Returns the character for escaping a quote delimiter. * * @return the character */ public String getQuoteEscape() { return m_QuoteEscape; } /** * Sets the string that is the start of a single-line comment. * * @param value the string */ public void setSingleLineCommentStart(String value) { m_SingleLineCommentStart = value; } /** * Retrusn the single line comment start string. * * @return the start string */ public String getSingleLineCommentStart() { return m_SingleLineCommentStart; } /** * Sets the string that is the start of a multi-line comment. * * @param value the string */ public void setMultiLineCommentStart(String value) { m_MultiLineCommentStart = value; } /** * Returns the string that is the start of a multi-line comment. * * @return the string */ public String getMultiLineCommentStart() { return m_MultiLineCommentStart; } /** * Sets the string that is the end of a multi-line comment. * * @param value the string */ public void setMultiLineCommentEnd(String value) { m_MultiLineCommentEnd = value; } /** * Returns the end of a multi-line comment. * * @return the end string */ public String getMultiLineCommentEnd() { return m_MultiLineCommentEnd; } /** * Sets the string that is the start of a block. * * @param value the string */ public void setBlockStart(String value) { m_BlockStart = value; } /** * Returns the start of a block. * * @return the end string */ public String getBlockStart() { return m_BlockStart; } /** * Sets the string that is the end of a block. * * @param value the string */ public void setBlockEnd(String value) { m_BlockEnd = value; } /** * Returns the end of a block. * * @return the end string */ public String getBlockEnd() { return m_BlockEnd; } /** * Sets whether matching block ends are inserted or not. * * @param value if true then matching block ends are inserted */ public void setAddMatchingEndBlocks(boolean value) { m_AddMatchingEndBlocks = value; } /** * Returns whether matching block ends are inserted or not. * * @return true if matching block ends are inserted */ public boolean getAddMatchingEndBlocks() { return m_AddMatchingEndBlocks; } /** * Sets whether to use blanks instead of tabs. * * @param value if true then blanks are used instead of tabs */ public void setUseBlanks(boolean value) { m_UseBlanks = value; } /** * Returns whether blanks are used instead of tabs. * * @return true if blanks are used instead of tabs */ public boolean getUseBlanks() { return m_UseBlanks; } /** * Sets the background color. * * @param value the background color */ public void setBackgroundColor(Color value) { m_BackgroundColor = value; } /** * Returns the background color. * * @return the background color */ public Color getBackgroundColor() { return m_BackgroundColor; } /** * Sets whether to enable multi-line comments. * * @param value if true then multi-line comments are enabled */ public void setMultiLineComment(boolean value) { m_MultiLineComment = value; } /** * Returns whether multi-line comments are enabled. * * @return true if multi-line comments are enabled */ public boolean getMultiLineComment() { return m_MultiLineComment; } /** * Sets whether the keywords are case-sensitive or not. * * @param value if true then keywords are treated case-sensitive */ public void setCaseSensitive(boolean value) { m_CaseSensitive = value; } /** * Returns whether blanks are used instead of tabs. * * @return true if keywords are case-sensitive */ public boolean getCaseSensitive() { return m_CaseSensitive; } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/scripting
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/scripting/event/ScriptExecutionEvent.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ScriptExecutionEvent.java * Copyright (C) 2009-2012 University of Waikato, Hamilton, New Zealand */ package weka.gui.scripting.event; import java.util.EventObject; import weka.gui.scripting.Script; /** * Event that gets sent when a script is executed. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class ScriptExecutionEvent extends EventObject { /** for serialization. */ private static final long serialVersionUID = -8357216611114356632L; /** * Defines the type of event. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public enum Type { /** started execution. */ STARTED, /** finished normal. */ FINISHED, /** finished with error. */ ERROR, /** got stopped by user. */ STOPPED } /** the type of event. */ protected Type m_Type; /** optional additional information. */ protected Object m_Additional; /** * Initializes the event. * * @param source the script that triggered the event * @param type the type of finish */ public ScriptExecutionEvent(Script source, Type type) { this(source, type, null); } /** * Initializes the event. * * @param source the script that triggered the event * @param type the type of finish * @param additional additional information, can be null */ public ScriptExecutionEvent(Script source, Type type, Object additional) { super(source); m_Type = type; m_Additional = additional; } /** * Returns the script that triggered the event. * * @return the script */ public Script getScript() { return (Script) getSource(); } /** * Returns the type of event. * * @return the type */ public Type getType() { return m_Type; } /** * Returns whether additional information is available. * * @return true if additional information is available * @see #getAdditional() */ public boolean hasAdditional() { return (m_Additional != null); } /** * Returns the additional information. * * @return the additional information, can be null */ public Object getAdditional() { return m_Additional; } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/scripting
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/scripting/event/ScriptExecutionListener.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ScriptExecutionListener.java * Copyright (C) 2009-2012 University of Waikato, Hamilton, New Zealand */ package weka.gui.scripting.event; /** * For classes that want to be notified about changes in the script execution. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public interface ScriptExecutionListener { /** * Gets sent when a script execution changes. * * @param e the event */ public void scriptFinished(ScriptExecutionEvent e); }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/scripting
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/scripting/event/TitleUpdatedEvent.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * TitleUpdatedEvent.java * Copyright (C) 2009-2012 University of Waikato, Hamilton, New Zealand */ package weka.gui.scripting.event; import java.util.EventObject; import weka.gui.scripting.ScriptingPanel; /** * Event that gets send in case a scripting panel updates the title. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class TitleUpdatedEvent extends EventObject { /** for serialization. */ private static final long serialVersionUID = 4971569742479666535L; /** * Initializes the event. * * @param source the scripting panel that triggered the event */ public TitleUpdatedEvent(ScriptingPanel source) { super(source); } /** * Returns the scripting panel that triggered the event. Use the * <code>getTitle()</code> method for accessing the new title. * * @return the panel */ public ScriptingPanel getPanel() { return (ScriptingPanel) getSource(); } }
0
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/scripting
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/gui/scripting/event/TitleUpdatedListener.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * TitleUpdatedListener.java * Copyright (C) 2009-2012 University of Waikato, Hamilton, New Zealand */ package weka.gui.scripting.event; /** * Interface for frames/dialogs that listen to changes of the title. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public interface TitleUpdatedListener { /** * Gets called when the title of the frame/dialog needs updating. * * @param event the event that got sent */ public void titleUpdated(TitleUpdatedEvent event); }
0
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/AbstractCommand.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * AbstractCommand.java * Copyright (C) 2018 University of Waikato, Hamilton, NZ */ package weka.gui.simplecli; import weka.core.PluginManager; import weka.core.Utils; import weka.gui.SimpleCLIPanel; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Ancestor for command. * * @author FracPete (fracpete at waikato dot ac dot nz) */ public abstract class AbstractCommand implements Serializable, Comparable<AbstractCommand> { /** the owner. */ protected SimpleCLIPanel m_Owner; /** the available commands. */ protected static List<AbstractCommand> m_Commands; /** * Sets the owner. * * @param value the owner */ public void setOwner(SimpleCLIPanel value) { m_Owner = value; } /** * Returns the owner. * * @return the owner */ public SimpleCLIPanel getOwner() { return m_Owner; } /** * Returns the name of the command. * * @return the name */ public abstract String getName(); /** * Returns the help string (no indentation). * * @return the help */ public abstract String getHelp(); /** * Returns the one-liner help string for the parameters. * * @return the help, empty if none available */ public abstract String getParameterHelp(); /** * Executes the command with the given parameters. * * @param params the parameters for the command * @throws Exception if command fails */ protected abstract void doExecute(String[] params) throws Exception; /** * Expands the variables in the string. * * @param s the string to expand * @return the expanded string */ protected String expandVars(String s) throws Exception { String result; int pos; int lastPos; int endPos; String var; result = s; pos = -1; while (true) { lastPos = pos; pos = result.indexOf("${", lastPos); if (pos == -1) { break; } if (lastPos == pos) { throw new Exception("Failed to expand variables in string: " + s); } endPos = result.indexOf("}", pos); if (endPos == -1) { throw new Exception("Failed to expand variables in string: " + s); } var = result.substring(pos + 2, endPos); if (var.startsWith("env.")) { var = var.substring(4); if (System.getenv(var) != null) { result = result.substring(0, pos) + System.getenv(var) + result.substring(endPos + 1); } else { throw new Exception("Unknown environment variable: " + var); } } else { if (m_Owner.getVariables().containsKey(var)) { result = result.substring(0, pos) + m_Owner.getVariables().get(var) + result.substring(endPos + 1); } else { throw new Exception("Unknown variable: " + var); } } } return result; } /** * Executes the command with the given parameters. * Expands any variables in the parameters. * * @param params the parameters for the command * @throws Exception if command fails */ public void execute(String[] params) throws Exception { int i; if (m_Owner == null) throw new Exception("No SimpleCLI owner set!"); for (i = 0; i < params.length; i++) params[i] = expandVars(params[i]); doExecute(params); m_Owner = null; } /** * Performs comparison just on the name. * * @param o the other command to compare with * @return less than, equal to, or greater than 0 * @see #getName() */ @Override public int compareTo(AbstractCommand o) { return getName().compareTo(o.getName()); } /** * Returns true if the object is a command with the same name. * * @param obj the other object to compare with * @return true if the same */ @Override public boolean equals(Object obj) { return (obj instanceof AbstractCommand) && (compareTo((AbstractCommand) obj) == 0); } /** * Returns all available commands. * * @return the commands */ public static synchronized List<AbstractCommand> getCommands() { List<String> classes; List<AbstractCommand> cmds; AbstractCommand cmd; if (m_Commands == null) { // get commands classes = PluginManager.getPluginNamesOfTypeList(AbstractCommand.class.getName()); cmds = new ArrayList<>(); for (String cls: classes) { try { cmd = (AbstractCommand) Utils.forName(AbstractCommand.class, cls, new String[0]); cmds.add(cmd); } catch (Exception e) { System.err.println("Failed to instantiate SimpleCLI command: " + cls); e.printStackTrace(); } } Collections.sort(cmds); m_Commands = cmds; } return m_Commands; } /** * Locates the command for the given name. * * @param name the command to look for * @return the command, null if not found */ public static AbstractCommand getCommand(String name) { AbstractCommand result; result = null; for (AbstractCommand c: getCommands()) { if (c.getName().equals(name)) { result = c; break; } } 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/simplecli/Capabilities.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * Capabilities.java * Copyright (C) 2018 University of Waikato, Hamilton, NZ */ package weka.gui.simplecli; import weka.core.CapabilitiesHandler; import weka.core.OptionHandler; import java.util.ArrayList; import java.util.List; /** * Outputs the capabilities of the specified class. * * @author FracPete (fracpete at waikato dot ac dot nz) */ public class Capabilities extends AbstractCommand { /** * Returns the name of the command. * * @return the name */ @Override public String getName() { return "capabilities"; } /** * 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 { try { Object obj = Class.forName(params[0]).newInstance(); if (obj instanceof CapabilitiesHandler) { if (obj instanceof OptionHandler) { List<String> args = new ArrayList<>(); for (int i = 1; i < params.length; i++) { args.add(params[i]); } ((OptionHandler) obj).setOptions(args.toArray(new String[args.size()])); } weka.core.Capabilities caps = ((CapabilitiesHandler) obj).getCapabilities(); System.out.println(caps.toString().replace("[", "\n").replace("]", "\n")); } else { System.out.println("'" + params[0] + "' is not a " + CapabilitiesHandler.class.getName() + "!"); } } catch (Exception e) { System.out.println(e); } } }