瀏覽代碼

PlottingMadeEasy

Tom 5 年之前
父節點
當前提交
d948f9b8ca

+ 0 - 640
src/api/AlgorithmFramework.java

@@ -1,640 +0,0 @@
-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.math.RoundingMode;
-import java.text.NumberFormat;
-import java.util.ArrayList;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Locale;
-import java.util.function.Consumer;
-import java.util.function.DoubleConsumer;
-import java.util.function.IntConsumer;
-import java.util.stream.Collectors;
-
-import javax.swing.BorderFactory;
-import javax.swing.Box;
-import javax.swing.BoxLayout;
-import javax.swing.ImageIcon;
-import javax.swing.JButton;
-import javax.swing.JCheckBox;
-import javax.swing.JFileChooser;
-import javax.swing.JFormattedTextField;
-import javax.swing.JLabel;
-import javax.swing.JOptionPane;
-import javax.swing.JPanel;
-import javax.swing.JProgressBar;
-import javax.swing.JScrollPane;
-import javax.swing.JSplitPane;
-import javax.swing.text.NumberFormatter;
-
-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();
-	private JPanel borderPanel = new JPanel();
-	
-	
-	//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;
-	private RunPrinter printer = new RunPrinter("plott.txt");
-
-
-
-	
-	
-	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));
-	}
-	
-	
-	
-	
-	
-	
-	private 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));
-		borderPanel.setLayout(new BoxLayout(borderPanel, BoxLayout.PAGE_AXIS));
-		addIntParameter("Rounds", rounds, intInput -> rounds = intInput, 1);
-		JScrollPane scrollPane = new JScrollPane(borderPanel);
-		scrollPane.setBounds(10, 0, 450, 292);
-		scrollPane.setBorder(BorderFactory.createEmptyBorder());
-		parameterPanel.add(scrollPane);	
-		
-		
-		
-		JButton selectGroupNodeButton = new JButton("Select GroupNode");
-		selectGroupNodeButton.setBounds(500, 0, 185, 30);
-		selectGroupNodeButton.addActionListener(actionEvent -> selectGroupNode());
-		parameterPanel.add(selectGroupNodeButton);	
-		JProgressBar progressBar = runProgressbar.getJProgressBar();
-		progressBar.setBounds(500, 35, 185, 20);
-		progressBar.setStringPainted(true);
-		parameterPanel.add(progressBar);
-		
-		return parameterPanel;
-	}
-	private 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 plottButton =  new JButton("Plott");
-		plottButton.addActionListener(actionEvent -> plott());
-		buttonPanel.add(plottButton);
-		
-		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;
-	}
-	
-	
-	
-	//ParameterImports
-	
-	//int
-	protected void addIntParameter(String parameterName, int parameterValue, IntConsumer setter) {
-		this.addIntParameter(parameterName, parameterValue, setter, Integer.MIN_VALUE, Integer.MAX_VALUE);
-	}
-	
-	protected void addIntParameter(String parameterName, int parameterValue, IntConsumer setter, int parameterMinValue) {
-		this.addIntParameter(parameterName, parameterValue, setter, parameterMinValue, Integer.MAX_VALUE);
-	}
-	
-	protected void addIntParameter(String parameterName, int parameterValue, IntConsumer setter, int parameterMinValue, int parameterMaxValue) {
-		JPanel singleParameterPanel = new JPanel();
-		singleParameterPanel.setLayout(new BoxLayout(singleParameterPanel, BoxLayout.LINE_AXIS));
-		singleParameterPanel.setAlignmentX(0.0f);
-		singleParameterPanel.add(new JLabel(parameterName + ": "));
-		singleParameterPanel.add(Box.createHorizontalGlue());
-		NumberFormat format = NumberFormat.getIntegerInstance();
-		format.setGroupingUsed(false);
-		format.setParseIntegerOnly(true);
-		NumberFormatter integerFormatter = new NumberFormatter(format);
-		integerFormatter.setMinimum(parameterMinValue);
-		integerFormatter.setMaximum(parameterMaxValue);
-		integerFormatter.setCommitsOnValidEdit(true);
-		JFormattedTextField singleParameterTextField = new  JFormattedTextField(integerFormatter);
-		singleParameterTextField.setValue(parameterValue);
-		String minValue = (parameterMinValue == Integer.MIN_VALUE)?"Integer.MIN_VALUE":String.valueOf(parameterMinValue);
-		String maxValue = (parameterMaxValue == Integer.MAX_VALUE)?"Integer.MAX_VALUE":String.valueOf(parameterMaxValue);
-		singleParameterTextField.setToolTipText("Only integer \u2208 [" + minValue + "," + maxValue + "]");
-		singleParameterTextField.addPropertyChangeListener(actionEvent -> setter.accept(Integer.parseInt(singleParameterTextField.getValue().toString())));
-		singleParameterTextField.setMaximumSize(new Dimension(200, 30));
-		singleParameterTextField.setPreferredSize(new Dimension(200, 30));
-		singleParameterPanel.add(singleParameterTextField);
-		borderPanel.add(singleParameterPanel);
-	}
-	
-	
-	//double
-	protected void addDoubleParameter(String parameterName, double parameterValue, DoubleConsumer setter) {
-		this.addDoubleParameter(parameterName, parameterValue, setter, Double.MIN_VALUE, Double.MAX_VALUE);
-	}
-	
-	
-	protected void addDoubleParameter(String parameterName, double parameterValue, DoubleConsumer setter, double parameterMinValue) {
-		this.addDoubleParameter(parameterName, parameterValue, setter, parameterMinValue, Double.MAX_VALUE);
-	}
-	
-	
-	protected void addDoubleParameter(String parameterName, double parameterValue, DoubleConsumer setter, double parameterMinValue, double parameterMaxValue) {
-		JPanel singleParameterPanel = new JPanel();
-		singleParameterPanel.setLayout(new BoxLayout(singleParameterPanel, BoxLayout.LINE_AXIS));
-		singleParameterPanel.setAlignmentX(0.0f);
-		singleParameterPanel.add(new JLabel(parameterName + ": "));
-		singleParameterPanel.add(Box.createHorizontalGlue());
-		NumberFormat doubleFormat = NumberFormat.getNumberInstance(Locale.US);
-		doubleFormat.setMinimumFractionDigits(1);
-		doubleFormat.setMaximumFractionDigits(10);
-		doubleFormat.setRoundingMode(RoundingMode.HALF_UP);
-		NumberFormatter doubleFormatter = new NumberFormatter(doubleFormat);
-		doubleFormatter.setMinimum(parameterMinValue);
-		doubleFormatter.setMaximum(parameterMaxValue);
-		JFormattedTextField singleParameterTextField = new  JFormattedTextField(doubleFormatter);
-		singleParameterTextField.setValue(parameterValue);
-		String minValue = (parameterMinValue == Double.MIN_VALUE)?"Double.MIN_VALUE":String.valueOf(parameterMinValue);
-		String maxValue = (parameterMaxValue == Double.MAX_VALUE)?"Double.MAX_VALUE":String.valueOf(parameterMaxValue);
-		singleParameterTextField.setToolTipText("Only double \u2208 [" + minValue + "," + maxValue + "]");
-		singleParameterTextField.addPropertyChangeListener(actionEvent -> setter.accept(Double.parseDouble(singleParameterTextField.getValue().toString())));
-		singleParameterTextField.setMaximumSize(new Dimension(200, 30));
-		singleParameterTextField.setPreferredSize(new Dimension(200, 30));
-		singleParameterPanel.add(singleParameterTextField);
-		borderPanel.add(singleParameterPanel);
-	}
-	//boolean
-	protected void addBooleanParameter(String parameterName, boolean parameterValue, Consumer<Boolean> setter){
-		JPanel singleParameterPanel = new JPanel();
-		singleParameterPanel.setLayout(new BoxLayout(singleParameterPanel, BoxLayout.LINE_AXIS));
-		singleParameterPanel.setAlignmentX(0.0f);
-		singleParameterPanel.add(new JLabel(parameterName + ": "));
-		singleParameterPanel.add(Box.createHorizontalGlue());
-		JCheckBox useGroupNodeCheckBox = new JCheckBox();
-		useGroupNodeCheckBox.setSelected(parameterValue);
-		useGroupNodeCheckBox.addActionListener(actionEvent -> setter.accept(useGroupNodeCheckBox.isSelected()));
-		singleParameterPanel.add(useGroupNodeCheckBox);
-		borderPanel.add(singleParameterPanel);
-	}
-	
-
-	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 plott() {
-		if(db!=null) {
-			console.println("Plott..");
-			printer.print("");
-		}else {
-			console.println("No run inistialized.");
-		}
-	}
-	
-	
-	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")));
-			setFilename(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;
-		}
-	}
-}

+ 12 - 6
src/api/AlgorithmFrameworkFlex.java

@@ -86,14 +86,16 @@ public abstract class AlgorithmFrameworkFlex implements AddOn{
 	protected boolean cancel = false;
 
 	//holeg interaction
-	private Control  control;
+	protected Control  control;
 
 	
 	//printing
 	protected RunDataBase db;
-	private RunPrinter printer = new RunPrinter("plott.txt");
+	private RunPrinter printer = new RunPrinter(plottFileName(), true);
 
 
+	
+	
 
 	
 	
@@ -295,7 +297,7 @@ public abstract class AlgorithmFrameworkFlex implements AddOn{
 	private void plott() {
 		if(db!=null) {
 			console.println("Plott..");
-			printer.print("");
+			printer.print(algoInformationToPrint());
 		}else {
 			console.println("No run inistialized.");
 		}
@@ -496,7 +498,7 @@ public abstract class AlgorithmFrameworkFlex implements AddOn{
 				initialState.add(false);
 			}
 		}
-		console.println(access.stream().map(Object::toString).collect(Collectors.joining(", ")));
+		//console.println(access.stream().map(Object::toString).collect(Collectors.joining(", ")));
 		return initialState;
 	}
 	
@@ -567,8 +569,8 @@ public abstract class AlgorithmFrameworkFlex implements AddOn{
 	
 	protected abstract int getProgressBarMaxCount();
 	
-	
-	
+	protected abstract String algoInformationToPrint();
+	protected abstract String plottFileName();
 	
 	public class RunDataBase{
 		List<List<Double>> allRuns = new ArrayList<List<Double>>();
@@ -619,6 +621,10 @@ public abstract class AlgorithmFrameworkFlex implements AddOn{
 			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())));
+			else
+				console.println("Something is wrong");
+			out.newLine();
+			out.newLine();
 		}
 	}
 		

+ 0 - 858
src/exampleAlgorithms/AcoAlgorithm.java

