Merge remote-tracking branch 'origin/master'

This commit is contained in:
Fabian Becker 2015-12-07 21:16:51 +01:00
commit 7da4880363
185 changed files with 1525 additions and 2114 deletions

View File

@ -68,8 +68,8 @@
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version> <version>2.3.2</version>
<configuration> <configuration>
<source>1.7</source> <source>1.8</source>
<target>1.7</target> <target>1.8</target>
</configuration> </configuration>
</plugin> </plugin>
<plugin> <plugin>

View File

@ -55,7 +55,7 @@ public class EvAInfo {
System.err.println(ex.getMessage()); System.err.println(ex.getMessage());
System.exit(1); System.exit(1);
} }
InputStream istr = BasicResourceLoader.instance().getStreamFromResourceLocation(EvAInfo.iconLocation); InputStream istr = BasicResourceLoader.getInstance().getStreamFromResourceLocation(EvAInfo.iconLocation);
if (istr == null) { if (istr == null) {
throw new RuntimeException(resourceNotFoundErrorMessage(EvAInfo.iconLocation) + " (EvAInfo.static)"); throw new RuntimeException(resourceNotFoundErrorMessage(EvAInfo.iconLocation) + " (EvAInfo.static)");
} }

View File

@ -1,11 +1,11 @@
package eva2; package eva2;
import eva2.optimization.OptimizationParameters;
import eva2.optimization.enums.DEType; import eva2.optimization.enums.DEType;
import eva2.optimization.enums.MutateESCrossoverType; import eva2.optimization.enums.MutateESCrossoverType;
import eva2.optimization.enums.PSOTopology; import eva2.optimization.enums.PSOTopology;
import eva2.optimization.enums.PostProcessMethod; import eva2.optimization.enums.PostProcessMethod;
import eva2.optimization.individuals.*; import eva2.optimization.individuals.*;
import eva2.optimization.OptimizationParameters;
import eva2.optimization.operator.archiving.ArchivingNSGAII; import eva2.optimization.operator.archiving.ArchivingNSGAII;
import eva2.optimization.operator.archiving.InformationRetrievalInserting; import eva2.optimization.operator.archiving.InformationRetrievalInserting;
import eva2.optimization.operator.archiving.InterfaceArchiving; import eva2.optimization.operator.archiving.InterfaceArchiving;

View File

@ -1,12 +1,12 @@
package eva2; package eva2;
import eva2.optimization.OptimizationStateListener;
import eva2.optimization.InterfaceOptimizationParameters; import eva2.optimization.InterfaceOptimizationParameters;
import eva2.optimization.OptimizationStateListener;
import eva2.optimization.Processor;
import eva2.optimization.individuals.IndividualInterface; import eva2.optimization.individuals.IndividualInterface;
import eva2.optimization.individuals.InterfaceDataTypeBinary; import eva2.optimization.individuals.InterfaceDataTypeBinary;
import eva2.optimization.individuals.InterfaceDataTypeDouble; import eva2.optimization.individuals.InterfaceDataTypeDouble;
import eva2.optimization.individuals.InterfaceDataTypeInteger; import eva2.optimization.individuals.InterfaceDataTypeInteger;
import eva2.optimization.Processor;
import eva2.optimization.operator.postprocess.InterfacePostProcessParams; import eva2.optimization.operator.postprocess.InterfacePostProcessParams;
import eva2.optimization.operator.postprocess.PostProcessParams; import eva2.optimization.operator.postprocess.PostProcessParams;
import eva2.optimization.operator.terminators.InterfaceTerminator; import eva2.optimization.operator.terminators.InterfaceTerminator;
@ -222,7 +222,7 @@ public class OptimizerRunnable implements Runnable {
} }
} }
public double[] getDoubleSolution() { public double[] getDoubleSolution() {
IndividualInterface indy = getResult(); IndividualInterface indy = getResult();
if (indy instanceof InterfaceDataTypeDouble) { if (indy instanceof InterfaceDataTypeDouble) {
return ((InterfaceDataTypeDouble) indy).getDoubleData(); return ((InterfaceDataTypeDouble) indy).getDoubleData();

View File

@ -2,23 +2,27 @@ package eva2.cli;
import eva2.EvAInfo; import eva2.EvAInfo;
import eva2.optimization.InterfaceOptimizationParameters; import eva2.optimization.InterfaceOptimizationParameters;
import eva2.optimization.individuals.IndividualInterface;
import eva2.optimization.OptimizationParameters; import eva2.optimization.OptimizationParameters;
import eva2.optimization.Processor; import eva2.optimization.Processor;
import eva2.optimization.individuals.IndividualInterface;
import eva2.optimization.operator.terminators.InterfaceTerminator; import eva2.optimization.operator.terminators.InterfaceTerminator;
import eva2.optimization.population.Population;
import eva2.optimization.population.PopulationInterface; import eva2.optimization.population.PopulationInterface;
import eva2.optimization.population.Population;
import eva2.optimization.statistics.*; import eva2.optimization.statistics.*;
import eva2.optimization.strategies.InterfaceOptimizer; import eva2.optimization.strategies.InterfaceOptimizer;
import eva2.problems.InterfaceAdditionalPopulationInformer; import eva2.problems.InterfaceAdditionalPopulationInformer;
import eva2.problems.InterfaceOptimizationProblem; import eva2.problems.InterfaceOptimizationProblem;
import eva2.tools.ReflectPackage; import eva2.tools.ReflectPackage;
import eva2.tools.StringTools;
import eva2.util.annotation.Description; import eva2.util.annotation.Description;
import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.Yaml;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
import java.util.*; import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/** /**
* *
@ -90,7 +94,7 @@ public class Main {
continue; continue;
} }
Description description = clazz.getAnnotation(Description.class); Description description = clazz.getAnnotation(Description.class);
System.out.printf("\t\033[1m%s\033[0m\n", type.getName()); System.out.printf("\t\033[1m%s\033[0m (%s)\n", type.getName(), StringTools.cutClassName(type.getName()));
if (description != null) { if (description != null) {
System.out.printf("\t\t%s", description.value()); System.out.printf("\t\t%s", description.value());
} else { } else {
@ -247,7 +251,7 @@ final class CommandLineStatistics implements InterfaceStatistics {
} }
@Override @Override
public void printToTextListener(String s) { public void printToTextListener(String... s) {
System.out.println(s); System.out.println(s);
} }

View File

@ -1,7 +1,7 @@
package eva2.cli; package eva2.cli;
import eva2.optimization.OptimizationStateListener;
import eva2.optimization.InterfaceOptimizationParameters; import eva2.optimization.InterfaceOptimizationParameters;
import eva2.optimization.OptimizationStateListener;
import eva2.optimization.population.InterfacePopulationChangedEventListener; import eva2.optimization.population.InterfacePopulationChangedEventListener;
import java.io.OutputStream; import java.io.OutputStream;

View File

@ -17,21 +17,27 @@ public class TerminatorExample {
double[] sol; double[] sol;
// A combined terminator for fitness and phenotype convergence // A combined terminator for fitness and phenotype convergence
CombinedTerminator convT = new CombinedTerminator( CombinedTerminator convT = new CombinedTerminator(
// fitness-based stagnation period, absolute threshold, consider stagnation // fitness-based stagnation period, absolute threshold, consider stagnation
// in both direction (per dim.) or w.r.t. minimization only // in both direction (per dim.) or w.r.t. minimization only
new FitnessConvergenceTerminator(0.0001, 1000, StagnationTypeEnum.fitnessCallBased, ChangeTypeEnum.absoluteChange, DirectionTypeEnum.decrease), new FitnessConvergenceTerminator(0.0001, 1000, StagnationTypeEnum.fitnessCallBased, ChangeTypeEnum.absoluteChange, DirectionTypeEnum.decrease),
new PhenotypeConvergenceTerminator(0.0001, 1000, StagnationTypeEnum.fitnessCallBased, ChangeTypeEnum.absoluteChange, DirectionTypeEnum.bidirectional), new PhenotypeConvergenceTerminator(0.0001, 1000, StagnationTypeEnum.fitnessCallBased, ChangeTypeEnum.absoluteChange, DirectionTypeEnum.bidirectional),
true); true
);
// Adding an evaluation terminator with OR to the convergence criterion // Adding an evaluation terminator with OR to the convergence criterion
OptimizerFactory.setTerminator(new CombinedTerminator( OptimizerFactory.setTerminator(new CombinedTerminator(
new EvaluationTerminator(20000), new EvaluationTerminator(20000),
convT, convT,
false)); false
));
sol = OptimizerFactory.optimizeToDouble(OptimizerFactory.PSO, f1, null); sol = OptimizerFactory.optimizeToDouble(OptimizerFactory.PSO, f1, null);
System.out.println(OptimizerFactory.lastEvalsPerformed() System.out.println(OptimizerFactory.lastEvalsPerformed()
+ " evals performed. " + " evals performed. "
+ OptimizerFactory.terminatedBecause() + OptimizerFactory.terminatedBecause()
+ " Found solution: "); + " Found solution: ");
for (int i = 0; i < f1.getProblemDimension(); i++) { for (int i = 0; i < f1.getProblemDimension(); i++) {
System.out.print(sol[i] + " "); System.out.print(sol[i] + " ");
} }

View File

@ -1,8 +1,8 @@
package eva2.examples; package eva2.examples;
import eva2.OptimizerFactory; import eva2.OptimizerFactory;
import eva2.optimization.individuals.AbstractEAIndividual;
import eva2.optimization.OptimizationParameters; import eva2.optimization.OptimizationParameters;
import eva2.optimization.individuals.AbstractEAIndividual;
import eva2.optimization.operator.postprocess.PostProcessParams; import eva2.optimization.operator.postprocess.PostProcessParams;
import eva2.optimization.operator.terminators.EvaluationTerminator; import eva2.optimization.operator.terminators.EvaluationTerminator;
import eva2.problems.FM0Problem; import eva2.problems.FM0Problem;

View File

@ -1,8 +1,8 @@
package eva2.examples; package eva2.examples;
import eva2.OptimizerFactory; import eva2.OptimizerFactory;
import eva2.optimization.individuals.AbstractEAIndividual;
import eva2.optimization.OptimizationParameters; import eva2.optimization.OptimizationParameters;
import eva2.optimization.individuals.AbstractEAIndividual;
import eva2.optimization.operator.crossover.CrossoverESDefault; import eva2.optimization.operator.crossover.CrossoverESDefault;
import eva2.optimization.operator.mutation.MutateESCovarianceMatrixAdaption; import eva2.optimization.operator.mutation.MutateESCovarianceMatrixAdaption;
import eva2.optimization.operator.terminators.EvaluationTerminator; import eva2.optimization.operator.terminators.EvaluationTerminator;

View File

@ -35,7 +35,7 @@ class AboutDialog extends JDialog {
setResizable(false); setResizable(false);
/* Load EvA2 Image */ /* Load EvA2 Image */
BasicResourceLoader loader = BasicResourceLoader.instance(); BasicResourceLoader loader = BasicResourceLoader.getInstance();
byte[] bytes = loader.getBytesFromResourceLocation(eva2.EvAInfo.splashLocation, true); byte[] bytes = loader.getBytesFromResourceLocation(eva2.EvAInfo.splashLocation, true);
ImageIcon imageIcon = new ImageIcon(Toolkit.getDefaultToolkit().createImage(bytes)); ImageIcon imageIcon = new ImageIcon(Toolkit.getDefaultToolkit().createImage(bytes));

View File

@ -123,12 +123,12 @@ public class EvATabbedFrameMaker implements Serializable, PanelMaker, InterfaceN
} }
} }
public JParaPanel getGOPanel() { public JParaPanel getOptimizationParametersPanel() {
try { try {
JParaPanel sP = (JParaPanel) pmContainer.get(1); JParaPanel sP = (JParaPanel) pmContainer.get(1);
return sP; return sP;
} catch (Exception e) { } catch (Exception e) {
System.err.println("Failed to get GO panel from " + this.getClass()); System.err.println("Failed to get OptimizationParameters panel from " + this.getClass());
} }
return null; return null;
} }

View File

@ -77,7 +77,7 @@ public class HtmlDemo {
return; return;
} }
JFrame frame = new JFrame(name); JFrame frame = new JFrame(name);
BasicResourceLoader loader = BasicResourceLoader.instance(); BasicResourceLoader loader = BasicResourceLoader.getInstance();
byte[] bytes = loader.getBytesFromResourceLocation(EvAInfo.iconLocation, true); byte[] bytes = loader.getBytesFromResourceLocation(EvAInfo.iconLocation, true);
frame.setIconImage(Toolkit.getDefaultToolkit().createImage(bytes)); frame.setIconImage(Toolkit.getDefaultToolkit().createImage(bytes));
JScrollPane scroller = new JScrollPane(); JScrollPane scroller = new JScrollPane();

View File

@ -14,19 +14,19 @@ public interface InterfaceSelectablePointIcon {
* *
* @param a The selection listener * @param a The selection listener
*/ */
public void addSelectionListener(InterfaceRefSolutionListener a); void addSelectionListener(InterfaceRefSolutionListener a);
/** /**
* This method allows to remove the selection listner to the PointIcon * This method allows to remove the selection listner to the PointIcon
*/ */
public void removeSelectionListeners(); void removeSelectionListeners();
/** /**
* This method returns the selection listner to the PointIcon * This method returns the selection listner to the PointIcon
* *
* @return InterfacePointIconSelectionListener * @return InterfacePointIconSelectionListener
*/ */
public InterfaceRefSolutionListener getSelectionListener(); InterfaceRefSolutionListener getSelectionListener();
/** /**
* Of course the PointIcon needs a reference to the individual * Of course the PointIcon needs a reference to the individual
@ -34,12 +34,12 @@ public interface InterfaceSelectablePointIcon {
* *
* @param indy * @param indy
*/ */
public void setEAIndividual(AbstractEAIndividual indy); void setEAIndividual(AbstractEAIndividual indy);
/** /**
* This method allows you to get the EAIndividual the icon stands for * This method allows you to get the EAIndividual the icon stands for
* *
* @return AbstractEAIndividual * @return AbstractEAIndividual
*/ */
public AbstractEAIndividual getEAIndividual(); AbstractEAIndividual getEAIndividual();
} }

View File

