Browse Source

Fitness, Reset+Fitenss, Plotting

Tom 4 years ago
parent
commit
0bdca25e6f

File diff suppressed because it is too large
+ 0 - 1
plott.txt


+ 99 - 14
src/exampleAlgorithms/AcoAlgorithm.java

@@ -5,6 +5,11 @@ 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;
@@ -19,6 +24,7 @@ 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;
@@ -36,6 +42,7 @@ 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;
@@ -74,10 +81,9 @@ public class AcoAlgorithm implements Algorithm {
 		//Parameter defined by Algo
 		private HashMap<Integer, AccessWrapper> access;
 		LinkedList<List<Boolean>> resetChain = new LinkedList<List<Boolean>>();
-		private List<Boolean> initialState;
 		private List<HolonSwitch> switchList;
 		private List<HolonObject> objectList;
-		
+		private boolean append = false;
 		//Gui Part:
 		private Control  control;
 		private Console console = new Console();
@@ -86,9 +92,10 @@ public class AcoAlgorithm implements Algorithm {
 		private JProgressBar progressBar = new JProgressBar();
 		private int progressBarCount = 0;
 		private long startTime;
-		private Thread runThread;
-
-
+		private Thread runThread = new Thread();
+		private RunDataBase db;
+		//Parameter for Plotting (Default Directory in Constructor)
+		private JFileChooser fileChooser = new JFileChooser();
 
 
 
@@ -107,7 +114,6 @@ public class AcoAlgorithm implements Algorithm {
 		      newFrame.pack();
 		      newFrame.setVisible(true);
 		      newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
-		      
 		}
 		public AcoAlgorithm() {
 			content.setLayout(new BorderLayout());
@@ -116,6 +122,8 @@ public class AcoAlgorithm implements Algorithm {
 			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());
@@ -260,6 +268,13 @@ public class AcoAlgorithm implements Algorithm {
 		}
 		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());
@@ -291,6 +306,16 @@ public class AcoAlgorithm implements Algorithm {
 			}
 		}
 		
+		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);
@@ -332,7 +357,15 @@ public class AcoAlgorithm implements Algorithm {
 			}
 		}
 		
