Several fixes and refactoring.

This commit is contained in:
Fabian Becker 2013-10-11 15:41:33 +02:00
parent 1f81075aee
commit 77e0e3ae73
14 changed files with 136 additions and 329 deletions

View File

@ -119,7 +119,7 @@ public class OptimizerRunnable implements Runnable {
} }
public void setStats(InterfaceStatistics stats) { public void setStats(InterfaceStatistics stats) {
if (proc.isOptRunning()) { if (proc.isOptimizationRunning()) {
throw new RuntimeException("Error - cannot change statistics instance during optimization."); throw new RuntimeException("Error - cannot change statistics instance during optimization.");
} }
InterfaceOptimizationParameters params = proc.getGOParams(); InterfaceOptimizationParameters params = proc.getGOParams();
@ -156,10 +156,10 @@ public class OptimizerRunnable implements Runnable {
proc.performPostProcessing((PostProcessParams)proc.getGOParams().getPostProcessParams(), listener); proc.performPostProcessing((PostProcessParams)proc.getGOParams().getPostProcessParams(), listener);
} else { } else {
if (doRestart) { if (doRestart) {
proc.restartOpt(); proc.restartOptimization();
} }
else { else {
proc.startOpt(); proc.startOptimization();
} }
proc.runOptOnce(); proc.runOptOnce();
} }
@ -188,11 +188,11 @@ public class OptimizerRunnable implements Runnable {
} }
public void restartOpt() { public void restartOpt() {
proc.restartOpt(); proc.restartOptimization();
} }
public void stopOpt() { public void stopOpt() {
proc.stopOpt(); proc.stopOptimization();
} }
public IndividualInterface getResult() { public IndividualInterface getResult() {

View File

@ -93,7 +93,7 @@ public class Main implements OptimizationStateListener {
Reflections reflections = new Reflections("eva2.optimization.problems"); Reflections reflections = new Reflections("eva2.optimization.problems");
Set<Class<? extends InterfaceOptimizationProblem>> problems = reflections.getSubTypesOf(InterfaceOptimizationProblem.class); Set<Class<? extends InterfaceOptimizationProblem>> problems = reflections.getSubTypesOf(InterfaceOptimizationProblem.class);
for(Class<? extends InterfaceOptimizationProblem> problem : problems) { for(Class<? extends InterfaceOptimizationProblem> problem : problems) {
// We only want instantiable classes.ya // We only want instantiable classes
if(problem.isInterface() || Modifier.isAbstract(problem.getModifiers())) { if(problem.isInterface() || Modifier.isAbstract(problem.getModifiers())) {
continue; continue;
} }
@ -108,8 +108,16 @@ public class Main implements OptimizationStateListener {
} }
public static void main(String[] args) { public static void main(String[] args) {
/**
* Default command line options only require help or optimizer.
* Later we build extended command line options depending on
* the selected optimizer.
*/
Options defaultOptions = createDefaultCommandLineOptions(); Options defaultOptions = createDefaultCommandLineOptions();
/**
* Parse default options.
*/
CommandLineParser cliParser = new BasicParser(); CommandLineParser cliParser = new BasicParser();
CommandLine commandLine = null; CommandLine commandLine = null;
try { try {
@ -119,6 +127,9 @@ public class Main implements OptimizationStateListener {
System.exit(-1); System.exit(-1);
} }
/**
* Process help and help sub pages.
*/
if(commandLine.hasOption("help")) { if(commandLine.hasOption("help")) {
String helpOption = commandLine.getOptionValue("help"); String helpOption = commandLine.getOptionValue("help");
if("optimizer".equals(helpOption)) { if("optimizer".equals(helpOption)) {
@ -129,6 +140,8 @@ public class Main implements OptimizationStateListener {
showHelp(defaultOptions); showHelp(defaultOptions);
} }
} }
} }
private static void showOptimizerHelp() { private static void showOptimizerHelp() {

View File

@ -5,6 +5,7 @@ import eva2.optimization.tools.FileTools;
import eva2.tools.BasicResourceLoader; import eva2.tools.BasicResourceLoader;
import eva2.tools.EVAHELP; import eva2.tools.EVAHELP;
import eva2.tools.SerializedObject; import eva2.tools.SerializedObject;
import org.reflections.Reflections;
import java.awt.*; import java.awt.*;
import java.awt.event.ActionEvent; import java.awt.event.ActionEvent;
@ -17,10 +18,9 @@ import java.beans.PropertyChangeSupport;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
import java.lang.reflect.Proxy; import java.lang.reflect.Proxy;
import java.util.ArrayList; import java.util.*;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Vector; import java.util.logging.Logger;
import javax.swing.*; import javax.swing.*;
import javax.swing.plaf.basic.BasicComboBoxRenderer; import javax.swing.plaf.basic.BasicComboBoxRenderer;
@ -28,6 +28,7 @@ import javax.swing.plaf.basic.BasicComboBoxRenderer;
* *
*/ */
public class GOEPanel extends JPanel implements ItemListener { public class GOEPanel extends JPanel implements ItemListener {
private static final Logger LOGGER = Logger.getLogger(GOEPanel.class.getName());
private Object backupObject; private Object backupObject;
private PropertyChangeSupport propChangeSupport; private PropertyChangeSupport propChangeSupport;
@ -311,6 +312,7 @@ public class GOEPanel extends JPanel implements ItemListener {
List<String> classesLongNames; List<String> classesLongNames;
ArrayList<Class<?>> instances = new ArrayList<Class<?>>(5); ArrayList<Class<?>> instances = new ArrayList<Class<?>>(5);
classesLongNames = GenericObjectEditor.getClassesFromProperties(genericObjectEditor.getClassType().getName(), instances); classesLongNames = GenericObjectEditor.getClassesFromProperties(genericObjectEditor.getClassType().getName(), instances);
LOGGER.finest("Selected type for GOEPanel: " + genericObjectEditor.getClassType().getName());
if (classesLongNames.size() > 1) { if (classesLongNames.size() > 1) {
classNameMap = new HashMap<String, String>(); classNameMap = new HashMap<String, String>();
for (String className : classesLongNames) { for (String className : classesLongNames) {

View File

@ -11,17 +11,17 @@ public interface InterfaceProcessor {
/** /**
* Start optimization. * Start optimization.
*/ */
void startOpt(); void startOptimization();
/** /**
* Restart optimization. * Restart optimization.
*/ */
void restartOpt(); void restartOptimization();
/** /**
* Stop optimization if running. * Stop optimization if running.
*/ */
void stopOpt(); void stopOptimization();
/** /**
* Adds a new OptimizationStateListener. * Adds a new OptimizationStateListener.

View File

@ -48,22 +48,12 @@ abstract public class AbstractModuleAdapter implements ModuleAdapter, Serializab
} }
} }
/**
* Get the name of the current adapter.
*
* @return The adapter name
*/
@Override
public String getAdapterName() {
return adapterName;
}
/** /**
* Start optimization on processor. * Start optimization on processor.
*/ */
@Override @Override
public void startOptimization() { public void startOptimization() {
processor.startOpt(); processor.startOptimization();
} }
/** /**
@ -71,7 +61,7 @@ abstract public class AbstractModuleAdapter implements ModuleAdapter, Serializab
*/ */
@Override @Override
public void restartOptimization() { public void restartOptimization() {
processor.restartOpt(); processor.restartOptimization();
} }
/** /**
@ -80,7 +70,7 @@ abstract public class AbstractModuleAdapter implements ModuleAdapter, Serializab
@Override @Override
public void stopOptimization() { public void stopOptimization() {
// This means user break // This means user break
processor.stopOpt(); processor.stopOptimization();
} }
/** /**
@ -124,7 +114,7 @@ abstract public class AbstractModuleAdapter implements ModuleAdapter, Serializab
public boolean isOptRunning() { public boolean isOptRunning() {
if ((processor != null) && (processor instanceof Processor)) { if ((processor != null) && (processor instanceof Processor)) {
return ((Processor) processor).isOptRunning(); return ((Processor) processor).isOptimizationRunning();
} else { } else {
return false; return false;
} }
@ -156,24 +146,6 @@ abstract public class AbstractModuleAdapter implements ModuleAdapter, Serializab
return hasConnection; return hasConnection;
} }
/**
*
*/
@Override
public void setRemoteThis(ModuleAdapter x) {
remoteModuleAdapter = x;
}
/**
* Returns the host name.
*
* @return The host name
*/
@Override
public String getHostName() {
return hostName;
}
/** /**
* *
*/ */

View File

@ -85,7 +85,7 @@ public class GenericModuleAdapter extends AbstractModuleAdapter implements Seria
EvATabbedFrameMaker frmMkr = new EvATabbedFrameMaker(); EvATabbedFrameMaker frmMkr = new EvATabbedFrameMaker();
InterfaceStatisticsParameter Stat = ((StatisticsWithGUI) statisticsModule).getStatisticsParameter(); InterfaceStatisticsParameter Stat = ((StatisticsWithGUI) statisticsModule).getStatisticsParameter();
EvAModuleButtonPanelMaker ButtonPanel = new EvAModuleButtonPanelMaker(remoteModuleAdapter, ((Processor) processor).isOptRunning()); EvAModuleButtonPanelMaker ButtonPanel = new EvAModuleButtonPanelMaker(remoteModuleAdapter, ((Processor) processor).isOptimizationRunning());
ButtonPanel.setHelperFilename(helperFilename); ButtonPanel.setHelperFilename(helperFilename);
frmMkr.addPanelMaker(ButtonPanel); frmMkr.addPanelMaker(ButtonPanel);
InterfaceOptimizationParameters goParams = ((Processor) processor).getGOParams(); InterfaceOptimizationParameters goParams = ((Processor) processor).getGOParams();

View File

@ -34,8 +34,6 @@ public interface ModuleAdapter extends OptimizationStateListener {
void stopOptimization(); void stopOptimization();
//void runScript();
/** /**
* Return true if post processing is available in principle, else false. * Return true if post processing is available in principle, else false.
* *
@ -52,13 +50,7 @@ public interface ModuleAdapter extends OptimizationStateListener {
void addOptimizationStateListener(OptimizationStateListener x); void addOptimizationStateListener(OptimizationStateListener x);
String getAdapterName();
void setConnection(boolean flag); void setConnection(boolean flag);
boolean hasConnection(); boolean hasConnection();
void setRemoteThis(ModuleAdapter x);
String getHostName();
} }

View File

@ -16,14 +16,11 @@ import java.util.logging.Level;
/** /**
* Created by IntelliJ IDEA. * OptimizationParamers for configuration of an
* Copyright: Copyright (c) 2003 * optimization run.
* Company: University of Tuebingen, Computer Architecture
* *
* @author Holger Ulmer, Felix Streichert, Hannes Planatscher * This class is used to generate the default GUI
* @version: $Revision: 306 $ * configuration panel for optimizations.
* $Date: 2007-12-04 14:22:52 +0100 (Tue, 04 Dec 2007) $
* $Author: mkron $
*/ */
public class OptimizationParameters extends AbstractOptimizationParameters implements InterfaceOptimizationParameters, Serializable { public class OptimizationParameters extends AbstractOptimizationParameters implements InterfaceOptimizationParameters, Serializable {
@ -34,7 +31,7 @@ public class OptimizationParameters extends AbstractOptimizationParameters imple
/** /**
* Create an instance from a given serialized parameter file. * Create an instance from a given serialized parameter file.
* *
* @param serParamFile * @param serParamFile Serialized Parameter File
* @param casually if true, standard parameters are used quietly if the params cannot be loaded * @param casually if true, standard parameters are used quietly if the params cannot be loaded
* @return a OptimizationParameters instance * @return a OptimizationParameters instance
*/ */

View File

@ -47,23 +47,19 @@ public class Processor extends Thread implements InterfaceProcessor, InterfacePo
private static final Logger LOGGER = Logger.getLogger(Processor.class.getName()); private static final Logger LOGGER = Logger.getLogger(Processor.class.getName());
private volatile boolean isOptimizationRunning; private volatile boolean isOptimizationRunning;
private InterfaceStatistics m_Statistics; private InterfaceStatistics statistics;
private InterfaceOptimizationParameters goParams; private InterfaceOptimizationParameters optimizationParameters;
private boolean m_createInitialPopulations = true; private boolean createInitialPopulations = true;
private boolean saveParams = true; private boolean saveParams = true;
private OptimizationStateListener optimizationStateListener; private OptimizationStateListener optimizationStateListener;
private boolean wasRestarted = false; private boolean wasRestarted = false;
private int runCounter = 0; private int runCounter = 0;
private Population resPop = null; private Population resultPopulation = null;
private boolean userAborted = false; private boolean userAborted = false;
@Override @Override
public void addListener(OptimizationStateListener module) { public void addListener(OptimizationStateListener module) {
LOGGER.log( LOGGER.log(Level.FINEST, "Processor: setting module as listener: " + ((module == null) ? "null" : module.toString()));
Level.FINEST,
"Processor: setting module as listener: " + ((module == null)
? "null" : module.toString()));
optimizationStateListener = module; optimizationStateListener = module;
} }
@ -73,25 +69,25 @@ public class Processor extends Thread implements InterfaceProcessor, InterfacePo
* *
* @see InterfaceNotifyOnInformers * @see InterfaceNotifyOnInformers
*/ */
public Processor(InterfaceStatistics Stat, ModuleAdapter moduleAdapter, InterfaceOptimizationParameters params) { public Processor(InterfaceStatistics statistics, ModuleAdapter moduleAdapter, InterfaceOptimizationParameters optimizationParameters) {
goParams = params; this.optimizationParameters = optimizationParameters;
m_Statistics = Stat; this.statistics = statistics;
optimizationStateListener = moduleAdapter; optimizationStateListener = moduleAdapter;
// 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 (statistics != null && (optimizationParameters != null)) {
if (Stat.getStatisticsParameter() instanceof InterfaceNotifyOnInformers) { if (statistics.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())); optimizationParameters.addInformableInstance((InterfaceNotifyOnInformers) (statistics.getStatisticsParameter()));
} }
} }
} }
public boolean isOptRunning() { public boolean isOptimizationRunning() {
return isOptimizationRunning; return isOptimizationRunning;
} }
protected void setOptRunning(boolean bRun) { protected void setOptimizationRunning(boolean bRun) {
isOptimizationRunning = bRun; isOptimizationRunning = bRun;
} }
@ -108,16 +104,16 @@ public class Processor extends Thread implements InterfaceProcessor, InterfacePo
* *
*/ */
@Override @Override
public void startOpt() { public void startOptimization() {
m_createInitialPopulations = true; createInitialPopulations = true;
if (isOptRunning()) { if (isOptimizationRunning()) {
LOGGER.log(Level.SEVERE, "Processor is already running."); LOGGER.log(Level.WARNING, "Processor is already running.");
return; return;
} }
resPop = null; resultPopulation = null;
userAborted = false; userAborted = false;
wasRestarted = false; wasRestarted = false;
setOptRunning(true); setOptimizationRunning(true);
} }
/** /**
@ -134,23 +130,23 @@ public class Processor extends Thread implements InterfaceProcessor, InterfacePo
* *
*/ */
@Override @Override
public void restartOpt() { public void restartOptimization() {
m_createInitialPopulations = false; createInitialPopulations = false;
if (isOptRunning()) { if (isOptimizationRunning()) {
LOGGER.log(Level.SEVERE, "Processor is already running."); LOGGER.log(Level.WARNING, "Processor is already running.");
return; return;
} }
userAborted = false; userAborted = false;
wasRestarted = true; wasRestarted = true;
setOptRunning(true); setOptimizationRunning(true);
} }
/** /**
* *
*/ */
@Override @Override
public void stopOpt() { // this means user break public void stopOptimization() { // this means user break
setOptRunning(false); setOptimizationRunning(false);
} }
/** /**
@ -172,16 +168,16 @@ public class Processor extends Thread implements InterfaceProcessor, InterfacePo
public Population runOptOnce() { public Population runOptOnce() {
try { try {
EVAERROR.clearMsgCache(); EVAERROR.clearMsgCache();
while (isOptRunning()) { while (isOptimizationRunning()) {
setPriority(3); setPriority(3);
if (saveParams) { if (saveParams) {
try { try {
goParams.saveInstance(); optimizationParameters.saveInstance();
} catch (Exception e) { } catch (Exception e) {
System.err.println("Error on saveInstance!"); System.err.println("Error on saveInstance!");
} }
} }
resPop = optimize("Run"); resultPopulation = this.optimize();
setPriority(1); setPriority(1);
} }
} catch (Exception e) { } catch (Exception e) {
@ -196,29 +192,29 @@ public class Processor extends Thread implements InterfaceProcessor, InterfacePo
} catch (Exception ex) { } catch (Exception ex) {
} catch (Error error) { } catch (Error error) {
} }
//m_Statistics.stopOptPerformed(false); //statistics.stopOptPerformed(false);
setOptRunning(false); // normal finish setOptimizationRunning(false); // normal finish
if (optimizationStateListener != null) { if (optimizationStateListener != null) {
optimizationStateListener.performedStop(); // is only needed in client server mode optimizationStateListener.performedStop(); // is only needed in client server mode
optimizationStateListener.updateProgress(0, errMsg); optimizationStateListener.updateProgress(0, errMsg);
} }
} }
return resPop; return resultPopulation;
} }
/** /**
* Main optimization loop. Return a population containing the solutions of * Main optimization loop. Return a population containing the solutions of
* the last run if there were multiple. * the last run if there were multiple.
*/ */
protected Population optimize(String infoString) { protected Population optimize() {
Population resultPop = null; Population resultPop = null;
if (!isOptRunning()) { if (!isOptimizationRunning()) {
System.err.println("warning, this shouldnt happen in processor! Was startOptimization called?"); System.err.println("warning, this shouldnt happen in processor! Was startOptimization called?");
setOptRunning(true); setOptimizationRunning(true);
} }
RNG.setRandomSeed(goParams.getSeed()); RNG.setRandomSeed(optimizationParameters.getSeed());
if (optimizationStateListener != null) { if (optimizationStateListener != null) {
if (wasRestarted) { if (wasRestarted) {
@ -228,67 +224,67 @@ public class Processor extends Thread implements InterfaceProcessor, InterfacePo
} }
} }
goParams.getOptimizer().addPopulationChangedEventListener(this); optimizationParameters.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 (isOptimizationRunning() && (runCounter < statistics.getStatisticsParameter().getMultiRuns())) {
m_Statistics.startOptPerformed(getInfoString(), runCounter, goParams, getInformerList()); statistics.startOptPerformed(getInfoString(), runCounter, optimizationParameters, getInformerList());
this.goParams.getProblem().initializeProblem(); this.optimizationParameters.getProblem().initializeProblem();
this.goParams.getOptimizer().setProblem(this.goParams.getProblem()); this.optimizationParameters.getOptimizer().setProblem(this.optimizationParameters.getProblem());
this.goParams.getTerminator().init(this.goParams.getProblem()); this.optimizationParameters.getTerminator().init(this.optimizationParameters.getProblem());
maybeInitParamCtrl(goParams); maybeInitParamCtrl(optimizationParameters);
if (this.m_createInitialPopulations) { if (this.createInitialPopulations) {
this.goParams.getOptimizer().init(); this.optimizationParameters.getOptimizer().init();
} }
//m_Statistics.createNextGenerationPerformed((PopulationInterface)this.m_ModulParameter.getOptimizer().getPopulation()); //statistics.createNextGenerationPerformed((PopulationInterface)this.m_ModulParameter.getOptimizer().getPopulation());
if (optimizationStateListener != null) { if (optimizationStateListener != null) {
optimizationStateListener.updateProgress(getStatusPercent(goParams.getOptimizer().getPopulation(), runCounter, m_Statistics.getStatisticsParameter().getMultiRuns()), null); optimizationStateListener.updateProgress(getStatusPercent(optimizationParameters.getOptimizer().getPopulation(), runCounter, statistics.getStatisticsParameter().getMultiRuns()), null);
} }
if (popLog != null) { if (popLog != null) {
EVAHELP.clearLog(popLog); EVAHELP.clearLog(popLog);
} }
do { // main loop do { // main loop
maybeUpdateParamCtrl(goParams); maybeUpdateParamCtrl(optimizationParameters);
this.goParams.getOptimizer().optimize(); this.optimizationParameters.getOptimizer().optimize();
// registerPopulationStateChanged *SHOULD* be fired by the optimizer or resp. the population // registerPopulationStateChanged *SHOULD* be fired by the optimizer or resp. the population
// as we are event listener // as we are event listener
if (popLog != null) { if (popLog != null) {
EVAHELP.logString(this.goParams.getOptimizer().getPopulation().getIndyList(), popLog); EVAHELP.logString(this.optimizationParameters.getOptimizer().getPopulation().getIndyList(), popLog);
} }
} }
while (isOptRunning() && !this.goParams.getTerminator().isTerminated(this.goParams.getOptimizer().getAllSolutions())); while (isOptimizationRunning() && !this.optimizationParameters.getTerminator().isTerminated(this.optimizationParameters.getOptimizer().getAllSolutions()));
runCounter++; runCounter++;
maybeFinishParamCtrl(goParams); maybeFinishParamCtrl(optimizationParameters);
userAborted = !isOptRunning(); // stop is "normal" if opt wasnt set false by the user (and thus still true) userAborted = !isOptimizationRunning(); // stop is "normal" if opt wasnt set false by the user (and thus still true)
//////////////// Default stats //////////////// Default stats
m_Statistics.stopOptPerformed(!userAborted, goParams.getTerminator().lastTerminationMessage()); // stop is "normal" if opt wasnt set false by the user (and thus still true) statistics.stopOptPerformed(!userAborted, optimizationParameters.getTerminator().lastTerminationMessage()); // stop is "normal" if opt wasnt set false by the user (and thus still true)
//////////////// PP or set results without further PP //////////////// PP or set results without further PP
if (!userAborted) { if (!userAborted) {
resultPop = performPostProcessing(); resultPop = performPostProcessing();
if (resultPop == null) { // post processing disabled, so use opt. solutions if (resultPop == null) { // post processing disabled, so use opt. solutions
resultPop = goParams.getOptimizer().getAllSolutions().getSolutions(); resultPop = optimizationParameters.getOptimizer().getAllSolutions().getSolutions();
} }
} else { } else {
resultPop = goParams.getOptimizer().getAllSolutions().getSolutions(); resultPop = optimizationParameters.getOptimizer().getAllSolutions().getSolutions();
} }
m_Statistics.postProcessingPerformed(resultPop); statistics.postProcessingPerformed(resultPop);
} }
setOptRunning(false); // normal finish setOptimizationRunning(false); // normal finish
if (optimizationStateListener != null) { if (optimizationStateListener != null) {
optimizationStateListener.performedStop(); // is only needed in client server mode optimizationStateListener.performedStop(); // is only needed in client server mode
} }
if (optimizationStateListener != null) { if (optimizationStateListener != null) {
optimizationStateListener.updateProgress(0, null); optimizationStateListener.updateProgress(0, null);
} }
goParams.getOptimizer().removePopulationChangedEventListener(this); optimizationParameters.getOptimizer().removePopulationChangedEventListener(this);
return resultPop; return resultPop;
} }
@ -361,11 +357,11 @@ public class Processor extends Thread implements InterfaceProcessor, InterfacePo
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.optimizationParameters.getTerminator() instanceof EvaluationTerminator) {
double curRunPerf = pop.getFunctionCalls() * percentPerRun / (double) ((EvaluationTerminator) this.goParams.getTerminator()).getFitnessCalls(); double curRunPerf = pop.getFunctionCalls() * percentPerRun / (double) ((EvaluationTerminator) this.optimizationParameters.getTerminator()).getFitnessCalls();
curProgress = (int) (currentRun * percentPerRun + curRunPerf); curProgress = (int) (currentRun * percentPerRun + curRunPerf);
} else if (this.goParams.getTerminator() instanceof GenerationTerminator) { } else if (this.optimizationParameters.getTerminator() instanceof GenerationTerminator) {
double curRunPerf = pop.getGeneration() * percentPerRun / (double) ((GenerationTerminator) this.goParams.getTerminator()).getGenerations(); double curRunPerf = pop.getGeneration() * percentPerRun / (double) ((GenerationTerminator) this.optimizationParameters.getTerminator()).getGenerations();
curProgress = (int) (currentRun * percentPerRun + curRunPerf); curProgress = (int) (currentRun * percentPerRun + curRunPerf);
} else { } else {
curProgress = (int) (currentRun * percentPerRun); curProgress = (int) (currentRun * percentPerRun);
@ -383,16 +379,16 @@ public class Processor extends Thread implements InterfaceProcessor, InterfacePo
@Override @Override
public void registerPopulationStateChanged(Object source, String name) { public void registerPopulationStateChanged(Object source, String name) {
if (name.equals(Population.NEXT_GENERATION_PERFORMED)) { if (name.equals(Population.NEXT_GENERATION_PERFORMED)) {
m_Statistics.createNextGenerationPerformed( statistics.createNextGenerationPerformed(
(PopulationInterface) this.goParams.getOptimizer().getPopulation(), (PopulationInterface) this.optimizationParameters.getOptimizer().getPopulation(),
this.goParams.getOptimizer(), this.optimizationParameters.getOptimizer(),
getInformerList()); getInformerList());
if (optimizationStateListener != null) { if (optimizationStateListener != null) {
optimizationStateListener.updateProgress( optimizationStateListener.updateProgress(
getStatusPercent( getStatusPercent(
goParams.getOptimizer().getPopulation(), optimizationParameters.getOptimizer().getPopulation(),
runCounter, runCounter,
m_Statistics.getStatisticsParameter().getMultiRuns()), statistics.getStatisticsParameter().getMultiRuns()),
null); null);
} }
} }
@ -400,9 +396,9 @@ public class Processor extends Thread implements InterfaceProcessor, InterfacePo
protected List<InterfaceAdditionalPopulationInformer> getInformerList() { protected List<InterfaceAdditionalPopulationInformer> getInformerList() {
List<InterfaceAdditionalPopulationInformer> informerList = new ArrayList<InterfaceAdditionalPopulationInformer>(2); List<InterfaceAdditionalPopulationInformer> informerList = new ArrayList<InterfaceAdditionalPopulationInformer>(2);
informerList.add(this.goParams.getProblem()); informerList.add(this.optimizationParameters.getProblem());
if (this.goParams.getOptimizer() instanceof InterfaceAdditionalPopulationInformer) { if (this.optimizationParameters.getOptimizer() instanceof InterfaceAdditionalPopulationInformer) {
informerList.add((InterfaceAdditionalPopulationInformer) this.goParams.getOptimizer()); informerList.add((InterfaceAdditionalPopulationInformer) this.optimizationParameters.getOptimizer());
} }
return informerList; return informerList;
} }
@ -426,13 +422,13 @@ public class Processor extends Thread implements InterfaceProcessor, InterfacePo
@Override @Override
public String getInfoString() { public String getInfoString() {
//StringBuffer sb = new StringBuffer("processing "); //StringBuffer sb = new StringBuffer("processing ");
StringBuilder sb = new StringBuilder(this.goParams.getProblem().getName()); StringBuilder sb = new StringBuilder(this.optimizationParameters.getProblem().getName());
sb.append("+"); sb.append("+");
sb.append(this.goParams.getOptimizer().getName()); sb.append(this.optimizationParameters.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(statistics.getStatistisParameter().getMultiRuns());
// sb.append(" runs"); // sb.append(" runs");
return sb.toString(); return sb.toString();
} }
@ -441,19 +437,19 @@ public class Processor extends Thread implements InterfaceProcessor, InterfacePo
* This method return the Statistics object. * This method return the Statistics object.
*/ */
public InterfaceStatistics getStatistics() { public InterfaceStatistics getStatistics() {
return m_Statistics; return statistics;
} }
/** /**
* These methods allow you to get and set the Module Parameters. * These methods allow you to get and set the Module Parameters.
*/ */
public InterfaceOptimizationParameters getGOParams() { public InterfaceOptimizationParameters getGOParams() {
return goParams; return optimizationParameters;
} }
public void setGOParams(InterfaceOptimizationParameters params) { public void setGOParams(InterfaceOptimizationParameters params) {
if (params != null) { if (params != null) {
goParams = params; optimizationParameters = params;
} else { } else {
System.err.println("Setting parameters failed (parameters were null) (Processor.setGOParams)"); System.err.println("Setting parameters failed (parameters were null) (Processor.setGOParams)");
} }
@ -465,11 +461,11 @@ public class Processor extends Thread implements InterfaceProcessor, InterfacePo
* @return the last solution population or null * @return the last solution population or null
*/ */
public Population getResultPopulation() { public Population getResultPopulation() {
return resPop; return resultPopulation;
} }
public Population performPostProcessing() { public Population performPostProcessing() {
return performPostProcessing((PostProcessParams) goParams.getPostProcessParams(), (InterfaceTextListener) m_Statistics); return performPostProcessing((PostProcessParams) optimizationParameters.getPostProcessParams(), (InterfaceTextListener) statistics);
} }
/** /**
@ -485,28 +481,28 @@ public class Processor extends Thread implements InterfaceProcessor, InterfacePo
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) { if (statistics instanceof StatisticsWithGUI) {
((StatisticsWithGUI) m_Statistics).maybeShowProxyPrinter(); ((StatisticsWithGUI) statistics).maybeShowProxyPrinter();
} }
} }
Population resultPop = (Population) (goParams.getOptimizer().getAllSolutions().getSolutions().clone()); Population resultPop = (Population) (optimizationParameters.getOptimizer().getAllSolutions().getSolutions().clone());
if (resultPop.getFunctionCalls() != goParams.getOptimizer().getPopulation().getFunctionCalls()) { if (resultPop.getFunctionCalls() != optimizationParameters.getOptimizer().getPopulation().getFunctionCalls()) {
// System.err.println("bad case in Processor::performNewPostProcessing "); // System.err.println("bad case in Processor::performNewPostProcessing ");
resultPop.setFunctionCalls(goParams.getOptimizer().getPopulation().getFunctionCalls()); resultPop.setFunctionCalls(optimizationParameters.getOptimizer().getPopulation().getFunctionCalls());
} }
// if (!resultPop.contains(m_Statistics.getBestSolution())) { // if (!resultPop.contains(statistics.getBestSolution())) {
// resultPop.add(m_Statistics.getBestSolution()); // resultPop.add(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) optimizationParameters.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) optimizationParameters.getProblem(), listener);
resPop = resultPop; resultPopulation = resultPop;
return resultPop; return resultPop;
} else { } else {
return null; return null;

View File

@ -41,12 +41,6 @@ public class StatisticsStandalone extends AbstractStatistics implements Interfac
private ArrayList<String> m_ResultHeaderStrings = null; private ArrayList<String> m_ResultHeaderStrings = null;
private boolean collectData = false; private boolean collectData = false;
// private boolean m_useMedian = false;
// private double m_MeanFinalFitness;
// private double m_SumLastBestCurrentFit = 0;
// private double[] m_LastBestCurrentFit;
// private double m_FitnessMedianofALL;
public StatisticsStandalone(InterfaceStatisticsParameter statParams) { public StatisticsStandalone(InterfaceStatisticsParameter statParams) {
super(); super();
@ -115,160 +109,6 @@ public class StatisticsStandalone extends AbstractStatistics implements Interfac
} }
} }
// public void startOptPerformed(String infoString, int runNumber, Object params) {
// super.startOptPerformed(infoString, runNumber, params);
// if (runNumber == 0) {
// m_Result = new ArrayList<ArrayList<Object[]>>();
// m_ResultString = new ArrayList<String>();
//// m_LastBestCurrentFit = new double[this.m_StatsParams.getMultiRuns()];
//// m_SumLastBestCurrentFit=0;
// } else {
// for (int i = 0; i < m_Result.size(); i++)
// ((ArrayList[]) m_Result.get(i))[optRunsPerformed] = new ArrayList<ArrayList<double[]>[]>();
// }
// m_InfoString = infoString;
// }
// public void stopOptPerformed(boolean normal, String stopMessage) {
// super.stopOptPerformed(normal, stopMessage);
// if (bestCurrentIndy != null) {
// m_SumLastBestCurrentFit = m_SumLastBestCurrentFit + bestCurrentIndy.getFitness()[0];
// m_LastBestCurrentFit[optRunsPerformed-1] = bestCurrentIndy.getFitness()[0];
// }
//
// //System.out.println("stopOptPerformed :"+m_OptRunsPerformed);
// if (optRunsPerformed == m_StatsParams.getMultiRuns()) {
// m_MeanFinalFitness = m_SumLastBestCurrentFit / ((double) optRunsPerformed);
// //System.out.println("m_FitnessMeanofALL "+m_FitnessMeanofALL);
// m_FitnessMedianofALL = Mathematics.median(m_LastBestCurrentFit, true);
//
//// finalizeOutput();
// }
// }
// /**
// * write result of all runs.
// */
// public static File[] writeResult_All_Container(ArrayList<StatisticsStandalone> StatList, String FileName) {
// File ret[] = new File[((StatisticsStandalone) StatList.get(0)).m_Result.size()];
// //System.out.println("StatList.size " + StatList.size());
// for (int counter = 0; counter < ret.length; counter++) {
// ArrayList<String> staticResult = new ArrayList<String>();
// String staticDescription = "calls ";
// for (int index = 0; index < StatList.size(); index++) {
// StatisticsStandalone Stat = (StatisticsStandalone) StatList.get(index);
// staticDescription = staticDescription + Stat.m_InfoString + " ";
// for (int row = 0; row < ((ArrayList[]) Stat.m_Result.get(counter))[0].size();
// row++) {
// double mean = 0;
// double calls = 0;
// double[] value = new double[((ArrayList[]) Stat.m_Result.get(counter)).
// length];
// for (int i = 0; i < ((ArrayList[]) Stat.m_Result.get(counter)).length; i++) {
// //double[] result = (double[]) Stat.m_QRestultContainer[i].get(row);
// double[] result = (double[]) ((ArrayList[]) Stat.m_Result.get(counter))[i].get(row);
// mean = mean + result[1];
// calls = result[0];
// value[i] = result[1];
// }
// //mean = mean / Stat.m_QRestultContainer.length;
// mean = mean / ((ArrayList[]) Stat.m_Result.get(counter)).length;
//// if (m_useMedian == true) // use the median
//// mean = getMedian(value);
// if (row == staticResult.size())
// staticResult.add(new String("" + calls));
// String temp = (String) staticResult.get(row);
// String newrow = new String(temp + " " + mean);
// //System.out.println("newrow"+newrow);
// staticResult.set(row, newrow);
// } // end of for row
// } // end of for index
// try {
// File d = new File(m_MyHostName);
// d.mkdir();
// String info = (String) ((StatisticsStandalone) StatList.get(0)).m_ResultString.get(counter);
// ret[counter] = new File(m_MyHostName + "//" + FileName + "_" + info + "_" + counter + ".txt");
// ret[counter].createNewFile();
// PrintWriter Out = new PrintWriter(new FileOutputStream(ret[counter]));
// Out.println(staticDescription);
// for (int i = 0; i < staticResult.size(); i++) {
// Out.println((String) staticResult.get(i));
// //System.out.println("print " + (String) staticResult.get(i));
// }
// Out.flush();
// Out.close();
// } catch (Exception e) {
// System.out.println("Error in wreiteresult" + e.getMessage());
// e.printStackTrace();
// }
// staticResult = null;
// staticDescription = "";
// }
// return ret;
// }
// /**
// * write result of all runs.
// */
// public static File writeResultErrorBar(ArrayList StatList, String FileName) {
// File ret = null;
// ArrayList staticResult = new ArrayList();
// String staticDescription = "";
// for (int index = 0; index < StatList.size(); index++) {
// StatisticsStandalone Stat = (StatisticsStandalone) StatList.get(index);
// staticDescription = staticDescription + Stat.m_InfoString + " ";
// System.out.println(" laenge m_result "+Stat.m_Result.size());
// for (int i=0;i<Stat.m_Result.size();i++) {
// ArrayList[] list = (ArrayList[])Stat.m_Result.get(i);
// System.out.println(" i "+i+" ArrayList[]" +list.length);
// for (int j=0;j<list.length;j++) {
// if (staticResult.size()==j)
// staticResult.add(new String(""));
// String temp = (String)staticResult.get(j);
// double[] x = ((double[])list[j].get(list[j].size()-1));
// temp = temp +" "+ x[1];staticResult.set(j,temp);
// //System.out.println(" list j "+j +" list[j].size "+ list[j].size());
// //System.out.println(" x "+x[0]+ " " + x.length);
//
// }
// }
// } // end of for index
// try {
// File d = new File(m_MyHostName);
// d.mkdir();
// ret = new File(m_MyHostName + "//" + "Error" + FileName + ".txt");
// ret.createNewFile();
// PrintWriter Out = new PrintWriter(new FileOutputStream(ret));
// Out.println(staticDescription);
// for (int i = 0; i < staticResult.size(); i++) {
// Out.println( (String) staticResult.get(i));
// System.out.println("print " + (String) staticResult.get(i));
// }
// Out.flush();
// Out.close();
// }
// catch (Exception e) {
// e.printStackTrace();
// }
// staticResult = null;
// staticDescription = "";
// return ret;
// }
// /**
// *
// */
// public double getBestFitnessMeanofALL() {
// return m_MeanFinalFitness;
// }
//
// /**
// *
// */
// public double getBestFitnessMedianofALL() {
// return m_FitnessMedianofALL;
// }
@Override @Override
public String getHostName() { public String getHostName() {
return m_MyHostName; return m_MyHostName;

View File

@ -35,6 +35,8 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial
protected Population population = new Population(); protected Population population = new Population();
protected transient Population children = null; protected transient Population children = null;
protected AbstractOptimizationProblem optimizationProblem = new F1Problem(); protected AbstractOptimizationProblem optimizationProblem = new F1Problem();
@Parameter(name = "DEType", description = "Mutation type for DE")
private DETypeEnum DEType; private DETypeEnum DEType;
@Parameter(name = "F", description = "Differential Weight") @Parameter(name = "F", description = "Differential Weight")

View File

@ -261,7 +261,7 @@ public class GeneticAlgorithm implements InterfaceOptimizer, java.io.Serializabl
*/ */
@Override @Override
public String getName() { public String getName() {
return "GA"; return "Genetic Algorithm";
} }
/** /**

View File

@ -40,22 +40,15 @@ public class Serializer {
*/ */
private static void store(Serializable o, OutputStream outStream, boolean serializeInMem) throws IOException { private static void store(Serializable o, OutputStream outStream, boolean serializeInMem) throws IOException {
ObjectOutputStream out = new ObjectOutputStream(outStream); ObjectOutputStream out = new ObjectOutputStream(outStream);
OutputStreamWriter out2 = new OutputStreamWriter(outStream);
try { try {
Object objToStore = o; Object objToStore = o;
if (serializeInMem) { if (serializeInMem) {
objToStore = new SerializedObject((Object) o); objToStore = new SerializedObject((Object) o);
} }
Gson gson = new Gson(); // I don't care!
//out.writeObject(objToStore);
String json = gson.toJson(o);
out2.write(json);
} catch (java.io.NotSerializableException ex) { } catch (java.io.NotSerializableException ex) {
LOGGER.log(Level.SEVERE, "Object is not serializable!", ex); LOGGER.log(Level.SEVERE, "Object is not serializable!", ex);
} }
out2.flush();
out2.close();
} }
/** /**

View File

@ -22,9 +22,9 @@ public class RNG {
/** /**
* *
*/ */
public static void setRandomSeed(long new_seed) { public static void setRandomSeed(long newSeed) {
// counter++; // counter++;
randomSeed = new_seed; randomSeed = newSeed;
if (randomSeed == 0) { if (randomSeed == 0) {
setRandomSeed(); setRandomSeed();
} else { } else {
@ -35,8 +35,8 @@ public class RNG {
/** /**
* Set the random seed without replacing zero with current system time. * Set the random seed without replacing zero with current system time.
*/ */
public static void setRandomSeedStrict(long new_seed) { public static void setRandomSeedStrict(long newSeed) {
randomSeed = new_seed; randomSeed = newSeed;
random.setSeed(randomSeed); random.setSeed(randomSeed);
} }
@ -51,8 +51,8 @@ public class RNG {
/** /**
* *
*/ */
public static void setRandom(Random base_random) { public static void setRandom(Random baseRandom) {
random = base_random; random = baseRandom;
} }
/** /**