merging MK branch revs. 318:329. misc tool adds.; gui renaming with command line arguments for the client; Modified InterfaceOptimizer; DE update; Parameter adaption mechanisms, especially for PSO.

This commit is contained in:
Marcel Kronfeld 2009-07-17 09:01:20 +00:00
parent 61a6c4649e
commit 0baeebaf98
73 changed files with 1892 additions and 941 deletions

View File

@ -17,6 +17,7 @@ import java.awt.BorderLayout;
import java.awt.Dimension; import java.awt.Dimension;
import java.awt.Event; import java.awt.Event;
import java.awt.Frame; import java.awt.Frame;
import java.awt.HeadlessException;
import java.awt.Toolkit; import java.awt.Toolkit;
import java.awt.Window; import java.awt.Window;
import java.awt.event.ActionEvent; import java.awt.event.ActionEvent;
@ -24,8 +25,10 @@ import java.awt.event.ActionListener;
import java.awt.event.KeyEvent; import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter; import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent; import java.awt.event.WindowEvent;
import java.beans.BeanInfo;
import java.io.Serializable; import java.io.Serializable;
import java.net.URL; import java.net.URL;
import java.util.LinkedList;
import java.util.Properties; import java.util.Properties;
import java.util.Set; import java.util.Set;
import java.util.Vector; import java.util.Vector;
@ -51,21 +54,24 @@ import javax.swing.event.MenuListener;
import wsi.ra.jproxy.RemoteStateListener; import wsi.ra.jproxy.RemoteStateListener;
import wsi.ra.tool.BasicResourceLoader; import wsi.ra.tool.BasicResourceLoader;
import eva2.EvAInfo; import eva2.EvAInfo;
import eva2.gui.BeanInspector;
import eva2.gui.ExtAction; import eva2.gui.ExtAction;
import eva2.gui.HtmlDemo; import eva2.gui.HtmlDemo;
import eva2.gui.JEFrame; import eva2.gui.JEFrame;
import eva2.gui.JEFrameRegister; import eva2.gui.JEFrameRegister;
import eva2.gui.JExtMenu; import eva2.gui.JExtMenu;
import eva2.gui.JTabbedModuleFrame; import eva2.gui.EvATabbedFrameMaker;
import eva2.gui.LogPanel; import eva2.gui.LogPanel;
import eva2.server.EvAServer; import eva2.server.EvAServer;
import eva2.server.go.InterfaceGOParameters; import eva2.server.go.InterfaceGOParameters;
import eva2.server.modules.AbstractModuleAdapter; import eva2.server.modules.AbstractModuleAdapter;
import eva2.server.modules.GenericModuleAdapter;
import eva2.server.modules.ModuleAdapter; import eva2.server.modules.ModuleAdapter;
import eva2.tools.EVAERROR; import eva2.tools.EVAERROR;
import eva2.tools.EVAHELP; import eva2.tools.EVAHELP;
import eva2.tools.ReflectPackage; import eva2.tools.ReflectPackage;
import eva2.tools.Serializer; import eva2.tools.Serializer;
import eva2.tools.StringTools;
/** /**
* *
@ -122,6 +128,8 @@ public class EvAClient implements RemoteStateListener, Serializable {
private transient String currentModule = null; private transient String currentModule = null;
Vector<RemoteStateListener> superListenerList = null; Vector<RemoteStateListener> superListenerList = null;
private boolean withGUI = true ;
private EvATabbedFrameMaker frmMkr = null;
public void addRemoteStateListener(RemoteStateListener l) { public void addRemoteStateListener(RemoteStateListener l) {
if (superListenerList == null) superListenerList = new Vector<RemoteStateListener>(); if (superListenerList == null) superListenerList = new Vector<RemoteStateListener>();
@ -165,22 +173,74 @@ public class EvAClient implements RemoteStateListener, Serializable {
* *
*/ */
public EvAClient(final String hostName) { public EvAClient(final String hostName) {
this(hostName, null); this(hostName, null, false, false);
} }
/** /**
* Constructor of GUI of EvA2. * A constructor. Splash screen is optional, Gui is activated, no parent window.
* Works as client for the EvA2 server.
* *
* @see #EvAClient(String, Window, String, boolean, boolean, boolean)
* @param hostName
* @param paramsFile
* @param autorun
* @param nosplash
*/ */
public EvAClient(final String hostName, final Window parent) { public EvAClient(final String hostName, final String paramsFile, boolean autorun, boolean nosplash) {
final SplashScreen fSplashScreen = new SplashScreen(EvAInfo.splashLocation); 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 // preload some classes (into system cache) in a parallel thread
preloadClasses(); preloadClasses();
withGUI = !noGui;
// activate the splash screen (show later using SwingUtilities) // 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; currentModule = null;
@ -189,14 +249,24 @@ public class EvAClient implements RemoteStateListener, Serializable {
SwingUtilities.invokeLater( new Runnable() { SwingUtilities.invokeLater( new Runnable() {
public void run(){ public void run(){
long startTime = System.currentTimeMillis(); long startTime = System.currentTimeMillis();
init(hostName, parent); // this takes a bit init(hostName, paramsFile, parent); // this takes a bit
long wait = System.currentTimeMillis() - startTime; long wait = System.currentTimeMillis() - startTime;
try { if (!autorun) {
// if splashScreenTime has not passed, sleep some more if (!noSplash) try {
if (wait < splashScreenTime) Thread.sleep(splashScreenTime - wait); // if splashScreenTime has not passed, sleep some more
} catch (Exception e) {} 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 // 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 //EVA_EDITOR_PROPERTIES
useDefaultModule = getProperty("DefaultModule"); useDefaultModule = getProperty("DefaultModule");
@ -218,52 +288,53 @@ public class EvAClient implements RemoteStateListener, Serializable {
if (useDefaultModule.length() < 1) useDefaultModule = null; if (useDefaultModule.length() < 1) useDefaultModule = null;
} }
if (withGUI ) {
m_Frame = new JEFrame(); m_Frame = new JEFrame();
BasicResourceLoader loader = BasicResourceLoader.instance(); BasicResourceLoader loader = BasicResourceLoader.instance();
byte[] bytes = loader.getBytesFromResourceLocation(EvAInfo.iconLocation); byte[] bytes = loader.getBytesFromResourceLocation(EvAInfo.iconLocation);
try { try {
m_Frame.setIconImage(Toolkit.getDefaultToolkit().createImage(bytes)); m_Frame.setIconImage(Toolkit.getDefaultToolkit().createImage(bytes));
} catch (java.lang.NullPointerException e) { } catch (java.lang.NullPointerException e) {
System.out.println("Could not find EvA2 icon, please move resources folder to working directory!"); 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<String> 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);
}
} }
}); 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<String> 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 (m_ComAdapter != null) {
if (hostName != null) selectHost(hostName); if (hostName != null) selectHost(hostName);
@ -273,20 +344,27 @@ public class EvAClient implements RemoteStateListener, Serializable {
// m_mnuModule.setText("Select module"); // m_mnuModule.setText("Select module");
// m_mnuModule.repaint(); // m_mnuModule.repaint();
m_LogPanel.logMessage("Working directory is: " + System.getProperty("user.dir")); if (withGUI) {
m_LogPanel.logMessage("Class path is: " + System.getProperty("java.class.path",".")); 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())) { if (!(m_Frame.isVisible())) {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); 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.setLocation((int)((screenSize.width-m_Frame.getWidth())/2), (int)((screenSize.height-m_Frame.getHeight())/2.5));
m_Frame.pack(); m_Frame.pack();
m_Frame.setVisible(true); 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 * @param args command line parameters
*/ */
@ -294,17 +372,59 @@ public class EvAClient implements RemoteStateListener, Serializable {
if (TRACE) { if (TRACE) {
System.out.println(EVAHELP.getSystemPropertyString()); 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<unknownArgs.length; i++) System.err.println(" " + args[unknownArgs[i]]);
if (values[0]==null) System.err.println("Try --help as argument.");
}
if (values[0]!=null) {
System.out.println(usage());
} else {
boolean autorun=(values[1]!=null);
boolean nosplash=(values[2]!=null);
boolean nogui=(values[3]!=null);
String hostName=StringTools.checkSingleStringArg(keys[4], values[4], arities[4]-1);
String paramsFile=StringTools.checkSingleStringArg(keys[5], values[5], arities[5]-1);
if (TRACE) System.out.println("Command line arguments were: ");
if (TRACE) System.out.println(" " + BeanInspector.toString(keys));
if (TRACE) System.out.println(" " + BeanInspector.toString(values));
EvAClient Client = new EvAClient(hostName, paramsFile, autorun, nosplash, nogui);
}
} }
// /** public static String usage() {
// * StringBuffer sbuf = new StringBuffer();
// */ sbuf.append(EvAInfo.productName);
// public void addInternalFrame(JInternalFrame newFrame) { sbuf.append(" - ");
// m_Desktop.add(newFrame); sbuf.append(EvAInfo.productLongName);
// newFrame.toFront(); sbuf.append(" - Version ");
// } sbuf.append(EvAInfo.versionNum);
sbuf.append("\n");
sbuf.append("License: ");
sbuf.append(EvAInfo.LGPLFile);
sbuf.append("\n");
sbuf.append("Homepage: ");
sbuf.append(EvAInfo.url);
sbuf.append("\n");
sbuf.append("Command-line arguments:\n");
sbuf.append(" --help: Show this text and exit\n");
sbuf.append(" --nosplash: Deactivate splash screen\n");
sbuf.append(" --nogui: Deactivate GUI (makes most sense with autorun and params set)\n");
sbuf.append(" --autorun: Start an optimization immediately and exit after execution\n");
sbuf.append(" --params PARAMFILE: Load the (serialized) parameters file on start\n");
sbuf.append(" --remotehost HOSTNAME: Try to load a module from a (remote) server\n");
return sbuf.toString();
}
/** /**
* *
@ -316,7 +436,7 @@ public class EvAClient implements RemoteStateListener, Serializable {
m_actModuleLoad = new ExtAction("&Load", "Load Module", m_actModuleLoad = new ExtAction("&Load", "Load Module",
KeyStroke.getKeyStroke(KeyEvent.VK_L, Event.CTRL_MASK)) { KeyStroke.getKeyStroke(KeyEvent.VK_L, Event.CTRL_MASK)) {
public void actionPerformed(ActionEvent e) { public void actionPerformed(ActionEvent e) {
loadModuleFromServer(null); loadModuleFromServer(null, null);
} }
}; };
@ -390,9 +510,6 @@ public class EvAClient implements RemoteStateListener, Serializable {
*/ */
} }
/**
*
*/
private void buildMenu() { private void buildMenu() {
m_barMenu = new JMenuBar(); m_barMenu = new JMenuBar();
m_Frame.setJMenuBar(m_barMenu); m_Frame.setJMenuBar(m_barMenu);
@ -400,11 +517,6 @@ public class EvAClient implements RemoteStateListener, Serializable {
JExtMenu mnuLookAndFeel = new JExtMenu("&Look and Feel"); JExtMenu mnuLookAndFeel = new JExtMenu("&Look and Feel");
ButtonGroup grpLookAndFeel = new ButtonGroup(); ButtonGroup grpLookAndFeel = new ButtonGroup();
UIManager.LookAndFeelInfo laf[] = UIManager.getInstalledLookAndFeels(); UIManager.LookAndFeelInfo laf[] = UIManager.getInstalledLookAndFeels();
// if (TRACE) {
// for (int i=0;i<3;i++)
// System.out.println(laf[i].getName());
// System.out.println ("->"+UIManager.getLookAndFeel().getClass().getName());
// }
String LAF = Serializer.loadString("LookAndFeel.ser"); 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) { if (m_ComAdapter.getHostName() == null) {
System.err.println("error in loadModuleFromServer!"); System.err.println("error in loadModuleFromServer!");
return; return;
@ -567,10 +679,12 @@ public class EvAClient implements RemoteStateListener, Serializable {
} else { } else {
Serializer.storeString("lastmodule.ser", selectedModule); Serializer.storeString("lastmodule.ser", selectedModule);
loadSpecificModule(selectedModule); loadSpecificModule(selectedModule, paramsFile);
m_actHost.setEnabled(true); if (withGUI) {
m_actAvailableHost.setEnabled(true); m_actHost.setEnabled(true);
m_actAvailableHost.setEnabled(true);
}
logMessage("Selected Module: " + selectedModule); logMessage("Selected Module: " + selectedModule);
// m_LogPanel.statusMessage("Selected Module: " + selectedModule); // m_LogPanel.statusMessage("Selected Module: " + selectedModule);
} }
@ -601,11 +715,11 @@ public class EvAClient implements RemoteStateListener, Serializable {
} else return false; } else return false;
} }
private void loadSpecificModule(String selectedModule) { private void loadSpecificModule(String selectedModule, String paramsFile) {
ModuleAdapter newModuleAdapter = null; ModuleAdapter newModuleAdapter = null;
// //
try { try {
newModuleAdapter = m_ComAdapter.getModuleAdapter(selectedModule); newModuleAdapter = m_ComAdapter.getModuleAdapter(selectedModule, paramsFile, withGUI ? null : "EvA2");
} catch (Exception e) { } catch (Exception e) {
logMessage("Error while m_ComAdapter.GetModuleAdapter Host: " + e.getMessage()); logMessage("Error while m_ComAdapter.GetModuleAdapter Host: " + e.getMessage());
e.printStackTrace(); e.printStackTrace();
@ -621,7 +735,7 @@ public class EvAClient implements RemoteStateListener, Serializable {
System.setProperty("java.class.path", cp + System.getProperty("path.separator") + baseDir.getPath()); System.setProperty("java.class.path", cp + System.getProperty("path.separator") + baseDir.getPath());
ReflectPackage.resetDynCP(); ReflectPackage.resetDynCP();
m_ComAdapter.updateLocalMainAdapter(); m_ComAdapter.updateLocalMainAdapter();
loadSpecificModule(selectedModule); // end recursive call! handle with care! loadSpecificModule(selectedModule, paramsFile); // end recursive call! handle with care!
return; return;
} }
showLoadModules = true; showLoadModules = true;
@ -633,30 +747,31 @@ public class EvAClient implements RemoteStateListener, Serializable {
newModuleAdapter.addRemoteStateListener((RemoteStateListener)this); newModuleAdapter.addRemoteStateListener((RemoteStateListener)this);
} }
try { try {
// this (or rather: JModuleGeneralPanel) is where the start button etc come from! if (withGUI) {
JTabbedModuleFrame Temp = newModuleAdapter.getModuleFrame(); // this (or rather: EvAModuleButtonPanelMaker) is where the start button etc come from!
// newModuleAdapter.setLogPanel(m_LogPanel); 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 boolean wasVisible = m_Frame.isVisible();
// m_Frame.setLayout(new BorderLayout()); m_Frame.setVisible(false);
boolean wasVisible = m_Frame.isVisible(); m_Frame.getContentPane().removeAll();
m_Frame.setVisible(false);
m_Frame.getContentPane().removeAll();
// nested info-panel so that we can stay with simple borderlayouts // nested info-panel so that we can stay with simple borderlayouts
JPanel infoPanel = new JPanel(); JPanel infoPanel = new JPanel();
infoPanel.setLayout(new BorderLayout()); infoPanel.setLayout(new BorderLayout());
infoPanel.add(m_ProgressBar, BorderLayout.SOUTH); infoPanel.add(m_ProgressBar, BorderLayout.SOUTH);
infoPanel.add(m_LogPanel, BorderLayout.NORTH); infoPanel.add(m_LogPanel, BorderLayout.NORTH);
m_Frame.add(Temp.getToolBar(), BorderLayout.NORTH); m_Frame.add(frmMkr.getToolBar(), BorderLayout.NORTH);
m_Frame.add(moduleContainer, BorderLayout.CENTER); m_Frame.add(moduleContainer, BorderLayout.CENTER);
//m_Frame.add(m_ProgressBar, BorderLayout.CENTER); //m_Frame.add(m_ProgressBar, BorderLayout.CENTER);
//m_Frame.add(m_LogPanel, BorderLayout.SOUTH); //m_Frame.add(m_LogPanel, BorderLayout.SOUTH);
m_Frame.add(infoPanel, BorderLayout.SOUTH); m_Frame.add(infoPanel, BorderLayout.SOUTH);
m_Frame.pack(); m_Frame.pack();
m_Frame.setVisible(wasVisible); m_Frame.setVisible(wasVisible);
}
currentModule = selectedModule; currentModule = selectedModule;
// m_ModulGUIContainer.add(Temp); // m_ModulGUIContainer.add(Temp);
@ -701,7 +816,7 @@ public class EvAClient implements RemoteStateListener, Serializable {
logMessage("Selected Host: " + hostName); logMessage("Selected Host: " + hostName);
if (currentModule != null) { if (currentModule != null) {
logMessage("Reloading module from server..."); logMessage("Reloading module from server...");
loadModuleFromServer(currentModule); loadModuleFromServer(currentModule, null);
} }
// m_mnuModule.setText("Select module"); // m_mnuModule.setText("Select module");
@ -782,6 +897,7 @@ public class EvAClient implements RemoteStateListener, Serializable {
} }
long t = (System.currentTimeMillis() - startTime); long t = (System.currentTimeMillis() - startTime);
logMessage(String.format("Stopped after %1$d.%2$tL s", (t / 1000), (t % 1000))); 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; private static final long serialVersionUID = 1281793825850423095L;
String imgLocation; String imgLocation;

View File

@ -63,14 +63,14 @@ public class EvAComAdapter extends ComAdapter {
* Creates the ModulAdapters RMI Object on the server * Creates the ModulAdapters RMI Object on the server
* @return * @return
*/ */
public ModuleAdapter getModuleAdapter(String str) { public ModuleAdapter getModuleAdapter(String selectedModuleName, String paramsFile, String noGuiStatsFile) {
ModuleAdapter newModuleAdapter; ModuleAdapter newModuleAdapter;
if ((m_RMIServer == null) && isRunLocally()) { if ((m_RMIServer == null) && isRunLocally()) {
//ret = evaAdapter.getModuleAdapter(Modul, hostAdd, this.m_MainAdapterClient); //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 { } else {
newModuleAdapter = ((RMIConnectionEvA)getConnection(getHostName())).getModuleAdapter(str); newModuleAdapter = ((RMIConnectionEvA)getConnection(getHostName())).getModuleAdapter(selectedModuleName);
if (newModuleAdapter == null) System.err.println("RMI Error for getting ModuleAdapterObject : " + str); if (newModuleAdapter == null) System.err.println("RMI Error for getting ModuleAdapterObject : " + selectedModuleName);
} }
return newModuleAdapter; return newModuleAdapter;
} }

View File

@ -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 obj
* @param mem * @param mem

View File

@ -33,13 +33,11 @@ import eva2.server.go.problems.InterfaceOptimizationProblem;
import eva2.server.go.strategies.InterfaceOptimizer; import eva2.server.go.strategies.InterfaceOptimizer;
import eva2.server.modules.AbstractModuleAdapter; import eva2.server.modules.AbstractModuleAdapter;
import eva2.server.modules.ModuleAdapter; 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; public static boolean TRACE = false;
private String m_Name ="undefined"; private String m_Name ="undefined";
private ModuleAdapter m_Adapter; 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_Name = "GENERAL";
m_StateRunning = state; m_StateRunning = state;
if (TRACE) System.out.println("Constructor JModuleGeneralPanel:"); if (TRACE) System.out.println("Constructor EvAModuleButtonPanelMaker:");
m_Adapter = Adapter; m_Adapter = Adapter;
} }
/**
* public JComponent makePanel() {
*/
public JComponent installActions() {
String myhostname = null; String myhostname = null;
m_Panel= new JPanel(); m_Panel= new JPanel();
@ -89,18 +85,8 @@ public class JModuleGeneralPanel implements RemoteStateListener, Serializable {
//System.out.println("Start tm_RunButton.addActionListener Run Opt pressed ====================!!!!!!!!!!!!!!!!!!"); //System.out.println("Start tm_RunButton.addActionListener Run Opt pressed ====================!!!!!!!!!!!!!!!!!!");
m_RunButton.addActionListener(new ActionListener() { m_RunButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){ public void actionPerformed(ActionEvent e){
//System.out.println("Run Opt pressed !!!!!!!!!!!!!!!!======================!!"); //Run Opt pressed !
try { onUserStart();
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() );
}
} }
} }
); );
@ -181,6 +167,20 @@ public class JModuleGeneralPanel implements RemoteStateListener, Serializable {
return m_Panel; 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() { private void makeHelpButton() {
/////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////
if (m_HelperFileName!=null && (!m_HelperFileName.equals(""))) { if (m_HelperFileName!=null && (!m_HelperFileName.equals(""))) {
@ -210,7 +210,7 @@ public class JModuleGeneralPanel implements RemoteStateListener, Serializable {
* *
*/ */
public void performedStop() { public void performedStop() {
if (TRACE) System.out.println("JModuleGeneralPanel.stopOptPerformed"); if (TRACE) System.out.println("EvAModuleButtonPanelMaker.stopOptPerformed");
m_RunButton.setEnabled(true); m_RunButton.setEnabled(true);
m_PPButton.setEnabled(true); m_PPButton.setEnabled(true);
m_RunButton.repaint(); m_RunButton.repaint();

View File

@ -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<PanelMaker> guiContainer;
private JExtToolBar m_BarStandard;
EvAModuleButtonPanelMaker butPanelMkr=null;
public EvATabbedFrameMaker(ArrayList<PanelMaker> 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<guiContainer.size();i++) {
PanelMaker element = guiContainer.get(i);
if (element instanceof EvAModuleButtonPanelMaker) {
m_BarStandard.add(element.makePanel());
butPanelMkr=(EvAModuleButtonPanelMaker)element;
} else if (element instanceof JParaPanel) {
m_MainPanel.addTab (((JParaPanel)element).getName(), element.makePanel());
}
}
m_SuperPanel.add(m_MainPanel, gbconst);
return m_SuperPanel;
}
public JExtToolBar getToolBar() {
return m_BarStandard;
}
/**
* Emulate pressing the start button.
*/
public void onUserStart() {
if (butPanelMkr!=null) {
butPanelMkr.onUserStart();
} else System.err.println("Error: button panel was null (EvATabbedFrameMaker)");
}
}

View File

@ -30,6 +30,7 @@ import javax.swing.JOptionPane;
import javax.swing.JPanel; import javax.swing.JPanel;
import wsi.ra.jproxy.RMIProxyLocal; import wsi.ra.jproxy.RMIProxyLocal;
import eva2.server.go.tools.FileTools;
import eva2.tools.EVAHELP; import eva2.tools.EVAHELP;
/** /**
* *
@ -55,8 +56,6 @@ public class GOEPanel extends JPanel implements ItemListener {
private JButton m_cancelBut; private JButton m_cancelBut;
/** edit source button */ /** edit source button */
// private JButton m_editSourceBut; // private JButton m_editSourceBut;
/** The filechooser for opening and saving object files */
private JFileChooser m_FileChooser;
/** Creates the GUI editor component */ /** Creates the GUI editor component */
private Vector<String> m_ClassesLongName; private Vector<String> m_ClassesLongName;
private GenericObjectEditor m_goe = null; private GenericObjectEditor m_goe = null;
@ -90,7 +89,8 @@ public class GOEPanel extends JPanel implements ItemListener {
m_OpenBut.setEnabled(true); m_OpenBut.setEnabled(true);
m_OpenBut.addActionListener(new ActionListener() { m_OpenBut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) { public void actionPerformed(ActionEvent e) {
Object object = openObject(); Object object = FileTools.openObject(m_OpenBut, m_goe.getClassType());
// Object object = openObject();
if (object != null) { if (object != null) {
// setValue takes care of: Making sure obj is of right type, // setValue takes care of: Making sure obj is of right type,
// and firing property change. // and firing property change.
@ -107,7 +107,8 @@ public class GOEPanel extends JPanel implements ItemListener {
m_SaveBut.setEnabled(true); m_SaveBut.setEnabled(true);
m_SaveBut.addActionListener(new ActionListener() { m_SaveBut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) { 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); 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 * Makes a copy of an object using serialization
* @param source the object to copy * @param source the object to copy

View File

@ -143,7 +143,12 @@ public class GenericObjectEditor implements PropertyEditor {
if (TRACE) System.out.println("Class " + class1 + " wants to be hidden from GOE, skipping..."); if (TRACE) System.out.println("Class " + class1 + " wants to be hidden from GOE, skipping...");
continue; continue;
} }
} catch (Exception e) {} } catch (Exception e) {
} catch (Error e) {
System.err.println("Error on checking fields of " + class1 + ": " + e);
continue;
}
// if (f) // if (f)
if (!Modifier.isAbstract(m) && !class1.isInterface()) { // dont take abstract classes or interfaces if (!Modifier.isAbstract(m) && !class1.isInterface()) { // dont take abstract classes or interfaces
try { try {

View File

@ -20,6 +20,8 @@ import java.awt.BasicStroke;
import java.io.Serializable; import java.io.Serializable;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import eva2.tools.Mathematics;
/*==========================================================================* /*==========================================================================*
* CLASS DECLARATION * CLASS DECLARATION
*==========================================================================*/ *==========================================================================*/
@ -30,7 +32,7 @@ public class GraphPointSet {
private String m_InfoString = "Incomplete_Run"; private String m_InfoString = "Incomplete_Run";
private int m_GraphLabel; private int m_GraphLabel;
private int colorOffset = 0; private int colorOffset = 0;
private ArrayList m_PointSetContainer = new ArrayList(); private ArrayList<PointSet> m_PointSetContainer = new ArrayList<PointSet>();
private float m_Stroke = (float) 1.0; private float m_Stroke = (float) 1.0;
private boolean m_isStatisticsGraph = false; private boolean m_isStatisticsGraph = false;
// private DPointSet m_PointSet_1; // 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 * @param useForce forces the add even if point counts mismatch, maybe losing some data points
*/ */
public void addGraph (GraphPointSet set,DMeasures measures, boolean useForce) { public void addGraph (GraphPointSet set,DMeasures measures, boolean useForce) {
if (set.m_ConnectedPointSet.getSize()!=m_ConnectedPointSet.getSize() && if (set.m_ConnectedPointSet.getSize()!=m_ConnectedPointSet.getSize() &&
m_ConnectedPointSet.getSize()!=0 && !useForce) { m_ConnectedPointSet.getSize()!=0 && !useForce) {
System.err.println("WARNING addGraph not possible, lost last graph"); System.err.println("WARNING addGraph not possible, lost last graph");
System.err.println(" m_ConnectedPointSet.getSize() "+ m_ConnectedPointSet.getSize()); System.err.println(" m_ConnectedPointSet.getSize() "+ m_ConnectedPointSet.getSize());
return; return;
} }
m_isStatisticsGraph = true; if (set.getPointSet().getSize()==0) {
removeAllPoints(); System.err.println("Refusing to add empty graph...");
m_ConnectedPointSet.setColor(set.getColor()); return;
// m_PointSet_1.setColor(m_ConnectedPointSet.getColor()); }
// m_PointSet_2.setColor(m_ConnectedPointSet.getColor()); m_isStatisticsGraph = true;
// m_PointSet_3.setColor(m_ConnectedPointSet.getColor()); removeAllPoints();
m_PointSetContainer.add(set.getPointSet()); m_ConnectedPointSet.setColor(set.getColor());
int[] index = new int[m_PointSetContainer.size()];
int[] GraphSize = new int[m_PointSetContainer.size()]; m_PointSetContainer.add(set.getPointSet());
for (int i=0;i<m_PointSetContainer.size();i++) int[] index = new int[m_PointSetContainer.size()];
GraphSize[i] = ((PointSet) m_PointSetContainer.get(i)).getSize(); int[] GraphSize = new int[m_PointSetContainer.size()];
boolean doit = true; for (int i=0;i<m_PointSetContainer.size();i++) {
double minx =0; GraphSize[i] = ((PointSet) m_PointSetContainer.get(i)).getSize();
while ( doit ) { if (GraphSize[i]<=0) System.err.println("Warning: invalid graph size of " + GraphSize[i] + " at " + i + "! (GraphPointSet.addGraph)");
minx = ((PointSet) m_PointSetContainer.get(0)).m_X[index[0]]; }
int minindex = 0; if (Mathematics.sum(GraphSize)==0) {
//System.out.println("m_PointSetContainer.size()"+m_PointSetContainer.size()); System.err.println("Error: not adding empty graphs... (GraphPointSet.addGraph)");
for (int i = 1;i<m_PointSetContainer.size();i++) { return;
//System.out.println("i="+i); }
if (minx > ((PointSet) m_PointSetContainer.get(i)).m_X[index[i]]) { boolean allSetsHaveMorePoints = true;
minindex = i; double nextXValue;
minx = ((PointSet) m_PointSetContainer.get(i)).m_X[index[i]]; double[] y = new double[m_PointSetContainer.size()];
} while ( allSetsHaveMorePoints ) { // Loop over all point sets, add them up and calc. mean
} // this is a bit more complicated because it is allowed that the point sets are asynchronouos
// Stelle minx wird gezeichnet. jetzt alle y werte dazu finden // in the sense that the x values do not have to match - y values for any x value found are averaged
int numberofpoints =0; // over all points. However curves may look strange if this happens, since they consist of
for (int i = 0;i<m_PointSetContainer.size();i++) { // heterogenous points.
if (minx == ((PointSet) m_PointSetContainer.get(i)).m_X[index[i]]) nextXValue = m_PointSetContainer.get(0).m_X[index[0]];
numberofpoints++; //System.out.println("m_PointSetContainer.size()"+m_PointSetContainer.size());
} for (int i = 1;i<m_PointSetContainer.size();i++) { // search for smalles x value at next index
double[] y = new double[numberofpoints]; //System.out.println("i="+i);
int c = 0; if (nextXValue > m_PointSetContainer.get(i).m_X[index[i]]) {
for (int i = 0;i<m_PointSetContainer.size();i++) { nextXValue = m_PointSetContainer.get(i).m_X[index[i]];
if (minx == ((PointSet) m_PointSetContainer.get(i)).m_X[index[i]]) { }
y[c]= ((PointSet) m_PointSetContainer.get(i)).m_Y[index[i]]; }
c++; // Stelle nextXValue wird gezeichnet. jetzt alle y werte dazu finden
index[i]++; int numberofpoints =0;
} for (int i = 0;i<m_PointSetContainer.size();i++) { // collect all points at next x-value
} if (nextXValue == m_PointSetContainer.get(i).m_X[index[i]]) {
double ymean =0; y[i]=m_PointSetContainer.get(i).m_Y[index[i]];
for (int i = 0;i<y.length;i++) index[i]++;
ymean = ymean + y[i]; numberofpoints++;
ymean = ymean / y.length; } else y[i]=0;
// compute median double median = getMedian(y); }
addDPoint(minx,ymean);// System.out.println("ymean "+ymean+" y.length "+ y.length); double ymean = Mathematics.sum(y)/numberofpoints;
//addDPoint(minx,median);// System.out.println("ymean "+ymean+" y.length "+ y.length); // compute median double median = getMedian(y);
doit = true; addDPoint(nextXValue,ymean);// System.out.println("ymean "+ymean+" y.length "+ y.length);
for (int i=0;i<m_PointSetContainer.size();i++) { //addDPoint(minx,median);// System.out.println("ymean "+ymean+" y.length "+ y.length);
if (GraphSize[i] <= index[i] ) { for (int i=0;i<m_PointSetContainer.size();i++) { // Stop if one of the point sets has no more points
doit = false; if (GraphSize[i] <= index[i] ) {
break; allSetsHaveMorePoints = false;
} break;
} }
// doit = false; }
// for (int i=0;i<m_PointSetContainer.size();i++) { }
// if (GraphSize[i] > index[i] ) {
// doit = true;
// break;
// }
// }
}
// m_PointSet_2.removeAllPoints();
} }
/** /**
* *
@ -422,65 +417,6 @@ public class GraphPointSet {
m_Stroke = stroke; m_Stroke = stroke;
//setStroke(new BasicStroke( m_Stroke )); //setStroke(new BasicStroke( m_Stroke ));
} }
// /**
// *
// */
// public SerPointSet getSerPointSet () {
// SerPointSet ret= new SerPointSet(this);
// return ret;
// }
//
// /**
// *
// */
// class SerPointSet implements Serializable {
// private String m_InfoString;
// private int m_GraphLabel;
// private Color m_Color;
// private float m_Stroke;
//// private PointSet m_PointSet_1;
//// private PointSet m_PointSet_2;
//// private PointSet m_PointSet_3;
// private PointSet m_ConnectedPointSet;
//// private PointSet m_VarPointSetPlus;
//// private PointSet m_VarPointSetMinus;
// private boolean m_isStatisticeGraph;
//// private boolean m_showVarianz;
// /**
// *
// */
// public SerPointSet (GraphPointSet Source) {
// m_InfoString = Source.m_InfoString;
// m_GraphLabel = Source.m_GraphLabel;
// m_Color = Source.m_Color;
// m_Stroke = Source.m_Stroke;
// m_isStatisticeGraph = Source.m_isStatisticsGraph;
//
// // save the connected points
// m_ConnectedPointSet = new PointSet(Source.getConnectedPointSet());
//// m_PointSet_1 = new PointSet (Source.m_PointSet_1);
//// m_PointSet_2 = new PointSet (Source.m_PointSet_2);
//// m_PointSet_3 = new PointSet (Source.m_PointSet_3);
// }
// /**
// *
// */
// public GraphPointSet getGraphPointSet () {
// GraphPointSet ret = new GraphPointSet(10,m_GraphLabel);
// ret.setInfoString(this.m_InfoString,this.m_Stroke);
// ret.setColor(this.m_Color);
// ret.m_Color = m_Color;
// ret.m_Stroke = m_Stroke;
// ret.m_isStatisticsGraph = m_isStatisticeGraph;
// //@todo why doesn't that work!?
//// ret.m_ConnectedPointSet = (DPointSetMultiIcon)m_ConnectedPointSet;
//// ret.m_PointSet_1 = m_PointSet_1.getDPointSet();
//// ret.m_PointSet_2 = m_PointSet_2.getDPointSet();
//// ret.m_PointSet_3 = m_PointSet_3.getDPointSet();
// ret.m_ConnectedPointSet.setConnected(true);
// return ret;
// }
// }
/** /**
* *

View File

@ -17,13 +17,7 @@ import java.beans.PropertyEditor;
import java.beans.PropertyEditorManager; import java.beans.PropertyEditorManager;
import java.io.Serializable; import java.io.Serializable;
/* public class JParaPanel implements Serializable, PanelMaker {
* ==========================================================================*
* CLASS DECLARATION
* ==========================================================================
*/
public class JParaPanel implements Serializable {
public static boolean TRACE = false; public static boolean TRACE = false;
protected String m_Name = "undefined"; protected String m_Name = "undefined";
@ -44,7 +38,7 @@ public class JParaPanel implements Serializable {
/** /**
*/ */
public JComponent installActions() { public JComponent makePanel() {
m_Panel = new JPanel(); m_Panel = new JPanel();
//m_Panel.setPreferredSize(new Dimension(200, 200)); // MK: this was evil, killing all the auto-layout mechanisms //m_Panel.setPreferredSize(new Dimension(200, 200)); // MK: this was evil, killing all the auto-layout mechanisms
PropertyEditorProvider.installEditors(); PropertyEditorProvider.installEditors();

View File

@ -1,152 +0,0 @@
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.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Toolkit;
import java.io.Serializable;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import wsi.ra.tool.BasicResourceLoader;
import eva2.EvAInfo;
import eva2.server.modules.ModuleAdapter;
/*==========================================================================*
* CLASS DECLARATION
*==========================================================================*/
/**
*
*/
public class JTabbedModuleFrame implements Serializable {
private ArrayList m_GUIContainer;
// private JTabbedPane m_MainPanel;
private ModuleAdapter m_ProxyModuleAdapter;
private JPanel m_PanelTool;
// private JPanel m_SuperPanel;
private JExtToolBar m_BarStandard;
private JFrame m_Frame;
private String m_AdapterName;
private String m_Host;
/**
*
*/
public JTabbedModuleFrame(ModuleAdapter newModuleAdapter,String AdapterName,String Host,ArrayList GUIContainer) {
m_ProxyModuleAdapter = newModuleAdapter;
m_AdapterName = AdapterName;
m_Host = Host;
m_GUIContainer = GUIContainer;
}
public JPanel createContentPane() {
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();
buildToolBar();
for (int i=0;i<m_GUIContainer.size();i++) {
Object TEMP = m_GUIContainer.get(i);
if (TEMP instanceof JModuleGeneralPanel) {
m_BarStandard.add((JPanel) ((JModuleGeneralPanel)TEMP).installActions());
continue;
}
if (TEMP instanceof JParaPanel) {
JPanel tmpPanel = (JPanel)((JParaPanel)TEMP).installActions();
m_MainPanel.addTab (((JParaPanel)TEMP).getName(), tmpPanel);
}
}
m_MainPanel.addChangeListener(new ChangeListener () {
public void stateChanged (ChangeEvent evt) {
//Dimension d = (m_MainPanel.getSelectedComponent()).getPreferredSize();
//System.out.println("HERETETETETE " + d.height + " " + d.width + " " + m_MainPanel.getSelectedIndex());
//m_Frame.setSize(d);
//m_MainPanel.validate();
//m_Frame.pack();
//m_Frame.validate();
}
});
m_SuperPanel.add(m_MainPanel, gbconst);
return m_SuperPanel;
}
public JExtToolBar getToolBar() {
return m_BarStandard;
}
/**
*
*/
public void createGUI() {
m_Frame = new JEFrame (m_AdapterName+" on "+m_Host);
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!");
}
JPanel m_SuperPanel = createContentPane();
m_Frame.getContentPane().add(m_SuperPanel);
m_Frame.getContentPane().add(m_PanelTool, BorderLayout.NORTH);
m_Frame.pack();
m_Frame.setVisible(true);
System.out.println(m_Frame.getPreferredSize().toString());
m_Frame.setDefaultCloseOperation(JInternalFrame.DO_NOTHING_ON_CLOSE);
m_Frame.toFront();
}
// /**
// *
// */
// private void removeGUI() {
// System.out.println("removeGUI");
// for (int i=0;i< m_GUIContainer.size();i++) {
// Object TEMP = m_GUIContainer.get(i);
// if (TEMP instanceof JPanel)
// m_MainPanel.remove((JPanel)TEMP);
// }
// m_Frame.repaint();
// }
/**
*
*/
private void buildToolBar(){
m_PanelTool = new JPanel(new FlowLayout(FlowLayout.LEFT));
m_BarStandard = new JExtToolBar();
m_BarStandard.setFloatable(false);
// m_BarStandard.setBorder(BorderFactory.createRaisedBevelBorder());
m_PanelTool.add(m_BarStandard);
// m_Frame.getContentPane().add(m_PanelTool, BorderLayout.NORTH);
}
}

View File

@ -23,6 +23,7 @@ import java.awt.event.MouseEvent;
import java.awt.event.MouseListener; import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter; import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent; import java.awt.event.WindowEvent;
import java.io.File;
import java.io.Serializable; import java.io.Serializable;
import javax.swing.BorderFactory; import javax.swing.BorderFactory;
@ -37,6 +38,7 @@ import javax.swing.event.ChangeListener;
import wsi.ra.tool.BasicResourceLoader; import wsi.ra.tool.BasicResourceLoader;
import eva2.EvAInfo; import eva2.EvAInfo;
import eva2.server.go.tools.FileTools;
/*==========================================================================* /*==========================================================================*
* CLASS DECLARATION * CLASS DECLARATION
*==========================================================================*/ *==========================================================================*/
@ -46,6 +48,7 @@ import eva2.EvAInfo;
public class JTextoutputFrame implements JTextoutputFrameInterface, public class JTextoutputFrame implements JTextoutputFrameInterface,
ActionListener, ActionListener,
Serializable { Serializable {
private JMenuItem clearItem, saveItem;
public static boolean TRACE = false; public static boolean TRACE = false;
protected String m_Name ="undefined"; protected String m_Name ="undefined";
private transient JTextArea m_TextArea = null; private transient JTextArea m_TextArea = null;
@ -161,9 +164,12 @@ Serializable {
void makePopupMenu() { void makePopupMenu() {
//Create the popup menu. //Create the popup menu.
popup = new JPopupMenu(); popup = new JPopupMenu();
JMenuItem menuItem = new JMenuItem("Clear"); clearItem = new JMenuItem("Clear");
menuItem.addActionListener(this); clearItem.addActionListener(this);
popup.add(menuItem); popup.add(clearItem);
saveItem = new JMenuItem("Save as...");
saveItem.addActionListener(this);
popup.add(saveItem);
// menuItem = new JMenuItem("Refine Multiruns"); // menuItem = new JMenuItem("Refine Multiruns");
// menuItem.addActionListener(this); // menuItem.addActionListener(this);
// popup.add(menuItem); // popup.add(menuItem);
@ -178,13 +184,13 @@ Serializable {
} }
public void actionPerformed(ActionEvent e) { public void actionPerformed(ActionEvent e) {
if (e.getSource() == popup.getComponent(0)) { JMenuItem src = (JMenuItem)e.getSource();
if (src == clearItem) {
m_TextArea.setText(null); m_TextArea.setText(null);
} } else if (src == saveItem) {
// else if (e.getSource() == popup.getComponent(1)) { FileTools.saveObjectWithFileChooser(frame, m_TextArea.getText());
// m_TextArea.append(MultirunRefiner.refineToText(m_TextArea.getText())); // File outfile = FileTools.writeString("TextOutput.txt", m_TextArea.getText());
// } } else System.err.println("Unknown popup component (JTextoutputFrame)!");
else System.out.println("no popup component!");
} }
} }

View File

@ -0,0 +1,12 @@
package eva2.gui;
import javax.swing.JComponent;
/**
* Simple helper interface.
* @author mkron
*
*/
public interface PanelMaker {
public JComponent makePanel();
}

View File

@ -25,9 +25,15 @@ public interface EvAMainAdapter extends MainAdapter {
public String[] getModuleNameList(); public String[] getModuleNameList();
// returns the corresponding ModuleAdapter // returns the corresponding ModuleAdapter
public ModuleAdapter getModuleAdapter(String str, public ModuleAdapter getModuleAdapter(String selectedModuleName,
boolean withoutRMI, boolean withoutRMI,
String hostAddress, String hostAddress,
MainAdapterClient client); MainAdapterClient client);
public ModuleAdapter getModuleAdapter(String selectedModuleName,
boolean withoutRMI,
String hostAddress,
String paramsFile,
String noGuiStatsFile,
MainAdapterClient client);
} }

View File

@ -24,27 +24,24 @@ import wsi.ra.jproxy.MainAdapterImpl;
*/ */
public class EvAMainAdapterImpl extends MainAdapterImpl implements EvAMainAdapter { public class EvAMainAdapterImpl extends MainAdapterImpl implements EvAMainAdapter {
private ModuleServer m_ModulServer=null; private ModuleServer m_ModulServer=null;
/**
*
*/
public EvAMainAdapterImpl() { public EvAMainAdapterImpl() {
super(); super();
m_ModulServer = new ModuleServer(EvAClient.getProperties()); m_ModulServer = new ModuleServer(EvAClient.getProperties());
} }
/**
*
*/
public String[] getModuleNameList() { public String[] getModuleNameList() {
return m_ModulServer.getModuleNameList(); return m_ModulServer.getModuleNameList();
} }
/** public ModuleAdapter getModuleAdapter(String selectedModuleName, boolean withoutRMI, String hostAddress, MainAdapterClient client) {
* return getModuleAdapter(selectedModuleName, withoutRMI, hostAddress, null, null, client);
*/
public ModuleAdapter getModuleAdapter(String str, boolean withoutRMI, String hostAddress, MainAdapterClient client) {
if (TRACE) System.out.println("MainAdapterImpl.GetModuleAdapter() for module " +
str +" for Client: "+hostAddress+ " called");
return m_ModulServer.createModuleAdapter(str,client,withoutRMI,hostAddress);
} }
public ModuleAdapter getModuleAdapter(String selectedModuleName, boolean withoutRMI, String hostAddress, String paramsFile, String noGuiStatsFile, MainAdapterClient client) {
if (TRACE) System.out.println("MainAdapterImpl.GetModuleAdapter() for module " +
selectedModuleName +" for Client: "+hostAddress+ " called");
return m_ModulServer.createModuleAdapter(selectedModuleName,client,withoutRMI,hostAddress, paramsFile, noGuiStatsFile);
}
} }

View File

@ -20,6 +20,7 @@ import java.util.Properties;
import wsi.ra.jproxy.MainAdapterClient; import wsi.ra.jproxy.MainAdapterClient;
import wsi.ra.jproxy.RMIProxyLocal; import wsi.ra.jproxy.RMIProxyLocal;
import eva2.server.modules.GOModuleAdapter;
import eva2.server.modules.ModuleAdapter; import eva2.server.modules.ModuleAdapter;
import eva2.tools.EVAERROR; import eva2.tools.EVAERROR;
import eva2.tools.ReflectPackage; import eva2.tools.ReflectPackage;
@ -120,7 +121,7 @@ public class ModuleServer {
*/ */
public ModuleAdapter createModuleAdapter(String selectedModuleName, public ModuleAdapter createModuleAdapter(String selectedModuleName,
MainAdapterClient Client, boolean runWithoutRMI, MainAdapterClient Client, boolean runWithoutRMI,
String hostAddress) { String hostAddress, String paramsFile, String noGuiLogFile) {
m_ModuleAdapterCounter++; m_ModuleAdapterCounter++;
String adapterName = new String("ERROR MODULADAPTER !!"); String adapterName = new String("ERROR MODULADAPTER !!");
if (TRACE) { if (TRACE) {
@ -156,13 +157,28 @@ public class ModuleServer {
adapterName = new String(m_ModuleAdapterCounter + "_Running_" + adapterName = new String(m_ModuleAdapterCounter + "_Running_" +
selectedModuleName); selectedModuleName);
Constructor<?>[] constructorArr = module.getConstructors();
// create a module instance // create a module instance
Constructor<?>[] Constructor = module.getConstructors(); if ((paramsFile==null && noGuiLogFile==null) || !module.equals(GOModuleAdapter.class)) {
Object[] Para = new Object[2]; if (paramsFile!=null) System.err.println("Cant load params - no matching constructor found for " + adapterName + " (ModuleServer)");
Class<?> paramTypes[] = (Constructor[0]).getParameterTypes(); if (noGuiLogFile!=null) System.err.println("Cant deactivate GUI - no matching constructor found for " + adapterName + " (ModuleServer)");
Para[0] = paramTypes[0].cast(adapterName); Object[] Para = new Object[2];
Para[1] = paramTypes[1].cast(Client); Class<?> paramTypes[] = (constructorArr[0]).getParameterTypes();
m_ModuleAdapter = (ModuleAdapter) Constructor[0].newInstance(Para); 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 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 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! // for a strange reason, it is _not_ enough if a superclass implements the same interface!

View File

@ -180,11 +180,11 @@ public class GOStandaloneVersion implements InterfaceGOStandalone, InterfacePopu
System.out.println("No Class found for " + tmp); System.out.println("No Class found for " + tmp);
} }
if ((object != null) && (editor != null)) paraPanel.registerEditor(object, editor); 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"); 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(); this.m_OptionsPanel = new JTabbedPane();
JParaPanel paraPanel2 = new JParaPanel(this.m_GO, "MyGUI"); 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 Parameters", this.m_O2);
((JTabbedPane)this.m_OptionsPanel).addTab("GO Statistics", this.m_O1); ((JTabbedPane)this.m_OptionsPanel).addTab("GO Statistics", this.m_O1);
this.m_MainPanel.add(this.m_OptionsPanel, BorderLayout.CENTER); this.m_MainPanel.add(this.m_OptionsPanel, BorderLayout.CENTER);

View File

@ -83,7 +83,7 @@ public class MOCCOProblemInitialization extends MOCCOPhase implements InterfaceP
this.m_Mocco.m_JPanelParameters.setLayout(new BorderLayout()); this.m_Mocco.m_JPanelParameters.setLayout(new BorderLayout());
this.m_Mocco.m_JPanelParameters.add(tmpP, BorderLayout.NORTH); this.m_Mocco.m_JPanelParameters.add(tmpP, BorderLayout.NORTH);
JParaPanel paraPanel = new JParaPanel(this.m_Mocco.m_State.m_OriginalProblem, "MyGUI"); 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() { ActionListener continue2 = new ActionListener() {

View File

@ -64,7 +64,7 @@ public class MOCCOProblemRedefinition extends MOCCOPhase implements InterfacePro
this.m_Mocco.m_JPanelParameters.add(tmpP, BorderLayout.NORTH); this.m_Mocco.m_JPanelParameters.add(tmpP, BorderLayout.NORTH);
JParaPanel paraPanel = new JParaPanel(this.m_Problem, "MyGUI"); 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_JPanelParameters.add(tmpC, BorderLayout.CENTER);
this.m_Mocco.m_JFrame.setVisible(true); this.m_Mocco.m_JFrame.setVisible(true);

View File

@ -81,7 +81,7 @@ public class TestESCrossover implements java.io.Serializable {
this.m_ButtonPanel.add(this.m_CrossButton); this.m_ButtonPanel.add(this.m_CrossButton);
this.m_MainPanel.add(this.m_ButtonPanel, BorderLayout.NORTH); this.m_MainPanel.add(this.m_ButtonPanel, BorderLayout.NORTH);
// build the Options Panel // 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); this.m_MainPanel.add(this.m_OptionsPanel, BorderLayout.CENTER);
// The plot frame // The plot frame
double[] tmpD = new double[2]; double[] tmpD = new double[2];

View File

@ -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 + ")";
}
}

View File

@ -1,6 +1,7 @@
package eva2.server.go.operators.paramcontrol; package eva2.server.go.operators.paramcontrol;
import eva2.gui.BeanInspector; import eva2.gui.BeanInspector;
import eva2.server.go.populations.Population;
/** /**
* Convenience class. Besides the init() method, two more remain to be implemented: * 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 * 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. * 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 * @author mkron
* *
*/ */
@ -15,7 +19,15 @@ public abstract class AbstractParameterControl implements InterfaceParameterCont
public Object[] initialValues = null; public Object[] initialValues = null;
protected static boolean TRACE=false; 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(); String[] params = getControlledParameters();
if (params != null) { if (params != null) {
initialValues=new Object[params.length]; 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(); String[] params = getControlledParameters();
if (params != null) { if (params != null) {
for (int i=0; i<params.length; i++) BeanInspector.setMem(obj, params[i], initialValues[i]); for (int i=0; i<params.length; i++) BeanInspector.setMem(obj, params[i], initialValues[i]);
} }
} }
public void updateParameters(Object obj, int iteration, int maxIteration) { public void updateParameters(Object obj, Population pop, int iteration, int maxIteration) {
String[] params = getControlledParameters(); String[] params = getControlledParameters();
Object[] vals = getValues(obj, iteration, maxIteration); Object[] vals = getValues(obj, pop, iteration, maxIteration);
for (int i=0; i<params.length; i++) { for (int i=0; i<params.length; i++) {
if (!BeanInspector.setMem(obj, params[i], vals[i])) { if (!BeanInspector.setMem(obj, params[i], vals[i])) {
System.err.println("Error: failed to set parameter from parameter control " + this.getClass().getName());; System.err.println("Error: failed to set parameter from parameter control " + this.getClass().getName());;
@ -44,7 +56,7 @@ public abstract class AbstractParameterControl implements InterfaceParameterCont
} }
public void updateParameters(Object obj) { public void updateParameters(Object obj) {
updateParameters(obj, -1, -1); updateParameters(obj, null, -1, -1);
} }
/** /**
@ -63,5 +75,5 @@ public abstract class AbstractParameterControl implements InterfaceParameterCont
* @param maxIteration maximum iteration count (or -1 if unknown) * @param maxIteration maximum iteration count (or -1 if unknown)
* @return * @return
*/ */
public abstract Object[] getValues(Object obj, int iteration, int maxIteration); public abstract Object[] getValues(Object obj, Population pop, int iteration, int maxIteration);
} }

View File

@ -2,7 +2,7 @@ package eva2.server.go.operators.paramcontrol;
import java.io.Serializable; import java.io.Serializable;
import eva2.server.go.InterfaceTerminator; import eva2.server.go.populations.Population;
/** /**
* Dummy implementation. This class is ignored by the Processor. Parameters will not be changed. * Dummy implementation. This class is ignored by the Processor. Parameters will not be changed.
@ -11,13 +11,23 @@ import eva2.server.go.InterfaceTerminator;
* *
*/ */
public class ConstantParameters extends AbstractParameterControl implements Serializable { public class ConstantParameters extends AbstractParameterControl implements Serializable {
public ConstantParameters() {}
public ConstantParameters(ConstantParameters o) {
super(o);
}
@Override
public Object clone() {
return new ConstantParameters(this);
}
public String[] getControlledParameters() { public String[] getControlledParameters() {
return null; return null;
} }
@Override @Override
public Object[] getValues(Object obj, int iteration, int maxIteration) { public Object[] getValues(Object obj, Population pop, int iteration, int maxIteration) {
return null; return null;
} }

View File

@ -0,0 +1,74 @@
package eva2.server.go.operators.paramcontrol;
import java.io.Serializable;
import eva2.server.go.populations.Population;
/**
* Adapt a generic parameter using exponential decay.
*
* @author mkron
*
*/
public class ExponentialDecayAdaption implements GenericParamAdaption, Serializable {
double startValue=0.2, halvingTimePerCent=50;
String target = "undefinedParameter";
public ExponentialDecayAdaption() {
startValue=0.2;
halvingTimePerCent=50;
target="undefinedParameter";
}
public ExponentialDecayAdaption(
ExponentialDecayAdaption o) {
startValue = o.startValue;
halvingTimePerCent = o.halvingTimePerCent;
target = o.target;
}
public Object clone() {
return new ExponentialDecayAdaption(this);
}
public Object calcValue(Object obj, Population pop, int iteration, int maxIteration) {
return startValue*Math.pow(0.5, (iteration/(double)maxIteration)*100/halvingTimePerCent);
}
public String getControlledParam() {
return target;
}
public double getStartValue() {
return startValue;
}
public void setStartValue(double startValue) {
this.startValue = startValue;
}
public double getHalvingTimePerCent() {
return halvingTimePerCent;
}
public void setHalvingTimePerCent(double halvingTimePerCent) {
this.halvingTimePerCent = halvingTimePerCent;
}
public void setControlledParam(String target) {
this.target = target;
}
public String getName() {
return "Exp. adapt. "+target+" ("+startValue + "/" + halvingTimePerCent + ")";
}
public String globalInfo() {
return "Exponential decay with a percentual halving time.";
}
public void finish(Object obj, Population pop) {}
public void init(Object obj, Population pop, Object[] initialValues) {}
}

View File

@ -0,0 +1,16 @@
package eva2.server.go.operators.paramcontrol;
/**
* This should be implemented by adaptors which can be applied to generic target properties.
*
* @author mkron
*
*/
public interface GenericParamAdaption extends ParamAdaption {
/**
* Set the target property which is to be adapted.
* @param prm
*/
public void setControlledParam(String prm);
}

View File

@ -9,23 +9,36 @@ import eva2.server.go.populations.Population;
* adapted dynamically, such as linearly decreasing weights or control parameters. In case of PSO, * adapted dynamically, such as linearly decreasing weights or control parameters. In case of PSO,
* this may be the linearly decreasing inertia weight or the activation feedback control mechanism. * this may be the linearly decreasing inertia weight or the activation feedback control mechanism.
* *
* Notice how Processor handles parameter control. For now, a controlled object must implement
* the method getParamControl() which is to return either an InterfaceParameterControl or an array
* of Objects which should either be instances of InterfaceParameterControl or
* themselves should implement getParamControl(). This allows recursive
* parameter adaption hierarchies.
*
* @author mkron * @author mkron
* *
*/ */
public interface InterfaceParameterControl { public interface InterfaceParameterControl {
/**
* Make a deep copy of the object.
* @return
*/
public Object clone();
/** /**
* Initialize the parameter control instance before a run. * Initialize the parameter control instance before a run.
* *
* @param obj The controlled object. * @param obj The controlled object.
*/ */
public void init(Object obj); public void init(Object obj, Population initialPop);
/** /**
* After an optimization run, finalizing stuff may be done. * After an optimization run, finalizing stuff may be done.
* *
* @param obj The controlled object. * @param obj The controlled object.
*/ */
public void finish(Object obj); public void finish(Object obj, Population finalPop);
/** /**
* For a given runtime (maxIteration) and current iteration, update the parameters of the object. * For a given runtime (maxIteration) and current iteration, update the parameters of the object.
@ -34,7 +47,7 @@ public interface InterfaceParameterControl {
* @param iteration * @param iteration
* @param maxIteration * @param maxIteration
*/ */
public void updateParameters(Object obj, int iteration, int maxIteration); public void updateParameters(Object obj, Population pop, int iteration, int maxIteration);
/** /**
* If no runtime in terms of iterations can be specified, the parameter control may try to infer * If no runtime in terms of iterations can be specified, the parameter control may try to infer

View File

@ -1,76 +0,0 @@
package eva2.server.go.operators.paramcontrol;
import java.io.Serializable;
import eva2.tools.Mathematics;
/**
* Adapt PSO inertness linearly by time, from given start to end value.
* This only works if iterations are known.
*
* @author mkron
*
*/
public class LinearInertnessAdaption extends AbstractParameterControl implements Serializable {
String[] params = {"inertnessOrChi"};
private double startV=0.7;
private double endV=0.2;
public LinearInertnessAdaption() {
startV=0.7;
endV=0.2;
}
public LinearInertnessAdaption(double startValue, double endValue, int functionCalls) {
startV=startValue;
endV=endValue;
}
public String[] getControlledParameters() {
return params;
}
public Object[] getValues(Object obj, int iteration, int maxIteration) {
if (maxIteration < 0) { // there is no maxIteration known
System.err.println("Not changing inertness - missing iteration information!");
return null;
} else {
Object[] vals=new Object[1];
vals[0] = new Double(calcInertness(iteration, maxIteration));
return vals;
}
}
private double calcInertness(int iteration, int max) {
return Mathematics.linearInterpolation(iteration, 0, max, startV, endV);
// return startV+((endV-startV)*(iteration/(double)max));
}
public double getStartVal() {
return startV;
}
public void setStartVal(double startV) {
this.startV = startV;
}
public String startValTipText() {
return "Start value for the inertness";
}
public double getEndVal() {
return endV;
}
public void setEndVal(double endV) {
this.endV = endV;
}
public String endValTipText() {
return "End value for the inertness";
}
public String globalInfo() {
return "Linearly adapt the inertnessOrChi value of PSO";
}
}

View File

@ -0,0 +1,46 @@
package eva2.server.go.operators.paramcontrol;
import java.io.Serializable;
import eva2.tools.Mathematics;
/**
* Linearly adapt a specific target String parameter.
*
* @author mkron
*
*/
public class LinearParamAdaption extends AbstractLinearParamAdaption implements GenericParamAdaption, Serializable {
String target = "undefinedParameter";
public LinearParamAdaption() {
super(0.2,0.7);
target = "undefinedParameter";
}
public LinearParamAdaption(LinearParamAdaption o) {
super(o);
target=o.target;
}
public LinearParamAdaption(String target, double startValue, double endValue) {
super(startValue, endValue);
this.target = target;
}
public Object clone() {
return new LinearParamAdaption(this);
}
public String getControlledParam() {
return target;
}
public void setControlledParam(String target) {
this.target = target;
}
public String globalInfo() {
return "Simple linear parameter adaption.";
}
}

View File

@ -2,6 +2,7 @@ package eva2.server.go.operators.paramcontrol;
import java.io.Serializable; import java.io.Serializable;
import eva2.server.go.populations.Population;
import eva2.server.go.strategies.ParticleSwarmOptimization; import eva2.server.go.strategies.ParticleSwarmOptimization;
import eva2.tools.Mathematics; import eva2.tools.Mathematics;
@ -21,35 +22,49 @@ import eva2.tools.Mathematics;
* @author mkron * @author mkron
* *
*/ */
public class ActivityFeedbackControl extends AbstractParameterControl implements Serializable { public class PSOActivityFeedbackControl implements ParamAdaption, Serializable {
private double minInert=0.5; private double minInert=0.5;
private double maxInert=1; private double maxInert=1;
private double startAct=0.17; private double startAct=0.17;
private double endAct=0; private double endAct=0;
private double deltaInertness = 0.1; private double deltaInertness = 0.1;
private static boolean TRACE=false;
private static String[] params = new String[]{"inertnessOrChi"}; private static String target = "inertnessOrChi";
@Override public PSOActivityFeedbackControl() {};
public String[] getControlledParameters() {
return params; public PSOActivityFeedbackControl(
PSOActivityFeedbackControl o) {
minInert = o.minInert;
maxInert = o.maxInert;
startAct = o.startAct;
endAct = o.endAct;
deltaInertness = o.deltaInertness;
} }
@Override public Object clone() {
public Object[] getValues(Object obj, int iteration, int maxIteration) { return new PSOActivityFeedbackControl(this);
}
public Object calcValue(Object obj, Population pop, int iteration, int maxIteration) {
if (obj instanceof ParticleSwarmOptimization) { if (obj instanceof ParticleSwarmOptimization) {
ParticleSwarmOptimization pso = (ParticleSwarmOptimization)obj; ParticleSwarmOptimization pso = (ParticleSwarmOptimization)obj;
Object[] vals = new Double[1];
double currentAct = calculateActivity(pso); double currentAct = calculateActivity(pso);
double currentInertness = pso.getInertnessOrChi(); double currentInertness = pso.getInertnessOrChi();
vals[0] = calcNewInertness(currentInertness, currentAct, desiredActivity(iteration, maxIteration)); Double val = calcNewInertness(currentInertness, currentAct, desiredActivity(iteration, maxIteration));
return vals; return val;
} else { } else {
System.err.println("Cant control this object type!!"); System.err.println("Cant control this object type!!");
return null; return null;
} }
} }
public String getControlledParam() {
return target;
}
private double calcNewInertness(double currentInertness, double currentAct, private double calcNewInertness(double currentInertness, double currentAct,
double desiredActivity) { double desiredActivity) {
if (TRACE) System.out.println("Activity was " + currentAct + ", desired: " + desiredActivity); if (TRACE) System.out.println("Activity was " + currentAct + ", desired: " + desiredActivity);
@ -121,4 +136,8 @@ public class ActivityFeedbackControl extends AbstractParameterControl implements
public String globalInfo() { public String globalInfo() {
return "Controls the inertness factor based on the average velocity."; return "Controls the inertness factor based on the average velocity.";
} }
public void finish(Object obj, Population pop) {}
public void init(Object obj, Population pop, Object[] initialValues) {}
} }

View File

@ -0,0 +1,38 @@
package eva2.server.go.operators.paramcontrol;
import java.io.Serializable;
import eva2.gui.GenericObjectEditor;
import eva2.tools.Mathematics;
/**
* Adapt PSO inertness linearly by time, from given start to end value.
* This only works if iterations are known. The new variant allows exponential adaption,
* where the second parameter (endV) is interpreted as halfing time in percent of the
* full run.
*
* @author mkron
*
*/
public class PSOInertnessAdaption extends LinearParamAdaption implements Serializable {
public PSOInertnessAdaption() {
super("inertnessOrChi", 0.7, 0.2);
}
public void hideHideable() {
GenericObjectEditor.setHideProperty(this.getClass(), "controlledParam", true);
}
public String startVTipText() {
return "Start value for the inertness";
}
public String endVTipText() {
return "End value for the inertness";
}
public String globalInfo() {
return "Adapt the inertnessOrChi value of PSO.";
}
}

View File

@ -0,0 +1,29 @@
package eva2.server.go.operators.paramcontrol;
import eva2.server.go.populations.Population;
/**
* Adapt exactly one parameter with a generic method.
* @author mkron
*
*/
public interface ParamAdaption {
public Object clone();
public String getControlledParam();
/**
* Perform the adaption.
*
* @param iteration
* @param maxIteration
* @return
*/
public Object calcValue(Object obj, Population pop, int iteration, int maxIteration);
public void init(Object obj, Population pop, Object[] initialValues);
public void finish(Object obj, Population pop);
}

View File

@ -0,0 +1,147 @@
package eva2.server.go.operators.paramcontrol;
import java.io.Serializable;
import java.util.Vector;
import eva2.gui.BeanInspector;
import eva2.server.go.populations.Population;
import eva2.server.modules.Processor;
/**
* The ParameterControlManager handles an array of ParamAdaption instances which dynamically adapt
* single properties of an object. To make single parameter adaption available for an object
* (e.g. Problem or Optimizer instance) add a member of type ParameterControlManager. The
* corresponding getter and setter may either return the ParameterControlManager itself
* or the array of singleAdapters directly. In the latter case, the GUI is simpler (because theres
* one fewer window layer) but there must be an additional method getParamControl implemented
* which returns the ParameterControlManager to make it available to the Processor.
*
* @see ParamAdaption
* @see Processor
* @see AbstractParameterControl
*
* @author mkron
*
*/
public class ParameterControlManager implements InterfaceParameterControl, Serializable {
public Object[] initialValues = null;
private ParamAdaption[] singleAdapters = new ParamAdaption[]{};
protected static boolean TRACE=false;
public ParameterControlManager() { }
public ParameterControlManager(ParamAdaption adaptor) {
singleAdapters = new ParamAdaption[]{adaptor};
}
public ParameterControlManager(ParamAdaption[] adaptors) {
singleAdapters = adaptors;
}
public ParameterControlManager(ParameterControlManager o) {
if (o.initialValues!=null) initialValues = o.initialValues.clone();
else initialValues=null;
if (o.singleAdapters != null) {
singleAdapters = new ParamAdaption[o.singleAdapters.length];
for (int i=0; i<singleAdapters.length; i++) singleAdapters[i]=(ParamAdaption)o.singleAdapters[i].clone();
}
}
public Object clone() {
return new ParameterControlManager(this);
}
public void init(Object obj, Population initialPop) {
String[] params = getControlledParameters();
if (params != null) {
initialValues=new Object[params.length];
for (int i=0; i<params.length; i++) initialValues[i]=BeanInspector.getMem(obj, params[i]);
}
for (ParamAdaption prm : singleAdapters) {
prm.init(obj, initialPop, initialValues);
}
}
public void finish(Object obj, Population finalPop) {
String[] params = getControlledParameters();
for (ParamAdaption prm : singleAdapters) {
prm.finish(obj, finalPop);
}
if (params != null) {
for (int i=0; i<params.length; i++) BeanInspector.setMem(obj, params[i], initialValues[i]);
}
}
public void updateParameters(Object obj, Population pop, int iteration, int maxIteration) {
String[] params = getControlledParameters();
Object[] vals = getValues(obj, pop, iteration, maxIteration);
for (int i=0; i<params.length; i++) {
Object oldVal=BeanInspector.getMem(obj, params[i]);
if (oldVal==null) System.err.println("Error, unable to compare old and new value (ParameterControlManager");
if (!BeanInspector.setMem(obj, params[i], vals[i])) {
System.err.println("Error: failed to set parameter from parameter control " + this.getClass().getName());;
System.err.println(" Tried to set name/val: " + params[i] + " / " + BeanInspector.toString(vals[i]));
} else {
if (TRACE) System.out.println("Successfully set " + params[i] + " / " + BeanInspector.toString(vals[i]) + " at " + iteration);
// if (!oldVal.equals(vals[i])) {
// if (obj instanceof InterfaceParamControllable) ((InterfaceParamControllable)obj).notifyParamChanged(params[i], oldVal, vals[i]);
// }
}
}
}
public void updateParameters(Object obj) {
updateParameters(obj, null, -1, -1);
}
/**
* Return a String array of canonical names of the parameters to be adapted.
*
* @return a String array of canonical names of the parameters to be adapted
*/
public String[] getControlledParameters() {
if (singleAdapters != null) {
Vector<String> names = new Vector<String>(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";
}
}

View File

@ -8,7 +8,7 @@ import eva2.server.go.individuals.AbstractEAIndividual;
import eva2.server.go.operators.archiving.ArchivingAllDominating; import eva2.server.go.operators.archiving.ArchivingAllDominating;
import eva2.server.go.populations.Population; import eva2.server.go.populations.Population;
import eva2.server.go.problems.AbstractMultiObjectiveOptimizationProblem; 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 /** The D1* Pareto front metric requires a refrence Pareto front
* and calculate the distance between the true Pareto front and * 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() { 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()); if (lines == null) System.out.println("Failed to read "+this.m_InputFilePath.getCompleteFilePath());
lines[0].trim(); lines[0].trim();
this.m_Titles = lines[0].split("\t"); this.m_Titles = lines[0].split("\t");

View File

@ -8,7 +8,7 @@ import eva2.server.go.individuals.AbstractEAIndividual;
import eva2.server.go.operators.archiving.ArchivingAllDominating; import eva2.server.go.operators.archiving.ArchivingAllDominating;
import eva2.server.go.populations.Population; import eva2.server.go.populations.Population;
import eva2.server.go.problems.AbstractMultiObjectiveOptimizationProblem; 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 /** The D1 Pareto front metric requires a refrence Pareto front
* and calculate the distance between the current solution and * 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() { 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()); if (lines == null) System.out.println("Failed to read "+this.m_InputFilePath.getCompleteFilePath());
lines[0].trim(); lines[0].trim();
this.m_Titles = lines[0].split("\t"); this.m_Titles = lines[0].split("\t");

View File

@ -11,7 +11,7 @@ import eva2.server.go.individuals.AbstractEAIndividual;
import eva2.server.go.operators.archiving.ArchivingAllDominating; import eva2.server.go.operators.archiving.ArchivingAllDominating;
import eva2.server.go.populations.Population; import eva2.server.go.populations.Population;
import eva2.server.go.problems.AbstractMultiObjectiveOptimizationProblem; 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 /** 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() { 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()); if (lines == null) System.out.println("Failed to read "+this.m_InputFilePath.getCompleteFilePath());
lines[0].trim(); lines[0].trim();
this.m_Titles = lines[0].split("\t"); this.m_Titles = lines[0].split("\t");

View File

@ -8,7 +8,7 @@ import eva2.server.go.individuals.AbstractEAIndividual;
import eva2.server.go.operators.archiving.ArchivingAllDominating; import eva2.server.go.operators.archiving.ArchivingAllDominating;
import eva2.server.go.populations.Population; import eva2.server.go.populations.Population;
import eva2.server.go.problems.AbstractMultiObjectiveOptimizationProblem; 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 /** Maximum Pareto Front Error gives the maximum distance of all minimum distances of each
* element in the current solution to the true Pareto front. * 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() { 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()); if (lines == null) System.out.println("Failed to read "+this.m_InputFilePath.getCompleteFilePath());
lines[0].trim(); lines[0].trim();
this.m_Titles = lines[0].split("\t"); this.m_Titles = lines[0].split("\t");

View File

@ -9,7 +9,7 @@ import eva2.server.go.individuals.ESIndividualDoubleData;
import eva2.server.go.operators.archiving.ArchivingAllDominating; import eva2.server.go.operators.archiving.ArchivingAllDominating;
import eva2.server.go.populations.Population; import eva2.server.go.populations.Population;
import eva2.server.go.problems.AbstractMultiObjectiveOptimizationProblem; 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. /** 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. * 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() { 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()); if (lines == null) System.out.println("Failed to read "+this.m_InputFilePath.getCompleteFilePath());
lines[0].trim(); lines[0].trim();
this.m_Titles = lines[0].split("\t"); this.m_Titles = lines[0].split("\t");

View File

@ -215,12 +215,17 @@ public class CHCAdaptiveSearchAlgorithm implements InterfaceOptimizer, java.io.S
this.firePropertyChangedEvent(Population.nextGenerationPerformed); this.firePropertyChangedEvent(Population.nextGenerationPerformed);
} }
/** This method allows you to add the LectureGUI as listener to the Optimizer
* @param ea
*/
public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) {
this.m_Listener = 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 /** Something has changed
*/ */
protected void firePropertyChangedEvent (String name) { protected void firePropertyChangedEvent (String name) {

View File

@ -639,21 +639,19 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis
spec.add(survivor); 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) { public void registerPopulationStateChanged(Object source, String name) {
//Population population = ((InterfaceOptimizer)source).getPopulation(); //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) { public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) {
this.m_Listener = 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) { protected void firePropertyChangedEvent (String name) {
if (this.m_Listener != null) this.m_Listener.registerPopulationStateChanged(this, name); if (this.m_Listener != null) this.m_Listener.registerPopulationStateChanged(this, name);
} }

View File

@ -105,7 +105,13 @@ public class ClusteringHillClimbing implements InterfacePopulationChangedEventLi
public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) {
this.m_Listener = 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() { public void init() {
loopCnt = 0; loopCnt = 0;
mutator = new MutateESFixedStepSize(initialStepSize); mutator = new MutateESFixedStepSize(initialStepSize);

View File

@ -20,12 +20,13 @@ import eva2.server.go.problems.InterfaceOptimizationProblem;
import eva2.tools.EVAERROR; import eva2.tools.EVAERROR;
import eva2.tools.Mathematics; 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. * Price and the Trigonometric DE published recently.
* Please note that DE will only work on real-valued genotypes and will ignore * Please note that DE will only work on real-valued genotypes and will ignore
* all mutation and crossover operators selected. * all mutation and crossover operators selected.
* User: streiche * Added aging mechanism to provide for dynamically changing problems. If an individual
* Date: 25.10.2004 * 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 { 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 AbstractOptimizationProblem m_Problem = new F1Problem();
private DETypeEnum m_DEType; private DETypeEnum m_DEType;
private double m_F = 0.8; 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_Lambda = 0.6;
private double m_Mt = 0.05; private double m_Mt = 0.05;
private int maximumAge = -1; private int maximumAge = -1;
// to log the parents of a newly created indy. // to log the parents of a newly created indy.
private boolean doLogParents = false; // TODO deactivate for better performance private boolean doLogParents = false; // deactivate for better performance
private Vector<AbstractEAIndividual> parents = null; private transient Vector<AbstractEAIndividual> parents = null;
private boolean randomizeFKLambda = false;
private String m_Identifier = ""; private String m_Identifier = "";
transient private InterfacePopulationChangedEventListener m_Listener; transient private InterfacePopulationChangedEventListener m_Listener;
private boolean forceRange = true; 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. * A constructor.
@ -55,6 +59,15 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial
m_DEType = DETypeEnum.DE2_CurrentToBest; 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. * The copy constructor.
* *
@ -69,6 +82,12 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial
this.m_k = a.m_k; this.m_k = a.m_k;
this.m_Lambda = a.m_Lambda; this.m_Lambda = a.m_Lambda;
this.m_Mt = a.m_Mt; 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() { public Object clone() {
@ -216,16 +235,17 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial
* @param pop The current population * @param pop The current population
* @return AbstractEAIndividual * @return AbstractEAIndividual
*/ */
public AbstractEAIndividual generateNewIndividual(Population pop) { public AbstractEAIndividual generateNewIndividual(Population pop, int parentIndex) {
int firstParentIndex; // int firstParentIndex;
AbstractEAIndividual indy; AbstractEAIndividual indy;
InterfaceDataTypeDouble esIndy; InterfaceDataTypeDouble esIndy;
if (doLogParents) parents = new Vector<AbstractEAIndividual>(); if (doLogParents) parents = new Vector<AbstractEAIndividual>();
else parents = null; else parents = null;
try { try {
// select one random indy as starting individual. its a parent in any case. // select one random indy as starting individual. its a parent in any case.
firstParentIndex = RNG.randomInt(0, pop.size()-1); if (parentIndex<0) parentIndex = RNG.randomInt(0, pop.size()-1);
indy = (AbstractEAIndividual)(pop.getEAIndividual(firstParentIndex)).getClone(); indy = (AbstractEAIndividual)(pop.getEAIndividual(parentIndex)).getClone();
esIndy = (InterfaceDataTypeDouble)indy; esIndy = (InterfaceDataTypeDouble)indy;
} catch (java.lang.ClassCastException e) { } catch (java.lang.ClassCastException e) {
EVAERROR.errorMsgOnce("Differential Evolution currently requires InterfaceESIndividual as basic data type!"); 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: { case DE1_Rand_1: {
// this is DE1 or DE/rand/1 // this is DE1 or DE/rand/1
double[] delta = this.fetchDeltaRandom(pop); 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++) { 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; break;
} }
@ -249,9 +269,9 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial
// this is DE2 or DE/current-to-best/1 // this is DE2 or DE/current-to-best/1
double[] rndDelta = this.fetchDeltaRandom(pop); double[] rndDelta = this.fetchDeltaRandom(pop);
double[] bestDelta = this.fetchDeltaBest(pop, esIndy); 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++) { 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; break;
} }
@ -263,13 +283,13 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial
double[] delta1 = this.fetchDeltaRandom(pop); double[] delta1 = this.fetchDeltaRandom(pop);
double[] delta2 = this.fetchDeltaRandom(pop); double[] delta2 = this.fetchDeltaRandom(pop);
for (int i = 0; i < oX.length; i++) { 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; break;
} }
case TrigonometricDE : { case TrigonometricDE : {
// this is trigonometric mutation // 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)) { if (RNG.flipCoin(this.m_Mt)) {
double[] xk, xl; double[] xk, xl;
double p, pj, pk, pl; double p, pj, pk, pl;
@ -297,16 +317,16 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial
} else { } else {
// this is DE1 // this is DE1
double[] delta = this.fetchDeltaRandom(pop); 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++) { 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; break;
} }
} }
for (int i =0; i < oX.length; i++) { for (int i =0; i < oX.length; i++) {
if (RNG.flipCoin(this.m_k)) { if (RNG.flipCoin(this.getCurrentK())) {
// it remains the same // it remains the same
nX[i] = oX[i]; nX[i] = oX[i];
} else { } 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? if (forceRange) Mathematics.projectToRange(nX, esIndy.getDoubleRange()); // why did this never happen before?
esIndy.SetDoubleGenotype(nX); esIndy.SetDoubleGenotype(nX);
indy.SetAge(0); indy.SetAge(0);
indy.resetConstraintViolation();
double[] fit = new double[1]; double[] fit = new double[1];
fit[0] = 0; fit[0] = 0;
indy.SetFitness(fit); indy.SetFitness(fit);
@ -325,7 +346,22 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial
return indy; 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(); return (AbstractEAIndividual)pop.getBestIndividual();
} }
@ -349,20 +385,20 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial
} }
public void optimize() { public void optimize() {
AbstractEAIndividual indy = null, org; AbstractEAIndividual indy = null, orig;
int index; int index;
int nextDoomed = getNextDoomed(m_Population, 0); int nextDoomed = getNextDoomed(m_Population, 0);
// required for dynamic problems especially // required for dynamic problems especially
m_Problem.evaluatePopulationStart(m_Population); 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++) { 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_Problem.evaluate(indy);
this.m_Population.incrFunctionCalls(); this.m_Population.incrFunctionCalls();
if (nextDoomed >= 0) { // this one is lucky, may replace an 'old' one 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(); ReplacementCrowding repl = new ReplacementCrowding();
repl.insertIndividual(indy, m_Population, null); repl.insertIndividual(indy, m_Population, null);
} else { } else {
index = RNG.randomInt(0, this.m_Population.size()-1); // index = RNG.randomInt(0, this.m_Population.size()-1);
org = (AbstractEAIndividual)this.m_Population.get(index); if (!compareToParent) index = RNG.randomInt(0, this.m_Population.size()-1);
if (indy.isDominatingDebConstraints(org)) this.m_Population.replaceIndividualAt(index, indy); 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) { public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) {
this.m_Listener = 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 /** Something has changed
* @param name * @param name
*/ */
@ -552,7 +596,7 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial
return this.m_k; return this.m_k;
} }
public String kTipText() { 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 /** 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() { public String checkRangeTipText() {
return "Set whether to enforce the problem range."; 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.";
}
} }

View File

@ -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) { protected double[] updateVelocity(int index, double[] lastVelocity, double[] bestPosition, double[] curPosition, double[] localBestPos, double[][] range) {
if (envHasChanged) { if (envHasChanged) {
double chi; double chi;
@ -473,7 +474,13 @@ public class DynamicParticleSwarmOptimization extends ParticleSwarmOptimization
return false; 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(); super.init();
setEmaPeriods(15); setEmaPeriods(15);
if (doSpeedAdaptation) setSpeedLimit(2*getInitialVelocity()); if (doSpeedAdaptation) setSpeedLimit(2*getInitialVelocity());

View File

@ -310,6 +310,13 @@ public class EvolutionStrategies implements InterfaceOptimizer, java.io.Serializ
public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) {
this.m_Listener = 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 /** Something has changed
*/ */
protected void firePropertyChangedEvent(String name) { protected void firePropertyChangedEvent(String name) {

View File

@ -128,6 +128,13 @@ public class EvolutionaryProgramming implements InterfaceOptimizer, java.io.Seri
public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) {
this.m_Listener = 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 /** Something has changed
*/ */
protected void firePropertyChangedEvent (String name) { protected void firePropertyChangedEvent (String name) {

View File

@ -171,6 +171,13 @@ public class FloodAlgorithm implements InterfaceOptimizer, java.io.Serializable
public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) {
this.m_Listener = 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 /** Something has changed
*/ */
protected void firePropertyChangedEvent (String name) { protected void firePropertyChangedEvent (String name) {

View File

@ -171,6 +171,13 @@ public class GeneticAlgorithm implements InterfaceOptimizer, java.io.Serializabl
public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) {
this.m_Listener = 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 /** Something has changed
*/ */
protected void firePropertyChangedEvent (String name) { protected void firePropertyChangedEvent (String name) {
@ -320,21 +327,4 @@ public class GeneticAlgorithm implements InterfaceOptimizer, java.io.Serializabl
public String partnerSelectionTipText() { public String partnerSelectionTipText() {
return "Choose a selection method for selecting recombination partners for given parents."; 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.";
// }
} }

View File

@ -302,7 +302,13 @@ public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Ser
public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) {
this.m_Listener = 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) { public static void main(String[] args) {
GradientDescentAlgorithm program = new GradientDescentAlgorithm(); GradientDescentAlgorithm program = new GradientDescentAlgorithm();
InterfaceOptimizationProblem problem = new F1Problem(); InterfaceOptimizationProblem problem = new F1Problem();

View File

@ -178,6 +178,13 @@ public class HillClimbing implements InterfaceOptimizer, java.io.Serializable {
public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) {
this.m_Listener = 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 /** Something has changed
*/ */
protected void firePropertyChangedEvent (String name) { protected void firePropertyChangedEvent (String name) {

View File

@ -29,11 +29,19 @@ public interface InterfaceOptimizer {
*/ */
public String getName(); 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 * @param ea
*/ */
public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener 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 /** This method will init the optimizer
*/ */
public void init(); public void init();

View File

@ -265,6 +265,13 @@ public class IslandModelEA implements InterfacePopulationChangedEventListener, I
public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) {
this.m_Listener = 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 /** Something has changed
*/ */
protected void firePropertyChangedEvent (String name, Population population) { protected void firePropertyChangedEvent (String name, Population population) {

View File

@ -204,7 +204,13 @@ public class MemeticAlgorithm implements InterfaceOptimizer,
InterfacePopulationChangedEventListener ea) { InterfacePopulationChangedEventListener ea) {
this.m_Listener = 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 * Something has changed
*/ */

View File

@ -150,6 +150,13 @@ public class MonteCarloSearch implements InterfaceOptimizer, java.io.Serializabl
public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) {
this.m_Listener = 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 /** Something has changed
*/ */
protected void firePropertyChangedEvent (String name) { protected void firePropertyChangedEvent (String name) {

View File

@ -151,14 +151,18 @@ public class MultiObjectiveEA implements InterfaceOptimizer, java.io.Serializabl
return result; return result;
} }
/** This method allows you to add the LectureGUI as listener to the Optimizer
* @param ea
*/
public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) {
this.m_Listener = 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) { protected void firePropertyChangedEvent (String name) {
if (this.m_Listener != null) this.m_Listener.registerPopulationStateChanged(this, name); if (this.m_Listener != null) this.m_Listener.registerPopulationStateChanged(this, name);
} }

View File

@ -41,6 +41,11 @@ public class NelderMeadSimplex implements InterfaceOptimizer, Serializable, Inte
setPopulation(new Population(populationSize)); setPopulation(new Population(populationSize));
} }
public NelderMeadSimplex(int popSize) {
populationSize=popSize;
setPopulation(new Population(populationSize));
}
public NelderMeadSimplex(NelderMeadSimplex a) { public NelderMeadSimplex(NelderMeadSimplex a) {
m_Problem = (AbstractOptimizationProblem)a.m_Problem.clone(); m_Problem = (AbstractOptimizationProblem)a.m_Problem.clone();
setPopulation((Population)a.m_Population.clone()); setPopulation((Population)a.m_Population.clone());
@ -82,6 +87,12 @@ public class NelderMeadSimplex implements InterfaceOptimizer, Serializable, Inte
if (!m_Listener.contains(ea)) m_Listener.add(ea); 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() {} public void freeWilly() {}
protected double[] calcChallengeVect(double[] centroid, double[] refX) { protected double[] calcChallengeVect(double[] centroid, double[] refX) {
@ -139,10 +150,11 @@ public class NelderMeadSimplex implements InterfaceOptimizer, Serializable, Inte
Mathematics.reflectBounds(r, range); Mathematics.reflectBounds(r, range);
} }
} }
AbstractEAIndividual reflectedInd = (AbstractEAIndividual)((AbstractEAIndividual)bestpop.getIndividual(1)).clone(); // AbstractEAIndividual reflectedInd = (AbstractEAIndividual)((AbstractEAIndividual)bestpop.getIndividual(1)).clone();
((InterfaceDataTypeDouble)reflectedInd).SetDoubleGenotype(r); // ((InterfaceDataTypeDouble)reflectedInd).SetDoubleGenotype(r);
//
m_Problem.evaluate(reflectedInd); // m_Problem.evaluate(reflectedInd);
AbstractEAIndividual reflectedInd = createEvalIndy(bestpop, r);
this.m_Population.incrFunctionCalls(); this.m_Population.incrFunctionCalls();
if (firstIsBetter(best, reflectedInd) && firstIsBetter(reflectedInd, bestpop.getWorstEAIndividual(fitIndex))) { 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<dim; i++) e[i] = 3*centroid[i] - 2*x_worst[i]; for (int i=0; i<dim; i++) e[i] = 3*centroid[i] - 2*x_worst[i];
if (checkConstraints && !Mathematics.isInRange(e, range)) Mathematics.projectToRange(e, range); if (checkConstraints && !Mathematics.isInRange(e, range)) Mathematics.projectToRange(e, range);
AbstractEAIndividual e_ind = (AbstractEAIndividual)((AbstractEAIndividual)bestpop.getIndividual(1)).clone(); AbstractEAIndividual e_ind = createEvalIndy(bestpop, e);
((InterfaceDataTypeDouble)e_ind).SetDoubleGenotype(e);
m_Problem.evaluate(e_ind);
this.m_Population.incrFunctionCalls(); this.m_Population.incrFunctionCalls();
if (firstIsBetter(e_ind, reflectedInd)) { //expandiertes ist besser als reflektiertes if (firstIsBetter(e_ind, reflectedInd)) { //expandiertes ist besser als reflektiertes
return e_ind; return e_ind;
} else { } else {
@ -167,9 +178,10 @@ public class NelderMeadSimplex implements InterfaceOptimizer, Serializable, Inte
for (int i=0; i<dim; i++) c[i] = 0.5*centroid[i] + 0.5*x_worst[i]; for (int i=0; i<dim; i++) c[i] = 0.5*centroid[i] + 0.5*x_worst[i];
if (checkConstraints && !Mathematics.isInRange(c, range)) Mathematics.projectToRange(c, range); if (checkConstraints && !Mathematics.isInRange(c, range)) Mathematics.projectToRange(c, range);
AbstractEAIndividual c_ind = (AbstractEAIndividual)((AbstractEAIndividual)bestpop.getIndividual(1)).clone(); // AbstractEAIndividual c_ind = (AbstractEAIndividual)((AbstractEAIndividual)bestpop.getIndividual(1)).clone();
((InterfaceDataTypeDouble)c_ind).SetDoubleGenotype(c); // ((InterfaceDataTypeDouble)c_ind).SetDoubleGenotype(c);
m_Problem.evaluate(c_ind); // m_Problem.evaluate(c_ind);
AbstractEAIndividual c_ind = createEvalIndy(bestpop, c);
this.m_Population.incrFunctionCalls(); this.m_Population.incrFunctionCalls();
if(firstIsBetterEqual(c_ind, worst)) { if(firstIsBetterEqual(c_ind, worst)) {
return c_ind; return c_ind;
@ -178,6 +190,17 @@ public class NelderMeadSimplex implements InterfaceOptimizer, Serializable, Inte
return null; return null;
} }
private AbstractEAIndividual createEvalIndy(Population pop, double[] newGenotype) {
AbstractEAIndividual e_ind = (AbstractEAIndividual)((AbstractEAIndividual)pop.getIndividual(1)).clone();
((InterfaceDataTypeDouble)e_ind).SetDoubleGenotype(newGenotype);
e_ind.resetConstraintViolation();
m_Problem.evaluate(e_ind);
if (e_ind.getFitness(0)<6000) {
m_Problem.evaluate(e_ind);
}
return e_ind;
}
public String getIdentifier() { public String getIdentifier() {
return m_Identifier; return m_Identifier;
} }
@ -255,6 +278,7 @@ public class NelderMeadSimplex implements InterfaceOptimizer, Serializable, Inte
double [] c= ((InterfaceDataTypeDouble) m_Population.getEAIndividual(j)).getDoubleData(); double [] c= ((InterfaceDataTypeDouble) m_Population.getEAIndividual(j)).getDoubleData();
for (int i=0; i<c.length; i++) c[i] = 0.5*c[i] + 0.5*u_1[i]; for (int i=0; i<c.length; i++) c[i] = 0.5*c[i] + 0.5*u_1[i];
((InterfaceDataTypeDouble) m_Population.getEAIndividual(j)).SetDoubleGenotype(c); ((InterfaceDataTypeDouble) m_Population.getEAIndividual(j)).SetDoubleGenotype(c);
// m_Population.getEAIndividual(j).resetConstraintViolation(); // not a good idea because during evaluation, a stats update may be performed which mustnt see indies which are evaluated, but possible constraints have been reset.
} }
m_Problem.evaluate(m_Population); m_Problem.evaluate(m_Population);
} }
@ -402,6 +426,7 @@ public class NelderMeadSimplex implements InterfaceOptimizer, Serializable, Inte
dat[i]=Math.max(dat[i]-curPerturb, range[i][0]); dat[i]=Math.max(dat[i]-curPerturb, range[i][0]);
} else dat[i] = Math.min(dat[i]+curPerturb, range[i][1]); } else dat[i] = Math.min(dat[i]+curPerturb, range[i][1]);
((InterfaceDataTypeDouble)indy).SetDoubleGenotype(dat); ((InterfaceDataTypeDouble)indy).SetDoubleGenotype(dat);
indy.resetConstraintViolation();
initialPop.add((AbstractEAIndividual)indy.clone()); initialPop.add((AbstractEAIndividual)indy.clone());
} }
initialPop.setPopulationSize(initialPop.size()); initialPop.setPopulationSize(initialPop.size());

View File

@ -240,20 +240,16 @@ public class ParticleFilterOptimization implements InterfaceOptimizer, java.io.S
} }
// protected void collectStatistics(Population population) {
// // TODO Auto-generated method stub
// int tMax = 5;
//
// }
/** This method allows you to add the LectureGUI as listener to the Optimizer
* @param ea
*/
public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) {
this.m_Listener = 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) { protected void firePropertyChangedEvent (String name) {
if (this.m_Listener != null) this.m_Listener.registerPopulationStateChanged(this, name); if (this.m_Listener != null) this.m_Listener.registerPopulationStateChanged(this, name);
} }

View File

@ -16,8 +16,8 @@ import eva2.server.go.individuals.AbstractEAIndividual;
import eva2.server.go.individuals.AbstractEAIndividualComparator; import eva2.server.go.individuals.AbstractEAIndividualComparator;
import eva2.server.go.individuals.InterfaceDataTypeDouble; import eva2.server.go.individuals.InterfaceDataTypeDouble;
import eva2.server.go.operators.distancemetric.PhenotypeMetric; import eva2.server.go.operators.distancemetric.PhenotypeMetric;
import eva2.server.go.operators.paramcontrol.ConstantParameters; import eva2.server.go.operators.paramcontrol.ParamAdaption;
import eva2.server.go.operators.paramcontrol.InterfaceParameterControl; import eva2.server.go.operators.paramcontrol.ParameterControlManager;
import eva2.server.go.populations.InterfaceSolutionSet; import eva2.server.go.populations.InterfaceSolutionSet;
import eva2.server.go.populations.Population; import eva2.server.go.populations.Population;
import eva2.server.go.populations.SolutionSet; import eva2.server.go.populations.SolutionSet;
@ -74,7 +74,7 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se
protected boolean wrapTopology = true; protected boolean wrapTopology = true;
protected int treeBranchDeg = 3; protected int treeBranchDeg = 3;
protected int treeLevels, treeOrphans, treeLastFullLevelNodeCnt; protected int treeLevels, treeOrphans, treeLastFullLevelNodeCnt;
protected InterfaceParameterControl paramControl = new ConstantParameters(); protected ParameterControlManager paramControl = new ParameterControlManager();
/** /**
* InertnessOrChi may contain the inertness or chi parameter depending on algoType * InertnessOrChi may contain the inertness or chi parameter depending on algoType
@ -140,6 +140,24 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se
//this.setCheckSpeedLimit(a.isCheckSpeedLimit()); //this.setCheckSpeedLimit(a.isCheckSpeedLimit());
} }
/**
* Constructor for most common parameters with constriction based approach.
*
* @param p1 the value for phi1
* @param p2 the value for phi1
* @param topo type of the neighbourhood topology
* @param topoRange range of the neighbourhood topology
* @param popSize swarm size
*/
public ParticleSwarmOptimization(int popSize, double p1, double p2, PSOTopologyEnum topo, int topoRange) {
this();
algType.setSelectedTag(1); // set to constriction
m_Population = new Population(popSize);
setPhiValues(p1, p2);
m_TopologyRange=topoRange;
topology=topo;
}
public Object clone() { public Object clone() {
return (Object) new ParticleSwarmOptimization(this); return (Object) new ParticleSwarmOptimization(this);
} }
@ -596,9 +614,11 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se
* @param indy * @param indy
*/ */
protected void resetFitness(AbstractEAIndividual indy) { protected void resetFitness(AbstractEAIndividual indy) {
double[] fit = new double[1]; // double[] fit = new double[1];
fit[0] = 0; // fit[0] = 0;
indy.SetFitness(fit); // indy.SetFitness(fit);
indy.resetFitness(0);
indy.resetConstraintViolation();
} }
/** /**
@ -607,7 +627,7 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se
* @param indy the individual to update * @param indy the individual to update
*/ */
protected void updateIndProps(AbstractEAIndividual indy) { protected void updateIndProps(AbstractEAIndividual indy) {
indy.putData(partBestFitKey, indy.getFitness()); indy.putData(partBestFitKey, indy.getFitness().clone());
indy.putData(partBestPosKey, ((InterfaceDataTypeDouble)indy).getDoubleData()); indy.putData(partBestPosKey, ((InterfaceDataTypeDouble)indy).getDoubleData());
} }
@ -995,6 +1015,7 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se
/** /**
* Update the given individuals position with given speed and position, maybe perform checkBounds. * Update the given individuals position with given speed and position, maybe perform checkBounds.
* Remember to reset the fitness and constraint violation of the individual.
* *
* @param indy * @param indy
* @param curVelocity * @param curVelocity
@ -1169,7 +1190,7 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se
protected void logBestIndividual() { protected void logBestIndividual() {
if (this.m_Population.getBestEAIndividual().isDominatingDebConstraints(this.m_BestIndividual)) { if (this.m_Population.getBestEAIndividual().isDominatingDebConstraints(this.m_BestIndividual)) {
this.m_BestIndividual = (AbstractEAIndividual)this.m_Population.getBestEAIndividual().clone(); this.m_BestIndividual = (AbstractEAIndividual)this.m_Population.getBestEAIndividual().clone();
this.m_BestIndividual.putData(partBestFitKey, this.m_BestIndividual.getFitness()); this.m_BestIndividual.putData(partBestFitKey, this.m_BestIndividual.getFitness().clone());
this.m_BestIndividual.putData(partBestPosKey, ((InterfaceDataTypeDouble)this.m_BestIndividual).getDoubleData()); this.m_BestIndividual.putData(partBestPosKey, ((InterfaceDataTypeDouble)this.m_BestIndividual).getDoubleData());
// System.out.println("new best: "+m_BestIndividual.toString()); // System.out.println("new best: "+m_BestIndividual.toString());
} }
@ -1341,14 +1362,16 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se
} }
} }
/** This method allows you to add the LectureGUI as listener to the Optimizer
* @param ea
*/
public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) {
this.m_Listener = 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) { protected void firePropertyChangedEvent (String name) {
if (this.m_Listener != null) this.m_Listener.registerPopulationStateChanged(this, name); if (this.m_Listener != null) this.m_Listener.registerPopulationStateChanged(this, name);
} }
@ -1499,7 +1522,8 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se
* where tau = tau1 + tau2 * where tau = tau1 + tau2
* See Clerc&Kennedy: The Particle Swarm: Explosion, stability and convergence, 2002. * See Clerc&Kennedy: The Particle Swarm: Explosion, stability and convergence, 2002.
* *
* @param tau2 the * @param tau1
* @param tau2
*/ */
protected void setWithConstriction(double tau1, double tau2) { protected void setWithConstriction(double tau1, double tau2) {
double pSum = tau1+tau2; double pSum = tau1+tau2;
@ -1510,7 +1534,6 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se
} }
} }
/** /**
* This method will set the inertness/chi value * This method will set the inertness/chi value
* @param k * @param k
@ -1782,11 +1805,34 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se
this.emaPeriods = emaPeriods; this.emaPeriods = emaPeriods;
} }
public InterfaceParameterControl getParamControl() { public ParameterControlManager getParamControl() {
return paramControl; return paramControl;
} }
public void setParamControl(InterfaceParameterControl paramControl) { public ParamAdaption[] getParameterControl() {
this.paramControl = paramControl; return paramControl.getSingleAdapters();
}
public void setParameterControl(ParamAdaption[] paramControl) {
this.paramControl.setSingleAdapters(paramControl);
}
/**
* Retrieve the set of personal best positions contained in the given population.
* @param population
* @return
*/
protected Population getPersonalBestPos(Population population) {
Population bests = new Population(population.size());
AbstractEAIndividual indy = (AbstractEAIndividual)population.getEAIndividual(0).clone();
if (!indy.hasData(partBestFitKey)) return null;
for (int i=0; i<population.size(); i++) {
double[] personalBestPos = (double[]) population.getEAIndividual(i).getData(partBestPosKey);
double[] personalBestfit = (double[]) population.getEAIndividual(i).getData(partBestFitKey);
((InterfaceDataTypeDouble)indy).SetDoubleGenotype(personalBestPos);
indy.SetFitness(personalBestfit);
bests.add((AbstractEAIndividual)indy.clone());
}
return bests;
} }
} }

View File

@ -144,13 +144,16 @@ public class PopulationBasedIncrementalLearning implements InterfaceOptimizer, j
public InterfaceOptimizationProblem getProblem () { public InterfaceOptimizationProblem getProblem () {
return this.m_Problem; return this.m_Problem;
} }
/** This method allows you to add the LectureGUI as listener to the Optimizer
* @param ea
*/
public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) {
this.m_Listener = 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 /** Something has changed
*/ */
protected void firePropertyChangedEvent (String name) { protected void firePropertyChangedEvent (String name) {

View File

@ -171,14 +171,16 @@ public class SimulatedAnnealing implements InterfaceOptimizer, java.io.Serializa
System.out.println("("+program.m_MultiRuns+"/"+program.m_FitnessCalls+") Mean Fitness : " + TmpMeanFitness + " Mean Calls needed: " + TmpMeanCalls); System.out.println("("+program.m_MultiRuns+"/"+program.m_FitnessCalls+") Mean Fitness : " + TmpMeanFitness + " Mean Calls needed: " + TmpMeanCalls);
} }
/** This method allows you to add the LectureGUI as listener to the Optimizer
* @param ea
*/
public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) {
this.m_Listener = 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) { protected void firePropertyChangedEvent (String name) {
if (this.m_Listener != null) this.m_Listener.registerPopulationStateChanged(this, name); if (this.m_Listener != null) this.m_Listener.registerPopulationStateChanged(this, name);
} }

View File

@ -113,15 +113,16 @@ public class SteadyStateGA implements InterfaceOptimizer, java.io.Serializable {
this.m_Population.incrGeneration(); this.m_Population.incrGeneration();
this.firePropertyChangedEvent(Population.nextGenerationPerformed); this.firePropertyChangedEvent(Population.nextGenerationPerformed);
} }
/** This method allows you to add the LectureGUI as listener to the Optimizer
* @param ea
*/
public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) {
this.m_Listener = 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) { protected void firePropertyChangedEvent (String name) {
if (this.m_Listener != null) this.m_Listener.registerPopulationStateChanged(this, name); if (this.m_Listener != null) this.m_Listener.registerPopulationStateChanged(this, name);
} }

View File

@ -162,15 +162,16 @@ public class ThresholdAlgorithm implements InterfaceOptimizer, java.io.Serializa
TmpMeanFitness = TmpMeanFitness/program.m_MultiRuns; TmpMeanFitness = TmpMeanFitness/program.m_MultiRuns;
System.out.println("("+program.m_MultiRuns+"/"+program.m_FitnessCalls+") Mean Fitness : " + TmpMeanFitness + " Mean Calls needed: " + TmpMeanCalls); System.out.println("("+program.m_MultiRuns+"/"+program.m_FitnessCalls+") Mean Fitness : " + TmpMeanFitness + " Mean Calls needed: " + TmpMeanCalls);
} }
/** This method allows you to add the LectureGUI as listener to the Optimizer
* @param ea
*/
public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) {
this.m_Listener = 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) { protected void firePropertyChangedEvent (String name) {
if (this.m_Listener != null) this.m_Listener.registerPopulationStateChanged(this, name); if (this.m_Listener != null) this.m_Listener.registerPopulationStateChanged(this, name);
} }

View File

@ -698,7 +698,13 @@ public class Tribes implements InterfaceOptimizer, java.io.Serializable {
public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) {
this.m_Listener = ea; this.m_Listener = ea;
} }
public boolean removePopulationChangedEventListener(
InterfacePopulationChangedEventListener ea) {
if (m_Listener==ea) {
m_Listener=null;
return true;
} else return false;
}
protected void firePropertyChangedEvent(String name) { protected void firePropertyChangedEvent(String name) {
if (this.m_Listener != null) this.m_Listener.registerPopulationStateChanged(this, name); if (this.m_Listener != null) this.m_Listener.registerPopulationStateChanged(this, name);
} }

View File

@ -213,6 +213,13 @@ public class WingedMultiObjectiveEA implements InterfaceOptimizer, java.io.Seria
public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) {
this.m_Listener = 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 /** Something has changed
*/ */
protected void firePropertyChangedEvent (String name) { protected void firePropertyChangedEvent (String name) {

View File

@ -1,57 +0,0 @@
package eva2.server.go.tools;
import wsi.ra.tool.BasicResourceLoader;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
/**
* Created by IntelliJ IDEA.
* User: streiche
* Date: 09.06.2005
* Time: 13:01:18
* To change this template use File | Settings | File Templates.
*/
public class FileLoader {
/** This method will load a file and will try to do this using the
* BasicResourceLoader and the standart technique.
* @param file The full filename and path
* @return A string[] containing the lines in the file
*/
static public String[] loadStringsFromFile(String file) {
String[] result = null;
BasicResourceLoader loader = BasicResourceLoader.instance();
byte bytes[] = loader.getBytesFromResourceLocation(file);
if (bytes != null) {
String data = new String(bytes);
result = data.split("\n");
} else {
System.out.println("BasicResourceLoader failed to read "+file);
BufferedReader reader= null;
try {
reader = new BufferedReader(new FileReader(file));
} catch (java.io.FileNotFoundException e) {
System.out.println("Could not find " + file);
return result;
}
String currentLine;
try {
ArrayList tmpA = new ArrayList();
while((currentLine=reader.readLine()) != null && currentLine.length()!=0) {
currentLine = currentLine.trim();
tmpA.add(currentLine);
}
result = new String[tmpA.size()];
for (int i = 0; i < tmpA.size(); i++) {
result[i] = (String)tmpA.get(i);
}
reader.close();
} catch (java.io.IOException e) {
System.out.println("Java.io.IOExeption: " + e.getMessage());
}
}
return result;
}
}

View File

@ -0,0 +1,205 @@
package eva2.server.go.tools;
import java.awt.Component;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import wsi.ra.tool.BasicResourceLoader;
/**
* Created by IntelliJ IDEA.
* User: streiche
* Date: 09.06.2005
* Time: 13:01:18
* To change this template use File | Settings | File Templates.
*/
public class FileTools {
/** This method will load a file and will try to do this using the
* BasicResourceLoader and the standart technique.
* @param file The full filename and path
* @return A string[] containing the lines in the file
*/
static public String[] loadStringsFromFile(String file) {
String[] result = null;
BasicResourceLoader loader = BasicResourceLoader.instance();
byte bytes[] = loader.getBytesFromResourceLocation(file);
if (bytes != null) {
String data = new String(bytes);
result = data.split("\n");
} else {
System.out.println("BasicResourceLoader failed to read "+file);
BufferedReader reader= null;
try {
reader = new BufferedReader(new FileReader(file));
} catch (java.io.FileNotFoundException e) {
System.out.println("Could not find " + file);
return result;
}
String currentLine;
try {
ArrayList tmpA = new ArrayList();
while((currentLine=reader.readLine()) != null && currentLine.length()!=0) {
currentLine = currentLine.trim();
tmpA.add(currentLine);
}
result = new String[tmpA.size()];
for (int i = 0; i < tmpA.size(); i++) {
result[i] = (String)tmpA.get(i);
}
reader.close();
} catch (java.io.IOException e) {
System.out.println("Java.io.IOExeption: " + e.getMessage());
}
}
return result;
}
/**
* Write a given string to a file. Uses {@link #createNewFile(String)} to
* create a new file.
*
* @param filename target file name
* @param str String to write
* @return the File instance or null on a failure
*/
public static File writeString(String filename, String str) {
File f = null;
try {
f = createNewFile(filename);
PrintWriter Out = new PrintWriter(new FileOutputStream(f));
Out.println(str);
Out.flush();
Out.close();
} catch (Exception e) {
System.err.println("Error:" + e.getMessage());
return null;
}
return f;
}
/**
* Try to create a new file. If the filename exists, numbers are appended (with dot)
* until a non-existing file name is found and the new file can be created.
* @param filename
* @return
*/
public static File createNewFile(String filename) {
File f=new File(filename);
try {
if (!f.createNewFile()) {
int i=1;
do {
f = new File(filename+"."+i);
} while (!f.createNewFile());
return f;
} else return f;
} catch(IOException e) {
System.err.println("IOException when trying to create new file!");
System.err.println(e.getMessage());
return null;
}
}
/**
* Saves the current object to a file selected by the user. Strings are written using
* a PrintWriter while other objects are written using an ObjectOutputStream.
*
* @param parentComponent the parent component
* @param fc a filechooser or null to create a new one
* @param object The object to save.
*/
public static boolean saveObjectWithFileChooser(Component parentComponent, Object object) {
int returnVal;
File sFile;
boolean finished = false;
do {
JFileChooser fc = createFileChooser();
returnVal = fc.showSaveDialog(parentComponent);
if (returnVal==JFileChooser.APPROVE_OPTION) {
sFile = fc.getSelectedFile();
if (sFile.exists()) {
int opt = JOptionPane.showConfirmDialog(parentComponent, "File " + sFile.getName() + " exists! Overwrite?", "Confirm to overwrite file", JOptionPane.YES_NO_CANCEL_OPTION);
if (opt==JOptionPane.OK_OPTION) finished=true;
if (opt==JOptionPane.CANCEL_OPTION) return false;
} else finished=true;
} else return false; // user break
} while (!finished); // wait until user selected valid file
if (returnVal==JFileChooser.APPROVE_OPTION) {
try {
if (object instanceof String) {
PrintWriter Out = new PrintWriter(new FileOutputStream(sFile));
Out.println((String)object);
Out.flush();
Out.close();
} else {
ObjectOutputStream oo = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(sFile)));
oo.writeObject(object);
oo.close();
}
return true;
} catch (Exception ex) {
JOptionPane.showMessageDialog(parentComponent,
"Couldn't write to file: "
+ sFile.getName()
+ "\n" + ex.getMessage(),
"Save object",
JOptionPane.ERROR_MESSAGE);
return false;
}
} else return false;
}
/**
* Opens an object from a file selected by the user.
*
* @return the loaded object, or null if the operation was cancelled
*/
public static Object openObject(Component parentComponent, Class clazz) {
Object obj=null;
JFileChooser fc = createFileChooser();
int returnVal = fc.showOpenDialog(parentComponent);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File selected = fc.getSelectedFile();
try {
ObjectInputStream oi = new ObjectInputStream(new BufferedInputStream(new FileInputStream(selected)));
obj = oi.readObject();
oi.close();
if (!clazz.isAssignableFrom(obj.getClass())) {
throw new Exception("Object not of type: " + clazz.getName());
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(parentComponent,
"Couldn't read object: "
+ selected.getName()
+ "\n" + ex.getMessage(),
"Open object file",
JOptionPane.ERROR_MESSAGE);
}
}
if (fc!=null) fc=null;
return obj;
}
public static JFileChooser createFileChooser() {
JFileChooser fc = new JFileChooser(new File("resources"));
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
return fc;
}
}

View File

@ -52,6 +52,14 @@ public abstract class AbstractGOParameters implements InterfaceGOParameters, Ser
this.m_Listener = ea; this.m_Listener = ea;
if (this.m_Optimizer != null) this.m_Optimizer.addPopulationChangedEventListener(this.m_Listener); if (this.m_Optimizer != null) this.m_Optimizer.addPopulationChangedEventListener(this.m_Listener);
} }
public boolean removePopulationChangedEventListener(
InterfacePopulationChangedEventListener ea) {
if (m_Listener==ea) {
m_Listener=null;
if (this.m_Optimizer!=null) this.m_Optimizer.removePopulationChangedEventListener(ea);
return true;
} else return false;
}
public String toString() { public String toString() {
StringBuffer sb = new StringBuffer(getName()); StringBuffer sb = new StringBuffer(getName());

View File

@ -18,14 +18,17 @@ import java.util.Vector;
import wsi.ra.jproxy.MainAdapterClient; import wsi.ra.jproxy.MainAdapterClient;
import wsi.ra.jproxy.RemoteStateListener; import wsi.ra.jproxy.RemoteStateListener;
import eva2.gui.JTabbedModuleFrame; import eva2.gui.EvATabbedFrameMaker;
import eva2.gui.LogPanel; import eva2.gui.LogPanel;
import eva2.server.go.InterfaceGOParameters; import eva2.server.go.InterfaceGOParameters;
import eva2.server.go.InterfaceProcessor; import eva2.server.go.InterfaceProcessor;
/*==========================================================================* /*==========================================================================*
* ABSTRACT CLASS DECLARATION * ABSTRACT CLASS DECLARATION
*==========================================================================*/ *==========================================================================*/
/** /**
* The module server expects a constructor with two arguments: String adapterName and MainAdapterClient client.
*
* *
*/ */
abstract public class AbstractModuleAdapter implements ModuleAdapter, Serializable { abstract public class AbstractModuleAdapter implements ModuleAdapter, Serializable {
@ -42,13 +45,6 @@ abstract public class AbstractModuleAdapter implements ModuleAdapter, Serializab
private Vector<RemoteStateListener> m_RemoteStateListeners; private Vector<RemoteStateListener> m_RemoteStateListeners;
protected LogPanel logPanel = null; protected LogPanel logPanel = null;
/**
*
*/
abstract public JTabbedModuleFrame getModuleFrame();
/**
*
*/
protected AbstractModuleAdapter(MainAdapterClient Client) { protected AbstractModuleAdapter(MainAdapterClient Client) {
if (TRACE) System.out.println("AbstractModuleAdapter.AbstractModuleAdapter()"); if (TRACE) System.out.println("AbstractModuleAdapter.AbstractModuleAdapter()");
m_InstanceCounter++; m_InstanceCounter++;
@ -126,6 +122,18 @@ abstract public class AbstractModuleAdapter implements ModuleAdapter, Serializab
} else return null; } 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() { public boolean isOptRunning() {
if ((m_Processor != null) && (m_Processor instanceof Processor)) { if ((m_Processor != null) && (m_Processor instanceof Processor)) {
return ((Processor)m_Processor).isOptRunning(); return ((Processor)m_Processor).isOptRunning();

View File

@ -29,6 +29,17 @@ public class GOModuleAdapter extends GenericModuleAdapter implements ModuleAdapt
* @param Client the client instance * @param Client the client instance
*/ */
public GOModuleAdapter(String adapterName, MainAdapterClient client) { 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);
} }
} }

View File

@ -23,32 +23,43 @@ public class GOParameters extends AbstractGOParameters implements InterfaceGOPar
public static boolean TRACE = false; public static boolean TRACE = false;
/**
*
*/
public static GOParameters getInstance() { public static GOParameters getInstance() {
if (TRACE) System.out.println("GOParameters getInstance 1"); return getInstance("GOParameters.ser", true);
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;
} }
/** /**
* 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 void saveInstance() { public static GOParameters getInstance(String serParamFile, boolean casually) {
Serializer.storeObject("GOParameters.ser",this); 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(String serParamFile) {
*/ if (TRACE) System.out.println("GOParameters: saveInstance to " + serParamFile);
Serializer.storeObject(serParamFile,this);
}
public void saveInstance() {
saveInstance("GOParameters.ser");
}
public GOParameters() { public GOParameters() {
super(new GeneticAlgorithm(), new F1Problem(), new EvaluationTerminator(1000)); super(new GeneticAlgorithm(), new F1Problem(), new EvaluationTerminator(1000));
// ((F1Problem)m_Problem).setEAIndividual(new GAIndividualDoubleData()); // ((F1Problem)m_Problem).setEAIndividual(new GAIndividualDoubleData());

View File

@ -5,21 +5,22 @@ import java.io.Serializable;
import java.lang.reflect.Proxy; import java.lang.reflect.Proxy;
import java.util.ArrayList; 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.MainAdapterClient;
import wsi.ra.jproxy.RMIProxyLocal; 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 { public class GenericModuleAdapter extends AbstractModuleAdapter implements Serializable {
private StatisticsWithGUI m_StatisticsModul; private AbstractStatistics m_StatisticsModul;
public String helperFilename; public String helperFilename;
/** /**
@ -29,8 +30,9 @@ public class GenericModuleAdapter extends AbstractModuleAdapter implements Seria
* @param Client The client to serve * @param Client The client to serve
* @param params a parameter set describing the optimizer module * @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 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); super (Client);
if (TRACE) System.out.println("Constructor GenericModuleAdapter --> start"); if (TRACE) System.out.println("Constructor GenericModuleAdapter --> start");
m_RemoteThis = this; m_RemoteThis = this;
@ -38,8 +40,12 @@ public class GenericModuleAdapter extends AbstractModuleAdapter implements Seria
m_MainAdapterClient = Client; m_MainAdapterClient = Client;
helperFilename = helperFName; helperFilename = helperFName;
m_StatisticsModul = new StatisticsWithGUI(Client); if (noGUIStatOut==null) {
m_Processor = new Processor((StatisticsWithGUI)m_StatisticsModul,this, params); 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 // this prevents the optimizer property to be shown by the GOE if optimizerExpert is true
GenericObjectEditor.setExpertProperty(params.getClass(), "optimizer", optimizerExpert); 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"); 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() { public GenericModuleAdapter(String adapterName, String helperFName, MainAdapterClient Client, InterfaceGOParameters params, boolean optimizerExpert) {
if (TRACE) System.out.println("GenericModulAdapter.getModuleFrame"); this(adapterName, helperFName, Client, params, optimizerExpert, null);
ArrayList<Object> GUIContainer = new ArrayList<Object>(); }
/** 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<PanelMaker> GUIContainer = new ArrayList<PanelMaker>();
InterfaceStatisticsParameter Stat = ((StatisticsWithGUI)m_StatisticsModul).getStatisticsParameter(); 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); ButtonPanel.setHelperFilename(helperFilename);
GUIContainer.add(ButtonPanel); GUIContainer.add(ButtonPanel);
InterfaceGOParameters Para = ((Processor)m_Processor).getGOParams(); 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())); if (m_RMI && !Proxy.isProxyClass(Stat.getClass())) GUIContainer.add(new JParaPanel( RMIProxyLocal.newInstance(Stat), Stat.getName()));
else GUIContainer.add(new JParaPanel(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() { public static String getName() {
return null; return null;
} }
/**
* Return the statistics module instance of this module.
* @return
*/
public AbstractStatistics getStatistics() {
return m_StatisticsModul;
}
} }

View File

@ -4,9 +4,7 @@ package eva2.server.modules;
import java.io.Serializable; import java.io.Serializable;
import java.util.ArrayList; import java.util.ArrayList;
import eva2.gui.JModuleGeneralPanel;
import eva2.gui.JParaPanel; import eva2.gui.JParaPanel;
import eva2.gui.JTabbedModuleFrame;
import eva2.server.EvAServer; import eva2.server.EvAServer;
import eva2.server.go.InterfaceGOParameters; import eva2.server.go.InterfaceGOParameters;
import eva2.server.stat.InterfaceStatisticsParameter; import eva2.server.stat.InterfaceStatisticsParameter;

View File

@ -12,7 +12,7 @@ package eva2.server.modules;
/*==========================================================================* /*==========================================================================*
* IMPORTS * IMPORTS
*==========================================================================*/ *==========================================================================*/
import eva2.gui.JTabbedModuleFrame; import eva2.gui.EvATabbedFrameMaker;
import eva2.gui.LogPanel; import eva2.gui.LogPanel;
import eva2.server.go.operators.postprocess.PostProcessParams; import eva2.server.go.operators.postprocess.PostProcessParams;
import eva2.server.stat.InterfaceTextListener; import eva2.server.stat.InterfaceTextListener;
@ -24,7 +24,7 @@ import wsi.ra.jproxy.RemoteStateListener;
* *
*/ */
public interface ModuleAdapter extends RemoteStateListener { public interface ModuleAdapter extends RemoteStateListener {
public JTabbedModuleFrame getModuleFrame(); public EvATabbedFrameMaker getModuleFrame();
public void startOpt(); // called from client public void startOpt(); // called from client
public void restartOpt(); public void restartOpt();
public void stopOpt(); public void stopOpt();

View File

@ -12,6 +12,7 @@ import eva2.server.go.InterfaceTerminator;
import eva2.server.go.PopulationInterface; import eva2.server.go.PopulationInterface;
import eva2.server.go.operators.paramcontrol.ConstantParameters; import eva2.server.go.operators.paramcontrol.ConstantParameters;
import eva2.server.go.operators.paramcontrol.InterfaceParameterControl; 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.PostProcess;
import eva2.server.go.operators.postprocess.PostProcessParams; import eva2.server.go.operators.postprocess.PostProcessParams;
import eva2.server.go.operators.terminators.EvaluationTerminator; import eva2.server.go.operators.terminators.EvaluationTerminator;
@ -25,11 +26,18 @@ import eva2.server.stat.InterfaceTextListener;
import eva2.server.stat.StatisticsWithGUI; import eva2.server.stat.StatisticsWithGUI;
import eva2.tools.EVAERROR; import eva2.tools.EVAERROR;
import eva2.tools.EVAHELP; import eva2.tools.EVAHELP;
import eva2.tools.Pair;
/** /**
* The Processor may run as a thread permanently (GenericModuleAdapter) and is then stopped and started * The Processor may run as a thread permanently (GenericModuleAdapter) and is then stopped and started
* by a switch in startOpt/stopOpt. * 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 * @author mkron
* *
*/ */
@ -200,16 +208,16 @@ public class Processor extends Thread implements InterfaceProcessor, InterfacePo
this.goParams.getProblem().initProblem(); this.goParams.getProblem().initProblem();
this.goParams.getOptimizer().SetProblem(this.goParams.getProblem()); this.goParams.getOptimizer().SetProblem(this.goParams.getProblem());
if (this.m_createInitialPopulations) this.goParams.getOptimizer().init();
this.goParams.getTerminator().init(this.goParams.getProblem()); 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()); //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 (m_ListenerModule!=null) m_ListenerModule.updateProgress(getStatusPercent(goParams.getOptimizer().getPopulation(), runCounter, m_Statistics.getStatisticsParameter().getMultiRuns()), null);
if (popLog != null) EVAHELP.clearLog(popLog); if (popLog != null) EVAHELP.clearLog(popLog);
maybeInitParamCtrl(goParams.getOptimizer());
do { // main loop do { // main loop
maybeUpdateParamCtrl(goParams.getOptimizer(), goParams.getTerminator()); maybeUpdateParamCtrl(goParams);
this.goParams.getOptimizer().optimize(); this.goParams.getOptimizer().optimize();
// registerPopulationStateChanged *SHOULD* be fired by the optimizer or resp. the population // 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); if (popLog != null) EVAHELP.logString(this.goParams.getOptimizer().getPopulation().getIndyList(), popLog);
} while (isOptRunning() && !this.goParams.getTerminator().isTerminated(this.goParams.getOptimizer().getAllSolutions())); } while (isOptRunning() && !this.goParams.getTerminator().isTerminated(this.goParams.getOptimizer().getAllSolutions()));
runCounter++; runCounter++;
maybeFinishParamCtrl(goParams.getOptimizer()); maybeFinishParamCtrl(goParams);
//////////////// Default stats //////////////// Default stats
m_Statistics.stopOptPerformed(isOptRunning(), goParams.getTerminator().lastTerminationMessage()); // stop is "normal" if opt wasnt set false by the user (and thus still true) 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 setOptRunning(false); // normal finish
if (m_ListenerModule!=null) m_ListenerModule.performedStop(); // is only needed in client server mode if (m_ListenerModule!=null) m_ListenerModule.performedStop(); // is only needed in client server mode
if (m_ListenerModule!=null) m_ListenerModule.updateProgress(0, null); if (m_ListenerModule!=null) m_ListenerModule.updateProgress(0, null);
goParams.getOptimizer().removePopulationChangedEventListener(this);
return resultPop; return resultPop;
} }
private void maybeInitParamCtrl(InterfaceOptimizer optimizer) { private void iterateParamCtrl(Object instance, String methodName, Object[] args) {
Object paramCtrl=null; Object paramCtrlReturn=null;
if (null!=(paramCtrl=BeanInspector.callIfAvailable(optimizer, "getParamControl", null))) { if (null!=(paramCtrlReturn=BeanInspector.callIfAvailable(instance, "getParamControl", null))) {
if (paramCtrl instanceof InterfaceParameterControl) { if (paramCtrlReturn instanceof Object[]) {
if (!(paramCtrl instanceof ConstantParameters)) { Object[] controllersOrSubControllables = (Object[])paramCtrlReturn;
((InterfaceParameterControl)paramCtrl).init(optimizer); 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) { private void maybeInitParamCtrl(InterfaceGOParameters goParams) {
Object paramCtrl=null; iterateParamCtrl(goParams.getOptimizer(), "init", new Object[]{goParams.getOptimizer(), goParams.getOptimizer().getPopulation()});
if (null!=(paramCtrl=BeanInspector.callIfAvailable(optimizer, "getParamControl", null))) { iterateParamCtrl(goParams.getProblem(), "init", new Object[]{goParams.getProblem(), goParams.getOptimizer().getPopulation()});
if (paramCtrl instanceof InterfaceParameterControl) {
if (!(paramCtrl instanceof ConstantParameters)) {
((InterfaceParameterControl)paramCtrl).finish(optimizer);
}
}
}
} }
private void maybeUpdateParamCtrl(InterfaceOptimizer optimizer,
InterfaceTerminator terminator) { private void maybeFinishParamCtrl(InterfaceGOParameters goParams) {
Object paramCtrl=null; iterateParamCtrl(goParams.getOptimizer(), "finish", new Object[]{goParams.getOptimizer(), goParams.getOptimizer().getPopulation()});
if (null!=(paramCtrl=BeanInspector.callIfAvailable(optimizer, "getParamControl", null))) { iterateParamCtrl(goParams.getProblem(), "finish", new Object[]{goParams.getProblem(), goParams.getOptimizer().getPopulation()});
if (paramCtrl instanceof InterfaceParameterControl) { }
if (!(paramCtrl instanceof ConstantParameters)) {
if (terminator instanceof GenerationTerminator) ((InterfaceParameterControl)paramCtrl).updateParameters(optimizer, optimizer.getPopulation().getGeneration(), ((GenerationTerminator)terminator).getGenerations()); private void maybeUpdateParamCtrl(InterfaceGOParameters goParams) {
else if (terminator instanceof EvaluationTerminator) ((InterfaceParameterControl)paramCtrl).updateParameters(optimizer, optimizer.getPopulation().getFunctionCalls(), ((EvaluationTerminator)terminator).getFitnessCalls()); Object[] args;
else ((InterfaceParameterControl)paramCtrl).updateParameters(optimizer); 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() { public InterfaceGOParameters getGOParams() {
return goParams; return goParams;
} }
public void setGOParams(InterfaceGOParameters x) { public void setGOParams(InterfaceGOParameters params) {
goParams= x; if (params!=null) goParams= params;
else System.err.println("Setting parameters failed (parameters were null) (Processor.setGOParams)");
} }
/** /**

View File

@ -16,6 +16,7 @@ import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InvalidClassException;
import java.io.ObjectInputStream; import java.io.ObjectInputStream;
import java.io.ObjectOutputStream; import java.io.ObjectOutputStream;
import java.io.PipedInputStream; import java.io.PipedInputStream;
@ -187,25 +188,40 @@ public class Serializer {
} }
return ret; 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 * Deserialize the contents of File with given name containing
* a string and return the resulting string. If the indicated file * a string and return the resulting string. If the indicated file
* doesnt exist or an error occurs, null is returned. * 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; Object s = null;
File f = new File(Filename); File f = new File(Filename);
if (f.exists()) { if (f.exists()) {
try { try {
s=(Object)load(new File(Filename)); 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("WARNING: loading object File "+Filename+ " not possible, this may happen on source code changes.");
System.err.println(e.getMessage()); System.err.println(e.getMessage());
//e.printStackTrace(); } catch (Exception e) {
return null; throw new RuntimeException("WARNING: loading object File "+Filename+ " not possible! ("+e.getMessage()+")");
} }
return s; return s;
} else return null; } else {
if (!casually) System.err.println("Error in Serializer: file " + Filename + " not found!");
return null;
}
} }
} }

View File

@ -1,7 +1,10 @@
package eva2.tools; package eva2.tools;
import java.util.LinkedList;
import java.util.StringTokenizer; import java.util.StringTokenizer;
import eva2.gui.BeanInspector;
public class StringTools { public class StringTools {
/** /**
@ -32,10 +35,99 @@ public class StringTools {
return sbuf.toString(); return sbuf.toString();
} }
public static void main(String[] args) { public static boolean arrayContains(String[] arr, String key, boolean ignoreCase) {
System.out.println(toHTML("Hallo-asdfsadfsafdsadfo, dies ist ein doller test text!", 15)); return (searchStringArray(arr, key, 0, ignoreCase))>=0;
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));
} }
/**
* 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<arr.length; i++) {
if (ignoreCase) {
if (arr[i].equalsIgnoreCase(key)) return i;
} else {
if (arr[i].equals(key)) return i;
}
}
return -1;
}
// 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));
// }
/**
* Parse an array of Strings as an argument list. Take the argument list, a set of keys together
* with their arities. Returns for each key a value depending on arity and whether it was found.
* For any key, if it was not found null is returned as value. Its index in the keys array is contained
* in the returned integer array.
* For any key, if it was found, the corresponding value is either Boolean(true) for zero-arity-keys
* or a String array of length of the arity containing the arguments to the key.
*
* @param args
* @param keys
* @param arities
* @param values
* @param ignoreCase
* @return
*/
public static Integer[] parseArguments(String[] args, String[] keys, int[] arities, Object[] values, boolean ignoreCase) {
LinkedList<Integer> unrecogs=new LinkedList<Integer>();
//for (String string : argsArr) args.add(string); // create a linked list copy
for (int i=0; i<args.length; i++) { // loop all arguments
boolean found=false;
for (int k=0; k<keys.length; k++) { // loop all keys
if ((ignoreCase && (args[i].equalsIgnoreCase(keys[k])))
|| (!ignoreCase && (args[i].equals(keys[k])))) { // if the key was found
found=true;
if (arities[k]==0) values[k]=new Boolean(true); // and its zero-arity, just return true as its value
else { // else return an array of size arity with following strings
values[k]=new String[arities[k]];
for (int j=0; j<arities[k]; j++) {
i++;
((String[])values[k])[j]=args[i];
}
}
}
}
if (!found) unrecogs.add(i);
}
return unrecogs.toArray(new Integer[unrecogs.size()]);
}
/**
* Check whether an object is a valid String array and if so return the i-th String.
* Returns null otherwise.
*
* @param key
* @param object
* @param i
* @return
*/
public static String checkSingleStringArg(String key, Object object, int i) {
if (object==null) return null;
if (object instanceof String[]) {
String[] arr = (String[])object;
if (i<arr.length) return arr[i];
else {
System.err.println("Not enough arguments for " + key);
return null;
}
} else {
System.err.println("Invalid argument: " + key + " " + BeanInspector.toString(object));
return null;
}
}
} }