diff --git a/ant/build.xml b/ant/build.xml index 00cb25d1..94f400ef 100644 --- a/ant/build.xml +++ b/ant/build.xml @@ -275,7 +275,7 @@ - - + - + @@ -372,7 +372,7 @@ - + @@ -389,7 +389,7 @@ - + - + diff --git a/ant/miniBuild.xml b/ant/miniBuild.xml index f69d7312..888140d7 100644 --- a/ant/miniBuild.xml +++ b/ant/miniBuild.xml @@ -197,7 +197,7 @@ - + - + diff --git a/pom.xml b/pom.xml index 283fa4d2..dd5f5d41 100644 --- a/pom.xml +++ b/pom.xml @@ -68,7 +68,7 @@ false true - eva2.client.EvAClient + eva2.gui.Main @@ -92,7 +92,7 @@ - eva2.client.EvAClient + eva2.gui.Main diff --git a/src/eva2/client/EvAClient.java b/src/eva2/gui/Main.java similarity index 87% rename from src/eva2/client/EvAClient.java rename to src/eva2/gui/Main.java index 63e5c100..b72db50f 100644 --- a/src/eva2/client/EvAClient.java +++ b/src/eva2/gui/Main.java @@ -1,24 +1,13 @@ -package eva2.client; +package eva2.gui; -/* - * Title: EvA2 - * Description: The main client class of the EvA framework. - * Copyright: Copyright (c) 2008 - * Company: University of Tuebingen, Computer - * Architecture - * - * @author Holger Ulmer, Felix Streichert, Hannes Planatscher - * @version: $Revision: 322 $ $Date: 2007-12-11 17:24:07 +0100 (Tue, 11 Dec 2007)$ - * $Author: mkron $ - */ import eva2.EvAInfo; -import eva2.gui.*; +import eva2.client.*; import eva2.optimization.OptimizationStateListener; import eva2.optimization.go.InterfaceOptimizationParameters; import eva2.optimization.modules.AbstractModuleAdapter; -import eva2.optimization.modules.OptimizationParameters; import eva2.optimization.modules.GenericModuleAdapter; import eva2.optimization.modules.ModuleAdapter; +import eva2.optimization.modules.OptimizationParameters; import eva2.optimization.stat.AbstractStatistics; import eva2.optimization.stat.InterfaceStatisticsListener; import eva2.optimization.stat.InterfaceStatisticsParameter; @@ -26,22 +15,22 @@ import eva2.tools.BasicResourceLoader; import eva2.tools.EVAERROR; import eva2.tools.ReflectPackage; import eva2.tools.StringTools; + +import javax.help.HelpSet; +import javax.help.JHelpContentViewer; +import javax.help.JHelpNavigator; +import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.net.URL; -import java.util.ArrayList; -import java.util.List; -import java.util.Set; +import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; -import javax.help.*; -import javax.swing.*; - /** * */ -public class EvAClient extends JFrame implements OptimizationStateListener { +public class Main extends JFrame implements OptimizationStateListener { /** * Generated serial version identifier. @@ -53,8 +42,8 @@ public class EvAClient extends JFrame implements OptimizationStateListener { private JDesktopPane desktopPane; private JPanel configurationPane; private JSplitPane horizontalSplit; - private Runnable initRnbl = null; - + private Runnable initRnbl = null; + //private EvAComAdapter comAdapter; private transient JMenuBar menuBar; private transient JExtMenu menuHelp; @@ -63,49 +52,49 @@ public class EvAClient extends JFrame implements OptimizationStateListener { private transient JExtMenu menuOptions; private JPanel statusBar; private transient JProgressBar progressBar; - + // Option private ExtAction actPreferences; private ExtAction actQuit; - + // LogPanel private LoggingPanel logPanel; - private static final Logger LOGGER = Logger.getLogger(EvAClient.class.getName()); - + private static final Logger LOGGER = Logger.getLogger(Main.class.getName()); + // Module: private ExtAction actModuleLoad; - // Hosts: + // Hosts: private ExtAction actHost; private ExtAction actAvailableHost; private ExtAction actKillHost; private ExtAction actKillAllHosts; private ModuleAdapter currentModuleAdapter = null; - + // Help: private ExtAction actHelp; private ExtAction actAbout; private ExtAction actLicense; - + // if not null, the module is loaded automatically and no other can be selected private String useDefaultModule = null; //"Genetic_Optimization"; private boolean showLoadModules = false; private boolean localMode = false; - + // measuring optimization runtime private long startTime = 0; // remember the module in use - private transient String currentModule = null; + private transient String currentModule = null; private boolean withGUI = true; private boolean withTreeView = false; private EvATabbedFrameMaker frameMaker = null; private Window parentWindow; - - private List superListenerList = null; - + + private java.util.List superListenerList = null; + private EvAComAdapter comAdapter; - + public void addOptimizationStateListener(OptimizationStateListener l) { if (superListenerList == null) { superListenerList = new ArrayList(); @@ -123,67 +112,67 @@ public class EvAClient extends JFrame implements OptimizationStateListener { /** * Constructor of GUI of EvA2. Works as client for the EvA2 server. Note - * that the EvAClient initialized multi-threaded for efficiency. Use {@link #awaitGuiInitialized()} + * that the Main initialized multi-threaded for efficiency. Use {@link #awaitGuiInitialized()} * to await full initialization if necessary. * */ - public EvAClient(final String hostName) { + public Main(final String hostName) { this(hostName, null, false, false); } /** * A constructor. Splash screen is optional, Gui is activated, no parent - * window. Note that the EvAClient initialized multi-threaded for + * window. Note that the Main initialized multi-threaded for * efficiency. Use {@link #awaitGuiInitialized()} to await full * initialization if necessary. * - * @see #EvAClient(String, Window, String, boolean, boolean, boolean) + * @see #EvAClient(String, java.awt.Window, String, boolean, boolean, boolean) * @param hostName * @param paramsFile * @param autorun * @param nosplash */ - public EvAClient(final String hostName, final String paramsFile, boolean autorun, boolean nosplash) { + public Main(final String hostName, final String paramsFile, boolean autorun, boolean nosplash) { this(hostName, null, paramsFile, null, autorun, nosplash, false, false); } /** - * A constructor with optional spash screen. Note that the EvAClient is + * A constructor with optional spash screen. Note that the Main is * initialized multi-threaded for efficiency. Use {@link #awaitGuiInitialized()} * to await full initialization if necessary. * - * @see #EvAClient(String, String, boolean, boolean) + * @see #Main(String, String, boolean, boolean) * * @param hostName * @param autorun * @param nosplash */ - public EvAClient(final String hostName, boolean autorun, boolean nosplash) { + public Main(final String hostName, boolean autorun, boolean nosplash) { this(hostName, null, autorun, nosplash); } /** - * A constructor with optional splash screen. Note that the EvAClient + * A constructor with optional splash screen. Note that the Main * initialized multi-threaded for efficiency. Use {@link #awaitGuiInitialized()} * to await full initialization if necessary. * - * @see #EvAClient(String, String, boolean, boolean) + * @see #Main(String, String, boolean, boolean) * @param hostName * @param paramsFile * @param autorun * @param noSplash * @param noGui */ - public EvAClient(final String hostName, String paramsFile, boolean autorun, boolean noSplash, boolean noGui, boolean withTreeView) { + public Main(final String hostName, String paramsFile, boolean autorun, boolean noSplash, boolean noGui, boolean withTreeView) { this(hostName, null, paramsFile, null, autorun, noSplash, noGui, withTreeView); } /** - * A constructor with optional splash screen. Note that the EvAClient + * A constructor with optional splash screen. Note that the Main * initialized multi-threaded for efficiency. Use {@link #awaitGuiInitialized()} * to await full initialization if necessary. * - * @see #EvAClient(String, String, boolean, boolean) + * @see #Main(String, String, boolean, boolean) * * @param hostName * @param paramsFile @@ -191,7 +180,7 @@ public class EvAClient extends JFrame implements OptimizationStateListener { * @param noSplash * @param noGui */ - public EvAClient(final String hostName, InterfaceOptimizationParameters goParams, boolean autorun, boolean noSplash, boolean noGui) { + public Main(final String hostName, InterfaceOptimizationParameters goParams, boolean autorun, boolean noSplash, boolean noGui) { this(hostName, null, null, goParams, autorun, noSplash, noGui, false); } @@ -206,7 +195,7 @@ public class EvAClient extends JFrame implements OptimizationStateListener { * @param noSplash * @param noGui */ - public EvAClient(final String hostName, final Window parent, final String paramsFile, final InterfaceOptimizationParameters goParams, final boolean autorun, final boolean noSplash, final boolean noGui) { + public Main(final String hostName, final Window parent, final String paramsFile, final InterfaceOptimizationParameters goParams, final boolean autorun, final boolean noSplash, final boolean noGui) { this(hostName, parent, paramsFile, goParams, autorun, noSplash, noGui, false); } @@ -215,7 +204,7 @@ public class EvAClient extends JFrame implements OptimizationStateListener { * locally or as client for the EvA2 server. GO parameters may be loaded * from a file (paramsFile) or given directly as a java instance. Both may * be null to start with standard parameters. If both are non null, the java - * instance has the higher priority. Note that the EvAClient initialized + * instance has the higher priority. Note that the Main initialized * multi-threaded for efficiency. Use {@link #awaitGuiInitialized()} to * await full initialization if necessary. * @@ -226,9 +215,9 @@ public class EvAClient extends JFrame implements OptimizationStateListener { * @param noSplash * @param noGui */ - public EvAClient(final String hostName, final Window parent, final String paramsFile, final InterfaceOptimizationParameters goParams, final boolean autorun, final boolean noSplash, final boolean noGui, final boolean showTreeView) { + public Main(final String hostName, final Window parent, final String paramsFile, final InterfaceOptimizationParameters goParams, final boolean autorun, final boolean noSplash, final boolean noGui, final boolean showTreeView) { clientInited = false; - final SplashScreen splashScreen = new SplashScreen(EvAInfo.splashLocation); + final eva2.gui.SplashScreen splashScreen = new eva2.gui.SplashScreen(EvAInfo.splashLocation); // preload some classes (into system cache) in a parallel thread preloadClasses(); @@ -261,7 +250,7 @@ public class EvAClient extends JFrame implements OptimizationStateListener { if (!autorun) { if (!noSplash) { try { - // if splashScreenTime has not passed, sleep some more + // if splashScreenTime has not passed, sleep some more if (wait < splashScreenTime) { Thread.sleep(splashScreenTime - wait); } @@ -294,7 +283,7 @@ public class EvAClient extends JFrame implements OptimizationStateListener { /** * Since the constructor runs multi-threaded for efficiency, this method may * be called to await the full initialization of a client instance. As soon - * as it returns, the EvAClient GUI is fully initialized. + * as it returns, the Main GUI is fully initialized. */ public void awaitClientInitialized() { if (initRnbl != null) { @@ -331,14 +320,14 @@ public class EvAClient extends JFrame implements OptimizationStateListener { } } - + /** * Set UI Font for all controls. - * + * * @param fontResource The FontUIResource for the controls - */ + */ private static void setUIFont(javax.swing.plaf.FontUIResource fontResource) { - java.util.Enumeration keys = UIManager.getDefaults().keys(); + Enumeration keys = UIManager.getDefaults().keys(); while (keys.hasMoreElements()) { Object key = keys.nextElement(); Object value = UIManager.get(key); @@ -355,9 +344,9 @@ public class EvAClient extends JFrame implements OptimizationStateListener { private void init(String hostName, String paramsFile, InterfaceOptimizationParameters goParams, final Window parent) { useDefaultModule = EvAInfo.propDefaultModule(); this.parentWindow = parent; - + setUIFont(new javax.swing.plaf.FontUIResource(Font.SANS_SERIF, 0, 11)); - + if (useDefaultModule != null) { useDefaultModule = useDefaultModule.trim(); if (useDefaultModule.length() < 1) { @@ -367,7 +356,7 @@ public class EvAClient extends JFrame implements OptimizationStateListener { if (withGUI) { GridBagConstraints gbConstraints = new GridBagConstraints(); - + /* Set Look and Feel */ try { //UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); @@ -375,18 +364,18 @@ public class EvAClient extends JFrame implements OptimizationStateListener { } catch (Exception ex) { LOGGER.log(Level.INFO, "Could not set Look&Feel", ex); } - + /* Create main frame with GridBagLayout */ setTitle(EvAInfo.productName); setLayout(new GridBagLayout()); setMinimumSize(new Dimension(800, 600)); /* Creates the desktopPane for Plot/Text Output */ - desktopPane = new JExtDesktopPane(); + desktopPane = new JExtDesktopPane(); JEFrameRegister.getInstance().setDesktopPane(desktopPane); /* Creates desktopPane ToolBar to show tiling buttons */ desktopToolBar = new JExtDesktopPaneToolBar((JExtDesktopPane) desktopPane); - + /* Pane to hold ToolBar + DesktopPane */ JPanel desktopPanel = new JPanel(new GridBagLayout()); GridBagConstraints desktopConst = new GridBagConstraints(); @@ -399,7 +388,7 @@ public class EvAClient extends JFrame implements OptimizationStateListener { desktopConst.fill = GridBagConstraints.BOTH; desktopConst.weighty = 1.0; desktopPanel.add(desktopPane, desktopConst); - + BasicResourceLoader loader = BasicResourceLoader.instance(); byte[] bytes = loader.getBytesFromResourceLocation(EvAInfo.iconLocation, true); // TODO: use setIconImages (for better support of multiple icons when changing programs etc.) @@ -410,7 +399,7 @@ public class EvAClient extends JFrame implements OptimizationStateListener { } catch (Exception e) { System.out.println("Error" + e.getMessage()); } - + logPanel = new LoggingPanel(LOGGER); logPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5)); @@ -421,9 +410,9 @@ public class EvAClient extends JFrame implements OptimizationStateListener { showLoadModules = false; // may be set to true again if default module couldnt be loaded } createActions(); - + setSize(800, 600); - + /* Create a new ConfigurationPanel (left side) */ configurationPane = new JPanel(new GridBagLayout()); gbConstraints.ipadx = 5; @@ -436,13 +425,13 @@ public class EvAClient extends JFrame implements OptimizationStateListener { gbConstraints.gridwidth = GridBagConstraints.RELATIVE; gbConstraints.gridheight = GridBagConstraints.RELATIVE; add(configurationPane, gbConstraints); - + /* SplitPane for desktopPanel and loggingPanel */ horizontalSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true); horizontalSplit.setTopComponent(desktopPanel); horizontalSplit.setBottomComponent(logPanel); - horizontalSplit.setDividerLocation(0.25); - horizontalSplit.setDividerSize(8); + horizontalSplit.setDividerLocation(0.25); + horizontalSplit.setDividerSize(8); horizontalSplit.setOneTouchExpandable(true); horizontalSplit.setResizeWeight(1.0); horizontalSplit.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY, 1)); @@ -454,33 +443,33 @@ public class EvAClient extends JFrame implements OptimizationStateListener { gbConstraints.gridwidth = GridBagConstraints.REMAINDER; gbConstraints.gridheight = GridBagConstraints.RELATIVE; add(horizontalSplit, gbConstraints); - + /* StatusBar of the main frame */ statusBar = new JPanel(new FlowLayout(FlowLayout.RIGHT)); JPanel statusBarControls = new JPanel(); statusBarControls.setLayout(new BoxLayout(statusBarControls, BoxLayout.LINE_AXIS)); - + statusBarControls.add(Box.createHorizontalGlue()); /* Logging settings drop down */ LoggingLevelLabel loggingOption = new LoggingLevelLabel(LOGGER); - + statusBarControls.add(loggingOption); - + statusBarControls.add(Box.createHorizontalStrut(5)); statusBarControls.add(new JSeparator(JSeparator.VERTICAL)); statusBarControls.add(Box.createHorizontalStrut(5)); - + /* Create ProgressBar and add it to the status bar */ statusBarControls.add(new JLabel("Progress")); statusBarControls.add(Box.createHorizontalStrut(5)); - + progressBar = new JProgressBar(); progressBar.setValue(0); progressBar.setStringPainted(true); statusBarControls.add(progressBar); - + statusBar.add(statusBarControls); - + gbConstraints.gridx = 0; gbConstraints.gridy = 2; gbConstraints.gridwidth = 2; @@ -488,11 +477,11 @@ public class EvAClient extends JFrame implements OptimizationStateListener { gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.anchor = GridBagConstraints.PAGE_END; add(statusBar, gbConstraints); - + setVisible(true); } if (useDefaultModule != null) { - /* + /* * if goParams are not defined and a params file is defined * try to load parameters from file */ @@ -509,12 +498,12 @@ public class EvAClient extends JFrame implements OptimizationStateListener { @Override public void windowClosing(final WindowEvent event) { int result = JOptionPane.showConfirmDialog( - EvAClient.this, + Main.this, "Do you really want to exit EvA2?", "Exit Application", JOptionPane.YES_NO_OPTION); if (result == JOptionPane.YES_OPTION) { - EvAClient.this.close(); + Main.this.close(); } } }); @@ -527,7 +516,7 @@ public class EvAClient extends JFrame implements OptimizationStateListener { if (!(configurationPane.isVisible())) { configurationPane.setVisible(true); } - + if (!(this.isVisible())) { Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); this.setLocation((int) ((screenSize.width - this.getWidth()) / 2), (int) ((screenSize.height - this.getHeight()) / 2.5)); @@ -536,13 +525,13 @@ public class EvAClient extends JFrame implements OptimizationStateListener { this.setVisible(true); this.setVisible(true); } - + // if this message is omitted, the stupid scroll pane runs to // the end of the last line which is ugly for a long class path LOGGER.info("EvA2 ready"); } } - + /** * Closes EvA2 workbench. Will not kill the JVM iff * the MATLAB environment variable has been set. @@ -572,7 +561,7 @@ public class EvAClient extends JFrame implements OptimizationStateListener { * The one and only main of the client program. Possible arguments: * --autorun immediately starts the optimization (with parameters loaded * from current directory if available. --hostname HOST: sets the hostname - * for the EvAClient to HOST --nosplash: skip the splash screen. --params + * for the Main to HOST --nosplash: skip the splash screen. --params * PFILE: load the optimization parameter from the serialized file PFILE * * @param args command line parameters @@ -587,21 +576,21 @@ public class EvAClient extends JFrame implements OptimizationStateListener { * command-line arguments! See above! */ System.setProperty("com.apple.mrj.application.apple.menu.about.name", EvAInfo.productName); - + System.setProperty("apple.awt.graphics.EnableQ2DX", "true"); System.setProperty("apple.laf.useScreenMenuBar", "true"); System.setProperty("com.apple.macos.smallTabs", "true"); System.setProperty("com.apple.macos.useScreenMenuBar", "true"); - + System.setProperty("com.apple.mrj.application.growbox.intrudes", "false"); System.setProperty("com.apple.mrj.application.live-resize", "true"); } /*==========================================================================*/ - - + + /* Available command-line parameters */ String[] keys = new String[]{ - "--help", "--autorun", "--nosplash", "--nogui", + "--help", "--autorun", "--nosplash", "--nogui", "--remotehost", "--params", "--treeView" }; /* Number of arguments per parameter */ @@ -630,7 +619,7 @@ public class EvAClient extends JFrame implements OptimizationStateListener { String hostName = StringTools.checkSingleStringArg(keys[4], values[4], arities[4] - 1); String paramsFile = StringTools.checkSingleStringArg(keys[5], values[5], arities[5] - 1); - new EvAClient(hostName, paramsFile, autorun, nosplash, nogui, treeView); + new Main(hostName, paramsFile, autorun, nosplash, nogui, treeView); } } @@ -643,12 +632,12 @@ public class EvAClient extends JFrame implements OptimizationStateListener { * optimization * @param windowListener additional window listener for client frame */ - public static EvAClient initClientGUI(OptimizationParameters goParams, + public static Main initClientGUI(OptimizationParameters goParams, InterfaceStatisticsListener statisticsListener, WindowListener windowListener, final Window parent) { - EvAClient evaClient; + Main evaClient; - evaClient = new EvAClient(null, parent, null, goParams, + evaClient = new Main(null, parent, null, goParams, false, true, false, false); // initializes GUI in the background // important: wait for GUI initialization before accessing any internal // settings: @@ -656,7 +645,7 @@ public class EvAClient extends JFrame implements OptimizationStateListener { // GUI is ready evaClient.addWindowListener(windowListener); // modify initial settings and activate output of all data: - evaClient.getStatistics().getStatisticsParameter().setOutputAllFieldsAsText(true); + evaClient.getStatistics().getStatisticsParameter().setOutputAllFieldsAsText(true); // add a data listener instance: evaClient.getStatistics().addDataListener(statisticsListener); @@ -718,16 +707,16 @@ public class EvAClient extends JFrame implements OptimizationStateListener { showLicense(); } }; - + actQuit = new ExtAction("&Quit", "Quit EvA2 workbench", KeyStroke.getKeyStroke(KeyEvent.VK_Q, Event.CTRL_MASK)) { @Override public void actionPerformed(final ActionEvent event) { - EvAClient.this.close(); + Main.this.close(); } }; - + actPreferences = new ExtAction("&Preferences", "Show preferences dialog", KeyStroke.getKeyStroke(KeyEvent.VK_P, Event.CTRL_MASK)) { @@ -736,7 +725,7 @@ public class EvAClient extends JFrame implements OptimizationStateListener { // ToDo } }; - + actHelp = new ExtAction("&Help", "Show help contents", KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0)) { @@ -744,7 +733,7 @@ public class EvAClient extends JFrame implements OptimizationStateListener { public void actionPerformed(final ActionEvent event) { // ToDo String helpHS = "EvA2Help/EvA2Help.hs"; - ClassLoader cl = EvAClient.class.getClassLoader(); + ClassLoader cl = Main.class.getClassLoader(); JHelpContentViewer helpPane; try { URL hsURL = HelpSet.findHelpSet(cl, helpHS); @@ -760,7 +749,7 @@ public class EvAClient extends JFrame implements OptimizationStateListener { } catch (Exception ee) { // Say what the exception really is LOGGER.log(Level.WARNING, "Could not open application help", ee); - } + } } }; } @@ -877,14 +866,14 @@ public class EvAClient extends JFrame implements OptimizationStateListener { frameMaker = newModuleAdapter.getModuleFrame(); /* This is the left TabPane on the main frame */ - JPanel moduleContainer = frameMaker.makePanel(); + JPanel moduleContainer = frameMaker.makePanel(); boolean wasVisible = configurationPane.isVisible(); configurationPane.setVisible(false); configurationPane.removeAll(); GridBagConstraints gbConstraints = new GridBagConstraints(); - + /* ToDo: Find a way to properly add the TreeView to the GOPanel */ if (withTreeView && (newModuleAdapter instanceof AbstractModuleAdapter)) { JComponent tree = null; @@ -896,8 +885,8 @@ public class EvAClient extends JFrame implements OptimizationStateListener { gbConstraints.weighty = 1.0; configurationPane.add(tree, gbConstraints); } - - + + gbConstraints.weightx = 1.0; gbConstraints.weighty = 0.0; gbConstraints.gridx = 0; @@ -906,13 +895,13 @@ public class EvAClient extends JFrame implements OptimizationStateListener { gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.anchor = GridBagConstraints.PAGE_START; add(frameMaker.getToolBar(), gbConstraints); - + GridBagConstraints gbConstraints2 = new GridBagConstraints(); gbConstraints2.gridx = 0; - gbConstraints2.gridy = 0; - gbConstraints2.fill = GridBagConstraints.VERTICAL; + gbConstraints2.gridy = 0; + gbConstraints2.fill = GridBagConstraints.VERTICAL; //gbConstraints2.gridheight = GridBagConstraints.REMAINDER; - gbConstraints2.weighty = 1.0; + gbConstraints2.weighty = 1.0; configurationPane.add(moduleContainer, gbConstraints2); configurationPane.validate(); } @@ -942,7 +931,7 @@ public class EvAClient extends JFrame implements OptimizationStateListener { * Create a tree view of an object based on EvATreeNode. It is encapsulated * in a JScrollPane. * - * @see EvATreeNode + * @see eva2.gui.EvATreeNode * @param title * @param object * @return @@ -954,7 +943,7 @@ public class EvAClient extends JFrame implements OptimizationStateListener { EvATreeSelectionListener treeListener = new EvATreeSelectionListener(root, goPanel.getEditor(), jtree); // hooks itself up as the tree listener. It reacts both to changes in the selection - // state of the tree (to update the parameter panel) and to changes in the + // state of the tree (to update the parameter panel) and to changes in the // parameters to update the tree return treeView; } @@ -1036,35 +1025,3 @@ public class EvAClient extends JFrame implements OptimizationStateListener { } } } -final class SplashScreen extends Frame { - - private static final long serialVersionUID = 1281793825850423095L; - private String imgLocation; - - public SplashScreen(String imgLoc) { - imgLocation = imgLoc; - } - - /** - * Show the splash screen to the end user. - * - *

Once this method returns, the splash screen is realized, which means - * that almost all work on the splash screen should proceed through the - * event dispatch thread. In particular, any call to - * dispose for the splash screen must be performed in the event - * dispatch thread. - */ - public void splash() { - JWindow splashWindow = new JWindow(this); - BasicResourceLoader loader = BasicResourceLoader.instance(); - byte[] bytes = loader.getBytesFromResourceLocation(imgLocation, true); - ImageIcon ii = new ImageIcon(Toolkit.getDefaultToolkit().createImage(bytes)); - JLabel splashLabel = new JLabel(ii); - - splashWindow.add(splashLabel); - splashWindow.pack(); - Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); - splashWindow.setLocation(screenSize.width / 2 - splashWindow.getSize().width / 2, screenSize.height / 2 - splashWindow.getSize().height / 2); - splashWindow.setVisible(true); - } -} \ No newline at end of file diff --git a/src/eva2/gui/SplashScreen.java b/src/eva2/gui/SplashScreen.java new file mode 100644 index 00000000..8fa6f111 --- /dev/null +++ b/src/eva2/gui/SplashScreen.java @@ -0,0 +1,51 @@ +package eva2.gui; + +/* + * Title: EvA2 + * Description: The main client class of the EvA framework. + * Copyright: Copyright (c) 2008 + * Company: University of Tuebingen, Computer + * Architecture + * + * @author Holger Ulmer, Felix Streichert, Hannes Planatscher + * @version: $Revision: 322 $ $Date: 2007-12-11 17:24:07 +0100 (Tue, 11 Dec 2007)$ + * $Author: mkron $ + */ +import eva2.tools.BasicResourceLoader; + +import java.awt.*; +import javax.swing.*; + + +class SplashScreen extends Frame { + + private static final long serialVersionUID = 1281793825850423095L; + private String imgLocation; + + public SplashScreen(String imgLoc) { + imgLocation = imgLoc; + } + + /** + * Show the splash screen to the end user. + * + *

Once this method returns, the splash screen is realized, which means + * that almost all work on the splash screen should proceed through the + * event dispatch thread. In particular, any call to + * dispose for the splash screen must be performed in the event + * dispatch thread. + */ + public void splash() { + JWindow splashWindow = new JWindow(this); + BasicResourceLoader loader = BasicResourceLoader.instance(); + byte[] bytes = loader.getBytesFromResourceLocation(imgLocation, true); + ImageIcon ii = new ImageIcon(Toolkit.getDefaultToolkit().createImage(bytes)); + JLabel splashLabel = new JLabel(ii); + + splashWindow.add(splashLabel); + splashWindow.pack(); + Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); + splashWindow.setLocation(screenSize.width / 2 - splashWindow.getSize().width / 2, screenSize.height / 2 - splashWindow.getSize().height / 2); + splashWindow.setVisible(true); + } +} \ No newline at end of file diff --git a/src/eva2/optimization/go/GOStandaloneVersion.java b/src/eva2/optimization/go/GOStandaloneVersion.java index cfaccd65..2ff23d08 100644 --- a/src/eva2/optimization/go/GOStandaloneVersion.java +++ b/src/eva2/optimization/go/GOStandaloneVersion.java @@ -166,7 +166,7 @@ public class GOStandaloneVersion implements InterfaceGOStandalone, InterfacePopu } this.m_O1 = (paraPanel.makePanel()); // TODO this is defunct anyways... (MK, 2010-03) -// EvAClient.setProperty("eva2.server.oa.go.Tools.InterfaceTest", "eva2.server.oa.go.Tools.Test1,eva2.server.oa.go.Tools.Test2"); +// Main.setProperty("eva2.server.oa.go.Tools.InterfaceTest", "eva2.server.oa.go.Tools.Test1,eva2.server.oa.go.Tools.Test2"); this.m_OptionsPanel = new JTabbedPane(); JParaPanel paraPanel2 = new JParaPanel(this.m_GO, "MyGUI"); this.m_O2 = (paraPanel2.makePanel()); diff --git a/src/eva2/optimization/operator/archiving/ArchivingNSGAII.java b/src/eva2/optimization/operator/archiving/ArchivingNSGAII.java index 9ec548de..7ce9aa12 100644 --- a/src/eva2/optimization/operator/archiving/ArchivingNSGAII.java +++ b/src/eva2/optimization/operator/archiving/ArchivingNSGAII.java @@ -39,25 +39,6 @@ public class ArchivingNSGAII extends ArchivingNSGA implements java.io.Serializab pop.SetArchive(new Population()); } - ////////////////////////////////////////////////////////////////////////////////////////////// - if (this.m_Debug && false) { - // plot the complete population - double[] tmpD = new double[2]; - tmpD[0] = 0; - tmpD[1] = 0; - this.m_Plot = new eva2.gui.Plot("Debug NSGAII", "Y1", "Y2", tmpD, tmpD); - System.out.println("Population size: " + pop.size()); - // plot the population - this.m_Plot.setUnconnectedPoint(0, 0, 11); - this.m_Plot.setUnconnectedPoint(1.05, 2.5, 11); - double[][] trueFitness = new double[pop.size()][]; - for (int i = 0; i < pop.size(); i++) { - trueFitness[i] = ((AbstractEAIndividual)pop.get(i)).getFitness(); - this.m_Plot.setUnconnectedPoint(trueFitness[i][0], trueFitness[i][1], 11); - } - } - ////////////////////////////////////////////////////////////////////////////////////////////// - // First merge the current population and the archive Population tmpPop = new Population(); tmpPop.addPopulation((Population)pop.getClone()); diff --git a/src/eva2/optimization/operator/archiving/ArchivingPESAII.java b/src/eva2/optimization/operator/archiving/ArchivingPESAII.java index 394f9fc9..4eedb070 100644 --- a/src/eva2/optimization/operator/archiving/ArchivingPESAII.java +++ b/src/eva2/optimization/operator/archiving/ArchivingPESAII.java @@ -48,36 +48,6 @@ public class ArchivingPESAII extends AbstractArchiving implements java.io.Serial } Population archive = pop.getArchive(); - //////////////////////////////////////////////////////////////////////////////////// - if (this.m_Debug) { - this.m_Plot = new eva2.gui.Plot("Debug SPEAII", "Y1", "Y2", true); - System.out.println("Population size: " + pop.size()); - // plot the population - this.m_Plot.setUnconnectedPoint(0, 0, 11); - this.m_Plot.setUnconnectedPoint(1.2, 2.0, 11); - Population tmpPop = new Population(); - tmpPop.addPopulation(pop); - tmpPop.addPopulation(pop.getArchive()); - double[][] trueFitness; - GraphPointSet mySet = new GraphPointSet(10, this.m_Plot.getFunctionArea()); - DPoint myPoint; - Chart2DDPointIconText tmp; - trueFitness = new double[archive.size()][]; - for (int i = 0; i < archive.size(); i++) { - trueFitness[i] = ((AbstractEAIndividual)archive.get(i)).getFitness(); - } - mySet.setConnectedMode(false); - for (int i = 0; i < trueFitness.length; i++) { - myPoint = new DPoint(trueFitness[i][0], trueFitness[i][1]); - tmp = new Chart2DDPointIconText(""); - tmp.setIcon(new Chart2DDPointIconCircle()); - myPoint.setIcon(tmp); - mySet.addDPoint(myPoint); - } - } - //////////////////////////////////////////////////////////////////////////////////// - - // test for each element in population if it // is dominating a element in the archive for (int i = 0; i < pop.size(); i++) { @@ -87,57 +57,7 @@ public class ArchivingPESAII extends AbstractArchiving implements java.io.Serial } //////////////////////////////////////////////////////////////////////////////////// - if (this.m_Debug) { - // first plot the grid - double[][] bounds; - double[][] trueFitness = new double[archive.size()][]; - // first calculate the bounds of the search space - bounds = new double[((AbstractEAIndividual)archive.get(0)).getFitness().length][2]; - for (int i = 0; i < bounds.length; i++) { - bounds[i][0] = Double.POSITIVE_INFINITY; - bounds[i][1] = Double.NEGATIVE_INFINITY; - } - for (int i = 0; i < archive.size(); i++) { - trueFitness[i] = ((AbstractEAIndividual)archive.get(i)).getFitness(); - for (int j = 0; j < trueFitness[i].length; j++) { - if (trueFitness[i][j] < bounds[j][0]) { - bounds[j][0] = trueFitness[i][j]; - } - if (trueFitness[i][j] > bounds[j][1]) { - bounds[j][1] = trueFitness[i][j]; - } - } - } - double gridx, gridy; - DLine line; - gridx = (bounds[0][1] - bounds[0][0])/this.m_GridSize; - gridy = (bounds[1][1] - bounds[1][0])/this.m_GridSize; - for (int i = 0; i <= this.m_GridSize; i++) { - line = new DLine(bounds[0][0]+gridx*i, bounds[1][0], bounds[0][0]+gridx*i, bounds[1][1], Color.BLUE); - this.m_Plot.getFunctionArea().addDElement(line); - line = new DLine(bounds[0][0], bounds[1][0]+gridy*i, bounds[0][1], bounds[1][0]+gridy*i, Color.BLUE); - this.m_Plot.getFunctionArea().addDElement(line); - } - - // now plot the archive with squeezing factor - int[] sqFactor = this.calculateSqueezeFactor(archive); - GraphPointSet mySet = new GraphPointSet(10, this.m_Plot.getFunctionArea()); - DPoint myPoint; - Chart2DDPointIconText tmp; - Chart2DDPointIconCircle tmp2; - mySet.setConnectedMode(false); - for (int i = 0; i < trueFitness.length; i++) { - myPoint = new DPoint(trueFitness[i][0], trueFitness[i][1]); - tmp = new Chart2DDPointIconText("SF:"+sqFactor[i]); - tmp2 = new Chart2DDPointIconCircle(); - tmp2.setFillColor(Color.GREEN); - tmp.setIcon(tmp2); - myPoint.setIcon(tmp); - mySet.addDPoint(myPoint); - } - } - //////////////////////////////////////////////////////////////////////////////////// // Now check whether there are individuals to remove int bigSqueeze, index; @@ -157,27 +77,6 @@ public class ArchivingPESAII extends AbstractArchiving implements java.io.Serial } archive.remove(index); } - //////////////////////////////////////////////////////////////////////////////////// - if (this.m_Debug) { - double[][] trueFitness; - GraphPointSet mySet = new GraphPointSet(10, this.m_Plot.getFunctionArea()); - DPoint myPoint; - Chart2DDPointIconCircle tmp; - trueFitness = new double[archive.size()][]; - for (int i = 0; i < archive.size(); i++) { - trueFitness[i] = ((AbstractEAIndividual)archive.get(i)).getFitness(); - } - mySet.setConnectedMode(false); - for (int i = 0; i < trueFitness.length; i++) { - myPoint = new DPoint(trueFitness[i][0], trueFitness[i][1]); - tmp = new Chart2DDPointIconCircle(); - tmp.setFillColor(Color.RED); - myPoint.setIcon(tmp); - mySet.addDPoint(myPoint); - } - } - //////////////////////////////////////////////////////////////////////////////////// - } /** This method will calculate the squeeze factor for a population diff --git a/src/eva2/optimization/operator/archiving/ArchivingSPEAII.java b/src/eva2/optimization/operator/archiving/ArchivingSPEAII.java index 84821ae8..37397849 100644 --- a/src/eva2/optimization/operator/archiving/ArchivingSPEAII.java +++ b/src/eva2/optimization/operator/archiving/ArchivingSPEAII.java @@ -48,16 +48,6 @@ public class ArchivingSPEAII extends AbstractArchiving implements java.io.Serial pop.SetArchive(new Population()); } - //////////////////////////////////////////////////////////////////////////////////// - if (this.m_Debug) { - this.m_Plot = new eva2.gui.Plot("Debug SPEAII", "Y1", "Y2", true); - System.out.println("Population size: " + pop.size()); - // plot the population - this.m_Plot.setUnconnectedPoint(0, 0, 11); - this.m_Plot.setUnconnectedPoint(1.2, 2.0, 11); - } - //////////////////////////////////////////////////////////////////////////////////// - // First merge the current population and the archive Population tmpPop = new Population(); tmpPop.addPopulation((Population)pop.getClone()); @@ -73,30 +63,6 @@ public class ArchivingSPEAII extends AbstractArchiving implements java.io.Serial // ((AbstractEAIndividual)tmpPop.get(i)).SetData("kthDistance", new Double(kthDistance[i])); // } - //////////////////////////////////////////////////////////////////////////////////// - if (this.m_Debug) { - double[][] trueFitness; - GraphPointSet mySet = new GraphPointSet(10, this.m_Plot.getFunctionArea()); - DPoint myPoint; - double tmp1, tmp2; - Chart2DDPointIconText tmp; - trueFitness = new double[tmpPop.size()][]; - for (int i = 0; i < tmpPop.size(); i++) { - trueFitness[i] = ((AbstractEAIndividual)tmpPop.get(i)).getFitness(); - } - mySet.setConnectedMode(false); - for (int i = 0; i < trueFitness.length; i++) { - myPoint = new DPoint(trueFitness[i][0], trueFitness[i][1]); - tmp1 = Math.round(RawFitness[i]*100)/(double)100; - tmp2 = Math.round(kthDistance[i]*100)/(double)100; - tmp = new Chart2DDPointIconText("RF:"+RawFitness[i]+"/ KD:"+tmp2); - tmp.setIcon(new Chart2DDPointIconCircle()); - myPoint.setIcon(tmp); - mySet.addDPoint(myPoint); - } - } - //////////////////////////////////////////////////////////////////////////////////// - // Now init the new archive Population archive = new Population(); archive.setTargetSize(pop.getArchive().getTargetSize()); @@ -110,54 +76,6 @@ public class ArchivingSPEAII extends AbstractArchiving implements java.io.Serial archive.add(tmpPop.get(i)); } } - /////////////////////////////////////////////////////////////////////////////// - -// double[][] p = this.showMay(archive); -// if ((true) && ((p[0][0] > d[0][0]) || (p[1][1] > d[1][1]))) { -// this.tz = true; -// this.calculateRawFitness(tmpPop); -// this.tz = false; -// this.m_Plot = new eva2.gui.Plot("Debug SPEAII", "Y1", "Y2"); -// // plot the population -// this.m_Plot.setUnconnectedPoint(0, 0, 11); -// this.m_Plot.setUnconnectedPoint(1.2, 2.0, 11); -// System.out.println("------------------Alert max!"); -// double[][] trueFitness; -// GraphPointSet mySet = new GraphPointSet(10, this.m_Plot.getFunctionArea()); -// DPoint myPoint; -// double tmp1, tmp2; -// Chart2DDPointIconText tmp; -// trueFitness = new double[tmpPop.size()][]; -// for (int i = 0; i < tmpPop.size(); i++) { -// trueFitness[i] = ((AbstractEAIndividual)tmpPop.get(i)).getFitness(); -// } -// mySet.setConnectedMode(false); -// for (int i = 0; i < trueFitness.length; i++) { -// myPoint = new DPoint(trueFitness[i][0], trueFitness[i][1]); -// tmp1 = Math.round(RawFitness[i]*100)/(double)100; -// tmp2 = Math.round(kthDistance[i]*100)/(double)100; -// tmp = new Chart2DDPointIconText(""+RawFitness[i]+"/"+tmp2); -// tmp.setIcon(new Chart2DDPointIconCircle()); -// myPoint.setIcon(tmp); -// mySet.addDPoint(myPoint); -// } -// -// mySet = new GraphPointSet(10, this.m_Plot.getFunctionArea()); -// Chart2DDPointIconCircle tmpC; -// trueFitness = new double[archive.size()][]; -// for (int i = 0; i < archive.size(); i++) { -// trueFitness[i] = ((AbstractEAIndividual)archive.get(i)).getFitness(); -// } -// mySet.setConnectedMode(false); -// for (int i = 0; i < trueFitness.length; i++) { -// myPoint = new DPoint(trueFitness[i][0], trueFitness[i][1]); -// tmpC = new Chart2DDPointIconCircle(); -// tmpC.setFillColor(Color.GREEN); -// myPoint.setIcon(tmpC); -// mySet.addDPoint(myPoint); -// } -// } - ///////////////////////////////////////////////////////////////////////////////////// // if there is some place left let's add some more int currentLevel = 0; @@ -169,26 +87,6 @@ public class ArchivingSPEAII extends AbstractArchiving implements java.io.Serial } } } - //////////////////////////////////////////////////////////////////////////////////// - if (this.m_Debug) { - double[][] trueFitness; - GraphPointSet mySet = new GraphPointSet(10, this.m_Plot.getFunctionArea()); - DPoint myPoint; - Chart2DDPointIconCircle tmp; - trueFitness = new double[archive.size()][]; - for (int i = 0; i < archive.size(); i++) { - trueFitness[i] = ((AbstractEAIndividual)archive.get(i)).getFitness(); - } - mySet.setConnectedMode(false); - for (int i = 0; i < trueFitness.length; i++) { - myPoint = new DPoint(trueFitness[i][0], trueFitness[i][1]); - tmp = new Chart2DDPointIconCircle(); - tmp.setFillColor(Color.GREEN); - myPoint.setIcon(tmp); - mySet.addDPoint(myPoint); - } - } - //////////////////////////////////////////////////////////////////////////////////// // Here i want to remove surplus individuals *pff* // So the basic idea is to search on the highes level of @@ -215,72 +113,8 @@ public class ArchivingSPEAII extends AbstractArchiving implements java.io.Serial archive.remove(ICurSma); } - //////////////////////////////////////////////////////////////////////////////////// - if (this.m_Debug) { - double[][] trueFitness; - GraphPointSet mySet = new GraphPointSet(10, this.m_Plot.getFunctionArea()); - DPoint myPoint; - Chart2DDPointIconCircle tmp; - trueFitness = new double[archive.size()][]; - for (int i = 0; i < archive.size(); i++) { - trueFitness[i] = ((AbstractEAIndividual)archive.get(i)).getFitness(); - } - mySet.setConnectedMode(false); - for (int i = 0; i < trueFitness.length; i++) { - myPoint = new DPoint(trueFitness[i][0], trueFitness[i][1]); - tmp = new Chart2DDPointIconCircle(); - tmp.setFillColor(Color.RED); - myPoint.setIcon(tmp); - mySet.addDPoint(myPoint); - } - } - //////////////////////////////////////////////////////////////////////////////////// pop.SetArchive(archive); - // if there are too many let's remove the surplus - // i could simply remove the individuals with the - // smallest distance to a neighbor selecting from - // all individuals or just selecting from the ones - // in the range of currentLevel to currentLevel+1 -// while (archive.size() > archive.getPopulationSize()) { -// // now it's time to use the <=d operator e.g. -// // remove the individuals that are to close -// // to thier neighbours -// double[][] dist -// -// } - -// -// // might sound stuid but as far as i understood this -// // i'll simply select the n best ones regarding SPEAFit -// Population archive = (Population)pop.getArchive().clone(); -// archive.clear(); -// double smallest; -// int index; -// for (int i = 0; i < archive.getPopulationSize(); i++) { -// // find the smallest one -// index = -1; -// smallest = Double.POSITIVE_INFINITY; -// for (int j = 0; j < SPEAFit.length; j++) { -// if (smallest > SPEAFit[j]) { -// smallest = SPEAFit[j]; -// index = j; -// } -// } -// -// if (index > -1) { -// SPEAFit[index] = Double.POSITIVE_INFINITY; -// archive.add(tmpPop.get(index)); -// } -// } -// if (this.m_Debug) { -// // plot the archive -// double[] tmpD; -// for (int i = 0; i < archive.size(); i++) { -// tmpD = ((AbstractEAIndividual)archive.get(i)).getFitness(); -// this.m_Plot.setUnconnectedPoint(tmpD[0], tmpD[1], 12); -// } -// } } private double[][] showMay(Population pop) { @@ -539,26 +373,6 @@ public class ArchivingSPEAII extends AbstractArchiving implements java.io.Serial ((AbstractEAIndividual)pop.get(i)).putData("SPEAFit", new Double(SPEAResult[i])); } - if (this.m_Debug && this.m_Plot != null) { - //System.out.println("k: " + k); - GraphPointSet mySet = new GraphPointSet(10, this.m_Plot.getFunctionArea()); - DPoint myPoint; - double tmp1, tmp2; - Chart2DDPointIconText tmp; - - mySet.setConnectedMode(false); - for (int i = 0; i < trueFitness.length; i++) { - - myPoint = new DPoint(trueFitness[i][0], trueFitness[i][1]); - tmp1 = Math.round(SPEAResult[i]*100)/(double)100; - tmp2 = Math.round(D[i]*100)/(double)100; - tmp = new Chart2DDPointIconText(""+SPEAStrength[i]+"/"+SPEAFitness[i]); - tmp.setIcon(new Chart2DDPointIconCircle()); - myPoint.setIcon(tmp); - mySet.addDPoint(myPoint); - } - } - // Puh! return SPEAResult; } diff --git a/src/eva2/optimization/problems/ERPStarter.java b/src/eva2/optimization/problems/ERPStarter.java index 19432881..e982bc94 100644 --- a/src/eva2/optimization/problems/ERPStarter.java +++ b/src/eva2/optimization/problems/ERPStarter.java @@ -2,7 +2,7 @@ package eva2.optimization.problems; import eva2.OptimizerFactory; import eva2.OptimizerRunnable; -import eva2.client.EvAClient; +import eva2.gui.Main; import eva2.gui.BeanInspector; import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.modules.OptimizationParameters; @@ -85,7 +85,7 @@ public class ERPStarter { // Instantiate optimization OptimizationParameters params = new OptimizationParameters(opt, erp, new EvaluationTerminator(maxEvals)); if (startGUI) { - EvAClient.initClientGUI(params, null, null, null); + Main.initClientGUI(params, null, null, null); } else { OptimizerRunnable rnbl = new OptimizerRunnable(params, new StatisticsStandalone(outputFilePrefix, 1, 3, true), false); // actually start the optimization diff --git a/src/eva2/optimization/stat/AbstractStatistics.java b/src/eva2/optimization/stat/AbstractStatistics.java index f46358e1..eb666c77 100644 --- a/src/eva2/optimization/stat/AbstractStatistics.java +++ b/src/eva2/optimization/stat/AbstractStatistics.java @@ -13,6 +13,7 @@ import eva2.tools.StringSelection; import eva2.tools.StringTools; import eva2.tools.ToolBox; import eva2.tools.math.Mathematics; + import java.io.File; import java.io.FileOutputStream; import java.io.PrintWriter; @@ -21,654 +22,637 @@ import java.util.*; /** * An abstract class handling statistics. Most important stuff happens in startOptPerformed, stopOptPerformed - * and createNextGenerationPerformed. Any measures (run based or multi-run based) are reset in startOptPerformed, + * and createNextGenerationPerformed. Any measures (run based or multi-run based) are reset in startOptPerformed, * updated per iteration in createNextGenerationPerformed and reported to listeners in stopOptPerformed. - * Several different verbosity levels are regarded. - * The method plotCurrentResults should be implemented to plot further results per iteration. - * + * Several different verbosity levels are regarded. + * The method plotCurrentResults should be implemented to plot further results per iteration. + *

* All displayable data is now routed through a single pipeline, which consists in a * list of Objects assembled in the getOutputValues method. This allows all simple data types which are * provided by the external informer instances to be handled uniformly to the internally collected data, and * thus they can be plotted and text-dumped in the same manner. * Basic fields are identified by the enum GraphSelectionEnum and are available independently of additional * informer instances. - * + *

* Depending on the field selection state and the informers, the list of data fields is dynamically altered, - * however changes during a multi-run are ignored, since the potential of inconsistencies is too high. - * - * Listeners implementing InterfaceTextListener receive String output (human readable). + * however changes during a multi-run are ignored, since the potential of inconsistencies is too high. + *

+ * Listeners implementing InterfaceTextListener receive String output (human readable). * Listeners implementing InterfaceStatisticsListener receive the raw data per iteration. - * - * @see StatsParameter - * @author mkron * + * @author mkron + * @see StatsParameter */ public abstract class AbstractStatistics implements InterfaceTextListener, InterfaceStatistics { - private transient PrintWriter resultOut; - public final static boolean TRACE = false; - protected InterfaceStatisticsParameter m_StatsParams; - - /** - * Keep track of all intermediate fitness values, best, avg. and worst, averaging over all runs - * for final output, "refining" the multi run data. - * If the runs have different lengths, the shortest of all defines the length - * of averaged data to be displayed. This mechanism expects that createNextGenerationPerformed - * comes in regular intervals (in terms of function calls performed). This needs to be emulated - * by dynamic population optimizers, also due to the graph output. - */ - private boolean refineMultiRuns = true; -// private ArrayList meanCollection; - private ArrayList finalObjectData; - private ArrayList sumDataCollection; // collect summed-up data of multiple runs indexed per iteration - protected Object[] currentStatObjectData = null; // the raw Object data collected in an iteration - protected Double[] currentStatDoubleData = null; // the parsed doubles collected in an iteration (or null for complex data fields) - protected String[] currentStatHeader = null; // the header Strings of the currently provided data - protected String[] currentStatMetaInfo = null; // meta information on the statistical data - private Double[] statDataSumOverAll = null; + private transient PrintWriter resultOut; + protected InterfaceStatisticsParameter m_StatsParams; + + /** + * Keep track of all intermediate fitness values, best, avg. and worst, averaging over all runs + * for final output, "refining" the multi run data. + * If the runs have different lengths, the shortest of all defines the length + * of averaged data to be displayed. This mechanism expects that createNextGenerationPerformed + * comes in regular intervals (in terms of function calls performed). This needs to be emulated + * by dynamic population optimizers, also due to the graph output. + */ + private boolean refineMultiRuns = true; + // private ArrayList meanCollection; + private ArrayList finalObjectData; + private ArrayList sumDataCollection; // collect summed-up data of multiple runs indexed per iteration + protected Object[] currentStatObjectData = null; // the raw Object data collected in an iteration + protected Double[] currentStatDoubleData = null; // the parsed doubles collected in an iteration (or null for complex data fields) + protected String[] currentStatHeader = null; // the header Strings of the currently provided data + protected String[] currentStatMetaInfo = null; // meta information on the statistical data + private Double[] statDataSumOverAll = null; // , lastAdditionalInfoSums=null; - // say whether the object should be written to a file every time - private boolean saveParams = true; - private boolean firstPlot = true; - private int iterationCounter = 0; - // show this many iterations of the averaged performance after a full multi-run - private int showAvgIntervals = 9; - - // collect data - protected int functionCalls; - protected int functionCallSum; - protected int convergenceCnt; - protected int feasibleFoundAfter; - protected int numOfRunsFeasibleFound; - protected double feasibleFoundAfterSum; - protected int optRunsPerformed; - protected double[] currentBestFit; - protected double[] currentBestFeasibleFit; -// protected double[] meanBestFeasibleFit; - protected double[] currentMeanFit; - protected double[] currentWorstFit; -// protected double[] meanBestOfRunFitness; - protected double currentAvgEucDistInPop, currentMaxEucDistInPop; - protected double currentAvgPopDistMetric, currentMaxPopDistMetric; - protected IndividualInterface bestCurrentIndy, bestOfRunIndy, bestOfRunFeasibleIndy, bestFeasibleAllRuns, bestIndyAllRuns; + // say whether the object should be written to a file every time + private boolean saveParams = true; + private boolean firstPlot = true; + private int iterationCounter = 0; + // show this many iterations of the averaged performance after a full multi-run + private int showAvgIntervals = 9; - // collect feasible results of a run - private ArrayList runBestFeasibleList; - private ArrayList runBestFitList; - - private transient ArrayList textListeners; - private transient List dataListeners = null; + // collect data + protected int functionCalls; + protected int functionCallSum; + protected int convergenceCnt; + protected int feasibleFoundAfter; + protected int numOfRunsFeasibleFound; + protected double feasibleFoundAfterSum; + protected int optRunsPerformed; + protected double[] currentBestFit; + protected double[] currentBestFeasibleFit; + // protected double[] meanBestFeasibleFit; + protected double[] currentMeanFit; + protected double[] currentWorstFit; + // protected double[] meanBestOfRunFitness; + protected double currentAvgEucDistInPop, currentMaxEucDistInPop; + protected double currentAvgPopDistMetric, currentMaxPopDistMetric; + protected IndividualInterface bestCurrentIndy, bestOfRunIndy, bestOfRunFeasibleIndy, bestFeasibleAllRuns, bestIndyAllRuns; + + // collect feasible results of a run + private ArrayList runBestFeasibleList; + private ArrayList runBestFitList; + + private transient ArrayList textListeners; + private transient List dataListeners = null; + + private List lastInformerList = null; + private PopulationInterface lastSols = null; + private String textFieldDelimiter = "\t"; + private int defaultFitCriterion = 0; // TODO this might be a user chosen int - or even more elegantly, a MOSOConverter + + protected StringSelection lastFieldSelection = null; // store the graph selection at the beginning of a multi-run + protected boolean lastIsShowFull = false; // store the "show full text" stats property at the beginning of a multi-run + + public AbstractStatistics() { + firstPlot = true; + functionCalls = 0; + functionCallSum = 0; + convergenceCnt = 0; + optRunsPerformed = 0; + iterationCounter = 0; + textListeners = new ArrayList(); + } - private List lastInformerList = null; - private PopulationInterface lastSols = null; - private String textFieldDelimiter = "\t"; - private int defaultFitCriterion = 0; // TODO this might be a user chosen int - or even more elegantly, a MOSOConverter - - protected StringSelection lastFieldSelection = null; // store the graph selection at the beginning of a multi-run - protected boolean lastIsShowFull = false; // store the "show full text" stats property at the beginning of a multi-run - - public AbstractStatistics() { - firstPlot = true; - functionCalls = 0; - functionCallSum = 0; - convergenceCnt = 0; - optRunsPerformed = 0; - iterationCounter = 0; - textListeners = new ArrayList(); - } - @Override - public void addDataListener(InterfaceStatisticsListener l) { - if (dataListeners==null) { - dataListeners=new LinkedList(); - } - if (l!=null && !dataListeners.contains(l)) { - dataListeners.add(l); - } - } - + public void addDataListener(InterfaceStatisticsListener l) { + if (dataListeners == null) { + dataListeners = new LinkedList(); + } + if (l != null && !dataListeners.contains(l)) { + dataListeners.add(l); + } + } + @Override - public boolean removeDataListener(InterfaceStatisticsListener l) { - if (dataListeners==null) { - return false; + public boolean removeDataListener(InterfaceStatisticsListener l) { + if (dataListeners == null) { + return false; + } else { + return dataListeners.remove(l); + } + } + + private void fireDataListeners() { + if (dataListeners != null) { + for (InterfaceStatisticsListener l : dataListeners) { + l.notifyGenerationPerformed(currentStatHeader, currentStatObjectData, currentStatDoubleData); } - else { - return dataListeners.remove(l); + } + } + + private void fireDataListenersFinalize() { + if (dataListeners != null) { + LinkedList toRemove = new LinkedList(); + for (InterfaceStatisticsListener l : dataListeners) { + boolean rm = l.notifyMultiRunFinished(currentStatHeader, finalObjectData); + if (rm) { + toRemove.add(l); + } } - } - - private void fireDataListeners() { - if (dataListeners!=null) { - for (InterfaceStatisticsListener l : dataListeners) { -l.notifyGenerationPerformed(currentStatHeader, currentStatObjectData, currentStatDoubleData); -} } - } - - private void fireDataListenersFinalize() { - if (dataListeners!=null) { - LinkedList toRemove = new LinkedList(); - for (InterfaceStatisticsListener l : dataListeners) { - boolean rm = l.notifyMultiRunFinished(currentStatHeader, finalObjectData); - if (rm) { - toRemove.add(l); - } - } - for (InterfaceStatisticsListener l : toRemove) { + for (InterfaceStatisticsListener l : toRemove) { dataListeners.remove(l); - } - } - } - - /** - * Notify listeners on the start and stop of a run. - * - * @param runNumber current run (started or stopped) - * @param normal in case of stop: the stop was terminated normally (as opposed to manually) - * @param start if true, give the start signal, otherwise the stop signal - */ - private void fireDataListenersStartStop(int runNumber, boolean normal, boolean start) { - if (dataListeners!=null) { - for (InterfaceStatisticsListener l : dataListeners) { - if (start) { - l.notifyRunStarted(runNumber, m_StatsParams.getMultiRuns(), - currentStatHeader, currentStatMetaInfo); - } else { - l.notifyRunStopped(optRunsPerformed, normal); -// if (optRunsPerformed > 1) { - l.finalMultiRunResults(currentStatHeader, - finalObjectData); -// } -} -} } - } - - @Override - public void addTextListener(InterfaceTextListener listener) { - if (!textListeners.contains(listener)) { - textListeners.add(listener); - } - } - - @Override - public boolean removeTextListener(InterfaceTextListener listener) { - return textListeners.remove(listener); - } - - /** - * Collect start date and time of the run and if indicated, open a file output stream. - * - * @param infoString - */ - protected void initOutput(String infoString) { - String startDate = getDateString(); - // open the result file: - if (doFileOutput() // not "text-window only" - && (m_StatsParams.getOutputVerbosity().getSelectedTagID() > StatisticsParameter.VERBOSITY_NONE)) { // verbosity accordingly high - //!resFName.equalsIgnoreCase("none") && !resFName.equals("")) { - String fnameBase = makeOutputFileName(m_StatsParams.getResultFilePrefix(), infoString, startDate); - int cnt=0; - String fname = fnameBase; - while (new File(fname).exists()) { - cnt++; - fname=fnameBase+"."+cnt; - } - if (TRACE) { - System.out.println("FileName =" + fname); - } - try { - resultOut = new PrintWriter(new FileOutputStream(fname)); - } catch (Exception e) { - e.printStackTrace(); - System.out.println("Error: " + e); - } - resultOut.println("StartDate:" + startDate); - resultOut.println("On Host:" + getHostName()); - } else { - resultOut = null; } - } - - /** - * Return a simple String describing the current date and time. - * @return - */ - public static String getDateString() { - SimpleDateFormat formatter = new SimpleDateFormat("E'_'yyyy.MM.dd'_at_'HH.mm.ss"); - String dt = formatter.format(new Date()); - return dt; - } - - protected boolean doFileOutput() { - return (m_StatsParams.getOutputTo().getSelectedTagID()!=1); // not "text-window only" - } - - private String makeOutputFileName(String prefix, String infoString, String startDate) { - return (prefix + "_" + infoString).replace(' ', '_') + "_" + startDate + ".txt"; - } - /** - * If set to true, before every run the parameters will be stored to a file at the start - * of each run. Default is true. - * - * @param doSave - */ - public void setSaveParams(boolean doSave) { - saveParams = doSave; - } + } + } + + /** + * Notify listeners on the start and stop of a run. + * + * @param runNumber current run (started or stopped) + * @param normal in case of stop: the stop was terminated normally (as opposed to manually) + * @param start if true, give the start signal, otherwise the stop signal + */ + private void fireDataListenersStartStop(int runNumber, boolean normal, boolean start) { + if (dataListeners != null) { + for (InterfaceStatisticsListener l : dataListeners) { + if (start) { + l.notifyRunStarted(runNumber, m_StatsParams.getMultiRuns(), + currentStatHeader, currentStatMetaInfo); + } else { + l.notifyRunStopped(optRunsPerformed, normal); +// if (optRunsPerformed > 1) { + l.finalMultiRunResults(currentStatHeader, + finalObjectData); +// } + } + } + } + } @Override - public void startOptPerformed(String infoString, int runNumber, Object params, List informerList) { - if (TRACE) { - System.out.println("AbstractStatistics.startOptPerformed " + runNumber); - System.out.println("Statsparams were " + BeanInspector.toString(m_StatsParams)); - } - - if (runNumber == 0) { - // store the intial graph selection state, so that modifications during runtime cannot cause inconsistencies - lastFieldSelection = (StringSelection)m_StatsParams.getFieldSelection().clone(); - lastIsShowFull = m_StatsParams.isOutputAllFieldsAsText(); + public void addTextListener(InterfaceTextListener listener) { + if (!textListeners.contains(listener)) { + textListeners.add(listener); + } + } - currentStatDoubleData=null; - currentStatObjectData=null; - - List headerFields=getOutputHeaderFieldNames(informerList); - currentStatHeader = headerFields.toArray(new String[headerFields.size()]); - currentStatMetaInfo = getOutputMetaInfoAsArray(informerList); - - functionCallSum = 0; - firstPlot = true; - optRunsPerformed = 0; - convergenceCnt = 0; - if (saveParams) { - m_StatsParams.saveInstance(); - } - initOutput(infoString); - bestIndyAllRuns = null; - bestFeasibleAllRuns = null; + @Override + public boolean removeTextListener(InterfaceTextListener listener) { + return textListeners.remove(listener); + } + + /** + * Collect start date and time of the run and if indicated, open a file output stream. + * + * @param infoString + */ + protected void initOutput(String infoString) { + String startDate = getDateString(); + // open the result file: + if (doFileOutput() // not "text-window only" + && (m_StatsParams.getOutputVerbosity().getSelectedTagID() > StatisticsParameter.VERBOSITY_NONE)) { // verbosity accordingly high + //!resFName.equalsIgnoreCase("none") && !resFName.equals("")) { + String fnameBase = makeOutputFileName(m_StatsParams.getResultFilePrefix(), infoString, startDate); + int cnt = 0; + String fname = fnameBase; + while (new File(fname).exists()) { + cnt++; + fname = fnameBase + "." + cnt; + } + try { + resultOut = new PrintWriter(new FileOutputStream(fname)); + } catch (Exception e) { + e.printStackTrace(); + System.out.println("Error: " + e); + } + resultOut.println("StartDate:" + startDate); + resultOut.println("On Host:" + getHostName()); + } else { + resultOut = null; + } + } + + /** + * Return a simple String describing the current date and time. + * + * @return + */ + public static String getDateString() { + SimpleDateFormat formatter = new SimpleDateFormat("E'_'yyyy.MM.dd'_at_'HH.mm.ss"); + String dt = formatter.format(new Date()); + return dt; + } + + protected boolean doFileOutput() { + return (m_StatsParams.getOutputTo().getSelectedTagID() != 1); // not "text-window only" + } + + private String makeOutputFileName(String prefix, String infoString, String startDate) { + return (prefix + "_" + infoString).replace(' ', '_') + "_" + startDate + ".txt"; + } + + /** + * If set to true, before every run the parameters will be stored to a file at the start + * of each run. Default is true. + * + * @param doSave + */ + public void setSaveParams(boolean doSave) { + saveParams = doSave; + } + + @Override + public void startOptPerformed(String infoString, int runNumber, Object params, List informerList) { + + if (runNumber == 0) { + // store the intial graph selection state, so that modifications during runtime cannot cause inconsistencies + lastFieldSelection = (StringSelection) m_StatsParams.getFieldSelection().clone(); + lastIsShowFull = m_StatsParams.isOutputAllFieldsAsText(); + + currentStatDoubleData = null; + currentStatObjectData = null; + + List headerFields = getOutputHeaderFieldNames(informerList); + currentStatHeader = headerFields.toArray(new String[headerFields.size()]); + currentStatMetaInfo = getOutputMetaInfoAsArray(informerList); + + functionCallSum = 0; + firstPlot = true; + optRunsPerformed = 0; + convergenceCnt = 0; + if (saveParams) { + m_StatsParams.saveInstance(); + } + initOutput(infoString); + bestIndyAllRuns = null; + bestFeasibleAllRuns = null; // meanBestOfRunFitness = null; // meanBestFeasibleFit = null; - runBestFeasibleList = new ArrayList(); - runBestFitList = new ArrayList(); + runBestFeasibleList = new ArrayList(); + runBestFitList = new ArrayList(); // if (refineMultiRuns) meanCollection = new ArrayList(); // else meanCollection = null; - if (refineMultiRuns) { - sumDataCollection = new ArrayList(); - } - else { - sumDataCollection = null; - } - - finalObjectData = null; - - statDataSumOverAll = null; -// lastAdditionalInfoSums = null; - feasibleFoundAfterSum=-1; - numOfRunsFeasibleFound=0; - - } - feasibleFoundAfter=-1; - bestCurrentIndy = null; - bestOfRunIndy = null; - currentBestFeasibleFit=null; - bestOfRunFeasibleIndy = null; - lastInformerList = null; - lastSols = null; - iterationCounter = 0; - if (printRunIntroVerbosity()) { - printToTextListener("\n****** Multirun "+runNumber); + if (refineMultiRuns) { + sumDataCollection = new ArrayList(); + } else { + sumDataCollection = null; } - if (params != null) { - if (printRunIntroVerbosity()) { + + finalObjectData = null; + + statDataSumOverAll = null; +// lastAdditionalInfoSums = null; + feasibleFoundAfterSum = -1; + numOfRunsFeasibleFound = 0; + + } + feasibleFoundAfter = -1; + bestCurrentIndy = null; + bestOfRunIndy = null; + currentBestFeasibleFit = null; + bestOfRunFeasibleIndy = null; + lastInformerList = null; + lastSols = null; + iterationCounter = 0; + if (printRunIntroVerbosity()) { + printToTextListener("\n****** Multirun " + runNumber); + } + if (params != null) { + if (printRunIntroVerbosity()) { printToTextListener("\nModule parameters: "); } - if (printRunIntroVerbosity()) { + if (printRunIntroVerbosity()) { printToTextListener(BeanInspector.niceToString(params)); } - } - if (printRunIntroVerbosity()) { - printToTextListener("\nStatistics parameters: "); - } - if (printRunIntroVerbosity()) { - printToTextListener(BeanInspector.niceToString(getStatisticsParameter()) + '\n'); - } - functionCalls = 0; - fireDataListenersStartStop(runNumber, true, true); - } - - @Override - public void stopOptPerformed(boolean normal, String stopMessage) { - if (TRACE) { - System.out.println("AbstractStatistics.stopOptPerformed"); - } - if (lastSols==null) { - System.err.println("WARNING, possibly there was no call to createNextGenerationPerformed before calling stopOptPerformed (AnstractStatistics)."); - } + } + if (printRunIntroVerbosity()) { + printToTextListener("\nStatistics parameters: "); + } + if (printRunIntroVerbosity()) { + printToTextListener(BeanInspector.niceToString(getStatisticsParameter()) + '\n'); + } + functionCalls = 0; + fireDataListenersStartStop(runNumber, true, true); + } - if (iterationCounter < sumDataCollection.size()) { - // no good: later run was shorter than the first one. What to do? Discard the longer one: - if (TRACE) { - System.err.println("Error in AbstractStatistics: later run was shorter than earlier one... discarding rest..."); - } - for (int i=sumDataCollection.size()-1; i>=iterationCounter; i--) { + @Override + public void stopOptPerformed(boolean normal, String stopMessage) { + if (lastSols == null) { + System.err.println("WARNING, possibly there was no call to createNextGenerationPerformed before calling stopOptPerformed (AnstractStatistics)."); + } + + if (iterationCounter < sumDataCollection.size()) { + // no good: later run was shorter than the first one. What to do? Discard the longer one: + for (int i = sumDataCollection.size() - 1; i >= iterationCounter; i--) { sumDataCollection.remove(i); } - } - optRunsPerformed++; - functionCallSum += functionCalls; - if (printRunStoppedVerbosity() && (stopMessage != null)) { - printToTextListener(" Termination message: " + stopMessage + "\n"); + } + optRunsPerformed++; + functionCallSum += functionCalls; + if (printRunStoppedVerbosity() && (stopMessage != null)) { + printToTextListener(" Termination message: " + stopMessage + "\n"); + } + if (printRunStoppedVerbosity()) { + printToTextListener(" Function calls run: " + functionCalls + ", sum: " + functionCallSum + "\n"); + } + // check if target zero was reached + if (bestCurrentIndy != null) { + if (Mathematics.norm(bestOfRunIndy.getFitness()) < this.m_StatsParams.getConvergenceRateThreshold()) { + convergenceCnt++; } - if (printRunStoppedVerbosity()) { - printToTextListener(" Function calls run: " + functionCalls + ", sum: " + functionCallSum + "\n"); + if (printRunStoppedVerbosity()) { + printIndy("Last best", bestCurrentIndy); + } + } + if (bestOfRunIndy != null) { + runBestFitList.add(bestOfRunIndy); + if (printRunStoppedVerbosity()) { + printIndy("Run best", bestOfRunIndy); } - // check if target zero was reached - if (bestCurrentIndy != null) { - if (Mathematics.norm(bestOfRunIndy.getFitness()) < this.m_StatsParams.getConvergenceRateThreshold()) { - convergenceCnt++; - } - if (printRunStoppedVerbosity()) { - printIndy("Last best", bestCurrentIndy); - } - } - if (bestOfRunIndy != null) { - runBestFitList.add(bestOfRunIndy); - if (printRunStoppedVerbosity()) { - printIndy("Run best", bestOfRunIndy); - } // if (meanBestOfRunFitness==null) { // meanBestOfRunFitness=bestRunIndividual.getFitness().clone(); // } else addSecond(meanBestOfRunFitness, bestRunIndividual.getFitness()); - } - if (feasibleFoundAfter>0) { - if (printRunStoppedVerbosity()) { - printToTextListener(" Feasible ind. found after " + feasibleFoundAfter + " evaluations.\n"); - } - } else { - if (printRunStoppedVerbosity()) { - printToTextListener(" NO feasible individual found.\n"); - } - } - if (printRunStoppedVerbosity()) { - printToTextListener(" Solution correlations (min,max,avg,med,var): " + BeanInspector.toString(((Population)lastSols).getCorrelations((Population)lastSols)) + "\n"); - } - if (bestOfRunFeasibleIndy != null) { - runBestFeasibleList.add(bestOfRunFeasibleIndy); + } + if (feasibleFoundAfter > 0) { + if (printRunStoppedVerbosity()) { + printToTextListener(" Feasible ind. found after " + feasibleFoundAfter + " evaluations.\n"); + } + } else { + if (printRunStoppedVerbosity()) { + printToTextListener(" NO feasible individual found.\n"); + } + } + if (printRunStoppedVerbosity()) { + printToTextListener(" Solution correlations (min,max,avg,med,var): " + BeanInspector.toString(((Population) lastSols).getCorrelations((Population) lastSols)) + "\n"); + } + if (bestOfRunFeasibleIndy != null) { + runBestFeasibleList.add(bestOfRunFeasibleIndy); // if (meanBestFeasibleFit==null) { // meanBestFeasibleFit=bestRunFeasibleIndy.getFitness().clone(); // } else addSecond(meanBestFeasibleFit, bestRunFeasibleIndy.getFitness()); - if (printRunStoppedVerbosity()) { - if ((bestOfRunFeasibleIndy instanceof AbstractEAIndividual) && ((AbstractEAIndividual)bestOfRunFeasibleIndy).equalGenotypes((AbstractEAIndividual)bestOfRunIndy)) { - printToTextListener("* Run best feasible individual equals best individual.\n"); - } else { - if (bestOfRunIndy instanceof AbstractEAIndividual) { - if (((AbstractEAIndividual)bestOfRunIndy).violatesConstraint()) { - printToTextListener(" Run best individual violates constraints by " + ((AbstractEAIndividual)bestOfRunIndy).getConstraintViolation() + "\n"); - } - if (((AbstractEAIndividual)bestOfRunIndy).isMarkedPenalized()) { - printToTextListener(" Run best individual is penalized.\n"); - } - } - printIndy("Run best feasible", bestOfRunFeasibleIndy); - } - } - } - if (finalObjectData==null) { - finalObjectData = new ArrayList(); - } - finalObjectData.add(currentStatObjectData); - - if (!printRunStoppedVerbosity() && printFinalVerbosity()) { - printToTextListener("."); + if (printRunStoppedVerbosity()) { + if ((bestOfRunFeasibleIndy instanceof AbstractEAIndividual) && ((AbstractEAIndividual) bestOfRunFeasibleIndy).equalGenotypes((AbstractEAIndividual) bestOfRunIndy)) { + printToTextListener("* Run best feasible individual equals best individual.\n"); + } else { + if (bestOfRunIndy instanceof AbstractEAIndividual) { + if (((AbstractEAIndividual) bestOfRunIndy).violatesConstraint()) { + printToTextListener(" Run best individual violates constraints by " + ((AbstractEAIndividual) bestOfRunIndy).getConstraintViolation() + "\n"); + } + if (((AbstractEAIndividual) bestOfRunIndy).isMarkedPenalized()) { + printToTextListener(" Run best individual is penalized.\n"); + } + } + printIndy("Run best feasible", bestOfRunFeasibleIndy); + } } + } + if (finalObjectData == null) { + finalObjectData = new ArrayList(); + } + finalObjectData.add(currentStatObjectData); + + if (!printRunStoppedVerbosity() && printFinalVerbosity()) { + printToTextListener("."); + } // if (currentBestFit!= null) { // if (printRunStoppedVerbosity()) printToTextListener(" Best Fitness: " + BeanInspector.toString(currentBestFit) + "\n"); // } - fireDataListenersStartStop(optRunsPerformed, normal, false); - } - + fireDataListenersStartStop(optRunsPerformed, normal, false); + } + @Override - public void postProcessingPerformed(Population resultPop) { // called from processor - if (!printRunStoppedVerbosity() && printFinalVerbosity() && optRunsPerformed >= m_StatsParams.getMultiRuns()) { - printToTextListener("\n"); + public void postProcessingPerformed(Population resultPop) { // called from processor + if (!printRunStoppedVerbosity() && printFinalVerbosity() && optRunsPerformed >= m_StatsParams.getMultiRuns()) { + printToTextListener("\n"); + } + if (printRunStoppedVerbosity()) { + if (resultPop != null && (resultPop.size() > 0)) { + printToTextListener("Resulting population: \n"); + for (int i = 0; i < resultPop.size(); i++) { + printToTextListener(AbstractEAIndividual.getDefaultStringRepresentation(resultPop.getEAIndividual(i))); + printToTextListener("\n"); + } } - if (printRunStoppedVerbosity()) { - if (resultPop!=null && (resultPop.size()>0)) { - printToTextListener("Resulting population: \n"); - for (int i=0; i= m_StatsParams.getMultiRuns()) { - finalizeOutput(); - fireDataListenersFinalize(); - } - } - - private PopulationInterface makeStatsPop() { - Population pop = new Population(1); - + } + if (optRunsPerformed >= m_StatsParams.getMultiRuns()) { + finalizeOutput(); + fireDataListenersFinalize(); + } + } + + private PopulationInterface makeStatsPop() { + Population pop = new Population(1); + // if (bestCurrentIndy!=null) pop.add(bestCurrentIndy); // if (bestOfRunIndy!=null) pop.add(bestOfRunIndy); // if (bestOfRunFeasibleIndy!=null) pop.add(bestOfRunFeasibleIndy); - if (bestIndyAllRuns!=null) { - pop.add(bestIndyAllRuns); - } - return pop; - } + if (bestIndyAllRuns != null) { + pop.add(bestIndyAllRuns); + } + return pop; + } - private void printIndy(String prefix, IndividualInterface indy) { - printToTextListener("* " + prefix + " ind.: " + BeanInspector.toString(indy) + '\n'); - printToTextListener(" solution data : " + AbstractEAIndividual.getDefaultDataString(indy) + '\n'); - printToTextListener(" solution fit : " + BeanInspector.toString(indy.getFitness())); - if (!(indy instanceof AbstractEAIndividual)) { - printToTextListener(" - feasibility unknown\n"); + private void printIndy(String prefix, IndividualInterface indy) { + printToTextListener("* " + prefix + " ind.: " + BeanInspector.toString(indy) + '\n'); + printToTextListener(" solution data : " + AbstractEAIndividual.getDefaultDataString(indy) + '\n'); + printToTextListener(" solution fit : " + BeanInspector.toString(indy.getFitness())); + if (!(indy instanceof AbstractEAIndividual)) { + printToTextListener(" - feasibility unknown\n"); + } else { + if (((AbstractEAIndividual) indy).isMarkedPenalized() || ((AbstractEAIndividual) indy).violatesConstraint()) { + printToTextListener(" - infeasible\n"); + } else { + printToTextListener("\n"); } - else { - if (((AbstractEAIndividual)indy).isMarkedPenalized() || ((AbstractEAIndividual)indy).violatesConstraint()) { - printToTextListener(" - infeasible\n"); - } - else { - printToTextListener("\n"); - } - } + } - } + } - /** - * Calculate the mean fitness of final best individuals over the last series of multi-runs. - * - * @return - */ - public double[] getMeanBestFit(boolean requireFeasible) { - return calcMeanFit(requireFeasible ? runBestFeasibleList : runBestFitList); - } - - /** - * Calculate the median fitness of final best individuals over the last series of multi-runs. - * - * @return - */ - public double[] getMedianBestFit(boolean requireFeasible) { - return calcMedianFit(requireFeasible ? runBestFeasibleList : runBestFitList); - } - - protected void finalizeOutput() { - if (printFinalVerbosity()) { - printToTextListener("*******\n Runs performed: " + optRunsPerformed + ", reached target " + convergenceCnt + " times with threshold " + m_StatsParams.getConvergenceRateThreshold() + ", rate " + convergenceCnt/(double)m_StatsParams.getMultiRuns() + '\n'); - } - if (printFinalVerbosity()) { - printToTextListener(" Average function calls: " + (functionCallSum/optRunsPerformed) + "\n"); - } - - if (printFinalVerbosity() && (feasibleFoundAfterSum>=0.)) { - printToTextListener(" Feasible solution found in " + numOfRunsFeasibleFound + " of " + optRunsPerformed + " runs \n"); - printToTextListener(" Average evaluations until feasible ind. was found in " + numOfRunsFeasibleFound + " runs: " + feasibleFoundAfterSum/numOfRunsFeasibleFound + " evaluations\n"); - } + /** + * Calculate the mean fitness of final best individuals over the last series of multi-runs. + * + * @return + */ + public double[] getMeanBestFit(boolean requireFeasible) { + return calcMeanFit(requireFeasible ? runBestFeasibleList : runBestFitList); + } - if (printFinalVerbosity() && (statDataSumOverAll != null)) { - printToTextListener(" Averaged sum of run statistical data: (" + optRunsPerformed + " runs):"); - for (int i=0; i= 0.)) { + printToTextListener(" Feasible solution found in " + numOfRunsFeasibleFound + " of " + optRunsPerformed + " runs \n"); + printToTextListener(" Average evaluations until feasible ind. was found in " + numOfRunsFeasibleFound + " runs: " + feasibleFoundAfterSum / numOfRunsFeasibleFound + " evaluations\n"); + } + + if (printFinalVerbosity() && (statDataSumOverAll != null)) { + printToTextListener(" Averaged sum of run statistical data: (" + optRunsPerformed + " runs):"); + for (int i = 0; i < statDataSumOverAll.length; i++) { + if (statDataSumOverAll[i] != null) { + printToTextListener(textFieldDelimiter + (statDataSumOverAll[i] / optRunsPerformed)); + } } - printToTextListener("\n Averaged last statistical data (" + optRunsPerformed + " runs):"); - Double[] lastSum = sumDataCollection.get(sumDataCollection.size()-1); - for (int i=0; i1) { - if (runBestFitList.size()>0) { + if (optRunsPerformed > 1) { + if (runBestFitList.size() > 0) { // Mathematics.svDiv((double)optRunsPerformed, meanBestOfRunFitness, meanBestOfRunFitness); - if (printFinalVerbosity()) { - double[] meanBestFit=getMeanBestFit(false); - printToTextListener(" MultiRun stats: Mean best fitness: " + BeanInspector.toString(meanBestFit)+"\n"); - if (meanBestFit.length==1) { - printToTextListener(" MultiRun stats: Variance/Std.Dev.: " + BeanInspector.toString(calcStdDevVar(runBestFitList, meanBestFit[0])) + "\n"); - } - printToTextListener(" MultiRun stats: Median best fitn.: " + BeanInspector.toString(getMedianBestFit(false))+"\n"); - } - } - if (printFinalVerbosity() && (bestFeasibleAllRuns != null)) { - printIndy("Overall best feasible", bestFeasibleAllRuns); + if (printFinalVerbosity()) { + double[] meanBestFit = getMeanBestFit(false); + printToTextListener(" MultiRun stats: Mean best fitness: " + BeanInspector.toString(meanBestFit) + "\n"); + if (meanBestFit.length == 1) { + printToTextListener(" MultiRun stats: Variance/Std.Dev.: " + BeanInspector.toString(calcStdDevVar(runBestFitList, meanBestFit[0])) + "\n"); } + printToTextListener(" MultiRun stats: Median best fitn.: " + BeanInspector.toString(getMedianBestFit(false)) + "\n"); + } + } + if (printFinalVerbosity() && (bestFeasibleAllRuns != null)) { + printIndy("Overall best feasible", bestFeasibleAllRuns); + } // if ((runBestFeasibleList.size()>0) && (!equalLists(runBestFeasibleList, runBestFitList))) { // is there a difference between best feasibles and best fit? - if (runBestFeasibleList.size()>0) { // always output feasible stats even if theyre equal - if (printFinalVerbosity()) { - double[] meanBestFeasibleFit=getMeanBestFit(true); - printToTextListener(" MultiRun stats: Mean best feasible fitness (" + numOfRunsFeasibleFound + " runs): " + BeanInspector.toString(meanBestFeasibleFit)+"\n"); - if (meanBestFeasibleFit.length==1) { - printToTextListener(" MultiRun stats: Variance/Std.Dev.: " + BeanInspector.toString(calcStdDevVar(runBestFeasibleList, meanBestFeasibleFit[0])) + "\n"); - } - printToTextListener(" MultiRun stats: Median best feasible fitn. (: " + numOfRunsFeasibleFound + " runs): " + BeanInspector.toString(getMedianBestFit(true))+"\n"); - } - } - if (refineMultiRuns && (sumDataCollection != null)) { - if (printFinalVerbosity()) { - printToTextListener(" Averaged performance:\n"); - } - // the summed-up values of the mean collection is divided by the number of runs - for (int i=0; i 0) { // always output feasible stats even if theyre equal + if (printFinalVerbosity()) { + double[] meanBestFeasibleFit = getMeanBestFit(true); + printToTextListener(" MultiRun stats: Mean best feasible fitness (" + numOfRunsFeasibleFound + " runs): " + BeanInspector.toString(meanBestFeasibleFit) + "\n"); + if (meanBestFeasibleFit.length == 1) { + printToTextListener(" MultiRun stats: Variance/Std.Dev.: " + BeanInspector.toString(calcStdDevVar(runBestFeasibleList, meanBestFeasibleFit[0])) + "\n"); + } + printToTextListener(" MultiRun stats: Median best feasible fitn. (: " + numOfRunsFeasibleFound + " runs): " + BeanInspector.toString(getMedianBestFit(true)) + "\n"); + } + } + if (refineMultiRuns && (sumDataCollection != null)) { + if (printFinalVerbosity()) { + printToTextListener(" Averaged performance:\n"); + } + // the summed-up values of the mean collection is divided by the number of runs + for (int i = 0; i < sumDataCollection.size(); i++) { divideMean(sumDataCollection.get(i), optRunsPerformed); } - if (printFinalVerbosity()) { - printToTextListener(refineToText(sumDataCollection, showAvgIntervals)); - } - } - if (printFinalVerbosity() && (finalObjectData!=null)) { - printToTextListener(" Last data line of " + finalObjectData.size() + " multi-runs:\n" ); - for (int i=0; i additionalFields = getAdditionalInfoHeader(lastInformerList, bestPop); - String additionalFields = getOutputHeaderFieldNamesAsString(lastInformerList); + String additionalFields = getOutputHeaderFieldNamesAsString(lastInformerList); // String header = getOutputHeader(lastInformerList, bestPop); - List vals = getOutputValues(lastInformerList, bestPop); - - StringBuffer sbuf = new StringBuffer("Overall best statistical data: "); - sbuf.append(additionalFields); - sbuf.append('\n'); - sbuf.append(StringTools.concatValues(vals, textFieldDelimiter)); + List vals = getOutputValues(lastInformerList, bestPop); + + StringBuffer sbuf = new StringBuffer("Overall best statistical data: "); + sbuf.append(additionalFields); + sbuf.append('\n'); + sbuf.append(StringTools.concatValues(vals, textFieldDelimiter)); // appendAdditionalInfo(lastInformerList, bestPop, sbuf); // getOutputLine(lastInformerList, makeStatsPop()); - return sbuf.toString(); - } + return sbuf.toString(); + } - private double[] calcStdDevVar(ArrayList list, double meanFit) { - double tmp=0, sum=0; - for (Iterator iter = list.iterator(); iter.hasNext();) { - IndividualInterface indy = iter.next(); - tmp=indy.getFitness()[0]-meanFit; - sum+=(tmp*tmp); - } - double[] res = new double[2]; - res[0]=sum/list.size(); - res[1]=Math.sqrt(res[0]); - return res; - } + private double[] calcStdDevVar(ArrayList list, double meanFit) { + double tmp = 0, sum = 0; + for (Iterator iter = list.iterator(); iter.hasNext(); ) { + IndividualInterface indy = iter.next(); + tmp = indy.getFitness()[0] - meanFit; + sum += (tmp * tmp); + } + double[] res = new double[2]; + res[0] = sum / list.size(); + res[1] = Math.sqrt(res[0]); + return res; + } - /** - * Calculate the mean fitness of a list of individuals. - * @param list - * @return - */ + /** + * Calculate the mean fitness of a list of individuals. + * + * @param list + * @return + */ public static double[] calcMeanFit(List list) { - double[] sumFit = list.get(0).getFitness().clone(); - for (int i=1; i list) { - ArrayList dblAList = new ArrayList(list.size()); - for (int i=0; i dblAList = new ArrayList(list.size()); + for (int i = 0; i < list.size(); i++) { dblAList.add(list.get(i).getFitness()); } - return Mathematics.median(dblAList, false); - } - - public String refineToText(ArrayList data, int iterationsToShow) { - String hd = getOutputHeaderFieldNamesAsString(lastInformerList); - StringBuffer sbuf = new StringBuffer("Iteration"); - sbuf.append(textFieldDelimiter); - sbuf.append(hd); - sbuf.append("\n"); - refineToText(data, iterationsToShow, sbuf, textFieldDelimiter); - return sbuf.toString(); + return Mathematics.median(dblAList, false); } - - public static void refineToText(ArrayList data, int iterationsToShow, StringBuffer sbuf, String delim) { - double step = data.size()/(iterationsToShow-1.); - int printedIteration=0; - Double[] meanData; - for(int i = 1; i < data.size()+1; i++) { - // print the first, last and intermediate iterations requested by the integer parameter - // first one is printed always, as printedIteration=0 - if ((i==data.size()) || ((i-1)==Math.round(printedIteration*step))) { - printedIteration++; - meanData = data.get(i-1); - sbuf.append(i); - for (int k=0; k data, int iterationsToShow) { + String hd = getOutputHeaderFieldNamesAsString(lastInformerList); + StringBuffer sbuf = new StringBuffer("Iteration"); + sbuf.append(textFieldDelimiter); + sbuf.append(hd); + sbuf.append("\n"); + refineToText(data, iterationsToShow, sbuf, textFieldDelimiter); + return sbuf.toString(); + } + + public static void refineToText(ArrayList data, int iterationsToShow, StringBuffer sbuf, String delim) { + double step = data.size() / (iterationsToShow - 1.); + int printedIteration = 0; + Double[] meanData; + for (int i = 1; i < data.size() + 1; i++) { + // print the first, last and intermediate iterations requested by the integer parameter + // first one is printed always, as printedIteration=0 + if ((i == data.size()) || ((i - 1) == Math.round(printedIteration * step))) { + printedIteration++; + meanData = data.get(i - 1); + sbuf.append(i); + for (int k = 0; k < meanData.length; k++) { + sbuf.append(delim); + sbuf.append(BeanInspector.toString(meanData[k])); + } + sbuf.append("\n"); + } } - + // double[][] mean; // StringBuffer sbuf = new StringBuffer("Iteration\tFun.Calls\tBest\tMean\tWorst\n"); // double step = result.size()/(iterationsToShow-1.); @@ -694,203 +678,225 @@ l.notifyGenerationPerformed(currentStatHeader, currentStatObjectData, currentSta // } // return sbuf.toString(); } - - public abstract String getHostName(); + + public abstract String getHostName(); @Override - public void printToTextListener(String s) { - if ((resultOut != null)) { - resultOut.print(s); + public void printToTextListener(String s) { + if ((resultOut != null)) { + resultOut.print(s); + } + for (InterfaceTextListener l : textListeners) { + if (m_StatsParams.getOutputTo().getSelectedTagID() >= 1) { + l.print(s); } - for (InterfaceTextListener l : textListeners) { - if (m_StatsParams.getOutputTo().getSelectedTagID() >= 1) { - l.print(s); - } - } - } - - ////////////// InterfaceTextListener - @Override - public void print(String str) { - printToTextListener(str); - } - ////////////// InterfaceTextListener - @Override - public void println(String str) { - printToTextListener(str); - printToTextListener("\n"); - } - - @Override - public InterfaceStatisticsParameter getStatisticsParameter() { - return m_StatsParams; - } - - protected boolean doTextOutput() { - return (resultOut != null) || (textListeners.size()>0); - } - - /** - * Collect all field names of both internal fields and fields of external informers. Then - * concatenate them to a string using the textFieldDelimiter of the instance. - * - * @param informerList - * @param pop - * @return - */ - protected String getOutputHeaderFieldNamesAsString(List informerList) { - List headlineFields = getOutputHeaderFieldNames(informerList); - return StringTools.concatFields(headlineFields, textFieldDelimiter); - } - - /** - * Collect meta information on both internal fields and fields of external informers. - * The length of this list depends on the field selection state. - * - * @param informerList - * @param pop - * @return - */ - protected List getOutputHeaderFieldNames(List informerList) { - ArrayList headlineFields = new ArrayList(5); - headlineFields.addAll(Arrays.asList(getSimpleOutputHeader())); - if (informerList != null) { - headlineFields.addAll(getAdditionalHeaderMetaInfo(informerList, null)); - } - return headlineFields; - } - - /** - * Collect all field names of both internal fields and fields of external informers. - * The length of this list depends on the field selection state. - * - * @param informerList - * @param pop - * @return - */ - protected List getOutputMetaInfo(List informerList) { - ArrayList infoStrings = new ArrayList(5); - ArrayList addStrings = new ArrayList(5); - infoStrings.addAll(Arrays.asList(getSimpleOutputMetaInfo())); - if (informerList != null) { - getAdditionalHeaderMetaInfo(informerList, addStrings); - } - infoStrings.addAll(addStrings); - return infoStrings; - } + } + } - protected String[] getOutputMetaInfoAsArray(List informerList) { - List metaStrings = getOutputMetaInfo(informerList); - return metaStrings.toArray( new String[metaStrings.size()]); - } - - /** - * Collect the names of data fields which are collected internally.This must correspond to the - * method {@link #getSimpleOutputValues()}. - * Basic fields are identified by the enum GraphSelectionEnum and are available independently of additional - * informer instances. - * @see #getSimpleOutputValues() - * @return - */ - protected String[] getSimpleOutputHeader() { - // collect the full header by using the entries of the GraphSelectionEnum - GraphSelectionEnum[] vals = GraphSelectionEnum.values(); - ArrayListheaderEntries = new ArrayList(); - headerEntries.add("FunctionCalls"); - for (int i=0; i headerInfo = new ArrayList(); - headerInfo.add("The number of function evaluations"); - for (int i=0; i 0); + } + + /** + * Collect all field names of both internal fields and fields of external informers. Then + * concatenate them to a string using the textFieldDelimiter of the instance. + * + * @param informerList + * @param pop + * @return + */ + protected String getOutputHeaderFieldNamesAsString(List informerList) { + List headlineFields = getOutputHeaderFieldNames(informerList); + return StringTools.concatFields(headlineFields, textFieldDelimiter); + } + + /** + * Collect meta information on both internal fields and fields of external informers. + * The length of this list depends on the field selection state. + * + * @param informerList + * @param pop + * @return + */ + protected List getOutputHeaderFieldNames(List informerList) { + ArrayList headlineFields = new ArrayList(5); + headlineFields.addAll(Arrays.asList(getSimpleOutputHeader())); + if (informerList != null) { + headlineFields.addAll(getAdditionalHeaderMetaInfo(informerList, null)); + } + return headlineFields; + } + + /** + * Collect all field names of both internal fields and fields of external informers. + * The length of this list depends on the field selection state. + * + * @param informerList + * @param pop + * @return + */ + protected List getOutputMetaInfo(List informerList) { + ArrayList infoStrings = new ArrayList(5); + ArrayList addStrings = new ArrayList(5); + infoStrings.addAll(Arrays.asList(getSimpleOutputMetaInfo())); + if (informerList != null) { + getAdditionalHeaderMetaInfo(informerList, addStrings); + } + infoStrings.addAll(addStrings); + return infoStrings; + } + + protected String[] getOutputMetaInfoAsArray(List informerList) { + List metaStrings = getOutputMetaInfo(informerList); + return metaStrings.toArray(new String[metaStrings.size()]); + } + + /** + * Collect the names of data fields which are collected internally.This must correspond to the + * method {@link #getSimpleOutputValues()}. + * Basic fields are identified by the enum GraphSelectionEnum and are available independently of additional + * informer instances. + * + * @return + * @see #getSimpleOutputValues() + */ + protected String[] getSimpleOutputHeader() { + // collect the full header by using the entries of the GraphSelectionEnum + GraphSelectionEnum[] vals = GraphSelectionEnum.values(); + ArrayList headerEntries = new ArrayList(); + headerEntries.add("FunctionCalls"); + for (int i = 0; i < vals.length; i++) { + if (isRequestedField(vals[i])) { + headerEntries.add(vals[i].toString()); + } + } +// return new String[]{"Fun.calls","Best","Mean", "Worst"}; + return headerEntries.toArray(new String[headerEntries.size()]); + } + + /** + * Collect the info strings of data fields collected internally. This must correspond to + * the method {@link #getSimpleOutputValues()}. + * Basic meta info is defined by the enum GraphSelectionEnum. + * + * @return + * @see #getSimpleOutputValues() + */ + protected String[] getSimpleOutputMetaInfo() { + GraphSelectionEnum[] vals = GraphSelectionEnum.values(); + ArrayList headerInfo = new ArrayList(); + headerInfo.add("The number of function evaluations"); + for (int i = 0; i < vals.length; i++) { + if (isRequestedField(vals[i])) { + headerInfo.add(GraphSelectionEnum.getInfoStrings()[i]); + } + } +// return new String[]{"Fun.calls","Best","Mean", "Worst"}; + return headerInfo.toArray(new String[headerInfo.size()]); + } + + /** + * Indicate whether the given statistics data type is requested to + * be displayed (and thus needs to be calculated). + * + * @param graphSelectionEnum + * @return + */ + protected boolean isRequestedField(GraphSelectionEnum graphSelectionEnum) { + return (lastIsShowFull || (lastFieldSelection.isSelected(graphSelectionEnum))); + } + + /** + * Indicate whether the given statistics data type is requested to + * be displayed (and thus needs to be calculated). + * + * @param index the index of the field within the string selection object + * @return + */ + protected boolean isRequestedField(int index) { + return (lastIsShowFull || (lastFieldSelection.isSelected(index))); + } + + /** + * Indicate whether the given statistics data type is requested to + * be displayed (and thus needs to be calculated). + * + * @param header the header string of the field in question + * @return + */ + protected boolean isRequestedAdditionalField(String header) { + return (lastIsShowFull || (lastFieldSelection.isSelected(header))); + } + + /** + * Return all simple data fields collected internally. This must correspond to the + * method {@link #getSimpleOutputHeader()}. + * + * @return + * @see #getSimpleOutputHeader() + */ + protected Object[] getSimpleOutputValues() { + GraphSelectionEnum[] selEnumVals = null; + selEnumVals = GraphSelectionEnum.values(); // else selEnumVals = (GraphSelectionEnum[]) (m_StatsParams.getGraphSelection().getSelectedEnum(GraphSelectionEnum.values())); - Object[] ret = new Object[1+selEnumVals.length]; - ret[0]=functionCalls; - for (int i=1; i<=selEnumVals.length; i++) { - switch (selEnumVals[i-1]) { // the field i+1 contains enum value i, because field 0 is reserved for the number of function calls + Object[] ret = new Object[1 + selEnumVals.length]; + ret[0] = functionCalls; + for (int i = 1; i <= selEnumVals.length; i++) { + switch (selEnumVals[i - 1]) { // the field i+1 contains enum value i, because field 0 is reserved for the number of function calls // currentBest, currentWorst, runBest, currentBestFeasible, runBestFeasible, avgPopDistance, maxPopDistance; - case currentBest: ret[i]=currentBestFit[defaultFitCriterion ]; break; - case meanFit: ret[i] = (currentMeanFit==null) ? Double.NaN : currentMeanFit[defaultFitCriterion]; break; - case currentWorst: ret[i] = (currentWorstFit==null) ? Double.NaN : currentWorstFit[defaultFitCriterion]; break; - case runBest: ret[i] = bestOfRunIndy.getFitness()[defaultFitCriterion]; break; - case currentBestFeasible: ret[i] = (currentBestFeasibleFit==null) ? Double.NaN : currentBestFeasibleFit[defaultFitCriterion]; break; - case runBestFeasible: ret[i] = (bestOfRunFeasibleIndy==null) ? Double.NaN : bestOfRunFeasibleIndy.getFitness()[defaultFitCriterion]; break; - case avgEucPopDistance: ret[i] = currentAvgEucDistInPop; break; - case maxEucPopDistance: ret[i] = currentMaxEucDistInPop; break; - case avgPopMetricDist: ret[i] = currentAvgPopDistMetric; break; - case maxPopMetricDist: ret[i] = currentMaxPopDistMetric; break; - } - } - // all standard fields should be filled now - return ret; - + case currentBest: + ret[i] = currentBestFit[defaultFitCriterion]; + break; + case meanFit: + ret[i] = (currentMeanFit == null) ? Double.NaN : currentMeanFit[defaultFitCriterion]; + break; + case currentWorst: + ret[i] = (currentWorstFit == null) ? Double.NaN : currentWorstFit[defaultFitCriterion]; + break; + case runBest: + ret[i] = bestOfRunIndy.getFitness()[defaultFitCriterion]; + break; + case currentBestFeasible: + ret[i] = (currentBestFeasibleFit == null) ? Double.NaN : currentBestFeasibleFit[defaultFitCriterion]; + break; + case runBestFeasible: + ret[i] = (bestOfRunFeasibleIndy == null) ? Double.NaN : bestOfRunFeasibleIndy.getFitness()[defaultFitCriterion]; + break; + case avgEucPopDistance: + ret[i] = currentAvgEucDistInPop; + break; + case maxEucPopDistance: + ret[i] = currentMaxEucDistInPop; + break; + case avgPopMetricDist: + ret[i] = currentAvgPopDistMetric; + break; + case maxPopMetricDist: + ret[i] = currentMaxPopDistMetric; + break; + } + } + // all standard fields should be filled now + return ret; + // Object[] ret = new Object[4]; // ret[0]=functionCalls; // ret[1]=currentBestFit; @@ -899,101 +905,101 @@ l.notifyGenerationPerformed(currentStatHeader, currentStatObjectData, currentSta // if (currentWorstFit!=null) ret[3] = currentWorstFit; // else ret[3]="#"; // return ret; - } - - /** - * Assemble a list of data fields which should be traced by the statistics class. - * Both internal fields as well as external informer data are collected in this list. - * It should be consistent with the getOutputHeader method, which provides the - * names of the corresponding fields in the same order. - * The length of this list depends on the field selection state. - * - * @see #getOutputHeader(List, PopulationInterface) - * @param informerList - * @param pop - * @return - */ - protected List getOutputValues(List informerList, PopulationInterface pop) { - LinkedList values = new LinkedList(); - values.addAll(Arrays.asList(getSimpleOutputValues())); - if (informerList != null) { - for (InterfaceAdditionalPopulationInformer informer : informerList) { - List reqList = Arrays.asList(informer.getAdditionalDataValue(pop)); - values.addAll(reqList); - } - } - // remove those which are not requested - Iterator iter = values.iterator(); - int cnt=0; - iter.next(); // skip the first field (function calls) which is not regarded here - if (!lastIsShowFull) { - while (iter.hasNext()) { - iter.next(); - if (!isRequestedField(cnt++)) { - iter.remove(); - } + } + + /** + * Assemble a list of data fields which should be traced by the statistics class. + * Both internal fields as well as external informer data are collected in this list. + * It should be consistent with the getOutputHeader method, which provides the + * names of the corresponding fields in the same order. + * The length of this list depends on the field selection state. + * + * @param informerList + * @param pop + * @return + * @see #getOutputHeader(List, PopulationInterface) + */ + protected List getOutputValues(List informerList, PopulationInterface pop) { + LinkedList values = new LinkedList(); + values.addAll(Arrays.asList(getSimpleOutputValues())); + if (informerList != null) { + for (InterfaceAdditionalPopulationInformer informer : informerList) { + List reqList = Arrays.asList(informer.getAdditionalDataValue(pop)); + values.addAll(reqList); + } + } + // remove those which are not requested + Iterator iter = values.iterator(); + int cnt = 0; + iter.next(); // skip the first field (function calls) which is not regarded here + if (!lastIsShowFull) { + while (iter.hasNext()) { + iter.next(); + if (!isRequestedField(cnt++)) { + iter.remove(); } } - return values; + } + return values; // return StringTools.concatValues(values, textFieldDelimiter); - } + } - /** - * Collect additional info header and (optionally) meta information for the fields selected. - * The length of this list depends on the field selection state. - * - * @param informerList - * @param pop - * @param metaInfo if non null, the meta info strings are returned in this list - * @return - */ - protected List getAdditionalHeaderMetaInfo(List informerList, List metaInfo) { - LinkedList headers = new LinkedList(); - if (metaInfo!=null && (metaInfo.size()>0)) { - System.err.println("Warning, metaInfo list should be empty in AbstractStatistics.getAdditionalHeaderMetaInfo"); - } - for (InterfaceAdditionalPopulationInformer informer : informerList) { - headers.addAll(Arrays.asList(informer.getAdditionalDataHeader())); - if (metaInfo!=null) { - metaInfo.addAll(Arrays.asList(informer.getAdditionalDataInfo())); - } + /** + * Collect additional info header and (optionally) meta information for the fields selected. + * The length of this list depends on the field selection state. + * + * @param informerList + * @param pop + * @param metaInfo if non null, the meta info strings are returned in this list + * @return + */ + protected List getAdditionalHeaderMetaInfo(List informerList, List metaInfo) { + LinkedList headers = new LinkedList(); + if (metaInfo != null && (metaInfo.size() > 0)) { + System.err.println("Warning, metaInfo list should be empty in AbstractStatistics.getAdditionalHeaderMetaInfo"); + } + for (InterfaceAdditionalPopulationInformer informer : informerList) { + headers.addAll(Arrays.asList(informer.getAdditionalDataHeader())); + if (metaInfo != null) { + metaInfo.addAll(Arrays.asList(informer.getAdditionalDataInfo())); + } // hdr = hdr + "\t " + informer.getAdditionalDataHeader(pop); - } - Iterator hIter = headers.iterator(); - Iterator mIter = (metaInfo!=null) ? metaInfo.iterator() : null; - if (!lastIsShowFull) { - while (hIter.hasNext()) { - if (mIter!=null && mIter.hasNext()) { - mIter.next(); - } - if (!isRequestedAdditionalField(hIter.next())) { - hIter.remove(); - if (mIter!=null && mIter.hasNext()) { - mIter.remove(); - } + } + Iterator hIter = headers.iterator(); + Iterator mIter = (metaInfo != null) ? metaInfo.iterator() : null; + if (!lastIsShowFull) { + while (hIter.hasNext()) { + if (mIter != null && mIter.hasNext()) { + mIter.next(); + } + if (!isRequestedAdditionalField(hIter.next())) { + hIter.remove(); + if (mIter != null && mIter.hasNext()) { + mIter.remove(); } } } - return headers; - } - - /** - * Take the output values and convert them to a concatenated String and a Double array. - * The array will have null entries whenever a field contained non-primitive numeric types (such - * as arrays or other non-numeric data). - * The string concatenation uses the textFieldDelimiter of the instance. - * - * @param informerList - * @param pop - * @return - */ - protected Pair getOutputData(List informerList, PopulationInterface pop) { - List statValues = getOutputValues(informerList, pop); - String statValuesString = StringTools.concatValues(statValues, textFieldDelimiter); + } + return headers; + } + + /** + * Take the output values and convert them to a concatenated String and a Double array. + * The array will have null entries whenever a field contained non-primitive numeric types (such + * as arrays or other non-numeric data). + * The string concatenation uses the textFieldDelimiter of the instance. + * + * @param informerList + * @param pop + * @return + */ + protected Pair getOutputData(List informerList, PopulationInterface pop) { + List statValues = getOutputValues(informerList, pop); + String statValuesString = StringTools.concatValues(statValues, textFieldDelimiter); + + return new Pair(statValuesString, statValues.toArray(new Object[statValues.size()])); + } - return new Pair(statValuesString, statValues.toArray(new Object[statValues.size()])); - } - // /** // * Append additional informer informations to the given StringBuffer. // * @@ -1027,251 +1033,247 @@ l.notifyGenerationPerformed(currentStatHeader, currentStatObjectData, currentSta // return null; // } - /** - * @deprecated The method {@link #createNextGenerationPerformed(PopulationInterface, List)} should be used instead. - */ + /** + * @deprecated The method {@link #createNextGenerationPerformed(PopulationInterface, List)} should be used instead. + */ @Override - public synchronized void createNextGenerationPerformed(double[] bestfit, - double[] worstfit, int calls) { - functionCalls = calls; - currentBestFit = bestfit; - currentWorstFit = worstfit; - currentBestFeasibleFit = null; - currentMeanFit = null; - - if (firstPlot) { - initPlots(null, null); + public synchronized void createNextGenerationPerformed(double[] bestfit, + double[] worstfit, int calls) { + functionCalls = calls; + currentBestFit = bestfit; + currentWorstFit = worstfit; + currentBestFeasibleFit = null; + currentMeanFit = null; + + if (firstPlot) { + initPlots(null, null); // if (doTextOutput()) printToTextListener(getOutputHeader(null, null)+'\n'); - firstPlot = false; - } - if ((iterationCounter == 0) && printHeaderByVerbosity()) { - printToTextListener(getOutputHeaderFieldNamesAsString(null)+'\n'); - } + firstPlot = false; + } + if ((iterationCounter == 0) && printHeaderByVerbosity()) { + printToTextListener(getOutputHeaderFieldNamesAsString(null) + '\n'); + } - if (doTextOutput() && printLineByVerbosity(calls)) { - Pair addInfo = getOutputData(null, null); - printToTextListener(addInfo.head()+'\n'); - if (addInfo.tail()!=null) { - statDataSumOverAll = updateSum(statDataSumOverAll, ToolBox.parseDoubles(addInfo.tail())); - } - } - plotCurrentResults(); - iterationCounter++; - } - - /** - * Add the given array to the member array. Do some checks etc. - * If a resultSum array is provided, it is used to add the info and returned. Otherwise - * a new array is allocated. - * - * @param curInfo - */ - private static Double[] updateSum(Double[] resultSum, Double[] curInfo) { - if (resultSum==null) { - resultSum = curInfo.clone(); - } else { - if (curInfo.length != resultSum.length) { - System.err.println("Error in AbstractStatistics.updateAdditionalInfo: mismatching info arrays!"); - } else { - for (int i=0; i addInfo = getOutputData(null, null); + printToTextListener(addInfo.head() + '\n'); + if (addInfo.tail() != null) { + statDataSumOverAll = updateSum(statDataSumOverAll, ToolBox.parseDoubles(addInfo.tail())); + } + } + plotCurrentResults(); + iterationCounter++; + } - /** - * If the population returns a specific data array, this method is called instead of doing standard output - * @param pop - * @param informer - */ - public abstract void plotSpecificData(PopulationInterface pop, List informerList); - - protected abstract void plotCurrentResults(); - - /** - * Called at the very first (multirun mode) plot of a fitness curve. - */ - protected abstract void initPlots(PopulationInterface pop, List informerList); - - /** - * To set a list of informers (even before the actual run is started). - * @param informerList - */ - public void setInitialInformerList(List informerList) { - lastInformerList = informerList; - } - - /** - * Collect statistical data for the given population, such as best individual, best fitness, - * population measures. - * This should be called exactly once per generation. - * - * @param pop - */ - private void collectPopData(PopulationInterface pop) { - bestCurrentIndy = pop.getBestIndividual().getClone(); - if ((bestIndyAllRuns == null) || (secondIsBetter(bestIndyAllRuns, bestCurrentIndy))) { - bestIndyAllRuns = bestCurrentIndy; - } - if ((bestOfRunIndy==null) || (secondIsBetter(bestOfRunIndy, bestCurrentIndy))) { - bestOfRunIndy=bestCurrentIndy; - } - if (bestCurrentIndy == null) { - System.err.println("createNextGenerationPerformed BestInd==null"); - } - currentBestFit = bestCurrentIndy.getFitness().clone(); - if (currentBestFit == null) { - System.err.println("BestFitness==null !"); - } - if (pop instanceof Population) { - AbstractEAIndividual curBestFeasible = ((Population)pop).getBestFeasibleIndividual(-1); - if (curBestFeasible!=null) { // a feasible ind. was found! - if (currentBestFeasibleFit==null) { // feasible indy found for the first time - numOfRunsFeasibleFound++; - feasibleFoundAfter=((Population)pop).getFunctionCalls(); - if (feasibleFoundAfterSum<0) { - feasibleFoundAfterSum=0.; - } // initial signaling value was -1. - feasibleFoundAfterSum+=feasibleFoundAfter; - } - currentBestFeasibleFit = curBestFeasible.getFitness().clone(); - if ((bestOfRunFeasibleIndy==null) || (secondIsBetter(bestOfRunFeasibleIndy, curBestFeasible))) { - bestOfRunFeasibleIndy=(AbstractEAIndividual)curBestFeasible.clone(); -// System.out.println("New best feasible: " + AbstractEAIndividual.getDefaultStringRepresentation((AbstractEAIndividual)bestRunFeasibleIndy)); - } - if ((bestFeasibleAllRuns == null) || (secondIsBetter(bestFeasibleAllRuns, bestOfRunFeasibleIndy))) { - bestFeasibleAllRuns = bestOfRunFeasibleIndy; - } - } - } else { - System.err.println("INVALID POPULATION (AbstractStatistics)"); - } - - // collect these data fields only if requested by the user - if (lastIsShowFull || GraphSelectionEnum.doPlotMean(lastFieldSelection)) { - currentMeanFit = pop.getMeanFitness().clone(); - } - else { - currentMeanFit = null; - } - if (lastIsShowFull || GraphSelectionEnum.doPlotWorst(lastFieldSelection)) { - currentWorstFit = pop.getWorstIndividual().getFitness().clone(); - } - else { - currentWorstFit = null; - } - - functionCalls = pop.getFunctionCalls(); - - if (lastIsShowFull || GraphSelectionEnum.doPlotAvgEucDist(lastFieldSelection) - || GraphSelectionEnum.doPlotMaxEucDist(lastFieldSelection)) { - double[] measures = ((Population)pop).getPopulationMeasures((InterfaceDistanceMetric)null); - if (measures != null) { - currentAvgEucDistInPop = measures[0]; - currentMaxEucDistInPop = measures[2]; - } - } - - if (lastIsShowFull || GraphSelectionEnum.doPlotAvgPopMetricDist(lastFieldSelection) - || GraphSelectionEnum.doPlotMaxPopMetricDist(lastFieldSelection)) { - double[] measures = ((Population)pop).getPopulationMeasures(); - if (measures != null) { - currentAvgPopDistMetric = measures[0]; - currentMaxPopDistMetric = measures[2]; - } - } - } - - public String[] getCurrentFieldHeaders() { - StringSelection fSel = m_StatsParams.getFieldSelection(); - return fSel.getSelected(); - } - - /** - * Do some data collection on the population. - * - */ - @Override - public synchronized void createNextGenerationPerformed(PopulationInterface - pop, InterfaceOptimizer opt, List informerList) { - lastInformerList = informerList; - if (TRACE) { - printToTextListener(".. in createNextGenPerformed after " + pop.getFunctionCalls() + " evals.\n"); - } - if (resultOut != null) { - resultOut.flush(); - } - if (firstPlot) { - initPlots(pop, informerList); -// if (doTextOutput()) printToTextListener(getOutputHeader(informer, pop)+'\n'); - firstPlot = false; - currentBestFeasibleFit=null; - } - - if (pop.getSpecificData() != null) { // this is more or less deprecated. the standard population implementation will always return null. However the ES module wont - plotSpecificData(pop, informerList); - return; - } - - collectPopData(pop); - - if (iterationCounter==0) { - String headerLine = StringTools.concatFields(currentStatHeader, textFieldDelimiter); - if (printHeaderByVerbosity()) { - printToTextListener(headerLine+'\n'); + /** + * Add the given array to the member array. Do some checks etc. + * If a resultSum array is provided, it is used to add the info and returned. Otherwise + * a new array is allocated. + * + * @param curInfo + */ + private static Double[] updateSum(Double[] resultSum, Double[] curInfo) { + if (resultSum == null) { + resultSum = curInfo.clone(); + } else { + if (curInfo.length != resultSum.length) { + System.err.println("Error in AbstractStatistics.updateAdditionalInfo: mismatching info arrays!"); + } else { + for (int i = 0; i < curInfo.length; i++) { + if (resultSum[i] == null || (curInfo[i] == null)) { + resultSum[i] = null; + } else { + resultSum[i] += curInfo[i]; } - } - - lastSols = (opt!=null) ? new Population(opt.getAllSolutions().getSolutions()) : pop; + } + } + } + return resultSum; + } + + /** + * If the population returns a specific data array, this method is called instead of doing standard output + * + * @param pop + * @param informer + */ + public abstract void plotSpecificData(PopulationInterface pop, List informerList); + + protected abstract void plotCurrentResults(); + + /** + * Called at the very first (multirun mode) plot of a fitness curve. + */ + protected abstract void initPlots(PopulationInterface pop, List informerList); + + /** + * To set a list of informers (even before the actual run is started). + * + * @param informerList + */ + public void setInitialInformerList(List informerList) { + lastInformerList = informerList; + } + + /** + * Collect statistical data for the given population, such as best individual, best fitness, + * population measures. + * This should be called exactly once per generation. + * + * @param pop + */ + private void collectPopData(PopulationInterface pop) { + bestCurrentIndy = pop.getBestIndividual().getClone(); + if ((bestIndyAllRuns == null) || (secondIsBetter(bestIndyAllRuns, bestCurrentIndy))) { + bestIndyAllRuns = bestCurrentIndy; + } + if ((bestOfRunIndy == null) || (secondIsBetter(bestOfRunIndy, bestCurrentIndy))) { + bestOfRunIndy = bestCurrentIndy; + } + if (bestCurrentIndy == null) { + System.err.println("createNextGenerationPerformed BestInd==null"); + } + currentBestFit = bestCurrentIndy.getFitness().clone(); + if (currentBestFit == null) { + System.err.println("BestFitness==null !"); + } + if (pop instanceof Population) { + AbstractEAIndividual curBestFeasible = ((Population) pop).getBestFeasibleIndividual(-1); + if (curBestFeasible != null) { // a feasible ind. was found! + if (currentBestFeasibleFit == null) { // feasible indy found for the first time + numOfRunsFeasibleFound++; + feasibleFoundAfter = ((Population) pop).getFunctionCalls(); + if (feasibleFoundAfterSum < 0) { + feasibleFoundAfterSum = 0.; + } // initial signaling value was -1. + feasibleFoundAfterSum += feasibleFoundAfter; + } + currentBestFeasibleFit = curBestFeasible.getFitness().clone(); + if ((bestOfRunFeasibleIndy == null) || (secondIsBetter(bestOfRunFeasibleIndy, curBestFeasible))) { + bestOfRunFeasibleIndy = (AbstractEAIndividual) curBestFeasible.clone(); +// System.out.println("New best feasible: " + AbstractEAIndividual.getDefaultStringRepresentation((AbstractEAIndividual)bestRunFeasibleIndy)); + } + if ((bestFeasibleAllRuns == null) || (secondIsBetter(bestFeasibleAllRuns, bestOfRunFeasibleIndy))) { + bestFeasibleAllRuns = bestOfRunFeasibleIndy; + } + } + } else { + System.err.println("INVALID POPULATION (AbstractStatistics)"); + } + + // collect these data fields only if requested by the user + if (lastIsShowFull || GraphSelectionEnum.doPlotMean(lastFieldSelection)) { + currentMeanFit = pop.getMeanFitness().clone(); + } else { + currentMeanFit = null; + } + if (lastIsShowFull || GraphSelectionEnum.doPlotWorst(lastFieldSelection)) { + currentWorstFit = pop.getWorstIndividual().getFitness().clone(); + } else { + currentWorstFit = null; + } + + functionCalls = pop.getFunctionCalls(); + + if (lastIsShowFull || GraphSelectionEnum.doPlotAvgEucDist(lastFieldSelection) + || GraphSelectionEnum.doPlotMaxEucDist(lastFieldSelection)) { + double[] measures = ((Population) pop).getPopulationMeasures((InterfaceDistanceMetric) null); + if (measures != null) { + currentAvgEucDistInPop = measures[0]; + currentMaxEucDistInPop = measures[2]; + } + } + + if (lastIsShowFull || GraphSelectionEnum.doPlotAvgPopMetricDist(lastFieldSelection) + || GraphSelectionEnum.doPlotMaxPopMetricDist(lastFieldSelection)) { + double[] measures = ((Population) pop).getPopulationMeasures(); + if (measures != null) { + currentAvgPopDistMetric = measures[0]; + currentMaxPopDistMetric = measures[2]; + } + } + } + + public String[] getCurrentFieldHeaders() { + StringSelection fSel = m_StatsParams.getFieldSelection(); + return fSel.getSelected(); + } + + /** + * Do some data collection on the population. + */ + @Override + public synchronized void createNextGenerationPerformed(PopulationInterface + pop, InterfaceOptimizer opt, List informerList) { + lastInformerList = informerList; + + if (resultOut != null) { + resultOut.flush(); + } + if (firstPlot) { + initPlots(pop, informerList); +// if (doTextOutput()) printToTextListener(getOutputHeader(informer, pop)+'\n'); + firstPlot = false; + currentBestFeasibleFit = null; + } + + if (pop.getSpecificData() != null) { // this is more or less deprecated. the standard population implementation will always return null. However the ES module wont + plotSpecificData(pop, informerList); + return; + } + + collectPopData(pop); + + if (iterationCounter == 0) { + String headerLine = StringTools.concatFields(currentStatHeader, textFieldDelimiter); + if (printHeaderByVerbosity()) { + printToTextListener(headerLine + '\n'); + } + } + + lastSols = (opt != null) ? new Population(opt.getAllSolutions().getSolutions()) : pop; // Pair addData = getOutputData(informerList, lastSols); // System.out.println("lastSols size: " + 500*PSymbolicRegression.getAvgIndySize(lastSols)); // System.out.println("Mem use: " + getMemoryUse()); - Pair addData = getOutputData(informerList, lastSols); - if (doTextOutput()) { // this is where the text output is actually written - if (printLineByVerbosity(iterationCounter)) { + Pair addData = getOutputData(informerList, lastSols); + if (doTextOutput()) { // this is where the text output is actually written + if (printLineByVerbosity(iterationCounter)) { // printToTextListener(functionCalls + textFieldDelimiter); - printToTextListener(addData.head()+'\n'); - } - } - currentStatObjectData = addData.tail(); - currentStatDoubleData = ToolBox.parseDoubles(currentStatObjectData); - if (currentStatObjectData!=null) { - statDataSumOverAll = updateSum(statDataSumOverAll, currentStatDoubleData); // this adds up all data of a single run - } else { - System.err.println("Warning in AbstractStatistics!"); - } + printToTextListener(addData.head() + '\n'); + } + } + currentStatObjectData = addData.tail(); + currentStatDoubleData = ToolBox.parseDoubles(currentStatObjectData); + if (currentStatObjectData != null) { + statDataSumOverAll = updateSum(statDataSumOverAll, currentStatDoubleData); // this adds up all data of a single run + } else { + System.err.println("Warning in AbstractStatistics!"); + } - if (sumDataCollection != null) { - // Collect average data - Double[] sumDataEntry = null; - if ((optRunsPerformed==0) && (sumDataCollection.size()<=iterationCounter)) { - // in the first run, newly allocate the arrays - // assume that all later data sets will have the same format + if (sumDataCollection != null) { + // Collect average data + Double[] sumDataEntry = null; + if ((optRunsPerformed == 0) && (sumDataCollection.size() <= iterationCounter)) { + // in the first run, newly allocate the arrays + // assume that all later data sets will have the same format // means = new double[4][currentBestFit.length]; // this only fits fitness vectors! of course this is sensible for multi-crit fitnesses... - sumDataEntry = currentStatDoubleData.clone(); - sumDataCollection.add(sumDataEntry); - } else { - if (sumDataCollection.size()<=iterationCounter) {// bad case! - // may happen for dynamic pop-sizes, e.g. in Tribes, when runs do not necessarily send the - // "generation performed" event the same number of times. - // thus: dont do an update for events that are "too late" - sumDataEntry = null; - } else { - sumDataEntry = sumDataCollection.get(iterationCounter); - } - if (sumDataEntry != null) { - updateSum(sumDataEntry, currentStatDoubleData); - } // this adds up data of a single iteration across multiple runs - } - } - + sumDataEntry = currentStatDoubleData.clone(); + sumDataCollection.add(sumDataEntry); + } else { + if (sumDataCollection.size() <= iterationCounter) {// bad case! + // may happen for dynamic pop-sizes, e.g. in Tribes, when runs do not necessarily send the + // "generation performed" event the same number of times. + // thus: dont do an update for events that are "too late" + sumDataEntry = null; + } else { + sumDataEntry = sumDataCollection.get(iterationCounter); + } + if (sumDataEntry != null) { + updateSum(sumDataEntry, currentStatDoubleData); + } // this adds up data of a single iteration across multiple runs + } + } + // if (doTextOutput()) { // Pair addInfo = getOutputLine(informerList, lastSols); // @@ -1283,111 +1285,107 @@ l.notifyGenerationPerformed(currentStatHeader, currentStatObjectData, currentSta // additionalInfoSums = updateAdditionalInfo(additionalInfoSums, addInfo.tail()); // } // } - plotCurrentResults(); - fireDataListeners(); - if (TRACE) { - printToTextListener(".. done createNextGenPerformed after " + pop.getFunctionCalls() + " evals.\n"); - } - if (resultOut != null) { - resultOut.flush(); - } - iterationCounter++; - } + plotCurrentResults(); + fireDataListeners(); + if (resultOut != null) { + resultOut.flush(); + } + iterationCounter++; + } - /** - * Returns true if the given iteration is a verbose one according to StatsParameter - meaning - * that full iteration data should be plotted. - * - * @param iteration - * @return - */ - private boolean printLineByVerbosity(int iteration) { - return (m_StatsParams.getOutputVerbosity().getSelectedTagID() > StatisticsParameter.VERBOSITY_KTH_IT) - || ((m_StatsParams.getOutputVerbosity().getSelectedTagID() == StatisticsParameter.VERBOSITY_KTH_IT) - && (isKthRun(iteration, m_StatsParams.getOutputVerbosityK()))); - } - - private boolean printRunIntroVerbosity() { - return (m_StatsParams.getOutputVerbosity().getSelectedTagID() >= StatisticsParameter.VERBOSITY_KTH_IT) - || (optRunsPerformed==0 && (m_StatsParams.getOutputVerbosity().getSelectedTagID() >= StatisticsParameter.VERBOSITY_FINAL)); - } - - private boolean printRunStoppedVerbosity() { - return (m_StatsParams.getOutputVerbosity().getSelectedTagID() >= StatisticsParameter.VERBOSITY_KTH_IT); - } - - private boolean printFinalVerbosity() { - return (m_StatsParams.getOutputVerbosity().getSelectedTagID() > StatisticsParameter.VERBOSITY_NONE); - } - - private boolean isKthRun(int i, int k) { - // ingeniously shifting i by two since the stats counter starts at 0 - // after two evaluations have already happened: initialization and first optimization - // this allows the last iteration to be within the displayed set if k is a divisor of whole iterations as expected - if ((i==0) || (k==0)) { - return true; + /** + * Returns true if the given iteration is a verbose one according to StatsParameter - meaning + * that full iteration data should be plotted. + * + * @param iteration + * @return + */ + private boolean printLineByVerbosity(int iteration) { + return (m_StatsParams.getOutputVerbosity().getSelectedTagID() > StatisticsParameter.VERBOSITY_KTH_IT) + || ((m_StatsParams.getOutputVerbosity().getSelectedTagID() == StatisticsParameter.VERBOSITY_KTH_IT) + && (isKthRun(iteration, m_StatsParams.getOutputVerbosityK()))); + } + + private boolean printRunIntroVerbosity() { + return (m_StatsParams.getOutputVerbosity().getSelectedTagID() >= StatisticsParameter.VERBOSITY_KTH_IT) + || (optRunsPerformed == 0 && (m_StatsParams.getOutputVerbosity().getSelectedTagID() >= StatisticsParameter.VERBOSITY_FINAL)); + } + + private boolean printRunStoppedVerbosity() { + return (m_StatsParams.getOutputVerbosity().getSelectedTagID() >= StatisticsParameter.VERBOSITY_KTH_IT); + } + + private boolean printFinalVerbosity() { + return (m_StatsParams.getOutputVerbosity().getSelectedTagID() > StatisticsParameter.VERBOSITY_NONE); + } + + private boolean isKthRun(int i, int k) { + // ingeniously shifting i by two since the stats counter starts at 0 + // after two evaluations have already happened: initialization and first optimization + // this allows the last iteration to be within the displayed set if k is a divisor of whole iterations as expected + if ((i == 0) || (k == 0)) { + return true; + } else { + if (i <= 2) { + return (i % k) == 0; + } // show more at the beginning (always first time) + else { + return ((i + 2) % k) == 0; + } + } + } + + private boolean printHeaderByVerbosity() { + return (m_StatsParams.getOutputVerbosity().getSelectedTagID() >= StatisticsParameter.VERBOSITY_KTH_IT); + } + + private static void divideMean(Double[] mean, double d) { + for (int j = 0; j < mean.length; j++) { + if (mean[j] != null) { + mean[j] /= d; } - else { - if (i<=2) { - return (i % k) == 0; - } // show more at the beginning (always first time) - else { - return ((i+2) % k) == 0; - } - } - } - - private boolean printHeaderByVerbosity() { - return (m_StatsParams.getOutputVerbosity().getSelectedTagID() >= StatisticsParameter.VERBOSITY_KTH_IT); - } - - private static void divideMean(Double[] mean, double d) { - for (int j=0; j informerList); // called from processor + void startOptPerformed(String InfoString,int runnumber, Object params, List informerList); // called from processor /** * Finalize statistics computations. */ - public void stopOptPerformed(boolean normal, String stopMessage); // called from processor - public void addDataListener(InterfaceStatisticsListener listener); - public boolean removeDataListener(InterfaceStatisticsListener listener); - public void addTextListener(InterfaceTextListener listener); - public boolean removeTextListener(InterfaceTextListener listener); - public void printToTextListener(String s); - public void createNextGenerationPerformed(PopulationInterface Pop, InterfaceOptimizer opt, List informerList); - public void createNextGenerationPerformed(double[] bestfit,double[] worstfit,int calls); - public InterfaceStatisticsParameter getStatisticsParameter(); // called from moduleadapter - public IndividualInterface getRunBestSolution(); // return the best fitness of the last run (may not be equal to the last population) - public IndividualInterface getBestSolution(); // returns the best overall solution - public double[] getBestFitness(); // returns the best overall fitness - public void postProcessingPerformed(Population resultPop); // called from processor + void stopOptPerformed(boolean normal, String stopMessage); // called from processor + void addDataListener(InterfaceStatisticsListener listener); + boolean removeDataListener(InterfaceStatisticsListener listener); + void addTextListener(InterfaceTextListener listener); + boolean removeTextListener(InterfaceTextListener listener); + void printToTextListener(String s); + void createNextGenerationPerformed(PopulationInterface Pop, InterfaceOptimizer opt, List informerList); + void createNextGenerationPerformed(double[] bestfit,double[] worstfit,int calls); + InterfaceStatisticsParameter getStatisticsParameter(); // called from moduleadapter + IndividualInterface getRunBestSolution(); // return the best fitness of the last run (may not be equal to the last population) + IndividualInterface getBestSolution(); // returns the best overall solution + double[] getBestFitness(); // returns the best overall fitness + void postProcessingPerformed(Population resultPop); // called from processor } \ No newline at end of file diff --git a/src/eva2/optimization/stat/MovingAverage.java b/src/eva2/optimization/stat/MovingAverage.java index b0f9549c..799909cb 100644 --- a/src/eva2/optimization/stat/MovingAverage.java +++ b/src/eva2/optimization/stat/MovingAverage.java @@ -1,20 +1,6 @@ package eva2.optimization.stat; -/* - * Title: EvA2 - * Description: - * Copyright: Copyright (c) 2003 - * Company: University of Tuebingen, Computer Architecture - * @author Holger Ulmer, Felix Streichert, Hannes Planatscher - * @version: $Revision: 16 $ - * $Date: 2006-12-20 10:42:57 +0100 (Wed, 20 Dec 2006) $ - * $Author: marcekro $ - */ -/*==========================================================================* - * IMPORTS - *==========================================================================*/ -/*==========================================================================* -* INTERFACE DECLARATION -*==========================================================================*/ + + /** * */ diff --git a/src/eva2/optimization/stat/StatisticsStandalone.java b/src/eva2/optimization/stat/StatisticsStandalone.java index eafb1e3c..f7e744d9 100644 --- a/src/eva2/optimization/stat/StatisticsStandalone.java +++ b/src/eva2/optimization/stat/StatisticsStandalone.java @@ -105,9 +105,6 @@ public class StatisticsStandalone extends AbstractStatistics implements Interfac @Override public void plotSpecificData(PopulationInterface pop, List informerList) { - if (TRACE) { - System.out.println(" m_SpecificData !!"); - } double[] specificData = pop.getSpecificData(); if (specificData != null) { for (int i = 0; i < specificData.length; i++) { diff --git a/src/eva2/optimization/tools/GeneralGEOFaker.java b/src/eva2/optimization/tools/GeneralGEOFaker.java index 3a3ab387..8c9c14b7 100644 --- a/src/eva2/optimization/tools/GeneralGEOFaker.java +++ b/src/eva2/optimization/tools/GeneralGEOFaker.java @@ -71,7 +71,7 @@ public class GeneralGEOFaker extends JPanel { // edit.setEnabled(false); // m_SourceCodeEditor = new SourceCodeEditor(); // String className = m_Editor.getValue().getClass().getName(); -// m_SourceCodeEditor.editSource(EvAClient.DYNAMICCLASSES_PROPERTIES.getProperty(className)); +// m_SourceCodeEditor.editSource(Main.DYNAMICCLASSES_PROPERTIES.getProperty(className)); // m_SourceCodeEditorFrame = new PropertyDialog(m_SourceCodeEditor, "test", 50, 50); // m_SourceCodeEditorFrame.pack(); // m_SourceCodeEditorFrame.addWindowListener(new WindowAdapter() { diff --git a/src/eva2/optimization/tools/GeneralGenericObjectEditorPanel.java b/src/eva2/optimization/tools/GeneralGenericObjectEditorPanel.java index 35ff0aec..82c0dcfb 100644 --- a/src/eva2/optimization/tools/GeneralGenericObjectEditorPanel.java +++ b/src/eva2/optimization/tools/GeneralGenericObjectEditorPanel.java @@ -99,7 +99,7 @@ public class GeneralGenericObjectEditorPanel extends JPanel implements ItemListe // m_editSourceBut.setEnabled(false); // m_SourceCodeEditor = new SourceCodeEditor(); // String className = m_ObjectEditor.getValue().getClass().getName(); -// m_SourceCodeEditor.editSource(EvAClient.DYNAMICCLASSES_PROPERTIES.getProperty(className)); +// m_SourceCodeEditor.editSource(Main.DYNAMICCLASSES_PROPERTIES.getProperty(className)); // m_SourceCodeEditorFrame = new PropertyDialog(m_SourceCodeEditor, "test", 50, 50); // m_SourceCodeEditorFrame.pack(); // m_SourceCodeEditorFrame.addWindowListener(new WindowAdapter() { diff --git a/src/eva2/tools/EVAERROR.java b/src/eva2/tools/EVAERROR.java index aff84183..d2f3c846 100644 --- a/src/eva2/tools/EVAERROR.java +++ b/src/eva2/tools/EVAERROR.java @@ -47,7 +47,7 @@ public class EVAERROR { * Send a message only once to System.err. Once means that the msg is stored for the lifetime of * the VM or until clearMsgCache() is called. * - * @param msg + * @param message */ public static void errorMsgOnce(String message) { if (errorMap == null) { diff --git a/src/eva2/tools/ReflectPackage.java b/src/eva2/tools/ReflectPackage.java index 83146ee5..32709881 100644 --- a/src/eva2/tools/ReflectPackage.java +++ b/src/eva2/tools/ReflectPackage.java @@ -464,7 +464,7 @@ public class ReflectPackage { // BasicResourceLoader rld = BasicResourceLoader.instance(); // byte[] b = rld.getBytesFromResourceLocation("images/Sub24.gif"); // System.out.println((b == null) ? "null" : b.toString()); -// b = rld.getBytesFromResourceLocation("src/eva2/client/EvAClient.java"); +// b = rld.getBytesFromResourceLocation("src/eva2/client/SplashScreen.java"); // System.out.println((b == null) ? "null" : b.toString()); HashSet h = new HashSet (20); diff --git a/src/eva2/tools/StringTools.java b/src/eva2/tools/StringTools.java index c1f09794..9dcf3349 100644 --- a/src/eva2/tools/StringTools.java +++ b/src/eva2/tools/StringTools.java @@ -19,7 +19,7 @@ public final class StringTools { private StringTools() { } /** - * Returns a HTML formated String, in which each line is at most lineBreak + * Returns a HTML formatted String, in which each line is at most lineBreak * symbols long. * * @param string