Logging is now completely implemented for EvA2Client class.
This commit is contained in:
Fabian Becker 2012-04-15 22:45:31 +00:00
parent e721e06e11
commit 454ddbc20f
4 changed files with 323 additions and 292 deletions

View File

@ -98,6 +98,8 @@ public class EvAInfo {
public static final String splashLocation = "resources/images/splashScreen2.png"; public static final String splashLocation = "resources/images/splashScreen2.png";
public static final String infoTitle = productName+" Information"; public static final String infoTitle = productName+" Information";
public static final String copyrightYear = "2010-2012"; public static final String copyrightYear = "2010-2012";
public static final String defaultLogger = "EvA2";
////////////// Property handling... ////////////// Property handling...

View File

@ -442,8 +442,6 @@ public class EvAClient implements RemoteStateListener, Serializable {
} }
}); });
logger.info("EvAClient Loggin enabled");
logger.warning("Logging could still die.");
m_ProgressBar = new JProgressBar(); m_ProgressBar = new JProgressBar();
evaFrame.getContentPane().add(m_ProgressBar, BorderLayout.SOUTH); evaFrame.getContentPane().add(m_ProgressBar, BorderLayout.SOUTH);
@ -469,7 +467,7 @@ public class EvAClient implements RemoteStateListener, Serializable {
evaFrame.addWindowListener(new WindowAdapter() { evaFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) { public void windowClosing(WindowEvent e) {
System.out.println("Closing EvA2 Client. Bye!"); logger.info("Closing EvA2 Client. Bye!");
evaFrame.dispose(); evaFrame.dispose();
Set<String> keys = System.getenv().keySet(); Set<String> keys = System.getenv().keySet();
if (keys.contains("MATLAB")) { if (keys.contains("MATLAB")) {
@ -488,14 +486,14 @@ public class EvAClient implements RemoteStateListener, Serializable {
selectHost(hostName); selectHost(hostName);
} }
m_ComAdapter.setLogPanel(logPanel); m_ComAdapter.setLogPanel(logPanel);
logMessage("Selected Host: " + m_ComAdapter.getHostName()); logger.log(Level.INFO, "Selected Host: {0}", m_ComAdapter.getHostName());
} }
// m_mnuModule.setText("Select module"); // m_mnuModule.setText("Select module");
// m_mnuModule.repaint(); // m_mnuModule.repaint();
if (withGUI) { if (withGUI) {
logPanel.logMessage("Working directory is: " + System.getProperty("user.dir")); logger.log(Level.INFO, "Working directory is: {0}", System.getProperty("user.dir"));
logPanel.logMessage("Class path is: " + System.getProperty("java.class.path", ".")); logger.log(Level.INFO, "Class path is: {0}", System.getProperty("java.class.path", "."));
if (!(evaFrame.isVisible())) { if (!(evaFrame.isVisible())) {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
@ -503,7 +501,9 @@ public class EvAClient implements RemoteStateListener, Serializable {
evaFrame.pack(); evaFrame.pack();
evaFrame.setVisible(true); evaFrame.setVisible(true);
} }
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 // if this message is omitted, the stupid scroll pane runs to
// the end of the last line which is ugly for a long class path
logger.info("EvA2 ready");
} }
} }
@ -635,7 +635,7 @@ public class EvAClient implements RemoteStateListener, Serializable {
@Override @Override
public void actionPerformed(ActionEvent e) { public void actionPerformed(ActionEvent e) {
logMessage(e.getActionCommand()); logger.info(e.getActionCommand());
showAboutDialog(); showAboutDialog();
} }
}; };
@ -644,7 +644,7 @@ public class EvAClient implements RemoteStateListener, Serializable {
@Override @Override
public void actionPerformed(ActionEvent e) { public void actionPerformed(ActionEvent e) {
logMessage(e.getActionCommand()); logger.info(e.getActionCommand());
showLicense(); showLicense();
} }
}; };
@ -653,7 +653,7 @@ public class EvAClient implements RemoteStateListener, Serializable {
@Override @Override
public void actionPerformed(ActionEvent e) { public void actionPerformed(ActionEvent e) {
logMessage(e.getActionCommand()); logger.info(e.getActionCommand());
selectAvailableHost(m_ComAdapter.getHostNameList()); selectAvailableHost(m_ComAdapter.getHostNameList());
} }
}; };
@ -662,7 +662,7 @@ public class EvAClient implements RemoteStateListener, Serializable {
@Override @Override
public void actionPerformed(ActionEvent e) { public void actionPerformed(ActionEvent e) {
logMessage(e.getActionCommand()); logger.info(e.getActionCommand());
showPleaseWaitDialog(); showPleaseWaitDialog();
Thread xx = new Thread() { Thread xx = new Thread() {
@ -679,7 +679,7 @@ public class EvAClient implements RemoteStateListener, Serializable {
@Override @Override
public void actionPerformed(ActionEvent e) { public void actionPerformed(ActionEvent e) {
logMessage(e.getActionCommand()); logger.info(e.getActionCommand());
showPleaseWaitDialog(); showPleaseWaitDialog();
Thread xx = new Thread() { Thread xx = new Thread() {
@ -695,7 +695,7 @@ public class EvAClient implements RemoteStateListener, Serializable {
@Override @Override
public void actionPerformed(ActionEvent e) { public void actionPerformed(ActionEvent e) {
logMessage(e.getActionCommand()); logger.info(e.getActionCommand());
showPleaseWaitDialog(); showPleaseWaitDialog();
Thread xx = new Thread() { Thread xx = new Thread() {
@ -835,10 +835,10 @@ public class EvAClient implements RemoteStateListener, Serializable {
if (useLocalRMI) { if (useLocalRMI) {
EvAServer Server = new EvAServer(true, false); EvAServer Server = new EvAServer(true, false);
m_ComAdapter.setLocalRMIServer(Server.getRMIServer()); m_ComAdapter.setLocalRMIServer(Server.getRMIServer());
logMessage("Local EvAServer started"); logger.info("Local EvAServer started");
m_ComAdapter.setRunLocally(false); // this is not quite true but should have the desired effect m_ComAdapter.setRunLocally(false); // this is not quite true but should have the desired effect
} else { } else {
logMessage("Working locally"); logger.info("Working locally");
m_ComAdapter.setLocalRMIServer(null); m_ComAdapter.setLocalRMIServer(null);
m_ComAdapter.setRunLocally(true); m_ComAdapter.setRunLocally(true);
} }
@ -874,7 +874,7 @@ public class EvAClient implements RemoteStateListener, Serializable {
m_actHost.setEnabled(true); m_actHost.setEnabled(true);
m_actAvailableHost.setEnabled(true); m_actAvailableHost.setEnabled(true);
} }
logMessage("Selected Module: " + selectedModule); logger.info("Selected Module: " + selectedModule);
// m_LogPanel.statusMessage("Selected Module: " + selectedModule); // m_LogPanel.statusMessage("Selected Module: " + selectedModule);
} }
} }
@ -921,8 +921,7 @@ public class EvAClient implements RemoteStateListener, Serializable {
try { try {
newModuleAdapter = m_ComAdapter.getModuleAdapter(selectedModule, goParams, withGUI ? null : "EvA2"); newModuleAdapter = m_ComAdapter.getModuleAdapter(selectedModule, goParams, withGUI ? null : "EvA2");
} catch (Exception e) { } catch (Exception e) {
logMessage("Error while m_ComAdapter.GetModuleAdapter Host: " + e.getMessage()); logger.log(Level.SEVERE, "Error while m_ComAdapter.GetModuleAdapter Host: " + e.getMessage(), e);
e.printStackTrace();
EVAERROR.EXIT("Error while m_ComAdapter.GetModuleAdapter Host: " + e.getMessage()); EVAERROR.EXIT("Error while m_ComAdapter.GetModuleAdapter Host: " + e.getMessage());
} }
if (newModuleAdapter == null) { if (newModuleAdapter == null) {
@ -1044,9 +1043,9 @@ public class EvAClient implements RemoteStateListener, Serializable {
private void selectHost(String hostName) { private void selectHost(String hostName) {
m_ComAdapter.setHostName(hostName); m_ComAdapter.setHostName(hostName);
logMessage("Selected Host: " + hostName); logger.info("Selected Host: " + hostName);
if (currentModule != null) { if (currentModule != null) {
logMessage("Reloading module from server..."); logger.info("Reloading module from server...");
loadModuleFromServer(currentModule, null); loadModuleFromServer(currentModule, null);
} }
} }
@ -1094,14 +1093,14 @@ public class EvAClient implements RemoteStateListener, Serializable {
if (HostName == null) { if (HostName == null) {
return; return;
} }
logMessage("Kill host process on = " + HostName); logger.info("Kill host process on = " + HostName);
m_ComAdapter.killServer(HostName); m_ComAdapter.killServer(HostName);
// m_LogPanel.statusMessage(""); // m_LogPanel.statusMessage("");
} }
private void selectAllAvailableHostToKill(String[] HostNames) { private void selectAllAvailableHostToKill(String[] hostNames) {
System.out.println("SelectAllAvailableHostToKill"); System.out.println("SelectAllAvailableHostToKill");
if (HostNames == null || HostNames.length == 0) { if (hostNames == null || hostNames.length == 0) {
System.out.println("no host is running"); System.out.println("no host is running");
return; return;
} }
@ -1114,7 +1113,7 @@ public class EvAClient implements RemoteStateListener, Serializable {
l.performedRestart(infoString); l.performedRestart(infoString);
} }
} }
logMessage("Restarted processing " + infoString); logger.log(Level.INFO, "Restarted processing {0}", infoString);
startTime = System.currentTimeMillis(); startTime = System.currentTimeMillis();
} }
@ -1124,7 +1123,7 @@ public class EvAClient implements RemoteStateListener, Serializable {
l.performedStart(infoString); l.performedStart(infoString);
} }
} }
logMessage("Started processing " + infoString); logger.log(Level.INFO, "Started processing {0}", infoString);
startTime = System.currentTimeMillis(); startTime = System.currentTimeMillis();
} }
@ -1135,7 +1134,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))); logger.info(String.format("Stopped after %1$d.%2$tL s", (t / 1000), (t % 1000)));
if (!withGUI) { if (!withGUI) {
System.exit(0); System.exit(0);
} }
@ -1153,7 +1152,7 @@ public class EvAClient implements RemoteStateListener, Serializable {
} }
} }
if (msg != null) { if (msg != null) {
logMessage(msg); logger.info(msg);
} }
if (this.m_ProgressBar != null) { if (this.m_ProgressBar != null) {
Runnable doSetProgressBarValue = new Runnable() { Runnable doSetProgressBarValue = new Runnable() {

View File

@ -1,5 +1,6 @@
package eva2.server.modules; package eva2.server.modules;
import eva2.EvAInfo;
import java.util.List; import java.util.List;
import java.util.Vector; import java.util.Vector;
@ -31,6 +32,8 @@ import eva2.tools.EVAHELP;
import eva2.tools.StringTools; import eva2.tools.StringTools;
import eva2.tools.jproxy.RemoteStateListener; import eva2.tools.jproxy.RemoteStateListener;
import eva2.tools.math.RNG; import eva2.tools.math.RNG;
import java.util.logging.Level;
import java.util.logging.Logger;
/** /**
* 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
@ -47,28 +50,27 @@ import eva2.tools.math.RNG;
*/ */
public class Processor extends Thread implements InterfaceProcessor, InterfacePopulationChangedEventListener { public class Processor extends Thread implements InterfaceProcessor, InterfacePopulationChangedEventListener {
private static final boolean TRACE=false; private static final Logger logger = Logger.getLogger(EvAInfo.defaultLogger);
private volatile boolean m_optRunning; private volatile boolean m_optRunning;
// private volatile boolean m_doRunScript; private InterfaceStatistics m_Statistics;
private InterfaceStatistics m_Statistics; private InterfaceGOParameters goParams;
private InterfaceGOParameters goParams; private boolean m_createInitialPopulations = true;
private boolean m_createInitialPopulations = true; private boolean saveParams = true;
private boolean saveParams = true; private RemoteStateListener m_ListenerModule;
private RemoteStateListener m_ListenerModule; private boolean wasRestarted = false;
private boolean wasRestarted = false; private int runCounter = 0;
// private int postProcessSteps = 0; private Population resPop = null;
private int runCounter = 0; private boolean userAborted = false;
private Population resPop = null;
private boolean userAborted = false;
// transient private String m_OutputPath = "";
// transient private BufferedWriter m_OutputFile = null;
public void addListener(RemoteStateListener module) { public void addListener(RemoteStateListener module) {
if (TRACE) System.out.println("Processor: setting module as listener: " + ((module==null) ? "null" : module.toString())); logger.log(
m_ListenerModule = module; Level.FINEST,
"Processor: setting module as listener: " + ((module == null)
? "null" : module.toString()));
m_ListenerModule = module;
} }
/** /**
* Construct a Processor instance and make statistics instance informable of the parameters, * Construct a Processor instance and make statistics instance informable of the parameters,
* such they can by dynamically show additional information. * such they can by dynamically show additional information.
@ -76,44 +78,43 @@ public class Processor extends Thread implements InterfaceProcessor, InterfacePo
* @see InterfaceNotifyOnInformers * @see InterfaceNotifyOnInformers
*/ */
public Processor(InterfaceStatistics Stat, ModuleAdapter Adapter, InterfaceGOParameters params) { public Processor(InterfaceStatistics Stat, ModuleAdapter Adapter, InterfaceGOParameters params) {
goParams = params; goParams = params;
m_Statistics = Stat; m_Statistics = Stat;
m_ListenerModule = Adapter; m_ListenerModule = Adapter;
// the statistics want to be informed if the strategy or the optimizer (which provide statistical data as InterfaceAdditionalInformer) change. // the statistics want to be informed if the strategy or the optimizer (which provide statistical data as InterfaceAdditionalInformer) change.
if (Stat!=null && (params != null)) { if (Stat != null && (params != null)) {
if (Stat.getStatisticsParameter() instanceof InterfaceNotifyOnInformers) { if (Stat.getStatisticsParameter() instanceof InterfaceNotifyOnInformers) {
// addition for the statistics revision with selectable strings - make sure the go parameters are represented within the statistics // addition for the statistics revision with selectable strings - make sure the go parameters are represented within the statistics
params.addInformableInstance((InterfaceNotifyOnInformers)(Stat.getStatisticsParameter())); params.addInformableInstance((InterfaceNotifyOnInformers) (Stat.getStatisticsParameter()));
} }
} }
} }
public boolean isOptRunning() { public boolean isOptRunning() {
return m_optRunning; return m_optRunning;
} }
protected void setOptRunning(boolean bRun) { protected void setOptRunning(boolean bRun) {
m_optRunning = bRun; m_optRunning = bRun;
} }
/** /**
* If set to true, before every run the parameters will be stored to a file. * If set to true, before every run the parameters will be stored to a file.
* *
* @param doSave * @param doSave
*/ */
public void setSaveParams(boolean doSave) { public void setSaveParams(boolean doSave) {
saveParams = doSave; saveParams = doSave;
} }
/** /**
* *
*/ */
public void startOpt() { public void startOpt() {
m_createInitialPopulations = true; m_createInitialPopulations = true;
if (TRACE) System.out.println("startOpt called:");
if (isOptRunning()) { if (isOptRunning()) {
System.err.println("ERROR: Processor is already running !!"); logger.log(Level.SEVERE, "Processor is already running.");
return; return;
} }
resPop = null; resPop = null;
@ -121,7 +122,7 @@ public class Processor extends Thread implements InterfaceProcessor, InterfacePo
wasRestarted = false; wasRestarted = false;
setOptRunning(true); setOptRunning(true);
} }
/** /**
* Return true if the optimization was stopped by the user instead of * Return true if the optimization was stopped by the user instead of
* the termination criterion. * the termination criterion.
@ -129,17 +130,16 @@ public class Processor extends Thread implements InterfaceProcessor, InterfacePo
* @return * @return
*/ */
public boolean wasAborted() { public boolean wasAborted() {
return userAborted; return userAborted;
} }
/** /**
* *
*/ */
public void restartOpt() { public void restartOpt() {
m_createInitialPopulations = false; m_createInitialPopulations = false;
if (TRACE) System.out.println("restartOpt called:");
if (isOptRunning()) { if (isOptRunning()) {
System.err.println("ERROR: Processor is already running !!"); logger.log(Level.SEVERE, "Processor is already running.");
return; return;
} }
userAborted = false; userAborted = false;
@ -151,58 +151,60 @@ public class Processor extends Thread implements InterfaceProcessor, InterfacePo
* *
*/ */
public void stopOpt() { // this means user break public void stopOpt() { // this means user break
if (TRACE) System.out.println("called StopOpt");
setOptRunning(false); setOptRunning(false);
if (TRACE) System.out.println("m_doRunScript = false ");
} }
/** /**
* *
*/ */
public void run() { public void run() {
setPriority(1); setPriority(1);
while (true) { while (true) {
try { try {
Thread.sleep(200); Thread.sleep(200);
} catch (Exception e) { } catch (Exception e) {
System.err.println ("There was an error in sleep Processor.run()" + e); System.err.println("There was an error in sleep Processor.run()" + e);
} }
runOptOnce(); runOptOnce();
} }
} }
public Population runOptOnce() { public Population runOptOnce() {
try { try {
EVAERROR.clearMsgCache(); EVAERROR.clearMsgCache();
while (isOptRunning()) { while (isOptRunning()) {
setPriority(3); setPriority(3);
if (saveParams) { if (saveParams) {
try { try {
goParams.saveInstance(); goParams.saveInstance();
} catch(Exception e) { } catch (Exception e) {
System.err.println("Error on saveInstance!"); System.err.println("Error on saveInstance!");
} }
} }
resPop = optimize("Run"); resPop = optimize("Run");
setPriority(1); setPriority(1);
} }
} catch (Exception e) { } catch (Exception e) {
String errMsg = e.toString(); String errMsg = e.toString();
if ((errMsg == null) || (errMsg.length() == 0)) errMsg="check console output for error messages."; if ((errMsg == null) || (errMsg.length() == 0)) {
errMsg = "Exception in Processor: "+errMsg; errMsg = "check console output for error messages.";
System.err.println(errMsg); }
e.printStackTrace(); errMsg = "Exception in Processor: " + errMsg;
try { System.err.println(errMsg);
JOptionPane.showMessageDialog(null, StringTools.wrapLine(errMsg, 60, 0.2), "Error in Optimization", JOptionPane.ERROR_MESSAGE); e.printStackTrace();
} catch (Exception ex) {} catch(Error er) {}; try {
//m_Statistics.stopOptPerformed(false); JOptionPane.showMessageDialog(null, StringTools.wrapLine(errMsg, 60, 0.2), "Error in Optimization", JOptionPane.ERROR_MESSAGE);
setOptRunning(false); // normal finish } catch (Exception ex) {
if (m_ListenerModule!=null) { } catch (Error er) {
m_ListenerModule.performedStop(); // is only needed in client server mode };
m_ListenerModule.updateProgress(0, errMsg); //m_Statistics.stopOptPerformed(false);
} setOptRunning(false); // normal finish
} if (m_ListenerModule != null) {
return resPop; m_ListenerModule.performedStop(); // is only needed in client server mode
m_ListenerModule.updateProgress(0, errMsg);
}
}
return resPop;
} }
/** /**
@ -210,125 +212,146 @@ public class Processor extends Thread implements InterfaceProcessor, InterfacePo
* Return a population containing the solutions of the last run if there were multiple. * Return a population containing the solutions of the last run if there were multiple.
*/ */
protected Population optimize(String infoString) { protected Population optimize(String infoString) {
Population resultPop = null; Population resultPop = null;
if (!isOptRunning()) { if (!isOptRunning()) {
System.err.println("warning, this shouldnt happen in processor! Was startOpt called?"); System.err.println("warning, this shouldnt happen in processor! Was startOpt called?");
setOptRunning(true); setOptRunning(true);
}
RNG.setRandomSeed(goParams.getSeed());
if (m_ListenerModule!=null) {
if (wasRestarted) m_ListenerModule.performedRestart(getInfoString());
else m_ListenerModule.performedStart(getInfoString());
} }
goParams.getOptimizer().addPopulationChangedEventListener(this); RNG.setRandomSeed(goParams.getSeed());
if (m_ListenerModule != null) {
if (wasRestarted) {
m_ListenerModule.performedRestart(getInfoString());
} else {
m_ListenerModule.performedStart(getInfoString());
}
}
goParams.getOptimizer().addPopulationChangedEventListener(this);
runCounter = 0; runCounter = 0;
String popLog = null; //"populationLog.txt"; String popLog = null; //"populationLog.txt";
while (isOptRunning() && (runCounter<m_Statistics.getStatisticsParameter().getMultiRuns())) { while (isOptRunning() && (runCounter < m_Statistics.getStatisticsParameter().getMultiRuns())) {
m_Statistics.startOptPerformed(getInfoString(),runCounter, goParams, getInformerList()); m_Statistics.startOptPerformed(getInfoString(), runCounter, goParams, getInformerList());
this.goParams.getProblem().initProblem(); this.goParams.getProblem().initProblem();
this.goParams.getOptimizer().SetProblem(this.goParams.getProblem()); this.goParams.getOptimizer().SetProblem(this.goParams.getProblem());
this.goParams.getTerminator().init(this.goParams.getProblem()); this.goParams.getTerminator().init(this.goParams.getProblem());
maybeInitParamCtrl(goParams); maybeInitParamCtrl(goParams);
if (this.m_createInitialPopulations) this.goParams.getOptimizer().init(); if (this.m_createInitialPopulations) {
this.goParams.getOptimizer().init();
//m_Statistics.createNextGenerationPerformed((PopulationInterface)this.m_ModulParameter.getOptimizer().getPopulation()); }
if (m_ListenerModule!=null) m_ListenerModule.updateProgress(getStatusPercent(goParams.getOptimizer().getPopulation(), runCounter, m_Statistics.getStatisticsParameter().getMultiRuns()), null);
if (popLog != null) EVAHELP.clearLog(popLog);
do { // main loop
maybeUpdateParamCtrl(goParams);
this.goParams.getOptimizer().optimize(); //m_Statistics.createNextGenerationPerformed((PopulationInterface)this.m_ModulParameter.getOptimizer().getPopulation());
// registerPopulationStateChanged *SHOULD* be fired by the optimizer or resp. the population if (m_ListenerModule != null) {
// as we are event listener m_ListenerModule.updateProgress(getStatusPercent(goParams.getOptimizer().getPopulation(), runCounter, m_Statistics.getStatisticsParameter().getMultiRuns()), null);
if (popLog != null) EVAHELP.logString(this.goParams.getOptimizer().getPopulation().getIndyList(), popLog); }
} while (isOptRunning() && !this.goParams.getTerminator().isTerminated(this.goParams.getOptimizer().getAllSolutions())); if (popLog != null) {
runCounter++; EVAHELP.clearLog(popLog);
maybeFinishParamCtrl(goParams); }
userAborted = !isOptRunning(); // stop is "normal" if opt wasnt set false by the user (and thus still true)
//////////////// Default stats do { // main loop
m_Statistics.stopOptPerformed(!userAborted, goParams.getTerminator().lastTerminationMessage()); // stop is "normal" if opt wasnt set false by the user (and thus still true) maybeUpdateParamCtrl(goParams);
//////////////// PP or set results without further PP this.goParams.getOptimizer().optimize();
if (!userAborted) { // registerPopulationStateChanged *SHOULD* be fired by the optimizer or resp. the population
resultPop = performPostProcessing(); // as we are event listener
if (resultPop==null) { // post processing disabled, so use opt. solutions if (popLog != null) {
resultPop = goParams.getOptimizer().getAllSolutions().getSolutions(); EVAHELP.logString(this.goParams.getOptimizer().getPopulation().getIndyList(), popLog);
} }
} else resultPop = goParams.getOptimizer().getAllSolutions().getSolutions(); } while (isOptRunning() && !this.goParams.getTerminator().isTerminated(this.goParams.getOptimizer().getAllSolutions()));
m_Statistics.postProcessingPerformed(resultPop); runCounter++;
maybeFinishParamCtrl(goParams);
userAborted = !isOptRunning(); // stop is "normal" if opt wasnt set false by the user (and thus still true)
//////////////// Default stats
m_Statistics.stopOptPerformed(!userAborted, goParams.getTerminator().lastTerminationMessage()); // stop is "normal" if opt wasnt set false by the user (and thus still true)
//////////////// PP or set results without further PP
if (!userAborted) {
resultPop = performPostProcessing();
if (resultPop == null) { // post processing disabled, so use opt. solutions
resultPop = goParams.getOptimizer().getAllSolutions().getSolutions();
}
} else {
resultPop = goParams.getOptimizer().getAllSolutions().getSolutions();
}
m_Statistics.postProcessingPerformed(resultPop);
} }
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) {
if (m_ListenerModule!=null) m_ListenerModule.updateProgress(0, null); m_ListenerModule.performedStop(); // is only needed in client server mode
}
if (m_ListenerModule != null) {
m_ListenerModule.updateProgress(0, null);
}
goParams.getOptimizer().removePopulationChangedEventListener(this); goParams.getOptimizer().removePopulationChangedEventListener(this);
return resultPop; return resultPop;
} }
private void iterateParamCtrl(Object instance, String methodName, Object[] args) {
Object paramCtrlReturn=null;
if (null!=(paramCtrlReturn=BeanInspector.callIfAvailable(instance, "getParamControl", null))) {
if (paramCtrlReturn instanceof Object[]) {
Object[] controllersOrSubControllables = (Object[])paramCtrlReturn;
for (Object controllerOrSubControllable : controllersOrSubControllables) {
// The returned array may contain (i) InterfaceParameterControl associated with the instance
// itself or (ii) sub-instances which have their own parameter controls. On these, the method
// is called recursively.
if (controllerOrSubControllable instanceof InterfaceParameterControl) {
args[0]=instance;
if (!((InterfaceParameterControl)controllerOrSubControllable instanceof ConstantParameters))
BeanInspector.callIfAvailable((InterfaceParameterControl)controllerOrSubControllable, 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 maybeInitParamCtrl(InterfaceGOParameters goParams) {
iterateParamCtrl(goParams.getOptimizer(), "init", new Object[]{goParams.getOptimizer(), goParams.getOptimizer().getPopulation()});
iterateParamCtrl(goParams.getProblem(), "init", new Object[]{goParams.getProblem(), goParams.getOptimizer().getPopulation()});
}
private void maybeFinishParamCtrl(InterfaceGOParameters goParams) {
iterateParamCtrl(goParams.getOptimizer(), "finish", new Object[]{goParams.getOptimizer(), goParams.getOptimizer().getPopulation()});
iterateParamCtrl(goParams.getProblem(), "finish", new Object[]{goParams.getProblem(), goParams.getOptimizer().getPopulation()});
}
private void maybeUpdateParamCtrl(InterfaceGOParameters goParams) {
Object[] args;
InterfaceTerminator terminator = goParams.getTerminator();
InterfaceOptimizer optimizer = goParams.getOptimizer();
if (terminator instanceof GenerationTerminator)
args = new Object[]{optimizer, optimizer.getPopulation(), optimizer.getPopulation().getGeneration(), ((GenerationTerminator)terminator).getGenerations()};
// ((InterfaceParameterControl)paramCtrl).updateParameters(optimizer, optimizer.getPopulation().getGeneration(), ((GenerationTerminator)terminator).getGenerations());
else if (terminator instanceof EvaluationTerminator)
args = new Object[] {optimizer, optimizer.getPopulation(), optimizer.getPopulation().getFunctionCalls(), ((EvaluationTerminator)terminator).getFitnessCalls()};
// ((InterfaceParameterControl)paramCtrl).updateParameters(optimizer, optimizer.getPopulation().getFunctionCalls(), ((EvaluationTerminator)terminator).getFitnessCalls());
else args = new Object[]{optimizer};
// ((InterfaceParameterControl)paramCtrl).updateParameters(optimizer);
if (args != null) { // only if iteration counting is available
iterateParamCtrl(optimizer, "updateParameters", args);
args[0]=goParams.getProblem();
iterateParamCtrl(goParams.getProblem(), "updateParameters", args);
}
}
/** private void iterateParamCtrl(Object instance, String methodName, Object[] args) {
Object paramCtrlReturn = null;
if (null != (paramCtrlReturn = BeanInspector.callIfAvailable(instance, "getParamControl", null))) {
if (paramCtrlReturn instanceof Object[]) {
Object[] controllersOrSubControllables = (Object[]) paramCtrlReturn;
for (Object controllerOrSubControllable : controllersOrSubControllables) {
// The returned array may contain (i) InterfaceParameterControl associated with the instance
// itself or (ii) sub-instances which have their own parameter controls. On these, the method
// is called recursively.
if (controllerOrSubControllable instanceof InterfaceParameterControl) {
args[0] = instance;
if (!((InterfaceParameterControl) controllerOrSubControllable instanceof ConstantParameters)) {
BeanInspector.callIfAvailable((InterfaceParameterControl) controllerOrSubControllable, 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 maybeInitParamCtrl(InterfaceGOParameters goParams) {
iterateParamCtrl(goParams.getOptimizer(), "init", new Object[]{goParams.getOptimizer(), goParams.getOptimizer().getPopulation()});
iterateParamCtrl(goParams.getProblem(), "init", new Object[]{goParams.getProblem(), goParams.getOptimizer().getPopulation()});
}
private void maybeFinishParamCtrl(InterfaceGOParameters goParams) {
iterateParamCtrl(goParams.getOptimizer(), "finish", new Object[]{goParams.getOptimizer(), goParams.getOptimizer().getPopulation()});
iterateParamCtrl(goParams.getProblem(), "finish", new Object[]{goParams.getProblem(), goParams.getOptimizer().getPopulation()});
}
private void maybeUpdateParamCtrl(InterfaceGOParameters goParams) {
Object[] args;
InterfaceTerminator terminator = goParams.getTerminator();
InterfaceOptimizer optimizer = goParams.getOptimizer();
if (terminator instanceof GenerationTerminator) {
args = new Object[]{optimizer, optimizer.getPopulation(), optimizer.getPopulation().getGeneration(), ((GenerationTerminator) terminator).getGenerations()};
} // ((InterfaceParameterControl)paramCtrl).updateParameters(optimizer, optimizer.getPopulation().getGeneration(), ((GenerationTerminator)terminator).getGenerations());
else if (terminator instanceof EvaluationTerminator) {
args = new Object[]{optimizer, optimizer.getPopulation(), optimizer.getPopulation().getFunctionCalls(), ((EvaluationTerminator) terminator).getFitnessCalls()};
} // ((InterfaceParameterControl)paramCtrl).updateParameters(optimizer, optimizer.getPopulation().getFunctionCalls(), ((EvaluationTerminator)terminator).getFitnessCalls());
else {
args = new Object[]{optimizer};
}
// ((InterfaceParameterControl)paramCtrl).updateParameters(optimizer);
if (args != null) { // only if iteration counting is available
iterateParamCtrl(optimizer, "updateParameters", args);
args[0] = goParams.getProblem();
iterateParamCtrl(goParams.getProblem(), "updateParameters", args);
}
}
/**
* Calculate the percentage of current (multi-)run already performed, based on evaluations/generations * Calculate the percentage of current (multi-)run already performed, based on evaluations/generations
* for the EvaluationTerminator/GenerationTerminator or multi-runs only. * for the EvaluationTerminator/GenerationTerminator or multi-runs only.
* *
@ -338,18 +361,20 @@ public class Processor extends Thread implements InterfaceProcessor, InterfacePo
* @return the percentage of current (multi-)run already performed * @return the percentage of current (multi-)run already performed
*/ */
private int getStatusPercent(Population pop, int currentRun, int multiRuns) { private int getStatusPercent(Population pop, int currentRun, int multiRuns) {
double percentPerRun = 100./multiRuns; double percentPerRun = 100. / multiRuns;
int curProgress; int curProgress;
if (this.goParams.getTerminator() instanceof EvaluationTerminator) { if (this.goParams.getTerminator() instanceof EvaluationTerminator) {
double curRunPerf = pop.getFunctionCalls()*percentPerRun/(double)((EvaluationTerminator)this.goParams.getTerminator()).getFitnessCalls(); double curRunPerf = pop.getFunctionCalls() * percentPerRun / (double) ((EvaluationTerminator) this.goParams.getTerminator()).getFitnessCalls();
curProgress = (int)(currentRun * percentPerRun + curRunPerf); curProgress = (int) (currentRun * percentPerRun + curRunPerf);
} else if (this.goParams.getTerminator() instanceof GenerationTerminator) { } else if (this.goParams.getTerminator() instanceof GenerationTerminator) {
double curRunPerf = pop.getGeneration()*percentPerRun/(double)((GenerationTerminator)this.goParams.getTerminator()).getGenerations(); double curRunPerf = pop.getGeneration() * percentPerRun / (double) ((GenerationTerminator) this.goParams.getTerminator()).getGenerations();
curProgress = (int)(currentRun * percentPerRun + curRunPerf); curProgress = (int) (currentRun * percentPerRun + curRunPerf);
} else curProgress = (int)(currentRun * percentPerRun); } else {
return curProgress; curProgress = (int) (currentRun * percentPerRun);
}
return curProgress;
} }
/** /**
* This method allows an optimizer to register a change in the optimizer. * This method allows an optimizer to register a change in the optimizer.
* Send some information to the statistics module and update the progress. * Send some information to the statistics module and update the progress.
@ -357,30 +382,32 @@ public class Processor extends Thread implements InterfaceProcessor, InterfacePo
* @param name Could be used to indicate the nature 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) {
if (name.equals(Population.nextGenerationPerformed)) { if (name.equals(Population.nextGenerationPerformed)) {
// System.out.println(getGOParams().getOptimizer().getPopulation().getFunctionCalls() + " " + getGOParams().getOptimizer().getPopulation().getBestFitness()[0]); // System.out.println(getGOParams().getOptimizer().getPopulation().getFunctionCalls() + " " + getGOParams().getOptimizer().getPopulation().getBestFitness()[0]);
m_Statistics.createNextGenerationPerformed( m_Statistics.createNextGenerationPerformed(
(PopulationInterface)this.goParams.getOptimizer().getPopulation(), (PopulationInterface) this.goParams.getOptimizer().getPopulation(),
this.goParams.getOptimizer(), this.goParams.getOptimizer(),
getInformerList()); getInformerList());
if (m_ListenerModule != null) { if (m_ListenerModule != null) {
m_ListenerModule.updateProgress( m_ListenerModule.updateProgress(
getStatusPercent( getStatusPercent(
goParams.getOptimizer().getPopulation(), goParams.getOptimizer().getPopulation(),
runCounter, runCounter,
m_Statistics.getStatisticsParameter().getMultiRuns()), m_Statistics.getStatisticsParameter().getMultiRuns()),
null); null);
} }
} }
} }
protected List<InterfaceAdditionalPopulationInformer> getInformerList() { protected List<InterfaceAdditionalPopulationInformer> getInformerList() {
Vector<InterfaceAdditionalPopulationInformer> informerList = new Vector<InterfaceAdditionalPopulationInformer>(2); Vector<InterfaceAdditionalPopulationInformer> informerList = new Vector<InterfaceAdditionalPopulationInformer>(2);
informerList.add(this.goParams.getProblem()); informerList.add(this.goParams.getProblem());
if (this.goParams.getOptimizer() instanceof InterfaceAdditionalPopulationInformer) informerList.add((InterfaceAdditionalPopulationInformer)this.goParams.getOptimizer()); if (this.goParams.getOptimizer() instanceof InterfaceAdditionalPopulationInformer) {
return informerList; informerList.add((InterfaceAdditionalPopulationInformer) this.goParams.getOptimizer());
}
return informerList;
} }
/** This method writes Data to file. /** This method writes Data to file.
* @param line The line that is to be added to the file * @param line The line that is to be added to the file
*/ */
@ -395,20 +422,19 @@ public class Processor extends Thread implements InterfaceProcessor, InterfacePo
// System.err.println("Problems writing to output file!"); // System.err.println("Problems writing to output file!");
// } // }
// } // }
public String getInfoString() { public String getInfoString() {
//StringBuffer sb = new StringBuffer("processing "); //StringBuffer sb = new StringBuffer("processing ");
StringBuffer sb = new StringBuffer(this.goParams.getProblem().getName()); StringBuilder sb = new StringBuilder(this.goParams.getProblem().getName());
sb.append("+"); sb.append("+");
sb.append(this.goParams.getOptimizer().getName()); sb.append(this.goParams.getOptimizer().getName());
// commented out because the number of multi-runs can be changed after start // commented out because the number of multi-runs can be changed after start
// so it might create misinformation (would still be the user's fault, though) // so it might create misinformation (would still be the user's fault, though)
// sb.append(" for "); // sb.append(" for ");
// sb.append(m_Statistics.getStatistisParameter().getMultiRuns()); // sb.append(m_Statistics.getStatistisParameter().getMultiRuns());
// sb.append(" runs"); // sb.append(" runs");
return sb.toString(); return sb.toString();
} }
/** /**
* This method return the Statistics object. * This method return the Statistics object.
*/ */
@ -422,24 +448,28 @@ public class Processor extends Thread implements InterfaceProcessor, InterfacePo
public InterfaceGOParameters getGOParams() { public InterfaceGOParameters getGOParams() {
return goParams; return goParams;
} }
public void setGOParams(InterfaceGOParameters params) { public void setGOParams(InterfaceGOParameters params) {
if (params!=null) goParams= params; if (params != null) {
else System.err.println("Setting parameters failed (parameters were null) (Processor.setGOParams)"); goParams = params;
} else {
System.err.println("Setting parameters failed (parameters were null) (Processor.setGOParams)");
}
} }
/** /**
* Return the last solution population or null if there is none available. * Return the last solution population or null if there is none available.
* *
* @return the last solution population or null * @return the last solution population or null
*/ */
public Population getResultPopulation() { public Population getResultPopulation() {
return resPop; return resPop;
} }
public Population performPostProcessing() { public Population performPostProcessing() {
return performPostProcessing((PostProcessParams)goParams.getPostProcessParams(), (InterfaceTextListener)m_Statistics); return performPostProcessing((PostProcessParams) goParams.getPostProcessParams(), (InterfaceTextListener) m_Statistics);
} }
/** /**
* Perform a post processing step with given parameters, based on all solutions found by the optimizer. * Perform a post processing step with given parameters, based on all solutions found by the optimizer.
* Use getResultPopulation() to retrieve results. * Use getResultPopulation() to retrieve results.
@ -448,31 +478,35 @@ public class Processor extends Thread implements InterfaceProcessor, InterfacePo
* @param listener * @param listener
*/ */
public Population performPostProcessing(PostProcessParams ppp, InterfaceTextListener listener) { public Population performPostProcessing(PostProcessParams ppp, InterfaceTextListener listener) {
if (ppp.isDoPostProcessing()) { if (ppp.isDoPostProcessing()) {
if (listener != null) { if (listener != null) {
listener.println("Post processing params: " + BeanInspector.toString(ppp)); listener.println("Post processing params: " + BeanInspector.toString(ppp));
// if textwindow was closed, check if it should be reopened for pp // if textwindow was closed, check if it should be reopened for pp
if (m_Statistics instanceof StatisticsWithGUI) ((StatisticsWithGUI)m_Statistics).maybeShowProxyPrinter(); if (m_Statistics instanceof StatisticsWithGUI) {
} ((StatisticsWithGUI) m_Statistics).maybeShowProxyPrinter();
Population resultPop = (Population)(goParams.getOptimizer().getAllSolutions().getSolutions().clone()); }
if (resultPop.getFunctionCalls() != goParams.getOptimizer().getPopulation().getFunctionCalls()) { }
// System.err.println("bad case in Processor::performNewPostProcessing "); Population resultPop = (Population) (goParams.getOptimizer().getAllSolutions().getSolutions().clone());
resultPop.SetFunctionCalls(goParams.getOptimizer().getPopulation().getFunctionCalls()); if (resultPop.getFunctionCalls() != goParams.getOptimizer().getPopulation().getFunctionCalls()) {
} // System.err.println("bad case in Processor::performNewPostProcessing ");
resultPop.SetFunctionCalls(goParams.getOptimizer().getPopulation().getFunctionCalls());
}
// if (!resultPop.contains(m_Statistics.getBestSolution())) { // if (!resultPop.contains(m_Statistics.getBestSolution())) {
// resultPop.add(m_Statistics.getBestSolution()); // resultPop.add(m_Statistics.getBestSolution());
// this is a minor cheat but guarantees that the best solution ever found is contained in the final results // this is a minor cheat but guarantees that the best solution ever found is contained in the final results
// This was evil in case multiple runs were performed with PP, because the best of an earlier run is added which is confusing. // This was evil in case multiple runs were performed with PP, because the best of an earlier run is added which is confusing.
// the minor cheat should not be necessary anymore anyways, since the getAllSolutions() variant replaced the earlier getPopulation() call // the minor cheat should not be necessary anymore anyways, since the getAllSolutions() variant replaced the earlier getPopulation() call
// resultPop.synchSize(); // resultPop.synchSize();
// } // }
PostProcess.checkAccuracy((AbstractOptimizationProblem)goParams.getProblem(), resultPop, ppp.getAccuracies(), ppp.getAccAssumeConv(), PostProcess.checkAccuracy((AbstractOptimizationProblem) goParams.getProblem(), resultPop, ppp.getAccuracies(), ppp.getAccAssumeConv(),
-1, ppp.getAccMaxEval(), (SolutionHistogram[]) null, true, listener); -1, ppp.getAccMaxEval(), (SolutionHistogram[]) null, true, listener);
resultPop = PostProcess.postProcess(ppp, resultPop, (AbstractOptimizationProblem)goParams.getProblem(), listener); resultPop = PostProcess.postProcess(ppp, resultPop, (AbstractOptimizationProblem) goParams.getProblem(), listener);
resPop = resultPop; resPop = resultPop;
return resultPop; return resultPop;
} else return null; } else {
return null;
}
} }
} }

View File

@ -11,12 +11,7 @@ import java.util.HashMap;
* $Date: 2007-11-08 17:24:53 +0100 (Thu, 08 Nov 2007) $ * $Date: 2007-11-08 17:24:53 +0100 (Thu, 08 Nov 2007) $
* $Author: mkron $ * $Author: mkron $
*/ */
/*==========================================================================*
* IMPORTS
*==========================================================================*/
/*==========================================================================*
* CLASS DECLARATION
*==========================================================================*/
/** /**
* *
*/ */
@ -55,6 +50,7 @@ public class EVAERROR {
static public void WARNING(String Message) { static public void WARNING(String Message) {
// if (MAIL_ON_WARNING) // if (MAIL_ON_WARNING)
// EVAMail.SendMail("EvA EXIT on ERROR !! ",Message,"ulmerh@informatik.uni-tuebingen.de"); // EVAMail.SendMail("EvA EXIT on ERROR !! ",Message,"ulmerh@informatik.uni-tuebingen.de");
System.err.println("WARNING: "+Message); System.err.println("WARNING: "+Message);
System.out.flush(); System.out.flush();
System.err.flush(); System.err.flush();
@ -71,7 +67,7 @@ public class EVAERROR {
if (!errMap.containsKey(msg)) { if (!errMap.containsKey(msg)) {
System.err.println(msg); System.err.println(msg);
errMap.put(msg, new Boolean(true)); errMap.put(msg, true);
} }
} }