@ -19,9 +19,6 @@ public class JParaPanel implements Serializable, PanelMaker {
*/ */
private JPanel tempPanel = new JPanel(); private JPanel tempPanel = new JPanel();
public JParaPanel() {
}
/** /**
*/ */
public JParaPanel(Object Parameter, String name) { public JParaPanel(Object Parameter, String name) {

View File

@ -80,6 +80,7 @@ public class JTextoutputFrame implements JTextoutputFrameInterface, ActionListen
textArea.setCaretPosition(0); textArea.setCaretPosition(0);
textArea.setTabSize(16); textArea.setTabSize(16);
textArea.setFont(new Font("Courier New", Font.PLAIN, 12)); textArea.setFont(new Font("Courier New", Font.PLAIN, 12));
// Limit text output to 2500 Lines
((AbstractDocument)textArea.getDocument()).setDocumentFilter(new LineBufferDocumentFilter(textArea, 2500)); ((AbstractDocument)textArea.getDocument()).setDocumentFilter(new LineBufferDocumentFilter(textArea, 2500));

View File

@ -1,552 +1,17 @@
package eva2.gui; package eva2.gui;
import eva2.EvAInfo; import eva2.EvAInfo;
import eva2.optimization.OptimizationParameters;
import eva2.optimization.OptimizationStateListener;
import eva2.optimization.InterfaceOptimizationParameters;
import eva2.optimization.modules.*;
import eva2.optimization.statistics.AbstractStatistics;
import eva2.optimization.statistics.InterfaceStatisticsListener;
import eva2.optimization.statistics.InterfaceStatisticsParameters;
import eva2.tools.BasicResourceLoader;
import eva2.tools.EVAERROR;
import eva2.tools.ReflectPackage;
import eva2.tools.StringTools; import eva2.tools.StringTools;
import eva2.util.ClassPreloader;
import eva2.util.EvAComAdapter;
import javax.help.HelpSet;
import javax.help.JHelpContentViewer;
import javax.help.JHelpNavigator;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Set;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
/** /**
* * Main method, creates and sets up MainFrame
*/ */
public class Main extends JFrame implements OptimizationStateListener { public class Main {
/**
* Generated serial version identifier.
*/
private static final long serialVersionUID = 8232856334379977970L;
private final int splashScreenTime;
private boolean clientInited = false;
private JDesktopPane desktopPane;
private JPanel configurationPane;
private Runnable initRunnable = null;
private transient JProgressBar progressBar;
// Option
private ExtAction actPreferences;
private ExtAction actQuit;
private static final Logger LOGGER = Logger.getLogger(Main.class.getName()); private static final Logger LOGGER = Logger.getLogger(Main.class.getName());
// Configurable module:
private ModuleAdapter currentModuleAdapter = null;
// Help:
private ExtAction actHelp;
private ExtAction actAbout;
private ExtAction actLicense;
// if not null, the module is loaded automatically and no other can be selected
private String useDefaultModule = null; //"Genetic_Optimization";
// measuring optimization runtime
private long startTime = 0;
private boolean withGUI = true;
private boolean withTreeView = false;
private EvATabbedFrameMaker frameMaker = null;
private Window parentWindow;
private java.util.List<OptimizationStateListener> superListenerList = null;
private EvAComAdapter comAdapter;
public void addOptimizationStateListener(OptimizationStateListener l) {
if (superListenerList == null) {
superListenerList = new ArrayList<>();
}
superListenerList.add(l);
}
public boolean removeOptimizationStateListener(OptimizationStateListener l) {
return superListenerList != null && superListenerList.remove(l);
}
/**
* Constructor of GUI of EvA2. Works as client for the EvA2 server. Note
* that the Main initialized multi-threaded for efficiency. Use {@link #awaitClientInitialized()} }
* to await full initialization if necessary.
*/
public Main() {
this(null, false, false);
}
/**
* A constructor. Splash screen is optional, Gui is activated, no parent
* window. Note that the Main initialized multi-threaded for
* efficiency. Use {@link #awaitClientInitialized()} to await full
* initialization if necessary.
*
* @param paramsFile
* @param autorun
* @param nosplash
*/
public Main(final String paramsFile, boolean autorun, boolean nosplash) {
this(null, paramsFile, null, autorun, nosplash, false, false);
}
/**
* A constructor with optional spash screen. Note that the Main is
* initialized multi-threaded for efficiency. Use {@link #awaitClientInitialized()}
* to await full initialization if necessary.
*
* @param autorun
* @param nosplash
* @see #Main(String, boolean, boolean)
*/
public Main(boolean autorun, boolean nosplash) {
this(null, autorun, nosplash);
}
/**
* A constructor with optional splash screen. Note that the Main
* initialized multi-threaded for efficiency. Use {@link #awaitClientInitialized()}
* to await full initialization if necessary.
*
* @param paramsFile
* @param autorun
* @param noSplash
* @param noGui
* @see #Main(boolean, boolean)
*/
public Main(String paramsFile, boolean autorun, boolean noSplash, boolean noGui, boolean withTreeView) {
this(null, paramsFile, null, autorun, noSplash, noGui, withTreeView);
}
/**
* A constructor with optional splash screen. Note that the Main
* initialized multi-threaded for efficiency. Use {@link #awaitClientInitialized()}
* to await full initialization if necessary.
*
* @param optimizationParameters
* @param autorun
* @param noSplash
* @param noGui
* @see #Main(String, boolean, boolean)
*/
public Main(InterfaceOptimizationParameters optimizationParameters, boolean autorun, boolean noSplash, boolean noGui) {
this(null, null, optimizationParameters, autorun, noSplash, noGui, false);
}
/**
* Do not use the tree view by default.
*
* @param parent
* @param paramsFile
* @param goParams
* @param autorun
* @param noSplash
* @param noGui
*/
public Main(final Window parent, final String paramsFile, final InterfaceOptimizationParameters goParams, final boolean autorun, final boolean noSplash, final boolean noGui) {
this(parent, paramsFile, goParams, autorun, noSplash, noGui, false);
}
/**
* Main constructor of the EvA2 client GUI. Works as standalone version
* locally or as client for the EvA2 server. GO parameters may be loaded
* from a file (paramsFile) or given directly as a java instance. Both may
* be null to start with standard parameters. If both are non null, the java
* instance has the higher priority. Note that the Main initialized
* multi-threaded for efficiency. Use {@link #awaitClientInitialized()} to
* await full initialization if necessary.
*
* @param parent
* @param paramsFile
* @param autorun
* @param noSplash
* @param noGui
*/
public Main(final Window parent, final String paramsFile, final InterfaceOptimizationParameters goParams, final boolean autorun, final boolean noSplash, final boolean noGui, final boolean showTreeView) {
clientInited = false;
final eva2.gui.SplashScreen splashScreen = new eva2.gui.SplashScreen(EvAInfo.splashLocation);
// preload some classes (into system cache) in a parallel thread
preloadClasses();
withGUI = !noGui;
withTreeView = showTreeView;
// activate the splash screen (show later using SwingUtilities)
if (!noSplash && withGUI) {
try {
splashScreen.splash();
} catch (HeadlessException e) {
LOGGER.severe("Error: no xserver present - deactivating GUI.");
withGUI = false;
}
}
this.comAdapter = EvAComAdapter.getInstance();
splashScreenTime = 2500;
initRunnable = new Runnable() {
@Override
public void run() {
synchronized (this) {
long startTime = System.currentTimeMillis();
init(paramsFile, goParams, parent); // this takes a bit
long wait = System.currentTimeMillis() - startTime;
LOGGER.info("Loaded EvA2 in " + wait + "ms.");
System.out.print(wait);
if (!autorun) {
if (!noSplash) {
try {
// if splashScreenTime has not passed, sleep some more
if (wait < splashScreenTime) {
Thread.sleep(splashScreenTime - wait);
}
} catch (Exception ignored) {
}
}
} else {
if (!withGUI && (currentModuleAdapter instanceof GenericModuleAdapter)) {
// do not save new parameters for an autorun without GUI - they weren't changed manually anyways.
((GenericModuleAdapter) currentModuleAdapter).getStatistics().setSaveParams(false);
LOGGER.info("Autorun without GUI - not saving statistics parameters...");
}
if (withGUI) {
frameMaker.onUserStart();
} else {
currentModuleAdapter.startOptimization();
}
}
// close splash screen
if (!noSplash && withGUI) {
splashScreen.dispose();
}
clientInited = true;
notifyAll();
}
}
};
SwingUtilities.invokeLater(initRunnable);
}
private void initLookAndFeel() {
// Properties for Mac OS X support.
if ((System.getProperty("mrj.version") != null)
|| (System.getProperty("os.name").toLowerCase().contains("mac"))) {
/*
* Note: the xDock name property must be set before parsing
* command-line arguments! See above!
*/
System.setProperty("com.apple.mrj.application.apple.menu.about.name", EvAInfo.productName);
System.setProperty("apple.awt.graphics.EnableQ2DX", "true");
System.setProperty("apple.laf.useScreenMenuBar", "true");
System.setProperty("com.apple.macos.smallTabs", "true");
System.setProperty("com.apple.macos.useScreenMenuBar", "true");
System.setProperty("com.apple.mrj.application.growbox.intrudes", "false");
System.setProperty("com.apple.mrj.application.live-resize", "true");
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
LOGGER.log(Level.INFO, "Could not set Look&Feel", ex);
}
} else {
/* Set Look and Feel */
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
//UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
} catch (Exception ex) {
LOGGER.log(Level.INFO, "Could not set Look&Feel", ex);
}
}
}
/**
* Since the constructor runs multi-threaded for efficiency, this method may
* be called to await the full initialization of a client instance. As soon
* as it returns, the Main GUI is fully initialized.
*/
public void awaitClientInitialized() {
if (initRunnable != null) {
synchronized (initRunnable) {
if (!clientInited) {
try {
initRunnable.wait();
initRunnable = null;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
private void preloadClasses() {
ClassPreloader cp = new ClassPreloader("eva2.optimization.strategies.InterfaceOptimizer", "eva2.problems.InterfaceOptimizationProblem", "eva2.optimization.operator.terminators.InterfaceTerminator");
new Thread(cp).start();
}
/**
* Try to start the optimization with current parameters on the loaded
* module. Return true on success, otherwise false.
*
* @return
*/
public boolean startOptimization() {
if (currentModuleAdapter != null) {
currentModuleAdapter.startOptimization();
return true;
} else {
return false;
}
}
/**
* Set UI Font for all controls.
*
* @param fontResource The FontUIResource for the controls
*/
private static void setUIFont(javax.swing.plaf.FontUIResource fontResource) {
Enumeration keys = UIManager.getDefaults().keys();
while (keys.hasMoreElements()) {
Object key = keys.nextElement();
Object value = UIManager.get(key);
if (value != null && value instanceof javax.swing.plaf.FontUIResource) {
UIManager.put(key, fontResource);
}
}
}
/**
* Tries to load OptimizationParameters from given file if not null.
*/
private void init(String paramsFile, InterfaceOptimizationParameters optimizationParameters, final Window parent) {
useDefaultModule = EvAInfo.propDefaultModule();
this.parentWindow = parent;
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
setUIFont(new javax.swing.plaf.FontUIResource(Font.SANS_SERIF, 0, 11));
if (useDefaultModule != null) {
useDefaultModule = useDefaultModule.trim();
if (useDefaultModule.length() < 1) {
useDefaultModule = null;
}
}
if (withGUI) {
// Initialize look and feel for EvA2
initLookAndFeel();
GridBagConstraints gbConstraints = new GridBagConstraints();
/* Create main frame with GridBagLayout */
setTitle(EvAInfo.productName);
setLayout(new GridBagLayout());
setMinimumSize(new Dimension(1024, 800));
/* Creates the desktopPane for Plot/Text Output */
desktopPane = new JExtDesktopPane();
JEFrameRegister.getInstance().setDesktopPane(desktopPane);
/* Creates desktopPane ToolBar to show tiling buttons */
JExtDesktopPaneToolBar desktopToolBar = new JExtDesktopPaneToolBar((JExtDesktopPane) desktopPane);
/* Pane to hold ToolBar + DesktopPane */
JPanel desktopPanel = new JPanel(new GridBagLayout());
GridBagConstraints desktopConst = new GridBagConstraints();
desktopConst.gridx = 0;
desktopConst.gridy = 0;
desktopConst.fill = GridBagConstraints.HORIZONTAL;
desktopConst.weightx = 1.0;
desktopPanel.add(desktopToolBar, desktopConst);
desktopConst.gridy = 1;
desktopConst.fill = GridBagConstraints.BOTH;
desktopConst.weighty = 1.0;
desktopPanel.add(desktopPane, desktopConst);
BasicResourceLoader loader = BasicResourceLoader.instance();
byte[] bytes = loader.getBytesFromResourceLocation(EvAInfo.iconLocation, true);
// TODO: use setIconImages (for better support of multiple icons when changing programs etc.)
setIconImage(Toolkit.getDefaultToolkit().createImage(bytes));
LoggingPanel logPanel = new LoggingPanel();
logPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
createActions();
setSize(1024, 800);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setLocation((screenSize.width - this.getWidth()) / 2, (int) ((screenSize.height - this.getHeight()) / 2.5));
/* Create a new ConfigurationPanel (left side) */
configurationPane = new JPanel(new GridBagLayout());
gbConstraints.ipadx = 5;
gbConstraints.weightx = 0.0;
gbConstraints.weighty = 1.0;
/* Set configurationPane at 0,1 */
gbConstraints.gridx = 0;
gbConstraints.gridy = 1;
gbConstraints.fill = GridBagConstraints.VERTICAL;
gbConstraints.gridwidth = GridBagConstraints.RELATIVE;
gbConstraints.gridheight = GridBagConstraints.RELATIVE;
add(configurationPane, gbConstraints);
/* SplitPane for desktopPanel and loggingPanel */
JSplitPane horizontalSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true);
horizontalSplit.setTopComponent(desktopPanel);
horizontalSplit.setBottomComponent(logPanel);
horizontalSplit.setDividerSize(8);
horizontalSplit.setOneTouchExpandable(true);
horizontalSplit.setResizeWeight(1.0);
horizontalSplit.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY, 1));
horizontalSplit.setContinuousLayout(true);
horizontalSplit.setDividerLocation(0.25);
/* Add horizontal split pane at 1,1 */
gbConstraints.gridx = 1;
gbConstraints.gridy = 1;
gbConstraints.fill = GridBagConstraints.BOTH;
gbConstraints.gridwidth = GridBagConstraints.REMAINDER;
gbConstraints.gridheight = GridBagConstraints.RELATIVE;
add(horizontalSplit, gbConstraints);
/* StatusBar of the main frame */
JPanel statusBar = new JPanel(new FlowLayout(FlowLayout.RIGHT));
JPanel statusBarControls = new JPanel();
statusBarControls.setLayout(new BoxLayout(statusBarControls, BoxLayout.LINE_AXIS));
statusBarControls.add(Box.createHorizontalGlue());
/* Set default logging level to INFO */
Logger.getLogger("eva2").setLevel(Level.INFO);
/* Logging settings drop down */
LoggingLevelLabel loggingOption = new LoggingLevelLabel();
statusBarControls.add(loggingOption);
statusBarControls.add(Box.createHorizontalStrut(5));
statusBarControls.add(new JSeparator(JSeparator.VERTICAL));
statusBarControls.add(Box.createHorizontalStrut(5));
/* Create ProgressBar and add it to the status bar */
statusBarControls.add(new JLabel("Progress"));
statusBarControls.add(Box.createHorizontalStrut(5));
progressBar = new JProgressBar();
progressBar.setValue(0);
progressBar.setStringPainted(true);
statusBarControls.add(progressBar);
statusBarControls.add(Box.createHorizontalStrut(5));
statusBarControls.add(new JSeparator(JSeparator.VERTICAL));
statusBarControls.add(Box.createHorizontalStrut(5));
/* Create ProgressBar and add it to the status bar */
statusBarControls.add(new JLabel("CPU"));
statusBarControls.add(Box.createHorizontalStrut(5));
statusBarControls.add(new CPUPanel(100));
statusBar.add(statusBarControls);
gbConstraints.gridx = 0;
gbConstraints.gridy = 2;
gbConstraints.gridwidth = 2;
gbConstraints.weighty = 0.0;
gbConstraints.fill = GridBagConstraints.HORIZONTAL;
gbConstraints.anchor = GridBagConstraints.PAGE_END;
add(statusBar, gbConstraints);
}
if (useDefaultModule != null) {
/*
* if optimizationParameters are not defined and a params file is defined
* try to load parameters from file
*/
if (optimizationParameters == null && (paramsFile != null && (paramsFile.length() > 0))) {
optimizationParameters = OptimizationParameters.getInstance(paramsFile, false);
}
loadSpecificModule(useDefaultModule, optimizationParameters);//loadSpecificModule
}
if (withGUI) {
buildMenu();
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(final WindowEvent event) {
int result = JOptionPane.showConfirmDialog(
Main.this,
"Do you really want to exit EvA2?",
"Exit Application",
JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.YES_OPTION) {
Main.this.close();
}
}
});
LOGGER.log(Level.INFO, "Working directory is: {0}", System.getProperty("user.dir"));
LOGGER.log(Level.FINE, "Class path is: {0}", System.getProperty("java.class.path", "."));
if (!(configurationPane.isVisible())) {
configurationPane.setVisible(true);
}
setVisible(true);
// if this message is omitted, the stupid scroll pane runs to
// the end of the last line which is ugly for a long class path
LOGGER.info("EvA2 ready");
}
}
/**
* Closes EvA2 workbench. Will not kill the JVM iff
* the MATLAB environment variable has been set.
*/
public void close() {
LOGGER.info("Closing EvA2 Client. Bye!");
Set<String> keys = System.getenv().keySet();
if (keys.contains("MATLAB")) {
LOGGER.info("EvA2 workbench has been started from Matlab: not killing JVM");
} else {
if (parentWindow == null) {
System.exit(1);
} else {
this.setVisible(false);
this.dispose();
}
}
}
/**
* Refresh the parameter panels (if settings have been changed outside of
* the GUI which should be updated in the GUI.
*/
public void refreshMainPanels() {
frameMaker.refreshPanels();
}
/** /**
* The one and only main of the client program. Possible arguments: * The one and only main of the client program. Possible arguments:
* --autorun: immediately starts the optimization (with parameters loaded * --autorun: immediately starts the optimization (with parameters loaded
@ -557,9 +22,27 @@ public class Main extends JFrame implements OptimizationStateListener {
* @param args command line parameters * @param args command line parameters
*/ */
public static void main(String[] args) { public static void main(String[] args) {
// Properties for Mac OS X support.
if ((System.getProperty("mrj.version") != null)
|| (System.getProperty("os.name").toLowerCase().contains("mac"))) {
/*
* Note: the xDock name property must be set before parsing
* command-line arguments! See above!
*/
System.setProperty("com.apple.mrj.application.apple.menu.about.name", EvAInfo.productName);
System.setProperty("apple.awt.application.name", EvAInfo.productName);
System.setProperty("apple.awt.graphics.EnableQ2DX", "true");
System.setProperty("apple.laf.useScreenMenuBar", "true");
System.setProperty("com.apple.macos.smallTabs", "true");
System.setProperty("com.apple.macos.useScreenMenuBar", "true");
System.setProperty("com.apple.mrj.application.growbox.intrudes", "false");
System.setProperty("com.apple.mrj.application.live-resize", "true");
}
/* Available command-line parameters */ /* Available command-line parameters */
String[] keys = new String[]{ String[] keys = new String[]{
"--help", "--autorun", "--nosplash", "--nogui", "--params", "--treeView" "--help", "--autorun", "--nosplash", "--nogui", "--params", "--treeView"
}; };
/* Number of arguments per parameter */ /* Number of arguments per parameter */
int[] arities = new int[]{0, 0, 0, 0, 1, 0}; int[] arities = new int[]{0, 0, 0, 0, 1, 0};
@ -591,42 +74,10 @@ public class Main extends JFrame implements OptimizationStateListener {
boolean treeView = (values[5] != null); boolean treeView = (values[5] != null);
String paramsFile = StringTools.checkSingleStringArg(keys[4], values[4], arities[4] - 1); String paramsFile = StringTools.checkSingleStringArg(keys[4], values[4], arities[4] - 1);
new Main(paramsFile, autorun, nosplash, nogui, treeView); new MainFrame(paramsFile, autorun, nosplash, nogui, treeView);
} }
} }
/**
* Initialize the client GUI with given parameters and set listeners. This
* will return as soon as the GUI is visible and ready.
*
* @param goParams optimization parameters
* @param statisticsListener statistics listener receiving data during
* optimization
* @param windowListener additional window listener for client frame
*/
public static Main initClientGUI(OptimizationParameters goParams,
InterfaceStatisticsListener statisticsListener,
WindowListener windowListener, final Window parent) {
Main evaClient;
evaClient = new Main(parent, null, goParams,
false, true, false, false); // initializes GUI in the background
// important: wait for GUI initialization before accessing any internal
// settings:
evaClient.awaitClientInitialized(); // this returns as soon as the
// GUI is ready
evaClient.addWindowListener(windowListener);
// modify initial settings and activate output of all data:
evaClient.getStatistics().getStatisticsParameters().setOutputAllFieldsAsText(true);
// add a data listener instance:
evaClient.getStatistics().addDataListener(statisticsListener);
// GUI update due to the changes made through the API
evaClient.refreshMainPanels();
return evaClient;
}
/** /**
* This method returns a readable usage string. * This method returns a readable usage string.
* *
@ -655,309 +106,4 @@ public class Main extends JFrame implements OptimizationStateListener {
return sbuf.toString(); return sbuf.toString();
} }
/**
*
*/
private void createActions() {
actAbout = new ExtAction("&About", "Product Information") {
@Override
public void actionPerformed(final ActionEvent event) {
LOGGER.info(event.getActionCommand());
showAboutDialog();
}
};
actLicense = new ExtAction("&License", "View License") {
@Override
public void actionPerformed(final ActionEvent event) {
LOGGER.info(event.getActionCommand());
showLicense();
}
};
actQuit = new ExtAction("&Quit", "Quit EvA2 workbench",
KeyStroke.getKeyStroke(KeyEvent.VK_Q, InputEvent.CTRL_MASK)) {
@Override
public void actionPerformed(final ActionEvent event) {
int result = JOptionPane.showConfirmDialog(
Main.this,
"Do you really want to exit EvA2?",
"Exit Application",
JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.YES_OPTION) {
Main.this.close();
}
}
};
actPreferences = new ExtAction("&Preferences", "Show preferences dialog",
KeyStroke.getKeyStroke(KeyEvent.VK_P, InputEvent.CTRL_MASK)) {
@Override
public void actionPerformed(final ActionEvent event) {
// ToDo
}
};
actHelp = new ExtAction("&Help", "Show help contents",
KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0)) {
@Override
public void actionPerformed(final ActionEvent event) {
// ToDo
String helpHS = "EvA2Help/EvA2Help.hs";
ClassLoader cl = Main.class.getClassLoader();
JHelpContentViewer helpPane;
try {
URL hsURL = HelpSet.findHelpSet(cl, helpHS);
HelpSet helpSet = new HelpSet(null, hsURL);
// Trigger the help viewer:
helpPane = new JHelpContentViewer(helpSet);
JHelpNavigator helpNavigator = (JHelpNavigator) helpSet.getNavigatorView("TOC").createNavigator(helpPane.getModel());
JEFrame helpFrame = new JEFrame("Help contents");
JSplitPane helpSplit = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, helpNavigator, helpPane);
helpFrame.add(helpSplit);
helpFrame.setVisible(true);
helpFrame.setMaximum(true);
} catch (Exception ee) {
// Say what the exception really is
LOGGER.log(Level.WARNING, "Could not open application help", ee);
}
}
};
}
/**
* Create the main menu and add actions.
*/
private void buildMenu() {
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JExtMenu menuHelp = new JExtMenu("&Help");
menuHelp.add(actHelp);
menuHelp.addSeparator();
menuHelp.add(actAbout);
menuHelp.add(actLicense);
JExtMenu menuOptions = new JExtMenu("&Options");
menuOptions.add(actPreferences);
menuOptions.addSeparator();
menuOptions.add(actQuit);
menuBar.add(menuOptions);
menuBar.add(((JExtDesktopPane) desktopPane).getWindowMenu());
menuBar.add(menuHelp);
}
/**
* Retrieve the optimization parameters of a loaded module. Return null if no module is
* loaded.
*
* @return
*/
public InterfaceOptimizationParameters getOptimizationParameters() {
if (currentModuleAdapter != null) {
if (currentModuleAdapter instanceof AbstractModuleAdapter) {
return ((AbstractModuleAdapter) currentModuleAdapter).getOptimizationParameters();
}
}
return null;
}
public AbstractStatistics getStatistics() {
return ((GenericModuleAdapter) currentModuleAdapter).getStatistics();
}
public InterfaceStatisticsParameters getStatisticsParameter() {
return ((GenericModuleAdapter) currentModuleAdapter).getStatistics().getStatisticsParameters();
}
private void loadSpecificModule(String selectedModule, InterfaceOptimizationParameters optimizationParameters) {
ModuleAdapter newModuleAdapter = null;
//
try {
InterfaceOptimizationParameters params = optimizationParameters;
if (optimizationParameters == null) {
params = OptimizationParameters.getInstance();
}
newModuleAdapter = new GOModuleAdapter(selectedModule, params, withGUI ? null : "EvA2");
//newModuleAdapter = comAdapter.getModuleAdapter(selectedModule, optimizationParameters, withGUI ? null : "EvA2");
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "Error loading module.", e);
EVAERROR.EXIT("Error while comAdapter.GetModuleAdapter Host: " + e.getMessage());
}
if (newModuleAdapter == null) {
// When launching a Java Web Start application, baseDir will always be null!
URL baseDir = getClass().getClassLoader().getResource("");
String cp = System.getProperty("java.class.path", ".");
String dir = (baseDir == null) ? System.getProperty("user.dir") : baseDir.getPath();
if (!cp.contains(dir)) {
// this was added due to matlab not adding base dir to base path...
System.err.println("classpath does not contain base directory!");
System.err.println("adding base dir and trying again...");
System.setProperty("java.class.path", cp + System.getProperty("path.separator") + dir);
ReflectPackage.resetDynCP();
comAdapter.updateLocalMainAdapter();
loadSpecificModule(selectedModule, optimizationParameters); // end recursive call! handle with care!
}
} else {
newModuleAdapter.addOptimizationStateListener(this);
try {
if (withGUI) {
// this (or rather: EvAModuleButtonPanelMaker) is where the start button etc come from!
frameMaker = newModuleAdapter.getModuleFrame();
/* This is the left TabPane on the main frame */
JPanel moduleContainer = frameMaker.makePanel();
configurationPane.setVisible(false);
configurationPane.removeAll();
GridBagConstraints gbConstraints = new GridBagConstraints();
/* ToDo: Find a way to properly add the TreeView to the GOPanel */
if (withTreeView && (newModuleAdapter instanceof AbstractModuleAdapter)) {
JComponent tree = null;
tree = getEvATreeView(frameMaker.getGOPanel(), "OptimizationParameters", ((AbstractModuleAdapter) newModuleAdapter).getOptimizationParameters());
gbConstraints.gridx = 0;
gbConstraints.gridy = 0;
gbConstraints.fill = GridBagConstraints.BOTH;
gbConstraints.weightx = 1.0;
gbConstraints.weighty = 1.0;
configurationPane.add(tree, gbConstraints);
}
gbConstraints.weightx = 1.0;
gbConstraints.weighty = 0.0;
gbConstraints.gridx = 0;
gbConstraints.gridy = 0;
gbConstraints.gridwidth = 2;
gbConstraints.fill = GridBagConstraints.HORIZONTAL;
gbConstraints.anchor = GridBagConstraints.PAGE_START;
add(frameMaker.getToolBar(), gbConstraints);
GridBagConstraints gbConstraints2 = new GridBagConstraints();
gbConstraints2.gridx = 0;
gbConstraints2.gridy = 0;
gbConstraints2.fill = GridBagConstraints.VERTICAL;
gbConstraints2.weighty = 1.0;
configurationPane.add(moduleContainer, gbConstraints2);
configurationPane.validate();
}
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "Error while newModuleAdapter.getModuleFrame(): " + e.getMessage(), e);
EVAERROR.EXIT("Error while newModuleAdapter.getModuleFrame(): " + e.getMessage());
}
currentModuleAdapter = newModuleAdapter;
}
}
/**
* Create a tree view of an object based on EvATreeNode. It is encapsulated
* in a JScrollPane.
*
* @param goPanel
* @param title
* @param object
* @return
* @see eva2.gui.EvATreeNode
*/
public JComponent getEvATreeView(JParaPanel goPanel, String title, Object object) {
EvATreeNode root = new EvATreeNode(title, object); // the root of the tree
JTree jtree = new JTree(root);
JScrollPane treeView = new JScrollPane(jtree);
EvATreeSelectionListener treeListener = new EvATreeSelectionListener(root, goPanel.getEditor(), jtree);
// hooks itself up as the tree listener. It reacts both to changes in the selection
// state of the tree (to update the parameter panel) and to changes in the
// parameters to update the tree
return treeView;
}
private void showAboutDialog() {
AboutDialog aboutDialog = new AboutDialog(this);
aboutDialog.setLocationRelativeTo(this);
aboutDialog.setVisible(true);
aboutDialog.setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
}
private void showLicense() {
HtmlDemo lgpl = new HtmlDemo(EvAInfo.LGPLFile);
HtmlDemo gpl = new HtmlDemo(EvAInfo.GPLFile);
gpl.show();
lgpl.show();
}
@Override
public void performedRestart(String infoString) {
if (superListenerList != null) {
for (OptimizationStateListener l : superListenerList) {
l.performedRestart(infoString);
}
}
LOGGER.log(Level.INFO, "Restarted processing {0}", infoString);
startTime = System.currentTimeMillis();
}
@Override
public void performedStart(String infoString) {
if (superListenerList != null) {
for (OptimizationStateListener l : superListenerList) {
l.performedStart(infoString);
}
}
LOGGER.log(Level.INFO, "Started processing {0}", infoString);
startTime = System.currentTimeMillis();
}
@Override
public void performedStop() {
if (superListenerList != null) {
for (OptimizationStateListener l : superListenerList) {
l.performedStop();
}
}
long t = (System.currentTimeMillis() - startTime);
LOGGER.info(String.format("Stopped after %1$d.%2$tL s", (t / 1000), (t % 1000)));
if (!withGUI) {
System.exit(0);
}
}
/**
* When the worker needs to update the GUI we do so by queuing a Runnable
* for the event dispatching thread with SwingUtilities.invokeLater(). In
* this case we're just changing the progress bars value.
*/
@Override
public void updateProgress(final int percent, String msg) {
if (superListenerList != null) {
for (OptimizationStateListener l : superListenerList) {
l.updateProgress(percent, msg);
}
}
if (msg != null) {
LOGGER.info(msg);
}
if (this.progressBar != null) {
Runnable doSetProgressBarValue = new Runnable() {
@Override
public void run() {
progressBar.setValue(percent);
}
};
SwingUtilities.invokeLater(doSetProgressBarValue);
}
}
} }

