Browse Source

Flex Update

Tom 4 years ago
parent
commit
5307f18aa8

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


+ 3 - 0
src/api/AlgorithmFramework.java

@@ -315,6 +315,7 @@ public abstract class AlgorithmFramework implements AddOn{
 	
 	protected double evaluatePosition(List<Boolean> positionToEvaluate) {
 		runProgressbar.step();
+		
 		setState(positionToEvaluate);
 		control.calculateStateOnlyForCurrentTimeStep();
 		DecoratedState actualstate = control.getSimManager().getActualDecorState();
@@ -348,7 +349,9 @@ public abstract class AlgorithmFramework implements AddOn{
 			if(roundBest.fitness < runBest.fitness) runBest = roundBest;
 		}
 		printElapsedTime();
+		
 		setState(runBest.position);
+		
 		updateVisual();
 		console.println("AlgoResult:" + runBest.fitness);
 		runProgressbar.stop();

+ 684 - 0
src/api/AlgorithmFrameworkFlex.java

@@ -0,0 +1,684 @@
+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.Flexibility;
+import classes.HolonElement;
+import classes.HolonObject;
+import classes.HolonSwitch;
+import ui.controller.Control;
+import ui.controller.FlexManager.FlexState;
+import ui.controller.FlexManager.FlexWrapper;
+import ui.model.DecoratedGroupNode;
+import ui.model.DecoratedState;
+import ui.model.Model;
+import ui.view.Console;
+
+public abstract class AlgorithmFrameworkFlex 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 AlgorithmFrameworkFlex(){
+		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();
+		control.getSimManager().resetFlexManagerForTimeStep(control.getModel().getCurIteration());
+		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();
+		control.getSimManager().resetFlexManagerForTimeStep(control.getModel().getCurIteration());
+		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() {
+		control.getSimManager().resetFlexManagerForTimeStep(control.getModel().getCurIteration());
+		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);
+		for(FlexWrapper flex :control.getSimManager().getActualFlexManager().getAllFlexWrapperWithState(FlexState.OFFERED)){
+			access.add(new AccessWrapper(flex.getFlex()));
+			initialState.add(false);
+		}
+		console.println(access.stream().map(Object::toString).collect(Collectors.joining(", ")));
+		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;
+		public static final int FLEXIBILITY = 2;
+		private int type;
+		private HolonSwitch hSwitch;
+		private HolonElement hElement;
+		private Flexibility flex;
+		public AccessWrapper(HolonSwitch hSwitch){
+			type = SWITCH;
+			this.hSwitch = hSwitch;
+		}
+		public AccessWrapper(HolonElement hElement){
+			type = HOLONELEMENT;
+			this.hElement = hElement;
+		}
+		
+		public AccessWrapper(Flexibility flex){
+			type = FLEXIBILITY;
+			this.flex = flex;
+		}
+		
+		public void setState(boolean state) {
+			switch(type) {
+				case HOLONELEMENT:
+					hElement.setActive(state);
+					break;
+				case SWITCH:
+					hSwitch.setManualMode(true);
+					hSwitch.setManualState(state);
+					break;
+				case FLEXIBILITY:
+					
+					if(state) {
+						console.println("Flex True");
+						if(flex == null) console.println("flex == null");
+						if(control.getSimManager() == null) console.println("control.getSimManager() == null");
+						if(control.getSimManager().getActualFlexManager() == null) console.println("control.getSimManager().getActualFlexManager() == null");
+						control.getSimManager().getActualFlexManager().orderFlex(flex);
+					}else {
+						console.println("Flex false");
+					}
+					break;
+				default:
+				
+			}
+		}
+		
+		public String typeString() {
+			switch(type) {
+				case HOLONELEMENT:
+					return "HOLONELEMENT";
+				case SWITCH:
+					return "SWITCH";
+				case FLEXIBILITY:
+					return "FLEXIBILITY";
+				default:
+					return "unknown";
+			}
+		}
+		
+		public String toString() {
+			return "[" +  typeString() + "]";
+		}
+	}
+	
+	
+	
+	
+	/**
+	* 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;
+		}
+	}
+}

+ 2 - 1
src/exampleAlgorithms/AcoAlgorithm2.java

@@ -8,9 +8,10 @@ import javax.swing.JFrame;
 import javax.swing.JPanel;
 
 import api.AlgorithmFramework;
+import api.AlgorithmFrameworkFlex;
 import ui.model.DecoratedState;
 
-public class AcoAlgorithm2 extends AlgorithmFramework{
+public class AcoAlgorithm2 extends AlgorithmFrameworkFlex{
 	
 	//Parameter for Algo with default Values:
 	/**

+ 9 - 2
src/exampleAlgorithms/Evaluation.java

@@ -3,6 +3,8 @@ package exampleAlgorithms;
 import classes.HolonObject;
 import ui.model.DecoratedNetwork;
 import ui.model.DecoratedState;
+import ui.controller.FlexManager.FlexState;
+import ui.controller.FlexManager.FlexWrapper;
 import ui.model.DecoratedHolonObject.HolonObjectState;
 
 public class Evaluation {
@@ -17,7 +19,7 @@ public class Evaluation {
 		double fitness = 0.0;
 		double nw_fitness =0.0;
 		double object_fitness = 0.0;
-		
+		double flexFitness = 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);
@@ -36,7 +38,12 @@ public class Evaluation {
 			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;
+		// calculate flexibility fitness
+		for(FlexWrapper flexWrapper :state.getFlexManager().getAllFlexWrapperWithState(FlexState.IN_USE)) {
+			flexFitness += flexWrapper.getFlex().cost / (double)flexWrapper.getFlex().getDuration();
+		}
+		
+		fitness = nw_fitness + object_fitness + flexFitness;
 		return fitness;
 	}
 

+ 2 - 1
src/exampleAlgorithms/GaAlgorithm2.java

@@ -8,9 +8,10 @@ import java.util.TreeSet;
 import javax.swing.JFrame;
 
 import api.AlgorithmFramework;
+import api.AlgorithmFrameworkFlex;
 import ui.model.DecoratedState;
 
-public class GaAlgorithm2 extends AlgorithmFramework{
+public class GaAlgorithm2 extends AlgorithmFrameworkFlex{
 
 	/**
 	 * Should be even.

+ 2 - 1
src/exampleAlgorithms/PsoAlgorithm2.java

@@ -8,9 +8,10 @@ import java.util.stream.Collectors;
 import javax.swing.JFrame;
 
 import api.AlgorithmFramework;
+import api.AlgorithmFrameworkFlex;
 import ui.model.DecoratedState;
 
-public class PsoAlgorithm2 extends AlgorithmFramework{
+public class PsoAlgorithm2 extends AlgorithmFrameworkFlex{
 	//Parameter for Algo with default Values:
 	private int swarmSize = 20; 
 	private int maxIterations = 100; 

+ 16 - 1
src/ui/controller/FlexManager.java

@@ -78,7 +78,10 @@ public class FlexManager {
 			if(flexToOrder!=null)flexToOrder.order();
 		});
 	}
-	
+	public void orderFlex(Flexibility flex) {
+		FlexWrapper flexToOrder =  accessFlexMap.get(flex);
+		if(flexToOrder!=null)flexToOrder.order();
+	}
 	public boolean isAFlexInUseOfHolonElement(HolonElement ele) {
 		return ele.flexList.stream().filter(flex -> this.accessFlexMap.containsKey(flex)).anyMatch(flex -> (this.accessFlexMap.get(flex).getState() == FlexState.IN_USE));
 	}
@@ -141,6 +144,18 @@ public class FlexManager {
 			}
 			return false;
 		}
+		public boolean cancel() {
+			if(allFlexesOrderedThisTimeStep.contains(flex)) {
+				state=FlexState.OFFERED;
+				durationEndTime = -1;
+				coolDownEndTime = -1;
+				allFlexesOrderedThisTimeStep.remove(flex);
+				accessFlexMap.values().stream().filter(flexWrapper -> (flexWrapper.getFlex().getElement() == flex.getElement() && flexWrapper != this)).forEach(otherFlex -> otherFlex.revalidateState());
+				
+				return true;
+			}
+			return false;
+		}
 		public int remainingTimeTillActivation() {
 			return Math.max(0, coolDownEndTime - timeStep);
 		}

+ 11 - 1
src/ui/controller/SimulationManager.java

@@ -57,6 +57,12 @@ public class SimulationManager {
 	public SimulationManager(Model m) {
 		model = m;
 	}
+	
+	
+	
+	
+	
+	
 	/**
 	 * calculates the flow of the edges and the supply for objects and consider old timesteps for burned cables.
 	 *
@@ -125,7 +131,7 @@ public class SimulationManager {
 			leftOverDecoratedCables.add(new DecoratedCable(cable.getModel(), cable.getState(), 0.0f));
 		}
 		ArrayList<DecoratedSwitch> listOfDecoratedSwitches = decorateSwitches(minimumModel, timestep);
-		DecoratedState stateFromThisTimestep = new DecoratedState(decorNetworks, leftOverDecoratedCables, listOfDecoratedSwitches, timestep);
+		DecoratedState stateFromThisTimestep = new DecoratedState(decorNetworks, leftOverDecoratedCables, listOfDecoratedSwitches, flexManagerFromActual, timestep);
 		saves.put(timestep, stateFromThisTimestep);
 		if(updateVisual)savesVisual.put(timestep, new VisualRepresentationalState(stateFromThisTimestep, minimumModel));
 	}
@@ -261,6 +267,10 @@ public class SimulationManager {
 	public void resetFlexManager(){
 		savesFlexManger.clear();
 	}
+	public void resetFlexManagerForTimeStep(int timestep) {
+		FlexManager newFlexManager = new FlexManager(model, timestep, savesFlexManger.getOrDefault(timestep-1, null));
+		savesFlexManger.put(timestep, newFlexManager);
+	}
 	
 	public DecoratedState getDecorState(int timestep) {
 		return saves.getOrDefault(timestep, null);

+ 8 - 1
src/ui/model/DecoratedState.java

@@ -2,17 +2,21 @@ package ui.model;
 
 import java.util.ArrayList;
 
+import ui.controller.FlexManager;
+
 
 public class DecoratedState {
 	int timestepOfState;
 	ArrayList<DecoratedNetwork> networkList;
 	ArrayList<DecoratedCable> leftOverEdges;
 	ArrayList<DecoratedSwitch> decoratedSwitches;
-	public DecoratedState(ArrayList<DecoratedNetwork> networkList, ArrayList<DecoratedCable> leftOverEdges, ArrayList<DecoratedSwitch> decoratedSwitches , int timestepOfState){
+	FlexManager flexManager;
+	public DecoratedState(ArrayList<DecoratedNetwork> networkList, ArrayList<DecoratedCable> leftOverEdges, ArrayList<DecoratedSwitch> decoratedSwitches, FlexManager flexManager , int timestepOfState){
 		this.networkList = networkList;
 		this.leftOverEdges = leftOverEdges;
 		this.decoratedSwitches = decoratedSwitches;
 		this.timestepOfState = timestepOfState;
+		this.flexManager = flexManager;
 	}
 	public ArrayList<DecoratedNetwork> getNetworkList() {
 		return networkList;
@@ -23,6 +27,9 @@ public class DecoratedState {
 	public ArrayList<DecoratedSwitch> getDecoratedSwitches() {
 		return decoratedSwitches;
 	}
+	public FlexManager getFlexManager() {
+		return flexManager;
+	}
 	public int getTimestepOfState() {
 		return timestepOfState;
 	}

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