@@ -1,858 +0,0 @@
-package exampleAlgorithms;
-
-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.math.RoundingMode;
-import java.text.NumberFormat;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.ListIterator;
-import java.util.Locale;
-import java.util.stream.Collectors;
-
-import javax.swing.BorderFactory;
-import javax.swing.ImageIcon;
-import javax.swing.JButton;
-import javax.swing.JCheckBox;
-import javax.swing.JFileChooser;
-import javax.swing.JFormattedTextField;
-import javax.swing.JFrame;
-import javax.swing.JLabel;
-import javax.swing.JOptionPane;
-import javax.swing.JPanel;
-import javax.swing.JProgressBar;
-import javax.swing.JScrollPane;
-import javax.swing.JSplitPane;
-import javax.swing.JTextArea;
-import javax.swing.text.NumberFormatter;
-
-import api.AddOn;
-import classes.AbstractCpsObject;
-import classes.CpsUpperNode;
-import classes.HolonElement;
-import classes.HolonObject;
-import classes.HolonSwitch;
-import exampleAlgorithms.GaAlgorithm.RunDataBase;
-import ui.controller.Control;
-import ui.model.DecoratedGroupNode;
-import ui.model.DecoratedState;
-import ui.model.Model;
-import ui.view.Console;
-import ui.model.DecoratedHolonObject.HolonObjectState;
-
-public class AcoAlgorithm implements AddOn {
-
-		//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 int rounds = 3;
-		
-		private int resetCount = 0;
-		private boolean moreInformation = false;
-		
-		
-		
-		
-		//Settings For GroupNode using and cancel
-		private boolean useGroupNode = false;
-		private DecoratedGroupNode dGroupNode = null;
-		private boolean cancel = false;
-		
-		
-
-		//Parameter defined by Algo
-		private HashMap<Integer, AccessWrapper> access;
-		LinkedList<List<Boolean>> resetChain = new LinkedList<List<Boolean>>();
-		private List<HolonSwitch> switchList;
-		private List<HolonObject> objectList;
-		private boolean append = false;
-		//Gui Part:
-		private Control  control;
-		private Console console = new Console();
-		private JPanel content = new JPanel();
-		//ProgressBar
-		private JProgressBar progressBar = new JProgressBar();
-		private int progressBarCount = 0;
-		private long startTime;
-		private Thread runThread = new Thread();
-		private RunDataBase db;
-		//Parameter for Plotting (Default Directory in Constructor)
-		private JFileChooser fileChooser = new JFileChooser();
-
-
-
-		
-		
-		
-		
-		
-		
-		
-		public static void main(String[] args)
-		{
-		      JFrame newFrame = new JFrame("exampleWindow");
-		      AcoAlgorithm instance = new AcoAlgorithm();
-		      newFrame.setContentPane(instance.getPanel());
-		      newFrame.pack();
-		      newFrame.setVisible(true);
-		      newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
-		}
-		public AcoAlgorithm() {
-			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));	
-			fileChooser.setCurrentDirectory(new File(System.getProperty("user.dir")));
-		    fileChooser.setSelectedFile(new File("plott.txt"));
-		}
-		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));
-			
-			
-				
-			JLabel maxGenerationsLabel = new JLabel("Max. Generations:");
-			maxGenerationsLabel.setBounds(20, 60, 150, 20);
-			parameterPanel.add(maxGenerationsLabel);
-			
-			JLabel populationLabel = new JLabel("Population Size:");
-			populationLabel.setBounds(20, 85, 150, 20);
-			parameterPanel.add(populationLabel);
-			
-			JLabel roundLabel = new JLabel("Rounds:");
-			roundLabel.setBounds(20, 110, 150, 20);
-			parameterPanel.add(roundLabel);
-			
-			JLabel vaporizationLabel = new JLabel("Vaporization:");
-			vaporizationLabel.setBounds(20, 135, 150, 20);
-			parameterPanel.add(vaporizationLabel);
-			
-		
-			JLabel resetLabel = new JLabel("Reset Trigger:");
-			resetLabel.setBounds(20, 160, 150, 20);
-			parameterPanel.add(resetLabel);
-			
-			
-			JLabel progressLabel = new JLabel("Progress:");
-			progressLabel.setBounds(350, 135, 170, 20);
-			parameterPanel.add(progressLabel);	
-			
-			progressBar.setBounds(350, 155, 185, 20);
-			progressBar.setStringPainted(true);
-			parameterPanel.add(progressBar);
-			
-			JCheckBox informationCheckBox = new JCheckBox("More Information");
-			informationCheckBox.setSelected(this.moreInformation);
-			informationCheckBox.setBounds(350, 60, 220, 20);
-			informationCheckBox.addActionListener(actionEvent -> {
-				moreInformation = informationCheckBox.isSelected();
-			});
-			parameterPanel.add(informationCheckBox);
-			
-			JPanel borderPanel = new JPanel(null);
-			borderPanel.setBounds(350, 85, 185, 50);
-			borderPanel.setBorder(BorderFactory.createTitledBorder(""));
-			parameterPanel.add(borderPanel);	
-			
-			JLabel showGroupNodeLabel = new JLabel("Use Group Node:");
-			showGroupNodeLabel.setBounds(10, 1, 170, 20);
-			borderPanel.add(showGroupNodeLabel);	
-			
-			JButton selectGroupNodeButton = new JButton("Select GroupNode");
-			selectGroupNodeButton.setEnabled(false);
-			selectGroupNodeButton.setBounds(10, 25, 165, 20);
-			selectGroupNodeButton.addActionListener(actionEvent -> selectGroupNode());
-			borderPanel.add(selectGroupNodeButton);	
-			
-			JCheckBox useGroupNodeCheckBox = new JCheckBox();
-			useGroupNodeCheckBox.setSelected(false);
-			useGroupNodeCheckBox.setBounds(155, 1, 25, 20);
-			useGroupNodeCheckBox.addActionListener(actionEvent -> {
-				useGroupNode = useGroupNodeCheckBox.isSelected();
-				selectGroupNodeButton.setEnabled(useGroupNode);
-			});
-			borderPanel.add(useGroupNodeCheckBox);
-			
-	
-			//Integer formatter
-			NumberFormat format = NumberFormat.getIntegerInstance();
-			format.setGroupingUsed(false);
-			format.setParseIntegerOnly(true);
-			NumberFormatter integerFormatter = new NumberFormatter(format);
-			integerFormatter.setMinimum(1);
-			integerFormatter.setCommitsOnValidEdit(true);
-			
-			
-			JFormattedTextField maxGenerationsTextField = new  JFormattedTextField(integerFormatter);
-			maxGenerationsTextField.setValue(this.maxGenerations);
-			maxGenerationsTextField.setToolTipText("Only positive Integer.");
-			maxGenerationsTextField.addPropertyChangeListener(actionEvent -> this.maxGenerations = Integer.parseInt(maxGenerationsTextField.getValue().toString()));
-			maxGenerationsTextField.setBounds(160, 60, 50, 20);
-			parameterPanel.add(maxGenerationsTextField);
-			
-			JFormattedTextField popSizeTextField = new JFormattedTextField(integerFormatter);
-			popSizeTextField.setValue(this.popsize);
-			popSizeTextField.setToolTipText("Only positive Integer.");
-			popSizeTextField.addPropertyChangeListener(propertyChange -> this.popsize = Integer.parseInt(popSizeTextField.getValue().toString()));
-			popSizeTextField.setBounds(160, 85, 50, 20);
-			parameterPanel.add(popSizeTextField);
-			
-			
-			JFormattedTextField roundsTextField = new JFormattedTextField(integerFormatter);
-			roundsTextField.setValue(this.rounds);
-			roundsTextField.setToolTipText("Only positive Integer.");
-			roundsTextField.addPropertyChangeListener(propertyChange -> this.rounds = Integer.parseInt(roundsTextField.getValue().toString()));
-			roundsTextField.setBounds(160, 110, 50, 20);
-			parameterPanel.add(roundsTextField);
-			
-			
-			//Double Format:
-			NumberFormat doubleFormat = NumberFormat.getNumberInstance(Locale.US);
-			doubleFormat.setMinimumFractionDigits(1);
-			doubleFormat.setMaximumFractionDigits(3);
-			doubleFormat.setRoundingMode(RoundingMode.HALF_UP);
-
-			//Limit Formatter:
-			NumberFormatter limitFormatter = new NumberFormatter(doubleFormat);
-			limitFormatter.setMinimum(0.0);
-			limitFormatter.setMaximum(1.0);
-			
-			JFormattedTextField vaporizationField = new JFormattedTextField(limitFormatter);
-			vaporizationField.setValue(this.p);
-			vaporizationField.setToolTipText("Only Double in range [0.0, 1.0] with DecimalSeperator Point('.').");
-			vaporizationField.addPropertyChangeListener(propertyChange -> p = Double.parseDouble(vaporizationField.getValue().toString()));
-			vaporizationField.setBounds(160, 135, 50, 20);
-			parameterPanel.add(vaporizationField);
-			
-			
-			
-			JFormattedTextField resetFactorField = new JFormattedTextField(limitFormatter);
-			resetFactorField.setValue(this.convergenceFactorReset);
-			resetFactorField.setToolTipText("Only Double in range [0.0, 1.0] with DecimalSeperator Point('.').");
-			resetFactorField.addPropertyChangeListener(propertyChange -> this.convergenceFactorReset = Double.parseDouble(resetFactorField.getValue().toString()));
-			resetFactorField.setBounds(160, 160, 50, 20);
-			parameterPanel.add(resetFactorField);
-			
-			
-			
-			return parameterPanel;
-		}
-		public JPanel createButtonPanel() {
-			JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
-			JButton fitnessButton =  new JButton("Fitness");
-			fitnessButton.setToolTipText("Fitness for the current state.");
-			fitnessButton.addActionListener(actionEvent -> fitness());
-			buttonPanel.add(fitnessButton);
-			JButton plottButton =  new JButton("Plott");
-			plottButton.addActionListener(actionEvent -> plott());
-			buttonPanel.add(plottButton);
-			JButton resetButton =  new JButton("ResetAll");
-			resetButton.setToolTipText("Resets the State to before the Algorithm has runed.");
-			resetButton.addActionListener(actionEvent -> resetAll());
-			buttonPanel.add(resetButton);
-			JButton cancelButton =  new JButton("Cancel Run");
-			cancelButton.addActionListener(actionEvent -> cancel());
-			buttonPanel.add(cancelButton);
-			JButton undoButton =  new JButton("Undo");
-			undoButton.setToolTipText("One Algo Step Back.");
-			undoButton.addActionListener(actionEvent -> resetLast());
-			buttonPanel.add(undoButton);
-			JButton runButton =  new JButton("Run");
-			runButton.addActionListener(actionEvent -> {
-				Runnable task = () -> run();
-				runThread = new Thread(task);
-				runThread.start();
-			});
-			buttonPanel.add(runButton);
-			return buttonPanel;
-		}
-		private void cancel() {
-			if(runThread.isAlive()) {
-				println("");
-				println("Cancel run.");
-				cancel = true;
-				progressBar.setValue(0);
-			} else {
-				println("Nothing to cancel.");
-			}
-		}
-		
-		private void fitness() {
-			if(runThread.isAlive()) {
-				println("Run have to be cancelled First.");
-				return;
-			}
-			double currentFitness = evaluatePosition(extractPositionAndAccess(), false);
-			resetChain.removeLast();
-			console.println("Actual Fitnessvalue: " + currentFitness);
-		}
-		
-		private void run() {
-			cancel = false;
-			disableGuiInput(true);
-			executeAlgoWithParameter();
-			updateVisual();
-			disableGuiInput(false);
-		}
-		
-		private void resetLast() {
-			if(runThread.isAlive()) {
-				println("Run have to be cancelled First.");
-				return;
-			}
-			if(!resetChain.isEmpty()) {
-				println("Resetting..");
-				resetState();
-				resetChain.removeLast();
-				control.resetSimulation();
-				updateVisual();
-			}else {
-				println("No run inistialized.");
-			}
-		}
-		
-		private void resetAll() {
-			if(runThread.isAlive()) {
-				println("Run have to be cancelled First.");
-				return;
-			}
-			if(!resetChain.isEmpty()) {
-				println("Resetting..");
-				setState(resetChain.getFirst());
-				resetChain.clear();
-				control.resetSimulation();
-				control.setCurIteration(0);
-				updateVisual();
-			}else {
-				println("No run inistialized.");
-			}
-		}
-		
-		private void plott() {
-			if(db!=null) {
-				console.println("Plott..");
-				db.initFileStream();
-			}else {
-				console.println("No run inistialized.");
-			}
-		}
-
-		
-		private void disableGuiInput(boolean bool) {
-			control.guiDisable(bool);
-		}
-		
-		
-
-		
-		
-		@Override
-		public JPanel getPanel() {
-			return content;
-		}
-		@Override
-		public void setController(Control control) {
-			this.control = control;
-			
-		}
-		private void println(String message) {
-			console.println(message);
-		}
-		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) {
-				println("Selected: " + selected);
-				dGroupNode = selected.object;
-			}
-		}
-		private void progressBarStep(){
-			progressBar.setValue(++progressBarCount);
-		}
-		private void calculateProgressBarParameter() {
-			int max = this.maxGenerations * this.popsize * this.rounds;
-			progressBarCount = 0;
-			progressBar.setValue(0);
-			progressBar.setMaximum(max);
-		}
-		
-		private void startTimer(){
-			startTime = System.currentTimeMillis();
-		}
-		private void printElapsedTime(){
-			long elapsedMilliSeconds = System.currentTimeMillis() - startTime;
-			println("Execution Time of Algo in Milliseconds:" + elapsedMilliSeconds);
-		}
-		
-		
-		
-		
-		private void executeAlgoWithParameter(){
-			
-			
-			
-			int actualIteration = control.getModel().getCurIteration();
-			println("TimeStep:" + actualIteration);
-			calculateProgressBarParameter();
-			println("Algo Parameter: p="+ p + " cfreset=" + convergenceFactorReset);
-			resetCount = 0;
-			startTimer();
-			Individual runBest = new Individual();
-			runBest.fitness = Double.MAX_VALUE;
-			db = new RunDataBase();
-			for(int r = 0; r < rounds; r++)
-			{		
-				List<Double> runList = db.insertNewRun();
-				Individual  roundBest = executeAcoAlgo(runList);
-				if(cancel)return;
-				resetState();
-				if(roundBest.fitness < runBest.fitness) runBest = roundBest;
-			}
-			printElapsedTime();
-			setState(runBest.position);
-			updateVisual();
-			if(moreInformation)println("ResetsCount:"+resetCount);
-			println("AlgoResult:" + runBest.fitness);
-			
-			
-		}
-		
-		
-		
-		
-		//Algo Part:
-		/** 	
-		 * 	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 
-		 */
-		private Individual executeAcoAlgo(List<Double> runList) {
-			Individual best = new Individual();
-			best.position = extractPositionAndAccess();
-			if(moreInformation)println("Bit-Array_length: " + best.position.size());
-			best.fitness = evaluatePosition(best.position, false);
-			runList.add(best.fitness);
-			console.print("Start with: " + best.fitness);
-			if(moreInformation)println("");
-			int problemSize = best.position.size();
-			if(problemSize == 0) return best;
-			List<Double> pheromones = initPheromones(problemSize);
-			List<Individual> population = new ArrayList<Individual>();
-			if(moreInformation)println("Size To Test:" + population.size());
-			for(int generation = 0; generation< maxGenerations; generation++) {
-				population.clear();
-				population = constructSolutionsBiasedBy(pheromones);
-				if(moreInformation)println("Generation" + generation + " start with Fitness: " + best.fitness);
-				for(Individual i : population) {
-					i.fitness = evaluatePosition(i.position, true);
-					if(moreInformation)println("Fitness" + i.fitness);
-					if(i.fitness < best.fitness) best = i;	
-				}
-				runList.add(best.fitness);
-				if(moreInformation)println("________________");
-				vaporizeIntensifiePheromons(pheromones, best.position, problemSize);
-				double cf = calculateConvergenceFactor(pheromones, problemSize);
-				if(moreInformation)println("ConvergenceFactor = " + cf);
-				if(cf > this.convergenceFactorReset) {
-					pheromones = initPheromones(problemSize);
-					resetCount++;
-				}
-				if(cancel)return null;
-			}
-			
-			
-			println("   End With:" + best.fitness);
-			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;
-		}
-		
-		
-		
-		/**
-		 * 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
-		 */
-		private List<Boolean> extractPositionAndAccess() {
-			Model model = control.getModel();
-			switchList = new ArrayList<HolonSwitch>();
-			objectList = new ArrayList<HolonObject>();
-			List<Boolean> initialState = new ArrayList<Boolean>();
-			access= new HashMap<Integer, AccessWrapper>();
-			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.put(positionToInit.size() - 1 , new AccessWrapper(hE));
-					}
-					objectList.add((HolonObject) aCps);
-				}
-				else if (aCps instanceof HolonSwitch) {
-					HolonSwitch sw = (HolonSwitch) aCps;
-					positionToInit.add(sw.getState(timeStep));
-					switchList.add(sw);
-					access.put(positionToInit.size() - 1 , new AccessWrapper(sw));
-				}
-				else if(aCps instanceof CpsUpperNode) {
-					rollOutNodes(((CpsUpperNode)aCps).getNodes(), positionToInit ,timeStep );
-				}
-			}
-		}
-		
-		
-		
-		private double evaluatePosition(List<Boolean> position, boolean doIncreaseCounter) {
-			setState(position);
-			if(doIncreaseCounter)progressBarStep();
-			control.calculateStateOnlyForCurrentTimeStep();
-			DecoratedState actualstate = control.getSimManager().getActualDecorState();		
-			return PSOAlgorithm.getFitnessValueForState(actualstate);
-		}
-		
-		
-		
-		/**
-		 * 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) {
-			for(int i = 0;i<position.size();i++) {
-				access.get(i).setState(position.get(i));
-			}
-		}
-		
-		private class Individual {
-			public double fitness;
-			public  List<Boolean> position;
-			
-			Individual(){};
-			/**
-			 *  Copy Constructor
-			 */
-			Individual(Individual c){
-				position = c.position.stream().collect(Collectors.toList());
-				fitness = c.fitness;
-			}
-		}
-		
-		
-		
-		
-		
-		
-		
-		/**
-		 * 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;
-			}
-		}
-		/**
-		 * A Database for all Global Best(G<sub>Best</sub>) Values in a execution of a the Algo. For Easy Printing.
-		 */
-		public class RunDataBase {
-			List<List<Double>> allRuns = new ArrayList<List<Double>>();
-			
-			
-			/**
-			 * Initialize The Stream before you can write to a File.
-			 */
-			public void initFileStream() {
-				File file = fileChooser.getSelectedFile();
-				try {
-					file.createNewFile();
-					BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
-						    new FileOutputStream(file, append), "UTF-8"));
-					printToStream(out);
-					out.close();
-				} catch (IOException e) {
-					console.println(e.getMessage());
-				}
-			}
-			
-			public void printToStream(BufferedWriter out) throws IOException {
-				try {
-					out.write(maxGenerations + 1 + "," + allRuns.size() + "," + popsize);
-					out.newLine();
-
-				}
-				catch(IOException e) {
-					console.println(e.getMessage());
-				}
-				allRuns.forEach(run -> {
-					try {
-						out.write( run.stream().map(Object::toString).collect(Collectors.joining(", ")));
-						out.newLine();
-					} catch (IOException e) {
-						console.println(e.getMessage());
-					}
-				} );
-			}
-			
-			public List<Double> insertNewRun(){
-				List<Double> newRun = new ArrayList<Double>();
-				allRuns.add(newRun);
-				return newRun;
-			}
-		}
-		
-		private class RunResult {
-			public int activatedFlex = 0;
-			public int deactivatedElements = 0;
-			public float totalCost = 0;
-			public LinkedList<TimeStepStateResult> timeStepList = new LinkedList<TimeStepStateResult>();
-			
-			
-			public TimeStepStateResult addTimeStepStateResult(){
-				TimeStepStateResult aResult = new TimeStepStateResult();
-				timeStepList.add(aResult);
-				return aResult;
-			}
-			
-			
-			public class TimeStepStateResult{
-				public int amountOfProducer = 0;
-				public int amountOfConsumer = 0;
-				public int amountOfPassiv = 0;
-				public int amountOfConsumerOverSupplied = 0;
-				public int amountOfConsumerSupplied = 0;
-				public int amountOfConsumerPartiallySupplied = 0;
-				public int amountOfConsumerUnSupplied= 0;
-				
-				public float getProportionWithState(HolonObjectState state) {
-					float amountOfObjects = amountOfProducer + amountOfConsumer + amountOfPassiv;
-					switch(state) {
-					case NOT_SUPPLIED:
-						return (float) amountOfConsumerUnSupplied / amountOfObjects;
-					case NO_ENERGY:
-						return (float) amountOfPassiv / amountOfObjects;
-					case OVER_SUPPLIED:
-						return (float) amountOfConsumerOverSupplied / amountOfObjects;
-					case PARTIALLY_SUPPLIED:
-						return (float) amountOfConsumerPartiallySupplied / amountOfObjects;
-					case PRODUCER:
-						return (float) amountOfProducer / amountOfObjects;
-					case SUPPLIED:
-						return (float) amountOfConsumerSupplied / amountOfObjects;
-					default:
-						return 0.f;
-					}
-				}
-			}
-			public float getAvergaeProportionWithState(HolonObjectState state) {
-				return timeStepList.stream().map(step -> step.getProportionWithState(state)).reduce((a,b) -> (a + b)).orElse(0.f) / (float) 100;
-			}
-		}
-		
-
-		/**
-		* To create Random and maybe switch the random generation in the future.
-		*/
-		private 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();
-			}
-		}
-
-}