872
src/eva2/gui/MainFrame.java Normal file
View File

@ -0,0 +1,872 @@
package eva2.gui;
import eva2.EvAInfo;
import eva2.optimization.InterfaceOptimizationParameters;
import eva2.optimization.OptimizationParameters;
import eva2.optimization.OptimizationStateListener;
import eva2.optimization.modules.AbstractModuleAdapter;
import eva2.optimization.modules.GenericModuleAdapter;
import eva2.optimization.modules.ModuleAdapter;
import eva2.optimization.modules.OptimizationModuleAdapter;
import eva2.optimization.statistics.AbstractStatistics;
import eva2.optimization.statistics.InterfaceStatisticsListener;
import eva2.optimization.statistics.InterfaceStatisticsParameters;
import eva2.tools.BasicResourceLoader;
import eva2.tools.EVAERROR;
import eva2.tools.ReflectPackage;
import eva2.util.ClassPreloader;
import javax.help.HelpSet;
import javax.help.JHelpContentViewer;
import javax.help.JHelpNavigator;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
*/
public class MainFrame extends JFrame implements OptimizationStateListener {
/**
* Generated serial version identifier.
*/
private static final long serialVersionUID = 8232856334379977970L;
private final int splashScreenTime;
private boolean clientInitialized = false;
private JDesktopPane desktopPane;
private JPanel configurationPane;
private Runnable initRunnable = null;
private transient JProgressBar progressBar;
// Option
private ExtAction actPreferences;
private ExtAction actQuit;
private static final Logger LOGGER = Logger.getLogger(MainFrame.class.getName());
// Configurable module:
private ModuleAdapter currentModuleAdapter = null;
// Help:
private ExtAction actHelp;
private ExtAction actAbout;
private ExtAction actLicense;
// if not null, the module is loaded automatically and no other can be selected
private String useDefaultModule = null; //"Genetic_Optimization";
// measuring optimization runtime
private long startTime = 0;
private boolean withGUI = true;
private boolean withTreeView = false;
private EvATabbedFrameMaker frameMaker = null;
private Window parentWindow;
private java.util.List<OptimizationStateListener> superListenerList = null;
public void addOptimizationStateListener(OptimizationStateListener l) {
if (superListenerList == null) {
superListenerList = new ArrayList<>();
}
superListenerList.add(l);
}
public boolean removeOptimizationStateListener(OptimizationStateListener l) {
return superListenerList != null && superListenerList.remove(l);
}
/**
* Constructor of GUI of EvA2. Works as client for the EvA2 server. Note
* that the Main initialized multi-threaded for efficiency. Use {@link #awaitClientInitialized()} }
* to await full initialization if necessary.
*/
public MainFrame() {
this(null, false, false);
}
/**
* A constructor. Splash screen is optional, Gui is activated, no parent
* window. Note that the Main initialized multi-threaded for
* efficiency. Use {@link #awaitClientInitialized()} to await full
* initialization if necessary.
*
* @param paramsFile
* @param autorun
* @param nosplash
*/
public MainFrame(final String paramsFile, boolean autorun, boolean nosplash) {
this(null, paramsFile, null, autorun, nosplash, false, false);
}
/**
* A constructor with optional spash screen. Note that the Main is
* initialized multi-threaded for efficiency. Use {@link #awaitClientInitialized()}
* to await full initialization if necessary.
*
* @param autorun
* @param nosplash
* @see #MainFrame(String, boolean, boolean)
*/
public MainFrame(boolean autorun, boolean nosplash) {
this(null, autorun, nosplash);
}
/**
* A constructor with optional splash screen. Note that the Main
* initialized multi-threaded for efficiency. Use {@link #awaitClientInitialized()}
* to await full initialization if necessary.
*
* @param paramsFile
* @param autorun
* @param noSplash
* @param noGui
* @see #MainFrame(boolean, boolean)
*/
public MainFrame(String paramsFile, boolean autorun, boolean noSplash, boolean noGui, boolean withTreeView) {
this(null, paramsFile, null, autorun, noSplash, noGui, withTreeView);
}
/**
* A constructor with optional splash screen. Note that the Main
* initialized multi-threaded for efficiency. Use {@link #awaitClientInitialized()}
* to await full initialization if necessary.
*
* @param optimizationParameters
* @param autorun
* @param noSplash
* @param noGui
* @see #MainFrame(String, boolean, boolean)
*/
public MainFrame(InterfaceOptimizationParameters optimizationParameters, boolean autorun, boolean noSplash, boolean noGui) {
this(null, null, optimizationParameters, autorun, noSplash, noGui, false);
}
/**
* Do not use the tree view by default.
*
* @param parent
* @param paramsFile
* @param goParams
* @param autorun
* @param noSplash
* @param noGui
*/
public MainFrame(final Window parent, final String paramsFile, final InterfaceOptimizationParameters goParams, final boolean autorun, final boolean noSplash, final boolean noGui) {
this(parent, paramsFile, goParams, autorun, noSplash, noGui, false);
}
/**
* Main constructor of the EvA2 client GUI. Works as standalone version
* locally or as client for the EvA2 server. GO parameters may be loaded
* from a file (paramsFile) or given directly as a java instance. Both may
* be null to start with standard parameters. If both are non null, the java
* instance has the higher priority. Note that the Main initialized
* multi-threaded for efficiency. Use {@link #awaitClientInitialized()} to
* await full initialization if necessary.
*
* @param parent
* @param paramsFile
* @param autorun
* @param noSplash
* @param noGui
*/
public MainFrame(final Window parent, final String paramsFile, final InterfaceOptimizationParameters optimizationParameters, final boolean autorun, final boolean noSplash, final boolean noGui, final boolean showTreeView) {
clientInitialized = false;
final eva2.gui.SplashScreen splashScreen = new eva2.gui.SplashScreen(EvAInfo.splashLocation);
// preload some classes (into system cache) in a parallel thread
preloadClasses();
withGUI = !noGui;
withTreeView = showTreeView;
// activate the splash screen (show later using SwingUtilities)
if (!noSplash && withGUI) {
try {
splashScreen.splash();
} catch (HeadlessException e) {
LOGGER.severe("Error: no xserver present - deactivating GUI.");
withGUI = false;
}
}
splashScreenTime = 2500;
initRunnable = new Runnable() {
@Override
public void run() {
synchronized (this) {
long startTime = System.currentTimeMillis();
init(paramsFile, optimizationParameters, parent); // this takes a bit
long wait = System.currentTimeMillis() - startTime;
LOGGER.info("Loaded EvA2 in " + wait + "ms.");
if (!autorun) {
if (!noSplash) {
try {
// if splashScreenTime has not passed, sleep some more
if (wait < splashScreenTime) {
Thread.sleep(splashScreenTime - wait);
}
} catch (Exception ignored) {
}
}
} else {
if (!withGUI && (currentModuleAdapter instanceof GenericModuleAdapter)) {
// do not save new parameters for an autorun without GUI - they weren't changed manually anyways.
((GenericModuleAdapter) currentModuleAdapter).getStatistics().setSaveParams(false);
LOGGER.info("Autorun without GUI - not saving statistics parameters...");
}
if (withGUI) {
frameMaker.onUserStart();
} else {
currentModuleAdapter.startOptimization();
}
}
// close splash screen
if (!noSplash && withGUI) {
splashScreen.dispose();
}
clientInitialized = true;
notifyAll();
}
}
};
SwingUtilities.invokeLater(initRunnable);
}
private void initLookAndFeel() {
// The native L&F on Linux looks horrible - don't set it.
if (System.getProperty("os.name").equals("Linux")) {
return;
}
// Properties for Mac OS X support.
if ((System.getProperty("mrj.version") != null)
|| (System.getProperty("os.name").toLowerCase().contains("mac"))) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
LOGGER.log(Level.INFO, "Could not set Look&Feel", ex);
}
} else {
/* Set Look and Feel */
try {
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
} catch (Exception ex) {
LOGGER.log(Level.INFO, "Could not set Look&Feel", ex);
}
}
}
/**
* Since the constructor runs multi-threaded for efficiency, this method may
* be called to await the full initialization of a client instance. As soon
* as it returns, the Main GUI is fully initialized.
*/
public void awaitClientInitialized() {
if (initRunnable != null) {
synchronized (initRunnable) {
if (!clientInitialized) {
try {
initRunnable.wait();
initRunnable = null;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
private void preloadClasses() {
ClassPreloader cp = new ClassPreloader("eva2.optimization.strategies.InterfaceOptimizer", "eva2.problems.InterfaceOptimizationProblem", "eva2.optimization.operator.terminators.InterfaceTerminator");
new Thread(cp).start();
}
/**
* Try to start the optimization with current parameters on the loaded
* module. Return true on success, otherwise false.
*
* @return
*/
public boolean startOptimization() {
if (currentModuleAdapter != null) {
currentModuleAdapter.startOptimization();
return true;
} else {
return false;
}
}
/**
* Set UI Font for all controls.
*
* @param fontResource The FontUIResource for the controls
*/
private static void setUIFont(javax.swing.plaf.FontUIResource fontResource) {
Enumeration keys = UIManager.getDefaults().keys();
while (keys.hasMoreElements()) {
Object key = keys.nextElement();
Object value = UIManager.get(key);
if (value != null && value instanceof javax.swing.plaf.FontUIResource) {
UIManager.put(key, fontResource);
}
}
}
/**
* Tries to load OptimizationParameters from given file if not null.
*/
private void init(String paramsFile, InterfaceOptimizationParameters optimizationParameters, final Window parent) {
useDefaultModule = EvAInfo.propDefaultModule();
this.parentWindow = parent;
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
setUIFont(new javax.swing.plaf.FontUIResource(Font.SANS_SERIF, 0, 11));
if (useDefaultModule != null) {
useDefaultModule = useDefaultModule.trim();
if (useDefaultModule.length() < 1) {
useDefaultModule = null;
}
}
if (withGUI) {
// Initialize look and feel for EvA2
initLookAndFeel();
GridBagConstraints gbConstraints = new GridBagConstraints();
/* Create main frame with GridBagLayout */
setTitle(EvAInfo.productName);
setLayout(new GridBagLayout());
setMinimumSize(new Dimension(1024, 800));
/* Creates the desktopPane for Plot/Text Output */
desktopPane = new JExtDesktopPane();
JEFrameRegister.getInstance().setDesktopPane(desktopPane);
/* Creates desktopPane ToolBar to show tiling buttons */
JExtDesktopPaneToolBar desktopToolBar = new JExtDesktopPaneToolBar((JExtDesktopPane) desktopPane);
/* Pane to hold ToolBar + DesktopPane */
JPanel desktopPanel = new JPanel(new GridBagLayout());
GridBagConstraints desktopConst = new GridBagConstraints();
desktopConst.gridx = 0;
desktopConst.gridy = 0;
desktopConst.fill = GridBagConstraints.HORIZONTAL;
desktopConst.weightx = 1.0;
desktopPanel.add(desktopToolBar, desktopConst);
desktopConst.gridy = 1;
desktopConst.fill = GridBagConstraints.BOTH;
desktopConst.weighty = 1.0;
desktopPanel.add(desktopPane, desktopConst);
BasicResourceLoader loader = BasicResourceLoader.getInstance();
byte[] bytes = loader.getBytesFromResourceLocation(EvAInfo.iconLocation, true);
// TODO: use setIconImages (for better support of multiple icons when changing programs etc.)
setIconImage(Toolkit.getDefaultToolkit().createImage(bytes));
LoggingPanel logPanel = new LoggingPanel();
logPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
createActions();
setSize(1024, 800);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setLocation((screenSize.width - this.getWidth()) / 2, (int) ((screenSize.height - this.getHeight()) / 2.5));
/* Create a new ConfigurationPanel (left side) */
configurationPane = new JPanel(new GridBagLayout());
gbConstraints.ipadx = 5;
gbConstraints.weightx = 0.0;
gbConstraints.weighty = 1.0;
/* Set configurationPane at 0,1 */
gbConstraints.gridx = 0;
gbConstraints.gridy = 1;
gbConstraints.fill = GridBagConstraints.VERTICAL;
gbConstraints.gridwidth = GridBagConstraints.RELATIVE;
gbConstraints.gridheight = GridBagConstraints.RELATIVE;
add(configurationPane, gbConstraints);
/* SplitPane for desktopPanel and loggingPanel */
JSplitPane horizontalSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true);
horizontalSplit.setTopComponent(desktopPanel);
horizontalSplit.setBottomComponent(logPanel);
horizontalSplit.setDividerSize(8);
horizontalSplit.setOneTouchExpandable(true);
horizontalSplit.setResizeWeight(1.0);
horizontalSplit.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY, 1));
horizontalSplit.setContinuousLayout(true);
horizontalSplit.setDividerLocation(0.25);
/* Add horizontal split pane at 1,1 */
gbConstraints.gridx = 1;
gbConstraints.gridy = 1;
gbConstraints.fill = GridBagConstraints.BOTH;
gbConstraints.gridwidth = GridBagConstraints.REMAINDER;
gbConstraints.gridheight = GridBagConstraints.RELATIVE;
add(horizontalSplit, gbConstraints);
/* StatusBar of the main frame */
JPanel statusBar = new JPanel(new FlowLayout(FlowLayout.RIGHT));
JPanel statusBarControls = new JPanel();
statusBarControls.setLayout(new BoxLayout(statusBarControls, BoxLayout.LINE_AXIS));
statusBarControls.add(Box.createHorizontalGlue());
/* Set default logging level to INFO */
Logger.getLogger("eva2").setLevel(Level.INFO);
/* Logging settings drop down */
LoggingLevelLabel loggingOption = new LoggingLevelLabel();
statusBarControls.add(loggingOption);
statusBarControls.add(Box.createHorizontalStrut(5));
statusBarControls.add(new JSeparator(JSeparator.VERTICAL));
statusBarControls.add(Box.createHorizontalStrut(5));
/* Create ProgressBar and add it to the status bar */
statusBarControls.add(new JLabel("Progress"));
statusBarControls.add(Box.createHorizontalStrut(5));
progressBar = new JProgressBar();
progressBar.setValue(0);
progressBar.setStringPainted(true);
statusBarControls.add(progressBar);
statusBarControls.add(Box.createHorizontalStrut(5));
statusBarControls.add(new JSeparator(JSeparator.VERTICAL));
statusBarControls.add(Box.createHorizontalStrut(5));
/* Create ProgressBar and add it to the status bar */
statusBarControls.add(new JLabel("CPU"));
statusBarControls.add(Box.createHorizontalStrut(5));
statusBarControls.add(new CPUPanel(100));
statusBar.add(statusBarControls);
gbConstraints.gridx = 0;
gbConstraints.gridy = 2;
gbConstraints.gridwidth = 2;
gbConstraints.weighty = 0.0;
gbConstraints.fill = GridBagConstraints.HORIZONTAL;
gbConstraints.anchor = GridBagConstraints.PAGE_END;
add(statusBar, gbConstraints);
}
if (useDefaultModule != null) {
/*
* if optimizationParameters are not defined and a params file is defined
* try to load parameters from file
*/
if (optimizationParameters == null && (paramsFile != null && (paramsFile.length() > 0))) {
optimizationParameters = OptimizationParameters.getInstance(paramsFile, false);
}
loadSpecificModule(useDefaultModule, optimizationParameters);//loadSpecificModule
}
if (withGUI) {
buildMenu();
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(final WindowEvent event) {
int result = JOptionPane.showConfirmDialog(
MainFrame.this,
"Do you really want to exit EvA2?",
"Exit Application",
JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.YES_OPTION) {
MainFrame.this.close();
}
}
});
LOGGER.log(Level.INFO, "Working directory is: {0}", System.getProperty("user.dir"));
LOGGER.log(Level.FINE, "Class path is: {0}", System.getProperty("java.class.path", "."));
if (!(configurationPane.isVisible())) {
configurationPane.setVisible(true);
}
setVisible(true);
// if this message is omitted, the stupid scroll pane runs to
// the end of the last line which is ugly for a long class path
LOGGER.info("EvA2 ready");
}
}
/**
* Closes EvA2 workbench. Will not kill the JVM iff
* the MATLAB environment variable has been set.
*/
public void close() {
LOGGER.info("Closing EvA2 Client. Bye!");
Set<String> keys = System.getenv().keySet();
if (keys.contains("MATLAB")) {
LOGGER.info("EvA2 workbench has been started from Matlab: not killing JVM");
} else {
if (parentWindow == null) {
System.exit(1);
} else {
this.setVisible(false);
this.dispose();
}
}
}
/**
* Refresh the parameter panels (if settings have been changed outside of
* the GUI which should be updated in the GUI.
*/
public void refreshMainPanels() {
frameMaker.refreshPanels();
}
/**
* Initialize the client GUI with given parameters and set listeners. This
* will return as soon as the GUI is visible and ready.
*
* @param goParams optimization parameters
* @param statisticsListener statistics listener receiving data during
* optimization
* @param windowListener additional window listener for client frame
*/
public static MainFrame initClientGUI(OptimizationParameters goParams,
InterfaceStatisticsListener statisticsListener,
WindowListener windowListener, final Window parent) {
MainFrame evaClient;
evaClient = new MainFrame(parent, null, goParams,
false, true, false, false); // initializes GUI in the background
// important: wait for GUI initialization before accessing any internal
// settings:
evaClient.awaitClientInitialized(); // this returns as soon as the
// GUI is ready
evaClient.addWindowListener(windowListener);
// modify initial settings and activate output of all data:
evaClient.getStatistics().getStatisticsParameters().setOutputAllFieldsAsText(true);
// add a data listener instance:
evaClient.getStatistics().addDataListener(statisticsListener);
// GUI update due to the changes made through the API
evaClient.refreshMainPanels();
return evaClient;
}
/**
*
*/
private void createActions() {
actAbout = new ExtAction("&About", "Product Information") {
@Override
public void actionPerformed(final ActionEvent event) {
LOGGER.info(event.getActionCommand());
showAboutDialog();
}
};
actLicense = new ExtAction("&License", "View License") {
@Override
public void actionPerformed(final ActionEvent event) {
LOGGER.info(event.getActionCommand());
showLicense();
}
};
actQuit = new ExtAction("&Quit", "Quit EvA2 workbench",
KeyStroke.getKeyStroke(KeyEvent.VK_Q, InputEvent.CTRL_MASK)) {
@Override
public void actionPerformed(final ActionEvent event) {
int result = JOptionPane.showConfirmDialog(
MainFrame.this,
"Do you really want to exit EvA2?",
"Exit Application",
JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.YES_OPTION) {
MainFrame.this.close();
}
}
};
actPreferences = new ExtAction("&Preferences", "Show preferences dialog",
KeyStroke.getKeyStroke(KeyEvent.VK_P, InputEvent.CTRL_MASK)) {
@Override
public void actionPerformed(final ActionEvent event) {
// ToDo
}
};
actHelp = new ExtAction("&Help", "Show help contents",
KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0)) {
@Override
public void actionPerformed(final ActionEvent event) {
// ToDo
String helpHS = "EvA2Help/EvA2Help.hs";
ClassLoader cl = MainFrame.class.getClassLoader();
JHelpContentViewer helpPane;
try {
URL hsURL = HelpSet.findHelpSet(cl, helpHS);
HelpSet helpSet = new HelpSet(null, hsURL);
// Trigger the help viewer:
helpPane = new JHelpContentViewer(helpSet);
JHelpNavigator helpNavigator = (JHelpNavigator) helpSet.getNavigatorView("TOC").createNavigator(helpPane.getModel());
JEFrame helpFrame = new JEFrame("Help contents");
JSplitPane helpSplit = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, helpNavigator, helpPane);
helpFrame.add(helpSplit);
helpFrame.setVisible(true);
helpFrame.setMaximum(true);
} catch (Exception ee) {
// Say what the exception really is
LOGGER.log(Level.WARNING, "Could not open application help", ee);
}
}
};
}
/**
* Create the main menu and add actions.
*/
private void buildMenu() {
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JExtMenu menuHelp = new JExtMenu("&Help");
menuHelp.add(actHelp);
menuHelp.addSeparator();
menuHelp.add(actAbout);
menuHelp.add(actLicense);
JExtMenu menuOptions = new JExtMenu("&Options");
menuOptions.add(actPreferences);
menuOptions.addSeparator();
menuOptions.add(actQuit);
menuBar.add(menuOptions);
menuBar.add(((JExtDesktopPane) desktopPane).getWindowMenu());
menuBar.add(menuHelp);
}
/**
* Retrieve the optimization parameters of a loaded module. Return null if no module is
* loaded.
*
* @return
*/
public InterfaceOptimizationParameters getOptimizationParameters() {
if (currentModuleAdapter != null) {
if (currentModuleAdapter instanceof AbstractModuleAdapter) {
return ((AbstractModuleAdapter) currentModuleAdapter).getOptimizationParameters();
}
}
return null;
}
public AbstractStatistics getStatistics() {
return ((GenericModuleAdapter) currentModuleAdapter).getStatistics();
}
public InterfaceStatisticsParameters getStatisticsParameter() {
return ((GenericModuleAdapter) currentModuleAdapter).getStatistics().getStatisticsParameters();
}
private void loadSpecificModule(String selectedModule, InterfaceOptimizationParameters optimizationParameters) {
ModuleAdapter newModuleAdapter = null;
//
try {
InterfaceOptimizationParameters params = optimizationParameters;
if (optimizationParameters == null) {
params = OptimizationParameters.getInstance();
}
newModuleAdapter = new OptimizationModuleAdapter(selectedModule, params, withGUI ? null : "EvA2");
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "Error loading module.", e);
EVAERROR.EXIT("Error while comAdapter.GetModuleAdapter Host: " + e.getMessage());
}
if (newModuleAdapter == null) {
// When launching a Java Web Start application, baseDir will always be null!
URL baseDir = getClass().getClassLoader().getResource("");
String cp = System.getProperty("java.class.path", ".");
String dir = (baseDir == null) ? System.getProperty("user.dir") : baseDir.getPath();
if (!cp.contains(dir)) {
// this was added due to matlab not adding base dir to base path...
System.err.println("classpath does not contain base directory!");
System.err.println("adding base dir and trying again...");
System.setProperty("java.class.path", cp + System.getProperty("path.separator") + dir);
ReflectPackage.resetDynCP();
loadSpecificModule(selectedModule, optimizationParameters); // end recursive call! handle with care!
}
} else {
newModuleAdapter.addOptimizationStateListener(this);
try {
if (withGUI) {
// this (or rather: EvAModuleButtonPanelMaker) is where the start button etc come from!
frameMaker = newModuleAdapter.getModuleFrame();
/* This is the left TabPane on the main frame */
JPanel moduleContainer = frameMaker.makePanel();
configurationPane.setVisible(false);
configurationPane.removeAll();
GridBagConstraints gbConstraints = new GridBagConstraints();
/* ToDo: Find a way to properly add the TreeView to the GOPanel */
if (false && (newModuleAdapter instanceof AbstractModuleAdapter)) {
JComponent tree = null;
tree = getEvATreeView(frameMaker.getOptimizationParametersPanel(), "OptimizationParameters", ((AbstractModuleAdapter) newModuleAdapter).getOptimizationParameters());
gbConstraints.gridx = 0;
gbConstraints.gridy = 0;
gbConstraints.fill = GridBagConstraints.BOTH;
gbConstraints.weightx = 1.0;
gbConstraints.weighty = 1.0;
configurationPane.add(tree, gbConstraints);
}
gbConstraints.weightx = 1.0;
gbConstraints.weighty = 0.0;
gbConstraints.gridx = 0;
gbConstraints.gridy = 0;
gbConstraints.gridwidth = 2;
gbConstraints.fill = GridBagConstraints.HORIZONTAL;
gbConstraints.anchor = GridBagConstraints.PAGE_START;
add(frameMaker.getToolBar(), gbConstraints);
GridBagConstraints gbConstraints2 = new GridBagConstraints();
gbConstraints2.gridx = 0;
gbConstraints2.gridy = 0;
gbConstraints2.fill = GridBagConstraints.VERTICAL;
gbConstraints2.weighty = 1.0;
configurationPane.add(moduleContainer, gbConstraints2);
configurationPane.validate();
}
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "Error while newModuleAdapter.getModuleFrame(): " + e.getMessage(), e);
EVAERROR.EXIT("Error while newModuleAdapter.getModuleFrame(): " + e.getMessage());
}
currentModuleAdapter = newModuleAdapter;
}
}
/**
* Create a tree view of an object based on EvATreeNode. It is encapsulated
* in a JScrollPane.
*
* @param goPanel
* @param title
* @param object
* @return
* @see eva2.gui.EvATreeNode
*/
public JComponent getEvATreeView(JParaPanel goPanel, String title, Object object) {
EvATreeNode root = new EvATreeNode(title, object); // the root of the tree
JTree jtree = new JTree(root);
JScrollPane treeView = new JScrollPane(jtree);
EvATreeSelectionListener treeListener = new EvATreeSelectionListener(root, goPanel.getEditor(), jtree);
// hooks itself up as the tree listener. It reacts both to changes in the selection
// state of the tree (to update the parameter panel) and to changes in the
// parameters to update the tree
return treeView;
}
private void showAboutDialog() {
AboutDialog aboutDialog = new AboutDialog(this);
aboutDialog.setLocationRelativeTo(this);
aboutDialog.setVisible(true);
aboutDialog.setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
}
private void showLicense() {
HtmlDemo lgpl = new HtmlDemo(EvAInfo.LGPLFile);
HtmlDemo gpl = new HtmlDemo(EvAInfo.GPLFile);
gpl.show();
lgpl.show();
}
@Override
public void performedRestart(String infoString) {
if (superListenerList != null) {
for (OptimizationStateListener l : superListenerList) {
l.performedRestart(infoString);
}
}
LOGGER.log(Level.INFO, "Restarted processing {0}", infoString);
startTime = System.currentTimeMillis();
}
@Override
public void performedStart(String infoString) {
if (superListenerList != null) {
for (OptimizationStateListener l : superListenerList) {
l.performedStart(infoString);
}
}
LOGGER.log(Level.INFO, "Started processing {0}", infoString);
startTime = System.currentTimeMillis();
}
@Override
public void performedStop() {
if (superListenerList != null) {
for (OptimizationStateListener l : superListenerList) {
l.performedStop();
}
}
long t = (System.currentTimeMillis() - startTime);
LOGGER.info(String.format("Stopped after %1$d.%2$tL s", (t / 1000), (t % 1000)));
if (!withGUI) {
System.exit(0);
}
}
/**
* When the worker needs to update the GUI we do so by queuing a Runnable
* for the event dispatching thread with SwingUtilities.invokeLater(). In
* this case we're just changing the progress bars value.
*/
@Override
public void updateProgress(final int percent, String msg) {
if (superListenerList != null) {
for (OptimizationStateListener l : superListenerList) {
l.updateProgress(percent, msg);
}
}
if (msg != null) {
LOGGER.info(msg);
}
if (this.progressBar != null) {
Runnable doSetProgressBarValue = new Runnable() {
@Override
public void run() {
progressBar.setValue(percent);
}
};
SwingUtilities.invokeLater(doSetProgressBarValue);
}
}
}

