Browse Source

AlgoFramework

Tom 4 years ago
parent
commit
5542d23072

+ 4 - 4
src/Connection/ConnectHandheld.java

@@ -22,7 +22,7 @@ import javax.swing.JSplitPane;
 import javax.swing.JTextArea;
 import javax.swing.text.NumberFormatter;
 
-import api.Algorithm;
+import api.AddOn;
 import classes.AbstractCpsObject;
 import classes.CpsUpperNode;
 import classes.HolonObject;
@@ -32,7 +32,7 @@ import Connection.socket.Server;
 import ui.controller.Control;
 import ui.view.Console;
 
-public class ConnectHandheld implements Algorithm{
+public class ConnectHandheld implements AddOn{
 	
 	//Holeg
 	Control control;
@@ -59,7 +59,7 @@ public class ConnectHandheld implements Algorithm{
 	{
 	      JFrame newFrame = new JFrame("exampleWindow");
 	      ConnectHandheld instance = new ConnectHandheld();
-	      newFrame.setContentPane(instance.getAlgorithmPanel());
+	      newFrame.setContentPane(instance.getPanel());
 	      newFrame.pack();
 	      newFrame.setVisible(true);
 	      newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
@@ -164,7 +164,7 @@ public class ConnectHandheld implements Algorithm{
 	
 
 	@Override
-	public JPanel getAlgorithmPanel() {
+	public JPanel getPanel() {
 		return content;
 	}
 

+ 4 - 4
src/Connection/ConnectPhysical.java

@@ -31,7 +31,7 @@ import javax.swing.JSplitPane;
 import javax.swing.JTextArea;
 import javax.swing.text.NumberFormatter;
 
-import api.Algorithm;
+import api.AddOn;
 import classes.AbstractCpsObject;
 import classes.CpsUpperNode;
 import classes.HolonElement;
@@ -44,7 +44,7 @@ import ui.view.Console;
  * @author tom
  *
  */
-public class ConnectPhysical implements Algorithm{
+public class ConnectPhysical implements AddOn{
 	//Holeg
 	private Control  control;
 	
@@ -113,7 +113,7 @@ public class ConnectPhysical implements Algorithm{
 	{
 	      JFrame newFrame = new JFrame("exampleWindow");
 	      ConnectPhysical instance = new ConnectPhysical();
-	      newFrame.setContentPane(instance.getAlgorithmPanel());
+	      newFrame.setContentPane(instance.getPanel());
 	      newFrame.pack();
 	      newFrame.setVisible(true);
 	      newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
@@ -502,7 +502,7 @@ public class ConnectPhysical implements Algorithm{
 	
 	
 	@Override
-	public JPanel getAlgorithmPanel() {
+	public JPanel getPanel() {
 		return content;
 	}
 

+ 3 - 3
src/api/Algorithm.java → src/api/AddOn.java

@@ -5,10 +5,10 @@ import javax.swing.JPanel;
 import ui.controller.Control;
 
 /**
- * Interface for a Algorithm that is executed on the current timestep.
+ * Interface for a Standart Addon.
  * @author Tom Troppmann
  */
-public interface Algorithm  {
-	public JPanel getAlgorithmPanel();
+public interface AddOn  {
+	public JPanel getPanel();
 	public void setController(Control control);
 }

+ 518 - 0
src/api/AlgorithmFramework.java

@@ -0,0 +1,518 @@
+package api;
+
+import java.awt.BorderLayout;
+import java.awt.Component;
+import java.awt.Dimension;
+import java.awt.FlowLayout;
+import java.awt.image.BufferedImage;
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStreamWriter;
+import java.util.ArrayList;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.stream.Collectors;
+
+import javax.swing.BorderFactory;
+import javax.swing.ImageIcon;
+import javax.swing.JButton;
+import javax.swing.JFileChooser;
+import javax.swing.JOptionPane;
+import javax.swing.JPanel;
+import javax.swing.JProgressBar;
+import javax.swing.JScrollPane;
+import javax.swing.JSplitPane;
+
+import classes.AbstractCpsObject;
+import classes.CpsUpperNode;
+import classes.HolonElement;
+import classes.HolonObject;
+import classes.HolonSwitch;
+import ui.controller.Control;
+import ui.model.DecoratedGroupNode;
+import ui.model.DecoratedState;
+import ui.model.Model;
+import ui.view.Console;
+
+public abstract class AlgorithmFramework implements AddOn{
+	//Algo
+	protected int rounds = 3;
+	
+	
+	
+	//Panel
+	private JPanel content = new JPanel();
+	protected Console console = new Console();
+	
+	
+	//Settings groupNode
+	private boolean useGroupNode = false;
+	private DecoratedGroupNode dGroupNode = null;
+	
+	
+	//access
+	private ArrayList<AccessWrapper> access;
+	LinkedList<List<Boolean>> resetChain = new LinkedList<List<Boolean>>();
+	
+	
+	//time
+	private long startTime;
+	
+	
+	
+	private RunProgressBar runProgressbar = new RunProgressBar();
+	
+	
+	
+	//concurrency
+	private Thread runThread = new Thread();
+	protected boolean cancel = false;
+
+	//holeg interaction
+	private Control  control;
+
+	
+	//printing
+	protected RunDataBase db;
+	
+	
+	public AlgorithmFramework(){
+		content.setLayout(new BorderLayout());
+		JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
+				createOptionPanel() , console);
+		splitPane.setResizeWeight(0.0);
+		content.add(splitPane, BorderLayout.CENTER);
+		content.setPreferredSize(new Dimension(800,800));
+	}
+	
+	
+	
+	
+	
+	
+	public JPanel createOptionPanel() {
+		JPanel optionPanel = new JPanel(new BorderLayout());
+		JScrollPane scrollPane = new JScrollPane(createParameterPanel());
+		scrollPane.setBorder(BorderFactory.createTitledBorder("Parameter"));
+		optionPanel.add(scrollPane,  BorderLayout.CENTER);
+		optionPanel.add(createButtonPanel(), BorderLayout.PAGE_END);
+		return optionPanel;
+	}
+	
+	private Component createParameterPanel() {
+		JPanel parameterPanel = new JPanel(null);
+		parameterPanel.setPreferredSize(new Dimension(510,300));
+		
+		JProgressBar progressBar = runProgressbar.getJProgressBar();
+		progressBar.setBounds(350, 155, 185, 20);
+		progressBar.setStringPainted(true);
+		parameterPanel.add(progressBar);
+		
+		JButton selectGroupNodeButton = new JButton("Select GroupNode");
+		selectGroupNodeButton.setBounds(350, 120, 185, 30);
+		selectGroupNodeButton.addActionListener(actionEvent -> selectGroupNode());
+		parameterPanel.add(selectGroupNodeButton);	
+		
+		
+		
+		return parameterPanel;
+	}
+	public JPanel createButtonPanel() {
+		JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
+		
+		JButton resetButton =  new JButton("Reset");
+		resetButton.setToolTipText("Resets the State to before the Algorithm has runed.");
+		resetButton.addActionListener(actionEvent -> reset());
+		buttonPanel.add(resetButton);
+		
+		JButton cancelButton =  new JButton("Cancel Run");
+		cancelButton.addActionListener(actionEvent -> cancel());
+		buttonPanel.add(cancelButton);
+		
+		JButton fitnessButton =  new JButton("Fitness");
+		fitnessButton.setToolTipText("Fitness for the current state.");
+		fitnessButton.addActionListener(actionEvent -> fitness());
+		buttonPanel.add(fitnessButton);
+		
+		JButton runButton =  new JButton("Run");
+		runButton.addActionListener(actionEvent -> {
+			Runnable task = () -> run();
+			runThread = new Thread(task);
+			runThread.start();
+		});
+		buttonPanel.add(runButton);
+		
+		
+		
+		return buttonPanel;
+	}
+	
+	
+
+	private void startTimer(){
+		startTime = System.currentTimeMillis();
+	}
+	private void printElapsedTime(){
+		long elapsedMilliSeconds = System.currentTimeMillis() - startTime;
+		console.println("Execution Time of Algo in Milliseconds:" + elapsedMilliSeconds);
+	}
+	
+	
+	
+	
+	private void cancel() {
+		if(runThread.isAlive()) {
+			console.println("Cancel run.");
+			cancel = true;
+			runProgressbar.stop();
+		} else {
+			console.println("Nothing to cancel.");
+		}
+	}
+	
+	
+	private void fitness() {
+		if(runThread.isAlive()) {
+			console.println("Run have to be cancelled First.");
+			return;
+		}
+		double currentFitness = evaluatePosition(extractPositionAndAccess());
+		resetChain.removeLast();
+		console.println("Actual Fitnessvalue: " + currentFitness);
+	}
+	
+	
+	private void selectGroupNode() {
+		Object[] possibilities = control.getSimManager().getActualVisualRepresentationalState().getCreatedGroupNodes().values().stream().map(aCps -> new Handle<DecoratedGroupNode>(aCps)).toArray();
+		@SuppressWarnings("unchecked")
+		Handle<DecoratedGroupNode> selected = (Handle<DecoratedGroupNode>) JOptionPane.showInputDialog(content, "Select GroupNode:", "GroupNode?",  JOptionPane.OK_OPTION,new ImageIcon(new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB)) , possibilities, "");
+		if(selected != null) {
+			console.println("Selected: " + selected);
+			dGroupNode = selected.object;
+		}
+	}
+	
+	protected double evaluatePosition(List<Boolean> positionToEvaluate) {
+		runProgressbar.step();
+		setState(positionToEvaluate);
+		control.calculateStateOnlyForCurrentTimeStep();
+		DecoratedState actualstate = control.getSimManager().getActualDecorState();
+		return evaluateState(actualstate);
+	}
+
+	protected abstract double evaluateState(DecoratedState actualstate);
+
+	
+	private void run() {
+		cancel = false;
+		control.guiDisable(true);
+		executeAlgoWithParameter();
+		updateVisual();
+		control.guiDisable(false);
+	}
+	
+	private void executeAlgoWithParameter(){
+		runProgressbar.start();
+		int actualIteration = control.getModel().getCurIteration();
+		console.println("TimeStep:" + actualIteration);
+		startTimer();
+		Individual runBest = new Individual();
+		runBest.fitness = Double.MAX_VALUE;
+		db = new RunDataBase();
+		for(int r = 0; r < rounds; r++)
+		{		
+			Individual  roundBest = executeAlgo();
+			if(cancel)return;
+			resetState();
+			if(roundBest.fitness < runBest.fitness) runBest = roundBest;
+		}
+		printElapsedTime();
+		setState(runBest.position);
+		updateVisual();
+		console.println("AlgoResult:" + runBest.fitness);
+		runProgressbar.stop();
+	}
+	
+	
+	protected abstract Individual executeAlgo();
+
+
+
+
+
+
+	private void reset() {
+		if(runThread.isAlive()) {
+			console.println("Run have to be cancelled First.");
+			return;
+		}
+		if(!resetChain.isEmpty()) {
+			console.println("Resetting..");
+			setState(resetChain.getFirst());
+			resetChain.clear();
+			control.resetSimulation();
+			control.setCurIteration(0);
+			updateVisual();
+		}else {
+			console.println("No run inistialized.");
+		}
+	}
+
+
+	/**
+	 * To let the User See the current state without touching the Canvas.
+	 */
+	private void updateVisual() {
+		control.calculateStateAndVisualForCurrentTimeStep();
+	}
+	/**
+	 * Sets the Model back to its original State before the LAST run.
+	 */
+	private void resetState() {
+		setState(resetChain.getLast());
+	}
+
+
+	/**
+	 * Sets the State out of the given position for calculation or to show the user.
+	 * @param position
+	 */
+	private void setState(List<Boolean> position) {
+		int i = 0;
+		for(Boolean bool: position) {
+			access.get(i++).setState(bool);
+		}
+}
+
+
+	/**
+	 * Method to get the current Position alias a ListOf Booleans for aktive settings on the Objects on the Canvas.
+	 * Also initialize the Access Hashmap to swap faster positions.
+	 * @param model
+	 * @return
+	 */
+	protected List<Boolean> extractPositionAndAccess() {
+		Model model = control.getModel();
+		access= new ArrayList<AccessWrapper>();
+		List<Boolean> initialState = new ArrayList<Boolean>();
+		rollOutNodes((useGroupNode && (dGroupNode != null))? dGroupNode.getModel().getNodes() :model.getObjectsOnCanvas(), initialState, model.getCurIteration());			
+		resetChain.add(initialState); 
+		return initialState;
+	}
+	
+	/**
+	 * Method to extract the Informations recursively out of the Model.
+	 * @param nodes
+	 * @param positionToInit
+	 * @param timeStep
+	 */
+	private void rollOutNodes(List<AbstractCpsObject> nodes, List<Boolean> positionToInit, int timeStep) {
+		for(AbstractCpsObject aCps : nodes) {
+			if (aCps instanceof HolonObject) {
+				for (HolonElement hE : ((HolonObject) aCps).getElements()) {
+					positionToInit.add(hE.isActive());
+					access.add(new AccessWrapper(hE));
+				}
+			}
+			else if (aCps instanceof HolonSwitch) {
+				HolonSwitch sw = (HolonSwitch) aCps;
+				positionToInit.add(sw.getState(timeStep));
+				access.add(new AccessWrapper(sw));
+			}
+			else if(aCps instanceof CpsUpperNode) {
+				rollOutNodes(((CpsUpperNode)aCps).getNodes(), positionToInit ,timeStep );
+			}
+		}
+	}
+	
+	
+	
+	
+	
+	
+
+	
+	@Override
+	public JPanel getPanel() {
+		return content;
+	}
+
+	@Override
+	public void setController(Control control) {
+		this.control = control;
+	}
+	
+	
+	
+	private class RunProgressBar{
+		//progressbar
+		private JProgressBar progressBar = new JProgressBar();
+		private int count = 0;
+		private boolean isActive = false;
+		public void step() {
+			if(isActive) progressBar.setValue(count++);
+			progressBar.setMaximum(getProgressBarMaxCount());
+		}
+		public void start() {
+			isActive = true;
+			progressBar.setValue(0);
+		}
+		public void stop() {
+			isActive = false;
+		}
+		public JProgressBar getJProgressBar(){
+			return progressBar;
+		}
+	}
+	
+	protected abstract int getProgressBarMaxCount();
+	
+	
+	
+	
+	public class RunDataBase{
+		List<List<Double>> allRuns = new ArrayList<List<Double>>();
+		public void insertNewRun(List<Double> newRun){
+			allRuns.add(newRun);
+		}
+		
+	}
+	
+	
+	
+	public class RunPrinter{
+		//Fields
+		private JFileChooser fileChooser = new JFileChooser();
+		private boolean append = false;
+		//Constructor
+		public RunPrinter(String filename) {
+			this(filename, false);
+		}
+		
+		public RunPrinter(String filename,  boolean append){
+			this.append = append;
+			fileChooser.setCurrentDirectory(new File(System.getProperty("user.dir")));
+		    fileChooser.setSelectedFile(new File(filename));
+		}
+		//public methods
+		public void enableAppend(boolean enable) {
+			append = enable;
+		}
+		public void setFilename(String filename) {
+			fileChooser.setSelectedFile(new File(filename));
+		}
+		public void print(String info) {
+			File file = fileChooser.getSelectedFile();
+			try {
+				file.createNewFile();
+				BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
+					    new FileOutputStream(file, append), "UTF-8"));
+				printToStream(out, info);
+				out.close();
+			} catch (IOException e) {
+				System.out.println(e.getMessage());
+			}
+		}
+		//private methods
+		private void printToStream(BufferedWriter out, String info) throws IOException {	
+			out.write(info);
+			out.newLine();
+			if(db != null)
+			out.write(db.allRuns.stream().map(list -> list.stream().map(Object::toString).collect(Collectors.joining(","))).collect(Collectors.joining(System.lineSeparator())));
+		}
+	}
+		
+	
+	/**
+	 * A Wrapper Class for Access HolonElement and HolonSwitch in one Element and not have to split the List.
+	 */
+	private class AccessWrapper {
+		public static final int HOLONELEMENT = 0;
+		public static final int SWITCH = 1;
+		private int type;
+		private HolonSwitch hSwitch;
+		private HolonElement hElement;
+		public AccessWrapper(HolonSwitch hSwitch){
+			type = SWITCH;
+			this.hSwitch = hSwitch;
+		}
+		public AccessWrapper(HolonElement hElement){
+			type = HOLONELEMENT;
+			this.hElement = hElement;
+		}
+		public void setState(boolean state) {
+			if(type == HOLONELEMENT) {
+				hElement.setActive(state);
+			}else{//is switch
+				hSwitch.setManualMode(true);
+				hSwitch.setManualState(state);
+			}
+				
+		}
+		public boolean getState(int timeStep) {
+			return (type == HOLONELEMENT)?hElement.isActive():hSwitch.getState(timeStep);
+		}
+		public int getType() {
+			return type;
+		}
+	}
+	
+	
+	
+	
+	/**
+	* To create Random and maybe switch the random generation in the future.
+	*/
+	protected static class Random{
+		private static java.util.Random random = new java.util.Random();
+		/**
+		 * True or false
+		 * @return the random boolean.
+		 */
+		public static boolean nextBoolean(){
+			return random.nextBoolean();
+		}
+		/**
+		 * Between 0.0(inclusive) and 1.0 (exclusive)
+		 * @return the random double.
+		 */
+		public static double nextDouble() {
+			return random.nextDouble();
+		}
+		
+		/**
+		 * Random Int in Range [min;max[ with UniformDistirbution
+		 * @param min
+		 * @param max
+		 * @return
+		 */
+		public static int nextIntegerInRange(int min, int max) {
+			return min + random.nextInt(max - min);
+		}
+	}
+	
+	private   class  Handle<T>{
+		public T object;
+		Handle(T object){
+			this.object = object;
+		}
+		public String toString() {
+			return object.toString();
+		}
+	}
+	public class Individual {
+		public double fitness;
+		public  List<Boolean> position;
+		
+		public Individual(){};
+		/**
+		 *  Copy Constructor
+		 */
+		public Individual(Individual c){
+			position = c.position.stream().collect(Collectors.toList());
+			fitness = c.fitness;
+		}
+	}
+}

+ 5 - 8
src/exampleAlgorithms/AcoAlgorithm.java

@@ -36,7 +36,7 @@ import javax.swing.JSplitPane;
 import javax.swing.JTextArea;
 import javax.swing.text.NumberFormatter;
 
-import api.Algorithm;
+import api.AddOn;
 import classes.AbstractCpsObject;
 import classes.CpsUpperNode;
 import classes.HolonElement;
@@ -50,7 +50,7 @@ import ui.model.Model;
 import ui.view.Console;
 import ui.model.DecoratedHolonObject.HolonObjectState;
 
-public class AcoAlgorithm implements Algorithm {
+public class AcoAlgorithm implements AddOn {
 
 		//Parameter for Algo with default Values:
 		/**
@@ -110,7 +110,7 @@ public class AcoAlgorithm implements Algorithm {
 		{
 		      JFrame newFrame = new JFrame("exampleWindow");
 		      AcoAlgorithm instance = new AcoAlgorithm();
-		      newFrame.setContentPane(instance.getAlgorithmPanel());
+		      newFrame.setContentPane(instance.getPanel());
 		      newFrame.pack();
 		      newFrame.setVisible(true);
 		      newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
@@ -368,7 +368,7 @@ public class AcoAlgorithm implements Algorithm {
 
 		
 		private void disableGuiInput(boolean bool) {
-			control.guiDiable(bool);
+			control.guiDisable(bool);
 		}
 		
 		
@@ -376,7 +376,7 @@ public class AcoAlgorithm implements Algorithm {
 		
 		
 		@Override
-		public JPanel getAlgorithmPanel() {
+		public JPanel getPanel() {
 			return content;
 		}
 		@Override
@@ -639,8 +639,6 @@ public class AcoAlgorithm implements Algorithm {
 		 */
 		private void updateVisual() {
 			control.calculateStateAndVisualForCurrentTimeStep();
-			//control.updateCanvas();
-			//control.getGui().triggerUpdateController(null);
 		}
 		/**
 		 * Sets the Model back to its original State before the LAST run.
@@ -717,7 +715,6 @@ public class AcoAlgorithm implements Algorithm {
 		 */
 		public class RunDataBase {
 			List<List<Double>> allRuns = new ArrayList<List<Double>>();
-
 			
 			
 			/**

+ 186 - 0
src/exampleAlgorithms/AcoAlgorithm2.java

@@ -0,0 +1,186 @@
+package exampleAlgorithms;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.ListIterator;
+
+import javax.swing.JFrame;
+import javax.swing.JPanel;
+
+import api.AlgorithmFramework;
+import ui.model.DecoratedState;
+import ui.view.Console;
+
+public class AcoAlgorithm2 extends AlgorithmFramework{
+	
+	//Parameter for Algo with default Values:
+	/**
+	 * Should be even.
+	 */
+	private int popsize = 20;
+	private int maxGenerations = 200;
+	/**
+	 * The vaporization factor;
+	 */
+	private double p = 0.3;
+	private double convergenceFactorReset = 0.99;
+	private boolean moreInformation = false;
+	
+	
+	
+	
+	
+	
+	
+	public static void main(String[] args)
+	{
+	      JFrame newFrame = new JFrame("exampleWindow");
+	      AcoAlgorithm2 instance = new AcoAlgorithm2();
+	      newFrame.setContentPane(instance.getPanel());
+	      newFrame.pack();
+	      newFrame.setVisible(true);
+	      newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+	}
+
+	@Override
+	protected double evaluateState(DecoratedState actualstate) {
+		return PSOAlgorithm.getFitnessValueForState(actualstate);
+	}
+
+
+	@Override
+	protected int getProgressBarMaxCount() {
+		return rounds * popsize * maxGenerations;
+	}
+	
+	
+	/** 	
+	 * 	Algorithm 20 !! Fitness is better when smaller.: 
+	 *  PseudoCode:
+	 *  Best <- actual;
+	 *  pheromones = initPheromons();
+	 * 	for(maxGeneration times){
+	 * 		population = createSolutionsBiasedBy(pheromones);
+	 * 		for(each Individual i from population){
+	 * 			fitness <- evaluatePosition(i);
+	 * 			if(fitness < best.fitnessValue) Best <- i;
+	 * 		}
+	 * 		vaporizeIntensifiePheromons(pheromones);
+	 * 	}
+	 * @return 
+	 */
+	@Override
+	protected Individual executeAlgo() {
+		Individual best = new Individual();
+		best.position = extractPositionAndAccess();
+		if(moreInformation )console.println("Bit-Array_length: " + best.position.size());
+		best.fitness = evaluatePosition(best.position);
+		List<Double> runList = new ArrayList<Double>();
+		runList.add(best.fitness);
+		console.print("Start with: " + best.fitness);
+		if(moreInformation)console.println("");
+		int problemSize = best.position.size();
+		if(problemSize == 0) return best;
+		List<Double> pheromones = initPheromones(problemSize);
+		List<Individual> population = new ArrayList<Individual>();
+		if(moreInformation)console.println("Size To Test:" + population.size());
+		for(int generation = 0; generation< maxGenerations; generation++) {
+			population.clear();
+			population = constructSolutionsBiasedBy(pheromones);
+			if(moreInformation)console.println("Generation" + generation + " start with Fitness: " + best.fitness);
+			for(Individual i : population) {
+				i.fitness = evaluatePosition(i.position);
+				if(moreInformation)console.println("Fitness" + i.fitness);
+				if(i.fitness < best.fitness) best = i;	
+			}
+			runList.add(best.fitness);
+			if(moreInformation)console.println("________________");
+			vaporizeIntensifiePheromons(pheromones, best.position, problemSize);
+			double cf = calculateConvergenceFactor(pheromones, problemSize);
+			if(moreInformation)console.println("ConvergenceFactor = " + cf);
+			if(cf > this.convergenceFactorReset) {
+				pheromones = initPheromones(problemSize);
+			}
+			if(cancel)return null;
+		}
+		
+		
+		console.println("   End With:" + best.fitness);
+		db.insertNewRun(runList);
+		return best;
+		
+	}
+			
+			
+	/**
+	 * tj1 is the pheromon level in the j position
+	 * cf is the convergence factor cf e [0;1]
+	 * difference = | tj1 - tj0 | = | tj1 - (1 - tj1) |
+	 * 
+	 * 
+	 * 
+	 * @param pheromones
+	 * @return cf
+	 */
+	private double calculateConvergenceFactor(List<Double> pheromones,int problemSize) {
+		double sumOfDifference = pheromones.stream().map(tj1 -> Math.abs(tj1 - (1.0 - tj1))).reduce(0.0, Double::sum);
+		double cf = sumOfDifference / (double)problemSize;
+		return cf;
+	}
+	/**
+	 * pheromone <- (1-p) * pheromone;
+	 * if(best is true at this position) pheromone <- pheromone + p;
+	 * @param pheromones
+	 * @param position
+	 */
+	private void vaporizeIntensifiePheromons(List<Double> pheromones, List<Boolean> position, int problemSize) {
+		ListIterator<Double> iterPheromone = pheromones.listIterator();
+		ListIterator<Boolean> iterBest = position.listIterator();
+		for(int i = 0; i < problemSize; i++) {
+			double pheromone = iterPheromone.next();
+			boolean bestDecision = iterBest.next();
+			iterPheromone.set((1.0 - p) * pheromone + (bestDecision?p:0.0));
+		}
+	}
+	/**
+	 * 
+	 * @param pheromones
+	 * @return
+	 */
+	private List<Individual> constructSolutionsBiasedBy(List<Double> pheromones) {
+		List<Individual> population =  new ArrayList<Individual>();
+		for(int i = 0; i < popsize; i++) {
+			population.add(constructASolutionBiasedBy(pheromones));
+		}
+		return population;
+	}
+	
+	
+	/**
+	 * Walks the path with a ant and decide by pheromones if should take true or false;
+	 * A pheromone have a level of 0 < pheromone < 1.
+	 * A Pheromone is  equal to the probability.
+	 * @param pheromones
+	 * @return
+	 */
+	private Individual constructASolutionBiasedBy(List<Double> pheromones) {
+		Individual result = new Individual();
+		result.position = new ArrayList<Boolean>();
+		for(double pheromone : pheromones) {
+			result.position.add((Random.nextDouble() < pheromone));
+		}
+		return result;
+	}
+	/**
+	 * Initialize Pheromons with 0.5
+	 */
+	private List<Double> initPheromones(int problemSize) {
+		List<Double> result = new ArrayList<Double>();
+		for(int i = 0; i < problemSize;i++) {
+			result.add(0.5);
+		}
+		return result;
+	}
+
+	
+}

+ 5 - 5
src/exampleAlgorithms/BaseLine.java

@@ -39,7 +39,7 @@ import javax.swing.JTextArea;
 import javax.swing.filechooser.FileNameExtensionFilter;
 import javax.swing.text.NumberFormatter;
 
-import api.Algorithm;
+import api.AddOn;
 import classes.AbstractCpsObject;
 import classes.CpsUpperNode;
 import classes.HolonElement;
@@ -56,7 +56,7 @@ import ui.model.DecoratedState;
 
 
 
-public class BaseLine implements Algorithm {
+public class BaseLine implements AddOn {
 	//Parameter for Algo with default Values:
 	private boolean closeSwitches = true;
 	
@@ -87,7 +87,7 @@ public class BaseLine implements Algorithm {
 	{
 	      JFrame newFrame = new JFrame("exampleWindow");
 	      BaseLine instance = new BaseLine();
-	      newFrame.setContentPane(instance.getAlgorithmPanel());
+	      newFrame.setContentPane(instance.getPanel());
 	      newFrame.pack();
 	      newFrame.setVisible(true);
 	      newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
@@ -218,7 +218,7 @@ public class BaseLine implements Algorithm {
 	
 	
 	private void disableGuiInput(boolean bool) {
-		control.guiDiable(bool);
+		control.guiDisable(bool);
 	}
 	
 	
@@ -227,7 +227,7 @@ public class BaseLine implements Algorithm {
 	
 	
 	@Override
-	public JPanel getAlgorithmPanel() {
+	public JPanel getPanel() {
 		return content;
 	}
 	@Override

+ 5 - 5
src/exampleAlgorithms/DemoAlgo.java

@@ -28,7 +28,7 @@ import javax.swing.JSplitPane;
 import javax.swing.JTextArea;
 import javax.swing.text.NumberFormatter;
 
-import api.Algorithm;
+import api.AddOn;
 import classes.AbstractCpsObject;
 import classes.CpsUpperNode;
 import classes.HolonElement;
@@ -40,7 +40,7 @@ import ui.model.DecoratedNetwork;
 import ui.model.DecoratedState;
 import ui.model.Model;
 
-public class DemoAlgo implements Algorithm {
+public class DemoAlgo implements AddOn {
 
 	//Parameter for Algo with default Values:
 		private boolean closeSwitches = true;
@@ -80,7 +80,7 @@ public class DemoAlgo implements Algorithm {
 		{
 		      JFrame newFrame = new JFrame("exampleWindow");
 		      DemoAlgo instance = new DemoAlgo();
-		      newFrame.setContentPane(instance.getAlgorithmPanel());
+		      newFrame.setContentPane(instance.getPanel());
 		      newFrame.pack();
 		      newFrame.setVisible(true);
 		      newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
@@ -244,7 +244,7 @@ public class DemoAlgo implements Algorithm {
 		
 		
 		private void disableGuiInput(boolean bool) {
-			control.guiDiable(bool);
+			control.guiDisable(bool);
 		}
 		
 		
@@ -253,7 +253,7 @@ public class DemoAlgo implements Algorithm {
 		
 		
 		@Override
-		public JPanel getAlgorithmPanel() {
+		public JPanel getPanel() {
 			return content;
 		}
 		@Override

+ 3 - 3
src/exampleAlgorithms/ExampleFitnessFunction.java

@@ -11,13 +11,13 @@ import javax.swing.JPanel;
 import javax.swing.JScrollPane;
 import javax.swing.JTextArea;
 
-import api.Algorithm;
+import api.AddOn;
 import ui.controller.Control;
 import ui.model.DecoratedHolonObject.HolonObjectState;
 import ui.model.DecoratedNetwork;
 import ui.model.DecoratedState;
 
-public class ExampleFitnessFunction implements Algorithm {
+public class ExampleFitnessFunction implements AddOn {
 	private Control  control;
 	private JTextArea textArea;
 	private JPanel content = new JPanel();
@@ -53,7 +53,7 @@ public class ExampleFitnessFunction implements Algorithm {
 		return parameterPanel;
 	}
 	@Override
-	public JPanel getAlgorithmPanel() {
+	public JPanel getPanel() {
 		return content;
 	}
 

+ 5 - 5
src/exampleAlgorithms/FlexExample.java

@@ -31,7 +31,7 @@ import javax.swing.JSplitPane;
 import javax.swing.JTextArea;
 import javax.swing.text.NumberFormatter;
 
-import api.Algorithm;
+import api.AddOn;
 import classes.AbstractCpsObject;
 import classes.CpsUpperNode;
 import classes.HolonElement;
@@ -48,7 +48,7 @@ import ui.model.DecoratedState;
 import ui.model.Model;
 import ui.model.DecoratedHolonObject.HolonObjectState;
 
-public class FlexExample implements Algorithm {
+public class FlexExample implements AddOn {
 
 	//Parameter for Algo with default Values:
 		private boolean closeSwitches = true;
@@ -89,7 +89,7 @@ public class FlexExample implements Algorithm {
 		{
 		      JFrame newFrame = new JFrame("exampleWindow");
 		      DemoAlgo instance = new DemoAlgo();
-		      newFrame.setContentPane(instance.getAlgorithmPanel());
+		      newFrame.setContentPane(instance.getPanel());
 		      newFrame.pack();
 		      newFrame.setVisible(true);
 		      newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
@@ -272,7 +272,7 @@ public class FlexExample implements Algorithm {
 		
 		
 		private void disableGuiInput(boolean bool) {
-			control.guiDiable(bool);
+			control.guiDisable(bool);
 		}
 		
 		
@@ -281,7 +281,7 @@ public class FlexExample implements Algorithm {
 		
 		
 		@Override
-		public JPanel getAlgorithmPanel() {
+		public JPanel getPanel() {
 			return content;
 		}
 		@Override

+ 5 - 5
src/exampleAlgorithms/GaAlgorithm.java

@@ -42,7 +42,7 @@ import javax.swing.JSplitPane;
 import javax.swing.JTextArea;
 import javax.swing.text.NumberFormatter;
 
-import api.Algorithm;
+import api.AddOn;
 import classes.AbstractCpsObject;
 import classes.CpsUpperNode;
 import classes.HolonElement;
@@ -56,7 +56,7 @@ import ui.model.Model;
 import ui.view.Console;
 import ui.model.DecoratedHolonObject.HolonObjectState;
 
-public class GaAlgorithm implements Algorithm {
+public class GaAlgorithm implements AddOn {
 
 		//Parameter for Algo with default Values:
 		/**
@@ -117,7 +117,7 @@ public class GaAlgorithm implements Algorithm {
 		{
 		      JFrame newFrame = new JFrame("exampleWindow");
 		      GaAlgorithm instance = new GaAlgorithm();
-		      newFrame.setContentPane(instance.getAlgorithmPanel());
+		      newFrame.setContentPane(instance.getPanel());
 		      newFrame.pack();
 		      newFrame.setVisible(true);
 		      newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
@@ -482,7 +482,7 @@ public class GaAlgorithm implements Algorithm {
 		}
 		
 		private void disableGuiInput(boolean bool) {
-			control.guiDiable(bool);
+			control.guiDisable(bool);
 		}
 		
 		private void plott() {
@@ -497,7 +497,7 @@ public class GaAlgorithm implements Algorithm {
 		
 		
 		@Override
-		public JPanel getAlgorithmPanel() {
+		public JPanel getPanel() {
 			return content;
 		}
 		@Override

+ 5 - 5
src/exampleAlgorithms/PSOAlgorithm.java

@@ -42,7 +42,7 @@ import javax.swing.JTextArea;
 import javax.swing.filechooser.FileNameExtensionFilter;
 import javax.swing.text.NumberFormatter;
 
-import api.Algorithm;
+import api.AddOn;
 import classes.AbstractCpsObject;
 import classes.CpsUpperNode;
 import classes.HolonElement;
@@ -60,7 +60,7 @@ import ui.model.DecoratedState;
 
 
 
-public class PSOAlgorithm implements Algorithm {
+public class PSOAlgorithm implements AddOn {
 	//Parameter for Algo with default Values:
 	private int swarmSize = 20; 
 	private int maxIterations = 100; 
@@ -106,7 +106,7 @@ public class PSOAlgorithm implements Algorithm {
 	{
 	      JFrame newFrame = new JFrame("exampleWindow");
 	      PSOAlgorithm instance = new PSOAlgorithm();
-	      newFrame.setContentPane(instance.getAlgorithmPanel());
+	      newFrame.setContentPane(instance.getPanel());
 	      newFrame.pack();
 	      newFrame.setVisible(true);
 	      newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
@@ -412,7 +412,7 @@ public class PSOAlgorithm implements Algorithm {
 		disableGuiInput(false);
 	}
 	private void disableGuiInput(boolean bool) {
-		control.guiDiable(bool);
+		control.guiDisable(bool);
 	}
 	
 	private void cancel() {
@@ -490,7 +490,7 @@ public class PSOAlgorithm implements Algorithm {
 		console.println("SwarmSize:" + swarmSize + ", MaxIter:" + maxIterations + ", Limit:" + limit + ", Dependency:" + dependency + ", Rounds:" + rounds +", DependentParameter: w:"+ w + ", c1:" + c1 + ", c2:" + c2 );
 	}
 	@Override
-	public JPanel getAlgorithmPanel() {
+	public JPanel getPanel() {
 		return content;
 	}
 	@Override

+ 4 - 4
src/exampleAlgorithms/RandomPriority.java

@@ -15,7 +15,7 @@ import javax.swing.JLabel;
 import javax.swing.JPanel;
 import javax.swing.JSlider;
 
-import api.Algorithm;
+import api.AddOn;
 import classes.AbstractCpsObject;
 import classes.CpsUpperNode;
 import classes.HolonElement;
@@ -31,7 +31,7 @@ import ui.controller.Control;
  */
 
 
-public class RandomPriority implements Algorithm {
+public class RandomPriority implements AddOn {
 	/**
 	 * Its like a Gradient the Values are on one Axis from Start to End:
 	 * |--start--lm--mh--he--end--|
@@ -57,7 +57,7 @@ public class RandomPriority implements Algorithm {
 	{
 	      JFrame newFrame = new JFrame("exampleWindow");
 	      RandomPriority instance = new RandomPriority();
-	      newFrame.setContentPane(instance.getAlgorithmPanel());
+	      newFrame.setContentPane(instance.getPanel());
 	      newFrame.pack();
 	      newFrame.setVisible(true);
 	      newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
@@ -197,7 +197,7 @@ public class RandomPriority implements Algorithm {
 	
 	
 	@Override
-	public JPanel getAlgorithmPanel() {
+	public JPanel getPanel() {
 		return content;
 	}
 	@Override

+ 3 - 3
src/exampleAlgorithms/RandomSwitch.java

@@ -12,11 +12,11 @@ import javax.swing.JLabel;
 import javax.swing.JPanel;
 import javax.swing.JSlider;
 
-import api.Algorithm;
+import api.AddOn;
 import classes.HolonSwitch;
 import ui.controller.Control;
 
-public class RandomSwitch implements Algorithm {
+public class RandomSwitch implements AddOn {
 	private double  randomChance = 0.5;
 	private Control  control;
 	
@@ -75,7 +75,7 @@ public class RandomSwitch implements Algorithm {
 		control.updateCanvas();
 	}
 	@Override
-	public JPanel getAlgorithmPanel() {
+	public JPanel getPanel() {
 		return content;
 	}
 	@Override

+ 4 - 4
src/exampleAlgorithms/Randomizer.java

@@ -29,7 +29,7 @@ import com.google.gson.JsonIOException;
 import com.google.gson.JsonParser;
 import com.google.gson.JsonSyntaxException;
 
-import api.Algorithm;
+import api.AddOn;
 import classes.AbstractCpsObject;
 import classes.CpsUpperNode;
 import classes.HolonElement;
@@ -38,7 +38,7 @@ import classes.HolonSwitch;
 import ui.controller.Control;
 import ui.model.Model;
 
-public class Randomizer implements Algorithm {
+public class Randomizer implements AddOn {
 	private Control  control;
 	private int minAmountOfElements = 3;
 	private int maxAmountOfElements = 7;
@@ -48,7 +48,7 @@ public class Randomizer implements Algorithm {
     {
         JFrame newFrame = new JFrame("exampleWindow");
         Randomizer instance = new Randomizer();
-        newFrame.setContentPane(instance.getAlgorithmPanel());
+        newFrame.setContentPane(instance.getPanel());
         newFrame.pack();
         newFrame.setVisible(true);
 	      newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
@@ -150,7 +150,7 @@ public class Randomizer implements Algorithm {
 	
 	
 	@Override
-	public JPanel getAlgorithmPanel() {
+	public JPanel getPanel() {
 		return content;
 	}
 	@Override

+ 1 - 1
src/ui/controller/Control.java

@@ -1031,7 +1031,7 @@ public class Control {
 		return gui;
 	}
 
-	public void guiDiable(boolean state) {
+	public void guiDisable(boolean state) {
 		gui.guiDisable(state);
 	}
 	

+ 11 - 12
src/ui/view/AlgoWindow.java → src/ui/view/AddOnWindow.java

@@ -31,18 +31,17 @@ import javax.swing.text.StyledDocument;
 import javax.tools.JavaCompiler;
 import javax.tools.ToolProvider;
 
-import api.Algorithm;
+import api.AddOn;
 import ui.controller.Control;
 
-//TODO delete old class AlgorithmMenu and change this class to AlgorithmMenu;
 @SuppressWarnings("serial")
-public class AlgoWindow extends JFrame{
-	private Algorithm actual;
+public class AddOnWindow extends JFrame{
+	private AddOn actual;
 	private Control control;
 	private JPanel content = new JPanel();
-	AlgoWindow(JFrame parentFrame, Control control){
+	AddOnWindow(JFrame parentFrame, Control control){
 		this.control = control;
-		this.setTitle("Algorithm");
+		this.setTitle("Add-Ons");
 		this.setVisible(true);
 		this.setContentPane(content);
 		this.setIconImage(Util.loadImage("/Images/Holeg.png", 30, 30));
@@ -75,11 +74,11 @@ public class AlgoWindow extends JFrame{
 		textPane.setParagraphAttributes(attribs, true);
 		textPane.setText("No algorithm is loaded."
 				+"\n OPTION[1]:"
-				+"\n  Select '.java'-file via the file browser. (File\u2192Open .jave-File..)"
+				+"\n  Select '.java'-file via the file browser. (File\u2192Open .jave-File..)"
 				+"\n"
 				+"\n OPTION[2]:"
-				+"\n• First select the folder where the algorithm '.java'-file is located. (File\u2192Open Folder..)"
-				+"\n Second load the algorithm. (File\u2192'YourAlgo')");
+				+"\n First select the folder where the addon '.java'-file is located. (File\u2192Open Folder..)"
+				+"\n Second load the algorithm. (File\u2192'YourAlgo')");
 		textPane.setFont(new Font("Serif", Font.PLAIN, 16));
 		
 		
@@ -160,12 +159,12 @@ public class AlgoWindow extends JFrame{
 		URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { folder.toURI().toURL() });
 		Class<?> cls = Class.forName(packageName.isEmpty()?name:packageName + "." +name, true, classLoader);
 		Object object = cls.newInstance();
-		if(!(object instanceof Algorithm)) {
+		if(!(object instanceof AddOn)) {
 			generateErrorDialog("Class does not implement CpsAlgorithm!");
 		}else {
-			actual = (Algorithm)object;
+			actual = (AddOn)object;
 			actual.setController(control);
-			this.setContentPane(actual.getAlgorithmPanel());
+			this.setContentPane(actual.getPanel());
 			this.pack();
 		}
 		} catch (MalformedURLException e) {

+ 1 - 1
src/ui/view/GUI.java

@@ -2513,7 +2513,7 @@ public class GUI implements CategoryListener {
 		//Algo
 		JMenuItem openMenu =  new JMenuItem("Open Algorithm Panel", new ImageIcon(Util.loadImage("/Button_Images/iconAlgo.png").getScaledInstance(20, 20, java.awt.Image.SCALE_SMOOTH)));
 		openMenu.addActionListener(actionEvent -> {
-			new AlgoWindow(holegJFrame, controller);
+			new AddOnWindow(holegJFrame, controller);
 		});
 		openMenu.setAccelerator(KeyStroke.getKeyStroke('N', Toolkit.getDefaultToolkit ().getMenuShortcutKeyMask()));
 		menuWindow.add(openMenu);