+ 22 - 1
src/exampleAlgorithms/AcoAlgorithm2.java

@@ -7,7 +7,6 @@ import java.util.ListIterator;
 import javax.swing.JFrame;
 import javax.swing.JPanel;
 
-import api.AlgorithmFramework;
 import api.AlgorithmFrameworkFlex;
 import ui.model.DecoratedState;
 
@@ -192,5 +191,27 @@ public class AcoAlgorithm2 extends AlgorithmFrameworkFlex{
 		return result;
 	}
 
+
+
+	@Override
+	protected String algoInformationToPrint() {
+//		private int popsize = 20;
+//		private int maxGenerations = 200;
+//		private double p = 0.3;
+//		private double convergenceFactorReset = 0.99;
+		return "AcoAlgo"+ " Rounds:" + rounds 
+				+ " maxGenerations:" + maxGenerations 
+				+ " popsize:" +  popsize
+				+ " vaporization:" +  p
+				+ " convergenceFactorReset:" +  convergenceFactorReset;
+	}
+
+
+
+	@Override
+	protected String plottFileName() {
+		return "plottAcoAlgo.txt";
+	}
+
 	
 }

+ 0 - 1050
src/exampleAlgorithms/GaAlgorithm.java

@@ -1,1050 +0,0 @@
-package exampleAlgorithms;
-
-import java.awt.BorderLayout;
-import java.awt.Component;
-import java.awt.Dimension;
-import java.awt.FlowLayout;
-import java.awt.event.ActionListener;
-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.math.RoundingMode;
-import java.text.NumberFormat;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.ListIterator;
-import java.util.Locale;
-import java.util.Set;
-import java.util.TreeSet;
-import java.util.stream.Collectors;
-
-import javax.swing.BorderFactory;
-import javax.swing.ButtonGroup;
-import javax.swing.ImageIcon;
-import javax.swing.JButton;
-import javax.swing.JCheckBox;
-import javax.swing.JFileChooser;
-import javax.swing.JFormattedTextField;
-import javax.swing.JFrame;
-import javax.swing.JLabel;
-import javax.swing.JOptionPane;
-import javax.swing.JPanel;
-import javax.swing.JProgressBar;
-import javax.swing.JRadioButton;
-import javax.swing.JScrollPane;
-import javax.swing.JSplitPane;
-import javax.swing.JTextArea;
-import javax.swing.text.NumberFormatter;
-
-import api.AddOn;
-import classes.AbstractCpsObject;
-import classes.CpsUpperNode;
-import classes.HolonElement;
-import classes.HolonObject;
-import classes.HolonSwitch;
-import exampleAlgorithms.PSOAlgorithm.RunDataBase;
-import ui.controller.Control;
-import ui.model.DecoratedGroupNode;
-import ui.model.DecoratedState;
-import ui.model.Model;
-import ui.view.Console;
-import ui.model.DecoratedHolonObject.HolonObjectState;
-
-public class GaAlgorithm implements AddOn {
-
-		//Parameter for Algo with default Values:
-		/**
-		 * Should be even.
-		 */
-		private int popsize = 20;
-		private int maxGenerations = 100;
-		private double tournamentSize = 2.0;
-		private double fixedSwapProbability = 0.02;
-		private boolean useFixedSpawProbability = false;
-		private double fixedMutateProbability = 0.02;
-		private boolean useFixedMutateProbability = false;
-		private boolean useIntervalMutation = true;
-		private double mutateProbabilityInterval = 0.01;
-		private double maxMutationPercent = 0.01;
-		private int rounds = 2;
-		private boolean moreInformation = false;
-		
-		
-		
-		//Settings For GroupNode using and cancel
-		private boolean useGroupNode = false;
-		private DecoratedGroupNode dGroupNode = null;
-		private boolean cancel = false;
-		private boolean append = false;
-
-		//Parameter defined by Algo
-		private HashMap<Integer, AccessWrapper> access;
-		LinkedList<List<Boolean>> resetChain = new LinkedList<List<Boolean>>();
-
-		private List<HolonSwitch> switchList;
-		private List<HolonObject> objectList;
-		
-		//Gui Part:
-		private Control  control;
-		private Console console = new Console();
-		private JPanel content = new JPanel();
-		//ProgressBar
-		private JProgressBar progressBar = new JProgressBar();
-		private int progressBarCount = 0;
-		private long startTime;
-		private Thread runThread = new Thread();
-		private RunDataBase db;
-
-
-
-		//Parameter for Plotting (Default Directory in Constructor)
-		private JFileChooser fileChooser = new JFileChooser();
-
-		
-		
-		
-		
-		
-		
-		
-		public static void main(String[] args)
-		{
-		      JFrame newFrame = new JFrame("exampleWindow");
-		      GaAlgorithm instance = new GaAlgorithm();
-		      newFrame.setContentPane(instance.getPanel());
-		      newFrame.pack();
-		      newFrame.setVisible(true);
-		      newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
-		}
-		public GaAlgorithm() {
-			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));	
-			fileChooser.setCurrentDirectory(new File(System.getProperty("user.dir")));
-			fileChooser.setSelectedFile(new File("plott.txt"));
-		}
-		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));
-			
-			
-				
-			JLabel maxGenerationsLabel = new JLabel("Max. Generations:");
-			maxGenerationsLabel.setBounds(20, 60, 150, 20);
-			parameterPanel.add(maxGenerationsLabel);
-			
-			JLabel populationLabel = new JLabel("Population Size:");
-			populationLabel.setBounds(20, 85, 150, 20);
-			parameterPanel.add(populationLabel);
-			
-			JLabel roundLabel = new JLabel("Rounds:");
-			roundLabel.setBounds(20, 110, 150, 20);
-			parameterPanel.add(roundLabel);
-			
-			JLabel mutationLabel = new JLabel("FixedMutation:");
-			mutationLabel.setBounds(50, 255, 150, 20);
-			mutationLabel.setEnabled(useFixedMutateProbability);
-			parameterPanel.add(mutationLabel);
-			
-		
-			JLabel swapLabel = new JLabel("FixedSwap:");
-			swapLabel.setBounds(50, 160, 150, 20);
-			swapLabel.setEnabled(this.useFixedSpawProbability);
-			parameterPanel.add(swapLabel);
-			
-			JLabel tournamentLabel = new JLabel("TournamentSize:");
-			tournamentLabel.setBounds(20, 185, 150, 20);
-			parameterPanel.add(tournamentLabel);
-			
-			
-			JLabel progressLabel = new JLabel("Progress:");
-			progressLabel.setBounds(350, 135, 170, 20);
-			parameterPanel.add(progressLabel);	
-			
-			progressBar.setBounds(350, 155, 185, 20);
-			progressBar.setStringPainted(true);
-			parameterPanel.add(progressBar);
-			
-			JPanel borderPanel = new JPanel(null);
-			borderPanel.setBounds(350, 85, 185, 50);
-			borderPanel.setBorder(BorderFactory.createTitledBorder(""));
-			parameterPanel.add(borderPanel);	
-			
-			JLabel showGroupNodeLabel = new JLabel("Use Group Node:");
-			showGroupNodeLabel.setBounds(10, 1, 170, 20);
-			borderPanel.add(showGroupNodeLabel);	
-			
-			JButton selectGroupNodeButton = new JButton("Select GroupNode");
-			selectGroupNodeButton.setEnabled(false);
-			selectGroupNodeButton.setBounds(10, 25, 165, 20);
-			selectGroupNodeButton.addActionListener(actionEvent -> selectGroupNode());
-			borderPanel.add(selectGroupNodeButton);	
-			
-			JCheckBox useGroupNodeCheckBox = new JCheckBox();
-			useGroupNodeCheckBox.setSelected(false);
-			useGroupNodeCheckBox.setBounds(155, 1, 25, 20);
-			useGroupNodeCheckBox.addActionListener(actionEvent -> {
-				useGroupNode = useGroupNodeCheckBox.isSelected();
-				selectGroupNodeButton.setEnabled(useGroupNode);
-			});
-			borderPanel.add(useGroupNodeCheckBox);
-			
-			JCheckBox informationCheckBox = new JCheckBox("More Information");
-			informationCheckBox.setSelected(this.moreInformation);
-			informationCheckBox.setBounds(350, 60, 220, 20);
-			informationCheckBox.addActionListener(actionEvent -> {
-				moreInformation = informationCheckBox.isSelected();
-			});
-			parameterPanel.add(informationCheckBox);
-			
-			
-			//Integer formatter
-			NumberFormat format = NumberFormat.getIntegerInstance();
-			format.setGroupingUsed(false);
-			format.setParseIntegerOnly(true);
-			NumberFormatter integerFormatter = new NumberFormatter(format);
-			integerFormatter.setMinimum(1);
-			integerFormatter.setCommitsOnValidEdit(true);
-			
-			
-			JFormattedTextField maxGenerationsTextField = new  JFormattedTextField(integerFormatter);
-			maxGenerationsTextField.setValue(this.maxGenerations);
-			maxGenerationsTextField.setToolTipText("Only positive Integer.");
-			maxGenerationsTextField.addPropertyChangeListener(actionEvent -> this.maxGenerations = Integer.parseInt(maxGenerationsTextField.getValue().toString()));
-			maxGenerationsTextField.setBounds(160, 60, 50, 20);
-			parameterPanel.add(maxGenerationsTextField);
-			
-			JFormattedTextField popSizeTextField = new JFormattedTextField(integerFormatter);
-			popSizeTextField.setValue(this.popsize);
-			popSizeTextField.setToolTipText("Only positive Integer.");
-			popSizeTextField.addPropertyChangeListener(propertyChange -> this.popsize = Integer.parseInt(popSizeTextField.getValue().toString()));
-			popSizeTextField.setBounds(160, 85, 50, 20);
-			parameterPanel.add(popSizeTextField);
-			
-			
-			JFormattedTextField roundsTextField = new JFormattedTextField(integerFormatter);
-			roundsTextField.setValue(this.rounds);
-			roundsTextField.setToolTipText("Only positive Integer.");
-			roundsTextField.addPropertyChangeListener(propertyChange -> this.rounds = Integer.parseInt(roundsTextField.getValue().toString()));
-			roundsTextField.setBounds(160, 110, 50, 20);
-			parameterPanel.add(roundsTextField);
-			
-			
-			//Double Format:
-			NumberFormat doubleFormat = NumberFormat.getNumberInstance(Locale.US);
-			doubleFormat.setMinimumFractionDigits(1);
-			doubleFormat.setMaximumFractionDigits(3);
-			doubleFormat.setRoundingMode(RoundingMode.HALF_UP);
-
-			//Limit Formatter:
-			NumberFormatter limitFormatter = new NumberFormatter(doubleFormat);
-			limitFormatter.setMinimum(0.0);
-			limitFormatter.setMaximum(1.0);
-			
-			
-			
-			JFormattedTextField mutateTextField = new JFormattedTextField(limitFormatter);
-			mutateTextField.setValue(this.fixedMutateProbability);
-			mutateTextField.setEnabled(this.useFixedMutateProbability);
-			mutateTextField.setToolTipText("Only Double in range [0.0, 1.0] with DecimalSeperator Point('.').");
-			mutateTextField.addPropertyChangeListener(propertyChange -> fixedMutateProbability = Double.parseDouble(mutateTextField.getValue().toString()));
-			mutateTextField.setBounds(160, 255, 50, 20);
-			parameterPanel.add(mutateTextField);
-			
-			JCheckBox useFixMutateCheckBox = new JCheckBox();
-			useFixMutateCheckBox.setSelected(this.useFixedMutateProbability);
-			useFixMutateCheckBox.setToolTipText("If not checked its 1/ProblemSize");
-			useFixMutateCheckBox.setBounds(20, 255, 25, 20);
-			useFixMutateCheckBox.addActionListener(actionEvent -> {
-				boolean state = useFixMutateCheckBox.isSelected();
-				this.useFixedMutateProbability = state;
-				mutateTextField.setEnabled(state);
-				mutationLabel.setEnabled(state);
-			});
-			parameterPanel.add(useFixMutateCheckBox);
-			
-			
-			JFormattedTextField swapTextField = new JFormattedTextField(limitFormatter);
-			swapTextField.setValue(this.fixedSwapProbability);
-			swapTextField.setEnabled(this.useFixedMutateProbability);
-			swapTextField.setToolTipText("Only Double in range [0.0, 1.0] with DecimalSeperator Point('.').");
-			swapTextField.addPropertyChangeListener(propertyChange -> this.fixedSwapProbability = Double.parseDouble(swapTextField.getValue().toString()));
-			swapTextField.setBounds(160, 160, 50, 20);
-			parameterPanel.add(swapTextField);
-			
-			JCheckBox useFixSwapCheckBox = new JCheckBox();
-			useFixSwapCheckBox.setSelected(this.useFixedSpawProbability);
-			useFixSwapCheckBox.setToolTipText("If not checked its 1/ProblemSize");
-			useFixSwapCheckBox.setBounds(20, 160, 25, 20);
-			useFixSwapCheckBox.addActionListener(actionEvent -> {
-				boolean state = useFixSwapCheckBox.isSelected();
-				this.useFixedSpawProbability = state;
-				swapTextField.setEnabled(state);
-				swapLabel.setEnabled(state);
-			});
-			parameterPanel.add(useFixSwapCheckBox);
-			
-			
-			NumberFormatter tournamentFormatter = new NumberFormatter(doubleFormat);
-			tournamentFormatter.setMinimum(1.0);
-			
-			
-			JFormattedTextField tournamentSizeTextField = new JFormattedTextField(tournamentFormatter);
-			tournamentSizeTextField.setValue(this.tournamentSize);
-			tournamentSizeTextField.setToolTipText("Only Double bigger or equal then 1.");
-			tournamentSizeTextField.addPropertyChangeListener(propertyChange -> this.tournamentSize = Double.parseDouble(tournamentSizeTextField.getValue().toString()));
-			tournamentSizeTextField.setBounds(160, 185, 50, 20);
-			parameterPanel.add(tournamentSizeTextField);
-			
-			
-			JLabel mutationIntervallLabel = new JLabel("MutationRate:");
-			mutationIntervallLabel.setBounds(220, 255, 150, 20);
-			mutationIntervallLabel.setEnabled(useIntervalMutation);
-			parameterPanel.add(mutationIntervallLabel);
-			
-			JFormattedTextField mutationRateField = new JFormattedTextField(limitFormatter);
-			mutationRateField.setValue(this.mutateProbabilityInterval);
-			mutationRateField.setEnabled(this.useIntervalMutation);
-			mutationRateField.setToolTipText("Only Double in range [0.0, 1.0] with DecimalSeperator Point('.').");
-			mutationRateField.addPropertyChangeListener(propertyChange -> this.mutateProbabilityInterval = Double.parseDouble(mutationRateField.getValue().toString()));
-			mutationRateField.setBounds(400, 255, 50, 20);
-			parameterPanel.add(mutationRateField);
-			
-			JLabel maxMutationPercentLabel = new JLabel("Max Mutation Percent:");
-			maxMutationPercentLabel.setBounds(220, 280, 200, 20);
-			maxMutationPercentLabel.setEnabled(useIntervalMutation);
-			parameterPanel.add(maxMutationPercentLabel);
-			
-			JFormattedTextField mutationMaxField = new JFormattedTextField(limitFormatter);
-			mutationMaxField.setValue(this.maxMutationPercent);
-			mutationMaxField.setEnabled(this.useIntervalMutation);
-			mutationMaxField.setToolTipText("Only Double in range [0.0, 1.0] with DecimalSeperator Point('.').");
-			mutationMaxField.addPropertyChangeListener(propertyChange -> this.maxMutationPercent = Double.parseDouble(mutationMaxField.getValue().toString()));
-			mutationMaxField.setBounds(400, 280, 50, 20);
-			parameterPanel.add(mutationMaxField);
-			
-			
-			
-			JRadioButton jRadioMutate = new  JRadioButton("Normal Mutate");
-			jRadioMutate.setBounds(20, 230, 200, 20);
-			jRadioMutate.setSelected(!useIntervalMutation);
-			jRadioMutate.setActionCommand("normal");
-			parameterPanel.add(jRadioMutate);
-			
-			JRadioButton jRadioMutateInterval = new  JRadioButton("Mutate Interval");
-			jRadioMutateInterval.setBounds(220, 230, 200, 20);
-			jRadioMutateInterval.setActionCommand("intervall");
-			jRadioMutateInterval.setSelected(useIntervalMutation);
-			parameterPanel.add(jRadioMutateInterval);
-			
-			ButtonGroup group = new ButtonGroup();
-			group.add(jRadioMutate);
-			group.add(jRadioMutateInterval);
-			ActionListener radioListener = e -> {
-				if(e.getActionCommand() == "normal") {
-					this.useIntervalMutation = false;
-					mutateTextField.setEnabled(true);
-					useFixMutateCheckBox.setEnabled(true);
-					mutationLabel.setEnabled(true);
-					mutationIntervallLabel.setEnabled(false);
-					mutationRateField.setEnabled(false);
-					maxMutationPercentLabel.setEnabled(false);
-					mutationMaxField.setEnabled(false);
-					
-				}else if(e.getActionCommand() == "intervall") {
-					this.useIntervalMutation = true;
-					mutateTextField.setEnabled(false);
-					useFixMutateCheckBox.setEnabled(false);
-					mutationLabel.setEnabled(false);
-					mutationIntervallLabel.setEnabled(true);
-					mutationRateField.setEnabled(true);
-					maxMutationPercentLabel.setEnabled(true);
-					mutationMaxField.setEnabled(true);
-				} 
-			};
-			jRadioMutate.addActionListener(radioListener);
-			jRadioMutateInterval.addActionListener(radioListener);
-			
-			return parameterPanel;
-		}
-		
-		
-		
-		
-		
-		public JPanel createButtonPanel() {
-			JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
-			JButton fitnessButton =  new JButton("Fitness");
-			fitnessButton.setToolTipText("Fitness for the current state.");
-			fitnessButton.addActionListener(actionEvent -> fitness());
-			buttonPanel.add(fitnessButton);
-			JButton plottButton =  new JButton("Plott");
-			plottButton.addActionListener(actionEvent -> plott());
-			buttonPanel.add(plottButton);
-			JButton resetButton =  new JButton("ResetAll");
-			resetButton.setToolTipText("Resets the State to before the Algorithm has runed.");
-			resetButton.addActionListener(actionEvent -> resetAll());
-			buttonPanel.add(resetButton);
-			JButton cancelButton =  new JButton("Cancel Run");
-			cancelButton.addActionListener(actionEvent -> cancel());
-			buttonPanel.add(cancelButton);
-			JButton undoButton =  new JButton("Undo");
-			undoButton.setToolTipText("One Algo Step Back.");
-			undoButton.addActionListener(actionEvent -> resetLast());
-			buttonPanel.add(undoButton);
-			JButton runButton =  new JButton("Run");
-			runButton.addActionListener(actionEvent -> {
-				Runnable task = () -> run();
-				runThread = new Thread(task);
-				runThread.start();
-			});
-			buttonPanel.add(runButton);
-			return buttonPanel;
-		}
-		private void cancel() {
-			if(runThread.isAlive()) {
-				println("");
-				println("Cancel run.");
-				cancel = true;
-				progressBar.setValue(0);
-			} else {
-				println("Nothing to cancel.");
-			}
-		}
-		
-		private void run() {
-			cancel = false;
-			disableGuiInput(true);
-			executeAlgoWithParameter();
-			updateVisual();
-			disableGuiInput(false);
-		}
-		
-		private void resetLast() {
-			if(runThread.isAlive()) {
-				println("Run have to be cancelled First.");
-				return;
-			}
-			if(!resetChain.isEmpty()) {
-				println("Resetting..");
-				resetState();
-				resetChain.removeLast();
-				control.resetSimulation();
-				updateVisual();
-			}else {
-				println("No run inistialized.");
-			}
-		}
-		
-		private void resetAll() {
-			if(runThread.isAlive()) {
-				println("Run have to be cancelled First.");
-				return;
-			}
-			if(!resetChain.isEmpty()) {
-				println("Resetting..");
-				setState(resetChain.getFirst());
-				resetChain.clear();
-				control.resetSimulation();
-				control.setCurIteration(0);
-				updateVisual();
-			}else {
-				println("No run inistialized.");
-			}
-		}
-		
-		private void fitness() {
-			if(runThread.isAlive()) {
-				println("Run have to be cancelled First.");
-				return;
-			}
-			double currentFitness = evaluatePosition(extractPositionAndAccess(), false);
-			resetChain.removeLast();
-			console.println("Actual Fitnessvalue: " + currentFitness);
-		}
-		
-		private void disableGuiInput(boolean bool) {
-			control.guiDisable(bool);
-		}
-		
-		private void plott() {
-			if(db!=null) {
-				console.println("Plott..");
-				db.initFileStream();
-			}else {
-				console.println("No run inistialized.");
-			}
-		}
-
-		
-		
-		@Override
-		public JPanel getPanel() {
-			return content;
-		}
-		@Override
-		public void setController(Control control) {
-			this.control = control;
-			
-		}
-		private void clear() {
-			console.clear();
-		}
-		private void println(String message) {
-			console.println(message);
-		}
-		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) {
-				println("Selected: " + selected);
-				dGroupNode = selected.object;
-			}
-		}
-		private void progressBarStep(){
-			progressBar.setValue(++progressBarCount);
-		}
-		private void calculateProgressBarParameter() {
-			int max = this.maxGenerations * this.popsize * this.rounds;
-			progressBarCount = 0;
-			progressBar.setValue(0);
-			progressBar.setMaximum(max);
-		}
-		
-		private void startTimer(){
-			startTime = System.currentTimeMillis();
-		}
-		private void printElapsedTime(){
-			long elapsedMilliSeconds = System.currentTimeMillis() - startTime;
-			println("Execution Time of Algo in Milliseconds:" + elapsedMilliSeconds);
-		}
-		
-		
-		
-		private void executeAlgoWithParameter(){
-			
-			
-			
-			int actualIteration = control.getModel().getCurIteration();
-			println("TimeStep:" + actualIteration);
-			calculateProgressBarParameter();
-			
-			startTimer();
-			Individual runBest = new Individual();
-			runBest.fitness = Double.MAX_VALUE;
-			db = new RunDataBase();
-			for(int r = 0; r < rounds; r++)
-			{		
-				List<Double> runList = db.insertNewRun();
-				Individual  roundBest = executeGaAlgo(runList);
-				if(cancel)return;
-				resetState();
-				if(roundBest.fitness < runBest.fitness) runBest = roundBest;
-			}
-			printElapsedTime();
-			setState(runBest.position);
-			updateVisual();
-			println("AlgoResult:" + runBest.fitness);
-			
-			
-		}
-		
-		
-		
-		
-		//Algo Part:
-		/** 	
-		 * 	Algorithm 20 !! Fitness is better when smaller.: 
-		 *  PseudoCode:
-		 *  Best <- actual;
-		 * 	population = initPopulationRandom();
-		 * 	for(maxGeneration times){
-		 * 		for(each Individual i from population){
-		 * 			fitness <- evaluatePosition(i);
-		 * 			if(fitness < best.fitnessValue) Best <- i;
-		 * 		}
-		 * 		childList <- {};
-		 * 		for(popsize/2 times){
-		 * 			parentA <- selectAParent(population);
-		 * 			parentB <- selectAParent(population);
-		 * 			childA,childB <- crossover(Copy(parentA ), Copy(parentB));
-		 * 			mutate(childA);
-		 * 			mutate(childB);
-		 * 			childList.add(childA);
-		 * 			childList.add(childB);
-		 * 		}
-		 * 		population = childList;	
-		 * 
-		 * 	}
-		 * @return 
-		 */
-		private Individual executeGaAlgo(List<Double> runList) {
-			Individual best = new Individual();
-			best.position = extractPositionAndAccess();
-			if(moreInformation)println("Bit-Array_length: " + best.position.size());
-			best.fitness = evaluatePosition(best.position, false);
-			runList.add(best.fitness);
-			console.print("Start with: " + best.fitness);
-			if(moreInformation)println("");
-			int problemSize = best.position.size();
-			List<Individual> population = initPopuluationRandom(problemSize, best);
-			if(moreInformation)println("Size To Test:" + population.size());
-			for(int generation = 0; generation< maxGenerations; generation++) {
-				if(moreInformation)println("Generation" + generation + " start with Fitness: " + best.fitness);
-				for(Individual i : population) {
-					i.fitness = evaluatePosition(i.position, true);
-					if(moreInformation)println("Fitness" + i.fitness);
-					if(i.fitness < best.fitness) best = i;
-					
-				}
-				runList.add(best.fitness);
-				List<Individual> childList = new ArrayList<Individual>();
-				for(int k = 0; k<popsize/2; k++) {
-					Individual parentA = selectAParent(population, popsize);
-					Individual parentB = selectAParent(population, popsize);
-					Individual childA = new Individual(parentA);
-					Individual childB = new Individual(parentB);
-					crossover(childA, childB, problemSize);
-					if(useIntervalMutation)mutateInterval(childA, problemSize);else mutate(childA, problemSize);
-					if(useIntervalMutation)mutateInterval(childB, problemSize);else mutate(childB, problemSize);
-					childList.add(childA);
-					childList.add(childB);
-				}
-				population = childList;
-				if(moreInformation)println("________________");
-				if(cancel)return null;
-			}
-			
-			
-			println("   End with:" + best.fitness);
-			return best;
-			
-		}
-		
-		/**
-		 * Algorithm 22 Bit-Flip Mutation.
-		 * 
-		 */
-		private void mutate(Individual child, int problemSize) {
-			double probability = (this.useFixedMutateProbability) ? this.fixedMutateProbability : 1.0/(double)problemSize;
-			ListIterator<Boolean> iter = child.position.listIterator();
-			while(iter.hasNext()) {
-				boolean boolValue = iter.next();
-				if(Random.nextDouble() <=  probability) {
-					iter.set(!boolValue);
-				}
-			}
-		}
-		
-		/**
-		 * Algorithm rolf
-		 * 
-		 */
-		private void mutateInterval(Individual child, int problemSize) {
-			//If not mutate skip
-			if(Random.nextDouble() >  this.mutateProbabilityInterval) {
-				return;
-			}
-			//println("problemSize:" + problemSize + "    maxMutationPercent:" + maxMutationPercent);
-			int maximumAmountOfMutatedBits = Math.max(1, (int)Math.round(((double) problemSize) * this.maxMutationPercent));
-			int randomUniformAmountOfMutatedValues = Random.nextIntegerInRange(1,maximumAmountOfMutatedBits + 1);
-			
-			//println("max:" + maximumAmountOfMutatedBits + "   actual:" + randomUniformAmountOfMutatedValues);
-			TreeSet<Integer> mutationLocation = new TreeSet<Integer>(); //sortedSet
-			//Choose the location to mutate
-			for(int i = 0; i< randomUniformAmountOfMutatedValues; i++) {
-				boolean success = mutationLocation.add(Random.nextIntegerInRange(0, problemSize));
-				if(!success) i--; //can be add up to some series long loops if maximumAmountOfMutatedBits get closed to problemsize.
-			}
-			//println("Set:" + mutationLocation);
-			ListIterator<Boolean> iter = child.position.listIterator();
-			if(mutationLocation.isEmpty()) return;
-			int firstindex = mutationLocation.pollFirst();
-			while(iter.hasNext()) {
-				int index = iter.nextIndex();
-				boolean boolValue = iter.next();
-				if(index == firstindex) {
-					iter.set(!boolValue);
-					//println("changed Value["+ index +"]");
-					if(mutationLocation.isEmpty()) break;
-					firstindex = mutationLocation.pollFirst();
-				}
-			}
-		}
-		
-		
-		
-		
-		/** 
-		 * Algorithm 25 Uniform Crossover.
-		 * Probability is set to 1/Problemsize when not changed.
-		 */
-		private void crossover(Individual childA, Individual childB, int problemSize) {
-			double probability = (this.useFixedSpawProbability) ? this.fixedSwapProbability : 1.0/(double)problemSize;
-			ListIterator<Boolean> iterA = childA.position.listIterator();
-			ListIterator<Boolean> iterB = childB.position.listIterator();
-			for(int i= 0; i < problemSize; i++) {
-				boolean boolA = iterA.next();
-				boolean boolB = iterB.next();
-				if(Random.nextDouble() <=  probability ) {
-					//Swap 
-					iterA.set(boolB);
-					iterB.set(boolA);
-				}
-			}
-		}
-		/**
-		 * Algorithm 32 Tournament Selection.
-		 * The fitnessValues are calculated for the Population List.
-		 * PseudoCode
-		 */
-		private Individual selectAParent(List<Individual> population,int popsize) {
-			Individual tournamentBest = population.get(Random.nextIntegerInRange(0, popsize));
-			double participants;
-			for(participants = tournamentSize ; participants >= 2; participants -= 1.0) {
-				Individual next = population.get(Random.nextIntegerInRange(0, popsize));
-				if(next.fitness < tournamentBest.fitness) tournamentBest = next;
-			}
-			//if tournament size is not a whole number like 2.5 or 3.6
-			//the remaining part is the chance to fight another time; 2.7 -> 70% chance to fight a second time
-			if( participants > 1) {		
-				if(Random.nextDouble() < participants - 1.0) {
-					//println("Chance to find a match");
-					Individual next = population.get(Random.nextIntegerInRange(0, popsize));
-					if(next.fitness < tournamentBest.fitness) tournamentBest = next;
-				}
-			}
-			return tournamentBest;
-		}
-		/**
-		 * Initialize the Population with Individuals that have a random Position.
-		 */
-		private List<Individual> initPopuluationRandom(int problemSize, Individual startIndidual){
-			List<Individual> population =  new ArrayList<Individual>();
-			for(int i = 0; i < popsize -1; i++) {
-				population.add(createRandomIndividualWithoutFitness(problemSize));
-			}
-			//Add Start Position
-			population.add(new Individual(startIndidual));
-			return population;
-		}
-		
-		
-		
-		/**
-		 * Algorithm 21 The BooleanVeator initialization.
-		 * @param problemSize
-		 * @return
-		 */
-		private Individual createRandomIndividualWithoutFitness(int problemSize) {
-			//create Random Individual Without Fitness
-			Individual result = new Individual();
-			result.position = new ArrayList<Boolean>();
-			for (int index = 0; index < problemSize; index++){
-				result.position.add(Random.nextBoolean());
-			}
-			return result;
-		}
-		/**
-		 * 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
-		 */
-		private List<Boolean> extractPositionAndAccess() {
-			Model model = control.getModel();
-			switchList = new ArrayList<HolonSwitch>();
-			objectList = new ArrayList<HolonObject>();
-			List<Boolean> initialState = new ArrayList<Boolean>();
-			access= new HashMap<Integer, AccessWrapper>();
-			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.put(positionToInit.size() - 1 , new AccessWrapper(hE));
-					}
-					objectList.add((HolonObject) aCps);
-				}
-				else if (aCps instanceof HolonSwitch) {
-					HolonSwitch sw = (HolonSwitch) aCps;
-					positionToInit.add(sw.getState(timeStep));
-					switchList.add(sw);
-					access.put(positionToInit.size() - 1 , new AccessWrapper(sw));
-				}
-				else if(aCps instanceof CpsUpperNode) {
-					rollOutNodes(((CpsUpperNode)aCps).getNodes(), positionToInit ,timeStep );
-				}
-			}
-		}
-		
-		
-		
-		private double evaluatePosition(List<Boolean> position, boolean doIncreaseCounter) {
-			setState(position);
-			if(doIncreaseCounter)progressBarStep();
-			control.calculateStateOnlyForCurrentTimeStep();
-			DecoratedState actualstate = control.getSimManager().getActualDecorState();		
-			return PSOAlgorithm.getFitnessValueForState(actualstate);
-		}
-		
-		
-		
-		/**
-		 * To let the User See the current state without touching the Canvas.
-		 */
-		private void updateVisual() {
-			control.calculateStateAndVisualForCurrentTimeStep();
-			//control.updateCanvas();
-			//control.getGui().triggerUpdateController(null);
-		}
-		/**
-		 * 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) {
-			for(int i = 0;i<position.size();i++) {
-				access.get(i).setState(position.get(i));
-			}
-		}
-		
-		private class Individual {
-			public double fitness;
-			public  List<Boolean> position;
-			
-			Individual(){};
-			/**
-			 *  Copy Constructor
-			 */
-			Individual(Individual c){
-				position = c.position.stream().collect(Collectors.toList());
-				fitness = c.fitness;
-			}
-		}
-		
-		
-		
-		
-		
-		
-		
-		/**
-		 * 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;
-			}
-		}
-		
-		/**
-		 * A Database for all Global Best(G<sub>Best</sub>) Values in a execution of a the Algo. For Easy Printing.
-		 */
-		public class RunDataBase {
-			List<List<Double>> allRuns = new ArrayList<List<Double>>();
-
-			
-			
-			/**
-			 * Initialize The Stream before you can write to a File.
-			 */
-			public void initFileStream() {
-				File file = fileChooser.getSelectedFile();
-				try {
-					file.createNewFile();
-					BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
-						    new FileOutputStream(file, append), "UTF-8"));
-					printToStream(out);
-					out.close();
-				} catch (IOException e) {
-					console.println(e.getMessage());
-				}
-			}
-			
-			public void printToStream(BufferedWriter out) throws IOException {
-				try {
-					out.write(maxGenerations + 1 + "," + allRuns.size() + "," + popsize);
-					out.newLine();
-
-				}
-				catch(IOException e) {
-					console.println(e.getMessage());
-				}
-				allRuns.forEach(run -> {
-					try {
-						out.write( run.stream().map(Object::toString).collect(Collectors.joining(", ")));
-						out.newLine();
-					} catch (IOException e) {
-						console.println(e.getMessage());
-					}
-				} );
-			}
-			
-			public List<Double> insertNewRun(){
-				List<Double> newRun = new ArrayList<Double>();
-				allRuns.add(newRun);
-				return newRun;
-			}
-		}
-		
-		
-		
-		
-		private class RunResult {
-			public int activatedFlex = 0;
-			public int deactivatedElements = 0;
-			public float totalCost = 0;
-			public LinkedList<TimeStepStateResult> timeStepList = new LinkedList<TimeStepStateResult>();
-			
-			
-			public TimeStepStateResult addTimeStepStateResult(){
-				TimeStepStateResult aResult = new TimeStepStateResult();
-				timeStepList.add(aResult);
-				return aResult;
-			}
-			
-			
-			public class TimeStepStateResult{
-				public int amountOfProducer = 0;
-				public int amountOfConsumer = 0;
-				public int amountOfPassiv = 0;
-				public int amountOfConsumerOverSupplied = 0;
-				public int amountOfConsumerSupplied = 0;
-				public int amountOfConsumerPartiallySupplied = 0;
-				public int amountOfConsumerUnSupplied= 0;
-				
-				public float getProportionWithState(HolonObjectState state) {
-					float amountOfObjects = amountOfProducer + amountOfConsumer + amountOfPassiv;
-					switch(state) {
-					case NOT_SUPPLIED:
-						return (float) amountOfConsumerUnSupplied / amountOfObjects;
-					case NO_ENERGY:
-						return (float) amountOfPassiv / amountOfObjects;
-					case OVER_SUPPLIED:
-						return (float) amountOfConsumerOverSupplied / amountOfObjects;
-					case PARTIALLY_SUPPLIED:
-						return (float) amountOfConsumerPartiallySupplied / amountOfObjects;
-					case PRODUCER:
-						return (float) amountOfProducer / amountOfObjects;
-					case SUPPLIED:
-						return (float) amountOfConsumerSupplied / amountOfObjects;
-					default:
-						return 0.f;
-					}
-				}
-			}
-			public float getAvergaeProportionWithState(HolonObjectState state) {
-				return timeStepList.stream().map(step -> step.getProportionWithState(state)).reduce((a,b) -> (a + b)).orElse(0.f) / (float) 100;
-			}
-		}
-		
-
-		/**
-		* To create Random and maybe switch the random generation in the future.
-		*/
-		private 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();
-			}
-		}
-
-}