View File

@ -22,7 +22,6 @@ import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport; import java.beans.PropertyChangeSupport;
import java.lang.reflect.Proxy; import java.lang.reflect.Proxy;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Vector; import java.util.Vector;
import java.util.logging.Logger; import java.util.logging.Logger;
@ -67,9 +66,7 @@ public class OptimizationEditorPanel extends JPanel implements ItemListener {
* Creates the GUI editor component * Creates the GUI editor component
*/ */
private GenericObjectEditor genericObjectEditor = null; private GenericObjectEditor genericObjectEditor = null;
private boolean withComboBoxToolTips = true; // should tool tips for the combo box be created?
private int tipMaxLen = 100; // maximum length of tool tip private int tipMaxLen = 100; // maximum length of tool tip
private HashMap<String, String> classNameMap;
/** /**
* *
@ -82,21 +79,20 @@ public class OptimizationEditorPanel extends JPanel implements ItemListener {
* *
*/ */
public OptimizationEditorPanel(Object target, Object backup, PropertyChangeSupport support, GenericObjectEditor goe, boolean withCancel) { public OptimizationEditorPanel(Object target, Object backup, PropertyChangeSupport support, GenericObjectEditor goe, boolean withCancel) {
Object object = target;
backupObject = backup; backupObject = backup;
propChangeSupport = support; propChangeSupport = support;
genericObjectEditor = goe; genericObjectEditor = goe;
try { try {
if (!(Proxy.isProxyClass(object.getClass()))) { if (!(Proxy.isProxyClass(target.getClass()))) {
backupObject = copyObject(object); backupObject = copyObject(target);
} }
} catch (OutOfMemoryError err) { } catch (OutOfMemoryError err) {
backupObject = null; backupObject = null;
System.gc(); System.gc();
System.err.println("Could not create backup object: not enough memory (OptimizationEditorPanel backup of " + object + ")"); System.err.println("Could not create backup object: not enough memory (OptimizationEditorPanel backup of " + target + ")");
} }
comboBoxModel = new DefaultComboBoxModel(new String[0]); comboBoxModel = new DefaultComboBoxModel(new Vector<Item>());
objectChooser = new JComboBox(comboBoxModel); objectChooser = new JComboBox(comboBoxModel);
objectChooser.setEditable(false); objectChooser.setEditable(false);
propertySheetPanel = new PropertySheetPanel(); propertySheetPanel = new PropertySheetPanel();
@ -227,14 +223,14 @@ public class OptimizationEditorPanel extends JPanel implements ItemListener {
* This method is duplicated from EvAModuleButtonPanelMaker. ToDo: Refactor * This method is duplicated from EvAModuleButtonPanelMaker. ToDo: Refactor
* this. * this.
* *
* @param iconSrc * @param iconSrc Source path of icon
* @param title * @param title Title of button
* @return * @return A JButton with the title and icon
*/ */
private JButton makeIconButton(final String iconSrc, final String title) { private JButton makeIconButton(final String iconSrc, final String title) {
JButton newButton; JButton newButton;
byte[] bytes; byte[] bytes;
bytes = BasicResourceLoader.instance().getBytesFromResourceLocation(iconSrc, false); bytes = BasicResourceLoader.getInstance().getBytesFromResourceLocation(iconSrc, false);
if (bytes == null) { if (bytes == null) {
newButton = new JButton(title); newButton = new JButton(title);
} else { } else {
@ -260,7 +256,6 @@ public class OptimizationEditorPanel extends JPanel implements ItemListener {
try { try {
SerializedObject so = new SerializedObject(source); SerializedObject so = new SerializedObject(source);
result = so.getObject(); result = so.getObject();
so = null;
} catch (Exception ex) { } catch (Exception ex) {
System.err.println("GenericObjectEditor: Problem making backup object"); System.err.println("GenericObjectEditor: Problem making backup object");
System.err.println(source.getClass().getName()); System.err.println(source.getClass().getName());
@ -318,15 +313,17 @@ public class OptimizationEditorPanel extends JPanel implements ItemListener {
classesLongNames = GenericObjectEditor.getClassesFromProperties(genericObjectEditor.getClassType().getName(), instances); classesLongNames = GenericObjectEditor.getClassesFromProperties(genericObjectEditor.getClassType().getName(), instances);
LOGGER.finest("Selected type for OptimizationEditorPanel: " + genericObjectEditor.getClassType().getName()); LOGGER.finest("Selected type for OptimizationEditorPanel: " + genericObjectEditor.getClassType().getName());
if (classesLongNames.size() > 1) { if (classesLongNames.size() > 1) {
classNameMap = new HashMap<>(); Vector<Item> classesList = new Vector<>();
String[] toolTips = collectComboToolTips(instances, tipMaxLen);
int i = 0;
for (String className : classesLongNames) { for (String className : classesLongNames) {
classNameMap.put(StringTools.cutClassName(className), className); String displayName = StringTools.cutClassName(className);
}
Vector<String> classesList = new Vector<>(classesLongNames); classesList.add(new Item(className, displayName, toolTips[i++]));
objectChooser.setModel(new DefaultComboBoxModel(classesList));
if (withComboBoxToolTips) {
objectChooser.setRenderer(new ToolTipComboBoxRenderer(collectComboToolTips(instances, tipMaxLen)));
} }
comboBoxModel = new DefaultComboBoxModel(classesList);
objectChooser.setModel(comboBoxModel);
objectChooser.setRenderer(new ToolTipComboBoxRenderer());
GridBagConstraints gbConstraints = new GridBagConstraints(); GridBagConstraints gbConstraints = new GridBagConstraints();
gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.fill = GridBagConstraints.HORIZONTAL;
gbConstraints.gridx = 0; gbConstraints.gridx = 0;
@ -342,7 +339,6 @@ public class OptimizationEditorPanel extends JPanel implements ItemListener {
for (int i = 0; i < tips.length; i++) { for (int i = 0; i < tips.length; i++) {
tips[i] = null; tips[i] = null;
Class[] classParams = new Class[]{};
String tip = null; String tip = null;
@ -363,20 +359,15 @@ public class OptimizationEditorPanel extends JPanel implements ItemListener {
} }
public void updateChooser() { public void updateChooser() {
String objectName = /* String objectName = genericObjectEditor.getValue().getClass().getName();
* EVAHELP.cutClassName
*/ (genericObjectEditor.getValue().getClass().getName());
boolean found = false;
for (int i = 0; i < comboBoxModel.getSize(); i++) { for (int i = 0; i < comboBoxModel.getSize(); i++) {
if (objectName.equals(comboBoxModel.getElementAt(i))) { Item element = (Item)comboBoxModel.getElementAt(i);
found = true;
if (objectName.equals(element.getId())) {
objectChooser.getModel().setSelectedItem(element);
break; break;
} }
} }
if (!found) {
comboBoxModel.addElement(objectName);
}
objectChooser.getModel().setSelectedItem(objectName);
} }
/** /**
@ -398,7 +389,7 @@ public class OptimizationEditorPanel extends JPanel implements ItemListener {
String className; String className;
if ((e.getSource() == objectChooser) && (e.getStateChange() == ItemEvent.SELECTED)) { if ((e.getSource() == objectChooser) && (e.getStateChange() == ItemEvent.SELECTED)) {
className = (String) objectChooser.getSelectedItem(); className = ((Item)objectChooser.getSelectedItem()).getId();
try { try {
Object n = Class.forName(className).newInstance(); Object n = Class.forName(className).newInstance();
genericObjectEditor.setValue(n); genericObjectEditor.setValue(n);
@ -423,30 +414,71 @@ public class OptimizationEditorPanel extends JPanel implements ItemListener {
class ToolTipComboBoxRenderer extends BasicComboBoxRenderer { class ToolTipComboBoxRenderer extends BasicComboBoxRenderer {
private static final long serialVersionUID = -5781643352198561208L; private static final long serialVersionUID = -5781643352198561208L;
String[] toolTips = null;
public ToolTipComboBoxRenderer(String[] tips) { public ToolTipComboBoxRenderer() {
super(); super();
toolTips = tips;
} }
@Override @Override
public Component getListCellRendererComponent(JList list, Object value, public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) { int index, boolean isSelected, boolean cellHasFocus) {
if (isSelected) {
setBackground(list.getSelectionBackground()); super.getListCellRendererComponent(list, value, index,
setForeground(list.getSelectionForeground()); isSelected, cellHasFocus);
if ((toolTips != null) && (index >= 0)) {
if (toolTips[index] != null) { if (value != null) {
list.setToolTipText(toolTips[index]); Item item = (Item)value;
} setText(item.getDisplayName());
if (isSelected) {
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
list.setToolTipText(item.getDescription());
} else {
setBackground(list.getBackground());
setForeground(list.getForeground());
} }
} else {
setBackground(list.getBackground());
setForeground(list.getForeground());
} }
if (index == -1) {
Item item = (Item)value;
setText(item.getDisplayName());
}
setFont(list.getFont()); setFont(list.getFont());
setText((value == null) ? "" : value.toString());
return this; return this;
} }
} }
class Item
{
private String id;
private String displayName;
private String description;
public Item(String id, String displayName, String description)
{
this.id = id;
this.displayName = displayName;
this.description = description;
}
public String getId()
{
return id;
}
public String getDescription()
{
return description;
}
public String getDisplayName() {
return displayName;
}
public String toString()
{
return id;
}
}

View File

@ -8,5 +8,5 @@ import javax.swing.*;
* @author mkron * @author mkron
*/ */
public interface PanelMaker { public interface PanelMaker {
public JComponent makePanel(); JComponent makePanel();
} }

View File

@ -23,7 +23,7 @@ public class PropertyDialog extends JDialog {
public PropertyDialog(Window parent, PropertyEditor editor, String title) { public PropertyDialog(Window parent, PropertyEditor editor, String title) {
super(parent, title, ModalityType.APPLICATION_MODAL); super(parent, title, ModalityType.APPLICATION_MODAL);
setTitle(getFrameNameFromEditor(editor)); setTitle(getFrameNameFromEditor(editor));
BasicResourceLoader loader = BasicResourceLoader.instance(); BasicResourceLoader loader = BasicResourceLoader.getInstance();
byte[] bytes = loader.getBytesFromResourceLocation(EvAInfo.iconLocation, true); byte[] bytes = loader.getBytesFromResourceLocation(EvAInfo.iconLocation, true);
setDefaultCloseOperation(DISPOSE_ON_CLOSE); setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setLayout(new BorderLayout()); setLayout(new BorderLayout());

View File

@ -73,19 +73,11 @@ public final class PropertySheetPanel extends JPanel implements PropertyChangeLi
* A count of the number of properties we have an editor for. * A count of the number of properties we have an editor for.
*/ */
private int numEditableProperties = 0; private int numEditableProperties = 0;
/**
* How long should a tip text line be (translated to HTML).
*/
private int tipTextLineLen = 50;
/** /**
* A support object for handling property change listeners. * A support object for handling property change listeners.
*/ */
private PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this); private PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);
/**
* set true to use the GOE by default if no other editor is registered.
*/
// If true, tool tips are used up to the first point only.
boolean stripToolTipToFirstPoint = false;
private ToolTipTable propertyTable; private ToolTipTable propertyTable;
private DefaultTableModel propertyTableModel; private DefaultTableModel propertyTableModel;

View File

@ -14,7 +14,7 @@ class SplashScreen extends JWindow {
public SplashScreen(String imgLoc) { public SplashScreen(String imgLoc) {
imgLocation = imgLoc; imgLocation = imgLoc;
BasicResourceLoader loader = BasicResourceLoader.instance(); BasicResourceLoader loader = BasicResourceLoader.getInstance();
byte[] bytes = loader.getBytesFromResourceLocation(imgLocation, true); byte[] bytes = loader.getBytesFromResourceLocation(imgLocation, true);
ImageIcon ii = new ImageIcon(Toolkit.getDefaultToolkit().createImage(bytes)); ImageIcon ii = new ImageIcon(Toolkit.getDefaultToolkit().createImage(bytes));
JLabel splashLabel = new JLabel(ii); JLabel splashLabel = new JLabel(ii);

View File

@ -1,11 +1,11 @@
package eva2.gui; package eva2.gui;
import eva2.gui.plot.Plot; import eva2.gui.plot.Plot;
import eva2.optimization.OptimizationParameters;
import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.individuals.AbstractEAIndividual;
import eva2.optimization.individuals.ESIndividualDoubleData; import eva2.optimization.individuals.ESIndividualDoubleData;
import eva2.optimization.individuals.GAIndividualDoubleData; import eva2.optimization.individuals.GAIndividualDoubleData;
import eva2.optimization.individuals.InterfaceDataTypeDouble; import eva2.optimization.individuals.InterfaceDataTypeDouble;
import eva2.optimization.OptimizationParameters;
import eva2.optimization.operator.crossover.CrossoverGAGINPoint; import eva2.optimization.operator.crossover.CrossoverGAGINPoint;
import eva2.optimization.operator.mutation.InterfaceMutation; import eva2.optimization.operator.mutation.InterfaceMutation;
import eva2.optimization.operator.mutation.MutateESFixedStepSize; import eva2.optimization.operator.mutation.MutateESFixedStepSize;
@ -149,6 +149,8 @@ public class StandaloneOptimization implements InterfaceStandaloneOptimization,
if ((object != null) && (editor != null)) { if ((object != null) && (editor != null)) {
paraPanel.registerEditor(object, editor); paraPanel.registerEditor(object, editor);
} }
// Tabs
this.parameterPanel1 = (paraPanel.makePanel()); this.parameterPanel1 = (paraPanel.makePanel());
this.optionsPanel = new JTabbedPane(); this.optionsPanel = new JTabbedPane();
JParaPanel paraPanel2 = new JParaPanel(this.optimizationParameters, "MyGUI"); JParaPanel paraPanel2 = new JParaPanel(this.optimizationParameters, "MyGUI");

View File

@ -414,7 +414,7 @@ public class ArrayEditor extends JPanel implements PropertyEditor {
} }
// Upper Button Panel // Upper Button Panel
JPanel combiUpperPanel = new JPanel(getButtonLayout(1, upperButtonList)); JPanel combiUpperPanel = new JPanel(getButtonLayout(0, upperButtonList));
// ToDo Figure out how to now show this on Job Pane // ToDo Figure out how to now show this on Job Pane
combiUpperPanel.add(view); combiUpperPanel.add(view);
view.setVisible(withAddButton); view.setVisible(withAddButton);

View File

@ -4,5 +4,5 @@ package eva2.gui.editor;
* *
*/ */
public interface ComponentFilter { public interface ComponentFilter {
public boolean accept(java.awt.Component component); boolean accept(java.awt.Component component);
} }

View File

@ -267,8 +267,7 @@ public class GenericObjectEditor implements PropertyEditor {
return; return;
} }
Vector<String> v = null; Vector<String> v = new Vector<>(getClassesFromProperties(classType.getName(), null));
v = new Vector<>(getClassesFromProperties(classType.getName(), null));
try { try {
if (v.size() > 0) { if (v.size() > 0) {

View File

@ -130,7 +130,7 @@ public class OptimizationObjectivesEditor extends JPanel implements PropertyEdit
* This method updates the server list * This method updates the server list
*/ */
private void updateTargetList() { private void updateTargetList() {
BasicResourceLoader loader = BasicResourceLoader.instance(); BasicResourceLoader loader = BasicResourceLoader.getInstance();
byte[] bytes; byte[] bytes;
InterfaceOptimizationObjective[] list = this.optimizationObjectives.getSelectedTargets(); InterfaceOptimizationObjective[] list = this.optimizationObjectives.getSelectedTargets();

View File

@ -140,7 +140,7 @@ public class OptimizationObjectivesWithParamEditor extends JPanel implements Pro
* This method updates the server list * This method updates the server list
*/ */
private void updateTargetList() { private void updateTargetList() {
BasicResourceLoader loader = BasicResourceLoader.instance(); BasicResourceLoader loader = BasicResourceLoader.getInstance();
byte[] bytes; byte[] bytes;
InterfaceOptimizationObjective[] list = this.optimizationObjectivesWithWeights.getSelectedTargets(); InterfaceOptimizationObjective[] list = this.optimizationObjectivesWithWeights.getSelectedTargets();
double[] weights = this.optimizationObjectivesWithWeights.getWeights(); double[] weights = this.optimizationObjectivesWithWeights.getWeights();

View File

@ -114,7 +114,7 @@ public class TagEditor extends PropertyEditorSupport {
ce.setValue(initial); ce.setValue(initial);
PropertyValueSelector ps = new PropertyValueSelector(ce); PropertyValueSelector ps = new PropertyValueSelector(ce);
JFrame f = new JFrame(); JFrame f = new JFrame();
BasicResourceLoader loader = BasicResourceLoader.instance(); BasicResourceLoader loader = BasicResourceLoader.getInstance();
byte[] bytes = loader.getBytesFromResourceLocation(EvAInfo.iconLocation, true); byte[] bytes = loader.getBytesFromResourceLocation(EvAInfo.iconLocation, true);
f.setIconImage(Toolkit.getDefaultToolkit().createImage(bytes)); f.setIconImage(Toolkit.getDefaultToolkit().createImage(bytes));
f.addWindowListener(new WindowAdapter() { f.addWindowListener(new WindowAdapter() {

View File

@ -14,7 +14,7 @@ package eva2.gui.plot;
* IMPORTS * IMPORTS
*==========================================================================*/ *==========================================================================*/
public interface DataViewerInterface { public interface DataViewerInterface {
public Graph getNewGraph(String InfoString); Graph getNewGraph(String InfoString);
public void init(); void init();
} }

View File

@ -1092,7 +1092,7 @@ public class FunctionArea extends DArea implements Serializable {
public void toggleLog() { public void toggleLog() {
boolean setMinPos = false; boolean setMinPos = false;
if (!log && !checkLoggable()) { if (!log && !checkLoggable()) {
System.err.println("Warning: toggling logarithmics scale with values <= 0! Some points will not be displayed."); LOGGER.warning("Warning: toggling logarithmic scale with values <= 0! Some points will not be displayed.");
setMinPos = true; setMinPos = true;
} }
if (log == false) { if (log == false) {

View File

@ -7,21 +7,21 @@ import eva2.problems.InterfaceOptimizationProblem;
* *
*/ */
public interface InterfaceDPointWithContent { public interface InterfaceDPointWithContent {
public void setEAIndividual(AbstractEAIndividual indy); void setEAIndividual(AbstractEAIndividual indy);
public AbstractEAIndividual getEAIndividual(); AbstractEAIndividual getEAIndividual();
/** /**
* This method allows you to set the according optimization problem * This method allows you to set the according optimization problem
* *
* @param problem InterfaceOptimizationProblem * @param problem InterfaceOptimizationProblem
*/ */
public void setProblem(InterfaceOptimizationProblem problem); void setProblem(InterfaceOptimizationProblem problem);
public InterfaceOptimizationProblem getProblem(); InterfaceOptimizationProblem getProblem();
/** /**
* This method allows you to draw additional data of the individual * This method allows you to draw additional data of the individual
*/ */
public void showIndividual(); void showIndividual();
} }

View File

@ -151,7 +151,7 @@ public class Plot implements PlotInterface, Serializable {
@Override @Override
public void init() { public void init() {
internalFrame = new JEFrame("Plot: " + plotName); internalFrame = new JEFrame("Plot: " + plotName);
BasicResourceLoader loader = BasicResourceLoader.instance(); BasicResourceLoader loader = BasicResourceLoader.getInstance();
byte[] bytes = loader.getBytesFromResourceLocation(EvAInfo.iconLocation, true); byte[] bytes = loader.getBytesFromResourceLocation(EvAInfo.iconLocation, true);
buttonPanel = new JPanel(); buttonPanel = new JPanel();

View File

@ -1,7 +1,7 @@
package eva2.gui.plot; package eva2.gui.plot;
public interface PlotInterface { public interface PlotInterface {
public void setConnectedPoint(double x, double y, int GraphLabel); void setConnectedPoint(double x, double y, int GraphLabel);
/** /**
* Add two graphs to form an average graph * Add two graphs to form an average graph
@ -10,25 +10,25 @@ public interface PlotInterface {
* @param g2 graph object two * @param g2 graph object two
* @param forceAdd if the graph mismatch in point counts, try to add them anyway in a useful manner. * @param forceAdd if the graph mismatch in point counts, try to add them anyway in a useful manner.
*/ */
public void addGraph(int g1, int g2, boolean forceAdd); void addGraph(int g1, int g2, boolean forceAdd);
public void setUnconnectedPoint(double x, double y, int GraphLabel); void setUnconnectedPoint(double x, double y, int GraphLabel);
public void clearAll(); void clearAll();
public void clearGraph(int GraphNumber); void clearGraph(int GraphNumber);
public void setInfoString(int GraphLabel, String Info, float stroke); void setInfoString(int GraphLabel, String Info, float stroke);
public void jump(); void jump();
public String getName(); String getName();
public int getPointCount(int graphLabel); int getPointCount(int graphLabel);
// public FunctionArea getFunctionArea(); // this is bad for RMI // public FunctionArea getFunctionArea(); // this is bad for RMI
public boolean isValid(); boolean isValid();
public void init(); void init();
} }

View File

@ -1,25 +0,0 @@
package eva2.optimization;
/**
* Title: EvA2
* Description: API for distributed and parallel computing.
* Copyright: Copyright (c) 2004
* Company: University of Tuebingen
* @version: $Revision: 259 $
* $Date: 2007-11-16 17:25:09 +0100 (Fri, 16 Nov 2007) $
* $Author: mkron $
*/
import eva2.optimization.modules.ModuleAdapter;
/**
*
*/
public interface EvAMainAdapter {
public String[] getModuleNameList();
// returns the corresponding ModuleAdapter
ModuleAdapter getModuleAdapter(String selectedModuleName);
ModuleAdapter getModuleAdapter(String selectedModuleName, InterfaceOptimizationParameters goParams, String noGuiStatsFile);
}

View File

@ -1,43 +0,0 @@
package eva2.optimization;
/**
* Title: The JProxy Framework
* Description: API for distributed and parallel computing.
* Copyright: Copyright (c) 2004
* Company: University of Tuebingen
* @version: $Revision: 315 $
* $Date: 2007-12-04 15:23:57 +0100 (Tue, 04 Dec 2007) $
* $Author: mkron $
*/
import eva2.EvAInfo;
import eva2.optimization.modules.ModuleAdapter;
/**
*
*/
public class EvAMainAdapterImpl implements EvAMainAdapter {
private ModuleServer moduleServer = null;
public EvAMainAdapterImpl() {
super();
moduleServer = new ModuleServer(EvAInfo.getProperties());
}
@Override
public String[] getModuleNameList() {
return moduleServer.getModuleNameList();
}
@Override
public ModuleAdapter getModuleAdapter(String selectedModule) {
return getModuleAdapter(selectedModule);
}
@Override
public ModuleAdapter getModuleAdapter(String selectedModule, InterfaceOptimizationParameters goParams, String noGuiStatsFile) {
return moduleServer.createModuleAdapter(selectedModule, goParams, noGuiStatsFile);
}
}

View File

@ -8,5 +8,5 @@ public interface InterfaceNotifyOnInformers {
/** /**
* Notify the object about informer instances. * Notify the object about informer instances.
*/ */
public void setInformers(List<InterfaceAdditionalPopulationInformer> informers); void setInformers(List<InterfaceAdditionalPopulationInformer> informers);
} }

View File

@ -1,8 +1,5 @@
package eva2.optimization; package eva2.optimization;
import eva2.optimization.OptimizationStateListener;
/** /**
* Interface for Optimization Processor. * Interface for Optimization Processor.
*/ */

View File

@ -1,162 +0,0 @@
package eva2.optimization;
import eva2.optimization.modules.ModuleAdapter;
import eva2.tools.EVAERROR;
import eva2.tools.ReflectPackage;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Collect available ModuleAdapter implementations and load them on request.
*/
public final class ModuleServer {
private static final Logger LOGGER = Logger.getLogger(ModuleServer.class.getName());
private static int instanceCounter = 0;
private List<Class<?>> moduleClassList;
private ModuleAdapter moduleAdapter;
private int moduleAdapterCounter = 0;
/**
*
* @param EvAProps
*/
public ModuleServer(Properties EvAProps) {
if (instanceCounter > 0) {
EVAERROR.EXIT("ModuleServer created twice");
}
moduleClassList = new ArrayList<>();
String modulePckg = null;
Class<?> filterBy = null;
try {
/* Fetch the name of the package containing the modules */
modulePckg = EvAProps.getProperty("ModulePackage");
/* Fetch the the super class for all modules */
filterBy = Class.forName(EvAProps.getProperty("ModuleFilterClass"));
} catch (Exception ex) {
System.err.println("Creating ModuleServer failed: couldn't load modules:" + ex.getMessage());
System.err.println("module path was " + modulePckg + ", is it valid?");
System.err.println("filter class path was " + ((filterBy == null) ? "null" : filterBy.getName()));
}
// this gets a list of all valid modules from the package
Class<?>[] classes = ReflectPackage.getAssignableClassesInPackage(modulePckg, filterBy, true, true);
for (Object cls : classes) {
moduleClassList.add((Class<?>) cls);
}
instanceCounter++;
}
/**
* Iterates over the list of available modules and fetches the name of the
* module by calling the static getName() method.
*
* @return Array of available modules
*/
public String[] getModuleNameList() {
List<String> moduleNameList = new ArrayList<>();
for (Class<?> module : moduleClassList) {
try {
Method[] methods = module.getDeclaredMethods();
for (Method method : methods) {
if (method.getName().equals("getName")) {
String name = (String) method.invoke(null, (Object[]) null);
if (name != null) {
moduleNameList.add(name);
} else {
LOGGER.log(Level.FINE, "Module {0} does not specify a diplayable name.", module.getCanonicalName());
}
break;
}
}
} catch (Exception ex) {
LOGGER.log(Level.WARNING, "Error while fetching name from module.", ex);
}
}
String[] x = new String[moduleNameList.size()];
moduleNameList.toArray(x);
return x;
}
/**
* Load the module indicated by the selectedModuleName from all available
* module classes; if necessary through a remote proxy. Try to load a given
* parameter file in case its a GOModuleAdapter.
*
* @param selectedModuleName
* @param optimizationParameters
* @param noGuiLogFile
* @return the loaded module adapter instance
*/
public ModuleAdapter createModuleAdapter(String selectedModuleName, InterfaceOptimizationParameters optimizationParameters, String noGuiLogFile) {
moduleAdapterCounter++;
String adapterName = "ERROR MODULADAPTER !!";
String moduleName = null;
Method[] methods;
for (Class<?> module : moduleClassList) {
try {
methods = module.getDeclaredMethods();
for (Method method : methods) {
if (method.getName().equals("getName")) {
moduleName = (String) method.invoke(null, (Object[]) null);
}
}
} catch (Exception ex) {
LOGGER.log(Level.WARNING, ex.getMessage(), ex);
}
if ((moduleName != null) && (selectedModuleName.equals(moduleName))) {
try {
adapterName = moduleAdapterCounter + "_Running_" + selectedModuleName;
Constructor<?>[] constructorArr = module.getConstructors();
/* create a module instance */
int constrIndex = 0;
if ((optimizationParameters == null && noGuiLogFile == null)) {
if (optimizationParameters != null) {
System.err.println("Cant set params - no matching constructor found for " + adapterName + " (ModuleServer)");
}
if (noGuiLogFile != null) {
System.err.println("Cant deactivate GUI - no matching constructor found for " + adapterName + " (ModuleServer)");
}
Object[] Para = new Object[1];
while ((constructorArr[constrIndex].getParameterTypes().length != 1) && (constrIndex < constructorArr.length)) {
constrIndex++;
}
Class<?> paramTypes[] = (constructorArr[constrIndex]).getParameterTypes();
Para[0] = paramTypes[0].cast(adapterName);
moduleAdapter = (ModuleAdapter) constructorArr[constrIndex].newInstance(Para);
} else {
Object[] param = new Object[4];
param[0] = adapterName;
param[1] = optimizationParameters;
param[2] = noGuiLogFile;
while ((constructorArr[constrIndex].getParameterTypes().length != 4) && (constrIndex < constructorArr.length)) {
constrIndex++;
}
moduleAdapter = (ModuleAdapter) constructorArr[constrIndex].newInstance(param);
}
} catch (Exception ex) {
LOGGER.log(Level.SEVERE, "Error in RMI-Moduladapter initialization", ex);
EVAERROR.EXIT("Error in RMI-Moduladapter initialization: " + ex.getMessage());
return null;
}
return moduleAdapter;
}
}
LOGGER.log(Level.SEVERE, "No valid module defined: {0}", selectedModuleName);
return null;
}
}

View File

@ -7,6 +7,7 @@ import eva2.optimization.strategies.InterfaceOptimizer;
import eva2.problems.F1Problem; import eva2.problems.F1Problem;
import eva2.problems.InterfaceOptimizationProblem; import eva2.problems.InterfaceOptimizationProblem;
import eva2.util.annotation.Description; import eva2.util.annotation.Description;
import eva2.yaml.OptimizationConstructor;
import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.Yaml;
import java.io.FileInputStream; import java.io.FileInputStream;
@ -45,9 +46,10 @@ public class OptimizationParameters extends AbstractOptimizationParameters imple
OptimizationParameters instance = null; OptimizationParameters instance = null;
try { try {
FileInputStream fileStream = new FileInputStream(yamlFile); FileInputStream fileStream = new FileInputStream(yamlFile);
instance = (OptimizationParameters) new Yaml().load(fileStream); instance = (OptimizationParameters) new Yaml(new OptimizationConstructor()).load(fileStream);
} catch (Exception ex) { } catch (Exception ex) {
LOGGER.log(Level.WARNING, "Could not load OptimizationParameters.yml.", ex); System.out.println(ex.getStackTrace() + "\n" + ex.getMessage());
LOGGER.log(Level.INFO, "Could not load OptimizationParameters.yml.", ex);
} }
if (instance == null) { if (instance == null) {
@ -56,6 +58,14 @@ public class OptimizationParameters extends AbstractOptimizationParameters imple
return instance; return instance;
} }
/**
* Default instructor that sets up a default optimizer, problem and terminator.
*
* Currently defaults to:
* - Differential Evolution
* - F1Problem
* - EvaluationTerminator with 5000 evaluations
*/
public OptimizationParameters() { public OptimizationParameters() {
super(new DifferentialEvolution(), new F1Problem(), new EvaluationTerminator(5000)); super(new DifferentialEvolution(), new F1Problem(), new EvaluationTerminator(5000));
} }

View File

@ -200,10 +200,7 @@ public abstract class AbstractEAIndividual implements IndividualInterface, java.
if (!this.mutationOperator.equals(indy.mutationOperator)) { if (!this.mutationOperator.equals(indy.mutationOperator)) {
return false; return false;
} }
if (!this.crossoverOperator.equals(indy.crossoverOperator)) { return this.crossoverOperator.equals(indy.crossoverOperator);
return false;
}
return true;
} else { } else {
return false; return false;
} }

View File

@ -61,10 +61,7 @@ public class GAESIndividualBinaryDoubleData extends AbstractEAIndividual impleme
if (!((AbstractEAIndividual) this.doubleIndividual).equalGenotypes((AbstractEAIndividual) indy.doubleIndividual)) { if (!((AbstractEAIndividual) this.doubleIndividual).equalGenotypes((AbstractEAIndividual) indy.doubleIndividual)) {
return false; return false;
} }
if (!((AbstractEAIndividual) this.binaryIndividual).equalGenotypes((AbstractEAIndividual) indy.binaryIndividual)) { return ((AbstractEAIndividual) this.binaryIndividual).equalGenotypes((AbstractEAIndividual) indy.binaryIndividual);
return false;
}
return true;
} else { } else {
return false; return false;
} }

View File

@ -78,10 +78,7 @@ public class GAIndividualBinaryData extends AbstractEAIndividual implements Inte
if ((this.genotype == null) || (indy.genotype == null)) { if ((this.genotype == null) || (indy.genotype == null)) {
return false; return false;
} }
if (!this.genotype.equals(indy.genotype)) { return this.genotype.equals(indy.genotype);
return false;
}
return true;
} else { } else {
return false; return false;
} }

View File

@ -57,10 +57,7 @@ public class GAPIndividualProgramData extends AbstractEAIndividual implements In
if (!((AbstractEAIndividual) this.numberData).equalGenotypes((AbstractEAIndividual) indy.numberData)) { if (!((AbstractEAIndividual) this.numberData).equalGenotypes((AbstractEAIndividual) indy.numberData)) {
return false; return false;
} }
if (!((AbstractEAIndividual) this.programData).equalGenotypes((AbstractEAIndividual) indy.programData)) { return ((AbstractEAIndividual) this.programData).equalGenotypes((AbstractEAIndividual) indy.programData);
return false;
}
return true;
} else { } else {
return false; return false;
} }

View File

@ -130,10 +130,7 @@ public class GEIndividualProgramData extends AbstractEAIndividual implements Int
if ((this.genotype == null) || (indy.genotype == null)) { if ((this.genotype == null) || (indy.genotype == null)) {
return false; return false;
} }
if (!this.genotype.equals(indy.genotype)) { return this.genotype.equals(indy.genotype);
return false;
}
return true;
} else { } else {
return false; return false;
} }

View File

@ -57,10 +57,7 @@ public class GIOBGAIndividualIntegerPermutationData extends AbstractEAIndividual
if (!((AbstractEAIndividual) this.integerData).equalGenotypes((AbstractEAIndividual) indy.integerData)) { if (!((AbstractEAIndividual) this.integerData).equalGenotypes((AbstractEAIndividual) indy.integerData)) {
return false; return false;
} }
if (!((AbstractEAIndividual) this.permutationData).equalGenotypes((AbstractEAIndividual) indy.permutationData)) { return ((AbstractEAIndividual) this.permutationData).equalGenotypes((AbstractEAIndividual) indy.permutationData);
return false;
}
return true;
} else { } else {
return false; return false;
} }

View File

@ -14,21 +14,21 @@ public interface InterfaceDataTypeBinary {
* *
* @param length The lenght of the BitSet that is to be optimized * @param length The lenght of the BitSet that is to be optimized
*/ */
public void setBinaryDataLength(int length); void setBinaryDataLength(int length);
/** /**
* This method returns the length of the binary data set * This method returns the length of the binary data set
* *
* @return The number of bits stored * @return The number of bits stored
*/ */
public int size(); int size();
/** /**
* This method allows you to read the binary data * This method allows you to read the binary data
* *
* @return BitSet representing the binary data. * @return BitSet representing the binary data.
*/ */
public BitSet getBinaryData(); BitSet getBinaryData();
/** /**
* This method allows you to read the binary data without * This method allows you to read the binary data without
@ -36,14 +36,14 @@ public interface InterfaceDataTypeBinary {
* *
* @return BitSet representing the binary data. * @return BitSet representing the binary data.
*/ */
public BitSet getBinaryDataWithoutUpdate(); BitSet getBinaryDataWithoutUpdate();
/** /**
* This method allows you to set the binary data. * This method allows you to set the binary data.
* *
* @param binaryData The new binary data. * @param binaryData The new binary data.
*/ */
public void setBinaryPhenotype(BitSet binaryData); void setBinaryPhenotype(BitSet binaryData);
/** /**
* This method allows you to set the binary data, this can be used for * This method allows you to set the binary data, this can be used for
@ -51,5 +51,5 @@ public interface InterfaceDataTypeBinary {
* *
* @param binaryData The new binary data. * @param binaryData The new binary data.
*/ */
public void setBinaryGenotype(BitSet binaryData); void setBinaryGenotype(BitSet binaryData);
} }

View File

@ -14,14 +14,14 @@ public interface InterfaceDataTypeDouble {
* *
* @param length The lenght of the double[] that is to be optimized * @param length The lenght of the double[] that is to be optimized
*/ */
public void setDoubleDataLength(int length); void setDoubleDataLength(int length);
/** /**
* This method returns the length of the double data set * This method returns the length of the double data set
* *
* @return The number of doubles stored * @return The number of doubles stored
*/ */
public int size(); int size();
/** /**
* This method will set the range of the double attributes. * This method will set the range of the double attributes.
@ -31,21 +31,21 @@ public interface InterfaceDataTypeDouble {
* @param range The new range for the double data. * @param range The new range for the double data.
*/ */
@Parameter(name = "range", description = "The initialization range for the individual.") @Parameter(name = "range", description = "The initialization range for the individual.")
public void setDoubleRange(double[][] range); void setDoubleRange(double[][] range);
/** /**
* This method will return the range for all double attributes. * This method will return the range for all double attributes.
* *
* @return The range array. * @return The range array.
*/ */
public double[][] getDoubleRange(); double[][] getDoubleRange();
/** /**
* This method allows you to read the double data * This method allows you to read the double data
* *
* @return double[] representing the double data. * @return double[] representing the double data.
*/ */
public double[] getDoubleData(); double[] getDoubleData();
/** /**
* This method allows you to read the double data without * This method allows you to read the double data without
@ -53,7 +53,7 @@ public interface InterfaceDataTypeDouble {
* *
* @return double[] representing the double data. * @return double[] representing the double data.
*/ */
public double[] getDoubleDataWithoutUpdate(); double[] getDoubleDataWithoutUpdate();
/** /**
* This method allows you to set the double data, usually the phenotype data. Consider using * This method allows you to set the double data, usually the phenotype data. Consider using
@ -61,7 +61,7 @@ public interface InterfaceDataTypeDouble {
* *
* @param doubleData The new double data. * @param doubleData The new double data.
*/ */
public void setDoublePhenotype(double[] doubleData); void setDoublePhenotype(double[] doubleData);
/** /**
* This method allows you to set the double data, this can be used for * This method allows you to set the double data, this can be used for
@ -69,5 +69,5 @@ public interface InterfaceDataTypeDouble {
* *
* @param doubleData The new double data. * @param doubleData The new double data.
*/ */
public void setDoubleGenotype(double[] doubleData); void setDoubleGenotype(double[] doubleData);
} }

View File

@ -2,7 +2,7 @@ package eva2.optimization.individuals;
/** /**
* This interface gives access to a integer phenotype and except * This interface gives access to a integer phenotype and except
* for problemspecific operators should only be used by the * for problem specific operators should only be used by the
* optimization problem. * optimization problem.
*/ */
public interface InterfaceDataTypeInteger { public interface InterfaceDataTypeInteger {
@ -10,16 +10,16 @@ public interface InterfaceDataTypeInteger {
/** /**
* This method allows you to request a certain amount of int data * This method allows you to request a certain amount of int data
* *
* @param length The lenght of the int[] that is to be optimized * @param length The length of the int[] that is to be optimized
*/ */
public void setIntegerDataLength(int length); void setIntegerDataLength(int length);
/** /**
* This method returns the length of the int data set * This method returns the length of the int data set
* *
* @return The number of integers stored * @return The number of integers stored
*/ */
public int size(); int size();
/** /**
* This method will set the range of the int attributes. * This method will set the range of the int attributes.
@ -28,21 +28,21 @@ public interface InterfaceDataTypeInteger {
* *
* @param range The new range for the int data. * @param range The new range for the int data.
*/ */
public void setIntRange(int[][] range); void setIntRange(int[][] range);
/** /**
* This method will return the range for all int attributes. * This method will return the range for all int attributes.
* *
* @return The range array. * @return The range array.
*/ */
public int[][] getIntRange(); int[][] getIntRange();
/** /**
* This method allows you to read the int data * This method allows you to read the int data
* *
* @return int[] representing the int data. * @return int[] representing the int data.
*/ */
public int[] getIntegerData(); int[] getIntegerData();
/** /**
* This method allows you to read the int data without * This method allows you to read the int data without
@ -50,14 +50,14 @@ public interface InterfaceDataTypeInteger {
* *
* @return int[] representing the int data. * @return int[] representing the int data.
*/ */
public int[] getIntegerDataWithoutUpdate(); int[] getIntegerDataWithoutUpdate();
/** /**
* This method allows you to set the int data. * This method allows you to set the int data.
* *
* @param intData The new int data. * @param intData The new int data.
*/ */
public void setIntPhenotype(int[] intData); void setIntPhenotype(int[] intData);
/** /**
* This method allows you to set the int data, this can be used for * This method allows you to set the int data, this can be used for
@ -65,5 +65,5 @@ public interface InterfaceDataTypeInteger {
* *
* @param intData The new int data. * @param intData The new int data.
*/ */
public void setIntGenotype(int[] intData); void setIntGenotype(int[] intData);
} }

View File

@ -13,7 +13,7 @@ public interface InterfaceDataTypePermutation {
* *
* @param length int new length * @param length int new length
*/ */
public void setPermutationDataLength(int[] length); void setPermutationDataLength(int[] length);
/** /**
@ -21,7 +21,7 @@ public interface InterfaceDataTypePermutation {
* *
* @return int * @return int
*/ */
public int[] sizePermutation(); int[] sizePermutation();
/** /**
* This method allows you to read the permutation data * This method allows you to read the permutation data
@ -36,7 +36,7 @@ public interface InterfaceDataTypePermutation {
* *
* @return int[] representing the permutation. * @return int[] representing the permutation.
*/ */
public int[][] getPermutationDataWithoutUpdate(); int[][] getPermutationDataWithoutUpdate();
/** /**
* This method allows you to set the permutation. * This method allows you to set the permutation.
@ -53,5 +53,5 @@ public interface InterfaceDataTypePermutation {
*/ */
void setPermutationGenotype(int[][] perm); void setPermutationGenotype(int[][] perm);
public void setFirstindex(int[] firstindex); void setFirstindex(int[] firstindex);
} }

View File

@ -14,14 +14,14 @@ public interface InterfaceDataTypeProgram {
* *
* @param length The lenght of the double[] that is to be optimized * @param length The lenght of the double[] that is to be optimized
*/ */
public void setProgramDataLength(int length); void setProgramDataLength(int length);
/** /**
* This method allows you to read the program stored as Koza style node tree * This method allows you to read the program stored as Koza style node tree
* *
* @return AbstractGPNode representing the binary data. * @return AbstractGPNode representing the binary data.
*/ */
public InterfaceProgram[] getProgramData(); InterfaceProgram[] getProgramData();
/** /**
* This method allows you to read the Program data without * This method allows you to read the Program data without
@ -29,33 +29,33 @@ public interface InterfaceDataTypeProgram {
* *
* @return InterfaceProgram[] representing the Program. * @return InterfaceProgram[] representing the Program.
*/ */
public InterfaceProgram[] getProgramDataWithoutUpdate(); InterfaceProgram[] getProgramDataWithoutUpdate();
/** /**
* This method allows you to set the program. * This method allows you to set the program.
* *
* @param program The new program. * @param program The new program.
*/ */
public void SetProgramPhenotype(InterfaceProgram[] program); void SetProgramPhenotype(InterfaceProgram[] program);
/** /**
* This method allows you to set the program. * This method allows you to set the program.
* *
* @param program The new program. * @param program The new program.
*/ */
public void SetProgramGenotype(InterfaceProgram[] program); void SetProgramGenotype(InterfaceProgram[] program);
/** /**
* This method allows you to set the function area * This method allows you to set the function area
* *
* @param area The area contains functions and terminals * @param area The area contains functions and terminals
*/ */
public void SetFunctionArea(Object[] area); void SetFunctionArea(Object[] area);
/** /**
* This method allows you to get the function area * This method allows you to get the function area
* *
* @return The area contains functions and terminals * @return The area contains functions and terminals
*/ */
public Object[] getFunctionArea(); Object[] getFunctionArea();
} }

View File

@ -12,20 +12,20 @@ public interface InterfaceESIndividual {
* *
* @return BitSet * @return BitSet
*/ */
public double[] getDGenotype(); double[] getDGenotype();
/** /**
* This method will allow the user to set the current ES 'genotype'. * This method will allow the user to set the current ES 'genotype'.
* *
* @param b The new genotype of the Individual * @param b The new genotype of the Individual
*/ */
public void setDGenotype(double[] b); void setDGenotype(double[] b);
/** /**
* This method will return the range for all double attributes. * This method will return the range for all double attributes.
* *
* @return The range array. * @return The range array.
*/ */
public double[][] getDoubleRange(); double[][] getDoubleRange();
} }

View File

@ -14,7 +14,7 @@ public interface InterfaceGAIndividual {
* *
* @return BitSet * @return BitSet
*/ */
public BitSet getBGenotype(); BitSet getBGenotype();
/** /**
* This method will allow the user to set the current GA genotype. * This method will allow the user to set the current GA genotype.
@ -24,7 +24,7 @@ public interface InterfaceGAIndividual {
* *
* @param b The new genotype of the Individual * @param b The new genotype of the Individual
*/ */
public void setBGenotype(BitSet b); void setBGenotype(BitSet b);
/** /**
* This method allows the user to read the length of the genotype. * This method allows the user to read the length of the genotype.
@ -33,6 +33,6 @@ public interface InterfaceGAIndividual {
* *
* @return The length of the genotype. * @return The length of the genotype.
*/ */
public int getGenotypeLength(); int getGenotypeLength();
} }

View File

@ -12,14 +12,14 @@ public interface InterfaceGIIndividual {
* *
* @param length The lenght of the int[] that is to be optimized * @param length The lenght of the int[] that is to be optimized
*/ */
public void setIntegerDataLength(int length); void setIntegerDataLength(int length);
/** /**
* This method will return the range for all int attributes. * This method will return the range for all int attributes.
* *
* @return The range array. * @return The range array.
*/ */
public int[][] getIntRange(); int[][] getIntRange();
/** /**
* This method will set the range of the int attributes. * This method will set the range of the int attributes.
@ -28,14 +28,14 @@ public interface InterfaceGIIndividual {
* *
* @param range The new range for the int data. * @param range The new range for the int data.
*/ */
public void setIntRange(int[][] range); void setIntRange(int[][] range);
/** /**
* This method will allow the user to read the GI genotype * This method will allow the user to read the GI genotype
* *
* @return BitSet * @return BitSet
*/ */
public int[] getIGenotype(); int[] getIGenotype();
/** /**
* This method will allow the user to set the current GI genotype. * This method will allow the user to set the current GI genotype.
@ -45,7 +45,7 @@ public interface InterfaceGIIndividual {
* *
* @param b The new genotype of the Individual * @param b The new genotype of the Individual
*/ */
public void setIGenotype(int[] b); void setIGenotype(int[] b);
/** /**
* This method allows the user to read the length of the genotype. * This method allows the user to read the length of the genotype.
@ -54,5 +54,5 @@ public interface InterfaceGIIndividual {
* *
* @return The length of the genotype. * @return The length of the genotype.
*/ */
public int getGenotypeLength(); int getGenotypeLength();
} }

View File

@ -13,14 +13,14 @@ public interface InterfaceGPIndividual {
* *
* @return AbstractGPNode * @return AbstractGPNode
*/ */
public AbstractGPNode[] getPGenotype(); AbstractGPNode[] getPGenotype();
/** /**
* This method will allow the user to set the current program 'genotype'. * This method will allow the user to set the current program 'genotype'.
* *
* @param b The new program genotype of the Individual * @param b The new program genotype of the Individual
*/ */
public void setPGenotype(AbstractGPNode[] b); void setPGenotype(AbstractGPNode[] b);
/** /**
* This method will allow the user to set the current program 'genotype'. * This method will allow the user to set the current program 'genotype'.
@ -28,19 +28,19 @@ public interface InterfaceGPIndividual {
* @param b The new program genotype of the Individual * @param b The new program genotype of the Individual
* @param i The index where to insert the new program * @param i The index where to insert the new program
*/ */
public void setPGenotype(AbstractGPNode b, int i); void setPGenotype(AbstractGPNode b, int i);
/** /**
* This method allows you to get the function area * This method allows you to get the function area
* *
* @return area The area contains functions and terminals * @return area The area contains functions and terminals
*/ */
public Object[] getFunctionArea(); Object[] getFunctionArea();
/** /**
* Return the maximal allowed depth of a GP tree (or -1 if it does not apply). * Return the maximal allowed depth of a GP tree (or -1 if it does not apply).
* *
* @return * @return
*/ */
public int getMaxAllowedDepth(); int getMaxAllowedDepth();
} }

View File

@ -13,7 +13,7 @@ public interface InterfaceOBGAIndividual {
* *
* @return int[] genotype * @return int[] genotype
*/ */
public int[][] getOBGenotype(); int[][] getOBGenotype();
/** /**
@ -21,5 +21,5 @@ public interface InterfaceOBGAIndividual {
* *
* @param b int[] new genotype * @param b int[] new genotype
*/ */
public void setOBGenotype(int[][] b); void setOBGenotype(int[][] b);
} }

View File

@ -17,7 +17,7 @@ public interface InterfaceGADoubleCoding {
* @param correction Enable automatic correction is enabled. * @param correction Enable automatic correction is enabled.
* @return The float value. * @return The float value.
*/ */
public double decodeValue(BitSet refBitSet, double[] range, int[] locus, boolean correction); double decodeValue(BitSet refBitSet, double[] range, int[] locus, boolean correction);
/** /**
* This method codes a given double value directly into a BitSet at * This method codes a given double value directly into a BitSet at
@ -29,5 +29,5 @@ public interface InterfaceGADoubleCoding {
* @param refBitSet The BitSet where the questioned value is stored. * @param refBitSet The BitSet where the questioned value is stored.
* @param locus The position and length on the BitSet that is to be coded. * @param locus The position and length on the BitSet that is to be coded.
*/ */
public void codeValue(double value, double[] range, BitSet refBitSet, int[] locus); void codeValue(double value, double[] range, BitSet refBitSet, int[] locus);
} }

View File

@ -18,7 +18,7 @@ public interface InterfaceGAIntegerCoding {
* @param correction Enable automatic correction is enabled. * @param correction Enable automatic correction is enabled.
* @return The float value. * @return The float value.
*/ */
public int decodeValue(BitSet refBitSet, int[] range, int[] locus, boolean correction); int decodeValue(BitSet refBitSet, int[] range, int[] locus, boolean correction);
/** /**
* This method codes a given int value directly into a BitSet at * This method codes a given int value directly into a BitSet at
@ -30,12 +30,12 @@ public interface InterfaceGAIntegerCoding {
* @param refBitSet The BitSet where the questioned value is stored. * @param refBitSet The BitSet where the questioned value is stored.
* @param locus The position and length on the BitSet that is to be coded. * @param locus The position and length on the BitSet that is to be coded.
*/ */
public void codeValue(int value, int[] range, BitSet refBitSet, int[] locus); void codeValue(int value, int[] range, BitSet refBitSet, int[] locus);
/** /**
* This method will calculate how many bits are to be used to code a given value * This method will calculate how many bits are to be used to code a given value
* *
* @param range The range for the value. * @param range The range for the value.
*/ */
public int calculateNecessaryBits(int[] range); int calculateNecessaryBits(int[] range);
} }

View File

@ -11,12 +11,12 @@ public interface InterfaceProgram {
* *
* @param environment * @param environment
*/ */
public Object evaluate(eva2.problems.InterfaceProgramProblem environment); Object evaluate(eva2.problems.InterfaceProgramProblem environment);
/** /**
* This method returns a string representation of the current program. * This method returns a string representation of the current program.
* *
* @return string * @return string
*/ */
public String getStringRepresentation(); String getStringRepresentation();
} }

View File

@ -8,13 +8,13 @@ public interface InterfaceProcessElement {
/** /**
* This method will call the initialize method and will go to stall * This method will call the initialize method and will go to stall
*/ */
public void initProcessElementParametrization(); void initProcessElementParametrization();
/** /**
* This method will wait for the parametrisation result * This method will wait for the parametrisation result
* *
* @return int Result * @return int Result
*/ */
public boolean isFinished(); boolean isFinished();
} }

View File

@ -45,7 +45,7 @@ public class MOCCOChooseMOStrategy extends MOCCOPhase implements InterfaceProces
JPanel tmpP = new JPanel(); JPanel tmpP = new JPanel();
tmpP.setLayout(new GridBagLayout()); tmpP.setLayout(new GridBagLayout());
JButton tmpB; JButton tmpB;
BasicResourceLoader loader = BasicResourceLoader.instance(); BasicResourceLoader loader = BasicResourceLoader.getInstance();
byte[] bytes; byte[] bytes;
GridBagConstraints gbc = new GridBagConstraints(); GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.WEST; gbc.anchor = GridBagConstraints.WEST;

View File

@ -1,10 +1,10 @@
package eva2.optimization.mocco; package eva2.optimization.mocco;
import eva2.gui.MOCCOStandalone;
import eva2.gui.PropertyDoubleArray; import eva2.gui.PropertyDoubleArray;
import eva2.gui.PropertyEditorProvider; import eva2.gui.PropertyEditorProvider;
import eva2.gui.editor.GenericObjectEditor; import eva2.gui.editor.GenericObjectEditor;
import eva2.gui.MOCCOStandalone;
import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.individuals.AbstractEAIndividual;
import eva2.optimization.operator.moso.MOSOWeightedFitness; import eva2.optimization.operator.moso.MOSOWeightedFitness;
import eva2.optimization.operator.terminators.InterfaceTerminator; import eva2.optimization.operator.terminators.InterfaceTerminator;

View File

@ -1,9 +1,9 @@
package eva2.optimization.mocco; package eva2.optimization.mocco;
import eva2.gui.MOCCOStandalone;
import eva2.gui.PropertyEditorProvider; import eva2.gui.PropertyEditorProvider;
import eva2.gui.editor.GenericObjectEditor; import eva2.gui.editor.GenericObjectEditor;
import eva2.gui.MOCCOStandalone;
import eva2.optimization.operator.terminators.InterfaceTerminator; import eva2.optimization.operator.terminators.InterfaceTerminator;
import eva2.optimization.population.Population; import eva2.optimization.population.Population;
import eva2.optimization.strategies.GeneticAlgorithm; import eva2.optimization.strategies.GeneticAlgorithm;

View File

@ -1,9 +1,9 @@
package eva2.optimization.mocco; package eva2.optimization.mocco;
import eva2.gui.MOCCOStandalone;
import eva2.gui.PropertyEditorProvider; import eva2.gui.PropertyEditorProvider;
import eva2.gui.editor.GenericObjectEditor; import eva2.gui.editor.GenericObjectEditor;
import eva2.gui.MOCCOStandalone;
import eva2.optimization.operator.migration.SOBestMigration; import eva2.optimization.operator.migration.SOBestMigration;
import eva2.optimization.operator.moso.MOSOLpMetric; import eva2.optimization.operator.moso.MOSOLpMetric;
import eva2.optimization.operator.terminators.InterfaceTerminator; import eva2.optimization.operator.terminators.InterfaceTerminator;

View File

@ -1,9 +1,9 @@
package eva2.optimization.mocco; package eva2.optimization.mocco;
import eva2.gui.MOCCOStandalone;
import eva2.gui.PropertyEditorProvider; import eva2.gui.PropertyEditorProvider;
import eva2.gui.editor.GenericObjectEditor; import eva2.gui.editor.GenericObjectEditor;
import eva2.gui.MOCCOStandalone;
import eva2.optimization.operator.terminators.InterfaceTerminator; import eva2.optimization.operator.terminators.InterfaceTerminator;
import eva2.optimization.strategies.GeneticAlgorithm; import eva2.optimization.strategies.GeneticAlgorithm;
import eva2.optimization.strategies.InterfaceOptimizer; import eva2.optimization.strategies.InterfaceOptimizer;

View File

@ -1,10 +1,10 @@
package eva2.optimization.mocco; package eva2.optimization.mocco;
import eva2.gui.MOCCOStandalone;
import eva2.gui.PropertyDoubleArray; import eva2.gui.PropertyDoubleArray;
import eva2.gui.PropertyEditorProvider; import eva2.gui.PropertyEditorProvider;
import eva2.gui.editor.GenericObjectEditor; import eva2.gui.editor.GenericObjectEditor;
import eva2.gui.MOCCOStandalone;
import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.individuals.AbstractEAIndividual;
import eva2.optimization.operator.moso.MOSOWeightedFitness; import eva2.optimization.operator.moso.MOSOWeightedFitness;
import eva2.optimization.operator.terminators.InterfaceTerminator; import eva2.optimization.operator.terminators.InterfaceTerminator;

View File

@ -1,9 +1,9 @@
package eva2.optimization.mocco; package eva2.optimization.mocco;
import eva2.gui.MOCCOStandalone;
import eva2.gui.PropertyEditorProvider; import eva2.gui.PropertyEditorProvider;
import eva2.gui.editor.GenericObjectEditor; import eva2.gui.editor.GenericObjectEditor;
import eva2.gui.MOCCOStandalone;
import eva2.optimization.operator.migration.SOBestMigration; import eva2.optimization.operator.migration.SOBestMigration;
import eva2.optimization.operator.moso.MOSOWeightedLPTchebycheff; import eva2.optimization.operator.moso.MOSOWeightedLPTchebycheff;
import eva2.optimization.operator.terminators.InterfaceTerminator; import eva2.optimization.operator.terminators.InterfaceTerminator;

View File

@ -10,5 +10,5 @@ public interface InterfaceParetoFrontView {
* the data has changed most likely due to changes in * the data has changed most likely due to changes in
* the problem definition * the problem definition
*/ */
public void updateView(); void updateView();
} }

View File

@ -10,5 +10,5 @@ public interface InterfaceRefPointListener {
* *
* @param point The selected point, most likely 2d * @param point The selected point, most likely 2d
*/ */
public void refPointGiven(double[] point); void refPointGiven(double[] point);
} }

View File

@ -13,5 +13,5 @@ public interface InterfaceRefSolutionListener {
* *
* @param indy The selected individual * @param indy The selected individual
*/ */
public void individualSelected(AbstractEAIndividual indy); void individualSelected(AbstractEAIndividual indy);
} }

View File

@ -1,10 +1,10 @@
package eva2.optimization.mocco.paretofrontviewer; package eva2.optimization.mocco.paretofrontviewer;
import eva2.gui.MOCCOStandalone;
import eva2.gui.plot.FunctionArea; import eva2.gui.plot.FunctionArea;
import eva2.gui.plot.GraphPointSet; import eva2.gui.plot.GraphPointSet;
import eva2.gui.plot.InterfaceDPointWithContent; import eva2.gui.plot.InterfaceDPointWithContent;
import eva2.gui.MOCCOStandalone;
import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.individuals.AbstractEAIndividual;
import eva2.optimization.population.Population; import eva2.optimization.population.Population;
import eva2.problems.InterfaceMultiObjectiveDeNovoProblem; import eva2.problems.InterfaceMultiObjectiveDeNovoProblem;

View File

@ -1,9 +1,9 @@
package eva2.optimization.modules; package eva2.optimization.modules;
import eva2.optimization.InterfaceOptimizationParameters;
import eva2.optimization.InterfaceProcessor; import eva2.optimization.InterfaceProcessor;
import eva2.optimization.OptimizationStateListener; import eva2.optimization.OptimizationStateListener;
import eva2.optimization.InterfaceOptimizationParameters;
import eva2.optimization.Processor; import eva2.optimization.Processor;
import java.io.Serializable; import java.io.Serializable;

View File

@ -7,10 +7,10 @@ import java.io.Serializable;
/** /**
* Starts a statistics GUI and the GOProcessor thread. * Starts a statistics GUI and the Processor thread.
*/ */
@SuppressWarnings("unused") @SuppressWarnings("unused")
public class GOModuleAdapter extends GenericModuleAdapter implements ModuleAdapter, Serializable { public class OptimizationModuleAdapter extends GenericModuleAdapter implements ModuleAdapter, Serializable {
private static final String moduleName = "Genetic_Optimization"; private static final String moduleName = "Genetic_Optimization";
@ -22,22 +22,22 @@ public class GOModuleAdapter extends GenericModuleAdapter implements ModuleAdapt
} }
/** /**
* Starts a statistics GUI and the GOProcessor thread. * Starts a statistics GUI and the Processor thread.
* *
* @param adapterName the title of the ModuleAdapter * @param adapterName the title of the ModuleAdapter
*/ */
public GOModuleAdapter(String adapterName) { public OptimizationModuleAdapter(String adapterName) {
super(adapterName, "", OptimizationParameters.getInstance(), false); super(adapterName, "", OptimizationParameters.getInstance(), false);
} }
/** /**
* Starts a statistics GUI and the GOProcessor thread with a given OptimizationParameters file. * Starts a statistics GUI and the Processor thread with a given OptimizationParameters file.
* *
* @param adapterName the title of the ModuleAdapter * @param adapterName the title of the ModuleAdapter
* @param optimizationParameters the client instance * @param optimizationParameters the client instance
* @param noGuiLogFile * @param noGuiLogFile
*/ */
public GOModuleAdapter(String adapterName, InterfaceOptimizationParameters optimizationParameters, String noGuiLogFile) { public OptimizationModuleAdapter(String adapterName, InterfaceOptimizationParameters optimizationParameters, String noGuiLogFile) {
super(adapterName, "", optimizationParameters, false, noGuiLogFile); super(adapterName, "", optimizationParameters, false, noGuiLogFile);
} }
} }

View File

@ -158,23 +158,6 @@ public abstract class AbstractArchiving implements InterfaceArchiving, java.io.S
p++; p++;
} }
/**********************************************************************************************************************
* These are for GUI
*/
// /** This method allows you to toggle the debug mode.
// * @param b True in case of the debug mode.
// */
// public void setDebugFront(boolean b) {
// this.debug = b;
// }
// public boolean getDebugFront() {
// return this.debug;
// }
// public String debugFrontTipText() {
// return "Toggles the debug mode.";
// }
/** /**
* Toggle the use of obeying the constraint violation principle * Toggle the use of obeying the constraint violation principle
* of Deb * of Deb

View File

@ -9,7 +9,7 @@ import java.util.Arrays;
public class ArchivingNSGAIISMeasure extends ArchivingNSGAII { public class ArchivingNSGAIISMeasure extends ArchivingNSGAII {
/** /**
* This method will cacluated the NSGAII crowding distance * This method will calculated the NSGAII crowding distance
* for all individuals * for all individuals
* *
* @param fronts The pareto fronts * @param fronts The pareto fronts
@ -18,14 +18,14 @@ public class ArchivingNSGAIISMeasure extends ArchivingNSGAII {
public void calculateCrowdingDistance(Population[] fronts) { public void calculateCrowdingDistance(Population[] fronts) {
//TODO Dimension der Zielfunktion checken //TODO Dimension der Zielfunktion checken
for (int rank = 0; rank < fronts.length; rank++) { for (Population front : fronts) {
calculateCrowdingDistance(fronts[rank]); calculateCrowdingDistance(front);
} }
} }
/** /**
* This mehtod will test if a given individual is dominant within * This method will test if a given individual is dominant within
* a given population * a given population
* *
* @param indy The individual that is to be tested. * @param indy The individual that is to be tested.
@ -68,7 +68,7 @@ public class ArchivingNSGAIISMeasure extends ArchivingNSGAII {
Arrays.sort(frontArray, new EAIndividualComparator(0)); Arrays.sort(frontArray, new EAIndividualComparator(0));
((AbstractEAIndividual) frontArray[0]).putData("HyperCube", Double.MAX_VALUE); //die beiden aussen bekommen maximal wert als smeasure ((AbstractEAIndividual) frontArray[0]).putData("HyperCube", Double.MAX_VALUE); //die beiden aussen bekommen maximal wert als measure
((AbstractEAIndividual) frontArray[frontArray.length - 1]).putData("HyperCube", Double.MAX_VALUE); ((AbstractEAIndividual) frontArray[frontArray.length - 1]).putData("HyperCube", Double.MAX_VALUE);
v[0] = Double.MAX_VALUE; v[0] = Double.MAX_VALUE;
v[frontArray.length - 1] = Double.MAX_VALUE; v[frontArray.length - 1] = Double.MAX_VALUE;

View File

@ -8,7 +8,7 @@ import eva2.util.annotation.Description;
import java.util.ArrayList; import java.util.ArrayList;
/** /**
* The Pareto envelope sorting algorithm using a hybergrid and * The Pareto envelope sorting algorithm using a hypergrid and
* the so called squeeze factor. * the so called squeeze factor.
*/ */
@Description("Pareto Envelope-based Selection Algorithm revision 2.0.") @Description("Pareto Envelope-based Selection Algorithm revision 2.0.")
@ -85,7 +85,6 @@ public class ArchivingPESAII extends AbstractArchiving implements java.io.Serial
double[][] bounds; double[][] bounds;
double[] tmpFit; double[] tmpFit;
AbstractEAIndividual tmpIndy; AbstractEAIndividual tmpIndy;
// boolean debug = true;
// first calculate the bounds of the search space // first calculate the bounds of the search space
bounds = new double[pop.get(0).getFitness().length][2]; bounds = new double[pop.get(0).getFitness().length][2];
@ -93,10 +92,9 @@ public class ArchivingPESAII extends AbstractArchiving implements java.io.Serial
bounds[i][0] = Double.POSITIVE_INFINITY; bounds[i][0] = Double.POSITIVE_INFINITY;
bounds[i][1] = Double.NEGATIVE_INFINITY; bounds[i][1] = Double.NEGATIVE_INFINITY;
} }
// if (debug) System.out.println("The individuals:");
for (int i = 0; i < pop.size(); i++) { for (int i = 0; i < pop.size(); i++) {
tmpFit = pop.get(i).getFitness(); tmpFit = pop.get(i).getFitness();
// if (debug) System.out.println("Individual "+i+": "+tmpFit[0] +"/"+tmpFit[1]);
result[i] = 0; result[i] = 0;
for (int j = 0; j < tmpFit.length; j++) { for (int j = 0; j < tmpFit.length; j++) {
if (tmpFit[j] < bounds[j][0]) { if (tmpFit[j] < bounds[j][0]) {
@ -107,15 +105,11 @@ public class ArchivingPESAII extends AbstractArchiving implements java.io.Serial
} }
} }
} }
// if (debug) {
// System.out.println("The bounds are ("+bounds[0][0]+"/"+bounds[0][1]+")("+bounds[1][0]+"/"+bounds[1][1]+")");
// System.out.println("Gridwidth is "+((bounds[0][1] - bounds[0][0])/this.gridSize)+"/"+((bounds[1][1] - bounds[1][0])/this.gridSize));
// }
// now that i got the bounds i can calculate the squeeze grid // now that i got the bounds i can calculate the squeeze grid
int[] curGrid = new int[bounds.length], tmpGrid = new int[bounds.length]; int[] curGrid, tmpGrid = new int[bounds.length];
double[] grid = new double[bounds.length]; double[] grid = new double[bounds.length];
ArrayList coll; ArrayList<Integer> coll;
boolean sameGrid; boolean sameGrid;
for (int i = 0; i < pop.size(); i++) { for (int i = 0; i < pop.size(); i++) {
if (result[i] == 0) { if (result[i] == 0) {
@ -123,16 +117,11 @@ public class ArchivingPESAII extends AbstractArchiving implements java.io.Serial
// haven't calculated the squeeze factor for this guy yet // haven't calculated the squeeze factor for this guy yet
// first i'll calculate the grid position this guy is in // first i'll calculate the grid position this guy is in
tmpFit = pop.get(i).getFitness(); tmpFit = pop.get(i).getFitness();
coll = new ArrayList(); coll = new ArrayList<>();
for (int j = 0; j < tmpFit.length; j++) { for (int j = 0; j < tmpFit.length; j++) {
grid[j] = (bounds[j][1] - bounds[j][0]) / this.gridSize; grid[j] = (bounds[j][1] - bounds[j][0]) / this.gridSize;
curGrid[j] = (int) ((tmpFit[j] - bounds[j][0]) / grid[j]); curGrid[j] = (int) ((tmpFit[j] - bounds[j][0]) / grid[j]);
} }
// if (debug) {
// System.out.println("Indy "+i+" ("+tmpFit[0] +"/"+tmpFit[1]+") unassigned is in grid ["+curGrid[0]+"/"+curGrid[1]+"]");
// System.out.println("");
// System.out.println("Checking for individuals in the same grid");
// }
coll.add(i); coll.add(i);
for (int j = i + 1; j < pop.size(); j++) { for (int j = i + 1; j < pop.size(); j++) {
if (result[j] == 0) { if (result[j] == 0) {
@ -142,25 +131,18 @@ public class ArchivingPESAII extends AbstractArchiving implements java.io.Serial
sameGrid = true; sameGrid = true;
for (int k = 0; k < tmpFit.length; k++) { for (int k = 0; k < tmpFit.length; k++) {
tmpGrid[k] = (int) ((tmpFit[k] - bounds[k][0]) / grid[k]); tmpGrid[k] = (int) ((tmpFit[k] - bounds[k][0]) / grid[k]);
if (curGrid[k] == tmpGrid[k]) { sameGrid &= curGrid[k] == tmpGrid[k];
sameGrid &= true;
} else {
sameGrid &= false;
}
} }
if (sameGrid) { if (sameGrid) {
coll.add(j); coll.add(j);
} }
// if (debug) {
// System.out.println("Checking indy "+j+" ("+tmpFit[0] +"/"+tmpFit[1]+") in grid ["+tmpGrid[0]+"/"+tmpGrid[1]+"]");
// }
} }
} }
// now i got all the boogies of the same grid element // now i got all the boogies of the same grid element
// lets assign them their squeeze factor // lets assign them their squeeze factor
for (int j = 0; j < coll.size(); j++) { for (int j = 0; j < coll.size(); j++) {
result[(int) coll.get(j)] = coll.size(); result[coll.get(j)] = coll.size();
tmpIndy = pop.get(((Integer) coll.get(j)).intValue()); tmpIndy = pop.get(coll.get(j).intValue());
tmpIndy.putData("SqueezeFactor", coll.size()); tmpIndy.putData("SqueezeFactor", coll.size());
tmpIndy.putData("GridBox", curGrid); tmpIndy.putData("GridBox", curGrid);
} }

View File

@ -12,7 +12,7 @@ public interface InterfaceArchiving {
* *
* @return the deep clone * @return the deep clone
*/ */
public Object clone(); Object clone();
/** /**
* This method allows you to merge populations into an archive. * This method allows you to merge populations into an archive.
@ -21,5 +21,5 @@ public interface InterfaceArchiving {
* *
* @param pop The population that may add Individuals to the archive. * @param pop The population that may add Individuals to the archive.
*/ */
public void addElementsToArchive(Population pop); void addElementsToArchive(Population pop);
} }

View File

@ -14,7 +14,7 @@ public interface InterfaceInformationRetrieval {
* *
* @return the deep clone * @return the deep clone
*/ */
public Object clone(); Object clone();
/** /**
* This method will allow Information Retrieval from a archive onto * This method will allow Information Retrieval from a archive onto
@ -22,6 +22,6 @@ public interface InterfaceInformationRetrieval {
* *
* @param pop The population. * @param pop The population.
*/ */
public void retrieveInformationFrom(Population pop); void retrieveInformationFrom(Population pop);
} }

View File

@ -14,7 +14,7 @@ public interface InterfaceRemoveSurplusIndividuals {
* *
* @return the deep clone * @return the deep clone
*/ */
public Object clone(); Object clone();
/** /**
* This method will remove surplus individuals * This method will remove surplus individuals
@ -22,5 +22,5 @@ public interface InterfaceRemoveSurplusIndividuals {
* *
* @param archive * @param archive
*/ */
public void removeSurplusIndividuals(Population archive); void removeSurplusIndividuals(Population archive);
} }

View File

@ -10,7 +10,7 @@ public interface InterfaceClassification {
* *
* @return the deep clone * @return the deep clone
*/ */
public Object clone(); Object clone();
/** /**
* This method will initialize the classificator * This method will initialize the classificator
@ -18,7 +18,7 @@ public interface InterfaceClassification {
* @param space The double[n][d] space* * @param space The double[n][d] space*
* @param type The classes [0,1,..] * @param type The classes [0,1,..]
*/ */
public void init(double[][] space, int[] type); void init(double[][] space, int[] type);
/** /**
* This method allows you to train the classificator based on * This method allows you to train the classificator based on
@ -28,7 +28,7 @@ public interface InterfaceClassification {
* @param space The double[n][d] space * @param space The double[n][d] space
* @param type The int[n] classes [0,1,..] * @param type The int[n] classes [0,1,..]
*/ */
public void train(double[][] space, int[] type); void train(double[][] space, int[] type);
/** /**
* This method will classify a given data point * This method will classify a given data point
@ -36,5 +36,5 @@ public interface InterfaceClassification {
* @param point The double[d] data point. * @param point The double[d] data point.
* @return type The resulting class. * @return type The resulting class.
*/ */
public int getClassFor(double[] point); int getClassFor(double[] point);
} }

View File

@ -180,11 +180,7 @@ public class ClusteringDensityBased implements InterfaceClusteringDistanceParam,
Population tmpPop = new Population(species1.size() + species2.size()); Population tmpPop = new Population(species1.size() + species2.size());
tmpPop.addPopulation(species1); tmpPop.addPopulation(species1);
tmpPop.addPopulation(species2); tmpPop.addPopulation(species2);
if (this.cluster(tmpPop, referencePop).length <= 2) { return this.cluster(tmpPop, referencePop).length <= 2;
return true;
} else {
return false;
}
} }
} }

View File

@ -354,11 +354,7 @@ public class ClusteringKMeans implements InterfaceClustering, java.io.Serializab
@Override @Override
public boolean mergingSpecies(Population species1, Population species2, Population referencePop) { public boolean mergingSpecies(Population species1, Population species2, Population referencePop) {
// TODO i could use the BIC metric from X-means to calculate this // TODO i could use the BIC metric from X-means to calculate this
if (metric.distance(species1.getBestEAIndividual(), species2.getBestEAIndividual()) < mergeDist) { return metric.distance(species1.getBestEAIndividual(), species2.getBestEAIndividual()) < mergeDist;
return true;
} else {
return false;
}
} }
// /** This method decides if a unclustered individual belongs to an already established species. // /** This method decides if a unclustered individual belongs to an already established species.

View File

@ -374,20 +374,12 @@ public class ClusteringNearestBetter implements InterfaceClustering, Serializabl
public boolean mergingSpecies(Population species1, Population species2, Population referenceSet) { public boolean mergingSpecies(Population species1, Population species2, Population referenceSet) {
getRefData(referenceSet, species1); getRefData(referenceSet, species1);
if (testConvergingSpeciesOnBestOnly) { if (testConvergingSpeciesOnBestOnly) {
if (this.metric.distance(species1.getBestEAIndividual(), species2.getBestEAIndividual()) < this.currentDistThreshold()) { return this.metric.distance(species1.getBestEAIndividual(), species2.getBestEAIndividual()) < this.currentDistThreshold();
return true;
} else {
return false;
}
} else { } else {
Population tmpPop = new Population(species1.size() + species2.size()); Population tmpPop = new Population(species1.size() + species2.size());
tmpPop.addPopulation(species1); tmpPop.addPopulation(species1);
tmpPop.addPopulation(species2); tmpPop.addPopulation(species2);
if (this.cluster(tmpPop, referenceSet).length <= 2) { return this.cluster(tmpPop, referenceSet).length <= 2;
return true;
} else {
return false;
}
} }
} }

View File

@ -16,7 +16,7 @@ public interface InterfaceClustering {
* *
* @return the deep clone * @return the deep clone
*/ */
public Object clone(); Object clone();
/** /**
* This method allows you to search for clusters in a given population. The method * This method allows you to search for clusters in a given population. The method
@ -37,7 +37,7 @@ public interface InterfaceClustering {
* @param referenceSet a reference population for dynamic measures * @param referenceSet a reference population for dynamic measures
* @return Population[] * @return Population[]
*/ */
public Population[] cluster(Population pop, Population referenceSet); Population[] cluster(Population pop, Population referenceSet);
/** /**
* This method allows you to decide if two species are to be merged regarding this clustering algorithm. * This method allows you to decide if two species are to be merged regarding this clustering algorithm.
@ -51,7 +51,7 @@ public interface InterfaceClustering {
* @param referenceSet a reference population for dynamic measures * @param referenceSet a reference population for dynamic measures
* @return True if species converge, else False. * @return True if species converge, else False.
*/ */
public boolean mergingSpecies(Population species1, Population species2, Population referenceSet); boolean mergingSpecies(Population species1, Population species2, Population referenceSet);
/** /**
* Do some pre-calculations on a population for clustering. If additional population data * Do some pre-calculations on a population for clustering. If additional population data
@ -59,7 +59,7 @@ public interface InterfaceClustering {
* *
* @param pop * @param pop
*/ */
public String initClustering(Population pop); String initClustering(Population pop);
/** /**
* Try to associate a set of loners with a given set of species. Return a list * Try to associate a set of loners with a given set of species. Return a list
@ -77,5 +77,5 @@ public interface InterfaceClustering {
* @param referenceSet a reference population for dynamic measures * @param referenceSet a reference population for dynamic measures
* @return associative list matching loners to species. * @return associative list matching loners to species.
*/ */
public int[] associateLoners(Population loners, Population[] species, Population referenceSet); int[] associateLoners(Population loners, Population[] species, Population referenceSet);
} }

