Tom 5 yıl önce
ebeveyn
işleme
fc4f7dbb76
84 değiştirilmiş dosya ile 6551 ekleme ve 3470 silme
  1. 1 0
      .gitignore
  2. BIN
      res/Button_Images/Close.png
  3. BIN
      res/Button_Images/Leaf.png
  4. BIN
      res/Button_Images/Open.png
  5. BIN
      res/Button_Images/iconAlgo.png
  6. BIN
      res/Button_Images/iconOutliner.png
  7. BIN
      res/Images/Thumbs.db
  8. BIN
      res/Images/arrowUp.png
  9. BIN
      res/Images/node.png
  10. BIN
      res/Images/replace.png
  11. 14 0
      src/api/Algorithm.java
  12. 0 16
      src/api/CpsAlgorithm.java
  13. 2 0
      src/classes/AbstractCpsObject.java
  14. 0 11
      src/classes/Constants.java
  15. 37 90
      src/classes/CpsEdge.java
  16. 13 0
      src/classes/CpsNode.java
  17. 8 1
      src/classes/CpsUpperNode.java
  18. 40 0
      src/classes/ExitCable.java
  19. 80 0
      src/classes/Flexibility.java
  20. 5 0
      src/classes/HolonBattery.java
  21. 2 1
      src/classes/HolonBody.java
  22. 11 68
      src/classes/HolonElement.java
  23. 89 327
      src/classes/HolonObject.java
  24. 13 1
      src/classes/HolonSwitch.java
  25. 0 90
      src/classes/HolonTransformer.java
  26. 46 0
      src/classes/IntermediateCalculationCable.java
  27. 4 4
      src/classes/comparator/EnergyMinToMaxComparator.java
  28. 2 2
      src/classes/comparator/MinEnergyComparator.java
  29. 2 2
      src/classes/comparator/TotalEnergyComparator.java
  30. 0 19
      src/classes/comparator/elementComparator/ElemCompOnFlexible.java
  31. 0 18
      src/classes/comparator/elementComparator/ElemCompOnIsFlexible.java
  32. 222 0
      src/connection/ConnectHandheld.java
  33. 518 0
      src/connection/ConnectPhysical.java
  34. 312 0
      src/connection/socket/Server.java
  35. 477 0
      src/exampleAlgorithms/BaseLine.java
  36. 495 0
      src/exampleAlgorithms/DemoAlgo.java
  37. 113 0
      src/exampleAlgorithms/ExampleFitnessFunction.java
  38. 981 0
      src/exampleAlgorithms/PSOAlgotihm.java
  39. 87 0
      src/exampleAlgorithms/RandomSwitch.java
  40. 0 34
      src/exampleAlgorithms/RandomSwitchesAlgorithm.java
  41. 0 44
      src/exampleAlgorithms/RepairAllEdges.java
  42. 1 0
      src/ui/controller/CanvasController.java
  43. 0 16
      src/ui/controller/CategoryController.java
  44. 0 63
      src/ui/controller/ConsoleController.java
  45. 41 73
      src/ui/controller/Control.java
  46. 3 8
      src/ui/controller/GlobalController.java
  47. 9 9
      src/ui/controller/HolonCanvasController.java
  48. 22 30
      src/ui/controller/NodeController.java
  49. 13 16
      src/ui/controller/ObjectController.java
  50. 163 1055
      src/ui/controller/SimulationManager.java
  51. 65 15
      src/ui/controller/UpdateController.java
  52. 85 0
      src/ui/model/Consumer.java
  53. 26 0
      src/ui/model/DecoratedCable.java
  54. 127 0
      src/ui/model/DecoratedGroupNode.java
  55. 24 0
      src/ui/model/DecoratedHolonObject.java
  56. 283 0
      src/ui/model/DecoratedNetwork.java
  57. 29 0
      src/ui/model/DecoratedState.java
  58. 24 0
      src/ui/model/DecoratedSwitch.java
  59. 37 0
      src/ui/model/IntermediateCableWithState.java
  60. 105 0
      src/ui/model/MinimumModel.java
  61. 33 0
      src/ui/model/MinimumNetwork.java
  62. 78 24
      src/ui/model/Model.java
  63. 15 0
      src/ui/model/Passiv.java
  64. 54 0
      src/ui/model/Supplier.java
  65. 359 0
      src/ui/model/VisualRepresentationalState.java
  66. 14 300
      src/ui/view/AbstractCanvas.java
  67. 0 4
      src/ui/view/AddElementPopUp.java
  68. 197 0
      src/ui/view/AlgoWindow.java
  69. 0 190
      src/ui/view/AlgorithmMenu.java
  70. 27 158
      src/ui/view/Console.java
  71. 3 3
      src/ui/view/CreateTemplatePopUp.java
  72. 3 33
      src/ui/view/EditEdgesPopUp.java
  73. 4 5
      src/ui/view/FlexiblePane.java
  74. 128 119
      src/ui/view/GUI.java
  75. 341 171
      src/ui/view/MyCanvas.java
  76. 250 0
      src/ui/view/Outliner.java
  77. 13 35
      src/ui/view/StatisticGraph.java
  78. 4 1
      src/ui/view/TimePanel.java
  79. 1 1
      src/ui/view/UnitGraph.java
  80. 384 309
      src/ui/view/UpperNodeCanvas.java
  81. 11 58
      tests/tests/PraktikumHolonsTestClasses.java
  82. 0 42
      tests/tests/PraktikumHolonsTestConsoleController.java
  83. 1 3
      tests/tests/PraktikumHolonsTestObjectController.java
  84. 0 1
      tests/tests/PraktikumHolonsTestSuite.java

+ 1 - 0
.gitignore

@@ -134,3 +134,4 @@ nbdist/
 ### added manually ###
 .idea/
 praktikum-holons.iml
+/gb_singlerun.txt

BIN
res/Button_Images/Close.png


BIN
res/Button_Images/Leaf.png


BIN
res/Button_Images/Open.png


BIN
res/Button_Images/iconAlgo.png


BIN
res/Button_Images/iconOutliner.png


BIN
res/Images/Thumbs.db


BIN
res/Images/arrowUp.png


BIN
res/Images/node.png


BIN
res/Images/replace.png


+ 14 - 0
src/api/Algorithm.java

@@ -0,0 +1,14 @@
+package api;
+
+import javax.swing.JPanel;
+
+import ui.controller.Control;
+
+/**
+ * Interface for a Algorithm that is executed on the current timestep.
+ * @author Tom Troppmann
+ */
+public interface Algorithm  {
+	public JPanel getAlgorithmPanel();
+	public void setController(Control control);
+}

+ 0 - 16
src/api/CpsAlgorithm.java

@@ -1,16 +0,0 @@
-package api;
-
-import ui.controller.Control;
-import ui.model.Model;
-
-/**
- * API Class for the CpsAlgorithm.
- * 
- * @author Gruppe14
- */
-public interface CpsAlgorithm {
-	/**
-	 * This Method will be called in each Iteration.
-	 */
-	public void runAlgorithm(Model model, Control controller);
-}

+ 2 - 0
src/classes/AbstractCpsObject.java

@@ -75,6 +75,8 @@ public abstract class AbstractCpsObject {
 		setId(IdCounter.nextId());
 		setImage(obj.getImage());
 	}
+	
+	public abstract AbstractCpsObject makeCopy();
 
 	/**
 	 * Getter for the type of the Object.

+ 0 - 11
src/classes/Constants.java

@@ -1,11 +0,0 @@
-package classes;
-
-public class Constants {
-
-	// Environment Constants
-
-	public static float gravity = 2000f;  // pixels per second
-	public static float restitution = 0.85f;
-	public static float epsilon = 0.000009f;
-
-}

+ 37 - 90
src/classes/CpsEdge.java

@@ -13,36 +13,10 @@ import java.util.ArrayList;
  */
 public class CpsEdge {
 
-    public static final int CON_UPPER_NODE = 0;
-    public static final int CON_UPPER_NODE_AND_INSIDE = 1;
-    public static final int CON_UPPER_NODE_NOT_INSIDE = 2;
-
-    public static final float CAPACITY_INFINITE = -1;
-    public static final float CAPACITY_TO_UPPER_NODE = -2;
     // Max. capacity of the Edge, if flow is greater than the status --> is
     // Working would be false
     @Expose
-    float maxCapacity;
-    // for internal use --> flow of electricity (simulation state)
-    // Current flow of electricity (through the edge)
-    @Expose
-    float flow;
-    /*
-     * Represents the actual status of the Edge (true = flows electricity; false
-     * = no flow of electricity) State represents the real status of the edge If
-     * it breaks --> stay ruin no matter the actual scenario The only way to
-     * repair it is through manual change (setStateEdge)
-     */
-    @Expose
-    boolean isWorking;
-    /*
-     * 0 = not connected to an upper node
-     * 1 = connected to an uppder node & connected inside
-     * 2 = connected to an upper node but not inside
-     * Is false when not
-     */
-    @Expose
-    int isConnected;
+    private float maxCapacity;
     ArrayList<Integer> tags;
     // for internal use --> flow of electricity (simulation state)
     ArrayList<Integer> pseudoTags;
@@ -51,6 +25,12 @@ public class CpsEdge {
     // Destination
     AbstractCpsObject b;
 
+    @Expose
+    private boolean breakedManuel = false;
+    @Expose
+    private boolean unlimitedCapacity = false;
+    
+    
     /**
      * Constructor without max. capacity (by default as 100)
      *
@@ -63,8 +43,6 @@ public class CpsEdge {
         this.a.addConnection(this);
         this.b.addConnection(this);
         this.maxCapacity = 100;
-        flow = 0;
-        isWorking = true;
         pseudoTags = new ArrayList<>();
     }
 
@@ -81,9 +59,6 @@ public class CpsEdge {
         this.a.addConnection(this);
         this.b.addConnection(this);
         this.maxCapacity = maxCap;
-        flow = 0;
-        isWorking = true;
-        isConnected = CON_UPPER_NODE;
         pseudoTags = new ArrayList<>();
     }
 
@@ -105,39 +80,9 @@ public class CpsEdge {
         this.maxCapacity = cap;
     }
 
-    /**
-     * Getter fot the current flow.
-     *
-     * @return the flow
-     */
-    public float getFlow() {
-        return flow;
-    }
 
-    /**
-     * Set the flow into a new one.
-     *
-     * @param flow the flow to set
-     */
-    public void setFlow(float flow) {
-        this.flow = flow;
-        /**
-         * if (flow <= maxCapacity || flow == -1) { isWorking = true; } else {
-         * isWorking = false; state = false;
-         **/
-    }
 
-    /**
-     * Calculates the state of the edge (see description of isWorking).
-     */
-    public void calculateState() {
-        if (flow > maxCapacity
-                && maxCapacity != CAPACITY_INFINITE
-                && maxCapacity != CAPACITY_TO_UPPER_NODE) {
-            isWorking = false;
-            flow = 0;
-        }
-    }
+
 
     /**
      * Getter for the Source.
@@ -175,23 +120,9 @@ public class CpsEdge {
         this.b = b;
     }
 
-    /**
-     * Getter for the status.
-     *
-     * @return the state
-     */
-    public boolean isWorking() {
-        return isWorking;
-    }
 
-    /**
-     * Set the state manually to a new one.
-     *
-     * @param state the state
-     */
-    public void setWorkingState(boolean state) {
-        isWorking = state;
-    }
+
+
 
     /**
      * Getter for the ArrayList of tags.
@@ -264,22 +195,38 @@ public class CpsEdge {
         }
     }
 
-    public int getConnected() {
-        return isConnected;
-    }
 
-    public void setConnected(int state) {
-        isConnected = state;
-        if (state == CON_UPPER_NODE_AND_INSIDE) {
-            //maxCapacity = CAPACITY_TO_UPPER_NODE;
-        }
-    }
     
+    /**
+     * Check if a CpsEdge is Connected to the AbstractCpsObject.
+     * @param holonObject the AbstractCpsObject to check.
+     * @return true if either a or b is the AbstractCpsObject to check.
+     */
+    public boolean isConnectedTo(AbstractCpsObject holonObject)
+    {
+    	return (holonObject.equals(a) || holonObject.equals(b));
+    }
     @Override
     public String toString(){
-    	String A = (a == null) ? "null" : a.getName();
-    	String B = (b == null) ? "null" : b.getName();
+    	String A = (a == null) ? "null" : a.getName() + "[" + a.getId()+ "]";
+    	String B = (b == null) ? "null" : b.getName() + "[" + b.getId()+ "]";
     	return "CpsEdge: " + A + " to " + B;
     }
 
+	public boolean isBreakedManuel() {
+		return breakedManuel;
+	}
+
+	public void setBreakedManuel(boolean breakedManuel) {
+		this.breakedManuel = breakedManuel;
+	}
+
+	public boolean isUnlimitedCapacity() {
+		return unlimitedCapacity;
+	}
+
+	public void setUnlimitedCapacity(boolean unlimitedCapacity) {
+		this.unlimitedCapacity = unlimitedCapacity;
+	}
+
 }

+ 13 - 0
src/classes/CpsNode.java

@@ -24,4 +24,17 @@ public class CpsNode extends AbstractCpsObject {
 		this.setSav("CVS");
 		this.setId(IdCounter.nextId());
 	}
+	
+	public CpsNode(CpsNode node){
+		super(node);
+	}
+	
+	public String toString(){
+		return "Node ID:" + super.id;
+	}
+	
+	@Override
+	public AbstractCpsObject makeCopy() {
+		return new CpsNode(this);
+	}
 }

+ 8 - 1
src/classes/CpsUpperNode.java

@@ -13,7 +13,7 @@ public class CpsUpperNode extends AbstractCpsObject {
 	private HashMap<Integer, Integer> nodesIdx;
 	
 	@Expose
-	private int leftBorder;
+	private int leftBorder; //TODO Delete leftBorder, jet is just set to 0
 	@Expose
 	private String imgPath = "";
 	@Expose
@@ -204,4 +204,11 @@ public class CpsUpperNode extends AbstractCpsObject {
 	public void setLeftBorder(int leftBorder) {
 		this.leftBorder = leftBorder;
 	}
+
+	@Override
+	public AbstractCpsObject makeCopy() {
+		return this;
+	}
+
+
 }

+ 40 - 0
src/classes/ExitCable.java

@@ -0,0 +1,40 @@
+package classes;
+
+import ui.model.DecoratedCable;
+/**
+ * For the Visual State.
+ * @author Tom
+ *
+ */
+public class ExitCable {
+	//Classification 
+	public enum ExitCableState {
+		UP, DOWN, DOWNUP, DOWNDOWN
+	}
+	private ExitCableState state;
+	//GroupNode or AbstractCpsObject
+	private AbstractCpsObject start;
+	private AbstractCpsObject finish;
+	private DecoratedCable cable;
+	
+	public ExitCable(ExitCableState state, AbstractCpsObject start, AbstractCpsObject finish, DecoratedCable cable) {
+		this.state = state;
+		this.start = start;
+		this.finish = finish;
+		this.cable = cable;
+	}
+
+	public ExitCableState getState() {
+		return state;
+	}
+	public AbstractCpsObject getStart() {
+		return start;
+	}
+	public AbstractCpsObject getFinish() {
+		return finish;
+	}
+	public DecoratedCable getCable() {
+		return cable;
+	}
+
+}

+ 80 - 0
src/classes/Flexibility.java

@@ -0,0 +1,80 @@
+package classes;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.function.Predicate;
+/**
+ * Representative of a flexibility for a HolonElement.
+ *
+ */
+public class Flexibility {
+	/** How fast in TimeSteps the Flexibility can be activated. */
+	public int speed;
+	/** How high the cost for a activation are. */
+	public float cost;
+	/** SHould this Flexibility be Offered when is constrainList is fulfilled the flexibility can be activated.*/
+	public boolean offered;
+	/** The Duration in TimeSteps how long the Flexibility is activated.*/
+	private int duration;
+	/** The Duration after a successful activation between the next possible activation.*/
+	private int cooldown;
+	/** The Element this flexibility is assigned.*/
+	private HolonElement element;
+	/** The List of Constrains the Flexibility */
+	public List<Predicate<Flexibility>> constrainList;
+	
+	
+	public Flexibility(HolonElement element){
+		this(0 , 0.f, 1, 0, false, element);		
+	}
+	public Flexibility(int speed, float cost, int duration, int cooldown, boolean offered, HolonElement element){
+		this.speed = speed;
+		this.cost = cost;
+		setDuration(duration);
+		setCooldown(cooldown);
+		this.offered=offered;
+		this.element = element;
+		constrainList = new ArrayList<Predicate<Flexibility>>();		
+	}
+	
+	
+	/** Checks if all assigned constrains are fulfilled. When no constrains assigned returns true.*/
+	public boolean fulfillsConstrains() {
+		return constrainList.stream().reduce(Predicate::and).orElse(f -> true).test(this);
+	}
+	
+	public HolonElement getElement() {
+		return element;
+	}
+
+	public int getDuration() {
+		return duration;
+	}
+	/** Minimum duration is 1 TimeStep.*/
+	public void setDuration(int duration) {
+		this.duration = Math.max(1, duration);
+	}
+
+	public int getCooldown() {
+		return cooldown;
+	}
+	/** No negative cooldown TimeSteps.*/
+	public void setCooldown(int cooldown) {
+		this.cooldown = Math.max(0, cooldown);
+	}
+
+	/** returns the total energy Amount accumulated over the TimeSteps.*/
+	public float magnitude() {
+		return ((float)duration) *  element.getEnergyPerElement();
+	}
+	
+	
+	//Example Constrains:
+	/** Flexibility should be offered when Element is active.*/
+	public Predicate<Flexibility> onConstrain = f 	-> 	f.getElement().isActive();
+	/** Flexibility should be offered when Element is inactive.*/
+	public Predicate<Flexibility> offConstrain = f	-> 	!f.getElement().isActive();
+	
+	
+	
+}

+ 5 - 0
src/classes/HolonBattery.java

@@ -184,4 +184,9 @@ public class HolonBattery extends AbstractCpsObject{
 		setImage(battery);
 		return battery;
 	}
+	
+	@Override
+	public HolonBattery makeCopy(){
+		return new HolonBattery(this);
+	}
 }

+ 2 - 1
src/classes/HolonBody.java

@@ -117,7 +117,8 @@ public class HolonBody implements Comparable<HolonBody> {
 			return;
 
 		// collision impulse
-		float i = (-(1.0f + Constants.restitution) * vn) / (im1 + im2);
+		float restitution = 0.85f;
+		float i = (-(1.0f + restitution) * vn) / (im1 + im2);
 		Vector2d impulse = mtd.multiply(i);
 
 		// change in momentum

+ 11 - 68
src/classes/HolonElement.java

@@ -43,11 +43,7 @@ public class HolonElement implements LocalMode, GraphEditable{
     @Expose
     private boolean active;
     /** Gives us whether this element is flexible and can flexibly use any part of the energy in flexibleEnergyAvailable */
-    @Expose
-    private boolean flexible;
-    /** Flexibility (meaning the actual */
-    @Expose
-    private float flexibleEnergyAvailable;
+
 
     
     /** Place where the Object is Stored */
@@ -57,8 +53,8 @@ public class HolonElement implements LocalMode, GraphEditable{
     @Expose
     private int id;
     
-    //private static final int DEFAULT_GRAPH_LENGTH=100;
-    //private int graphLength=DEFAULT_GRAPH_LENGTH; Unimplementable due to former developer's dark magic.
+    
+    public java.util.List<Flexibility> flexList;
     
     /*
      * Energy at each point of the graph with 100 predefined points. At the
@@ -100,8 +96,6 @@ public class HolonElement implements LocalMode, GraphEditable{
         initGraphPoints();
         sampleGraph();
         setId(id);
-        setFlexibleEnergyAvailable(0);
-        setFlexible(false);
     }
 
     /**
@@ -124,8 +118,7 @@ public class HolonElement implements LocalMode, GraphEditable{
         sampleGraph();
         setSaving(null);
         setId(IdCounterElem.nextId());
-        setFlexibleEnergyAvailable(0);
-        setFlexible(false);
+
     }
 
 	public String getObjName() {
@@ -235,9 +228,8 @@ public class HolonElement implements LocalMode, GraphEditable{
      *
      * @return totalEnergy (actual)
      */
-    public float getOverallEnergy() {
-        float totalEnergy =  amount * energyPerElement;
-        return totalEnergy;
+    public float getMaximumEnergy() {
+        return amount * energyPerElement;
     }
 
     /**
@@ -247,62 +239,15 @@ public class HolonElement implements LocalMode, GraphEditable{
      * @return energyPerElement value
      */
     public float getOverallEnergyAtTimeStep(int timestep) {
-    	if (flexible) {
-            return ((float) amount) * energyPerElement;
-        } else {
-            return ((float) amount) * energyPerElement * curveSample[IndexTranslator.getEffectiveIndex(this, timestep)];
-        }
+       return ((float) amount) * energyPerElement * curveSample[IndexTranslator.getEffectiveIndex(this, timestep)];
     }
     /**
      * Get the energyPerElement currently(at given time step) available
      */
-    public float getAvailableEnergyAt(int timestep) {
-    	System.out.println("getAvailableEnergyAt");
+    public float getEnergyAtTimeStep(int timestep) {
     	return amount * energyPerElement * this.curveSample[IndexTranslator.getEffectiveIndex(this, timestep)];
     }
 
-    /**
-     * Get the flexibleEnergyAvailable of an element
-     */
-    public float getFlexibleEnergyAvailablePerElement() {
-        return this.flexibleEnergyAvailable;
-    }
-
-    /**
-     * Set the flexibleEnergyAvailable of an element
-     */
-    public void setFlexibleEnergyAvailable(float energy) {
-        this.flexibleEnergyAvailable = energy;
-    }
-
-    /**
-     * Get the flexibleEnergyAvailable of an element
-     */
-    public boolean isFlexible() {
-        return this.flexible;
-    }
-
-    /**
-     * Set the flexibleEnergyAvailable of an element, ~switches energyPerElement and flexible energyPerElement
-     */
-    public void setFlexible(boolean b) {
-        // if flexibleEnergyAvailable was set to true
-        if (b && !this.flexible) {
-            this.flexible = b;
-            // move energyPerElement to flexibleEnergyAvailable (becomes the possible-to-use energyPerElement)
-            if (getEnergyPerElement() != 0) {
-                setFlexibleEnergyAvailable(getEnergyPerElement());
-                setEnergyPerElement(0);
-            }
-        } else if (!b && this.flexible) {
-            this.flexible = b;
-            // move the energyPerElement to actually used energyPerElement and set flexible amount to 0
-            if (getFlexibleEnergyAvailablePerElement() != 0) {
-                setEnergyPerElement(getFlexibleEnergyAvailablePerElement());
-            }
-            setFlexibleEnergyAvailable(0);
-        }
-    }
 
     /**
      * Get the Id of the selected HolonElement.
@@ -344,9 +289,7 @@ public class HolonElement implements LocalMode, GraphEditable{
                 .append(", eleName=").append(eleName)
                 .append(", amount=").append(amount)
                 .append(", active=").append(active)
-                .append(", flexible=").append(flexible)
-                .append(", energyPerElement used=").append(energyPerElement)
-                .append(", flexible energyPerElement available=").append(flexibleEnergyAvailable);
+                .append(", energyPerElement used=").append(energyPerElement);
         sb.append("]");
 
         return sb.toString();
@@ -435,7 +378,7 @@ public class HolonElement implements LocalMode, GraphEditable{
 	/**
 	 * Helper method for {@link HolonElement#sampleGraph(int)}.
 	 * <p>
-	 * Its get the start and Endposition and calculate the Points in between for the Beziér Curve.
+	 * Its get the start and Endposition and calculate the Points in between for the Bezi�r Curve.
 	 * Then its get the Y Value a.k.a. the percentage from the curve at the X value t.  
 	 * @param t is in Range [0,1] and represent how much the X value is traverse along the Curve between the two Points.
 	 * @param start is the start Point of the Curve.
@@ -461,7 +404,7 @@ public class HolonElement implements LocalMode, GraphEditable{
 	 */
 	private Point.Double getBezierPoint(double t, Point.Double p0, Point.Double p1,Point.Double p2,Point.Double p3) {
 		/*
-		 * Calculate Beziér:
+		 * Calculate Bezi�r:
 		 * B(t) = (1-t)^3 * P0 + 3*(1-t)^2 * t * P1 + 3*(1-t)*t^2 * P2 + t^3 * P3 , 0 < t < 1
 		 * 
 		 * Source: //http://www.theappguruz.com/blog/bezier-curve-in-games

+ 89 - 327
src/classes/HolonObject.java

@@ -2,9 +2,9 @@ package classes;
 
 import com.google.gson.annotations.Expose;
 
-import java.awt.*;
 import java.util.ArrayList;
 
+
 
 /**
  * The class HolonObject represents any Object on the system which capability of
@@ -13,48 +13,16 @@ import java.util.ArrayList;
  *
  * @author Gruppe14
  */
-public class HolonObject extends AbstractCpsObject {
-    /*
-     * the constants showing a HolonObject's current state
-     * (whether it needs no energy, whether it is not supplied, fully supplied,
-     * a producer, partially supplied or over-supplied)
-     */
-    public final static int NO_ENERGY = 0;
-    public final static int NOT_SUPPLIED = 1;
-    public final static int SUPPLIED = 2;
-    public final static int PRODUCER = 3;
-    public final static int PARTIALLY_SUPPLIED = 4;
-    public final static int OVER_SUPPLIED = 5;
-    
-    private static final int DEFAULT_GRAPH_LENGTH = 100;//TODO
-    /*
-     * Color of the actual state (red = no supplied, yellow = partially supplied
-     * and green = supplied)
-     */
-    @Expose
-    private Color stateColor;
+public class HolonObject extends AbstractCpsObject { 
     /* Array of all consumers */
     private ArrayList<HolonElement> elements;
-    /* Total of consumption */
-    @Expose
-    private float currentEnergy;
     /* Array for tracking Production */
     private float[] trackingProd;
     /* Array for tracking Consumption */
     private float[] trackingCons;
     /* Total Flexibility */
     private float totalFlex;
-    @Expose
-    private int state = 0;
-    /**
-     * Energy level that was supplied by other HolonObjects in the current Calculation
-     */
-    private float currentSupply;
     
-    /**
-     * Percentage of supplied energy of the energy level needed to supply all elements
-     */
-    private float suppliedPercentage;
     /**
      * Constructor Set by default the name of the object equals to the category
      * name, until the user changes it.
@@ -64,7 +32,6 @@ public class HolonObject extends AbstractCpsObject {
     public HolonObject(String objName) {
         super(objName);
         setElements(new ArrayList<>());
-        setState();
         setTrackingProd(new float[100]);
         setTrackingCons(new float[100]);
     }
@@ -77,33 +44,11 @@ public class HolonObject extends AbstractCpsObject {
     public HolonObject(AbstractCpsObject obj) {
         super(obj);
         setElements(copyElements(((HolonObject) obj).getElements()));
-        setState();
         setTrackingProd(new float[100]);
         setTrackingCons(new float[100]);
     }
 
-    /**
-     * sets the State, whether object is a producer, zero Energy, supplied,
-     * partially or over-supplied
-     */
-    public void setState() {
-        if (getMaxActiveEnergy() > 0) {
-            setState(PRODUCER);
-            stateColor = Color.lightGray;
-        } else {
-            if (getMaxActiveEnergy() == 0) {
-                setState(NO_ENERGY);
-                stateColor = Color.WHITE;
-            } else {
-                if (checkIfPartiallySupplied(0)) {
-                    stateColor = Color.yellow;
-                } else {
-                    stateColor = new Color(230, 120, 100);
-                }
-
-            }
-        }
-    }
+ 
 
     /**
      * Getter for all Elements in the HolonObject.
@@ -133,87 +78,18 @@ public class HolonObject extends AbstractCpsObject {
     }
 
     /**
-     * Calculate the maximum energy a holonObject can consume from all object that are aktive this moment;
+     * deletes Element at a given index.
      *
-     * @return the maximal active energy possibel
+     * @param idx index
      */
-    public float getMaxActiveEnergy() {
-        float temp = 0;
-        for (HolonElement e : getElements()) {
-            if (e.isActive()) {
-                temp += e.getOverallEnergy();
-            }
-        }
-        currentEnergy = temp;
-        return temp;
+    public void deleteElement(int idx) {
+    	elements.remove(idx);
     }
     
-    
 
-	public HolonElement getMinimalConsumingElement() {
-		HolonElement min = elements.get(0);
-		for (HolonElement e : elements) {
-			if (e.getOverallEnergy() < 0 && e.getOverallEnergy() > min.getOverallEnergy()) {
-				min = e;
-			}
-		}
-		return min;
-	}
     
-    /**
-     * Getter for the current energy at a given timestep.
-     *
-     * @param x timestep
-     * @return corresponding energy
-     */
-    public float getCurrentEnergyAtTimeStep(int x) {
-        float temp = 0;
-        float cons = 0;
-        float prod = currentSupply;
-        float t;
-        for (HolonElement e : getElements()) {
-            if (e.isActive()) {
-                t = e.getOverallEnergyAtTimeStep(x);
-                if(t<0){
-                	cons+=t;
-                }else{
-                	prod+=t;
-                }
-                temp += t;
-            }
-        }
-        currentEnergy = temp;
-        suppliedPercentage = prod / -cons;
-        return currentEnergy;
-    }
 
-    /**
-     * Getter for the current energy at a given timestep.
-     *
-     * @param x timestep
-     * @return corresponding energy
-     */
-    public float getCurrentEnergyAtTimeStepWithoutFlexiblesAndResetFlexibles(int x) {
-        float temp = 0;
-        for (HolonElement e : getElements()) {
-            if (e.isActive() && !e.isFlexible()) {
-                temp += e.getOverallEnergyAtTimeStep(x);
-            } else if (e.isFlexible()) {
-                e.setEnergyPerElement(0);
-            }
-        }
-        currentEnergy = temp;
-        return currentEnergy;
-    }
 
-    /**
-     * deletes Element at a given index.
-     *
-     * @param idx index
-     */
-    public void deleteElement(int idx) {
-        elements.remove(idx);
-    }
 
     /**
      * String of all consumers in this HolonObject.
@@ -247,53 +123,9 @@ public class HolonObject extends AbstractCpsObject {
         return newArr;
     }
 
-    /**
-     * Get the state of the Object.
-     *
-     * @return state the State of the Element
-     */
-    public int getState() {
-        return this.state;
-    }
-
-    /**
-     * Set the state of the Object.
-     *
-     * @param state boolean if the Object is fully supplied
-     */
-    public void setState(int state) {
-        this.state = state;
-        switch (state) {
-            case NO_ENERGY:
-                stateColor = Color.WHITE;
-                break;
-
-            case NOT_SUPPLIED:
-                stateColor = new Color(230, 120, 100);
-                break;
-
-            case SUPPLIED:
-                stateColor = Color.GREEN;
-                break;
-
-            case PRODUCER:
-                stateColor = Color.lightGray;
-                break;
-
-            case PARTIALLY_SUPPLIED:
-                stateColor = Color.YELLOW;
-                break;
-
-            case OVER_SUPPLIED:
-                // find different purple-tones at
-                // http://www.rapidtables.com/web/color/purple-color.htm
-                stateColor = new Color(138, 43, 226);
-                break;
-        }
-    }
 
     /**
-     * Search for the element with the name.
+     * Search for the first element with the name.
      *
      * @param name name of the object to be searched
      * @return the searched HolonElement
@@ -303,6 +135,7 @@ public class HolonObject extends AbstractCpsObject {
         for (HolonElement e : getElements()) {
             if (e.getEleName().equals(name)) {
                 ele = e;
+                break;
             }
         }
         return ele;
@@ -319,105 +152,94 @@ public class HolonObject extends AbstractCpsObject {
         for (HolonElement e : getElements()) {
             if (e.getId() == id) {
                 ele = e;
+                break;
             }
         }
         return ele;
     }
 
+  
+    
+    
+    //New Methods:
     /**
-     * Check if Partially Supplied.
-     *
-     * @param x current Iteration
-     * @return boolean is partially supplied
+     * This Method returns the smallest consuming HolonElement that is ACTIVE.
+     * If the HolonObject has no Consumer its return null. 
+     * @param timestep is the TimeStep to compare the HolonElements.
+     * @return The smallest consuming HolonElement or null.
      */
-    public boolean checkIfPartiallySupplied(int x) {
-        
-    	if (getElements().size() == 0) {
-            return false;
-        }
-        float minConsum = 0;
-        // Search for a activ element
-		for (HolonElement e : getElements()) {
-			if (e.isActive()) {
-				float overallEnergy = e.getOverallEnergyAtTimeStep(x);
-				if (overallEnergy < 0) {
-					// Is a consumer
-					minConsum = overallEnergy;
-				}
-			}
-		}
-        float prod = 0;
-        float cons = 0;
-        for (HolonElement e : getElements()) {
-            if (e.isActive()) {
-                float overallEnergy = e.getOverallEnergyAtTimeStep(x);
-                if (overallEnergy > 0) {
-                    prod += overallEnergy;
-                }else{
-                	cons += overallEnergy;
-                }
-                if (minConsum < 0 && (overallEnergy > minConsum && overallEnergy < 0)) {
-                    minConsum = overallEnergy;   
-                }
-            }
-        }
-        suppliedPercentage = -(prod + currentSupply)/cons;
-        // System.out.println("minCons: " + minConsum + " prod: " + prod);
-        if (minConsum < 0 && prod >= -minConsum) {
-            return true;
-        } else {
-            return false;
-        }
+    public HolonElement getMinimumConsumingElement(int timestep){
+    	return getElements().stream().filter(element -> element.isActive() && (element.getEnergyAtTimeStep(timestep) < 0) ).max((lhs,rhs) -> Float.compare(lhs.getEnergyAtTimeStep(timestep), rhs.getEnergyAtTimeStep(timestep))).orElse(null);
+    }
+    /**
+     * This Method returns the smallest consuming HolonElement'Energy that is ACTIVE.
+     * If the HolonObject has no Consumer its return 0. 
+     * @param timestep is the TimeStep to compare the HolonElements.
+     * @return The smallest consuming HolonElement or 0.
+     */
+    public float getMinimumConsumingElementEnergy(int timestep){
+    	return getElements().stream().filter(element -> element.isActive() && (element.getEnergyAtTimeStep(timestep) < 0) ).map(element -> -element.getEnergyAtTimeStep(timestep)).min((lhs,rhs) ->Float.compare(lhs, rhs)).orElse(0.0f);
     }
     
-    /**@param x TimeStep
-     * @return 
+    /**
+     * This Method returns the biggest consuming HolonElement'Energy that is ACTIVE.
+     * If the HolonObject has no Consumer its return 0. 
+     * @param timestep is the TimeStep to compare the HolonElements.
+     * @return The biggest consuming HolonElement or 0.
+     */
+    public float getMaximumConsumingElementEnergy(int timestep){
+    	return getElements().stream().filter(element -> element.isActive() && (element.getEnergyAtTimeStep(timestep) < 0) ).map(element -> -element.getEnergyAtTimeStep(timestep)).max((lhs,rhs) ->Float.compare(lhs, rhs)).orElse(0.0f);
+    }
+    /** 
+     * This Method returns the Energy of a HolonObject. Its sums all Energies from the HolonElements of the HolonObject that are ACTIVE.
+     * If the HolonObject have no HolonElement its return 0;
+     * Is the returned Energy negative then the HolonObject need Energy because its consuming HolonElements need more Energy then the producing HolonElements.
+     * Is the returned Energy positive its reversed.
+     * @param timestep is the TimeStep to compare the HolonElements.
+     * @return The Energy of the HolonObject.
      */
-    public float getSelfMadeEnergy(int x)
+    public float getEnergyAtTimeStep(int timestep)
     {
-    	return getElements().stream()
-    			.map(e ->(e.isActive() && e.getOverallEnergyAtTimeStep(x) > 0) ? e.getOverallEnergyAtTimeStep(x) : 0.0f)
-    			.reduce(0.0f, (a , b) -> a + b );
+    	return getElements().stream().filter(element -> element.isActive()).map(element -> element.getEnergyAtTimeStep(timestep)).reduce(0.0f, (a, b) -> a + b);
     }
-    /**
-     * Calculates the minimumEnergy Needed to turn on atleast on device
-     * of this HolonObject
-     * @param x Timestep of the calculation
-     * @return minEnergy, -inf if no Devices are consuming power
+    /** 
+     * This Method returns the Energy that all HolonElements from the HolonObject produce by itself. Its sums all Energies from the HolonElements of the HolonObject that are ACTIVE and are Producer.
+     * If the HolonObject have no HolonElement its return 0;
+     * @param timestep is the TimeStep to compare the HolonElements.
+     * @return The Energy of the producing HolonElements.
      */
-    public float getMinEnergy(int x) {
-        if (getElements().size() == 0) {
-            return Float.NEGATIVE_INFINITY;
-        }
-        float minConsum = Float.NEGATIVE_INFINITY;
-        for (HolonElement e : getElements()) {
-            if (e.isActive()) {
-                float overallEnergy = e.getOverallEnergyAtTimeStep(x);
-                if (minConsum < 0 && (overallEnergy > minConsum && overallEnergy < 0)) {
-                    minConsum = overallEnergy;
-                } 
-            }
-        }
-        return minConsum;
+    public float getEnergySelfProducingFromProducingElements(int timestep) {
+    	return getElements().stream().filter(element -> element.isActive() && (element.getEnergyAtTimeStep(timestep) > 0)).map(element -> element.getEnergyAtTimeStep(timestep)).reduce(0.0f, (a, b) -> a + b);
     }
-
+    /** 
+     * This Method returns the Energy of all HolonElements from the HolonObject that are consuming. Its sums all Energies from the HolonElements of the HolonObject that are ACTIVE and are Consumer.
+     * If the HolonObject have no HolonElement its return 0;
+     * @param timestep is the TimeStep to compare the HolonElements.
+     * @return The Energy of the consuming HolonElements.
+     */
+    public float getEnergyNeededFromConsumingElements(int timestep) {
+    	return getElements().stream().filter(element -> element.isActive() && (element.getEnergyAtTimeStep(timestep) < 0)).map(element -> -element.getEnergyAtTimeStep(timestep)).reduce(0.0f, (a, b) -> a + b);
+    }
+    
     /**
-     * Get the Color.
-     *
-     * @return stateColor the Color
+     * This Method calculate the amount of HolonElements that are consuming Energy and are ACTIVE.
+     * @param timestep is the TimeStep to compare the HolonElements.
+     * @return The amount of HolonElements that are consuming Energy.
      */
-    public Color getColor() {
-        return stateColor;
+    public int countConsumingElements(int timestep) {
+    	return (int) getElements().stream().filter(element -> element.isActive() && (element.getEnergyAtTimeStep(timestep) < 0)).count();
     }
-
     /**
-     * Set the State Color.
-     *
-     * @param color the Color
+     * This Method calculate the amount of HolonElements that are producing Energy and are ACTIVE.
+     * @param timestep is the TimeStep to compare the HolonElements.
+     * @return The amount of HolonElements that are producing Energy.
      */
-    public void setColor(Color color) {
-        stateColor = color;
+    public int countProducingElements(int timestep) {
+    	return (int) getElements().stream().filter(element -> element.isActive() && (element.getEnergyAtTimeStep(timestep) > 0)).count();
     }
+    
+
+
 
     /**
      * Get the Array Production
@@ -461,44 +283,8 @@ public class HolonObject extends AbstractCpsObject {
         this.totalFlex = totalFlex;
     }
 
-    /**
-     * Update the totalFlex
-     */
-    public void updateTotalFlex() {
-        float tempFlex = 0;
-        for (HolonElement e : getElements()) {
-            if (e.isFlexible()) {
-                tempFlex += e.getFlexibleEnergyAvailablePerElement() * e.getAmount();
-            }
-        }
-        this.totalFlex = tempFlex;
-    }
 
-    /**
-     * calculates total flexible Production
-     */
-    public float getFlexProd() {
-        float tempFlex = 0;
-        for (HolonElement e : getElements()) {
-            if (e.getFlexibleEnergyAvailablePerElement() > 0) {
-                tempFlex += e.getFlexibleEnergyAvailablePerElement() * e.getAmount();
-            }
-        }
-        return tempFlex;
-    }
 
-    /**
-     * calculates total flexible Concumption
-     */
-    public float getFlexCons() {
-        float tempFlex = 0;
-        for (HolonElement e : getElements()) {
-            if (e.getFlexibleEnergyAvailablePerElement() < 0) {
-                tempFlex += e.getFlexibleEnergyAvailablePerElement() * e.getAmount();
-            }
-        }
-        return tempFlex;
-    }
 
     /**
      * If the user track any HolonObject the tracking information will be
@@ -535,26 +321,6 @@ public class HolonObject extends AbstractCpsObject {
         sb.append("id=").append(id)
                 .append(", name=").append(name)
                 .append(", state=");
-        switch (state) {
-            case NO_ENERGY:
-                sb.append("NO_ENERGY");
-                break;
-            case NOT_SUPPLIED:
-                sb.append("NOT_SUPPLIED");
-                break;
-            case SUPPLIED:
-                sb.append("SUPPLIED");
-                break;
-            case PRODUCER:
-                sb.append("PRODUCER");
-                break;
-            case PARTIALLY_SUPPLIED:
-                sb.append("PARTIALLY_SUPPLIED");
-                break;
-            case OVER_SUPPLIED:
-                sb.append("OVER_SUPPLIED");
-                break;
-        }
         sb.append(", elements=[");
         for (int i = 0; i < getElements().size(); i++) {
             HolonElement el = getElements().get(i);
@@ -567,25 +333,21 @@ public class HolonObject extends AbstractCpsObject {
 
         return sb.toString();
     }
-
-	/**
-	 * @return the {@link #currentSupply}
-	 */
-	public float getCurrentSupply() {
-		return currentSupply;
+    
+    @Override
+	public HolonObject makeCopy(){
+		return new HolonObject(this);
 	}
 
-	/**
-	 * @param currentSupply the {@link #currentSupply} to set
-	 */
-	public void setCurrentSupply(float currentSupply) {
-		this.currentSupply = currentSupply;
+	public int getNumberOfActiveElements() {
+		return (int) elements.stream().filter(ele -> ele.isActive()).count();
+	}
+	
+	public int getNumberOfInActiveElements() {
+		return (int) elements.stream().filter(ele -> !ele.isActive()).count();
 	}
 	
-	/**
-	 * @return {@link #suppliedPercentage}
-	 */
-	public float getSuppliedPercentage(){
-		return suppliedPercentage;
+	public int getNumberOfElements() {
+		return (int) elements.stream().count();
 	}
 }

+ 13 - 1
src/classes/HolonSwitch.java

@@ -120,11 +120,18 @@ public class HolonSwitch extends AbstractCpsObject implements LocalMode, GraphEd
 
 	}
 
+	public static String getSwitchClosedImage(){
+		return "/Images/switch-on.png";
+	}
+	
+	public static String getSwitchOpenImage(){
+		return "/Images/switch-off.png";
+	}
 	/**
 	 * Getter for the status of the Switch at a given timestep.
 	 * 
 	 * @param timeStep state at given iteration.
-	 * @return state value
+	 * @return state value (true if closed/active, false if open)
 	 */
 	public boolean getState(int timeStep) {
 		if (manualMode) {
@@ -302,4 +309,9 @@ public class HolonSwitch extends AbstractCpsObject implements LocalMode, GraphEd
 	public void setUseLocalPeriod(boolean state) {
 		this.localPeriodActive=state;
 	}
+	
+	@Override
+	public HolonSwitch makeCopy(){
+		return new HolonSwitch(this);
+	}
 }

+ 0 - 90
src/classes/HolonTransformer.java

@@ -1,90 +0,0 @@
-package classes;
-/**
- * The class HolonTransformer represents a Transformer that transforms a flow to a lower flow.
- * Transforemer are not used in the current State of the Project but could be used the future.
- * 
- * @author Gruppe14
- *
- */
-public class HolonTransformer extends AbstractCpsObject {
-
-	/* Ratio of the transformer */
-	float transformRatio;
-
-	/* Fixed transform value */
-	float transformFixed;
-	
-	float maxInput;
-	
-	float maxOutput;
-
-	/**
-	 * Constructor Set type of object (Transformer), its transform ratio and the
-	 * default name ("Transformer").
-	 * 
-	 * @param objName name for the Object
-	 */
-	public HolonTransformer(String objName) {
-		super(objName);
-	}
-
-	/**
-	 * Copy of the Object.
-	 * 
-	 * @param obj the Object to Copy
-	 */
-	public HolonTransformer(AbstractCpsObject obj) {
-		super(obj);
-		this.setTransformRatio(((HolonTransformer) obj).getTransformRatio());
-		this.setTransformFixed(((HolonTransformer) obj).getTransformFixed());
-	}
-
-	/**
-	 * Set transform ratio.
-	 * 
-	 * @param ratio
-	 *            desired ratio
-	 */
-	public void setTransformRatio(float ratio) {
-		this.transformRatio = ratio;
-	}
-
-	/**
-	 * Output the actual ratio of the transformer.
-	 * 
-	 * @return actual ratio of the transformer
-	 */
-	public float getTransformRatio() {
-		return this.transformRatio;
-	}
-
-	/**
-	 * Set fixed Transform Value.
-	 * 
-	 * @param fixed
-	 *            desired fixed Transform Value
-	 */
-	public void setTransformFixed(float fixed) {
-		this.transformFixed = fixed;
-	}
-
-	/**
-	 * Output the actual fixed Transform Value.
-	 * 
-	 * @return actual fixed Transform Value
-	 */
-	public float getTransformFixed() {
-		return this.transformFixed;
-	}
-
-	/**
-	 * Get the Output of the Transformer.
-	 * 
-	 * @return The Output
-	 */
-	public float getOutput() {
-		float output = 0;
-		return output;
-
-	}
-}

+ 46 - 0
src/classes/IntermediateCalculationCable.java

@@ -0,0 +1,46 @@
+package classes;
+
+import ui.model.DecoratedCable;
+
+/**
+ * A VisualRepresentation to represent a connection from a UpperNode to a AbstactCpsObject, but actually the UpperNode is not connected.
+ * @author Tom
+ *
+ */
+public class IntermediateCalculationCable {
+	private AbstractCpsObject outsideObject;
+	private AbstractCpsObject insideObject;
+	private CpsUpperNode getInsideUpperNode;
+	private CpsUpperNode getOutsideUpperNode;
+	private DecoratedCable cable;
+	public IntermediateCalculationCable(DecoratedCable cable, CpsUpperNode getInsideUpperNode,CpsUpperNode getOutsideUpperNode, AbstractCpsObject insideObject, AbstractCpsObject outsideObject){
+		this.cable = cable;
+		this.getInsideUpperNode = getInsideUpperNode;
+		this.getOutsideUpperNode = getOutsideUpperNode;
+		this.insideObject = insideObject;
+		this.outsideObject = outsideObject;
+	}
+	public AbstractCpsObject getOusideObject() {
+		return outsideObject;
+	}
+	public AbstractCpsObject getInsideObject() {
+		return insideObject;
+	}
+	public CpsUpperNode getInsideUpperNode() {
+		return getInsideUpperNode;
+	}
+	public DecoratedCable getCable() {
+		return cable;
+	}
+	public CpsEdge getModel() {
+		return cable.getModel();
+	}
+	public CpsUpperNode getOutsideUpperNode() {
+		return getOutsideUpperNode;
+	}
+	public String toString() {
+		return getModel().toString();
+		
+	}
+
+}

+ 4 - 4
src/classes/comparator/EnergyMinToMaxComparator.java

@@ -24,10 +24,10 @@ public class EnergyMinToMaxComparator implements Comparator<HolonObject> {
 
 	@Override
 	public int compare(HolonObject o1, HolonObject o2) {
-		float minEnergy1 = o1.getMinEnergy(timeStep);
-		float minEnergy2 = o2.getMinEnergy(timeStep);
-		float totalEnergy1 = o1.getCurrentEnergyAtTimeStep(timeStep);
-		float totalEnergy2 = o2.getCurrentEnergyAtTimeStep(timeStep);
+		float minEnergy1 = o1.getMinimumConsumingElementEnergy(timeStep);
+		float minEnergy2 = o2.getMinimumConsumingElementEnergy(timeStep);
+		float totalEnergy1 = o1.getEnergyAtTimeStep(timeStep);
+		float totalEnergy2 = o2.getEnergyAtTimeStep(timeStep);
 		float difference1 = totalEnergy1 - minEnergy1;
 		float difference2 = totalEnergy2 - minEnergy2;
 		if(difference1 < difference2)

+ 2 - 2
src/classes/comparator/MinEnergyComparator.java

@@ -23,8 +23,8 @@ public class MinEnergyComparator implements Comparator<HolonObject> {
 
 	@Override
 	public int compare(HolonObject o1, HolonObject o2) {
-		float minEnergy1 = o1.getMinEnergy(timeStep);
-		float minEnergy2 = o2.getMinEnergy(timeStep);
+		float minEnergy1 = o1.getMinimumConsumingElementEnergy(timeStep);
+		float minEnergy2 = o2.getMinimumConsumingElementEnergy(timeStep);
 		if(minEnergy1<minEnergy2)
 			return 1;
 		else if (minEnergy1 == minEnergy2) 

+ 2 - 2
src/classes/comparator/TotalEnergyComparator.java

@@ -23,8 +23,8 @@ public class TotalEnergyComparator implements Comparator<HolonObject> {
 
 	@Override
 	public int compare(HolonObject o1, HolonObject o2) {
-		float totalEnergy1 = o1.getCurrentEnergyAtTimeStep(timeStep);
-		float totalEnergy2 = o2.getCurrentEnergyAtTimeStep(timeStep);
+		float totalEnergy1 = o1.getEnergyAtTimeStep(timeStep);
+		float totalEnergy2 = o2.getEnergyAtTimeStep(timeStep);
 		if(totalEnergy1<totalEnergy2)
 			return -1;
 		else if (totalEnergy1 == totalEnergy2) 

+ 0 - 19
src/classes/comparator/elementComparator/ElemCompOnFlexible.java

@@ -1,19 +0,0 @@
-package classes.comparator.elementComparator;
-
-import classes.HolonElement;
-
-public class ElemCompOnFlexible extends ElementComparator {
-	
-	@Override
-	public int compare(HolonElement a, HolonElement b) {
-
-		float flexA = a.getFlexibleEnergyAvailablePerElement();
-		float flexB = b.getFlexibleEnergyAvailablePerElement();
-		if (flexA < flexB)
-			return -1;
-		if (flexA > flexB)
-			return 1;
-		return 0;
-
-	}
-}

+ 0 - 18
src/classes/comparator/elementComparator/ElemCompOnIsFlexible.java

@@ -1,18 +0,0 @@
-package classes.comparator.elementComparator;
-
-import classes.HolonElement;
-
-public class ElemCompOnIsFlexible extends ElementComparator{
-
-	@Override
-	public int compare(HolonElement a, HolonElement b) {
-		boolean ifA = a.isFlexible();
-		boolean ifB = b.isFlexible();
-		if (ifA&&!ifB)
-			return -1;
-		if (!ifA && ifB)
-			return 1;
-		return 0;
-	}
-
-}

+ 222 - 0
src/connection/ConnectHandheld.java

@@ -0,0 +1,222 @@
+package connection;
+
+import java.awt.BorderLayout;
+import java.awt.Dimension;
+import java.awt.image.BufferedImage;
+import java.io.IOException;
+import java.net.BindException;
+import java.text.NumberFormat;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+
+import javax.swing.ImageIcon;
+import javax.swing.JButton;
+import javax.swing.JFormattedTextField;
+import javax.swing.JFrame;
+import javax.swing.JLabel;
+import javax.swing.JOptionPane;
+import javax.swing.JPanel;
+import javax.swing.JScrollPane;
+import javax.swing.JSplitPane;
+import javax.swing.JTextArea;
+import javax.swing.text.NumberFormatter;
+
+import api.Algorithm;
+import classes.AbstractCpsObject;
+import classes.CpsUpperNode;
+import classes.HolonObject;
+import connection.ConnectPhysical.HolonObjectStatus;
+import connection.ConnectPhysical.PhysicalLinkWrapper;
+import connection.socket.Server;
+import ui.controller.Control;
+import ui.view.Console;
+
+public class ConnectHandheld implements Algorithm{
+	
+	//Holeg
+	Control control;
+	private HolonObject observed;
+	
+	//Gui
+	private JPanel content = new JPanel();
+	private JTextArea textArea;
+	
+
+	//TCP
+	int port = 4242;
+	Server server;
+	
+	private Console console;
+	private boolean holonObjectConnected;
+	private JLabel houseLabel;
+	
+
+
+
+
+	public static void main(String[] args)
+	{
+	      JFrame newFrame = new JFrame("exampleWindow");
+	      ConnectHandheld instance = new ConnectHandheld();
+	      newFrame.setContentPane(instance.getAlgorithmPanel());
+	      newFrame.pack();
+	      newFrame.setVisible(true);
+	      newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+	}
+
+	
+	
+	
+	
+	public ConnectHandheld() {
+		content.setLayout(new BorderLayout());
+		
+		textArea = new JTextArea();
+		textArea.setEditable(false);
+		console = new Console();
+		JScrollPane scrollPane = new JScrollPane(console);
+		JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
+				createSettingsPanel() , scrollPane);
+		splitPane.setResizeWeight(0.0);
+		content.add(splitPane, BorderLayout.CENTER);
+		content.setPreferredSize(new Dimension(400,600));	
+	}
+
+
+	
+	private JPanel createSettingsPanel() {
+		JPanel settingsPanel = new JPanel(null);
+		settingsPanel.setPreferredSize(new Dimension(400, 400));
+		settingsPanel.setMinimumSize(new Dimension(400, 225));
+		
+		NumberFormat format = NumberFormat.getIntegerInstance();
+		format.setGroupingUsed(false);
+		format.setParseIntegerOnly(true);
+		NumberFormatter integerFormatter = new NumberFormatter(format);
+		integerFormatter.setMinimum(0);
+		integerFormatter.setMaximum(65535);
+		integerFormatter.setCommitsOnValidEdit(true);
+		
+		
+		
+		JLabel portLabel = new JLabel("Port:");
+		portLabel.setBounds(10, 20, 35, 30);
+		settingsPanel.add(portLabel);
+		JFormattedTextField portTF = new JFormattedTextField(integerFormatter);
+		portTF.setText(""+port);
+		portTF.setBounds(55 ,20, 80, 30);
+		portTF.addPropertyChangeListener(propertyChange ->{
+			String text = portTF.getValue().toString();
+			text = text.replaceAll("\\s", "");
+			port = Integer.parseInt((text));
+		});
+		settingsPanel.add(portTF);
+		
+		
+		houseLabel = new JLabel("House Status: " + (holonObjectConnected?"Connected":"Not selected"));
+		houseLabel.setBounds(10, 90, 220, 30);
+		settingsPanel.add(houseLabel);
+		
+		JButton selectRoom1Button = new JButton("Select");
+		selectRoom1Button.setBounds(230,95, 90, 20);
+		selectRoom1Button.addActionListener(actionEvent -> this.selectHolonObject());
+		settingsPanel.add(selectRoom1Button);
+		
+		
+		JButton connectButton = new JButton("Start Server");
+		connectButton.setBounds(100 ,175, 200, 50);
+		connectButton.addActionListener(actionEvent -> connect());
+		settingsPanel.add(connectButton);
+
+		return settingsPanel;
+	}
+
+
+
+
+
+
+
+
+
+
+
+	private void connect() {
+		if(!holonObjectConnected) {
+			console.println("Select a HolonObject");
+			return;
+		}
+		try {
+			if(server != null) {
+				server.stopServer();
+			}
+			console.println("Start Server on Port:" + port);
+			server = new Server(port, console, observed, control);
+		}catch(BindException e){
+			console.println(e.getMessage());
+		}
+		catch (IOException e) {
+			// TODO Auto-generated catch block
+			e.printStackTrace();
+		}
+	}
+	
+
+	@Override
+	public JPanel getAlgorithmPanel() {
+		return content;
+	}
+
+	@Override
+	public void setController(Control control) {
+		this.control = control;
+	}
+
+	
+		private void selectHolonObject() {
+			List<HolonObject> holonObjectList = new ArrayList<HolonObject>();
+			addObjectToList(control.getModel().getObjectsOnCanvas(),holonObjectList);
+			Object[] possibilities = holonObjectList.stream().map(aCps -> new Handle<HolonObject>(aCps)).toArray();
+			@SuppressWarnings("unchecked")
+			Handle<HolonObject> selected = (Handle<HolonObject>) JOptionPane.showInputDialog(content, "Select HolonObject:", "HolonObject?",  JOptionPane.OK_OPTION,new ImageIcon(new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB)) , possibilities, "");
+			if(selected != null) {
+				console.println("Selected: " + selected);
+				observed = selected.object;
+				holonObjectConnected = true;
+				if(server != null) {
+					server.setObserved(selected.object);
+				}
+				updateSelectionLabel();
+			}
+		}
+		
+		private void updateSelectionLabel() {
+			houseLabel.setText("House Status: " + (holonObjectConnected?"Connected":"Not selected"));
+		}
+
+
+
+
+
+		private void addObjectToList(List<AbstractCpsObject> listToSearch, List<HolonObject> listToAdd){
+			for (AbstractCpsObject aCps : listToSearch) {
+				if (aCps instanceof HolonObject) listToAdd.add((HolonObject) aCps);
+				else if(aCps instanceof CpsUpperNode) {
+					addObjectToList(((CpsUpperNode)aCps).getNodes(),listToAdd);
+				}
+			}
+		}
+		
+		
+		private   class  Handle<T>{
+			public T object;
+			Handle(T object){
+				this.object = object;
+			}
+			public String toString() {
+				return object.toString();
+			}
+		}
+	
+}

+ 518 - 0
src/connection/ConnectPhysical.java

@@ -0,0 +1,518 @@
+package connection;
+import java.awt.BorderLayout;
+import java.awt.Component;
+import java.awt.Dimension;
+import java.awt.FlowLayout;
+import java.awt.image.BufferedImage;
+import java.io.IOException;
+import java.net.HttpURLConnection;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.text.NumberFormat;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Collectors;
+
+import javax.swing.BorderFactory;
+import javax.swing.ImageIcon;
+import javax.swing.JButton;
+import javax.swing.JCheckBox;
+import javax.swing.JFormattedTextField;
+import javax.swing.JFrame;
+import javax.swing.JLabel;
+import javax.swing.JOptionPane;
+import javax.swing.JPanel;
+import javax.swing.JScrollPane;
+import javax.swing.JSplitPane;
+import javax.swing.JTextArea;
+import javax.swing.text.NumberFormatter;
+
+import api.Algorithm;
+import classes.AbstractCpsObject;
+import classes.CpsUpperNode;
+import classes.HolonElement;
+import classes.HolonObject;
+import ui.controller.Control;
+import ui.view.Console;
+/**
+ * Easy Connection via Http Request. Repeat Request with a delay.
+ * 
+ * @author tom
+ *
+ */
+public class ConnectPhysical implements Algorithm{
+	//Holeg
+	private Control  control;
+	
+	
+	
+	
+	//Gui
+	private JPanel content = new JPanel();
+	private Console console;
+
+	private JLabel rotorLabel;
+	private JLabel houseLabel;
+	private boolean onlyOnChange = false;
+	//
+	Future<?> future;
+	private boolean lessInformation = false;
+	private int delay = 1000;
+	JLabel warningLabel;
+	
+	public enum HolonObjectStatus{
+		Connected , NotSelected, ObjectDeleted 
+	}
+	
+	public class PhysicalLinkWrapper{
+		public HolonObject hObject;
+		public HolonObjectStatus status;
+		public String postAddress;
+		
+		PhysicalLinkWrapper(HolonObject hObject, HolonObjectStatus status, String postAddress){
+			this.hObject = hObject;
+			this.status = status;
+			this.postAddress = postAddress;
+		}
+	}
+	
+	
+	//Object to look at
+	PhysicalLinkWrapper rotor = new PhysicalLinkWrapper(null, HolonObjectStatus.NotSelected, "/rotor/");
+	
+	//Because House is special
+	PhysicalLinkWrapper house = new PhysicalLinkWrapper(null, HolonObjectStatus.NotSelected, "notUsed");
+	String room1Address = "/room1/";
+	String room2Address = "/room2/";
+	//the keywords are for the sepreation in 2 rooms
+	String room1Keyword = "room1";
+	String room2Keyword = "room2";
+
+
+	//OnChange
+	int oldValueRotor = -1;
+	int oldValueRoom1 = -1;
+	int oldValueRoom2 = -1;
+
+
+
+
+	
+
+
+
+
+
+
+
+	public static void main(String[] args)
+	{
+	      JFrame newFrame = new JFrame("exampleWindow");
+	      ConnectPhysical instance = new ConnectPhysical();
+	      newFrame.setContentPane(instance.getAlgorithmPanel());
+	      newFrame.pack();
+	      newFrame.setVisible(true);
+	      newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+	}
+
+	
+	
+	
+	
+	public ConnectPhysical() {
+		content.setLayout(new BorderLayout());
+		console = new Console();
+		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));	
+	}
+
+	private Component createOptionPanel() {
+		JPanel optionPanel = new JPanel(new BorderLayout());
+		JScrollPane scrollPane = new JScrollPane(createParameterPanel());
+		scrollPane.setBorder(BorderFactory.createTitledBorder("Settings"));
+		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 lessInformationLabel = new JLabel("Less information in Console:");
+		lessInformationLabel.setBounds(200, 180, 200, 20);
+		parameterPanel.add(lessInformationLabel);	
+		
+		JCheckBox lessInformationCheckBox = new JCheckBox();
+		lessInformationCheckBox.setSelected(false);
+		lessInformationCheckBox.setBounds(400, 180, 25, 20);
+		lessInformationCheckBox.addActionListener(actionEvent -> {
+			lessInformation = lessInformationCheckBox.isSelected();
+		});
+		parameterPanel.add(lessInformationCheckBox);
+		
+		JLabel onlyOnChangeLabel = new JLabel("OnlyOnChange:");
+		onlyOnChangeLabel.setBounds(200, 240, 200, 20);
+		parameterPanel.add(onlyOnChangeLabel);	
+		
+		
+		JCheckBox onlyOnChangeCheckBox = new JCheckBox();
+		onlyOnChangeCheckBox.setSelected(false);
+		onlyOnChangeCheckBox.setBounds(400, 240, 25, 20);
+		onlyOnChangeCheckBox.addActionListener(actionEvent -> {
+			onlyOnChange = onlyOnChangeCheckBox.isSelected();
+		});
+		parameterPanel.add(onlyOnChangeCheckBox);
+		
+		
+		
+		
+		JLabel delayLabel = new JLabel("Delay:");
+		delayLabel.setBounds(200, 210, 50, 20);
+		parameterPanel.add(delayLabel);	
+		
+		JLabel delayUnitLabel = new JLabel("[ms]");
+		delayUnitLabel.setBounds(300, 210, 50, 20);
+		parameterPanel.add(delayUnitLabel);	
+		
+		warningLabel = new JLabel(stringToHtml(stringWithColor("You need to Stop and Run again to affect delay change.", "red")));
+		warningLabel.setBounds(200, 280, 400, 20);
+		warningLabel.setVisible(false);
+		parameterPanel.add(warningLabel);	
+		
+		//Integer formatter
+		NumberFormat format = NumberFormat.getIntegerInstance();
+		format.setGroupingUsed(false);
+		format.setParseIntegerOnly(true);
+		NumberFormatter integerFormatter = new NumberFormatter(format);
+		integerFormatter.setMinimum(0);
+		integerFormatter.setCommitsOnValidEdit(true);
+		
+		
+		JFormattedTextField delayTextField = new  JFormattedTextField(integerFormatter);
+		delayTextField.setValue(delay);
+		delayTextField.setToolTipText("Only positive Integer.");
+		delayTextField.addPropertyChangeListener(actionEvent -> {
+			delay = Integer.parseInt(delayTextField.getValue().toString());
+			if(future != null && !future.isCancelled()) {
+				console.println("You need to Stop and Run again to affect this change.");
+				warningLabel.setVisible(true);
+			}
+		});
+		delayTextField.setBounds(250, 210, 50, 20);
+		parameterPanel.add(delayTextField);
+
+		
+		
+		rotorLabel = new JLabel(stringToHtml("Rotor Status: " + statusToString(rotor.status)));
+		rotorLabel.setBounds(200, 60, 220, 30);
+		parameterPanel.add(rotorLabel);	
+		
+		houseLabel = new JLabel(stringToHtml("House Status: " + statusToString(house.status)));
+		houseLabel.setBounds(200, 90, 220, 30);
+		parameterPanel.add(houseLabel);
+		
+		JLabel keywordsLabel = new JLabel("Room Seperation Keywords: " + room1Keyword + " " + room2Keyword);
+		keywordsLabel.setBounds(200, 120, 320, 30);
+		parameterPanel.add(keywordsLabel);
+		
+		JLabel keywordsHintLabel = new JLabel("HolonElements with a name that contains the Keyword count.");
+		keywordsHintLabel.setBounds(200, 135, 450, 30);
+		parameterPanel.add(keywordsHintLabel);
+		
+		
+		JButton selectRotorButton = new JButton("Select");
+		selectRotorButton.setBounds(420,65, 90, 20);
+		selectRotorButton.addActionListener(actionEvent -> this.selectGroupNode(rotor));
+		parameterPanel.add(selectRotorButton);
+		
+		JButton selectRoom1Button = new JButton("Select");
+		selectRoom1Button.setBounds(420,95, 90, 20);
+		selectRoom1Button.addActionListener(actionEvent -> this.selectGroupNode(house));
+		parameterPanel.add(selectRoom1Button);
+		
+		
+		
+		return parameterPanel;
+	}
+
+
+
+	private String stringToHtml(String string) {
+		return "<html>" + string + "</html>";
+	}
+
+	private String statusToString(HolonObjectStatus status) {
+		switch(status) {
+		case Connected:
+			return stringWithColor("Connected", "green");
+		case NotSelected:
+			return stringWithColor("Not selected", "red");
+		case ObjectDeleted:
+			return stringWithColor("Object deleted", "red");
+		default:
+			return "";
+		
+		}
+	}
+	private String stringWithColor(String string, String color) {
+		return "<font color='"+color + "'>" + string + "</font>";
+	}
+
+	private void  updateStatusLabels() {
+		rotorLabel.setText(stringToHtml("Rotor Status: " + statusToString(rotor.status)));
+		houseLabel.setText(stringToHtml("House Status: " + statusToString(house.status)));
+	}
+	
+	
+	
+	private Component createButtonPanel() {
+		JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
+		JButton clearButton =  new JButton("Clear Console");
+		clearButton.addActionListener(actionEvent -> console.clear());
+		buttonPanel.add(clearButton);
+		JButton stopButton =  new JButton("Stop");
+		stopButton.addActionListener(actionEvent -> stop());
+		buttonPanel.add(stopButton);
+		JButton runButton =  new JButton("Run");
+		runButton.addActionListener(actionEvent -> initSchedule());
+		buttonPanel.add(runButton);
+		return buttonPanel;
+	}
+
+	
+	private void stop() {
+		if(future!= null) {
+			if(future.isCancelled()) {
+				console.println("Is cancelled.");
+			}
+			else {
+				future.cancel(true);
+				console.println("Stopped sending Requests on localhost:2019 ...");
+			}
+		}
+		else {
+			console.println("Not started jet.");
+		}
+	}
+
+	private void initSchedule() {
+		if(future != null && !future.isCancelled()) {
+			console.println("Is running.");
+			return;
+		}
+		warningLabel.setVisible(false);
+		console.println("Starting sending Requests on localhost:2019");
+		final ScheduledExecutorService 	executorService = Executors.newSingleThreadScheduledExecutor();
+		final Runnable beeper = new Runnable() {
+				
+				//RepeatedMethod
+		       	public void run() {
+		       		if(lessInformation)console.print(".");
+		       		checkWrapper(rotor);
+		       		checkWrapperHouseSpecial(house);
+		       	}
+
+
+				private void checkWrapper(PhysicalLinkWrapper wrapper) {
+					if(wrapper.status == HolonObjectStatus.Connected) checkConnected(wrapper);
+		       		else if(!lessInformation)console.println(wrapper.postAddress +" is not connected.");
+				}
+
+				private void checkConnected(PhysicalLinkWrapper wrapper) {
+					if(wrapper.hObject == null) {
+						wrapper.status =  HolonObjectStatus.ObjectDeleted;
+						updateStatusLabels();
+						return;
+					}
+					if(wrapper.hObject.getNumberOfElements() > 0) {
+						//OnlyForRotor
+						
+						int value = Math.round(((float)wrapper.hObject.getNumberOfActiveElements()/(float) wrapper.hObject.getNumberOfElements())*(float) 100);					
+						if(onlyOnChange) {
+							if(oldValueRotor != value) {
+								sendRequest(wrapper.postAddress, value);
+								oldValueRotor = value; 
+							}
+						}else {
+							sendRequest(wrapper.postAddress, value);
+						}
+						
+						
+					}else {
+						if(onlyOnChange) {
+							if(oldValueRotor != 0) {
+								sendRequest(wrapper.postAddress, 0);
+								oldValueRotor = 0; 
+							}
+						}else {
+							sendRequest(wrapper.postAddress, 0);
+						}
+					}
+						
+					
+						
+				}
+
+				private void sendRequest(String postAddress, int value) {
+					if(!lessInformation)console.println("Send " + "http://localhost:2019" + postAddress + value);
+					doHttpUrlConnectionAction("http://localhost:2019" + postAddress + value);
+				
+				}
+
+				  /**
+				   * Send A Request to a URL.
+				   * 
+				   * @param desiredUrl
+				   * @return
+				   */
+				  private void doHttpUrlConnectionAction(String desiredUrl)
+				  {
+				    URL url = null;
+
+				      // create the HttpURLConnection
+				      try {
+						url = new URL(desiredUrl);
+					
+				      HttpURLConnection connection = (HttpURLConnection) url.openConnection();
+				      
+				      // just want to do an HTTP GET here
+				      connection.setRequestMethod("GET");
+
+				      connection.getResponseCode();
+				     
+				      // give it 15 seconds to respond
+				      connection.setReadTimeout(1000);
+				      connection.connect();
+				      } catch (MalformedURLException e) {
+				    	  console.println("MalformedURLException");
+				    	  e.printStackTrace();
+					} catch (IOException e) {
+						console.println("IOException: Connection refused");
+						e.printStackTrace();
+					}
+				  }
+				  private void checkWrapperHouseSpecial(PhysicalLinkWrapper house) {
+					if(!(house.status == HolonObjectStatus.Connected)) {
+						if(!lessInformation)console.println("House" + " is not connected.");
+						return;
+					}
+			       	//House is Connected
+					if(house.hObject == null) {
+						house.status =  HolonObjectStatus.ObjectDeleted;
+						updateStatusLabels();
+						return;
+					}
+					//House exist
+					List<HolonElement> elementsOfRoom1 = house.hObject.getElements().stream().filter(ele -> ele.getEleName().contains(room1Keyword)).collect(Collectors.toList());
+					List<HolonElement> elementsOfRoom2 = house.hObject.getElements().stream().filter(ele -> ele.getEleName().contains(room2Keyword)).collect(Collectors.toList());
+					
+					if(elementsOfRoom1.isEmpty()){
+						if(onlyOnChange) {
+							if(oldValueRoom1 != 0) {
+								sendRequest(room1Address, 0);
+								oldValueRoom1 = 0; 
+							}
+						}else {
+							sendRequest(room1Address, 0);
+						}
+					}
+					else{
+						int value = Math.round(((float)elementsOfRoom1.stream().filter(ele -> ele.isActive()).count()/(float) elementsOfRoom1.size())*(float) 100);					
+						if(onlyOnChange) {
+							if(oldValueRoom1 != value) {
+								sendRequest(room1Address, value);
+								oldValueRoom1 = value; 
+							}
+						}else {
+							sendRequest(room1Address, value);
+						}
+					}
+					if(elementsOfRoom2.isEmpty()){
+						if(onlyOnChange) {
+							if(oldValueRoom2 != 0) {
+								sendRequest(room2Address, 0);
+								oldValueRoom2 = 0; 
+							}
+						}else {
+							sendRequest(room2Address, 0);
+						}
+					}
+					else{
+						int value = Math.round(((float)elementsOfRoom2.stream().filter(ele -> ele.isActive()).count()/(float) elementsOfRoom2.size())*(float) 100);					
+						if(onlyOnChange) {
+							if(oldValueRoom2 != value) {
+								sendRequest(room2Address, value);
+								oldValueRoom2 = value; 
+							}
+						}else {
+							sendRequest(room2Address, value);
+						}
+					}
+					
+					
+				  }
+		     };
+		future = executorService.scheduleAtFixedRate(beeper, 0, delay, TimeUnit.MILLISECONDS);
+	}
+	
+
+	
+	private void addObjectToList(List<AbstractCpsObject> listToSearch, List<HolonObject> listToAdd){
+		for (AbstractCpsObject aCps : listToSearch) {
+			if (aCps instanceof HolonObject) listToAdd.add((HolonObject) aCps);
+			else if(aCps instanceof CpsUpperNode) {
+				addObjectToList(((CpsUpperNode)aCps).getNodes(),listToAdd);
+			}
+		}
+	}
+	
+	//SelectGroupNode
+	private void selectGroupNode(PhysicalLinkWrapper wrapper) {
+		List<HolonObject> holonObjectList = new ArrayList<HolonObject>();
+		addObjectToList(control.getModel().getObjectsOnCanvas(),holonObjectList);
+		Object[] possibilities = holonObjectList.stream().map(aCps -> new Handle<HolonObject>(aCps)).toArray();
+		@SuppressWarnings("unchecked")
+		Handle<HolonObject> selected = (Handle<HolonObject>) JOptionPane.showInputDialog(content, "Select HolonObject:", "HolonObject?",  JOptionPane.OK_OPTION,new ImageIcon(new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB)) , possibilities, "");
+		if(selected != null) {
+			console.println("Selected: " + selected);
+			wrapper.hObject = selected.object;
+			wrapper.status = HolonObjectStatus.Connected;
+			updateStatusLabels();
+		}
+	}
+	private   class  Handle<T>{
+		public T object;
+		Handle(T object){
+			this.object = object;
+		}
+		public String toString() {
+			return object.toString();
+		}
+	}
+	
+	
+	@Override
+	public JPanel getAlgorithmPanel() {
+		return content;
+	}
+
+	@Override
+	public void setController(Control control) {
+		this.control = control;
+	}
+	
+
+	
+	
+
+}

+ 312 - 0
src/connection/socket/Server.java

@@ -0,0 +1,312 @@
+package connection.socket;
+import java.net.*;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+
+import classes.HolonElement;
+import classes.HolonObject;
+import ui.controller.Control;
+
+import java.io.*;
+
+public class Server implements Runnable{
+	private ServerSocket serverSocket;
+    private Socket clientSocket;
+    private DataOutputStream out;
+    private DataInputStream in;
+    private boolean stopped = false;		
+    private boolean connection = false;
+    private ui.view.Console console;
+    
+    
+    private HolonObject observed;
+	private HolonObjectModel modelField;
+    private HolonObjectModel newModelField;
+	private Control control;
+    
+    public Server(int port, ui.view.Console console, HolonObject observed, Control control) throws IOException {
+    	this.observed = observed;
+    	this.console = console;
+    	this.control = control;
+    	//Bind Port
+    	serverSocket = new ServerSocket(port);
+        //Wait for Connection
+    	Thread serverThread = new Thread(this);
+        serverThread.start();
+        this.modelField = createModel();
+        this.newModelField = createModel();
+        
+        
+    }
+ 
+    public void stopServer() throws IOException {
+    	stopped = true;
+        stopConnection();
+        if(serverSocket != null)serverSocket.close();
+		console.println("Server Closed");
+    }
+
+	private void stopConnection() throws IOException {
+		connection = false;
+		if(in != null)in.close();
+		if(out != null)out.close();
+		if(clientSocket != null)clientSocket.close();
+	}
+
+	@Override
+	public void run() {
+		while(!stopped) {
+			try {
+			//Wait for new Connection
+			console.println("Wait for Connection..");
+			clientSocket = serverSocket.accept();
+			console.println("Connection from " + clientSocket.getInetAddress() + ":" + clientSocket.getPort());
+			connection = true;
+			out = new DataOutputStream(clientSocket.getOutputStream());
+			in = new DataInputStream(new BufferedInputStream(clientSocket.getInputStream()));
+			if(observed == null) stopConnection();	
+			this.modelField = createModel();
+			Thread updateThread = new Thread(new UpdateLoop());
+			updateThread.start();
+			//InputLoop
+			try {
+				inputLoop();
+			}catch(EOFException e){
+				console.println("Connection Closed");
+			}
+			stopConnection();	
+			}
+			catch(SocketException e){
+				//ServerSocket is closed
+				stopped = true;
+			}
+			catch (IOException e) {
+				e.printStackTrace();
+			}
+			connection = false;
+		}
+	}
+
+	private void inputLoop() throws IOException {
+		while (connection) {
+			//WaitForInput
+			byte inputByte = in.readByte();
+			//UpdateHoleg
+			if (inputByte == Command.SetAmount) {
+				if(observed == null) stopConnection();
+				console.println("Res: [" + inputByte + "] -> SetAmount");
+				int index = in.readInt();
+				int amount = in.readInt();
+				modelField.getElements().get(index).amount = amount;
+				observed.getElements().get(index).setAmount(amount);
+				
+			}else if (inputByte == Command.SetEnable) {
+				if(observed == null) stopConnection();
+				console.println("Res: [" + inputByte + "] -> SetEnable");
+				int index = in.readInt();
+				boolean enabled = in.readBoolean();
+				modelField.getElements().get(index).enabled = enabled;
+				observed.getElements().get(index).setActive(enabled);
+			}else if (inputByte == Command.IncreaseAmount) {
+				if(observed == null) stopConnection();
+				console.println("Res: [" + inputByte + "] -> IncreaseAmount");
+				int index = in.readInt();
+				modelField.getElements().get(index).amount++;
+				HolonElement ele = observed.getElements().get(index);
+				ele.setAmount(ele.getAmount()+1);
+				
+			}else if (inputByte == Command.DecreaseAmount) {
+				if(observed == null) stopConnection();
+				console.println("Res: [" + inputByte + "] -> DecreaseAmount");
+				int index = in.readInt();
+				modelField.getElements().get(index).amount--;
+				HolonElement ele = observed.getElements().get(index);
+				ele.setAmount(ele.getAmount()-1);
+				
+			} else{
+				console.println("Res: [" + inputByte + "] -> unknown");
+			}
+			control.calculateStateAndVisualForCurrentTimeStep();
+			control.updateCanvas();
+			control.getGui().triggerUpdateController(null);
+		}
+	}
+	
+	
+	private HolonObjectModel createModel() {
+		HolonObjectModel model = new HolonObjectModel();
+		int index = 0;
+		for(HolonElement ele :observed.getElements()) {
+			model.add(ele, index++);
+		}
+		return model;
+	}
+	
+	
+	
+	
+	
+	public class UpdateLoop implements Runnable{
+		public UpdateLoop(){
+		}
+		@Override
+		public void run() {
+			sendUpdate();
+			while(!stopped && connection) {
+				if(checkForUpdates()){
+					sendUpdate();
+				}else {
+					waitOneSecond();	
+				}
+			}
+			
+		}
+
+		private void waitOneSecond() {
+			//wait one second
+			try {
+				TimeUnit.SECONDS.sleep(1);
+			} catch (InterruptedException e) {
+			}
+		}
+
+		private boolean checkForUpdates() {
+			//TODO Delete And CheckforUpdatesReal
+			newModelField = createModel();
+			if(compareModels(modelField,newModelField)) {
+				return false;
+			}
+			modelField = newModelField;
+			return true;
+			
+		}
+		/**
+		 * Returns true if both are the same.
+		 * @param modelField
+		 * @param newModelField
+		 * @return
+		 */
+		private void sendUpdate() {
+			try {
+				if(observed == null) stopConnection();
+				console.println("Send: [" + Command.Update + "] -> Update");
+				out.writeByte(Command.Update);
+				out.writeInt(modelField.size());
+				for(HolonElementWrapper wrapper : modelField.getElements()) {
+					out.writeUTF(wrapper.name);
+					out.writeInt(wrapper.amount);
+					out.writeFloat(wrapper.energy);
+					out.writeBoolean(wrapper.enabled);
+				}
+				
+				
+				
+			} catch (IOException e) {
+				if(connection)console.println(e.getMessage());
+			}
+		}
+	}
+	
+	private boolean compareModels(HolonObjectModel model, HolonObjectModel newModel) {
+		if(model.size() != newModel.size()) {
+			return false;
+		}
+		for(int i = 0; i < model.size(); i++) {
+			if(!model.getElements().get(i).equals(newModel.getElements().get(i))) {				
+				return false;
+			}
+		}
+		return true;
+	}
+	public void setObserved(HolonObject observed) {
+		this.observed = observed;
+	}
+	
+	public class Command {
+		//InputCommands
+		public static final int SetAmount = 10;
+		public static final int SetEnable = 11;
+		public static final int IncreaseAmount = 12;
+		public static final int DecreaseAmount = 13;
+		//UpdateResiveCommands
+		public static final int Update = 20;
+	}
+	
+	
+	
+	public class HolonObjectModel {
+		//Field
+		private List<HolonElementWrapper> elements;
+		private String holonObjectName;
+		
+		//constructor
+		public HolonObjectModel(){
+			elements = new ArrayList<HolonElementWrapper>();
+		}
+		
+		
+		public void add(HolonElement ele, int index ) {
+			String name = ele.getEleName();
+			int amount =ele.getAmount();
+			float energy =  ele.getEnergyPerElement();
+			boolean enabled = ele.isActive();
+			elements.add(new HolonElementWrapper(name, amount, energy, enabled, index));
+		}
+		
+		public int size() {
+			return elements.size();
+		}
+
+		//Getter/Setter
+		public List<HolonElementWrapper> getElements() {
+			return elements;
+		}
+		
+		public String getHolonObjectName() {
+			return holonObjectName;
+		}
+		public void setHolonObjectName(String holonObjectName) {
+			this.holonObjectName = holonObjectName;
+		}
+
+	}
+	public class HolonElementWrapper{
+		public int index;
+		public String name;
+		public int amount;
+		public float energy;
+		public boolean enabled;
+		public HolonElementWrapper(){
+			
+		}
+		public HolonElementWrapper(String name, int amount, float energy, boolean enabled, int index){
+			this.name = name;
+			this.amount = amount;
+			this.energy = energy;
+			this.enabled = enabled;
+		}
+		@Override
+		public boolean equals(Object obj) {
+			if (obj == this) {
+				return true;
+			}
+			if (!(obj instanceof HolonElementWrapper)) {
+			   return false;
+			}
+			HolonElementWrapper element = (HolonElementWrapper) obj;
+			
+			
+			
+			return this.name.compareTo(element.name) == 0 &&
+				   this.amount == element.amount &&
+				   this.energy == element.energy &&
+				   this.enabled == element.enabled;
+		}
+		
+	}
+	
+	
+	
+	
+}

+ 477 - 0
src/exampleAlgorithms/BaseLine.java

@@ -0,0 +1,477 @@
+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.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.Comparator;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+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.filechooser.FileNameExtensionFilter;
+import javax.swing.text.NumberFormatter;
+
+import api.Algorithm;
+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.model.DecoratedHolonObject.HolonObjectState;
+import ui.model.DecoratedGroupNode;
+import ui.model.DecoratedNetwork;
+import ui.model.DecoratedState;
+
+
+
+
+
+public class BaseLine implements Algorithm {
+	//Parameter for Algo with default Values:
+	private boolean closeSwitches = true;
+	
+	//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;
+	private List<Boolean> initialState;
+	private List<HolonSwitch> switchList;
+	private List<HolonObject> objectList;
+	
+	//Gui Part:
+	private Control  control;
+	private JTextArea textArea;
+	private JPanel content = new JPanel();
+	//ProgressBar
+	private JProgressBar progressBar = new JProgressBar();
+	private int progressBarCount = 0;
+	private long startTime;
+	private Thread runThread;
+	
+	
+	public static void main(String[] args)
+	{
+	      JFrame newFrame = new JFrame("exampleWindow");
+	      BaseLine instance = new BaseLine();
+	      newFrame.setContentPane(instance.getAlgorithmPanel());
+	      newFrame.pack();
+	      newFrame.setVisible(true);
+	      newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+	}
+	public BaseLine() {
+		content.setLayout(new BorderLayout());
+	
+		textArea = new JTextArea();
+		textArea.setEditable(false);
+		JScrollPane scrollPane = new JScrollPane(textArea);
+		JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
+				createOptionPanel() , scrollPane);
+		splitPane.setResizeWeight(0.0);
+		content.add(splitPane, BorderLayout.CENTER);
+		content.setPreferredSize(new Dimension(800,800));	
+	}
+	public JPanel createOptionPanel() {
+		JPanel optionPanel = new JPanel(new BorderLayout());
+		JScrollPane scrollPane = new JScrollPane(createParameterPanel());
+		scrollPane.setBorder(BorderFactory.createTitledBorder("Parameter"));
+		optionPanel.add(scrollPane,  BorderLayout.CENTER);
+		optionPanel.add(createButtonPanel(), BorderLayout.PAGE_END);
+		return optionPanel;
+	}
+	
+	private Component createParameterPanel() {
+		JPanel parameterPanel = new JPanel(null);
+		parameterPanel.setPreferredSize(new Dimension(510,300));
+		
+		
+	
+		JLabel showDiagnosticsLabel = new JLabel("Set all switches closed:");
+		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);
+		
+		
+		JCheckBox switchesCheckBox = new JCheckBox();
+		switchesCheckBox.setSelected(closeSwitches);
+		switchesCheckBox.setBounds(370, 60, 25, 20);
+		switchesCheckBox.addActionListener(actionEvent -> closeSwitches = switchesCheckBox.isSelected());
+		parameterPanel.add(switchesCheckBox);
+		
+
+		
+		
+		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 clearButton =  new JButton("Clear Console");
+		clearButton.addActionListener(actionEvent -> clear());
+		buttonPanel.add(clearButton);
+		JButton resetButton =  new JButton("Reset");
+		resetButton.setToolTipText("Resets the State to before the Algorithm has runed.");
+		resetButton.addActionListener(actionEvent -> reset());
+		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 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);
+		startTimer();
+		executeBaseLine();
+		if(cancel) {
+			reset();
+			disableGuiInput(false);
+			return;
+		}
+		printElapsedTime();
+		disableGuiInput(false);
+	}
+	
+	private void reset() {
+		if(initialState != null) {
+			println("Resetting..");
+			resetState();
+			updateVisual();
+		}else {
+			println("No run inistialized.");
+		}
+	}
+	
+	
+	private void disableGuiInput(boolean bool) {
+		control.guiDiable(bool);
+	}
+	
+	
+	
+
+	
+	
+	@Override
+	public JPanel getAlgorithmPanel() {
+		return content;
+	}
+	@Override
+	public void setController(Control control) {
+		this.control = control;
+		
+	}
+	private void clear() {
+		textArea.setText("");
+	}
+	private void print(String message) {
+		textArea.append(message);
+	}
+	private void println(String message) {
+		textArea.append(message  + "\n");
+	}
+	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 = 100;
+		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);
+	}
+	
+	
+	
+	
+	//Algo Part:
+	/**
+	 * The Execution of the BaseLine Algo.
+	 * 
+	 * 
+	 * Begin
+	 * 		set HolonElements aktiv;
+	 * 		for(All Networks) do
+	 * 			if(not (production < consumption)) continue;
+	 * 			inAktiveCount = 0;
+	 * 			while(inAktiveCount <= consumerWihtMaxNumberElements) do
+	 * 				conList = createListWithConsumerThatHaveInActiveElementsAmountOf(inAktiveCount);
+	 * 				sortByBiggestElement(conList);
+	 * 				for(con : conList) do
+	 * 					for(element : con.getAllActiveElementsSortByConsumption) do 
+	 * 						if(element <= production) do 
+	 * 							set element inAktiv;
+	 * 							continue;
+	 * 						end do
+	 * 					end do
+	 * 				end do
+	 * 				inAktiveCount += 1;
+	 * 			end while
+	 * 		end for
+	 * End
+	 * 
+	 */
+	private void executeBaseLine() {
+		extractPositionAndAccess();
+		int actualIteration = control.getModel().getCurIteration();
+		if(closeSwitches)setAllSwitchesClosed();
+		setHolonElemntsAktiv();
+		control.calculateStateAndVisualForCurrentTimeStep();
+		DecoratedState actualstate = control.getSimManager().getActualDecorState();	
+		for(DecoratedNetwork net : actualstate.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);
+			float difference = Math.abs(production - consumption);
+			println("production:" + production + "  consumption:" + consumption);
+			if(!(production < consumption))continue;
+			if(net.getConsumerList().isEmpty() && net.getConsumerSelfSuppliedList().isEmpty())continue;
+			//Stream.concat(net.getConsumerList().stream(), net.getConsumerSelfSuppliedList().stream());
+			int consumerWihtMaxNumberElements = Stream.concat(net.getConsumerList().stream(), net.getConsumerSelfSuppliedList().stream()).map(con -> con.getModel().getNumberOfElements()).max((lhs,rhs) ->Integer.compare(lhs, rhs)).orElse(0);
+			println("consumerWihtMaxNumberElements:" + consumerWihtMaxNumberElements);
+			for(int inAktiveCount = 0;inAktiveCount <= consumerWihtMaxNumberElements; inAktiveCount++) {
+				println("inAktiveCount:" + inAktiveCount);
+				final int inAktiveCountFinal = inAktiveCount;
+				List<HolonObject> conList = Stream.concat(net.getConsumerList().stream(), net.getConsumerSelfSuppliedList().stream()).map(con -> con.getModel()).filter(object -> objectList.contains(object)).filter(object -> (object.getNumberOfInActiveElements() == inAktiveCountFinal)).collect(Collectors.toList());
+				conList.sort((a,b) -> Float.compare(a.getMaximumConsumingElementEnergy(actualIteration), b.getMaximumConsumingElementEnergy(actualIteration)));
+				consumer:
+				for(HolonObject con: conList) {
+					//println("Consumer" + con);
+					List<HolonElement> sortedElementList = con.getElements().stream().filter(ele -> ele.isActive() && ele.isConsumer()).sorted((a,b) -> -Float.compare(-a.getEnergyAtTimeStep(actualIteration), -b.getEnergyAtTimeStep(actualIteration))).collect(Collectors.toList());
+					for(HolonElement element: sortedElementList) {
+						float elementConsumption = -element.getEnergyAtTimeStep(actualIteration);
+						if(elementConsumption <= difference) {
+							println("elementConsumption:" + elementConsumption);
+							difference -= elementConsumption;
+							element.setActive(false);
+							continue consumer;
+						}
+					}
+				}
+			}
+		}
+		updateVisual();
+	}
+
+	
+	
+
+	private void setHolonElemntsAktiv() {
+		for(int i = 0;i<access.size();i++) {
+			AccessWrapper aw = access.get(i);
+			if(aw.getType() == AccessWrapper.HOLONELEMENT) aw.setState(true);
+		}
+	}
+	private void setAllSwitchesClosed() {
+		for(HolonSwitch hSwitch : switchList) {
+			hSwitch.setManualMode(true);
+			hSwitch.setManualState(true);
+		}
+		
+	}
+	/**
+	 * 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>();
+		initialState = new ArrayList<Boolean>(); 
+		access= new HashMap<Integer, AccessWrapper>();
+		rollOutNodes((useGroupNode && (dGroupNode != null))? dGroupNode.getModel().getNodes() :model.getObjectsOnCanvas(), initialState, model.getCurIteration());
+		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 );
+			}
+		}
+	}
+	/**
+	 * 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(initialState);
+	}
+	
+	/**
+	 * 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 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;
+		}
+	}
+	
+	
+	
+	
+	private   class  Handle<T>{
+		public T object;
+		Handle(T object){
+			this.object = object;
+		}
+		public String toString() {
+			return object.toString();
+		}
+	}
+	
+}

+ 495 - 0
src/exampleAlgorithms/DemoAlgo.java

@@ -0,0 +1,495 @@
+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.text.NumberFormat;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import javax.swing.BorderFactory;
+import javax.swing.ImageIcon;
+import javax.swing.JButton;
+import javax.swing.JCheckBox;
+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.Algorithm;
+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.DecoratedNetwork;
+import ui.model.DecoratedState;
+import ui.model.Model;
+
+public class DemoAlgo implements Algorithm {
+
+	//Parameter for Algo with default Values:
+		private boolean closeSwitches = true;
+		
+		//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;
+		private List<Boolean> initialState;
+		private List<HolonSwitch> switchList;
+		private List<HolonObject> objectList;
+		
+		//Gui Part:
+		private Control  control;
+		private JTextArea textArea;
+		private JPanel content = new JPanel();
+		//ProgressBar
+		private JProgressBar progressBar = new JProgressBar();
+		private int progressBarCount = 0;
+		private long startTime;
+		private Thread runThread;
+		//Windrad
+		private HolonObject windrad;
+		
+		
+		private int waitDurationWindradStep = 400;
+		private int waitDurationEnd = 1000;
+
+		int counter;
+		
+		
+		public static void main(String[] args)
+		{
+		      JFrame newFrame = new JFrame("exampleWindow");
+		      DemoAlgo instance = new DemoAlgo();
+		      newFrame.setContentPane(instance.getAlgorithmPanel());
+		      newFrame.pack();
+		      newFrame.setVisible(true);
+		      newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+		}
+		public DemoAlgo() {
+			content.setLayout(new BorderLayout());
+		
+			textArea = new JTextArea();
+			textArea.setEditable(false);
+			JScrollPane scrollPane = new JScrollPane(textArea);
+			JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
+					createOptionPanel() , scrollPane);
+			splitPane.setResizeWeight(0.0);
+			content.add(splitPane, BorderLayout.CENTER);
+			content.setPreferredSize(new Dimension(800,800));	
+		}
+		public JPanel createOptionPanel() {
+			JPanel optionPanel = new JPanel(new BorderLayout());
+			JScrollPane scrollPane = new JScrollPane(createParameterPanel());
+			scrollPane.setBorder(BorderFactory.createTitledBorder("Parameter"));
+			optionPanel.add(scrollPane,  BorderLayout.CENTER);
+			optionPanel.add(createButtonPanel(), BorderLayout.PAGE_END);
+			return optionPanel;
+		}
+		
+		private Component createParameterPanel() {
+			JPanel parameterPanel = new JPanel(null);
+			parameterPanel.setPreferredSize(new Dimension(510,300));
+			
+			
+		
+//			JLabel showDiagnosticsLabel = new JLabel("Set all switches closed:");
+//			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);
+			
+			
+//			JCheckBox switchesCheckBox = new JCheckBox();
+//			switchesCheckBox.setSelected(closeSwitches);
+//			switchesCheckBox.setBounds(370, 60, 25, 20);
+//			switchesCheckBox.addActionListener(actionEvent -> closeSwitches = switchesCheckBox.isSelected());
+//			parameterPanel.add(switchesCheckBox);
+			
+			JButton selectRoom1Button = new JButton("Select");
+			selectRoom1Button.setBounds(10,300, 90, 20);
+			selectRoom1Button.addActionListener(actionEvent -> this.selectHolonObject());
+			parameterPanel.add(selectRoom1Button);
+			NumberFormat format = NumberFormat.getIntegerInstance();
+			format.setGroupingUsed(false);
+			format.setParseIntegerOnly(true);
+			NumberFormatter integerFormatter = new NumberFormatter(format);
+			integerFormatter.setMinimum(0);
+			integerFormatter.setCommitsOnValidEdit(true);
+			JLabel portLabel = new JLabel("between:");
+			portLabel.setBounds(10, 330, 70, 30);
+			parameterPanel.add(portLabel);
+			JFormattedTextField betweenTF = new JFormattedTextField(integerFormatter);
+			betweenTF.setText(""+waitDurationWindradStep);
+			betweenTF.setBounds(80 ,330, 80, 30);
+			betweenTF.addPropertyChangeListener(propertyChange ->{
+				String text = betweenTF.getValue().toString();
+				text = text.replaceAll("\\s", "");
+				waitDurationWindradStep = Integer.parseInt((text));
+			});
+			parameterPanel.add(betweenTF);
+			JLabel afterLabel = new JLabel("after:");
+			afterLabel.setBounds(10, 360, 70, 30);
+			parameterPanel.add(afterLabel);
+			JFormattedTextField afterTF = new JFormattedTextField(integerFormatter);
+			afterTF.setText(""+waitDurationEnd);
+			afterTF.setBounds(80 ,360, 80, 30);
+			afterTF.addPropertyChangeListener(propertyChange ->{
+				String text = afterTF.getValue().toString();
+				text = text.replaceAll("\\s", "");
+				waitDurationEnd = Integer.parseInt((text));
+			});
+			parameterPanel.add(afterTF);
+			
+			
+			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 clearButton =  new JButton("Clear Console");
+			clearButton.addActionListener(actionEvent -> clear());
+			buttonPanel.add(clearButton);
+			JButton resetButton =  new JButton("Reset");
+			resetButton.setToolTipText("Resets the State to before the Algorithm has runed.");
+			resetButton.addActionListener(actionEvent -> reset());
+			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 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);
+			startTimer();
+			executeDemoAlgo();
+			if(cancel) {
+				reset();
+				disableGuiInput(false);
+				return;
+			}
+			printElapsedTime();
+			disableGuiInput(false);
+		}
+		
+		private void reset() {
+			if(initialState != null) {
+				println("Resetting..");
+				resetState();
+				updateVisual();
+			}else {
+				println("No run inistialized.");
+			}
+		}
+		
+		
+		private void disableGuiInput(boolean bool) {
+			control.guiDiable(bool);
+		}
+		
+		
+		
+
+		
+		
+		@Override
+		public JPanel getAlgorithmPanel() {
+			return content;
+		}
+		@Override
+		public void setController(Control control) {
+			this.control = control;
+			
+		}
+		private void clear() {
+			textArea.setText("");
+		}
+		private void print(String message) {
+			textArea.append(message);
+		}
+		private void println(String message) {
+			textArea.append(message  + "\n");
+		}
+		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 = 100;
+			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);
+		}
+		
+		
+		
+		
+		//Algo Part:
+		
+		private void executeDemoAlgo() {
+			extractPositionAndAccess();
+			counter = 0;
+			int actualIteration = control.getModel().getCurIteration();
+			deactivateWindrad();
+			setAllSwitchesClosed();
+			updateVisual();
+			
+			try {
+				//Schalte Slow das Windrad Ein
+				if(windrad == null)return;
+				for(int i = 0; i< windrad.getNumberOfElements(); i++) {
+					windrad.getElements().get(i).setActive(true);
+					TimeUnit.MILLISECONDS.sleep(waitDurationWindradStep);
+					updateVisual();
+				}
+				TimeUnit.MILLISECONDS.sleep(waitDurationEnd);
+			} catch (InterruptedException e) {
+			}
+			
+			setHolonElemntsAktiv(actualIteration);
+			println("Changed Elements: " + counter);
+			updateVisual();
+		}
+
+		
+		
+
+			
+		
+		private void deactivateWindrad() {
+			if(windrad == null)return;
+			windrad.getElements().stream().forEach(ele -> ele.setActive(false));
+		}
+		private void setHolonElemntsAktiv(int actualIteration) {
+			for(int i = 0;i<access.size();i++) {
+				AccessWrapper aw = access.get(i);
+				if(aw.getState(actualIteration) ==false) counter++;
+				if(aw.getType() == AccessWrapper.HOLONELEMENT) aw.setState(true);
+			}
+		}
+		private void setAllSwitchesClosed() {
+			for(HolonSwitch hSwitch : switchList) {
+				if(hSwitch.getManualMode() == false) counter++;
+				hSwitch.setManualMode(true);
+				hSwitch.setManualState(true);
+			}
+			
+		}
+		/**
+		 * 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>();
+			initialState = new ArrayList<Boolean>(); 
+			access= new HashMap<Integer, AccessWrapper>();
+			rollOutNodes((useGroupNode && (dGroupNode != null))? dGroupNode.getModel().getNodes() :model.getObjectsOnCanvas(), initialState, model.getCurIteration());
+			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 );
+				}
+			}
+		}
+		/**
+		 * 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(initialState);
+		}
+		
+		/**
+		 * 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 void selectHolonObject() {
+			List<HolonObject> holonObjectList = new ArrayList<HolonObject>();
+			addObjectToList(control.getModel().getObjectsOnCanvas(),holonObjectList);
+			Object[] possibilities = holonObjectList.stream().map(aCps -> new Handle<HolonObject>(aCps)).toArray();
+			@SuppressWarnings("unchecked")
+			Handle<HolonObject> selected = (Handle<HolonObject>) JOptionPane.showInputDialog(content, "Select HolonObject:", "HolonObject?",  JOptionPane.OK_OPTION,new ImageIcon(new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB)) , possibilities, "");
+			if(selected != null) {
+				//println("Selected: " + selected);
+				windrad = selected.object;
+			}
+		}
+
+
+
+
+		private void addObjectToList(List<AbstractCpsObject> listToSearch, List<HolonObject> listToAdd){
+			for (AbstractCpsObject aCps : listToSearch) {
+				if (aCps instanceof HolonObject) listToAdd.add((HolonObject) aCps);
+				else if(aCps instanceof CpsUpperNode) {
+					addObjectToList(((CpsUpperNode)aCps).getNodes(),listToAdd);
+				}
+			}
+		}
+		
+		
+		
+		
+		/**
+		 * 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;
+			}
+		}
+		
+		
+		
+		
+		private   class  Handle<T>{
+			public T object;
+			Handle(T object){
+				this.object = object;
+			}
+			public String toString() {
+				return object.toString();
+			}
+		}
+
+}

+ 113 - 0
src/exampleAlgorithms/ExampleFitnessFunction.java

@@ -0,0 +1,113 @@
+package exampleAlgorithms;
+
+import java.awt.BorderLayout;
+import java.awt.Component;
+import java.awt.Dimension;
+
+import javax.swing.BoxLayout;
+import javax.swing.JButton;
+import javax.swing.JFrame;
+import javax.swing.JPanel;
+import javax.swing.JScrollPane;
+import javax.swing.JTextArea;
+
+import api.Algorithm;
+import ui.controller.Control;
+import ui.model.DecoratedHolonObject.HolonObjectState;
+import ui.model.DecoratedNetwork;
+import ui.model.DecoratedState;
+
+public class ExampleFitnessFunction implements Algorithm {
+	private Control  control;
+	private JTextArea textArea;
+	private JPanel content = new JPanel();
+//	public static void main(String[] args)
+//	{
+//	      JFrame newFrame = new JFrame("exampleWindow");
+//	      ExampleFitnessFunction instance = new ExampleFitnessFunction();
+//	      newFrame.setContentPane(instance.getAlgorithmPanel());
+//	      newFrame.pack();
+//	      newFrame.setVisible(true);
+//		  newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+//	}
+	public ExampleFitnessFunction(){
+		content.setLayout(new BorderLayout());
+		content.add(createParameterPanel(), BorderLayout.CENTER);
+		JButton buttonRun = new JButton("Run");
+		buttonRun.addActionListener(actionEvent -> run());
+		content.add(buttonRun, BorderLayout.PAGE_END);
+		content.setPreferredSize(new Dimension(300,300));
+	}
+	private void run() {
+		
+		float fitness = getFitnessValue();
+		println("" + fitness);
+	}
+	private JPanel createParameterPanel() {
+		JPanel parameterPanel = new JPanel();
+		parameterPanel.setLayout(new BoxLayout(parameterPanel, BoxLayout.PAGE_AXIS));
+		textArea = new JTextArea();
+		textArea.setEditable(false);
+		JScrollPane scrollPane = new JScrollPane(textArea);
+		parameterPanel.add(scrollPane);
+		return parameterPanel;
+	}
+	@Override
+	public JPanel getAlgorithmPanel() {
+		return content;
+	}
+
+	@Override
+	public void setController(Control control) {
+		this.control = control;
+	}
+	private void clear() {
+		textArea.setText("");
+	}
+	private void print(String message) {
+		textArea.append(message);
+	}
+	private void println(String message) {
+		textArea.append(message + "\n");
+	}
+	
+	private float getFitnessValue() {
+		float overallFitness = 0f;
+		//Calculate all timesteps
+		for(int timestep = 0; timestep <100; timestep++) {
+			control.calculateStateAndVisualForTimeStep(timestep);
+		}
+		//Calculate all timesteps
+		for(int timestep = 0; timestep <100; timestep++) {
+			overallFitness += getFitnessValueForState(control.getSimManager().getDecorState(timestep));
+		}
+		return overallFitness;
+	}
+
+	private float getFitnessValueForState(DecoratedState state) {
+		float fitnessOfTimestep = 0f;
+		for(DecoratedNetwork net : state.getNetworkList()) {
+			fitnessOfTimestep += net.getConsumerList().stream().map(con -> con.getState()).map(objectState -> StateToFloat(objectState)).reduce(0.0f, (a, b) -> (a + b));
+			fitnessOfTimestep += net.getConsumerSelfSuppliedList().stream().map(con -> 1f).reduce(0.0f, (a, b) -> (a + b));
+		}
+		return fitnessOfTimestep;
+	}
+	private float StateToFloat(HolonObjectState state) {
+		switch (state) {
+		case NOT_SUPPLIED:
+			return 10f;
+		case NO_ENERGY:
+			return 15f;
+		case OVER_SUPPLIED:
+			return 5f;
+		case PARTIALLY_SUPPLIED:
+			return 3f;
+		case PRODUCER:
+			return 2f;
+		case SUPPLIED:
+			return 0f;
+		default:
+			return 0f;
+		}
+	}
+}

+ 981 - 0
src/exampleAlgorithms/PSOAlgotihm.java

@@ -0,0 +1,981 @@
+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.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.List;
+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.filechooser.FileNameExtensionFilter;
+import javax.swing.text.NumberFormatter;
+
+import api.Algorithm;
+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.model.DecoratedHolonObject.HolonObjectState;
+import ui.model.DecoratedGroupNode;
+import ui.model.DecoratedNetwork;
+import ui.model.DecoratedState;
+
+
+
+
+
+public class PSOAlgotihm implements Algorithm {
+	//Parameter for Algo with default Values:
+	private int swarmSize = 20; 
+	private int maxIterations = 100; 
+	private double limit = 0.01; 
+	private double dependency = 2.07; 
+	private int rounds = 20;
+	private int mutationInterval = 0;
+	
+	//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;
+	private List<Boolean> initialState;
+	private double c1, c2, w;
+	private RunDataBase db;
+	
+	//Parameter for Plotting (Default Directory in Constructor)
+	private JFileChooser fileChooser = new JFileChooser();
+
+	
+	
+	//Gui Part:
+	private Control  control;
+	private JTextArea textArea;
+	private JPanel content = new JPanel();
+	//ProgressBar
+	private JProgressBar progressBar = new JProgressBar();
+	private int progressBarCount = 0;
+	private long startTime;
+	private Thread runThread;
+	private boolean cancel = false;
+	
+	
+	public static void main(String[] args)
+	{
+	      JFrame newFrame = new JFrame("exampleWindow");
+	      PSOAlgotihm instance = new PSOAlgotihm();
+	      newFrame.setContentPane(instance.getAlgorithmPanel());
+	      newFrame.pack();
+	      newFrame.setVisible(true);
+	      newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+	}
+	public PSOAlgotihm() {
+		content.setLayout(new BorderLayout());
+	
+		textArea = new JTextArea();
+		textArea.setEditable(false);
+		JScrollPane scrollPane = new JScrollPane(textArea);
+		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, 110, 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, 110, 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);*/
+		
+		JFormattedTextField mutationIntervalTextfield = new JFormattedTextField(integerFormatter);
+		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 ------------------------------------------------------------------------------------------
+		
+		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 clearButton =  new JButton("Clear Console");
+		clearButton.addActionListener(actionEvent -> clear());
+		buttonPanel.add(clearButton);
+		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 -> reset());
+		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) {
+			reset();
+			disableGuiInput(false);
+			return;
+		}
+		printElapsedTime();
+		disableGuiInput(false);
+	}
+	private void disableGuiInput(boolean bool) {
+		control.guiDiable(bool);
+	}
+	
+	private void cancel() {
+		if(runThread.isAlive()) {
+			println("");
+			println("Cancel run.");
+			cancel = true;
+			progressBar.setValue(0);
+		} else {
+			println("Nothing to cancel.");
+		}
+	}
+	private void fitness() {
+		initDependentParameter();
+		double currentFitness = evaluatePosition(extractPositionAndAccess(control.getModel()), false);
+		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) {
+			println("Set save File to:" + fileChooser.getSelectedFile().getAbsolutePath());
+		}
+		
+	}
+	private void plott() {
+		if(db!=null) {
+			println("Plott..");
+			db.initFileStream();
+		}else {
+			println("No run inistialized.");
+		}
+	}
+	private void reset() {
+		if(initialState != null) {
+			println("Resetting..");
+			resetState();
+			updateVisual();
+		}else {
+			println("No run inistialized.");
+		}
+	}
+	private void printParameter() {
+		println("SwarmSize:" + swarmSize + ", MaxIter:" + maxIterations + ", Limit:" + limit + ", Dependency:" + dependency + ", Rounds:" + rounds +", DependentParameter: w:"+ w + ", c1:" + c1 + ", c2:" + c2 );
+	}
+	@Override
+	public JPanel getAlgorithmPanel() {
+		return content;
+	}
+	@Override
+	public void setController(Control control) {
+		this.control = control;
+		
+	}
+	private void clear() {
+		textArea.setText("");
+	}
+	private void print(String message) {
+		textArea.append(message);
+	}
+	private void println(String message) {
+		textArea.append(message  + "\n");
+	}
+	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 = 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;
+		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;
+		}
+		println("AlgoResult:" + runBest.value);
+		//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);
+		print("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);				
+				for(int index = 0; index < dimensions; index++) {
+					updateVelocity(particle, index, globalBest);
+					updateGenotype(particle, index);
+		//-------Rolf changes below------------------------
+				if(mutationAllowed == 0 && iteration != 0)
+					mutation(particle, index);
+					decode(particle, index);
+				}
+			}
+			if(cancel)return null;
+			evaluation(globalBest, swarm);
+			runList.add(globalBest.value);
+		}
+		println(" End Value:" + globalBest.value);
+		return globalBest;
+	}
+	/**
+	 * 	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(-4.0, Math.min(4.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
+	 */
+	private 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.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 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.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 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 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) {
+		initialState = new ArrayList<Boolean>(); 
+		access= new HashMap<Integer, AccessWrapper>();
+		rollOutNodes((useGroupNode && (dGroupNode != null))? dGroupNode.getModel().getNodes() :model.getObjectsOnCanvas(), initialState, model.getCurIteration());
+		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(initialState);
+	}
+	
+	/**
+	 * 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.
+	 */
+	private class RunDataBase {
+		List<List<Double>> allRuns;
+		RunDataBase(){
+			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) {
+				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) {
+				println(e.getMessage());
+			}
+			allRuns.forEach(run -> {
+				try {
+					out.write( run.stream().map(Object::toString).collect(Collectors.joining(", ")));
+					out.newLine();
+				} catch (IOException e) {
+					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);
+			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{
+			/**
+			 * True or false
+			 * @return the random boolean.
+			 */
+			public static boolean nextBoolean(){
+				return (Math.random() < 0.5);
+			}
+			/**
+			 * Between 0.0 and 1.0
+			 * @return the random double.
+			 */
+			public static double nextDouble(){
+				return Math.random();
+			}
+		}
+	
+	
+	private   class  Handle<T>{
+		public T object;
+		Handle(T object){
+			this.object = object;
+		}
+		public String toString() {
+			return object.toString();
+		}
+	}
+	
+}

+ 87 - 0
src/exampleAlgorithms/RandomSwitch.java

@@ -0,0 +1,87 @@
+package exampleAlgorithms;
+
+import java.awt.BorderLayout;
+import java.awt.Dimension;
+import java.util.Hashtable;
+
+import javax.swing.BorderFactory;
+import javax.swing.BoxLayout;
+import javax.swing.JButton;
+import javax.swing.JFrame;
+import javax.swing.JLabel;
+import javax.swing.JPanel;
+import javax.swing.JSlider;
+
+import api.Algorithm;
+import classes.HolonSwitch;
+import ui.controller.Control;
+
+public class RandomSwitch implements Algorithm {
+	private double  randomChance = 0.5;
+	private Control  control;
+	
+	private JPanel content = new JPanel();
+//	To Test the Layout Faster   
+//	public static void main(String[] args)
+//    {
+//        JFrame newFrame = new JFrame("exampleWindow");
+//        RandomSwitch instance = new RandomSwitch();
+//        newFrame.setContentPane(instance.getAlgorithmPanel());
+//        newFrame.pack();
+//        newFrame.setVisible(true);
+//	      newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+//    }
+	
+	public RandomSwitch(){
+		content.setLayout(new BorderLayout());
+		content.add(createParameterPanel(), BorderLayout.CENTER);
+		JButton buttonRun = new JButton("Run");
+		buttonRun.addActionListener(actionEvent -> run());
+		content.add(buttonRun, BorderLayout.PAGE_END);
+		content.setPreferredSize(new Dimension(300,300));
+	}
+	private JPanel createParameterPanel() {
+		JPanel parameterPanel = new JPanel();
+		parameterPanel.setLayout(new BoxLayout(parameterPanel, BoxLayout.PAGE_AXIS));
+		parameterPanel.add(createFlipChanceSlider());
+		return parameterPanel;
+	}
+	private JSlider createFlipChanceSlider() {
+		JSlider flipChance =new JSlider(JSlider.HORIZONTAL,0, 100, 50);
+		flipChance.setBorder(BorderFactory.createTitledBorder("FlipChance"));
+		flipChance.setMajorTickSpacing(50);
+		flipChance.setMinorTickSpacing(5);
+		flipChance.setPaintTicks(true);
+		Hashtable<Integer, JLabel> labelTable = new Hashtable<Integer, JLabel>();
+		labelTable.put( new Integer( 0 ), new JLabel("0.0") );
+		labelTable.put( new Integer( 50 ), new JLabel("0.5") );
+		labelTable.put( new Integer( 100 ), new JLabel("1.0") );
+		flipChance.addChangeListener(actionEvent ->randomChance =(double)flipChance.getValue()/100.0);
+		flipChance.setLabelTable( labelTable );
+		flipChance.setPaintLabels(true);
+		return flipChance;
+	}
+	private void run() {
+		for (HolonSwitch s : control.getModel().getSwitches()) {
+			// Set to Manual Mode
+			s.setManualMode(true);
+			// Generate a random number between 0 and 1
+			double randomDouble = Math.random();
+			if (randomDouble < randomChance) {
+				s.setManualState(!s.getActiveManual());
+			} 
+		}
+		control.calculateStateAndVisualForCurrentTimeStep();
+		control.updateCanvas();
+	}
+	@Override
+	public JPanel getAlgorithmPanel() {
+		return content;
+	}
+	@Override
+	public void setController(Control control) {
+		this.control = control;
+		
+	}
+
+}

+ 0 - 34
src/exampleAlgorithms/RandomSwitchesAlgorithm.java

@@ -1,34 +0,0 @@
-package exampleAlgorithms;
-
-import api.CpsAlgorithm;
-import ui.controller.Control;
-import ui.model.Model;
-import classes.*;
-
-public class RandomSwitchesAlgorithm implements CpsAlgorithm {
-
-	@Override
-	public void runAlgorithm(Model model, Control controller) {
-		randomSwitches(model);
-	}
-
-	/**
-	 * Sets every Switch to a random state.
-	 * 
-	 * @param model
-	 *            the Model
-	 */
-	private void randomSwitches(Model model) {
-		for (HolonSwitch s : model.getSwitches()) {
-			// Set to Manual Mode
-			s.setManualMode(true);
-			// Generate a random number between 0 and 1
-			double randomDouble = Math.random();
-			if (randomDouble < 0.5) {
-				s.setManualState(true);
-			} else {
-				s.setManualState(false);
-			}
-		}
-	}
-}

+ 0 - 44
src/exampleAlgorithms/RepairAllEdges.java

@@ -1,44 +0,0 @@
-package exampleAlgorithms;
-
-import api.CpsAlgorithm;
-import classes.AbstractCpsObject;
-import classes.CpsEdge;
-import classes.CpsUpperNode;
-import ui.controller.Control;
-import ui.model.Model;
-
-public class RepairAllEdges implements CpsAlgorithm {
-
-	@Override
-	public void runAlgorithm(Model model, Control controller) {
-		repairAllEdgesOnMainCanvas(model);
-	}
-
-	/**
-	 * Repairs all Edges on the main Canvas.
-	 * 
-	 * @param model
-	 *            the Model
-	 */
-	private void repairAllEdgesOnMainCanvas(Model model) {
-		for (AbstractCpsObject obj : model.getObjectsOnCanvas()) {
-			if (obj instanceof CpsUpperNode) {
-				repairAllEdgesInUpperNode((CpsUpperNode) obj);
-			}
-			for (CpsEdge e : obj.getConnections()) {
-				e.setWorkingState(true);
-			}
-		}
-	}
-
-	private void repairAllEdgesInUpperNode(CpsUpperNode uNode) {
-		for (AbstractCpsObject obj : uNode.getNodes()) {
-			if (obj instanceof CpsUpperNode) {
-				repairAllEdgesInUpperNode((CpsUpperNode) obj);
-			}
-			for (CpsEdge e : obj.getConnections()) {
-				e.setWorkingState(true);
-			}
-		}
-	}
-}

+ 1 - 0
src/ui/controller/CanvasController.java

@@ -403,4 +403,5 @@ public class CanvasController {
 		model.setCanvasImageWidth(width);
 		model.setCanvasImageHeight(height);
 	}
+	
 }

+ 0 - 16
src/ui/controller/CategoryController.java

@@ -167,22 +167,6 @@ public class CategoryController {
 		addObject(category, obj);
 	}
 
-	/**
-	 * Add new Holon Transformer.
-	 * 
-	 * @param cat
-	 *            Category
-	 * @param objName
-	 *            New Object Name
-	 * @param image
-	 *            the image Path
-	 */
-	public void addNewHolonTransformer(Category cat, String objName, String image) {
-		HolonTransformer transformer = new HolonTransformer(objName);
-		transformer.setImage(image);
-		transformer.setSav(cat.getName());
-		addObject(cat, transformer);
-	}
 
 	/**
 	 * Add new Holon Switch.

+ 0 - 63
src/ui/controller/ConsoleController.java

@@ -1,63 +0,0 @@
-package ui.controller;
-
-import java.awt.Color;
-
-import ui.model.Model;
-
-/**
- * Controller for the Canvas.
- * 
- * @author Gruppe14
- */
-public class ConsoleController {
-
-	private Model model;
-
-	/**
-	 * Constructor.
-	 * 
-	 * @param model
-	 *            the Model
-	 */
-	public ConsoleController(Model model) {
-		this.model = model;
-	}
-
-	/**
-	 * Print Text on the console.
-	 *
-	 * @param text
-	 *            String the Text
-	 * @param color
-	 *            the color of the Text
-	 * @param p
-	 *            size of the Text
-	 * @param bold
-	 *            bold or not
-	 * @param italic
-	 *            italic or not
-	 * @param nl
-	 *            new line or not
-	 * 
-	 **/
-	public void addTextToConsole(String text, Color color, int p, boolean bold, boolean italic, boolean nl) {
-		model.getConsole().addText(text, color, p, bold, italic, nl);
-	}
-
-	/**
-	 * Print Text on the console in black and font size 12.
-	 *
-	 * @param text
-	 *            String the Text
-	 */
-	public void addTextToConsole(String text) {
-		model.getConsole().addText(text);
-	}
-
-	/**
-	 * Clears the console.
-	 */
-	public void clearConsole() {
-		model.getConsole().clearConsole();
-	}
-}

+ 41 - 73
src/ui/controller/Control.java

@@ -10,9 +10,12 @@ import interfaces.CategoryListener;
 import org.apache.commons.compress.archivers.ArchiveException;
 
 import ui.model.Model;
+import ui.model.Model.FairnessModel;
 import ui.view.CreateTemplatePopUp;
 import ui.view.FlexiblePane;
+import ui.view.GUI;
 import ui.view.MyCanvas;
+import ui.view.Outliner;
 import ui.view.StatisticGraphPanel;
 
 import java.awt.*;
@@ -32,7 +35,6 @@ import javax.swing.JFrame;
  */
 public class Control {
 
-    private final ConsoleController consoleController;
     private final MultiPurposeController multiPurposeController;
     private final CategoryController categoryController;
     private final ObjectController objectController;
@@ -46,6 +48,7 @@ public class Control {
     private final ClipboardController clipboardController;
     private final HolonCanvasController holonCanvasController;
     private Model model;
+    private GUI gui;
     private SimulationManager simulationManager;
     private String autosaveDir = "";
     private String categoryDir = "";
@@ -72,7 +75,6 @@ public class Control {
                 nodeController, multiPurposeController);
         this.simulationManager = new SimulationManager(model);
         this.autoSaveController = new AutoSaveController(model);
-        this.consoleController = new ConsoleController(model);
         this.statsController = new StatsController(model);
         this.clipboardController = new ClipboardController(model, saveController, loadController, canvasController,
                 objectController, nodeController, multiPurposeController);
@@ -220,15 +222,6 @@ public class Control {
         saveCategory();
     }
 
-    /**
-     * Add new Holon Transformer to a Category.
-     *
-     * @param cat Category
-     * @param obj New Object Name
-     */
-    public void addTransformer(Category cat, String obj) {
-        categoryController.addNewHolonTransformer(cat, obj, "/Images/transformer-1.png");
-    }
 
     /**
      * Add new Holon Switch to a Category.
@@ -308,7 +301,7 @@ public class Control {
      */
     public void addObjectCanvas(AbstractCpsObject object) {
         canvasController.addNewObject(object);
-        simulationManager.calculateStateForTimeStep(model.getCurIteration());
+        calculateStateAndVisualForTimeStep(model.getCurIteration());
         if (!(object instanceof CpsNode)) {
             try {
                 autoSave();
@@ -326,7 +319,7 @@ public class Control {
      */
     public void delCanvasObject(AbstractCpsObject obj, boolean save) {
         canvasController.deleteObjectOnCanvas(obj);
-        calculateStateForCurrentTimeStep();
+        calculateStateAndVisualForCurrentTimeStep();
         if (obj instanceof CpsUpperNode)
             canvasController.bfsNodeCleaner((CpsUpperNode) obj);
         if (save)
@@ -550,19 +543,21 @@ public class Control {
      * calculates the flow of the edges and the supply for objects for the
      * current Timestep.
      */
-    public void calculateStateForCurrentTimeStep() {
-        // simulationManager.reset();
-        simulationManager.calculateStateForTimeStep(model.getCurIteration());
+    public void calculateStateAndVisualForCurrentTimeStep() {
+    	calculateStateAndVisualForTimeStep(model.getCurIteration());
     }
 
+    public void calculateStateOnlyForCurrentTimeStep() {
+    	simulationManager.calculateStateForTimeStep(model.getCurIteration(), false);
+    }
     /**
      * calculates the flow of the edges and the supply for objects.
      *
      * @param x current Iteration
      */
-    public void calculateStateForTimeStep(int x) {
-        // simulationManager.reset();
-        simulationManager.calculateStateForTimeStep(x);
+    public void calculateStateAndVisualForTimeStep(int x) {
+        simulationManager.calculateStateForTimeStep(x, true);
+        updateOutliner();
     }
 
     /**
@@ -571,17 +566,8 @@ public class Control {
      */
     public void resetSimulation() {
         setIsSimRunning(false);
-        simulationManager.resetSimulation();
     }
 
-    /**
-     * Set the Canvas.
-     *
-     * @param can the Canvas
-     */
-    public void setCanvas(MyCanvas can) {
-        simulationManager.setCanvas(can);
-    }
 
     /**
      * make an autosave.
@@ -683,36 +669,7 @@ public class Control {
         return simulationManager;
     }
 
-    /**
-     * Getter for selected CpsObject.
-     *
-     * @param text   String the Text
-     * @param color  the color of the Text
-     * @param p      size of the Text
-     * @param bold   bold or not
-     * @param italic italic or not
-     * @param nl     new line or not
-     */
-    public void addTextToConsole(String text, Color color, int p, boolean bold, boolean italic, boolean nl) {
-        consoleController.addTextToConsole(text, color, p, bold, italic, nl);
-    }
-
-    /**
-     * Print Text on the console in black and font size 12.
-     *
-     * @param text String the Text
-     */
-    public void addTextToConsole(String text) {
-        consoleController.addTextToConsole(text);
-    }
-
-    /**
-     * Clears the console.
-     */
-    public void clearConsole() {
-        consoleController.clearConsole();
-    }
-
+  
     /**
      * Set the timerSpeed.
      *
@@ -825,7 +782,7 @@ public class Control {
     }
 
     public void addObjUpperNode(AbstractCpsObject object, CpsUpperNode upperNode) {
-        nodeController.addObjectInUpperNode(object, upperNode, true);
+    	nodeController.addObjectInUpperNode(object, upperNode, true);
         try {
             autoSave();
         } catch (IOException e) {
@@ -907,17 +864,17 @@ public class Control {
     public int getNumberHolonObjects(ArrayList<AbstractCpsObject> list) {
         return objectController.getNumberHolonObjects(list);
     }
-
+    
     /**
-     * Get the number of HolonObjects with the given state in the given List
+     * Get the number of HolonObjects in the given List
      *
      * @param list
-     * @param state
      */
-    public int getNumberStateObjects(ArrayList<AbstractCpsObject> list, int state) {
-        return objectController.getNumberStateObjects(list, state);
+    public ArrayList<HolonObject> getAllHolonObjects(ArrayList<AbstractCpsObject> list) {
+        return objectController.getAllHolonObjects(list);
     }
 
+
     /**
      * Returns HolonBodySCALE.
      *
@@ -1036,14 +993,6 @@ public class Control {
         globalController.setIsSimRunning(isRunning);
     }
 
-    /**
-     * Sets showConsoleLog.
-     *
-     * @param showConsoleLog
-     */
-    public void setShowConsoleLog(boolean showConsoleLog) {
-        globalController.setShowConsoleLog(showConsoleLog);
-    }
 
     /**
      * Sets show
@@ -1057,7 +1006,26 @@ public class Control {
      * Sets fairness Model
      * @param fairnessModel that should be used. 
      */
-	public void setFairnessModel(short fairnessModel) {
+	public void setFairnessModel(FairnessModel fairnessModel) {
 		globalController.setFairnessModel(fairnessModel);
 	}
+	
+	public void updateOutliner() {
+		gui.updateOutliners(simulationManager.getActualDecorState());
+	}
+	public void updateCanvas() {
+		gui.repaintCanvas();
+	}
+	public GUI getGui() {
+		return gui;
+	}
+
+	public void guiDiable(boolean state) {
+		gui.guiDisable(state);
+	}
+	
+	public void setGui(GUI gui) {
+		this.gui = gui;
+	}
+	
 }

+ 3 - 8
src/ui/controller/GlobalController.java

@@ -3,6 +3,7 @@ package ui.controller;
 import java.awt.Color;
 
 import ui.model.Model;
+import ui.model.Model.FairnessModel;
 import ui.view.StatisticGraphPanel;
 
 /**
@@ -157,13 +158,7 @@ public class GlobalController {
 		}
 	}
 	
-	/**
-	 * Sets showConsoleLog.
-	 * @param showConsoleLog
-	 */
-	public void setShowConsoleLog(boolean showConsoleLog) {
-		model.setShowConsoleLog(showConsoleLog);
-	}
+
 	
 	/**
 	 * sets showSupplyBars
@@ -177,7 +172,7 @@ public class GlobalController {
 	 * sets showSupplyBars
 	 * @param showSupplyBars
 	 */
-	public void setFairnessModel(short fairnessModel) {
+	public void setFairnessModel(FairnessModel fairnessModel) {
 		model.setFairnessModel(fairnessModel);
 	}
 }

+ 9 - 9
src/ui/controller/HolonCanvasController.java

@@ -103,8 +103,8 @@ public class HolonCanvasController {
 		for (AbstractCpsObject obj : objects) {
 			if (obj instanceof HolonObject) {
 				for (HolonElement ele : ((HolonObject) obj).getElements()) {
-                    if (ele.getAvailableEnergyAt(tStep) > 0 && ele.isActive()) {
-                        val += ele.getAvailableEnergyAt(tStep) * ele.getAmount();
+                    if (ele.getEnergyAtTimeStep(tStep) > 0 && ele.isActive()) {
+                        val += ele.getEnergyAtTimeStep(tStep) * ele.getAmount();
                     }
                 }
 				if (val > 0)
@@ -134,8 +134,8 @@ public class HolonCanvasController {
 		for (AbstractCpsObject obj : objects) {
 			if (obj instanceof HolonObject) {
 				for (HolonElement ele : ((HolonObject) obj).getElements()) {
-                    if (ele.getAvailableEnergyAt(tStep) < 0 && ele.isActive()) {
-                        val += ele.getAvailableEnergyAt(tStep) * ele.getAmount();
+                    if (ele.getEnergyAtTimeStep(tStep) < 0 && ele.isActive()) {
+                        val += ele.getEnergyAtTimeStep(tStep) * ele.getAmount();
                     }
                 }
 			} else if (obj instanceof CpsUpperNode) {
@@ -151,8 +151,8 @@ public class HolonCanvasController {
 		for (AbstractCpsObject obj : objects) {
 			if (obj instanceof HolonObject) {
 				for (HolonElement ele : ((HolonObject) obj).getElements()) {
-                    if (ele.getAvailableEnergyAt(tStep) > 0 && ele.isActive()) {
-                        val += ele.getAvailableEnergyAt(tStep) * ele.getAmount();
+                    if (ele.getEnergyAtTimeStep(tStep) > 0 && ele.isActive()) {
+                        val += ele.getEnergyAtTimeStep(tStep) * ele.getAmount();
                     }
                 }
 			} else if (obj instanceof CpsUpperNode) {
@@ -173,10 +173,10 @@ public class HolonCanvasController {
 				bodies.get(i).position.setY(
 						(float) (bodies.get(i).position.getY() + (bodies.get(i).velocity.getY() * (elapsedSeconds))
 								- ((bodies.get(i).position.getY() - center.getHeight()) / (50 + subCount))));
-
-				if (Math.abs(bodies.get(i).velocity.getX()) < Constants.epsilon)
+				float epsilon = 0.000009f;
+				if (Math.abs(bodies.get(i).velocity.getX()) < epsilon)
 					bodies.get(i).velocity.setX(0);
-				if (Math.abs(bodies.get(i).velocity.getY()) < Constants.epsilon)
+				if (Math.abs(bodies.get(i).velocity.getY()) < epsilon)
 					bodies.get(i).velocity.setY(0);
 			}
 		}

+ 22 - 30
src/ui/controller/NodeController.java

@@ -5,6 +5,7 @@ import classes.CpsEdge;
 import classes.CpsNode;
 import classes.CpsUpperNode;
 import classes.Position;
+import classes.IntermediateCalculationCable;
 import ui.model.Model;
 
 import java.awt.*;
@@ -29,7 +30,6 @@ class NodeController {
 	 * Add a CpsUpperNode into Canvas
 	 */
     void doUpperNode(String nodeName, CpsUpperNode upperNode, ArrayList<AbstractCpsObject> toGroup) {
-
 		CpsUpperNode node = new CpsUpperNode(nodeName);
 		node.setPosition(calculatePos(toGroup));
 		makeAdjacent(node, upperNode, toGroup);
@@ -179,16 +179,7 @@ class NodeController {
 		}
 
 		(upperNode == null ? model.getEdgesOnCanvas() : upperNode.getNodeEdges()).removeAll(toDelete);
-
-		// für alle objekte in adjazenzliste mach
-		for (AbstractCpsObject cps : adj) {
-			CpsEdge newEdge = new CpsEdge(cps, node, maxCapacity.get(adj.indexOf(cps)));
-			if (upperNode == null)
-				cvs.addEdgeOnCanvas(newEdge);
-			else
-				upperNode.getNodeEdges().add(newEdge);
-
-		}
+		
 	}
 
 	/**
@@ -241,6 +232,7 @@ class NodeController {
 			// wenn der zu suchende ein CpsUpperNode war
 			if (toSearch instanceof CpsUpperNode) {
 
+				System.out.println("UpperNode!");
 				// guck einfach in den Connections des Verlorenen nach Edges die
 				// auf der Canvas sind.
 				for (CpsEdge e : lost.getConnections()) {
@@ -320,25 +312,25 @@ class NodeController {
 			node.getOldEdges().addAll(backup);
 
 			// neue adjazent muss hergestellt werden in den alten oldEdges
-			for (CpsEdge edge : upperNode.getOldEdges()) {
-
-				if (node.getNodes().contains(edge.getA()))
-					if (!adj.contains(edge.getB())) {
-						adj.add(edge.getB());
-						maxCapacity.add(edge.getCapacity());
-					} else if (maxCapacity.get(adj.indexOf(edge.getB())) < edge.getCapacity()) {
-						maxCapacity.set(adj.indexOf(edge.getB()), edge.getCapacity());
-
-					}
-				if (node.getNodes().contains(edge.getB()))
-					if (!adj.contains(edge.getA())) {
-						adj.add(edge.getA());
-						maxCapacity.add(edge.getCapacity());
-					} else if (maxCapacity.get(adj.indexOf(edge.getA())) < edge.getCapacity()) {
-						maxCapacity.set(adj.indexOf(edge.getA()), edge.getCapacity());
-
-					}
-			}
+//			for (CpsEdge edge : upperNode.getOldEdges()) {
+//
+//				if (node.getNodes().contains(edge.getA()))
+//					if (!adj.contains(edge.getB())) {
+//						adj.add(edge.getB());
+//						maxCapacity.add(edge.getCapacity());
+//					} else if (maxCapacity.get(adj.indexOf(edge.getB())) < edge.getCapacity()) {
+//						maxCapacity.set(adj.indexOf(edge.getB()), edge.getCapacity());
+//
+//					}
+//				if (node.getNodes().contains(edge.getB()))
+//					if (!adj.contains(edge.getA())) {
+//						adj.add(edge.getA());
+//						maxCapacity.add(edge.getCapacity());
+//					} else if (maxCapacity.get(adj.indexOf(edge.getA())) < edge.getCapacity()) {
+//						maxCapacity.set(adj.indexOf(edge.getA()), edge.getCapacity());
+//
+//					}
+//			}
 			// alle übertragenen Edges werden gelöscht
 			upperNode.getOldEdges().removeAll(backup);
 			// neue edges werden erzeugt

+ 13 - 16
src/ui/controller/ObjectController.java

@@ -176,27 +176,24 @@ public class ObjectController {
         }
         return val;
     }
-
-    /**
-     * Get the number of HolonObjects with the given state in the given List
-     *
-     * @param list
-     * @param state
-     */
-    public int getNumberStateObjects(ArrayList<AbstractCpsObject> list, int state) {
-        int val = 0;
-
-        for (AbstractCpsObject obj : list) {
+/**
+ * Helper added by Rolf TODO: macht hier vll keinen Sinn...
+ */
+    public ArrayList<HolonObject> getAllHolonObjects(ArrayList<AbstractCpsObject> list){
+    	ArrayList<HolonObject> allObj = new ArrayList<HolonObject>();
+    	
+    	for (AbstractCpsObject obj : list) {
             if (obj instanceof HolonObject) {
-                if (((HolonObject) obj).getState() == state || (state == 2 && ((HolonObject) obj).getState() == 3)) {
-                    val++;
-                }
+                allObj.add((HolonObject)obj);
             } else if (obj instanceof CpsUpperNode) {
-                val += getNumberStateObjects(((CpsUpperNode) obj).getNodes(), state);
+                 allObj.addAll(getAllHolonObjects(((CpsUpperNode) obj).getNodes()));
             }
         }
-        return val;
+    	
+    	
+    	return allObj;
     }
+   
 
     /**
      * add the ID of a HolonBody.

Dosya farkı çok büyük olduğundan ihmal edildi
+ 163 - 1055
src/ui/controller/SimulationManager.java


+ 65 - 15
src/ui/controller/UpdateController.java

@@ -3,13 +3,13 @@ package ui.controller;
 import classes.*;
 import classes.comparator.elementComparator.ElemCompOnEleName;
 import classes.comparator.elementComparator.ElemCompOnEnergy;
-import classes.comparator.elementComparator.ElemCompOnFlexible;
 import classes.comparator.elementComparator.ElemCompOnId;
 import classes.comparator.elementComparator.ElemCompOnIsActivated;
-import classes.comparator.elementComparator.ElemCompOnIsFlexible;
 import classes.comparator.elementComparator.ElemCompOnObj;
 import classes.comparator.elementComparator.ElemCompOnQuantity;
 import classes.comparator.elementComparator.ElementComparator;
+import ui.model.DecoratedGroupNode;
+import ui.model.DecoratedHolonObject.HolonObjectState;
 import ui.model.Model;
 import ui.view.DefaulTable;
 import ui.view.Languages;
@@ -48,9 +48,8 @@ public class UpdateController {
 			if (tempCps != null && tempCps.getClass() == HolonObject.class) {
 				if (table.getRowCount() != 0) {
 					table.removeRow(2);
-					Object[] tempEnergy = { Languages.getLanguage()[73], ((HolonObject) tempCps).getMaxActiveEnergy() };
+					Object[] tempEnergy = { Languages.getLanguage()[73], ((HolonObject) tempCps).getEnergyNeededFromConsumingElements(model.getCurIteration()) };
 					table.insertRow(2, tempEnergy);
-					((HolonObject) tempCps).updateTotalFlex();
 					table.removeRow(3);
 					Object[] tempFlex = { "Flexibility", ((HolonObject) tempCps).getTotalFlex() };
 					table.insertRow(3, tempFlex);
@@ -82,7 +81,7 @@ public class UpdateController {
 			}
 			for (HolonElement e1 : elemList) {
 				Object[] temp2 = { e1.getObjName(), e1.getId(), e1.getEleName(), e1.getEnergyPerElement(),
-						e1.getFlexibleEnergyAvailablePerElement(), e1.getAmount(), e1.isActive(), e1.isFlexible() };
+						666.f, e1.getAmount(), e1.isActive(), false };
 				table.addRow(temp2);
 			}
 
@@ -96,7 +95,7 @@ public class UpdateController {
 				
 				for (HolonElement e1 : elemList) {
 					Object[] temp2 = { e1.getId(), e1.getEleName(), e1.getEnergyPerElement(),
-							e1.getFlexibleEnergyAvailablePerElement(), e1.getAmount(), e1.isActive(), e1.isFlexible() };
+							666.f, e1.getAmount(), e1.isActive(), false };
 					table.addRow(temp2);
 				}
 			}
@@ -122,7 +121,7 @@ public class UpdateController {
 			elemList.sort(new ElemCompOnEnergy());
 			break;
 		case 4://"Flexible Energy Available": 
-			elemList.sort(new ElemCompOnFlexible());
+			elemList.sort(null);
 			break;
 		case 5://"Quantity": 
 			elemList.sort(new ElemCompOnQuantity());
@@ -131,7 +130,7 @@ public class UpdateController {
 			elemList.sort(new ElemCompOnIsActivated());
 			break;
 		case 7://"Flexible": 
-			elemList.sort(new ElemCompOnIsFlexible());
+			elemList.sort(null);
 			break;
 		default: 
 			elemList.sort(new ElemCompOnId());
@@ -297,7 +296,7 @@ public class UpdateController {
 			// consumption) is calculated
 			if (obj instanceof HolonObject) {
 				refreshTableHolonElement(model.getMultiTable(), model.getSingleTable());
-				Object[] tempEnergy = { Languages.getLanguage()[73], ((HolonObject) obj).getMaxActiveEnergy() };
+				Object[] tempEnergy = { Languages.getLanguage()[73], ((HolonObject) obj).getEnergyNeededFromConsumingElements(model.getCurIteration()) };
 				Object[] tempFlex = { "Flexibility", ((HolonObject) obj).getTotalFlex() };
 				model.getPropertyTable().addRow(tempEnergy);
 				model.getPropertyTable().addRow(tempFlex);
@@ -329,14 +328,64 @@ public class UpdateController {
 			} else if (obj instanceof CpsUpperNode) {
 				deleteRows(model.getSingleTable());
 				deleteRows(model.getMultiTable());
-				Object[] numEle = { "Number of Elements", ((CpsUpperNode) obj).getNodes().size() };
-				Object[] numObj = { "Number of HolonObject", ((CpsUpperNode) obj).getNumHolonObj().size() };
-				Object[] numSwi = { "Number of HolonSwitch", ((CpsUpperNode) obj).getNumSwitches().size() };
-				Object[] numUpp = { "Number of UpperNodes", ((CpsUpperNode) obj).getNumUpperNodes().size() };
+				//short fix please make me new
+				DecoratedGroupNode dGroupNode = controller.getSimManager().getVisualRepresentationalState(model.getCurIteration()).getCreatedGroupNodes().get((CpsUpperNode) obj);
+				Object[] info = { "Statistics:", "" };
+				
+				Object[] numEle = { "Number of Objects (total)", ((CpsUpperNode) obj).getNodes().size() };
+				Object[] numObj = { "Number of HolonObjects", ((CpsUpperNode) obj).getNumHolonObj().size() };
+				Object[] numSwi = { "Number of HolonSwitches", ((CpsUpperNode) obj).getNumSwitches().size() };
+				Object[] numUpp = { "Number of GroupNodes", ((CpsUpperNode) obj).getNumUpperNodes().size() };
+				model.getPropertyTable().addRow(info);
 				model.getPropertyTable().addRow(numEle);
 				model.getPropertyTable().addRow(numObj);
 				model.getPropertyTable().addRow(numSwi);
 				model.getPropertyTable().addRow(numUpp);
+				if(dGroupNode != null) {
+					int numerator, denominator;
+					Object[] title = { "HolonObject Statistics:", "" };
+					
+					denominator	= dGroupNode.getAmountOfConsumer() + dGroupNode.getAmountOfSupplier() + dGroupNode.getAmountOfPassiv();
+					
+					numerator = dGroupNode.getAmountOfSupplier();
+					Object[] producer = { "Producer:",  numerator + "/" + denominator + "("+ (float)numerator/(float)denominator * 100 + "%)"};					
+					numerator = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.NOT_SUPPLIED);
+					Object[] notSupplied = { "UnSupplied:",  numerator + "/" + denominator + "("+ (float)numerator/(float)denominator * 100 + "%)"};
+					numerator = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.PARTIALLY_SUPPLIED);
+					Object[] partiallySupplied = { "PartriallySupplied:",  numerator + "/" + denominator + "("+ (float)numerator/(float)denominator * 100 + "%)"};
+					numerator = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.SUPPLIED);
+					Object[] supplied = { "Supplied:",  numerator + "/" + denominator + "("+ (float)numerator/(float)denominator * 100 + "%)"};
+					numerator = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.OVER_SUPPLIED);
+					Object[] overSupplied = { "OverSupplied:",  numerator + "/" + denominator + "("+ (float)numerator/(float)denominator * 100 + "%)"};
+					numerator = dGroupNode.getAmountOfPassiv();
+					Object[] passiv = { "Passiv(%):",  numerator + "/" + denominator + "("+ (float)numerator/(float)denominator * 100 + "%)"};
+					
+					Object[] nothing= {"", ""};
+					numerator = dGroupNode.getAmountOfAktiveElemntsFromHolonObjects();
+					denominator = dGroupNode.getAmountOfElemntsFromHolonObjects();
+					Object[] aktiv = { "Active HolonElements:",  numerator + "/" + denominator + "("+ (float)numerator/(float)denominator * 100 + "%)"};
+					float consumption = dGroupNode.getConsumptionFromConsumer();
+					float production = dGroupNode.getProductionFromSupplier();
+					Object[] consumptionObj = { "Total Consumption:",  consumption};
+					Object[] productionObj = { "Total Production:",  production};
+					Object[] difference = { "Difference:", production - consumption};
+					
+					
+					model.getPropertyTable().addRow(title);
+					model.getPropertyTable().addRow(producer);
+					model.getPropertyTable().addRow(notSupplied);
+					model.getPropertyTable().addRow(partiallySupplied);
+					model.getPropertyTable().addRow(supplied);
+					model.getPropertyTable().addRow(overSupplied);
+					model.getPropertyTable().addRow(passiv);
+					model.getPropertyTable().addRow(nothing);
+					model.getPropertyTable().addRow(aktiv);
+					model.getPropertyTable().addRow(nothing);
+					model.getPropertyTable().addRow(consumptionObj);
+					model.getPropertyTable().addRow(productionObj);
+					model.getPropertyTable().addRow(difference);
+				}
+				
 			} else if (obj instanceof HolonBattery) {
 				deleteRows(model.getSingleTable());
 				deleteRows(model.getMultiTable());
@@ -392,13 +441,13 @@ public class UpdateController {
 							+ model.getSelectedEdge().getB().getName() };
 			model.getPropertyTable().addRow(tempName);
 			// Current Flow displayed
-			Object[] tempFlow = { Languages.getLanguage()[80], model.getSelectedEdge().getFlow() };
+			Object[] tempFlow = { Languages.getLanguage()[80], "" };
 			model.getPropertyTable().addRow(tempFlow);
 			// Max Capacity displayed
 			Object[] tempCapacity = { Languages.getLanguage()[81], model.getSelectedEdge().getCapacity() };
 			model.getPropertyTable().addRow(tempCapacity);
 			// Status displayed
-            Object[] tempStatus = {Languages.getLanguage()[82], model.getSelectedEdge().isWorking()};
+            Object[] tempStatus = {Languages.getLanguage()[82], ""};
             model.getPropertyTable().addRow(tempStatus);
             // For edges, the only possible editable cell is the max
 			// flow
@@ -436,6 +485,7 @@ public class UpdateController {
 	 */
 	public void paintHolonBody(int id) {
 		if (id != -1) {
+			
 			ArrayList<SubNet> subs = controller.getSimManager().getSubNets();
 			if (!subs.isEmpty()) {
 				SubNet sub = subs.get(id);

+ 85 - 0
src/ui/model/Consumer.java

@@ -0,0 +1,85 @@
+package ui.model;
+
+import java.util.ArrayList;
+
+import classes.HolonObject;
+
+public class Consumer extends DecoratedHolonObject {
+
+	private ArrayList<SupplierListEntry> supplierList = new ArrayList<SupplierListEntry>();
+	private float energyFromNetwork;
+	private float minimumConsumingElementEnergy;
+	private float energyNeededFromNetwork;
+	private float energyFromConsumingElemnets;
+	private float energySelfSupplied;
+	public Consumer(HolonObject objectToLookAt) {
+		super(objectToLookAt);
+		energyNeededFromNetwork = 0.0f;
+	}
+
+	@Override
+	float getEnergy() {
+		return energyFromNetwork-energyNeededFromNetwork;
+	}
+	public float getEnergyFromNetwork() {
+		return energyFromNetwork;
+	}
+	public void setEnergyFromNetwork(float energyFromNetwork) {
+		this.energyFromNetwork = energyFromNetwork;
+	}
+
+	public float getMinimumConsumingElementEnergy() {
+		return minimumConsumingElementEnergy;
+	}
+
+	public void setMinimumConsumingElementEnergy(float minimumConsumingElementEnergy) {
+		this.minimumConsumingElementEnergy = minimumConsumingElementEnergy;
+	}
+
+	public ArrayList<SupplierListEntry> getSupplierList() {
+		return supplierList;
+	}
+
+	public void setSupplierList(ArrayList<SupplierListEntry> supplierList) {
+		this.supplierList = supplierList;
+	}
+
+	public float getEnergyNeededFromNetwork() {
+		return energyNeededFromNetwork;
+	}
+
+	public void setEnergyNeededFromNetwork(float energyNeededFromNetwork) {
+		this.energyNeededFromNetwork = energyNeededFromNetwork;
+	}
+	@Override
+	public String toString() {
+		return getModel().getName() + ":" + getModel().getId()  + ", Energy: "+ getEnergy() +
+				" [" + (energyFromNetwork + energySelfSupplied) +"/" + energyFromConsumingElemnets +"]";	
+	}
+	public float getEnergyFromConsumingElemnets() {
+		return energyFromConsumingElemnets;
+	}
+
+	public void setEnergyFromConsumingElemnets(float energyFromConsumingElemnets) {
+		this.energyFromConsumingElemnets = energyFromConsumingElemnets;
+	}
+	public float getEnergySelfSupplied() {
+		return energySelfSupplied;
+	}
+
+	public float getSupplyBarPercentage() {
+		return (getEnergyFromNetwork()+ this.getEnergySelfSupplied())/(getEnergyNeededFromNetwork()+ this.getEnergySelfSupplied());
+	}
+	public void setEnergySelfSupplied(float energySelfSupplied) {
+		this.energySelfSupplied = energySelfSupplied;
+	}
+	public class SupplierListEntry{
+		public Supplier supplier;
+		public float energyFromSupplier;
+		public SupplierListEntry(Supplier supplier,float energyFromSupplier) {
+			this.supplier = supplier;
+			this.energyFromSupplier = energyFromSupplier;
+		}
+	}
+
+}

+ 26 - 0
src/ui/model/DecoratedCable.java

@@ -0,0 +1,26 @@
+package ui.model;
+
+import classes.CpsEdge;
+
+public class DecoratedCable {
+	public enum CableState{
+		Working, Burned
+	}
+	private CpsEdge model;
+	private CableState state;
+	private float flowEnergy;
+	public DecoratedCable(CpsEdge edge, CableState state, float flowEnergy){
+		this.model = edge;
+		this.state = state;
+		this.flowEnergy = flowEnergy;
+	}
+	public CpsEdge getModel() {
+		return model;
+	}
+	public CableState getState() {
+		return state;
+	}
+	public float getFlowEnergy() {
+		return flowEnergy;
+	}
+}

+ 127 - 0
src/ui/model/DecoratedGroupNode.java

@@ -0,0 +1,127 @@
+package ui.model;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.stream.Collector;
+import java.util.stream.Collectors;
+
+import classes.CpsNode;
+import classes.CpsUpperNode;
+import classes.IntermediateCalculationCable;
+import ui.model.DecoratedHolonObject.HolonObjectState;
+import classes.ExitCable;
+/**
+ * For the @VisualRepresentationalState only.
+ * @author Tom
+ *
+ */
+public class DecoratedGroupNode {
+	private CpsUpperNode model;
+	private ArrayList<Supplier> supplierList;
+	private ArrayList<Passiv> passivList;
+	private ArrayList<Consumer> consumerList;
+	private ArrayList<CpsNode> nodeList;
+	/**
+	 * Cables that only exist on that group node. From a object in that group node to a object in that group Node.
+	 * Not exit the group node (a layer down).
+	 */
+	private ArrayList<DecoratedCable> internCableList;
+	/**
+	 * Cables that exit this group node (a Layer Up). From a object in this group node to a object in a upper layer.
+	 */
+	private ArrayList<ExitCable> exitCableList;	
+	private ArrayList<DecoratedSwitch> switchList;
+	private ArrayList<DecoratedGroupNode> groupNodeList;
+
+
+
+	public DecoratedGroupNode(CpsUpperNode model) {
+		this.model = model;
+		this.supplierList = new ArrayList<Supplier>();
+		this.passivList = new ArrayList<Passiv>();
+		this.consumerList = new ArrayList<Consumer>();
+		this.nodeList = new ArrayList<CpsNode>();
+		this.internCableList = new ArrayList<DecoratedCable>();
+		this.exitCableList = new ArrayList<ExitCable>();
+		this.switchList = new ArrayList<DecoratedSwitch>();
+		this.groupNodeList = new ArrayList<DecoratedGroupNode>();
+	}
+	public CpsUpperNode getModel() {
+		return model;
+	}
+	public ArrayList<Supplier> getSupplierList() {
+		return supplierList;
+	}
+	public ArrayList<Passiv> getPassivList() {
+		return passivList;
+	}
+	public ArrayList<Consumer> getConsumerList() {
+		return consumerList;
+	}
+	public ArrayList<CpsNode> getNodeList() {
+		return nodeList;
+	}
+	public ArrayList<DecoratedCable> getInternCableList() {
+		return internCableList;
+	}
+	public ArrayList<ExitCable> getExitCableList() {
+		return exitCableList;
+	}
+	public ArrayList<DecoratedSwitch> getSwitchList() {
+		return switchList;
+	}
+	public ArrayList<DecoratedGroupNode> getGroupNodeList() {
+		return groupNodeList;
+	}
+	
+	//Gather Informations:
+	public int getAmountOfSupplier() {
+		return supplierList.size() + groupNodeList.stream().map(groupNode -> groupNode.getAmountOfSupplier()).reduce(0, (a,b)->a+b);
+	}
+	public int getAmountOfConsumer() {
+		return consumerList.size() + groupNodeList.stream().map(groupNode -> groupNode.getAmountOfConsumer()).reduce(0, (a,b)->a+b);
+	}
+	public int getAmountOfPassiv() {
+		return passivList.size() + groupNodeList.stream().map(groupNode -> groupNode.getAmountOfPassiv()).reduce(0, (a,b)->a+b);
+	}
+	
+	public int getAmountOfConsumerWithState(HolonObjectState state) {
+		return ((int) consumerList.stream().map(con -> con.getState()).filter(rightState -> (rightState == state)).count()) +  groupNodeList.stream().map(groupNode -> groupNode.getAmountOfConsumerWithState(state)).reduce(0, (a,b)->a+b);
+	}
+	
+	public int getAmountOfElemntsFromHolonObjects() {
+		return passivList.stream().map(object -> object.getModel().getElements().size()).reduce(0, (a, b) -> a + b)+
+				supplierList.stream().map(object -> object.getModel().getElements().size()).reduce(0, (a, b) -> a + b)+
+				consumerList.stream().map(object -> object.getModel().getElements().size()).reduce(0, (a, b) -> a + b)+
+				groupNodeList.stream().map(groupNode -> groupNode.getAmountOfElemntsFromHolonObjects()).reduce(0, (a,b)->a+b);
+	}
+
+	public int getAmountOfAktiveElemntsFromHolonObjects() {
+		return passivList.stream().map(object -> object.getModel().getNumberOfActiveElements()).reduce(0, (a, b) -> a + b)+
+				supplierList.stream().map(object -> object.getModel().getNumberOfActiveElements()).reduce(0, (a, b) -> a + b)+
+				consumerList.stream().map(object -> object.getModel().getNumberOfActiveElements()).reduce(0, (a, b) -> a + b)+
+				groupNodeList.stream().map(groupNode -> groupNode.getAmountOfAktiveElemntsFromHolonObjects()).reduce(0, (a,b)->a+b);
+	}
+	public float getConsumptionFromConsumer() {		
+		return consumerList.stream().map(con -> con.getEnergyNeededFromNetwork()).reduce(0.f, (a, b) -> a + b)+
+				groupNodeList.stream().map(groupNode -> groupNode.getConsumptionFromConsumer()).reduce(0.f, (a,b)->a+b);
+	}
+	public float getProductionFromSupplier() {		
+		return supplierList.stream().map(sup -> sup.getEnergyToSupplyNetwork()).reduce(0.f, (a, b) -> a + b)+
+				groupNodeList.stream().map(groupNode -> groupNode.getProductionFromSupplier()).reduce(0.f, (a,b)->a+b);
+	}
+	
+	
+	
+	
+	
+	public String toString() {
+		return 
+				"GroupNode with [Supplier:" + getAmountOfSupplier() 
+				+ ", NotSupplied:" + getAmountOfConsumerWithState(HolonObjectState.NOT_SUPPLIED) 
+				+ ", PartiallySupplied:" + getAmountOfConsumerWithState(HolonObjectState.PARTIALLY_SUPPLIED) 
+				+ ", Supplied:" + getAmountOfConsumerWithState(HolonObjectState.SUPPLIED) 
+				+ ", OverSupplied:" + getAmountOfConsumerWithState(HolonObjectState.OVER_SUPPLIED) 
+				+ ", Passiv:"+ getAmountOfPassiv() + "]";
+	}
+}

+ 24 - 0
src/ui/model/DecoratedHolonObject.java

@@ -0,0 +1,24 @@
+package ui.model;
+
+import classes.HolonObject;
+
+public abstract class DecoratedHolonObject {
+	public enum HolonObjectState {
+		NO_ENERGY, NOT_SUPPLIED, SUPPLIED, PRODUCER, PARTIALLY_SUPPLIED, OVER_SUPPLIED
+	}
+	private HolonObject model;
+	private HolonObjectState state;
+	public DecoratedHolonObject(HolonObject objectToLookAt){
+		model = objectToLookAt;
+	}
+	abstract float getEnergy();
+	public HolonObject getModel() {
+		return model;
+	}
+	public HolonObjectState getState() {
+		return state;
+	}
+	public void setState(HolonObjectState state) {
+		this.state = state;
+	}
+}

+ 283 - 0
src/ui/model/DecoratedNetwork.java

@@ -0,0 +1,283 @@
+package ui.model;
+
+import java.util.ArrayList;
+
+import classes.HolonObject;
+import ui.model.DecoratedCable.CableState;
+import ui.model.DecoratedHolonObject.HolonObjectState;
+import ui.model.Model.FairnessModel;
+
+public class DecoratedNetwork {
+	private ArrayList<Supplier> supplierList = new ArrayList<Supplier>();
+	private ArrayList<Consumer> consumerList = new ArrayList<Consumer>();
+	private ArrayList<Consumer> consumerSelfSuppliedList = new ArrayList<Consumer>();
+	private ArrayList<Passiv> passivNoEnergyList = new ArrayList<Passiv>();
+	private ArrayList<DecoratedCable> decoratedCableList = new ArrayList<DecoratedCable>();
+
+	public DecoratedNetwork(MinimumNetwork minimumNetwork, int Iteration, FairnessModel actualFairnessModel){	
+		switch(actualFairnessModel) {
+		case AllEqual:
+			calculateAllEqualNetwork(minimumNetwork, Iteration);
+			break;
+		case MininumDemandFirst:
+		default:
+			calculateMinimumDemandFirstNetwork(minimumNetwork, Iteration);
+			break;		
+		}
+	}
+
+
+	//Getter:
+	public ArrayList<Supplier> getSupplierList() {
+		return supplierList;
+	}
+
+
+	public ArrayList<Consumer> getConsumerList() {
+		return consumerList;
+	}
+
+
+	public ArrayList<Consumer> getConsumerSelfSuppliedList() {
+		return consumerSelfSuppliedList;
+	}
+
+
+	public ArrayList<Passiv> getPassivNoEnergyList() {
+		return passivNoEnergyList;
+	}
+	public ArrayList<DecoratedCable> getDecoratedCableList(){
+		return decoratedCableList;
+	}
+	
+	
+	//Calculations:
+	private void calculateMinimumDemandFirstNetwork(MinimumNetwork minimumNetwork, int Iteration) {
+		categorize(minimumNetwork, Iteration);
+		//Sort SupplierList according to the EnergyToSupplyNetwork maximum first.
+		//Sort ConsumerList according to the MinimumConsumingElementEnergy minimum first.
+		supplierList.sort((Supplier lhs,Supplier rhs) -> -Float.compare(lhs.getEnergyToSupplyNetwork(), rhs.getEnergyToSupplyNetwork()));
+		consumerList.sort((Consumer lhs,Consumer rhs) -> Float.compare(lhs.getMinimumConsumingElementEnergy()  , rhs.getMinimumConsumingElementEnergy()));
+		//consumerList.forEach((con) -> System.out.println(con.getMinimumConsumingElementEnergy()));
+		//consumerList.forEach((con) -> System.out.println("AfterSorting" + con));
+		float energyToSupplyInTheNetwork = supplierList.stream().map(supplier -> supplier.getEnergyToSupplyNetwork() - supplier.getEnergySupplied()).reduce( 0.0f, (a, b) -> a + b);
+		decorateCable(minimumNetwork, energyToSupplyInTheNetwork);
+		
+		outerLoop:
+			for(Consumer con : consumerList)
+			{
+				//gehe Supplier list durch wer ihn supplien kann.
+				for(Supplier sup : supplierList) {
+					float  energyRdyToSupply = sup.getEnergyToSupplyNetwork() - sup.getEnergySupplied();
+					if(energyRdyToSupply == 0.0f) continue;
+					float energyNeededForMinimumConsumingElement=con.getMinimumConsumingElementEnergy()-con.getEnergyFromNetwork();
+					if(energyNeededForMinimumConsumingElement>energyToSupplyInTheNetwork) {
+						//Dont supply a minimumElement when you cant supply it fully
+						break outerLoop;
+					}
+					if(energyRdyToSupply>=energyNeededForMinimumConsumingElement) {
+						energyToSupplyInTheNetwork -= energyNeededForMinimumConsumingElement;
+						supply(con, sup, energyNeededForMinimumConsumingElement);
+						continue outerLoop;
+					}else
+					{
+						energyToSupplyInTheNetwork -= energyRdyToSupply;
+						supply(con, sup, energyRdyToSupply);
+					}
+				}
+				//No more Energy in the network
+				break;
+			}
+		//consumerList.forEach((con) -> System.out.println("AfterSuppliing MinimumDemand " + con));
+		
+		//Sort ConsumerList according to the EnergyNeeded to supply fully after minimum Demand First.
+		consumerList.sort((Consumer lhs,Consumer rhs) -> Float.compare(lhs.getEnergyNeededFromNetwork()-lhs.getEnergyFromNetwork() , rhs.getEnergyNeededFromNetwork()-rhs.getEnergyFromNetwork() ));
+		//Supply consumer fully 
+		outerLoop:
+			for(Consumer con : consumerList)
+			{
+				//gehe Supplier list durch wer ihn supplien kann.
+				for(Supplier sup : supplierList) {
+					float  energyRdyToSupply = sup.getEnergyToSupplyNetwork() - sup.getEnergySupplied();
+					if(energyRdyToSupply == 0.0f) continue;
+					float energyNeededForFullySupply = con.getEnergyNeededFromNetwork() - con.getEnergyFromNetwork();
+					if(energyNeededForFullySupply == 0.0f) continue outerLoop;
+					if(energyRdyToSupply>=energyNeededForFullySupply) {
+						supply(con, sup, energyNeededForFullySupply);
+						continue outerLoop;
+					}else
+					{
+						supply(con, sup, energyRdyToSupply);
+					}
+				}
+				//No more Energy in the network
+				break;
+			}
+		//consumerList.forEach((con) -> System.out.println("AfterFullySuplieing" + con));
+		//If Energy Left Supply all equal
+		//Count EnergyLeft
+		float energyLeft = supplierList.stream().map(supplier -> supplier.getEnergyToSupplyNetwork() - supplier.getEnergySupplied()).reduce( 0.0f, (a, b) -> a + b);
+		//System.out.println("EnergyLeft: " +  energyLeft);
+		if(energyLeft > 0.0f && (consumerList.size() + consumerSelfSuppliedList.size() != 0))
+		{
+			float equalAmountOfEnergyToSupply = energyLeft / ((float)(consumerList.size() + consumerSelfSuppliedList.size()));
+			outerLoop:
+				for(Consumer con : consumerList)
+				{
+					//gehe Supplier list durch wer ihn supplien kann.
+					for(Supplier sup : supplierList) {
+						float  energyRdyToSupply = sup.getEnergyToSupplyNetwork() - sup.getEnergySupplied();
+						if(energyRdyToSupply == 0.0f) continue;
+						float energyNeededToSupplyConsumerTheEqualAmount = equalAmountOfEnergyToSupply +con.getEnergyNeededFromNetwork()- con.getEnergyFromNetwork();
+						if(energyRdyToSupply>=energyNeededToSupplyConsumerTheEqualAmount) {
+							supply(con, sup, energyNeededToSupplyConsumerTheEqualAmount);
+							continue outerLoop;
+						}else
+						{
+							supply(con, sup, energyRdyToSupply);
+						}
+					}
+					//No more Energy in the network
+					break;
+				}
+			outerLoop:
+				for(Consumer con : consumerSelfSuppliedList)
+				{
+					//gehe Supplier list durch wer ihn supplien kann.
+					for(Supplier sup : supplierList) {
+						float  energyRdyToSupply = sup.getEnergyToSupplyNetwork() - sup.getEnergySupplied();
+						if(energyRdyToSupply == 0.0f) continue;
+						float energyNeededToSupplyConsumerTheEqualAmount = equalAmountOfEnergyToSupply +con.getEnergyNeededFromNetwork()- con.getEnergyFromNetwork();
+						if(energyRdyToSupply>=energyNeededToSupplyConsumerTheEqualAmount) {
+							supply(con, sup, energyNeededToSupplyConsumerTheEqualAmount);
+							continue outerLoop;
+						}else
+						{
+							supply(con, sup, energyRdyToSupply);
+						}
+						
+					}
+					//No more Energy in the network
+					break;
+				}
+		}
+		//consumerList.forEach((con) -> System.out.println("AfterOverSuppleiing" + con));
+		
+		//consumerSelfSuppliedList.forEach((con) -> System.out.println("AfterOverSuppleiing" + con));
+		
+		calculateStates();
+	}
+
+
+	private void decorateCable(MinimumNetwork minimumNetwork, float energyToSupplyInTheNetwork) {
+		//DecoratedCables
+		//Minimum demand first:
+		for(IntermediateCableWithState edge: minimumNetwork.getEdgeList()) {		
+			decoratedCableList.add(new DecoratedCable(edge.getModel(), edge.getState(), (edge.getState() == CableState.Working) ? energyToSupplyInTheNetwork : 0.0f));
+		}
+	}
+
+
+
+	private void calculateAllEqualNetwork(MinimumNetwork minimumNetwork, int Iteration) {
+		categorize(minimumNetwork, Iteration);
+		float energyToSupplyInTheNetwork = supplierList.stream().map(supplier -> supplier.getEnergyToSupplyNetwork() - supplier.getEnergySupplied()).reduce( 0.0f, (a, b) -> a + b);
+		float energyForEachConsumer = (consumerList.size() != 0) ? energyToSupplyInTheNetwork / consumerList.size() : 0.0f;
+		decorateCable(minimumNetwork, energyToSupplyInTheNetwork);
+		//Supply consumer equal 
+		outerLoop:
+		for(Consumer con : consumerList)
+		{
+			//gehe Supplier list durch wer ihn supplien kann.
+			float energyNeededForEqualSupply = energyForEachConsumer;
+			for(Supplier sup : supplierList) {
+				float  energyRdyToSupply = sup.getEnergyToSupplyNetwork() - sup.getEnergySupplied();
+				if(energyRdyToSupply == 0.0f) continue;
+				if(energyRdyToSupply>=energyNeededForEqualSupply) {
+					supply(con, sup, energyNeededForEqualSupply);
+					continue outerLoop;
+				}else
+				{
+					supply(con, sup, energyRdyToSupply);
+					energyNeededForEqualSupply -= energyRdyToSupply;
+				}
+			}
+			//No more Energy in the network
+			break;
+		}
+		calculateStates();
+	}
+
+	private void calculateStates() {
+		//CalculateStates:
+		supplierList.forEach(sup -> sup.setState(HolonObjectState.PRODUCER));
+		passivNoEnergyList.forEach(sup -> sup.setState(HolonObjectState.NO_ENERGY));
+		for(Consumer con : this.consumerList)
+		{
+			setConsumerState(con);
+		}
+		for(Consumer con : this.consumerSelfSuppliedList)
+		{
+			setConsumerState(con);
+		}
+	}
+	private void categorize(MinimumNetwork minimumNetwork, int Iteration) {
+		//Categorize
+		for(HolonObject hObject: minimumNetwork.getHolonObjectList()) {
+			float energyNeeded = hObject.getEnergyNeededFromConsumingElements(Iteration);
+			float energySelfProducing = hObject.getEnergySelfProducingFromProducingElements(Iteration);
+			if(energyNeeded < energySelfProducing) {
+				Supplier sup = new Supplier(hObject, energySelfProducing - energyNeeded);
+				supplierList.add(sup);
+			} else if (energyNeeded > energySelfProducing) {
+				Consumer con = new Consumer(hObject);
+				con.setEnergyNeededFromNetwork(energyNeeded - energySelfProducing);
+				con.setMinimumConsumingElementEnergy(hObject.getMinimumConsumingElementEnergy(Iteration));
+				con.setEnergyFromConsumingElemnets(hObject.getEnergyNeededFromConsumingElements(Iteration));
+				con.setEnergySelfSupplied(hObject.getEnergySelfProducingFromProducingElements(Iteration));
+				consumerList.add(con);
+			}else if(energyNeeded == energySelfProducing) {
+				
+				if (energySelfProducing == 0.0f) {
+					Passiv pas = new Passiv(hObject);
+					passivNoEnergyList.add(pas);
+				} else {
+					Consumer con = new Consumer(hObject);
+					con.setEnergyNeededFromNetwork(0.0f);
+					con.setMinimumConsumingElementEnergy(hObject.getMinimumConsumingElementEnergy(Iteration));
+					con.setEnergyFromConsumingElemnets(hObject.getEnergyNeededFromConsumingElements(Iteration));
+					con.setEnergySelfSupplied(hObject.getEnergySelfProducingFromProducingElements(Iteration));
+					consumerSelfSuppliedList.add(con);
+				}
+				
+			}
+		}
+	}
+	
+	
+	private void setConsumerState(Consumer con) {
+		if(con.getEnergySelfSupplied() + con.getEnergyFromNetwork() > con.getEnergyFromConsumingElemnets()) {
+			con.setState(HolonObjectState.OVER_SUPPLIED);
+		}else if(con.getEnergySelfSupplied() + con.getEnergyFromNetwork() == con.getEnergyFromConsumingElemnets()) {
+			con.setState(HolonObjectState.SUPPLIED);
+		}else if(con.getEnergySelfSupplied() + con.getEnergyFromNetwork() >= con.getMinimumConsumingElementEnergy()) {
+			con.setState(HolonObjectState.PARTIALLY_SUPPLIED);
+		}else {
+			con.setState(HolonObjectState.NOT_SUPPLIED);
+		}
+	}
+	
+	
+	/**
+	 * No Checks.
+	 * @param con
+	 * @param sup
+	 * @param energy
+	 */
+	private void supply(Consumer con, Supplier sup, float energy) {
+		sup.getConsumerList().add(sup.new ConsumerListEntry(con , energy));
+		sup.setEnergySupplied(sup.getEnergySupplied() + energy);
+		con.getSupplierList().add(con.new SupplierListEntry(sup, energy));
+		con.setEnergyFromNetwork(con.getEnergyFromNetwork() + energy);
+	}
+}

+ 29 - 0
src/ui/model/DecoratedState.java

@@ -0,0 +1,29 @@
+package ui.model;
+
+import java.util.ArrayList;
+
+
+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){
+		this.networkList = networkList;
+		this.leftOverEdges = leftOverEdges;
+		this.decoratedSwitches = decoratedSwitches;
+		this.timestepOfState = timestepOfState;
+	}
+	public ArrayList<DecoratedNetwork> getNetworkList() {
+		return networkList;
+	}
+	public ArrayList<DecoratedCable> getLeftOverEdges() {
+		return leftOverEdges;
+	}
+	public ArrayList<DecoratedSwitch> getDecoratedSwitches() {
+		return decoratedSwitches;
+	}
+	public int getTimestepOfState() {
+		return timestepOfState;
+	}
+}

+ 24 - 0
src/ui/model/DecoratedSwitch.java

@@ -0,0 +1,24 @@
+package ui.model;
+
+import classes.HolonSwitch;
+
+public class DecoratedSwitch {
+	public enum SwitchState{
+		Closed, Open
+	}
+	private SwitchState state;
+	private HolonSwitch model;
+	public DecoratedSwitch(HolonSwitch hSwitch, SwitchState state){
+		this.model = hSwitch;
+		this.state = state;
+	}
+	public SwitchState getState() {
+		return state;
+	}
+
+	public HolonSwitch getModel() {
+		return model;
+	}
+
+	
+}

+ 37 - 0
src/ui/model/IntermediateCableWithState.java

@@ -0,0 +1,37 @@
+package ui.model;
+
+import classes.CpsEdge;
+import classes.HolonObject;
+import ui.model.DecoratedCable.CableState;
+
+/**
+ * Intermediate to calculate/simulate the burning of Cables.
+ * When all burning is done the Cable will be represented as a DecoratedCable.
+ * @see DecoratedCable
+ */
+public class IntermediateCableWithState {
+	private CableState state;
+	private CpsEdge model;
+	public IntermediateCableWithState(CpsEdge model,CableState state)
+	{
+		this.model = model;
+		this.state = state;
+	}
+	public CableState getState() {
+		return state;
+	}
+	public void setState(CableState state) {
+		this.state = state;
+	}
+	public CpsEdge getModel() {
+		return model;
+	}
+	//ugly
+	public float getEnergyFromConnetedAtTimestep(int iteration) {
+		float energy = 0.0f;
+		if(model.getA() instanceof HolonObject && ((HolonObject) model.getA()).getEnergyAtTimeStep(iteration) > 0) energy += ((HolonObject) model.getA()).getEnergyAtTimeStep(iteration);
+		if(model.getB() instanceof HolonObject && ((HolonObject) model.getB()).getEnergyAtTimeStep(iteration) > 0) energy += ((HolonObject) model.getB()).getEnergyAtTimeStep(iteration);
+		return energy;
+	}
+	
+}

+ 105 - 0
src/ui/model/MinimumModel.java

@@ -0,0 +1,105 @@
+package ui.model;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+
+import classes.AbstractCpsObject;
+import classes.CpsEdge;
+import classes.CpsNode;
+import classes.CpsUpperNode;
+import classes.HolonObject;
+import classes.HolonSwitch;
+import ui.model.DecoratedCable.CableState;
+
+/**
+ * For DecoratedState And VisualRepresentationalState
+ * @author Tom
+ *
+ */
+public class MinimumModel {
+	
+	private ArrayList<HolonObject> holonObjectList = new ArrayList<HolonObject>();
+	private ArrayList<IntermediateCableWithState> cableList = new ArrayList<IntermediateCableWithState>();
+	private ArrayList<CpsNode> nodeList = new ArrayList<CpsNode>();
+	private ArrayList<HolonSwitch> switchList = new ArrayList<HolonSwitch>();
+	
+	//-->Only for Visual:
+	private ArrayList<CpsUpperNode> uppderNodeList = new ArrayList<CpsUpperNode>();
+	private HashMap<AbstractCpsObject, CpsUpperNode> inGroupObjects = new HashMap<>();
+	private HashMap<CpsEdge, CpsUpperNode> inGroupEdges = new HashMap<>();
+	//<--
+	
+	public MinimumModel(ArrayList<AbstractCpsObject> abstractObjectList, ArrayList<CpsEdge> edgeList) {// Constructor because of old Model
+		for (AbstractCpsObject aCps : abstractObjectList) {
+			if (aCps instanceof HolonObject) holonObjectList.add((HolonObject) aCps);
+			else if (aCps instanceof CpsNode) nodeList.add((CpsNode) aCps);
+			else if (aCps instanceof HolonSwitch) switchList.add((HolonSwitch) aCps);
+			else if(aCps instanceof CpsUpperNode) {
+				addUpperObjects((CpsUpperNode)aCps);
+				uppderNodeList.add((CpsUpperNode)aCps);
+			}
+		}
+		for (CpsEdge edge : edgeList) {
+			this.cableList.add(new IntermediateCableWithState(edge, CableState.Working));
+		}
+	}
+
+	private void addUpperObjects(CpsUpperNode aUpperNode) {
+		for(AbstractCpsObject aCps : aUpperNode.getNodes()) {
+			if (aCps instanceof HolonObject) holonObjectList.add((HolonObject) aCps);
+			else if (aCps instanceof CpsNode) nodeList.add((CpsNode) aCps);
+			else if (aCps instanceof HolonSwitch) switchList.add((HolonSwitch) aCps);
+			else if(aCps instanceof CpsUpperNode) {
+				addUpperObjects((CpsUpperNode)aCps);
+				uppderNodeList.add((CpsUpperNode)aCps);
+			}
+			inGroupObjects.put(aCps, aUpperNode);
+		}
+		for (CpsEdge edge : aUpperNode.getNodeEdges()) {
+			this.cableList.add(new IntermediateCableWithState(edge, CableState.Working));
+			inGroupEdges.put(edge, aUpperNode);
+		}
+		for (CpsEdge edge : aUpperNode.getOldEdges()) {
+			this.cableList.add(new IntermediateCableWithState(edge, CableState.Working));
+			inGroupEdges.put(edge, aUpperNode);
+		}
+	}
+	
+	public ArrayList<HolonObject> getHolonObjectList() {
+		return holonObjectList;
+	}
+	public void setHolonObjectList(ArrayList<HolonObject> holonObjectList) {
+		this.holonObjectList = holonObjectList;
+	}
+	public ArrayList<IntermediateCableWithState> getEdgeList() {
+		return cableList;
+	}
+	public void setEdgeList(ArrayList<IntermediateCableWithState> cableList) {
+		this.cableList = cableList;
+	}
+	public ArrayList<CpsNode> getNodeList() {
+		return nodeList;
+	}
+	public void setNodeList(ArrayList<CpsNode> nodeList) {
+		this.nodeList = nodeList;
+	}
+	public ArrayList<HolonSwitch> getSwitchList() {
+		return switchList;
+	}
+	public void setSwitchList(ArrayList<HolonSwitch> switchList) {
+		this.switchList = switchList;
+	}
+
+	public ArrayList<CpsUpperNode> getUppderNodeList() {
+		return uppderNodeList;
+	}
+
+	public HashMap<AbstractCpsObject, CpsUpperNode> getInGroupObjects() {
+		return inGroupObjects;
+	}
+
+	public HashMap<CpsEdge, CpsUpperNode> getInGroupEdges() {
+		return inGroupEdges;
+	}
+	
+}

+ 33 - 0
src/ui/model/MinimumNetwork.java

@@ -0,0 +1,33 @@
+package ui.model;
+
+import java.util.ArrayList;
+import classes.HolonObject;
+
+public class MinimumNetwork {
+	private ArrayList<HolonObject> holonObjectList = new ArrayList<HolonObject>();
+	private ArrayList<IntermediateCableWithState> edgeList = new ArrayList<IntermediateCableWithState>();
+	public MinimumNetwork(ArrayList<HolonObject> holonObjectList, ArrayList<IntermediateCableWithState> edgeList){
+		this.holonObjectList = holonObjectList;
+		this.edgeList = edgeList;
+	}
+	public ArrayList<HolonObject> getHolonObjectList() {
+		return holonObjectList;
+	}
+	public ArrayList<IntermediateCableWithState> getEdgeList() {
+		return edgeList;
+	}
+	public String toString()
+	{
+		String objecte = "[";
+		for(HolonObject object :holonObjectList) {
+			objecte += " " + object.getObjName();
+		}
+		objecte += "]";
+		String edges = "[";
+		for(IntermediateCableWithState edge :edgeList) {
+			edges += " " + edge.getModel();
+		}
+		edges += "]";
+		return objecte + edges;
+	}
+}

+ 78 - 24
src/ui/model/Model.java

@@ -41,8 +41,8 @@ public class Model {
     private int backgroundMode = 0;
     private int backgroundWidth = 0;
     private int backgroundHeight = 0;
-    private int canvasX = 1000;
-    private int canvasY = 1000;
+    private int canvasX = 3000;
+    private int canvasY = 3000;
     private int curIteration = 0;
     private LinkedList<Color> subNetColors = new LinkedList<>();
     // ID of the Selected Object
@@ -51,7 +51,6 @@ public class Model {
     private CpsEdge selectedEdge;
     private ArrayList<AbstractCpsObject> selectedObjects = new ArrayList<>();
     private ArrayList<AbstractCpsObject> clipboardObjects = new ArrayList<>();
-    private Console console;
     private HashMap<Integer, ArrayList<HolonElement>> eleToDelete;
     // Capacity for Edge
     private float maxCapacity;
@@ -60,7 +59,7 @@ public class Model {
     /** Table for the properties of HolonObjects, Edges etc */
     private JTable propertyTable;
     
-    private ArrayList<GraphListener> graphListeners = new ArrayList();
+    private ArrayList<GraphListener> graphListeners = new ArrayList<GraphListener>();
     // Iteration Speed
     private int timerSpeed = 1000;
     private int selectedID = 0;
@@ -79,8 +78,26 @@ public class Model {
     //TODO:
     private int iterations=100;
     
+    /**
+	 * All implemented FairnessModels:<br>
+	 * {@link FairnessModel#MininumDemandFirst}<br>
+	 * {@link FairnessModel#AllEqual}
+	 */
+	public enum FairnessModel{
+		/**
+		 * One Element of each HolonObject will be powered first, starting with the
+		 * smallest Demand. If ale HolonObjects have an active Element, the
+		 * simulation will try to fully supply as many HolonObjects as possible.
+		 */
+		MininumDemandFirst, 
+		/**
+		 * All HolonObjects will receive the same amount of energy.
+		 */
+		AllEqual
+	}
     /** the Fairness model in use */
-    private short fairnessModel = 0;
+    private FairnessModel fairnessModel = FairnessModel.MininumDemandFirst;
+    
     /*
      * Array of all categories in the model. It is set by default with the
      * categories ENERGY, BUILDINGS and COMPONENTS
@@ -103,6 +120,20 @@ public class Model {
      * list.
      */
     private ArrayList<CpsEdge> edgesOnCanvas;
+    
+    
+    private ArrayList<HolonObject> holonObjectsOnCanvas = new ArrayList<HolonObject>();
+    private ArrayList<CpsNode> nodesOnCanvas= new ArrayList<CpsNode>();
+    private ArrayList<HolonSwitch> switchsOnCanvas= new ArrayList<HolonSwitch>();
+    
+    
+    
+    
+    
+    
+    
+    
+    
     /*
      * Array for all Listeners
      */
@@ -522,23 +553,6 @@ public class Model {
         this.clipboardObjects = c;
     }
 
-    /**
-     * Returns the Console.
-     *
-     * @return console the console
-     */
-    public Console getConsole() {
-        return console;
-    }
-
-    /**
-     * Sets the console.
-     *
-     * @param console the console
-     */
-    public void setConsole(Console console) {
-        this.console = console;
-    }
 
     /**
      * @return the maxCapacity
@@ -956,14 +970,14 @@ public class Model {
 	/**
 	 * @return the fairnessModel
 	 */
-	public short getFairnessModel() {
+	public FairnessModel getFairnessModel() {
 		return fairnessModel;
 	}
 	
 	/**
 	 * @param fairnessModel the fairnessModel to set
 	 */
-	public void setFairnessModel(short fairnessModel) {
+	public void setFairnessModel(FairnessModel fairnessModel) {
 		this.fairnessModel = fairnessModel;
 	}
 	
@@ -1023,4 +1037,44 @@ public class Model {
     public void setHashcodeMap(HashMap<Integer, CpsUpperNode> hashcodeMap) {
         this.hashcodeMap = hashcodeMap;
     }
+
+    
+    
+    
+    
+    
+	public ArrayList<HolonSwitch> getSwitchsOnCanvas() {
+		return switchsOnCanvas;
+	}
+
+	public void setSwitchsOnCanvas(ArrayList<HolonSwitch> switchsOnCanvas) {
+		this.switchsOnCanvas = switchsOnCanvas;
+	}
+
+	public ArrayList<CpsNode> getNodesOnCanvas() {
+		return nodesOnCanvas;
+	}
+
+	public void setNodesOnCanvas(ArrayList<CpsNode> nodesOnCanvas) {
+		this.nodesOnCanvas = nodesOnCanvas;
+	}
+
+	public ArrayList<HolonObject> getHolonObjectsOnCanvas() {
+		return holonObjectsOnCanvas;
+	}
+
+	public void setHolonObjectsOnCanvas(ArrayList<HolonObject> holonObjectsOnCanvas) {
+		this.holonObjectsOnCanvas = holonObjectsOnCanvas;
+	}
+	
+	public void defineLists() {
+		switchsOnCanvas.clear();
+		nodesOnCanvas.clear();
+		holonObjectsOnCanvas.clear();
+		for(AbstractCpsObject aCps : this.objectsOnCanvas) {
+			if(aCps instanceof HolonObject)holonObjectsOnCanvas.add((HolonObject) aCps);
+			else if(aCps instanceof CpsNode)nodesOnCanvas.add((CpsNode) aCps);
+			else if(aCps instanceof HolonSwitch)switchsOnCanvas.add((HolonSwitch) aCps);
+		}
+	}
 }

+ 15 - 0
src/ui/model/Passiv.java

@@ -0,0 +1,15 @@
+package ui.model;
+
+import classes.HolonObject;
+
+public class Passiv extends DecoratedHolonObject {
+	public Passiv(HolonObject objectToLookAt) {
+		super(objectToLookAt);
+	}
+	
+	@Override
+	float getEnergy() {
+		return 0;
+	}
+
+}

+ 54 - 0
src/ui/model/Supplier.java

@@ -0,0 +1,54 @@
+package ui.model;
+
+import java.util.ArrayList;
+
+import classes.HolonObject;
+
+public class Supplier extends DecoratedHolonObject {
+
+	private ArrayList<ConsumerListEntry> consumerList = new ArrayList<ConsumerListEntry>();
+	private float energyToSupplyNetwork;
+	private float energySupplied;
+	public Supplier(HolonObject objectToLookAt, float energyToSupplyNetwork) {
+		super(objectToLookAt);
+		this.energyToSupplyNetwork = energyToSupplyNetwork;
+		energySupplied = 0.0f;
+	}
+
+	@Override
+	float getEnergy() {
+		return energyToSupplyNetwork;
+	}
+
+	public ArrayList<ConsumerListEntry> getConsumerList() {
+		return consumerList;
+	}
+
+	public void setConsumerList(ArrayList<ConsumerListEntry> consumerList) {
+		this.consumerList = consumerList;
+	}
+
+	public float getEnergyToSupplyNetwork() {
+		return energyToSupplyNetwork;
+	}
+
+	public float getEnergySupplied() {
+		return energySupplied;
+	}
+
+	public void setEnergySupplied(float energySupplied) {
+		this.energySupplied = energySupplied;
+	}
+	public class ConsumerListEntry{
+		public Consumer consumer;
+		public float energyToConsumer;
+		public ConsumerListEntry(Consumer consumer, float energyToConsumer) {
+			this.consumer= consumer;
+			this.energyToConsumer = energyToConsumer;
+		}
+	}
+	@Override
+	public String toString() {
+		return getModel().getName();
+	}
+}

+ 359 - 0
src/ui/model/VisualRepresentationalState.java

@@ -0,0 +1,359 @@
+package ui.model;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.ListIterator;
+import java.util.stream.Collectors;
+
+import classes.AbstractCpsObject;
+import classes.CpsEdge;
+import classes.CpsNode;
+import classes.CpsUpperNode;
+import classes.IntermediateCalculationCable;
+import classes.ExitCable;
+import classes.ExitCable.ExitCableState;
+
+public class VisualRepresentationalState {
+	private ArrayList<Supplier> supplierList = new ArrayList<Supplier>();
+	private ArrayList<Passiv> passivList= new ArrayList<Passiv>();
+	private ArrayList<Consumer> consumerList= new ArrayList<Consumer>();
+	private ArrayList<CpsNode> nodeList= new ArrayList<CpsNode>();
+	private ArrayList<DecoratedCable> cableList= new ArrayList<DecoratedCable>();
+	private ArrayList<DecoratedSwitch> switchList= new ArrayList<DecoratedSwitch>();
+	private ArrayList<DecoratedGroupNode> groupNodeList= new ArrayList<DecoratedGroupNode>();
+	private ArrayList<ExitCable> exitCableList= new ArrayList<ExitCable>();
+	
+	//ForFastAccessIndividualGroupNodes:
+	private HashMap<CpsUpperNode, DecoratedGroupNode> createdGroupNodes;
+	
+	public VisualRepresentationalState(DecoratedState stateFromThisTimestep, MinimumModel minimumModel) {
+		reassignObjects(stateFromThisTimestep, minimumModel);
+	}
+
+
+	//Getter:
+	public ArrayList<Supplier> getSupplierList() {
+		return supplierList;
+	}
+	public ArrayList<Passiv> getPassivList() {
+		return passivList;
+	}
+	public ArrayList<Consumer> getConsumerList() {
+		return consumerList;
+	}
+	public ArrayList<CpsNode> getNodeList() {
+		return nodeList;
+	}
+	public ArrayList<DecoratedCable> getCableList() {
+		return cableList;
+	}
+	public ArrayList<DecoratedSwitch> getSwitchList() {
+		return switchList;
+	}
+	public ArrayList<DecoratedGroupNode> getGroupNodeList() {
+		return groupNodeList;
+	}
+	
+	//Reassignments:
+	private void reassignObjects(DecoratedState stateFromThisTimestep, MinimumModel minimumModel) {
+		HashMap<AbstractCpsObject, CpsUpperNode> inGroupObjects = minimumModel.getInGroupObjects();
+		HashMap<CpsEdge, CpsUpperNode> inGroupEdges = minimumModel.getInGroupEdges();
+		createdGroupNodes =  new HashMap<CpsUpperNode, DecoratedGroupNode>();
+		
+		ArrayList<IntermediateCalculationCable> exitCables = new ArrayList<IntermediateCalculationCable>();
+		//createThem
+		for(CpsUpperNode groupNode :  minimumModel.getUppderNodeList()) {
+			createdGroupNodes.put(groupNode, new DecoratedGroupNode(groupNode));
+		}
+		//unrolling Networks
+		for(DecoratedNetwork net : stateFromThisTimestep.getNetworkList()) {
+			for(Consumer con : net.getConsumerList()) {
+				DecoratedGroupNode groupNodeFromObject = addObject(inGroupObjects, con.getModel(), consumerList, con, createdGroupNodes);
+				if(groupNodeFromObject != null) {
+					addToGroupNode(con, groupNodeFromObject.getConsumerList());
+				}
+			}
+			for(Consumer con : net.getConsumerSelfSuppliedList()) {
+				DecoratedGroupNode groupNodeFromObject = addObject(inGroupObjects, con.getModel(), consumerList, con, createdGroupNodes);
+				if(groupNodeFromObject != null) {
+					addToGroupNode(con, groupNodeFromObject.getConsumerList());
+				}
+			}
+			for(Supplier sup : net.getSupplierList()) {
+				DecoratedGroupNode groupNodeFromObject = addObject(inGroupObjects, sup.getModel(), supplierList, sup, createdGroupNodes);
+				if(groupNodeFromObject != null) {
+					addToGroupNode(sup, groupNodeFromObject.getSupplierList());
+				}
+			}
+			for(Passiv pas : net.getPassivNoEnergyList()) {
+				DecoratedGroupNode groupNodeFromObject = addObject(inGroupObjects, pas.getModel(), passivList, pas, createdGroupNodes);
+				if(groupNodeFromObject != null) {
+					addToGroupNode(pas, groupNodeFromObject.getPassivList());
+				}
+			}
+			for(DecoratedCable cable : net.getDecoratedCableList()) {
+				DecoratedGroupNode groupNodeFromObject = addObject(inGroupEdges, cable.getModel(), cableList ,cable, createdGroupNodes);
+				addCable(inGroupObjects, cable, groupNodeFromObject, exitCables);
+			}
+		}
+		for(DecoratedCable cable : stateFromThisTimestep.getLeftOverEdges()) {
+			DecoratedGroupNode groupNodeFromObject = addObject(inGroupEdges, cable.getModel(), cableList ,cable, createdGroupNodes);
+			addCable(inGroupObjects, cable, groupNodeFromObject, exitCables);
+		}
+		for(CpsNode node : minimumModel.getNodeList()) {
+			DecoratedGroupNode groupNodeFromObject = addObject(inGroupObjects, node, nodeList ,node, createdGroupNodes);
+			if(groupNodeFromObject != null) {
+				addToGroupNode(node, groupNodeFromObject.getNodeList());
+			}
+		}
+		for(DecoratedSwitch dSwitch: stateFromThisTimestep.getDecoratedSwitches()) {
+			DecoratedGroupNode groupNodeFromObject = addObject(inGroupObjects, dSwitch.getModel(), switchList, dSwitch, createdGroupNodes);
+			if(groupNodeFromObject != null) {
+				addToGroupNode(dSwitch, groupNodeFromObject.getSwitchList());
+			}
+		}
+		for(DecoratedGroupNode dGroupNode: createdGroupNodes.values()) {
+			DecoratedGroupNode groupNodeFromObject = addObject(inGroupObjects, dGroupNode.getModel(), groupNodeList, dGroupNode, createdGroupNodes);
+			if(groupNodeFromObject != null) {
+				addToGroupNode(dGroupNode, groupNodeFromObject.getGroupNodeList());
+			}
+		}
+		//Create TreeNodeModel:
+		HashMap<CpsUpperNode, TreeNode<TreeGroupNodeData>> fastaccess= new HashMap<CpsUpperNode, TreeNode<TreeGroupNodeData>>();
+		TreeNode<TreeGroupNodeData> root = new TreeNode<TreeGroupNodeData>(null, new ArrayList<TreeNode<TreeGroupNodeData>>(), new TreeGroupNodeData(null, 0));
+		fastaccess.put(null, root);
+		for(DecoratedGroupNode dGroupNode: getGroupNodeList()) {
+			addTreeNode(root, dGroupNode, 1, fastaccess);
+		}
+		for(IntermediateCalculationCable cable : exitCables) {
+			createExitEdgesV2(root,cable.getCable() , cable.getInsideObject(),cable.getInsideUpperNode(),cable.getOusideObject(),cable.getOutsideUpperNode(), fastaccess);			
+		}
+	}
+
+
+	private void createExitEdgesV2(TreeNode<TreeGroupNodeData> root, DecoratedCable cable,  AbstractCpsObject insideObject,
+			CpsUpperNode insideUpperNode, AbstractCpsObject ousideObject, CpsUpperNode outsideUpperNode, HashMap<CpsUpperNode, TreeNode<TreeGroupNodeData>> fastaccess) {
+		//Create Up List
+		LinkedList<TreeNode<TreeGroupNodeData>> listFromStart = createList(insideUpperNode, fastaccess);
+		LinkedList<TreeNode<TreeGroupNodeData>> listFromEnd = createList(outsideUpperNode, fastaccess);
+		LinkedList<TreeNode<TreeGroupNodeData>> common = new LinkedList<TreeNode<TreeGroupNodeData>>(listFromStart);
+		common.retainAll(listFromEnd);
+		TreeNode<TreeGroupNodeData> firstCommon = common.getFirst();
+		LinkedList<TreeNode<TreeGroupNodeData>> resultList = new LinkedList<TreeNode<TreeGroupNodeData>>();
+		//Add from listFromStart till firstCommon
+		createresultList(listFromStart, firstCommon, resultList);		
+		//Add firstCommon
+		resultList.add(firstCommon);
+		//Add from listFromEnd till firstCommon
+		createresultList(listFromEnd, firstCommon, resultList);
+		LinkedList<NodeInfo> infoList = new LinkedList<NodeInfo>();
+		//Categorize:
+		ListIterator<TreeNode<TreeGroupNodeData>> iter = resultList.listIterator();
+		
+		while(iter.hasNext()) {
+			//categorize
+			TreeNode<TreeGroupNodeData> actual, next = null, previous = null;
+			if(iter.hasPrevious()) {
+				previous =iter.previous();
+				iter.next();
+			}
+			actual = iter.next();
+			if(iter.hasNext()) {
+				next =iter.next();
+				iter.previous();
+			}
+			NodeInfo actualInfo = new NodeInfo(actual.getData().groupNode);
+			if(previous!= null) {
+				actualInfo.previousGroupNode = previous.getData().groupNode;
+				if(previous == actual.getParent()) {
+					actualInfo.previous = Info.Parent;
+				}else {
+					actualInfo.previous = Info.Child;
+				}
+			}
+			if(next!= null) {
+				actualInfo.nextGroupNode = next.getData().groupNode;
+				if(next == actual.getParent()) {
+					actualInfo.next = Info.Parent;
+				}else {
+					actualInfo.next = Info.Child;
+				}
+			}
+			infoList.add(actualInfo);
+		}
+		for(NodeInfo info: infoList) {
+			DecoratedGroupNode group = this.createdGroupNodes.get(info.groupNode);
+			ArrayList<ExitCable> mylist;
+			if(group == null) {
+				mylist = this.getExitCableList();
+			}else{
+				mylist = group.getExitCableList();
+			}
+			ExitCableState state =null;
+			if(info.previous == Info.Nothing) {
+				if(info.next == Info.Child) {
+					state = ExitCableState.DOWN;
+					mylist.add(new ExitCable(state, insideObject, info.nextGroupNode, cable));
+				}else if(info.next == Info.Parent) {
+					state = ExitCableState.UP;
+					mylist.add(new ExitCable(state, insideObject, ousideObject, cable));
+				}else {
+					System.out.println("Error in VisualState");
+				}
+			}else if(info.previous == Info.Child) {
+				if(info.next == Info.Child) {
+					state = ExitCableState.DOWNDOWN;
+					mylist.add(new ExitCable(state, info.previousGroupNode, info.nextGroupNode, cable));
+				}else if(info.next == Info.Parent) {
+					state = ExitCableState.DOWNUP;
+					mylist.add(new ExitCable(state, info.previousGroupNode, ousideObject, cable));
+				}else {
+					state = ExitCableState.DOWN;
+					mylist.add(new ExitCable(state, info.previousGroupNode, ousideObject, cable));
+				}
+			}else {//(info.previous == Info.Parent)
+				if(info.next == Info.Child) {
+					state = ExitCableState.DOWNUP;
+					mylist.add(new ExitCable(state, info.nextGroupNode, insideObject, cable));
+				}else if(info.next == Info.Parent) {
+					System.out.println("Error in VisualState");
+				}else {
+					state = ExitCableState.UP;
+					mylist.add(new ExitCable(state, ousideObject, insideObject, cable));
+				}
+			}
+		}
+	}
+
+
+	private void createresultList(LinkedList<TreeNode<TreeGroupNodeData>> list,
+			TreeNode<TreeGroupNodeData> firstCommon, LinkedList<TreeNode<TreeGroupNodeData>> resultList) {
+		for(TreeNode<TreeGroupNodeData> node: list) {
+			if(node == firstCommon) {
+				break;
+			}
+			resultList.add(node);
+		}
+	}
+
+
+	private LinkedList<TreeNode<TreeGroupNodeData>> createList(CpsUpperNode insideUpperNode,
+			HashMap<CpsUpperNode, TreeNode<TreeGroupNodeData>> fastaccess) {
+		TreeNode<TreeGroupNodeData> actualNode = fastaccess.get(insideUpperNode);
+		LinkedList<TreeNode<TreeGroupNodeData>> list = new LinkedList<TreeNode<TreeGroupNodeData>>();
+		list.add(actualNode);
+		while(actualNode.getParent() != null) {
+			actualNode = actualNode.getParent();
+			list.add(actualNode);
+		}
+		return list;
+	}
+
+
+	private void addCable(HashMap<AbstractCpsObject, CpsUpperNode> inGroupObjects, DecoratedCable cable,
+			DecoratedGroupNode groupNodeFromObject,ArrayList<IntermediateCalculationCable> exitCables) {
+		if(groupNodeFromObject != null) {
+			boolean isIntern = inGroupObjects.get(cable.getModel().getA()) == inGroupObjects.get(cable.getModel().getB()); //Case null == null is not possible trough before Filtering MinimumModel#addUpperObjects(CpsUpperNode)
+			if(isIntern) {
+				addToGroupNode(cable, groupNodeFromObject.getInternCableList());						
+			}else {
+				if(inGroupObjects.get(cable.getModel().getA()) == groupNodeFromObject.getModel() && inGroupObjects.get(cable.getModel().getB()) != groupNodeFromObject.getModel()) {					
+					//addToGroupNode(new ExitCable(cable, groupNodeFromObject.getModel(),inGroupObjects.get(cable.getModel().getB()), cable.getModel().getA(), cable.getModel().getB()), groupNodeFromObject.getExitCableList());		
+					exitCables.add(new IntermediateCalculationCable(cable, groupNodeFromObject.getModel(),inGroupObjects.get(cable.getModel().getB()), cable.getModel().getA(), cable.getModel().getB()));
+				}else if(inGroupObjects.get(cable.getModel().getA()) != groupNodeFromObject.getModel() && inGroupObjects.get(cable.getModel().getB()) == groupNodeFromObject.getModel()) {					
+					//addToGroupNode(new ExitCable(cable, groupNodeFromObject.getModel(),inGroupObjects.get(cable.getModel().getA()), cable.getModel().getB(), cable.getModel().getA()), groupNodeFromObject.getExitCableList());		
+					exitCables.add(new IntermediateCalculationCable(cable, groupNodeFromObject.getModel(),inGroupObjects.get(cable.getModel().getA()), cable.getModel().getB(), cable.getModel().getA()));
+				}
+			}
+		}
+	}
+
+
+	private <DecoratedObject> void addToGroupNode(DecoratedObject object, ArrayList<DecoratedObject> groupNodeListPar) {
+		groupNodeListPar.add(object);
+	}
+
+	//Generics
+	private <ModelOfObject, DecoratedObject> DecoratedGroupNode addObject(HashMap<ModelOfObject, CpsUpperNode> inGroupObjects, ModelOfObject modelOfObject, ArrayList<DecoratedObject> listToAdd, DecoratedObject object, HashMap<CpsUpperNode, DecoratedGroupNode> createdGroupNodes) {
+		if(inGroupObjects.containsKey(modelOfObject)) {
+			return  createdGroupNodes.get(inGroupObjects.get(modelOfObject));
+		}
+		listToAdd.add(object);
+		return null;
+	}
+
+	public enum Info{
+		Nothing, Parent, Child
+	}
+	private class NodeInfo{
+		public CpsUpperNode groupNode;
+		public Info previous = Info.Nothing;
+		public Info next = Info.Nothing;
+		public CpsUpperNode previousGroupNode = null;
+		public CpsUpperNode nextGroupNode = null;
+		
+		public NodeInfo(CpsUpperNode groupNode) {
+			this.groupNode = groupNode;
+		}
+		public String toString() {
+			return "Previuos: " + previous.toString() + "|Next: " + next.toString();
+		}
+		
+	}
+	public HashMap<CpsUpperNode, DecoratedGroupNode> getCreatedGroupNodes() {
+		return createdGroupNodes;
+	}
+	private class TreeNode<T> {
+		private  TreeNode<T> parentNode;
+		private List<TreeNode<T>> children;
+		private T data;
+		
+		public TreeNode( TreeNode<T> parentNode, List<TreeNode<T>> children, T data) {
+			this.parentNode = parentNode;
+			this.children = children;
+			this.data = data;
+		}
+		
+		//Methods
+		public TreeNode<T> getParent(){
+			return parentNode;
+		}
+		public List<TreeNode<T>> getChildren(){
+			return children;
+		}
+		public T getData() {
+			return data;
+		}
+		public String toString() {
+			return "[" + data.toString() + " Children(" + children.stream().map(Object::toString).collect(Collectors.joining(", ")) + ")]";
+		}
+	}
+	private class TreeGroupNodeData{
+		public CpsUpperNode groupNode;
+		public int layer;
+		public TreeGroupNodeData(CpsUpperNode groupNode, int layer) {
+			this.groupNode = groupNode;
+			this.layer = layer;
+		}
+		public String toString() {
+			return "Layer:" + layer;
+		}
+	}
+	
+	private void addTreeNode(TreeNode<TreeGroupNodeData> node, DecoratedGroupNode dGroupNode, int layer, HashMap<CpsUpperNode, TreeNode<TreeGroupNodeData>> fastaccess) {
+		TreeNode<TreeGroupNodeData> newNode = new TreeNode<TreeGroupNodeData> (node, new ArrayList<TreeNode<TreeGroupNodeData>>() , new TreeGroupNodeData(dGroupNode.getModel(), layer));
+		node.getChildren().add(newNode);
+		fastaccess.put(newNode.data.groupNode, newNode);
+		for(DecoratedGroupNode dGroupNodeIntern: dGroupNode.getGroupNodeList()) {
+			addTreeNode(newNode, dGroupNodeIntern, layer+1, fastaccess);
+		}
+	}
+
+
+	public ArrayList<ExitCable> getExitCableList() {
+		return exitCableList;
+	}
+}
+

+ 14 - 300
src/ui/view/AbstractCanvas.java

@@ -92,300 +92,18 @@ public abstract class AbstractCanvas extends JPanel {
 
 	// ------------------------------------------ METHODS
 	// ------------------------------------------
-	String paintEdge(CpsEdge con, String maxCap) {
-		if (con!=null && con.getA() != null && con.getB() != null && con.getA().getId() != model.getSelectedObjectID() && con.getB().getId() != model.getSelectedObjectID()
-				&& con != edgeHighlight) {
-			if (con.getConnected() == CpsEdge.CON_UPPER_NODE
-					|| con.getConnected() == CpsEdge.CON_UPPER_NODE_AND_INSIDE) {
-				setEdgeState(con);
-			} else {
-				g2.setColor(Color.DARK_GRAY);
-				g2.setStroke(new BasicStroke(2));
-			}
-			g2.drawLine(con.getA().getPosition().x, con.getA().getPosition().y, con.getB().getPosition().x,
-					con.getB().getPosition().y);
-
-			maxCap = setCapacityString(con, maxCap);
-
-			if (showedInformation[0]) {
-				if (con.getConnected() == CpsEdge.CON_UPPER_NODE
-						|| con.getConnected() == CpsEdge.CON_UPPER_NODE_AND_INSIDE) {
-					g2.drawString(con.getFlow() + "/" + maxCap,
-							(con.getA().getPosition().x + con.getB().getPosition().x) / 2,
-							(con.getA().getPosition().y + con.getB().getPosition().y) / 2);
-				} else {
-					g2.drawString("not connected", (con.getA().getPosition().x + con.getB().getPosition().x) / 2,
-							(con.getA().getPosition().y + con.getB().getPosition().y) / 2);
-				}
-			}
-		}
-
-		return maxCap;
-	}
-
-	void setEdgeState(CpsEdge con) {
-		if (con.isWorking()) {
-			g2.setColor(Color.GREEN);
-			if (con.getCapacity() != CpsEdge.CAPACITY_INFINITE) {
-				g2.setStroke(new BasicStroke(Math.min(((con.getFlow() / con.getCapacity() * 3) + 1), 4)));
-			}
-		} else {
-			g2.setColor(Color.RED);
-			g2.setStroke(new BasicStroke(2));
-		}
-	}
-
-	String setCapacityString(CpsEdge con, String maxCap) {
-		if (con.getCapacity() == -1) {
-			maxCap = Character.toString('\u221e');
-		} else if (con.getCapacity() == -2) {
-			maxCap = "???";
-		} else {
-			maxCap = String.valueOf(con.getCapacity());
-		}
-		return maxCap;
-	}
-
-	String drawEdgeLine(CpsEdge con, String maxCap) {
-		if (con.getA().getId() == model.getSelectedObjectID() || model.getSelectedCpsObjects().contains(con.getA())
-				|| tempSelected.contains(con.getA()) || con.getB().getId() == model.getSelectedObjectID()
-				|| model.getSelectedCpsObjects().contains(con.getB())
-				|| tempSelected.contains(con.getB()) && con != edgeHighlight) {
-			g2.drawLine(con.getA().getPosition().x, con.getA().getPosition().y, con.getB().getPosition().x,
-					con.getB().getPosition().y);
-
-			maxCap = setCapacityString(con, maxCap);
-
-			if (showedInformation[0]) {
-				if (con.getConnected() == CpsEdge.CON_UPPER_NODE
-						|| con.getConnected() == CpsEdge.CON_UPPER_NODE_AND_INSIDE) {
-					g2.drawString(con.getFlow() + "/" + maxCap,
-							(con.getA().getPosition().x + con.getB().getPosition().x) / 2,
-							(con.getA().getPosition().y + con.getB().getPosition().y) / 2);
-				} else {
-					g2.drawString("not connected", (con.getA().getPosition().x + con.getB().getPosition().x) / 2,
-							(con.getA().getPosition().y + con.getB().getPosition().y) / 2);
-				}
-			}
-		}
-
-		return maxCap;
-	}
-
-	/**
-	 * Paints the SupplyBar for the given cps object on the canvas
-	 * 
-	 * @param g
-	 *            Graphics used
-	 * @param cps
-	 *            cpsObject which the supplyBar should be drawn for
-	 */
-	protected void paintSupplyBar(Graphics g, AbstractCpsObject cps) {
-		g2.setColor(Color.black);
-		/**
-		 * draw and fill the supply Bar
-		 */
-		if (model.getShowSupplyBars() && (cps instanceof HolonObject || cps instanceof HolonBattery))
-		{
-			// set Color & Percentage
-			/**
-			 * percentage the SupplyBar is representing
-			 */
-			float percentage = 0;
-			/**
-			 * color of the SupplyBar
-			 */
-			Color paintColor = Color.WHITE;
-			if(cps instanceof HolonObject)
-			{
-				HolonObject hl = (HolonObject) cps;
-				if (hl == null || !(hl.getState() == HolonObject.NOT_SUPPLIED
-						|| hl.getState() == HolonObject.PARTIALLY_SUPPLIED || hl.getState() == HolonObject.OVER_SUPPLIED)) {
-					/**
-					 * don't show Bars for unsupplied oder fully supplied Objects
-					 */
-					return;
-				}
-				/**
-				 * calculate Percentage & set Color
-				 */
-				percentage = hl.getSuppliedPercentage();
-				paintColor = hl.getColor();
-			}
-			else if (cps instanceof HolonBattery){
-				HolonBattery hB = (HolonBattery) cps;
-				if(hB == null || hB.getCapacity() == 0){
-					return;
-				}
-				/**
-				 *  get percentage filled
-				 */
-				percentage = hB.getStateOfChargeAtTimeStep(model.getCurIteration()-1) / hB.getCapacity();
-
-				/**
-				 * calculate the Color (Red->Yellow->Green)
-				 */
-				Color color1 = Color.RED;
-				Color color2 = Color.GREEN;
-				//
-				float colorPercentage;
-				if(percentage < 0.5f){
-					colorPercentage = percentage * 2;
-					color1 = Color.RED;
-					color2 = Color.YELLOW;
-				}
-				else {
-					colorPercentage = (percentage - 0.5f) * 2;
-					color1 = Color.YELLOW;
-					color2 = Color.GREEN;
-				}
-				final int dRed = color2.getRed() - color1.getRed();
-				final int dGreen = color2.getGreen() - color1.getGreen();
-				final int dBlue = color2.getBlue() - color1.getBlue();	
-				
-				int resultRed = color1.getRed() +  (int)(colorPercentage * dRed);
-				int resultGreen = color1.getGreen() +  (int)(colorPercentage * dGreen);
-				int resultBlue = color1.getBlue() + (int)( colorPercentage * dBlue);
-				
-				paintColor = new Color(	resultRed,resultGreen,resultBlue);
-			}
-			
-			/**
-			 * Starting position x of the bar
-			 */
-			int barX = (int) (cps.getPosition().x - controller.getScaleDiv2() - scalediv20);
-			
-			/**
-			 * Starting position y of the bar
-			 */
-			int barY = (int) (cps.getPosition().y - controller.getScaleDiv2() + controller.getScale() + 1);
-			
-			/**
-			 * if object should be replaced -> move bar below the ReplacementIndicator
-			 */
-			if(mayBeReplaced==cps) barY += 3;
-			
-			/**
-			 * Width of the bar
-			 */
-			int barWidth = (int) (controller.getScale() + ((scalediv20) * 2) - 1);
-			
-			/**
-			 * Height of the bar 
-			 */
-			int barHeight = (int) (controller.getScale() / 5);
-
-			/** 
-			 * draw Rectangle below the image 
-			 */
-			g2.setStroke(new BasicStroke(1));
-			g2.drawRect(barX, barY, barWidth, barHeight);
-				
-			g2.setColor(paintColor);
-
-			/** fill it accordingly if filled partially */
-			if (percentage < 1)
-				g2.fillRect(barX + 1, barY + 1, (int) ((barWidth - 1) * percentage), barHeight - 1);
-			else /** over supplied / supplied bar should be fully filled */
-				g2.fillRect(barX + 1, barY + 1, (int) (barWidth - 1), barHeight - 1);
-			
-			/** write percentage */
-			if(percentage>1)
-				g2.setColor(Color.WHITE);
-			else
-				g2.setColor(Color.BLACK);
-			
-			/** original font */
-			Font oldFont = g2.getFont();
-			
-			g.setFont(new Font("TimesRoman", Font.PLAIN, (int) (barHeight * 1.5) - 2));
-			
-			String percentageString = (Math.round((percentage * 100))) + "%";
-			int stringWidth = (int) g2.getFontMetrics().getStringBounds(percentageString, g2).getWidth();
-			g2.drawString(percentageString, barX + barWidth / 2 + 1 - stringWidth / 2, barY + barHeight);
 	
-			/** recover Font and Color */
-			g2.setFont(oldFont);
-			g2.setColor(Color.BLACK);
-				
-		}
-	}
-
-	void setEdgePictureAndHighlighting(AbstractCpsObject cps) {
-		// node image
-		if (cps instanceof CpsNode && (cps == tempCps || model.getSelectedCpsObject() == cps
-				|| model.getSelectedCpsObjects().contains(cps) || tempSelected.contains(cps))) {
-			img = Util.loadImage("/Images/node_selected.png");
-		} else {
-			if (cps instanceof HolonSwitch) {//TODO: What the hell are thes ecalls doing here?
-				if (((HolonSwitch) cps).getState(model.getCurIteration())) {
-					((HolonSwitch) cps).setAutoState(true);
-				} else {
-					((HolonSwitch) cps).setAutoState(false);
-				}
-			}
-			// Highlighting
-			if ((cps == tempCps && model.getSelectedCpsObjects().size() == 0 && tempSelected.size() == 0)
-					|| model.getSelectedCpsObjects().contains(cps) || tempSelected.contains(cps)) {
-				/**
-				 * draw selected Blue Frame
-				 */
-				g2.setColor(Color.BLUE);
-				g2.fillRect((int) (cps.getPosition().x - controller.getScaleDiv2() - scalediv20),
-						(int) (cps.getPosition().y - controller.getScaleDiv2() - scalediv20),
-						(int) (controller.getScale() + (scalediv20 * 2)),
-						(int) (controller.getScale() + (scalediv20 * 2)));
-				/**
-				 * 
-				 */
-				if(cps instanceof HolonObject){
-					g2.setColor(((HolonObject)cps).getColor());
-					g2.fillRect((int) (cps.getPosition().x - controller.getScaleDiv2() - scalediv20+3),
-							(int) (cps.getPosition().y - controller.getScaleDiv2() - scalediv20+3),
-							(int) (controller.getScale() + (scalediv20 * 2)-6),
-							(int) (controller.getScale() + (scalediv20 * 2)-6));					
-				}
-				
-				if (showedInformation[1] && cps instanceof HolonObject) {
-					g2.setColor(Color.BLACK);
-					float totalEnergy = ((HolonObject) cps).getCurrentEnergyAtTimeStep(model.getCurIteration());
-					g2.drawString(Float.toString(totalEnergy), cps.getPosition().x - controller.getScaleDiv2(),
-							cps.getPosition().y - controller.getScaleDiv2() - 10);
-				}else if (showedInformation[1] && cps instanceof HolonBattery)
-                {
-                	g2.setColor(Color.BLACK);
-                    g2.drawString(((HolonBattery) cps).getCanvasBatteryString(model.getCurIteration()), cps.getPosition().x - controller.getScaleDiv2(),
-                            cps.getPosition().y - controller.getScaleDiv2() - 10);
-                }
-			} else if (cps instanceof HolonObject) {
-				g2.setColor(((HolonObject) cps).getColor());
 
-				g2.fillRect((int) (cps.getPosition().x - controller.getScaleDiv2() - scalediv20),
-						(int) (cps.getPosition().y - controller.getScaleDiv2() - scalediv20),
-						(int) (controller.getScale() + (scalediv20 * 2)),
-						(int) (controller.getScale() + (scalediv20 * 2)));
+	
+	
 
-				if (showedInformation[1]) {
-					g2.setColor(Color.BLACK);
-					float totalEnergy = ((HolonObject) cps).getCurrentEnergyAtTimeStep(model.getCurIteration());
-					g2.drawString(Float.toString(totalEnergy), cps.getPosition().x - controller.getScaleDiv2(),
-							cps.getPosition().y - controller.getScaleDiv2() - 10);
-				}
-			}else if (cps instanceof HolonBattery) {
-                if (showedInformation[1]) {
-                	g2.setColor(Color.BLACK);
-                    g2.drawString(((HolonBattery) cps).getCanvasBatteryString(model.getCurIteration()), cps.getPosition().x - controller.getScaleDiv2(),
-                            cps.getPosition().y - controller.getScaleDiv2() - 10);
-                }
-            }
-			// set image
-			if(cps instanceof HolonBattery)
-			{
-				img = Util.loadImage(((HolonBattery) cps).getImageBattery());
-			}else
-			{
-				img = Util.loadImage(cps.getImage());
-			}
+	class ACpsHandle{
+		public AbstractCpsObject object;
+		ACpsHandle(AbstractCpsObject object){
+			this.object = object;
+		}
+		public String toString() {
+			return object.toString();
 		}
 	}
 
@@ -400,7 +118,10 @@ public abstract class AbstractCanvas extends JPanel {
 			g2.drawRect(sx, y, x - sx, sy - y);
 		}
 	}
-
+	/**
+	 * @deprecated
+	 * @param g
+	 */
 	void showTooltip(Graphics g) {
 		if (toolTip) {
 			g2.setColor(new Color(255, 225, 150));
@@ -427,14 +148,7 @@ public abstract class AbstractCanvas extends JPanel {
 		}
 	}
 
-	void setConsoleTextAfterSelect(AbstractCpsObject cps) {
-		if (model.getShowConsoleLog()) {
-			controller.addTextToConsole("Selected: ", Color.BLACK, 12, false, false, false);
-			controller.addTextToConsole("" + cps.getName(), Color.BLUE, 12, true, false, false);
-			controller.addTextToConsole(", ID:", Color.BLACK, 12, false, false, false);
-			controller.addTextToConsole("" + cps.getId(), Color.RED, 12, true, false, true);
-		}
-	}
+
 
 	void setRightClickMenu(MouseEvent e) {
 		if (e.getButton() == MouseEvent.BUTTON3) {

+ 0 - 4
src/ui/view/AddElementPopUp.java

@@ -175,8 +175,6 @@ public class AddElementPopUp extends JDialog {
 		hl = holonElement;
 		elementName.setText(hl.getEleName());
 		amount.setText(""+hl.getAmount());
-		flexibleEnergy.setText(""+hl.getFlexibleEnergyAvailablePerElement());
-		checkboxFlexible.setSelected(hl.isFlexible());
 		providedEnergy.setText(""+hl.getEnergyPerElement());
 		checkBoxActive.setSelected(hl.isActive());
 		
@@ -205,8 +203,6 @@ public class AddElementPopUp extends JDialog {
 					hl.setEnergyPerElement(energy);
 				}
 				hl.setActive(checkBoxActive.isSelected());
-				hl.setFlexible(checkboxFlexible.isSelected());
-				hl.setFlexibleEnergyAvailable(Float.parseFloat(flexibleEnergy.getText()));
 				dispose();
 			} catch (NumberFormatException e) {
 				JOptionPane.showMessageDialog(new JFrame(), Languages.getLanguage()[68]);

+ 197 - 0
src/ui/view/AlgoWindow.java

@@ -0,0 +1,197 @@
+package ui.view;
+
+import java.awt.BorderLayout;
+import java.awt.Dimension;
+import java.awt.Font;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileReader;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.util.Arrays;
+import java.util.Scanner;
+import java.util.stream.Collectors;
+
+import javax.swing.JButton;
+import javax.swing.JFileChooser;
+import javax.swing.JFrame;
+import javax.swing.JLabel;
+import javax.swing.JMenu;
+import javax.swing.JMenuBar;
+import javax.swing.JMenuItem;
+import javax.swing.JOptionPane;
+import javax.swing.JPanel;
+import javax.swing.JTextArea;
+import javax.swing.JTextPane;
+import javax.swing.filechooser.FileNameExtensionFilter;
+import javax.swing.text.SimpleAttributeSet;
+import javax.swing.text.StyleConstants;
+import javax.swing.text.StyledDocument;
+import javax.tools.JavaCompiler;
+import javax.tools.ToolProvider;
+
+import api.Algorithm;
+import ui.controller.Control;
+
+//TODO delete old class AlgorithmMenu and change this class to AlgorithmMenu;
+@SuppressWarnings("serial")
+public class AlgoWindow extends JFrame{
+	private Algorithm actual;
+	private Control control;
+	private JPanel content = new JPanel();
+	AlgoWindow(JFrame parentFrame, Control control){
+		this.control = control;
+		this.setTitle("Algorithm");
+		this.setVisible(true);
+		this.setContentPane(content);
+		this.setIconImage(Util.loadImage("/Images/Holeg.png", 30, 30));
+		initMenuBar();
+		initDefaultContentPanel();
+		this.pack();
+		this.setLocationRelativeTo(parentFrame);
+	}
+	private void initMenuBar() {
+		JMenuBar menuBar = new JMenuBar();
+		JMenu menuSelect = new JMenu("File");
+		JMenuItem menuItemAlgorithm= new JMenuItem("Open .java-File..");
+		menuItemAlgorithm.addActionListener(actionEvent -> openJavaFile());
+		menuSelect.add(menuItemAlgorithm);
+		JMenuItem menuItemFolder= new JMenuItem("Open Folder..");
+		menuItemFolder.addActionListener(actionEvent->openFolder(menuSelect));
+		menuSelect.add(menuItemFolder);
+		menuSelect.addSeparator();
+		JMenu menuHelp = new JMenu("Help");
+		menuBar.add(menuSelect);
+		menuBar.add(menuHelp);
+		this.setJMenuBar(menuBar);
+	}
+	
+	private void initDefaultContentPanel() {
+		content.setLayout(new BorderLayout());
+		JTextPane textPane = new JTextPane();
+		SimpleAttributeSet attribs = new SimpleAttributeSet();  
+		StyleConstants.setAlignment(attribs , StyleConstants.ALIGN_JUSTIFIED);
+		textPane.setParagraphAttributes(attribs, true);
+		textPane.setText("No algorithm is loaded."
+				+"\n OPTION[1]:"
+				+"\n•  Select '.java'-file via the file browser. (File\u2192Open .jave-File..)"
+				+"\n"
+				+"\n OPTION[2]:"
+				+"\n• First select the folder where the algorithm '.java'-file is located. (File\u2192Open Folder..)"
+				+"\n• Second load the algorithm. (File\u2192'YourAlgo')");
+		textPane.setFont(new Font("Serif", Font.PLAIN, 16));
+		
+		
+		content.add(textPane, BorderLayout.CENTER);
+		content.setPreferredSize(new Dimension(500, 500));
+	}
+	
+	/**
+	 * 
+	 */
+	private void openJavaFile() {
+		JFileChooser fileChooser = new JFileChooser();
+		fileChooser.setCurrentDirectory(new File(System.getProperty("user.dir")+"/src/"));
+		fileChooser.setFileFilter(new FileNameExtensionFilter("JAVA Source Files", "java"));
+		fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
+		fileChooser.setAcceptAllFileFilterUsed(false);
+		int result = fileChooser.showOpenDialog(this);
+		if(result == JFileChooser.APPROVE_OPTION) {
+			//Found a file
+			loadAlgorithm(fileChooser.getSelectedFile());
+		}
+	}
+	
+	private void openFolder(JMenu menuSelect) {
+		JFileChooser fileChooser = new JFileChooser();
+		fileChooser.setCurrentDirectory(new File(System.getProperty("user.dir")+"/src/"));
+		fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
+		fileChooser.setAcceptAllFileFilterUsed(false);
+		int result = fileChooser.showOpenDialog(this);
+		if(result == JFileChooser.APPROVE_OPTION) {
+			File[] files = fileChooser.getSelectedFile().listFiles(file -> file.getName().endsWith(".java"));
+			
+			//Remove all Index from old Folder
+			for(int i= menuSelect.getItemCount()-1; i> 2; i--) {
+				menuSelect.remove(i);
+			}
+			for(File file: files) {
+				JMenuItem insertMenuItem = new JMenuItem(getNameWithoutExtension(file));
+				insertMenuItem.addActionListener(actionEvent -> loadAlgorithm(file));
+				menuSelect.add(insertMenuItem);
+			}
+		}
+	}
+	/**
+	 * Compile and load a java File.
+	 * @param javafile
+	 */
+	
+	private void loadAlgorithm(File javafile) {
+		//Get Class name:
+		String name = getNameWithoutExtension(javafile);
+		//get Package name
+		String packageName = "";
+		Scanner in = null;
+		try {
+			in = new Scanner(javafile);
+		} catch (FileNotFoundException e) {
+			generateErrorDialog("File not Found");
+		}
+		while(in.hasNext()) {
+			String line = in.nextLine().trim();
+			if(line.startsWith("package")) {
+				packageName = line.substring(8, line.length()-1);
+				break;
+			}
+		}
+		//GetPathName
+		//String path =  javafile.getParentFile().isDirectory() ? javafile.getParentFile().getAbsolutePath() : "";
+		File folder = javafile.getParentFile();
+		// Compile source file.
+		JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
+		if (ToolProvider.getSystemJavaCompiler() == null) {
+			generateErrorDialog("Please install the JDK on your system.");
+		}else {
+			compiler.run(null, null, null, javafile.getAbsolutePath());					
+		}
+		try {
+		URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { folder.toURI().toURL() });
+		Class<?> cls = Class.forName(packageName.isEmpty()?name:packageName + "." +name, true, classLoader);
+		Object object = cls.newInstance();
+		if(!(object instanceof Algorithm)) {
+			generateErrorDialog("Class does not implement CpsAlgorithm!");
+		}else {
+			actual = (Algorithm)object;
+			actual.setController(control);
+			this.setContentPane(actual.getAlgorithmPanel());
+			this.pack();
+		}
+		} catch (MalformedURLException e) {
+			generateErrorDialog("URLClassLoader error");
+		} catch (ClassNotFoundException e) {
+			generateErrorDialog("ClassNotFound error" + e.getMessage());
+		} catch (InstantiationException e) {
+			generateErrorDialog("Class does not implement a Constructor." + e.getMessage());
+		} catch (IllegalAccessException e) {
+			generateErrorDialog("Class set this method privat or protected needs to be public." + e.getMessage());
+		}
+	}
+	/**
+	 * Returns the Name of a file without Extension.
+	 * @param file
+	 * @return
+	 */
+	private String getNameWithoutExtension(File file) {
+		return file.getName().substring(0, file.getName().lastIndexOf("."));
+	}
+	/**
+	 * Generate a little Error Dialog to inform the User.
+	 * @param message
+	 */
+	private void generateErrorDialog(String message) {
+		System.out.println(message);
+		JOptionPane.showConfirmDialog(this, message, "Error", JOptionPane.OK_OPTION, JOptionPane.ERROR_MESSAGE);
+	}
+}

+ 0 - 190
src/ui/view/AlgorithmMenu.java

@@ -1,190 +0,0 @@
-package ui.view;
-
-import api.CpsAlgorithm;
-import ui.controller.Control;
-import ui.model.Model;
-
-import javax.swing.*;
-import javax.tools.JavaCompiler;
-import javax.tools.ToolProvider;
-import java.awt.*;
-import java.awt.event.ActionEvent;
-import java.awt.event.ActionListener;
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileReader;
-import java.net.URL;
-import java.net.URLClassLoader;
-import java.util.HashMap;
-
-/**
- * This Class represents the Menu, where you can select the Algorithms.
- * 
- * @author Gruppe14
- */
-public class AlgorithmMenu extends JMenu {
-
-	private static final long serialVersionUID = 1L;
-
-	JMenuItem algoFolderButton = new JMenuItem("Select Algorithm Folder");
-	// root Directory
-	File root = null;
-	Model model;
-	Control controller;
-    private JMenu mnSelectAlgorithm = new JMenu("Select Algorithm");
-    private HashMap<String, File> algosHash = new HashMap<>();
-    private JMenuItem noneItem = new JMenuItem("none");
-
-	/**
-	 * Constructor.
-	 * 
-	 * @param mod
-	 *            the Model
-	 * @param cont
-	 *            the Controller
-	 */
-    public AlgorithmMenu(Model mod, Control cont, GUI parentGui) {
-        super();
-		// Init Stuff
-		this.model = mod;
-		this.controller = cont;
-		this.setText("Algorithm");
-
-		// algoFolderButton Action
-		algoFolderButton.addActionListener(new ActionListener() {
-
-			@Override
-			public void actionPerformed(java.awt.event.ActionEvent evt) {
-				menuSetFolderActionPerformed(evt);
-			}
-
-			private void menuSetFolderActionPerformed(java.awt.event.ActionEvent evt) {
-				JFileChooser fileChooser = new JFileChooser();
-				fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
-				fileChooser.setAcceptAllFileFilterUsed(false);
-
-                if (fileChooser.showOpenDialog(parentGui.getFrmCyberPhysical()) == JFileChooser.APPROVE_OPTION) {
-                    // empty everything and reset the selected algorithm
-					controller.setAlgorithm(null);
-					mnSelectAlgorithm.removeAll();
-					mnSelectAlgorithm.add(noneItem);
-					noneItem.doClick();
-
-					File[] files = fileChooser.getSelectedFile().listFiles();
-					// Set Root Folder Path
-					root = new File(fileChooser.getCurrentDirectory().getPath());
-
-					for (int i = 0; i < files.length; i++) {
-						if (files[i].toString()
-								.endsWith(".java") /*
-													 * || files[i].toString().
-													 * endsWith(".class")
-													 */) {
-							String name = files[i].getName();
-							int tmpB = name.lastIndexOf('.');
-							name = name.substring(0, tmpB);
-							algosHash.put(name, files[i]);
-							JMenuItem tempItem = new JMenuItem(name);
-							tempItem.addActionListener(new ActionListener() {
-
-								@Override
-								public void actionPerformed(ActionEvent e) {
-									for (int i = 0; i < mnSelectAlgorithm.getItemCount(); i++) {
-										mnSelectAlgorithm.getItem(i).setForeground(null);
-									}
-									tempItem.setForeground(Color.BLUE);
-									setAlgorithm(algosHash.get(tempItem.getText()), tempItem.getText());
-								}
-							});
-							mnSelectAlgorithm.add(tempItem);
-						}
-					}
-
-				}
-			}
-
-		});
-
-		// Add to Panel
-		this.add(algoFolderButton);
-		this.add(mnSelectAlgorithm);
-		mnSelectAlgorithm.add(noneItem);
-		noneItem.setForeground(Color.BLUE);
-		noneItem.addActionListener(new ActionListener() {
-			@Override
-			public void actionPerformed(ActionEvent e) {
-				for (int i = 0; i < mnSelectAlgorithm.getItemCount(); i++) {
-					mnSelectAlgorithm.getItem(i).setForeground(null);
-				}
-				noneItem.setForeground(Color.BLUE);
-				controller.setAlgorithm(null);
-			}
-		});
-	}
-
-	public void setAlgorithm(File file, String name) {
-		boolean missingCompiler = false;
-		boolean instantiationError = false;
-		try {
-			BufferedReader br = new BufferedReader(new FileReader(file.getPath()));
-			String line = br.readLine();
-			// Package Name
-			String packageName = "";
-
-			while (line != null) {
-				line = line.trim();
-				if (!line.isEmpty()) {
-					if (line.length() >= 7 && line.substring(0, 7).equals("package")) {
-						packageName = line.substring(8, line.length() - 1);
-					}
-				}
-				if (packageName.isEmpty()) {
-					line = br.readLine();
-				} else {
-					line = null;
-				}
-
-			}
-
-			// Compile source file.
-			JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
-
-			if (ToolProvider.getSystemJavaCompiler() == null) {
-				missingCompiler = true;
-			}
-
-			compiler.run(null, null, null, file.getPath());
-
-			// Load and instantiate compiled class.
-			URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { root.toURI().toURL() });
-
-			instantiationError = true;
-			Class<?> cls;
-			if (packageName.isEmpty()) {
-				cls = Class.forName(name, true, classLoader);
-			} else {
-				cls = Class.forName(packageName + "." + name, true, classLoader);
-			}
-
-			Object t = cls.newInstance();
-			if (t instanceof CpsAlgorithm) {
-				controller.setAlgorithm(t);
-			} else {
-				JOptionPane.showMessageDialog(null, "Class does not implement CpsAlgorithm!", "Error!",
-						JOptionPane.ERROR_MESSAGE);
-				noneItem.doClick();
-			}
-		} catch (Exception e) {
-			if (missingCompiler) {
-				JOptionPane.showMessageDialog(null, "Missing Compiiler! Please install the JDK!", "Error!",
-						JOptionPane.ERROR_MESSAGE);
-			} else if (instantiationError) {
-				JOptionPane.showMessageDialog(null, "Class does not implement CpsAlgorithm!", "Error!",
-						JOptionPane.ERROR_MESSAGE);
-				noneItem.doClick();
-			} else {
-				JOptionPane.showMessageDialog(null, e.toString(), "Error!", JOptionPane.ERROR_MESSAGE);
-			}
-		}
-	}
-}

+ 27 - 158
src/ui/view/Console.java

@@ -1,158 +1,27 @@
-package ui.view;
-
-import java.awt.Color;
-import java.awt.Toolkit;
-import java.awt.datatransfer.StringSelection;
-import java.awt.event.ActionEvent;
-import java.awt.event.ActionListener;
-import java.awt.event.MouseAdapter;
-import java.awt.event.MouseEvent;
-import javax.swing.JScrollPane;
-
-import java.awt.BorderLayout;
-import javax.swing.JTextPane;
-import javax.swing.text.BadLocationException;
-import javax.swing.text.Style;
-import javax.swing.text.StyleConstants;
-import javax.swing.text.StyledDocument;
-import javax.swing.JMenuItem;
-import javax.swing.JPanel;
-import javax.swing.JPopupMenu;
-
-/**
- * A Console is a Pane where text can be Printed on.
- * 
- * @author Gruppe14
- * 
- */
-public class Console extends JScrollPane {
-
-	private static final long serialVersionUID = 1L;
-	private final JTextPane consoleText = new JTextPane();
-	private final JPanel panel = new JPanel();
-	private Style style;
-	private StyledDocument doc;
-
-	// PopUpMenu
-	private JPopupMenu popmenu = new JPopupMenu();
-	private JMenuItem itemCopy = new JMenuItem("Copy");
-	private JMenuItem itemClear = new JMenuItem("Clear Console");
-
-	/**
-	 * Constructor.
-	 */
-	public Console() {
-		super();
-		this.setBackground(Color.WHITE);
-		consoleText.setForeground(Color.BLACK);
-		consoleText.setEditable(false);
-
-		doc = consoleText.getStyledDocument();
-
-		style = consoleText.addStyle("I'm a Style", null);
-
-		this.setViewportView(panel);
-		panel.setLayout(new BorderLayout(0, 0));
-		panel.setBackground(Color.WHITE);
-		panel.add(consoleText);
-
-		setViewportView(panel);
-
-		// PopUpMenu
-		popmenu.add(itemCopy);
-		popmenu.add(itemClear);
-
-		itemCopy.addActionListener(new ActionListener() {
-			@Override
-			public void actionPerformed(ActionEvent e) {
-				Toolkit.getDefaultToolkit().getSystemClipboard()
-						.setContents(new StringSelection(consoleText.getSelectedText()), null);
-			}
-		});
-
-		itemClear.addActionListener(new ActionListener() {
-			@Override
-			public void actionPerformed(ActionEvent e) {
-				clearConsole();
-			}
-		});
-
-		// MouseListener
-		consoleText.addMouseListener(new MouseAdapter() {
-			@SuppressWarnings("static-access")
-			@Override
-			public void mouseReleased(MouseEvent e) {
-				if (e.getButton() == e.BUTTON3) {
-					itemClear.setEnabled(!consoleText.getText().isEmpty());
-					itemCopy.setEnabled(consoleText.getSelectedText() != null);
-					popmenu.show(e.getComponent(), e.getX(), e.getY());
-				}
-			}
-		});
-	}
-
-	/**
-	 * Print Text on the console.
-	 *
-	 * @param text
-	 *            String the Text
-	 * @param color
-	 *            the color of the Text
-	 * @param p
-	 *            size of the Text
-	 * @param bold
-	 *            bold or not
-	 * @param italic
-	 *            italic or not
-	 * @param nl
-	 *            new line or not
-	 * 
-	 */
-	public void addText(String text, Color color, int p, boolean bold, boolean italic, boolean nl) {
-		StyleConstants.setForeground(style, color);
-		StyleConstants.setFontSize(style, p);
-		StyleConstants.setBold(style, bold);
-		StyleConstants.setItalic(style, italic);
-
-		try {
-			doc.insertString(doc.getLength(), text, style);
-			if (nl) {
-				doc.insertString(doc.getLength(), "\n", style);
-			}
-		} catch (BadLocationException e) {
-		}
-	}
-
-	/**
-	 * Print Text on the console in black and font size 12.
-	 *
-	 * @param text
-	 *            String the Text
-	 */
-	public void addText(String text) {
-		StyleConstants.setForeground(style, Color.BLACK);
-		StyleConstants.setFontSize(style, 12);
-		StyleConstants.setBold(style, false);
-		StyleConstants.setItalic(style, false);
-
-		try {
-			doc.insertString(doc.getLength(), text + "\n", style);
-		} catch (BadLocationException e) {
-		}
-	}
-
-	/**
-	 * Clears the console.
-	 */
-	public void clearConsole() {
-		consoleText.setText("");
-	}
-	
-	/**
-	 * get the Console TextPane
-	 * @return 
-	 */
-	public JTextPane getConsoleText(){
-		return this.consoleText;
-	}
-}
+package ui.view;
+
+import javax.swing.JTextArea;
+import javax.swing.text.DefaultCaret;
+/**
+ * Little new swing object to print data to a console.
+ * @author tom
+ *
+ */
+public class Console extends JTextArea {
+	public Console() {
+		super();
+		this.setEditable(false);
+		DefaultCaret caret = (DefaultCaret)this.getCaret();
+		caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
+	}
+	public void clear() {
+		this.setText("");
+	}
+	public void print(String message) {
+		this.append(message);
+
+	}
+	public void println(String message) {
+		this.append(message  + "\n");
+	}
+}

+ 3 - 3
src/ui/view/CreateTemplatePopUp.java

@@ -210,7 +210,7 @@ public class CreateTemplatePopUp extends JDialog {
 		 */
 		for (HolonElement he : template.getElements())
 			listModel.addElement(he.getAmount() + " * " + he.getEleName()
-					+ ": " + he.getOverallEnergy() + "U");
+					+ ": " + he.getMaximumEnergy() + "U");
 
 		/**
 		 * Add ScrollPane to List
@@ -321,7 +321,7 @@ public class CreateTemplatePopUp extends JDialog {
 		HolonElement he = popUp.getElement();
 		if (he != null) {
 			listModel.addElement(he.getAmount() + " * " + he.getEleName()
-					+ ": " + he.getOverallEnergy() + "U");
+					+ ": " + he.getMaximumEnergy() + "U");
 			template.addElement(he);
 			he.setSaving(new Pair<>(category, textField_name.getText()));
 		}
@@ -354,7 +354,7 @@ public class CreateTemplatePopUp extends JDialog {
 		if (he != null) {
 			listModel.remove(index);
 			listModel.addElement(he.getAmount() + " * " + he.getEleName()
-					+ ": " + he.getOverallEnergy() + "U");
+					+ ": " + he.getMaximumEnergy() + "U");
 			template.deleteElement(index);
 			template.addElement(he);
 			he.setSaving(new Pair<>(category, textField_name.getText()));

+ 3 - 33
src/ui/view/EditEdgesPopUp.java

@@ -35,16 +35,7 @@ public class EditEdgesPopUp extends JDialog {
 	 * @param args
 	 *            standard
 	 */
-//	public static void main(String[] args) {
-//		try {
-//
-//			EditEdgesPopUp dialog = new EditEdgesPopUp();
-//			dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
-//			dialog.setVisible(true);
-//		} catch (Exception e) {
-//			e.printStackTrace();
-//		}
-//	}
+
 
 	/**
 	 * Constructor.
@@ -53,7 +44,7 @@ public class EditEdgesPopUp extends JDialog {
         super((java.awt.Frame) null, true);
 		setModalityType(java.awt.Dialog.ModalityType.APPLICATION_MODAL);
 		this.setTitle(Languages.getLanguage()[46]);
-		setBounds(100, 100, 600, 220);
+		setBounds(100, 100, 400, 220);
         setLocationRelativeTo(parentFrame);
         getContentPane().setLayout(new BorderLayout());
 		contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
@@ -95,21 +86,6 @@ public class EditEdgesPopUp extends JDialog {
 		JButton btnOk1 = new JButton("OK");
 		btnOk1.addActionListener(new ActionListener() {
 			public void actionPerformed(ActionEvent e) {
-				if (capacityField.getText().equals("infinite")) {
-					capacity = -1;
-					if (rdbtnChangeForAll.isSelected()) {
-						changeForExisting(capacity);
-						dispose();
-					} else if (rdbtnChangeForNew.isSelected()) {
-						changeForNew(capacity);
-						dispose();
-					} else if (rdbtnChangeForAll1.isSelected()) {
-						changeForExAndNew(capacity);
-						dispose();
-					} else {
-						JOptionPane.showMessageDialog(new JFrame(), Languages.getLanguage()[52]);
-					}
-				} else {
 					try {
 						capacity = Float.parseFloat(capacityField.getText().toString());
 						if (capacity < 0) {
@@ -130,7 +106,6 @@ public class EditEdgesPopUp extends JDialog {
 					} catch (NumberFormatException eex) {
 						JOptionPane.showMessageDialog(new JFrame(), Languages.getLanguage()[53]);
 					}
-				}
 			}
 		});
 		btnOk1.setBounds(186, 147, 89, 23);
@@ -140,10 +115,6 @@ public class EditEdgesPopUp extends JDialog {
 		bG.add(rdbtnChangeForAll1);
 		bG.add(rdbtnChangeForNew);
 		bG.add(rdbtnChangeForAll);
-
-		lblenterinfiniteFor = new JLabel(Languages.getLanguage()[55]);
-		lblenterinfiniteFor.setBounds(237, 11, 360, 14);
-		contentPanel.add(lblenterinfiniteFor);
 	}
 
 	/**
@@ -192,7 +163,6 @@ public class EditEdgesPopUp extends JDialog {
 		 */
 		for (CpsEdge edge : controller.getModel().getEdgesOnCanvas()) {
 			edge.setCapacity(cap);
-            edge.setWorkingState(true);
         }
         for (AbstractCpsObject abs : controller.getModel().getObjectsOnCanvas()) {
 			if (abs instanceof CpsUpperNode) {
@@ -200,7 +170,7 @@ public class EditEdgesPopUp extends JDialog {
 			}
 		}
 		controller.resetSimulation();
-		controller.calculateStateForCurrentTimeStep();
+		controller.calculateStateAndVisualForCurrentTimeStep();
 		canvas.repaint();
 	}
 

+ 4 - 5
src/ui/view/FlexiblePane.java

@@ -59,10 +59,9 @@ public class FlexiblePane extends JScrollPane implements ObjectListener {
 			float subCons = 0;
 			Color subColor = netColors.get(colorCounter);
 			for(HolonObject hl: sn.getObjects()){
-				subProd += hl.getFlexProd();
-				subCons += hl.getFlexCons();
+				
 				FlexibleData tmp = new FlexibleData(hl.getName()+" "+hl.getId(),
-						hl.getFlexProd(), hl.getFlexCons(), gridProd, gridCons);
+						666.f, 666.f, gridProd, gridCons);
 				tmp.getColorPanel().setBackground(subColor);
 				objects.add(tmp);
 			}
@@ -92,8 +91,8 @@ public class FlexiblePane extends JScrollPane implements ObjectListener {
 		if(sn != null){
 			for(SubNet s: sn){
 				for(HolonObject h: s.getObjects()){
-					prod += h.getFlexProd();
-					cons += h.getFlexCons();
+					prod += 666.f;
+					cons += 666.f;
 				}
 			}
 			result.add(prod);

+ 128 - 119
src/ui/view/GUI.java

@@ -15,7 +15,9 @@ import org.apache.commons.compress.archivers.ArchiveException;
 import ui.controller.Control;
 import ui.controller.SimulationManager;
 import ui.controller.UpdateController;
+import ui.model.DecoratedState;
 import ui.model.Model;
+import ui.model.Model.FairnessModel;
 import ui.view.NewPopUp.Option;
 
 import javax.swing.*;
@@ -41,7 +43,10 @@ import java.io.IOException;
 import java.net.URI;
 import java.net.URISyntaxException;
 import java.util.ArrayList;
+import java.util.Collections;
 import java.util.List;
+import java.util.ListIterator;
+import java.util.Objects;
 import java.util.Timer;
 import java.util.TimerTask;
 import java.util.stream.Collectors;
@@ -59,12 +64,11 @@ public class GUI implements CategoryListener {
 	 * Menu on the Top containing File, Edit View Help etc
 	 */
 	private final JMenuBar menuBar = new JMenuBar();
-	
 	private final JMenu mnNewMenu = new JMenu("File");
 	private final JMenu mnNewMenuEdit = new JMenu("Edit");
 	private final JMenu mnNewMenuOptions = new JMenu("Options");
 	private final JMenu mnNewMenuView = new JMenu("View");
-	private final AlgorithmMenu algorithmMenu;
+	private final JMenu menuWindow = new JMenu("Window");
 	
 	/** Help Menu containing helpful Informations and the AboutUs Popup */
 	private final JMenu mnHelp = new JMenu("Help");
@@ -116,8 +120,6 @@ public class GUI implements CategoryListener {
 	private final JMenuItem mntmSplitView = new JMenuItem("Split View");
 	private final JSplitPane splitPane = new JSplitPane();
 	private final JSplitPane splitPane1 = new JSplitPane();
-	private final JSplitPane splitPaneCanvasConsole = new JSplitPane(
-			JSplitPane.VERTICAL_SPLIT);
 	// the tabbed canvas containing the different sub-net tabs of the grid (Main
 	// Grid + Nodes of Nodes)
 	
@@ -232,7 +234,6 @@ public class GUI implements CategoryListener {
 	private final JMenuItem germanBtn = new JMenuItem("DE");
 	private final JMenuItem czechBtn = new JMenuItem("CZ");
 	private final JMenuItem chineseBtn = new JMenuItem("ZH");
-	private final Console console = new Console();
 	private final MyCanvas canvas;
 	private final HolonCanvas holonCanvas;
 	private final UnitGraph unitGraph;
@@ -302,6 +303,8 @@ public class GUI implements CategoryListener {
 	private String eraseCategory = "Do you really want to delete the Category ";
 	private String selectObjBeforeErase = "Please select a Category or an Object in the left library in order to delete something.";
 
+	
+	private List<Outliner> outlinerList = new ArrayList<Outliner>();
 	/**
 	 * Create the application.
 	 *
@@ -311,6 +314,7 @@ public class GUI implements CategoryListener {
 	GUI(Control control) {
 		this.controller = control;
 		this.model = control.getModel();
+		control.setGui(this);
 		statSplitPane = new StatisticPanel(controller);
 		model.addGraphListener(statSplitPane);
 		model.setStatPanel(statSplitPane);
@@ -320,10 +324,7 @@ public class GUI implements CategoryListener {
 		this.holonCanvas = new HolonCanvas(model, control);
 
 		control.initListener(this);
-		controller.setCanvas(canvas);
-		model.setConsole(console);
 		model.setTableProperties(tableProperties);
-		algorithmMenu = new AlgorithmMenu(model, control, this);
 		initialize();
 		updateCategories(model.getCategories());
 		updCon = new UpdateController(model, controller);
@@ -360,7 +361,7 @@ public class GUI implements CategoryListener {
 			public void windowClosing(java.awt.event.WindowEvent windowEvent) {
 				if (JOptionPane.showConfirmDialog(frmCyberPhysical,
 						Languages.getLanguage()[88],
-						"Cyber Physical Systems Model",
+						"HOLEG",
 						JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) {
 					controller.deleteDirectory(new File(System
 							.getProperty("user.home")
@@ -401,7 +402,7 @@ public class GUI implements CategoryListener {
 					controller.loadAutoSave(controller.getUndoSave());
 					closeInvalidUpperNodeTabs();
 					
-					controller.calculateStateForCurrentTimeStep();
+					controller.calculateStateAndVisualForCurrentTimeStep();
 					canvas.repaint();
 					unitGraph.update(model.getObjectsOnCanvas());
 					updateUpperNodes();
@@ -424,7 +425,7 @@ public class GUI implements CategoryListener {
 
 					closeInvalidUpperNodeTabs();
 					
-					controller.calculateStateForCurrentTimeStep();
+					controller.calculateStateAndVisualForCurrentTimeStep();
 					canvas.repaint();
 					unitGraph.update(model.getObjectsOnCanvas());
 					updateUpperNodes();
@@ -487,16 +488,12 @@ public class GUI implements CategoryListener {
 
 				// check whether a producer was deleted (this triggers a
 				// complete re-evaluation of the net)
-				boolean wasProducerDeleted = false;
+				boolean wasProducerDeleted = true;
 
 				if (canvasOrUpperNodeCanvas instanceof UpperNodeCanvas) {
 					UpperNodeCanvas uNC = (UpperNodeCanvas) canvasOrUpperNodeCanvas;
 					for (AbstractCpsObject cps : model.getSelectedCpsObjects()) {
 
-						if (cps instanceof HolonObject
-								&& ((HolonObject) cps).getState() == HolonObject.PRODUCER) {
-							wasProducerDeleted = true;
-						}
 
 						controller.removeTrackingObj(cps);
 						if (uNC.upperNode.getNodes().contains(cps)) {
@@ -541,10 +538,7 @@ public class GUI implements CategoryListener {
 						AbstractCpsObject cps = model.getSelectedCpsObjects()
 								.get(j);
 
-						if (cps instanceof HolonObject
-								&& ((HolonObject) cps).getState() == HolonObject.PRODUCER) {
-							wasProducerDeleted = true;
-						}
+					
 
 						controller.removeTrackingObj(cps);
 						if (j < model.getSelectedCpsObjects().size() - 1)
@@ -561,7 +555,7 @@ public class GUI implements CategoryListener {
 				// recalculate net if a producer was deleted
 				if (wasProducerDeleted) {
 					controller.resetSimulation();
-					controller.calculateStateForCurrentTimeStep();
+					controller.calculateStateAndVisualForCurrentTimeStep();
 				}
 
 				model.getSelectedCpsObjects().clear();
@@ -638,12 +632,12 @@ public class GUI implements CategoryListener {
 										canvasOrUpperNodeCanvas
 												.getMousePosition());
 						unitGraph.update(model.getSelectedCpsObjects());
-						controller.calculateStateForCurrentTimeStep();
+						controller.calculateStateAndVisualForCurrentTimeStep();
 						scrollPane.getViewport().getComponent(0).repaint();
 					} else {
 						controller.paste(null, canvas.getMousePosition());
 						unitGraph.update(model.getSelectedCpsObjects());
-						controller.calculateStateForCurrentTimeStep();
+						controller.calculateStateAndVisualForCurrentTimeStep();
 						canvas.repaint();
 					}
 				} catch (HeadlessException | JsonParseException
@@ -672,11 +666,11 @@ public class GUI implements CategoryListener {
 					if (scrollPane.getViewport().getComponent(0) instanceof UpperNodeCanvas) {
 						controller.cut(((UpperNodeCanvas) scrollPane
 								.getViewport().getComponent(0)).upperNode);
-						controller.calculateStateForCurrentTimeStep();
+						controller.calculateStateAndVisualForCurrentTimeStep();
 						scrollPane.getViewport().getComponent(0).repaint();
 					} else {
 						controller.cut(null);
-						controller.calculateStateForCurrentTimeStep();
+						controller.calculateStateAndVisualForCurrentTimeStep();
 						canvas.repaint();
 					}
 					if (!model.getClipboradObjects().isEmpty()) {
@@ -789,14 +783,12 @@ public class GUI implements CategoryListener {
 				}
 				controller.resetCategorys();
 			} catch (Exception e2) {
+				System.out.println(e2.getMessage());
 			}
 
 			tree.repaint();
 		});
-		mnNewMenuOptions.add(consoleLogCheckBox);
-		consoleLogCheckBox.setSelected(true);
-		consoleLogCheckBox.addActionListener(arg0 -> controller
-				.setShowConsoleLog(consoleLogCheckBox.isSelected()));
+
 
 		mnNewMenuOptions.add(useFlexibleDevicesCheckBox);
 		useFlexibleDevicesCheckBox.setSelected(true);
@@ -818,12 +810,11 @@ public class GUI implements CategoryListener {
 
 		mntmFairMinFirst
 				.addActionListener(arg0 -> {
-					controller
-							.setFairnessModel(SimulationManager.fairnessMininumDemandFirst);
+					controller.setFairnessModel(FairnessModel.MininumDemandFirst);
 					mntmFairMinFirst.setForeground(Color.BLUE);
 					mntmFairAlleEqual.setForeground(mnFairnessModel
 							.getForeground());
-					controller.calculateStateForCurrentTimeStep();
+					controller.calculateStateAndVisualForCurrentTimeStep();
 					// Update UpperNodes
 					Component canvasOrUpperNodeCanvas = getScrollPaneFromTabbedPane()
 							.getViewport().getComponent(0);
@@ -838,10 +829,10 @@ public class GUI implements CategoryListener {
 				.setToolTipText("HolonObjects will all get the same amount of energy.");
 
 		mntmFairAlleEqual.addActionListener(arg0 -> {
-			controller.setFairnessModel(SimulationManager.fairnessAllEqual);
+			controller.setFairnessModel(FairnessModel.AllEqual);
 			mntmFairAlleEqual.setForeground(Color.BLUE);
 			mntmFairMinFirst.setForeground(mnFairnessModel.getForeground());
-			controller.calculateStateForCurrentTimeStep();
+			controller.calculateStateAndVisualForCurrentTimeStep();
 			// Update UpperNodes
 				Component canvasOrUpperNodeCanvas = getScrollPaneFromTabbedPane()
 						.getViewport().getComponent(0);
@@ -860,7 +851,7 @@ public class GUI implements CategoryListener {
 					frmCyberPhysical);
 			popUp.setVisible(true);
 		});
-
+		
 		mnNewMenuView.add(splitPane3);
 
 		sizeSlider.setMinimum(15);
@@ -913,49 +904,41 @@ public class GUI implements CategoryListener {
 		showTooltipsCheckBox.addActionListener(arg0 -> {
 			showHint(showTooltipsCheckBox.isSelected());
 			});
-		
-
+		initWindowMenu();
 		// Split View
 		mntmSplitView
 				.addActionListener(actionEvent -> {
-					if (splitPaneCanvasConsole.getLeftComponent() instanceof JSplitPane) {
-						initSplit = true;
-						Component tempC = tabbedPaneSplit
-								.getSelectedComponent();
-						tabbedPaneOriginal.setComponentAt(
-								tabbedPaneSplit.getSelectedIndex(), tempC);
-						tabbedPaneSplit.removeAll();
-						splitPaneCanvasConsole
-								.setLeftComponent(tabbedPaneOriginal);
+					for (int i = 0; i < tabbedPaneOriginal.getTabCount(); i++) {
+						// add outer tabs
+						// (inner tabs are added by tabbedPaneSplit
+						// changelistener)
+						tabbedPaneSplit.addTab(
+								tabbedPaneOriginal.getTitleAt(i), null);
+					}
+					if (tabbedPaneOriginal.getSelectedComponent() == statScrollPane) {
+						tabbedPaneOriginal.setComponentAt(0, null);
+						tabbedPaneSplit.setComponentAt(0, canvasSP);
+						tabbedPaneSplit.setSelectedIndex(0);
 					} else {
-						for (int i = 0; i < tabbedPaneOriginal.getTabCount(); i++) {
-							// add outer tabs
-							// (inner tabs are added by tabbedPaneSplit
-							// changelistener)
-							tabbedPaneSplit.addTab(
-									tabbedPaneOriginal.getTitleAt(i), null);
-						}
-						if (tabbedPaneOriginal.getSelectedComponent() == statScrollPane) {
-							tabbedPaneOriginal.setComponentAt(0, null);
-							tabbedPaneSplit.setComponentAt(0, canvasSP);
-							tabbedPaneSplit.setSelectedIndex(0);
-						} else {
-							tabbedPaneOriginal.setComponentAt(1, null);
-							tabbedPaneSplit.setComponentAt(1, statScrollPane);
-							tabbedPaneSplit.setSelectedIndex(1);
-						}
-						tempSplit = new JSplitPane();
-						tempSplit.setBorder(null);
-						tempSplit.setRightComponent(tabbedPaneSplit);
-						tempSplit.setLeftComponent(tabbedPaneOriginal);
-						tempSplit.setDividerLocation(tabbedPaneOriginal
-								.getWidth() / 2);
-						tempSplit.setResizeWeight(0.9);
-						splitPaneCanvasConsole.setLeftComponent(tempSplit);
-						initSplit = false;
+						tabbedPaneOriginal.setComponentAt(1, null);
+						tabbedPaneSplit.setComponentAt(1, statScrollPane);
+						tabbedPaneSplit.setSelectedIndex(1);
 					}
+					tempSplit = new JSplitPane();
+					tempSplit.setBorder(null);
+					tempSplit.setRightComponent(tabbedPaneSplit);
+					tempSplit.setLeftComponent(tabbedPaneOriginal);
+					tempSplit.setDividerLocation(tabbedPaneOriginal
+							.getWidth() / 2);
+					tempSplit.setResizeWeight(0.9);
+					initSplit = false;
+				
 					contentPane.updateUI();
 				});
+		
+		
+		
+		
 		mnNewMenuView.add(mntmBackground);
 
 		mntmBackground
@@ -1001,7 +984,6 @@ public class GUI implements CategoryListener {
 
 		splitPane_1.setLeftComponent(lblHolonBodySize);
 
-		menuBar.add(algorithmMenu);
 
 		/**
 		 * add Help Menu and its items
@@ -1221,7 +1203,7 @@ public class GUI implements CategoryListener {
 								ele.getAmount(), ele.getEnergyPerElement(),
 								ele.getId());
 					}
-					controller.calculateStateForTimeStep(model
+					controller.calculateStateAndVisualForTimeStep(model
 							.getCurIteration());
 					triggerUpdateController(null);
 					contentPane.updateUI();
@@ -1247,7 +1229,7 @@ public class GUI implements CategoryListener {
 						for (HolonElement e : selectedElements) {
 							controller.deleteElementCanvas(obj.getId(),
 									e.getId());
-							controller.calculateStateForTimeStep(model
+							controller.calculateStateAndVisualForTimeStep(model
 									.getCurIteration());
 							triggerUpdateController(null);
 							contentPane.updateUI();
@@ -1417,7 +1399,7 @@ public class GUI implements CategoryListener {
 													selectedValueBX).toString();
 									Boolean bTemp = Boolean
 											.parseBoolean(newBStuff);
-									eleBTemp.setFlexible(bTemp);
+									//TODO: delete here more
 								} else {
 									// Update of HolonElement
 									HolonElement eleTemp = updCon
@@ -1441,7 +1423,7 @@ public class GUI implements CategoryListener {
 									else if (selectedValueX == 4) {
 										Float ftemp = Float
 												.parseFloat(newStuff);
-										eleTemp.setFlexibleEnergyAvailable(ftemp);
+										//TODO and here
 									}
 									// Amount of Elements update
 									else if (selectedValueX == 5) {
@@ -1491,7 +1473,7 @@ public class GUI implements CategoryListener {
 													selectedValueBX).toString();
 									Boolean bTemp = Boolean
 											.parseBoolean(newBStuff);
-									eleTemp.setFlexible(bTemp);
+									//TODO: delete Boolean bTemp = Boolean.parseBoolean(newBStuff);
 
 								} else {
 									// Update of HolonElement
@@ -1514,16 +1496,13 @@ public class GUI implements CategoryListener {
 									else if (selectedValueX == 3) {
 										Float ftemp = Float
 												.parseFloat(newStuff);
-										eleTemp.setFlexibleEnergyAvailable(ftemp);
+										//TODO ---
 
 										// if this is a flexible device and the
 										// flexibly available energy was
 										// changed,
 										// set used energy to 0, so that it can
 										// be computed anew
-										if (eleTemp.isFlexible()) {
-											eleTemp.setEnergyPerElement(0);
-										}
 									}
 									// Amount of Elements update
 									else if (selectedValueX == 4) {
@@ -1538,7 +1517,7 @@ public class GUI implements CategoryListener {
 										selectedValueBY);
 							}
 						}
-						controller.calculateStateForTimeStep(model
+						controller.calculateStateAndVisualForTimeStep(model
 								.getCurIteration());
 						model.getSingleTable().fireTableDataChanged();
 						triggerUpdateController(null);
@@ -1667,7 +1646,6 @@ public class GUI implements CategoryListener {
 				// Status edition through a check box
 				if (selValueYBool == 3) {
 					Boolean bbTemp = Boolean.parseBoolean(btemp.toString());
-					model.getSelectedEdge().setWorkingState(bbTemp);
 				}
 			}
 			canvas.repaint();
@@ -1838,14 +1816,12 @@ public class GUI implements CategoryListener {
 				try {
 					if (dragging) {
 						chooseTabTemp();
-
 						JScrollPane scrollPane = getScrollPaneFromTabbedPane();
 						Component canvasOrUpperNodeCanvas = scrollPane
 								.getViewport().getComponent(0);
 
 						if (canvasOrUpperNodeCanvas instanceof UpperNodeCanvas) {
 							UpperNodeCanvas unc = (UpperNodeCanvas) canvasOrUpperNodeCanvas;
-
 							int x = (int) unc.getMousePosition().getX() + 16;
 							int y = (int) unc.getMousePosition().getY() + 16;
 
@@ -1858,9 +1834,6 @@ public class GUI implements CategoryListener {
 								if (tempCps instanceof HolonSwitch) {
 									h = new HolonSwitch(tempCps);
 								}
-								if (tempCps instanceof HolonTransformer) {
-									h = new HolonTransformer(tempCps);
-								}
 								if (tempCps instanceof HolonBattery)
 								{
 									h = new HolonBattery(tempCps);
@@ -1880,6 +1853,7 @@ public class GUI implements CategoryListener {
 								 */
 								unc.mayBeReplaced = null; 
 								unc.invalidate();
+								controller.calculateStateAndVisualForCurrentTimeStep();
 								unc.repaint();
 								unc.setXY((int) canvas.getMousePosition()
 										.getX(), (int) canvas
@@ -1911,7 +1885,6 @@ public class GUI implements CategoryListener {
 							if(canvas.mayBeReplaced!=null &&canvas.mayBeReplaced instanceof CpsUpperNode){
 								canvas.closeUpperNodeTab(canvas.mayBeReplaced.getId());
 							}
-							
 							controller.addObjectCanvas(h);
 							/**
 							 * no object should get replaced
@@ -1923,7 +1896,7 @@ public class GUI implements CategoryListener {
 									(int) canvas.getMousePosition().getY());
 							canvas.repaint();
 						}
-						controller.calculateStateForCurrentTimeStep();
+						controller.calculateStateAndVisualForCurrentTimeStep();
 						contentPane.updateUI();
 						dragging = false;
 					}
@@ -2371,7 +2344,7 @@ public class GUI implements CategoryListener {
 					
 					closeInvalidUpperNodeTabs();
 					
-					controller.calculateStateForCurrentTimeStep();
+					controller.calculateStateAndVisualForCurrentTimeStep();
 					canvas.repaint();
 
 					repaintGraphAfterUndoRedo();
@@ -2394,7 +2367,7 @@ public class GUI implements CategoryListener {
 					
 					closeInvalidUpperNodeTabs();
 					
-					controller.calculateStateForCurrentTimeStep();
+					controller.calculateStateAndVisualForCurrentTimeStep();
 					canvas.repaint();
 
 					repaintGraphAfterUndoRedo();
@@ -2407,15 +2380,10 @@ public class GUI implements CategoryListener {
 
 		timePanel = new TimePanel(this,controller);
 		timePanel.setBorder(null);
-		((JSlider)
-				(
-						((Container)timePanel.getComponent(1))//timePanel
-						.getComponent(1)//timeSlider
-				)
-		)//TODO: This hardcoded stuff
+		timePanel.getTimeSlider()
 				.addChangeListener(changeEvent -> {
-					int i = model.getCurIteration();
-					controller.calculateStateForTimeStep(i);
+					//TimeSliderChanged event
+					controller.calculateStateAndVisualForTimeStep(timePanel.getTimeSlider().getValue());
 					unitGraph.repaint();
 					if (model.getIsSimRunning()) {
 						controller.runAlgorithm(model, controller);
@@ -2427,11 +2395,8 @@ public class GUI implements CategoryListener {
 		splitPane.setRightComponent(splitPane1);
 		splitPane.setDividerLocation(200);
 		splitPane1.setDividerLocation(500);
-		splitPaneCanvasConsole.setDividerLocation(550);
-		splitPaneCanvasConsole.setResizeWeight(0.9);
 
 		splitPane.setLeftComponent(scrollPane1);
-		splitPaneCanvasConsole.setLeftComponent(tabbedPaneOriginal);
 		tabbedPaneOriginal.addTab("View", tabbedPaneInnerOriginal);
 		
 		
@@ -2448,9 +2413,7 @@ public class GUI implements CategoryListener {
 		controller.setFlexiblePane(flexPane);
 		controller.getModel().getObjectListeners().add(flexPane);
 		tabbedPaneOriginal.addTab("Flexibility", flexPane);
-
-		splitPaneCanvasConsole.setRightComponent(console);
-		splitPane1.setLeftComponent(splitPaneCanvasConsole);
+		splitPane1.setLeftComponent(tabbedPaneOriginal);
 		splitPane1.setRightComponent(splitHolonElPro);
 
 		splitPane1.setResizeWeight(0.9);
@@ -2465,7 +2428,6 @@ public class GUI implements CategoryListener {
 		splitGraphHolonEl.setTopComponent(scrollElements);
 		splitGraphHolonEl.setBottomComponent(scrollGraph);
 		canvasSP.setViewportView(canvas);
-		algorithmMenu.setBackground(new Color(240, 240, 240));
 
 		tabbedPaneOriginal.setBorder(null);
 		scrollProperties.setBorder(null);
@@ -2473,7 +2435,6 @@ public class GUI implements CategoryListener {
 		scrollElements.setBorder(null);
 		splitPane.setBorder(null);
 		splitPane1.setBorder(null);
-		splitPaneCanvasConsole.setBorder(null);
 		splitHolonElPro.setBorder(null);
 		splitGraphHolonEl.setBorder(null);
 		panelHolonEl.setBorder(null);
@@ -2483,10 +2444,7 @@ public class GUI implements CategoryListener {
 
 		frmCyberPhysical.getContentPane().add(timePanel, BorderLayout.SOUTH);
 
-		MouseAdapter focusCanvasAdapter = new FocusCanvasMouseAdapter();
-		model.getTableHolonElement().addMouseListener(focusCanvasAdapter);
-		tableProperties.addMouseListener(focusCanvasAdapter);
-		console.getConsoleText().addMouseListener(focusCanvasAdapter);
+
 
 		try {
 			controller.loadAutoSave(System.getProperty("user.home")
@@ -2535,6 +2493,38 @@ public class GUI implements CategoryListener {
 		});
 	}
 
+	private void initWindowMenu() {
+		menuBar.add(menuWindow);
+		//Algo
+		JMenuItem openMenu =  new JMenuItem("Open Algorithm Panel", new ImageIcon(Util.loadImage("/Button_Images/iconAlgo.png").getScaledInstance(20, 20, java.awt.Image.SCALE_SMOOTH)));
+		openMenu.addActionListener(actionEvent -> {
+			new AlgoWindow(frmCyberPhysical, controller);
+		});
+		openMenu.setAccelerator(KeyStroke.getKeyStroke('N', Toolkit.getDefaultToolkit ().getMenuShortcutKeyMask()));
+		menuWindow.add(openMenu);
+		//Outliner
+		JMenuItem openOutliner =  new JMenuItem("Open Outliner", new ImageIcon(Util.loadImage("/Button_Images/iconOutliner.png").getScaledInstance(20, 20, java.awt.Image.SCALE_SMOOTH)));
+		openOutliner.addActionListener(actionEvent -> {
+			outlinerList.add(new Outliner(frmCyberPhysical, model, controller));
+		});
+		openOutliner.setAccelerator(KeyStroke.getKeyStroke('O', Toolkit.getDefaultToolkit ().getMenuShortcutKeyMask()));
+		menuWindow.add(openOutliner);
+	}
+
+
+	public void updateOutliners(DecoratedState state)
+	{
+		//remove closed Outliner
+		ListIterator<Outliner> iter = outlinerList.listIterator();
+		while(iter.hasNext())
+		{
+			if(iter.next().isClosed) iter.remove();
+		}
+		//update open Outliner
+		for(Outliner out : outlinerList) {
+			out.repaintWithDecoratedState(state);
+		}
+	}
 	private void showScrollGraph() {
 		scrollGraph.setVisible(true);
 		splitGraphHolonEl.setBottomComponent(scrollGraph);
@@ -2722,8 +2712,6 @@ public class GUI implements CategoryListener {
 		saveBeforeNew = tempArray[28];
 		eraseCategory = tempArray[29];
 		selectObjBeforeErase = tempArray[30];
-		// SimMenu
-		algorithmMenu.algoFolderButton.setText(Languages.getLanguage()[85]);
 		// TimePanel
 		timePanel.playBtn.setToolTipText(Languages.getLanguage()[89]);
 		timePanel.timeResetBtn.setToolTipText(Languages.getLanguage()[90]);
@@ -2765,12 +2753,12 @@ public class GUI implements CategoryListener {
 		JScrollPane scrollPane = getScrollPaneFromTabbedPane();
 		if (scrollPane.getViewport().getComponent(0) instanceof MyCanvas) {
 			unc = new UpperNodeCanvas(model, controller, unitGraph,
-					(CpsUpperNode) temp, "");
+					(CpsUpperNode) temp, "", scrollPane.getViewport().getComponent(0));
 
 		} else {
 			unc = new UpperNodeCanvas(model, controller, unitGraph,
 					(CpsUpperNode) temp, ((UpperNodeCanvas) scrollPane
-							.getViewport().getComponent(0)).path + " -> ");
+							.getViewport().getComponent(0)).path + " -> ", scrollPane.getViewport().getComponent(0));
 		}
 		unc.setShowedInformation(canvas.getShowedInformation());
 
@@ -3034,20 +3022,20 @@ public class GUI implements CategoryListener {
 	 */
 	private void updateElementTableAfterChange(HolonElement eleBTemp,
 			int selectedValueBY) {
-		model.getSingleTable().setValueAt(eleBTemp.isFlexible(),
+		model.getSingleTable().setValueAt(false,
 				selectedValueBY, 6);
 		model.getSingleTable().setValueAt(eleBTemp.isActive(), selectedValueBY,
 				5);
 		model.getSingleTable().setValueAt(eleBTemp.getAmount(),
 				selectedValueBY, 4);
 		model.getSingleTable().setValueAt(
-				eleBTemp.getFlexibleEnergyAvailablePerElement(),
+				666.f,
 				selectedValueBY, 3);
 		model.getSingleTable().setValueAt(eleBTemp.getEnergyPerElement(),
 				selectedValueBY, 2);
 	}
 
-	private void triggerUpdateController(AbstractCpsObject temp) {
+	public void triggerUpdateController(AbstractCpsObject temp) {
 		if (temp != null) {
 			updCon.paintProperties(temp);
 		}
@@ -3156,4 +3144,25 @@ public class GUI implements CategoryListener {
 			}
 		}
 	}
+	
+	public void repaintCanvas() {
+		tabbedPaneInnerOriginal.repaint();
+	}
+	
+	/**
+	 * Class should be reworked as soon as possible!
+	 * @param state
+	 */
+	public void guiDisable(boolean state) {
+		canvas.disabled = state;
+		for (int i = 1; i < tabbedPaneInnerOriginal.getTabCount(); i++) {
+			JScrollPane scrollPaneOriginal = (JScrollPane) tabbedPaneInnerOriginal
+					.getComponentAt(i);
+			if (((UpperNodeCanvas) scrollPaneOriginal.getViewport()
+					.getComponent(0)).upperNode != null) {
+				((UpperNodeCanvas) scrollPaneOriginal.getViewport()
+						.getComponent(0)).disable = state;
+			}
+		}
+	}
 }

+ 341 - 171
src/ui/view/MyCanvas.java

@@ -6,19 +6,38 @@ import com.google.gson.JsonParseException;
 
 import ui.controller.Control;
 import ui.controller.UpdateController;
+import ui.model.IntermediateCableWithState;
+import ui.model.Consumer;
+import ui.model.DecoratedCable;
+import ui.model.DecoratedGroupNode;
+import ui.model.DecoratedHolonObject;
+import ui.model.DecoratedHolonObject.HolonObjectState;
+import ui.model.DecoratedNetwork;
+import ui.model.DecoratedSwitch;
+import ui.model.DecoratedSwitch.SwitchState;
 import ui.model.Model;
+import ui.model.Passiv;
+import ui.model.Supplier;
+import ui.model.VisualRepresentationalState;
 
 import javax.swing.*;
 
 import java.awt.*;
 import java.awt.datatransfer.UnsupportedFlavorException;
+import java.awt.event.ActionEvent;
+import java.awt.event.KeyEvent;
+import java.awt.event.KeyListener;
 import java.awt.event.MouseEvent;
 import java.awt.event.MouseListener;
 import java.awt.event.MouseMotionListener;
 import java.awt.font.LineMetrics;
 import java.awt.geom.Line2D;
+import java.awt.image.BufferedImage;
 import java.io.IOException;
 import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.stream.Collectors;
 
 /**
  * This Class is the Canvas. All Objects will be visualized here
@@ -29,7 +48,7 @@ public class MyCanvas extends AbstractCanvas implements MouseListener,
 		MouseMotionListener {
 
 	private static final long serialVersionUID = 1L;
-
+	public boolean disabled = false;
 	/**
 	 * Constructor.
 	 *
@@ -43,14 +62,14 @@ public class MyCanvas extends AbstractCanvas implements MouseListener,
 		toolTip = false;
 		this.controller = control;
 		this.model = mod;
+		
 		scalediv20 = model.getScale() / 20;
-
+		
 		showedInformation[0] = true;
 		showedInformation[1] = true;
 		showedInformation[3] = false;
 		showedInformation[4] = true;
 		control.setMaxCapacity(10000);
-
 		popmenu.add(itemCut);
 		popmenu.add(itemCopy);
 		popmenu.add(itemPaste);
@@ -116,9 +135,10 @@ public class MyCanvas extends AbstractCanvas implements MouseListener,
 							animCps.get(i).getPosition().x = savePos.get(i).x;
 							animCps.get(i).getPosition().y = savePos.get(i).y;
 						}
-						controller.addUpperNode("NodeOfNode", null, animCps);
-						controller.calculateStateForCurrentTimeStep();
+						controller.addUpperNode("GroupNode", null, animCps);
+						controller.calculateStateAndVisualForCurrentTimeStep();
 						triggerUpdateController();
+						model.getSelectedCpsObjects().clear();
 						repaint();
 					}
 				});
@@ -151,6 +171,7 @@ public class MyCanvas extends AbstractCanvas implements MouseListener,
 					animT = new javax.swing.Timer(
 							animDelay,
 							actionEvent1 -> {
+								model.getSelectedCpsObjects().clear();
 								if (animDuration - animDelay >= 0) {
 									for (int i = 0; i < animCps.size(); i++) {
 										Position pos = animCps.get(i).getPosition();
@@ -172,9 +193,7 @@ public class MyCanvas extends AbstractCanvas implements MouseListener,
 										animCps.get(i).getPosition().y = savePos
 												.get(i).y;
 									}
-
-									controller
-											.calculateStateForCurrentTimeStep();
+									controller.calculateStateAndVisualForCurrentTimeStep();
 									triggerUpdateController();
 									repaint();
 								}
@@ -191,16 +210,6 @@ public class MyCanvas extends AbstractCanvas implements MouseListener,
 						((HolonObject) o).updateTrackingInfo();
 					}
 				}
-				if (model.getShowConsoleLog()) {
-					controller.addTextToConsole("Tracking: ", Color.BLACK, 12,
-							false, false, false);
-					controller.addTextToConsole("" + o.getName(), Color.BLUE,
-							12, true, false, false);
-					controller.addTextToConsole(", ID:", Color.BLACK, 12,
-							false, false, false);
-					controller.addTextToConsole("" + o.getId(), Color.RED, 12,
-							true, false, true);
-				}
 			}
 		});
 
@@ -225,16 +234,6 @@ public class MyCanvas extends AbstractCanvas implements MouseListener,
 				((HolonObject) o).setTrackingProd(new float[100]);
 				((HolonObject) o).setTrackingCons(new float[100]);
 			}
-			if (model.getShowConsoleLog()) {
-				controller.addTextToConsole("Untracking: ", Color.BLACK, 12,
-						false, false, false);
-				controller.addTextToConsole("" + o.getName(), Color.BLUE, 12,
-						true, false, false);
-				controller.addTextToConsole(", ID:", Color.BLACK, 12, false,
-						false, false);
-				controller.addTextToConsole("" + o.getId(), Color.RED, 12,
-						true, false, true);
-			}
 		}
 	}
 })		;
@@ -364,166 +363,307 @@ public class MyCanvas extends AbstractCanvas implements MouseListener,
 	 * @param g
 	 *            Graphics
 	 */
-	public void paintComponent(Graphics g) {
-		String maxCap = null;
-		super.paintComponent(g);
-		// Rendering
-		g2 = (Graphics2D) g;
-		RenderingHints rh = new RenderingHints(RenderingHints.KEY_ANTIALIASING,
-				RenderingHints.VALUE_ANTIALIAS_ON);
-		g2.setRenderingHints(rh);
-
-		// Paint the Background
-		if (!model.getCanvasImagePath().isEmpty()) {
-			img = new ImageIcon(model.getCanvasImagePath()).getImage();
-			switch (model.getCanvasImageMode()) {
-			case BackgroundPopUp.IMAGE_PIXELS:
-				g2.drawImage(img, 0, 0, img.getWidth(null),
-						img.getHeight(null), null);
-				break;
-			case BackgroundPopUp.STRETCHED:
-				g2.drawImage(img, 0, 0, model.getCanvasX(), model.getCanvasY(),
-						null);
-				break;
-			case BackgroundPopUp.CUSTOM:
-				g2.drawImage(img, 0, 0, model.getCanvasImageWidth(),
-						model.getCanvasImageHeight(), null);
-				break;
-			default:
-				break;
-			}
+	
+	private Color getStateColor(HolonObjectState state) {
+		switch(state) {
+		case NOT_SUPPLIED:
+			return new Color(230, 120, 100);
+		case NO_ENERGY:
+			return Color.white;
+		case OVER_SUPPLIED:
+			return new Color(166, 78, 229);
+		case PARTIALLY_SUPPLIED:
+			return Color.yellow;
+		case PRODUCER:
+			return Color.lightGray;
+		case SUPPLIED:
+			return new Color(13, 175, 28);
+		default:
+			return Color.BLACK;
 		}
-
-		// SubNet Coloring
-		int i = 0;
-		for (SubNet s : controller.getSimManager().getSubNets()) {
-
-			if (model.getSubNetColors().size() - 1 < i) {
-				controller.addSubNetColor(new Color(
-						(int) (Math.random() * 255),
-						(int) (Math.random() * 255),
-						(int) (Math.random() * 255)));
-			}
-			if (showedInformation[3]) {
-				for (HolonObject cps : s.getObjects()) {
-					cps.setBorderColor(model.getSubNetColors().get(i));
-				}
-			}
-			i++;
+	}
+	private void paintCanvasObject(Graphics2D g, DecoratedHolonObject decoratedHolonObject){
+		Position pos = decoratedHolonObject.getModel().getPosition();
+		Color statecolor = getStateColor(decoratedHolonObject.getState());
+		g.setColor(statecolor);
+		g.fillRect(pos.x - controller.getScaleDiv2(), pos.y - controller.getScaleDiv2(), controller.getScale(), controller.getScale());
+		drawCanvasObject(g, decoratedHolonObject.getModel().getImage(), pos);
+	}
+	private void drawCanvasObjectString(Graphics2D g, Position posOfCanvasObject, float energy) {
+		g.setColor(Color.BLACK);
+		g.setFont(new Font("TimesNewRoman", Font.PLAIN, (int) (controller.getScale() / 4f) )); 
+		g.drawString((energy > 0)? "+" + Float.toString(energy): Float.toString(energy), posOfCanvasObject.x - controller.getScaleDiv2(), posOfCanvasObject.y - controller.getScaleDiv2() - 1);
+	}
+	private void paintConsumer(Graphics2D g, Consumer con){
+		paintCanvasObject(g, con);
+		paintSupplyBar(g,con.getSupplyBarPercentage(), getStateColor(con.getState()), con.getModel().getPosition());
+		drawCanvasObjectString(g, con.getModel().getPosition(), -con.getEnergyNeededFromNetwork());
+	}
+	private void paintSupplier(Graphics2D g, Supplier sup){
+		paintCanvasObject(g, sup);
+		drawCanvasObjectString(g, sup.getModel().getPosition(), sup.getEnergyToSupplyNetwork());
+	}
+	
+	private void drawCanvasObject(Graphics2D g, String Image, Position pos) {
+		g.drawImage(Util.loadImage(Image, controller.getScale(), controller.getScale()) , 
+				pos.x - controller.getScaleDiv2(),
+				pos.y - controller.getScaleDiv2(),
+				controller.getScale(), controller.getScale() , null);
+	}
+	
+	private void paintCable(Graphics2D g, DecoratedCable cable, boolean isSelected)
+	{
+		Position start = cable.getModel().getA().getPosition();
+		Position end =  cable.getModel().getB().getPosition();
+		float currentEnergy = cable.getFlowEnergy();
+		float capacity = cable.getModel().getCapacity();
+		boolean unlimited = cable.getModel().isUnlimitedCapacity();
+		switch(cable.getState()) {
+		case Burned:
+			g.setColor(Color.RED);
+			g.setStroke(new BasicStroke(2));
+			break;
+		case Working:
+			g.setColor(new Color(13, 175, 28));
+			g.setStroke(new BasicStroke(unlimited?2f:(currentEnergy / capacity * 2f) + 1));
+			break;
 		}
-
-		// drawEdges that is being dragged
-		if (drawEdge) {
-			g2.setColor(Color.BLACK);
-			g2.setStroke(new BasicStroke(2));
-			g2.drawLine(tempCps.getPosition().x, tempCps.getPosition().y, x, y);
-		}
-
-		if(model.getEdgesOnCanvas().isEmpty() && !model.getObjectsOnCanvas().isEmpty()
-				&& !model.getObjectsOnCanvas().get(0).getConnections().isEmpty()){
-			ArrayList<CpsEdge> edgesOnCanvas= model.getEdgesOnCanvas();
-			for(AbstractCpsObject cps :model.getObjectsOnCanvas())
-				for(CpsEdge e: cps.getConnections()){
-					if(!edgesOnCanvas.contains(e))
-						model.addEdgeOnCanvas(e);
-				}
+		if(isSelected){
+			g.setColor(Color.lightGray);
+		}
+		g.drawLine(start.x, start.y, end.x, end.y);
+		Position middle = new Position((start.x + end.x) / 2, (start.y + end.y) / 2);
+		g.setFont(new Font("TimesRoman", Font.PLAIN, Math.max((int) (controller.getScale() / 3.5f), 10) )); 
+		g.drawString(currentEnergy + "/" + (unlimited?"\u221E":capacity) , middle.x, middle.y);
+	}
+	private void paintSwitch(Graphics2D g, DecoratedSwitch dSwitch)
+	{
+		drawCanvasObject(g, dSwitch.getState() == SwitchState.Open ? HolonSwitch.getSwitchOpenImage(): HolonSwitch.getSwitchClosedImage() , dSwitch.getModel().getPosition());
+	}
+	
+	private void paintExitCable(Graphics2D g, ExitCable eCable) {
+		Position start = eCable.getStart().getPosition();
+		Position end = eCable.getFinish().getPosition();
+		float currentEnergy = eCable.getCable().getFlowEnergy();
+		float capacity = eCable.getCable().getModel().getCapacity();
+		boolean unlimited = eCable.getCable().getModel().isUnlimitedCapacity();
+		switch(eCable.getCable().getState()) {
+		case Burned:
+			g.setColor(Color.RED);
+			g.setStroke(new BasicStroke(2));
+			break;
+		case Working:
+			g.setColor(new Color(13, 175, 28));
+			g.setStroke(new BasicStroke(unlimited?2f:(currentEnergy / capacity * 2f) + 1));
+			break;
 		}
+		g.drawLine(start.x, start.y, end.x, end.y);
+		Position middle = new Position((start.x + end.x) / 2, (start.y + end.y) / 2);
+		g.setFont(new Font("TimesRoman", Font.PLAIN, Math.max((int) (controller.getScale() / 3.5f), 10) )); 
+		g.drawString(currentEnergy + "/" + (unlimited?"\u221E":capacity) , middle.x, middle.y);
+	}
+	private void paintGroupNode(Graphics2D g, DecoratedGroupNode dGroupNode) {
+		Position pos = dGroupNode.getModel().getPosition();
+		g.setColor(Color.lightGray);
+		g.fillRect(pos.x - controller.getScaleDiv2(), pos.y - controller.getScaleDiv2(), controller.getScale(), controller.getScale());
+		drawCanvasObject(g, "/Images/upper_node.png" , pos);
+		paintGroupNodeBar(g, dGroupNode, pos);
+	}
+	private void paintGroupNodeBar(Graphics2D g, DecoratedGroupNode dGroupNode , Position pos) {
+		// +1, -2, -1 little Adjustment for pixel perfect alignment
+		int barWidth = (int) (controller.getScale());
+		int barHeight = (int) (controller.getScale() / 5);
+		g.setColor(Color.WHITE);
+		g.fillRect(pos.x - controller.getScaleDiv2(), pos.y + controller.getScaleDiv2() - 1, (int) barWidth, barHeight);
+		float[] percentages = getGroupNodeBarPercentages(dGroupNode);
+		Color[] colors = new Color[6];
+		colors[0] = getStateColor(HolonObjectState.PRODUCER);
+		colors[1] = getStateColor(HolonObjectState.NOT_SUPPLIED);
+		colors[2] = getStateColor(HolonObjectState.PARTIALLY_SUPPLIED);
+		colors[3] = getStateColor(HolonObjectState.SUPPLIED);
+		colors[4] = getStateColor(HolonObjectState.OVER_SUPPLIED);
+		colors[5] = getStateColor(HolonObjectState.NO_ENERGY);
+				
+		for(int i = 5; i>=0; i--) {
+			g.setColor(colors[i]);
+			g.fillRect(pos.x - controller.getScaleDiv2(), pos.y + controller.getScaleDiv2() - 1, (int) (barWidth * percentages[i] - 1), barHeight);		
+		}
+//		g.setColor(color);
+//		g.fillRect(pos.x - controller.getScaleDiv2(), pos.y + controller.getScaleDiv2() - 1, (int) (barWidth * (percentage < 1 ? percentage : 1.0f) - 1), barHeight);
+		g.setColor(Color.BLACK);
+		g.setStroke(new BasicStroke(1));
+		g.drawRect(pos.x - controller.getScaleDiv2(), pos.y + controller.getScaleDiv2() - 1, barWidth - 1 , barHeight);
+	}
+	/**
+	 * HardCoded Stuff dont try at Home ;)
+	 * @param dGroupNode
+	 * @return
+	 */
+	public float[] getGroupNodeBarPercentages(DecoratedGroupNode dGroupNode) {
+		int[] amountOfObjects = new int[6];
+		amountOfObjects[0] = dGroupNode.getAmountOfSupplier();
+		amountOfObjects[1] = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.NOT_SUPPLIED);
+		amountOfObjects[2] = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.PARTIALLY_SUPPLIED);
+		amountOfObjects[3] = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.SUPPLIED);
+		amountOfObjects[4] = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.OVER_SUPPLIED);
+		amountOfObjects[5] = dGroupNode.getAmountOfPassiv();
+		int countHolonObjects = amountOfObjects[0] + 	amountOfObjects[1] + amountOfObjects[2] + amountOfObjects[3] + amountOfObjects[4] + amountOfObjects[5];
+		float[] percentages = new float[6];
+		int count = 0;
+		for(int i = 0; i < 6; i++) {
+			count += amountOfObjects[i];
+			percentages[i] = (float)count / (float)countHolonObjects;
+		}
+		return percentages;
+	}
+	private void paintSupplyBar(Graphics2D g, float percentage, Color color, Position pos) {
+		// +1, -2, -1 little Adjustment for pixel perfect alignment
+		int barWidth = (int) (controller.getScale());
+		int barHeight = (int) (controller.getScale() / 5);
+		g.setColor(Color.WHITE);
+		g.fillRect(pos.x - controller.getScaleDiv2(), pos.y + controller.getScaleDiv2() - 1, (int) barWidth, barHeight);
+		g.setColor(color);
+		g.fillRect(pos.x - controller.getScaleDiv2(), pos.y + controller.getScaleDiv2() - 1, (int) (barWidth * (percentage < 1 ? percentage : 1.0f) - 1), barHeight);
+		g.setColor(Color.BLACK);
+		g.setStroke(new BasicStroke(1));
+		g.drawRect(pos.x - controller.getScaleDiv2(), pos.y + controller.getScaleDiv2() - 1, barWidth - 1 , barHeight);
+		g.setFont(new Font("TimesNewRoman", Font.PLAIN, (int) (barHeight * 1.5) - 2)); 
+		String percentageString = (Math.round((percentage * 100))) + "%";
+		int stringWidth = (int) g.getFontMetrics().getStringBounds(percentageString, g).getWidth();
+		if(percentage > 1.0f) g.setColor(Color.WHITE); //Just to see better on purple
+		g.drawString(percentageString, pos.x + 1 - stringWidth / 2, pos.y + controller.getScaleDiv2() - 1+ barHeight);
 		
-		for (CpsEdge con : model.getEdgesOnCanvas()) {
-			maxCap = paintEdge(con, maxCap);
-		}
-
-		// Highlighted Edge
-		if (!model.getSelectedCpsObjects().isEmpty() || !tempSelected.isEmpty() || model.getSelectedObjectID() > 0) {
-			g2.setColor(Color.BLUE);
-			for (CpsEdge con : model.getEdgesOnCanvas()) {
-				if (con.getFlow() <= con.getCapacity()) {
-					g2.setStroke(new BasicStroke(Math.min(
-							((con.getFlow() / con.getCapacity() * 3) + 1), 4)));
-				} else {
-					g2.setStroke(new BasicStroke(2));
-				}
-
-				maxCap = drawEdgeLine(con, maxCap);
-			}
-		} else if (edgeHighlight != null) {
-			g2.setColor(Color.BLUE);
-			if (edgeHighlight.getFlow() <= edgeHighlight.getCapacity()) {
-				g2.setStroke(new BasicStroke(Math.min(((edgeHighlight.getFlow()
-						/ edgeHighlight.getCapacity() * 3) + 1), 4)));
-			} else {
-				g2.setStroke(new BasicStroke(2));
-			}
-			g2.drawLine(edgeHighlight.getA().getPosition().x, edgeHighlight
-					.getA().getPosition().y,
-					edgeHighlight.getB().getPosition().x, edgeHighlight.getB()
-							.getPosition().y);
-
-			maxCap = setCapacityString(edgeHighlight, maxCap);
-
-			if (showedInformation[0]) {
-				g2.drawString(edgeHighlight.getFlow() + "/" + maxCap,
-						(edgeHighlight.getA().getPosition().x + edgeHighlight
-								.getB().getPosition().x) / 2, (edgeHighlight
-								.getA().getPosition().y + edgeHighlight.getB()
-								.getPosition().y) / 2);
+	}
+	
+	//old code
+	void drawMarker(Graphics2D g) {
+		Color transparentGrey = new Color(128, 174, 247, 40);
+		if (sx > x && sy > y) {
+			g.drawRect(x, y, sx - x, sy - y);
+			g.setColor(transparentGrey);
+			g.fillRect(x, y, sx - x, sy - y);
+		} else if (sx < x && sy < y) {
+			g.drawRect(sx, sy, x - sx, y - sy);
+			g.setColor(transparentGrey);
+			g.fillRect(sx, sy, x - sx, y - sy);
+		} else if (sx >= x) {
+			g.drawRect(x, sy, sx - x, y - sy);
+			g.setColor(transparentGrey);
+			g.fillRect(x, sy, sx - x, y - sy);
+		} else if (sy >= y) {
+			g.drawRect(sx, y, x - sx, sy - y);
+			g.setColor(transparentGrey);
+			g.fillRect(sx, y, x - sx, sy - y);
+		}
+	}
+	public void paintComponent(Graphics g) {		
+		super.paintComponent(g);
+		Graphics2D g2d = (Graphics2D) g;
+		g2d.setRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING,
+				RenderingHints.VALUE_ANTIALIAS_ON));
+		//-->Old code
+		if (drawEdge) {
+			g2d.setColor(Color.BLACK);
+			g2d.setStroke(new BasicStroke(1));
+			g2d.drawLine(tempCps.getPosition().x, tempCps.getPosition().y, x, y);
+		}
+		//<--
+		//SelectedCable
+		HashSet<CpsEdge> selectedEdges = new HashSet<CpsEdge>();
+		for(AbstractCpsObject aCps:  model.getSelectedCpsObjects()) {
+			for(CpsEdge edge: aCps.getConnections()) {
+				selectedEdges.add(edge);
 			}
 		}
-
-
-		/**
-		 * highlight the Object that would be replaced
-		 */
-		highlightMayBeReplaced(g2);
+		if(model.getSelectedEdge() != null) selectedEdges.add(model.getSelectedEdge());
+		//timstep:
+		g.setFont(new Font("TimesNewRoman", Font.PLAIN, Math.max((int) (controller.getScale() / 3.5f), 10) )); 
+		g2d.setColor(Color.BLACK);
 		
-		// Objects
-		for (AbstractCpsObject cps : model.getObjectsOnCanvas()) {
-			// Border Highlighting
-			if (showedInformation[3]) {
-				g2.setColor(cps.getBorderColor());
-				if (g2.getColor() != Color.WHITE && !(cps instanceof CpsNode)) {
-					g2.fillRect(
-							(int) (cps.getPosition().x
-									- controller.getScaleDiv2() - scalediv20 - 3),
-							(int) (cps.getPosition().y
-									- controller.getScaleDiv2() - scalediv20 - 3),
-							(int) (controller.getScale() + ((scalediv20 + 3) * 2)),
-							(int) (controller.getScale() + ((scalediv20 + 3) * 2)));
-				}
-			}
-
-			setEdgePictureAndHighlighting(cps);
-
-			g2.drawImage(img, cps.getPosition().x - controller.getScaleDiv2(),
-					cps.getPosition().y - controller.getScaleDiv2(),
-					controller.getScale(), controller.getScale(), null);
-
-			paintSupplyBar(g, cps);
+		VisualRepresentationalState  visualState = controller.getSimManager().getActualVisualRepresentationalState();
+		//VisualState Representation:
+		for(ExitCable cable : visualState.getExitCableList()) {
+			paintExitCable(g2d, cable);
+		}
+		for(DecoratedCable cable : visualState.getCableList()) {
+			paintCable(g2d, cable, selectedEdges.contains(cable.getModel()));
+		}
+		for(DecoratedGroupNode dGroupNode : visualState.getGroupNodeList()) {
+			paintGroupNode(g2d, dGroupNode);
+		}
+		for(Consumer con: visualState.getConsumerList()) {
+			paintConsumer(g2d, con);					
+		}
+		for(Supplier sup: visualState.getSupplierList()) {
+			paintSupplier(g2d, sup);				
+		}
+		for(Passiv pas: visualState.getPassivList()) {
+			paintCanvasObject(g2d, pas);
+		}
+		for(DecoratedSwitch dSwitch : visualState.getSwitchList()) {
+				paintSwitch(g2d, dSwitch);
+		}
+		for(CpsNode node : visualState.getNodeList()) {
+			drawCanvasObject(g2d, "/Images/node.png" , node.getPosition());
 		}
 		
-		// Dragged marker Highlighting
+		//-->oldCode 
 		if (doMark) {
-			g2.setColor(Color.BLACK);
-			g2.setStroke(new BasicStroke(0));
-			drawMarker();
+			g2d.setColor(Color.BLACK);
+			g2d.setStroke(new BasicStroke(0));
+			drawMarker(g2d);
+		}
+		//Test Selection
+		//Objects:
+		g2d.setColor(Color.BLUE);
+		g2d.setStroke(new BasicStroke(1));
+		Color transparentGrey = new Color(128, 174, 247, 40);
+		for(AbstractCpsObject aCps:  model.getSelectedCpsObjects()) {
+			if(aCps instanceof CpsNode) {
+				Position pos = aCps.getPosition();
+				g2d.setColor(transparentGrey);
+				g2d.fillOval(pos.x - (int) (controller.getScaleDiv2()), pos.y - (int) (controller.getScaleDiv2()),  controller.getScale(),  controller.getScale());
+				g2d.setColor(Color.LIGHT_GRAY);
+				g2d.setStroke(new BasicStroke(2));
+				g2d.drawOval(pos.x - (int) (controller.getScaleDiv2()), pos.y - (int) (controller.getScaleDiv2()),  controller.getScale(),  controller.getScale());
+			}
+			else {
+				Position pos = aCps.getPosition();
+				g2d.setColor(transparentGrey);
+				g2d.fillRect(pos.x - (int) (controller.getScaleDiv2()* 1.5f), pos.y - (int) (controller.getScaleDiv2()* 1.5f), (int) (controller.getScale()* 1.5f) , (int) (controller.getScale()* 1.5f));
+				g2d.setColor(Color.LIGHT_GRAY);
+				g2d.setStroke(new BasicStroke(2));
+				g2d.drawRect(pos.x - (int) (controller.getScaleDiv2()* 1.5f), pos.y - (int) (controller.getScaleDiv2()* 1.5f), (int) (controller.getScale()* 1.5f) , (int) (controller.getScale()* 1.5f));				
+			}
+
+		}
+		//maybeReplace:
+		if(mayBeReplaced != null){
+			g2d.setColor(Color.RED);
+			Position pos = mayBeReplaced.getPosition();
+			g2d.drawImage(Util.loadImage("/Images/replace.png") , 
+					pos.x + controller.getScaleDiv2(),
+					pos.y - controller.getScale(),
+					controller.getScaleDiv2(), controller.getScaleDiv2(), null);
 		}
-		// Tooltip
-		showTooltip(g);
+		//<-- OldCode
 	}
 
 	@Override
 	public void mouseClicked(MouseEvent e) {
-		if (e.getButton() == MouseEvent.BUTTON1) {
+		if(!disabled){
+			if (e.getButton() == MouseEvent.BUTTON1) {
 			DefaulTable propertyTable = model.getPropertyTable();
 			if (propertyTable.getRowCount() > 0) {
 				for (int i = propertyTable.getRowCount() - 1; i > -1; i--) {
 					propertyTable.removeRow(i);
 				}
 			}
+
 			triggerUpdateController();
+			}
+			stopEditing();
 		}
-
-		stopEditing();
 	}
 
 	@Override
@@ -536,6 +676,7 @@ public class MyCanvas extends AbstractCanvas implements MouseListener,
 
 	@Override
 	public void mousePressed(MouseEvent e) {
+		if(!disabled){
 		stopEditing();
 		tempCps = null;
 		edgeHighlight = null;
@@ -548,7 +689,6 @@ public class MyCanvas extends AbstractCanvas implements MouseListener,
 					&& y - controller.getScale() <= cy && x >= cx && y >= cy) {
 				tempCps = cps;
 
-				setConsoleTextAfterSelect(cps);
 
 				dragging = true;
 
@@ -593,10 +733,12 @@ public class MyCanvas extends AbstractCanvas implements MouseListener,
 		}
 
 		repaint();
+		}
 	}
 
 	@Override
 	public void mouseReleased(MouseEvent e) {
+		if(!disabled){
 		x = e.getX();
 		y = e.getY();
 
@@ -658,16 +800,17 @@ public class MyCanvas extends AbstractCanvas implements MouseListener,
 			((HolonSwitch) tempCps).switchState();
 
 		}
-		controller.calculateStateForTimeStep(model.getCurIteration());
+		controller.calculateStateAndVisualForTimeStep(model.getCurIteration());
 
 		triggerUpdateController();
 
 		repaint();
-
+		}
 	}
 
 	@Override
 	public void mouseDragged(MouseEvent e) {
+		if(!disabled){
 		// If Edge is drawn
 		x = e.getX();
 		y = e.getY();
@@ -769,11 +912,12 @@ public class MyCanvas extends AbstractCanvas implements MouseListener,
 		}
 
 		repaint();
-
+		}
 	}
 
 	@Override
 	public void mouseMoved(MouseEvent e) {	
+		if(!disabled){
 		x = e.getX();
 		y = e.getY();
 
@@ -788,8 +932,10 @@ public class MyCanvas extends AbstractCanvas implements MouseListener,
 		if(on||(!on && toolTip))
 		repaint();
 		toolTip = on;
+		}
 	}
 
+
 	/**
 	 * Draws or Deletes an Edge.
 	 */
@@ -829,8 +975,29 @@ public class MyCanvas extends AbstractCanvas implements MouseListener,
 							deleteNode = true;
 						}
 					} else {
-						e = new CpsEdge(cps, tempCps, model.getMaxCapacity());
-						controller.addEdgeOnCanvas(e);
+						if(!(cps instanceof CpsUpperNode || tempCps instanceof CpsUpperNode)) {
+							e = new CpsEdge(cps, tempCps, model.getMaxCapacity());
+							controller.addEdgeOnCanvas(e);
+						}else if (cps instanceof CpsUpperNode && !(tempCps instanceof CpsUpperNode)){
+							CpsUpperNode thisUpperNode = (CpsUpperNode)cps;
+							Object[] possibilities = thisUpperNode.getNodes().stream().map(aCps -> new ACpsHandle(aCps)).filter(aCpsHandle -> !(aCpsHandle.object instanceof CpsUpperNode)).toArray();
+							if(possibilities.length != 0) {
+								ACpsHandle selected = (ACpsHandle) JOptionPane.showInputDialog(this, "Select a inside Object:", "Connection To?",  JOptionPane.OK_OPTION,new ImageIcon(new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB)) , possibilities, "");
+								if(selected != null) {
+									e = new CpsEdge(selected.object, tempCps, model.getMaxCapacity());
+									controller.addEdgeUpperNode(e, (CpsUpperNode)cps);
+								}
+							}else {
+								CpsNode n = new CpsNode("Node");
+
+								n.setPosition(x, y);
+								controller.addObjUpperNode(n, thisUpperNode);
+								e = new CpsEdge(n, tempCps, model.getMaxCapacity());
+								controller.addEdgeUpperNode(e, (CpsUpperNode)cps);
+							}
+							
+						}
+						
 					}
 				}
 			}
@@ -1019,4 +1186,7 @@ public class MyCanvas extends AbstractCanvas implements MouseListener,
 			}
 		}
 	}
+	
+	
+	   
 }

+ 250 - 0
src/ui/view/Outliner.java

@@ -0,0 +1,250 @@
+package ui.view;
+
+import java.awt.BorderLayout;
+import java.awt.Color;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.swing.ImageIcon;
+import javax.swing.JFrame;
+
+import javax.swing.JPanel;
+import javax.swing.JScrollPane;
+import javax.swing.JTabbedPane;
+import javax.swing.JTree;
+import javax.swing.event.TreeModelEvent;
+import javax.swing.event.TreeModelListener;
+import javax.swing.tree.DefaultMutableTreeNode;
+import javax.swing.tree.DefaultTreeCellRenderer;
+
+import classes.AbstractCpsObject;
+
+import classes.CpsNode;
+
+import ui.controller.Control;
+
+import ui.model.Consumer;
+import ui.model.DecoratedCable;
+import ui.model.DecoratedHolonObject.HolonObjectState;
+import ui.model.DecoratedNetwork;
+import ui.model.DecoratedState;
+import ui.model.DecoratedSwitch;
+import ui.model.MinimumNetwork;
+import ui.model.Model;
+import ui.model.Passiv;
+import ui.model.Supplier;
+
+
+
+
+
+
+public class Outliner extends JFrame {
+	private static final long serialVersionUID = 1L;
+	JTabbedPane tabbedPane = new JTabbedPane();
+	JPanel listPanel = new JPanel(new BorderLayout());
+	JPanel statePanel = new JPanel(new BorderLayout());
+	public boolean isClosed = false;
+	ArrayList<MinimumNetwork> list;
+	Outliner(JFrame parentFrame, Model model, Control controller){ 
+		setBounds(0, 0, 400, parentFrame.getHeight());
+		this.setIconImage(Util.loadImage("/Images/Holeg.png", 30, 30));
+		this.setTitle("Outliner");
+		setLocationRelativeTo(parentFrame);
+		this.setVisible(true);
+		repaintWithDecoratedState(controller.getSimManager().getActualDecorState());
+		this.getContentPane().add(tabbedPane);
+		this.addWindowListener(new java.awt.event.WindowAdapter() {
+		    @Override
+		    public void windowClosing(java.awt.event.WindowEvent windowEvent) {
+		    	isClosed = true;
+		    }
+		});
+		tabbedPane.addTab("List", listPanel);
+		tabbedPane.addTab("State", statePanel);
+	}
+
+	public void repaintWithDecoratedState(DecoratedState decoratedState) {
+		//tabbedPane.removeAll();
+		listPanel.removeAll();
+		statePanel.removeAll();
+		DefaultMutableTreeNode topListPanel = new DefaultMutableTreeNode();
+		DefaultMutableTreeNode objects = new DefaultMutableTreeNode("HolonObjects");
+		DefaultMutableTreeNode switches = new DefaultMutableTreeNode("Switches");
+		DefaultMutableTreeNode nodes = new DefaultMutableTreeNode("Nodes");
+		DefaultMutableTreeNode cables = new DefaultMutableTreeNode("Cable");
+		topListPanel.add(objects);
+		topListPanel.add(switches);
+		topListPanel.add(nodes);
+		topListPanel.add(cables);
+		DefaultMutableTreeNode topStatePanel = new DefaultMutableTreeNode();
+		
+		for(DecoratedSwitch dSwitch: decoratedState.getDecoratedSwitches()) {
+			switches.add(new DefaultMutableTreeNode(dSwitch.getModel().getName()));
+		}
+		
+		/*for(CpsNode node: decoratedState.getNodeList()) {
+			nodes.add(new DefaultMutableTreeNode(node.getName()));
+		}*/
+		
+		for(DecoratedNetwork dNet: decoratedState.getNetworkList()) {
+			DefaultMutableTreeNode network = new DefaultMutableTreeNode("Network");
+			if(!dNet.getConsumerList().isEmpty() || !dNet.getConsumerSelfSuppliedList().isEmpty()) {
+				DefaultMutableTreeNode consumer = new DefaultMutableTreeNode("ConsumerList");
+				for (Consumer con : dNet.getConsumerList()) {
+					DefaultMutableTreeNode consumerNode = new ColoredTreeNode(con.toString(),con.getState().toString(), getStateColor(con.getState()) );
+					consumer.add(consumerNode);
+					objects.add(new DefaultMutableTreeNode(con.getModel().getName()));
+				}
+				for (Consumer con : dNet.getConsumerSelfSuppliedList()) {
+					DefaultMutableTreeNode consumerNode = new DefaultMutableTreeNode(con.toString() + con.getState());
+					consumer.add(consumerNode);
+					objects.add(new DefaultMutableTreeNode(con.getModel().getName()));
+				}
+				network.add(consumer);
+			}
+			if(!dNet.getSupplierList().isEmpty()) {
+				DefaultMutableTreeNode supplier = new DefaultMutableTreeNode("SupplierList");
+				for (Supplier sup : dNet.getSupplierList()) {
+					supplier.add(new DefaultMutableTreeNode(sup.toString()));
+					objects.add(new DefaultMutableTreeNode(sup.getModel().getName()));
+				}
+				network.add(supplier);
+			}
+			for(Passiv pas: dNet.getPassivNoEnergyList()) {
+				objects.add(new DefaultMutableTreeNode(pas.getModel().getName()));
+			}
+			topStatePanel.add(network);
+			for(DecoratedCable cable : dNet.getDecoratedCableList()) {
+				cables.add(new DefaultMutableTreeNode(cable.getModel().toString()));
+			}
+		}
+		
+		for(DecoratedCable cable : decoratedState.getLeftOverEdges()) {
+			cables.add(new DefaultMutableTreeNode(cable.getModel().toString()));
+		}
+		
+		
+		JTree listTree = new JTree(topListPanel);
+		signIconsForTree(listTree);
+		listTree.setRootVisible(false);
+		for (int i = 0; i < listTree.getRowCount(); i++) {
+			listTree.expandRow(i);
+		}
+		JScrollPane listScroller = new JScrollPane(listTree);
+		listPanel.add(listScroller);
+		
+		JTree stateTree = new JTree(topStatePanel);
+		signIconsForTree(stateTree);
+		stateTree.setRootVisible(false);
+		for (int i = 0; i < stateTree.getRowCount(); i++) {
+			stateTree.expandRow(i);
+		}
+		statePanel.add(new JScrollPane(stateTree));
+		
+		listPanel.revalidate();;
+		statePanel.revalidate();
+		listPanel.repaint();
+	}
+
+
+
+
+
+
+	private void signIconsForTree(JTree t) {
+		ImageIcon ClosedIcon = new ImageIcon(Util.loadImage("/Button_Images/Close.png",9,9));
+		ImageIcon OpenIcon = new ImageIcon(Util.loadImage("/Button_Images/Open.png",9,9));
+		ImageIcon LeafIcon = new ImageIcon(Util.loadImage("/Button_Images/Leaf.png",9,9));
+		if (ClosedIcon != null && OpenIcon != null && LeafIcon!= null) {
+		    DefaultTreeCellRenderer renderer = 
+		        new DefaultTreeCellRenderer();
+		    renderer.setClosedIcon(ClosedIcon);
+		    renderer.setOpenIcon(OpenIcon);
+		    renderer.setLeafIcon(LeafIcon);
+		    t.setCellRenderer(renderer);
+		}
+	}
+	
+	class MyTreeModelListener implements TreeModelListener {
+
+		@Override
+		public void treeNodesChanged(TreeModelEvent tmE) {
+			// TODO Auto-generated method stub
+			System.out.println("treeNodesChanged");
+		}
+
+		@Override
+		public void treeNodesInserted(TreeModelEvent tmE) {
+			// TODO Auto-generated method stub
+			System.out.println("treeNodesInserted");
+		}
+
+		@Override
+		public void treeNodesRemoved(TreeModelEvent tmE) {
+			// TODO Auto-generated method stub
+			System.out.println("treeNodesRemoved");
+		}
+
+		@Override
+		public void treeStructureChanged(TreeModelEvent tmE) {
+			// TODO Auto-generated method stub
+			System.out.println("treeStructureChanged");
+		}
+	
+	}
+	private Color getStateColor(HolonObjectState state) {
+		switch(state) {
+		case NOT_SUPPLIED:
+			return new Color(230, 120, 100);
+		case NO_ENERGY:
+			return Color.white;
+		case OVER_SUPPLIED:
+			return new Color(166, 78, 229);
+		case PARTIALLY_SUPPLIED:
+			return Color.yellow;
+		case PRODUCER:
+			return Color.lightGray;
+		case SUPPLIED:
+			return new Color(13, 175, 28);
+		default:
+			return Color.BLACK;
+		}
+	}
+	
+	
+	@SuppressWarnings("serial")
+	class ColoredTreeNode extends DefaultMutableTreeNode{
+		private Color color;
+		public ColoredTreeNode(String string, String state, Color color) {
+			//"<html>Some text <font color='red'>" + "bla" + "some text in red</font></html>"
+			//Integer.toHexString(color.getRGB()).substring(2)
+			//String c = string + "<html><font bgcolor='#132122'>" + state +"</font></html>";
+			super(( "<html>" + string + "<font bgcolor='#" + Integer.toHexString(color.getRGB()).substring(2) + "'>" + state +"</font></html>"));
+			//this.color = color;
+		}
+		public Color getColor(){
+			return color;
+		}
+		public void setColor(Color color) {
+			this.color = color;
+		}
+		
+	}
+	
+	class AbstractCpsObjectInfo {
+		private AbstractCpsObject aCps;
+		AbstractCpsObjectInfo(AbstractCpsObject aCps){
+			this.aCps = aCps;
+		}
+		@Override
+		public String toString(){
+			return aCps.getName() + " Id:"+ aCps.getId();
+		}
+		
+		public AbstractCpsObject getAbstractCpsObject()
+		{
+			return aCps;
+		}
+	}
+}

+ 13 - 35
src/ui/view/StatisticGraph.java

@@ -165,7 +165,7 @@ public class StatisticGraph extends JPanel {
         float temp = 0;
         for (HolonElement e : obj.getElements()) {
             if (e.isActive()) {
-                temp = temp + e.getAvailableEnergyAt(model.getCurIteration());
+                temp = temp + e.getEnergyAtTimeStep(model.getCurIteration());
             }
         }
         return temp;
@@ -182,7 +182,7 @@ public class StatisticGraph extends JPanel {
                 case TrackedDataSet.CONSUMPTION:
                     for (HolonElement h : ((HolonObject) set.getCpsObject()).getElements()) {
                         if (h.getEnergyPerElement() < 0) {
-                            val += (h.getEnergyPerElement() + h.getFlexibleEnergyAvailablePerElement()) * h.getAmount();
+                            val += (h.getEnergyPerElement() ) * h.getAmount();
                         }
                     }
                     val *= -1;
@@ -190,7 +190,7 @@ public class StatisticGraph extends JPanel {
                 case TrackedDataSet.PRODUCTION:
                     for (HolonElement h : ((HolonObject) set.getCpsObject()).getElements()) {
                         if (h.getEnergyPerElement() > 0) {
-                            val += (h.getEnergyPerElement() + h.getFlexibleEnergyAvailablePerElement()) * h.getAmount();
+                            val += (h.getEnergyPerElement() ) * h.getAmount();
                         }
                     }
                     break;
@@ -373,18 +373,8 @@ public class StatisticGraph extends JPanel {
                     float wasted = getTotalWastedEnergyAt(model.getObjectsOnCanvas(), model.getCurIteration());
                     set.setValAt(wasted, model.getCurIteration());
                     break;
-                case TrackedDataSet.PERCENT_SUPPLIED:
-                    set.setValAt(getPercentState(model.getObjectsOnCanvas(), HolonObject.SUPPLIED),
-                            model.getCurIteration());
-                    break;
-                case TrackedDataSet.PERCENT_NOT_SUPPLIED:
-                    set.setValAt(getPercentState(model.getObjectsOnCanvas(), HolonObject.NOT_SUPPLIED),
-                            model.getCurIteration());
-                    break;
-                case TrackedDataSet.PERCENT_PARTIAL_SUPPLIED:
-                    set.setValAt(getPercentState(model.getObjectsOnCanvas(), HolonObject.PARTIALLY_SUPPLIED),
-                            model.getCurIteration());
-                    break;
+               
+              
                 case TrackedDataSet.GROUP_PRODUCTION:
                     set.setValAt(
                             getTotalProductionAt(((CpsUpperNode) set.getCpsObject()).getNodes(), model.getCurIteration()),
@@ -425,7 +415,7 @@ public class StatisticGraph extends JPanel {
                 case TrackedDataSet.AVG_AMOUNT_PRODUCERS_IN_HOLONS:
                     for (SubNet sub : controller.getSimManager().getSubNets()) {
                         for (HolonObject obj : sub.getObjects()) {
-                            if (obj.getCurrentEnergyAtTimeStep(model.getCurIteration()) > 0) {
+                            if (obj.getEnergyAtTimeStep(model.getCurIteration()) > 0) {
                                 val++;
                             }
                         }
@@ -466,9 +456,9 @@ public class StatisticGraph extends JPanel {
                     float cons = 0;
                     for (SubNet sub : controller.getSimManager().getSubNets()) {
                         for (HolonObject obj : sub.getObjects()) {
-                            if (obj.getCurrentEnergyAtTimeStep(model.getCurIteration()) > 0) {
+                            if (obj.getEnergyAtTimeStep(model.getCurIteration()) > 0) {
                                 prod++;
-                            } else if (obj.getCurrentEnergyAtTimeStep(model.getCurIteration()) < 0) {
+                            } else if (obj.getEnergyAtTimeStep(model.getCurIteration()) < 0) {
                                 cons++;
                             }
                         }
@@ -564,7 +554,6 @@ public class StatisticGraph extends JPanel {
                     convertToCanvasY((set.getValues()[1] * (maximum / 3 * 2)) + (maximum / 6)));
         }
         for (int i = 0; i < model.getCurIteration(); i++) {
-            controller.addTextToConsole(set.getValues()[i] + "");
             if (set.getValues()[i + 1] != -1) {
                 path.lineTo((i + 1) * this.getWidth() / model.getIterations(),
                         convertToCanvasY((set.getValues()[i + 1] * (maximum / 3 * 2)) + (maximum / 6)));
@@ -612,7 +601,7 @@ public class StatisticGraph extends JPanel {
             if (obj instanceof HolonObject) {
                 for (HolonElement ele : ((HolonObject) obj).getElements()) {
                     if (ele.getEnergyPerElement() > 0) {
-                        val += (ele.getEnergyPerElement() + ele.getFlexibleEnergyAvailablePerElement()) * ele.getAmount();
+                        val += (ele.getEnergyPerElement() ) * ele.getAmount();
                     }
                 }
             } else if (obj instanceof CpsUpperNode) {
@@ -632,7 +621,7 @@ public class StatisticGraph extends JPanel {
             if (obj instanceof HolonObject) {
                 for (HolonElement ele : ((HolonObject) obj).getElements()) {
                     if (ele.getEnergyPerElement() < 0) {
-                        val += (ele.getEnergyPerElement() + ele.getFlexibleEnergyAvailablePerElement()) * ele.getAmount();
+                        val += (ele.getEnergyPerElement() ) * ele.getAmount();
                     }
                 }
             } else if (obj instanceof CpsUpperNode) {
@@ -653,7 +642,7 @@ public class StatisticGraph extends JPanel {
         for (AbstractCpsObject obj : objects) {
             if (obj instanceof HolonObject) {
                 for (HolonElement ele : ((HolonObject) obj).getElements()) {
-                    val += (ele.getEnergyPerElement() + ele.getFlexibleEnergyAvailablePerElement()) * ele.getAmount();
+                    val += (ele.getEnergyPerElement() ) * ele.getAmount();
                 }
             } else if (obj instanceof CpsUpperNode) {
                 val += getMaxWastedEnergy(((CpsUpperNode) obj).getNodes());
@@ -693,7 +682,7 @@ public class StatisticGraph extends JPanel {
         for (AbstractCpsObject obj : objects) {
             if (obj instanceof HolonObject) {
                 for (HolonElement ele : ((HolonObject) obj).getElements()) {
-                    if (ele.isActive() && ele.getAvailableEnergyAt(tStep) < 0 ) {
+                    if (ele.isActive() && ele.getEnergyAtTimeStep(tStep) < 0 ) {
                         val += ele.getOverallEnergyAtTimeStep(tStep);
                     }
                 }
@@ -726,18 +715,7 @@ public class StatisticGraph extends JPanel {
     }
 
 
-    /**
-     * get the Percentage of how many objects with the given state are in the
-     * given List
-     *
-     * @param objects List of Objects
-     */
-    private float getPercentState(ArrayList<AbstractCpsObject> objects, int state) {
-        float count = controller.getNumberHolonObjects(objects);
-        float stateObjectss = controller.getNumberStateObjects(objects, state);
-
-        return stateObjectss / count;
-    }
+  
 
     /**
      * Return all TrackedDataSets

+ 4 - 1
src/ui/view/TimePanel.java

@@ -104,6 +104,9 @@ public class TimePanel extends JPanel implements ActionListener{
 			@Override
 			public void actionPerformed(ActionEvent ae) {
 				timeSlider.setValue(timeSlider.getValue() + 1);
+				System.out.println(timeSlider.getValue());
+				int test = timeSlider.getValue();
+				System.out.println(test);
 				controller.setCurIteration(timeSlider.getValue());
 				timer.setDelay(cont.getModel().getTimerSpeed());
 				if (timeSlider.getValue() >= cont.getModel().getIterations() - 1) {
@@ -373,7 +376,7 @@ public class TimePanel extends JPanel implements ActionListener{
 	}
 
 	@Override
-	public void actionPerformed(ActionEvent arg0) {//I dislike anon classes.
+	public void actionPerformed(ActionEvent arg0) {
 		updateIterationsInput();
 	}
 	/**

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

@@ -794,7 +794,7 @@ public class UnitGraph extends JPanel implements MouseListener, MouseMotionListe
 	 * @param obj
 	 */
 	public void update(ArrayList<AbstractCpsObject> obj) {
-		System.out.println("update");
+		
 	}
     
 

+ 384 - 309
src/ui/view/UpperNodeCanvas.java

@@ -6,7 +6,17 @@ import com.google.gson.JsonParseException;
 
 import ui.controller.Control;
 import ui.controller.UpdateController;
+import ui.model.Consumer;
+import ui.model.DecoratedCable;
+import ui.model.DecoratedGroupNode;
+import ui.model.DecoratedHolonObject;
+import ui.model.DecoratedSwitch;
 import ui.model.Model;
+import ui.model.Passiv;
+import ui.model.Supplier;
+import ui.model.VisualRepresentationalState;
+import ui.model.DecoratedHolonObject.HolonObjectState;
+import ui.model.DecoratedSwitch.SwitchState;
 
 import javax.swing.*;
 
@@ -16,9 +26,11 @@ import java.awt.event.MouseEvent;
 import java.awt.event.MouseListener;
 import java.awt.event.MouseMotionListener;
 import java.awt.geom.Line2D;
+import java.awt.image.BufferedImage;
 import java.io.File;
 import java.io.IOException;
 import java.util.ArrayList;
+import java.util.HashSet;
 
 /**
  * This Class is the Canvas. All Objects will be visualized here
@@ -35,7 +47,9 @@ public class UpperNodeCanvas extends AbstractCanvas implements MouseListener, Mo
     int code;
     private JLabel breadCrumb;
     private int upperNodeID;
-
+    private Component parent;
+    private BufferedImage parentPreview;
+    public boolean disable = false;
     /**
      * Constructor.
      *
@@ -43,7 +57,7 @@ public class UpperNodeCanvas extends AbstractCanvas implements MouseListener, Mo
      * @param control   the Controller
      * @param unitGraph
      */
-    UpperNodeCanvas(Model mod, Control control, UnitGraph unitGraph, CpsUpperNode UpperNode, String parentPath) {
+    UpperNodeCanvas(Model mod, Control control, UnitGraph unitGraph, CpsUpperNode UpperNode, String parentPath, Component parentComponent) {
         toolTip = false;
 
         this.controller = control;
@@ -53,11 +67,13 @@ public class UpperNodeCanvas extends AbstractCanvas implements MouseListener, Mo
         this.code = UpperNode.hashCode();
         this.path = parentPath + upperNode.getName();
         this.breadCrumb = new JLabel(path);
+        this.parent =  parentComponent;
+        parentPreview = this.getScaledImageOfComponent(parentComponent, 1f);
         // this.add(breadCrumb);
         scalediv20 = model.getScale() / 20;
 
         // Cps objecte aus dem border links schieben
-        upperNode.setLeftBorder((int) (50 + scalediv20 + scalediv20 + 10));
+        upperNode.setLeftBorder(/*(int) (50 + scalediv20 + scalediv20 + 10)*/ 0);
         for (AbstractCpsObject cps : upperNode.getNodes()) {
             if (cps.getPosition().x < model.getScaleDiv2() + upperNode.getLeftBorder() + 5) {
                 cps.setPosition(
@@ -138,8 +154,8 @@ public class UpperNodeCanvas extends AbstractCanvas implements MouseListener, Mo
                         animCps.get(i).getPosition().x = savePos.get(i).x;
                         animCps.get(i).getPosition().y = savePos.get(i).y;
                     }
-                    controller.addUpperNode("NodeOfNode", upperNode, model.getSelectedCpsObjects());
-                    controller.calculateStateForCurrentTimeStep();
+                    controller.addUpperNode("GroupNode", upperNode, model.getSelectedCpsObjects());
+                    controller.calculateStateAndVisualForCurrentTimeStep();
                     repaint();
                 }
             });
@@ -186,7 +202,7 @@ public class UpperNodeCanvas extends AbstractCanvas implements MouseListener, Mo
                         animCps.get(i).getPosition().y = savePos.get(i).y;
                     }
 
-                    controller.calculateStateForCurrentTimeStep();
+                    controller.calculateStateAndVisualForCurrentTimeStep();
                     repaint();
                 }
             });
@@ -210,12 +226,6 @@ public class UpperNodeCanvas extends AbstractCanvas implements MouseListener, Mo
                         controller.addTrackingObj(o);
                         ((HolonObject) o).updateTrackingInfo();
                     }
-                    if (model.getShowConsoleLog()) {
-                        controller.addTextToConsole("Tracking: ", Color.BLACK, 12, false, false, false);
-                        controller.addTextToConsole("" + o.getName(), Color.BLUE, 12, true, false, false);
-                        controller.addTextToConsole(", ID:", Color.BLACK, 12, false, false, false);
-                        controller.addTextToConsole("" + o.getId(), Color.RED, 12, true, false, true);
-                    }
                 }
             }
         });
@@ -334,264 +344,338 @@ public class UpperNodeCanvas extends AbstractCanvas implements MouseListener, Mo
         this.addMouseMotionListener(this);
     }
 
-    /**
-     * Paints all Components on the Canvas.
-     *
-     * @param g Graphics
-     */
-    public void paintComponent(Graphics g) {
-        String maxCap = null;
-        super.paintComponent(g);
-        ((JScrollPane) this.getParent().getParent()).setColumnHeaderView(breadCrumb);
-        // Rendering
-        g2 = (Graphics2D) g;
-        RenderingHints rh = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
-        g2.setRenderingHints(rh);
-
-        // Paint the Background
-        if (!upperNode.getImagePath().isEmpty()) {
-            img = new ImageIcon(upperNode.getImagePath()).getImage();
-            switch (upperNode.getBackgroundMode()) {
-                case BackgroundPopUp.IMAGE_PIXELS:
-                    g2.drawImage(img, upperNode.getLeftBorder(), 0, img.getWidth(null), img.getHeight(null), null);
-                    break;
-                case BackgroundPopUp.STRETCHED:
-                    g2.drawImage(img, upperNode.getLeftBorder(), 0, model.getCanvasX(), model.getCanvasY(), null);
-                    break;
-                case BackgroundPopUp.CUSTOM:
-                    g2.drawImage(img, upperNode.getLeftBorder(), 0, upperNode.getImageWidht(), upperNode.getImageHeight(),
-                            null);
-                    break;
-                default:
-                    break;
-            }
-        }
-
-        // Draw Left Border
-        g2.setColor(new Color(230, 230, 230));
-        g2.fillRect(0, 0, upperNode.getLeftBorder(), this.getHeight());
-        g2.setColor(Color.BLACK);
-        g2.drawLine(0, 0, this.getWidth(), 0);
-
-        // Test SubNet Coloring
-        int i = 0;
-        for (SubNet s : controller.getSimManager().getSubNets()) {
-
-            if (model.getSubNetColors().size() - 1 < i) {
-                controller.addSubNetColor(new Color((int) (Math.random() * 255), (int) (Math.random() * 255),
-                        (int) (Math.random() * 255)));
-            }
-
-            for (HolonObject cps : s.getObjects()) {
-                cps.setBorderColor(model.getSubNetColors().get(i));
-            }
-            i++;
-        }
-
-        // drawEdges that is being dragged
-        if (drawEdge) {
-            g2.setColor(Color.BLACK);
-            g2.setStroke(new BasicStroke(2));
-
-            // If TempCps is an outside Object
-            if (!upperNode.getNodes().contains(tempCps)) {
-                int count = 0;
-                for (CpsEdge e : upperNode.getConnections()) {
-                    if (e.getA().equals(tempCps)) {
-                        g2.drawLine(upperNode.getLeftBorder() >> 1, (int) (model.getScaleDiv2() + scalediv20 + 5
-                                + (model.getScale() + scalediv20 + 10) * count), x, y);
-                    } else if (e.getB().equals(tempCps)) {
-                        g2.drawLine(upperNode.getLeftBorder() >> 1, (int) (model.getScaleDiv2() + scalediv20 + 5
-                                + (model.getScale() + scalediv20 + 10) * count), x, y);
-                    }
-                    count++;
-                }
-            } else {
-                g2.drawLine(tempCps.getPosition().x, tempCps.getPosition().y, x, y);
-            }
-        }
-        // draw Edges
-        for (CpsEdge con : upperNode.getNodeEdges()) {
-            maxCap = paintEdge(con, maxCap);
-        }
-
-        // Objects connected to upperNode
-        int count = 0;
-        for (CpsEdge e : upperNode.getConnections()) {
-            AbstractCpsObject cps;
-            if (e.getA().equals(this.upperNode)) {
-                cps = e.getB();
-            } else {
-                cps = e.getA();
-            }
-            // Show and Highlight
-            if (model.getSelectedCpsObjects().contains(cps) || showedInformation[4]) {
-                for (CpsEdge ed : cps.getConnections()) {
-                    AbstractCpsObject obj = null;
-                    if (upperNode.getNodes().contains(ed.getA())) {
-                        obj = ed.getA();
-                    } else if (upperNode.getNodes().contains(ed.getB())) {
-                        obj = ed.getB();
-                    }
-                    if (obj != null) {
-                        if (ed.getConnected() == 0) {
-
-                            setEdgeState(ed);
-
-                            if (ed.getA().getId() == model.getSelectedObjectID()
-                                    || ed.getB().getId() == model.getSelectedObjectID() || edgeHighlight == ed)
-                                g2.setColor(Color.BLUE);
-                        } else {
-                            g2.setColor(Color.DARK_GRAY);
-                            g2.setStroke(new BasicStroke(2));
-                        }
-                        g2.drawLine(obj.getPosition().x, obj.getPosition().y, (upperNode.getLeftBorder() >> 1),
-                                (int) (scalediv20 + 5 + (50 + scalediv20 + 10) * count) + 25);
-                        if (showedInformation[0]) {
-
-                            maxCap = setCapacityString(ed, maxCap);
-
-                            if (ed.getConnected() == 0 || ed.getConnected() == 1) {
-                                g2.drawString(ed.getFlow() + "/" + maxCap,
-                                        (obj.getPosition().x + (upperNode.getLeftBorder() >> 1)) / 2,
-                                        (obj.getPosition().y + (int) (scalediv20 + 5 + (50 + scalediv20 + 10) * count)
-                                                + 25) / 2);
-                            } else {
-                                g2.drawString("not connected",
-                                        (obj.getPosition().x + (upperNode.getLeftBorder() >> 1)) / 2,
-                                        (obj.getPosition().y + (int) (scalediv20 + 5 + (50 + scalediv20 + 10) * count)
-                                                + 25) / 2);
-                            }
-                        }
-                    }
-                }
-            }
-
-            // Border Highlighting
-            if (showedInformation[3]) {
-                g2.setColor(cps.getBorderColor());
-                if (g2.getColor() != Color.WHITE) {
-                    g2.fillRect((int) ((upperNode.getLeftBorder() >> 1) - 25 - scalediv20) - 3,
-                            (int) (scalediv20 + 5 + (25 + scalediv20 + 10) * count - scalediv20) - 3,
-                            (int) (50 + ((scalediv20 + 3) * 2)), (int) (50 + ((scalediv20 + 3) * 2)));
-                }
-            }
-
-            // node image
-            if (cps instanceof CpsNode && (cps == tempCps || model.getSelectedCpsObject() == cps
-                    || model.getSelectedCpsObjects().contains(cps) || tempSelected.contains(cps))) {
-            	img = Util.loadImage("/Images/node_selected.png");
-            } else {
-                if (cps instanceof HolonSwitch) {
-                    if (((HolonSwitch) cps).getState(model.getCurIteration())) {
-                        ((HolonSwitch) cps).setAutoState(true);
-                    } else {
-                        ((HolonSwitch) cps).setAutoState(false);
-                    }
-                }
-                // Highlighting
-                if ((cps == tempCps && model.getSelectedCpsObjects().size() == 0 && tempSelected.size() == 0)
-                        || model.getSelectedCpsObjects().contains(cps) || tempSelected.contains(cps)) {
-                    g2.setColor(Color.BLUE);
-                    g2.fillRect((int) ((upperNode.getLeftBorder() >> 1) - 25 - scalediv20),
-                            (int) (scalediv20 + 5 + (50 + scalediv20 + 10) * count - scalediv20),
-                            (int) (50 + (scalediv20 * 2)), (int) (50 + (scalediv20 * 2)));
-                } else if (cps instanceof HolonObject) {
-                    g2.setColor(((HolonObject) cps).getColor());
-
-                    g2.fillRect((int) ((upperNode.getLeftBorder() >> 1) - 25 - scalediv20),
-                            (int) (scalediv20 + 5 + (50 + scalediv20 + 10) * count - scalediv20),
-                            (int) (50 + (scalediv20 * 2)), (int) (50 + (scalediv20 * 2)));
-                }
-                // draw image
-                File checkPath = new File(cps.getImage());
-                if (checkPath.exists()) {
-                    img = new ImageIcon(cps.getImage()).getImage();
-                } else {
-                	img = Util.loadImage(cps.getImage());
-                }
-            }
-            g2.drawImage(img, (upperNode.getLeftBorder() >> 1) - 25,
-                    (int) (scalediv20 + 5 + (50 + scalediv20 + 10) * count), 50, 50, null);
-            count++;
-        }
-        // Highlighted Edge
-        if (model.getSelectedObjectID() > 0 || !model.getSelectedCpsObjects().isEmpty() || !tempSelected.isEmpty()) {
-            g2.setColor(Color.BLUE);
-            for (CpsEdge con : upperNode.getNodeEdges()) {
-                if (con.getFlow() <= con.getCapacity()) {
-                    g2.setStroke(new BasicStroke(Math.min((con.getFlow() / con.getCapacity() * 3) + 1, 4)));
-                } else {
-                    g2.setStroke(new BasicStroke(2));
-                }
-
-                maxCap = drawEdgeLine(con, maxCap);
-            }
-        } else if (edgeHighlight != null) {
-            g2.setColor(Color.BLUE);
-            if (edgeHighlight.getFlow() <= edgeHighlight.getCapacity()) {
-                g2.setStroke(
-                        new BasicStroke(Math.min((edgeHighlight.getFlow() / edgeHighlight.getCapacity() * 3) + 1, 4)));
-            } else {
-                g2.setStroke(new BasicStroke(2));
-            }
-            if (upperNode.getNodeEdges().contains(edgeHighlight)) {
-                g2.drawLine(edgeHighlight.getA().getPosition().x, edgeHighlight.getA().getPosition().y,
-                        edgeHighlight.getB().getPosition().x, edgeHighlight.getB().getPosition().y);
-
-                maxCap = setCapacityString(edgeHighlight, maxCap);
-
-                if (showedInformation[0]) {
-                    g2.drawString(edgeHighlight.getFlow() + "/" + maxCap,
-                            (edgeHighlight.getA().getPosition().x + edgeHighlight.getB().getPosition().x) / 2,
-                            (edgeHighlight.getA().getPosition().y + edgeHighlight.getB().getPosition().y) / 2);
-                }
-            }
-        }
-
-
-        //Draw ReplaceHighlight
-        highlightMayBeReplaced(g2);
-        
-        // Objects in upper node
-        for (AbstractCpsObject cps : upperNode.getNodes()) {
-            // Border Highlighting
-            if (showedInformation[3]) {
-                g2.setColor(cps.getBorderColor());
-                if (g2.getColor() != Color.WHITE) {
-                    g2.fillRect((int) (cps.getPosition().x - controller.getScaleDiv2() - scalediv20 - 3),
-                            (int) (cps.getPosition().y - model.getScaleDiv2() - scalediv20 - 3),
-                            (int) (controller.getScale() + ((scalediv20 + 3) * 2)),
-                            (int) (controller.getScale() + ((scalediv20 + 3) * 2)));
-                }
-            }
-
-            setEdgePictureAndHighlighting(cps);
-
-            g2.drawImage(img, cps.getPosition().x - model.getScaleDiv2(), cps.getPosition().y - model.getScaleDiv2(),
-                    controller.getScale(), controller.getScale(), null);
-            paintSupplyBar(g2,cps);
-        }
-        
-        // Dragged marker Highlighting
-        g2.setStroke(new BasicStroke(1));
-        if (doMark) {
-            g2.setColor(Color.BLACK);
-            drawMarker();
+	/**
+	 * Paints all Components on the Canvas.
+	 *
+	 * @param g
+	 *            Graphics
+	 */
+	
+	private Color getStateColor(HolonObjectState state) {
+		switch(state) {
+		case NOT_SUPPLIED:
+			return new Color(230, 120, 100);
+		case NO_ENERGY:
+			return Color.white;
+		case OVER_SUPPLIED:
+			return new Color(166, 78, 229);
+		case PARTIALLY_SUPPLIED:
+			return Color.yellow;
+		case PRODUCER:
+			return Color.lightGray;
+		case SUPPLIED:
+			return new Color(13, 175, 28);
+		default:
+			return Color.BLACK;
+		}
+	}
+	private void paintCanvasObject(Graphics2D g, DecoratedHolonObject decoratedHolonObject){
+		Position pos = decoratedHolonObject.getModel().getPosition();
+		Color statecolor = getStateColor(decoratedHolonObject.getState());
+		g.setColor(statecolor);
+		g.fillRect(pos.x - controller.getScaleDiv2(), pos.y - controller.getScaleDiv2(), controller.getScale(), controller.getScale());
+		drawCanvasObject(g, decoratedHolonObject.getModel().getImage(), pos);
+	}
+	private void drawCanvasObjectString(Graphics2D g, Position posOfCanvasObject, float energy) {
+		g.setColor(Color.BLACK);
+		g.setFont(new Font("TimesNewRoman", Font.PLAIN, (int) (controller.getScale() / 4f) )); 
+		g.drawString((energy > 0)? "+" + Float.toString(energy): Float.toString(energy), posOfCanvasObject.x - controller.getScaleDiv2(), posOfCanvasObject.y - controller.getScaleDiv2() - 1);
+	}
+	private void paintConsumer(Graphics2D g, Consumer con){
+		paintCanvasObject(g, con);
+		paintSupplyBar(g,con.getSupplyBarPercentage(), getStateColor(con.getState()), con.getModel().getPosition());
+		drawCanvasObjectString(g, con.getModel().getPosition(), -con.getEnergyNeededFromNetwork());
+	}
+	private void paintSupplier(Graphics2D g, Supplier sup){
+		paintCanvasObject(g, sup);
+		drawCanvasObjectString(g, sup.getModel().getPosition(), sup.getEnergyToSupplyNetwork());
+	}
+	
+	private void drawCanvasObject(Graphics2D g, String Image, Position pos) {
+		g.drawImage(Util.loadImage(Image, controller.getScale(), controller.getScale()) , 
+				pos.x - controller.getScaleDiv2(),
+				pos.y - controller.getScaleDiv2(),
+				controller.getScale(), controller.getScale() , null);
+	}
+	
+	private void paintCable(Graphics2D g, DecoratedCable cable, boolean isSelected)
+	{
+		Position start = cable.getModel().getA().getPosition();
+		Position end =  cable.getModel().getB().getPosition();
+		float currentEnergy = cable.getFlowEnergy();
+		float capacity = cable.getModel().getCapacity();
+		boolean unlimited = cable.getModel().isUnlimitedCapacity();
+		switch(cable.getState()) {
+		case Burned:
+			g.setColor(Color.RED);
+			g.setStroke(new BasicStroke(2));
+			break;
+		case Working:
+			g.setColor(new Color(13, 175, 28));
+			g.setStroke(new BasicStroke(unlimited?2f:(currentEnergy / capacity * 2f) + 1));
+			break;
+		}
+		if(isSelected){
+			g.setColor(Color.lightGray);
+		}
+		g.drawLine(start.x, start.y, end.x, end.y);
+		Position middle = new Position((start.x + end.x) / 2, (start.y + end.y) / 2);
+		g.setFont(new Font("TimesRoman", Font.PLAIN, Math.max((int) (controller.getScale() / 3.5f), 10) )); 
+		g.drawString(currentEnergy + "/" + (unlimited?"\u221E":capacity) , middle.x, middle.y);
+	}
+	private void paintSwitch(Graphics2D g, DecoratedSwitch dSwitch)
+	{
+		drawCanvasObject(g, dSwitch.getState() == SwitchState.Open ? HolonSwitch.getSwitchOpenImage(): HolonSwitch.getSwitchClosedImage() , dSwitch.getModel().getPosition());
+	}
+	private void paintGroupNode(Graphics2D g, DecoratedGroupNode dGroupNode) {
+		Position pos = dGroupNode.getModel().getPosition();
+		g.setColor(Color.lightGray);
+		g.fillRect(pos.x - controller.getScaleDiv2(), pos.y - controller.getScaleDiv2(), controller.getScale(), controller.getScale());
+		drawCanvasObject(g, "/Images/upper_node.png" , pos);
+		paintGroupNodeBar(g, dGroupNode, pos);
+	}
+	private void paintGroupNodeBar(Graphics2D g, DecoratedGroupNode dGroupNode , Position pos) {
+		// +1, -2, -1 little Adjustment for pixel perfect alignment
+		int barWidth = (int) (controller.getScale());
+		int barHeight = (int) (controller.getScale() / 5);
+		g.setColor(Color.WHITE);
+		g.fillRect(pos.x - controller.getScaleDiv2(), pos.y + controller.getScaleDiv2() - 1, (int) barWidth, barHeight);
+		float[] percentages = getGroupNodeBarPercentages(dGroupNode);
+		Color[] colors = new Color[6];
+		colors[0] = getStateColor(HolonObjectState.PRODUCER);
+		colors[1] = getStateColor(HolonObjectState.NOT_SUPPLIED);
+		colors[2] = getStateColor(HolonObjectState.PARTIALLY_SUPPLIED);
+		colors[3] = getStateColor(HolonObjectState.SUPPLIED);
+		colors[4] = getStateColor(HolonObjectState.OVER_SUPPLIED);
+		colors[5] = getStateColor(HolonObjectState.NO_ENERGY);
+				
+		for(int i = 5; i>=0; i--) {
+			g.setColor(colors[i]);
+			g.fillRect(pos.x - controller.getScaleDiv2(), pos.y + controller.getScaleDiv2() - 1, (int) (barWidth * percentages[i] - 1), barHeight);		
+		}
+//		g.setColor(color);
+//		g.fillRect(pos.x - controller.getScaleDiv2(), pos.y + controller.getScaleDiv2() - 1, (int) (barWidth * (percentage < 1 ? percentage : 1.0f) - 1), barHeight);
+		g.setColor(Color.BLACK);
+		g.setStroke(new BasicStroke(1));
+		g.drawRect(pos.x - controller.getScaleDiv2(), pos.y + controller.getScaleDiv2() - 1, barWidth - 1 , barHeight);
+	}
+	/**
+	 * HardCoded Stuff dont try at Home ;)
+	 * @param dGroupNode
+	 * @return
+	 */
+	public float[] getGroupNodeBarPercentages(DecoratedGroupNode dGroupNode) {
+		int[] amountOfObjects = new int[6];
+		amountOfObjects[0] = dGroupNode.getAmountOfSupplier();
+		amountOfObjects[1] = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.NOT_SUPPLIED);
+		amountOfObjects[2] = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.PARTIALLY_SUPPLIED);
+		amountOfObjects[3] = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.SUPPLIED);
+		amountOfObjects[4] = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.OVER_SUPPLIED);
+		amountOfObjects[5] = dGroupNode.getAmountOfPassiv();
+		int countHolonObjects = amountOfObjects[0] + 	amountOfObjects[1] + amountOfObjects[2] + amountOfObjects[3] + amountOfObjects[4] + amountOfObjects[5];
+		float[] percentages = new float[6];
+		int count = 0;
+		for(int i = 0; i < 6; i++) {
+			count += amountOfObjects[i];
+			percentages[i] = (float)count / (float)countHolonObjects;
+		}
+		return percentages;
+	}
+	private void paintExitCable(Graphics2D g, ExitCable eCable) {
+		Position start = eCable.getStart().getPosition();
+		Position end = eCable.getFinish().getPosition();
+		float currentEnergy = eCable.getCable().getFlowEnergy();
+		float capacity = eCable.getCable().getModel().getCapacity();
+		boolean unlimited = eCable.getCable().getModel().isUnlimitedCapacity();
+		switch(eCable.getCable().getState()) {
+		case Burned:
+			g.setColor(Color.RED);
+			g.setStroke(new BasicStroke(2));
+			break;
+		case Working:
+			g.setColor(new Color(13, 175, 28));
+			g.setStroke(new BasicStroke(unlimited?2f:(currentEnergy / capacity * 2f) + 1));
+			break;
+		}
+		switch(eCable.getState()) {
+		case DOWN:
+		case DOWNDOWN:
+			g.drawLine(start.x, start.y, end.x, end.y);
+			Position middle = new Position((start.x + end.x) / 2, (start.y + end.y) / 2);
+			g.setFont(new Font("TimesRoman", Font.PLAIN, Math.max((int) (controller.getScale() / 3.5f), 10) )); 
+			g.drawString(currentEnergy + "/" + (unlimited?"\u221E":capacity) , middle.x, middle.y);
+			break;
+		case DOWNUP:
+		case UP:
+			Vector2d vStart = new Vector2d(start.x, start.y);
+			Vector2d vEnd = new Vector2d(end.x, end.y);
+			float stretchFactor = 4 * model.getScale();
+			stretchFactor =  (stretchFactor > vStart.getDistance(vEnd))? vStart.getDistance(vEnd) : stretchFactor;
+			Vector2d vPosition = vStart.add((vEnd.subtract(vStart)).normalize().multiply(stretchFactor));
+			Position result = new Position(Math.round(vPosition.getX()),Math.round(vPosition.getY()));
+			g.drawLine(start.x, start.y, result.x, result.y);
+			Position middle1 = new Position((start.x +result.x) / 2, (start.y + +result.y) / 2);
+			g.setFont(new Font("TimesRoman", Font.PLAIN, Math.max((int) (controller.getScale() / 3.5f), 10) )); 
+			g.drawString(currentEnergy + "/" + (unlimited?"\u221E":capacity) , middle1.x, middle1.y);
+			drawCanvasObject(g, "/Images/arrowUp.png" , result);
+			break;
+		default:
+			System.out.println("Error");
+			break;
+		}
+	}
+	private void paintSupplyBar(Graphics2D g, float percentage, Color color, Position pos) {
+		// +1, -2, -1 little Adjustment for pixel perfect alignment
+		int barWidth = (int) (controller.getScale());
+		int barHeight = (int) (controller.getScale() / 5);
+		g.setColor(Color.WHITE);
+		g.fillRect(pos.x - controller.getScaleDiv2(), pos.y + controller.getScaleDiv2() - 1, (int) barWidth, barHeight);
+		g.setColor(color);
+		g.fillRect(pos.x - controller.getScaleDiv2(), pos.y + controller.getScaleDiv2() - 1, (int) (barWidth * (percentage < 1 ? percentage : 1.0f) - 1), barHeight);
+		g.setColor(Color.BLACK);
+		g.setStroke(new BasicStroke(1));
+		g.drawRect(pos.x - controller.getScaleDiv2(), pos.y + controller.getScaleDiv2() - 1, barWidth - 1 , barHeight);
+		g.setFont(new Font("TimesNewRoman", Font.PLAIN, (int) (barHeight * 1.5) - 2)); 
+		String percentageString = (Math.round((percentage * 100))) + "%";
+		int stringWidth = (int) g.getFontMetrics().getStringBounds(percentageString, g).getWidth();
+		if(percentage > 1.0f) g.setColor(Color.WHITE); //Just to see better on purple
+		g.drawString(percentageString, pos.x + 1 - stringWidth / 2, pos.y + controller.getScaleDiv2() - 1+ barHeight);
+		
+	}
+	
+	//old code
+	void drawMarker(Graphics2D g) {
+		Color transparentGrey = new Color(128, 174, 247, 40);
+		if (sx > x && sy > y) {
+			g.drawRect(x, y, sx - x, sy - y);
+			g.setColor(transparentGrey);
+			g.fillRect(x, y, sx - x, sy - y);
+		} else if (sx < x && sy < y) {
+			g.drawRect(sx, sy, x - sx, y - sy);
+			g.setColor(transparentGrey);
+			g.fillRect(sx, sy, x - sx, y - sy);
+		} else if (sx >= x) {
+			g.drawRect(x, sy, sx - x, y - sy);
+			g.setColor(transparentGrey);
+			g.fillRect(x, sy, sx - x, y - sy);
+		} else if (sy >= y) {
+			g.drawRect(sx, y, x - sx, sy - y);
+			g.setColor(transparentGrey);
+			g.fillRect(sx, y, x - sx, sy - y);
+		}
+	}
+   private BufferedImage getScaledImageOfComponent(Component component, double scale) {
+            BufferedImage bi = new BufferedImage(
+                (int)(component.getWidth()*scale),
+                (int)(component.getHeight()*scale),
+                BufferedImage.TYPE_INT_RGB);
+            Graphics2D gNew = bi.createGraphics();
+            gNew.scale(scale, scale);
+            component.paint(gNew);
+            gNew.dispose();
+
+            return bi;
         }
+	public void paintComponent(Graphics g) {		
+		super.paintComponent(g);
+		Graphics2D g2d = (Graphics2D) g;
+		g2d.setRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING,
+				RenderingHints.VALUE_ANTIALIAS_ON));
+		//-->Old code
+		if (drawEdge) {
+			g2d.setColor(Color.BLACK);
+			g2d.setStroke(new BasicStroke(1));
+			g2d.drawLine(tempCps.getPosition().x, tempCps.getPosition().y, x, y);
+		}
+		//<--
+		//SelectedCable
+		HashSet<CpsEdge> selectedEdges = new HashSet<CpsEdge>();
+		for(AbstractCpsObject aCps:  model.getSelectedCpsObjects()) {
+			for(CpsEdge edge: aCps.getConnections()) {
+				selectedEdges.add(edge);
+			}
+		}
+		if(model.getSelectedEdge() != null) selectedEdges.add(model.getSelectedEdge());
 
-        // Border Line
-        g2.setColor(Color.BLACK);
-        g2.drawLine(upperNode.getLeftBorder(), 0, upperNode.getLeftBorder(), this.getHeight());
+		
+		DecoratedGroupNode  actualGroupNode = controller.getSimManager().getActualVisualRepresentationalState().getCreatedGroupNodes().get(upperNode);
+		//VisualState Representation:
+		for(ExitCable cable : actualGroupNode.getExitCableList()) {
+			paintExitCable(g2d, cable);
+		}
+		for(DecoratedCable cable : actualGroupNode.getInternCableList()) {
+			paintCable(g2d, cable, selectedEdges.contains(cable.getModel()));
+		}
+	
+		
+		for(DecoratedGroupNode dGroupNode : actualGroupNode.getGroupNodeList()) {
+			paintGroupNode(g2d, dGroupNode);
+		}
+		for(Consumer con: actualGroupNode.getConsumerList()) {
+			paintConsumer(g2d, con);					
+		}
+		for(Supplier sup: actualGroupNode.getSupplierList()) {
+			paintSupplier(g2d, sup);				
+		}
+		for(Passiv pas: actualGroupNode.getPassivList()) {
+			paintCanvasObject(g2d, pas);
+		}
+		for(DecoratedSwitch dSwitch : actualGroupNode.getSwitchList()) {
+				paintSwitch(g2d, dSwitch);
+		}
+		for(CpsNode node : actualGroupNode.getNodeList()) {
+			drawCanvasObject(g2d, "/Images/node.png" , node.getPosition());
+		}
+		
+		//-->oldCode 
+		if (doMark) {
+			g2d.setColor(Color.BLACK);
+			g2d.setStroke(new BasicStroke(0));
+			drawMarker(g2d);
+		}
+		//Test Selection
+		//Objects:
+		g2d.setColor(Color.BLUE);
+		g2d.setStroke(new BasicStroke(1));
+		Color transparentGrey = new Color(128, 174, 247, 40);
+		for(AbstractCpsObject aCps:  model.getSelectedCpsObjects()) {
+			if(aCps instanceof CpsNode) {
+				Position pos = aCps.getPosition();
+				g2d.setColor(transparentGrey);
+				g2d.fillOval(pos.x - (int) (controller.getScaleDiv2()), pos.y - (int) (controller.getScaleDiv2()),  controller.getScale(),  controller.getScale());
+				g2d.setColor(Color.LIGHT_GRAY);
+				g2d.setStroke(new BasicStroke(2));
+				g2d.drawOval(pos.x - (int) (controller.getScaleDiv2()), pos.y - (int) (controller.getScaleDiv2()),  controller.getScale(),  controller.getScale());
+			}
+			else {
+				Position pos = aCps.getPosition();
+				g2d.setColor(transparentGrey);
+				g2d.fillRect(pos.x - (int) (controller.getScaleDiv2()* 1.5f), pos.y - (int) (controller.getScaleDiv2()* 1.5f), (int) (controller.getScale()* 1.5f) , (int) (controller.getScale()* 1.5f));
+				g2d.setColor(Color.LIGHT_GRAY);
+				g2d.setStroke(new BasicStroke(2));
+				g2d.drawRect(pos.x - (int) (controller.getScaleDiv2()* 1.5f), pos.y - (int) (controller.getScaleDiv2()* 1.5f), (int) (controller.getScale()* 1.5f) , (int) (controller.getScale()* 1.5f));				
+			}
 
-        // Tooltip
-        showTooltip(g);
-    }
+		}
+		//maybeReplace:
+		if(mayBeReplaced != null){
+			g2d.setColor(Color.RED);
+			Position pos = mayBeReplaced.getPosition();
+			g.drawImage(Util.loadImage("/Images/replace.png") , 
+					pos.x + controller.getScaleDiv2(),
+					pos.y - controller.getScale(),
+					controller.getScaleDiv2(), controller.getScaleDiv2(), null);
+		}
+		//<-- OldCode
+	}
+   
 
     @Override
     public void mouseClicked(MouseEvent e) {
+    	if(!disable){
         triggerUpdateController();
         stopEditing();
+    	}
     }
 
     @Override
@@ -604,6 +688,7 @@ public class UpperNodeCanvas extends AbstractCanvas implements MouseListener, Mo
 
     @Override
     public void mousePressed(MouseEvent e) {
+    	if(!disable){
     	stopEditing();
         tempCps = null;
         dataSelected = null;
@@ -626,7 +711,6 @@ public class UpperNodeCanvas extends AbstractCanvas implements MouseListener, Mo
                 if (x - controller.getScale() <= cx && y - controller.getScale() <= cy && x >= cx && y >= cy) {
                     tempCps = cps;
 
-                    setConsoleTextAfterSelect(cps);
 
                     dragging = true;
                     if (e.isControlDown() && tempCps != null) {
@@ -666,13 +750,6 @@ public class UpperNodeCanvas extends AbstractCanvas implements MouseListener, Mo
                         && x >= (upperNode.getLeftBorder() >> 1) - model.getScaleDiv2()
                         && y >= (scalediv20 + 5 + (model.getScale() + scalediv20 + 10) * count)) {
                     tempCps = cps;
-                    if (model.getShowConsoleLog()) {
-                        controller.addTextToConsole("Selected: ", Color.BLACK, 12, false, false, false);
-                        controller.addTextToConsole("" + cps.getName(), Color.BLUE, 12, true, false, false);
-                        controller.addTextToConsole(", ID:", Color.BLACK, 12, false, false, false);
-                        controller.addTextToConsole("" + cps.getId(), Color.RED, 12, true, false, true);
-                        controller.setSelectedObjectID(tempCps.getId());
-                    }
                     // If drawing an Edge (CTRL down)
                     if (tempCps.getClass() == HolonObject.class) {
                         HolonObject tempObj = ((HolonObject) tempCps);
@@ -713,10 +790,12 @@ public class UpperNodeCanvas extends AbstractCanvas implements MouseListener, Mo
             // }
             repaint();
         }
+    	}
     }
 
     @Override
     public void mouseReleased(MouseEvent e) {
+    	if(!disable){
         x = e.getX();
         y = e.getY();
         dragging = false;
@@ -776,14 +855,15 @@ public class UpperNodeCanvas extends AbstractCanvas implements MouseListener, Mo
             ((HolonSwitch) tempCps).switchState();
         }
 
-        controller.calculateStateForTimeStep(model.getCurIteration());
+        controller.calculateStateAndVisualForTimeStep(model.getCurIteration());
         triggerUpdateController();
         repaint();
-
+    	}
     }
 
     @Override
     public void mouseDragged(MouseEvent e) {
+    	if(!disable){
         // If Edge is drawn
         x = e.getX();
         y = e.getY();
@@ -852,10 +932,11 @@ public class UpperNodeCanvas extends AbstractCanvas implements MouseListener, Mo
                 if(model.getSelectedCpsObjects().size()==1)
                 	checkForReplacement(upperNode.getNodes(), tempCps, x, y);
 
-                repaint();
+               repaint();
             } catch (Exception eex) {
 
             }
+        	
         }
 
         // Mark Objects
@@ -910,14 +991,14 @@ public class UpperNodeCanvas extends AbstractCanvas implements MouseListener, Mo
         }
 
         repaint();
-
+    	}
     }
 
     @Override
     public void mouseMoved(MouseEvent e) {
+    	{
         x = e.getX();
         y = e.getY();
-
         // Everything for the tooltip :)
         boolean on = false;
         for (AbstractCpsObject cps : upperNode.getNodes()) {
@@ -952,6 +1033,7 @@ public class UpperNodeCanvas extends AbstractCanvas implements MouseListener, Mo
 
         toolTip = on;
         repaint();
+    	}
     }
 
     /**
@@ -997,12 +1079,32 @@ public class UpperNodeCanvas extends AbstractCanvas implements MouseListener, Mo
                         deleteNode = true;
                     }
                 } else {
-                    e = new CpsEdge(cps, tempCps, model.getMaxCapacity());
-                    if (outsideCon) {
-                        controller.connectNodes(e, upperNode);
-                    } else {
-                        controller.addEdgeUpperNode(e, upperNode);
-                    }
+                	if(!(cps instanceof CpsUpperNode || tempCps instanceof CpsUpperNode)) {
+						e = new CpsEdge(cps, tempCps, model.getMaxCapacity());
+						if (outsideCon) {
+							controller.connectNodes(e, upperNode);
+						} else {
+							controller.addEdgeUpperNode(e, upperNode);
+						}
+					}else if (cps instanceof CpsUpperNode && !(tempCps instanceof CpsUpperNode)){
+						CpsUpperNode thisUpperNode = (CpsUpperNode)cps;
+						Object[] possibilities = thisUpperNode.getNodes().stream().map(aCps -> new ACpsHandle(aCps)).filter(aCpsHandle -> !(aCpsHandle.object instanceof CpsUpperNode)).toArray();
+						if(possibilities.length != 0) {
+							ACpsHandle selected = (ACpsHandle) JOptionPane.showInputDialog(this, "Select a inside Object:", "Connection To?",  JOptionPane.OK_OPTION,new ImageIcon(new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB)) , possibilities, "");
+							if(selected != null) {
+								e = new CpsEdge(selected.object, tempCps, model.getMaxCapacity());
+								controller.addEdgeUpperNode(e, (CpsUpperNode)cps);
+							}
+						}else {
+							CpsNode n = new CpsNode("Node");
+
+							n.setPosition(x, y);
+							controller.addObjUpperNode(n, thisUpperNode);
+							e = new CpsEdge(n, tempCps, model.getMaxCapacity());
+							controller.addEdgeUpperNode(e, (CpsUpperNode)cps);
+						}
+						
+					}
                 }
             }
         }
@@ -1203,23 +1305,7 @@ public class UpperNodeCanvas extends AbstractCanvas implements MouseListener, Mo
         return null;
     }
 
-//    /**
-//     * sets the Edge Capacity.
-//     *
-//     * @param cap capacity
-//     */
-//    public void setEdgeCapacity(float cap) {
-//        controller.setMaxCapacity(cap);
-//    }
-
-//    /**
-//     * Returns if Information should be shown.
-//     *
-//     * @return Array of boolean [0] = connection, [1] = objects
-//     */
-//    public boolean[] getShowedInformation() {
-//        return showedInformation;
-//    }
+
 
     /**
      * copies a set of given informations
@@ -1230,17 +1316,6 @@ public class UpperNodeCanvas extends AbstractCanvas implements MouseListener, Mo
         showedInformation = informations;
     }
 
-//    /**
-//     * Set the Background Image;
-//     *
-//     * @param imagePath Image Path
-//     * @param mode      Image Mode
-//     * @param width     Image custom width
-//     * @param height    Image custom height
-//     */
-//    public void setBackgroundImage(String imagePath, int mode, int width, int height) {
-//        upperNode.setBackgroundImage(imagePath, mode, width, height);
-//    }
 
     /**
      * set tooltIp

+ 11 - 58
tests/tests/PraktikumHolonsTestClasses.java

@@ -60,48 +60,21 @@ public class PraktikumHolonsTestClasses {
 		arr.add(ele);
 		arr.add(ele);
 		assertTrue("Should be Empty", test2.getElements().isEmpty());
-		assertTrue("Current Energy not corrent", test2.getMaxActiveEnergy() == 0);
+
 		test2.setElements(arr);
 		assertTrue("Should not be Empty", !test2.getElements().isEmpty());
-		assertTrue("Current Energy not corrent", test2.getMaxActiveEnergy() == 20);
-		assertTrue("Current Energy not corrent", test2.getCurrentEnergyAtTimeStep(20) == 20);
+
+		assertTrue("Current Energy not corrent", test2.getEnergyAtTimeStep(20) == 20);
 		String str = test2.toStringElements();
 		assertTrue("String not corrent", str.equals("Element, Element"));
 		test2.deleteElement(0);
 		test2.addElement(ele);
-		assertTrue("Current Energy not corrent", test2.getMaxActiveEnergy() == 20);
+
 		assertTrue("Should be Empty", test3.getElements().isEmpty());
 		test3.setElements(test2.copyElements(test2.getElements()));
-		assertTrue("Should be Empty", !test3.getElements().isEmpty());
-		assertTrue("Should be state 0", test3.getState() == 0);
-		test3.setState(1);
-		assertTrue("Should be state 1", test3.getState() == 1);
-		test3.setState(2);
-		assertTrue("Should be state 2", test3.getState() == 2);
-		test3.setState(3);
-		assertTrue("Should be state 3", test3.getState() == 3);
-		test3.setState(4);
-		assertTrue("Should be state 4", test3.getState() == 4);
+		
 		assertTrue("Element not Found", test3.searchElement("Element") != null);
 		test1.setElements(new ArrayList<>());
-		assertTrue("Not Empty", !test1.checkIfPartiallySupplied(1));
-		test3.addElement(new HolonElement("Element2", 1, -10, IdCounterElem.nextId(),null));
-		assertTrue("Not Partially Supplied", test3.checkIfPartiallySupplied(1));
-		test3.addElement(new HolonElement("Element2", 2, -10, IdCounterElem.nextId(),null));
-		assertTrue("Not Partially Supplied", test3.checkIfPartiallySupplied(1));
-		test1.addElement(new HolonElement("Element2", 2, -10, IdCounterElem.nextId(),null));
-		assertTrue("minSupply < 0", !test1.checkIfPartiallySupplied(1));
-		Color color = test3.getColor();
-		test3.setColor(new Color(0, 255, 255));
-		assertTrue(color.getBlue() != test3.getColor().getBlue());
-		test3.addElement(new HolonElement("Element3", 3, 50, IdCounterElem.nextId(),null));
-		test3.setState();
-		assertTrue("Should be state 3", test3.getState() == 3);
-		test1.setState();
-		assertTrue("Should be state 0", test1.getState() == 0);
-		test2.setState();
-		test2.setBorderColor(color);
-		assertTrue("Color not Same", color == test2.getBorderColor());
 	}
 
 	/**
@@ -143,29 +116,10 @@ public class PraktikumHolonsTestClasses {
 		CpsEdge edge1 = new CpsEdge(node1, node2, 100);
 		CpsEdge edge2 = new CpsEdge(node2, node3);
 
-		assertTrue("Flow not 0", edge1.getFlow() == 0);
-		edge1.setFlow(50);
-		assertTrue("Capacity not right", edge1.getCapacity() == 100);
-		edge2.setFlow(50);
-		edge1.setCapacity(200);
-		assertTrue("Flow was not changed", edge1.getFlow() == 50);
-		assertTrue("Capacity not right", edge1.getCapacity() == 200);
-        assertTrue("line broken", edge2.isWorking());
-        edge2.calculateState();
-        assertTrue("line broken", edge2.isWorking());
-        edge2.setFlow(200);
-        edge2.calculateState();
-        assertTrue("line not broken", !edge2.isWorking());
-        edge1.setCapacity(-1);
-        edge1.calculateState();
-		edge1.setCapacity(500);
-		edge1.calculateState();
 		node1 = (CpsNode) edge1.getB();
 		node2 = (CpsNode) edge2.getA();
 		assertTrue("Not Same", node1 == node2);
-        assertTrue("State not right", edge1.isWorking());
-        edge1.setWorkingState(false);
-        assertTrue("State not right", !edge1.isWorking());
+    
         edge2.setTags(new ArrayList<>());
         edge1.setTags(new ArrayList<>());
 		assertTrue("Tags not Empty", edge2.getTags().isEmpty());
@@ -181,18 +135,17 @@ public class PraktikumHolonsTestClasses {
 	 */
 	@Test
 	public void testHolonElement() {
-		HolonElement ele1 = new HolonElement("TV", 2, -20, IdCounterElem.nextId(),null);
-		HolonElement ele2 = new HolonElement("Fridge", 1, -50, IdCounterElem.nextId(),null);
-
-        assertTrue("Array not empty", ele1.getAvailableEnergyAt(0) == -20);
-        assertTrue("Array not empty", ele1.getAvailableEnergyAt(2) == -20);
+		HolonElement ele1 = new HolonElement("TV", 2, -20f, IdCounterElem.nextId(),null);
+		HolonElement ele2 = new HolonElement("Fridge", 1, -50f, IdCounterElem.nextId(),null);
+        assertTrue("Array not empty",  ele1.getEnergyAtTimeStep(0) == -40);
+        assertTrue("Array not empty", ele1.getEnergyAtTimeStep(2) == -40);
         assertTrue("Name not correct", ele1.getEleName().equals("TV"));
         ele1.setEleName(ele2.getEleName());
 		assertTrue("Name not correct", ele1.getEleName().equals("Fridge"));
 		assertTrue("Amount not correct", ele2.getAmount() == 1);
 		ele2.setAmount(5);
 		assertTrue("Amount not correct", ele2.getAmount() == 5);
-        assertTrue("Total Energy not Correct", ele2.getOverallEnergy() == ele2.getAmount() * ele2.getEnergyPerElement());
+        assertTrue("Total Energy not Correct", ele2.getMaximumEnergy() == ele2.getAmount() * ele2.getEnergyPerElement());
 	}
 	/**
 	 * Test for Position.

+ 0 - 42
tests/tests/PraktikumHolonsTestConsoleController.java

@@ -1,42 +0,0 @@
-package tests;
-
-import org.junit.Before;
-import org.junit.Test;
-
-import ui.controller.ConsoleController;
-import ui.model.Model;
-import ui.view.Console;
-
-import java.awt.Color;
-
-/**
- * Tests for the ConsoleController.
- * 
- * @author Gruppe14
- */
-public class PraktikumHolonsTestConsoleController {
-
-	protected Model model;
-	protected ConsoleController controller;
-
-	/**
-	 * Setup.
-	 */
-	@Before
-	public void setUp() {
-		model = new Model();
-		model.setConsole(new Console());
-		controller = new ConsoleController(model);
-	}
-
-	/**
-	 * Test for ConsoleController.
-	 */
-	@Test
-	public void testConsoleController() {
-		controller.addTextToConsole("Hello World");
-		controller.addTextToConsole("Hello World2!", new Color(255, 255, 255), 11, false, true, false);
-		controller.clearConsole();
-
-	}
-}

+ 1 - 3
tests/tests/PraktikumHolonsTestObjectController.java

@@ -69,9 +69,7 @@ public class PraktikumHolonsTestObjectController {
 		for (int i = 2; i < 27; i++) {
 			controller.addNewElementIntoCategoryObject("Building", "House", adapter.generate(i), i, -10);
 			// n(n+1) / 2
-			assertTrue("Total Energy does not match", ((HolonObject) mp.searchCatObj(mp.searchCat("Building"), "House"))
-					.getMaxActiveEnergy() == -1800 + ((i * (i + 1)) / 2) * -10);
-			assertTrue("Number of Elements does not Match",
+					assertTrue("Number of Elements does not Match",
 					((HolonObject) mp.searchCatObj(mp.searchCat("Building"), "House")).getElements().size() == 6 + i);
 		}
 

+ 0 - 1
tests/tests/PraktikumHolonsTestSuite.java

@@ -25,7 +25,6 @@ public class PraktikumHolonsTestSuite {
 		suite.addTest(new JUnit4TestAdapter(PraktikumHolonsTestLoadAndStoreController.class));
 		suite.addTest(new JUnit4TestAdapter(PraktikumHolonsTestGlobalController.class));
 		suite.addTest(new JUnit4TestAdapter(PraktikumHolonsTestAutoSaveController.class));
-		suite.addTest(new JUnit4TestAdapter(PraktikumHolonsTestConsoleController.class));
 		suite.addTest(new JUnit4TestAdapter(PraktikumHolonsTestClasses.class));
 		return suite;
 	}

Bu fark içinde çok fazla dosya değişikliği olduğu için bazı dosyalar gösterilmiyor