+ 30 - 1
src/exampleAlgorithms/GaAlgorithm2.java

@@ -7,7 +7,6 @@ import java.util.TreeSet;
 
 import javax.swing.JFrame;
 
-import api.AlgorithmFramework;
 import api.AlgorithmFrameworkFlex;
 import ui.model.DecoratedState;
 
@@ -106,6 +105,7 @@ public class GaAlgorithm2 extends AlgorithmFrameworkFlex{
 		
 		
 		console.println("   End with:" + best.fitness);
+		db.insertNewRun(runList);
 		return best;
 	}
 	/**
@@ -232,4 +232,33 @@ public class GaAlgorithm2 extends AlgorithmFrameworkFlex{
 		}
 		return result;
 	}
+
+	@Override
+	protected String algoInformationToPrint() {
+//		private int popsize = 20;
+//		private int maxGenerations = 100;
+//		private double tournamentSize = 2.0;
+//		private double fixedSwapProbability = 0.02;
+//		private boolean useFixedSpawProbability = false;
+//		private double fixedMutateProbability = 0.02;
+//		private boolean useFixedMutateProbability = false;
+//		private boolean useIntervalMutation = true;
+//		private double mutateProbabilityInterval = 0.01;
+//		private double maxMutationPercent = 0.01;
+		return "GaAlgo"+ " Rounds:" + rounds 
+				+ " maxGenerations:" + maxGenerations
+				+ " popsize:" + popsize
+				+ " tournamentSize:" +  tournamentSize
+				+ (useFixedSpawProbability? " fixedSwapProbability:" +  fixedSwapProbability:" swapProbability:" + 1.0f/ (float)popsize)
+				+ (useIntervalMutation? 
+						(" mutateProbabilityInterval:" +  mutateProbabilityInterval
+						+ " maxMutationPercent:" +  maxMutationPercent)
+						: 
+						(useFixedMutateProbability? " fixedMutateProbability:" +  fixedMutateProbability:" mutateProbability:" + 1.0f/ (float)popsize));
+	}
+
+	@Override
+	protected String plottFileName() {
+		return "plottGaAlgo.txt";
+	}
 }

+ 0 - 1102
src/exampleAlgorithms/PSOAlgorithm.java

@@ -1,1102 +0,0 @@
-package exampleAlgorithms;
-
-import java.awt.BorderLayout;
-import java.awt.Component;
-import java.awt.Cursor;
-import java.awt.Dimension;
-import java.awt.FlowLayout;
-import java.awt.Font;
-import java.awt.event.ActionListener;
-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.math.RoundingMode;
-import java.text.NumberFormat;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Locale;
-import java.util.TreeSet;
-import java.util.stream.Collectors;
-
-import javax.swing.BorderFactory;
-import javax.swing.ButtonGroup;
-import javax.swing.ImageIcon;
-import javax.swing.JButton;
-import javax.swing.JCheckBox;
-import javax.swing.JFileChooser;
-import javax.swing.JFormattedTextField;
-import javax.swing.JFrame;
-import javax.swing.JLabel;
-import javax.swing.JOptionPane;
-import javax.swing.JPanel;
-import javax.swing.JProgressBar;
-import javax.swing.JRadioButton;
-import javax.swing.JScrollPane;
-import javax.swing.JSplitPane;
-import javax.swing.JTextArea;
-import javax.swing.filechooser.FileNameExtensionFilter;
-import javax.swing.text.NumberFormatter;
-
-import api.AddOn;
-import classes.AbstractCpsObject;
-import classes.CpsUpperNode;
-import classes.HolonElement;
-import classes.HolonObject;
-import classes.HolonSwitch;
-import ui.controller.Control;
-import ui.model.Model;
-import ui.view.Console;
-import ui.model.DecoratedHolonObject.HolonObjectState;
-import ui.model.DecoratedGroupNode;
-import ui.model.DecoratedNetwork;
-import ui.model.DecoratedState;
-
-
-
-
-
-public class PSOAlgorithm implements AddOn {
-	//Parameter for Algo with default Values:
-	private int swarmSize = 150; 
-	private int maxIterations = 200; 
-	private double limit = 0.01; 
-	private double dependency = 2.07; 
-	private int rounds = 20;
-	private int mutationInterval = 1;
-	private boolean useIntervalMutation = true;
-	private double mutateProbabilityInterval = 0.01;
-	private double maxMutationPercent = 0.01;
-	
-	
-	private double c1, c2, w;
-	
-	
-	//Settings For GroupNode using and plotting
-	private boolean append = false;
-	private boolean useGroupNode = false;
-	private DecoratedGroupNode dGroupNode = null;
-	
-	//Parameter defined by Algo
-	private HashMap<Integer, AccessWrapper> access;
-	LinkedList<List<Boolean>> resetChain = new LinkedList<List<Boolean>>();
-	private RunDataBase db;
-	
-	//Parameter for Plotting (Default Directory in Constructor)
-	private JFileChooser fileChooser = new JFileChooser();
-	
-	
-	//Gui Part:
-	private Control  control;
-	private Console console = new Console();
-	private JPanel content = new JPanel();
-	//ProgressBar
-	private JProgressBar progressBar = new JProgressBar();
-	private int progressBarCount = 0;
-	private long startTime;
-	private Thread runThread = new Thread();
-	private boolean cancel = false;
-	
-	
-	public static void main(String[] args)
-	{
-	      JFrame newFrame = new JFrame("exampleWindow");
-	      PSOAlgorithm instance = new PSOAlgorithm();
-	      newFrame.setContentPane(instance.getPanel());
-	      newFrame.pack();
-	      newFrame.setVisible(true);
-	      newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
-	}
-	public PSOAlgorithm() {
-		content.setLayout(new BorderLayout());
-		JScrollPane scrollPane = new JScrollPane(console);
-		JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
-				createOptionPanel() , scrollPane);
-		splitPane.setResizeWeight(0.0);
-		content.add(splitPane, BorderLayout.CENTER);
-		content.setPreferredSize(new Dimension(800,800));	
-		//Default Directory
-		fileChooser.setCurrentDirectory(new File(System.getProperty("user.dir")));
-		fileChooser.setSelectedFile(new File("plott.txt"));
-	}
-	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));
-		
-		JLabel info = new JLabel("Tune the variables of the PSO algorithm in order to reach better results.");
-		info.setBounds(10, 10, 480, 15);
-		parameterPanel.add(info);
-		
-		JLabel swarmSizeLabel = new JLabel("Swarm Size:");
-		swarmSizeLabel.setBounds(20, 60, 100, 20);
-		parameterPanel.add(swarmSizeLabel);
-			
-		JLabel maxIterLabel = new JLabel("Max. Iterations:");
-		maxIterLabel.setBounds(20, 85, 100, 20);
-		parameterPanel.add(maxIterLabel);
-		
-		JLabel limitLabel = new JLabel("Limit:");
-		limitLabel.setBounds(20, 255, 100, 20);
-		parameterPanel.add(limitLabel);
-		
-		JLabel dependecyLabel = new JLabel("Dependency:");
-		dependecyLabel.setBounds(20, 135, 100, 20);
-		parameterPanel.add(dependecyLabel);
-			
-		JLabel roundsLabel = new JLabel("Round:");
-		roundsLabel.setBounds(20, 160, 100, 20);
-		parameterPanel.add(roundsLabel);
-		
-		JLabel mutationIntervalLabel = new JLabel("Mutation Interval");
-		mutationIntervalLabel.setBounds(20, 185, 100, 20);
-		parameterPanel.add(mutationIntervalLabel);
-		
-		JLabel cautionLabel = new JLabel(
-				"Caution: High values in the fields of 'Swarm Size' and 'Max. Iteration' may take some time to calculate.");
-		cautionLabel.setFont(new Font("Serif", Font.ITALIC, 12));
-
-		JLabel showDiagnosticsLabel = new JLabel("Append Plott on existing File:");
-		showDiagnosticsLabel.setBounds(200, 60, 170, 20);
-		parameterPanel.add(showDiagnosticsLabel);		
-		
-		JPanel borderPanel = new JPanel(null);
-		borderPanel.setBounds(200, 85, 185, 50);
-		borderPanel.setBorder(BorderFactory.createTitledBorder(""));
-		parameterPanel.add(borderPanel);	
-		
-		JLabel showGroupNodeLabel = new JLabel("Use Group Node:");
-		showGroupNodeLabel.setBounds(10, 1, 170, 20);
-		borderPanel.add(showGroupNodeLabel);	
-		
-		JButton selectGroupNodeButton = new JButton("Select GroupNode");
-		selectGroupNodeButton.setEnabled(false);
-		selectGroupNodeButton.setBounds(10, 25, 165, 20);
-		selectGroupNodeButton.addActionListener(actionEvent -> selectGroupNode());
-		borderPanel.add(selectGroupNodeButton);	
-		
-		JCheckBox useGroupNodeCheckBox = new JCheckBox();
-		useGroupNodeCheckBox.setSelected(false);
-		useGroupNodeCheckBox.setBounds(155, 1, 25, 20);
-		useGroupNodeCheckBox.addActionListener(actionEvent -> {
-			useGroupNode = useGroupNodeCheckBox.isSelected();
-			selectGroupNodeButton.setEnabled(useGroupNode);
-		});
-		borderPanel.add(useGroupNodeCheckBox);
-		
-		JLabel progressLabel = new JLabel("Progress:");
-		progressLabel.setBounds(200, 135, 170, 20);
-		parameterPanel.add(progressLabel);	
-		
-		progressBar.setBounds(200, 155, 185, 20);
-		progressBar.setStringPainted(true);
-		parameterPanel.add(progressBar);
-		
-		cautionLabel.setBounds(10, 210, 500, 15);
-		parameterPanel.add(cautionLabel);
-		
-		JCheckBox diagnosticsCheckBox = new JCheckBox();
-		diagnosticsCheckBox.setSelected(false);
-		diagnosticsCheckBox.setBounds(370, 60, 25, 20);
-		diagnosticsCheckBox.addActionListener(actionEvent -> append = diagnosticsCheckBox.isSelected());
-		parameterPanel.add(diagnosticsCheckBox);
-		
-
-		
-		//Integer formatter
-		NumberFormat format = NumberFormat.getIntegerInstance();
-		format.setGroupingUsed(false);
-		format.setParseIntegerOnly(true);
-		NumberFormatter integerFormatter = new NumberFormatter(format);
-		integerFormatter.setMinimum(0);
-		integerFormatter.setCommitsOnValidEdit(true);
-		
-		
-		JFormattedTextField swarmSizeTextField = new  JFormattedTextField(integerFormatter);
-		swarmSizeTextField.setValue(swarmSize);
-		swarmSizeTextField.setToolTipText("Only positive Integer.");
-		swarmSizeTextField.addPropertyChangeListener(actionEvent -> swarmSize = Integer.parseInt(swarmSizeTextField.getValue().toString()));
-		swarmSizeTextField.setBounds(125, 60, 50, 20);
-		parameterPanel.add(swarmSizeTextField);
-		
-		JFormattedTextField maxIterTextField = new JFormattedTextField(integerFormatter);
-		maxIterTextField.setValue(maxIterations);
-		maxIterTextField.setToolTipText("Only positive Integer.");
-		maxIterTextField.addPropertyChangeListener(propertyChange -> maxIterations = Integer.parseInt(maxIterTextField.getValue().toString()));
-		maxIterTextField.setBounds(125, 85, 50, 20);
-		parameterPanel.add(maxIterTextField);
-
-		//Double Format:
-		NumberFormat doubleFormat = NumberFormat.getNumberInstance(Locale.US);
-		doubleFormat.setMinimumFractionDigits(1);
-		doubleFormat.setMaximumFractionDigits(3);
-		doubleFormat.setRoundingMode(RoundingMode.HALF_UP);
-
-		//Limit Formatter:
-		NumberFormatter limitFormatter = new NumberFormatter(doubleFormat);
-		limitFormatter.setMinimum(0.0);
-		limitFormatter.setMaximum(1.0);
-		
-		JFormattedTextField limitTextField = new JFormattedTextField(limitFormatter);
-		limitTextField.setValue(limit);
-		limitTextField.setToolTipText("Only Double in range [0.0, 1.0] with DecimalSeperator Point('.').");
-		limitTextField.addPropertyChangeListener(propertyChange -> limit = Double.parseDouble(limitTextField.getValue().toString()));
-		limitTextField.setBounds(125, 255, 50, 20);
-		parameterPanel.add(limitTextField);
-		
-		//Limit Formatter:
-		NumberFormatter dependencyFormatter = new NumberFormatter(doubleFormat);
-		dependencyFormatter.setMinimum(2.001);
-		dependencyFormatter.setMaximum(2.4);
-		
-		
-		JFormattedTextField dependencyTextField = new JFormattedTextField(dependencyFormatter);
-		dependencyTextField.setValue(dependency);
-		dependencyTextField.setToolTipText("Only Double in range [2.001, 2.4] with DecimalSeperator Point('.').");
-		dependencyTextField.addPropertyChangeListener(propertyChange -> dependency = Double.parseDouble(dependencyTextField.getValue().toString()));
-		dependencyTextField.setBounds(125, 135, 50, 20);
-		parameterPanel.add(dependencyTextField);
-		
-		NumberFormatter roundsFormatter = new NumberFormatter(format);
-		roundsFormatter.setMinimum(1);
-		roundsFormatter.setCommitsOnValidEdit(true);
-		
-		JFormattedTextField roundsTextField = new JFormattedTextField(roundsFormatter);
-		roundsTextField.setValue(rounds);
-		roundsTextField.setToolTipText("Number of algorithm repetitions for the same starting situation ");
-		roundsTextField.addPropertyChangeListener(propertyChange -> rounds = Integer.parseInt((roundsTextField.getValue().toString())));
-		roundsTextField.setBounds(125, 160, 50, 20);
-		parameterPanel.add(roundsTextField);
-	//--- subsequently Rolf Did stuff ------------------------------------------------------------------------------------------
-		/*NumberFormatter mutationIntervalFormatter = new NumberFormatter(inte);
-		mutationIntervalFormatter.setMinimum(0);
-		mutationIntervalFormatter.setMaximum(maxIterations);
-		mutationIntervalFormatter.setCommitsOnValidEdit(true);*/
-		
-		NumberFormatter mutationFormatter = new NumberFormatter(format);
-		mutationFormatter.setMinimum(1);
-		mutationFormatter.setCommitsOnValidEdit(true);
-		JFormattedTextField mutationIntervalTextfield = new JFormattedTextField(mutationFormatter);
-		mutationIntervalTextfield.setValue(mutationInterval);
-		mutationIntervalTextfield.setToolTipText("The number of Iterations after which one mutation iteration is conducted");
-		mutationIntervalTextfield.addPropertyChangeListener(propertyChange -> mutationInterval = Integer.parseInt((mutationIntervalTextfield.getValue().toString())));
-		mutationIntervalTextfield.setBounds(125, 185, 50, 20);
-		parameterPanel.add(mutationIntervalTextfield);
-	//--- previously Rolf Did stuff ------------------------------------------------------------------------------------------
-		
-		
-		
-		
-		JLabel mutationIntervallLabel = new JLabel("MutationRate:");
-		mutationIntervallLabel.setBounds(220, 255, 150, 20);
-		mutationIntervallLabel.setEnabled(useIntervalMutation);
-		parameterPanel.add(mutationIntervallLabel);
-		
-		
-		
-		JFormattedTextField mutationRateField = new JFormattedTextField(limitFormatter);
-		mutationRateField.setValue(this.mutateProbabilityInterval);
-		mutationRateField.setEnabled(this.useIntervalMutation);
-		mutationRateField.setToolTipText("Only Double in range [0.0, 1.0] with DecimalSeperator Point('.').");
-		mutationRateField.addPropertyChangeListener(propertyChange -> this.mutateProbabilityInterval = Double.parseDouble(mutationRateField.getValue().toString()));
-		mutationRateField.setBounds(400, 255, 50, 20);
-		parameterPanel.add(mutationRateField);
-		
-		JLabel maxMutationPercentLabel = new JLabel("Max Mutation Percent:");
-		maxMutationPercentLabel.setBounds(220, 280, 200, 20);
-		maxMutationPercentLabel.setEnabled(useIntervalMutation);
-		parameterPanel.add(maxMutationPercentLabel);
-		
-		JFormattedTextField mutationMaxField = new JFormattedTextField(limitFormatter);
-		mutationMaxField.setValue(this.maxMutationPercent);
-		mutationMaxField.setEnabled(this.useIntervalMutation);
-		mutationMaxField.setToolTipText("Only Double in range [0.0, 1.0] with DecimalSeperator Point('.').");
-		mutationMaxField.addPropertyChangeListener(propertyChange -> this.maxMutationPercent = Double.parseDouble(mutationMaxField.getValue().toString()));
-		mutationMaxField.setBounds(400, 280, 50, 20);
-		parameterPanel.add(mutationMaxField);
-		
-		
-		
-		JRadioButton jRadioMutate = new  JRadioButton("Normal Mutate");
-		jRadioMutate.setBounds(20, 230, 200, 20);
-		jRadioMutate.setSelected(!useIntervalMutation);
-		jRadioMutate.setActionCommand("normal");
-		parameterPanel.add(jRadioMutate);
-		
-		JRadioButton jRadioMutateInterval = new  JRadioButton("Mutate Interval");
-		jRadioMutateInterval.setBounds(220, 230, 200, 20);
-		jRadioMutateInterval.setActionCommand("intervall");
-		jRadioMutateInterval.setSelected(useIntervalMutation);
-		parameterPanel.add(jRadioMutateInterval);
-		
-		ButtonGroup group = new ButtonGroup();
-		group.add(jRadioMutate);
-		group.add(jRadioMutateInterval);
-		ActionListener radioListener = e -> {
-			if(e.getActionCommand() == "normal") {
-				this.useIntervalMutation = false;
-				limitTextField.setEnabled(true);
-				limitLabel.setEnabled(true);
-				mutationIntervallLabel.setEnabled(false);
-				mutationRateField.setEnabled(false);
-				maxMutationPercentLabel.setEnabled(false);
-				mutationMaxField.setEnabled(false);
-				
-			}else if(e.getActionCommand() == "intervall") {
-				this.useIntervalMutation = true;
-				limitTextField.setEnabled(false);
-				limitLabel.setEnabled(false);
-				mutationIntervallLabel.setEnabled(true);
-				mutationRateField.setEnabled(true);
-				maxMutationPercentLabel.setEnabled(true);
-				mutationMaxField.setEnabled(true);
-			} 
-		};
-		jRadioMutate.addActionListener(radioListener);
-		jRadioMutateInterval.addActionListener(radioListener);
-		
-		
-		return parameterPanel;
-	}
-	public JPanel createButtonPanel() {
-		JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
-		
-		JButton cancelButton =  new JButton("Cancel Run");
-		cancelButton.addActionListener(actionEvent -> cancel());
-		buttonPanel.add(cancelButton);
-		JButton folderButton =  new JButton("Change Plott-File");
-		folderButton.addActionListener(actionEvent -> setSaveFile());
-		buttonPanel.add(folderButton);
-		JButton fitnessButton =  new JButton("Actual Fitness");
-		fitnessButton.addActionListener(actionEvent -> fitness());
-		buttonPanel.add(fitnessButton);
-		JButton plottButton =  new JButton("Plott");
-		plottButton.addActionListener(actionEvent -> plott());
-		buttonPanel.add(plottButton);
-		JButton resetButton =  new JButton("Reset");
-		resetButton.setToolTipText("Resets the State to before the Algorithm has runed.");
-		resetButton.addActionListener(actionEvent -> resetAll());
-		buttonPanel.add(resetButton);
-		JButton runButton =  new JButton("Run");
-		runButton.addActionListener(actionEvent -> {
-			Runnable task = () -> run();
-			runThread = new Thread(task);
-			runThread.start();
-		});
-		buttonPanel.add(runButton);
-		return buttonPanel;
-	}
-	private void run() {
-		cancel = false;
-		disableGuiInput(true);
-		startTimer();
-		executePsoAlgoWithCurrentParameters();
-		if(cancel) {
-			resetLast();
-			disableGuiInput(false);
-			return;
-		}
-		printElapsedTime();
-		disableGuiInput(false);
-	}
-	private void disableGuiInput(boolean bool) {
-		control.guiDisable(bool);
-	}
-	
-	private void cancel() {
-		if(runThread.isAlive()) {
-			console.println("");
-			console.println("Cancel run.");
-			cancel = true;
-			progressBar.setValue(0);
-		} else {
-			console.println("Nothing to cancel.");
-		}
-	}
-	private void fitness() {
-		if(runThread.isAlive()) {
-			console.println("Run have to be cancelled First.");
-			return;
-		}
-		initDependentParameter();
-		double currentFitness = evaluatePosition(extractPositionAndAccess(control.getModel()), false);
-		resetChain.removeLast();
-		console.println("Actual Fitnessvalue: " + currentFitness);
-	}
-	private void setSaveFile() {
-		fileChooser.setFileFilter(new FileNameExtensionFilter("File", "txt"));
-		fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
-		int result = fileChooser.showSaveDialog(content);
-		if(result == JFileChooser.APPROVE_OPTION) {
-			console.println("Set save File to:" + fileChooser.getSelectedFile().getAbsolutePath());
-		}
-		
-	}
-	private void plott() {
-		if(db!=null) {
-			console.println("Plott..");
-			db.initFileStream();
-		}else {
-			console.println("No run inistialized.");
-		}
-	}
-	
-	
-	private void resetLast() {
-		if(runThread.isAlive()) {
-			console.println("Run have to be cancelled First.");
-			return;
-		}
-		if(!resetChain.isEmpty()) {
-			console.println("Resetting..");
-			resetState();
-			resetChain.removeLast();
-			control.resetSimulation();
-			updateVisual();
-		}else {
-			console.println("No run inistialized.");
-		}
-	}
-	
-	private void resetAll() {
-		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.");
-		}
-	}
-	private void printParameter() {
-		console.println("SwarmSize:" + swarmSize + ", MaxIter:" + maxIterations + ", Limit:" + limit + ", Dependency:" + dependency + ", Rounds:" + rounds +", DependentParameter: w:"+ w + ", c1:" + c1 + ", c2:" + c2 );
-	}
-	@Override
-	public JPanel getPanel() {
-		return content;
-	}
-	@Override
-	public void setController(Control control) {
-		this.control = control;
-		
-	}
-
-	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;
-		}
-	}
-	private void progressBarStep(){
-		progressBar.setValue(++progressBarCount);
-	}
-	private void calculateProgressBarParameter() {
-		int max = swarmSize * (maxIterations + 1)* rounds + rounds;
-		progressBarCount = 0;
-		progressBar.setValue(0);
-		progressBar.setMaximum(max);
-	}
-	
-	private void startTimer(){
-		startTime = System.currentTimeMillis();
-	}
-	private void printElapsedTime(){
-		long elapsedMilliSeconds = System.currentTimeMillis() - startTime;
-		console.println("Execution Time of Algo in Milliseconds:" + elapsedMilliSeconds);
-	}
-	
-	
-	
-	
-	//Algo Part:
-	/**
-	 * The Execution of the Algo its initialize the missing parameter and execute single Algo runs successively.
-	 */
-	private void executePsoAlgoWithCurrentParameters() {
-		initDependentParameter();
-		calculateProgressBarParameter();
-		printParameter();
-		Best runBest = new Best();
-		runBest.value = Double.MAX_VALUE;
-		db = new RunDataBase();
-		for(int r = 0; r < rounds; r++)
-		{		
-          
-		  List<Double> runList = db.insertNewRun();
-		  Best lastRunBest = executePSOoneTime(runList);
-		  if(cancel)return;
-		  resetState();
-		  if(lastRunBest.value < runBest.value) runBest = lastRunBest;
-		}
-		console.println("AlgoResult:" + runBest.value);
-		//console.println("[" + lastRunBest.position.stream().map(Object::toString).collect(Collectors.joining(", ")) + "]");
-		setState(runBest.position);
-		updateVisual();
-	}
-	/**
-	 * Calculate w, c1, c2
-	 */
-	private void initDependentParameter() {
-		w = 1.0 / (dependency - 1 + Math.sqrt(dependency * dependency - 2 * dependency));
-		c1 = c2 = dependency * w;
-	}
-	/**
-	 *  <p>Algo from Paper:</p><font size="3"><pre>
-	 *  
-	 *  Begin
-	 *  	t = 0; {t: generation index}
-	 *  	initialize particles x<sub>p,i,j</sub>(t);
-	 *  	evaluation x<sub>p,i,j</sub>(t);
-	 *  	while (termination condition &ne; true) do
-	 *  		v<sub>i,j</sub>(t) = update v<sub>i,j</sub>(t); {by Eq. (6)}
-	 *  		x<sub>g,i,j</sub>(t) = update x<sub>g,i,j</sub>(t); {by Eq. (7)}
-	 *  		x<sub>g,i,j</sub>(t) = mutation x<sub>g,i,j</sub>(t); {by Eq. (11)}
-	 *  		x<sub>p,i,j</sub>(t) = decode x<sub>g,i,j</sub>(t); {by Eqs. (8) and (9)}
-	 *  		evaluate x<sub>p,i,j</sub>(t);
-	 *  		t = t + 1;
-	 *  	end while
-	 *  End</pre></font>
-	 *  <p>with:</p><font size="3">
-	 *  
-	 *  x<sub>g,i,j</sub>: genotype ->genetic information -> in continuous space<br>
-	 *  x<sub>p,i,j</sub>: phenotype -> observable characteristics-> in binary space<br>
-	 *  X<sub>g,max</sub>: is the Maximum here set to 4.<br>
-	 *  Eq. (6):v<sub>i,j</sub>(t + 1) = wv<sub>i,j</sub>+c<sub>1</sub>R<sub>1</sub>(P<sub>best,i,j</sub>-x<sub>p,i,j</sub>(t))+c<sub>2</sub>R<sub>2</sub>(g<sub>best,i,j</sub>-x<sub>p,i,j</sub>(t))<br>
-	 *  Eq. (7):x<sub>g,i,j</sub>(t + 1) = x<sub>g,i,j</sub>(t) + v<sub>i,j</sub>(t + 1)<br>
-	 *  Eq. (11):<b>if(</b>rand()&lt;r<sub>mu</sub><b>)then</b> x<sub>g,i,j</sub>(t + 1) = -x<sub>g,i,j</sub>(t + 1)<br>
-	 *  Eq. (8):x<sub>p,i,j</sub>(t + 1) = <b>(</b>rand() &lt; S(x<sub>g,i,j</sub>(t + 1))<b>) ?</b> 1 <b>:</b> 0<br>
-	 *  Eq. (9) Sigmoid:S(x<sub>g,i,j</sub>(t + 1)) := 1/(1 + e<sup>-x<sub>g,i,j</sub>(t + 1)</sup>)<br></font>
-	 *  <p>Parameter:</p>
-	 *  w inertia, calculated from phi(Variable:{@link #dependency})<br>
-	 *  c1:	influence, calculated from phi(Variable:{@link #dependency}) <br>
-	 *  c2:	influence, calculated from phi(Variable:{@link #dependency})<br>
-	 *  r<sub>mu</sub>: probability that the proposed operation is conducted defined by limit(Variable:{@link #limit})<br>
-	 *  
-	 *  
-	 */
-	private Best executePSOoneTime(List<Double> runList) {
-		Best globalBest = new Best();
-		globalBest.position = extractPositionAndAccess(control.getModel());
-		globalBest.value = evaluatePosition(globalBest.position, true);
-		console.println("Start Value:" + globalBest.value);
-		int dimensions = globalBest.position.size();
-		List<Particle> swarm= initializeParticles(dimensions);
-		runList.add(globalBest.value);
-		evaluation(globalBest, swarm);
-		runList.add(globalBest.value);
-		for (int iteration = 0; iteration < maxIterations ; iteration++) {
-			int mutationAllowed = iteration % mutationInterval;
-			for (int particleNumber = 0; particleNumber < swarmSize; particleNumber++) {
-				Particle particle = swarm.get(particleNumber);		
-				
-				if(this.useIntervalMutation) {
-					boolean allowMutation = (Random.nextDouble() <  this.mutateProbabilityInterval);
-					TreeSet<Integer> mutationLocation = null;
-					if(allowMutation)mutationLocation = locationsToMutate(dimensions);
-					for(int index = 0; index < dimensions; index++) {
-						updateVelocity(particle, index, globalBest);
-						updateGenotype(particle, index);
-						if(allowMutation &&mutationAllowed == 0 && iteration != 0 && mutationLocation.contains(index))mutation(particle, index);
-						decode(particle, index);
-					}
-				}else {					
-					for(int index = 0; index < dimensions; index++) {
-						updateVelocity(particle, index, globalBest);
-						updateGenotype(particle, index);
-						if(mutationAllowed == 0 && iteration != 0)mutation(particle, index);
-						decode(particle, index);
-					}
-				}
-			}
-			if(cancel)return null;
-			evaluation(globalBest, swarm);
-			runList.add(globalBest.value);
-		}
-		console.println(" End Value:" + globalBest.value);
-		return globalBest;
-	}
-	private TreeSet<Integer> locationsToMutate(int dimensions) {
-		TreeSet<Integer> mutationLocation = new TreeSet<Integer>(); //sortedSet
-		int maximumAmountOfMutatedBits = Math.max(1, (int)Math.round(((double) dimensions) * this.maxMutationPercent));
-		int randomUniformAmountOfMutatedValues = Random.nextIntegerInRange(1,maximumAmountOfMutatedBits + 1);
-		for(int i = 0; i< randomUniformAmountOfMutatedValues; i++) {
-			boolean success = mutationLocation.add(Random.nextIntegerInRange(0, dimensions));
-			if(!success) i--; //can be add up to some series long loops if maximumAmountOfMutatedBits get closed to problemsize.
-		}
-		//console.println(mutationLocation.toString());
-		return mutationLocation;
-	}
-	/**
-	 * 	Eq. (6):v<sub>i,j</sub>(t + 1) = wv<sub>i,j</sub>+c<sub>1</sub>R<sub>1</sub>(P<sub>best,i,j</sub>-x<sub>p,i,j</sub>(t))+c<sub>2</sub>R<sub>2</sub>(g<sub>best,i,j</sub>-x<sub>p,i,j</sub>(t))<br>
-	 * @param particle
-	 * @param index
-	 * @param globalBest
-	 */
-	private void updateVelocity(Particle particle, int index, Best globalBest) {
-		double r1 = Random.nextDouble();
-		double r2 =	Random.nextDouble();
-		double posValue = particle.xPhenotype.get(index)?1.0:0.0;
-		particle.velocity.set(index, clamp(w*particle.velocity.get(index) + c1*r1*((particle.localBest.position.get(index)?1.0:0.0)  - posValue) + c2*r2*((globalBest.position.get(index)?1.0:0.0)- posValue)) );
-	}
-	/**
-	 * Eq. (7):x<sub>g,i,j</sub>(t + 1) = x<sub>g,i,j</sub>(t) + v<sub>i,j</sub>(t + 1)<br>
-	 * @param particle
-	 * @param index
-	 */
-	private void updateGenotype(Particle particle, int index) {
-		particle.xGenotype.set(index, clamp(particle.xGenotype.get(index) + particle.velocity.get(index)));
-	}
-	/**
-	 * Eq. (11):<b>if(</b>rand()&lt;r<sub>mu</sub><b>)then</b> x<sub>g,i,j</sub>(t + 1) = -x<sub>g,i,j</sub>(t + 1)<br>
-	 * @param particle
-	 * @param index
-	 */
-	private void mutation(Particle particle, int index) {
-		if(Random.nextDouble() < limit) particle.xGenotype.set(index, -particle.xGenotype.get(index));
-	}
-	/**
-	 * Eq. (8):x<sub>p,i,j</sub>(t + 1) = <b>(</b>rand() &lt; S(x<sub>g,i,j</sub>(t + 1))<b>) ?</b> 1 <b>:</b> 0<br>
-	 * @param particle
-	 * @param index
-	 */
-	private void decode(Particle particle, int index) {
-		particle.xPhenotype.set(index, Random.nextDouble() < Sigmoid(particle.xGenotype.get(index)));
-	}
-	/**
-	 * Eq. (9) Sigmoid:S(x<sub>g,i,j</sub>(t + 1)) := 1/(1 + e<sup>-x<sub>g,i,j</sub>(t + 1)</sup>)<br></font>
-	 * @param value
-	 * @return
-	 */
-	private double Sigmoid(double value) {
-		return 1.0 / (1.0 + Math.exp(-value));
-	}
-
-	/**
-	 * To clamp X<sub>g,j,i</sub> and v<sub>i,j</sub> in Range [-X<sub>g,max</sub>|+X<sub>g,max</sub>] with {X<sub>g,max</sub>= 4}
-	 * @param value
-	 * @return
-	 */
-	private double clamp(double value) {
-		return Math.max(-8.0, Math.min(8.0, value));
-	}
-	/**
-	 * 
-	 * @param j maximum index of position in the particle
-	 * @return
-	 */
-	private List<Particle> initializeParticles(int j) {
-		List<Particle> swarm = new ArrayList<Particle>();
-		//Create The Particle
-		for (int particleNumber = 0; particleNumber < swarmSize; particleNumber++){
-			//Create a Random position
-			List<Boolean> aRandomPosition = new ArrayList<Boolean>();
-			for (int index = 0; index < j; index++){
-				aRandomPosition.add(Random.nextBoolean());
-			}
-			swarm.add(new Particle(aRandomPosition));
-		}
-		return swarm;
-	}
-	/**
-	 * Evaluate each particle and update the global Best position;
-	 * @param globalBest
-	 * @param swarm
-	 */
-	private void evaluation(Best globalBest, List<Particle> swarm) {
-		for(Particle p: swarm) {
-			double localEvaluationValue = evaluatePosition(p.xPhenotype, true);
-			p.checkNewEvaluationValue(localEvaluationValue);
-			if(localEvaluationValue < globalBest.value) {
-				globalBest.value = localEvaluationValue;
-				globalBest.position = p.localBest.position;
-			}
-		}
-	}
-	/**
-	 * Evaluate a position.
-	 * @param position
-	 * @return
-	 */
-	private double evaluatePosition(List<Boolean> position, boolean doIncreaseCounter) {
-		setState(position);
-		if(doIncreaseCounter)progressBarStep();
-		control.calculateStateOnlyForCurrentTimeStep();
-		DecoratedState actualstate = control.getSimManager().getActualDecorState();		
-		return getFitnessValueForState(actualstate);
-	}
-	/**
-	 * Calculate the Fitness(Penelty) Value for a state (alias the calculated Position).
-	 * TODO: Make me better Rolf.
-	 * @param state
-	 * @return
-	 */
-	public static double getFitnessValueForState(DecoratedState state) {
-		double fitness = 0.0;
-		double nw_fitness =0.0;
-		double object_fitness = 0.0;
-		
-		// calculate network_fitness
-		for(DecoratedNetwork net : state.getNetworkList()) {
-			float production = net.getSupplierList().stream().map(supplier -> supplier.getEnergyToSupplyNetwork()).reduce(0.0f, (a, b) -> a + b);
-			float consumption = net.getConsumerList().stream().map(con -> con.getEnergyNeededFromNetwork()).reduce(0.0f, (a, b) -> a + b);
-			nw_fitness += Math.abs((production - consumption)/100); //Energy is now everywhere positive
-		}
-		
-		// calculate object_fitness
-		for(DecoratedNetwork net : state.getNetworkList()) {
-			object_fitness += net.getConsumerList().stream().map(con -> holonObjectSupplyPenaltyFunction(con.getSupplyBarPercentage()) + inactiveHolonElementPenalty(con.getModel())).reduce(0.0, (a, b) -> (a + b));
-			//warum war das im network fitness und nicht hier im Object fitness??
-			object_fitness += net.getConsumerList().stream().map(con -> StateToDouble(con.getState())).reduce(0.0, (a,b) -> (a+b));
-			//System.out.console.println("objectfitness for statestuff: " + object_fitness);
-			//object_fitness += net.getPassivNoEnergyList().stream().map(con -> 1000.0).reduce(0.0, (a, b) -> (a + b));
-			object_fitness += net.getPassivNoEnergyList().stream().map(sup -> inactiveHolonElementPenalty(sup.getModel())).reduce(0.0, (a, b) -> (a + b));
-			object_fitness += net.getSupplierList().stream().map(sup -> inactiveHolonElementPenalty(sup.getModel())).reduce(0.0, (a, b) -> (a + b));
-			object_fitness += net.getConsumerSelfSuppliedList().stream().map(con -> inactiveHolonElementPenalty(con.getModel())).reduce(0.0, (a, b) -> (a + b));
-		}
-		fitness = nw_fitness + object_fitness;
-		return fitness;
-	}
-
-	
-	/**
-	 * Untouched:
-	 * Function that returns the fitness depending on the number of elements deactivated in a single holon object
-	 * @param obj Holon Object that contains Holon Elements
-	 * @return fitness value for that object depending on the number of deactivated holon elements
-	 */
-	private static double inactiveHolonElementPenalty(HolonObject obj) {
-		float result = 0;
-		int activeElements = obj.getNumberOfActiveElements();
-		int maxElements = obj.getElements().size();
-		
-		//result = (float) Math.pow((maxElements -activeElements),2)*10;
-		result = (float) Math.pow(5, 4* ( (float) maxElements - (float) activeElements)/ (float) maxElements) - 1;
-		//System.out.console.println("max: " + maxElements + " active: " + activeElements + " results in penalty: " + result);
-	return result;
-		
-	}
-	/**
-	 * Untouched:
-	 * Calculates a penalty value based on the HOs current supply percentage
-	 * @param supplyPercentage
-	 * @return
-	 */
-	private static double holonObjectSupplyPenaltyFunction(float supplyPercentage) {
-		double result = 0;
-		/*if(supplyPercentage == 1)
-			return result;
-		else if(supplyPercentage < 1 && supplyPercentage >= 0.25) // undersupplied inbetween 25% and 100%
-			result = (float) Math.pow(1/supplyPercentage, 2);
-		else if (supplyPercentage < 0.25) //undersupplied with less than 25%
-			result = (float) Math.pow(1/supplyPercentage,2);
-		else if (supplyPercentage < 1.25)  //Oversupplied less than 25%
-			result = (float) Math.pow(supplyPercentage,3) ;
-		else result = (float) Math.pow(supplyPercentage,4); //Oversupplied more than 25%
-		
-		
-		if(Float.isInfinite(result) || Float.isNaN(result))
-			result = 1000;
-	*/
-		if(supplyPercentage <= 1.0) {
-			result = Math.pow(5,((100 - (supplyPercentage*100))/50 + 2)) - Math.pow(5, 2);
-		}
-		else {
-			result = Math.pow(6,((100 - (supplyPercentage*100))/50 + 2)) - Math.pow(6, 2);
-		}
-		
-		return result;
-	}
-	/**
-	 * If you want to get in touch with a reliable state? Working function not in use currently.
-	 * @param state
-	 * @return
-	 */
-	private static double StateToDouble(HolonObjectState state) {
-		switch (state) {
-		case NOT_SUPPLIED:
-			return 150.0;
-		case NO_ENERGY:
-			return 150.0;
-		case OVER_SUPPLIED:
-			return 100.0;
-		case PARTIALLY_SUPPLIED:
-			return 100.0;
-		case PRODUCER:
-			return 0;
-		case SUPPLIED:
-			return 0;
-		default:
-			return 0;
-		}
-	}
-	
-
-	/**
-	 * 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
-	 */
-	private List<Boolean> extractPositionAndAccess(Model model) {
-		List<Boolean> initialState = new ArrayList<Boolean>(); 
-		access= new HashMap<Integer, AccessWrapper>();
-		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.put(positionToInit.size() - 1 , new AccessWrapper(hE));
-				}
-			}
-			else if (aCps instanceof HolonSwitch) {
-				HolonSwitch sw = (HolonSwitch) aCps;
-				positionToInit.add(sw.getState(timeStep));
-				access.put(positionToInit.size() - 1 , new AccessWrapper(sw));
-			}
-			else if(aCps instanceof CpsUpperNode) {
-				rollOutNodes(((CpsUpperNode)aCps).getNodes(), positionToInit ,timeStep );
-			}
-		}
-	}
-	/**
-	 * To let the User See the current state without touching the Canvas.
-	 */
-	private void updateVisual() {
-		control.calculateStateAndVisualForCurrentTimeStep();
-		control.updateCanvas();
-	}
-	/**
-	 * 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) {
-		for(int i = 0;i<position.size();i++) {
-			access.get(i).setState(position.get(i));
-		}
-	}
-	
-	/**
-	 * A Database for all Global Best(G<sub>Best</sub>) Values in a execution of a the Algo. For Easy Printing.
-	 */
-	public class RunDataBase {
-		List<List<Double>> allRuns = new ArrayList<List<Double>>();
-
-		
-		
-		/**
-		 * Initialize The Stream before you can write to a File.
-		 */
-		public void initFileStream() {
-			File file = fileChooser.getSelectedFile();
-			try {
-				file.createNewFile();
-				BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
-					    new FileOutputStream(file, append), "UTF-8"));
-				printToStream(out);
-				out.close();
-			} catch (IOException e) {
-				console.println(e.getMessage());
-			}
-		}
-		
-		/**
-		 * 
-		 * TODO: Rolf Change this method to suit your Python script respectively. 
-		 * A run have maxIterations + 2 values. As described: First is the InitialState Value, 
-		 * Second is The best Value after the swarm is Initialized not have moved jet, and then comes the Iterations that described 
-		 * each step of movement from the swarm.
-		 */
-		public void printToStream(BufferedWriter out) throws IOException {
-			try {
-				out.write(maxIterations + 2 + "," + allRuns.size() + "," + swarmSize);
-				out.newLine();
-
-			}
-			catch(IOException e) {
-				console.println(e.getMessage());
-			}
-			allRuns.forEach(run -> {
-				try {
-					out.write( run.stream().map(Object::toString).collect(Collectors.joining(", ")));
-					out.newLine();
-				} catch (IOException e) {
-					console.println(e.getMessage());
-				}
-			} );
-		}
-		
-		public List<Double> insertNewRun(){
-			List<Double> newRun = new ArrayList<Double>();
-			allRuns.add(newRun);
-			return newRun;
-		}
-	}
-	
-	
-	/**
-	 * To give the Local Best of a Partice(P<sub>Best</sub>) or the Global Best(G<sub>Best</sub>) a Wrapper to have Position And Evaluation Value in one Place.
-	 */
-	private class Best{
-		public double value;
-		public  List<Boolean> position;
-		public Best(){
-		}
-	}
-	/**
-	 * 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);
-		}
-	}
-	/**
-	 * Class to represent a Particle.
-	 */
-	private class Particle{
-		/**
-		 * The velocity of a particle.
-		 */
-		public List<Double> velocity;
-		/**
-		 * The positions genotype.
-		 */
-		public List<Double> xGenotype;
-		/**
-		 * The positions phenotype. Alias the current position.
-		 */
-		public List<Boolean> xPhenotype;
-		
-		public Best localBest;
-		
-		Particle(List<Boolean> position){
-			this.xPhenotype = position;
-			//Init velocity, xGenotype with 0.0 values.
-			this.velocity = position.stream().map(bool -> 0.0).collect(Collectors.toList());
-			this.xGenotype = position.stream().map(bool -> 0.0).collect(Collectors.toList());
-			localBest = new Best();
-			localBest.value = Double.MAX_VALUE;
-		}
-		public void checkNewEvaluationValue(double newEvaluationValue) {
-			if(newEvaluationValue < localBest.value) {
-				localBest.value = newEvaluationValue;
-				localBest.position = xPhenotype.stream().map(bool -> bool).collect(Collectors.toList());
-			}
-		}
-		public String toString() {
-			return "Particle with xPhenotype(Position), xGenotype, velocity:[" 
-					+ listToString(xPhenotype) + "],[" + listToString(xGenotype) + "],[" 
-					+ listToString(velocity) + "]";
-		}
-		private <Type> String listToString(List<Type> list) {
-			return list.stream().map(Object::toString).collect(Collectors.joining(", "));
-		}
-		
-	}
-	
-	/**
-	* To create Random and maybe switch the random generation in the future.
-	*/
-	private 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();
-		}
-	}
-	
-}