View File

@ -6,7 +6,7 @@ package eva2.optimization.operator.cluster;
* @author mkron * @author mkron
*/ */
public interface InterfaceClusteringDistanceParam extends InterfaceClustering { public interface InterfaceClusteringDistanceParam extends InterfaceClustering {
public double getClustDistParam(); double getClustDistParam();
public void setClustDistParam(double param); void setClustDistParam(double param);
} }

View File

@ -8,7 +8,7 @@ import eva2.optimization.operator.distancemetric.InterfaceDistanceMetric;
* @author mkron * @author mkron
*/ */
public interface InterfaceClusteringMetricBased { public interface InterfaceClusteringMetricBased {
public InterfaceDistanceMetric getMetric(); InterfaceDistanceMetric getMetric();
public void setMetric(InterfaceDistanceMetric m); void setMetric(InterfaceDistanceMetric m);
} }

View File

@ -41,11 +41,7 @@ public class ConstObjectivesInEqualityBiggerThanLinear implements InterfaceConst
if (d.length != 2) { if (d.length != 2) {
return true; return true;
} }
if ((this.m * d[0] + this.b) < d[1]) { return (this.m * d[0] + this.b) < d[1];
return true;
} else {
return false;
}
} }
} }

View File

@ -38,11 +38,7 @@ public class ConstObjectivesInEqualityBiggerThanSurface implements InterfaceCons
@Override @Override
public boolean isValid(AbstractEAIndividual indy) { public boolean isValid(AbstractEAIndividual indy) {
double[] d = indy.getFitness(); double[] d = indy.getFitness();
if (this.getScalarProduct(norm, this.getSubstraction(d, base)) >= 0) { return this.getScalarProduct(norm, this.getSubstraction(d, base)) >= 0;
return true;
} else {
return false;
}
} }
private double[] getSubstraction(double[] a, double[] b) { private double[] getSubstraction(double[] a, double[] b) {

View File

@ -41,10 +41,6 @@ public class ConstObjectivesInEqualityLesserThanLinear implements InterfaceConst
if (d.length != 2) { if (d.length != 2) {
return true; return true;
} }
if ((this.m * d[0] + this.b) > d[1]) { return (this.m * d[0] + this.b) > d[1];
return true;
} else {
return false;
}
} }
} }

