diff --git a/src/eva2/client/EvAClient.java b/src/eva2/client/EvAClient.java index be550c26..e205584e 100644 --- a/src/eva2/client/EvAClient.java +++ b/src/eva2/client/EvAClient.java @@ -498,8 +498,7 @@ public class EvAClient implements RemoteStateListener { gbConstraints.fill = GridBagConstraints.HORIZONTAL; gbConstraints.anchor = GridBagConstraints.PAGE_END; mainFrame.add(statusBar, gbConstraints); - - mainFrame.pack(); + mainFrame.setVisible(true); } if (useDefaultModule != null) { diff --git a/src/eva2/gui/EvAModuleButtonPanelMaker.java b/src/eva2/gui/EvAModuleButtonPanelMaker.java index 0771b0b2..bf5b8f82 100644 --- a/src/eva2/gui/EvAModuleButtonPanelMaker.java +++ b/src/eva2/gui/EvAModuleButtonPanelMaker.java @@ -10,242 +10,231 @@ package eva2.gui; * $Author: mkron $ */ import eva2.EvAInfo; +import eva2.server.modules.ModuleAdapter; +import eva2.server.stat.EvAJob; +import eva2.tools.ToolBoxGui; +import eva2.tools.jproxy.RMIProxyLocal; +import eva2.tools.jproxy.RemoteStateListener; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.Serializable; import java.net.InetAddress; - -import javax.swing.JButton; -import javax.swing.JComponent; -import javax.swing.JOptionPane; -import javax.swing.JPanel; - -import eva2.server.modules.ModuleAdapter; -import eva2.server.stat.EvAJob; -import eva2.tools.BasicResourceLoader; -import eva2.tools.jproxy.RMIProxyLocal; -import eva2.tools.jproxy.RemoteStateListener; -import java.awt.Toolkit; import java.util.logging.Level; import java.util.logging.Logger; -import javax.swing.*; +import javax.swing.JButton; +import javax.swing.JOptionPane; +import javax.swing.JToolBar; /** - * Contains the GUI elements of start and stop buttons and optionally a help button. + * Contains the GUI elements of start and stop buttons and optionally a help + * button. */ -public class EvAModuleButtonPanelMaker implements RemoteStateListener, Serializable, PanelMaker { - private static final Logger logger = Logger.getLogger(EvAInfo.defaultLogger); - private String m_Name = "undefined"; - private ModuleAdapter moduleAdapter; - private boolean runningState; - private JButton runButton; - private JButton postProcessButton; - private JButton stopButton; - private JButton scheduleButton; -// private JButton m_actExitMod; - private JButton helpButton; -// private JButton m_ShowSolButton; - private JToolBar toolBar; - private String helpFileName; +public class EvAModuleButtonPanelMaker implements RemoteStateListener, Serializable, PanelMaker { - /** - * - */ - public EvAModuleButtonPanelMaker(ModuleAdapter adapter, boolean state) { - m_Name = "GENERAL"; - runningState = state; - moduleAdapter = adapter; - } + private static final Logger LOGGER = Logger.getLogger(EvAInfo.defaultLogger); + private String m_Name = "undefined"; + private ModuleAdapter moduleAdapter; + private boolean runningState; + private JButton runButton; + private JButton postProcessButton; + private JButton stopButton; + private JButton scheduleButton; + private JButton helpButton; + private JToolBar toolBar; + private String helpFileName; - public JToolBar makePanel() { - String myhostname = null; + /** + * + */ + public EvAModuleButtonPanelMaker(ModuleAdapter adapter, boolean state) { + m_Name = "GENERAL"; + runningState = state; + moduleAdapter = adapter; + } - toolBar = new JToolBar(); - toolBar.setFloatable(false); - - if (moduleAdapter.hasConnection()) { // we might be in rmi mode - try { - myhostname = InetAddress.getLocalHost().getHostName(); - } catch (Exception e) { - logger.log(Level.WARNING, "Could not get hostname", e); - } - } - if (!moduleAdapter.hasConnection()) { - moduleAdapter.addRemoteStateListener((RemoteStateListener)(this)); - } else {// there is a network RMI connection - moduleAdapter.addRemoteStateListener((RemoteStateListener)RMIProxyLocal.newInstance(this)); - } + public JToolBar makePanel() { + toolBar = new JToolBar(); + toolBar.setFloatable(false); - ////////////////////////////////////////////////////////////// - runButton = makeIconButton("resources/images/Play24.gif", "Start"); - runButton.setToolTipText("Start the current optimization run."); - runButton.addActionListener(new ActionListener() { + /* ToDo: This is useless? */ + if (moduleAdapter.hasConnection()) { // we might be in rmi mode + try { + String myhostname = InetAddress.getLocalHost().getHostName(); + } catch (Exception e) { + LOGGER.log(Level.WARNING, "Could not get hostname", e); + } + } + if (!moduleAdapter.hasConnection()) { + moduleAdapter.addRemoteStateListener((RemoteStateListener) (this)); + } else {// there is a network RMI connection + moduleAdapter.addRemoteStateListener((RemoteStateListener) RMIProxyLocal.newInstance(this)); + } - public void actionPerformed(ActionEvent event) { - //Run Opt pressed ! - onUserStart(); - } - }); + ////////////////////////////////////////////////////////////// + runButton = ToolBoxGui.createIconifiedButton("resources/images/Play24.gif", "Start", true); + runButton.setToolTipText("Start the current optimization run."); - runButton.setEnabled(!runningState); // enabled if not running + runButton.addActionListener(new ActionListener() { - toolBar.add(runButton); + @Override + public void actionPerformed(ActionEvent event) { + //Run Opt pressed ! + onUserStart(); + } + }); - stopButton = makeIconButton("resources/images/Stop24.gif", "Stop"); - stopButton.setToolTipText("Stop the current optimization run."); - stopButton.addActionListener(new ActionListener() { + runButton.setEnabled(!runningState); // enabled if not running - public void actionPerformed(ActionEvent event) { - try { - // this means user break - moduleAdapter.stopOpt(); - } catch (Exception ee) { - logger.log(Level.WARNING, "Error while stopping job.", ee); - } - } - }); + toolBar.add(runButton); - stopButton.setEnabled(runningState); - toolBar.add(stopButton); + stopButton = ToolBoxGui.createIconifiedButton("resources/images/Stop24.gif", "Stop", true); + stopButton.setToolTipText("Stop the current optimization run."); + //stopButton.setBorderPainted(false); + stopButton.addActionListener(new ActionListener() { - postProcessButton = makeIconButton("resources/images/History24.gif", "Post Process"); - postProcessButton.setToolTipText("Start post processing according to available parameters."); - postProcessButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent event) { + try { + // this means user break + moduleAdapter.stopOpt(); + } catch (Exception ee) { + LOGGER.log(Level.WARNING, "Error while stopping job.", ee); + } + } + }); - public void actionPerformed(ActionEvent e) { - try { - if (!moduleAdapter.startPostProcessing()) { - JOptionPane.showMessageDialog(null, "Post processing seems deactivated! Check the settings.", "Warning", JOptionPane.WARNING_MESSAGE); - } - } catch (Exception ee) { - logger.log(Level.WARNING, "Error in run", ee); - } - } - }); - postProcessButton.setEnabled(runningState && moduleAdapter.hasPostProcessing()); - toolBar.add(postProcessButton); -// ////////////////////////////////////////////////////////////// - scheduleButton= makeIconButton("resources/images/Server24.gif", "Schedule"); - scheduleButton.setToolTipText("Schedule the currently configured optimization as a job."); - scheduleButton.addActionListener(new ActionListener() { + stopButton.setEnabled(runningState); + toolBar.add(stopButton); - public void actionPerformed(ActionEvent e) { - EvAJob job = moduleAdapter.scheduleJob(); - if (job == null) { - logger.log(Level.WARNING, "There was an error on scheduling your job"); - } - } - }); - scheduleButton.setEnabled(true); - toolBar.add(scheduleButton); + postProcessButton = ToolBoxGui.createIconifiedButton("resources/images/History24.gif", "Post Process", true); + postProcessButton.setToolTipText("Start post processing according to available parameters."); + //postProcessButton.setBorderPainted(false); + postProcessButton.addActionListener(new ActionListener() { - makeHelpButton(); + @Override + public void actionPerformed(ActionEvent event) { + try { + if (!moduleAdapter.startPostProcessing()) { + JOptionPane.showMessageDialog(null, "Post processing seems deactivated! Check the settings.", "Warning", JOptionPane.WARNING_MESSAGE); + } + } catch (Exception ee) { + LOGGER.log(Level.WARNING, "Error in run", ee); + } + } + }); + postProcessButton.setEnabled(runningState && moduleAdapter.hasPostProcessing()); + toolBar.add(postProcessButton); + + scheduleButton = ToolBoxGui.createIconifiedButton("resources/images/Server24.gif", "Schedule", true); + scheduleButton.setToolTipText("Schedule the currently configured optimization as a job."); + //scheduleButton.setBorderPainted(false); + scheduleButton.addActionListener(new ActionListener() { - return toolBar; - } - - private JButton makeIconButton(final String iconSrc, final String title) { - JButton newButton; - byte[] bytes; - bytes = BasicResourceLoader.instance().getBytesFromResourceLocation(iconSrc, false); - if (bytes == null) { - newButton = new JButton(title); - } else { - newButton = new JButton(title, new ImageIcon(Toolkit.getDefaultToolkit().createImage(bytes))); - } - return newButton; - } - - public void onUserStart() { - try { - moduleAdapter.startOpt(); - stopButton.setEnabled(true); - runButton.setEnabled(false); - postProcessButton.setEnabled(false); -// m_RestartButton.setEnabled(false); -// m_JHelpButton.setEnabled(true); - } catch (Exception ee) { - ee.printStackTrace(); - System.err.print ("Error in run: " +ee +" : " + ee.getMessage() ); - } - } - - private void makeHelpButton() { - /////////////////////////////////////////////////////////////// - if (helpFileName != null && (!helpFileName.equals(""))) { - helpButton = new JButton("Description"); - helpButton.setToolTipText("Description of the current optimization algorithm."); - helpButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent event) { + EvAJob job = moduleAdapter.scheduleJob(); + if (job == null) { + LOGGER.log(Level.WARNING, "There was an error on scheduling your job"); + } + } + }); + scheduleButton.setEnabled(true); + toolBar.add(scheduleButton); - public void actionPerformed(ActionEvent e) { - //System.out.println("Run Opt pressed !!!!!!!!!!!!!!!!======================!!"); - try { - if (helpFileName != null) { - HtmlDemo temp = new HtmlDemo(helpFileName); - temp.show(); - } - helpButton.setEnabled(true); - } catch (Exception ee) { - ee.printStackTrace(); - System.out.print("Error in run: " + ee + " : " + ee.getMessage()); - } - } - }); - toolBar.add(helpButton); - } - } - - /** - * - */ - public void performedStop() { - runButton.setEnabled(true); - postProcessButton.setEnabled(true); - runButton.repaint(); - stopButton.setEnabled(false); - toolBar.repaint(); - } + makeHelpButton(); - public void performedStart(String infoString) { -// m_ShowSolButton.setEnabled(true); - } + return toolBar; + } + public void onUserStart() { + try { + moduleAdapter.startOpt(); + stopButton.setEnabled(true); + runButton.setEnabled(false); + postProcessButton.setEnabled(false); + } catch (Exception ex) { + ex.printStackTrace(); + System.err.print("Error in run: " + ex + " : " + ex.getMessage()); + } + } - public void performedRestart(String infoString) { - } - - public void updateProgress(final int percent, String msg) { - } - - /** - * - */ - public String getName() { - return m_Name; - } - /** - * - */ - public void setHelperFilename(String fileName) { - if ((fileName == null) && (fileName == helpFileName)) { - return; // both are null, do nothing - } - if (fileName != null) { - if (helpFileName == null) { - // only old is null, nothing to be removed - helpFileName = fileName; - makeHelpButton(); - } else { - if (!helpFileName.equals(fileName)) { - toolBar.remove(helpButton); - helpFileName = fileName; - makeHelpButton(); - } //else // both are equal, do nothing - } - } else { // s is null, so just remove - toolBar.remove(helpButton); - helpFileName = fileName; - } - } + private void makeHelpButton() { + /////////////////////////////////////////////////////////////// + if (helpFileName != null && (!helpFileName.equals(""))) { + helpButton = new JButton("Description"); + helpButton.setToolTipText("Description of the current optimization algorithm."); + helpButton.addActionListener(new ActionListener() { + + public void actionPerformed(ActionEvent e) { + //System.out.println("Run Opt pressed !!!!!!!!!!!!!!!!======================!!"); + try { + if (helpFileName != null) { + HtmlDemo temp = new HtmlDemo(helpFileName); + temp.show(); + } + helpButton.setEnabled(true); + } catch (Exception ee) { + ee.printStackTrace(); + System.out.print("Error in run: " + ee + " : " + ee.getMessage()); + } + } + }); + toolBar.add(helpButton); + } + } + + /** + * + */ + public void performedStop() { + runButton.setEnabled(true); + postProcessButton.setEnabled(true); + runButton.repaint(); + stopButton.setEnabled(false); + toolBar.repaint(); + } + + @Override + public void performedStart(String infoString) { + } + + @Override + public void performedRestart(String infoString) { + } + + @Override + public void updateProgress(final int percent, String msg) { + } + + /** + * + */ + public String getName() { + return m_Name; + } + + /** + * + */ + public void setHelperFilename(String fileName) { + if ((fileName == null) && (fileName.equals(helpFileName))) { + return; // both are null, do nothing + } + if (fileName != null) { + if (helpFileName == null) { + // only old is null, nothing to be removed + helpFileName = fileName; + makeHelpButton(); + } else { + if (!helpFileName.equals(fileName)) { + toolBar.remove(helpButton); + helpFileName = fileName; + makeHelpButton(); + } //else // both are equal, do nothing + } + } else { // s is null, so just remove + toolBar.remove(helpButton); + helpFileName = fileName; + } + } } - diff --git a/src/eva2/gui/GOEPanel.java b/src/eva2/gui/GOEPanel.java index dbeafeb0..1d1ee5d5 100644 --- a/src/eva2/gui/GOEPanel.java +++ b/src/eva2/gui/GOEPanel.java @@ -326,7 +326,8 @@ public class GOEPanel extends JPanel implements ItemListener { for (String className : classesLongNames) { classNameMap.put(EVAHELP.cutClassName(className), className); } - objectChooser.setModel(new DefaultComboBoxModel(classNameMap.keySet().toArray())); + Vector classesList = new Vector(classesLongNames); + objectChooser.setModel(new DefaultComboBoxModel(classesList)); if (withComboBoxToolTips) { objectChooser.setRenderer(new ToolTipComboBoxRenderer(collectComboToolTips(instances, tipMaxLen))); } @@ -405,7 +406,7 @@ public class GOEPanel extends JPanel implements ItemListener { if ((e.getSource() == objectChooser) && (e.getStateChange() == ItemEvent.SELECTED)) { className = (String) objectChooser.getSelectedItem(); - className = classNameMap.get(className); + //className = classNameMap.get(className); try { Object n = (Object) Class.forName(className).newInstance(); genericObjectEditor.setValue(n); diff --git a/src/eva2/server/go/PopulationInterface.java b/src/eva2/server/go/PopulationInterface.java index 307a5606..32152428 100644 --- a/src/eva2/server/go/PopulationInterface.java +++ b/src/eva2/server/go/PopulationInterface.java @@ -1,5 +1,4 @@ package eva2.server.go; - /* * Title: EvA2 * Description: @@ -10,39 +9,73 @@ package eva2.server.go; * $Date: 2007-12-04 14:22:52 +0100 (Tue, 04 Dec 2007) $ * $Author: mkron $ */ -/*==========================================================================* - * IMPORTS - *==========================================================================*/ - -/*==========================================================================* - * INTERFACE DECLARATION - *==========================================================================*/ /** * */ public interface PopulationInterface { - public IndividualInterface getBestIndividual(); - public IndividualInterface getWorstIndividual(); - public double[] getBestFitness(); - public double[] getWorstFitness(); - public double[] getMeanFitness(); - public double[] getPopulationMeasures(); - public int getFunctionCalls(); - public int getGeneration(); - /** This method returns problem specific data - * @return double[] - */ - public double[] getSpecificData(); - /** This method returns identifiers for the - * specific data - * Note: "Pareto-Front" is reserved for mulit-crit. Problems - * string[1] gives the dimension of the fitness values - * @return String[] - */ - public String[] getSpecificDataNames(); - public Object get(int i); - public int size(); - public void clear(); + /** + * Returns the best individual of the population. + * + * @return The best individual + */ + IndividualInterface getBestIndividual(); + + /** + * Returns the worst individual of the population. + * + * @return The worst individual + */ + IndividualInterface getWorstIndividual(); + + double[] getBestFitness(); + + double[] getWorstFitness(); + + double[] getMeanFitness(); + + double[] getPopulationMeasures(); + + /** + * Returns the number of function calls. + * @return The number of function calls + */ + int getFunctionCalls(); + + /** + * The current generation count. + * @return int The current generation + */ + int getGeneration(); + + /** + * This method returns problem specific data + * + * @return double[] + */ + double[] getSpecificData(); + + /** + * This method returns identifiers for the specific data Note: + * "Pareto-Front" is reserved for multi-crit. Problems string[1] gives the + * dimension of the fitness values + * + * @return String[] + */ + String[] getSpecificDataNames(); + + + Object get(int i); + + /** + * Return the size of the population. + * @return int size of the population + */ + int size(); + + /** + * Clear the population. + */ + void clear(); } \ No newline at end of file diff --git a/src/eva2/server/go/individuals/AbstractEAIndividual.java b/src/eva2/server/go/individuals/AbstractEAIndividual.java index e2814101..32f2f856 100644 --- a/src/eva2/server/go/individuals/AbstractEAIndividual.java +++ b/src/eva2/server/go/individuals/AbstractEAIndividual.java @@ -1,12 +1,5 @@ package eva2.server.go.individuals; - -import java.util.ArrayList; -import java.util.BitSet; -import java.util.Formatter; -import java.util.HashMap; -import java.util.List; - import eva2.gui.BeanInspector; import eva2.server.go.IndividualInterface; import eva2.server.go.individuals.codings.gp.InterfaceProgram; @@ -21,6 +14,7 @@ import eva2.server.go.populations.Population; import eva2.server.go.problems.InterfaceOptimizationProblem; import eva2.tools.EVAERROR; import eva2.tools.math.RNG; +import java.util.*; /** This is the abstract EA individual implementing the most important methods giving * access to mutation and crossover rates and operators, fitness values and selection @@ -37,64 +31,62 @@ import eva2.tools.math.RNG; * To change this template use Options | File Templates. */ public abstract class AbstractEAIndividual implements IndividualInterface, java.io.Serializable { - public int m_FunctionCalls = 0; // TODO ist irgendwie eine Kruecke - protected int m_Age = 0; -// protected String m_Name = GONamingBox.getRandomName(); - - private long m_ID = 0; - private static long m_IDcounter = 0; -// private int logParentLen = 10; - private boolean logParents = false; - // heritage is to contain a list of all parents of the individual - private Long[] parentIDs = null; - transient private AbstractEAIndividual[] parentTree = null; - protected double[] m_Fitness = new double[1]; - private double m_ConstraintViolation = 0; - public boolean m_AreaConst4ParallelViolated = false; // no idea what felix used this for... - public boolean m_Marked = false; // is for GUI only! - public boolean m_isPenalized = false; // may be set true for penalty based constraints - - protected double[] m_SelectionProbability = new double[1];; - protected double m_CrossoverProbability = 1.0; - protected double m_MutationProbability = 0.2; - protected InterfaceMutation m_MutationOperator = new NoMutation(); - protected InterfaceCrossover m_CrossoverOperator = new NoCrossover(); - protected InterfaceInitialization m_InitOperator = new DefaultInitialization(); - - // protected String[] m_Identifiers = new String[m_ObjectIncrement]; + public int m_FunctionCalls = 0; // TODO ist irgendwie eine Kruecke + protected int m_Age = 0; + private long m_ID = 0; + private static long m_IDcounter = 0; + private boolean logParents = false; + // heritage is to contain a list of all parents of the individual + private Long[] parentIDs = null; + transient private AbstractEAIndividual[] parentTree = null; + protected double[] m_Fitness = new double[1]; + private double m_ConstraintViolation = 0; + public boolean m_AreaConst4ParallelViolated = false; // no idea what felix used this for... + public boolean m_Marked = false; // is for GUI only! + public boolean m_isPenalized = false; // may be set true for penalty based constraints + protected double[] m_SelectionProbability = new double[1]; + ; + protected double m_CrossoverProbability = 1.0; + protected double m_MutationProbability = 0.2; + protected InterfaceMutation m_MutationOperator = new NoMutation(); + protected InterfaceCrossover m_CrossoverOperator = new NoCrossover(); + protected InterfaceInitialization m_InitOperator = new DefaultInitialization(); + // protected String[] m_Identifiers = new String[m_ObjectIncrement]; // protected Object[] m_Objects = new Object[m_ObjectIncrement]; - protected HashMap m_dataHash = new HashMap(); - + protected HashMap m_dataHash = new HashMap(); // introduced for the nichingPSO/ANPSO (M.Aschoff) private int individualIndex = -1; - + public AbstractEAIndividual() { - m_IDcounter++; - m_ID = m_IDcounter; + m_IDcounter++; + m_ID = m_IDcounter; // System.out.println("my id is " + m_ID); } public long getIndyID() { - return m_ID; + return m_ID; } public int getIndividualIndex() { - return individualIndex; + return individualIndex; } public void SetIndividualIndex(int index) { - this.individualIndex = index; + this.individualIndex = index; } - - /** This method will enable you to clone a given individual + + /** + * This method will enable you to clone a given individual + * * @return The clone */ public abstract Object clone(); /** - * Set the init/mutation/crossover operator and probabilities to the given values. - * + * Set the init/mutation/crossover operator and probabilities to the given + * values. + * * @param initOp * @param mutOp * @param pMut @@ -102,46 +94,48 @@ public abstract class AbstractEAIndividual implements IndividualInterface, java. * @param pCross */ public void setOperators(InterfaceInitialization initOp, InterfaceMutation mutOp, double pMut, InterfaceCrossover coOp, double pCross) { - m_InitOperator = initOp; - m_MutationProbability = pMut; - m_MutationOperator = mutOp; - m_CrossoverProbability = pCross; - m_CrossoverOperator = coOp; + m_InitOperator = initOp; + m_MutationProbability = pMut; + m_MutationOperator = mutOp; + m_CrossoverProbability = pCross; + m_CrossoverOperator = coOp; } - + /** - * Set the mutation/crossover operator and probabilities to the given values. - * + * Set the mutation/crossover operator and probabilities to the given + * values. + * * @param mutOp * @param pMut * @param coOp * @param pCross */ public void setOperators(InterfaceMutation mutOp, double pMut, InterfaceCrossover coOp, double pCross) { - setOperators(new DefaultInitialization(), mutOp, pMut, coOp, pCross); + setOperators(new DefaultInitialization(), mutOp, pMut, coOp, pCross); } - + /** - * Clone and init the mutation/crossover operator for the individual - * and initialize the operators and probabilities to the given values. - * + * Clone and init the mutation/crossover operator for the individual and + * initialize the operators and probabilities to the given values. + * * @param mutOp * @param pMut * @param coOp * @param pCross */ public void initCloneOperators(InterfaceMutation mutOp, double pMut, InterfaceCrossover coOp, double pCross, InterfaceOptimizationProblem problem) { - m_MutationProbability = pMut; - m_MutationOperator = (InterfaceMutation)mutOp.clone(); - m_MutationOperator.init(this, problem); - m_CrossoverProbability = pCross; - m_CrossoverOperator = (InterfaceCrossover)coOp.clone(); - m_CrossoverOperator.init(this, problem); + m_MutationProbability = pMut; + m_MutationOperator = (InterfaceMutation) mutOp.clone(); + m_MutationOperator.init(this, problem); + m_CrossoverProbability = pCross; + m_CrossoverOperator = (InterfaceCrossover) coOp.clone(); + m_CrossoverOperator.init(this, problem); } - + /** - * Set the mutation/crossover operator and probabilities of the given individual to the given values. - * + * Set the mutation/crossover operator and probabilities of the given + * individual to the given values. + * * @param indy * @param mutOp * @param pMut @@ -150,57 +144,76 @@ public abstract class AbstractEAIndividual implements IndividualInterface, java. * @return the modified AbstractEAIndividual */ public static AbstractEAIndividual setOperators(AbstractEAIndividual indy, InterfaceMutation mutOp, double pMut, InterfaceCrossover coOp, double pCross) { - indy.setOperators(mutOp, pMut, coOp, pCross); - return indy; + indy.setOperators(mutOp, pMut, coOp, pCross); + return indy; } - - /** This methods allows you to clone the user data - * Objects - * @param individual The individual to clone. + + /** + * This methods allows you to clone the user data Objects + * + * @param individual The individual to clone. */ public void cloneAEAObjects(AbstractEAIndividual individual) { // m_Name = new String(individual.m_Name); - m_dataHash = (HashMap)(individual.m_dataHash.clone()); + m_dataHash = (HashMap) (individual.m_dataHash.clone()); m_ConstraintViolation = individual.m_ConstraintViolation; // m_AreaConst4ParallelViolated = individual.m_AreaConst4ParallelViolated; - m_Marked = individual.m_Marked; - m_isPenalized = individual.m_isPenalized; + m_Marked = individual.m_Marked; + m_isPenalized = individual.m_isPenalized; individualIndex = individual.individualIndex; m_InitOperator = individual.m_InitOperator.clone(); if (individual.parentIDs != null) { - parentIDs = new Long[individual.parentIDs.length]; - System.arraycopy(individual.parentIDs, 0, parentIDs, 0, parentIDs.length); - parentTree = new AbstractEAIndividual[individual.parentTree.length]; - for (int i=0; i 0)) { - for (int i=0; i 0)) { + for (int i = 0; i < parents.size(); i++) { + parentIDs[i + 1] = parents.getEAIndividual(i).getIndyID(); + parentTree[i + 1] = (AbstractEAIndividual) parents.getEAIndividual(i).clone(); + } + } + // addHeritage(parentIDs); - } - - /** - * Add an ancestor list with multiple parents. - * - * @param parents - */ - public void setParents(List parents) { - if ((parents == null) || (parents.size() == 0)) { - parentIDs = null; - parentTree = null; - } else { - int parentCnt = parents.size(); - parentIDs = new Long[parentCnt]; - parentTree = new AbstractEAIndividual[parentCnt]; - - for (int i=0; i 0) && (parentTree != null)) { - sb.append("[ "); - for (int i=0; i parents) { + if ((parents == null) || (parents.size() == 0)) { + parentIDs = null; + parentTree = null; + } else { + int parentCnt = parents.size(); + parentIDs = new Long[parentCnt]; + parentTree = new AbstractEAIndividual[parentCnt]; + + for (int i = 0; i < parentCnt; i++) { + parentIDs[i] = parents.get(i).getIndyID(); + parentTree[i] = (AbstractEAIndividual) parents.get(i).clone(); + } + } + } + + public String getHeritageTree(int depth) { + StringBuffer sb = new StringBuffer(); + sb.append(getIndyID()); + sb.append(" "); + if ((depth > 0) && (parentTree != null)) { + sb.append("[ "); + for (int i = 0; i < parentTree.length; i++) { + sb.append(parentTree[i].getHeritageTree(depth - 1)); // if ((i+1) < parentTree.length) sb.append(", "); - } - sb.append("] "); - } - return sb.toString(); - } - + } + sb.append("] "); + } + return sb.toString(); + } + // private void addHeritage(Long[] parentIDs) { // heritage.add(parentIDs); //// if (heritage.size() > logParentLen) heritage.remove(0); // } - - /** - * Add an ancestor generation with only one parent. - * - * @param parent - */ - protected void setParent(AbstractEAIndividual parent) { - setParents(parent, null); - } - - public Long[] getParentIDs() { - return parentIDs; - } - + /** + * Add an ancestor generation with only one parent. + * + * @param parent + */ + protected void setParent(AbstractEAIndividual parent) { + setParents(parent, null); + } + + public Long[] getParentIDs() { + return parentIDs; + } + // /** // * Returns the last set of parental IDs or null if none are available. // * @@ -442,136 +467,172 @@ public abstract class AbstractEAIndividual implements IndividualInterface, java. // if (heritage != null) return heritage.getLast(); // else return null; // } - - /** This method will allow you to get the current age of an individual - * Zero means it has not even been evaluated. + /** + * This method will allow you to get the current age of an individual Zero + * means it has not even been evaluated. + * * @return The current age. */ public int getAge() { return this.m_Age; } - /** This method allows you to set the age of an individual. The only - * class allowed to set the age on an individual is the problem. - * @param age The new age. + /** + * This method allows you to set the age of an individual. The only class + * allowed to set the age on an individual is the problem. + * + * @param age The new age. */ public void SetAge(int age) { this.m_Age = age; } - /** This method will incr the current age by one. + /** + * This method will incr the current age by one. */ public void incrAge() { this.m_Age++; } - /** This method allows you to reset the user data + /** + * This method allows you to reset the user data */ public void resetUserData() { - m_dataHash.clear(); + m_dataHash.clear(); } - /** This method allows you to reset the level of constraint violation for an + /** + * This method allows you to reset the level of constraint violation for an * individual */ public void resetConstraintViolation() { - m_isPenalized=false; + m_isPenalized = false; this.m_ConstraintViolation = 0; } - /** This method allows you to add a new constraint violation to - * the current level of constraint violation - * @param c The constraint violation. + /** + * This method allows you to add a new constraint violation to the current + * level of constraint violation + * + * @param c The constraint violation. */ public void addConstraintViolation(double c) { this.m_ConstraintViolation += Math.abs(c); } - /** This method allows you to read the current level of constraint violation + /** + * This method allows you to read the current level of constraint violation + * * @return The current level of constraint violation */ public double getConstraintViolation() { return this.m_ConstraintViolation; } - /** This method checks whether or not a constraint is violated + /** + * This method checks whether or not a constraint is violated + * * @return True if constraints are violated */ public boolean violatesConstraint() { - if (this.m_ConstraintViolation > 0) return true; - else return false; + if (this.m_ConstraintViolation > 0) { + return true; + } else { + return false; + } } - /** This method returns whether or not the individual is marked. This - * feature is for GUI only and has been especially introduced for the - * MOCCO GUI. + /** + * This method returns whether or not the individual is marked. This feature + * is for GUI only and has been especially introduced for the MOCCO GUI. + * * @return true if marked false if not */ public boolean getMarked() { return this.m_Marked; } + public void SetMarked(boolean t) { this.m_Marked = t; } + public boolean isMarked() { return this.m_Marked; } + public void unmark() { this.m_Marked = false; } + public void mark() { this.m_Marked = true; } /** * Allows marking an individual as infeasible if fitness penalty is used. + * * @return */ public boolean isMarkedPenalized() { - return m_isPenalized; - } + return m_isPenalized; + } + /** * Allows marking an individual as infeasible if fitness penalty is used. + * * @return */ public void SetMarkPenalized(boolean p) { - m_isPenalized=p; + m_isPenalized = p; } - - /** This method can be used to read the current fitness of the individual. + + /** + * This method can be used to read the current fitness of the individual. * Please note that the fitness can be based on multiple criteria therefore * double[] is used instead of a single double. + * * @return The complete fitness array */ public double[] getFitness() { return this.m_Fitness; } - /** This method returns the i-th fitness value if existent. If the i-th fitness - * value does not exist zero is returned as default. - * @param index The index of the requested fitness value. + /** + * This method returns the i-th fitness value if existent. If the i-th + * fitness value does not exist zero is returned as default. + * + * @param index The index of the requested fitness value. * @return The fitness value at index */ public double getFitness(int index) { - if (this.m_Fitness.length > index) return this.m_Fitness[index]; - else return 0; + if (this.m_Fitness.length > index) { + return this.m_Fitness[index]; + } else { + return 0; + } } - /** This method will set the complete Fitness of the individual - * @param fitness The new fitness array + /** + * This method will set the complete Fitness of the individual + * + * @param fitness The new fitness array + * @deprecated */ public void SetFitness(double[] fitness) { this.m_Fitness = fitness; } - /** This method allows you to set the i-th fitness value - * @param index The index of the fitness value to set. + /** + * This method allows you to set the i-th fitness value + * + * @param index The index of the fitness value to set. * @param fitness The new fitness value. */ public void SetFitness(int index, double fitness) { - if (this.m_Fitness.length > index) this.m_Fitness[index] = fitness; - else { - double[] tmpD = new double[index+1]; + if (this.m_Fitness.length > index) { + this.m_Fitness[index] = fitness; + } else { + double[] tmpD = new double[index + 1]; for (int i = 0; i < this.m_Fitness.length; i++) { tmpD[i] = this.m_Fitness[i]; } @@ -579,40 +640,51 @@ public abstract class AbstractEAIndividual implements IndividualInterface, java. this.m_Fitness[index] = fitness; } } - - /** - * This method will set the fitness of the individual to the given value in every component. - * If the fitness was null, nothing will be done. - * - * @param resetVal The new fitness array + + /** + * This method will set the fitness of the individual to the given value in + * every component. If the fitness was null, nothing will be done. + * + * @param resetVal The new fitness array */ public void resetFitness(double resetVal) { - if (m_Fitness!=null) { - for (int i=0; i= b); - } + if (Double.isNaN(a) || Double.isInfinite(a)) { + return false; + } else { + return (a >= b); + } + } private static boolean firstIsFiniteAndLargerNonEqual(double a, double b) { - if (Double.isNaN(a) || Double.isInfinite(a)) return false; - else return (a > b); - } - - /** - * Returns true if the first fitness vector truly dominates the second one in every component. - * + if (Double.isNaN(a) || Double.isInfinite(a)) { + return false; + } else { + return (a > b); + } + } + + /** + * Returns true if the first fitness vector truly dominates the second one + * in every component. + * * @param fit1 first fitness vector to look at * @param fit2 second fitness vector to look at * @return true, if the first fitness vector truly dominates the second one */ public static boolean isDominatingFitnessNotEqual(double[] fit1, double fit2[]) { - boolean result = true; - int i=0; - while (result && (i < fit1.length) && (i < fit2.length)) { - if (fit1[i] >= fit2[i]) result = false; - i++; - } - return result; + boolean result = true; + int i = 0; + while (result && (i < fit1.length) && (i < fit2.length)) { + if (fit1[i] >= fit2[i]) { + result = false; + } + i++; + } + return result; } - - /** - * This method will allow you to compare two individuals regarding the constraint violation only, - * and only if the specific tag has been set. (For, e.g., additive penalty there is no way of discriminating - * fitness and penalty after assigning). - * The one with lesser violation is regarded better. If the instance is better than the given - * indy, 1 is returned. If it is worse than the given indy, -1 is returned. - * If they both violate them equally, 0 is returned. - * This means that if both do not violate the constraints, 0 is returned. - * - * @param indy The individual to compare to. - * @return 1 if the instance is better (regarding constraints only), -1 if is worse, 0 if they are equal in that respect. + + /** + * This method will allow you to compare two individuals regarding the + * constraint violation only, and only if the specific tag has been set. + * (For, e.g., additive penalty there is no way of discriminating fitness + * and penalty after assigning). The one with lesser violation is regarded + * better. If the instance is better than the given indy, 1 is returned. If + * it is worse than the given indy, -1 is returned. If they both violate + * them equally, 0 is returned. This means that if both do not violate the + * constraints, 0 is returned. + * + * @param indy The individual to compare to. + * @return 1 if the instance is better (regarding constraints only), -1 if + * is worse, 0 if they are equal in that respect. */ public int compareConstraintViolation(AbstractEAIndividual indy) { - if ((this.m_ConstraintViolation > 0) && (indy.m_ConstraintViolation <= 0)) return -1; - if ((this.m_ConstraintViolation <= 0) && (indy.m_ConstraintViolation > 0)) return 1; - else { // both violate: ((this.m_ConstraintViolation > 0) && (indy.m_ConstraintViolation > 0)) { - if (this.m_ConstraintViolation < indy.m_ConstraintViolation) return 1 ; - else if (this.m_ConstraintViolation > indy.m_ConstraintViolation) return -1; - else return 0; + if ((this.m_ConstraintViolation > 0) && (indy.m_ConstraintViolation <= 0)) { + return -1; + } + if ((this.m_ConstraintViolation <= 0) && (indy.m_ConstraintViolation > 0)) { + return 1; + } else { // both violate: ((this.m_ConstraintViolation > 0) && (indy.m_ConstraintViolation > 0)) { + if (this.m_ConstraintViolation < indy.m_ConstraintViolation) { + return 1; + } else if (this.m_ConstraintViolation > indy.m_ConstraintViolation) { + return -1; + } else { + return 0; + } } } - - /** This method will allow you to compare two individuals regarding the dominance. - * Note this is dominance! If the individuals are not comparable this method will - * return false! - * @param indy The individual to compare to. + + /** + * This method will allow you to compare two individuals regarding the + * dominance. Note this is dominance! If the individuals are not comparable + * this method will return false! + * + * @param indy The individual to compare to. * @return True if the own fitness dominates the other indy's */ public boolean isDominatingDebConstraints(AbstractEAIndividual indy) { int constrViolComp = compareConstraintViolation(indy); - if (constrViolComp==0) return isDominatingFitness(getFitness(), indy.getFitness()); - else return (constrViolComp > 0); + if (constrViolComp == 0) { + return isDominatingFitness(getFitness(), indy.getFitness()); + } else { + return (constrViolComp > 0); + } // for (int i = 0; (i < this.m_Fitness.length) && (i < tmpFitness.length); i++) { // if (this.m_Fitness[i] <= tmpFitness[i]) result &= true; // else result &= false; @@ -705,69 +803,91 @@ public abstract class AbstractEAIndividual implements IndividualInterface, java. // return result; } - /** This method will allow you to compare two individuals regarding the dominance. - * Note this is dominance! If the individuals are not comparable this method will - * return false! - * @param indy The individual to compare to. + /** + * This method will allow you to compare two individuals regarding the + * dominance. Note this is dominance! If the individuals are not comparable + * this method will return false! + * + * @param indy The individual to compare to. * @return True if better false else */ public boolean isDominatingEqual(AbstractEAIndividual indy) { - // TODO: should this method really be called "..Equal"? - if (this.m_AreaConst4ParallelViolated) return false; - if (indy.m_AreaConst4ParallelViolated) return true; + // TODO: should this method really be called "..Equal"? + if (this.m_AreaConst4ParallelViolated) { + return false; + } + if (indy.m_AreaConst4ParallelViolated) { + return true; + } return isDominatingFitnessNotEqual(getFitness(), indy.getFitness()); } - /** - * This method will allow you to compare two individuals regarding the dominance. - * Note this is dominance! If the individuals are not comparable this method will - * return false! + /** + * This method will allow you to compare two individuals regarding the + * dominance. Note this is dominance! If the individuals are not comparable + * this method will return false! * - * @param indy The individual to compare to. + * @param indy The individual to compare to. * @return True if better false else */ public boolean isDominatingDebConstraintsEqual(AbstractEAIndividual indy) { - // TODO: should this method really be called "..Equal"? + // TODO: should this method really be called "..Equal"? int constrViolComp = compareConstraintViolation(indy); - if (constrViolComp==0) return isDominatingFitnessNotEqual(getFitness(), indy.getFitness()); - else return (constrViolComp > 0); + if (constrViolComp == 0) { + return isDominatingFitnessNotEqual(getFitness(), indy.getFitness()); + } else { + return (constrViolComp > 0); + } // return isDominatingFitnessNotEqual(getFitness(), indy.getFitness()); } - /** This method can be used to read the current selection probability of the individual. - * Please note that the selection probability can be based on multiple criteria therefore - * double[] is used instead of a single double. + /** + * This method can be used to read the current selection probability of the + * individual. Please note that the selection probability can be based on + * multiple criteria therefore double[] is used instead of a single double. + * * @return The complete selection probability array */ public double[] getSelectionProbability() { return this.m_SelectionProbability; } - /** This method returns the i-th selection probability value if existent. If the i-th selection probability - * value does not exist zero is returned as default. - * @param index The index of the requested fitness value. + /** + * This method returns the i-th selection probability value if existent. If + * the i-th selection probability value does not exist zero is returned as + * default. + * + * @param index The index of the requested fitness value. * @return The selection probability value at index */ public double getSelectionProbability(int index) { - if (this.m_SelectionProbability.length > index) return this.m_SelectionProbability[index]; - else return 0; + if (this.m_SelectionProbability.length > index) { + return this.m_SelectionProbability[index]; + } else { + return 0; + } } - /** This method will set the complete selection probability of the individual - * @param sel The new selection probability array + /** + * This method will set the complete selection probability of the individual + * + * @param sel The new selection probability array */ public void SetSelectionProbability(double[] sel) { this.m_SelectionProbability = sel; } - /** This method allows you to set the i-th selection probability value - * @param index The index of the selection probability value to set. - * @param sel The new selection probability value. + /** + * This method allows you to set the i-th selection probability value + * + * @param index The index of the selection probability value to set. + * @param sel The new selection probability value. */ public void SetSelectionProbability(int index, double sel) { - if (this.m_SelectionProbability.length > index) this.m_SelectionProbability[index] = sel; - else { - double[] tmpD = new double[index+1]; + if (this.m_SelectionProbability.length > index) { + this.m_SelectionProbability[index] = sel; + } else { + double[] tmpD = new double[index + 1]; for (int i = 0; i < this.m_SelectionProbability.length; i++) { tmpD[i] = this.m_SelectionProbability[i]; } @@ -776,90 +896,118 @@ public abstract class AbstractEAIndividual implements IndividualInterface, java. } } - /** This method allows you to choose from multiple mutation operators. - * Note: If the operator doeesn't suite the data nothing will happen. - * @param mutator The mutation operator. + /** + * This method allows you to choose from multiple mutation operators. Note: + * If the operator doeesn't suite the data nothing will happen. + * + * @param mutator The mutation operator. */ public void setMutationOperator(InterfaceMutation mutator) { this.m_MutationOperator = mutator; } + public InterfaceMutation getMutationOperator() { return this.m_MutationOperator; } + public String mutationOperatorTipText() { return "Choose the mutation operator to use."; } - /** This method allows you to set the mutation probability, e.g. the chance that - * mutation occurs at all. - * @param mutprob The mutation probability. + /** + * This method allows you to set the mutation probability, e.g. the chance + * that mutation occurs at all. + * + * @param mutprob The mutation probability. */ public void setMutationProbability(double mutprob) { - if (mutprob < 0) mutprob = 0; - if (mutprob > 1) mutprob = 1; + if (mutprob < 0) { + mutprob = 0; + } + if (mutprob > 1) { + mutprob = 1; + } m_MutationProbability = mutprob; } + public double getMutationProbability() { return m_MutationProbability; } + public String mutationProbabilityTipText() { return "The chance that mutation occurs."; } - /** This method allows you to choose from multiple crossover operators. - * Note: If the operator doeesn't suite the data nothing will happen. - * @param crossover The crossover operator. + /** + * This method allows you to choose from multiple crossover operators. Note: + * If the operator doeesn't suite the data nothing will happen. + * + * @param crossover The crossover operator. */ public void setCrossoverOperator(InterfaceCrossover crossover) { this.m_CrossoverOperator = crossover; } + public InterfaceCrossover getCrossoverOperator() { return this.m_CrossoverOperator; } + public String crossoverOperatorTipText() { return "Choose the crossover operator to use."; } - /** This method allows to set the crossover probability + /** + * This method allows to set the crossover probability + * * @param prob */ public void setCrossoverProbability(double prob) { this.m_CrossoverProbability = prob; - if (this.m_CrossoverProbability > 1) this.m_CrossoverProbability = 1; - if (this.m_CrossoverProbability < 0) this.m_CrossoverProbability = 0; + if (this.m_CrossoverProbability > 1) { + this.m_CrossoverProbability = 1; + } + if (this.m_CrossoverProbability < 0) { + this.m_CrossoverProbability = 0; + } } + public double getCrossoverProbability() { return this.m_CrossoverProbability; } + public String crossoverProbabilityTipText() { return "The chance that crossover occurs."; } public InterfaceInitialization getInitOperator() { - return m_InitOperator; - } - public void setInitOperator(InterfaceInitialization mInitOperator) { - m_InitOperator = mInitOperator; - } - public String initOperatorTipText() { - return "An initialization method for the individual"; - } - - /** This method allows you to store an arbitrary value under an arbitrary - * name. - * @param name The identifying name. - * @param obj The object that is to be stored. - */ - public void putData(String name, Object obj) { - m_dataHash.put(name, obj); + return m_InitOperator; } - /** - * This method will return a stored object associated with a key String. - * The String "Fitness" is always a valid key connected to the - * individual fitness array. - * - * @param name The name of the requested Object + public void setInitOperator(InterfaceInitialization mInitOperator) { + m_InitOperator = mInitOperator; + } + + public String initOperatorTipText() { + return "An initialization method for the individual"; + } + + /** + * This method allows you to store an arbitrary value under an arbitrary + * name. + * + * @param name The identifying name. + * @param obj The object that is to be stored. + */ + public void putData(String name, Object obj) { + m_dataHash.put(name, obj); + } + + /** + * This method will return a stored object associated with a key String. The + * String "Fitness" is always a valid key connected to the individual + * fitness array. + * + * @param name The name of the requested Object * @return Object The associated object or null if none is found */ public Object getData(String name) { @@ -867,268 +1015,296 @@ public abstract class AbstractEAIndividual implements IndividualInterface, java. // if (name.equalsIgnoreCase("SelectionProbabilityArray")) return this.getSelectionProbability(); // if (name.equalsIgnoreCase("Fitness")) return this.getFitness(); // if (name.equalsIgnoreCase("FitnessArray")) return this.getFitness(); - Object data = m_dataHash.get(name); - if (data==null) { // Fitness is actually in use... so lets have a minor special treatment + Object data = m_dataHash.get(name); + if (data == null) { // Fitness is actually in use... so lets have a minor special treatment // try { - if (name.compareToIgnoreCase("Fitness")==0) data = getFitness(); - else { - EVAERROR.errorMsgOnce("Warning: data key " + name + " unknown (pot. multiple errors)!"); + if (name.compareToIgnoreCase("Fitness") == 0) { + data = getFitness(); + } else { + EVAERROR.errorMsgOnce("Warning: data key " + name + " unknown (pot. multiple errors)!"); // throw new RuntimeException(name + ": unknown key!"); - } + } // } catch(Exception e) { // e.printStackTrace(System.err); // } - } + } return data; } - - /** - * Check whether the individual has an object in store which is associated with - * the given key String. The String "Fitness" is always a valid key connected to the - * individual fitness array. - * - * @param key The name of the requested Object. + + /** + * Check whether the individual has an object in store which is associated + * with the given key String. The String "Fitness" is always a valid key + * connected to the individual fitness array. + * + * @param key The name of the requested Object. * @return true if data is associated with the key, else false */ public boolean hasData(String key) { - if (m_dataHash.get(key)==null) { - return (key.compareToIgnoreCase("Fitness")==0); - } else return true; + if (m_dataHash.get(key) == null) { + return (key.compareToIgnoreCase("Fitness") == 0); + } else { + return true; + } } - /** This method will return a string description of the Individal - * noteably the Genotype. + /** + * This method will return a string description of the Individal noteably + * the Genotype. + * * @return A descriptive string */ public abstract String getStringRepresentation(); - - /** - * This method creates a default String representation for an AbstractEAIndividual - * with genotype and fitness representation. - * - * @param individual The individual that is to be shown. + + /** + * This method creates a default String representation for an + * AbstractEAIndividual with genotype and fitness representation. + * + * @param individual The individual that is to be shown. * @return The description. */ public static String getDefaultStringRepresentation(AbstractEAIndividual individual) { - // Note that changing this method might change the hashcode of an individual - // which might interfere with some functionality. - StringBuffer sb = new StringBuffer("Fit.:\t"); + // Note that changing this method might change the hashcode of an individual + // which might interfere with some functionality. + StringBuilder sb = new StringBuilder("Fit.:\t"); sb.append(BeanInspector.toString(individual.getFitness())); - if (individual.isMarkedPenalized() || individual.violatesConstraint()) - sb.append(", X"); + if (individual.isMarkedPenalized() || individual.violatesConstraint()) { + sb.append(", X"); + } sb.append(", ID: "); sb.append(individual.getIndyID()); sb.append(",\t"); sb.append(getDefaultDataString(individual)); - if (individual.getParentIDs()!=null) { - sb.append(", parents: "); + if (individual.getParentIDs() != null) { + sb.append(", parents: "); sb.append(BeanInspector.toString(individual.getParentIDs())); } return sb.toString(); } - + /** - * This method creates a default String representation for a number Individual interfaces - * containing the genotype. - * + * This method creates a default String representation for a number + * Individual interfaces containing the genotype. + * * @param individual * @return */ public static String getDefaultDataString(IndividualInterface individual) { - // Note that changing this method might change the hashcode of an individual - // which might interfere with some functionality. - return getDefaultDataString(individual, ","); + // Note that changing this method might change the hashcode of an individual + // which might interfere with some functionality. + return getDefaultDataString(individual, ","); } - + /** - * This method returns the default data object of an individual containing the - * individuals solution representation. - * + * This method returns the default data object of an individual containing + * the individuals solution representation. + * * @param individual * @return */ public static Object getDefaultDataObject(IndividualInterface individual) { if (individual instanceof InterfaceDataTypeBinary) { - return ((InterfaceDataTypeBinary)individual).getBinaryData().clone(); + return ((InterfaceDataTypeBinary) individual).getBinaryData().clone(); } else if (individual instanceof InterfaceDataTypeInteger) { - return ((InterfaceDataTypeInteger)individual).getIntegerData().clone(); + return ((InterfaceDataTypeInteger) individual).getIntegerData().clone(); } else if (individual instanceof InterfaceDataTypeDouble) { - return ((InterfaceDataTypeDouble)individual).getDoubleData().clone(); + return ((InterfaceDataTypeDouble) individual).getDoubleData().clone(); } else if (individual instanceof InterfaceDataTypePermutation) { - return ((InterfaceDataTypePermutation)individual).getPermutationData()[0].clone(); + return ((InterfaceDataTypePermutation) individual).getPermutationData()[0].clone(); } else if (individual instanceof InterfaceDataTypeProgram) { - return ((InterfaceDataTypeProgram)individual).getProgramDataWithoutUpdate().clone(); + return ((InterfaceDataTypeProgram) individual).getProgramDataWithoutUpdate().clone(); } else { - System.err.println("error in AbstractEAIndividual.getDefaultDataObject: type " + individual.getClass() + " not implemented"); - return individual; + System.err.println("error in AbstractEAIndividual.getDefaultDataObject: type " + individual.getClass() + " not implemented"); + return individual; } } - + /** - * This method creates a default String representation for a number Individual interfaces - * containing the genotype. - * + * This method creates a default String representation for a number + * Individual interfaces containing the genotype. + * * @param individual * @return */ public static String getDefaultDataString(IndividualInterface individual, String separator) { - // Note that changing this method might change the hashcode of an individual - // which might interfere with some functionality. - if (individual == null) return "null"; + // Note that changing this method might change the hashcode of an individual + // which might interfere with some functionality. + if (individual == null) { + return "null"; + } StringBuffer sb = new StringBuffer(""); Formatter fm = new Formatter(sb); char left = '{'; char right = '}'; sb.append(left); if (individual instanceof InterfaceDataTypeBinary) { - BitSet b = ((InterfaceDataTypeBinary)individual).getBinaryData(); - for (int i = 0; i < ((InterfaceDataTypeBinary)individual).size(); i++) { - if (b.get(i)) sb.append("1"); - else sb.append("0"); + BitSet b = ((InterfaceDataTypeBinary) individual).getBinaryData(); + for (int i = 0; i < ((InterfaceDataTypeBinary) individual).size(); i++) { + if (b.get(i)) { + sb.append("1"); + } else { + sb.append("0"); + } } } else if (individual instanceof InterfaceDataTypeInteger) { - int[] b = ((InterfaceDataTypeInteger)individual).getIntegerData(); + int[] b = ((InterfaceDataTypeInteger) individual).getIntegerData(); for (int i = 0; i < b.length; i++) { sb.append(b[i]); - if ((i+1) < b.length) sb.append(separator); + if ((i + 1) < b.length) { + sb.append(separator); + } } } else if (individual instanceof InterfaceDataTypeDouble) { - double[] d = ((InterfaceDataTypeDouble)individual).getDoubleData(); + double[] d = ((InterfaceDataTypeDouble) individual).getDoubleData(); for (int i = 0; i < d.length; i++) { // sb.append(d[i]); // if ((i+1) < d.length) sb.append(separator); - fm.format("% .3f", d[i]); - if ((i+1) < d.length) sb.append(separator); + fm.format("% .3f", d[i]); + if ((i + 1) < d.length) { + sb.append(separator); + } } } else if (individual instanceof InterfaceDataTypePermutation) { - int[] b = ((InterfaceDataTypePermutation)individual).getPermutationData()[0]; + int[] b = ((InterfaceDataTypePermutation) individual).getPermutationData()[0]; for (int i = 0; i < b.length; i++) { sb.append(b[i]); - if ((i+1) < b.length) sb.append(separator); + if ((i + 1) < b.length) { + sb.append(separator); + } } } else if (individual instanceof InterfaceDataTypeProgram) { - InterfaceProgram[] b = ((InterfaceDataTypeProgram)individual).getProgramDataWithoutUpdate(); + InterfaceProgram[] b = ((InterfaceDataTypeProgram) individual).getProgramDataWithoutUpdate(); for (int i = 0; i < b.length; i++) { sb.append(b[i].getStringRepresentation()); - if ((i+1) < b.length) sb.append(separator); + if ((i + 1) < b.length) { + sb.append(separator); + } } } else if (BeanInspector.hasMethod(individual, "toString", null) != null) { - EVAERROR.errorMsgOnce("warning in AbstractEAIndividual::getDefaultDataString: type " + individual.getClass() + " has no default data representation, using toString..."); - return individual.toString(); + EVAERROR.errorMsgOnce("warning in AbstractEAIndividual::getDefaultDataString: type " + individual.getClass() + " has no default data representation, using toString..."); + return individual.toString(); } else { - System.err.println("error in AbstractEAIndividual::getDefaultDataString: type " + individual.getClass() + " not implemented"); + System.err.println("error in AbstractEAIndividual::getDefaultDataString: type " + individual.getClass() + " not implemented"); } sb.append(right); return sb.toString(); } + @Override public String toString() { - return getDefaultStringRepresentation(this); + return getDefaultStringRepresentation(this); } - - /** - * For any AbstractEAIndividual try retrieve its position as double[]. - * Returns null if there is no conversion available. Makes shallow copies if possible. - * - * @param indy - * @return double valued position of an individual or null - */ - public static double[] getDoublePositionShallow(AbstractEAIndividual indy) { - if (indy instanceof InterfaceESIndividual) { - return ((InterfaceESIndividual)indy).getDGenotype(); - } else if (indy instanceof InterfaceDataTypeDouble) { - return ((InterfaceDataTypeDouble)indy).getDoubleData(); - } else if (indy instanceof InterfaceDataTypeInteger) { - int[] intData = ((InterfaceDataTypeInteger)indy).getIntegerData(); - double[] pos = new double[intData.length]; - for (int i=0; i seedCardinality=new Pair(5,1); - private double aroundDist=0.1; - transient private ArrayList listeners = null; + private static final Logger LOGGER = Logger.getLogger(eva2.EvAInfo.defaultLogger); + protected int generationCount = 0; + protected int functionCallCount = 0; + protected int targetPopSize = 50; + protected Population populationArchive = null; + PopulationInitMethod initMethod = PopulationInitMethod.individualDefault; + private double[] seedPos = new double[10]; + private Pair seedCardinality = new Pair(5, 1); + private double aroundDist = 0.1; + transient private ArrayList listeners = null; // the evaluation interval at which listeners are notified - protected int notifyEvalInterval = 0; + protected int notifyEvalInterval = 0; // additional data connected to the population - protected HashMap additionalPopData = null; + protected HashMap additionalPopData = null; // historical best indidivuals may be traced for a given number of generations. Set to -1 to trace all, set to 0 to not trace at all int historyMaxLen = 0; -// boolean useHistory = false; - private transient LinkedList m_History = new LinkedList(); - + private transient LinkedList m_History = new LinkedList(); // remember when the last sorted queue was prepared private int lastQModCount = -1; // a sorted queue (for efficiency) transient private ArrayList sortedArr = null; private Comparator lastSortingComparator = null; - private InterfaceDistanceMetric popDistMetric = null; // an associated metric + private InterfaceDistanceMetric popDistMetric = null; // an associated metric // private AbstractEAIndividualComparator historyComparator = null; - public static final String funCallIntervalReached = "FunCallIntervalReached"; public static final String populationInitialized = "PopulationReinitOccured"; public static final String nextGenerationPerformed = "NextGenerationPerformed"; - + public Population() { - if (TRACE) System.err.println("TRACING POP"); - } - - /** - * Constructor setting initial capacity and target population size to the given - * integer value. - * - * @param initialCapacity initial capacity and population size of the instance - */ - public Population(int initialCapacity) { - super(initialCapacity); - if (TRACE) System.err.println("TRACING POP"); - setTargetSize(initialCapacity); + LOGGER.log(Level.FINER, "New population has been created."); } /** - * Clones parameters, individuals, history and archive. - * + * Constructor setting initial capacity and target population size to the + * given integer value. + * + * @param initialCapacity initial capacity and population size of the + * instance + */ + public Population(int initialCapacity) { + super(initialCapacity); + LOGGER.log(Level.FINER, "New population has been created."); + setTargetSize(initialCapacity); + } + + /** + * Clones parameters, individuals, history and archive. + * * @param population */ public Population(Population population) { - if (TRACE) System.err.println("TRACING POP"); + LOGGER.log(Level.FINER, "New population has been created."); setSameParams(population); for (int i = 0; i < population.size(); i++) { - if (population.get(i) != null) - this.add((((AbstractEAIndividual)population.get(i))).clone()); + if (population.get(i) != null) { + this.add((((AbstractEAIndividual) population.get(i))).clone()); + } } copyHistAndArchive(population); } - + public static Population makePopFromList(List indies) { - Population pop = new Population(indies.size()); - if (TRACE) System.err.println("TRACING POP"); - pop.setTargetSize(indies.size()); - for (AbstractEAIndividual indy : indies) { - pop.add(indy); - } - return pop; - } + Population pop = new Population(indies.size()); + pop.setTargetSize(indies.size()); + for (AbstractEAIndividual indy : indies) { + pop.add(indy); + } + return pop; + } /** - * Create a new population from a solution set by merging - * both current population and solutions from the set. - * + * Create a new population from a solution set by merging both current + * population and solutions from the set. + * * @param allSolutions */ - public Population(InterfaceSolutionSet allSolutions) { - this(allSolutions.getCurrentPopulation().size()+allSolutions.getSolutions().size()); - if (TRACE) System.err.println("TRACING POP"); - addPopulation(allSolutions.getCurrentPopulation(), false); - HashMap checkCols = new HashMap(size()); - for (int i=0; i checkCols = new HashMap(size()); + for (int i = 0; i < size(); i++) { + checkCols.put(getEAIndividual(i).getIndyID(), 1); + } + Population sols = allSolutions.getSolutions(); + for (int i = 0; i < sols.size(); i++) { // addPopulation(allSolutions.getSolutions()); - if (!checkCols.containsKey(sols.getEAIndividual(i).getIndyID())) add(sols.getEAIndividual(i)); - } - } - - /** - * Initialize a population with a binCardinality initialization, meaning that - * the individuals are initialized with N(binCard, binStdDev) bits set. - * @param targetSize - * @param binCard - * @param binStdDev - */ - public Population(int targetSize, int binCard, int binStdDev) { - this(targetSize); - this.setSeedCardinality(new Pair(binCard, binStdDev)); - this.setInitMethod(PopulationInitMethod.binCardinality); - } - - public void hideHideable() { - setInitMethod(getInitMethod()); - } - - /** - * Make (shallow) copies of the given instance within the current instance. - * @param population - */ - public void copyHistAndArchive(Population population) { - if (population.m_Archive != null) this.m_Archive = (Population)population.m_Archive.clone(); - if (population.m_History != null) this.m_History = (LinkedList)population.m_History.clone(); - if (population.additionalPopData!=null) { - this.additionalPopData = (HashMap)additionalPopData.clone(); - if (population.additionalPopData.size()>0) { - for (String key : population.additionalPopData.keySet()) { - additionalPopData.put(key, population.additionalPopData.get(key)); - } - } - } + if (!checkCols.containsKey(sols.getEAIndividual(i).getIndyID())) { + add(sols.getEAIndividual(i)); + } + } } - + /** - * Takes over all scalar parameters of the given population and copies the additional data - * as well as listeners and the seed position. Those are considered functional. + * Initialize a population with a binCardinality initialization, meaning + * that the individuals are initialized with N(binCard, binStdDev) bits set. + * + * @param targetSize + * @param binCard + * @param binStdDev + */ + public Population(int targetSize, int binCard, int binStdDev) { + this(targetSize); + this.setSeedCardinality(new Pair(binCard, binStdDev)); + this.setInitMethod(PopulationInitMethod.binCardinality); + } + + public void hideHideable() { + setInitMethod(getInitMethod()); + } + + /** + * Make (shallow) copies of the given instance within the current instance. + * + * @param population + */ + public void copyHistAndArchive(Population population) { + if (population.populationArchive != null) { + this.populationArchive = (Population) population.populationArchive.clone(); + } + if (population.m_History != null) { + this.m_History = (LinkedList) population.m_History.clone(); + } + if (population.additionalPopData != null) { + this.additionalPopData = (HashMap) additionalPopData.clone(); + if (population.additionalPopData.size() > 0) { + for (String key : population.additionalPopData.keySet()) { + additionalPopData.put(key, population.additionalPopData.get(key)); + } + } + } + } + + /** + * Takes over all scalar parameters of the given population and copies the + * additional data as well as listeners and the seed position. Those are + * considered functional. + * * @param population */ public void setSameParams(Population population) { - this.m_Generation = population.m_Generation; - this.m_FunctionCalls = population.m_FunctionCalls; - this.m_TargetSize = population.m_TargetSize; - this.historyMaxLen = population.historyMaxLen; + this.generationCount = population.generationCount; + this.functionCallCount = population.functionCallCount; + this.targetPopSize = population.targetPopSize; + this.historyMaxLen = population.historyMaxLen; this.notifyEvalInterval = population.notifyEvalInterval; - this.initMethod = population.initMethod; - this.aroundDist = population.aroundDist; - this.seedCardinality = population.seedCardinality.clone(); - if (population.getPopMetric()!=null) this.popDistMetric = (InterfaceDistanceMetric)population.popDistMetric.clone(); - if (population.seedPos!=null) this.seedPos = population.seedPos.clone(); + this.initMethod = population.initMethod; + this.aroundDist = population.aroundDist; + this.seedCardinality = population.seedCardinality.clone(); + if (population.getPopMetric() != null) { + this.popDistMetric = (InterfaceDistanceMetric) population.popDistMetric.clone(); + } + if (population.seedPos != null) { + this.seedPos = population.seedPos.clone(); + } // this.m_Listener = population.m_Listener; - if (population.listeners != null) this.listeners = (ArrayList)population.listeners.clone(); - else listeners = null; + if (population.listeners != null) { + this.listeners = (ArrayList) population.listeners.clone(); + } else { + listeners = null; + } if (population.additionalPopData != null) { - additionalPopData = new HashMap(); - Set keys = additionalPopData.keySet(); - for (String key : keys) { - additionalPopData.put(key, population.additionalPopData.get(key)); - } + additionalPopData = new HashMap(); + Set keys = additionalPopData.keySet(); + for (String key : keys) { + additionalPopData.put(key, population.additionalPopData.get(key)); + } } } /** - * Be aware that this does not check all fields. Fields which are not considered - * functional are omitted, such as archive, history and the listeners. + * Be aware that this does not check all fields. Fields which are not + * considered functional are omitted, such as archive, history and the + * listeners. */ public boolean equals(Object o) { - if (!super.equals(o)) return false; - if (o==null) return false; - if (!(o instanceof Population)) return false; - Population opop = (Population)o; - if (this.m_Generation != opop.m_Generation) return false; - if (this.m_FunctionCalls != opop.m_FunctionCalls) return false; - if (this.m_TargetSize != opop.m_TargetSize) return false; - if (this.historyMaxLen != opop.historyMaxLen) return false; - if (this.notifyEvalInterval != opop.notifyEvalInterval) return false; - if (this.initMethod != opop.initMethod) return false; - if (this.aroundDist != opop.aroundDist) return false; - if ((this.seedPos!=null) ^ (opop.seedPos!=null)) return false; - if ((this.seedPos!=null) && (!this.seedPos.equals(opop.seedPos))) return false; - //listeners may be omitted - if ((this.additionalPopData!=null) ^ (opop.additionalPopData!=null)) return false; - if (this.additionalPopData!=null) for (String s : this.additionalPopData.keySet()) { - if (this.additionalPopData.get(s)==null && (opop.additionalPopData.get(s)!=null)) return false; - if (this.additionalPopData.get(s)!=null && (!this.additionalPopData.get(s).equals(this.additionalPopData))) return false; - } - return true; + if (!super.equals(o)) { + return false; + } + if (o == null) { + return false; + } + if (!(o instanceof Population)) { + return false; + } + Population opop = (Population) o; + if (this.generationCount != opop.generationCount) { + return false; + } + if (this.functionCallCount != opop.functionCallCount) { + return false; + } + if (this.targetPopSize != opop.targetPopSize) { + return false; + } + if (this.historyMaxLen != opop.historyMaxLen) { + return false; + } + if (this.notifyEvalInterval != opop.notifyEvalInterval) { + return false; + } + if (this.initMethod != opop.initMethod) { + return false; + } + if (this.aroundDist != opop.aroundDist) { + return false; + } + if ((this.seedPos != null) ^ (opop.seedPos != null)) { + return false; + } + if ((this.seedPos != null) && (!this.seedPos.equals(opop.seedPos))) { + return false; + } + //listeners may be omitted + if ((this.additionalPopData != null) ^ (opop.additionalPopData != null)) { + return false; + } + if (this.additionalPopData != null) { + for (String s : this.additionalPopData.keySet()) { + if (this.additionalPopData.get(s) == null && (opop.additionalPopData.get(s) != null)) { + return false; + } + if (this.additionalPopData.get(s) != null && (!this.additionalPopData.get(s).equals(this.additionalPopData))) { + return false; + } + } + } + return true; } - + public void putData(String key, Object value) { - if (additionalPopData == null) additionalPopData = new HashMap(); - additionalPopData.put(key, value); + if (additionalPopData == null) { + additionalPopData = new HashMap(); + } + additionalPopData.put(key, value); } - + public Object getData(String key) { - if (additionalPopData == null) return null; - else return additionalPopData.get(key); + if (additionalPopData == null) { + return null; + } else { + return additionalPopData.get(key); + } } - + public boolean hasData(String key) { - if (additionalPopData != null) return (additionalPopData.get(key)!=null); - else return false; + if (additionalPopData != null) { + return (additionalPopData.get(key) != null); + } else { + return false; + } } - + public Object clone() { return (Object) new Population(this); } - + /** - * Clone the population without cloning every individual. This produces an empty population - * which can be used to fill with the next generation by an EA and is implemented for efficiency. - * - * @return an empty population with equal members but not containing any individuals + * Clone the population without cloning every individual. This produces an + * empty population which can be used to fill with the next generation by an + * EA and is implemented for efficiency. + * + * @return an empty population with equal members but not containing any + * individuals */ public Population cloneWithoutInds() { - // these two basically clone without cloning every individual - Population res = new Population(); - res.setSameParams(this); - res.copyHistAndArchive(this); - if (additionalPopData!=null) res.additionalPopData = (HashMap)(additionalPopData.clone()); - return res; + // these two basically clone without cloning every individual + Population res = new Population(); + res.setSameParams(this); + res.copyHistAndArchive(this); + if (additionalPopData != null) { + res.additionalPopData = (HashMap) (additionalPopData.clone()); + } + return res; } /** - * Clone the population with shallow copies of the individual. This should be used with care! + * Clone the population with shallow copies of the individual. This should + * be used with care! + * * @return */ public Population cloneShallowInds() { - Population pop = cloneWithoutInds(); - pop.addAll(this); - return pop; - } + Population pop = cloneWithoutInds(); + pop.addAll(this); + return pop; + } - /** This method inits the state of the population AFTER the individuals - * have been inited by a problem + /** + * This method inits the state of the population AFTER the individuals have + * been inited by a problem */ public void init() { this.m_History = new LinkedList(); - this.m_Generation = 0; - this.m_FunctionCalls = 0; + this.generationCount = 0; + this.functionCallCount = 0; double[] popSeed = null; // evaluationTimeHashes = null; // evaluationTimeModCount = -1; - if (this.m_Archive != null) { - this.m_Archive.clear(); - this.m_Archive.init(); + if (this.populationArchive != null) { + this.populationArchive.clear(); + this.populationArchive.init(); } switch (initMethod) { - case individualDefault: - break; - case randomLatinHypercube: - createRLHSampling(this, false); - break; - case aroundSeed: - case aroundRandomSeed: - AbstractEAIndividual template = (AbstractEAIndividual) getEAIndividual(0).clone(); - // use random initial position or the predefined one - if (initMethod==PopulationInitMethod.aroundRandomSeed) popSeed=RNG.randomDoubleArray(PostProcess.getDoubleRange(template)); - else popSeed = seedPos; - if (template.getDoublePosition().length<=popSeed.length) { - if (template.getDoublePosition().length0) curCard += (int)Math.round(RNG.gaussianDouble((double)stdDev)); - curCard=Math.max(0, Math.min(curCard, gaIndy.getGenotypeLength())); -// System.out.println("Current cardinality: " + curCard); - gaIndy.SetBGenotype(RNG.randomBitSet(curCard, gaIndy.getGenotypeLength())); -// System.out.println(pop.getEAIndividual(i)); - } - } else { - System.err.println("Error: InterfaceGAIndividual required for binary cardinality initialization!"); - } + if (pop.size() <= 0) { + System.err.println("createBinCardinality needs at least one template individual in the population"); + return; + } + AbstractEAIndividual template = pop.getEAIndividual(0); + if (fillPop) { + pop.fill(template); + } + if (template instanceof InterfaceGAIndividual) { + for (int i = 0; i < pop.size(); i++) { + InterfaceGAIndividual gaIndy = (InterfaceGAIndividual) pop.getEAIndividual(i); + int curCard = cardinality; + if (stdDev > 0) { + curCard += (int) Math.round(RNG.gaussianDouble((double) stdDev)); + } + curCard = Math.max(0, Math.min(curCard, gaIndy.getGenotypeLength())); + gaIndy.SetBGenotype(RNG.randomBitSet(curCard, gaIndy.getGenotypeLength())); + } + } else { + System.err.println("Error: InterfaceGAIndividual required for binary cardinality initialization!"); + } } - + /** - * Fill the population up to the target size with clones of a template individual. - * + * Fill the population up to the target size with clones of a template + * individual. + * * @param template a template individual used to fill the population */ public void fill(AbstractEAIndividual template) { - if (this.size() getHistory() { - return m_History; - } - - public void SetHistory(LinkedList theHist) { - m_History = theHist; - } - - /** This method will allow you to increment the current number of function calls. - */ - public void incrFunctionCalls() { - this.m_FunctionCalls++; - if (doEvalNotify()) { -// System.out.println("checking funcall event..."); - if ((m_FunctionCalls % notifyEvalInterval) == 0) firePropertyChangedEvent(funCallIntervalReached); + if (useHist) { + setMaxHistoryLength(-1); // trace full history! + } else { + setMaxHistoryLength(0); // dont trace at all! } } - /** - * This method will allow you to increment the current number of function calls by a number > 1. - * Notice that it might slightly disturb notification if a notifyEvalInterval is set. - * - * @param d The number of function calls to increment by. - */ - public void incrFunctionCallsBy(int d) { - if (doEvalNotify()) { -// System.out.println("checking funcall event..."); - int nextStep; // next interval boundary - while ((nextStep = calcNextBoundary()) <= (m_FunctionCalls+d)) { - // the notify interval will be stepped over or hit - int toHit = (nextStep - m_FunctionCalls); - this.m_FunctionCalls += toHit; // little cheat, notify may be after some more evals - firePropertyChangedEvent(funCallIntervalReached); - d = d-toHit; -// this.m_FunctionCalls += (d-toHit); - } - if (d>0) this.m_FunctionCalls += d; // add up the rest - } else this.m_FunctionCalls += d; + + public boolean isUsingHistory() { + return historyMaxLen != 0; } - private int calcNextBoundary() { - return ((m_FunctionCalls/notifyEvalInterval)+1) * notifyEvalInterval; - } - - /** Something has changed + public void setMaxHistoryLength(int len) { + historyMaxLen = len; + } + + public int getMaxHistLength() { + return historyMaxLen; + } + + public int getHistoryLength() { + if (historyMaxLen != 0) { + return m_History.size(); + } else { + return 0; + } + } + + public LinkedList getHistory() { + return m_History; + } + + public void SetHistory(LinkedList theHist) { + m_History = theHist; + } + + /** + * This method will allow you to increment the current number of function + * calls. + */ + public void incrFunctionCalls() { + this.functionCallCount++; + if (doEvalNotify()) { + if ((functionCallCount % notifyEvalInterval) == 0) { + firePropertyChangedEvent(funCallIntervalReached); + } + } + } + + /** + * This method will allow you to increment the current number of function + * calls by a number > 1. Notice that it might slightly disturb notification + * if a notifyEvalInterval is set. + * + * @param d The number of function calls to increment by. + */ + public void incrFunctionCallsBy(int d) { + if (doEvalNotify()) { +// System.out.println("checking funcall event..."); + int nextStep; // next interval boundary + while ((nextStep = calcNextBoundary()) <= (functionCallCount + d)) { + // the notify interval will be stepped over or hit + int toHit = (nextStep - functionCallCount); + this.functionCallCount += toHit; // little cheat, notify may be after some more evals + firePropertyChangedEvent(funCallIntervalReached); + d = d - toHit; +// this.m_FunctionCalls += (d-toHit); + } + if (d > 0) { + this.functionCallCount += d; // add up the rest + } + } else { + this.functionCallCount += d; + } + } + + private int calcNextBoundary() { + return ((functionCallCount / notifyEvalInterval) + 1) * notifyEvalInterval; + } + + /** + * Something has changed */ protected void firePropertyChangedEvent(String name) { if (listeners != null) { - for (Iterator iterator = listeners.iterator(); iterator.hasNext();) { - InterfacePopulationChangedEventListener listener = iterator.next(); - if (listener!=null) listener.registerPopulationStateChanged(this, name); - } + for (Iterator iterator = listeners.iterator(); iterator.hasNext();) { + InterfacePopulationChangedEventListener listener = iterator.next(); + if (listener != null) { + listener.registerPopulationStateChanged(this, name); + } + } } } - + private boolean doEvalNotify() { - return ((listeners != null) && (listeners.size() > 0) && (notifyEvalInterval > 0)); - } - - /** This method return the current number of function calls performed. - * @return The number of function calls performed. - */ - public int getFunctionCalls() { - return this.m_FunctionCalls; + return ((listeners != null) && (listeners.size() > 0) && (notifyEvalInterval > 0)); } - /** This method set the current number of function calls performed. - * Use with care - * @param d The new number of functioncalls. + /** + * This method return the current number of function calls performed. + * + * @return The number of function calls performed. + */ + @Override + public int getFunctionCalls() { + return this.functionCallCount; + } + + /** + * This method set the current number of function calls performed. Use with + * care + * + * @deprecated + * @param d The new number of functioncalls. */ public void SetFunctionCalls(int d) { - this.m_FunctionCalls = d; + this.functionCallCount = d; } /** - * To initialize (or invalidate) all current fitness values, this method sets them - * to the given array. - * + * This method set the current number of function calls performed. Use with + * care + * + * @param d The new number of functioncalls. + */ + public void setFunctionCalls(int d) { + this.functionCallCount = d; + } + + /** + * To initialize (or invalidate) all current fitness values, this method + * sets them to the given array. + * * @param f */ public void setAllFitnessValues(double[] f) { - AbstractEAIndividual indy; - for (int i=0; i= 1)) { - if (historyMaxLen>0 && (m_History.size()>=historyMaxLen)) { - // oldest one must be replaced.. should be the one in front - m_History.removeFirst(); - } - this.m_History.add((AbstractEAIndividual)this.getBestEAIndividual().clone()); + if (historyMaxLen > 0 && (m_History.size() >= historyMaxLen)) { + // oldest one must be replaced.. should be the one in front + m_History.removeFirst(); + } + this.m_History.add((AbstractEAIndividual) this.getBestEAIndividual().clone()); } - for (int i=0; i(3); - if (!listeners.contains(ea)) { - listeners.add(ea); - } - } - } - - public void removePopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { - if (listeners != null) { - listeners.remove(ea); - } + if (ea != null) { + if (listeners == null) { + listeners = new ArrayList(3); + } + if (!listeners.contains(ea)) { + listeners.add(ea); + } + } } - /** This method allows you to add a complete population to the current population. - * Note: After this operation the target population size may be exceeded. - * This method does not check for duplicate object pointers. - * - * @param pop The population that is to be added. + public void removePopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { + if (listeners != null) { + listeners.remove(ea); + } + } + + /** + * This method allows you to add a complete population to the current + * population. Note: After this operation the target population size may be + * exceeded. This method does not check for duplicate object pointers. + * + * @param pop The population that is to be added. */ public Population addPopulation(Population pop) { - return this.addPopulation(pop, false); + return this.addPopulation(pop, false); } - + /** - * This method allows you to add a complete population to the current population. - * Note: After this operation the target population size may be exceeded. - * If indicated, this method checks for and avoids duplicate object pointers. - * - * @param pop The population that is to be added. - * @param avoidDuplicatePointers if true, duplicate object pointers are forbidden + * This method allows you to add a complete population to the current + * population. Note: After this operation the target population size may be + * exceeded. If indicated, this method checks for and avoids duplicate + * object pointers. + * + * @param pop The population that is to be added. + * @param avoidDuplicatePointers if true, duplicate object pointers are + * forbidden */ public Population addPopulation(Population pop, boolean avoidDuplicatePointers) { if (pop != null) { - for (int i = 0; i < pop.size(); i++) { - AbstractEAIndividual indy = (AbstractEAIndividual)pop.get(i); - if (avoidDuplicatePointers && this.contains(indy)) { - System.err.println("Warning, duplicate indy avoided in Population.addPopulation! Index of " + this.indexOf(indy)); - } else { - if (indy != null) { - this.add(indy); - } - } - } + for (int i = 0; i < pop.size(); i++) { + AbstractEAIndividual indy = (AbstractEAIndividual) pop.get(i); + if (avoidDuplicatePointers && this.contains(indy)) { + System.err.println("Warning, duplicate indy avoided in Population.addPopulation! Index of " + this.indexOf(indy)); + } else { + if (indy != null) { + this.add(indy); + } + } + } } return this; } - - /** - * Fill the population up to the given size with random elements - * from the given population. - * - * @param upTo target size of the population - * @param fromPop The population that is to be added. - * + + /** + * Fill the population up to the given size with random elements from the + * given population. + * + * @param upTo target size of the population + * @param fromPop The population that is to be added. + * */ public boolean fillWithRandom(int upTo, Population fromPop) { - if (upTo <= this.size()) return true; - else if (fromPop==null || (fromPop.size()<1)) return false; - else { - int[] perm = RNG.randomPerm(fromPop.size()); - int i=0; - while ((i> findSamePositions() { - ArrayList> dupes = new ArrayList>(); - for (int i=0; i= 0) dupes.add(new Pair(i, nextIndex)); - } - return dupes; + public List> findSamePositions() { + ArrayList> dupes = new ArrayList>(); + for (int i = 0; i < size() - 1; i++) { + int nextIndex = indexByPosition(i + 1, getEAIndividual(i)); + if (nextIndex >= 0) { + dupes.add(new Pair(i, nextIndex)); + } + } + return dupes; } - + /** - * Return true if an individual with equal position is contained within the population. - * + * Return true if an individual with equal position is contained within the + * population. + * * @param indy * @return */ public boolean containsByPosition(AbstractEAIndividual indy) { - return indexByPosition(0,indy)>=0; - } + return indexByPosition(0, indy) >= 0; + } /** - * Return the index of the first individual which has an equal position or -1. - * + * Return the index of the first individual which has an equal position or + * -1. + * * @param startIndex the first index to start the search * @param indy - * @return the index of the first individual which has an equal position or -1 + * @return the index of the first individual which has an equal position or + * -1 */ - public int indexByPosition(int startIndex, AbstractEAIndividual indy) { - for (int i=startIndex; ifit2[fitIndex]; - } - } - - /** - * This method will return the index of the current best individual from the - * population. If the population is empty, -1 is returned. + /** + * Compare two fitness vectors. If bChooseBetter is true, the function + * delivers the predicate "first is better than second" using the fitness + * component indicated by fitIndex or a dominance criterion if fitIndex < 0. * + * @param bChooseBetter + * @param fit1 + * @param fit2 + * @param fitIndex + * @return + */ + private boolean compareFit(boolean bChooseBetter, double[] fit1, double[] fit2, int fitIndex) { + if (fitIndex < 0) { // multiobjective case + if (bChooseBetter) { + return AbstractEAIndividual.isDominatingFitness(fit1, fit2); + } else { + return AbstractEAIndividual.isDominatingFitness(fit2, fit1); + } + } else { + if (bChooseBetter) { + return fit1[fitIndex] < fit2[fitIndex]; + } else { + return fit1[fitIndex] > fit2[fitIndex]; + } + } + } + + /** + * This method will return the index of the current best individual from the + * population. If the population is empty, -1 is returned. + * * @see getIndexOfBestOrWorstIndividual() * @return The index of the best individual. */ public int getIndexOfBestIndividualPrefFeasible() { - if (size()<1) return -1; - return getIndexOfBestOrWorstIndy(true, true, -1); + if (size() < 1) { + return -1; + } + return getIndexOfBestOrWorstIndy(true, true, -1); } - - /** - * This method will return the index of the current worst individual from the - * population. - * + + /** + * This method will return the index of the current worst individual from + * the population. + * * @see getIndexOfBestOrWorstIndividual() * @return The index of the worst individual. */ public int getIndexOfWorstIndividualNoConstr() { - return getIndexOfBestOrWorstIndy(false, false, -1); + return getIndexOfBestOrWorstIndy(false, false, -1); } - - /** - * This method will return the index of the current best individual from the - * population in the given fitness component (or using dominance when fitIndex < 0). - * If the population is empty, -1 is returned. - * + + /** + * This method will return the index of the current best individual from the + * population in the given fitness component (or using dominance when + * fitIndex < 0). If the population is empty, -1 is returned. + * + + * * @see getIndexOfBestOrWorstIndividual() * @return The index of the best individual. */ public int getIndexOfBestIndividualPrefFeasible(int fitIndex) { - if (size()<1) return -1; - return getIndexOfBestOrWorstIndy(true, true, fitIndex); + if (size() < 1) { + return -1; + } + return getIndexOfBestOrWorstIndy(true, true, fitIndex); } - - /** - * This method will return the index of the current best individual from the - * population in the given fitness component (or using dominance when fitIndex < 0). - * + + /** + * This method will return the index of the current best individual from the + * population in the given fitness component (or using dominance when + * fitIndex < 0). + * * @see getIndexOfBestOrWorstIndividual() * @return The index of the best individual. */ public int getIndexOfWorstIndividualNoConstr(int fitIndex) { - return getIndexOfBestOrWorstIndy(false, false, fitIndex); + return getIndexOfBestOrWorstIndy(false, false, fitIndex); } - + /** - * Return the best feasible individual or null if the population contains - * no or only infeasible individuals. This considers both aspects: the constraint setting - * as well as penalization. An individual is feasible only if it is both unpenalized and - * not violating the constraints. - * + * Return the best feasible individual or null if the population contains no + * or only infeasible individuals. This considers both aspects: the + * constraint setting as well as penalization. An individual is feasible + * only if it is both unpenalized and not violating the constraints. + * * @param fitIndex * @return the best feasible individual or null if none is feasible */ public AbstractEAIndividual getBestFeasibleIndividual(int fitIndex) { - int index=getIndexOfBestOrWorstFeasibleIndividual(true, fitIndex); - if (index<0) return null; - else return getEAIndividual(index); + int index = getIndexOfBestOrWorstFeasibleIndividual(true, fitIndex); + if (index < 0) { + return null; + } else { + return getEAIndividual(index); + } } - -// /** -// * Return the best individual which has a zero penalty value (is feasible concerning -// * penalty). If all are penalized, null is returned. -// * -// * @param fitIndex -// * @return -// */ -// public AbstractEAIndividual getBestUnpenalizedIndividual(int fitIndex) { -// int result = -1; -// double[] curSelFitness = null; -// boolean allViolate = true; -// -// for (int i = 0; i < super.size(); i++) { -// if (!(getEAIndividual(i).isMarkedPenalized())) { -// allViolate = false; -// if ((result<0) || (compareFit(true, getEAIndividual(i).getFitness(), curSelFitness, fitIndex))) { -// // fit i is better than remembered -// result = i; -// curSelFitness = getEAIndividual(i).getFitness(); // remember fit i -// } -// } -// } -// if (allViolate) { -// return null; -// } else { -// return getEAIndividual(result); -// } -// } - - /** - * This method will return the index of the current best (worst) individual from the - * population. A given comparator is employed for individual comparisons. - * - * @param bBest if true, the best (first) index is returned, else the worst (last) one + + /** + * This method will return the index of the current best (worst) individual + * from the population. A given comparator is employed for individual + * comparisons. + * + * @param bBest if true, the best (first) index is returned, else the worst + * (last) one * @param comparator indicate whether constraints should be regarded * @return The index of the best (worst) individual. */ public int getIndexOfBestOrWorstIndividual(boolean bBest, Comparator comparator) { - ArrayList sorted = sortBy(comparator); - if (bBest) return indexOf(sorted.get(0)); - else return indexOfInstance(sorted.get(sorted.size()-1)); + ArrayList sorted = sortBy(comparator); + if (bBest) { + return indexOf(sorted.get(0)); + } else { + return indexOfInstance(sorted.get(sorted.size() - 1)); + } } public int getIndexOfBestEAIndividual(AbstractEAIndividualComparator comparator) { - return getIndexOfBestOrWorstIndividual(true, comparator); + return getIndexOfBestOrWorstIndividual(true, comparator); } - + public AbstractEAIndividual getBestEAIndividual(Comparator comparator) { - int index = getIndexOfBestOrWorstIndividual(true, comparator); - return getEAIndividual(index); + int index = getIndexOfBestOrWorstIndividual(true, comparator); + return getEAIndividual(index); } /** - * Return the index of the best (or worst) indy using an AbstractEAIndividualComparator - * that checks the constraints first and then for the given fitness criterion (or - * a pareto criterion if it is -1). - * - * @param bBest if true, the best (first) index is returned, else the worst (last) one + * Return the index of the best (or worst) indy using an + * AbstractEAIndividualComparator that checks the constraints first and then + * for the given fitness criterion (or a pareto criterion if it is -1). + * + * @param bBest if true, the best (first) index is returned, else the worst + * (last) one * @param checkConstraints * @param fitIndex * @see #getIndexOfBestOrWorstIndividual(boolean, Comparator) @@ -933,486 +1063,417 @@ public class Population extends ArrayList implements PopulationInterface, Clonea * @return */ public int getIndexOfBestOrWorstIndy(boolean bBest, boolean checkConstraints, int fitIndex) { - return getIndexOfBestOrWorstIndividual(bBest, new AbstractEAIndividualComparator(fitIndex, checkConstraints)); + return getIndexOfBestOrWorstIndividual(bBest, new AbstractEAIndividualComparator(fitIndex, checkConstraints)); } - + /** - * Returns the index of the first occurrence of the specified element - * in this list, or -1 if this list does not contain the element. - * This only checks for pointer equality. Different instances which - * have equal properties will be considered different. + * Returns the index of the first occurrence of the specified element in + * this list, or -1 if this list does not contain the element. This only + * checks for pointer equality. Different instances which have equal + * properties will be considered different. */ public int indexOfInstance(Object o) { - if (o == null) { - System.err.println("Error, instance null should not be contained! (Population.indexOfInstance)"); - } else { - for (int i = 0; i < size(); i++) { - if (o==get(i)) { - return i; - } - } - } - return -1; + if (o == null) { + System.err.println("Error, instance null should not be contained! (Population.indexOfInstance)"); + } else { + for (int i = 0; i < size(); i++) { + if (o == get(i)) { + return i; + } + } + } + return -1; } -// /** -// * This method will return the index of the current best (worst) individual from the -// * population. If indicated, only those are regarded which do not violate the constraints. -// * If all violate the constraints, the smallest (largest) violation is selected. -// * Comparisons are done multicriterial, but note that for incomparable sets (pareto fronts) -// * this selection will not be fair (always the lowest index of incomparable sets will be returned). -// * -// * @param bBest if true, smallest fitness (regarded best) index is returned, else the highest one -// * @param indicate whether constraints should be regarded -// * @return The index of the best (worst) individual. -// */ -// public int getIndexOfBestOrWorstIndividual(boolean bBest, boolean checkConstraints, int fitIndex) { -// int result = -1; -// double[] curSelFitness = null; -// boolean allViolate = true; -// -// for (int i = 0; i < super.size(); i++) { -// if (!checkConstraints || !(getEAIndividual(i).violatesConstraint())) { -// allViolate = false; -// if ((result<0) || (compareFit(bBest, getEAIndividual(i).getFitness(), curSelFitness, fitIndex))) { -// // fit i is better than remembered -// result = i; -// curSelFitness = getEAIndividual(i).getFitness(); // remember fit i -// } -// } -// } -// if (result < 0) { -// if (checkConstraints && allViolate) { -// // darn all seem to violate the constraint -// // so lets search for the guy who is close to feasible -// -// // to avoid problems with NaN or infinite fitness value, preselect an ind. -// result = 0; -// double minViol = getEAIndividual(0).getConstraintViolation(); -// for (int i = 1; i < super.size(); i++) { -// if ((bBest && getEAIndividual(i).getConstraintViolation() < minViol) || -// (!bBest && (getEAIndividual(i).getConstraintViolation() > minViol))) { -// result = i; -// minViol = ((AbstractEAIndividual)super.get(i)).getConstraintViolation(); -// } -// } -//// System.err.println("Population reports: All individuals violate the constraints, choosing smallest constraint violation."); -// // this is now really reported nicer... -// } else { -// // not all violate, maybe all are NaN! -// // so just select a random one -// System.err.println("Population reports: All individuals seem to have NaN or infinite fitness!"); -// result = RNG.randomInt(size()); -// } -// } -// int testcmp = getIndexOfBestOrWorstIndy(bBest, checkConstraints, fitIndex); -// if (result!=testcmp) { -// if (((getEAIndividual(result).getFitness(0)!=getEAIndividual(testcmp).getFitness(0)) && (!violatesConstraints(testcmp) || !violatesConstraints(result))) -// || (violatesConstraints(testcmp) && violatesConstraints(result) && (!equalConstraintViolation(testcmp, result)))) { -// System.err.println("Error in comparison!!! " + getIndexOfBestOrWorstIndy(bBest, checkConstraints, fitIndex)); -// } -// } else System.err.println("Succ with " + bBest + " " + checkConstraints + " " + fitIndex); -// return result; -// } - -// private boolean equalConstraintViolation(int a, int b) { -// return (getEAIndividual(a).getConstraintViolation()==getEAIndividual(b).getConstraintViolation()); -// } -// -// private boolean violatesConstraints(int i) { -// return (getEAIndividual(i).isMarkedPenalized() || getEAIndividual(i).violatesConstraint()); -// } - - /** - * Search the population for the best (worst) considering the given criterion (or all criteria - * for fitIndex<0) which also does not violate constraints. - * Returns -1 if no feasible solution is found, else the index of the best feasible solution. - * + /** + * Search the population for the best (worst) considering the given + * criterion (or all criteria for fitIndex less than 0) which also does not violate + * constraints. Returns -1 if no feasible solution is found, else the index + * of the best feasible solution. + * * @param bBest * @param fitIndex - * @return -1 if no feasible solution is found, else the index of the best feasible individual + * @return -1 if no feasible solution is found, else the index of the best + * feasible individual */ public int getIndexOfBestOrWorstFeasibleIndividual(boolean bBest, int fitIndex) { - int result = -1; - double[] curSelFitness = null; + int result = -1; + double[] curSelFitness = null; for (int i = 0; i < super.size(); i++) { if (!(getEAIndividual(i).violatesConstraint()) && !(getEAIndividual(i).isMarkedPenalized())) { - if ((result<0) || (compareFit(bBest, getEAIndividual(i).getFitness(), curSelFitness, fitIndex))) { - // fit i is better than remembered - result = i; - curSelFitness = getEAIndividual(i).getFitness(); // remember fit i - } + if ((result < 0) || (compareFit(bBest, getEAIndividual(i).getFitness(), curSelFitness, fitIndex))) { + // fit i is better than remembered + result = i; + curSelFitness = getEAIndividual(i).getFitness(); // remember fit i + } } } return result; } - - /** - * This method returns the current best individual from the population. - * If the population is empty, null is returned. - * + + /** + * This method returns the current best individual from the population. If + * the population is empty, null is returned. + * * @return The best individual */ public AbstractEAIndividual getBestEAIndividual() { - return getBestEAIndividual(-1); + return getBestEAIndividual(-1); } - - /** - * This method returns the currently best individual from the population - * by a given fitness component while prioritizing feasible ones. - * If the population is empty, null is returned. + + /** + * This method returns the currently best individual from the population by + * a given fitness component while prioritizing feasible ones. If the + * population is empty, null is returned. * * @param fitIndex the fitness criterion index or -1 * @return The best individual */ public AbstractEAIndividual getBestEAIndividual(int fitIndex) { - if (size()<1) return null; - int best = this.getIndexOfBestIndividualPrefFeasible(fitIndex); - if (best == -1) { - System.err.println("This shouldnt happen!"); - return null; - } else { - AbstractEAIndividual result = (AbstractEAIndividual)this.get(best); - if (result == null) System.err.println("Serious Problem! Population Size: " + this.size()); - return result; - } + if (size() < 1) { + return null; + } + int best = this.getIndexOfBestIndividualPrefFeasible(fitIndex); + if (best == -1) { + System.err.println("This shouldnt happen!"); + return null; + } else { + AbstractEAIndividual result = (AbstractEAIndividual) this.get(best); + if (result == null) { + System.err.println("Serious Problem! Population Size: " + this.size()); + } + return result; + } } - /** - * This method returns the n current best individuals from the population, where - * the sorting criterion is delivered by an AbstractEAIndividualComparator. - * There are less than n individuals returned if the population is smaller than n. - * If n is <= 0, then all individuals are returned and effectively just sorted - * by fitness. - * This does not check constraints! - * + /** + * This method returns the n current best individuals from the population, + * where the sorting criterion is delivered by an + * AbstractEAIndividualComparator. There are less than n individuals + * returned if the population is smaller than n. If n is <= 0, then all + * individuals are returned and effectively just sorted by fitness. This + * does not check constraints! + * * @param n number of individuals to look out for * @return The m best individuals, where m <= n - * + * */ public Population getBestNIndividuals(int n, int fitIndex) { - if (n<=0 || (n>super.size())) n=super.size(); - Population pop = new Population(n); - getSortedNIndividuals(n, true, pop, new AbstractEAIndividualComparator(fitIndex)); - return pop; + if (n <= 0 || (n > super.size())) { + n = super.size(); + } + Population pop = new Population(n); + getSortedNIndividuals(n, true, pop, new AbstractEAIndividualComparator(fitIndex)); + return pop; } - - /** - * This method returns the n current worst individuals from the population, where - * the sorting criterion is delivered by an AbstractEAIndividualComparator. - * There are less than n individuals returned if the population is smaller than n. - * If n is <= 0, then all individuals are returned and effectively just sorted - * by fitness. - * This does not check constraints! - * + + /** + * This method returns the n current worst individuals from the population, + * where the sorting criterion is delivered by an + * AbstractEAIndividualComparator. There are less than n individuals + * returned if the population is smaller than n. If n is <= 0, then all + * individuals are returned and effectively just sorted by fitness. This + * does not check constraints! + * * @param n number of individuals to look out for * @return The m worst individuals, where m <= n - * + * */ public Population getWorstNIndividuals(int n, int fitIndex) { - Population pop = new Population(n); - getSortedNIndividuals(n, false, pop, new AbstractEAIndividualComparator(fitIndex)); - return pop; + Population pop = new Population(n); + getSortedNIndividuals(n, false, pop, new AbstractEAIndividualComparator(fitIndex)); + return pop; } - - /** - * This method returns a clone of the population instance with sorted individuals, where - * the sorting criterion is delivered by a Comparator. + + /** + * This method returns a clone of the population instance with sorted + * individuals, where the sorting criterion is delivered by a Comparator. + * * @see #getSortedNIndividuals(int, boolean, Population, Comparator) - * - * @return a clone of the population instance with sorted individuals, best fitness first + * + * @return a clone of the population instance with sorted individuals, best + * fitness first */ public Population getSortedBestFirst(Comparator comp) { - Population result = this.cloneWithoutInds(); - getSortedNIndividuals(size(), true, result, comp); - result.synchSize(); - return result; + Population result = this.cloneWithoutInds(); + getSortedNIndividuals(size(), true, result, comp); + result.synchSize(); + return result; } - - /** - * This method returns the n current best individuals from the population, where - * the sorting criterion is delivered by an AbstractEAIndividualComparator. - * @see getSortedNIndividuals(int n, boolean bBestOrWorst, Population res) - * - * @param n number of individuals to look out for - * @param bBestOrWorst if true, the best n are returned, else the worst n individuals - * @return The m sorted best or worst individuals, where m <= n - * - */ -// public Population getSortedNIndividuals(int n, boolean bBestOrWorst) { -// Population result = new Population((n > 0) ? n : this.size()); -// getSortedNIndividuals(n, bBestOrWorst, result); -// return result; -// } - - /** - * This method returns the n current best individuals from the population, where - * the sorting criterion is delivered by a Comparator instance. - * There are less than n individuals returned if the population is smaller than n. + + /** + * This method returns the n current best individuals from the population, + * where the sorting criterion is delivered by a Comparator instance. There + * are less than n individuals returned if the population is smaller than n. * This does not check constraints! - * + * * @param n number of individuals to look out for - * @param bBestOrWorst if true, the best n are returned, else the worst n individuals + * @param bBestOrWorst if true, the best n are returned, else the worst n + * individuals * @param res sorted result population, will be cleared * @param comp the Comparator to use with individuals * @return The m sorted best or worst individuals, where m <= n - * + * */ public void getSortedNIndividuals(int n, boolean bBestOrWorst, Population res, Comparator comp) { - if ((n < 0) || (n>super.size())) { - // this may happen, treat it gracefully - //System.err.println("invalid request to getSortedNIndividuals: n="+n + ", size is " + super.size()); - n = super.size(); - } - int skip = 0; - if (!bBestOrWorst) skip = super.size()-n; - + if ((n < 0) || (n > super.size())) { + // this may happen, treat it gracefully + //System.err.println("invalid request to getSortedNIndividuals: n="+n + ", size is " + super.size()); + n = super.size(); + } + int skip = 0; + if (!bBestOrWorst) { + skip = super.size() - n; + } + // hier getSorted aufrufen - ArrayList sorted = getSorted(comp); - res.clear(); - for (int i = skip; i < skip+n; i++) { - res.add(sorted.get(i)); + ArrayList sorted = getSorted(comp); + res.clear(); + for (int i = skip; i < skip + n; i++) { + res.add(sorted.get(i)); } res.synchSize(); } - -// /** -// * Get the n best (or worst) individuals from the population. The last comparator -// * is reused, or if none has been employed yet, a standard comparator is used. -// * -// * @param n -// * @param bBestOrWorst -// * @param res -// */ -// public void getSortedNIndividuals(int n, boolean bBestOrWorst, Population res) { -// getSortedNIndividuals(n, bBestOrWorst, res, lastSortingComparator); -// } - + /** * From the given list, remove all but the first n elements. + * * @param n * @param l */ public static List toHead(int n, List l) { - l.subList(n, l.size()).clear(); - return l; + l.subList(n, l.size()).clear(); + return l; } - + /** * From the given list, remove all but the last n elements. + * * @param n * @param l */ public static List toTail(int n, List l) { - l.subList(0, l.size()-n).clear(); - return l; + l.subList(0, l.size() - n).clear(); + return l; } - + /** - * Return a new population containing only the last n elements of the instance. + * Return a new population containing only the last n elements of the + * instance. + * * @param n * @param l */ public Population toTail(int n) { - Population retPop = new Population(n); - retPop.addAll(subList(0, size()-n)); - return retPop; + Population retPop = new Population(n); + retPop.addAll(subList(0, size() - n)); + return retPop; } - + /** - * Set a fitness criterion for sorting procedures. This sorts the - * population once and influences further getBest* methods if no - * specific comparator is given. + * Set a fitness criterion for sorting procedures. This sorts the population + * once and influences further getBest* methods if no specific comparator is + * given. + * * @param fitIndex */ public void setSortingFitnessCriterion(int fitIndex) { - getSorted(new AbstractEAIndividualComparator(fitIndex)); + getSorted(new AbstractEAIndividualComparator(fitIndex)); } - -// /** -// * Reuses the last fitness criterion. Avoid having to sort again in several calls without modifications in between. -// * The returned array should not be modified! -// * -// * @return -// */ -// protected ArrayList getSorted() { -// return getSorted(lastFitCrit); -// } /** - * Sort the population returning a new ArrayList. - * The returned array should not be modified! - * - * @param comp A comparator by which sorting is performed - it should work on AbstractEAIndividual instances. + * Sort the population returning a new ArrayList. The returned array should + * not be modified! + * + * @param comp A comparator by which sorting is performed - it should work + * on AbstractEAIndividual instances. * @return */ protected ArrayList sortBy(Comparator comp) { - if (super.size()==0) return new ArrayList(); - PriorityQueue sQueue = new PriorityQueue(super.size(), comp); - for (int i = 0; i < super.size(); i++) { - AbstractEAIndividual indy = getEAIndividual(i); - if (indy != null) sQueue.add(indy); - } - ArrayList sArr = new ArrayList(this.size()); - AbstractEAIndividual indy; - while ((indy=sQueue.poll())!=null) sArr.add(indy); - return sArr; + if (super.isEmpty()) { + return new ArrayList(); + } + PriorityQueue sQueue = new PriorityQueue(super.size(), comp); + for (int i = 0; i < super.size(); i++) { + AbstractEAIndividual indy = getEAIndividual(i); + if (indy != null) { + sQueue.add(indy); + } + } + ArrayList sArr = new ArrayList(this.size()); + AbstractEAIndividual indy; + while ((indy = sQueue.poll()) != null) { + sArr.add(indy); + } + return sArr; } - + /** - * Return a sorted list of individuals. The order is based on the - * given comparator. Repeated calls do not resort the population every - * time as long as an equal comparator is used (implement the equals() method!) - * and the population has not been modified. - * The returned array must not be altered! - * - * @param fitIndex the fitness criterion to be used or -1 for pareto dominance + * Return a sorted list of individuals. The order is based on the given + * comparator. Repeated calls do not resort the population every time as + * long as an equal comparator is used (implement the equals() method!) and + * the population has not been modified. The returned array must not be + * altered! + * + * @param fitIndex the fitness criterion to be used or -1 for pareto + * dominance * @return */ public ArrayList getSorted(Comparator comp) { -// Comparator comp = new AbstractEAIndividualComparator(fitIndex); -// if (!comp.equals(lastSortingComparator)) return sortedArr; - if (!comp.equals(lastSortingComparator) || (sortedArr == null) || (super.modCount != lastQModCount)) { -// lastFitCrit=fitIndex;lastSortingComparator - ArrayList sArr = sortBy(comp); - if (sortedArr==null) sortedArr = sArr; - else { - sortedArr.clear(); - sortedArr.addAll(sArr); - } - lastSortingComparator = (Comparator) Serializer.deepClone(comp); - lastQModCount = super.modCount; - } - return sortedArr; + if (!comp.equals(lastSortingComparator) || (sortedArr == null) || (super.modCount != lastQModCount)) { + ArrayList sArr = sortBy(comp); + if (sortedArr == null) { + sortedArr = sArr; + } else { + sortedArr.clear(); + sortedArr.addAll(sArr); + } + lastSortingComparator = (Comparator) Serializer.deepClone(comp); + lastQModCount = super.modCount; + } + return sortedArr; } /** * Returns the sorted population as a new population instance. + * * @see getSorted(Comparator) */ public Population getSortedPop(Comparator comp) { - Population pop = this.cloneWithoutInds(); - ArrayList sortedIndies = getSorted(comp); - pop.addAll(sortedIndies); - return pop; - } - - /** - * This method retrieves n random individuals from the population and - * returns them within a new population. - * - * @param n number of individuals to look out for - * @return The n best individuals - * - */ - public Population getRandNIndividuals(int n) { - if (n>=size()) return (Population)clone(); - else { - Population pop = cloneShallowInds(); - Population retPop = cloneWithoutInds(); - moveNInds(n, pop, retPop); - return retPop; - } - } - - /** - * This method removes n random individuals from the population and - * returns them within a new population. - * - * @param n number of individuals to look out for - * @return The n best individuals - * - */ - public Population moveRandNIndividuals(int n) { - return moveRandNIndividualsExcept(n, new Population()); - } - - /** - * This method removes n random individuals from the population (excluding the given ones) - * and returns them in a new population instance. - * - * @param n number of individuals to look out for - * @return The n random individuals - * - */ - public Population moveRandNIndividualsExcept(int n, Population exclude) { - return moveNInds(n, filter(exclude), new Population()); + Population pop = this.cloneWithoutInds(); + ArrayList sortedIndies = getSorted(comp); + pop.addAll(sortedIndies); + return pop; } /** - * Moves n random individuals from src Population to dst Population and returns dst Population. - * + * This method retrieves n random individuals from the population and + * returns them within a new population. + * + * @param n number of individuals to look out for + * @return The n best individuals + * + */ + public Population getRandNIndividuals(int n) { + if (n >= size()) { + return (Population) clone(); + } else { + Population pop = cloneShallowInds(); + Population retPop = cloneWithoutInds(); + moveNInds(n, pop, retPop); + return retPop; + } + } + + /** + * This method removes n random individuals from the population and returns + * them within a new population. + * + * @param n number of individuals to look out for + * @return The n best individuals + * + */ + public Population moveRandNIndividuals(int n) { + return moveRandNIndividualsExcept(n, new Population()); + } + + /** + * This method removes n random individuals from the population (excluding + * the given ones) and returns them in a new population instance. + * + * @param n number of individuals to look out for + * @return The n random individuals + * + */ + public Population moveRandNIndividualsExcept(int n, Population exclude) { + return moveNInds(n, filter(exclude), new Population()); + } + + /** + * Moves n random individuals from src Population to dst Population and + * returns dst Population. + * * @param n * @param from * @param to * @return */ public static Population moveNInds(int n, Population src, Population dst) { - if ((n == 0) || (src.size() == 0)) return dst; - else { // Ingenious superior Scheme tail recursive style! - moveRandIndFromTo(src, dst); - return moveNInds(n-1, src, dst); - } - } - + if ((n == 0) || (src.size() == 0)) { + return dst; + } else { // Ingenious superior Scheme tail recursive style! + moveRandIndFromTo(src, dst); + return moveNInds(n - 1, src, dst); + } + } + /** * Move one random individual from src to dst population. + * * @param from * @param to */ public static void moveRandIndFromTo(Population src, Population dst) { - int k = RNG.randomInt(src.size()); - dst.add(src.removeIndexSwitched(k)); + int k = RNG.randomInt(src.size()); + dst.add(src.removeIndexSwitched(k)); } - + /** - * Returns a subset of this population which does not contain the individuals - * in the given exclude list as shallow copies. + * Returns a subset of this population which does not contain the + * individuals in the given exclude list as shallow copies. + * * @param exclude * @return */ public Population filter(Population exclude) { - if (exclude.size() == 0) return this; - Population pop = new Population(); - for (Object o : this) { - if (!exclude.contains(o)) pop.add(o); - } - return pop; + if (exclude.size() == 0) { + return this; + } + Population pop = new Population(); + for (Object o : this) { + if (!exclude.contains(o)) { + pop.add(o); + } + } + return pop; } - - /** + + /** * This method returns the currently worst individual from the population + * * @return The best individual */ public AbstractEAIndividual getWorstEAIndividual() { - return getWorstEAIndividual(-1); - } - - public AbstractEAIndividual getWorstEAIndividual(int fitIndex) { - return getEAIndividual(getIndexOfWorstIndividualNoConstr(fitIndex)); + return getWorstEAIndividual(-1); } - /** - * This method will remove N individuals from the population - * Note: the current strategy will be remove N individuals - * at random but later a special heuristic could be introduced. - * @param n The number of individuals for be removed + public AbstractEAIndividual getWorstEAIndividual(int fitIndex) { + return getEAIndividual(getIndexOfWorstIndividualNoConstr(fitIndex)); + } + + /** + * This method will remove + * N individuals from the population Note: the + * current strategy will be remove N individuals at random but later a + * special heuristic could be introduced. + * + * @param n The number of individuals for be removed */ public void removeNIndividuals(int n) { for (int i = 0; i < n; i++) { - this.remove(RNG.randomInt(0, this.size()-1)); + this.remove(RNG.randomInt(0, this.size() - 1)); } } - /** This method will remove double instances from the population. - * This method relies on the implementation of the equals method - * in the individuals. + /** + * This method will remove double instances from the population. This method + * relies on the implementation of the equals method in the individuals. */ public void removeRedundantIndies() { for (int i = 0; i < this.size(); i++) { - for (int j = i+1; j < this.size(); j++) { - if (((AbstractEAIndividual)this.get(i)).equals(this.get(j))) { + for (int j = i + 1; j < this.size(); j++) { + if (((AbstractEAIndividual) this.get(i)).equals(this.get(j))) { this.remove(j); j--; } @@ -1421,36 +1482,38 @@ public class Population extends ArrayList implements PopulationInterface, Clonea } public Population removeRedundantIndiesAsNew() { - Population pop = this.cloneShallowInds(); - pop.removeRedundantIndies(); - return pop; + Population pop = this.cloneShallowInds(); + pop.removeRedundantIndies(); + return pop; } - /** - * Return the number of individuals within this instance that are - * seen as being equal by the equals relation of the individual. - * - * @return the number of equal individuals - * - */ - public int getRedundancyCount() { - int redund = 0; - for (int i=0; i