+ 85 - 3
src/exampleAlgorithms/PsoAlgorithm2.java

@@ -7,7 +7,7 @@ import java.util.stream.Collectors;
 
 import javax.swing.JFrame;
 
-import api.AlgorithmFramework;
+
 import api.AlgorithmFrameworkFlex;
 import ui.model.DecoratedState;
 
@@ -238,13 +238,32 @@ public class PsoAlgorithm2 extends AlgorithmFrameworkFlex{
 			boolean success = mutationLocation.add(Random.nextIntegerInRange(0, dimensions));
 			if(!success) i--; //can be add up to some series long loops if maximumAmountOfMutatedBits get closed to problemsize.
 		}
-		//console.println(mutationLocation.toString());
 		return mutationLocation;
 	}
 	
 	
 	
-	
+		@Override
+	protected String algoInformationToPrint() {
+//			private int swarmSize = 20; 
+//			private int maxIterations = 100; 
+//			private double limit = 0.01; 
+//			private double dependency = 2.07; 
+//			private int mutationInterval = 1;
+//			private boolean useIntervalMutation = true;
+//			private double mutateProbabilityInterval = 0.01;
+//			private double maxMutationPercent = 0.01;
+		return "PsoAlgo"+ " Rounds:" + rounds 
+				+ " maxIterations:" + maxIterations
+				+ " swarmSize:" + swarmSize
+				+ " dependency:" +  dependency
+				+ " mutationInterval:" +  mutationInterval
+				+ (useIntervalMutation? 
+						(" mutateProbabilityInterval:" +  mutateProbabilityInterval
+						+ " maxMutationPercent:" +  maxMutationPercent)
+						: 
+						(" limit(mutationProbability):" +  limit));
+	}
 	
 	
 	
@@ -315,6 +334,69 @@ public class PsoAlgorithm2 extends AlgorithmFrameworkFlex{
 		}
 		
 	}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+	@Override
+	protected String plottFileName() {
+		return "plottPsoAlgo.txt";
+	}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+