View File

@ -38,11 +38,7 @@ public class ConstObjectivesInEqualitySmallerThanSurface implements InterfaceCon
@Override @Override
public boolean isValid(AbstractEAIndividual indy) { public boolean isValid(AbstractEAIndividual indy) {
double[] d = indy.getFitness(); double[] d = indy.getFitness();
if (this.getScalarProduct(norm, this.getSubstraction(d, base)) < 0) { return this.getScalarProduct(norm, this.getSubstraction(d, base)) < 0;
return true;
} else {
return false;
}
} }
private double[] getSubstraction(double[] a, double[] b) { private double[] getSubstraction(double[] a, double[] b) {

View File

@ -13,7 +13,7 @@ public interface InterfaceConstraint {
* *
* @return the deep clone * @return the deep clone
*/ */
public Object clone(); Object clone();
/** /**
* This method allows you wether or not a given individual * This method allows you wether or not a given individual
@ -22,5 +22,5 @@ public interface InterfaceConstraint {
* @param indy The individual to check. * @param indy The individual to check.
* @return true if valid false else. * @return true if valid false else.
*/ */
public boolean isValid(AbstractEAIndividual indy); boolean isValid(AbstractEAIndividual indy);
} }

View File

@ -10,7 +10,7 @@ public interface InterfaceDoubleConstraint {
* *
* @return the deep clone * @return the deep clone
*/ */
public Object clone(); Object clone();
/** /**
* Returns the boolean information whether the constraint is satisfied. * Returns the boolean information whether the constraint is satisfied.
@ -18,7 +18,7 @@ public interface InterfaceDoubleConstraint {
* @param indyX * @param indyX
* @return * @return
*/ */
public boolean isSatisfied(double[] indyX); boolean isSatisfied(double[] indyX);
/** /**
* Return the absolute (positive) degree of violation or zero if the constraint * Return the absolute (positive) degree of violation or zero if the constraint
@ -27,5 +27,5 @@ public interface InterfaceDoubleConstraint {
* @param indyX possibly the decoded individual position * @param indyX possibly the decoded individual position
* @return true if valid false else. * @return true if valid false else.
*/ */
public double getViolation(double[] indyX); double getViolation(double[] indyX);
} }

