diff --git a/src/eva2/client/EvAClient.java b/src/eva2/client/EvAClient.java index 1ac65a49..85c9ae5c 100644 --- a/src/eva2/client/EvAClient.java +++ b/src/eva2/client/EvAClient.java @@ -17,6 +17,7 @@ import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Event; import java.awt.Frame; +import java.awt.HeadlessException; import java.awt.Toolkit; import java.awt.Window; import java.awt.event.ActionEvent; @@ -24,8 +25,10 @@ import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; +import java.beans.BeanInfo; import java.io.Serializable; import java.net.URL; +import java.util.LinkedList; import java.util.Properties; import java.util.Set; import java.util.Vector; @@ -51,21 +54,24 @@ import javax.swing.event.MenuListener; import wsi.ra.jproxy.RemoteStateListener; import wsi.ra.tool.BasicResourceLoader; import eva2.EvAInfo; +import eva2.gui.BeanInspector; import eva2.gui.ExtAction; import eva2.gui.HtmlDemo; import eva2.gui.JEFrame; import eva2.gui.JEFrameRegister; import eva2.gui.JExtMenu; -import eva2.gui.JTabbedModuleFrame; +import eva2.gui.EvATabbedFrameMaker; import eva2.gui.LogPanel; import eva2.server.EvAServer; import eva2.server.go.InterfaceGOParameters; import eva2.server.modules.AbstractModuleAdapter; +import eva2.server.modules.GenericModuleAdapter; import eva2.server.modules.ModuleAdapter; import eva2.tools.EVAERROR; import eva2.tools.EVAHELP; import eva2.tools.ReflectPackage; import eva2.tools.Serializer; +import eva2.tools.StringTools; /** * @@ -122,6 +128,8 @@ public class EvAClient implements RemoteStateListener, Serializable { private transient String currentModule = null; Vector superListenerList = null; + private boolean withGUI = true ; + private EvATabbedFrameMaker frmMkr = null; public void addRemoteStateListener(RemoteStateListener l) { if (superListenerList == null) superListenerList = new Vector(); @@ -165,22 +173,74 @@ public class EvAClient implements RemoteStateListener, Serializable { * */ public EvAClient(final String hostName) { - this(hostName, null); + this(hostName, null, false, false); } - + /** - * Constructor of GUI of EvA2. - * Works as client for the EvA2 server. - * + * A constructor. Splash screen is optional, Gui is activated, no parent window. + * + * @see #EvAClient(String, Window, String, boolean, boolean, boolean) + * @param hostName + * @param paramsFile + * @param autorun + * @param nosplash */ - public EvAClient(final String hostName, final Window parent) { - final SplashScreen fSplashScreen = new SplashScreen(EvAInfo.splashLocation); + public EvAClient(final String hostName, final String paramsFile, boolean autorun, boolean nosplash) { + this(hostName, null, paramsFile, autorun, nosplash, false); + } + + /** + * A constructor with optional spash screen. + * @see #EvAClient(String, String, boolean, boolean) + * + * @param hostName + * @param autorun + * @param nosplash + */ + public EvAClient(final String hostName, boolean autorun, boolean nosplash) { + this(hostName, null, autorun, nosplash); + } + + /** + * A constructor with optional spash screen. + * @see #EvAClient(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) { + this(hostName, null, paramsFile, autorun, noSplash, noGui); + } + /** + * Constructor of GUI of EvA2. Works as client for the EvA2 server. + * + * @param hostName + * @param parent + * @param paramsFile + * @param autorun + * @param noSplash + * @param noGui + */ + + public EvAClient(final String hostName, final Window parent, final String paramsFile, final boolean autorun, final boolean noSplash, final boolean noGui) { + final SplashScreenShell fSplashScreen = new SplashScreenShell(EvAInfo.splashLocation); // preload some classes (into system cache) in a parallel thread preloadClasses(); + withGUI = !noGui; // activate the splash screen (show later using SwingUtilities) - fSplashScreen.splash(); + if (!noSplash && withGUI) { + try { + fSplashScreen.splash(); + } catch(HeadlessException e) { + System.err.println("Error: no xserver present - deactivating GUI."); + withGUI=false; + } + } currentModule = null; @@ -189,14 +249,24 @@ public class EvAClient implements RemoteStateListener, Serializable { SwingUtilities.invokeLater( new Runnable() { public void run(){ long startTime = System.currentTimeMillis(); - init(hostName, parent); // this takes a bit + init(hostName, paramsFile, parent); // this takes a bit long wait = System.currentTimeMillis() - startTime; - try { - // if splashScreenTime has not passed, sleep some more - if (wait < splashScreenTime) Thread.sleep(splashScreenTime - wait); - } catch (Exception e) {} + if (!autorun) { + if (!noSplash) try { + // if splashScreenTime has not passed, sleep some more + if (wait < splashScreenTime) Thread.sleep(splashScreenTime - wait); + } catch (Exception e) {} + } else { + if (!withGUI && (currentModuleAdapter instanceof GenericModuleAdapter)) { + // do not save new parameters for an autorun without GUI - they werent changed manually anyways. + ((GenericModuleAdapter)currentModuleAdapter).getStatistics().setSaveParams(false); + System.out.println("Autorun without GUI - not saving statistics parameters..."); + } + if (withGUI) frmMkr.onUserStart(); + else currentModuleAdapter.startOpt(); + } // close splash screen - fSplashScreen.dispose(); + if (!noSplash && withGUI) fSplashScreen.dispose(); } }); } @@ -207,9 +277,9 @@ public class EvAClient implements RemoteStateListener, Serializable { } /** - * + * Sets given hostname and tries to load GOParamsters from given file if non null. */ - private void init(String hostName, final Window parent) { + private void init(String hostName, String paramsFile, final Window parent) { //EVA_EDITOR_PROPERTIES useDefaultModule = getProperty("DefaultModule"); @@ -218,53 +288,54 @@ public class EvAClient implements RemoteStateListener, Serializable { if (useDefaultModule.length() < 1) useDefaultModule = null; } - - m_Frame = new JEFrame(); - BasicResourceLoader loader = BasicResourceLoader.instance(); - byte[] bytes = loader.getBytesFromResourceLocation(EvAInfo.iconLocation); - try { - m_Frame.setIconImage(Toolkit.getDefaultToolkit().createImage(bytes)); - } catch (java.lang.NullPointerException e) { - System.out.println("Could not find EvA2 icon, please move resources folder to working directory!"); - } - m_Frame.setTitle(EvAInfo.productName + " workbench"); - - try { - Thread.sleep(200); - } catch (Exception e) { - System.out.println("Error" + e.getMessage()); - } - - m_Frame.getContentPane().setLayout(new BorderLayout()); - m_LogPanel = new LogPanel(); - m_Frame.getContentPane().add(m_LogPanel, BorderLayout.CENTER); - m_ProgressBar = new JProgressBar(); - m_Frame.getContentPane().add(m_ProgressBar, BorderLayout.SOUTH); - - if (getProperty("ShowModules") != null) showLoadModules = true; - else showLoadModules = false; // may be set to true again if default module couldnt be loaded - - createActions(); - - if (useDefaultModule != null) { - loadModuleFromServer(useDefaultModule);//loadSpecificModule - } - - buildMenu(); - - m_Frame.addWindowListener(new WindowAdapter() { - public void windowClosing(WindowEvent e) { - System.out.println("Closing EvA2 Client. Bye!"); - m_Frame.dispose(); - Set keys = System.getenv().keySet(); - if (keys.contains("MATLAB")) { - System.out.println("Seems like Ive been started from Matlab: not killing JVM"); - } else { - if (parent == null) System.exit(1); - } + if (withGUI ) { + m_Frame = new JEFrame(); + BasicResourceLoader loader = BasicResourceLoader.instance(); + byte[] bytes = loader.getBytesFromResourceLocation(EvAInfo.iconLocation); + try { + m_Frame.setIconImage(Toolkit.getDefaultToolkit().createImage(bytes)); + } catch (java.lang.NullPointerException e) { + System.out.println("Could not find EvA2 icon, please move resources folder to working directory!"); } - }); + m_Frame.setTitle(EvAInfo.productName + " workbench"); + try { + Thread.sleep(200); + } catch (Exception e) { + System.out.println("Error" + e.getMessage()); + } + + m_Frame.getContentPane().setLayout(new BorderLayout()); + m_LogPanel = new LogPanel(); + m_Frame.getContentPane().add(m_LogPanel, BorderLayout.CENTER); + m_ProgressBar = new JProgressBar(); + m_Frame.getContentPane().add(m_ProgressBar, BorderLayout.SOUTH); + + if (getProperty("ShowModules") != null) showLoadModules = true; + else showLoadModules = false; // may be set to true again if default module couldnt be loaded + + createActions(); + } + if (useDefaultModule != null) { + loadModuleFromServer(useDefaultModule, paramsFile);//loadSpecificModule + } + + if (withGUI) { + buildMenu(); + m_Frame.addWindowListener(new WindowAdapter() { + public void windowClosing(WindowEvent e) { + System.out.println("Closing EvA2 Client. Bye!"); + m_Frame.dispose(); + Set keys = System.getenv().keySet(); + if (keys.contains("MATLAB")) { + System.out.println("Seems like Ive been started from Matlab: not killing JVM"); + } else { + if (parent == null) System.exit(1); + } + } + }); + } + if (m_ComAdapter != null) { if (hostName != null) selectHost(hostName); m_ComAdapter.setLogPanel(m_LogPanel); @@ -273,38 +344,87 @@ public class EvAClient implements RemoteStateListener, Serializable { // m_mnuModule.setText("Select module"); // m_mnuModule.repaint(); - m_LogPanel.logMessage("Working directory is: " + System.getProperty("user.dir")); - m_LogPanel.logMessage("Class path is: " + System.getProperty("java.class.path",".")); + if (withGUI) { + m_LogPanel.logMessage("Working directory is: " + System.getProperty("user.dir")); + m_LogPanel.logMessage("Class path is: " + System.getProperty("java.class.path",".")); - if (!(m_Frame.isVisible())) { - Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); - m_Frame.setLocation((int)((screenSize.width-m_Frame.getWidth())/2), (int)((screenSize.height-m_Frame.getHeight())/2.5)); - m_Frame.pack(); - m_Frame.setVisible(true); + if (!(m_Frame.isVisible())) { + Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); + m_Frame.setLocation((int)((screenSize.width-m_Frame.getWidth())/2), (int)((screenSize.height-m_Frame.getHeight())/2.5)); + m_Frame.pack(); + m_Frame.setVisible(true); + } + m_LogPanel.logMessage("EvA2 ready"); // 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 } - m_LogPanel.logMessage("EvA2 ready"); // 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 } /** - * The one and only main of the client program. - * + * 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 PFILE: load the optimization parameter from the serialized file PFILE + * * @param args command line parameters */ public static void main(String[] args) { if (TRACE) { System.out.println(EVAHELP.getSystemPropertyString()); } - EvAClient Client = new EvAClient((args.length == 1) ? args[0] : null, null); + String[] keys= new String[]{"--help", "--autorun", "--nosplash", "--nogui", "--remotehost", "--params"}; + int[] arities = new int[]{0, 0, 0, 0, 1, 1}; + Object[] values = new Object[6]; + + Integer[] unknownArgs = StringTools.parseArguments(args, keys, arities, values, true); + + if (unknownArgs.length>0) { + System.err.println("Unrecognized command line options: "); + for (int i=0; i"+UIManager.getLookAndFeel().getClass().getName()); -// } String LAF = Serializer.loadString("LookAndFeel.ser"); @@ -525,7 +637,7 @@ public class EvAClient implements RemoteStateListener, Serializable { /** * */ - private void loadModuleFromServer(String selectedModule) { + private void loadModuleFromServer(String selectedModule, String paramsFile) { if (m_ComAdapter.getHostName() == null) { System.err.println("error in loadModuleFromServer!"); return; @@ -567,10 +679,12 @@ public class EvAClient implements RemoteStateListener, Serializable { } else { Serializer.storeString("lastmodule.ser", selectedModule); - loadSpecificModule(selectedModule); + loadSpecificModule(selectedModule, paramsFile); - m_actHost.setEnabled(true); - m_actAvailableHost.setEnabled(true); + if (withGUI) { + m_actHost.setEnabled(true); + m_actAvailableHost.setEnabled(true); + } logMessage("Selected Module: " + selectedModule); // m_LogPanel.statusMessage("Selected Module: " + selectedModule); } @@ -601,11 +715,11 @@ public class EvAClient implements RemoteStateListener, Serializable { } else return false; } - private void loadSpecificModule(String selectedModule) { + private void loadSpecificModule(String selectedModule, String paramsFile) { ModuleAdapter newModuleAdapter = null; // try { - newModuleAdapter = m_ComAdapter.getModuleAdapter(selectedModule); + newModuleAdapter = m_ComAdapter.getModuleAdapter(selectedModule, paramsFile, withGUI ? null : "EvA2"); } catch (Exception e) { logMessage("Error while m_ComAdapter.GetModuleAdapter Host: " + e.getMessage()); e.printStackTrace(); @@ -621,7 +735,7 @@ public class EvAClient implements RemoteStateListener, Serializable { System.setProperty("java.class.path", cp + System.getProperty("path.separator") + baseDir.getPath()); ReflectPackage.resetDynCP(); m_ComAdapter.updateLocalMainAdapter(); - loadSpecificModule(selectedModule); // end recursive call! handle with care! + loadSpecificModule(selectedModule, paramsFile); // end recursive call! handle with care! return; } showLoadModules = true; @@ -633,31 +747,32 @@ public class EvAClient implements RemoteStateListener, Serializable { newModuleAdapter.addRemoteStateListener((RemoteStateListener)this); } try { - // this (or rather: JModuleGeneralPanel) is where the start button etc come from! - JTabbedModuleFrame Temp = newModuleAdapter.getModuleFrame(); -// newModuleAdapter.setLogPanel(m_LogPanel); + if (withGUI) { + // this (or rather: EvAModuleButtonPanelMaker) is where the start button etc come from! + frmMkr = newModuleAdapter.getModuleFrame(); +// newModuleAdapter.setLogPanel(m_LogPanel); + JPanel moduleContainer = frmMkr.makePanel(); // MK the main frame is actually painted in here - JPanel moduleContainer = Temp.createContentPane(); // MK the frame is actually painted in here - // m_Frame.setLayout(new BorderLayout()); - boolean wasVisible = m_Frame.isVisible(); - m_Frame.setVisible(false); - m_Frame.getContentPane().removeAll(); + boolean wasVisible = m_Frame.isVisible(); + m_Frame.setVisible(false); + m_Frame.getContentPane().removeAll(); + + // nested info-panel so that we can stay with simple borderlayouts + JPanel infoPanel = new JPanel(); + infoPanel.setLayout(new BorderLayout()); + infoPanel.add(m_ProgressBar, BorderLayout.SOUTH); + infoPanel.add(m_LogPanel, BorderLayout.NORTH); + + m_Frame.add(frmMkr.getToolBar(), BorderLayout.NORTH); + m_Frame.add(moduleContainer, BorderLayout.CENTER); + //m_Frame.add(m_ProgressBar, BorderLayout.CENTER); + //m_Frame.add(m_LogPanel, BorderLayout.SOUTH); + m_Frame.add(infoPanel, BorderLayout.SOUTH); + + m_Frame.pack(); + m_Frame.setVisible(wasVisible); + } - // nested info-panel so that we can stay with simple borderlayouts - JPanel infoPanel = new JPanel(); - infoPanel.setLayout(new BorderLayout()); - infoPanel.add(m_ProgressBar, BorderLayout.SOUTH); - infoPanel.add(m_LogPanel, BorderLayout.NORTH); - - m_Frame.add(Temp.getToolBar(), BorderLayout.NORTH); - m_Frame.add(moduleContainer, BorderLayout.CENTER); - //m_Frame.add(m_ProgressBar, BorderLayout.CENTER); - //m_Frame.add(m_LogPanel, BorderLayout.SOUTH); - m_Frame.add(infoPanel, BorderLayout.SOUTH); - - m_Frame.pack(); - m_Frame.setVisible(wasVisible); - currentModule = selectedModule; // m_ModulGUIContainer.add(Temp); } catch (Exception e) { @@ -701,7 +816,7 @@ public class EvAClient implements RemoteStateListener, Serializable { logMessage("Selected Host: " + hostName); if (currentModule != null) { logMessage("Reloading module from server..."); - loadModuleFromServer(currentModule); + loadModuleFromServer(currentModule, null); } // m_mnuModule.setText("Select module"); @@ -782,6 +897,7 @@ public class EvAClient implements RemoteStateListener, Serializable { } long t = (System.currentTimeMillis() - startTime); logMessage(String.format("Stopped after %1$d.%2$tL s", (t / 1000), (t % 1000))); + if (!withGUI) System.exit(0); } /** @@ -806,7 +922,28 @@ public class EvAClient implements RemoteStateListener, Serializable { } } -final class SplashScreen extends Frame { +final class SplashScreenShell { + SplashScreen splScr = null; + String imgLoc = null; + + public SplashScreenShell(String imageLoc) { + imgLoc = imageLoc; + } + + public void splash() { + splScr = new SplashScreen(imgLoc); + splScr.splash(); + } + + public void dispose() { + if (splScr!=null) { + splScr.dispose(); + splScr=null; + } + } +} + +class SplashScreen extends Frame { private static final long serialVersionUID = 1281793825850423095L; String imgLocation; diff --git a/src/eva2/client/EvAComAdapter.java b/src/eva2/client/EvAComAdapter.java index e60d837b..dc42a92a 100644 --- a/src/eva2/client/EvAComAdapter.java +++ b/src/eva2/client/EvAComAdapter.java @@ -63,14 +63,14 @@ public class EvAComAdapter extends ComAdapter { * Creates the ModulAdapters RMI Object on the server * @return */ - public ModuleAdapter getModuleAdapter(String str) { + public ModuleAdapter getModuleAdapter(String selectedModuleName, String paramsFile, String noGuiStatsFile) { ModuleAdapter newModuleAdapter; if ((m_RMIServer == null) && isRunLocally()) { //ret = evaAdapter.getModuleAdapter(Modul, hostAdd, this.m_MainAdapterClient); - newModuleAdapter = getLocalMainAdapter().getModuleAdapter(str, true, getHostName(), null); + newModuleAdapter = getLocalMainAdapter().getModuleAdapter(selectedModuleName, true, getHostName(), paramsFile, noGuiStatsFile, null); } else { - newModuleAdapter = ((RMIConnectionEvA)getConnection(getHostName())).getModuleAdapter(str); - if (newModuleAdapter == null) System.err.println("RMI Error for getting ModuleAdapterObject : " + str); + newModuleAdapter = ((RMIConnectionEvA)getConnection(getHostName())).getModuleAdapter(selectedModuleName); + if (newModuleAdapter == null) System.err.println("RMI Error for getting ModuleAdapterObject : " + selectedModuleName); } return newModuleAdapter; } diff --git a/src/eva2/gui/BeanInspector.java b/src/eva2/gui/BeanInspector.java index 6b0dd7c8..5b89bdc7 100644 --- a/src/eva2/gui/BeanInspector.java +++ b/src/eva2/gui/BeanInspector.java @@ -597,7 +597,8 @@ public class BeanInspector { /** - * Try to get an object member value. + * Try to get an object member value using the default getter. + * Returns null if not successful. * * @param obj * @param mem diff --git a/src/eva2/gui/JModuleGeneralPanel.java b/src/eva2/gui/EvAModuleButtonPanelMaker.java similarity index 88% rename from src/eva2/gui/JModuleGeneralPanel.java rename to src/eva2/gui/EvAModuleButtonPanelMaker.java index 0574dee2..4d8ac319 100644 --- a/src/eva2/gui/JModuleGeneralPanel.java +++ b/src/eva2/gui/EvAModuleButtonPanelMaker.java @@ -33,13 +33,11 @@ import eva2.server.go.problems.InterfaceOptimizationProblem; import eva2.server.go.strategies.InterfaceOptimizer; import eva2.server.modules.AbstractModuleAdapter; import eva2.server.modules.ModuleAdapter; -/*==========================================================================* - * CLASS DECLARATION - *==========================================================================*/ + /** - * + * Contains the GUI elements of start and stop buttons and optionally a help button. */ -public class JModuleGeneralPanel implements RemoteStateListener, Serializable { +public class EvAModuleButtonPanelMaker implements RemoteStateListener, Serializable, PanelMaker { public static boolean TRACE = false; private String m_Name ="undefined"; private ModuleAdapter m_Adapter; @@ -56,16 +54,14 @@ public class JModuleGeneralPanel implements RemoteStateListener, Serializable { /** * */ - public JModuleGeneralPanel(ModuleAdapter Adapter, boolean state) { + public EvAModuleButtonPanelMaker(ModuleAdapter Adapter, boolean state) { m_Name = "GENERAL"; m_StateRunning = state; - if (TRACE) System.out.println("Constructor JModuleGeneralPanel:"); + if (TRACE) System.out.println("Constructor EvAModuleButtonPanelMaker:"); m_Adapter = Adapter; } - /** - * - */ - public JComponent installActions() { + + public JComponent makePanel() { String myhostname = null; m_Panel= new JPanel(); @@ -89,18 +85,8 @@ public class JModuleGeneralPanel implements RemoteStateListener, Serializable { //System.out.println("Start tm_RunButton.addActionListener Run Opt pressed ====================!!!!!!!!!!!!!!!!!!"); m_RunButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){ - //System.out.println("Run Opt pressed !!!!!!!!!!!!!!!!======================!!"); - try { - m_Adapter.startOpt(); - m_actStop.setEnabled(true); - m_RunButton.setEnabled(false); - m_PPButton.setEnabled(false); -// m_RestartButton.setEnabled(false); -// m_JHelpButton.setEnabled(true); - } catch (Exception ee) { - ee.printStackTrace(); - System.err.print ("Error in run: " +ee +" : " + ee.getMessage() ); - } + //Run Opt pressed ! + onUserStart(); } } ); @@ -181,6 +167,20 @@ public class JModuleGeneralPanel implements RemoteStateListener, Serializable { return m_Panel; } + public void onUserStart() { + try { + m_Adapter.startOpt(); + m_actStop.setEnabled(true); + m_RunButton.setEnabled(false); + m_PPButton.setEnabled(false); +// m_RestartButton.setEnabled(false); +// m_JHelpButton.setEnabled(true); + } catch (Exception ee) { + ee.printStackTrace(); + System.err.print ("Error in run: " +ee +" : " + ee.getMessage() ); + } + } + private void makeHelpButton() { /////////////////////////////////////////////////////////////// if (m_HelperFileName!=null && (!m_HelperFileName.equals(""))) { @@ -210,7 +210,7 @@ public class JModuleGeneralPanel implements RemoteStateListener, Serializable { * */ public void performedStop() { - if (TRACE) System.out.println("JModuleGeneralPanel.stopOptPerformed"); + if (TRACE) System.out.println("EvAModuleButtonPanelMaker.stopOptPerformed"); m_RunButton.setEnabled(true); m_PPButton.setEnabled(true); m_RunButton.repaint(); diff --git a/src/eva2/gui/EvATabbedFrameMaker.java b/src/eva2/gui/EvATabbedFrameMaker.java new file mode 100644 index 00000000..d2560bc0 --- /dev/null +++ b/src/eva2/gui/EvATabbedFrameMaker.java @@ -0,0 +1,76 @@ +package eva2.gui; +/* + * Title: EvA2 + * Description: + * Copyright: Copyright (c) 2003 + * Company: University of Tuebingen, Computer Architecture + * @author Holger Ulmer, Felix Streichert, Hannes Planatscher + * @version: $Revision: 272 $ + * $Date: 2007-11-21 18:06:36 +0100 (Wed, 21 Nov 2007) $ + * $Author: mkron $ + */ +/*==========================================================================* + * IMPORTS + *==========================================================================*/ + +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.io.Serializable; +import java.util.ArrayList; + +import javax.swing.JPanel; +import javax.swing.JTabbedPane; + +/** + * Produces the main EvA2 frame and a tool bar instance. + */ +public class EvATabbedFrameMaker implements Serializable, PanelMaker { + private ArrayList guiContainer; + private JExtToolBar m_BarStandard; + EvAModuleButtonPanelMaker butPanelMkr=null; + + public EvATabbedFrameMaker(ArrayList GUIContainer) { + guiContainer = GUIContainer; + } + + public JPanel makePanel() { + JPanel m_SuperPanel = new JPanel(); + m_SuperPanel.setLayout(new GridBagLayout()); + GridBagConstraints gbconst = new GridBagConstraints(); + gbconst.fill = GridBagConstraints.BOTH; + gbconst.weightx = 1; + gbconst.weighty = 1; + gbconst.gridwidth = GridBagConstraints.REMAINDER; + + JTabbedPane m_MainPanel = new JTabbedPane(); + + m_BarStandard = new JExtToolBar(); + m_BarStandard.setFloatable(false); + + for (int i=0;i m_ClassesLongName; private GenericObjectEditor m_goe = null; @@ -90,7 +89,8 @@ public class GOEPanel extends JPanel implements ItemListener { m_OpenBut.setEnabled(true); m_OpenBut.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { - Object object = openObject(); + Object object = FileTools.openObject(m_OpenBut, m_goe.getClassType()); +// Object object = openObject(); if (object != null) { // setValue takes care of: Making sure obj is of right type, // and firing property change. @@ -107,7 +107,8 @@ public class GOEPanel extends JPanel implements ItemListener { m_SaveBut.setEnabled(true); m_SaveBut.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { - saveObject(m_goe.getValue()); + FileTools.saveObjectWithFileChooser(m_SaveBut, m_goe.getValue()); +// saveObject(m_goe.getValue()); } }); // @@ -195,68 +196,6 @@ public class GOEPanel extends JPanel implements ItemListener { m_ObjectChooser.addItemListener(this); } - /** - * Opens an object from a file selected by the user. - * - * @return the loaded object, or null if the operation was cancelled - */ - protected Object openObject() { - if (m_FileChooser == null) { - createFileChooser(); - } - int returnVal = m_FileChooser.showOpenDialog(this); - if (returnVal == JFileChooser.APPROVE_OPTION) { - File selected = m_FileChooser.getSelectedFile(); - try { - ObjectInputStream oi = new ObjectInputStream(new BufferedInputStream(new FileInputStream(selected))); - Object obj = oi.readObject(); - oi.close(); - if (!m_goe.getClassType().isAssignableFrom(obj.getClass())) { - throw new Exception("Object not of type: " + m_goe.getClassType().getName()); - } - return obj; - } catch (Exception ex) { - JOptionPane.showMessageDialog(this, - "Couldn't read object: " - + selected.getName() - + "\n" + ex.getMessage(), - "Open object file", - JOptionPane.ERROR_MESSAGE); - } - } - return null; - } - - /** Saves the current object to a file selected by the user. - * @param object The object to save. - */ - protected void saveObject(Object object) { - - if (m_FileChooser == null) { - createFileChooser(); - } - int returnVal = m_FileChooser.showSaveDialog(this); - if (returnVal == JFileChooser.APPROVE_OPTION) { - File sFile = m_FileChooser.getSelectedFile(); - try { - ObjectOutputStream oo = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(sFile))); - oo.writeObject(object); - oo.close(); - } catch (Exception ex) { - JOptionPane.showMessageDialog(this, - "Couldn't write to file: " - + sFile.getName() - + "\n" + ex.getMessage(), - "Save object", - JOptionPane.ERROR_MESSAGE); - } - } - } - protected void createFileChooser() { - m_FileChooser = new JFileChooser(new File("/resources")); - m_FileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); - } - /** * Makes a copy of an object using serialization * @param source the object to copy diff --git a/src/eva2/gui/GenericObjectEditor.java b/src/eva2/gui/GenericObjectEditor.java index 07b66ace..437dd3d0 100644 --- a/src/eva2/gui/GenericObjectEditor.java +++ b/src/eva2/gui/GenericObjectEditor.java @@ -143,7 +143,12 @@ public class GenericObjectEditor implements PropertyEditor { if (TRACE) System.out.println("Class " + class1 + " wants to be hidden from GOE, skipping..."); continue; } - } catch (Exception e) {} + } catch (Exception e) { + + } catch (Error e) { + System.err.println("Error on checking fields of " + class1 + ": " + e); + continue; + } // if (f) if (!Modifier.isAbstract(m) && !class1.isInterface()) { // dont take abstract classes or interfaces try { diff --git a/src/eva2/gui/GraphPointSet.java b/src/eva2/gui/GraphPointSet.java index 11067ff9..9842a416 100644 --- a/src/eva2/gui/GraphPointSet.java +++ b/src/eva2/gui/GraphPointSet.java @@ -20,6 +20,8 @@ import java.awt.BasicStroke; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; + +import eva2.tools.Mathematics; /*==========================================================================* * CLASS DECLARATION *==========================================================================*/ @@ -30,7 +32,7 @@ public class GraphPointSet { private String m_InfoString = "Incomplete_Run"; private int m_GraphLabel; private int colorOffset = 0; - private ArrayList m_PointSetContainer = new ArrayList(); + private ArrayList m_PointSetContainer = new ArrayList(); private float m_Stroke = (float) 1.0; private boolean m_isStatisticsGraph = false; // private DPointSet m_PointSet_1; @@ -317,74 +319,67 @@ public class GraphPointSet { * @param useForce forces the add even if point counts mismatch, maybe losing some data points */ public void addGraph (GraphPointSet set,DMeasures measures, boolean useForce) { - if (set.m_ConnectedPointSet.getSize()!=m_ConnectedPointSet.getSize() && - m_ConnectedPointSet.getSize()!=0 && !useForce) { - System.err.println("WARNING addGraph not possible, lost last graph"); - System.err.println(" m_ConnectedPointSet.getSize() "+ m_ConnectedPointSet.getSize()); - return; - } - m_isStatisticsGraph = true; - removeAllPoints(); - m_ConnectedPointSet.setColor(set.getColor()); -// m_PointSet_1.setColor(m_ConnectedPointSet.getColor()); -// m_PointSet_2.setColor(m_ConnectedPointSet.getColor()); -// m_PointSet_3.setColor(m_ConnectedPointSet.getColor()); - m_PointSetContainer.add(set.getPointSet()); - int[] index = new int[m_PointSetContainer.size()]; - int[] GraphSize = new int[m_PointSetContainer.size()]; - for (int i=0;i index[i] ) { -// doit = true; -// break; -// } -// } - } -// m_PointSet_2.removeAllPoints(); + if (set.m_ConnectedPointSet.getSize()!=m_ConnectedPointSet.getSize() && + m_ConnectedPointSet.getSize()!=0 && !useForce) { + System.err.println("WARNING addGraph not possible, lost last graph"); + System.err.println(" m_ConnectedPointSet.getSize() "+ m_ConnectedPointSet.getSize()); + return; + } + if (set.getPointSet().getSize()==0) { + System.err.println("Refusing to add empty graph..."); + return; + } + m_isStatisticsGraph = true; + removeAllPoints(); + m_ConnectedPointSet.setColor(set.getColor()); + + m_PointSetContainer.add(set.getPointSet()); + int[] index = new int[m_PointSetContainer.size()]; + int[] GraphSize = new int[m_PointSetContainer.size()]; + for (int i=0;i[] constructorArr = module.getConstructors(); // create a module instance - Constructor[] Constructor = module.getConstructors(); - Object[] Para = new Object[2]; - Class paramTypes[] = (Constructor[0]).getParameterTypes(); - Para[0] = paramTypes[0].cast(adapterName); - Para[1] = paramTypes[1].cast(Client); - m_ModuleAdapter = (ModuleAdapter) Constructor[0].newInstance(Para); + if ((paramsFile==null && noGuiLogFile==null) || !module.equals(GOModuleAdapter.class)) { + if (paramsFile!=null) System.err.println("Cant load params - no matching constructor found for " + adapterName + " (ModuleServer)"); + if (noGuiLogFile!=null) System.err.println("Cant deactivate GUI - no matching constructor found for " + adapterName + " (ModuleServer)"); + Object[] Para = new Object[2]; + Class paramTypes[] = (constructorArr[0]).getParameterTypes(); + Para[0] = paramTypes[0].cast(adapterName); + Para[1] = paramTypes[1].cast(Client); + m_ModuleAdapter = (ModuleAdapter) constructorArr[0].newInstance(Para); + } else { + Object[] Para = new Object[4]; + Para[0] = (String)adapterName; + Para[1] = (String)paramsFile; + Para[2] = (String)noGuiLogFile; + Para[3] = (MainAdapterClient)Client; + int constrIndex=0; + while ((constructorArr[constrIndex].getParameterTypes().length!=4) && (constrIndex < constructorArr.length)) { + constrIndex++; + } + m_ModuleAdapter = (ModuleAdapter) constructorArr[constrIndex].newInstance(Para); + } if (!runWithoutRMI) { // if we're using RMI, send the object to a remote server // for this to work the class of m_ModuleAdapter itself must implement the ModuleAdapter interface // for a strange reason, it is _not_ enough if a superclass implements the same interface! diff --git a/src/eva2/server/go/GOStandaloneVersion.java b/src/eva2/server/go/GOStandaloneVersion.java index 4911a129..8f09b26d 100644 --- a/src/eva2/server/go/GOStandaloneVersion.java +++ b/src/eva2/server/go/GOStandaloneVersion.java @@ -180,11 +180,11 @@ public class GOStandaloneVersion implements InterfaceGOStandalone, InterfacePopu System.out.println("No Class found for " + tmp); } if ((object != null) && (editor != null)) paraPanel.registerEditor(object, editor); - this.m_O1 = (paraPanel.installActions()); + this.m_O1 = (paraPanel.makePanel()); EvAClient.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.installActions()); + this.m_O2 = (paraPanel2.makePanel()); ((JTabbedPane)this.m_OptionsPanel).addTab("GO Parameters", this.m_O2); ((JTabbedPane)this.m_OptionsPanel).addTab("GO Statistics", this.m_O1); this.m_MainPanel.add(this.m_OptionsPanel, BorderLayout.CENTER); diff --git a/src/eva2/server/go/mocco/MOCCOProblemInitialization.java b/src/eva2/server/go/mocco/MOCCOProblemInitialization.java index 88c6812a..73d6c650 100644 --- a/src/eva2/server/go/mocco/MOCCOProblemInitialization.java +++ b/src/eva2/server/go/mocco/MOCCOProblemInitialization.java @@ -83,7 +83,7 @@ public class MOCCOProblemInitialization extends MOCCOPhase implements InterfaceP this.m_Mocco.m_JPanelParameters.setLayout(new BorderLayout()); this.m_Mocco.m_JPanelParameters.add(tmpP, BorderLayout.NORTH); JParaPanel paraPanel = new JParaPanel(this.m_Mocco.m_State.m_OriginalProblem, "MyGUI"); - this.m_Mocco.m_JPanelParameters.add(paraPanel.installActions(), BorderLayout.CENTER); + this.m_Mocco.m_JPanelParameters.add(paraPanel.makePanel(), BorderLayout.CENTER); } ActionListener continue2 = new ActionListener() { diff --git a/src/eva2/server/go/mocco/MOCCOProblemRedefinition.java b/src/eva2/server/go/mocco/MOCCOProblemRedefinition.java index b5889b08..ef323163 100644 --- a/src/eva2/server/go/mocco/MOCCOProblemRedefinition.java +++ b/src/eva2/server/go/mocco/MOCCOProblemRedefinition.java @@ -64,7 +64,7 @@ public class MOCCOProblemRedefinition extends MOCCOPhase implements InterfacePro this.m_Mocco.m_JPanelParameters.add(tmpP, BorderLayout.NORTH); JParaPanel paraPanel = new JParaPanel(this.m_Problem, "MyGUI"); - tmpC = (paraPanel.installActions()); + tmpC = (paraPanel.makePanel()); this.m_Mocco.m_JPanelParameters.add(tmpC, BorderLayout.CENTER); this.m_Mocco.m_JFrame.setVisible(true); diff --git a/src/eva2/server/go/operators/crossover/TestESCrossover.java b/src/eva2/server/go/operators/crossover/TestESCrossover.java index c03b2fc0..6970f559 100644 --- a/src/eva2/server/go/operators/crossover/TestESCrossover.java +++ b/src/eva2/server/go/operators/crossover/TestESCrossover.java @@ -81,7 +81,7 @@ public class TestESCrossover implements java.io.Serializable { this.m_ButtonPanel.add(this.m_CrossButton); this.m_MainPanel.add(this.m_ButtonPanel, BorderLayout.NORTH); // build the Options Panel - this.m_OptionsPanel = (new JParaPanel(this, "MyGUI").installActions()); + this.m_OptionsPanel = (new JParaPanel(this, "MyGUI").makePanel()); this.m_MainPanel.add(this.m_OptionsPanel, BorderLayout.CENTER); // The plot frame double[] tmpD = new double[2]; diff --git a/src/eva2/server/go/operators/paramcontrol/AbstractLinearParamAdaption.java b/src/eva2/server/go/operators/paramcontrol/AbstractLinearParamAdaption.java new file mode 100644 index 00000000..3a3ed7b7 --- /dev/null +++ b/src/eva2/server/go/operators/paramcontrol/AbstractLinearParamAdaption.java @@ -0,0 +1,62 @@ +package eva2.server.go.operators.paramcontrol; + +import java.io.Serializable; + +import eva2.gui.BeanInspector; +import eva2.server.go.populations.Population; +import eva2.tools.Mathematics; + +/** + * Simple linear adaption of a String property. + * + * @author mkron + * + */ +public abstract class AbstractLinearParamAdaption implements ParamAdaption, Serializable { + private double startV=0.2, endV=0.7; + + public AbstractLinearParamAdaption(AbstractLinearParamAdaption o) { + startV=o.startV; + endV=o.endV; + } + + public AbstractLinearParamAdaption(double startValue, double endValue) { + this.startV = startValue; + this.endV = endValue; + } + + @Override + public abstract Object clone(); + + public Object calcValue(Object obj, Population pop, int iteration, int maxIteration) { + return Mathematics.linearInterpolation(iteration, 0, maxIteration, startV, endV); + } + + public abstract String getControlledParam(); + + public void init(Object obj, Population pop, Object[] initialValues) { + BeanInspector.setMem(obj, getControlledParam(), startV); + } + public void finish(Object obj, Population pop) {} + + public double getStartV() { + return startV; + } + + public void setStartV(double startV) { + this.startV = startV; + } + + public double getEndV() { + return endV; + } + + public void setEndV(double endV) { + this.endV = endV; + } + + public String getName() { + return "Lin.adpt." + getControlledParam() + "(" + startV + "-" + endV + ")"; + } + +} diff --git a/src/eva2/server/go/operators/paramcontrol/AbstractParameterControl.java b/src/eva2/server/go/operators/paramcontrol/AbstractParameterControl.java index d54968f3..a8f79418 100644 --- a/src/eva2/server/go/operators/paramcontrol/AbstractParameterControl.java +++ b/src/eva2/server/go/operators/paramcontrol/AbstractParameterControl.java @@ -1,6 +1,7 @@ package eva2.server.go.operators.paramcontrol; import eva2.gui.BeanInspector; +import eva2.server.go.populations.Population; /** * Convenience class. Besides the init() method, two more remain to be implemented: @@ -8,6 +9,9 @@ import eva2.gui.BeanInspector; * and the second one to produce an object array of the same length with the values to be assigned * at the iteration. If there is no iteration known, iteration counts will be set to -1. * + * This class can be used to implement strategies to adapt multiple parameters within one strategy. + * For single parameter adaption, better use the ParamAdaption inheritance tree and the ParameterControlManager class. + * * @author mkron * */ @@ -15,7 +19,15 @@ public abstract class AbstractParameterControl implements InterfaceParameterCont public Object[] initialValues = null; protected static boolean TRACE=false; - public void init(Object obj) { + public AbstractParameterControl() { } + + public AbstractParameterControl(AbstractParameterControl o) { + initialValues = o.initialValues.clone(); + } + + public abstract Object clone(); + + public void init(Object obj, Population initialPop) { String[] params = getControlledParameters(); if (params != null) { initialValues=new Object[params.length]; @@ -23,16 +35,16 @@ public abstract class AbstractParameterControl implements InterfaceParameterCont } } - public void finish(Object obj) { + public void finish(Object obj, Population finalPop) { String[] params = getControlledParameters(); if (params != null) { for (int i=0; i names = new Vector(singleAdapters.length); + for (int i = 0; i < singleAdapters.length; i++) { + String prm=singleAdapters[i].getControlledParam(); + if (prm!=null) names.add(prm); + } + return names.toArray(new String[names.size()]); + } else return null; + } + + /** + * Retrieve the values of the adaptable parameters at a given iteration. + * If the maximum iteration is not known, both iteration and maxIteration will be set to -1. + * + * @param obj The instance which is controlled + * @param iteration current iteration (or -1 if unknown) + * @param maxIteration maximum iteration count (or -1 if unknown) + * @return + */ + public Object[] getValues(Object obj, Population pop, int iteration, int maxIteration) { + if (singleAdapters != null) { + Object[] vals = new Object[singleAdapters.length]; + for (int i = 0; i < vals.length; i++) { + vals[i]=singleAdapters[i].calcValue(obj, pop, iteration, maxIteration); + } + return vals; + } else return null; + } + + public ParamAdaption[] getSingleAdapters() { + return singleAdapters; + } + + public void setSingleAdapters(ParamAdaption[] singleAdapters) { + this.singleAdapters = singleAdapters; + } + + public String globalInfo() { + return "Define a list of dynamically adapted parameters."; + } + + public String getName() { + return "ParameterControlManager"; + } +} diff --git a/src/eva2/server/go/operators/paretofrontmetrics/MetricD1ApproxParetoFront.java b/src/eva2/server/go/operators/paretofrontmetrics/MetricD1ApproxParetoFront.java index bf60b778..d9bcf4c8 100644 --- a/src/eva2/server/go/operators/paretofrontmetrics/MetricD1ApproxParetoFront.java +++ b/src/eva2/server/go/operators/paretofrontmetrics/MetricD1ApproxParetoFront.java @@ -8,7 +8,7 @@ import eva2.server.go.individuals.AbstractEAIndividual; import eva2.server.go.operators.archiving.ArchivingAllDominating; import eva2.server.go.populations.Population; import eva2.server.go.problems.AbstractMultiObjectiveOptimizationProblem; -import eva2.server.go.tools.FileLoader; +import eva2.server.go.tools.FileTools; /** The D1* Pareto front metric requires a refrence Pareto front * and calculate the distance between the true Pareto front and @@ -61,7 +61,7 @@ public class MetricD1ApproxParetoFront implements eva2.server.go.operators.paret * */ private void loadReferenceData() { - String[] tmpS, lines = FileLoader.loadStringsFromFile(this.m_InputFilePath.getCompleteFilePath()); + String[] tmpS, lines = FileTools.loadStringsFromFile(this.m_InputFilePath.getCompleteFilePath()); if (lines == null) System.out.println("Failed to read "+this.m_InputFilePath.getCompleteFilePath()); lines[0].trim(); this.m_Titles = lines[0].split("\t"); diff --git a/src/eva2/server/go/operators/paretofrontmetrics/MetricD1TrueParetoFront.java b/src/eva2/server/go/operators/paretofrontmetrics/MetricD1TrueParetoFront.java index ec5f7628..8de1950c 100644 --- a/src/eva2/server/go/operators/paretofrontmetrics/MetricD1TrueParetoFront.java +++ b/src/eva2/server/go/operators/paretofrontmetrics/MetricD1TrueParetoFront.java @@ -8,7 +8,7 @@ import eva2.server.go.individuals.AbstractEAIndividual; import eva2.server.go.operators.archiving.ArchivingAllDominating; import eva2.server.go.populations.Population; import eva2.server.go.problems.AbstractMultiObjectiveOptimizationProblem; -import eva2.server.go.tools.FileLoader; +import eva2.server.go.tools.FileTools; /** The D1 Pareto front metric requires a refrence Pareto front * and calculate the distance between the current solution and @@ -64,7 +64,7 @@ public class MetricD1TrueParetoFront implements eva2.server.go.operators.paretof * */ private void loadReferenceData() { - String[] tmpS, lines = FileLoader.loadStringsFromFile(this.m_InputFilePath.getCompleteFilePath()); + String[] tmpS, lines = FileTools.loadStringsFromFile(this.m_InputFilePath.getCompleteFilePath()); if (lines == null) System.out.println("Failed to read "+this.m_InputFilePath.getCompleteFilePath()); lines[0].trim(); this.m_Titles = lines[0].split("\t"); diff --git a/src/eva2/server/go/operators/paretofrontmetrics/MetricErrorRatio.java b/src/eva2/server/go/operators/paretofrontmetrics/MetricErrorRatio.java index 528198da..349f91c8 100644 --- a/src/eva2/server/go/operators/paretofrontmetrics/MetricErrorRatio.java +++ b/src/eva2/server/go/operators/paretofrontmetrics/MetricErrorRatio.java @@ -11,7 +11,7 @@ import eva2.server.go.individuals.AbstractEAIndividual; import eva2.server.go.operators.archiving.ArchivingAllDominating; import eva2.server.go.populations.Population; import eva2.server.go.problems.AbstractMultiObjectiveOptimizationProblem; -import eva2.server.go.tools.FileLoader; +import eva2.server.go.tools.FileTools; /** The error ratio metric only suited for small discrete @@ -67,7 +67,7 @@ public class MetricErrorRatio implements eva2.server.go.operators.paretofrontmet * */ private void loadReferenceData() { - String[] tmpS, lines = FileLoader.loadStringsFromFile(this.m_InputFilePath.getCompleteFilePath()); + String[] tmpS, lines = FileTools.loadStringsFromFile(this.m_InputFilePath.getCompleteFilePath()); if (lines == null) System.out.println("Failed to read "+this.m_InputFilePath.getCompleteFilePath()); lines[0].trim(); this.m_Titles = lines[0].split("\t"); diff --git a/src/eva2/server/go/operators/paretofrontmetrics/MetricMaximumParetoFrontError.java b/src/eva2/server/go/operators/paretofrontmetrics/MetricMaximumParetoFrontError.java index cefd6ab1..e486f06e 100644 --- a/src/eva2/server/go/operators/paretofrontmetrics/MetricMaximumParetoFrontError.java +++ b/src/eva2/server/go/operators/paretofrontmetrics/MetricMaximumParetoFrontError.java @@ -8,7 +8,7 @@ import eva2.server.go.individuals.AbstractEAIndividual; import eva2.server.go.operators.archiving.ArchivingAllDominating; import eva2.server.go.populations.Population; import eva2.server.go.problems.AbstractMultiObjectiveOptimizationProblem; -import eva2.server.go.tools.FileLoader; +import eva2.server.go.tools.FileTools; /** Maximum Pareto Front Error gives the maximum distance of all minimum distances of each * element in the current solution to the true Pareto front. @@ -60,7 +60,7 @@ public class MetricMaximumParetoFrontError implements eva2.server.go.operators.p * */ private void loadReferenceData() { - String[] tmpS, lines = FileLoader.loadStringsFromFile(this.m_InputFilePath.getCompleteFilePath()); + String[] tmpS, lines = FileTools.loadStringsFromFile(this.m_InputFilePath.getCompleteFilePath()); if (lines == null) System.out.println("Failed to read "+this.m_InputFilePath.getCompleteFilePath()); lines[0].trim(); this.m_Titles = lines[0].split("\t"); diff --git a/src/eva2/server/go/operators/paretofrontmetrics/MetricSWithReference.java b/src/eva2/server/go/operators/paretofrontmetrics/MetricSWithReference.java index 1c8be8ec..7c345050 100644 --- a/src/eva2/server/go/operators/paretofrontmetrics/MetricSWithReference.java +++ b/src/eva2/server/go/operators/paretofrontmetrics/MetricSWithReference.java @@ -9,7 +9,7 @@ import eva2.server.go.individuals.ESIndividualDoubleData; import eva2.server.go.operators.archiving.ArchivingAllDominating; import eva2.server.go.populations.Population; import eva2.server.go.problems.AbstractMultiObjectiveOptimizationProblem; -import eva2.server.go.tools.FileLoader; +import eva2.server.go.tools.FileTools; /** S-Metric calculates the hyper-volume covered between the current solutions and a reference point. * But here the difference to a given hybervolume is to be minimized. @@ -74,7 +74,7 @@ public class MetricSWithReference implements InterfaceParetoFrontMetric, java.io * */ private void loadReferenceData() { - String[] tmpS, lines = FileLoader.loadStringsFromFile(this.m_InputFilePath.getCompleteFilePath()); + String[] tmpS, lines = FileTools.loadStringsFromFile(this.m_InputFilePath.getCompleteFilePath()); if (lines == null) System.out.println("Failed to read "+this.m_InputFilePath.getCompleteFilePath()); lines[0].trim(); this.m_Titles = lines[0].split("\t"); diff --git a/src/eva2/server/go/strategies/CHCAdaptiveSearchAlgorithm.java b/src/eva2/server/go/strategies/CHCAdaptiveSearchAlgorithm.java index 478f8897..8b61bed6 100644 --- a/src/eva2/server/go/strategies/CHCAdaptiveSearchAlgorithm.java +++ b/src/eva2/server/go/strategies/CHCAdaptiveSearchAlgorithm.java @@ -215,12 +215,17 @@ public class CHCAdaptiveSearchAlgorithm implements InterfaceOptimizer, java.io.S this.firePropertyChangedEvent(Population.nextGenerationPerformed); } - /** This method allows you to add the LectureGUI as listener to the Optimizer - * @param ea - */ public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { this.m_Listener = ea; } + public boolean removePopulationChangedEventListener( + InterfacePopulationChangedEventListener ea) { + if (m_Listener==ea) { + m_Listener=null; + return true; + } else return false; + } + /** Something has changed */ protected void firePropertyChangedEvent (String name) { diff --git a/src/eva2/server/go/strategies/ClusterBasedNichingEA.java b/src/eva2/server/go/strategies/ClusterBasedNichingEA.java index c6c3c337..467a2f60 100644 --- a/src/eva2/server/go/strategies/ClusterBasedNichingEA.java +++ b/src/eva2/server/go/strategies/ClusterBasedNichingEA.java @@ -638,22 +638,20 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis spec.clear(); spec.add(survivor); } - - /** This method allows an optimizer to register a change in the optimizer. - * @param source The source of the event. - * @param name Could be used to indicate the nature of the event. - */ + public void registerPopulationStateChanged(Object source, String name) { //Population population = ((InterfaceOptimizer)source).getPopulation(); } - /** This method allows you to add the LectureGUI as listener to the Optimizer - * @param ea - */ public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { this.m_Listener = ea; } - /** Something has changed - */ + public boolean removePopulationChangedEventListener( + InterfacePopulationChangedEventListener ea) { + if (m_Listener==ea) { + m_Listener=null; + return true; + } else return false; + } protected void firePropertyChangedEvent (String name) { if (this.m_Listener != null) this.m_Listener.registerPopulationStateChanged(this, name); } diff --git a/src/eva2/server/go/strategies/ClusteringHillClimbing.java b/src/eva2/server/go/strategies/ClusteringHillClimbing.java index 782e9be4..b1cbe5e2 100644 --- a/src/eva2/server/go/strategies/ClusteringHillClimbing.java +++ b/src/eva2/server/go/strategies/ClusteringHillClimbing.java @@ -105,7 +105,13 @@ public class ClusteringHillClimbing implements InterfacePopulationChangedEventLi public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { this.m_Listener = ea; } - + public boolean removePopulationChangedEventListener( + InterfacePopulationChangedEventListener ea) { + if (m_Listener==ea) { + m_Listener=null; + return true; + } else return false; + } public void init() { loopCnt = 0; mutator = new MutateESFixedStepSize(initialStepSize); diff --git a/src/eva2/server/go/strategies/DifferentialEvolution.java b/src/eva2/server/go/strategies/DifferentialEvolution.java index 3c14c7b9..4e500cc1 100644 --- a/src/eva2/server/go/strategies/DifferentialEvolution.java +++ b/src/eva2/server/go/strategies/DifferentialEvolution.java @@ -20,12 +20,13 @@ import eva2.server.go.problems.InterfaceOptimizationProblem; import eva2.tools.EVAERROR; import eva2.tools.Mathematics; -/** Differential evolution implementing DE1 and DE2 following the paper of Storm and +/** + * Differential evolution implementing DE1 and DE2 following the paper of Storm and * Price and the Trigonometric DE published recently. * Please note that DE will only work on real-valued genotypes and will ignore * all mutation and crossover operators selected. - * User: streiche - * Date: 25.10.2004 + * Added aging mechanism to provide for dynamically changing problems. If an individual + * reaches the age limit, it is doomed and replaced by the next challenge vector, even if its worse. * */ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serializable { @@ -34,17 +35,20 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial private AbstractOptimizationProblem m_Problem = new F1Problem(); private DETypeEnum m_DEType; private double m_F = 0.8; - private double m_k = 0.6; + private double m_k = 0.6; // AKA CR private double m_Lambda = 0.6; private double m_Mt = 0.05; private int maximumAge = -1; // to log the parents of a newly created indy. - private boolean doLogParents = false; // TODO deactivate for better performance - private Vector parents = null; + private boolean doLogParents = false; // deactivate for better performance + private transient Vector parents = null; + private boolean randomizeFKLambda = false; private String m_Identifier = ""; transient private InterfacePopulationChangedEventListener m_Listener; private boolean forceRange = true; + private boolean cyclePop = false; // if true, individuals are used as parents in a cyclic sequence - otherwise randomly + private boolean compareToParent = true; // if true, the challenge indy is compared to its parent, otherwise to a random individual /** * A constructor. @@ -54,6 +58,15 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial // sets DE2 as default m_DEType = DETypeEnum.DE2_CurrentToBest; } + + public DifferentialEvolution(int popSize, DETypeEnum type, double f, double k, double lambda, double mt) { + m_Population=new Population(popSize); + m_DEType = type; + m_F = f; + m_k = k; + m_Lambda = lambda; + m_Mt = mt; + } /** * The copy constructor. @@ -69,6 +82,12 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial this.m_k = a.m_k; this.m_Lambda = a.m_Lambda; this.m_Mt = a.m_Mt; + + this.maximumAge = a.maximumAge; + this.randomizeFKLambda = a.randomizeFKLambda; + this.forceRange = a.forceRange; + this.cyclePop = a.cyclePop; + this.compareToParent = a.compareToParent; } public Object clone() { @@ -216,16 +235,17 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial * @param pop The current population * @return AbstractEAIndividual */ - public AbstractEAIndividual generateNewIndividual(Population pop) { - int firstParentIndex; + public AbstractEAIndividual generateNewIndividual(Population pop, int parentIndex) { +// int firstParentIndex; AbstractEAIndividual indy; InterfaceDataTypeDouble esIndy; + if (doLogParents) parents = new Vector(); else parents = null; try { // select one random indy as starting individual. its a parent in any case. - firstParentIndex = RNG.randomInt(0, pop.size()-1); - indy = (AbstractEAIndividual)(pop.getEAIndividual(firstParentIndex)).getClone(); + if (parentIndex<0) parentIndex = RNG.randomInt(0, pop.size()-1); + indy = (AbstractEAIndividual)(pop.getEAIndividual(parentIndex)).getClone(); esIndy = (InterfaceDataTypeDouble)indy; } catch (java.lang.ClassCastException e) { EVAERROR.errorMsgOnce("Differential Evolution currently requires InterfaceESIndividual as basic data type!"); @@ -239,9 +259,9 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial case DE1_Rand_1: { // this is DE1 or DE/rand/1 double[] delta = this.fetchDeltaRandom(pop); - if (parents != null) parents.add(pop.getEAIndividual(firstParentIndex)); // Add wherever oX is used directly + if (parents != null) parents.add(pop.getEAIndividual(parentIndex)); // Add wherever oX is used directly for (int i = 0; i < oX.length; i++) { - vX[i] = oX[i] + this.m_F*delta[i]; + vX[i] = oX[i] + this.getCurrentF()*delta[i]; } break; } @@ -249,9 +269,9 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial // this is DE2 or DE/current-to-best/1 double[] rndDelta = this.fetchDeltaRandom(pop); double[] bestDelta = this.fetchDeltaBest(pop, esIndy); - if (parents != null) parents.add(pop.getEAIndividual(firstParentIndex)); // Add wherever oX is used directly + if (parents != null) parents.add(pop.getEAIndividual(parentIndex)); // Add wherever oX is used directly for (int i = 0; i < oX.length; i++) { - vX[i] = oX[i] + this.m_Lambda * bestDelta[i] + this.m_F * rndDelta[i]; + vX[i] = oX[i] + this.getCurrentLambda() * bestDelta[i] + this.getCurrentF() * rndDelta[i]; } break; } @@ -263,13 +283,13 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial double[] delta1 = this.fetchDeltaRandom(pop); double[] delta2 = this.fetchDeltaRandom(pop); for (int i = 0; i < oX.length; i++) { - vX[i] = oX[i] + this.m_F * (delta1[i] + delta2[i]); + vX[i] = oX[i] + this.getCurrentF() * (delta1[i] + delta2[i]); } break; } case TrigonometricDE : { // this is trigonometric mutation - if (parents != null) parents.add(pop.getEAIndividual(firstParentIndex)); // Add wherever oX is used directly + if (parents != null) parents.add(pop.getEAIndividual(parentIndex)); // Add wherever oX is used directly if (RNG.flipCoin(this.m_Mt)) { double[] xk, xl; double p, pj, pk, pl; @@ -297,16 +317,16 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial } else { // this is DE1 double[] delta = this.fetchDeltaRandom(pop); - if (parents != null) parents.add(pop.getEAIndividual(firstParentIndex)); // Add wherever oX is used directly + if (parents != null) parents.add(pop.getEAIndividual(parentIndex)); // Add wherever oX is used directly for (int i = 0; i < oX.length; i++) { - vX[i] = oX[i] + this.m_F*delta[i]; + vX[i] = oX[i] + this.getCurrentF()*delta[i]; } } break; } } for (int i =0; i < oX.length; i++) { - if (RNG.flipCoin(this.m_k)) { + if (RNG.flipCoin(this.getCurrentK())) { // it remains the same nX[i] = oX[i]; } else { @@ -318,6 +338,7 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial if (forceRange) Mathematics.projectToRange(nX, esIndy.getDoubleRange()); // why did this never happen before? esIndy.SetDoubleGenotype(nX); indy.SetAge(0); + indy.resetConstraintViolation(); double[] fit = new double[1]; fit[0] = 0; indy.SetFitness(fit); @@ -325,7 +346,22 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial return indy; } - private AbstractEAIndividual getBestIndy(Population pop) { + private double getCurrentK() { + if (randomizeFKLambda) return RNG.randomDouble(m_k*0.8, m_k * 1.2); + else return m_k; + } + + private double getCurrentLambda() { + if (randomizeFKLambda) return RNG.randomDouble(m_Lambda*0.8, m_Lambda * 1.2); + else return m_Lambda; + } + + private double getCurrentF() { + if (randomizeFKLambda) return RNG.randomDouble(m_F*0.8, m_F * 1.2); + else return m_F; + } + + private AbstractEAIndividual getBestIndy(Population pop) { return (AbstractEAIndividual)pop.getBestIndividual(); } @@ -349,20 +385,20 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial } public void optimize() { - AbstractEAIndividual indy = null, org; + AbstractEAIndividual indy = null, orig; int index; int nextDoomed = getNextDoomed(m_Population, 0); // required for dynamic problems especially m_Problem.evaluatePopulationStart(m_Population); - /** - * MK: added aging mechanism to provide for dynamically changing problems. If an individual - * reaches the age limit, it is doomed and replaced by the next challenge vector, even if its worse. - */ - + for (int i = 0; i < this.m_Population.size(); i++) { - indy = this.generateNewIndividual(this.m_Population); + if (cyclePop) index=i; + else index=RNG.randomInt(0, this.m_Population.size()-1); + indy = generateNewIndividual(m_Population, index); +// if (cyclePop) indy = this.generateNewIndividual(this.m_Population, i); +// else indy = this.generateNewIndividual(this.m_Population, -1); this.m_Problem.evaluate(indy); this.m_Population.incrFunctionCalls(); if (nextDoomed >= 0) { // this one is lucky, may replace an 'old' one @@ -373,9 +409,10 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial ReplacementCrowding repl = new ReplacementCrowding(); repl.insertIndividual(indy, m_Population, null); } else { - index = RNG.randomInt(0, this.m_Population.size()-1); - org = (AbstractEAIndividual)this.m_Population.get(index); - if (indy.isDominatingDebConstraints(org)) this.m_Population.replaceIndividualAt(index, indy); +// index = RNG.randomInt(0, this.m_Population.size()-1); + if (!compareToParent) index = RNG.randomInt(0, this.m_Population.size()-1); + orig = (AbstractEAIndividual)this.m_Population.get(index); + if (indy.isDominatingDebConstraints(orig)) this.m_Population.replaceIndividualAt(index, indy); } } } @@ -446,6 +483,13 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { this.m_Listener = ea; } + public boolean removePopulationChangedEventListener( + InterfacePopulationChangedEventListener ea) { + if (m_Listener==ea) { + m_Listener=null; + return true; + } else return false; + } /** Something has changed * @param name */ @@ -552,7 +596,7 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial return this.m_k; } public String kTipText() { - return "Probability of alteration through DE (something like a discrete uniform crossover is performed here)."; + return "Probability of alteration through DE (a.k.a. CR, similar to discrete uniform crossover)."; } /** Enhance greediness through amplification of the differential vector to the best individual for DE2 @@ -634,4 +678,40 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial public String checkRangeTipText() { return "Set whether to enforce the problem range."; } + + public boolean isRandomizeFKLambda() { + return randomizeFKLambda; + } + + public void setRandomizeFKLambda(boolean randomizeFK) { + this.randomizeFKLambda = randomizeFK; + } + + public String randomizeFKLambdaTipText() { + return "If true, values for k, f, lambda are randomly sampled around +/- 20% of the given values."; + } + +// public boolean isCyclePop() { +// return cyclePop; +// } +// +// public void setCyclePop(boolean cyclePop) { +// this.cyclePop = cyclePop; +// } +// +// public String cyclePopTipText() { +// return "Use all individuals as parents in cyclic sequence instead of randomly."; +// } + + public boolean isCompareToParent() { + return compareToParent; + } + + public void setCompareToParent(boolean compareToParent) { + this.compareToParent = compareToParent; + } + + public String compareToParentTipText() { + return "Compare a challenge individual to its original parent instead of a random one."; + } } \ No newline at end of file diff --git a/src/eva2/server/go/strategies/DynamicParticleSwarmOptimization.java b/src/eva2/server/go/strategies/DynamicParticleSwarmOptimization.java index 2ad922cd..218f256e 100644 --- a/src/eva2/server/go/strategies/DynamicParticleSwarmOptimization.java +++ b/src/eva2/server/go/strategies/DynamicParticleSwarmOptimization.java @@ -286,6 +286,7 @@ public class DynamicParticleSwarmOptimization extends ParticleSwarmOptimization // } // } + @Override protected double[] updateVelocity(int index, double[] lastVelocity, double[] bestPosition, double[] curPosition, double[] localBestPos, double[][] range) { if (envHasChanged) { double chi; @@ -473,7 +474,13 @@ public class DynamicParticleSwarmOptimization extends ParticleSwarmOptimization return false; } - public void init() { + @Override + public void setPopulation(Population pop) { + super.setPopulation(pop); + if (detectAnchor>=pop.size()) detectAnchor=0; + } + + public void init() { super.init(); setEmaPeriods(15); if (doSpeedAdaptation) setSpeedLimit(2*getInitialVelocity()); diff --git a/src/eva2/server/go/strategies/EvolutionStrategies.java b/src/eva2/server/go/strategies/EvolutionStrategies.java index 8fa8a336..9ad99654 100644 --- a/src/eva2/server/go/strategies/EvolutionStrategies.java +++ b/src/eva2/server/go/strategies/EvolutionStrategies.java @@ -310,6 +310,13 @@ public class EvolutionStrategies implements InterfaceOptimizer, java.io.Serializ public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { this.m_Listener = ea; } + public boolean removePopulationChangedEventListener( + InterfacePopulationChangedEventListener ea) { + if (m_Listener==ea) { + m_Listener=null; + return true; + } else return false; + } /** Something has changed */ protected void firePropertyChangedEvent(String name) { diff --git a/src/eva2/server/go/strategies/EvolutionaryProgramming.java b/src/eva2/server/go/strategies/EvolutionaryProgramming.java index 5359849d..d157ac21 100644 --- a/src/eva2/server/go/strategies/EvolutionaryProgramming.java +++ b/src/eva2/server/go/strategies/EvolutionaryProgramming.java @@ -128,6 +128,13 @@ public class EvolutionaryProgramming implements InterfaceOptimizer, java.io.Seri public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { this.m_Listener = ea; } + public boolean removePopulationChangedEventListener( + InterfacePopulationChangedEventListener ea) { + if (m_Listener==ea) { + m_Listener=null; + return true; + } else return false; + } /** Something has changed */ protected void firePropertyChangedEvent (String name) { diff --git a/src/eva2/server/go/strategies/FloodAlgorithm.java b/src/eva2/server/go/strategies/FloodAlgorithm.java index aff76d6b..9b5fca45 100644 --- a/src/eva2/server/go/strategies/FloodAlgorithm.java +++ b/src/eva2/server/go/strategies/FloodAlgorithm.java @@ -171,6 +171,13 @@ public class FloodAlgorithm implements InterfaceOptimizer, java.io.Serializable public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { this.m_Listener = ea; } + public boolean removePopulationChangedEventListener( + InterfacePopulationChangedEventListener ea) { + if (m_Listener==ea) { + m_Listener=null; + return true; + } else return false; + } /** Something has changed */ protected void firePropertyChangedEvent (String name) { diff --git a/src/eva2/server/go/strategies/GeneticAlgorithm.java b/src/eva2/server/go/strategies/GeneticAlgorithm.java index 257bbbef..31bee1fc 100644 --- a/src/eva2/server/go/strategies/GeneticAlgorithm.java +++ b/src/eva2/server/go/strategies/GeneticAlgorithm.java @@ -171,6 +171,13 @@ public class GeneticAlgorithm implements InterfaceOptimizer, java.io.Serializabl public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { this.m_Listener = ea; } + public boolean removePopulationChangedEventListener( + InterfacePopulationChangedEventListener ea) { + if (m_Listener==ea) { + m_Listener=null; + return true; + } else return false; + } /** Something has changed */ protected void firePropertyChangedEvent (String name) { @@ -320,21 +327,4 @@ public class GeneticAlgorithm implements InterfaceOptimizer, java.io.Serializabl public String partnerSelectionTipText() { return "Choose a selection method for selecting recombination partners for given parents."; } - - /** This method will set the number of individuals that are to be removed - * due to a plague [compare Saving Computational Effort in GP by means of - * Plagues, Fernandez, Tomassini, Vanneschi] - * offsprings by mating - * @param p - */ -// public void setImpactOfPlague(int p) { -// if (p < 0) p = 0; -// this.m_Plague = p; -// } -// public int getImpactOfPlague() { -// return this.m_Plague; -// } -// public String impactOfPlagueTipText() { -// return "This gives the number of individuals that are to be removed each generation due to plague."; -// } } diff --git a/src/eva2/server/go/strategies/GradientDescentAlgorithm.java b/src/eva2/server/go/strategies/GradientDescentAlgorithm.java index 80ae00f4..f91256c5 100644 --- a/src/eva2/server/go/strategies/GradientDescentAlgorithm.java +++ b/src/eva2/server/go/strategies/GradientDescentAlgorithm.java @@ -302,7 +302,13 @@ public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Ser public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { this.m_Listener = ea; } - + public boolean removePopulationChangedEventListener( + InterfacePopulationChangedEventListener ea) { + if (m_Listener==ea) { + m_Listener=null; + return true; + } else return false; + } public static void main(String[] args) { GradientDescentAlgorithm program = new GradientDescentAlgorithm(); InterfaceOptimizationProblem problem = new F1Problem(); diff --git a/src/eva2/server/go/strategies/HillClimbing.java b/src/eva2/server/go/strategies/HillClimbing.java index 4a9cd790..49391432 100644 --- a/src/eva2/server/go/strategies/HillClimbing.java +++ b/src/eva2/server/go/strategies/HillClimbing.java @@ -178,6 +178,13 @@ public class HillClimbing implements InterfaceOptimizer, java.io.Serializable { public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { this.m_Listener = ea; } + public boolean removePopulationChangedEventListener( + InterfacePopulationChangedEventListener ea) { + if (m_Listener==ea) { + m_Listener=null; + return true; + } else return false; + } /** Something has changed */ protected void firePropertyChangedEvent (String name) { diff --git a/src/eva2/server/go/strategies/InterfaceOptimizer.java b/src/eva2/server/go/strategies/InterfaceOptimizer.java index 1a106fc1..7470238b 100644 --- a/src/eva2/server/go/strategies/InterfaceOptimizer.java +++ b/src/eva2/server/go/strategies/InterfaceOptimizer.java @@ -29,11 +29,19 @@ public interface InterfaceOptimizer { */ public String getName(); - /** This method allows you to add the LectureGUI as listener to the Optimizer + /** + * This method allows you to add a listener to the Optimizer. * @param ea */ public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea); - + + /** + * This method removes a listener from the Optimizer. It returns true on success, + * false if the listener could not be found. + * @param ea + */ + public boolean removePopulationChangedEventListener(InterfacePopulationChangedEventListener ea); + /** This method will init the optimizer */ public void init(); diff --git a/src/eva2/server/go/strategies/IslandModelEA.java b/src/eva2/server/go/strategies/IslandModelEA.java index 6d27d3ec..1618801c 100644 --- a/src/eva2/server/go/strategies/IslandModelEA.java +++ b/src/eva2/server/go/strategies/IslandModelEA.java @@ -265,6 +265,13 @@ public class IslandModelEA implements InterfacePopulationChangedEventListener, I public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { this.m_Listener = ea; } + public boolean removePopulationChangedEventListener( + InterfacePopulationChangedEventListener ea) { + if (m_Listener==ea) { + m_Listener=null; + return true; + } else return false; + } /** Something has changed */ protected void firePropertyChangedEvent (String name, Population population) { diff --git a/src/eva2/server/go/strategies/MemeticAlgorithm.java b/src/eva2/server/go/strategies/MemeticAlgorithm.java index 1b62e4f0..2fc84329 100644 --- a/src/eva2/server/go/strategies/MemeticAlgorithm.java +++ b/src/eva2/server/go/strategies/MemeticAlgorithm.java @@ -204,7 +204,13 @@ public class MemeticAlgorithm implements InterfaceOptimizer, InterfacePopulationChangedEventListener ea) { this.m_Listener = ea; } - + public boolean removePopulationChangedEventListener( + InterfacePopulationChangedEventListener ea) { + if (m_Listener==ea) { + m_Listener=null; + return true; + } else return false; + } /** * Something has changed */ diff --git a/src/eva2/server/go/strategies/MonteCarloSearch.java b/src/eva2/server/go/strategies/MonteCarloSearch.java index d7700094..79e7c838 100644 --- a/src/eva2/server/go/strategies/MonteCarloSearch.java +++ b/src/eva2/server/go/strategies/MonteCarloSearch.java @@ -150,6 +150,13 @@ public class MonteCarloSearch implements InterfaceOptimizer, java.io.Serializabl public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { this.m_Listener = ea; } + public boolean removePopulationChangedEventListener( + InterfacePopulationChangedEventListener ea) { + if (m_Listener==ea) { + m_Listener=null; + return true; + } else return false; + } /** Something has changed */ protected void firePropertyChangedEvent (String name) { diff --git a/src/eva2/server/go/strategies/MultiObjectiveEA.java b/src/eva2/server/go/strategies/MultiObjectiveEA.java index 497d27c9..ddf103d3 100644 --- a/src/eva2/server/go/strategies/MultiObjectiveEA.java +++ b/src/eva2/server/go/strategies/MultiObjectiveEA.java @@ -151,14 +151,18 @@ public class MultiObjectiveEA implements InterfaceOptimizer, java.io.Serializabl return result; } - /** This method allows you to add the LectureGUI as listener to the Optimizer - * @param ea - */ public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { this.m_Listener = ea; } - /** Something has changed - */ + + public boolean removePopulationChangedEventListener( + InterfacePopulationChangedEventListener ea) { + if (m_Listener==ea) { + m_Listener=null; + return true; + } else return false; + } + protected void firePropertyChangedEvent (String name) { if (this.m_Listener != null) this.m_Listener.registerPopulationStateChanged(this, name); } diff --git a/src/eva2/server/go/strategies/NelderMeadSimplex.java b/src/eva2/server/go/strategies/NelderMeadSimplex.java index d4a2965f..209515f2 100644 --- a/src/eva2/server/go/strategies/NelderMeadSimplex.java +++ b/src/eva2/server/go/strategies/NelderMeadSimplex.java @@ -40,7 +40,12 @@ public class NelderMeadSimplex implements InterfaceOptimizer, Serializable, Inte public NelderMeadSimplex() { setPopulation(new Population(populationSize)); } - + + public NelderMeadSimplex(int popSize) { + populationSize=popSize; + setPopulation(new Population(populationSize)); + } + public NelderMeadSimplex(NelderMeadSimplex a) { m_Problem = (AbstractOptimizationProblem)a.m_Problem.clone(); setPopulation((Population)a.m_Population.clone()); @@ -81,7 +86,13 @@ public class NelderMeadSimplex implements InterfaceOptimizer, Serializable, Inte if (m_Listener == null) m_Listener = new Vector(); if (!m_Listener.contains(ea)) m_Listener.add(ea); } - + + public boolean removePopulationChangedEventListener( + InterfacePopulationChangedEventListener ea) { + if (m_Listener==null) return false; + else return m_Listener.remove(ea); + } + public void freeWilly() {} protected double[] calcChallengeVect(double[] centroid, double[] refX) { @@ -139,10 +150,11 @@ public class NelderMeadSimplex implements InterfaceOptimizer, Serializable, Inte Mathematics.reflectBounds(r, range); } } - AbstractEAIndividual reflectedInd = (AbstractEAIndividual)((AbstractEAIndividual)bestpop.getIndividual(1)).clone(); - ((InterfaceDataTypeDouble)reflectedInd).SetDoubleGenotype(r); - - m_Problem.evaluate(reflectedInd); +// AbstractEAIndividual reflectedInd = (AbstractEAIndividual)((AbstractEAIndividual)bestpop.getIndividual(1)).clone(); +// ((InterfaceDataTypeDouble)reflectedInd).SetDoubleGenotype(r); +// +// m_Problem.evaluate(reflectedInd); + AbstractEAIndividual reflectedInd = createEvalIndy(bestpop, r); this.m_Population.incrFunctionCalls(); if (firstIsBetter(best, reflectedInd) && firstIsBetter(reflectedInd, bestpop.getWorstEAIndividual(fitIndex))) { @@ -152,10 +164,9 @@ public class NelderMeadSimplex implements InterfaceOptimizer, Serializable, Inte for (int i=0; i m_RemoteStateListeners; protected LogPanel logPanel = null; - - /** - * - */ - abstract public JTabbedModuleFrame getModuleFrame(); - /** - * - */ + protected AbstractModuleAdapter(MainAdapterClient Client) { if (TRACE) System.out.println("AbstractModuleAdapter.AbstractModuleAdapter()"); m_InstanceCounter++; @@ -126,6 +122,18 @@ abstract public class AbstractModuleAdapter implements ModuleAdapter, Serializab } else return null; } +// public void setGOParameters(InterfaceGOParameters params) { +// if ((m_Processor != null) && (m_Processor instanceof Processor)) { +// ((Processor)m_Processor).setGOParams(params); +// } +// } + +// public void loadGOParameters(String serParamsFile) { +// if ((m_Processor != null) && (m_Processor instanceof Processor)) { +// ((Processor)m_Processor).setGOParams(GOParameters.getInstance(serParamsFile, false)); +// } +// } + public boolean isOptRunning() { if ((m_Processor != null) && (m_Processor instanceof Processor)) { return ((Processor)m_Processor).isOptRunning(); diff --git a/src/eva2/server/modules/GOModuleAdapter.java b/src/eva2/server/modules/GOModuleAdapter.java index 74592f3b..a562af12 100644 --- a/src/eva2/server/modules/GOModuleAdapter.java +++ b/src/eva2/server/modules/GOModuleAdapter.java @@ -29,6 +29,17 @@ public class GOModuleAdapter extends GenericModuleAdapter implements ModuleAdapt * @param Client the client instance */ public GOModuleAdapter(String adapterName, MainAdapterClient client) { - super (adapterName, "", client, GOParameters.getInstance(), false); + super(adapterName, "", client, GOParameters.getInstance(), false); + } + + /** + * Starts a statistics GUI and the GOProcessor thread with a given GOParameters file. + * + * @param AdapterName the title of the ModulAdapter + * @param Client the client instance + */ + public GOModuleAdapter(String adapterName, String serParamsFile, String noGuiLogFile, MainAdapterClient client) { + //super(adapterName, "", client, GOParameters.getInstance(serParamsFile, false), false); + super(adapterName, "", client, GOParameters.getInstance(serParamsFile, serParamsFile==null), false, noGuiLogFile); } } \ No newline at end of file diff --git a/src/eva2/server/modules/GOParameters.java b/src/eva2/server/modules/GOParameters.java index 3cf1e359..8527c438 100644 --- a/src/eva2/server/modules/GOParameters.java +++ b/src/eva2/server/modules/GOParameters.java @@ -23,32 +23,43 @@ public class GOParameters extends AbstractGOParameters implements InterfaceGOPar public static boolean TRACE = false; - /** - * - */ public static GOParameters getInstance() { - if (TRACE) System.out.println("GOParameters getInstance 1"); - GOParameters Instance = null; - try { - Instance = (GOParameters) Serializer.loadObject("GOParameters.ser"); - } catch(Exception e) { - System.err.println("Error loading GOParameters!"); - Instance = null; - } - if (TRACE) System.out.println("GOParameters getInstance 2"); - if (Instance == null) Instance = new GOParameters(); - return Instance; + return getInstance("GOParameters.ser", true); + } + + /** + * Create an instance from a given serialized parameter file. + * + * @param serParamFile + * @param casually if true, standard parameters are used quietly if the params cannot be loaded + * @return a GOParameters instance + */ + public static GOParameters getInstance(String serParamFile, boolean casually) { + if (TRACE) System.out.println("GOParameters getInstance 1 - " + serParamFile + " , " + casually); + GOParameters Instance = null; + if (serParamFile!=null) { + try { + Instance = (GOParameters) Serializer.loadObject(serParamFile, casually); + if (TRACE) System.out.println("Loading succeded."); + } catch(Exception e) { + System.err.println("Error loading GOParameters from " + serParamFile); + Instance = null; + } + } else if (!casually) System.err.println("Error: null argument for noncasual param file loading! (GOParameters)"); + if (TRACE) System.out.println("GOParameters getInstance 2"); + if (Instance == null) Instance = new GOParameters(); + return Instance; } - /** - * - */ - public void saveInstance() { - Serializer.storeObject("GOParameters.ser",this); + public void saveInstance(String serParamFile) { + if (TRACE) System.out.println("GOParameters: saveInstance to " + serParamFile); + Serializer.storeObject(serParamFile,this); } - /** - * - */ + + public void saveInstance() { + saveInstance("GOParameters.ser"); + } + public GOParameters() { super(new GeneticAlgorithm(), new F1Problem(), new EvaluationTerminator(1000)); // ((F1Problem)m_Problem).setEAIndividual(new GAIndividualDoubleData()); diff --git a/src/eva2/server/modules/GenericModuleAdapter.java b/src/eva2/server/modules/GenericModuleAdapter.java index cd81e88a..295eb429 100644 --- a/src/eva2/server/modules/GenericModuleAdapter.java +++ b/src/eva2/server/modules/GenericModuleAdapter.java @@ -5,21 +5,22 @@ import java.io.Serializable; import java.lang.reflect.Proxy; import java.util.ArrayList; -import eva2.gui.GenericObjectEditor; -import eva2.gui.JModuleGeneralPanel; -import eva2.gui.JParaPanel; -import eva2.gui.JTabbedModuleFrame; -import eva2.server.EvAServer; -import eva2.server.go.InterfaceGOParameters; -import eva2.server.stat.InterfaceStatisticsParameter; -import eva2.server.stat.StatisticsWithGUI; - import wsi.ra.jproxy.MainAdapterClient; import wsi.ra.jproxy.RMIProxyLocal; +import eva2.gui.EvAModuleButtonPanelMaker; +import eva2.gui.EvATabbedFrameMaker; +import eva2.gui.GenericObjectEditor; +import eva2.gui.JParaPanel; +import eva2.gui.PanelMaker; +import eva2.server.go.InterfaceGOParameters; +import eva2.server.stat.AbstractStatistics; +import eva2.server.stat.InterfaceStatisticsParameter; +import eva2.server.stat.StatisticsStandalone; +import eva2.server.stat.StatisticsWithGUI; public class GenericModuleAdapter extends AbstractModuleAdapter implements Serializable { - private StatisticsWithGUI m_StatisticsModul; + private AbstractStatistics m_StatisticsModul; public String helperFilename; /** @@ -29,8 +30,9 @@ public class GenericModuleAdapter extends AbstractModuleAdapter implements Seria * @param Client The client to serve * @param params a parameter set describing the optimizer module * @param optimizerExpert set to true if setting the optimizer is an expert option being hidden from the gui + * @param noGUIStatOut if null, statistics with GUI are used, else the standalone statistics with given output filename. */ - public GenericModuleAdapter(String adapterName, String helperFName, MainAdapterClient Client, InterfaceGOParameters params, boolean optimizerExpert) { + public GenericModuleAdapter(String adapterName, String helperFName, MainAdapterClient Client, InterfaceGOParameters params, boolean optimizerExpert, String noGUIStatOut) { super (Client); if (TRACE) System.out.println("Constructor GenericModuleAdapter --> start"); m_RemoteThis = this; @@ -38,8 +40,12 @@ public class GenericModuleAdapter extends AbstractModuleAdapter implements Seria m_MainAdapterClient = Client; helperFilename = helperFName; - m_StatisticsModul = new StatisticsWithGUI(Client); - m_Processor = new Processor((StatisticsWithGUI)m_StatisticsModul,this, params); + if (noGUIStatOut==null) { + m_StatisticsModul = new StatisticsWithGUI(Client); + } else { + m_StatisticsModul = new StatisticsStandalone(noGUIStatOut); + } + m_Processor = new Processor(m_StatisticsModul,this, params); // this prevents the optimizer property to be shown by the GOE if optimizerExpert is true GenericObjectEditor.setExpertProperty(params.getClass(), "optimizer", optimizerExpert); @@ -48,14 +54,31 @@ public class GenericModuleAdapter extends AbstractModuleAdapter implements Seria if (TRACE) System.out.println("Constructor GenericModuleAdapter <-- end"); } - /** This method returns a GUI element - * @return the JTabbedModulFrame + /** + * Constructor of the ModuleAdapter. Convenience constructor with GUI. + * + * @param adapterName The AdapterName + * @param helperFName name of a html help file name + * @param Client The client to serve + * @param params a parameter set describing the optimizer module + * @param optimizerExpert set to true if setting the optimizer is an expert option being hidden from the gui */ - public JTabbedModuleFrame getModuleFrame() { - if (TRACE) System.out.println("GenericModulAdapter.getModuleFrame"); - ArrayList GUIContainer = new ArrayList(); + public GenericModuleAdapter(String adapterName, String helperFName, MainAdapterClient Client, InterfaceGOParameters params, boolean optimizerExpert) { + this(adapterName, helperFName, Client, params, optimizerExpert, null); + } + + /** This method returns a GUI element + * @return the EvATabbedFrameMaker + */ + public EvATabbedFrameMaker getModuleFrame() { + if (TRACE) System.out.println("GenericModulAdapter.getModuleFrame"); + if (!(m_StatisticsModul instanceof StatisticsWithGUI)) { + System.err.println("Error: Unable to create Frame when startet with noGUI option (GenericModuleAdapter)!"); + return null; + } + ArrayList GUIContainer = new ArrayList(); InterfaceStatisticsParameter Stat = ((StatisticsWithGUI)m_StatisticsModul).getStatisticsParameter(); - JModuleGeneralPanel ButtonPanel = new JModuleGeneralPanel(m_RemoteThis,((Processor)m_Processor).isOptRunning()); + EvAModuleButtonPanelMaker ButtonPanel = new EvAModuleButtonPanelMaker(m_RemoteThis,((Processor)m_Processor).isOptRunning()); ButtonPanel.setHelperFilename(helperFilename); GUIContainer.add(ButtonPanel); InterfaceGOParameters Para = ((Processor)m_Processor).getGOParams(); @@ -66,11 +89,18 @@ public class GenericModuleAdapter extends AbstractModuleAdapter implements Seria if (m_RMI && !Proxy.isProxyClass(Stat.getClass())) GUIContainer.add(new JParaPanel( RMIProxyLocal.newInstance(Stat), Stat.getName())); else GUIContainer.add(new JParaPanel(Stat, Stat.getName())); - return new JTabbedModuleFrame(m_RemoteThis,getName(),m_myHostName+EvAServer.m_NumberOfVM,GUIContainer); + return new EvATabbedFrameMaker(GUIContainer); } public static String getName() { return null; } + /** + * Return the statistics module instance of this module. + * @return + */ + public AbstractStatistics getStatistics() { + return m_StatisticsModul; + } } diff --git a/src/eva2/server/modules/MOEAModuleAdapter.java b/src/eva2/server/modules/MOEAModuleAdapter.java index 06910417..6471713d 100644 --- a/src/eva2/server/modules/MOEAModuleAdapter.java +++ b/src/eva2/server/modules/MOEAModuleAdapter.java @@ -4,9 +4,7 @@ package eva2.server.modules; import java.io.Serializable; import java.util.ArrayList; -import eva2.gui.JModuleGeneralPanel; import eva2.gui.JParaPanel; -import eva2.gui.JTabbedModuleFrame; import eva2.server.EvAServer; import eva2.server.go.InterfaceGOParameters; import eva2.server.stat.InterfaceStatisticsParameter; diff --git a/src/eva2/server/modules/ModuleAdapter.java b/src/eva2/server/modules/ModuleAdapter.java index e1617fe1..1caa5d3b 100644 --- a/src/eva2/server/modules/ModuleAdapter.java +++ b/src/eva2/server/modules/ModuleAdapter.java @@ -12,7 +12,7 @@ package eva2.server.modules; /*==========================================================================* * IMPORTS *==========================================================================*/ -import eva2.gui.JTabbedModuleFrame; +import eva2.gui.EvATabbedFrameMaker; import eva2.gui.LogPanel; import eva2.server.go.operators.postprocess.PostProcessParams; import eva2.server.stat.InterfaceTextListener; @@ -24,7 +24,7 @@ import wsi.ra.jproxy.RemoteStateListener; * */ public interface ModuleAdapter extends RemoteStateListener { - public JTabbedModuleFrame getModuleFrame(); + public EvATabbedFrameMaker getModuleFrame(); public void startOpt(); // called from client public void restartOpt(); public void stopOpt(); diff --git a/src/eva2/server/modules/Processor.java b/src/eva2/server/modules/Processor.java index 36f980e1..c8be7ff6 100644 --- a/src/eva2/server/modules/Processor.java +++ b/src/eva2/server/modules/Processor.java @@ -12,6 +12,7 @@ import eva2.server.go.InterfaceTerminator; import eva2.server.go.PopulationInterface; import eva2.server.go.operators.paramcontrol.ConstantParameters; import eva2.server.go.operators.paramcontrol.InterfaceParameterControl; +import eva2.server.go.operators.paramcontrol.ParamAdaption; import eva2.server.go.operators.postprocess.PostProcess; import eva2.server.go.operators.postprocess.PostProcessParams; import eva2.server.go.operators.terminators.EvaluationTerminator; @@ -25,10 +26,17 @@ import eva2.server.stat.InterfaceTextListener; import eva2.server.stat.StatisticsWithGUI; import eva2.tools.EVAERROR; import eva2.tools.EVAHELP; +import eva2.tools.Pair; /** * The Processor may run as a thread permanently (GenericModuleAdapter) and is then stopped and started * by a switch in startOpt/stopOpt. + * + * Processor also handles adaptive parameter control by checking for the method getParamControl in (so far) + * Optimizer and Problem instances. The return-value may be InterfaceParameterControl or an array of Objects. + * If it is a control interface, it is applied to the instance that returned it directly. For arrays of objects + * each array entry is again handled by checking for getParamControl, thus recursive controllable structures + * are possible. * * @author mkron * @@ -200,16 +208,16 @@ public class Processor extends Thread implements InterfaceProcessor, InterfacePo this.goParams.getProblem().initProblem(); this.goParams.getOptimizer().SetProblem(this.goParams.getProblem()); - if (this.m_createInitialPopulations) this.goParams.getOptimizer().init(); this.goParams.getTerminator().init(this.goParams.getProblem()); + maybeInitParamCtrl(goParams); + if (this.m_createInitialPopulations) this.goParams.getOptimizer().init(); //m_Statistics.createNextGenerationPerformed((PopulationInterface)this.m_ModulParameter.getOptimizer().getPopulation()); if (m_ListenerModule!=null) m_ListenerModule.updateProgress(getStatusPercent(goParams.getOptimizer().getPopulation(), runCounter, m_Statistics.getStatisticsParameter().getMultiRuns()), null); if (popLog != null) EVAHELP.clearLog(popLog); - maybeInitParamCtrl(goParams.getOptimizer()); do { // main loop - maybeUpdateParamCtrl(goParams.getOptimizer(), goParams.getTerminator()); + maybeUpdateParamCtrl(goParams); this.goParams.getOptimizer().optimize(); // registerPopulationStateChanged *SHOULD* be fired by the optimizer or resp. the population @@ -217,7 +225,7 @@ public class Processor extends Thread implements InterfaceProcessor, InterfacePo if (popLog != null) EVAHELP.logString(this.goParams.getOptimizer().getPopulation().getIndyList(), popLog); } while (isOptRunning() && !this.goParams.getTerminator().isTerminated(this.goParams.getOptimizer().getAllSolutions())); runCounter++; - maybeFinishParamCtrl(goParams.getOptimizer()); + maybeFinishParamCtrl(goParams); //////////////// Default stats m_Statistics.stopOptPerformed(isOptRunning(), goParams.getTerminator().lastTerminationMessage()); // stop is "normal" if opt wasnt set false by the user (and thus still true) @@ -234,42 +242,60 @@ public class Processor extends Thread implements InterfaceProcessor, InterfacePo setOptRunning(false); // normal finish if (m_ListenerModule!=null) m_ListenerModule.performedStop(); // is only needed in client server mode if (m_ListenerModule!=null) m_ListenerModule.updateProgress(0, null); + goParams.getOptimizer().removePopulationChangedEventListener(this); return resultPop; } - private void maybeInitParamCtrl(InterfaceOptimizer optimizer) { - Object paramCtrl=null; - if (null!=(paramCtrl=BeanInspector.callIfAvailable(optimizer, "getParamControl", null))) { - if (paramCtrl instanceof InterfaceParameterControl) { - if (!(paramCtrl instanceof ConstantParameters)) { - ((InterfaceParameterControl)paramCtrl).init(optimizer); - } + private void iterateParamCtrl(Object instance, String methodName, Object[] args) { + Object paramCtrlReturn=null; + if (null!=(paramCtrlReturn=BeanInspector.callIfAvailable(instance, "getParamControl", null))) { + if (paramCtrlReturn instanceof Object[]) { + Object[] controllersOrSubControllables = (Object[])paramCtrlReturn; + for (Object controllerOrSubControllable : controllersOrSubControllables) { + // The returned array may contain (i) InterfaceParameterControl associated with the instance + // itself or (ii) sub-instances which have their own parameter controls. On these, the method + // is called recursively. + if (controllerOrSubControllable instanceof InterfaceParameterControl) { + if (!((InterfaceParameterControl)paramCtrlReturn instanceof ConstantParameters)) + BeanInspector.callIfAvailable((InterfaceParameterControl)paramCtrlReturn, methodName, args); + } else { + args[0]=controllerOrSubControllable; + iterateParamCtrl(controllerOrSubControllable, methodName, args); + } + } + } else if (paramCtrlReturn instanceof InterfaceParameterControl) { + if (!((InterfaceParameterControl)paramCtrlReturn instanceof ConstantParameters)) + BeanInspector.callIfAvailable((InterfaceParameterControl)paramCtrlReturn, methodName, args); } } } - private void maybeFinishParamCtrl(InterfaceOptimizer optimizer) { - Object paramCtrl=null; - if (null!=(paramCtrl=BeanInspector.callIfAvailable(optimizer, "getParamControl", null))) { - if (paramCtrl instanceof InterfaceParameterControl) { - if (!(paramCtrl instanceof ConstantParameters)) { - ((InterfaceParameterControl)paramCtrl).finish(optimizer); - } - } - } + private void maybeInitParamCtrl(InterfaceGOParameters goParams) { + iterateParamCtrl(goParams.getOptimizer(), "init", new Object[]{goParams.getOptimizer(), goParams.getOptimizer().getPopulation()}); + iterateParamCtrl(goParams.getProblem(), "init", new Object[]{goParams.getProblem(), goParams.getOptimizer().getPopulation()}); } - private void maybeUpdateParamCtrl(InterfaceOptimizer optimizer, - InterfaceTerminator terminator) { - Object paramCtrl=null; - if (null!=(paramCtrl=BeanInspector.callIfAvailable(optimizer, "getParamControl", null))) { - if (paramCtrl instanceof InterfaceParameterControl) { - if (!(paramCtrl instanceof ConstantParameters)) { - if (terminator instanceof GenerationTerminator) ((InterfaceParameterControl)paramCtrl).updateParameters(optimizer, optimizer.getPopulation().getGeneration(), ((GenerationTerminator)terminator).getGenerations()); - else if (terminator instanceof EvaluationTerminator) ((InterfaceParameterControl)paramCtrl).updateParameters(optimizer, optimizer.getPopulation().getFunctionCalls(), ((EvaluationTerminator)terminator).getFitnessCalls()); - else ((InterfaceParameterControl)paramCtrl).updateParameters(optimizer); - } - } - } + + private void maybeFinishParamCtrl(InterfaceGOParameters goParams) { + iterateParamCtrl(goParams.getOptimizer(), "finish", new Object[]{goParams.getOptimizer(), goParams.getOptimizer().getPopulation()}); + iterateParamCtrl(goParams.getProblem(), "finish", new Object[]{goParams.getProblem(), goParams.getOptimizer().getPopulation()}); + } + + private void maybeUpdateParamCtrl(InterfaceGOParameters goParams) { + Object[] args; + InterfaceTerminator terminator = goParams.getTerminator(); + InterfaceOptimizer optimizer = goParams.getOptimizer(); + if (terminator instanceof GenerationTerminator) + args = new Object[]{optimizer, optimizer.getPopulation(), optimizer.getPopulation().getGeneration(), ((GenerationTerminator)terminator).getGenerations()}; +// ((InterfaceParameterControl)paramCtrl).updateParameters(optimizer, optimizer.getPopulation().getGeneration(), ((GenerationTerminator)terminator).getGenerations()); + else if (terminator instanceof EvaluationTerminator) + args = new Object[] {optimizer, optimizer.getPopulation(), optimizer.getPopulation().getFunctionCalls(), ((EvaluationTerminator)terminator).getFitnessCalls()}; +// ((InterfaceParameterControl)paramCtrl).updateParameters(optimizer, optimizer.getPopulation().getFunctionCalls(), ((EvaluationTerminator)terminator).getFitnessCalls()); + else args = new Object[]{optimizer, optimizer.getPopulation()}; +// ((InterfaceParameterControl)paramCtrl).updateParameters(optimizer); + + iterateParamCtrl(optimizer, "updateParameters", args); + args[0]=goParams.getProblem(); + iterateParamCtrl(goParams.getProblem(), "updateParameters", args); } /** @@ -361,8 +387,9 @@ public class Processor extends Thread implements InterfaceProcessor, InterfacePo public InterfaceGOParameters getGOParams() { return goParams; } - public void setGOParams(InterfaceGOParameters x) { - goParams= x; + public void setGOParams(InterfaceGOParameters params) { + if (params!=null) goParams= params; + else System.err.println("Setting parameters failed (parameters were null) (Processor.setGOParams)"); } /** diff --git a/src/eva2/tools/Serializer.java b/src/eva2/tools/Serializer.java index 57088da8..b29c5627 100644 --- a/src/eva2/tools/Serializer.java +++ b/src/eva2/tools/Serializer.java @@ -16,6 +16,7 @@ import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; +import java.io.InvalidClassException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.PipedInputStream; @@ -187,25 +188,40 @@ public class Serializer { } return ret; } + + /** + * Deserialize the contents of File with given name containing + * a string and return the resulting string. If the indicated file + * doesnt exist or an error occurs, null is returned. + **/ + public static Object loadObject (String Filename) { + return loadObject(Filename, true); + } + /** * Deserialize the contents of File with given name containing * a string and return the resulting string. If the indicated file * doesnt exist or an error occurs, null is returned. + * If casually is false, an error message is printed and an exception + * is raised if the file was not found or an error occured on loading. **/ - public static Object loadObject (String Filename) { + public static Object loadObject (String Filename, boolean casually) { Object s = null; File f = new File(Filename); if (f.exists()) { try { s=(Object)load(new File(Filename)); - } catch (Exception e) { + } catch (InvalidClassException e) { System.err.println("WARNING: loading object File "+Filename+ " not possible, this may happen on source code changes."); System.err.println(e.getMessage()); - //e.printStackTrace(); - return null; + } catch (Exception e) { + throw new RuntimeException("WARNING: loading object File "+Filename+ " not possible! ("+e.getMessage()+")"); } return s; - } else return null; + } else { + if (!casually) System.err.println("Error in Serializer: file " + Filename + " not found!"); + return null; + } } } diff --git a/src/eva2/tools/StringTools.java b/src/eva2/tools/StringTools.java index 0c50301c..c0c9b8c4 100644 --- a/src/eva2/tools/StringTools.java +++ b/src/eva2/tools/StringTools.java @@ -1,7 +1,10 @@ package eva2.tools; +import java.util.LinkedList; import java.util.StringTokenizer; +import eva2.gui.BeanInspector; + public class StringTools { /** @@ -32,10 +35,99 @@ public class StringTools { return sbuf.toString(); } - public static void main(String[] args) { - System.out.println(toHTML("Hallo-asdfsadfsafdsadfo, dies ist ein doller test text!", 15)); - System.out.println(toHTML("Set the interval of data output for intermediate verbosity (in generations).", 15)); - System.out.println(toHTML("Set the interval of data output for intermediate verbosity (in generations).", 25)); - System.out.println(toHTML("Set the interval of data output for intermediate verbosity (in generations).", 30)); + public static boolean arrayContains(String[] arr, String key, boolean ignoreCase) { + return (searchStringArray(arr, key, 0, ignoreCase))>=0; } + + /** + * Search a String array for a given String and return its index if it is found. + * If it is not found, -1 is returned. + * + * @param arr + * @param key + * @param startIndex + * @param ignoreCase + * @return + */ + public static int searchStringArray(String[] arr, String key, int startIndex, boolean ignoreCase) { + for (int i=startIndex; i unrecogs=new LinkedList(); + //for (String string : argsArr) args.add(string); // create a linked list copy + for (int i=0; i