-		
+		private void plott() {
+			if(db!=null) {
+				console.println("Plott..");
+				db.initFileStream();
+			}else {
+				console.println("No run inistialized.");
+			}
+		}
+
 		
 		private void disableGuiInput(boolean bool) {
 			control.guiDiable(bool);
@@ -396,12 +429,14 @@ public class AcoAlgorithm implements Algorithm {
 			startTimer();
 			Individual runBest = new Individual();
 			runBest.fitness = Double.MAX_VALUE;
+			db = new RunDataBase();
 			for(int r = 0; r < rounds; r++)
 			{		
-			  Individual  roundBest = executeAcoAlgo();
-			  if(cancel)return;
-			  resetState();
-			  if(roundBest.fitness < runBest.fitness) runBest = roundBest;
+				List<Double> runList = db.insertNewRun();
+				Individual  roundBest = executeAcoAlgo(runList);
+				if(cancel)return;
+				resetState();
+				if(roundBest.fitness < runBest.fitness) runBest = roundBest;
 			}
 			printElapsedTime();
 			setState(runBest.position);
@@ -431,11 +466,12 @@ public class AcoAlgorithm implements Algorithm {
 		 * 	}
 		 * @return 
 		 */
-		private Individual executeAcoAlgo() {
+		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();
@@ -452,6 +488,7 @@ public class AcoAlgorithm implements Algorithm {
 					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);
@@ -552,7 +589,7 @@ public class AcoAlgorithm implements Algorithm {
 			Model model = control.getModel();
 			switchList = new ArrayList<HolonSwitch>();
 			objectList = new ArrayList<HolonObject>();
-			initialState = new ArrayList<Boolean>();
+			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); 
@@ -675,7 +712,55 @@ public class AcoAlgorithm implements Algorithm {
 				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;

+ 101 - 12
src/exampleAlgorithms/GaAlgorithm.java

@@ -6,6 +6,11 @@ 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;
@@ -24,6 +29,7 @@ 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;
@@ -42,6 +48,7 @@ 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;
@@ -74,12 +81,12 @@ public class GaAlgorithm implements Algorithm {
 		private DecoratedGroupNode dGroupNode = null;
 		private boolean cancel = false;
 		private boolean moreInformation = false;
-		
+		private boolean append = false;
 
 		//Parameter defined by Algo
 		private HashMap<Integer, AccessWrapper> access;
 		LinkedList<List<Boolean>> resetChain = new LinkedList<List<Boolean>>();
-		private List<Boolean> initialState;
+
 		private List<HolonSwitch> switchList;
 		private List<HolonObject> objectList;
 		
@@ -91,11 +98,13 @@ public class GaAlgorithm implements Algorithm {
 		private JProgressBar progressBar = new JProgressBar();
 		private int progressBarCount = 0;
 		private long startTime;
-		private Thread runThread;
-
+		private Thread runThread = new Thread();
+		private RunDataBase db;
 
 
 
+		//Parameter for Plotting (Default Directory in Constructor)
+		private JFileChooser fileChooser = new JFileChooser();
 
 		
 		
@@ -120,6 +129,8 @@ public class GaAlgorithm implements Algorithm {
 			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());
@@ -381,6 +392,13 @@ public class GaAlgorithm implements Algorithm {
 		
 		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());
@@ -453,13 +471,28 @@ public class GaAlgorithm implements Algorithm {
 			}
 		}
 		
-		
+		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.guiDiable(bool);
 		}
 		
-		
+		private void plott() {
+			if(db!=null) {
+				console.println("Plott..");
+				db.initFileStream();
+			}else {
+				console.println("No run inistialized.");
+			}
+		}
 
 		
 		
@@ -518,12 +551,14 @@ public class GaAlgorithm implements Algorithm {
 			startTimer();
 			Individual runBest = new Individual();
 			runBest.fitness = Double.MAX_VALUE;
+			db = new RunDataBase();
 			for(int r = 0; r < rounds; r++)
 			{		
-			  Individual  roundBest = executeGaAlgo();
-			  if(cancel)return;
-			  resetState();
-			  if(roundBest.fitness < runBest.fitness) runBest = roundBest;
+				List<Double> runList = db.insertNewRun();
+				Individual  roundBest = executeGaAlgo(runList);
+				if(cancel)return;
+				resetState();
+				if(roundBest.fitness < runBest.fitness) runBest = roundBest;
 			}
 			printElapsedTime();
 			setState(runBest.position);
@@ -562,11 +597,12 @@ public class GaAlgorithm implements Algorithm {
 		 * 	}
 		 * @return 
 		 */
-		private Individual executeGaAlgo() {
+		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();
@@ -580,6 +616,7 @@ public class GaAlgorithm implements Algorithm {
 					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);
@@ -737,7 +774,7 @@ public class GaAlgorithm implements Algorithm {
 			Model model = control.getModel();
 			switchList = new ArrayList<HolonSwitch>();
 			objectList = new ArrayList<HolonObject>();
-			initialState = new ArrayList<Boolean>();
+			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); 
@@ -861,6 +898,58 @@ public class GaAlgorithm implements Algorithm {
 			}
 		}
 		
+		/**
+		 * 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;

+ 43 - 29
src/exampleAlgorithms/PSOAlgorithm.java

@@ -17,6 +17,7 @@ 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;
@@ -81,7 +82,7 @@ public class PSOAlgorithm implements Algorithm {
 	
 	//Parameter defined by Algo
 	private HashMap<Integer, AccessWrapper> access;
-	private List<Boolean> initialState;
+	LinkedList<List<Boolean>> resetChain = new LinkedList<List<Boolean>>();
 	private double c1, c2, w;
 	private RunDataBase db;
 	
@@ -97,7 +98,7 @@ public class PSOAlgorithm implements Algorithm {
 	private JProgressBar progressBar = new JProgressBar();
 	private int progressBarCount = 0;
 	private long startTime;
-	private Thread runThread;
+	private Thread runThread = new Thread();
 	private boolean cancel = false;
 	
 	
@@ -386,7 +387,7 @@ public class PSOAlgorithm implements Algorithm {
 		buttonPanel.add(plottButton);
 		JButton resetButton =  new JButton("Reset");
 		resetButton.setToolTipText("Resets the State to before the Algorithm has runed.");
-		resetButton.addActionListener(actionEvent -> reset());
+		resetButton.addActionListener(actionEvent -> resetAll());
 		buttonPanel.add(resetButton);
 		JButton runButton =  new JButton("Run");
 		runButton.addActionListener(actionEvent -> {
@@ -403,7 +404,7 @@ public class PSOAlgorithm implements Algorithm {
 		startTimer();
 		executePsoAlgoWithCurrentParameters();
 		if(cancel) {
-			reset();
+			resetLast();
 			disableGuiInput(false);
 			return;
 		}
@@ -425,8 +426,13 @@ public class PSOAlgorithm implements Algorithm {
 		}
 	}
 	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() {
@@ -446,10 +452,35 @@ public class PSOAlgorithm implements Algorithm {
 			console.println("No run inistialized.");
 		}
 	}
-	private void reset() {
-		if(initialState != null) {
+	
+	
+	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.");
@@ -828,9 +859,10 @@ public class PSOAlgorithm implements Algorithm {
 	 * @return
 	 */
 	private List<Boolean> extractPositionAndAccess(Model model) {
-		initialState = new ArrayList<Boolean>(); 
+		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;
 	}
 	/**
@@ -868,7 +900,7 @@ public class PSOAlgorithm implements Algorithm {
 	 * Sets the Model back to its original State before the LAST run.
 	 */
 	private void resetState() {
-		setState(initialState);
+		setState(resetChain.getLast());
 	}
 	
 	/**
@@ -884,11 +916,9 @@ public class PSOAlgorithm implements Algorithm {
 	/**
 	 * A Database for all Global Best(G<sub>Best</sub>) Values in a execution of a the Algo. For Easy Printing.
 	 */
-	private class RunDataBase {
-		List<List<Double>> allRuns;
-		RunDataBase(){
-			allRuns = new ArrayList<List<Double>>();
-		}
+	public class RunDataBase {
+		List<List<Double>> allRuns = new ArrayList<List<Double>>();
+
 		
 		
 		/**
@@ -931,24 +961,8 @@ public class PSOAlgorithm implements Algorithm {
 					console.println(e.getMessage());
 				}
 			} );
-		/*	out.write("AverageRun:");
-			out.newLine();
-			out.write(calculateAverageRun().stream().map(Object::toString).collect(Collectors.joining(", ")));
-			out.newLine();
-			*/
 		}
 		
-		private List<Double> calculateAverageRun(){
-			int amountOfRuns = allRuns.size();
-			List<Double> newAverageRun = new ArrayList<Double>();
-			for(int iteration = 0; iteration < maxIterations + 2; iteration++) {
-				final int  currentIter = iteration;
-				double sum = 0.0;
-				sum = allRuns.stream().map(run -> run.get(currentIter)).reduce(0.0, (a, b) -> a + b);
-				newAverageRun.add(sum / amountOfRuns);
-			}
-			return newAverageRun;
-		}
 		public List<Double> insertNewRun(){
 			List<Double> newRun = new ArrayList<Double>();
 			allRuns.add(newRun);

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