View File

@ -86,11 +86,7 @@ public class CrossoverOBGAPMX implements InterfaceCrossover, java.io.Serializabl
*/ */
@Override @Override
public boolean equals(Object crossover) { public boolean equals(Object crossover) {
if (crossover instanceof CrossoverOBGAPMX) { return crossover instanceof CrossoverOBGAPMX;
return true;
} else {
return false;
}
} }
@Override @Override

View File

@ -84,11 +84,7 @@ public class CrossoverOBGAPMXUniform implements InterfaceCrossover, java.io.Seri
*/ */
@Override @Override
public boolean equals(Object crossover) { public boolean equals(Object crossover) {
if (crossover instanceof CrossoverOBGAPMXUniform) { return crossover instanceof CrossoverOBGAPMXUniform;
return true;
} else {
return false;
}
} }

View File

@ -15,7 +15,7 @@ public interface InterfaceCrossover {
* *
* @return The clone * @return The clone
*/ */
public Object clone(); Object clone();
/** /**
* This method performs crossover on two individuals. Note: the genotype of the individuals * This method performs crossover on two individuals. Note: the genotype of the individuals
@ -24,7 +24,7 @@ public interface InterfaceCrossover {
* @param indy1 The first individual * @param indy1 The first individual
* @param partners The second individual * @param partners The second individual
*/ */
public AbstractEAIndividual[] mate(AbstractEAIndividual indy1, Population partners); AbstractEAIndividual[] mate(AbstractEAIndividual indy1, Population partners);
/** /**
* This method will allow the crossover operator to be initialized depending on the * This method will allow the crossover operator to be initialized depending on the
@ -35,7 +35,7 @@ public interface InterfaceCrossover {
* @param individual The individual that will be mutated. * @param individual The individual that will be mutated.
* @param opt The optimization problem. * @param opt The optimization problem.
*/ */
public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt); void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt);
/** /**
* This method allows you to get a string representation of the mutation * This method allows you to get a string representation of the mutation
@ -43,7 +43,7 @@ public interface InterfaceCrossover {
* *
* @return A descriptive string. * @return A descriptive string.
*/ */
public String getStringRepresentation(); String getStringRepresentation();
/** /**
* This method allows you to evaluate wether two crossover operators * This method allows you to evaluate wether two crossover operators
@ -52,5 +52,5 @@ public interface InterfaceCrossover {
* @param crossover The other crossover operator * @param crossover The other crossover operator
*/ */
@Override @Override
public boolean equals(Object crossover); boolean equals(Object crossover);
} }

View File

@ -7,7 +7,7 @@ public interface InterfaceEvaluatingCrossoverOperator extends InterfaceCrossover
* *
* @return * @return
*/ */
public int getEvaluations(); int getEvaluations();
public void resetEvaluations(); void resetEvaluations();
} }

View File

@ -137,7 +137,7 @@ public class PropertyCrossoverMixerEditor extends JPanel implements PropertyEdit
* This method updates the server list * This method updates the server list
*/ */
private void updateTargetList() { private void updateTargetList() {
BasicResourceLoader loader = BasicResourceLoader.instance(); BasicResourceLoader loader = BasicResourceLoader.getInstance();
byte[] bytes; byte[] bytes;
InterfaceCrossover[] list = this.crossoverMixer.getSelectedCrossers(); InterfaceCrossover[] list = this.crossoverMixer.getSelectedCrossers();
double[] weights = this.crossoverMixer.getWeights(); double[] weights = this.crossoverMixer.getWeights();

View File

@ -16,7 +16,7 @@ public interface InterfaceDistanceMetric {
* *
* @return the deep clone * @return the deep clone
*/ */
public Object clone(); Object clone();
/** /**
* This method allows you to compute the distance between two individuals. * This method allows you to compute the distance between two individuals.
@ -27,5 +27,5 @@ public interface InterfaceDistanceMetric {
* @param indy2 The second individual. * @param indy2 The second individual.
* @return double * @return double
*/ */
public double distance(AbstractEAIndividual indy1, AbstractEAIndividual indy2); double distance(AbstractEAIndividual indy1, AbstractEAIndividual indy2);
} }

View File

@ -14,6 +14,6 @@ public interface InterfaceFitnessModifier {
* your problem to store the unaltered fitness somewhere else so that * your problem to store the unaltered fitness somewhere else so that
* you may still fetch it! * you may still fetch it!
*/ */
public void modifyFitness(Population population); void modifyFitness(Population population);
} }

View File

@ -20,12 +20,12 @@ public interface InterfaceInitialization {
* @param indy the target individual to initialize * @param indy the target individual to initialize
* @param problem the problem instance under consideration * @param problem the problem instance under consideration
*/ */
public void initialize(AbstractEAIndividual indy, InterfaceOptimizationProblem problem); void initialize(AbstractEAIndividual indy, InterfaceOptimizationProblem problem);
/** /**
* A specific cloning method. * A specific cloning method.
* *
* @return * @return
*/ */
public InterfaceInitialization clone(); InterfaceInitialization clone();
} }

Some files were not shown because too many files have changed in this diff Show More