瀏覽代碼

Deleted Deprecated Classes and obsolete code solves 200+ Warnings.

Tom Troppmann 3 年之前
父節點
當前提交
3b8df5edb0
共有 100 個文件被更改,包括 9394 次插入13370 次删除
  1. 0 10
      .checkstyle
  2. 2 1
      .gitignore
  3. 0 15
      API_Instruction
  4. 0 89
      ChangelogV2_1.md
  5. 二進制
      QS-Gruppe14-FinalVersion.pdf
  6. 64 80
      README.md
  7. 0 143
      build.gradle
  8. 二進制
      gradle/wrapper/gradle-wrapper.jar
  9. 0 6
      gradle/wrapper/gradle-wrapper.properties
  10. 0 164
      gradlew
  11. 0 90
      gradlew.bat
  12. 二進制
      jars/CpsAlgorithm.jar
  13. 0 23
      settings.gradle
  14. 二進制
      slider.JPG
  15. 219 222
      src/Connection/ConnectHandheld.java
  16. 517 518
      src/Connection/ConnectPhysical.java
  17. 0 41
      src/DataSets/GraphDataSet.java
  18. 0 36
      src/DataSets/PropertyDataSet.java
  19. 0 4
      src/TypeAdapter/AbstractCpsObjectAdapter.java
  20. 0 2
      src/TypeAdapter/ColorAdapter.java
  21. 2 6
      src/TypeAdapter/PairAdapter.java
  22. 2 4
      src/TypeAdapter/PositionAdapter.java
  23. 372 372
      src/addOns/InformationPanel.java
  24. 0 18
      src/addOns/RandomOfferdFlexibility.java
  25. 3 4
      src/addOns/RandomSwitch.java
  26. 2 2
      src/addOns/Randomizer.java
  27. 177 177
      src/addOns/Utility/EmailNotification.java
  28. 42 42
      src/addOns/Utility/FlexibilitySketch.java
  29. 72 111
      src/addOns/Utility/HolonElementSketch.java
  30. 134 135
      src/addOns/Utility/RandomPriotity.java
  31. 210 213
      src/algorithm/binary/AcoAlgorithm.java
  32. 0 35
      src/algorithm/binary/BaseLine.java
  33. 251 254
      src/algorithm/binary/GaAlgorithm.java
  34. 412 415
      src/algorithm/binary/PsoAlgorithm.java
  35. 473 495
      src/algorithm/example/DemoAlgo.java
  36. 615 655
      src/algorithm/example/FlexExample.java
  37. 1 0
      src/algorithm/objectiveFunction/Evaluation.java
  38. 490 491
      src/algorithm/objectiveFunction/GraphMetrics.java
  39. 265 270
      src/algorithm/objectiveFunction/ObjectiveFunctionByCarlos.java
  40. 312 314
      src/algorithm/objectiveFunction/TopologieObjectiveFunction.java
  41. 184 190
      src/algorithm/topologie/AcoAlgorithm.java
  42. 227 233
      src/algorithm/topologie/GaAlgorithm.java
  43. 326 340
      src/algorithm/topologie/PsoAlgorithm.java
  44. 1365 1364
      src/api/AlgorithmFrameworkFlex.java
  45. 1289 1304
      src/api/TopologieAlgorithmFramework.java
  46. 0 2
      src/classes/AbstractCanvasObject.java
  47. 13 25
      src/classes/HolonBattery.java
  48. 0 2
      src/classes/HolonElement.java
  49. 0 1
      src/classes/HolonObject.java
  50. 0 2
      src/classes/HolonSwitch.java
  51. 1 0
      src/classes/IdCounter.java
  52. 8 4
      src/classes/Pair.java
  53. 0 105
      src/classes/SubNet.java
  54. 0 105
      src/classes/TrackedDataSet.java
  55. 0 19
      src/interfaces/CategoryListener.java
  56. 3 23
      src/ui/controller/CanvasController.java
  57. 0 26
      src/ui/controller/CategoryController.java
  58. 18 136
      src/ui/controller/Control.java
  59. 0 44
      src/ui/controller/GlobalController.java
  60. 0 31
      src/ui/controller/HolonCanvasController.java
  61. 0 13
      src/ui/controller/LoadController.java
  62. 1 24
      src/ui/controller/MultiPurposeController.java
  63. 1 46
      src/ui/controller/NodeController.java
  64. 0 9
      src/ui/controller/ObjectController.java
  65. 0 42
      src/ui/controller/SaveController.java
  66. 0 35
      src/ui/controller/SimulationManager.java
  67. 0 21
      src/ui/controller/SingletonControl.java
  68. 0 53
      src/ui/controller/StatsController.java
  69. 0 40
      src/ui/controller/UpdateController.java
  70. 0 5
      src/ui/model/DecoratedGroupNode.java
  71. 2 2
      src/ui/model/ExitCable.java
  72. 4 2
      src/ui/model/IntermediateCalculationCable.java
  73. 0 1
      src/ui/model/MinimumNetwork.java
  74. 27 240
      src/ui/model/Model.java
  75. 1 20
      src/ui/model/VisualRepresentationalState.java
  76. 445 432
      src/ui/view/AbstractCanvas.java
  77. 1 4
      src/ui/view/AddElementPopUp.java
  78. 539 522
      src/ui/view/AddObjectPopUp.java
  79. 4 9
      src/ui/view/AddOnWindow.java
  80. 0 1
      src/ui/view/BackgroundPopUp.java
  81. 0 5
      src/ui/view/CanvasResizePopUp.java
  82. 71 73
      src/ui/view/Console.java
  83. 3 3
      src/ui/view/CreateNewDialog.java
  84. 21 21
      src/ui/view/CreateTemplatePopUp.java
  85. 0 99
      src/ui/view/DisplayedInformationPopUp.java
  86. 16 9
      src/ui/view/EditEdgesPopUp.java
  87. 0 102
      src/ui/view/FlexSubData.java
  88. 0 115
      src/ui/view/FlexibleData.java
  89. 0 113
      src/ui/view/FlexiblePane.java
  90. 106 289
      src/ui/view/GUI.java
  91. 36 88
      src/ui/view/GroupNodeCanvas.java
  92. 0 244
      src/ui/view/HolonCanvas.java
  93. 9 20
      src/ui/view/IndexTranslator.java
  94. 0 74
      src/ui/view/LabelHint.java
  95. 2 2
      src/ui/view/Languages.java
  96. 1 3
      src/ui/view/Main.java
  97. 32 60
      src/ui/view/MyCanvas.java
  98. 1 8
      src/ui/view/Outliner.java
  99. 0 759
      src/ui/view/StatisticGraph.java
  100. 0 349
      src/ui/view/StatisticGraphPanel.java

+ 0 - 10
.checkstyle

@@ -1,10 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-
-<fileset-config file-format-version="1.2.0" simple-config="true" sync-formatter="false">
-  <local-check-config name="Checkstyle_BP" location="/home/jessey/Downloads/Checkstyle_BP" type="external" description="">
-    <additional-data name="protect-config-file" value="false"/>
-  </local-check-config>
-  <fileset name="all" enabled="true" check-config-name="BP Configuration" local="false">
-    <file-match-pattern match-pattern="." include-pattern="true"/>
-  </fileset>
-</fileset-config>

+ 2 - 1
.gitignore

@@ -1,6 +1,6 @@
 build/
 .gradle/
-
+target/
 
 # Created by:
 # https://www.gitignore.io/api/eclipse
@@ -141,3 +141,4 @@ praktikum-holons.iml
 /gb_singlerun.txt
 /PSO i100 p20 m3e-3 v4 (52).metalog
 /PSO i100 p20 m3e-3 v6.metalog
+/target/

+ 0 - 15
API_Instruction

@@ -1,15 +0,0 @@
-Create a new Java Project and add the jar "CpsAlgorithm" to your Build Path.
-Then create a new Package and create a new Class.
-That Class has to implement the Interface "cpsAlgorithm".
-Your Class then has to implement the method runAlgorithm.
-This Method gets a Model and the Controller.
-You can access all Data via the Model.
-The Controller has several Methods you can use as well.
-
-Your Class should look something like the example in the exampleAlgorithm Package
-
-Then in the program click on the Algorithm Button.
-Go to your project and select the folder where your .java files are.
-Then you can Select the Algorithm you want to use in the ComboBox, which then will be compiled.
-
-Your algorithm will now be used.

+ 0 - 89
ChangelogV2_1.md

@@ -1,89 +0,0 @@
-# Changelog
-## Holeg Update 2.1
-### Energy Distribution Overhaul
-#### Added different Fairness Models
-	* EveryoneEqual:	  All HolonObjects will get the same supply
-	* MinimumDemandFirst: As many HolonObjects as possible are supplied (partially & fully)
-#### Added SupplyBars
-	* Each HolonObject got a SupplyBar, which shows how much percent of its needed energy it was supplied with
-	* Can be turned off
-#### Simulation is more precise now
-	* Supply and Color will be calculated per HolonObject instead of Subnet
-
-### HolonBatteries
-	* HolonBattery was added
-	* Can be added to Categories
-	* Can be edited in the Categories
-	* Can be added to Canvas
-	* Can be saved (including it's states)
-	* Will charge if there is overproduction in it's Subnet
-	* Will discharge if there is underproduction in it's Subnet (and it is partially filled)
-	* Has a small Bar, which shows how much it is charged
-
-### IterationLimit was removed
-	* The Maximum number of Iterations can be increased up to 100000
-	* Each HolonElement can have an own Graph Length
-	* HolonElements can be set to copy the Global Iteration Length
-	* HolonElement Local Iterations will be saved
-	
-### Template Functionality
-	* It is possible to create Templates of HolonObjects in the Category Menu
-	* HolonObject including Elements/Graphs/Lengths will be saved
-	* right click on HolonObject
-
-### Drag & Drop Replacements
-	* AbstractCpsObjects can be replaced by Dragged ...
-		+ Category Objects
-		+ Canvas Objects
-	* Objects that would be Replaced when the mouse is released are highlighted Red
-
-### Small Quality of Life Improvements
-#### Starting Holeg without Gradle
-	* Added Possibility to start it from Eclipse/classes or any other IDE
-	* Starting via Gradle remains possible
-#### Improved SpeedSlider
-	* Left is slow (~1 step/sec)
-	* Right Side is fast (~ 64steps/sec)
-	* Logarithmic Scale 1,2,4,8,16,32,64
-#### Sorting the HolonElement List
-	* Can be sorted by Columns
-#### Improved Help Menu
-	* Added Links to the Wiki, User Manual etc.
-#### Play Button improvement
-	* Will reset the Simulation and start over, if simulation is over
-#### Simple Align Feature
-	* Adds possibility to align all objects (option menu)
-	* Or just the selected ones (rightclick on selected)
-#### Many UI Improvements
-	* Improved New/Delete Buttons, PupOps etc.
-	* Renamed Frame
-	* Added some ToolTips
-	* Added Draw Edges Hints
-	* Some Improved PopUps
-	* HolonElementTable Items that should not be edited, can not be edited
-	* New Icon: HOLEG Light Bulb
-
-### Performance Improvements
-#### Simulation
-	* around 30% faster
-#### Loading of Images refactored
-	* Often Used Images will be stored
-	* Works inside Jar and simple .class Files
-	
-### Many Bugfixes
-	* Hundreds of NullPointers fixed (e.g. pressing buttons, when mouse isn't on canvas)
-	* Saving/Loading improved (e.g. Graphs)
-	* Some Group Cable Bugs
-	* Added closing invalid UpperNodeTabs (on Redo/Undo etc.)
-	* No more Cells in EditModus, without a corresponding Table
-	* Added some missing repaints/recalculates
-	* removed Possibility to remove Graph End Points
-	* Fixes most crashes
-#### Language refactored
-	* Languages Arrays moved to resource Files
-	* uses UTF8 Labels on all operating systems
-	* no more unknown charset console spam
-
-### General Changes
-#### Added [License](https://git.tk.informatik.tu-darmstadt.de/carlos.garcia/praktikum-holons/src/master/license.md)
-#### Added [Git Readme](https://git.tk.informatik.tu-darmstadt.de/carlos.garcia/praktikum-holons/src/master/README.md)

二進制
QS-Gruppe14-FinalVersion.pdf


+ 64 - 80
README.md

@@ -1,80 +1,64 @@
-# Holeg Simulator
-
-Cyber-physical systems simulation software following a Holon-based smart grid system.
-
-## Prerequisites
-
-* Java 1.8 compatible VM
-* Gradle >= 3.1 (may be downloaded on-the-fly)
-
-## Building
-
-This project uses Gradle. If Gradle is not available on your system, run the included shell 
-script `gradlew` (or `gradlew.bat` on Windows) instead of the `gradle` command.
-
-### Available tasks
-
-	$ gradle build		# Assembles and tests this project.
-	
-	$ gradle test		# Runs the included unit tests.
-	
-	$ gradle run		# Starts the Holeg Simulator as JVM Application.
-	
-	$ gradle tasks		# Displays all the tasks runnable from root project.
-
-## Introduction and User Manual
-
-The Wiki contains some general [Information](https://git.tk.informatik.tu-darmstadt.de/carlos.garcia/praktikum-holons/wiki/Introduction) and a [User Manual](https://git.tk.informatik.tu-darmstadt.de/carlos.garcia/praktikum-holons/wiki/User+Manual)
-
-## API Instructions
-
-Check out the [API Instructions Wiki](https://git.tk.informatik.tu-darmstadt.de/carlos.garcia/praktikum-holons/wiki/Algorithms) for some Instructions
-
-## License
-
-This project is licensed under a modified MIT License - see the [LICENSE.md](https://git.tk.informatik.tu-darmstadt.de/carlos.garcia/praktikum-holons/src/master/license.md) file for details
-	
-## Built With
-
-* [JUnit](http://junit.org) - The used test system
-* [Gson](https://github.com/google/gson) - Used for Saving/Loading
-* [Apache Common Compress ](https://rometools.github.io/rome/) - Creates zip/tar Archives
-
-## Contributors
-
-### Version 1.0 to 1.1.0
-
-*  Kevin Julian Trometer
-*  Dominik Fabio Rieder
-*  Teh-Hai Julian Zheng
-*  Edgardo Ernesto Palza Paredes
-*  Jessey Steven Widhalm
-
-### Version 2.0
-
-*  Isabella Dix
-*  Carlos Garcia
-
-### Version 2.1 [Changelog](https://git.tk.informatik.tu-darmstadt.de/carlos.garcia/praktikum-holons/src/master/ChangelogV2_1.md)
-
-*  Andreas T. Meyer-Berg
-*  Ludwig Tietze
-*  Antonio Schneider
-*  Tom Troppmann
-
-## Under contract from:
-
-*  Darmstadt University of Technology
-*  Department of Computer Science, Telecooperation
-*  Hochschulstr. 10
-*  Informatik Telecooperation Lab (TK)
-*  D-64289 Darmstadt, Germany
-
-### Version 1.0 to 1.1.0
-
-*  Andreas Tundis
-*  Carlos Garcia
-
-### Version 2.1
-
-*  Rolf Egert
+# Holeg Simulator
+
+Cyber-physical systems simulation software following a Holon-based smart grid system.
+
+## Prerequisites
+
+* Java 1.8 compatible VM
+
+## Introduction and User Manual
+
+The Wiki contains some general [Information](https://git.tk.informatik.tu-darmstadt.de/carlos.garcia/praktikum-holons/wiki/Introduction) and a [User Manual](https://git.tk.informatik.tu-darmstadt.de/carlos.garcia/praktikum-holons/wiki/User+Manual)
+
+## API Instructions
+
+Check out the [API Instructions Wiki](https://git.tk.informatik.tu-darmstadt.de/carlos.garcia/praktikum-holons/wiki/Algorithms) for some Instructions
+
+## License
+
+This project is licensed under a modified MIT License - see the [LICENSE.md](https://git.tk.informatik.tu-darmstadt.de/carlos.garcia/praktikum-holons/src/master/license.md) file for details
+	
+## Built With
+
+* [JUnit](http://junit.org) - The used test system
+* [Gson](https://github.com/google/gson) - Used for Saving/Loading
+* [Apache Common Compress ](https://rometools.github.io/rome/) - Creates zip/tar Archives
+
+## Contributors
+
+### Version 1.0 to 1.1.0
+
+*  Kevin Julian Trometer
+*  Dominik Fabio Rieder
+*  Teh-Hai Julian Zheng
+*  Edgardo Ernesto Palza Paredes
+*  Jessey Steven Widhalm
+
+### Version 2.0
+
+*  Isabella Dix
+*  Carlos Garcia
+
+### Version 2.1 [Changelog](https://git.tk.informatik.tu-darmstadt.de/carlos.garcia/praktikum-holons/src/master/ChangelogV2_1.md)
+
+*  Andreas T. Meyer-Berg
+*  Ludwig Tietze
+*  Antonio Schneider
+*  Tom Troppmann
+
+## Under contract from:
+
+*  Darmstadt University of Technology
+*  Department of Computer Science, Telecooperation
+*  Hochschulstr. 10
+*  Informatik Telecooperation Lab (TK)
+*  D-64289 Darmstadt, Germany
+
+### Version 1.0 to 1.1.0
+
+*  Andreas Tundis
+*  Carlos Garcia
+
+### Version 2.1
+
+*  Rolf Egert

+ 0 - 143
build.gradle

@@ -1,143 +0,0 @@
-/*
- * This build file was auto generated by running the Gradle 'init' task
- * by 'jessey' at '04.07.16 13:33' with Gradle 2.2.1
- *
- * This generated file contains a commented-out sample Java project to get you started.
- * For more details take a look at the Java Quickstart chapter in the Gradle
- * user guide available at http://gradle.org/docs/2.2.1/userguide/tutorial_java_projects.html
- */
-buildscript {
-    repositories {
-        jcenter()
-    }
-    dependencies {
-        classpath 'gradle.plugin.edu.sc.seis.gradle:launch4j:2.3.0'
-    }
-}
-
-
-plugins {
-    id 'edu.sc.seis.launch4j' version '2.3.0'
-}
-
-// Apply the java plugin to add support for Java
-apply plugin: 'java'
-apply plugin: 'eclipse'
-apply plugin: 'application'
-apply plugin: 'edu.sc.seis.launch4j'
-
-
-version = '2.1'
-
-mainClassName = 'ui.view.Main'
-def projectName = 'holeg'
-def mainClass = 'ui.view.Main'
-
-// the fatJar includes all dependencies (all used libraries)
-task fatJar(type: Jar) {
-    manifest {
-        attributes 'Implmenetation-Title': projectName,
-                'Implementation-Version': version,
-                'Main-Class': mainClass
-    }
-    baseName = projectName + '-all'
-    from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
-    with jar
-}
-
-jar {
-    manifest {
-        attributes 'Main-Class': mainClass
-    }
-    baseName = projectName
-}
-
-sourceSets {
-    test {
-        java {
-            srcDir 'tests'
-        }
-        resources {
-            srcDir 'res'
-        }
-    }
-    main {
-        java {
-            srcDir 'src'
-        }
-        resources {
-            srcDir 'res'
-        }
-    }
-}
-
-repositories {
-    mavenCentral()
-    jcenter()
-}
-
-dependencies {
-	// download jars on the fly
-	// https://mvnrepository.com/artifact/org.apache.commons/commons-compress
-	compile group: 'org.apache.commons', name: 'commons-compress', version: '1.13'
-    // https://mvnrepository.com/artifact/com.google.code.gson/gson
-    compile group: 'com.google.code.gson', name: 'gson', version: '2.8.2'
-	// https://mvnrepository.com/artifact/junit/junit
-	testCompile group: 'junit', name: 'junit', version: '4.12'
-	compile group: 'junit', name: 'junit', version: '4.12'
-
-	// use /jar Folder (old system)
-    compile fileTree(dir: 'jars/commons-compress-1.13', include: ['*.jar'])
-	compile fileTree(dir: 'jars', include: ['*.jar'])
-    testCompile group: 'junit', name: 'junit', version: '4.+'
-}
-
-
-// execute by command-line with 'gradlew clean jar createAllExecutables -Pl4j-debug --stacktrace'
-// then add jre8-distribution to folder 'jre8' in same directory
-//
-// the directory-structure afterwards should look like
-// |- [projectName].exe
-// |> lib
-//   |- commons-compress-1.13.jar
-//   ...
-// |> jre8
-//   |> bin
-//   |> lib
-//   ...
-
-launch4j {
-    mainClassName='ui.view.Main'
-
-    // relative path at which the bundled JRE lies
-    bundledJrePath = 'jre8'
-
-    // for 64b: comment in, for 32b: comment out
-    bundledJre64Bit = true
-
-    // names of output file
-    productName = projectName
-    outfile = projectName + '.exe'
-}
-
-
-/*
-// In this section you declare where to find the dependencies of your project
-repositories {
-    // Use 'jcenter' for resolving your dependencies.
-    // You can declare any Maven/Ivy/file repository here.
-    jcenter()
-}
-
-// In this section you declare the dependencies for your production and test code
-dependencies {
-    // The production code uses the SLF4J logging API at compile time
-    compile 'org.slf4j:slf4j-api:1.7.7'
-
-    // Declare the dependency for your favourite test framework you want to use in your tests.
-    // TestNG is also supported by the Gradle Test task. Just change the
-    // testCompile dependency to testCompile 'org.testng:testng:6.8.1' and add
-    // 'test.useTestNG()' to your build script.
-    testCompile "junit:junit:4.11"
-}
-*/

二進制
gradle/wrapper/gradle-wrapper.jar


+ 0 - 6
gradle/wrapper/gradle-wrapper.properties

@@ -1,6 +0,0 @@
-#Tue Apr 04 16:44:00 CEST 2017
-distributionBase=GRADLE_USER_HOME
-distributionPath=wrapper/dists
-zipStoreBase=GRADLE_USER_HOME
-zipStorePath=wrapper/dists
-distributionUrl=https\://services.gradle.org/distributions/gradle-2.2.1-all.zip

+ 0 - 164
gradlew

@@ -1,164 +0,0 @@
-#!/usr/bin/env bash
-
-##############################################################################
-##
-##  Gradle start up script for UN*X
-##
-##############################################################################
-
-# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
-DEFAULT_JVM_OPTS=""
-
-APP_NAME="Gradle"
-APP_BASE_NAME=`basename "$0"`
-
-# Use the maximum available, or set MAX_FD != -1 to use that value.
-MAX_FD="maximum"
-
-warn ( ) {
-    echo "$*"
-}
-
-die ( ) {
-    echo
-    echo "$*"
-    echo
-    exit 1
-}
-
-# OS specific support (must be 'true' or 'false').
-cygwin=false
-msys=false
-darwin=false
-case "`uname`" in
-  CYGWIN* )
-    cygwin=true
-    ;;
-  Darwin* )
-    darwin=true
-    ;;
-  MINGW* )
-    msys=true
-    ;;
-esac
-
-# For Cygwin, ensure paths are in UNIX format before anything is touched.
-if $cygwin ; then
-    [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
-fi
-
-# Attempt to set APP_HOME
-# Resolve links: $0 may be a link
-PRG="$0"
-# Need this for relative symlinks.
-while [ -h "$PRG" ] ; do
-    ls=`ls -ld "$PRG"`
-    link=`expr "$ls" : '.*-> \(.*\)$'`
-    if expr "$link" : '/.*' > /dev/null; then
-        PRG="$link"
-    else
-        PRG=`dirname "$PRG"`"/$link"
-    fi
-done
-SAVED="`pwd`"
-cd "`dirname \"$PRG\"`/" >&-
-APP_HOME="`pwd -P`"
-cd "$SAVED" >&-
-
-CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
-
-# Determine the Java command to use to start the JVM.
-if [ -n "$JAVA_HOME" ] ; then
-    if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
-        # IBM's JDK on AIX uses strange locations for the executables
-        JAVACMD="$JAVA_HOME/jre/sh/java"
-    else
-        JAVACMD="$JAVA_HOME/bin/java"
-    fi
-    if [ ! -x "$JAVACMD" ] ; then
-        die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
-
-Please set the JAVA_HOME variable in your environment to match the
-location of your Java installation."
-    fi
-else
-    JAVACMD="java"
-    which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
-
-Please set the JAVA_HOME variable in your environment to match the
-location of your Java installation."
-fi
-
-# Increase the maximum file descriptors if we can.
-if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
-    MAX_FD_LIMIT=`ulimit -H -n`
-    if [ $? -eq 0 ] ; then
-        if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
-            MAX_FD="$MAX_FD_LIMIT"
-        fi
-        ulimit -n $MAX_FD
-        if [ $? -ne 0 ] ; then
-            warn "Could not set maximum file descriptor limit: $MAX_FD"
-        fi
-    else
-        warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
-    fi
-fi
-
-# For Darwin, add options to specify how the application appears in the dock
-if $darwin; then
-    GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
-fi
-
-# For Cygwin, switch paths to Windows format before running java
-if $cygwin ; then
-    APP_HOME=`cygpath --path --mixed "$APP_HOME"`
-    CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
-
-    # We build the pattern for arguments to be converted via cygpath
-    ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
-    SEP=""
-    for dir in $ROOTDIRSRAW ; do
-        ROOTDIRS="$ROOTDIRS$SEP$dir"
-        SEP="|"
-    done
-    OURCYGPATTERN="(^($ROOTDIRS))"
-    # Add a user-defined pattern to the cygpath arguments
-    if [ "$GRADLE_CYGPATTERN" != "" ] ; then
-        OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
-    fi
-    # Now convert the arguments - kludge to limit ourselves to /bin/sh
-    i=0
-    for arg in "$@" ; do
-        CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
-        CHECK2=`echo "$arg"|egrep -c "^-"`                                 ### Determine if an option
-
-        if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then                    ### Added a condition
-            eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
-        else
-            eval `echo args$i`="\"$arg\""
-        fi
-        i=$((i+1))
-    done
-    case $i in
-        (0) set -- ;;
-        (1) set -- "$args0" ;;
-        (2) set -- "$args0" "$args1" ;;
-        (3) set -- "$args0" "$args1" "$args2" ;;
-        (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
-        (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
-        (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
-        (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
-        (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
-        (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
-    esac
-fi
-
-# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
-function splitJvmOpts() {
-    JVM_OPTS=("$@")
-}
-eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
-JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
-
-exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"

+ 0 - 90
gradlew.bat

@@ -1,90 +0,0 @@
-@if "%DEBUG%" == "" @echo off
-@rem ##########################################################################
-@rem
-@rem  Gradle startup script for Windows
-@rem
-@rem ##########################################################################
-
-@rem Set local scope for the variables with windows NT shell
-if "%OS%"=="Windows_NT" setlocal
-
-@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
-set DEFAULT_JVM_OPTS=
-
-set DIRNAME=%~dp0
-if "%DIRNAME%" == "" set DIRNAME=.
-set APP_BASE_NAME=%~n0
-set APP_HOME=%DIRNAME%
-
-@rem Find java.exe
-if defined JAVA_HOME goto findJavaFromJavaHome
-
-set JAVA_EXE=java.exe
-%JAVA_EXE% -version >NUL 2>&1
-if "%ERRORLEVEL%" == "0" goto init
-
-echo.
-echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
-echo.
-echo Please set the JAVA_HOME variable in your environment to match the
-echo location of your Java installation.
-
-goto fail
-
-:findJavaFromJavaHome
-set JAVA_HOME=%JAVA_HOME:"=%
-set JAVA_EXE=%JAVA_HOME%/bin/java.exe
-
-if exist "%JAVA_EXE%" goto init
-
-echo.
-echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
-echo.
-echo Please set the JAVA_HOME variable in your environment to match the
-echo location of your Java installation.
-
-goto fail
-
-:init
-@rem Get command-line arguments, handling Windowz variants
-
-if not "%OS%" == "Windows_NT" goto win9xME_args
-if "%@eval[2+2]" == "4" goto 4NT_args
-
-:win9xME_args
-@rem Slurp the command line arguments.
-set CMD_LINE_ARGS=
-set _SKIP=2
-
-:win9xME_args_slurp
-if "x%~1" == "x" goto execute
-
-set CMD_LINE_ARGS=%*
-goto execute
-
-:4NT_args
-@rem Get arguments from the 4NT Shell from JP Software
-set CMD_LINE_ARGS=%$
-
-:execute
-@rem Setup the command line
-
-set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
-
-@rem Execute Gradle
-"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
-
-:end
-@rem End local scope for the variables with windows NT shell
-if "%ERRORLEVEL%"=="0" goto mainEnd
-
-:fail
-rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
-rem the _cmd.exe /c_ return code!
-if  not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
-exit /b 1
-
-:mainEnd
-if "%OS%"=="Windows_NT" endlocal
-
-:omega

二進制
jars/CpsAlgorithm.jar


+ 0 - 23
settings.gradle

@@ -1,23 +0,0 @@
-/*
- * This settings file was auto generated by the Gradle buildInit task
- * by 'jessey' at '04.07.16 13:33' with Gradle 2.2.1
- *
- * The settings file is used to specify which projects to include in your build.
- * In a single project build this file can be empty or even removed.
- *
- * Detailed information about configuring a multi-project build in Gradle can be found
- * in the user guide at http://gradle.org/docs/2.2.1/userguide/multi_project_builds.html
- */
-
-/*
-// To declare projects as part of a multi-project build use the 'include' method
-include 'shared'
-include 'api'
-include 'services:webservice'
-*/
-
-rootProject.name = 'praktikum-holons'
-
-includeFlat 'commons-compress'
-includeFlat 'gson'
-includeFlat 'junit'

二進制
slider.JPG


+ 219 - 222
src/Connection/ConnectHandheld.java

@@ -1,222 +1,219 @@
-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.AddOn;
-import classes.AbstractCanvasObject;
-import classes.GroupNode;
-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 AddOn{
-	
-	//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.getPanel());
-	      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 getPanel() {
-		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<AbstractCanvasObject> listToSearch, List<HolonObject> listToAdd){
-			for (AbstractCanvasObject aCps : listToSearch) {
-				if (aCps instanceof HolonObject) listToAdd.add((HolonObject) aCps);
-				else if(aCps instanceof GroupNode) {
-					addObjectToList(((GroupNode)aCps).getNodes(),listToAdd);
-				}
-			}
-		}
-		
-		
-		private   class  Handle<T>{
-			public T object;
-			Handle(T object){
-				this.object = object;
-			}
-			public String toString() {
-				return object.toString();
-			}
-		}
-	
-}
+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 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.AddOn;
+import classes.AbstractCanvasObject;
+import classes.GroupNode;
+import classes.HolonObject;
+import Connection.socket.Server;
+import ui.controller.Control;
+import ui.view.Console;
+
+public class ConnectHandheld implements AddOn{
+	
+	//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.getPanel());
+	      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 getPanel() {
+		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<AbstractCanvasObject> listToSearch, List<HolonObject> listToAdd){
+			for (AbstractCanvasObject aCps : listToSearch) {
+				if (aCps instanceof HolonObject) listToAdd.add((HolonObject) aCps);
+				else if(aCps instanceof GroupNode) {
+					addObjectToList(((GroupNode)aCps).getNodes(),listToAdd);
+				}
+			}
+		}
+		
+		
+		private   class  Handle<T>{
+			public T object;
+			Handle(T object){
+				this.object = object;
+			}
+			public String toString() {
+				return object.toString();
+			}
+		}
+	
+}

+ 517 - 518
src/Connection/ConnectPhysical.java

@@ -1,518 +1,517 @@
-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.AddOn;
-import classes.AbstractCanvasObject;
-import classes.GroupNode;
-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 AddOn{
-	//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.getPanel());
-	      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<AbstractCanvasObject> listToSearch, List<HolonObject> listToAdd){
-		for (AbstractCanvasObject aCps : listToSearch) {
-			if (aCps instanceof HolonObject) listToAdd.add((HolonObject) aCps);
-			else if(aCps instanceof GroupNode) {
-				addObjectToList(((GroupNode)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 getPanel() {
-		return content;
-	}
-
-	@Override
-	public void setController(Control control) {
-		this.control = control;
-	}
-	
-
-	
-	
-
-}
+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.text.NumberFormatter;
+
+import api.AddOn;
+import classes.AbstractCanvasObject;
+import classes.GroupNode;
+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 AddOn{
+	//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.getPanel());
+	      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<AbstractCanvasObject> listToSearch, List<HolonObject> listToAdd){
+		for (AbstractCanvasObject aCps : listToSearch) {
+			if (aCps instanceof HolonObject) listToAdd.add((HolonObject) aCps);
+			else if(aCps instanceof GroupNode) {
+				addObjectToList(((GroupNode)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 getPanel() {
+		return content;
+	}
+
+	@Override
+	public void setController(Control control) {
+		this.control = control;
+	}
+	
+
+	
+	
+
+}

+ 0 - 41
src/DataSets/GraphDataSet.java

@@ -1,41 +0,0 @@
-package DataSets;
-
-import java.util.Hashtable;
-
-import classes.AbstractCanvasObject;
-
-/*
- * a class which contains one AbstractCpsObject and a corresponding Hashtable
- * for the properties "total Consumption", "total Produktion" and "number of activated Elements"
- * so far...
- */
-public class GraphDataSet {
-	Hashtable<String, PropertyDataSet> propertyTable;
-	AbstractCanvasObject cpsObject;
-	
-	public GraphDataSet(AbstractCanvasObject obj){
-		cpsObject = obj;
-		propertyTable = new Hashtable<String, PropertyDataSet>();
-	}
-	
-	public GraphDataSet(AbstractCanvasObject obj, Hashtable<String, PropertyDataSet> ht){
-		cpsObject = obj;
-		propertyTable = ht;
-	}
-	
-	public void setObject(AbstractCanvasObject aco){
-		cpsObject = aco;
-	}
-	
-	public void setPropertyTable(Hashtable<String, PropertyDataSet> ht){
-		propertyTable = ht;
-	}
-	
-	public AbstractCanvasObject getObject(){
-		return cpsObject;
-	}
-	
-	public Hashtable<String, PropertyDataSet> getPropertytTable(){
-		return propertyTable;
-	}
-}

+ 0 - 36
src/DataSets/PropertyDataSet.java

@@ -1,36 +0,0 @@
-package DataSets;
-
-import java.awt.Color;
-
-public class PropertyDataSet {
-	//contains the Name of the Graph in which the information is shown//
-	private String assignedGraph;
-	//the color in which the Graph is drawn//
-	private Color color;
-	
-	public PropertyDataSet(){
-		assignedGraph = "";
-		color = new Color(255,255,255);
-	}
-	
-	public PropertyDataSet(String graph, Color color){
-		assignedGraph = graph;
-		this.color = color;
-	}
-	
-	public void setColor(Color color){
-		this.color = color;
-	}
-	
-	public void setGraph(String graph){
-		assignedGraph = graph;
-	}
-	
-	public Color getColor(){
-		return this.color;
-	}
-	
-	public String getAssignedGraph(){
-		return assignedGraph;
-	}
-}

+ 0 - 4
src/TypeAdapter/AbstractCpsObjectAdapter.java

@@ -13,14 +13,12 @@ import com.google.gson.JsonSerializer;
 
 import classes.AbstractCanvasObject;
 import classes.GroupNode;
-import ui.view.GroupNodeCanvas;
 
 public class AbstractCpsObjectAdapter
 		implements JsonSerializer<AbstractCanvasObject>, JsonDeserializer<AbstractCanvasObject> {
 
 	@Override
 	public JsonElement serialize(AbstractCanvasObject arg0, Type arg1, JsonSerializationContext arg2) {
-		// TODO Auto-generated method stub
 		JsonObject object = new JsonObject();
 		object.add("type", new JsonPrimitive(arg0.getClass().getSimpleName()));
 		object.add("properties", arg2.serialize(arg0, arg0.getClass()));
@@ -32,7 +30,6 @@ public class AbstractCpsObjectAdapter
 	@Override
 	public AbstractCanvasObject deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2)
 			throws JsonParseException {
-		// TODO Auto-generated method stub
 		JsonObject object = arg0.getAsJsonObject();
 		String type = object.get("type").getAsString();
 		JsonElement element = object.get("properties");
@@ -40,7 +37,6 @@ public class AbstractCpsObjectAdapter
 			String packageName = "classes.";
 			return arg2.deserialize(element, Class.forName(packageName + type));
 		} catch (ClassNotFoundException cnfe) {
-			// TODO: handle exception
 			throw new JsonParseException("Unknown element type: " + type, cnfe);
 		}
 

+ 0 - 2
src/TypeAdapter/ColorAdapter.java

@@ -16,7 +16,6 @@ public class ColorAdapter implements JsonSerializer<Color>, JsonDeserializer<Col
 
 	@Override
 	public Color deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
-		// TODO Auto-generated method stub
 		JsonObject object = arg0.getAsJsonObject();
 		return new Color(object.get("R").getAsInt(), object.get("G").getAsInt(), object.get("B").getAsInt());
 		
@@ -24,7 +23,6 @@ public class ColorAdapter implements JsonSerializer<Color>, JsonDeserializer<Col
 
 	@Override
 	public JsonElement serialize(Color arg0, Type arg1, JsonSerializationContext arg2) {
-		// TODO Auto-generated method stub
 		JsonObject object = new JsonObject();
 		object.add("R", new JsonPrimitive(arg0.getRed()));
 		object.add("G", new JsonPrimitive(arg0.getGreen()));

+ 2 - 6
src/TypeAdapter/PairAdapter.java

@@ -20,16 +20,12 @@ public class PairAdapter implements JsonSerializer<Pair<String, String>>, JsonDe
 	@Override
 	public Pair<String, String> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
 			throws JsonParseException {
-		// TODO Auto-generated method stub
-		JsonObject object = json.getAsJsonObject();
-		
+		JsonObject object = json.getAsJsonObject();	
 		return new Pair<String, String>(object.get("KEY").getAsString(), object.get("VALUE").getAsString());
 	}
 
 	@Override
-	public JsonElement serialize(Pair<String, String> src, Type typeOfSrc, JsonSerializationContext context) {
-		// TODO Auto-generated method stub
-		
+	public JsonElement serialize(Pair<String, String> src, Type typeOfSrc, JsonSerializationContext context) {		
 		JsonObject object = new JsonObject();
 		object.add("KEY", new JsonPrimitive(src.getKey()));
 		object.add("VALUE", new JsonPrimitive(src.getValue()));

+ 2 - 4
src/TypeAdapter/PositionAdapter.java

@@ -15,13 +15,11 @@ public class PositionAdapter implements JsonSerializer<Position>, JsonDeserializ
 
 	@Override
 	public JsonElement serialize(Position arg0, Type arg1, JsonSerializationContext arg2) {
-		// TODO Auto-generated method stub
 		return new JsonPrimitive(arg0.x + ":" + arg0.y);
 	}
 
 	@Override
 	public Position deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) {
-		// TODO Auto-generated method stub
 		try {
 			String arg = arg0.getAsString();
 			int mid = arg.indexOf(':');
@@ -29,8 +27,8 @@ public class PositionAdapter implements JsonSerializer<Position>, JsonDeserializ
 			int y = Integer.parseInt(arg.substring(mid + 1, arg.length()));
 			return new Position(x, y);
 
-		} catch (Exception e) {
-			// TODO: handle exception
+		} catch (NumberFormatException e) {
+			System.err.println(e);
 		}
 		return new Position(-1, -1);
 	}

+ 372 - 372
src/addOns/InformationPanel.java

@@ -1,372 +1,372 @@
-package addOns;
-
-import java.awt.BorderLayout;
-import java.awt.Dimension;
-import java.awt.GridBagConstraints;
-import java.awt.GridBagLayout;
-import java.awt.Insets;
-import java.util.ArrayList;
-import java.util.DoubleSummaryStatistics;
-import java.util.List;
-import java.util.Locale;
-import java.util.Random;
-import java.util.function.Supplier;
-import java.util.stream.Collectors;
-
-import javax.swing.JButton;
-import javax.swing.JFrame;
-import javax.swing.JLabel;
-import javax.swing.JPanel;
-import javax.swing.JScrollPane;
-import javax.swing.JSeparator;
-import javax.swing.JTextField;
-
-import api.AddOn;
-import classes.Flexibility;
-import classes.HolonElement;
-import classes.HolonElement.Priority;
-import ui.controller.Control;
-import ui.controller.FlexManager.FlexState;
-import ui.model.DecoratedHolonObject.HolonObjectState;
-import ui.model.DecoratedState;
-import ui.model.DecoratedSwitch.SwitchState;
-import ui.model.VisualRepresentationalState;
-
-public class InformationPanel implements AddOn {
-	Control control;
-	
-	private JPanel content = new JPanel();
-	private JScrollPane scrollPane;
-	
-	
-	//Fields
-	private int amountSwitch;
-	private int amountActiveSwitch;
-	private int amountInactiveSwitch;
-	private int amountHolonObjects;
-		private int amountConsumer;
-			private int	amountUnderSupplied;
-			private int amountPatiallySupplied;
-			private int amountFullySupplied;
-			private int amountOversupllied;
-		private int amountSupplier;
-	private DoubleSummaryStatistics partiallySuppliedStats;
-	private DoubleSummaryStatistics overSuppliedStats;
-	
-	private int amountHolonElements;
-		private int amountElementEssential;
-		private int amountElementHigh;
-		private int amountElementMedium;
-		private int amountElementLow;
-		private int amountElementActiveEssential;
-		private int amountElementActiveHigh;
-		private int amountElementActiveMedium;
-		private int amountElementActiveLow;
-		private int amountElementInactiveEssential;
-		private int amountElementInactiveHigh;
-		private int amountElementInactiveMedium;
-		private int amountElementInactiveLow;
-	private int amountActiveHolonElements;
-	private int amountInactiveHolonElements;
-	private int amountFlexibilities;
-	private int amountActiveFlexibilities;
-		private int amountEssential;
-		private int amountActiveEssential;
-		private int amountHigh;
-		private int amountActiveHigh;
-		private int amountMedium;
-		private int amountActiveMedium;
-		private int amountLow;
-		private int amountActiveLow;
-
-		private int amountConsumingFlexibilities;
-		private int amountProducingFlexibilities;
-	private int amountPassiv;
-		
-	private int amountGroupNodes;
-	private int amountHolons;
-	
-	List<IEntry> entryList = new ArrayList<IEntry>();
-
-	private int currentEntryVerticalPosition = 0;
-
-
-
-
-
-	Random r = new Random();
-
-
-
-
-	
-	
-	public InformationPanel(){
-		content.setLayout(new BorderLayout());
-		scrollPane = new JScrollPane(createMiddlePanel(),  JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
-	            JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
-		int size = 75;
-		scrollPane.setPreferredSize(new Dimension(16*size, 9*size));
-		content.add(scrollPane, BorderLayout.CENTER);
-		JButton button = new JButton("calculate");
-		button.addActionListener(action -> updateEntrys());
-		content.add(button, BorderLayout.SOUTH);
-	}
-	
-	public static void main(String[] args)
-	{
-	      JFrame newFrame = new JFrame("exampleWindow");
-	      InformationPanel instance = new InformationPanel();
-	      newFrame.setContentPane(instance.getPanel());
-	      newFrame.pack();
-	      newFrame.setVisible(true);
-	      newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
-	}
-	
-	
-	private JPanel createMiddlePanel() {
-		JPanel middle = new JPanel();
-		middle.setLayout(new GridBagLayout());
-		
-		
-		
-
-		entryList.add(new Entry(() -> Integer.toString(amountHolonObjects), "HolonObjects", middle));
-		entryList.add(new Entry(() -> Integer.toString(amountConsumer) + addPercentage(amountConsumer, amountHolonObjects), "\tConsumer", middle));
-		entryList.add(new Entry(() -> Integer.toString(amountUnderSupplied) + addPercentage(amountUnderSupplied, amountConsumer), "\t\tUnderSupplied", middle));
-		entryList.add(new Entry(() -> Integer.toString(amountPatiallySupplied) + addPercentage(amountPatiallySupplied, amountConsumer), "\t\tPatiallySupplied", middle));
-		entryList.add(new StatEntry(() -> StatToFancyString(partiallySuppliedStats), middle));		
-		entryList.add(new Entry(() -> Integer.toString(amountFullySupplied) + addPercentage(amountFullySupplied, amountConsumer), "\t\tFullySupplied", middle));
-		entryList.add(new Entry(() -> Integer.toString(amountOversupllied) + addPercentage(amountOversupllied, amountConsumer), "\t\tOversupllied", middle));
-		entryList.add(new StatEntry(() -> StatToFancyString(overSuppliedStats), middle));
-		entryList.add(new Entry(() -> Integer.toString(amountSupplier) + addPercentage(amountSupplier, amountHolonObjects), "\tSupplier", middle));
-		entryList.add(new Entry(() -> Integer.toString(amountPassiv) + addPercentage(amountPassiv, amountHolonObjects), "\tPassiv", middle));
-		addSeperator(middle);
-		entryList.add(new Entry(() -> Integer.toString(amountSwitch), "Switch (not a HolonObject)", middle));
-		entryList.add(new Entry(() -> Integer.toString(amountActiveSwitch) + addPercentage(amountActiveSwitch, amountSwitch), "\t[Active] Switch", middle));
-		entryList.add(new Entry(() -> Integer.toString(amountInactiveSwitch) + addPercentage(amountInactiveSwitch, amountSwitch), "\t[Inactive] Switch", middle));
-		
-		addSeperator(middle);
-		entryList.add(new Entry(() -> Integer.toString(amountHolonElements), "HolonElements", middle));
-		entryList.add(new Entry(() -> Integer.toString(this.amountElementLow) + addPercentage(amountElementLow, amountHolonElements), "\tLow", middle));
-		entryList.add(new Entry(() -> Integer.toString(this.amountElementMedium) + addPercentage(amountElementMedium, amountHolonElements), "\tMedium", middle));
-		entryList.add(new Entry(() -> Integer.toString(this.amountElementHigh) + addPercentage(amountElementHigh, amountHolonElements), "\tHigh", middle));
-		entryList.add(new Entry(() -> Integer.toString(this.amountElementEssential) + addPercentage(amountElementEssential, amountHolonElements), "\tEssential", middle));
-		addSeperator(middle);
-		entryList.add(new Entry(() -> Integer.toString(amountActiveHolonElements) + addPercentage(amountActiveHolonElements, amountHolonElements), "[Active] HolonElements", middle));
-		entryList.add(new Entry(() -> Integer.toString(this.amountElementActiveLow) + addPercentage(amountElementActiveLow, amountActiveHolonElements), "\tLow", middle));
-		entryList.add(new Entry(() -> Integer.toString(this.amountElementActiveMedium) + addPercentage(amountElementActiveMedium, amountActiveHolonElements), "\tMedium", middle));
-		entryList.add(new Entry(() -> Integer.toString(this.amountElementActiveHigh) + addPercentage(amountElementActiveHigh, amountActiveHolonElements), "\tHigh", middle));
-		entryList.add(new Entry(() -> Integer.toString(this.amountElementActiveEssential) + addPercentage(amountElementActiveEssential, amountActiveHolonElements), "\tEssential", middle));
-		addSeperator(middle);
-		entryList.add(new Entry(() -> Integer.toString(amountInactiveHolonElements) + addPercentage(amountInactiveHolonElements, amountHolonElements), "[Inactive] HolonElements", middle));
-		entryList.add(new Entry(() -> Integer.toString(this.amountElementInactiveLow) + addPercentage(amountElementInactiveLow, amountInactiveHolonElements), "\tLow", middle));
-		entryList.add(new Entry(() -> Integer.toString(this.amountElementInactiveMedium) + addPercentage(amountElementInactiveMedium, amountInactiveHolonElements), "\tMedium", middle));
-		entryList.add(new Entry(() -> Integer.toString(this.amountElementInactiveHigh) + addPercentage(amountElementInactiveHigh, amountInactiveHolonElements), "\tHigh", middle));
-		entryList.add(new Entry(() -> Integer.toString(this.amountElementInactiveEssential) + addPercentage(amountElementInactiveEssential, amountInactiveHolonElements), "\tEssential", middle));
-		
-		addSeperator(middle);
-		entryList.add(new Entry(() -> Integer.toString(amountFlexibilities), "Flexibilities", middle));
-		entryList.add(new Entry(() -> Integer.toString(amountConsumingFlexibilities) + addPercentage(amountConsumingFlexibilities, amountFlexibilities), "\tConsumingFlexibilities", middle));
-		entryList.add(new Entry(() -> Integer.toString(amountProducingFlexibilities) + addPercentage(amountProducingFlexibilities, amountFlexibilities), "\tProducingFlexibilities", middle));
-		addSeperator(middle);
-		entryList.add(new Entry(() -> Integer.toString(amountFlexibilities), "Flexibilities", middle));
-		entryList.add(new Entry(() -> Integer.toString(amountLow) + addPercentage(amountLow, amountFlexibilities), "\tLow", middle));
-		entryList.add(new Entry(() -> Integer.toString(amountMedium) + addPercentage(amountMedium, amountFlexibilities), "\tMedium", middle));
-		entryList.add(new Entry(() -> Integer.toString(amountHigh) + addPercentage(amountHigh, amountFlexibilities), "\tHigh", middle));
-		entryList.add(new Entry(() -> Integer.toString(amountEssential) + addPercentage(amountEssential, amountFlexibilities), "\tEssential", middle));
-		addSeperator(middle);
-		entryList.add(new Entry(() -> Integer.toString(amountActiveFlexibilities), "ActiveFlexibilities", middle));
-		entryList.add(new Entry(() -> Integer.toString(amountActiveLow) + addPercentage(amountActiveLow, amountActiveFlexibilities), "\tLow", middle));
-		entryList.add(new Entry(() -> Integer.toString(amountActiveMedium) + addPercentage(amountActiveMedium, amountActiveFlexibilities), "\tMedium", middle));
-		entryList.add(new Entry(() -> Integer.toString(amountActiveHigh) + addPercentage(amountActiveHigh, amountActiveFlexibilities), "\tHigh", middle));
-		entryList.add(new Entry(() -> Integer.toString(amountActiveEssential) + addPercentage(amountActiveEssential, amountActiveFlexibilities), "\tEssential", middle));
-		addSeperator(middle);
-		entryList.add(new Entry(() -> Integer.toString(amountGroupNodes), "GroupNodes", middle));
-		entryList.add(new Entry(() -> Integer.toString(amountHolons), "Holons", middle));
-		
-		return middle;
-	}
-
-	String addPercentage(int amountActual, int amountMaximum) {
-		return (amountMaximum > 0) ? "                " + String.format (Locale.US, "%.2f", ((float) amountActual) / ((float) amountMaximum) * 100) + "%" : "";
-	}
-	
-	
-	
-	private void addSeperator(JPanel middle) {
-		GridBagConstraints c = new GridBagConstraints();
-		c.fill = GridBagConstraints.HORIZONTAL;
-		c.gridwidth = 2;
-		c.weighty = 0.5;
-		c.weightx = 0.5;
-		c.gridx = 0;
-		c.gridy = this.currentEntryVerticalPosition++;
-		middle.add(new JSeparator(JSeparator.HORIZONTAL), c);
-	}
-
-	private GridBagConstraints createGbConstrain(int x, int y) {
-		GridBagConstraints c = new GridBagConstraints();
-		c.fill = GridBagConstraints.HORIZONTAL;
-		c.insets = new Insets(3,6, 3, 6);  
-		c.weighty = 0.5;
-		c.weightx = 0.5;
-		c.gridx = x;
-		c.gridy = y;
-		return c;
-	}
-	
-	
-	void updateEntrys() {
-		calculateValues();
-		entryList.forEach(entry -> entry.update());
-		//printInfos();
-	}
-	
-	
-	void calculateValues(){
-		DecoratedState dState = control.getSimManager().getActualDecorState();
-		amountConsumer = dState.getNetworkList().stream().map(net -> net.getAmountOfConsumer()).reduce(0, Integer::sum);
-		this.amountSwitch = dState.getDecoratedSwitches().size();
-		amountActiveSwitch = (int)dState.getDecoratedSwitches().stream().filter(dswitch -> (dswitch.getState() == SwitchState.Closed)).count();
-		amountInactiveSwitch = amountSwitch - amountActiveSwitch;
-		this.amountUnderSupplied = dState.getNetworkList().stream().map(net -> net.getAmountOfConsumerWithState(HolonObjectState.NOT_SUPPLIED)).reduce(0, Integer::sum);
-		this.amountPatiallySupplied = dState.getNetworkList().stream().map(net -> net.getAmountOfConsumerWithState(HolonObjectState.PARTIALLY_SUPPLIED)).reduce(0, Integer::sum);
-		
-		this.amountFullySupplied = dState.getNetworkList().stream().map(net -> net.getAmountOfConsumerWithState(HolonObjectState.SUPPLIED)).reduce(0, Integer::sum);
-		this.amountOversupllied = dState.getNetworkList().stream().map(net -> net.getAmountOfConsumerWithState(HolonObjectState.OVER_SUPPLIED)).reduce(0, Integer::sum);
-		amountSupplier = dState.getNetworkList().stream().map(net -> net.getAmountOfSupplier()).reduce(0, Integer::sum);
-		amountPassiv = dState.getNetworkList().stream().map(net -> net.getAmountOfPassiv()).reduce(0, Integer::sum);
-		
-		this.amountHolonObjects = amountConsumer + amountSupplier + amountPassiv;
-		
-		partiallySuppliedStats = dState.getNetworkList().stream().flatMap(net -> {
-			return net.getConsumerList().stream().filter(con -> con.getState() == HolonObjectState.PARTIALLY_SUPPLIED);
-		}).mapToDouble(con -> con.getSupplyBarPercentage()).summaryStatistics();
-		
-		overSuppliedStats = dState.getNetworkList().stream().flatMap(net -> {
-			return net.getConsumerList().stream().filter(con -> con.getState() == HolonObjectState.OVER_SUPPLIED);
-		}).mapToDouble(con -> con.getSupplyBarPercentage()).summaryStatistics();
-		
-		List<Flexibility> flexList = control.getSimManager().getActualFlexManager().getAllFlexWrapper().stream().filter(flexwrapper -> flexwrapper.getFlex().offered).map(flex -> flex.getFlex()).collect(Collectors.toList());
-		amountEssential = (int)flexList.stream().filter(flex -> flex.getElement().getPriority() == Priority.Essential).count();
-		amountHigh = (int)flexList.stream().filter(flex -> flex.getElement().getPriority() == Priority.High).count();
-		amountMedium = (int)flexList.stream().filter(flex -> flex.getElement().getPriority() == Priority.Medium).count();
-		amountLow = (int)flexList.stream().filter(flex -> flex.getElement().getPriority() == Priority.Low).count();
-		this.amountFlexibilities = amountEssential + amountHigh + amountMedium + amountLow;
-		
-		
-		List<Flexibility> flexActiveList = control.getSimManager().getActualFlexManager().getAllFlexWrapperWithState(FlexState.IN_USE).stream().map(flex -> flex.getFlex()).collect(Collectors.toList());
-		amountActiveEssential = (int)flexActiveList.stream().filter(flex -> flex.getElement().getPriority() == Priority.Essential).count();
-		amountActiveHigh = (int)flexActiveList.stream().filter(flex -> flex.getElement().getPriority() == Priority.High).count();
-		amountActiveMedium = (int)flexActiveList.stream().filter(flex -> flex.getElement().getPriority() == Priority.Medium).count();
-		amountActiveLow = (int)flexActiveList.stream().filter(flex -> flex.getElement().getPriority() == Priority.Low).count();
-		this.amountActiveFlexibilities = amountActiveEssential + amountActiveHigh + amountActiveMedium + amountActiveLow;
-		VisualRepresentationalState visualState =control.getSimManager().getActualVisualRepresentationalState();
-		amountGroupNodes = visualState.getAmountfOfGroupNodes();
-		
-		
-		amountHolons = dState.getNetworkList().size();
-		List<HolonElement> listHolonElements = control.getModel().getAllHolonElemnts();
-		this.amountHolonElements = listHolonElements.size();
-		List<HolonElement> listAcitveHolonElemnts = listHolonElements.stream().filter(ele -> ele.isActive()).collect(Collectors.toList());
-		this.amountActiveHolonElements = listAcitveHolonElemnts.size();
-		this.amountInactiveHolonElements = amountHolonElements - amountActiveHolonElements;
-		this.amountElementLow = (int) listHolonElements.stream().filter(ele -> ele.getPriority() == Priority.Low).count();
-		this.amountElementMedium= (int) listHolonElements.stream().filter(ele -> ele.getPriority() == Priority.Medium).count();
-		this.amountElementHigh = (int) listHolonElements.stream().filter(ele -> ele.getPriority() == Priority.High).count();
-		this.amountElementEssential = (int) listHolonElements.stream().filter(ele -> ele.getPriority() == Priority.Essential).count();
-		this.amountElementActiveLow = (int) listAcitveHolonElemnts.stream().filter(ele -> ele.getPriority() == Priority.Low).count();
-		this.amountElementActiveMedium= (int) listAcitveHolonElemnts.stream().filter(ele -> ele.getPriority() == Priority.Medium).count();
-		this.amountElementActiveHigh = (int) listAcitveHolonElemnts.stream().filter(ele -> ele.getPriority() == Priority.High).count();
-		this.amountElementActiveEssential = (int) listAcitveHolonElemnts.stream().filter(ele -> ele.getPriority() == Priority.Essential).count();
-		this.amountElementInactiveLow = amountElementLow - amountElementActiveLow;
-		this.amountElementInactiveMedium= amountElementMedium - amountElementActiveMedium;
-		this.amountElementInactiveHigh = amountElementHigh - amountElementActiveHigh;
-		this.amountElementInactiveEssential = amountElementEssential - amountElementActiveEssential;
-		
-		
-		
-		int cost = 0;
-		int consumingFlex = 0;
-		float consumingFlexEnergy = 0.0f;
-		int producingFlex = 0;
-		float producingFlexEnergy = 0.0f;
-		int maxCooldown = 0;
-		for(Flexibility flex :flexList) {
-			cost += flex.cost;
-			float energy = flex.bringtmir();
-			if(energy < 0) {
-				consumingFlex++;
-				consumingFlexEnergy += -energy;
-			}else {
-				producingFlex++;
-				producingFlexEnergy += energy;
-			}
-		}
-		this.amountConsumingFlexibilities = consumingFlex;
-		this.amountProducingFlexibilities = producingFlex;
-		
-	}
-	
-
-	
-	
-
-	
-	@Override
-	public JPanel getPanel() {
-		return content;
-	}
-
-	@Override
-	public void setController(Control control) {
-		this.control = control;
-		if(control != null)  updateEntrys();
-	}
-	
-	private class Entry implements IEntry{
-		public Entry( Supplier<String> getter, String label, JPanel panel) {
-			this.getter = getter;
-			//RegisterToPanel
-			label = label.replaceAll("\t", "                   ");
-			JLabel jlabel = new JLabel(label);
-			panel.add(jlabel, createGbConstrain(0, currentEntryVerticalPosition));
-			tf = new JTextField(getter.get());
-			tf.setEditable(false);
-			panel.add(tf, createGbConstrain(1, currentEntryVerticalPosition));
-			currentEntryVerticalPosition++;
-		}
-		
-		private JTextField tf; //the Textfield to update
-		private Supplier<String> getter; //Getter for the field
-		public void update() {
-			tf.setText(getter.get());
-		}
-		
-		
-		
-	}
-	private String StatToFancyString (DoubleSummaryStatistics stats) {
-		return "Min:" + stats.getMin() + " Max:" + stats.getMax() + " Average:" + stats.getAverage();
-	}
-	public  class StatEntry implements IEntry 
-	{
-		JLabel textLabel = new JLabel("Nothing");
-		private Supplier<String> updateFunction = null;
-		public StatEntry( Supplier<String> updateText, JPanel panel){
-			updateFunction = updateText;
-			panel.add(textLabel, createGbConstrain(1, currentEntryVerticalPosition));
-			currentEntryVerticalPosition++;
-		}
-		@Override
-		public void update() {
-			textLabel.setText(updateFunction.get());
-		}
-	}
-	
-	
-	private interface IEntry{
-		public void update();
-	}
-}
+package addOns;
+
+import java.awt.BorderLayout;
+import java.awt.Dimension;
+import java.awt.GridBagConstraints;
+import java.awt.GridBagLayout;
+import java.awt.Insets;
+import java.util.ArrayList;
+import java.util.DoubleSummaryStatistics;
+import java.util.List;
+import java.util.Locale;
+import java.util.Random;
+import java.util.function.Supplier;
+import java.util.stream.Collectors;
+
+import javax.swing.JButton;
+import javax.swing.JFrame;
+import javax.swing.JLabel;
+import javax.swing.JPanel;
+import javax.swing.JScrollPane;
+import javax.swing.JSeparator;
+import javax.swing.JTextField;
+
+import api.AddOn;
+import classes.Flexibility;
+import classes.HolonElement;
+import classes.HolonElement.Priority;
+import ui.controller.Control;
+import ui.controller.FlexManager.FlexState;
+import ui.model.DecoratedHolonObject.HolonObjectState;
+import ui.model.DecoratedState;
+import ui.model.DecoratedSwitch.SwitchState;
+import ui.model.VisualRepresentationalState;
+
+public class InformationPanel implements AddOn {
+	Control control;
+	
+	private JPanel content = new JPanel();
+	private JScrollPane scrollPane;
+	
+	
+	//Fields
+	private int amountSwitch;
+	private int amountActiveSwitch;
+	private int amountInactiveSwitch;
+	private int amountHolonObjects;
+		private int amountConsumer;
+			private int	amountUnderSupplied;
+			private int amountPatiallySupplied;
+			private int amountFullySupplied;
+			private int amountOversupllied;
+		private int amountSupplier;
+	private DoubleSummaryStatistics partiallySuppliedStats;
+	private DoubleSummaryStatistics overSuppliedStats;
+	
+	private int amountHolonElements;
+		private int amountElementEssential;
+		private int amountElementHigh;
+		private int amountElementMedium;
+		private int amountElementLow;
+		private int amountElementActiveEssential;
+		private int amountElementActiveHigh;
+		private int amountElementActiveMedium;
+		private int amountElementActiveLow;
+		private int amountElementInactiveEssential;
+		private int amountElementInactiveHigh;
+		private int amountElementInactiveMedium;
+		private int amountElementInactiveLow;
+	private int amountActiveHolonElements;
+	private int amountInactiveHolonElements;
+	private int amountFlexibilities;
+	private int amountActiveFlexibilities;
+		private int amountEssential;
+		private int amountActiveEssential;
+		private int amountHigh;
+		private int amountActiveHigh;
+		private int amountMedium;
+		private int amountActiveMedium;
+		private int amountLow;
+		private int amountActiveLow;
+
+		private int amountConsumingFlexibilities;
+		private int amountProducingFlexibilities;
+	private int amountPassiv;
+		
+	private int amountGroupNodes;
+	private int amountHolons;
+	
+	List<IEntry> entryList = new ArrayList<IEntry>();
+
+	private int currentEntryVerticalPosition = 0;
+
+
+
+
+
+	Random r = new Random();
+
+
+
+
+	
+	
+	public InformationPanel(){
+		content.setLayout(new BorderLayout());
+		scrollPane = new JScrollPane(createMiddlePanel(),  JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
+	            JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
+		int size = 75;
+		scrollPane.setPreferredSize(new Dimension(16*size, 9*size));
+		content.add(scrollPane, BorderLayout.CENTER);
+		JButton button = new JButton("calculate");
+		button.addActionListener(action -> updateEntrys());
+		content.add(button, BorderLayout.SOUTH);
+	}
+	
+	public static void main(String[] args)
+	{
+	      JFrame newFrame = new JFrame("exampleWindow");
+	      InformationPanel instance = new InformationPanel();
+	      newFrame.setContentPane(instance.getPanel());
+	      newFrame.pack();
+	      newFrame.setVisible(true);
+	      newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+	}
+	
+	
+	private JPanel createMiddlePanel() {
+		JPanel middle = new JPanel();
+		middle.setLayout(new GridBagLayout());
+		
+		
+		
+
+		entryList.add(new Entry(() -> Integer.toString(amountHolonObjects), "HolonObjects", middle));
+		entryList.add(new Entry(() -> Integer.toString(amountConsumer) + addPercentage(amountConsumer, amountHolonObjects), "\tConsumer", middle));
+		entryList.add(new Entry(() -> Integer.toString(amountUnderSupplied) + addPercentage(amountUnderSupplied, amountConsumer), "\t\tUnderSupplied", middle));
+		entryList.add(new Entry(() -> Integer.toString(amountPatiallySupplied) + addPercentage(amountPatiallySupplied, amountConsumer), "\t\tPatiallySupplied", middle));
+		entryList.add(new StatEntry(() -> StatToFancyString(partiallySuppliedStats), middle));		
+		entryList.add(new Entry(() -> Integer.toString(amountFullySupplied) + addPercentage(amountFullySupplied, amountConsumer), "\t\tFullySupplied", middle));
+		entryList.add(new Entry(() -> Integer.toString(amountOversupllied) + addPercentage(amountOversupllied, amountConsumer), "\t\tOversupllied", middle));
+		entryList.add(new StatEntry(() -> StatToFancyString(overSuppliedStats), middle));
+		entryList.add(new Entry(() -> Integer.toString(amountSupplier) + addPercentage(amountSupplier, amountHolonObjects), "\tSupplier", middle));
+		entryList.add(new Entry(() -> Integer.toString(amountPassiv) + addPercentage(amountPassiv, amountHolonObjects), "\tPassiv", middle));
+		addSeperator(middle);
+		entryList.add(new Entry(() -> Integer.toString(amountSwitch), "Switch (not a HolonObject)", middle));
+		entryList.add(new Entry(() -> Integer.toString(amountActiveSwitch) + addPercentage(amountActiveSwitch, amountSwitch), "\t[Active] Switch", middle));
+		entryList.add(new Entry(() -> Integer.toString(amountInactiveSwitch) + addPercentage(amountInactiveSwitch, amountSwitch), "\t[Inactive] Switch", middle));
+		
+		addSeperator(middle);
+		entryList.add(new Entry(() -> Integer.toString(amountHolonElements), "HolonElements", middle));
+		entryList.add(new Entry(() -> Integer.toString(this.amountElementLow) + addPercentage(amountElementLow, amountHolonElements), "\tLow", middle));
+		entryList.add(new Entry(() -> Integer.toString(this.amountElementMedium) + addPercentage(amountElementMedium, amountHolonElements), "\tMedium", middle));
+		entryList.add(new Entry(() -> Integer.toString(this.amountElementHigh) + addPercentage(amountElementHigh, amountHolonElements), "\tHigh", middle));
+		entryList.add(new Entry(() -> Integer.toString(this.amountElementEssential) + addPercentage(amountElementEssential, amountHolonElements), "\tEssential", middle));
+		addSeperator(middle);
+		entryList.add(new Entry(() -> Integer.toString(amountActiveHolonElements) + addPercentage(amountActiveHolonElements, amountHolonElements), "[Active] HolonElements", middle));
+		entryList.add(new Entry(() -> Integer.toString(this.amountElementActiveLow) + addPercentage(amountElementActiveLow, amountActiveHolonElements), "\tLow", middle));
+		entryList.add(new Entry(() -> Integer.toString(this.amountElementActiveMedium) + addPercentage(amountElementActiveMedium, amountActiveHolonElements), "\tMedium", middle));
+		entryList.add(new Entry(() -> Integer.toString(this.amountElementActiveHigh) + addPercentage(amountElementActiveHigh, amountActiveHolonElements), "\tHigh", middle));
+		entryList.add(new Entry(() -> Integer.toString(this.amountElementActiveEssential) + addPercentage(amountElementActiveEssential, amountActiveHolonElements), "\tEssential", middle));
+		addSeperator(middle);
+		entryList.add(new Entry(() -> Integer.toString(amountInactiveHolonElements) + addPercentage(amountInactiveHolonElements, amountHolonElements), "[Inactive] HolonElements", middle));
+		entryList.add(new Entry(() -> Integer.toString(this.amountElementInactiveLow) + addPercentage(amountElementInactiveLow, amountInactiveHolonElements), "\tLow", middle));
+		entryList.add(new Entry(() -> Integer.toString(this.amountElementInactiveMedium) + addPercentage(amountElementInactiveMedium, amountInactiveHolonElements), "\tMedium", middle));
+		entryList.add(new Entry(() -> Integer.toString(this.amountElementInactiveHigh) + addPercentage(amountElementInactiveHigh, amountInactiveHolonElements), "\tHigh", middle));
+		entryList.add(new Entry(() -> Integer.toString(this.amountElementInactiveEssential) + addPercentage(amountElementInactiveEssential, amountInactiveHolonElements), "\tEssential", middle));
+		
+		addSeperator(middle);
+		entryList.add(new Entry(() -> Integer.toString(amountFlexibilities), "Flexibilities", middle));
+		entryList.add(new Entry(() -> Integer.toString(amountConsumingFlexibilities) + addPercentage(amountConsumingFlexibilities, amountFlexibilities), "\tConsumingFlexibilities", middle));
+		entryList.add(new Entry(() -> Integer.toString(amountProducingFlexibilities) + addPercentage(amountProducingFlexibilities, amountFlexibilities), "\tProducingFlexibilities", middle));
+		addSeperator(middle);
+		entryList.add(new Entry(() -> Integer.toString(amountFlexibilities), "Flexibilities", middle));
+		entryList.add(new Entry(() -> Integer.toString(amountLow) + addPercentage(amountLow, amountFlexibilities), "\tLow", middle));
+		entryList.add(new Entry(() -> Integer.toString(amountMedium) + addPercentage(amountMedium, amountFlexibilities), "\tMedium", middle));
+		entryList.add(new Entry(() -> Integer.toString(amountHigh) + addPercentage(amountHigh, amountFlexibilities), "\tHigh", middle));
+		entryList.add(new Entry(() -> Integer.toString(amountEssential) + addPercentage(amountEssential, amountFlexibilities), "\tEssential", middle));
+		addSeperator(middle);
+		entryList.add(new Entry(() -> Integer.toString(amountActiveFlexibilities), "ActiveFlexibilities", middle));
+		entryList.add(new Entry(() -> Integer.toString(amountActiveLow) + addPercentage(amountActiveLow, amountActiveFlexibilities), "\tLow", middle));
+		entryList.add(new Entry(() -> Integer.toString(amountActiveMedium) + addPercentage(amountActiveMedium, amountActiveFlexibilities), "\tMedium", middle));
+		entryList.add(new Entry(() -> Integer.toString(amountActiveHigh) + addPercentage(amountActiveHigh, amountActiveFlexibilities), "\tHigh", middle));
+		entryList.add(new Entry(() -> Integer.toString(amountActiveEssential) + addPercentage(amountActiveEssential, amountActiveFlexibilities), "\tEssential", middle));
+		addSeperator(middle);
+		entryList.add(new Entry(() -> Integer.toString(amountGroupNodes), "GroupNodes", middle));
+		entryList.add(new Entry(() -> Integer.toString(amountHolons), "Holons", middle));
+		
+		return middle;
+	}
+
+	String addPercentage(int amountActual, int amountMaximum) {
+		return (amountMaximum > 0) ? "                " + String.format (Locale.US, "%.2f", ((float) amountActual) / ((float) amountMaximum) * 100) + "%" : "";
+	}
+	
+	
+	
+	private void addSeperator(JPanel middle) {
+		GridBagConstraints c = new GridBagConstraints();
+		c.fill = GridBagConstraints.HORIZONTAL;
+		c.gridwidth = 2;
+		c.weighty = 0.5;
+		c.weightx = 0.5;
+		c.gridx = 0;
+		c.gridy = this.currentEntryVerticalPosition++;
+		middle.add(new JSeparator(JSeparator.HORIZONTAL), c);
+	}
+
+	private GridBagConstraints createGbConstrain(int x, int y) {
+		GridBagConstraints c = new GridBagConstraints();
+		c.fill = GridBagConstraints.HORIZONTAL;
+		c.insets = new Insets(3,6, 3, 6);  
+		c.weighty = 0.5;
+		c.weightx = 0.5;
+		c.gridx = x;
+		c.gridy = y;
+		return c;
+	}
+	
+	
+	void updateEntrys() {
+		calculateValues();
+		entryList.forEach(entry -> entry.update());
+		//printInfos();
+	}
+	
+	
+	void calculateValues(){
+		DecoratedState dState = control.getSimManager().getActualDecorState();
+		amountConsumer = dState.getNetworkList().stream().map(net -> net.getAmountOfConsumer()).reduce(0, Integer::sum);
+		this.amountSwitch = dState.getDecoratedSwitches().size();
+		amountActiveSwitch = (int)dState.getDecoratedSwitches().stream().filter(dswitch -> (dswitch.getState() == SwitchState.Closed)).count();
+		amountInactiveSwitch = amountSwitch - amountActiveSwitch;
+		this.amountUnderSupplied = dState.getNetworkList().stream().map(net -> net.getAmountOfConsumerWithState(HolonObjectState.NOT_SUPPLIED)).reduce(0, Integer::sum);
+		this.amountPatiallySupplied = dState.getNetworkList().stream().map(net -> net.getAmountOfConsumerWithState(HolonObjectState.PARTIALLY_SUPPLIED)).reduce(0, Integer::sum);
+		
+		this.amountFullySupplied = dState.getNetworkList().stream().map(net -> net.getAmountOfConsumerWithState(HolonObjectState.SUPPLIED)).reduce(0, Integer::sum);
+		this.amountOversupllied = dState.getNetworkList().stream().map(net -> net.getAmountOfConsumerWithState(HolonObjectState.OVER_SUPPLIED)).reduce(0, Integer::sum);
+		amountSupplier = dState.getNetworkList().stream().map(net -> net.getAmountOfSupplier()).reduce(0, Integer::sum);
+		amountPassiv = dState.getNetworkList().stream().map(net -> net.getAmountOfPassiv()).reduce(0, Integer::sum);
+		
+		this.amountHolonObjects = amountConsumer + amountSupplier + amountPassiv;
+		
+		partiallySuppliedStats = dState.getNetworkList().stream().flatMap(net -> {
+			return net.getConsumerList().stream().filter(con -> con.getState() == HolonObjectState.PARTIALLY_SUPPLIED);
+		}).mapToDouble(con -> con.getSupplyBarPercentage()).summaryStatistics();
+		
+		overSuppliedStats = dState.getNetworkList().stream().flatMap(net -> {
+			return net.getConsumerList().stream().filter(con -> con.getState() == HolonObjectState.OVER_SUPPLIED);
+		}).mapToDouble(con -> con.getSupplyBarPercentage()).summaryStatistics();
+		
+		List<Flexibility> flexList = control.getSimManager().getActualFlexManager().getAllFlexWrapper().stream().filter(flexwrapper -> flexwrapper.getFlex().offered).map(flex -> flex.getFlex()).collect(Collectors.toList());
+		amountEssential = (int)flexList.stream().filter(flex -> flex.getElement().getPriority() == Priority.Essential).count();
+		amountHigh = (int)flexList.stream().filter(flex -> flex.getElement().getPriority() == Priority.High).count();
+		amountMedium = (int)flexList.stream().filter(flex -> flex.getElement().getPriority() == Priority.Medium).count();
+		amountLow = (int)flexList.stream().filter(flex -> flex.getElement().getPriority() == Priority.Low).count();
+		this.amountFlexibilities = amountEssential + amountHigh + amountMedium + amountLow;
+		
+		
+		List<Flexibility> flexActiveList = control.getSimManager().getActualFlexManager().getAllFlexWrapperWithState(FlexState.IN_USE).stream().map(flex -> flex.getFlex()).collect(Collectors.toList());
+		amountActiveEssential = (int)flexActiveList.stream().filter(flex -> flex.getElement().getPriority() == Priority.Essential).count();
+		amountActiveHigh = (int)flexActiveList.stream().filter(flex -> flex.getElement().getPriority() == Priority.High).count();
+		amountActiveMedium = (int)flexActiveList.stream().filter(flex -> flex.getElement().getPriority() == Priority.Medium).count();
+		amountActiveLow = (int)flexActiveList.stream().filter(flex -> flex.getElement().getPriority() == Priority.Low).count();
+		this.amountActiveFlexibilities = amountActiveEssential + amountActiveHigh + amountActiveMedium + amountActiveLow;
+		VisualRepresentationalState visualState =control.getSimManager().getActualVisualRepresentationalState();
+		amountGroupNodes = visualState.getAmountfOfGroupNodes();
+		
+		
+		amountHolons = dState.getNetworkList().size();
+		List<HolonElement> listHolonElements = control.getModel().getAllHolonElemnts();
+		this.amountHolonElements = listHolonElements.size();
+		List<HolonElement> listAcitveHolonElemnts = listHolonElements.stream().filter(ele -> ele.isActive()).collect(Collectors.toList());
+		this.amountActiveHolonElements = listAcitveHolonElemnts.size();
+		this.amountInactiveHolonElements = amountHolonElements - amountActiveHolonElements;
+		this.amountElementLow = (int) listHolonElements.stream().filter(ele -> ele.getPriority() == Priority.Low).count();
+		this.amountElementMedium= (int) listHolonElements.stream().filter(ele -> ele.getPriority() == Priority.Medium).count();
+		this.amountElementHigh = (int) listHolonElements.stream().filter(ele -> ele.getPriority() == Priority.High).count();
+		this.amountElementEssential = (int) listHolonElements.stream().filter(ele -> ele.getPriority() == Priority.Essential).count();
+		this.amountElementActiveLow = (int) listAcitveHolonElemnts.stream().filter(ele -> ele.getPriority() == Priority.Low).count();
+		this.amountElementActiveMedium= (int) listAcitveHolonElemnts.stream().filter(ele -> ele.getPriority() == Priority.Medium).count();
+		this.amountElementActiveHigh = (int) listAcitveHolonElemnts.stream().filter(ele -> ele.getPriority() == Priority.High).count();
+		this.amountElementActiveEssential = (int) listAcitveHolonElemnts.stream().filter(ele -> ele.getPriority() == Priority.Essential).count();
+		this.amountElementInactiveLow = amountElementLow - amountElementActiveLow;
+		this.amountElementInactiveMedium= amountElementMedium - amountElementActiveMedium;
+		this.amountElementInactiveHigh = amountElementHigh - amountElementActiveHigh;
+		this.amountElementInactiveEssential = amountElementEssential - amountElementActiveEssential;
+		
+		
+		
+		//int cost = 0;
+		int consumingFlex = 0;
+		//float consumingFlexEnergy = 0.0f;
+		int producingFlex = 0;
+		//float producingFlexEnergy = 0.0f;
+		//int maxCooldown = 0;
+		for(Flexibility flex :flexList) {
+//			cost += flex.cost;
+			float energy = flex.bringtmir();
+			if(energy < 0) {
+				consumingFlex++;
+//				consumingFlexEnergy += -energy;
+			}else {
+				producingFlex++;
+//				producingFlexEnergy += energy;
+			}
+		}
+		this.amountConsumingFlexibilities = consumingFlex;
+		this.amountProducingFlexibilities = producingFlex;
+		
+	}
+	
+
+	
+	
+
+	
+	@Override
+	public JPanel getPanel() {
+		return content;
+	}
+
+	@Override
+	public void setController(Control control) {
+		this.control = control;
+		if(control != null)  updateEntrys();
+	}
+	
+	private class Entry implements IEntry{
+		public Entry( Supplier<String> getter, String label, JPanel panel) {
+			this.getter = getter;
+			//RegisterToPanel
+			label = label.replaceAll("\t", "                   ");
+			JLabel jlabel = new JLabel(label);
+			panel.add(jlabel, createGbConstrain(0, currentEntryVerticalPosition));
+			tf = new JTextField(getter.get());
+			tf.setEditable(false);
+			panel.add(tf, createGbConstrain(1, currentEntryVerticalPosition));
+			currentEntryVerticalPosition++;
+		}
+		
+		private JTextField tf; //the Textfield to update
+		private Supplier<String> getter; //Getter for the field
+		public void update() {
+			tf.setText(getter.get());
+		}
+		
+		
+		
+	}
+	private String StatToFancyString (DoubleSummaryStatistics stats) {
+		return "Min:" + stats.getMin() + " Max:" + stats.getMax() + " Average:" + stats.getAverage();
+	}
+	public  class StatEntry implements IEntry 
+	{
+		JLabel textLabel = new JLabel("Nothing");
+		private Supplier<String> updateFunction = null;
+		public StatEntry( Supplier<String> updateText, JPanel panel){
+			updateFunction = updateText;
+			panel.add(textLabel, createGbConstrain(1, currentEntryVerticalPosition));
+			currentEntryVerticalPosition++;
+		}
+		@Override
+		public void update() {
+			textLabel.setText(updateFunction.get());
+		}
+	}
+	
+	
+	private interface IEntry{
+		public void update();
+	}
+}

+ 0 - 18
src/addOns/RandomOfferdFlexibility.java

@@ -25,16 +25,9 @@ import javax.swing.JLabel;
 import javax.swing.JPanel;
 import javax.swing.JSlider;
 import javax.swing.text.NumberFormatter;
-
-import com.google.gson.internal.Streams;
-
 import api.AddOn;
-import classes.AbstractCanvasObject;
-import classes.GroupNode;
 import classes.Flexibility;
-import classes.HolonElement;
 import classes.HolonElement.Priority;
-import classes.HolonObject;
 import ui.controller.Control;
 
 /**
@@ -325,21 +318,10 @@ public class RandomOfferdFlexibility implements AddOn {
 	}
 	
 	
-	
-
-	private List<HolonObject> createListOfHolonObjects(List<AbstractCanvasObject> objectsOnCanvas) {
-	List<HolonObject> list = new ArrayList<HolonObject>();
-	for(AbstractCanvasObject aCps :  objectsOnCanvas) {
-		if(aCps instanceof HolonObject) list.add((HolonObject) aCps);
-		else if(aCps instanceof GroupNode)list.addAll(createListOfHolonObjects(((GroupNode)aCps).getNodes()));
-	}
-	return list;
-	}
 	public void update() {
 		if(control == null) {
 			return;
 		}
-		List<HolonElement> elementList = createListOfHolonObjects(control.getModel().getObjectsOnCanvas()).stream().flatMap(hObject -> hObject.getElements().stream()).collect(Collectors.toList());
 		control.calculateStateAndVisualForCurrentTimeStep();
 		control.updateCanvas();
 		List<Flexibility> flexList = control.getSimManager().getActualFlexManager().getAllFlexWrapper().stream().filter(flexwrapper -> flexwrapper.getFlex().offered).map(flex -> flex.getFlex()).collect(Collectors.toList());

+ 3 - 4
src/addOns/RandomSwitch.java

@@ -7,7 +7,6 @@ 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;
@@ -53,9 +52,9 @@ public class RandomSwitch implements AddOn {
 		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") );
+		labelTable.put( Integer.valueOf(0), new JLabel("0.0") );
+		labelTable.put( Integer.valueOf(50), new JLabel("0.5") );
+		labelTable.put( Integer.valueOf(100), new JLabel("1.0") );
 		flipChance.addChangeListener(actionEvent ->randomChance =(double)flipChance.getValue()/100.0);
 		flipChance.setLabelTable( labelTable );
 		flipChance.setPaintLabels(true);

+ 2 - 2
src/addOns/Randomizer.java

@@ -37,14 +37,14 @@ import com.google.gson.JsonIOException;
 import com.google.gson.JsonParser;
 import com.google.gson.JsonSyntaxException;
 
-import addOns.JSON.HolonElementSketch;
+import addOns.Utility.HolonElementSketch;
+import addOns.Utility.RandomPriotity;
 import api.AddOn;
 import classes.AbstractCanvasObject;
 import classes.GroupNode;
 import classes.HolonElement;
 import classes.HolonObject;
 import ui.controller.Control;
-import ui.view.RandomPriotity;
 import utility.Random;
 import utility.ImageImport;
 

+ 177 - 177
src/api/EmailNotification.java → src/addOns/Utility/EmailNotification.java

@@ -1,177 +1,177 @@
-package api;
-import java.awt.BorderLayout;
-import java.awt.ComponentOrientation;
-import java.awt.Dimension;
-import java.awt.FlowLayout;
-import java.awt.GridLayout;
-import java.util.prefs.*;
-
-import javax.swing.BorderFactory;
-import javax.swing.JButton;
-import javax.swing.JFrame;
-import javax.swing.JLabel;
-import javax.swing.JPanel;
-import javax.swing.JPasswordField;
-import javax.swing.JTextField;
-
-import org.apache.commons.mail.*;
-
-import utility.ImageImport;
-
-
-public class EmailNotification {
-	private static Preferences _prefs;
-	private static EmailSmtpInformation _info = new EmailSmtpInformation();
-	
-	
-	
-	public static class EmailSmtpInformation{
-		public String Hostname;
-		public int Port;
-		public String Username;
-		public String Password;
-		public String FromEmail;
-		public String ToEmail;
-	}
-	
-	
-	
-	
-	
-	
-	
-	public static void main(String[] args) {
-		OpenEmailSettings(null);
-	}
-
-	public static void OpenEmailSettings(JPanel parent) {
-		loadPreferences();
-		JFrame frame = new JFrame();
-		frame.setTitle("Email Settings");
-		frame.setIconImage(ImageImport.loadImage("/Images/Holeg.png",30,30));
-		frame.setContentPane(createEditFormular(frame));
-		frame.pack();
-		frame.setPreferredSize(new Dimension(400,frame.getHeight()));
-		frame.pack();
-		frame.setVisible(true);
-		frame.setLocationRelativeTo(parent);
-		frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
-	}
-	
-	
-	private static JPanel createEditFormular(JFrame frame) {
-		JPanel panel = new JPanel();
-		panel.setLayout(new BorderLayout());
-		panel.setBorder(BorderFactory.createEmptyBorder(0,5,0,5));
-		
-		JPanel infoPanel = new JPanel();
-		GridLayout infoLayout= new GridLayout(0,2);
-		infoPanel.add(new JLabel("SMTP Hostname:"));
-		JTextField hostnameTextField = new JTextField(_info.Hostname);
-		infoPanel.add(hostnameTextField);
-		infoPanel.add(new JLabel("Port:"));
-		JTextField portTextField = new JTextField(Integer.toString(_info.Port));
-		infoPanel.add(portTextField);
-		infoPanel.add(new JLabel("Username:"));
-		JTextField usernameTextField = new JTextField(_info.Username);
-		infoPanel.add(usernameTextField);
-		infoPanel.add(new JLabel("Password:"));
-		JPasswordField  passwordTextField = new JPasswordField (_info.Password);
-		infoPanel.add(passwordTextField);
-		infoPanel.add(new JLabel("From Email:"));
-		JTextField fromEmailTextField = new JTextField(_info.FromEmail);
-		infoPanel.add(fromEmailTextField);
-		infoPanel.add(new JLabel("To Email:"));
-		JTextField toEmailTextField = new JTextField(_info.ToEmail);
-		infoPanel.add(toEmailTextField);
-		infoPanel.setLayout(infoLayout);
-		panel.add(infoPanel, BorderLayout.CENTER);
-		
-		JPanel controlPanel = new JPanel();
-		controlPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
-		controlPanel.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
-		JButton cancelButton = new JButton("Cancel");
-		cancelButton.addActionListener(event -> {
-			frame.dispose();
-		});
-		controlPanel.add(cancelButton);
-		JButton applyButton = new JButton("Apply and Close");
-		applyButton.addActionListener(event -> {
-			// parse Textfields
-			_info.Hostname = hostnameTextField.getText();
-			_info.Port = Integer.valueOf(portTextField.getText());
-			_info.Username = usernameTextField.getText();
-			_info.Password = passwordTextField.getText();
-			_info.FromEmail = fromEmailTextField.getText();
-			_info.ToEmail = toEmailTextField.getText();
-			// Save Preferences
-			savePreferences();
-			frame.dispose();
-		});
-		controlPanel.add(applyButton);
-		
-		JButton testButton = new JButton("Send Test-Email");
-		testButton.addActionListener(event -> {
-			// parse Textfields
-			EmailSmtpInformation testinfo = new EmailSmtpInformation();
-			testinfo.Hostname = hostnameTextField.getText();
-			testinfo.Port = Integer.valueOf(portTextField.getText());
-			testinfo.Username = usernameTextField.getText();
-			testinfo.Password = passwordTextField.getText();
-			testinfo.FromEmail = fromEmailTextField.getText();
-			testinfo.ToEmail = toEmailTextField.getText();
-			sendEmail(testinfo, "Holeg Notification Test", "Success.");
-		});
-		controlPanel.add(testButton);
-		
-		panel.add(controlPanel, BorderLayout.PAGE_END);
-		
-		
-		
-		return panel;
-	}
-	public static void sendEmail(String subject, String message) {
-		loadPreferences();
-		sendEmail(_info, subject, message);
-	}
-
-	public static void sendEmail(EmailSmtpInformation info, String subject, String message) {
-		Email email = new SimpleEmail();
-		email.setHostName(info.Hostname);
-		email.setSmtpPort(info.Port);
-		email.setAuthenticator(new DefaultAuthenticator(info.Username, info.Password));
-		email.setSSLOnConnect(true);
-		email.setSubject(subject);
-		try {
-			email.setFrom(info.FromEmail);
-			email.setMsg(message);
-			email.addTo(info.ToEmail);
-			email.send();
-		} catch (EmailException e) {
-			e.printStackTrace();
-		}
-	}
-	
-	private static void savePreferences() {
-		_prefs = Preferences.userRoot().node("EmailNotification");
-		_prefs.put("Hostname", _info.Hostname);
-		_prefs.putInt("Port", _info.Port);
-		_prefs.put("Username", _info.Username);
-		_prefs.put("Password", _info.Password);
-		_prefs.put("FromEmail", _info.FromEmail);
-		_prefs.put("ToEmail", _info.ToEmail);
-	}
-	
-	private static void loadPreferences() {
-		_prefs = Preferences.userRoot().node("EmailNotification");
-		_info.Hostname = _prefs.get("Hostname", "");
-		_info.Port = _prefs.getInt("Port", 465);
-		_info.Username = _prefs.get("Username", "");
-		_info.Password = _prefs.get("Password", "");
-		_info.FromEmail= _prefs.get("FromEmail", "");
-		_info.ToEmail = _prefs.get("ToEmail", "");
-	}
-	
-	
-	
-}
+package addOns.Utility;
+import java.awt.BorderLayout;
+import java.awt.ComponentOrientation;
+import java.awt.Dimension;
+import java.awt.FlowLayout;
+import java.awt.GridLayout;
+import java.util.prefs.*;
+
+import javax.swing.BorderFactory;
+import javax.swing.JButton;
+import javax.swing.JFrame;
+import javax.swing.JLabel;
+import javax.swing.JPanel;
+import javax.swing.JPasswordField;
+import javax.swing.JTextField;
+
+import org.apache.commons.mail.*;
+
+import utility.ImageImport;
+
+
+public class EmailNotification {
+	private static Preferences _prefs;
+	private static EmailSmtpInformation _info = new EmailSmtpInformation();
+	
+	
+	
+	public static class EmailSmtpInformation{
+		public String Hostname;
+		public int Port;
+		public String Username;
+		public String Password;
+		public String FromEmail;
+		public String ToEmail;
+	}
+	
+	
+	
+	
+	
+	
+	
+	public static void main(String[] args) {
+		OpenEmailSettings(null);
+	}
+
+	public static void OpenEmailSettings(JPanel parent) {
+		loadPreferences();
+		JFrame frame = new JFrame();
+		frame.setTitle("Email Settings");
+		frame.setIconImage(ImageImport.loadImage("/Images/Holeg.png",30,30));
+		frame.setContentPane(createEditFormular(frame));
+		frame.pack();
+		frame.setPreferredSize(new Dimension(400,frame.getHeight()));
+		frame.pack();
+		frame.setVisible(true);
+		frame.setLocationRelativeTo(parent);
+		frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
+	}
+	
+	
+	private static JPanel createEditFormular(JFrame frame) {
+		JPanel panel = new JPanel();
+		panel.setLayout(new BorderLayout());
+		panel.setBorder(BorderFactory.createEmptyBorder(0,5,0,5));
+		
+		JPanel infoPanel = new JPanel();
+		GridLayout infoLayout= new GridLayout(0,2);
+		infoPanel.add(new JLabel("SMTP Hostname:"));
+		JTextField hostnameTextField = new JTextField(_info.Hostname);
+		infoPanel.add(hostnameTextField);
+		infoPanel.add(new JLabel("Port:"));
+		JTextField portTextField = new JTextField(Integer.toString(_info.Port));
+		infoPanel.add(portTextField);
+		infoPanel.add(new JLabel("Username:"));
+		JTextField usernameTextField = new JTextField(_info.Username);
+		infoPanel.add(usernameTextField);
+		infoPanel.add(new JLabel("Password:"));
+		JPasswordField  passwordTextField = new JPasswordField (_info.Password);
+		infoPanel.add(passwordTextField);
+		infoPanel.add(new JLabel("From Email:"));
+		JTextField fromEmailTextField = new JTextField(_info.FromEmail);
+		infoPanel.add(fromEmailTextField);
+		infoPanel.add(new JLabel("To Email:"));
+		JTextField toEmailTextField = new JTextField(_info.ToEmail);
+		infoPanel.add(toEmailTextField);
+		infoPanel.setLayout(infoLayout);
+		panel.add(infoPanel, BorderLayout.CENTER);
+		
+		JPanel controlPanel = new JPanel();
+		controlPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
+		controlPanel.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
+		JButton cancelButton = new JButton("Cancel");
+		cancelButton.addActionListener(event -> {
+			frame.dispose();
+		});
+		controlPanel.add(cancelButton);
+		JButton applyButton = new JButton("Apply and Close");
+		applyButton.addActionListener(event -> {
+			// parse Textfields
+			_info.Hostname = hostnameTextField.getText();
+			_info.Port = Integer.valueOf(portTextField.getText());
+			_info.Username = usernameTextField.getText();
+			_info.Password =  String.valueOf(passwordTextField.getPassword());
+			_info.FromEmail = fromEmailTextField.getText();
+			_info.ToEmail = toEmailTextField.getText();
+			// Save Preferences
+			savePreferences();
+			frame.dispose();
+		});
+		controlPanel.add(applyButton);
+		
+		JButton testButton = new JButton("Send Test-Email");
+		testButton.addActionListener(event -> {
+			// parse Textfields
+			EmailSmtpInformation testinfo = new EmailSmtpInformation();
+			testinfo.Hostname = hostnameTextField.getText();
+			testinfo.Port = Integer.valueOf(portTextField.getText());
+			testinfo.Username = usernameTextField.getText();
+			testinfo.Password = String.valueOf(passwordTextField.getPassword());
+			testinfo.FromEmail = fromEmailTextField.getText();
+			testinfo.ToEmail = toEmailTextField.getText();
+			sendEmail(testinfo, "Holeg Notification Test", "Success.");
+		});
+		controlPanel.add(testButton);
+		
+		panel.add(controlPanel, BorderLayout.PAGE_END);
+		
+		
+		
+		return panel;
+	}
+	public static void sendEmail(String subject, String message) {
+		loadPreferences();
+		sendEmail(_info, subject, message);
+	}
+
+	public static void sendEmail(EmailSmtpInformation info, String subject, String message) {
+		Email email = new SimpleEmail();
+		email.setHostName(info.Hostname);
+		email.setSmtpPort(info.Port);
+		email.setAuthenticator(new DefaultAuthenticator(info.Username, info.Password));
+		email.setSSLOnConnect(true);
+		email.setSubject(subject);
+		try {
+			email.setFrom(info.FromEmail);
+			email.setMsg(message);
+			email.addTo(info.ToEmail);
+			email.send();
+		} catch (EmailException e) {
+			e.printStackTrace();
+		}
+	}
+	
+	private static void savePreferences() {
+		_prefs = Preferences.userRoot().node("EmailNotification");
+		_prefs.put("Hostname", _info.Hostname);
+		_prefs.putInt("Port", _info.Port);
+		_prefs.put("Username", _info.Username);
+		_prefs.put("Password", _info.Password);
+		_prefs.put("FromEmail", _info.FromEmail);
+		_prefs.put("ToEmail", _info.ToEmail);
+	}
+	
+	private static void loadPreferences() {
+		_prefs = Preferences.userRoot().node("EmailNotification");
+		_info.Hostname = _prefs.get("Hostname", "");
+		_info.Port = _prefs.getInt("Port", 465);
+		_info.Username = _prefs.get("Username", "");
+		_info.Password = _prefs.get("Password", "");
+		_info.FromEmail= _prefs.get("FromEmail", "");
+		_info.ToEmail = _prefs.get("ToEmail", "");
+	}
+	
+	
+	
+}

+ 42 - 42
src/addOns/JSON/FlexibilitySketch.java → src/addOns/Utility/FlexibilitySketch.java

@@ -1,43 +1,43 @@
-package addOns.JSON;
-
-public class FlexibilitySketch{
-	public double flexChance;
-	public float minCost;
-	public float maxCost;
-	/** The Duration in TimeSteps how long the Flexibility is activated.*/
-	public int minDuration;
-	public int maxDuration;
-	/** The Duration after a successful activation between the next possible activation.*/
-	public int minCooldown;
-	public int maxCooldown;
-	
-	
-	public void checkValues(){
-
-		minDuration = Math.abs(minDuration);
-		maxDuration = Math.abs(maxDuration);
-		if(maxDuration < minDuration) {
-			//Swap
-			int intermediate = minDuration;
-			minDuration = maxDuration;
-			maxDuration = intermediate;
-		}
-		minCooldown = Math.abs(minCooldown);
-		maxCooldown = Math.abs(maxCooldown);
-		if(maxCooldown < minCooldown) {
-			//Swap
-			int intermediate = minCooldown;
-			minCooldown = maxCooldown;
-			maxCooldown = intermediate;
-		}
-		minCost = Math.abs(minCost);
-		maxCost = Math.abs(maxCost);
-		if(maxCost < minCost) {
-			//Swap
-			float intermediate = minCost;
-			minCost = maxCost;
-			maxCost = intermediate;
-		}
-		flexChance = Math.max(0, Math.min(1, flexChance)); //Clamp
-	}
+package addOns.Utility;
+
+public class FlexibilitySketch{
+	public double flexChance;
+	public float minCost;
+	public float maxCost;
+	/** The Duration in TimeSteps how long the Flexibility is activated.*/
+	public int minDuration;
+	public int maxDuration;
+	/** The Duration after a successful activation between the next possible activation.*/
+	public int minCooldown;
+	public int maxCooldown;
+	
+	
+	public void checkValues(){
+
+		minDuration = Math.abs(minDuration);
+		maxDuration = Math.abs(maxDuration);
+		if(maxDuration < minDuration) {
+			//Swap
+			int intermediate = minDuration;
+			minDuration = maxDuration;
+			maxDuration = intermediate;
+		}
+		minCooldown = Math.abs(minCooldown);
+		maxCooldown = Math.abs(maxCooldown);
+		if(maxCooldown < minCooldown) {
+			//Swap
+			int intermediate = minCooldown;
+			minCooldown = maxCooldown;
+			maxCooldown = intermediate;
+		}
+		minCost = Math.abs(minCost);
+		maxCost = Math.abs(maxCost);
+		if(maxCost < minCost) {
+			//Swap
+			float intermediate = minCost;
+			minCost = maxCost;
+			maxCost = intermediate;
+		}
+		flexChance = Math.max(0, Math.min(1, flexChance)); //Clamp
+	}
 }

+ 72 - 111
src/addOns/JSON/HolonElementSketch.java → src/addOns/Utility/HolonElementSketch.java

@@ -1,111 +1,72 @@
-package addOns.JSON;
-
-import classes.Constrain;
-import classes.Flexibility;
-import classes.HolonElement;
-import classes.HolonElement.Priority;
-import classes.HolonObject;
-import ui.model.Model;
-
-public class HolonElementSketch {
-	//HolonElement
-	public String name;
-	public int minAmount;
-	public int maxAmount;
-	public float energy;
-	
-	public String priority;
-	
-	public FlexibilitySketch onFlex;
-	public FlexibilitySketch offFlex;
-	
-	public HolonElementSketch(String name, int minAmount, int maxAmount, float energy) {
-		this.name = name;
-		this.minAmount = minAmount;
-		this.maxAmount = maxAmount;
-		this.energy = energy;
-	}
-	public HolonElement createHolonElement(HolonObject parentObject, boolean active) {
-		HolonElement ele = new HolonElement(parentObject, name, Random.nextIntegerInRange(minAmount, maxAmount + 1), energy);
-		ele.setActive(active);
-		if(onFlex != null && Random.nextDouble() < onFlex.flexChance)addFlex(ele, parentObject.getName(), true);
-		if(offFlex != null && Random.nextDouble() < offFlex.flexChance)addFlex(ele, parentObject.getName(), false);
-		ele.setPriority(Priority.valueOf(priority));
-		return ele;
-	}
-	
-	public void checkValues() {
-		minAmount = Math.abs(minAmount);
-		maxAmount = Math.abs(maxAmount);
-		if(maxAmount < minAmount) {
-			//Swap
-			int intermediate = minAmount;
-			minAmount = maxAmount;
-			maxAmount = intermediate;
-		}
-		if(onFlex != null) {
-			onFlex.checkValues();				
-		}
-		if(offFlex != null) {
-			onFlex.checkValues();				
-		}
-	}
-	
-	public void addFlex(HolonElement ele, String nameOfHolonObject,boolean onConstrain) {
-		Flexibility toCreateFlex = new Flexibility(ele);
-		FlexibilitySketch constrain = onConstrain?onFlex:offFlex;
-		
-		
-		toCreateFlex.name = nameOfHolonObject + "_" + ele.getEleName() + (onConstrain?"_OnFlex":"_OffFlex");
-		toCreateFlex.speed = 0;
-		toCreateFlex.setDuration(Random.nextIntegerInRange(constrain.minDuration, constrain.maxDuration+1));
-		toCreateFlex.cost = Random.nextFloatInRange(constrain.minCost, constrain.maxCost);
-		toCreateFlex.setCooldown(Random.nextIntegerInRange(constrain.minCooldown, constrain.maxCooldown+1));
-		toCreateFlex.offered=true;
-		if(onConstrain) {
-			toCreateFlex.constrainList.add(Constrain.createOnConstrain());
-		}else {
-			toCreateFlex.constrainList.add(Constrain.createOffConstrain());
-		}
-		ele.flexList.add(toCreateFlex);
-	}
-private static class Random{
-		
-		
-		private static java.util.Random random = new java.util.Random();
-	
-		/**
-		 * True or false
-		 * @return the random boolean.
-		 */
-		public static boolean nextBoolean(){
-			return random.nextBoolean();
-		}
-		/**
-		 * Between 0.0(inclusive) and 1.0 (exclusive)
-		 * @return the random double.
-		 */
-		public static double nextDouble() {
-			return random.nextDouble();
-		}
-		
-		public static float nextFloatInRange(float min, float max) {
-			return min + random.nextFloat() * Math.abs(max - min);
-		}
-		
-		
-		public static double nextDoubleInRange(double min, double max) {
-			return min + random.nextDouble() * Math.abs(max - min);
-		}
-		
-		/**
-		 * Random Int in Range [min;max[ with UniformDistirbution
-		 * @param min
-		 * @param max
-		 * @return
-		 */
-		public static int nextIntegerInRange(int min, int max) {
-			return min + random.nextInt(max - min);
-		}
-	}
-}
+package addOns.Utility;
+
+import classes.Constrain;
+import classes.Flexibility;
+import classes.HolonElement;
+import classes.HolonElement.Priority;
+import classes.HolonObject;
+import utility.Random;
+
+public class HolonElementSketch {
+	//HolonElement
+	public String name;
+	public int minAmount;
+	public int maxAmount;
+	public float energy;
+	
+	public String priority;
+	
+	public FlexibilitySketch onFlex;
+	public FlexibilitySketch offFlex;
+	
+	public HolonElementSketch(String name, int minAmount, int maxAmount, float energy) {
+		this.name = name;
+		this.minAmount = minAmount;
+		this.maxAmount = maxAmount;
+		this.energy = energy;
+	}
+	public HolonElement createHolonElement(HolonObject parentObject, boolean active) {
+		HolonElement ele = new HolonElement(parentObject, name, Random.nextIntegerInRange(minAmount, maxAmount + 1), energy);
+		ele.setActive(active);
+		if(onFlex != null && Random.nextDouble() < onFlex.flexChance)addFlex(ele, parentObject.getName(), true);
+		if(offFlex != null && Random.nextDouble() < offFlex.flexChance)addFlex(ele, parentObject.getName(), false);
+		ele.setPriority(Priority.valueOf(priority));
+		return ele;
+	}
+	
+	public void checkValues() {
+		minAmount = Math.abs(minAmount);
+		maxAmount = Math.abs(maxAmount);
+		if(maxAmount < minAmount) {
+			//Swap
+			int intermediate = minAmount;
+			minAmount = maxAmount;
+			maxAmount = intermediate;
+		}
+		if(onFlex != null) {
+			onFlex.checkValues();				
+		}
+		if(offFlex != null) {
+			onFlex.checkValues();				
+		}
+	}
+	
+	public void addFlex(HolonElement ele, String nameOfHolonObject,boolean onConstrain) {
+		Flexibility toCreateFlex = new Flexibility(ele);
+		FlexibilitySketch constrain = onConstrain?onFlex:offFlex;
+		
+		
+		toCreateFlex.name = nameOfHolonObject + "_" + ele.getEleName() + (onConstrain?"_OnFlex":"_OffFlex");
+		toCreateFlex.speed = 0;
+		toCreateFlex.setDuration(Random.nextIntegerInRange(constrain.minDuration, constrain.maxDuration+1));
+		toCreateFlex.cost = Random.nextFloatInRange(constrain.minCost, constrain.maxCost);
+		toCreateFlex.setCooldown(Random.nextIntegerInRange(constrain.minCooldown, constrain.maxCooldown+1));
+		toCreateFlex.offered=true;
+		if(onConstrain) {
+			toCreateFlex.constrainList.add(Constrain.createOnConstrain());
+		}else {
+			toCreateFlex.constrainList.add(Constrain.createOffConstrain());
+		}
+		ele.flexList.add(toCreateFlex);
+	}
+}

+ 134 - 135
src/ui/view/RandomPriotity.java → src/addOns/Utility/RandomPriotity.java

@@ -1,135 +1,134 @@
-package ui.view;
-
-import java.util.Hashtable;
-
-import javax.swing.BorderFactory;
-import javax.swing.BoxLayout;
-import javax.swing.JLabel;
-import javax.swing.JPanel;
-import javax.swing.JSlider;
-
-import classes.HolonElement.Priority;
-
-@SuppressWarnings("serial")
-public class RandomPriotity extends JPanel{
-	/**
-	 * Its like a Gradient the Values are on one Axis from Start to End:
-	 * |--start--lm--mh--he--end--|
-	 * lm: lowMedium
-	 * mh: mediumHigh
-	 * he: highEssential
-	 */
-	private int lm = 25 , mh = 50, he = 75;
-	private final int start = 0, end = 100;
-	
-	private JSlider lowChanceSlider = new JSlider(JSlider.HORIZONTAL,0, 100, lm - start);
-	private JSlider mediumChanceSlider = new JSlider(JSlider.HORIZONTAL,0, 100, mh - lm);
-	private JSlider highChanceSlider = new JSlider(JSlider.HORIZONTAL,0, 100, he - mh);
-	private JSlider essentialChanceSlider = new JSlider(JSlider.HORIZONTAL,0, 100, end - he);
-	
-	
-	public RandomPriotity(){
-		this.setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
-		this.add(initVisualizeSlider(this.lowChanceSlider, "Low"));
-		this.add(initVisualizeSlider(this.mediumChanceSlider, "Medium"));
-		this.add(initVisualizeSlider(this.highChanceSlider, "High"));
-		this.add(initVisualizeSlider(this.essentialChanceSlider, "Essential"));
-		lowChanceSlider.setToolTipText("" +((double)lowChanceSlider.getValue()/ 100.0));
-		mediumChanceSlider.setToolTipText("" +((double)mediumChanceSlider.getValue()/ 100.0));
-		highChanceSlider.setToolTipText("" +((double)highChanceSlider.getValue()/ 100.0));
-		essentialChanceSlider.setToolTipText("" +((double)essentialChanceSlider.getValue()/ 100.0));
-		lowChanceSlider.addChangeListener(actionEvent ->{
-			setLM(lowChanceSlider.getValue());
-			updateSliders();
-			lowChanceSlider.setToolTipText("" +((double)lowChanceSlider.getValue()/ 100.0));
-			System.out.println("lowChance = " +lowChanceSlider.getValue());
-		});
-		mediumChanceSlider.addChangeListener(actionEvent ->{
-			if(lm + mediumChanceSlider.getValue() <= 100) setMH(lm + mediumChanceSlider.getValue());
-			else setLM(end - mediumChanceSlider.getValue());
-			updateSliders();
-			mediumChanceSlider.setToolTipText("" +((double)mediumChanceSlider.getValue()/ 100.0));
-			System.out.println("mediumChance = " +  mediumChanceSlider.getValue());
-		});
-		highChanceSlider.addChangeListener(actionEvent ->{
-			if(mh + highChanceSlider.getValue() <= 100) setHE(mh + highChanceSlider.getValue());
-			else setMH(end - highChanceSlider.getValue());
-			updateSliders();
-			highChanceSlider.setToolTipText("" +((double)highChanceSlider.getValue()/ 100.0));
-			System.out.println("highChance = " +highChanceSlider.getValue());
-		});
-		essentialChanceSlider.addChangeListener(actionEvent ->{
-			setHE(end - essentialChanceSlider.getValue());
-			updateSliders();
-			essentialChanceSlider.setToolTipText("" +((double)essentialChanceSlider.getValue()/ 100.0));
-			System.out.println("essentialChance = " +essentialChanceSlider.getValue());
-		});
-	}
-
-	private void setLM(int value) {
-		lm = clamp(value, 0, 100);
-		if(lm > mh) mh = lm;
-		if(lm > he) he = lm;
-	}
-	
-	private void setMH(int value) {
-		mh = clamp(value, 0, 100);
-		if(mh < lm) lm = mh;
-		if(mh > he) he = mh;
-	}
-	
-	private void setHE(int value) {
-		he = clamp(value, 0, 100);
-		if(he < lm) lm = he;
-		if(he < mh) mh = he;
-	}
-	
-	
-	private int clamp(int input, int min , int max) {
-		return Math.max(min, Math.min(max, input));
-	}
-	
-	
-	private void updateSliders(){
-		lowChanceSlider.setValue(lm - start);
-		mediumChanceSlider.setValue(mh - lm);
-		highChanceSlider.setValue(he - mh);
-		essentialChanceSlider.setValue(end - he);
-	}
-	
-	
-
-	private JSlider initVisualizeSlider(JSlider jslider, String name) {
-		jslider.setBorder(BorderFactory.createTitledBorder(name));
-		jslider.setMajorTickSpacing(50);
-		jslider.setMinorTickSpacing(5);
-		jslider.setPaintTicks(true);
-		Hashtable<Integer, JLabel> labelTable = new Hashtable<Integer, JLabel>();
-		labelTable.put( Integer.valueOf( 0 ), new JLabel("0.0") );
-		labelTable.put( Integer.valueOf( 50 ), new JLabel("0.5") );
-		labelTable.put( Integer.valueOf( 100 ), new JLabel("1.0") );
-		jslider.setLabelTable( labelTable );
-		jslider.setPaintLabels(true);
-		return jslider;
-	}
-	
-	public Priority getPriority() {
-		double randomDoubleInRange = Math.random() * 100.0;
-		if(randomDoubleInRange <= lm) {
-			return Priority.Low;
-		} else if(randomDoubleInRange <= mh) {
-			return Priority.Medium;
-		} else if(randomDoubleInRange <= he) {
-			return Priority.High;
-		} else {
-			return Priority.Essential;
-		}
-	}
-	@Override
-	public void setEnabled(boolean value) {
-		lowChanceSlider.setEnabled(value);
-		mediumChanceSlider.setEnabled(value);
-		highChanceSlider.setEnabled(value);
-		essentialChanceSlider.setEnabled(value);
-	}
-}
+package addOns.Utility;
+
+import java.util.Hashtable;
+
+import javax.swing.BorderFactory;
+import javax.swing.BoxLayout;
+import javax.swing.JLabel;
+import javax.swing.JPanel;
+import javax.swing.JSlider;
+
+import classes.HolonElement.Priority;
+
+public class RandomPriotity extends JPanel{
+	/**
+	 * Its like a Gradient the Values are on one Axis from Start to End:
+	 * |--start--lm--mh--he--end--|
+	 * lm: lowMedium
+	 * mh: mediumHigh
+	 * he: highEssential
+	 */
+	private int lm = 25 , mh = 50, he = 75;
+	private final int start = 0, end = 100;
+	
+	private JSlider lowChanceSlider = new JSlider(JSlider.HORIZONTAL,0, 100, lm - start);
+	private JSlider mediumChanceSlider = new JSlider(JSlider.HORIZONTAL,0, 100, mh - lm);
+	private JSlider highChanceSlider = new JSlider(JSlider.HORIZONTAL,0, 100, he - mh);
+	private JSlider essentialChanceSlider = new JSlider(JSlider.HORIZONTAL,0, 100, end - he);
+	
+	
+	public RandomPriotity(){
+		this.setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
+		this.add(initVisualizeSlider(this.lowChanceSlider, "Low"));
+		this.add(initVisualizeSlider(this.mediumChanceSlider, "Medium"));
+		this.add(initVisualizeSlider(this.highChanceSlider, "High"));
+		this.add(initVisualizeSlider(this.essentialChanceSlider, "Essential"));
+		lowChanceSlider.setToolTipText("" +((double)lowChanceSlider.getValue()/ 100.0));
+		mediumChanceSlider.setToolTipText("" +((double)mediumChanceSlider.getValue()/ 100.0));
+		highChanceSlider.setToolTipText("" +((double)highChanceSlider.getValue()/ 100.0));
+		essentialChanceSlider.setToolTipText("" +((double)essentialChanceSlider.getValue()/ 100.0));
+		lowChanceSlider.addChangeListener(actionEvent ->{
+			setLM(lowChanceSlider.getValue());
+			updateSliders();
+			lowChanceSlider.setToolTipText("" +((double)lowChanceSlider.getValue()/ 100.0));
+			System.out.println("lowChance = " +lowChanceSlider.getValue());
+		});
+		mediumChanceSlider.addChangeListener(actionEvent ->{
+			if(lm + mediumChanceSlider.getValue() <= 100) setMH(lm + mediumChanceSlider.getValue());
+			else setLM(end - mediumChanceSlider.getValue());
+			updateSliders();
+			mediumChanceSlider.setToolTipText("" +((double)mediumChanceSlider.getValue()/ 100.0));
+			System.out.println("mediumChance = " +  mediumChanceSlider.getValue());
+		});
+		highChanceSlider.addChangeListener(actionEvent ->{
+			if(mh + highChanceSlider.getValue() <= 100) setHE(mh + highChanceSlider.getValue());
+			else setMH(end - highChanceSlider.getValue());
+			updateSliders();
+			highChanceSlider.setToolTipText("" +((double)highChanceSlider.getValue()/ 100.0));
+			System.out.println("highChance = " +highChanceSlider.getValue());
+		});
+		essentialChanceSlider.addChangeListener(actionEvent ->{
+			setHE(end - essentialChanceSlider.getValue());
+			updateSliders();
+			essentialChanceSlider.setToolTipText("" +((double)essentialChanceSlider.getValue()/ 100.0));
+			System.out.println("essentialChance = " +essentialChanceSlider.getValue());
+		});
+	}
+
+	private void setLM(int value) {
+		lm = clamp(value, 0, 100);
+		if(lm > mh) mh = lm;
+		if(lm > he) he = lm;
+	}
+	
+	private void setMH(int value) {
+		mh = clamp(value, 0, 100);
+		if(mh < lm) lm = mh;
+		if(mh > he) he = mh;
+	}
+	
+	private void setHE(int value) {
+		he = clamp(value, 0, 100);
+		if(he < lm) lm = he;
+		if(he < mh) mh = he;
+	}
+	
+	
+	private int clamp(int input, int min , int max) {
+		return Math.max(min, Math.min(max, input));
+	}
+	
+	
+	private void updateSliders(){
+		lowChanceSlider.setValue(lm - start);
+		mediumChanceSlider.setValue(mh - lm);
+		highChanceSlider.setValue(he - mh);
+		essentialChanceSlider.setValue(end - he);
+	}
+	
+	
+
+	private JSlider initVisualizeSlider(JSlider jslider, String name) {
+		jslider.setBorder(BorderFactory.createTitledBorder(name));
+		jslider.setMajorTickSpacing(50);
+		jslider.setMinorTickSpacing(5);
+		jslider.setPaintTicks(true);
+		Hashtable<Integer, JLabel> labelTable = new Hashtable<Integer, JLabel>();
+		labelTable.put( Integer.valueOf( 0 ), new JLabel("0.0") );
+		labelTable.put( Integer.valueOf( 50 ), new JLabel("0.5") );
+		labelTable.put( Integer.valueOf( 100 ), new JLabel("1.0") );
+		jslider.setLabelTable( labelTable );
+		jslider.setPaintLabels(true);
+		return jslider;
+	}
+	
+	public Priority getPriority() {
+		double randomDoubleInRange = Math.random() * 100.0;
+		if(randomDoubleInRange <= lm) {
+			return Priority.Low;
+		} else if(randomDoubleInRange <= mh) {
+			return Priority.Medium;
+		} else if(randomDoubleInRange <= he) {
+			return Priority.High;
+		} else {
+			return Priority.Essential;
+		}
+	}
+	@Override
+	public void setEnabled(boolean value) {
+		lowChanceSlider.setEnabled(value);
+		mediumChanceSlider.setEnabled(value);
+		highChanceSlider.setEnabled(value);
+		essentialChanceSlider.setEnabled(value);
+	}
+}

+ 210 - 213
src/algorithm/binary/AcoAlgorithm.java

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

+ 0 - 35
src/algorithm/binary/BaseLine.java

@@ -2,23 +2,12 @@ package algorithm.binary;
 
 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;
 
@@ -26,18 +15,13 @@ 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.AddOn;
 import classes.AbstractCanvasObject;
@@ -47,7 +31,6 @@ 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;
@@ -77,8 +60,6 @@ public class BaseLine implements AddOn {
 	private JTextArea textArea;
 	private JPanel content = new JPanel();
 	//ProgressBar
-	private JProgressBar progressBar = new JProgressBar();
-	private int progressBarCount = 0;
 	private long startTime;
 	private Thread runThread;
 	
@@ -186,7 +167,6 @@ public class BaseLine implements AddOn {
 			println("");
 			println("Cancel run.");
 			cancel = true;
-			progressBar.setValue(0);
 		} else {
 			println("Nothing to cancel.");
 		}
@@ -238,9 +218,6 @@ public class BaseLine implements AddOn {
 	private void clear() {
 		textArea.setText("");
 	}
-	private void print(String message) {
-		textArea.append(message);
-	}
 	private void println(String message) {
 		textArea.append(message  + "\n");
 	}
@@ -253,15 +230,6 @@ public class BaseLine implements AddOn {
 			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();
@@ -453,9 +421,6 @@ public class BaseLine implements AddOn {
 			}
 				
 		}
-		public boolean getState(int timeStep) {
-			return (type == HOLONELEMENT)?hElement.isActive():hSwitch.getState(timeStep);
-		}
 		public int getType() {
 			return type;
 		}

+ 251 - 254
src/algorithm/binary/GaAlgorithm.java

@@ -1,254 +1,251 @@
-package algorithm.binary;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.ListIterator;
-import java.util.TreeSet;
-
-import javax.swing.JFrame;
-
-import algorithm.objectiveFunction.ObjectiveFunctionByCarlos;
-import api.AlgorithmFrameworkFlex;
-import ui.model.DecoratedState;
-
-public class GaAlgorithm extends AlgorithmFrameworkFlex{
-
-	/**
-	 * Should be even.
-	 */
-	private int popsize = 20;
-	private int maxGenerations = 100;
-	private double tournamentSize = 2.0;
-	private double swapProbability = 0.02;
-	private double mutateProbability = 0.02;
-	private boolean useIntervalMutation = false;
-	private double mutateProbabilityInterval = 0.01;
-	private double maxMutationPercent = 0.01;
-	private boolean moreInformation = false;
-	
-	
-	public GaAlgorithm() {
-		super();
-		addIntParameter("popsize", popsize, intValue -> popsize = intValue, () -> popsize, 1);
-		addIntParameter("maxGenerations", maxGenerations, intValue -> maxGenerations = intValue, () -> maxGenerations, 1);
-		addDoubleParameter("tournamentSize", tournamentSize, doubleValue -> tournamentSize = doubleValue, () -> tournamentSize, 1.0);
-		addDoubleParameter("SwapProbability", swapProbability, doubleValue -> swapProbability = doubleValue, () -> swapProbability, 0.0, 1.0);
-		addDoubleParameter("MutateProbability", mutateProbability, doubleValue -> mutateProbability = doubleValue, () -> mutateProbability, 0.0, 1.0);
-		addBooleanParameter("useIntervalMutation", useIntervalMutation, booleanValue -> useIntervalMutation = booleanValue);
-		addDoubleParameter("mutateProbabilityInterval", mutateProbabilityInterval, doubleValue -> mutateProbabilityInterval = doubleValue, () -> mutateProbabilityInterval, 0.0, 1.0);
-		addDoubleParameter("maxMutationPercent", maxMutationPercent, doubleValue -> maxMutationPercent = doubleValue, () -> maxMutationPercent, 0.0, 1.0);
-		addBooleanParameter("moreInformation", moreInformation, booleanValue -> moreInformation = booleanValue);
-	}
-	
-	public static void main(String[] args)
-	{
-	      JFrame newFrame = new JFrame("exampleWindow");
-	      GaAlgorithm instance = new GaAlgorithm();
-	      newFrame.setContentPane(instance.getPanel());
-	      newFrame.pack();
-	      newFrame.setVisible(true);
-	      newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
-	}
-	
-
-	@Override
-	protected int getProgressBarMaxCount() {
-		return this.maxGenerations * this.popsize * this.rounds + rounds;
-	}
-	
-	@Override
-	protected Individual executeAlgo() {
-		Individual best = new Individual();
-		best.position = extractPositionAndAccess();
-		if(moreInformation)console.println("Bit-Array_length: " + best.position.size());
-		best.fitness = evaluatePosition(best.position);
-		List<Double> runList = new ArrayList<Double>();
-		runList.add(best.fitness);
-		console.print("Start with: " + best.fitness);
-		if(moreInformation)console.println("");
-		int problemSize = best.position.size();
-		List<Individual> population = initPopuluationRandom(problemSize, best);
-		if(moreInformation)console.println("Size To Test:" + population.size());
-		for(int generation = 0; generation< maxGenerations; generation++) {
-			if(moreInformation)console.println("Generation" + generation + " start with Fitness: " + best.fitness);
-			for(Individual i : population) {
-				i.fitness = evaluatePosition(i.position);
-				if(moreInformation)console.println("Fitness" + i.fitness);
-				if(i.fitness < best.fitness) best = i;
-				
-			}
-			runList.add(best.fitness);
-			List<Individual> childList = new ArrayList<Individual>();
-			for(int k = 0; k<popsize/2; k++) {
-				Individual parentA = selectAParent(population, popsize);
-				Individual parentB = selectAParent(population, popsize);
-				Individual childA = new Individual(parentA);
-				Individual childB = new Individual(parentB);
-				crossover(childA, childB, problemSize);
-				if(useIntervalMutation)mutateInterval(childA, problemSize);else mutate(childA, problemSize);
-				if(useIntervalMutation)mutateInterval(childB, problemSize);else mutate(childB, problemSize);
-				childList.add(childA);
-				childList.add(childB);
-			}
-			population = childList;
-			if(moreInformation)console.println("________________");
-			if(cancel)return null;
-		}
-		
-		
-		console.println("   End with:" + best.fitness);
-		this.runList = runList;
-		return best;
-	}
-	/**
-	 * Algorithm 22 Bit-Flip Mutation.
-	 * 
-	 */
-	private void mutate(Individual child, int problemSize) {
-		ListIterator<Boolean> iter = child.position.listIterator();
-		while(iter.hasNext()) {
-			boolean boolValue = iter.next();
-			if(Random.nextDouble() <=  this.mutateProbability) {
-				iter.set(!boolValue);
-			}
-		}
-	}
-	
-	/**
-	 * Algorithm rolf
-	 * 
-	 */
-	private void mutateInterval(Individual child, int problemSize) {
-		//If not mutate skip
-		if(Random.nextDouble() >  this.mutateProbabilityInterval) {
-			return;
-		}
-		//println("problemSize:" + problemSize + "    maxMutationPercent:" + maxMutationPercent);
-		int maximumAmountOfMutatedBits = Math.max(1, (int)Math.round(((double) problemSize) * this.maxMutationPercent));
-		int randomUniformAmountOfMutatedValues = Random.nextIntegerInRange(1,maximumAmountOfMutatedBits + 1);
-		
-		//println("max:" + maximumAmountOfMutatedBits + "   actual:" + randomUniformAmountOfMutatedValues);
-		TreeSet<Integer> mutationLocation = new TreeSet<Integer>(); //sortedSet
-		//Choose the location to mutate
-		for(int i = 0; i< randomUniformAmountOfMutatedValues; i++) {
-			boolean success = mutationLocation.add(Random.nextIntegerInRange(0, problemSize));
-			if(!success) i--; //can be add up to some series long loops if maximumAmountOfMutatedBits get closed to problemsize.
-		}
-		//println("Set:" + mutationLocation);
-		ListIterator<Boolean> iter = child.position.listIterator();
-		if(mutationLocation.isEmpty()) return;
-		int firstindex = mutationLocation.pollFirst();
-		while(iter.hasNext()) {
-			int index = iter.nextIndex();
-			boolean boolValue = iter.next();
-			if(index == firstindex) {
-				iter.set(!boolValue);
-				if(mutationLocation.isEmpty()) break;
-				firstindex = mutationLocation.pollFirst();
-			}
-		}
-	}
-	
-	
-	
-	
-	/** 
-	 * Algorithm 25 Uniform Crossover.
-	 * Probability is set to 1/Problemsize when not changed.
-	 */
-	private void crossover(Individual childA, Individual childB, int problemSize) {
-		ListIterator<Boolean> iterA = childA.position.listIterator();
-		ListIterator<Boolean> iterB = childB.position.listIterator();
-		for(int i= 0; i < problemSize; i++) {
-			boolean boolA = iterA.next();
-			boolean boolB = iterB.next();
-			if(Random.nextDouble() <=  this.swapProbability ) {
-				//Swap 
-				iterA.set(boolB);
-				iterB.set(boolA);
-			}
-		}
-	}
-	/**
-	 * Algorithm 32 Tournament Selection.
-	 * The fitnessValues are calculated for the Population List.
-	 * PseudoCode
-	 */
-	private Individual selectAParent(List<Individual> population,int popsize) {
-		Individual tournamentBest = population.get(Random.nextIntegerInRange(0, popsize));
-		double participants;
-		for(participants = tournamentSize ; participants >= 2; participants -= 1.0) {
-			Individual next = population.get(Random.nextIntegerInRange(0, popsize));
-			if(next.fitness < tournamentBest.fitness) tournamentBest = next;
-		}
-		//if tournament size is not a whole number like 2.5 or 3.6
-		//the remaining part is the chance to fight another time; 2.7 -> 70% chance to fight a second time
-		if( participants > 1) {		
-			if(Random.nextDouble() < participants - 1.0) {
-				//println("Chance to find a match");
-				Individual next = population.get(Random.nextIntegerInRange(0, popsize));
-				if(next.fitness < tournamentBest.fitness) tournamentBest = next;
-			}
-		}
-		return tournamentBest;
-	}
-	/**
-	 * Initialize the Population with Individuals that have a random Position.
-	 */
-	private List<Individual> initPopuluationRandom(int problemSize, Individual startIndidual){
-		List<Individual> population =  new ArrayList<Individual>();
-		for(int i = 0; i < popsize -1; i++) {
-			population.add(createRandomIndividualWithoutFitness(problemSize));
-		}
-		//Add Start Position
-		population.add(new Individual(startIndidual));
-		return population;
-	}
-	
-	
-	
-	/**
-	 * Algorithm 21 The BooleanVeator initialization.
-	 * @param problemSize
-	 * @return
-	 */
-	private Individual createRandomIndividualWithoutFitness(int problemSize) {
-		//create Random Individual Without Fitness
-		Individual result = new Individual();
-		result.position = new ArrayList<Boolean>();
-		for (int index = 0; index < problemSize; index++){
-			result.position.add(Random.nextBoolean());
-		}
-		return result;
-	}
-
-	@Override
-	protected String algoInformationToPrint() {
-//		private int popsize = 20;
-//		private int maxGenerations = 100;
-//		private double tournamentSize = 2.0;
-//		private double fixedSwapProbability = 0.02;
-//		private boolean useFixedSpawProbability = false;
-//		private double fixedMutateProbability = 0.02;
-//		private boolean useFixedMutateProbability = false;
-//		private boolean useIntervalMutation = true;
-//		private double mutateProbabilityInterval = 0.01;
-//		private double maxMutationPercent = 0.01;
-		return "GaAlgo"
-				+ " Rounds: " + rounds 
-				+ " Iterations: " + maxGenerations
-				+ " Individuals: " + popsize
-				+ " TournamentSize: " +  tournamentSize
-				+ " SwapProbability: " +  swapProbability
-				+ (useIntervalMutation? 
-						(" MutateProbabilityInterval: " +  mutateProbabilityInterval
-						+ " MaxMutationPercent: " +  maxMutationPercent)
-						: 
-						(" MutateProbability: " +  mutateProbability));
-	}
-
-	@Override
-	protected String plottFileName() {
-		return "plottGaAlgo.txt";
-	}
-}
+package algorithm.binary;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.ListIterator;
+import java.util.TreeSet;
+
+import javax.swing.JFrame;
+import api.AlgorithmFrameworkFlex;
+
+public class GaAlgorithm extends AlgorithmFrameworkFlex{
+
+	/**
+	 * Should be even.
+	 */
+	private int popsize = 20;
+	private int maxGenerations = 100;
+	private double tournamentSize = 2.0;
+	private double swapProbability = 0.02;
+	private double mutateProbability = 0.02;
+	private boolean useIntervalMutation = false;
+	private double mutateProbabilityInterval = 0.01;
+	private double maxMutationPercent = 0.01;
+	private boolean moreInformation = false;
+	
+	
+	public GaAlgorithm() {
+		super();
+		addIntParameter("popsize", popsize, intValue -> popsize = intValue, () -> popsize, 1);
+		addIntParameter("maxGenerations", maxGenerations, intValue -> maxGenerations = intValue, () -> maxGenerations, 1);
+		addDoubleParameter("tournamentSize", tournamentSize, doubleValue -> tournamentSize = doubleValue, () -> tournamentSize, 1.0);
+		addDoubleParameter("SwapProbability", swapProbability, doubleValue -> swapProbability = doubleValue, () -> swapProbability, 0.0, 1.0);
+		addDoubleParameter("MutateProbability", mutateProbability, doubleValue -> mutateProbability = doubleValue, () -> mutateProbability, 0.0, 1.0);
+		addBooleanParameter("useIntervalMutation", useIntervalMutation, booleanValue -> useIntervalMutation = booleanValue);
+		addDoubleParameter("mutateProbabilityInterval", mutateProbabilityInterval, doubleValue -> mutateProbabilityInterval = doubleValue, () -> mutateProbabilityInterval, 0.0, 1.0);
+		addDoubleParameter("maxMutationPercent", maxMutationPercent, doubleValue -> maxMutationPercent = doubleValue, () -> maxMutationPercent, 0.0, 1.0);
+		addBooleanParameter("moreInformation", moreInformation, booleanValue -> moreInformation = booleanValue);
+	}
+	
+	public static void main(String[] args)
+	{
+	      JFrame newFrame = new JFrame("exampleWindow");
+	      GaAlgorithm instance = new GaAlgorithm();
+	      newFrame.setContentPane(instance.getPanel());
+	      newFrame.pack();
+	      newFrame.setVisible(true);
+	      newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+	}
+	
+
+	@Override
+	protected int getProgressBarMaxCount() {
+		return this.maxGenerations * this.popsize * this.rounds + rounds;
+	}
+	
+	@Override
+	protected Individual executeAlgo() {
+		Individual best = new Individual();
+		best.position = extractPositionAndAccess();
+		if(moreInformation)console.println("Bit-Array_length: " + best.position.size());
+		best.fitness = evaluatePosition(best.position);
+		List<Double> runList = new ArrayList<Double>();
+		runList.add(best.fitness);
+		console.print("Start with: " + best.fitness);
+		if(moreInformation)console.println("");
+		int problemSize = best.position.size();
+		List<Individual> population = initPopuluationRandom(problemSize, best);
+		if(moreInformation)console.println("Size To Test:" + population.size());
+		for(int generation = 0; generation< maxGenerations; generation++) {
+			if(moreInformation)console.println("Generation" + generation + " start with Fitness: " + best.fitness);
+			for(Individual i : population) {
+				i.fitness = evaluatePosition(i.position);
+				if(moreInformation)console.println("Fitness" + i.fitness);
+				if(i.fitness < best.fitness) best = i;
+				
+			}
+			runList.add(best.fitness);
+			List<Individual> childList = new ArrayList<Individual>();
+			for(int k = 0; k<popsize/2; k++) {
+				Individual parentA = selectAParent(population, popsize);
+				Individual parentB = selectAParent(population, popsize);
+				Individual childA = new Individual(parentA);
+				Individual childB = new Individual(parentB);
+				crossover(childA, childB, problemSize);
+				if(useIntervalMutation)mutateInterval(childA, problemSize);else mutate(childA, problemSize);
+				if(useIntervalMutation)mutateInterval(childB, problemSize);else mutate(childB, problemSize);
+				childList.add(childA);
+				childList.add(childB);
+			}
+			population = childList;
+			if(moreInformation)console.println("________________");
+			if(cancel)return null;
+		}
+		
+		
+		console.println("   End with:" + best.fitness);
+		this.runList = runList;
+		return best;
+	}
+	/**
+	 * Algorithm 22 Bit-Flip Mutation.
+	 * 
+	 */
+	private void mutate(Individual child, int problemSize) {
+		ListIterator<Boolean> iter = child.position.listIterator();
+		while(iter.hasNext()) {
+			boolean boolValue = iter.next();
+			if(Random.nextDouble() <=  this.mutateProbability) {
+				iter.set(!boolValue);
+			}
+		}
+	}
+	
+	/**
+	 * Algorithm rolf
+	 * 
+	 */
+	private void mutateInterval(Individual child, int problemSize) {
+		//If not mutate skip
+		if(Random.nextDouble() >  this.mutateProbabilityInterval) {
+			return;
+		}
+		//println("problemSize:" + problemSize + "    maxMutationPercent:" + maxMutationPercent);
+		int maximumAmountOfMutatedBits = Math.max(1, (int)Math.round(((double) problemSize) * this.maxMutationPercent));
+		int randomUniformAmountOfMutatedValues = Random.nextIntegerInRange(1,maximumAmountOfMutatedBits + 1);
+		
+		//println("max:" + maximumAmountOfMutatedBits + "   actual:" + randomUniformAmountOfMutatedValues);
+		TreeSet<Integer> mutationLocation = new TreeSet<Integer>(); //sortedSet
+		//Choose the location to mutate
+		for(int i = 0; i< randomUniformAmountOfMutatedValues; i++) {
+			boolean success = mutationLocation.add(Random.nextIntegerInRange(0, problemSize));
+			if(!success) i--; //can be add up to some series long loops if maximumAmountOfMutatedBits get closed to problemsize.
+		}
+		//println("Set:" + mutationLocation);
+		ListIterator<Boolean> iter = child.position.listIterator();
+		if(mutationLocation.isEmpty()) return;
+		int firstindex = mutationLocation.pollFirst();
+		while(iter.hasNext()) {
+			int index = iter.nextIndex();
+			boolean boolValue = iter.next();
+			if(index == firstindex) {
+				iter.set(!boolValue);
+				if(mutationLocation.isEmpty()) break;
+				firstindex = mutationLocation.pollFirst();
+			}
+		}
+	}
+	
+	
+	
+	
+	/** 
+	 * Algorithm 25 Uniform Crossover.
+	 * Probability is set to 1/Problemsize when not changed.
+	 */
+	private void crossover(Individual childA, Individual childB, int problemSize) {
+		ListIterator<Boolean> iterA = childA.position.listIterator();
+		ListIterator<Boolean> iterB = childB.position.listIterator();
+		for(int i= 0; i < problemSize; i++) {
+			boolean boolA = iterA.next();
+			boolean boolB = iterB.next();
+			if(Random.nextDouble() <=  this.swapProbability ) {
+				//Swap 
+				iterA.set(boolB);
+				iterB.set(boolA);
+			}
+		}
+	}
+	/**
+	 * Algorithm 32 Tournament Selection.
+	 * The fitnessValues are calculated for the Population List.
+	 * PseudoCode
+	 */
+	private Individual selectAParent(List<Individual> population,int popsize) {
+		Individual tournamentBest = population.get(Random.nextIntegerInRange(0, popsize));
+		double participants;
+		for(participants = tournamentSize ; participants >= 2; participants -= 1.0) {
+			Individual next = population.get(Random.nextIntegerInRange(0, popsize));
+			if(next.fitness < tournamentBest.fitness) tournamentBest = next;
+		}
+		//if tournament size is not a whole number like 2.5 or 3.6
+		//the remaining part is the chance to fight another time; 2.7 -> 70% chance to fight a second time
+		if( participants > 1) {		
+			if(Random.nextDouble() < participants - 1.0) {
+				//println("Chance to find a match");
+				Individual next = population.get(Random.nextIntegerInRange(0, popsize));
+				if(next.fitness < tournamentBest.fitness) tournamentBest = next;
+			}
+		}
+		return tournamentBest;
+	}
+	/**
+	 * Initialize the Population with Individuals that have a random Position.
+	 */
+	private List<Individual> initPopuluationRandom(int problemSize, Individual startIndidual){
+		List<Individual> population =  new ArrayList<Individual>();
+		for(int i = 0; i < popsize -1; i++) {
+			population.add(createRandomIndividualWithoutFitness(problemSize));
+		}
+		//Add Start Position
+		population.add(new Individual(startIndidual));
+		return population;
+	}
+	
+	
+	
+	/**
+	 * Algorithm 21 The BooleanVeator initialization.
+	 * @param problemSize
+	 * @return
+	 */
+	private Individual createRandomIndividualWithoutFitness(int problemSize) {
+		//create Random Individual Without Fitness
+		Individual result = new Individual();
+		result.position = new ArrayList<Boolean>();
+		for (int index = 0; index < problemSize; index++){
+			result.position.add(Random.nextBoolean());
+		}
+		return result;
+	}
+
+	@Override
+	protected String algoInformationToPrint() {
+//		private int popsize = 20;
+//		private int maxGenerations = 100;
+//		private double tournamentSize = 2.0;
+//		private double fixedSwapProbability = 0.02;
+//		private boolean useFixedSpawProbability = false;
+//		private double fixedMutateProbability = 0.02;
+//		private boolean useFixedMutateProbability = false;
+//		private boolean useIntervalMutation = true;
+//		private double mutateProbabilityInterval = 0.01;
+//		private double maxMutationPercent = 0.01;
+		return "GaAlgo"
+				+ " Rounds: " + rounds 
+				+ " Iterations: " + maxGenerations
+				+ " Individuals: " + popsize
+				+ " TournamentSize: " +  tournamentSize
+				+ " SwapProbability: " +  swapProbability
+				+ (useIntervalMutation? 
+						(" MutateProbabilityInterval: " +  mutateProbabilityInterval
+						+ " MaxMutationPercent: " +  maxMutationPercent)
+						: 
+						(" MutateProbability: " +  mutateProbability));
+	}
+
+	@Override
+	protected String plottFileName() {
+		return "plottGaAlgo.txt";
+	}
+}

+ 412 - 415
src/algorithm/binary/PsoAlgorithm.java

@@ -1,415 +1,412 @@
-package algorithm.binary;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.TreeSet;
-import java.util.stream.Collectors;
-
-import javax.swing.JFrame;
-
-import algorithm.objectiveFunction.ObjectiveFunctionByCarlos;
-import api.AlgorithmFrameworkFlex;
-import ui.model.DecoratedState;
-
-public class PsoAlgorithm extends AlgorithmFrameworkFlex{
-	//Parameter for Algo with default Values:
-	private int swarmSize = 20; 
-	private int maxIterations = 100; 
-	private double dependency = 2.07; 
-	private int mutationInterval = 1;
-	private boolean useIntervalMutation = true;
-	private double mutationRate = 0.01;
-	private double mutateProbabilityInterval = 0.01;
-	private double maxMutationPercent = 0.01;
-	private double c1, c2, w;
-	private double maxVelocity = 4.0;
-	private boolean moreInformation = false;
-	
-	
-	
-	public static void main(String[] args)
-	{
-	      JFrame newFrame = new JFrame("exampleWindow");
-	      PsoAlgorithm instance = new PsoAlgorithm();
-	      newFrame.setContentPane(instance.getPanel());
-	      newFrame.pack();
-	      newFrame.setVisible(true);
-	      newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
-	}
-	
-	
-	public PsoAlgorithm() {
-		super();
-		addIntParameter("swarmSize", swarmSize, intValue -> swarmSize = intValue, () -> swarmSize, 1);
-		addIntParameter("maxIterations", maxIterations, intValue -> maxIterations = intValue, () -> maxIterations, 1);
-		addDoubleParameter("dependency", dependency, doubleValue -> dependency = doubleValue, () -> dependency, 2.001, 2.4);
-		addIntParameter("mutationInterval", mutationInterval, intValue -> mutationInterval = intValue, () -> mutationInterval, 0);
-		addBooleanParameter("useIntervalMutation", useIntervalMutation, booleanValue -> useIntervalMutation = booleanValue);
-		addDoubleParameter("mutateProbabilityInterval", mutateProbabilityInterval, doubleValue -> mutateProbabilityInterval = doubleValue, () -> mutateProbabilityInterval, 0.0, 1.0);
-		addDoubleParameter("mutationRate", mutationRate, doubleValue -> mutationRate = doubleValue, () -> mutationRate, 0.0, 1.0);
-		addDoubleParameter("maxMutationPercent", maxMutationPercent, doubleValue -> maxMutationPercent = doubleValue, () -> maxMutationPercent, 0.0, 1.0);
-		addDoubleParameter("maxVelocity", maxVelocity, doubleValue -> maxVelocity = doubleValue, () -> maxVelocity, 0.0);
-		
-		addBooleanParameter("moreInformation", moreInformation , booleanValue -> moreInformation = booleanValue);
-	}
-	
-
-	@Override
-	protected int getProgressBarMaxCount() {
-		return swarmSize * (maxIterations + 1)* rounds + rounds;
-	}
-	/**
-	 *  <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>
-	 *  
-	 *  
-	 */
-	@Override
-	protected Individual executeAlgo() {
-		initDependentParameter();
-		Individual globalBest = new Individual();
-		globalBest.position = extractPositionAndAccess();
-		globalBest.fitness = evaluatePosition(globalBest.position);
-		console.println("Start Value:" + globalBest.fitness);
-		int dimensions = globalBest.position.size();
-		List<Particle> swarm= initializeParticles(dimensions);
-		List<Double> runList = new ArrayList<Double>();
-		runList.add(globalBest.fitness);
-		evaluation(globalBest, swarm);
-		runList.add(globalBest.fitness);
-		for (int iteration = 0; iteration < maxIterations ; iteration++) {
-			int mutationAllowed = iteration % mutationInterval;
-			double bitsFlipped = 0;
-			for (int particleNumber = 0; particleNumber < swarmSize; particleNumber++) {
-				Particle particle = swarm.get(particleNumber);		
-				
-				if(this.useIntervalMutation) {
-					boolean allowMutation = (Random.nextDouble() <  this.mutateProbabilityInterval);
-					TreeSet<Integer> mutationLocationSet = null;
-					if(allowMutation)mutationLocationSet = locationsToMutate(dimensions);
-					for(int index = 0; index < dimensions; index++) {
-						updateVelocity(particle, index, globalBest);
-						updateGenotype(particle, index);
-						if(allowMutation &&mutationAllowed == 0 && iteration != 0 && mutationLocationSet.contains(index))mutation(particle, index);
-						decode(particle, index);
-					}
-				}else {				
-					int count = 0;
-					for(int index = 0; index < dimensions; index++) {
-						updateVelocity(particle, index, globalBest);
-						updateGenotype(particle, index);
-						if(mutationAllowed == 0 && iteration != 0 && Random.nextDouble() < mutationRate) {
-							count++;
-							mutation(particle, index);
-						}
-						decode(particle, index);
-					}
-					bitsFlipped += count;
-				}
-			}
-			if(moreInformation) console.println("\t\t\t\t\t\tAvgBitsMutate: " + (bitsFlipped / (double)swarmSize));
-			if(cancel)return null;
-			evaluation(globalBest, swarm);
-			runList.add(globalBest.fitness);
-			if(moreInformation) console.println("------------------------");
-		}
-		console.println(" End Value:" + globalBest.fitness);
-		this.runList = runList;
-		return globalBest;
-	}
-	/**
-	 * 
-	 * @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;
-	}
-	/**
-	 * Calculate w, c1, c2
-	 */
-	private void initDependentParameter() {
-		w = 1.0 / (dependency - 1 + Math.sqrt(dependency * dependency - 2 * dependency));
-		c1 = c2 = dependency * w;
-	}
-	/**
-	 * Evaluate each particle and update the global Best position;
-	 * @param globalBest
-	 * @param swarm
-	 */
-	private void evaluation(Individual globalBest, List<Particle> swarm) {
-		for(Particle p: swarm) {
-			double localEvaluationValue = evaluatePosition(p.xPhenotype);
-			if(moreInformation) console.println("Fitness " + localEvaluationValue);
-			p.checkNewEvaluationValue(localEvaluationValue);
-			if(localEvaluationValue < globalBest.fitness) {
-				globalBest.fitness = localEvaluationValue;
-				globalBest.position = p.localBest.position;
-			}
-		}
-	}
-	/**
-	 * 	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, Individual 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(-maxVelocity, Math.min(maxVelocity, value));
-	}
-	private TreeSet<Integer> locationsToMutate(int dimensions) {
-		TreeSet<Integer> mutationLocation = new TreeSet<Integer>(); //sortedSet
-		int maximumAmountOfMutatedBits = Math.max(1, (int)Math.round(((double) dimensions) * this.maxMutationPercent));
-		int randomUniformAmountOfMutatedValues = Random.nextIntegerInRange(1,maximumAmountOfMutatedBits + 1);
-		for(int i = 0; i< randomUniformAmountOfMutatedValues; i++) {
-			boolean success = mutationLocation.add(Random.nextIntegerInRange(0, dimensions));
-			if(!success) i--; //can be add up to some series long loops if maximumAmountOfMutatedBits get closed to problemsize.
-		}
-		return mutationLocation;
-	}
-	
-	
-	
-		@Override
-	protected String algoInformationToPrint() {
-//			private int swarmSize = 20; 
-//			private int maxIterations = 100; 
-//			private double limit = 0.01; 
-//			private double dependency = 2.07; 
-//			private int mutationInterval = 1;
-//			private boolean useIntervalMutation = true;
-//			private double mutateProbabilityInterval = 0.01;
-//			private double maxMutationPercent = 0.01;
-		return "PsoAlgo"+ " Rounds:" + rounds 
-				+ " maxIterations:" + maxIterations
-				+ " swarmSize:" + swarmSize
-				+ " dependency:" +  dependency
-				+ " mutationInterval:" +  mutationInterval
-				+ " maxVelocity: " + maxVelocity
-				+ (useIntervalMutation? 
-						(" mutateProbabilityInterval:" +  mutateProbabilityInterval
-						+ " maxMutationPercent:" +  maxMutationPercent) : " mutationRate:" + mutationRate);
-	}
-	
-	
-	
-	
-	
-	
-	
-	
-	
-	
-	
-	
-	
-	
-	
-	
-	
-	
-	
-	
-	
-	
-	
-	
-	
-	
-	
-	/**
-	 * 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 Individual 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 Individual();
-			localBest.fitness = Double.MAX_VALUE;
-		}
-		public void checkNewEvaluationValue(double newEvaluationValue) {
-			if(newEvaluationValue < localBest.fitness) {
-				localBest.fitness = 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(", "));
-		}
-		
-	}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-	@Override
-	protected String plottFileName() {
-		return "plottPsoAlgo.txt";
-	}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-		
-		
-		
-		
-		
-
-}
+package algorithm.binary;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.TreeSet;
+import java.util.stream.Collectors;
+
+import javax.swing.JFrame;
+import api.AlgorithmFrameworkFlex;
+
+public class PsoAlgorithm extends AlgorithmFrameworkFlex{
+	//Parameter for Algo with default Values:
+	private int swarmSize = 20; 
+	private int maxIterations = 100; 
+	private double dependency = 2.07; 
+	private int mutationInterval = 1;
+	private boolean useIntervalMutation = true;
+	private double mutationRate = 0.01;
+	private double mutateProbabilityInterval = 0.01;
+	private double maxMutationPercent = 0.01;
+	private double c1, c2, w;
+	private double maxVelocity = 4.0;
+	private boolean moreInformation = false;
+	
+	
+	
+	public static void main(String[] args)
+	{
+	      JFrame newFrame = new JFrame("exampleWindow");
+	      PsoAlgorithm instance = new PsoAlgorithm();
+	      newFrame.setContentPane(instance.getPanel());
+	      newFrame.pack();
+	      newFrame.setVisible(true);
+	      newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+	}
+	
+	
+	public PsoAlgorithm() {
+		super();
+		addIntParameter("swarmSize", swarmSize, intValue -> swarmSize = intValue, () -> swarmSize, 1);
+		addIntParameter("maxIterations", maxIterations, intValue -> maxIterations = intValue, () -> maxIterations, 1);
+		addDoubleParameter("dependency", dependency, doubleValue -> dependency = doubleValue, () -> dependency, 2.001, 2.4);
+		addIntParameter("mutationInterval", mutationInterval, intValue -> mutationInterval = intValue, () -> mutationInterval, 0);
+		addBooleanParameter("useIntervalMutation", useIntervalMutation, booleanValue -> useIntervalMutation = booleanValue);
+		addDoubleParameter("mutateProbabilityInterval", mutateProbabilityInterval, doubleValue -> mutateProbabilityInterval = doubleValue, () -> mutateProbabilityInterval, 0.0, 1.0);
+		addDoubleParameter("mutationRate", mutationRate, doubleValue -> mutationRate = doubleValue, () -> mutationRate, 0.0, 1.0);
+		addDoubleParameter("maxMutationPercent", maxMutationPercent, doubleValue -> maxMutationPercent = doubleValue, () -> maxMutationPercent, 0.0, 1.0);
+		addDoubleParameter("maxVelocity", maxVelocity, doubleValue -> maxVelocity = doubleValue, () -> maxVelocity, 0.0);
+		
+		addBooleanParameter("moreInformation", moreInformation , booleanValue -> moreInformation = booleanValue);
+	}
+	
+
+	@Override
+	protected int getProgressBarMaxCount() {
+		return swarmSize * (maxIterations + 1)* rounds + rounds;
+	}
+	/**
+	 *  <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>
+	 *  
+	 *  
+	 */
+	@Override
+	protected Individual executeAlgo() {
+		initDependentParameter();
+		Individual globalBest = new Individual();
+		globalBest.position = extractPositionAndAccess();
+		globalBest.fitness = evaluatePosition(globalBest.position);
+		console.println("Start Value:" + globalBest.fitness);
+		int dimensions = globalBest.position.size();
+		List<Particle> swarm= initializeParticles(dimensions);
+		List<Double> runList = new ArrayList<Double>();
+		runList.add(globalBest.fitness);
+		evaluation(globalBest, swarm);
+		runList.add(globalBest.fitness);
+		for (int iteration = 0; iteration < maxIterations ; iteration++) {
+			int mutationAllowed = iteration % mutationInterval;
+			double bitsFlipped = 0;
+			for (int particleNumber = 0; particleNumber < swarmSize; particleNumber++) {
+				Particle particle = swarm.get(particleNumber);		
+				
+				if(this.useIntervalMutation) {
+					boolean allowMutation = (Random.nextDouble() <  this.mutateProbabilityInterval);
+					TreeSet<Integer> mutationLocationSet = null;
+					if(allowMutation)mutationLocationSet = locationsToMutate(dimensions);
+					for(int index = 0; index < dimensions; index++) {
+						updateVelocity(particle, index, globalBest);
+						updateGenotype(particle, index);
+						if(allowMutation &&mutationAllowed == 0 && iteration != 0 && mutationLocationSet.contains(index))mutation(particle, index);
+						decode(particle, index);
+					}
+				}else {				
+					int count = 0;
+					for(int index = 0; index < dimensions; index++) {
+						updateVelocity(particle, index, globalBest);
+						updateGenotype(particle, index);
+						if(mutationAllowed == 0 && iteration != 0 && Random.nextDouble() < mutationRate) {
+							count++;
+							mutation(particle, index);
+						}
+						decode(particle, index);
+					}
+					bitsFlipped += count;
+				}
+			}
+			if(moreInformation) console.println("\t\t\t\t\t\tAvgBitsMutate: " + (bitsFlipped / (double)swarmSize));
+			if(cancel)return null;
+			evaluation(globalBest, swarm);
+			runList.add(globalBest.fitness);
+			if(moreInformation) console.println("------------------------");
+		}
+		console.println(" End Value:" + globalBest.fitness);
+		this.runList = runList;
+		return globalBest;
+	}
+	/**
+	 * 
+	 * @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;
+	}
+	/**
+	 * Calculate w, c1, c2
+	 */
+	private void initDependentParameter() {
+		w = 1.0 / (dependency - 1 + Math.sqrt(dependency * dependency - 2 * dependency));
+		c1 = c2 = dependency * w;
+	}
+	/**
+	 * Evaluate each particle and update the global Best position;
+	 * @param globalBest
+	 * @param swarm
+	 */
+	private void evaluation(Individual globalBest, List<Particle> swarm) {
+		for(Particle p: swarm) {
+			double localEvaluationValue = evaluatePosition(p.xPhenotype);
+			if(moreInformation) console.println("Fitness " + localEvaluationValue);
+			p.checkNewEvaluationValue(localEvaluationValue);
+			if(localEvaluationValue < globalBest.fitness) {
+				globalBest.fitness = localEvaluationValue;
+				globalBest.position = p.localBest.position;
+			}
+		}
+	}
+	/**
+	 * 	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, Individual 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(-maxVelocity, Math.min(maxVelocity, value));
+	}
+	private TreeSet<Integer> locationsToMutate(int dimensions) {
+		TreeSet<Integer> mutationLocation = new TreeSet<Integer>(); //sortedSet
+		int maximumAmountOfMutatedBits = Math.max(1, (int)Math.round(((double) dimensions) * this.maxMutationPercent));
+		int randomUniformAmountOfMutatedValues = Random.nextIntegerInRange(1,maximumAmountOfMutatedBits + 1);
+		for(int i = 0; i< randomUniformAmountOfMutatedValues; i++) {
+			boolean success = mutationLocation.add(Random.nextIntegerInRange(0, dimensions));
+			if(!success) i--; //can be add up to some series long loops if maximumAmountOfMutatedBits get closed to problemsize.
+		}
+		return mutationLocation;
+	}
+	
+	
+	
+		@Override
+	protected String algoInformationToPrint() {
+//			private int swarmSize = 20; 
+//			private int maxIterations = 100; 
+//			private double limit = 0.01; 
+//			private double dependency = 2.07; 
+//			private int mutationInterval = 1;
+//			private boolean useIntervalMutation = true;
+//			private double mutateProbabilityInterval = 0.01;
+//			private double maxMutationPercent = 0.01;
+		return "PsoAlgo"+ " Rounds:" + rounds 
+				+ " maxIterations:" + maxIterations
+				+ " swarmSize:" + swarmSize
+				+ " dependency:" +  dependency
+				+ " mutationInterval:" +  mutationInterval
+				+ " maxVelocity: " + maxVelocity
+				+ (useIntervalMutation? 
+						(" mutateProbabilityInterval:" +  mutateProbabilityInterval
+						+ " maxMutationPercent:" +  maxMutationPercent) : " mutationRate:" + mutationRate);
+	}
+	
+	
+	
+	
+	
+	
+	
+	
+	
+	
+	
+	
+	
+	
+	
+	
+	
+	
+	
+	
+	
+	
+	
+	
+	
+	
+	
+	/**
+	 * 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 Individual 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 Individual();
+			localBest.fitness = Double.MAX_VALUE;
+		}
+		public void checkNewEvaluationValue(double newEvaluationValue) {
+			if(newEvaluationValue < localBest.fitness) {
+				localBest.fitness = 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(", "));
+		}
+		
+	}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+	@Override
+	protected String plottFileName() {
+		return "plottPsoAlgo.txt";
+	}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+		
+		
+		
+		
+		
+
+}

+ 473 - 495
src/algorithm/example/DemoAlgo.java

@@ -1,495 +1,473 @@
-package algorithm.example;
-
-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.AddOn;
-import classes.AbstractCanvasObject;
-import classes.GroupNode;
-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 AddOn {
-
-	//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.getPanel());
-		      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.guiDisable(bool);
-		}
-		
-		
-		
-
-		
-		
-		@Override
-		public JPanel getPanel() {
-			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<AbstractCanvasObject> nodes, List<Boolean> positionToInit, int timeStep) {
-			for(AbstractCanvasObject 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 GroupNode) {
-					rollOutNodes(((GroupNode)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<AbstractCanvasObject> listToSearch, List<HolonObject> listToAdd){
-			for (AbstractCanvasObject aCps : listToSearch) {
-				if (aCps instanceof HolonObject) listToAdd.add((HolonObject) aCps);
-				else if(aCps instanceof GroupNode) {
-					addObjectToList(((GroupNode)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();
-			}
-		}
-
-}
+package algorithm.example;
+
+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 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.AddOn;
+import classes.AbstractCanvasObject;
+import classes.GroupNode;
+import classes.HolonElement;
+import classes.HolonObject;
+import classes.HolonSwitch;
+import ui.controller.Control;
+import ui.model.DecoratedGroupNode;
+import ui.model.Model;
+
+public class DemoAlgo implements AddOn {
+
+	//Parameter for Algo with default Values:
+		
+		//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();
+		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.getPanel());
+		      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;
+			} 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.guiDisable(bool);
+		}
+		
+		
+		
+
+		
+		
+		@Override
+		public JPanel getPanel() {
+			return content;
+		}
+		@Override
+		public void setController(Control control) {
+			this.control = control;
+			
+		}
+		private void clear() {
+			textArea.setText("");
+		}
+		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 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<AbstractCanvasObject> nodes, List<Boolean> positionToInit, int timeStep) {
+			for(AbstractCanvasObject 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 GroupNode) {
+					rollOutNodes(((GroupNode)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<AbstractCanvasObject> listToSearch, List<HolonObject> listToAdd){
+			for (AbstractCanvasObject aCps : listToSearch) {
+				if (aCps instanceof HolonObject) listToAdd.add((HolonObject) aCps);
+				else if(aCps instanceof GroupNode) {
+					addObjectToList(((GroupNode)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();
+			}
+		}
+
+}

+ 615 - 655
src/algorithm/example/FlexExample.java

@@ -1,655 +1,615 @@
-package algorithm.example;
-
-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.HashSet;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Set;
-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.AddOn;
-import classes.AbstractCanvasObject;
-import classes.GroupNode;
-import classes.HolonElement;
-import classes.HolonElement.Priority;
-import classes.HolonObject;
-import classes.HolonSwitch;
-import ui.controller.Control;
-import ui.controller.FlexManager;
-import ui.controller.FlexManager.FlexState;
-import ui.controller.FlexManager.FlexWrapper;
-import ui.model.DecoratedGroupNode;
-import ui.model.DecoratedNetwork;
-import ui.model.DecoratedState;
-import ui.model.Model;
-import ui.model.DecoratedHolonObject.HolonObjectState;
-
-public class FlexExample implements AddOn {
-
-	//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;
-		private boolean overAllTimeSteps = false;
-		
-		
-
-		//Parameter defined by Algo
-		private HashMap<Integer, AccessWrapper> access;
-		LinkedList<List<Boolean>> resetChain = new LinkedList<List<Boolean>>();
-		private List<Boolean> initialState;
-		private List<HolonSwitch> switchList;
-		private List<HolonObject> objectList;
-		
-		//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");
-		      DemoAlgo instance = new DemoAlgo();
-		      newFrame.setContentPane(instance.getPanel());
-		      newFrame.pack();
-		      newFrame.setVisible(true);
-		      newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
-		}
-		public FlexExample() {
-			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 overAllTimeStepsCheckbox = new JCheckBox("overAllTimeSteps");
-			overAllTimeStepsCheckbox.setSelected(false);
-			overAllTimeStepsCheckbox.setBounds(20, 30, 250, 30);
-			overAllTimeStepsCheckbox.addActionListener(actionEvent -> {
-				overAllTimeSteps = overAllTimeStepsCheckbox.isSelected();
-			});
-			parameterPanel.add(overAllTimeStepsCheckbox);
-			
-			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);
-			JLabel afterLabel = new JLabel("after:");
-			afterLabel.setBounds(10, 360, 70, 30);
-			parameterPanel.add(afterLabel);
-			
-			
-			return parameterPanel;
-		}
-		public JPanel createButtonPanel() {
-			JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
-			JButton resetButton =  new JButton("ResetAll");
-			resetButton.setToolTipText("Resets the State to before the Algorithm has runed.");
-			resetButton.addActionListener(actionEvent -> resetAll());
-			buttonPanel.add(resetButton);
-			JButton cancelButton =  new JButton("Cancel Run");
-			cancelButton.addActionListener(actionEvent -> cancel());
-			buttonPanel.add(cancelButton);
-			JButton clearButton =  new JButton("Clear Console");
-			clearButton.addActionListener(actionEvent -> clear());
-			buttonPanel.add(clearButton);
-			JButton undoButton =  new JButton("Undo");
-			undoButton.setToolTipText("One Algo Step Back.");
-			undoButton.addActionListener(actionEvent -> resetLast());
-			buttonPanel.add(undoButton);
-			JButton runButton =  new JButton("Run");
-			runButton.addActionListener(actionEvent -> {
-				Runnable task = () -> {
-					if(this.overAllTimeSteps)runAll();
-					else 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 runAll() {
-			cancel = false;
-			disableGuiInput(true);
-			startTimer();
-			control.resetSimulation();
-			RunResult result= new RunResult();
-			for(int i = 0; i < 100; i++) {
-				control.setCurIteration(i);
-				executeDemoAlgo(result);
-				if(cancel) {
-					resetLast();
-					disableGuiInput(false);
-					return;
-				}				
-			}
-			updateVisual();
-			calculateAllResults(result);
-			println("Amount of activatedFlex:" + result.activatedFlex + "   Amount of deactivatedElements:"+ result.deactivatedElements + "   TotalCost:"+result.totalCost);
-			printElapsedTime();
-			disableGuiInput(false);
-		}
-		private void run() {
-			disableGuiInput(true);
-			startTimer();
-			executeDemoAlgo(new RunResult());
-			updateVisual();
-			printElapsedTime();
-			disableGuiInput(false);
-		}
-		
-		private void resetLast() {
-			if(!resetChain.isEmpty()) {
-				println("Resetting..");
-				resetState();
-				resetChain.removeLast();
-				control.resetSimulation();
-				updateVisual();
-			}else {
-				println("No run inistialized.");
-			}
-		}
-		
-		private void resetAll() {
-			if(!resetChain.isEmpty()) {
-				println("Resetting..");
-				setState(resetChain.getFirst());
-				resetChain.clear();
-				control.resetSimulation();
-				control.setCurIteration(0);
-				updateVisual();
-			}else {
-				println("No run inistialized.");
-			}
-		}
-		
-		
-		
-		private void disableGuiInput(boolean bool) {
-			control.guiDisable(bool);
-		}
-		
-		
-		
-
-		
-		
-		@Override
-		public JPanel getPanel() {
-			return content;
-		}
-		@Override
-		public void setController(Control control) {
-			this.control = control;
-			
-		}
-		private void 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 FlexAlgo.
-		 * 
-		 * 
-		 * Begin
-		 * 		for(All Networks) do
-		 * 			
-		 * 			if(not (production < consumption)) continue;
-		 * 			
-		 * 
-		 * 			for(Priority emergencyShutDownPriority: priorityListASC) do
-		 * 				difference = Math.abs(production - consumption);
-		 * 				amountOfAllEnergyOffered = sumEnergyAvailable(flexList); 
-		 * 				if(amountOfAllEnergyOffered > difference) break; 
-		 * 				shutDownAllConsumerWithPriority(emergencyShutDownPriority)
-		 * 			end for
-		 * 			
-		 * 			takeAKombinationOfOffers(); (nach welchem Kriterium)
-		 * 			
-		 * 			
-		 * 		end for
-		 * End
-		 * 
-		 */
-		private void executeDemoAlgo(RunResult result) {
-			extractPositionAndAccess();
-			int actualIteration = control.getModel().getCurIteration();
-			println("TimeStep:" + actualIteration);
-			control.calculateStateOnlyForCurrentTimeStep();
-			List<Priority> priorityListASC = createPriorityListASC();
-			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);
-				println("consumption: " + consumption);
-				println("difference: " + difference);
-				if(production > consumption) continue;
-				if(difference == 0)continue;
-				Set<HolonElement> allHolonElemntsInThisNetwork = createListOfAllHolonElemnts(net);
-				FlexManager flexManager = control.getSimManager().getActualFlexManager();
-				
-				List<FlexWrapper> allOfferedFlex = flexManager.getAllFlexWrapperWithState(FlexState.OFFERED).stream().filter(flexWrapper -> allHolonElemntsInThisNetwork.contains(flexWrapper.getFlex().getElement())).collect(Collectors.toList());
-				List<FlexWrapper> allFlexThatGetMeEnergy = allOfferedFlex.stream().filter(flexWrapper -> (flexWrapper.getFlex().bringtmir() > 0)).collect(Collectors.toList());
-				float amountOfAllEnergyOffered = sumEnergyAvailable(allFlexThatGetMeEnergy);
-				println("amountOfAllFlexEnergyOffered:" + amountOfAllEnergyOffered);
-				//ShuddownPriorities
-				for(Priority emergencyShutDownPriority: priorityListASC) {
-					if(amountOfAllEnergyOffered >= difference) break; 
-					println("ShutDown: " + emergencyShutDownPriority);
-					difference -= shutDownAllConsumerElementsWithPriority(flexManager, allHolonElemntsInThisNetwork, emergencyShutDownPriority, result);
-				}
-				
-				//SortFlexes
-				allFlexThatGetMeEnergy.sort((flex1, flex2) -> Float.compare(flex1.getFlex().cost / flex1.getFlex().bringtmir(), flex2.getFlex().cost / flex2.getFlex().bringtmir()));
-				//OrderFlexes
-				float costForThisTimeStep = 0f;
-				int amountflexActivated = 0;
-				for(FlexWrapper flexWrapper : allFlexThatGetMeEnergy) {
-					if(!flexWrapper.canOrder()) continue;
-					float energy = flexWrapper.getFlex().bringtmir();
-					if(energy <= difference) {
-						println("energyGained:" + energy);
-						difference -= energy;
-						costForThisTimeStep += flexWrapper.getFlex().cost;
-						flexWrapper.order();
-						amountflexActivated++;
-						continue;
-					}
-				}
-				result.activatedFlex += 	amountflexActivated;
-				
-				println("Activated FlexThisTimeStep: "+ amountflexActivated+"   CostForThisTimeStep:" + costForThisTimeStep);
-				result.totalCost += costForThisTimeStep;
-			}
-			calculateStateResult(result);
-		}
-		private void calculateStateResult(RunResult result) {
-			control.calculateStateOnlyForCurrentTimeStep();
-			RunResult.TimeStepStateResult timeStepState = result.addTimeStepStateResult();
-			
-			for(DecoratedNetwork network: control.getSimManager().getActualDecorState().getNetworkList()) {
-				timeStepState.amountOfConsumer += network.getAmountOfConsumer();
-				timeStepState.amountOfConsumerOverSupplied += network.getAmountOfConsumerWithState(HolonObjectState.OVER_SUPPLIED);
-				timeStepState.amountOfConsumerPartiallySupplied += network.getAmountOfConsumerWithState(HolonObjectState.PARTIALLY_SUPPLIED);
-				timeStepState.amountOfConsumerSupplied += network.getAmountOfConsumerWithState(HolonObjectState.SUPPLIED);
-				timeStepState.amountOfConsumerUnSupplied += network.getAmountOfConsumerWithState(HolonObjectState.NOT_SUPPLIED);
-				timeStepState.amountOfPassiv += network.getAmountOfPassiv();
-				timeStepState.amountOfProducer += network.getAmountOfSupplier();	
-			}
-			println("Producer: " + timeStepState.amountOfProducer);
-			println("Consumer: " + timeStepState.amountOfConsumer);
-			println("ConsumerOverSupplied: " + timeStepState.amountOfConsumerOverSupplied);
-			println("ConsumerSupplied: " + timeStepState.amountOfConsumerSupplied);
-			println("ConsumerPartiallySupplied: " + timeStepState.amountOfConsumerPartiallySupplied);
-			println("ConsumerUnSupplied: " + timeStepState.amountOfConsumerUnSupplied);
-			println("ConsumerUnSupplied: " + timeStepState.amountOfPassiv);
-		}
-		private void calculateAllResults(RunResult result) {
-			println("----------");
-			println("Average producer proportion: " + result.getAvergaeProportionWithState(HolonObjectState.PRODUCER));
-			println("Average producer OverSupplied: " + result.getAvergaeProportionWithState(HolonObjectState.OVER_SUPPLIED));
-			println("Average producer Supplied: " + result.getAvergaeProportionWithState(HolonObjectState.SUPPLIED));
-			println("Average producer PartiallySupplied: " + result.getAvergaeProportionWithState(HolonObjectState.PARTIALLY_SUPPLIED));
-			println("Average producer NotSupplied: " + result.getAvergaeProportionWithState(HolonObjectState.NOT_SUPPLIED));
-			println("Average producer NoEnergy: " + result.getAvergaeProportionWithState(HolonObjectState.NO_ENERGY));
-		}
-		
-		
-		
-		
-		
-		private float shutDownAllConsumerElementsWithPriority(FlexManager flexManager, Set<HolonElement> allHolonElemntsInThisNetwork,
-				Priority emergencyShutDownPriority, RunResult result) {
-			
-			List<HolonElement> elementsOfPriorityToShutdown = allHolonElemntsInThisNetwork.stream().filter(hElement -> hElement.isConsumer() && hElement.getPriority() == emergencyShutDownPriority && !hElement.isFlexActive(flexManager) && hElement.isActive()).collect(Collectors.toList());
-					//.forEach(hElement -> hElement.setActive(false));
-			float energyGained = elementsOfPriorityToShutdown.stream().map(hElement -> -hElement.getEnergyPerElement() * hElement.getAmount()).reduce(0.0f, (a, b) -> a + b);
-			elementsOfPriorityToShutdown.forEach(hElement -> hElement.setActive(false));
-			int shutdownCount = elementsOfPriorityToShutdown.size();
-			result.deactivatedElements += shutdownCount;
-			println("Gained " + energyGained + "Energy from Shutdown with Priority:" + emergencyShutDownPriority + " AmountOfShutDowned HolonElements: " + shutdownCount);
-			return energyGained;
-		}
-		private Set<HolonElement> createListOfAllHolonElemnts(DecoratedNetwork net) {
-			Set<HolonElement> allHolonElemntsInThisNetwork = new HashSet<HolonElement>();
-			allHolonElemntsInThisNetwork.addAll(net.getConsumerList().stream().flatMap(con -> con.getModel().getElements().stream()).collect(Collectors.toList()));
-			allHolonElemntsInThisNetwork.addAll(net.getConsumerSelfSuppliedList().stream().flatMap(con -> con.getModel().getElements().stream()).collect(Collectors.toList()));
-			allHolonElemntsInThisNetwork.addAll(net.getSupplierList().stream().flatMap(con -> con.getModel().getElements().stream()).collect(Collectors.toList()));
-			return allHolonElemntsInThisNetwork;
-		}
-
-	
-		private float sumEnergyAvailable(List<FlexWrapper> flexList) {
-			HashMap<HolonElement, FlexWrapper> dublicateFilter = new HashMap<HolonElement, FlexWrapper>();
-			flexList.stream().forEach(flexWrapper -> dublicateFilter.put(flexWrapper.getFlex().getElement(), flexWrapper));
-			
-			return dublicateFilter.values().stream().map(flexWrapper -> flexWrapper.getFlex().bringtmir()).reduce(0.0f,(a, b) -> a + b);
-		}
-		private List<Priority> createPriorityListASC() {
-			List<Priority> priorityASC = new ArrayList<Priority>();
-			priorityASC.add(Priority.Low);
-			priorityASC.add(Priority.Medium);
-			priorityASC.add(Priority.High);
-			priorityASC.add(Priority.Essential);
-			return priorityASC;
-		}
-		/**
-		 * 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());			
-			resetChain.add(initialState); 
-			return initialState;
-		}
-		/**
-		 * Method to extract the Informations recursively out of the Model.
-		 * @param nodes
-		 * @param positionToInit
-		 * @param timeStep
-		 */
-		private void rollOutNodes(List<AbstractCanvasObject> nodes, List<Boolean> positionToInit, int timeStep) {
-			for(AbstractCanvasObject 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 GroupNode) {
-					rollOutNodes(((GroupNode)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(resetChain.getLast());
-		}
-		
-		/**
-		 * Sets the State out of the given position for calculation or to show the user.
-		 * @param position
-		 */
-		private void setState(List<Boolean> position) {
-			for(int i = 0;i<position.size();i++) {
-				access.get(i).setState(position.get(i));
-			}
-		}
-	
-
-
-
-		private void addObjectToList(List<AbstractCanvasObject> listToSearch, List<HolonObject> listToAdd){
-			for (AbstractCanvasObject aCps : listToSearch) {
-				if (aCps instanceof HolonObject) listToAdd.add((HolonObject) aCps);
-				else if(aCps instanceof GroupNode) {
-					addObjectToList(((GroupNode)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 RunResult {
-			public int activatedFlex = 0;
-			public int deactivatedElements = 0;
-			public float totalCost = 0;
-			public LinkedList<TimeStepStateResult> timeStepList = new LinkedList<TimeStepStateResult>();
-			
-			
-			public TimeStepStateResult addTimeStepStateResult(){
-				TimeStepStateResult aResult = new TimeStepStateResult();
-				timeStepList.add(aResult);
-				return aResult;
-			}
-			
-			
-			public class TimeStepStateResult{
-				public int amountOfProducer = 0;
-				public int amountOfConsumer = 0;
-				public int amountOfPassiv = 0;
-				public int amountOfConsumerOverSupplied = 0;
-				public int amountOfConsumerSupplied = 0;
-				public int amountOfConsumerPartiallySupplied = 0;
-				public int amountOfConsumerUnSupplied= 0;
-				
-				public float getProportionWithState(HolonObjectState state) {
-					float amountOfObjects = amountOfProducer + amountOfConsumer + amountOfPassiv;
-					switch(state) {
-					case NOT_SUPPLIED:
-						return (float) amountOfConsumerUnSupplied / amountOfObjects;
-					case NO_ENERGY:
-						return (float) amountOfPassiv / amountOfObjects;
-					case OVER_SUPPLIED:
-						return (float) amountOfConsumerOverSupplied / amountOfObjects;
-					case PARTIALLY_SUPPLIED:
-						return (float) amountOfConsumerPartiallySupplied / amountOfObjects;
-					case PRODUCER:
-						return (float) amountOfProducer / amountOfObjects;
-					case SUPPLIED:
-						return (float) amountOfConsumerSupplied / amountOfObjects;
-					default:
-						return 0.f;
-					}
-				}
-			}
-			public float getAvergaeProportionWithState(HolonObjectState state) {
-				return timeStepList.stream().map(step -> step.getProportionWithState(state)).reduce((a,b) -> (a + b)).orElse(0.f) / (float) 100;
-			}
-		}
-		
-		private   class  Handle<T>{
-			public T object;
-			Handle(T object){
-				this.object = object;
-			}
-			public String toString() {
-				return object.toString();
-			}
-		}
-
-}
+package algorithm.example;
+
+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.HashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import javax.swing.BorderFactory;
+import javax.swing.ImageIcon;
+import javax.swing.JButton;
+import javax.swing.JCheckBox;
+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.AddOn;
+import classes.AbstractCanvasObject;
+import classes.GroupNode;
+import classes.HolonElement;
+import classes.HolonElement.Priority;
+import classes.HolonObject;
+import classes.HolonSwitch;
+import ui.controller.Control;
+import ui.controller.FlexManager;
+import ui.controller.FlexManager.FlexState;
+import ui.controller.FlexManager.FlexWrapper;
+import ui.model.DecoratedGroupNode;
+import ui.model.DecoratedNetwork;
+import ui.model.DecoratedState;
+import ui.model.Model;
+import ui.model.DecoratedHolonObject.HolonObjectState;
+
+public class FlexExample implements AddOn {
+		
+		//Settings For GroupNode using and cancel
+		private boolean useGroupNode = false;
+		private DecoratedGroupNode dGroupNode = null;
+		private boolean cancel = false;
+		private boolean overAllTimeSteps = false;
+		
+		
+
+		//Parameter defined by Algo
+		private HashMap<Integer, AccessWrapper> access;
+		LinkedList<List<Boolean>> resetChain = new LinkedList<List<Boolean>>();
+		private List<Boolean> initialState;
+		private List<HolonSwitch> switchList;
+		private List<HolonObject> objectList;
+		
+		//Gui Part:
+		private Control  control;
+		private JTextArea textArea;
+		private JPanel content = new JPanel();
+		//ProgressBar
+		private long startTime;
+		private Thread runThread;
+
+		
+		
+		
+		
+		
+		
+		
+		public static void main(String[] args)
+		{
+		      JFrame newFrame = new JFrame("exampleWindow");
+		      DemoAlgo instance = new DemoAlgo();
+		      newFrame.setContentPane(instance.getPanel());
+		      newFrame.pack();
+		      newFrame.setVisible(true);
+		      newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+		}
+		public FlexExample() {
+			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 overAllTimeStepsCheckbox = new JCheckBox("overAllTimeSteps");
+			overAllTimeStepsCheckbox.setSelected(false);
+			overAllTimeStepsCheckbox.setBounds(20, 30, 250, 30);
+			overAllTimeStepsCheckbox.addActionListener(actionEvent -> {
+				overAllTimeSteps = overAllTimeStepsCheckbox.isSelected();
+			});
+			parameterPanel.add(overAllTimeStepsCheckbox);
+			
+			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);
+			JLabel afterLabel = new JLabel("after:");
+			afterLabel.setBounds(10, 360, 70, 30);
+			parameterPanel.add(afterLabel);
+			
+			
+			return parameterPanel;
+		}
+		public JPanel createButtonPanel() {
+			JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
+			JButton resetButton =  new JButton("ResetAll");
+			resetButton.setToolTipText("Resets the State to before the Algorithm has runed.");
+			resetButton.addActionListener(actionEvent -> resetAll());
+			buttonPanel.add(resetButton);
+			JButton cancelButton =  new JButton("Cancel Run");
+			cancelButton.addActionListener(actionEvent -> cancel());
+			buttonPanel.add(cancelButton);
+			JButton clearButton =  new JButton("Clear Console");
+			clearButton.addActionListener(actionEvent -> clear());
+			buttonPanel.add(clearButton);
+			JButton undoButton =  new JButton("Undo");
+			undoButton.setToolTipText("One Algo Step Back.");
+			undoButton.addActionListener(actionEvent -> resetLast());
+			buttonPanel.add(undoButton);
+			JButton runButton =  new JButton("Run");
+			runButton.addActionListener(actionEvent -> {
+				Runnable task = () -> {
+					if(this.overAllTimeSteps)runAll();
+					else run();
+				};
+				runThread = new Thread(task);
+				runThread.start();
+			});
+			buttonPanel.add(runButton);
+			return buttonPanel;
+		}
+		private void cancel() {
+			if(runThread.isAlive()) {
+				println("");
+				println("Cancel run.");
+				cancel = true;
+			} else {
+				println("Nothing to cancel.");
+			}
+		}
+		
+		private void runAll() {
+			cancel = false;
+			disableGuiInput(true);
+			startTimer();
+			control.resetSimulation();
+			RunResult result= new RunResult();
+			for(int i = 0; i < 100; i++) {
+				control.setCurIteration(i);
+				executeDemoAlgo(result);
+				if(cancel) {
+					resetLast();
+					disableGuiInput(false);
+					return;
+				}				
+			}
+			updateVisual();
+			calculateAllResults(result);
+			println("Amount of activatedFlex:" + result.activatedFlex + "   Amount of deactivatedElements:"+ result.deactivatedElements + "   TotalCost:"+result.totalCost);
+			printElapsedTime();
+			disableGuiInput(false);
+		}
+		private void run() {
+			disableGuiInput(true);
+			startTimer();
+			executeDemoAlgo(new RunResult());
+			updateVisual();
+			printElapsedTime();
+			disableGuiInput(false);
+		}
+		
+		private void resetLast() {
+			if(!resetChain.isEmpty()) {
+				println("Resetting..");
+				resetState();
+				resetChain.removeLast();
+				control.resetSimulation();
+				updateVisual();
+			}else {
+				println("No run inistialized.");
+			}
+		}
+		
+		private void resetAll() {
+			if(!resetChain.isEmpty()) {
+				println("Resetting..");
+				setState(resetChain.getFirst());
+				resetChain.clear();
+				control.resetSimulation();
+				control.setCurIteration(0);
+				updateVisual();
+			}else {
+				println("No run inistialized.");
+			}
+		}
+		
+		
+		
+		private void disableGuiInput(boolean bool) {
+			control.guiDisable(bool);
+		}
+		
+		
+		
+
+		
+		
+		@Override
+		public JPanel getPanel() {
+			return content;
+		}
+		@Override
+		public void setController(Control control) {
+			this.control = control;
+			
+		}
+		private void clear() {
+			textArea.setText("");
+		}
+		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 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 FlexAlgo.
+		 * 
+		 * 
+		 * Begin
+		 * 		for(All Networks) do
+		 * 			
+		 * 			if(not (production < consumption)) continue;
+		 * 			
+		 * 
+		 * 			for(Priority emergencyShutDownPriority: priorityListASC) do
+		 * 				difference = Math.abs(production - consumption);
+		 * 				amountOfAllEnergyOffered = sumEnergyAvailable(flexList); 
+		 * 				if(amountOfAllEnergyOffered > difference) break; 
+		 * 				shutDownAllConsumerWithPriority(emergencyShutDownPriority)
+		 * 			end for
+		 * 			
+		 * 			takeAKombinationOfOffers(); (nach welchem Kriterium)
+		 * 			
+		 * 			
+		 * 		end for
+		 * End
+		 * 
+		 */
+		private void executeDemoAlgo(RunResult result) {
+			extractPositionAndAccess();
+			int actualIteration = control.getModel().getCurIteration();
+			println("TimeStep:" + actualIteration);
+			control.calculateStateOnlyForCurrentTimeStep();
+			List<Priority> priorityListASC = createPriorityListASC();
+			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);
+				println("consumption: " + consumption);
+				println("difference: " + difference);
+				if(production > consumption) continue;
+				if(difference == 0)continue;
+				Set<HolonElement> allHolonElemntsInThisNetwork = createListOfAllHolonElemnts(net);
+				FlexManager flexManager = control.getSimManager().getActualFlexManager();
+				
+				List<FlexWrapper> allOfferedFlex = flexManager.getAllFlexWrapperWithState(FlexState.OFFERED).stream().filter(flexWrapper -> allHolonElemntsInThisNetwork.contains(flexWrapper.getFlex().getElement())).collect(Collectors.toList());
+				List<FlexWrapper> allFlexThatGetMeEnergy = allOfferedFlex.stream().filter(flexWrapper -> (flexWrapper.getFlex().bringtmir() > 0)).collect(Collectors.toList());
+				float amountOfAllEnergyOffered = sumEnergyAvailable(allFlexThatGetMeEnergy);
+				println("amountOfAllFlexEnergyOffered:" + amountOfAllEnergyOffered);
+				//ShuddownPriorities
+				for(Priority emergencyShutDownPriority: priorityListASC) {
+					if(amountOfAllEnergyOffered >= difference) break; 
+					println("ShutDown: " + emergencyShutDownPriority);
+					difference -= shutDownAllConsumerElementsWithPriority(flexManager, allHolonElemntsInThisNetwork, emergencyShutDownPriority, result);
+				}
+				
+				//SortFlexes
+				allFlexThatGetMeEnergy.sort((flex1, flex2) -> Float.compare(flex1.getFlex().cost / flex1.getFlex().bringtmir(), flex2.getFlex().cost / flex2.getFlex().bringtmir()));
+				//OrderFlexes
+				float costForThisTimeStep = 0f;
+				int amountflexActivated = 0;
+				for(FlexWrapper flexWrapper : allFlexThatGetMeEnergy) {
+					if(!flexWrapper.canOrder()) continue;
+					float energy = flexWrapper.getFlex().bringtmir();
+					if(energy <= difference) {
+						println("energyGained:" + energy);
+						difference -= energy;
+						costForThisTimeStep += flexWrapper.getFlex().cost;
+						flexWrapper.order();
+						amountflexActivated++;
+						continue;
+					}
+				}
+				result.activatedFlex += 	amountflexActivated;
+				
+				println("Activated FlexThisTimeStep: "+ amountflexActivated+"   CostForThisTimeStep:" + costForThisTimeStep);
+				result.totalCost += costForThisTimeStep;
+			}
+			calculateStateResult(result);
+		}
+		private void calculateStateResult(RunResult result) {
+			control.calculateStateOnlyForCurrentTimeStep();
+			RunResult.TimeStepStateResult timeStepState = result.addTimeStepStateResult();
+			
+			for(DecoratedNetwork network: control.getSimManager().getActualDecorState().getNetworkList()) {
+				timeStepState.amountOfConsumer += network.getAmountOfConsumer();
+				timeStepState.amountOfConsumerOverSupplied += network.getAmountOfConsumerWithState(HolonObjectState.OVER_SUPPLIED);
+				timeStepState.amountOfConsumerPartiallySupplied += network.getAmountOfConsumerWithState(HolonObjectState.PARTIALLY_SUPPLIED);
+				timeStepState.amountOfConsumerSupplied += network.getAmountOfConsumerWithState(HolonObjectState.SUPPLIED);
+				timeStepState.amountOfConsumerUnSupplied += network.getAmountOfConsumerWithState(HolonObjectState.NOT_SUPPLIED);
+				timeStepState.amountOfPassiv += network.getAmountOfPassiv();
+				timeStepState.amountOfProducer += network.getAmountOfSupplier();	
+			}
+			println("Producer: " + timeStepState.amountOfProducer);
+			println("Consumer: " + timeStepState.amountOfConsumer);
+			println("ConsumerOverSupplied: " + timeStepState.amountOfConsumerOverSupplied);
+			println("ConsumerSupplied: " + timeStepState.amountOfConsumerSupplied);
+			println("ConsumerPartiallySupplied: " + timeStepState.amountOfConsumerPartiallySupplied);
+			println("ConsumerUnSupplied: " + timeStepState.amountOfConsumerUnSupplied);
+			println("ConsumerUnSupplied: " + timeStepState.amountOfPassiv);
+		}
+		private void calculateAllResults(RunResult result) {
+			println("----------");
+			println("Average producer proportion: " + result.getAvergaeProportionWithState(HolonObjectState.PRODUCER));
+			println("Average producer OverSupplied: " + result.getAvergaeProportionWithState(HolonObjectState.OVER_SUPPLIED));
+			println("Average producer Supplied: " + result.getAvergaeProportionWithState(HolonObjectState.SUPPLIED));
+			println("Average producer PartiallySupplied: " + result.getAvergaeProportionWithState(HolonObjectState.PARTIALLY_SUPPLIED));
+			println("Average producer NotSupplied: " + result.getAvergaeProportionWithState(HolonObjectState.NOT_SUPPLIED));
+			println("Average producer NoEnergy: " + result.getAvergaeProportionWithState(HolonObjectState.NO_ENERGY));
+		}
+		
+		
+		
+		
+		
+		private float shutDownAllConsumerElementsWithPriority(FlexManager flexManager, Set<HolonElement> allHolonElemntsInThisNetwork,
+				Priority emergencyShutDownPriority, RunResult result) {
+			
+			List<HolonElement> elementsOfPriorityToShutdown = allHolonElemntsInThisNetwork.stream().filter(hElement -> hElement.isConsumer() && hElement.getPriority() == emergencyShutDownPriority && !hElement.isFlexActive(flexManager) && hElement.isActive()).collect(Collectors.toList());
+					//.forEach(hElement -> hElement.setActive(false));
+			float energyGained = elementsOfPriorityToShutdown.stream().map(hElement -> -hElement.getEnergyPerElement() * hElement.getAmount()).reduce(0.0f, (a, b) -> a + b);
+			elementsOfPriorityToShutdown.forEach(hElement -> hElement.setActive(false));
+			int shutdownCount = elementsOfPriorityToShutdown.size();
+			result.deactivatedElements += shutdownCount;
+			println("Gained " + energyGained + "Energy from Shutdown with Priority:" + emergencyShutDownPriority + " AmountOfShutDowned HolonElements: " + shutdownCount);
+			return energyGained;
+		}
+		private Set<HolonElement> createListOfAllHolonElemnts(DecoratedNetwork net) {
+			Set<HolonElement> allHolonElemntsInThisNetwork = new HashSet<HolonElement>();
+			allHolonElemntsInThisNetwork.addAll(net.getConsumerList().stream().flatMap(con -> con.getModel().getElements().stream()).collect(Collectors.toList()));
+			allHolonElemntsInThisNetwork.addAll(net.getConsumerSelfSuppliedList().stream().flatMap(con -> con.getModel().getElements().stream()).collect(Collectors.toList()));
+			allHolonElemntsInThisNetwork.addAll(net.getSupplierList().stream().flatMap(con -> con.getModel().getElements().stream()).collect(Collectors.toList()));
+			return allHolonElemntsInThisNetwork;
+		}
+
+	
+		private float sumEnergyAvailable(List<FlexWrapper> flexList) {
+			HashMap<HolonElement, FlexWrapper> dublicateFilter = new HashMap<HolonElement, FlexWrapper>();
+			flexList.stream().forEach(flexWrapper -> dublicateFilter.put(flexWrapper.getFlex().getElement(), flexWrapper));
+			
+			return dublicateFilter.values().stream().map(flexWrapper -> flexWrapper.getFlex().bringtmir()).reduce(0.0f,(a, b) -> a + b);
+		}
+		private List<Priority> createPriorityListASC() {
+			List<Priority> priorityASC = new ArrayList<Priority>();
+			priorityASC.add(Priority.Low);
+			priorityASC.add(Priority.Medium);
+			priorityASC.add(Priority.High);
+			priorityASC.add(Priority.Essential);
+			return priorityASC;
+		}
+		/**
+		 * 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());			
+			resetChain.add(initialState); 
+			return initialState;
+		}
+		/**
+		 * Method to extract the Informations recursively out of the Model.
+		 * @param nodes
+		 * @param positionToInit
+		 * @param timeStep
+		 */
+		private void rollOutNodes(List<AbstractCanvasObject> nodes, List<Boolean> positionToInit, int timeStep) {
+			for(AbstractCanvasObject 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 GroupNode) {
+					rollOutNodes(((GroupNode)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(resetChain.getLast());
+		}
+		
+		/**
+		 * Sets the State out of the given position for calculation or to show the user.
+		 * @param position
+		 */
+		private void setState(List<Boolean> position) {
+			for(int i = 0;i<position.size();i++) {
+				access.get(i).setState(position.get(i));
+			}
+		}
+	
+		
+		
+		
+		
+		/**
+		 * A 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);
+				}
+					
+			}
+		}
+		
+		
+		private class RunResult {
+			public int activatedFlex = 0;
+			public int deactivatedElements = 0;
+			public float totalCost = 0;
+			public LinkedList<TimeStepStateResult> timeStepList = new LinkedList<TimeStepStateResult>();
+			
+			
+			public TimeStepStateResult addTimeStepStateResult(){
+				TimeStepStateResult aResult = new TimeStepStateResult();
+				timeStepList.add(aResult);
+				return aResult;
+			}
+			
+			
+			public class TimeStepStateResult{
+				public int amountOfProducer = 0;
+				public int amountOfConsumer = 0;
+				public int amountOfPassiv = 0;
+				public int amountOfConsumerOverSupplied = 0;
+				public int amountOfConsumerSupplied = 0;
+				public int amountOfConsumerPartiallySupplied = 0;
+				public int amountOfConsumerUnSupplied= 0;
+				
+				public float getProportionWithState(HolonObjectState state) {
+					float amountOfObjects = amountOfProducer + amountOfConsumer + amountOfPassiv;
+					switch(state) {
+					case NOT_SUPPLIED:
+						return (float) amountOfConsumerUnSupplied / amountOfObjects;
+					case NO_ENERGY:
+						return (float) amountOfPassiv / amountOfObjects;
+					case OVER_SUPPLIED:
+						return (float) amountOfConsumerOverSupplied / amountOfObjects;
+					case PARTIALLY_SUPPLIED:
+						return (float) amountOfConsumerPartiallySupplied / amountOfObjects;
+					case PRODUCER:
+						return (float) amountOfProducer / amountOfObjects;
+					case SUPPLIED:
+						return (float) amountOfConsumerSupplied / amountOfObjects;
+					default:
+						return 0.f;
+					}
+				}
+			}
+			public float getAvergaeProportionWithState(HolonObjectState state) {
+				return timeStepList.stream().map(step -> step.getProportionWithState(state)).reduce((a,b) -> (a + b)).orElse(0.f) / (float) 100;
+			}
+		}
+		
+		private   class  Handle<T>{
+			public T object;
+			Handle(T object){
+				this.object = object;
+			}
+			public String toString() {
+				return object.toString();
+			}
+		}
+
+}

+ 1 - 0
src/algorithm/objectiveFunction/Evaluation.java

@@ -81,6 +81,7 @@ public class Evaluation {
 	 * @param obj Holon Object that contains Holon Elements
 	 * @return fitness value for that object depending on the number of deactivated holon elements
 	 */
+	@SuppressWarnings("unused")
 	private static double inactiveHolonElementPenalty(HolonObject obj) {
 		float result = 0;
 		int activeElements = obj.getNumberOfActiveElements();

+ 490 - 491
src/algorithm/objectiveFunction/GraphMetrics.java

@@ -1,491 +1,490 @@
-package algorithm.objectiveFunction;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map.Entry;
-import java.util.Set;
-
-import classes.AbstractCanvasObject;
-import classes.HolonObject;
-import classes.HolonSwitch;
-import ui.model.Consumer;
-import ui.model.DecoratedCable;
-import ui.model.DecoratedNetwork;
-import ui.model.Passiv;
-import ui.model.Supplier;
-
-public class GraphMetrics {
-	
-	
-	
-	public static class Vertex{
-		public int id = 0;
-		public Vertex(int id){
-			this.id = id;
-		}
-		public String toString() {
-			return "" + id;
-		}
-	}
-	private static class Edge{
-		public int idA, idB;
-		public double weight;
-		public Edge(int idA, int idB, double weight){
-			this.idA = idA;
-			this.idB = idB;
-			this.weight = weight;
-		}
-	}
-	
-	public static class Graph{
-		Vertex[] V;
-		Edge[] E;
-		/**Only the Sources/Trains for disjoint Path no Switch or Node**/
-		Vertex[] S;
-		
-		public String toString() {
-			String vList = "V" + Arrays.toString(V);
-			String sList = "S" + Arrays.toString(S);
-			return vList + ", " + sList;
-		}
-	}
-	
-	
-	
-	/**
-	 * Convert a DecoratedNetwork to a Graph
-	 * @param net
-	 * @return a equivalent Graph to the DecoratedNetwork
-	 */
-	public static Graph convertDecoratedNetworkToGraph(DecoratedNetwork net) {
-		Graph G = new Graph();
-		HashMap<AbstractCanvasObject, Integer> objectToId = new HashMap<>();
-		List<Integer> sourcesList = new ArrayList<Integer>();
-		int count = 0;
-		for(Consumer con: net.getConsumerList()) {
-			objectToId.put(con.getModel(), count);
-			sourcesList.add(count);
-			count++;
-		}
-		for(Consumer con: net.getConsumerSelfSuppliedList()) {
-			objectToId.put(con.getModel(), count);
-			sourcesList.add(count);
-			count++;
-		}
-		for(Passiv pas: net.getPassivNoEnergyList()) {
-			objectToId.put(pas.getModel(), count);
-			sourcesList.add(count);
-			count++;
-		}
-		for(Supplier sup: net.getSupplierList()) {
-			objectToId.put(sup.getModel(), count);
-			sourcesList.add(count);
-			count++;
-		}
-		
-		
-		
-		//Generate EdgeList 
-		List<Edge> edgeList = new ArrayList<Edge>();
-		for(DecoratedCable cable : net.getDecoratedCableList()){
-			
-			AbstractCanvasObject objectA = cable.getModel().getA();
-			AbstractCanvasObject objectB = cable.getModel().getB();
-			if(objectA == null) {
-				System.out.println("Edge: " + cable + "objectA == null");
-				continue;
-			}
-			if(objectB == null) {
-				System.out.println("Edge: " + cable + "objectB == null");
-				continue;
-			}
-			
-			//SpecialCase for open switches
-			if(objectA instanceof HolonSwitch && !((HolonSwitch)objectA).getManualState()) {
-				continue;
-			}
-			if(objectB instanceof HolonSwitch && !((HolonSwitch)objectB).getManualState()) {
-				continue;
-			}
-			
-			int idA = -1;
-			if(objectToId.containsKey(objectA)) {
-				idA = objectToId.get(objectA);
-			}else {
-				idA = count;
-				objectToId.put(objectA, count++);
-			}
-			int idB = -1;
-			if(objectToId.containsKey(objectB)) {
-				idB = objectToId.get(objectB);
-			}else {
-				idB = count;
-				objectToId.put(objectB, count++);
-			}
-			double length = cable.getModel().getLength();
-			edgeList.add(new Edge(idA, idB, length));
-		}
-		//Generate EdgeArray
-		G.E = new Edge[edgeList.size()];
-		for(int i=0;i<edgeList.size();i++)
-	    {
-				G.E[i] =  edgeList.get(i);
-	    }
-		//Generate VertexArray
-		G.V = new Vertex[objectToId.size()];
-		int entryCount = 0;
-		for(Entry<AbstractCanvasObject, Integer> entry : objectToId.entrySet()) {
-			G.V[entryCount] =  new Vertex(entry.getValue());
-			entryCount++;
-		}
-		//Generate Sources Array
-		int sourceCount = 0;
-		G.S = new Vertex[sourcesList.size()];
-		for(int source : sourcesList) {
-			G.S[sourceCount] = new Vertex(source);
-			sourceCount++;
-		}
-		return G;
-	}
-	
-	
-// Example Test
-	 public static void main(String[] args){
-		 Graph G = new Graph();
-		 G.V = new Vertex[4];
-		 for(int i=0;i<G.V.length;i++)
-	     {
-				G.V[i] =  new Vertex(i);
-	     }
-		 G.E = new Edge[4];
-		 
-		 G.E[0] = new Edge(0, 1, 1);
-		 G.E[1] = new Edge(1, 2, 1);
-		 G.E[2] = new Edge(2, 3, 1);
-		 G.E[3] = new Edge(3, 0, 1);
-		 
-		 G.S = new Vertex[4];
-		 G.S[0] = new Vertex(0);
-		 G.S[1] = new Vertex(1);
-		 G.S[2] = new Vertex(2);
-		 G.S[3] = new Vertex(3);
-		 System.out.println(G);
-		 System.out.println("minimumCut: " + minimumCut(G.V, G.E));
-		 System.out.println("AvgShortestDistance " + averageShortestDistance(G));
-		 System.out.println("DisjointPath " + averageEdgeDisjointPathProblem(G));
-	 }
-	 
-	 static int[][] generateDisjointWeightMatrix(Vertex[] V, Edge[] E){
-			int[][] L = new int[V.length][V.length];
-			for(int i = 0; i < E.length; i++) {
-				L[E[i].idA][E[i].idB] = 1;
-				L[E[i].idB][E[i].idA] = 1;
-			}
-			return L;
-		}
-	 
-	 /** find the average s_t disjoint paths between all pairs of s and t **/
-	 static double averageEdgeDisjointPathProblem(Graph G) {
-		 //This matrix indicates if a Edge is existent between two vertices
-		int[][] L = generateDisjointWeightMatrix(G.V, G.E);
-		double disjointPathSum = 0.0;
-		 for(int s = 0; s < G.S.length; s++) {
-			 for(int t = s; t < G.S.length; t++) {
-				 disjointPathSum += s_t_EdgeDisjointPath(G.S[s].id, G.S[t].id, L);					 
-			 }
-		 }
-		 //Returns the Average
-		 return disjointPathSum / ((G.S.length * (G.S.length - 1)) / 2);
-	 }
-	 
-	 
-	 
-	 /** find the amount of s_t disjoint paths between s and t **/
-	 private static double s_t_EdgeDisjointPath(int s, int t, int[][] L_input) {
-		 if(s == t) return 0;
-		 //Make Copy of L
-		int [][] L = makeCopyOfMatrix(L_input);
-		double foundPaths = 0;
-		//RepeatBreathFirst search till no path is found
-		boolean b_foundpath = true;
-		while(b_foundpath) {
-			b_foundpath = breathFirstSearch(s,t,L);
-			if(b_foundpath) {
-				foundPaths++;
-			}
-		}
-		return foundPaths;
-	}
-
-	 /** execute one breathFirstSearch to find a path between s and t **/
-	 private static boolean breathFirstSearch(int s, int t, int[][] L) {
-		 //Visited Notes 
-		 Set<Integer> visitedNotes = new HashSet<Integer>();
-		 //Queue to check which node to search next
-		 LinkedList<Integer> queue = new LinkedList<Integer>();
-		 //Map to traverse the path back when found a path 
-		 HashMap<Integer,Integer> noteBeforeMap = new HashMap<Integer,Integer>();
-		 //Add starting Point
-		 queue.add(s);
-		 //Visit all neighbours of the next point in queue
-		 while(!queue.isEmpty()) {
-			 int id = queue.pollFirst();
-			 visitedNotes.add(id);
-			 //For all neighbors add to queue
-			 for(int i = 0; i < L[id].length; i++) {
-				 //Check if edge exist and not visited before
-				 if(L[id][i] != 0 && !visitedNotes.contains(i)) {
-					 
-					 queue.add(i);
-					 noteBeforeMap.putIfAbsent(i, id);
-					 //check if train is found
-					 if(i == t) {
-						 //update connectionMatrix l and remove the found path
-						 int actualID = t;
-						 while(actualID != s) {
-							 int nextID = noteBeforeMap.get(actualID);
-							 //remove edge
-							 L[nextID][actualID] = 0;
-							 L[actualID][nextID] = 0;
-							 actualID = nextID; 
-						 }
-						 return true;
-					 }
-				 }
-				 
-			 }
-		 }
-		 //if last queue element is searched but t is not reachable 
-		 return false;
-	}
-
-	/**
-	  * Makes a deep Copy of a Integer Matrix
-	  * @param l_input
-	  * @return
-	  */
-	private static int[][] makeCopyOfMatrix(int[][] matrix) {
-		int[][] copyMatrix = new int[matrix.length][matrix[0].length];
-		for(int i = 0; i < matrix.length; i++) {
-			for(int j = 0; j < matrix[0].length; j++) {
-				copyMatrix[i][j] = matrix[i][j];
-			}
-		}
-		return copyMatrix;
-	}
-
-	/**
-	  * Stoer Wagner Minimal Cut Algo
-	  * Source from
-	  * <a href="https://github.com/hunglvosu/algorithm/blob/master/algorithm/src/Stoer-Wagner.c">
-	  * https://github.com/hunglvosu/algorithm/blob/master/algorithm/src/Stoer-Wagner.c</a> <br>
-	  * in C formatted written in java
-	  * @param V Vertex Array
-	  * @param E Edge Array
-	  * @return
-	  */
-	 
-	 static int minimumCut(Vertex[] V, Edge[] E) {
-		 int[][] W = generateDisjointWeightMatrix(V, E); 
-		 boolean[] Del = new boolean[V.length];
-		 int n = V.length;				// the number of veritces
-		 int m = E.length;
-		return StoerWagner(n, m, W, Del);
-		 
-	 }
-	 
-	 static int StoerWagner(int n, int m, int[][] W, boolean[] Del){
-			int C = Integer.MAX_VALUE;
-			for(int V = n; V > 1; V--){
-				int cutValue = minCutPhase(V, W, Del, n, m);
-				C = (C < cutValue ? C: cutValue);	
-			}
-			return C;
-		}
-	 
-	 static int minCutPhase(int V, int[][] W, boolean[] Del, int n, int m){
-			int i = 0, j = 0;
-			int[] s = new int[2];
-			if(V  == 2) {
-				for( i = 0; i < n; i++){
-					if(Del[i] == false){
-						s[j] = i; j++;
-					}
-				}
-				return W[s[0]][s[1]];
-			}
-			int[] L = new int[n];
-			boolean[] T = new boolean[n];
-			
-			i = 1;	// the number of vertices in the tree T
-			j = 0;
-			int v,u;
-			while( i <= V){
-				v = maxStickiness(T,L, Del, n);
-				T[v] = true;
-				for(u = 0; u < n; u++){
-					if(W[v][u] != 0 && Del[u] == false && T[u] == false){
-						L[u] = L[u] + W[u][v];
-					}
-				}
-				if( i >= V-1){
-					s[j] = v; j++;
-				}
-				i++;
-			}
-			merge(s[0], s[1], n, W, Del);
-			return L[s[1]];	
-		}
-	 
-
-		static int maxStickiness(boolean[] T, int[] L, boolean[] Del, int n){
-			int i = 0;
-			int v = 0;
-			int max = 0;
-			for(i = 0; i < n; i++){
-				if(Del[i] == false && T[i] == false && max < L[i]){
-					v = i;
-					max = L[i];
-				} 
-			}
-			return v;
-		}
-	 
-
-		static void merge(int s, int t, int n, int[][] W, boolean[] Del){
-			int v = 0;
-			for(v = 0; v < n; v++){
-				if(Del[v] == false && v != s && v!= t){
-					W[s][v] = W[s][v] + W[v][t];
-					W[v][s] = W[s][v];
-				}
-			}
-			Del[t] = true;	
-		}
-
-
-
-
-
-	static double[][] basicAllPairsShortestPath(Vertex[] V, Edge[] E){
-		 double[][] L = generateWeightMatrix(V, E);
-		 double[][] D = generateDistanceMatrix(V);
-		 boolean[] flag = generateFlagList(V);
-		 for(int i=0;i<V.length;i++) {
-			 modifiedDikstra(V[i].id, L, D, flag);
-		 }
-		 return D;
-	 }
-	 static double averageShortestDistance(Graph G) {
-		 if(G.V.length <= 1) return 0.0;
-		 double[][] D = basicAllPairsShortestPath(G.V, G.E);
-		 double sum = 0.0;
-		 for(int s = 0; s < G.S.length; s++) {
-			 for(int t = s; t < G.S.length; t++) {
-				sum += D[G.S[s].id][G.S[t].id];					 
-			 }
-		 }
-		 //Returns the Average
-		 return sum / ((G.S.length * (G.S.length - 1)) / 2);
-	 } 
-	/** 
-	 * @return Updated Distance Matrix D and flag List 
-	 */
-	static void modifiedDikstra(int source, double[][] L, double[][] D, boolean[] flag) {
-		D[source][source] = 0;
-		LinkedList<Integer> visitedNotes = new LinkedList<Integer>(); 
-		LinkedList<Integer> minPriorityQueue = new LinkedList<Integer>(); 
-		minPriorityQueue.add(source);
-		
-		
-		
-		while(!minPriorityQueue.isEmpty()) {
-			minPriorityQueue.sort((a,b) -> Double.compare(D[source][a],  D[source][b]));
-			int target =  minPriorityQueue.pop();
-			if(flag[source] == true) {
-				for(int outgoingID = 0; outgoingID < L.length; outgoingID++) {
-					if(D[source][target] + L[target][outgoingID] < D[source][outgoingID]) {
-						D[source][outgoingID] = D[source][target] + L[target][outgoingID];
-					}
-				}
-			}else {
-				for(int outgoingID = 0; outgoingID < L.length; outgoingID++) {
-					if(L[target][outgoingID] == Double.POSITIVE_INFINITY) continue;
-					if(D[source][target] + L[target][outgoingID] < D[source][outgoingID]) {
-						D[source][outgoingID] = D[source][target] + L[target][outgoingID];
-						if(!visitedNotes.contains(outgoingID)) {
-							minPriorityQueue.add(outgoingID);
-						}
-					}
-				}
-			}
-			visitedNotes.add(target);
-		}
-		flag[source] = true;
-	}
-	
-	static void printMatrix(int[][] matrix) {
-		for(int i=0;i<matrix.length;i++)
-        {
-            for(int j=0;j<matrix.length;j++)
-            {
-                System.out.print(matrix[i][j] +  " ");
-            }
-            System.out.println();
-        }
-	}
-	static void printMatrix(double[][] matrix) {
-		for(int i=0;i<matrix.length;i++)
-        {
-            for(int j=0;j<matrix.length;j++)
-            {
-                System.out.print(matrix[i][j] +  " ");
-            }
-            System.out.println();
-        }
-	}
-	static double[][] generateWeightMatrix(Vertex[] V, Edge[] E){
-		double[][] L = new double[V.length][V.length];
-		for(int i = 0; i < E.length; i++) {
-			try {
-			L[E[i].idA][E[i].idB] = E[i].weight;
-			L[E[i].idB][E[i].idA] = E[i].weight;
-			}catch(java.lang.NullPointerException e) {
-				System.out.println("E[i].idA:" + E[i].idA + " E[i].idB:" + E[i].idB + " E[i].weight:" + E[i].weight);
-			}
-		}
-		for(int i=0;i<L.length;i++)
-        {
-            for(int j=0;j<L.length;j++)
-            {
-                if(L[i][j]==0.0) L[i][j] = Double.POSITIVE_INFINITY;
-            }
-        }
-		for(int i=0;i<L.length;i++)
-        {
-			L[i][i] = 0.0;
-        }
-		return L;
-	}
-	static double[][] generateDistanceMatrix(Vertex[] V) {
-		double[][] D = new double[V.length][V.length];
-		for(int i=0;i<D.length;i++)
-        {
-            for(int j=0;j<D.length;j++)
-            {
-                D[i][j] = Double.POSITIVE_INFINITY;
-            }
-        }
-		return D;
-	}
-	private static boolean[] generateFlagList(Vertex[] V) {
-		boolean[] flag = new boolean[V.length];
-		return flag;
-	}
-
-
-}
+package algorithm.objectiveFunction;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map.Entry;
+import java.util.Set;
+
+import classes.AbstractCanvasObject;
+import classes.HolonSwitch;
+import ui.model.Consumer;
+import ui.model.DecoratedCable;
+import ui.model.DecoratedNetwork;
+import ui.model.Passiv;
+import ui.model.Supplier;
+
+public class GraphMetrics {
+	
+	
+	
+	public static class Vertex{
+		public int id = 0;
+		public Vertex(int id){
+			this.id = id;
+		}
+		public String toString() {
+			return "" + id;
+		}
+	}
+	private static class Edge{
+		public int idA, idB;
+		public double weight;
+		public Edge(int idA, int idB, double weight){
+			this.idA = idA;
+			this.idB = idB;
+			this.weight = weight;
+		}
+	}
+	
+	public static class Graph{
+		Vertex[] V;
+		Edge[] E;
+		/**Only the Sources/Trains for disjoint Path no Switch or Node**/
+		Vertex[] S;
+		
+		public String toString() {
+			String vList = "V" + Arrays.toString(V);
+			String sList = "S" + Arrays.toString(S);
+			return vList + ", " + sList;
+		}
+	}
+	
+	
+	
+	/**
+	 * Convert a DecoratedNetwork to a Graph
+	 * @param net
+	 * @return a equivalent Graph to the DecoratedNetwork
+	 */
+	public static Graph convertDecoratedNetworkToGraph(DecoratedNetwork net) {
+		Graph G = new Graph();
+		HashMap<AbstractCanvasObject, Integer> objectToId = new HashMap<>();
+		List<Integer> sourcesList = new ArrayList<Integer>();
+		int count = 0;
+		for(Consumer con: net.getConsumerList()) {
+			objectToId.put(con.getModel(), count);
+			sourcesList.add(count);
+			count++;
+		}
+		for(Consumer con: net.getConsumerSelfSuppliedList()) {
+			objectToId.put(con.getModel(), count);
+			sourcesList.add(count);
+			count++;
+		}
+		for(Passiv pas: net.getPassivNoEnergyList()) {
+			objectToId.put(pas.getModel(), count);
+			sourcesList.add(count);
+			count++;
+		}
+		for(Supplier sup: net.getSupplierList()) {
+			objectToId.put(sup.getModel(), count);
+			sourcesList.add(count);
+			count++;
+		}
+		
+		
+		
+		//Generate EdgeList 
+		List<Edge> edgeList = new ArrayList<Edge>();
+		for(DecoratedCable cable : net.getDecoratedCableList()){
+			
+			AbstractCanvasObject objectA = cable.getModel().getA();
+			AbstractCanvasObject objectB = cable.getModel().getB();
+			if(objectA == null) {
+				System.out.println("Edge: " + cable + "objectA == null");
+				continue;
+			}
+			if(objectB == null) {
+				System.out.println("Edge: " + cable + "objectB == null");
+				continue;
+			}
+			
+			//SpecialCase for open switches
+			if(objectA instanceof HolonSwitch && !((HolonSwitch)objectA).getManualState()) {
+				continue;
+			}
+			if(objectB instanceof HolonSwitch && !((HolonSwitch)objectB).getManualState()) {
+				continue;
+			}
+			
+			int idA = -1;
+			if(objectToId.containsKey(objectA)) {
+				idA = objectToId.get(objectA);
+			}else {
+				idA = count;
+				objectToId.put(objectA, count++);
+			}
+			int idB = -1;
+			if(objectToId.containsKey(objectB)) {
+				idB = objectToId.get(objectB);
+			}else {
+				idB = count;
+				objectToId.put(objectB, count++);
+			}
+			double length = cable.getModel().getLength();
+			edgeList.add(new Edge(idA, idB, length));
+		}
+		//Generate EdgeArray
+		G.E = new Edge[edgeList.size()];
+		for(int i=0;i<edgeList.size();i++)
+	    {
+				G.E[i] =  edgeList.get(i);
+	    }
+		//Generate VertexArray
+		G.V = new Vertex[objectToId.size()];
+		int entryCount = 0;
+		for(Entry<AbstractCanvasObject, Integer> entry : objectToId.entrySet()) {
+			G.V[entryCount] =  new Vertex(entry.getValue());
+			entryCount++;
+		}
+		//Generate Sources Array
+		int sourceCount = 0;
+		G.S = new Vertex[sourcesList.size()];
+		for(int source : sourcesList) {
+			G.S[sourceCount] = new Vertex(source);
+			sourceCount++;
+		}
+		return G;
+	}
+	
+	
+// Example Test
+	 public static void main(String[] args){
+		 Graph G = new Graph();
+		 G.V = new Vertex[4];
+		 for(int i=0;i<G.V.length;i++)
+	     {
+				G.V[i] =  new Vertex(i);
+	     }
+		 G.E = new Edge[4];
+		 
+		 G.E[0] = new Edge(0, 1, 1);
+		 G.E[1] = new Edge(1, 2, 1);
+		 G.E[2] = new Edge(2, 3, 1);
+		 G.E[3] = new Edge(3, 0, 1);
+		 
+		 G.S = new Vertex[4];
+		 G.S[0] = new Vertex(0);
+		 G.S[1] = new Vertex(1);
+		 G.S[2] = new Vertex(2);
+		 G.S[3] = new Vertex(3);
+		 System.out.println(G);
+		 System.out.println("minimumCut: " + minimumCut(G.V, G.E));
+		 System.out.println("AvgShortestDistance " + averageShortestDistance(G));
+		 System.out.println("DisjointPath " + averageEdgeDisjointPathProblem(G));
+	 }
+	 
+	 static int[][] generateDisjointWeightMatrix(Vertex[] V, Edge[] E){
+			int[][] L = new int[V.length][V.length];
+			for(int i = 0; i < E.length; i++) {
+				L[E[i].idA][E[i].idB] = 1;
+				L[E[i].idB][E[i].idA] = 1;
+			}
+			return L;
+		}
+	 
+	 /** find the average s_t disjoint paths between all pairs of s and t **/
+	 static double averageEdgeDisjointPathProblem(Graph G) {
+		 //This matrix indicates if a Edge is existent between two vertices
+		int[][] L = generateDisjointWeightMatrix(G.V, G.E);
+		double disjointPathSum = 0.0;
+		 for(int s = 0; s < G.S.length; s++) {
+			 for(int t = s; t < G.S.length; t++) {
+				 disjointPathSum += s_t_EdgeDisjointPath(G.S[s].id, G.S[t].id, L);					 
+			 }
+		 }
+		 //Returns the Average
+		 return disjointPathSum / ((G.S.length * (G.S.length - 1)) / 2);
+	 }
+	 
+	 
+	 
+	 /** find the amount of s_t disjoint paths between s and t **/
+	 private static double s_t_EdgeDisjointPath(int s, int t, int[][] L_input) {
+		 if(s == t) return 0;
+		 //Make Copy of L
+		int [][] L = makeCopyOfMatrix(L_input);
+		double foundPaths = 0;
+		//RepeatBreathFirst search till no path is found
+		boolean b_foundpath = true;
+		while(b_foundpath) {
+			b_foundpath = breathFirstSearch(s,t,L);
+			if(b_foundpath) {
+				foundPaths++;
+			}
+		}
+		return foundPaths;
+	}
+
+	 /** execute one breathFirstSearch to find a path between s and t **/
+	 private static boolean breathFirstSearch(int s, int t, int[][] L) {
+		 //Visited Notes 
+		 Set<Integer> visitedNotes = new HashSet<Integer>();
+		 //Queue to check which node to search next
+		 LinkedList<Integer> queue = new LinkedList<Integer>();
+		 //Map to traverse the path back when found a path 
+		 HashMap<Integer,Integer> noteBeforeMap = new HashMap<Integer,Integer>();
+		 //Add starting Point
+		 queue.add(s);
+		 //Visit all neighbours of the next point in queue
+		 while(!queue.isEmpty()) {
+			 int id = queue.pollFirst();
+			 visitedNotes.add(id);
+			 //For all neighbors add to queue
+			 for(int i = 0; i < L[id].length; i++) {
+				 //Check if edge exist and not visited before
+				 if(L[id][i] != 0 && !visitedNotes.contains(i)) {
+					 
+					 queue.add(i);
+					 noteBeforeMap.putIfAbsent(i, id);
+					 //check if train is found
+					 if(i == t) {
+						 //update connectionMatrix l and remove the found path
+						 int actualID = t;
+						 while(actualID != s) {
+							 int nextID = noteBeforeMap.get(actualID);
+							 //remove edge
+							 L[nextID][actualID] = 0;
+							 L[actualID][nextID] = 0;
+							 actualID = nextID; 
+						 }
+						 return true;
+					 }
+				 }
+				 
+			 }
+		 }
+		 //if last queue element is searched but t is not reachable 
+		 return false;
+	}
+
+	/**
+	  * Makes a deep Copy of a Integer Matrix
+	  * @param l_input
+	  * @return
+	  */
+	private static int[][] makeCopyOfMatrix(int[][] matrix) {
+		int[][] copyMatrix = new int[matrix.length][matrix[0].length];
+		for(int i = 0; i < matrix.length; i++) {
+			for(int j = 0; j < matrix[0].length; j++) {
+				copyMatrix[i][j] = matrix[i][j];
+			}
+		}
+		return copyMatrix;
+	}
+
+	/**
+	  * Stoer Wagner Minimal Cut Algo
+	  * Source from
+	  * <a href="https://github.com/hunglvosu/algorithm/blob/master/algorithm/src/Stoer-Wagner.c">
+	  * https://github.com/hunglvosu/algorithm/blob/master/algorithm/src/Stoer-Wagner.c</a> <br>
+	  * in C formatted written in java
+	  * @param V Vertex Array
+	  * @param E Edge Array
+	  * @return
+	  */
+	 
+	 static int minimumCut(Vertex[] V, Edge[] E) {
+		 int[][] W = generateDisjointWeightMatrix(V, E); 
+		 boolean[] Del = new boolean[V.length];
+		 int n = V.length;				// the number of veritces
+		 int m = E.length;
+		return StoerWagner(n, m, W, Del);
+		 
+	 }
+	 
+	 static int StoerWagner(int n, int m, int[][] W, boolean[] Del){
+			int C = Integer.MAX_VALUE;
+			for(int V = n; V > 1; V--){
+				int cutValue = minCutPhase(V, W, Del, n, m);
+				C = (C < cutValue ? C: cutValue);	
+			}
+			return C;
+		}
+	 
+	 static int minCutPhase(int V, int[][] W, boolean[] Del, int n, int m){
+			int i = 0, j = 0;
+			int[] s = new int[2];
+			if(V  == 2) {
+				for( i = 0; i < n; i++){
+					if(Del[i] == false){
+						s[j] = i; j++;
+					}
+				}
+				return W[s[0]][s[1]];
+			}
+			int[] L = new int[n];
+			boolean[] T = new boolean[n];
+			
+			i = 1;	// the number of vertices in the tree T
+			j = 0;
+			int v,u;
+			while( i <= V){
+				v = maxStickiness(T,L, Del, n);
+				T[v] = true;
+				for(u = 0; u < n; u++){
+					if(W[v][u] != 0 && Del[u] == false && T[u] == false){
+						L[u] = L[u] + W[u][v];
+					}
+				}
+				if( i >= V-1){
+					s[j] = v; j++;
+				}
+				i++;
+			}
+			merge(s[0], s[1], n, W, Del);
+			return L[s[1]];	
+		}
+	 
+
+		static int maxStickiness(boolean[] T, int[] L, boolean[] Del, int n){
+			int i = 0;
+			int v = 0;
+			int max = 0;
+			for(i = 0; i < n; i++){
+				if(Del[i] == false && T[i] == false && max < L[i]){
+					v = i;
+					max = L[i];
+				} 
+			}
+			return v;
+		}
+	 
+
+		static void merge(int s, int t, int n, int[][] W, boolean[] Del){
+			int v = 0;
+			for(v = 0; v < n; v++){
+				if(Del[v] == false && v != s && v!= t){
+					W[s][v] = W[s][v] + W[v][t];
+					W[v][s] = W[s][v];
+				}
+			}
+			Del[t] = true;	
+		}
+
+
+
+
+
+	static double[][] basicAllPairsShortestPath(Vertex[] V, Edge[] E){
+		 double[][] L = generateWeightMatrix(V, E);
+		 double[][] D = generateDistanceMatrix(V);
+		 boolean[] flag = generateFlagList(V);
+		 for(int i=0;i<V.length;i++) {
+			 modifiedDikstra(V[i].id, L, D, flag);
+		 }
+		 return D;
+	 }
+	 static double averageShortestDistance(Graph G) {
+		 if(G.V.length <= 1) return 0.0;
+		 double[][] D = basicAllPairsShortestPath(G.V, G.E);
+		 double sum = 0.0;
+		 for(int s = 0; s < G.S.length; s++) {
+			 for(int t = s; t < G.S.length; t++) {
+				sum += D[G.S[s].id][G.S[t].id];					 
+			 }
+		 }
+		 //Returns the Average
+		 return sum / ((G.S.length * (G.S.length - 1)) / 2);
+	 } 
+	/** 
+	 * @return Updated Distance Matrix D and flag List 
+	 */
+	static void modifiedDikstra(int source, double[][] L, double[][] D, boolean[] flag) {
+		D[source][source] = 0;
+		LinkedList<Integer> visitedNotes = new LinkedList<Integer>(); 
+		LinkedList<Integer> minPriorityQueue = new LinkedList<Integer>(); 
+		minPriorityQueue.add(source);
+		
+		
+		
+		while(!minPriorityQueue.isEmpty()) {
+			minPriorityQueue.sort((a,b) -> Double.compare(D[source][a],  D[source][b]));
+			int target =  minPriorityQueue.pop();
+			if(flag[source] == true) {
+				for(int outgoingID = 0; outgoingID < L.length; outgoingID++) {
+					if(D[source][target] + L[target][outgoingID] < D[source][outgoingID]) {
+						D[source][outgoingID] = D[source][target] + L[target][outgoingID];
+					}
+				}
+			}else {
+				for(int outgoingID = 0; outgoingID < L.length; outgoingID++) {
+					if(L[target][outgoingID] == Double.POSITIVE_INFINITY) continue;
+					if(D[source][target] + L[target][outgoingID] < D[source][outgoingID]) {
+						D[source][outgoingID] = D[source][target] + L[target][outgoingID];
+						if(!visitedNotes.contains(outgoingID)) {
+							minPriorityQueue.add(outgoingID);
+						}
+					}
+				}
+			}
+			visitedNotes.add(target);
+		}
+		flag[source] = true;
+	}
+	
+	static void printMatrix(int[][] matrix) {
+		for(int i=0;i<matrix.length;i++)
+        {
+            for(int j=0;j<matrix.length;j++)
+            {
+                System.out.print(matrix[i][j] +  " ");
+            }
+            System.out.println();
+        }
+	}
+	static void printMatrix(double[][] matrix) {
+		for(int i=0;i<matrix.length;i++)
+        {
+            for(int j=0;j<matrix.length;j++)
+            {
+                System.out.print(matrix[i][j] +  " ");
+            }
+            System.out.println();
+        }
+	}
+	static double[][] generateWeightMatrix(Vertex[] V, Edge[] E){
+		double[][] L = new double[V.length][V.length];
+		for(int i = 0; i < E.length; i++) {
+			try {
+			L[E[i].idA][E[i].idB] = E[i].weight;
+			L[E[i].idB][E[i].idA] = E[i].weight;
+			}catch(java.lang.NullPointerException e) {
+				System.out.println("E[i].idA:" + E[i].idA + " E[i].idB:" + E[i].idB + " E[i].weight:" + E[i].weight);
+			}
+		}
+		for(int i=0;i<L.length;i++)
+        {
+            for(int j=0;j<L.length;j++)
+            {
+                if(L[i][j]==0.0) L[i][j] = Double.POSITIVE_INFINITY;
+            }
+        }
+		for(int i=0;i<L.length;i++)
+        {
+			L[i][i] = 0.0;
+        }
+		return L;
+	}
+	static double[][] generateDistanceMatrix(Vertex[] V) {
+		double[][] D = new double[V.length][V.length];
+		for(int i=0;i<D.length;i++)
+        {
+            for(int j=0;j<D.length;j++)
+            {
+                D[i][j] = Double.POSITIVE_INFINITY;
+            }
+        }
+		return D;
+	}
+	private static boolean[] generateFlagList(Vertex[] V) {
+		boolean[] flag = new boolean[V.length];
+		return flag;
+	}
+
+
+}

+ 265 - 270
src/algorithm/objectiveFunction/ObjectiveFunctionByCarlos.java

@@ -1,271 +1,266 @@
-package algorithm.objectiveFunction;
-
-import ui.model.DecoratedNetwork;
-import ui.model.DecoratedState;
-import java.lang.Exception;
-import java.util.Locale;
-
-import classes.Flexibility;
-import classes.HolonElement.Priority;
-
-public class ObjectiveFunctionByCarlos {
-	//Parameters
-	
-	//weight for f_g(H)
-	static double w_eb = .3, w_state = .3, w_pro = .2, w_perf = .1, w_holon=.1;
-	//killswitch weights
-	//static double w_eb = 0.5, w_state = 0.5, w_pro = 0.0f, w_perf = .0, w_holon=.0;
-	
-	//kappas for squashing function
-//	
-	static double k_eb = 1050000.f, k_state = 10000, k_pro = 2000, k_perf = 11000, k_holon= 150000;
-//  oversupplied
-//	static double k_eb = 750000.f, k_state = 20000, k_pro = 3000, k_perf = 15000, k_holon= 200000;
-	
-//	old values undersupplied 
-//	static double k_eb = 1000000.f, k_state = 15000, k_pro = 2100, k_perf = 12000, k_holon= 200000;
-	
-	//theta for f_pro
-	static double theta = 3;
-	
-	//kappas for f_perf:
-	static double kappa_f_unre = 120;
-	static double kappa_f_cool = 60*60*24;
-	static double kappa_f_dur = 60*60;
-	
-	//lambdas for f_perf:
-	static double lambda_f_unre = 10;
-	static double lambda_f_cool = 10;
-	static double lambda_f_dur = 10;
-	
-	static double lambda_f_change = 1000;
-	
-	
-	
-	//pre-calculated parameters for partial function terms:
-	/** 
-	 * Pre calculated for the squash function
-	 * <br>
-	 *  {@link ObjectiveFunctionByCarlos#squash}
-	 */
-	static double squash_subtract = 1.0f / (1.f + (float) Math.exp(5.0));
-	static double range_for_kappa_f_unre = range(kappa_f_unre);
-	static double range_for_kappa_f_cool = range(kappa_f_cool);
-	static double range_for_kappa_f_dur = range(kappa_f_dur);
-	
-	
-	public static void main(String[] args) {
-		System.out.println("Hello World");
-		System.out.println("range_for_kappa_f_unre:" + range_for_kappa_f_unre);
-		double input = 0;
-		System.out.println(input + ": " + durationPenalty(input));
-		input = 60;
-		System.out.println(input + ": " + durationPenalty(input));
-		input = 1000;
-		System.out.println(input + ": " + durationPenalty(input));
-		input = 3600;
-		System.out.println(input + ": " + durationPenalty(input));
-	}
-	static {
-        //init
-		checkParameter();
-    }
-	
-	/**
-	 * Check parameter Setting and print error when wrong values are put in.
-	 * Here should all invariants be placed to be checked on initialization.
-	 */
-	private static void checkParameter() {
-		if(!(Math.abs(w_eb + w_state + w_pro + w_perf + w_holon - 1) < 0.001)) {
-			System.err.println("ParameterError in ObjectiveFunction: w1 + w2 + w3 + w4 + w5 should be 1");
-		}
-	}
-	
-	/**
-	 * ObjectifeFunction by Carlos.
-	 * Function computes f_g:
-	 * f_g = w1 * squash(f_eb, k1) + w2 * squash(f_state, k2) + w3 * squash(f_pro, k3) + w4 * squash(f_perf, k4) + w5 * squash(f_holon, k5) 
-	 * 
-	 * 
-	 * squash is the squashing function {@link ObjectiveFunctionByCarlos#squash}
-	 * 
-	 * 
-	 * @param state
-	 * @return f_g value between 0 and 100
-	 */
-	static public double getFitnessValueForState(DecoratedState state) {
-		
-		//Calculate f_eb the penalty for unbalenced energy in the network
-		double f_eb = 0;
-		//sum over all objects
-		for(DecoratedNetwork net : state.getNetworkList()) {
-			double netEnergyDifference = 0;
-			netEnergyDifference += net.getConsumerList().stream().map(con -> con.getEnergySelfSupplied() - con.getEnergyFromConsumingElemnets()).reduce(0.f, Float::sum);
-			netEnergyDifference += net.getConsumerSelfSuppliedList().stream().map(con -> con.getEnergySelfSupplied() - con.getEnergyFromConsumingElemnets()).reduce(0.f, Float::sum);
-			netEnergyDifference += net.getSupplierList().stream().map(sup -> sup.getEnergyProducing() - sup.getEnergySelfConsuming()).reduce(0.f, Float::sum);
-			//abs
-			f_eb += Math.abs(netEnergyDifference);
-		}
-		
-		//Calculate f_state the penalty function for the supply state
-		double f_state = 0;
-		for(DecoratedNetwork net : state.getNetworkList()) {
-			f_state += net.getConsumerList().stream().map(con -> supplyPenalty(con.getSupplyBarPercentage())).reduce(0., Double::sum);
-		}
-		
-		//calculate f_pro the penalty function for priority usage 
-		// for each active flexibility punish
-		double f_pro = 0;
-		f_pro = state.getFlexManager().getAllFlexesOrderedThisTimeStep().stream().map(flex -> Math.pow(theta, priorityToDouble(flex.getElement().getPriority()) ) - 1.0).reduce(0.0, Double::sum);
-		
-		//calculate f_perf the penalty function for the quality of a flexibility used
-		
-		// and the subfuction f_unre, f_cool, f_dur
-		double f_perf = 0;
-		for(Flexibility flex : state.getFlexManager().getAllFlexesOrderedThisTimeStep()) {
-			double f_unre =  unresponsivnessPenalty(flex.getSpeed());
-			double f_cool = cooldownPenalty(flex.getCooldown());
-			double f_dur = durationPenalty(flex.getDuration());
-			f_perf += f_unre + f_cool + f_dur;
-		}
-		
-		//calculate f_holon
-		double f_holon = 0;
-		for(DecoratedNetwork net : state.getNetworkList()) {
-			double f_elements_diviation_production = net.getDeviationInProductionInNetworkForHolonObjects();
-			double f_elements_diviation_consumption = net.getDeviationInProductionInNetworkForHolonObjects();
-			double f_flexibility_diviation_consumption = net.getDiviationInFlexibilityConsumption();
-			double f_flexibility_diviation_production = net.getDiviationInFlexibilityProduction();
-			
-			
-			double con = net.getTotalConsumption();
-			double prod = net.getTotalProduction();
-			double flexcapProd = net.getFlexibilityProductionCapacity();
-			double flexcapCon = net.getFlexibilityConsumptionCapacity();
-			double f_change_positive = lambda_f_change - lambda_f_change * Math.min(1, (con > 0.0)?  flexcapProd / con : 1.0 );
-			double f_change_negativ = lambda_f_change - lambda_f_change * Math.min(1, (prod > 0.0)? flexcapCon / prod: 1.0);
-			
-			
-			
-
-			
-			double f_element = f_elements_diviation_production +f_elements_diviation_consumption;
-			double f_flexibility = f_flexibility_diviation_consumption +f_flexibility_diviation_production;
-			double f_change = f_change_positive + f_change_negativ;
-			
-			f_holon += f_element + f_flexibility + f_change;
-//			System.out.print( "f_element=" + doubleToString(f_element));
-//			System.out.print( " f_flexibility=" + doubleToString(f_flexibility));
-//			System.out.println( " f_change=" + doubleToString(f_change));
-//			System.out.print( "f+elements=" + doubleToString(f_elements_diviation_production));
-//			System.out.print( " f-elements=" + doubleToString(f_elements_diviation_consumption));
-//			System.out.print( " f+flexibility" + doubleToString(f_flexibility_diviation_consumption));
-//			System.out.print( " f-flexibility" + doubleToString(f_flexibility_diviation_production));
-//			System.out.print( " f+change(" +  doubleToString(flexcapProd) + "/" + doubleToString(con) + ")=" + doubleToString(f_change_positive));
-//			System.out.print( " f-change(" +  doubleToString(flexcapCon) + "/" + doubleToString(prod) + ")="+ doubleToString(f_change_negativ));
-//			System.out.println( " sum=" + doubleToString(sum));
-		}
-		
-		
-		
-		
-//		System.out.print( "f_ebVALUE=" + f_eb);
-//		System.out.print( " f_state=" + f_state);
-//		System.out.print( " f_pro=" + f_pro);
-//		System.out.print( " f_perf=" + f_perf);
-//		System.out.println( " f_holon=" + f_holon);
-		double q1 = squash(f_eb, k_eb);
-		double q2 = squash(f_state, k_state);
-		double q3 = squash(f_pro, k_pro);
-		double q4 = squash(f_perf, k_perf);
-		double q5 = squash(f_holon, k_holon);
-//		System.out.print( "f_eb=" + q1);
-//		System.out.print( " f_state=" + q2);
-//		System.out.println( " f_pro=" + q3);
-//		System.out.println( " f_perf=" + q4);
-//		System.out.println( " f_holon=" + q5);
-//		
-		return  w_eb * q1 + w_state * q2 + w_pro * q3 + w_perf * q4 + w_holon * q5;
-		//return (float) (f_eb + f_state + f_pro + f_perf + f_holon);
-	}
-	
-	private static String doubleToString(double value) {
-		return String.format (Locale.US, "%.2f", value);
-	}
-	
-	
-	
-	
-	
-	/**
-	 * The squashing function in paper
-	 * @param x the input
-	 * @param kappa the corresponding kappa
-	 * @return
-	 */
-	static public double squash(double x, double kappa) {
-		return 100.f/(1.0f + Math.exp(-(10.f * (x - kappa/2.f))/ kappa)) - squash_subtract;
-	}
-	
-	/**
-	 * f_sup in paper
-	 * @param supply from 0 to 1
-	 * @return
-	 */
-	static public double supplyPenalty(double supply) {
-		double supplyPercentage = 100 * supply;
-		//	double test = (supplyPercentage < 100) ? -0.5 * supplyPercentage + 50: supplyPercentage - 100;
-		return (supplyPercentage < 100) ? -0.5 * supplyPercentage + 50: supplyPercentage - 100;
-	}
-	
-	/**
-	 * prio function in the paper
-	 * @param priority
-	 * @return
-	 */
-	private static double priorityToDouble(Priority priority) {
-		switch(priority) {
-		case Essential:
-			return 3.;
-		case High:
-			return 2.;
-		case Medium:
-			return 1.;
-		case Low:
-		default:		
-			return 0.;
-		}
-	}
-	
-	/**
-	 * Attention Math.log calcultae ln not log
-	 * @param kappa
-	 * @return
-	 */
-	private static double range(double kappa) {
-		return - kappa / Math.log(Math.pow(2.0, 0.05) - 1.0 );
-	}
-	/**
-	 * f_unre
-	 * @param unresponsiv
-	 * @return
-	 */
-	private static double unresponsivnessPenalty(double unresponsiv) {
-		return (2.0 * lambda_f_unre) / (1 + Math.exp(- unresponsiv/ range_for_kappa_f_unre)) - lambda_f_unre;
-	}
-	/**
-	 * f_cool
-	 * @param cooldown
-	 * @return
-	 */
-	private static double cooldownPenalty(double cooldown) {
-		return (2.0 * lambda_f_cool) / (1 + Math.exp(- cooldown/ range_for_kappa_f_cool)) - lambda_f_cool;
-	}
-
-	
-	private static double durationPenalty(double duration) {
-		double lambda_dur_times2 = 2.0 * lambda_f_dur;
-		return - lambda_dur_times2 / (1 + Math.exp(- duration/ range_for_kappa_f_dur)) + lambda_dur_times2;
-	}
-
+package algorithm.objectiveFunction;
+
+import ui.model.DecoratedNetwork;
+import ui.model.DecoratedState;
+
+import classes.Flexibility;
+import classes.HolonElement.Priority;
+
+public class ObjectiveFunctionByCarlos {
+	//Parameters
+	
+	//weight for f_g(H)
+	static double w_eb = .3, w_state = .3, w_pro = .2, w_perf = .1, w_holon=.1;
+	//killswitch weights
+	//static double w_eb = 0.5, w_state = 0.5, w_pro = 0.0f, w_perf = .0, w_holon=.0;
+	
+	//kappas for squashing function
+//	
+	static double k_eb = 1050000.f, k_state = 10000, k_pro = 2000, k_perf = 11000, k_holon= 150000;
+//  oversupplied
+//	static double k_eb = 750000.f, k_state = 20000, k_pro = 3000, k_perf = 15000, k_holon= 200000;
+	
+//	old values undersupplied 
+//	static double k_eb = 1000000.f, k_state = 15000, k_pro = 2100, k_perf = 12000, k_holon= 200000;
+	
+	//theta for f_pro
+	static double theta = 3;
+	
+	//kappas for f_perf:
+	static double kappa_f_unre = 120;
+	static double kappa_f_cool = 60*60*24;
+	static double kappa_f_dur = 60*60;
+	
+	//lambdas for f_perf:
+	static double lambda_f_unre = 10;
+	static double lambda_f_cool = 10;
+	static double lambda_f_dur = 10;
+	
+	static double lambda_f_change = 1000;
+	
+	
+	
+	//pre-calculated parameters for partial function terms:
+	/** 
+	 * Pre calculated for the squash function
+	 * <br>
+	 *  {@link ObjectiveFunctionByCarlos#squash}
+	 */
+	static double squash_subtract = 1.0f / (1.f + (float) Math.exp(5.0));
+	static double range_for_kappa_f_unre = range(kappa_f_unre);
+	static double range_for_kappa_f_cool = range(kappa_f_cool);
+	static double range_for_kappa_f_dur = range(kappa_f_dur);
+	
+	
+	public static void main(String[] args) {
+		System.out.println("Hello World");
+		System.out.println("range_for_kappa_f_unre:" + range_for_kappa_f_unre);
+		double input = 0;
+		System.out.println(input + ": " + durationPenalty(input));
+		input = 60;
+		System.out.println(input + ": " + durationPenalty(input));
+		input = 1000;
+		System.out.println(input + ": " + durationPenalty(input));
+		input = 3600;
+		System.out.println(input + ": " + durationPenalty(input));
+	}
+	static {
+        //init
+		checkParameter();
+    }
+	
+	/**
+	 * Check parameter Setting and print error when wrong values are put in.
+	 * Here should all invariants be placed to be checked on initialization.
+	 */
+	private static void checkParameter() {
+		if(!(Math.abs(w_eb + w_state + w_pro + w_perf + w_holon - 1) < 0.001)) {
+			System.err.println("ParameterError in ObjectiveFunction: w1 + w2 + w3 + w4 + w5 should be 1");
+		}
+	}
+	
+	/**
+	 * ObjectifeFunction by Carlos.
+	 * Function computes f_g:
+	 * f_g = w1 * squash(f_eb, k1) + w2 * squash(f_state, k2) + w3 * squash(f_pro, k3) + w4 * squash(f_perf, k4) + w5 * squash(f_holon, k5) 
+	 * 
+	 * 
+	 * squash is the squashing function {@link ObjectiveFunctionByCarlos#squash}
+	 * 
+	 * 
+	 * @param state
+	 * @return f_g value between 0 and 100
+	 */
+	static public double getFitnessValueForState(DecoratedState state) {
+		
+		//Calculate f_eb the penalty for unbalenced energy in the network
+		double f_eb = 0;
+		//sum over all objects
+		for(DecoratedNetwork net : state.getNetworkList()) {
+			double netEnergyDifference = 0;
+			netEnergyDifference += net.getConsumerList().stream().map(con -> con.getEnergySelfSupplied() - con.getEnergyFromConsumingElemnets()).reduce(0.f, Float::sum);
+			netEnergyDifference += net.getConsumerSelfSuppliedList().stream().map(con -> con.getEnergySelfSupplied() - con.getEnergyFromConsumingElemnets()).reduce(0.f, Float::sum);
+			netEnergyDifference += net.getSupplierList().stream().map(sup -> sup.getEnergyProducing() - sup.getEnergySelfConsuming()).reduce(0.f, Float::sum);
+			//abs
+			f_eb += Math.abs(netEnergyDifference);
+		}
+		
+		//Calculate f_state the penalty function for the supply state
+		double f_state = 0;
+		for(DecoratedNetwork net : state.getNetworkList()) {
+			f_state += net.getConsumerList().stream().map(con -> supplyPenalty(con.getSupplyBarPercentage())).reduce(0., Double::sum);
+		}
+		
+		//calculate f_pro the penalty function for priority usage 
+		// for each active flexibility punish
+		double f_pro = 0;
+		f_pro = state.getFlexManager().getAllFlexesOrderedThisTimeStep().stream().map(flex -> Math.pow(theta, priorityToDouble(flex.getElement().getPriority()) ) - 1.0).reduce(0.0, Double::sum);
+		
+		//calculate f_perf the penalty function for the quality of a flexibility used
+		
+		// and the subfuction f_unre, f_cool, f_dur
+		double f_perf = 0;
+		for(Flexibility flex : state.getFlexManager().getAllFlexesOrderedThisTimeStep()) {
+			double f_unre =  unresponsivnessPenalty(flex.getSpeed());
+			double f_cool = cooldownPenalty(flex.getCooldown());
+			double f_dur = durationPenalty(flex.getDuration());
+			f_perf += f_unre + f_cool + f_dur;
+		}
+		
+		//calculate f_holon
+		double f_holon = 0;
+		for(DecoratedNetwork net : state.getNetworkList()) {
+			double f_elements_diviation_production = net.getDeviationInProductionInNetworkForHolonObjects();
+			double f_elements_diviation_consumption = net.getDeviationInProductionInNetworkForHolonObjects();
+			double f_flexibility_diviation_consumption = net.getDiviationInFlexibilityConsumption();
+			double f_flexibility_diviation_production = net.getDiviationInFlexibilityProduction();
+			
+			
+			double con = net.getTotalConsumption();
+			double prod = net.getTotalProduction();
+			double flexcapProd = net.getFlexibilityProductionCapacity();
+			double flexcapCon = net.getFlexibilityConsumptionCapacity();
+			double f_change_positive = lambda_f_change - lambda_f_change * Math.min(1, (con > 0.0)?  flexcapProd / con : 1.0 );
+			double f_change_negativ = lambda_f_change - lambda_f_change * Math.min(1, (prod > 0.0)? flexcapCon / prod: 1.0);
+			
+			
+			
+
+			
+			double f_element = f_elements_diviation_production +f_elements_diviation_consumption;
+			double f_flexibility = f_flexibility_diviation_consumption +f_flexibility_diviation_production;
+			double f_change = f_change_positive + f_change_negativ;
+			
+			f_holon += f_element + f_flexibility + f_change;
+//			System.out.print( "f_element=" + doubleToString(f_element));
+//			System.out.print( " f_flexibility=" + doubleToString(f_flexibility));
+//			System.out.println( " f_change=" + doubleToString(f_change));
+//			System.out.print( "f+elements=" + doubleToString(f_elements_diviation_production));
+//			System.out.print( " f-elements=" + doubleToString(f_elements_diviation_consumption));
+//			System.out.print( " f+flexibility" + doubleToString(f_flexibility_diviation_consumption));
+//			System.out.print( " f-flexibility" + doubleToString(f_flexibility_diviation_production));
+//			System.out.print( " f+change(" +  doubleToString(flexcapProd) + "/" + doubleToString(con) + ")=" + doubleToString(f_change_positive));
+//			System.out.print( " f-change(" +  doubleToString(flexcapCon) + "/" + doubleToString(prod) + ")="+ doubleToString(f_change_negativ));
+//			System.out.println( " sum=" + doubleToString(sum));
+		}
+		
+		
+		
+		
+//		System.out.print( "f_ebVALUE=" + f_eb);
+//		System.out.print( " f_state=" + f_state);
+//		System.out.print( " f_pro=" + f_pro);
+//		System.out.print( " f_perf=" + f_perf);
+//		System.out.println( " f_holon=" + f_holon);
+		double q1 = squash(f_eb, k_eb);
+		double q2 = squash(f_state, k_state);
+		double q3 = squash(f_pro, k_pro);
+		double q4 = squash(f_perf, k_perf);
+		double q5 = squash(f_holon, k_holon);
+//		System.out.print( "f_eb=" + q1);
+//		System.out.print( " f_state=" + q2);
+//		System.out.println( " f_pro=" + q3);
+//		System.out.println( " f_perf=" + q4);
+//		System.out.println( " f_holon=" + q5);
+//		
+		return  w_eb * q1 + w_state * q2 + w_pro * q3 + w_perf * q4 + w_holon * q5;
+		//return (float) (f_eb + f_state + f_pro + f_perf + f_holon);
+	}
+
+	
+	
+	
+	
+	
+	/**
+	 * The squashing function in paper
+	 * @param x the input
+	 * @param kappa the corresponding kappa
+	 * @return
+	 */
+	static public double squash(double x, double kappa) {
+		return 100.f/(1.0f + Math.exp(-(10.f * (x - kappa/2.f))/ kappa)) - squash_subtract;
+	}
+	
+	/**
+	 * f_sup in paper
+	 * @param supply from 0 to 1
+	 * @return
+	 */
+	static public double supplyPenalty(double supply) {
+		double supplyPercentage = 100 * supply;
+		//	double test = (supplyPercentage < 100) ? -0.5 * supplyPercentage + 50: supplyPercentage - 100;
+		return (supplyPercentage < 100) ? -0.5 * supplyPercentage + 50: supplyPercentage - 100;
+	}
+	
+	/**
+	 * prio function in the paper
+	 * @param priority
+	 * @return
+	 */
+	private static double priorityToDouble(Priority priority) {
+		switch(priority) {
+		case Essential:
+			return 3.;
+		case High:
+			return 2.;
+		case Medium:
+			return 1.;
+		case Low:
+		default:		
+			return 0.;
+		}
+	}
+	
+	/**
+	 * Attention Math.log calcultae ln not log
+	 * @param kappa
+	 * @return
+	 */
+	private static double range(double kappa) {
+		return - kappa / Math.log(Math.pow(2.0, 0.05) - 1.0 );
+	}
+	/**
+	 * f_unre
+	 * @param unresponsiv
+	 * @return
+	 */
+	private static double unresponsivnessPenalty(double unresponsiv) {
+		return (2.0 * lambda_f_unre) / (1 + Math.exp(- unresponsiv/ range_for_kappa_f_unre)) - lambda_f_unre;
+	}
+	/**
+	 * f_cool
+	 * @param cooldown
+	 * @return
+	 */
+	private static double cooldownPenalty(double cooldown) {
+		return (2.0 * lambda_f_cool) / (1 + Math.exp(- cooldown/ range_for_kappa_f_cool)) - lambda_f_cool;
+	}
+
+	
+	private static double durationPenalty(double duration) {
+		double lambda_dur_times2 = 2.0 * lambda_f_dur;
+		return - lambda_dur_times2 / (1 + Math.exp(- duration/ range_for_kappa_f_dur)) + lambda_dur_times2;
+	}
+
 }

+ 312 - 314
src/algorithm/objectiveFunction/TopologieObjectiveFunction.java

@@ -1,315 +1,313 @@
-package algorithm.objectiveFunction;
-
-
-import ui.model.DecoratedHolonObject;
-import ui.model.DecoratedNetwork;
-import ui.model.DecoratedState;
-import ui.model.DecoratedSwitch;
-
-import java.util.HashSet;
-import java.util.Locale;
-import algorithm.objectiveFunction.GraphMetrics.Graph;
-import api.TopologieAlgorithmFramework.IndexCable;
-import classes.FloatLog;
-
-public class TopologieObjectiveFunction {
-	//Parameters
-	
-	//weight for f_g(H)
-	static double w_eb = 0.2, w_max = 0.5, w_holon= 0.1, w_selection = .1, w_grid = 0.1;
-	
-	
-	//--> f_eb parameter
-	/**
-	 * Maximum Energie Difference(kappa)
-	 */
-	static double k_eb = 5000.f;
-	/**
-	 * Maximum when all on Energie Difference(kappa)
-	 */
-	static double k_max = 10.f;
-	static double lambda_max = 10.;
-	
-	//--> f_holon parameter
-	/**
-	 * maximum penalty from holon element distribution
-	 */
-	static double k_holon= 4000;
-	
-	
-	//--> f_selection paramaeter;
-	/**
-	 *  average Maximum Cost for selction(kappa) of switch and elements.
-	 */
-	static double k_selection = 200000;
-	static double cost_switch = 3000;
-	private static double cost_of_cable_per_meter = 6;
-
-	//--> f_grid parameter
-	
-	
-	
-	/**
-	 * The avergae shortest path maximum length -> kappa for the squash function
-	 */
-	static double k_avg_shortest_path = 1600;
-	//Disjpijoint path cant have zero as output it starts with the value 1
-	static double centerValue_disjoint_path = 1.0; 
-	static double k_disjoint_path = 2.4;
-	static double lambda_avg_shortest_path = 10;
-	static double lambda_disjoint_path = 10;
-	static double k_grid = lambda_avg_shortest_path;// + lambda_disjoint_path;
-	
-	
-	
-	//pre-calculated parameters for partial function terms:
-	/** 
-	 * Pre calculated for the squash function
-	 * <br>
-	 *  {@link TopologieObjectiveFunction#squash}
-	 */
-	static double squash_subtract = 1.0f / (1.f + (float) Math.exp(5.0));
-	static double range_for_k_avg_shortest_path = range(k_avg_shortest_path);
-	static double range_for_k_disjoint_path = range(k_disjoint_path - centerValue_disjoint_path);
-
-	public static FloatLog log = new FloatLog();
-	static boolean useLog = false;
-	static {
-        //init
-		checkParameter();
-    }
-	
-	/**
-	 * Check parameter Setting and print error when wrong values are put in.
-	 * Here should all invariants be placed to be checked on initialization.
-	 */
-	private static void checkParameter() {
-		if(!(Math.abs(w_eb + w_holon + w_selection + w_grid + w_max - 1) < 0.001)) {
-			System.err.println("ParameterError in ObjectiveFunction: Sum of all weights should be 1");
-		}
-	}
-	
-	/**
-	 * ObjectifeFunction by Carlos.
-	 * Function computes f_g:
-	 * f_g = w1 * squash(f_eb, k1) + w2 * squash(f_state, k2) + w3 * squash(f_pro, k3) + w4 * squash(f_perf, k4) + w5 * squash(f_holon, k5) 
-	 * 
-	 * 
-	 * squash is the squashing function {@link TopologieObjectiveFunction#squash}
-	 * 
-	 * 
-	 * @param state
-	 * @param moreInformation TODO
-	 * @return f_g value between 0 and 100
-	 */
-	static public float getFitnessValueForState(DecoratedState state, int amountOfAddedSwitch, double addedCableMeters, boolean moreInformation) {
-		
-		
-
-		//Calculate f_eb the penalty for unbalenced energy in the network
-		double f_eb = 0;
-		for(DecoratedNetwork net : state.getNetworkList()) {
-			//abs
-			f_eb += Math.abs(net.getTotalConsumption() - net.getTotalProduction());
-		}
-		//Average?
-		f_eb /= state.getNetworkList().size();
-		
-		
-		
-		
-		double f_maximum = 0;
-		for(DecoratedNetwork net : state.getNetworkList()) {
-			double prod = net.getTotalProduction();
-			double con = net.getTotalConsumption();
-			if(prod == 0 || con == 0) {
-				f_maximum += lambda_max;
-			}else {
-				f_maximum += lambda_max * (Math.abs(prod - con)/Math.max(prod, con));				
-			}
-		}
-		//Average?
-		f_maximum /= state.getNetworkList().size();
-		
-		//calculate f_holon
-		double f_holon = 0;
-		for(DecoratedNetwork net : state.getNetworkList()) {
-			double f_elements_deviation_production = net.getDeviationInProductionInNetworkForHolonObjects();
-			double f_elements_deviation_consumption = net.getDeviationInConsumptionInNetworkForHolonObjects();
-			double f_element = f_elements_deviation_production+f_elements_deviation_consumption;
-			f_holon += f_element;
-		}
-		f_holon /= state.getNetworkList().size();
-		
-		//calculating f_selection
-		double f_selection = calculateTopologieCost(state, amountOfAddedSwitch, addedCableMeters);
-		//if(moreInformation)System.out.println("CostForWildcards:" + cost + ", CostSwitches(#" + amountOfAddedSwitch +"):" + cost_switch * amountOfAddedSwitch + ", CostCables(" +addedCableMeters+ "m):" + cost_of_cable_per_meter * addedCableMeters);
-		
-		
-		//calculating f_grid
-		double f_grid = 0;
-		//each network is a holon
-		for(DecoratedNetwork net: state.getNetworkList()) {
-			Graph G = GraphMetrics.convertDecoratedNetworkToGraph(net);
-			//We have to penalize single Networks;
-			if(G.V.length <= 1 || G.S.length <= 1) {
-				f_grid += lambda_avg_shortest_path;// + lambda_disjoint_path;
-				continue;
-			}
-		
-			double avgShortestPath = GraphMetrics.averageShortestDistance(G);
-			//double disjpointPaths = GraphMetrics.averageEdgeDisjointPathProblem(G);
-			if(useLog) {
-				log.addSample("avgShortestPath", (float)avgShortestPath);
-			}
-			f_grid += avgShortestPathPenalty(avgShortestPath);// + disjoinPathPenalty(disjpointPaths);
-		}
-		//take average to encourage splitting
-		f_grid /= state.getNetworkList().size();
-		
-		
-		
-		
-		if(moreInformation) {
-			printWeightedValues(f_eb, f_maximum, f_holon, f_selection, f_grid);
-			if(useLog) {
-				System.out.println("Log");
-				System.out.println(log);
-			}
-		}
-		//printUnsquashedValues(f_eb, f_maximum, f_holon, f_selection, f_grid);
-		if(useLog) {
-			log.addSample("Unsquashed f_eb", (float)f_eb);
-			log.addSample("Unsquashed f_maximum", (float)f_maximum);
-			log.addSample("Unsquashed f_holon", (float)f_holon);
-			log.addSample("Unsquashed f_selection", (float)f_selection);
-			log.addSample("Unsquashed f_grid", (float)f_grid);
-		}
-		return (float) (w_eb * squash(f_eb, k_eb) 
-				+ w_max * squash(f_maximum, k_max) 
-				+ w_holon * squash(f_holon, k_holon) 
-				+ w_selection * squash(f_selection, k_selection) 
-				+ w_grid * squash(f_grid, k_grid));
-	}
-
-	public static double calculateTopologieCost(DecoratedState state, int amountOfAddedSwitch,
-			double addedCableMeters) {
-		double cost = calculateWildcardCost(state);
-		cost += calculateAddedSwitchCost(amountOfAddedSwitch);
-		cost += calculateAddedCableCost(addedCableMeters);		
-		return cost;
-	}
-
-	public static double calculateAddedCableCost(double addedCableMeters) {
-		return cost_of_cable_per_meter * addedCableMeters;
-	}
-
-	public static double calculateAddedSwitchCost(int amountOfAddedSwitch) {
-		return cost_switch * amountOfAddedSwitch;
-	}
-
-	public static double calculateWildcardCost(DecoratedState state) {
-		double cost = 0;
-		for(DecoratedNetwork net : state.getNetworkList()) {
-			for(DecoratedHolonObject dHobject : net.getConsumerList()) {
-				if(dHobject.getModel().getName().contains("Wildcard")){
-					if(dHobject.getModel().getName().length() > 9) {
-						String costString = dHobject.getModel().getName().substring(9);
-						cost += Double.parseDouble(costString);
-					}
-				}
-			}
-			for(DecoratedHolonObject dHobject : net.getConsumerSelfSuppliedList()) {
-				if(dHobject.getModel().getName().contains("Wildcard")){
-					if(dHobject.getModel().getName().length() > 9) {
-						String costString = dHobject.getModel().getName().substring(9);
-						cost += Double.parseDouble(costString);
-					}
-				}
-			}
-			for(DecoratedHolonObject dHobject : net.getSupplierList()) {
-				if(dHobject.getModel().getName().contains("Wildcard")){
-					if(dHobject.getModel().getName().length() > 9) {
-						String costString = dHobject.getModel().getName().substring(9);
-						cost += Double.parseDouble(costString);
-					}
-				}
-			}
-		}
-		return cost;
-	}
-
-	private static String doubleToString(double value) {
-		return String.format (Locale.US, "%.2f", value);
-	}
-	
-
-	private static double disjoinPathPenalty(double value) {
-		return -(2.0 * lambda_disjoint_path) / (1 + Math.exp(- (value - centerValue_disjoint_path)/ range_for_k_disjoint_path)) + (2.0 * lambda_disjoint_path);
-	}
-	private static double avgShortestPathPenalty(double value) {
-		return (2.0 * lambda_avg_shortest_path) / (1 + Math.exp(- value/ range_for_k_avg_shortest_path)) - lambda_avg_shortest_path;
-	}
-	/**
-	 * Attention Math.log calcultae ln not log
-	 * @param kappa
-	 * @return
-	 */
-	private static double range(double kappa) {
-		return - kappa / Math.log(Math.pow(2.0, 0.05) - 1.0 );
-	}
-	
-	/**
-	 * The squashing function in paper
-	 * @param x the input
-	 * @param kappa the corresponding kappa
-	 * @return
-	 */
-	static public double squash(double x, double kappa) {
-		return 100.f/(1.0f + Math.exp(-(10.f * (x - kappa/2.f))/ kappa)) - squash_subtract;
-	}
-	
-	/**
-	 * f_sup in paper
-	 * @param supply from 0 to 1
-	 * @return
-	 */
-	static public double supplyPenalty(double supply) {
-		double supplyPercentage = 100 * supply;
-		return (supplyPercentage < 100) ? -0.5 * supplyPercentage + 50: supplyPercentage - 100;
-	}
-	
-	static void printWeightedValues(double f_eb, double f_maximum, double f_holon, double f_selection, double f_grid){
-		 System.out.println("===================================================================");
-		 System.out.println(" f_eb: " + f_eb + ", k_eb: " + k_eb + ", w_eb: " + w_eb); 
-		 System.out.println(" squash(f_eb, k_eb): " + doubleToString(squash(f_eb, k_eb))); 
-		 System.out.println(" w_eb * squash(f_eb, k_eb): " + doubleToString(w_eb * squash(f_eb, k_eb))); 
-		 System.out.println("===================================================================");
-		 System.out.println(" f_maximum: " + f_maximum + ", k_max: " + k_max + ", w_max: " + w_max); 
-		 System.out.println(" squash(f_maximum, k_max): " + doubleToString(squash(f_maximum, k_max))); 
-		 System.out.println(" w_max * squash(f_maximum, k_max): " + doubleToString(w_max * squash(f_maximum, k_max))); 
-		 System.out.println("===================================================================");
-		 System.out.println(" f_selection: " + f_selection + ", k_selection: " + k_selection + ", w_selection: " + w_selection); 
-		 System.out.println(" squash(f_selection, k_selection): " + doubleToString(squash(f_selection, k_selection))); 
-		 System.out.println(" w_selection * squash(f_selection, k_selection): " + doubleToString(w_selection * squash(f_selection, k_selection))); 
-		 System.out.println("===================================================================");
-		 System.out.println(" f_holon: " + f_holon + ", k_holon: " + k_holon + ", w_holon: " + w_holon); 
-		 System.out.println(" squash(f_holon, k_holon): " + doubleToString(squash(f_holon, k_holon))); 
-		 System.out.println(" w_holon * squash(f_holon, k_holon): " + doubleToString(w_holon * squash(f_holon, k_holon))); 
-		 System.out.println("===================================================================");
-		 System.out.println(" f_grid: " + f_grid + ", k_grid: " + k_grid + ", w_grid: " + w_grid); 
-		 System.out.println(" squash(f_grid, k_grid): " + doubleToString(squash(f_grid, k_grid))); 
-		 System.out.println(" w_grid * squash(f_grid, k_grid): " + doubleToString(w_grid * squash(f_grid, k_grid))); 
-		 System.out.println("===================================================================");
-		 System.out.println();
-		 System.out.println();
-	}
-	static void printUnsquashedValues(double f_eb, double f_maximum, double f_holon, double f_selection, double f_grid){
-		 System.out.print(" f_eb(" + f_eb + ") ");
-		 System.out.print(" f_maximum(" + f_maximum + ") ");
-		 System.out.print(" f_holon(" + f_holon + ") ");
-		 System.out.print(" f_selection(" + f_selection + ") ");
-		 System.out.println(" f_grid(" + f_grid + ") ");
-	}
-
+package algorithm.objectiveFunction;
+
+
+import ui.model.DecoratedHolonObject;
+import ui.model.DecoratedNetwork;
+import ui.model.DecoratedState;
+import utility.FloatLog;
+
+import java.util.Locale;
+import algorithm.objectiveFunction.GraphMetrics.Graph;
+
+public class TopologieObjectiveFunction {
+	//Parameters
+	
+	//weight for f_g(H)
+	static double w_eb = 0.2, w_max = 0.5, w_holon= 0.1, w_selection = .1, w_grid = 0.1;
+	
+	
+	//--> f_eb parameter
+	/**
+	 * Maximum Energie Difference(kappa)
+	 */
+	static double k_eb = 5000.f;
+	/**
+	 * Maximum when all on Energie Difference(kappa)
+	 */
+	static double k_max = 10.f;
+	static double lambda_max = 10.;
+	
+	//--> f_holon parameter
+	/**
+	 * maximum penalty from holon element distribution
+	 */
+	static double k_holon= 4000;
+	
+	
+	//--> f_selection paramaeter;
+	/**
+	 *  average Maximum Cost for selction(kappa) of switch and elements.
+	 */
+	static double k_selection = 200000;
+	static double cost_switch = 3000;
+	private static double cost_of_cable_per_meter = 6;
+
+	//--> f_grid parameter
+	
+	
+	
+	/**
+	 * The avergae shortest path maximum length -> kappa for the squash function
+	 */
+	static double k_avg_shortest_path = 1600;
+	//Disjpijoint path cant have zero as output it starts with the value 1
+	static double centerValue_disjoint_path = 1.0; 
+	static double k_disjoint_path = 2.4;
+	static double lambda_avg_shortest_path = 10;
+	static double lambda_disjoint_path = 10;
+	static double k_grid = lambda_avg_shortest_path;// + lambda_disjoint_path;
+	
+	
+	
+	//pre-calculated parameters for partial function terms:
+	/** 
+	 * Pre calculated for the squash function
+	 * <br>
+	 *  {@link TopologieObjectiveFunction#squash}
+	 */
+	static double squash_subtract = 1.0f / (1.f + (float) Math.exp(5.0));
+	static double range_for_k_avg_shortest_path = range(k_avg_shortest_path);
+	static double range_for_k_disjoint_path = range(k_disjoint_path - centerValue_disjoint_path);
+
+	public static FloatLog log = new FloatLog();
+	static boolean useLog = false;
+	static {
+        //init
+		checkParameter();
+    }
+	
+	/**
+	 * Check parameter Setting and print error when wrong values are put in.
+	 * Here should all invariants be placed to be checked on initialization.
+	 */
+	private static void checkParameter() {
+		if(!(Math.abs(w_eb + w_holon + w_selection + w_grid + w_max - 1) < 0.001)) {
+			System.err.println("ParameterError in ObjectiveFunction: Sum of all weights should be 1");
+		}
+	}
+	
+	/**
+	 * ObjectifeFunction by Carlos.
+	 * Function computes f_g:
+	 * f_g = w1 * squash(f_eb, k1) + w2 * squash(f_state, k2) + w3 * squash(f_pro, k3) + w4 * squash(f_perf, k4) + w5 * squash(f_holon, k5) 
+	 * 
+	 * 
+	 * squash is the squashing function {@link TopologieObjectiveFunction#squash}
+	 * 
+	 * 
+	 * @param state
+	 * @param moreInformation TODO
+	 * @return f_g value between 0 and 100
+	 */
+	static public float getFitnessValueForState(DecoratedState state, int amountOfAddedSwitch, double addedCableMeters, boolean moreInformation) {
+		
+		
+
+		//Calculate f_eb the penalty for unbalenced energy in the network
+		double f_eb = 0;
+		for(DecoratedNetwork net : state.getNetworkList()) {
+			//abs
+			f_eb += Math.abs(net.getTotalConsumption() - net.getTotalProduction());
+		}
+		//Average?
+		f_eb /= state.getNetworkList().size();
+		
+		
+		
+		
+		double f_maximum = 0;
+		for(DecoratedNetwork net : state.getNetworkList()) {
+			double prod = net.getTotalProduction();
+			double con = net.getTotalConsumption();
+			if(prod == 0 || con == 0) {
+				f_maximum += lambda_max;
+			}else {
+				f_maximum += lambda_max * (Math.abs(prod - con)/Math.max(prod, con));				
+			}
+		}
+		//Average?
+		f_maximum /= state.getNetworkList().size();
+		
+		//calculate f_holon
+		double f_holon = 0;
+		for(DecoratedNetwork net : state.getNetworkList()) {
+			double f_elements_deviation_production = net.getDeviationInProductionInNetworkForHolonObjects();
+			double f_elements_deviation_consumption = net.getDeviationInConsumptionInNetworkForHolonObjects();
+			double f_element = f_elements_deviation_production+f_elements_deviation_consumption;
+			f_holon += f_element;
+		}
+		f_holon /= state.getNetworkList().size();
+		
+		//calculating f_selection
+		double f_selection = calculateTopologieCost(state, amountOfAddedSwitch, addedCableMeters);
+		//if(moreInformation)System.out.println("CostForWildcards:" + cost + ", CostSwitches(#" + amountOfAddedSwitch +"):" + cost_switch * amountOfAddedSwitch + ", CostCables(" +addedCableMeters+ "m):" + cost_of_cable_per_meter * addedCableMeters);
+		
+		
+		//calculating f_grid
+		double f_grid = 0;
+		//each network is a holon
+		for(DecoratedNetwork net: state.getNetworkList()) {
+			Graph G = GraphMetrics.convertDecoratedNetworkToGraph(net);
+			//We have to penalize single Networks;
+			if(G.V.length <= 1 || G.S.length <= 1) {
+				f_grid += lambda_avg_shortest_path;// + lambda_disjoint_path;
+				continue;
+			}
+		
+			double avgShortestPath = GraphMetrics.averageShortestDistance(G);
+			//double disjpointPaths = GraphMetrics.averageEdgeDisjointPathProblem(G);
+			if(useLog) {
+				log.addSample("avgShortestPath", (float)avgShortestPath);
+			}
+			f_grid += avgShortestPathPenalty(avgShortestPath);// + disjoinPathPenalty(disjpointPaths);
+		}
+		//take average to encourage splitting
+		f_grid /= state.getNetworkList().size();
+		
+		
+		
+		
+		if(moreInformation) {
+			printWeightedValues(f_eb, f_maximum, f_holon, f_selection, f_grid);
+			if(useLog) {
+				System.out.println("Log");
+				System.out.println(log);
+			}
+		}
+		//printUnsquashedValues(f_eb, f_maximum, f_holon, f_selection, f_grid);
+		if(useLog) {
+			log.addSample("Unsquashed f_eb", (float)f_eb);
+			log.addSample("Unsquashed f_maximum", (float)f_maximum);
+			log.addSample("Unsquashed f_holon", (float)f_holon);
+			log.addSample("Unsquashed f_selection", (float)f_selection);
+			log.addSample("Unsquashed f_grid", (float)f_grid);
+		}
+		return (float) (w_eb * squash(f_eb, k_eb) 
+				+ w_max * squash(f_maximum, k_max) 
+				+ w_holon * squash(f_holon, k_holon) 
+				+ w_selection * squash(f_selection, k_selection) 
+				+ w_grid * squash(f_grid, k_grid));
+	}
+
+	public static double calculateTopologieCost(DecoratedState state, int amountOfAddedSwitch,
+			double addedCableMeters) {
+		double cost = calculateWildcardCost(state);
+		cost += calculateAddedSwitchCost(amountOfAddedSwitch);
+		cost += calculateAddedCableCost(addedCableMeters);		
+		return cost;
+	}
+
+	public static double calculateAddedCableCost(double addedCableMeters) {
+		return cost_of_cable_per_meter * addedCableMeters;
+	}
+
+	public static double calculateAddedSwitchCost(int amountOfAddedSwitch) {
+		return cost_switch * amountOfAddedSwitch;
+	}
+
+	public static double calculateWildcardCost(DecoratedState state) {
+		double cost = 0;
+		for(DecoratedNetwork net : state.getNetworkList()) {
+			for(DecoratedHolonObject dHobject : net.getConsumerList()) {
+				if(dHobject.getModel().getName().contains("Wildcard")){
+					if(dHobject.getModel().getName().length() > 9) {
+						String costString = dHobject.getModel().getName().substring(9);
+						cost += Double.parseDouble(costString);
+					}
+				}
+			}
+			for(DecoratedHolonObject dHobject : net.getConsumerSelfSuppliedList()) {
+				if(dHobject.getModel().getName().contains("Wildcard")){
+					if(dHobject.getModel().getName().length() > 9) {
+						String costString = dHobject.getModel().getName().substring(9);
+						cost += Double.parseDouble(costString);
+					}
+				}
+			}
+			for(DecoratedHolonObject dHobject : net.getSupplierList()) {
+				if(dHobject.getModel().getName().contains("Wildcard")){
+					if(dHobject.getModel().getName().length() > 9) {
+						String costString = dHobject.getModel().getName().substring(9);
+						cost += Double.parseDouble(costString);
+					}
+				}
+			}
+		}
+		return cost;
+	}
+
+	private static String doubleToString(double value) {
+		return String.format (Locale.US, "%.2f", value);
+	}
+	
+
+	@SuppressWarnings("unused")
+	private static double disjoinPathPenalty(double value) {
+		return -(2.0 * lambda_disjoint_path) / (1 + Math.exp(- (value - centerValue_disjoint_path)/ range_for_k_disjoint_path)) + (2.0 * lambda_disjoint_path);
+	}
+	private static double avgShortestPathPenalty(double value) {
+		return (2.0 * lambda_avg_shortest_path) / (1 + Math.exp(- value/ range_for_k_avg_shortest_path)) - lambda_avg_shortest_path;
+	}
+	/**
+	 * Attention Math.log calcultae ln not log
+	 * @param kappa
+	 * @return
+	 */
+	private static double range(double kappa) {
+		return - kappa / Math.log(Math.pow(2.0, 0.05) - 1.0 );
+	}
+	
+	/**
+	 * The squashing function in paper
+	 * @param x the input
+	 * @param kappa the corresponding kappa
+	 * @return
+	 */
+	static public double squash(double x, double kappa) {
+		return 100.f/(1.0f + Math.exp(-(10.f * (x - kappa/2.f))/ kappa)) - squash_subtract;
+	}
+	
+	/**
+	 * f_sup in paper
+	 * @param supply from 0 to 1
+	 * @return
+	 */
+	static public double supplyPenalty(double supply) {
+		double supplyPercentage = 100 * supply;
+		return (supplyPercentage < 100) ? -0.5 * supplyPercentage + 50: supplyPercentage - 100;
+	}
+	
+	static void printWeightedValues(double f_eb, double f_maximum, double f_holon, double f_selection, double f_grid){
+		 System.out.println("===================================================================");
+		 System.out.println(" f_eb: " + f_eb + ", k_eb: " + k_eb + ", w_eb: " + w_eb); 
+		 System.out.println(" squash(f_eb, k_eb): " + doubleToString(squash(f_eb, k_eb))); 
+		 System.out.println(" w_eb * squash(f_eb, k_eb): " + doubleToString(w_eb * squash(f_eb, k_eb))); 
+		 System.out.println("===================================================================");
+		 System.out.println(" f_maximum: " + f_maximum + ", k_max: " + k_max + ", w_max: " + w_max); 
+		 System.out.println(" squash(f_maximum, k_max): " + doubleToString(squash(f_maximum, k_max))); 
+		 System.out.println(" w_max * squash(f_maximum, k_max): " + doubleToString(w_max * squash(f_maximum, k_max))); 
+		 System.out.println("===================================================================");
+		 System.out.println(" f_selection: " + f_selection + ", k_selection: " + k_selection + ", w_selection: " + w_selection); 
+		 System.out.println(" squash(f_selection, k_selection): " + doubleToString(squash(f_selection, k_selection))); 
+		 System.out.println(" w_selection * squash(f_selection, k_selection): " + doubleToString(w_selection * squash(f_selection, k_selection))); 
+		 System.out.println("===================================================================");
+		 System.out.println(" f_holon: " + f_holon + ", k_holon: " + k_holon + ", w_holon: " + w_holon); 
+		 System.out.println(" squash(f_holon, k_holon): " + doubleToString(squash(f_holon, k_holon))); 
+		 System.out.println(" w_holon * squash(f_holon, k_holon): " + doubleToString(w_holon * squash(f_holon, k_holon))); 
+		 System.out.println("===================================================================");
+		 System.out.println(" f_grid: " + f_grid + ", k_grid: " + k_grid + ", w_grid: " + w_grid); 
+		 System.out.println(" squash(f_grid, k_grid): " + doubleToString(squash(f_grid, k_grid))); 
+		 System.out.println(" w_grid * squash(f_grid, k_grid): " + doubleToString(w_grid * squash(f_grid, k_grid))); 
+		 System.out.println("===================================================================");
+		 System.out.println();
+		 System.out.println();
+	}
+	static void printUnsquashedValues(double f_eb, double f_maximum, double f_holon, double f_selection, double f_grid){
+		 System.out.print(" f_eb(" + f_eb + ") ");
+		 System.out.print(" f_maximum(" + f_maximum + ") ");
+		 System.out.print(" f_holon(" + f_holon + ") ");
+		 System.out.print(" f_selection(" + f_selection + ") ");
+		 System.out.println(" f_grid(" + f_grid + ") ");
+	}
+
 }

+ 184 - 190
src/algorithm/topologie/AcoAlgorithm.java

@@ -1,191 +1,185 @@
-package algorithm.topologie;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.ListIterator;
-import java.util.TreeSet;
-import java.util.stream.Collectors;
-
-import algorithm.objectiveFunction.ObjectiveFunctionByCarlos;
-import algorithm.objectiveFunction.TopologieObjectiveFunction;
-import api.TopologieAlgorithmFramework;
-import api.AlgorithmFrameworkFlex.Individual;
-import api.TopologieAlgorithmFramework.IndexCable;
-import ui.model.DecoratedState;
-import utility.Random;
-
-public class AcoAlgorithm extends TopologieAlgorithmFramework {
-
-	private int popsize = 20;
-	private int maxGenerations = 100;
-	private boolean moreInformation = false;
-	/**
-	 * The vaporization factor;
-	 */
-	private double p = 0.05;
-	private double convergenceFactorReset = 0.90;
-	
-	public AcoAlgorithm(){
-		addIntParameter("popsize", popsize, intValue -> popsize = intValue, () -> popsize, 1);
-		addIntParameter("maxGenerations", maxGenerations, intValue -> maxGenerations = intValue, () -> maxGenerations, 1);
-		addSeperator();
-		addDoubleParameter("Vaporization", p, doubleValue -> p = doubleValue, () -> p, true, 0.0, 1.0);
-		addDoubleParameter("FactorReset", convergenceFactorReset, doubleValue -> convergenceFactorReset = doubleValue, () -> convergenceFactorReset, true, 0.0, 1.0);
-		addSeperator();
-		addBooleanParameter("moreInformation", moreInformation, booleanValue -> moreInformation = booleanValue, new LinkedList<String>(), new LinkedList<String>());
-
-	}
-	@Override
-	protected double evaluateState(DecoratedState actualstate, int amountOfAddedSwitch, double addedCableMeters, boolean moreInformation) {
-		return TopologieObjectiveFunction.getFitnessValueForState(actualstate, amountOfAddedSwitch, addedCableMeters, moreInformation);
-	}
-
-	@Override
-	protected Individual executeAlgo() {
-		resetWildcards();
-		Individual best = new Individual();
-		best.position = extractPositionAndAccess();
-		int problemSize =  best.position.size();
-		best.fitness = evaluatePosition(best.position);
-		List<Double> runList = new ArrayList<Double>();
-		runList.add(best.fitness);
-		console.println("Integer_Array_length: " + best.position.size());
-		List<List<Double>> pheromones = initPheromones(problemSize);
-		List<Individual> population = new ArrayList<Individual>();
-		if(moreInformation)console.println("Size To Test:" + population.size());
-		for(int generation = 0; generation< maxGenerations; generation++) {
-			population.clear();
-			population = constructSolutionsBiasedBy(pheromones);
-			if(moreInformation)console.println("Generation" + generation + " start with Fitness: " + best.fitness);
-			for(Individual i : population) {
-				i.fitness = evaluatePosition(i.position);
-				if(moreInformation)console.println("Fitness" + i.fitness);
-				if(i.fitness < best.fitness) best = i;	
-			}
-			runList.add(best.fitness);
-			if(moreInformation)console.println("________________");
-			vaporizeIntensifiePheromons(pheromones, best.position, problemSize);
-			double cf = calculateConvergenceFactor(pheromones, problemSize);
-			if(moreInformation)console.println("ConvergenceFactor = " + cf);
-			if(moreInformation)console.println("pheromones:" + pheromones);
-			if(cf > this.convergenceFactorReset) {
-				pheromones = initPheromones(problemSize);
-			}
-			if(cancel)return null;
-		}
-		console.println("   End with:" + best.fitness);
-		this.runList = runList;
-		return best;
-	}
-
-	@Override
-	protected int getProgressBarMaxCount() {
-		return rounds * maxGenerations * popsize + 1;
-	}
-
-	@Override
-	protected String algoInformationToPrint() {
-		return "Aco for Topologie "+ " Rounds:" + rounds 
-				+ " maxGenerations:" + maxGenerations 
-				+ " popsize:" +  popsize
-				+ " vaporization:" +  p
-				+ " convergenceFactorReset:" +  convergenceFactorReset;
-	}
-
-	@Override
-	protected String plottFileName() {
-		return "aco-topologie.txt";
-	}
-	/**
-	 * tj1 is the pheromon level in the j position
-	 * cf is the convergence factor cf e [0;1]
-	 * 
-	 * 
-	 * 
-	 * @param pheromones
-	 * @return cf
-	 */
-	private double calculateConvergenceFactor(List<List<Double>> pheromones,int problemSize) {
-		double sumofmax = pheromones.stream().map(listPheromons -> listPheromons.stream().max((a,b) -> Double.compare(a,b)).get()).reduce(0.0, Double::sum);
-		double cf = sumofmax / (double)problemSize;
-		return cf;
-	}
-	/**
-	 * pheromone <- (1-p) * pheromone;
-	 * if(best is true at this position) pheromone <- pheromone + p;
-	 * @param pheromones
-	 * @param position
-	 */
-	private void vaporizeIntensifiePheromons(List<List<Double>> pheromones, List<Integer> position, int problemSize) {
-		ListIterator<List<Double>> iterPheromone = pheromones.listIterator();
-		ListIterator<Integer> iterBest = position.listIterator();
-		for(int i = 0; i < problemSize; i++) {
-			List<Double> tauList = iterPheromone.next();
-			int bestDecision = iterBest.next();
-			ListIterator<Double> tauListiter = tauList.listIterator();
-			for(int k = 0; tauListiter.hasNext(); k++) {
-				double value = tauListiter.next();
-				tauListiter.set((1.0 - p) * value + (k == bestDecision?p:0.0));
-			}
-		}
-	}
-	/**
-	 * 
-	 * @param pheromones
-	 * @return
-	 */
-	private List<Individual> constructSolutionsBiasedBy(List<List<Double>> pheromones) {
-		List<Individual> population =  new ArrayList<Individual>();
-		for(int i = 0; i < popsize; i++) {
-			population.add(constructASolutionBiasedBy(pheromones));
-		}
-		return population;
-	}
-	
-	
-	/**
-	 * Walks the path with a ant and decide by pheromones if should take true or false;
-	 * A pheromone have a level of 0 < pheromone < 1.
-	 * A Pheromone is  equal to the probability.
-	 * @param pheromones
-	 * @return
-	 */
-	private Individual constructASolutionBiasedBy(List<List<Double>> pheromones) {
-		Individual result = new Individual();
-		result.position = new ArrayList<Integer>();
-		for(List<Double> pheromoneList : pheromones) {
-			ListIterator<Double> tauListiter = pheromoneList.listIterator();
-			double radnomValue = Random.nextDouble();
-			for(int i = 0;tauListiter.hasNext(); i++) {
-				double actualtau = tauListiter.next();
-				if(radnomValue > actualtau) {
-					radnomValue -= actualtau;
-				}else {
-					result.position.add(i);
-					break;
-				}
-			}
-		}
-		return result;
-	}
-	/**
-	 * Initialize Pheromons with 1.0 / maxIndex;
-	 */
-	private List<List<Double>> initPheromones(int problemSize) {
-		List<List<Double>> result = new ArrayList<List<Double>>();
-		for(int i = 0; i < problemSize;i++) {
-			//generate list equal tau values with max Int
-			int maxIndex = this.getMaximumIndexObjects(i);
-			double tauValue = 1.0 / (double) (maxIndex + 1);
-			List<Double> tauList = new ArrayList<Double>();
-			for(int tau= 0; tau < maxIndex + 1; tau++) {
-				tauList.add(tauValue);				
-			}
-			result.add(tauList);
-		}
-		return result;
-	}
-}
+package algorithm.topologie;
+
+import java.util.ArrayList;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.ListIterator;
+
+import algorithm.objectiveFunction.TopologieObjectiveFunction;
+import api.TopologieAlgorithmFramework;
+import ui.model.DecoratedState;
+import utility.Random;
+
+public class AcoAlgorithm extends TopologieAlgorithmFramework {
+
+	private int popsize = 20;
+	private int maxGenerations = 100;
+	private boolean moreInformation = false;
+	/**
+	 * The vaporization factor;
+	 */
+	private double p = 0.05;
+	private double convergenceFactorReset = 0.90;
+	
+	public AcoAlgorithm(){
+		addIntParameter("popsize", popsize, intValue -> popsize = intValue, () -> popsize, 1);
+		addIntParameter("maxGenerations", maxGenerations, intValue -> maxGenerations = intValue, () -> maxGenerations, 1);
+		addSeperator();
+		addDoubleParameter("Vaporization", p, doubleValue -> p = doubleValue, () -> p, true, 0.0, 1.0);
+		addDoubleParameter("FactorReset", convergenceFactorReset, doubleValue -> convergenceFactorReset = doubleValue, () -> convergenceFactorReset, true, 0.0, 1.0);
+		addSeperator();
+		addBooleanParameter("moreInformation", moreInformation, booleanValue -> moreInformation = booleanValue, new LinkedList<String>(), new LinkedList<String>());
+
+	}
+	@Override
+	protected double evaluateState(DecoratedState actualstate, int amountOfAddedSwitch, double addedCableMeters, boolean moreInformation) {
+		return TopologieObjectiveFunction.getFitnessValueForState(actualstate, amountOfAddedSwitch, addedCableMeters, moreInformation);
+	}
+
+	@Override
+	protected Individual executeAlgo() {
+		resetWildcards();
+		Individual best = new Individual();
+		best.position = extractPositionAndAccess();
+		int problemSize =  best.position.size();
+		best.fitness = evaluatePosition(best.position);
+		List<Double> runList = new ArrayList<Double>();
+		runList.add(best.fitness);
+		console.println("Integer_Array_length: " + best.position.size());
+		List<List<Double>> pheromones = initPheromones(problemSize);
+		List<Individual> population = new ArrayList<Individual>();
+		if(moreInformation)console.println("Size To Test:" + population.size());
+		for(int generation = 0; generation< maxGenerations; generation++) {
+			population.clear();
+			population = constructSolutionsBiasedBy(pheromones);
+			if(moreInformation)console.println("Generation" + generation + " start with Fitness: " + best.fitness);
+			for(Individual i : population) {
+				i.fitness = evaluatePosition(i.position);
+				if(moreInformation)console.println("Fitness" + i.fitness);
+				if(i.fitness < best.fitness) best = i;	
+			}
+			runList.add(best.fitness);
+			if(moreInformation)console.println("________________");
+			vaporizeIntensifiePheromons(pheromones, best.position, problemSize);
+			double cf = calculateConvergenceFactor(pheromones, problemSize);
+			if(moreInformation)console.println("ConvergenceFactor = " + cf);
+			if(moreInformation)console.println("pheromones:" + pheromones);
+			if(cf > this.convergenceFactorReset) {
+				pheromones = initPheromones(problemSize);
+			}
+			if(cancel)return null;
+		}
+		console.println("   End with:" + best.fitness);
+		this.runList = runList;
+		return best;
+	}
+
+	@Override
+	protected int getProgressBarMaxCount() {
+		return rounds * maxGenerations * popsize + 1;
+	}
+
+	@Override
+	protected String algoInformationToPrint() {
+		return "Aco for Topologie "+ " Rounds:" + rounds 
+				+ " maxGenerations:" + maxGenerations 
+				+ " popsize:" +  popsize
+				+ " vaporization:" +  p
+				+ " convergenceFactorReset:" +  convergenceFactorReset;
+	}
+
+	@Override
+	protected String plottFileName() {
+		return "aco-topologie.txt";
+	}
+	/**
+	 * tj1 is the pheromon level in the j position
+	 * cf is the convergence factor cf e [0;1]
+	 * 
+	 * 
+	 * 
+	 * @param pheromones
+	 * @return cf
+	 */
+	private double calculateConvergenceFactor(List<List<Double>> pheromones,int problemSize) {
+		double sumofmax = pheromones.stream().map(listPheromons -> listPheromons.stream().max((a,b) -> Double.compare(a,b)).get()).reduce(0.0, Double::sum);
+		double cf = sumofmax / (double)problemSize;
+		return cf;
+	}
+	/**
+	 * pheromone <- (1-p) * pheromone;
+	 * if(best is true at this position) pheromone <- pheromone + p;
+	 * @param pheromones
+	 * @param position
+	 */
+	private void vaporizeIntensifiePheromons(List<List<Double>> pheromones, List<Integer> position, int problemSize) {
+		ListIterator<List<Double>> iterPheromone = pheromones.listIterator();
+		ListIterator<Integer> iterBest = position.listIterator();
+		for(int i = 0; i < problemSize; i++) {
+			List<Double> tauList = iterPheromone.next();
+			int bestDecision = iterBest.next();
+			ListIterator<Double> tauListiter = tauList.listIterator();
+			for(int k = 0; tauListiter.hasNext(); k++) {
+				double value = tauListiter.next();
+				tauListiter.set((1.0 - p) * value + (k == bestDecision?p:0.0));
+			}
+		}
+	}
+	/**
+	 * 
+	 * @param pheromones
+	 * @return
+	 */
+	private List<Individual> constructSolutionsBiasedBy(List<List<Double>> pheromones) {
+		List<Individual> population =  new ArrayList<Individual>();
+		for(int i = 0; i < popsize; i++) {
+			population.add(constructASolutionBiasedBy(pheromones));
+		}
+		return population;
+	}
+	
+	
+	/**
+	 * Walks the path with a ant and decide by pheromones if should take true or false;
+	 * A pheromone have a level of 0 < pheromone < 1.
+	 * A Pheromone is  equal to the probability.
+	 * @param pheromones
+	 * @return
+	 */
+	private Individual constructASolutionBiasedBy(List<List<Double>> pheromones) {
+		Individual result = new Individual();
+		result.position = new ArrayList<Integer>();
+		for(List<Double> pheromoneList : pheromones) {
+			ListIterator<Double> tauListiter = pheromoneList.listIterator();
+			double radnomValue = Random.nextDouble();
+			for(int i = 0;tauListiter.hasNext(); i++) {
+				double actualtau = tauListiter.next();
+				if(radnomValue > actualtau) {
+					radnomValue -= actualtau;
+				}else {
+					result.position.add(i);
+					break;
+				}
+			}
+		}
+		return result;
+	}
+	/**
+	 * Initialize Pheromons with 1.0 / maxIndex;
+	 */
+	private List<List<Double>> initPheromones(int problemSize) {
+		List<List<Double>> result = new ArrayList<List<Double>>();
+		for(int i = 0; i < problemSize;i++) {
+			//generate list equal tau values with max Int
+			int maxIndex = this.getMaximumIndexObjects(i);
+			double tauValue = 1.0 / (double) (maxIndex + 1);
+			List<Double> tauList = new ArrayList<Double>();
+			for(int tau= 0; tau < maxIndex + 1; tau++) {
+				tauList.add(tauValue);				
+			}
+			result.add(tauList);
+		}
+		return result;
+	}
+}
  

+ 227 - 233
src/algorithm/topologie/GaAlgorithm.java

@@ -1,233 +1,227 @@
-package algorithm.topologie;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.ListIterator;
-import java.util.TreeSet;
-import java.util.stream.Collectors;
-
-import algorithm.objectiveFunction.ObjectiveFunctionByCarlos;
-import algorithm.objectiveFunction.TopologieObjectiveFunction;
-import api.TopologieAlgorithmFramework;
-import api.AlgorithmFrameworkFlex.Individual;
-import api.TopologieAlgorithmFramework.IndexCable;
-import ui.model.DecoratedState;
-import utility.Random;
-
-public class GaAlgorithm extends TopologieAlgorithmFramework {
-
-	private int popsize = 20;
-	private int maxGenerations = 100;
-	private double tournamentSize = 2.0;
-	private double fixedSwapProbability = 0.02;
-	private boolean useFixedSpawProbability = false;
-	private double fixedMutateProbability = 0.02;
-	private boolean useFixedMutateProbability = false;
-	private boolean useIntervalMutation = false;
-	private double mutateProbabilityInterval = 0.01;
-	private double maxMutationPercent = 0.01;
-	private boolean moreInformation = false;
-	
-	public GaAlgorithm(){
-		addIntParameter("popsize", popsize, intValue -> popsize = intValue, () -> popsize, 1);
-		addIntParameter("maxGenerations", maxGenerations, intValue -> maxGenerations = intValue, () -> maxGenerations, 1);
-		addDoubleParameter("tournamentSize", tournamentSize, doubleValue -> tournamentSize = doubleValue, () -> tournamentSize, 1.0);
-		addBooleanParameter("useFixedSpawProbability", useFixedSpawProbability, booleanValue -> useFixedSpawProbability = booleanValue, Arrays.asList("fixedSwapProbability"), new LinkedList<String>());
-		addDoubleParameter("fixedSwapProbability", fixedSwapProbability, doubleValue -> fixedSwapProbability = doubleValue, () -> fixedSwapProbability, useFixedSpawProbability, 0.0, 1.0);
-		addSeperator();
-		addBooleanParameter("Use Interval Mutation", useIntervalMutation, booleanValue -> useIntervalMutation = booleanValue, Arrays.asList("Probability for Frequency Mutation", "Scope of Mutation"), Arrays.asList("Probability for Bit-wise Mutation"));
-		addDoubleParameter("Probability for Frequency Mutation", mutateProbabilityInterval, doubleValue -> mutateProbabilityInterval = doubleValue, () -> mutateProbabilityInterval, useIntervalMutation, 0.0, 1.0);
-		addDoubleParameter("Probability for Bit-wise Mutation", fixedMutateProbability, doubleValue -> fixedMutateProbability = doubleValue, () -> fixedMutateProbability, !useIntervalMutation, 0.0, 1.0);
-		addDoubleParameter("Scope of Mutation", maxMutationPercent, doubleValue -> maxMutationPercent = doubleValue, () -> maxMutationPercent, useIntervalMutation, 0.0, 1.0);
-		addSeperator();
-		addBooleanParameter("Print Auxiliary Information", moreInformation, booleanValue -> moreInformation = booleanValue, new LinkedList<String>(), new LinkedList<String>());
-	
-	}
-	@Override
-	protected double evaluateState(DecoratedState actualstate, int amountOfAddedSwitch, double addedCableMeters, boolean moreInformation) {
-		return TopologieObjectiveFunction.getFitnessValueForState(actualstate, amountOfAddedSwitch, addedCableMeters, moreInformation);
-	}
-
-	@Override
-	protected Individual executeAlgo() {
-		resetWildcards();
-		Individual best = new Individual();
-		best.position = extractPositionAndAccess();
-		int problemSize =  best.position.size();
-		best.fitness = evaluatePosition(best.position);
-		List<Double> runList = new ArrayList<Double>();
-		runList.add(best.fitness);
-		console.println("Integer_Array_length: " + best.position.size());
-		List<Individual> population = initPopuluationRandom(problemSize, best);
-		for(int generation = 0; generation< maxGenerations; generation++) {
-			if(moreInformation)console.println("Generation" + generation + " start with Fitness: " + best.fitness);
-			for(Individual i : population) {
-				i.fitness = evaluatePosition(i.position);
-				if(moreInformation)console.println("Fitness" + i.fitness);
-				if(i.fitness < best.fitness) best = i;
-			}
-			runList.add(best.fitness);
-			List<Individual> childList = new ArrayList<Individual>();
-			for(int k = 0; k<popsize/2; k++) {
-				Individual parentA = selectAParent(population, popsize);
-				Individual parentB = selectAParent(population, popsize);
-				Individual childA = new Individual(parentA);
-				Individual childB = new Individual(parentB);
-				crossover(childA, childB, problemSize);
-				if(useIntervalMutation)mutateInterval(childA, problemSize);else mutate(childA, problemSize);
-				if(useIntervalMutation)mutateInterval(childB, problemSize);else mutate(childB, problemSize);
-				childList.add(childA);
-				childList.add(childB);
-			}
-			population = childList;
-			if(moreInformation)console.println("________________");
-			if(cancel)return null;
-		}
-		
-		console.println("   End with:" + best.fitness);
-		this.runList = runList;
-		return best;
-	}
-
-	@Override
-	protected int getProgressBarMaxCount() {
-		return rounds * maxGenerations * popsize + 1;
-	}
-
-	@Override
-	protected String algoInformationToPrint() {
-		return "GaAlgo"+ " Rounds:" + rounds 
-				+ " maxGenerations:" + maxGenerations
-				+ " popsize:" + popsize
-				+ " tournamentSize:" +  tournamentSize
-				+ (useFixedSpawProbability? " fixedSwapProbability:" +  fixedSwapProbability:" swapProbability:" + "1.0f/problemsize")
-				+ (useIntervalMutation? 
-						(" mutateProbabilityInterval:" +  mutateProbabilityInterval
-						+ " maxMutationPercent:" +  maxMutationPercent)
-						: 
-						(useFixedMutateProbability? " fixedMutateProbability:" +  fixedMutateProbability:" mutateProbability:" + "1.0f/problemsize"));
-	}
-
-	@Override
-	protected String plottFileName() {
-		return "ga-topologie.txt";
-	}
-	/**
-	 * Initialize the Population with Individuals that have a random Position.
-	 */
-	private List<Individual> initPopuluationRandom(int problemSize, Individual startIndidual){
-		List<Individual> population =  new ArrayList<Individual>();
-		for(int i = 0; i < popsize -1; i++) {
-			population.add(createRandomIndividualWithoutFitness(problemSize));
-		}
-		//Add Start Position
-		population.add(new Individual(startIndidual));
-		return population;
-	}
-	
-	private Individual createRandomIndividualWithoutFitness(int problemSize) {
-		//create Random Individual Without Fitness
-		Individual result = new Individual();
-		result.position = new ArrayList<Integer>();
-		for (int index = 0; index < problemSize; index++){
-			result.position.add(Random.nextIntegerInRange(0, this.getMaximumIndexObjects(index) + 1));
-		}
-		//console.println("[" +result.position.stream().map(Object::toString).collect(Collectors.joining(", ")) + "]");
-		return result;
-	}
-	
-	/**
-	 * Algorithm 32 Tournament Selection.
-	 * The fitnessValues are calculated for the Population List.
-	 * PseudoCode
-	 */
-	private Individual selectAParent(List<Individual> population,int popsize) {
-		Individual tournamentBest = population.get(Random.nextIntegerInRange(0, popsize));
-		double participants;
-		for(participants = tournamentSize ; participants >= 2; participants -= 1.0) {
-			Individual next = population.get(Random.nextIntegerInRange(0, popsize));
-			if(next.fitness < tournamentBest.fitness) tournamentBest = next;
-		}
-		//if tournament size is not a whole number like 2.5 or 3.6
-		//the remaining part is the chance to fight another time; 2.7 -> 70% chance to fight a second time
-		if( participants > 1) {		
-			if(Random.nextDouble() < participants - 1.0) {
-				//println("Chance to find a match");
-				Individual next = population.get(Random.nextIntegerInRange(0, popsize));
-				if(next.fitness < tournamentBest.fitness) tournamentBest = next;
-			}
-		}
-		return tournamentBest;
-	}
-	/** 
-	 * Algorithm 25 Uniform Crossover.
-	 * Probability is set to 1/Problemsize when not changed.
-	 */
-	private void crossover(Individual childA, Individual childB, int problemSize) {
-		double probability = (this.useFixedSpawProbability) ? this.fixedSwapProbability : 1.0/(double)problemSize;
-		ListIterator<Integer> iterA = childA.position.listIterator();
-		ListIterator<Integer> iterB = childB.position.listIterator();
-		for(int i= 0; i < problemSize; i++) {
-			int intA = iterA.next();
-			int intB = iterB.next();
-			if(Random.nextDouble() <=  probability ) {
-				//Swap 
-				iterA.set(intB);
-				iterB.set(intA);
-			}
-		}
-	}
-	/**
-	 * Algorithm 22 Bit-Flip Mutation.
-	 * 
-	 */
-	private void mutate(Individual child, int problemSize) {
-		double probability = (this.useFixedMutateProbability) ? this.fixedMutateProbability : 1.0/(double)problemSize;
-		ListIterator<Integer> iter = child.position.listIterator();
-		while(iter.hasNext()) {
-			int index = iter.nextIndex();
-			Integer intValue = iter.next();
-			if(Random.nextDouble() <=  probability) {
-				iter.set(Random.nextIntegerInRangeExcept(0, this.getMaximumIndexObjects(index), intValue));
-			}
-		}
-	}
-	/**
-	 * Algorithm rolf
-	 * 
-	 */
-	private void mutateInterval(Individual child, int problemSize) {
-		//If not mutate skip
-		if(Random.nextDouble() >  this.mutateProbabilityInterval) {
-			return;
-		}
-		//println("problemSize:" + problemSize + "    maxMutationPercent:" + maxMutationPercent);
-		int maximumAmountOfMutatedBits = Math.max(1, (int)Math.round(((double) problemSize) * this.maxMutationPercent));
-		int randomUniformAmountOfMutatedValues = Random.nextIntegerInRange(1,maximumAmountOfMutatedBits + 1);
-		
-		//println("max:" + maximumAmountOfMutatedBits + "   actual:" + randomUniformAmountOfMutatedValues);
-		TreeSet<Integer> mutationLocation = new TreeSet<Integer>(); //sortedSet
-		//Choose the location to mutate
-		for(int i = 0; i< randomUniformAmountOfMutatedValues; i++) {
-			boolean success = mutationLocation.add(Random.nextIntegerInRange(0, problemSize));
-			if(!success) i--; //can be add up to some series long loops if maximumAmountOfMutatedBits get closed to problemsize.
-		}
-		//println("Set:" + mutationLocation);
-		ListIterator<Integer> iter = child.position.listIterator();
-		if(mutationLocation.isEmpty()) return;
-		int firstindex = mutationLocation.pollFirst();
-		while(iter.hasNext()) {
-			int index = iter.nextIndex();
-			int intValue = iter.next();
-			if(index == firstindex) {
-				iter.set(Random.nextIntegerInRangeExcept(0, this.getMaximumIndexObjects(index), intValue));
-				//println("changed Value["+ index +"]");
-				if(mutationLocation.isEmpty()) break;
-				firstindex = mutationLocation.pollFirst();
-			}
-		}
-	}
-}
+package algorithm.topologie;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.ListIterator;
+import java.util.TreeSet;
+import algorithm.objectiveFunction.TopologieObjectiveFunction;
+import api.TopologieAlgorithmFramework;
+import ui.model.DecoratedState;
+import utility.Random;
+
+public class GaAlgorithm extends TopologieAlgorithmFramework {
+
+	private int popsize = 20;
+	private int maxGenerations = 100;
+	private double tournamentSize = 2.0;
+	private double fixedSwapProbability = 0.02;
+	private boolean useFixedSpawProbability = false;
+	private double fixedMutateProbability = 0.02;
+	private boolean useFixedMutateProbability = false;
+	private boolean useIntervalMutation = false;
+	private double mutateProbabilityInterval = 0.01;
+	private double maxMutationPercent = 0.01;
+	private boolean moreInformation = false;
+	
+	public GaAlgorithm(){
+		addIntParameter("popsize", popsize, intValue -> popsize = intValue, () -> popsize, 1);
+		addIntParameter("maxGenerations", maxGenerations, intValue -> maxGenerations = intValue, () -> maxGenerations, 1);
+		addDoubleParameter("tournamentSize", tournamentSize, doubleValue -> tournamentSize = doubleValue, () -> tournamentSize, 1.0);
+		addBooleanParameter("useFixedSpawProbability", useFixedSpawProbability, booleanValue -> useFixedSpawProbability = booleanValue, Arrays.asList("fixedSwapProbability"), new LinkedList<String>());
+		addDoubleParameter("fixedSwapProbability", fixedSwapProbability, doubleValue -> fixedSwapProbability = doubleValue, () -> fixedSwapProbability, useFixedSpawProbability, 0.0, 1.0);
+		addSeperator();
+		addBooleanParameter("Use Interval Mutation", useIntervalMutation, booleanValue -> useIntervalMutation = booleanValue, Arrays.asList("Probability for Frequency Mutation", "Scope of Mutation"), Arrays.asList("Probability for Bit-wise Mutation"));
+		addDoubleParameter("Probability for Frequency Mutation", mutateProbabilityInterval, doubleValue -> mutateProbabilityInterval = doubleValue, () -> mutateProbabilityInterval, useIntervalMutation, 0.0, 1.0);
+		addDoubleParameter("Probability for Bit-wise Mutation", fixedMutateProbability, doubleValue -> fixedMutateProbability = doubleValue, () -> fixedMutateProbability, !useIntervalMutation, 0.0, 1.0);
+		addDoubleParameter("Scope of Mutation", maxMutationPercent, doubleValue -> maxMutationPercent = doubleValue, () -> maxMutationPercent, useIntervalMutation, 0.0, 1.0);
+		addSeperator();
+		addBooleanParameter("Print Auxiliary Information", moreInformation, booleanValue -> moreInformation = booleanValue, new LinkedList<String>(), new LinkedList<String>());
+	
+	}
+	@Override
+	protected double evaluateState(DecoratedState actualstate, int amountOfAddedSwitch, double addedCableMeters, boolean moreInformation) {
+		return TopologieObjectiveFunction.getFitnessValueForState(actualstate, amountOfAddedSwitch, addedCableMeters, moreInformation);
+	}
+
+	@Override
+	protected Individual executeAlgo() {
+		resetWildcards();
+		Individual best = new Individual();
+		best.position = extractPositionAndAccess();
+		int problemSize =  best.position.size();
+		best.fitness = evaluatePosition(best.position);
+		List<Double> runList = new ArrayList<Double>();
+		runList.add(best.fitness);
+		console.println("Integer_Array_length: " + best.position.size());
+		List<Individual> population = initPopuluationRandom(problemSize, best);
+		for(int generation = 0; generation< maxGenerations; generation++) {
+			if(moreInformation)console.println("Generation" + generation + " start with Fitness: " + best.fitness);
+			for(Individual i : population) {
+				i.fitness = evaluatePosition(i.position);
+				if(moreInformation)console.println("Fitness" + i.fitness);
+				if(i.fitness < best.fitness) best = i;
+			}
+			runList.add(best.fitness);
+			List<Individual> childList = new ArrayList<Individual>();
+			for(int k = 0; k<popsize/2; k++) {
+				Individual parentA = selectAParent(population, popsize);
+				Individual parentB = selectAParent(population, popsize);
+				Individual childA = new Individual(parentA);
+				Individual childB = new Individual(parentB);
+				crossover(childA, childB, problemSize);
+				if(useIntervalMutation)mutateInterval(childA, problemSize);else mutate(childA, problemSize);
+				if(useIntervalMutation)mutateInterval(childB, problemSize);else mutate(childB, problemSize);
+				childList.add(childA);
+				childList.add(childB);
+			}
+			population = childList;
+			if(moreInformation)console.println("________________");
+			if(cancel)return null;
+		}
+		
+		console.println("   End with:" + best.fitness);
+		this.runList = runList;
+		return best;
+	}
+
+	@Override
+	protected int getProgressBarMaxCount() {
+		return rounds * maxGenerations * popsize + 1;
+	}
+
+	@Override
+	protected String algoInformationToPrint() {
+		return "GaAlgo"+ " Rounds:" + rounds 
+				+ " maxGenerations:" + maxGenerations
+				+ " popsize:" + popsize
+				+ " tournamentSize:" +  tournamentSize
+				+ (useFixedSpawProbability? " fixedSwapProbability:" +  fixedSwapProbability:" swapProbability:" + "1.0f/problemsize")
+				+ (useIntervalMutation? 
+						(" mutateProbabilityInterval:" +  mutateProbabilityInterval
+						+ " maxMutationPercent:" +  maxMutationPercent)
+						: 
+						(useFixedMutateProbability? " fixedMutateProbability:" +  fixedMutateProbability:" mutateProbability:" + "1.0f/problemsize"));
+	}
+
+	@Override
+	protected String plottFileName() {
+		return "ga-topologie.txt";
+	}
+	/**
+	 * Initialize the Population with Individuals that have a random Position.
+	 */
+	private List<Individual> initPopuluationRandom(int problemSize, Individual startIndidual){
+		List<Individual> population =  new ArrayList<Individual>();
+		for(int i = 0; i < popsize -1; i++) {
+			population.add(createRandomIndividualWithoutFitness(problemSize));
+		}
+		//Add Start Position
+		population.add(new Individual(startIndidual));
+		return population;
+	}
+	
+	private Individual createRandomIndividualWithoutFitness(int problemSize) {
+		//create Random Individual Without Fitness
+		Individual result = new Individual();
+		result.position = new ArrayList<Integer>();
+		for (int index = 0; index < problemSize; index++){
+			result.position.add(Random.nextIntegerInRange(0, this.getMaximumIndexObjects(index) + 1));
+		}
+		//console.println("[" +result.position.stream().map(Object::toString).collect(Collectors.joining(", ")) + "]");
+		return result;
+	}
+	
+	/**
+	 * Algorithm 32 Tournament Selection.
+	 * The fitnessValues are calculated for the Population List.
+	 * PseudoCode
+	 */
+	private Individual selectAParent(List<Individual> population,int popsize) {
+		Individual tournamentBest = population.get(Random.nextIntegerInRange(0, popsize));
+		double participants;
+		for(participants = tournamentSize ; participants >= 2; participants -= 1.0) {
+			Individual next = population.get(Random.nextIntegerInRange(0, popsize));
+			if(next.fitness < tournamentBest.fitness) tournamentBest = next;
+		}
+		//if tournament size is not a whole number like 2.5 or 3.6
+		//the remaining part is the chance to fight another time; 2.7 -> 70% chance to fight a second time
+		if( participants > 1) {		
+			if(Random.nextDouble() < participants - 1.0) {
+				//println("Chance to find a match");
+				Individual next = population.get(Random.nextIntegerInRange(0, popsize));
+				if(next.fitness < tournamentBest.fitness) tournamentBest = next;
+			}
+		}
+		return tournamentBest;
+	}
+	/** 
+	 * Algorithm 25 Uniform Crossover.
+	 * Probability is set to 1/Problemsize when not changed.
+	 */
+	private void crossover(Individual childA, Individual childB, int problemSize) {
+		double probability = (this.useFixedSpawProbability) ? this.fixedSwapProbability : 1.0/(double)problemSize;
+		ListIterator<Integer> iterA = childA.position.listIterator();
+		ListIterator<Integer> iterB = childB.position.listIterator();
+		for(int i= 0; i < problemSize; i++) {
+			int intA = iterA.next();
+			int intB = iterB.next();
+			if(Random.nextDouble() <=  probability ) {
+				//Swap 
+				iterA.set(intB);
+				iterB.set(intA);
+			}
+		}
+	}
+	/**
+	 * Algorithm 22 Bit-Flip Mutation.
+	 * 
+	 */
+	private void mutate(Individual child, int problemSize) {
+		double probability = (this.useFixedMutateProbability) ? this.fixedMutateProbability : 1.0/(double)problemSize;
+		ListIterator<Integer> iter = child.position.listIterator();
+		while(iter.hasNext()) {
+			int index = iter.nextIndex();
+			Integer intValue = iter.next();
+			if(Random.nextDouble() <=  probability) {
+				iter.set(Random.nextIntegerInRangeExcept(0, this.getMaximumIndexObjects(index), intValue));
+			}
+		}
+	}
+	/**
+	 * Algorithm rolf
+	 * 
+	 */
+	private void mutateInterval(Individual child, int problemSize) {
+		//If not mutate skip
+		if(Random.nextDouble() >  this.mutateProbabilityInterval) {
+			return;
+		}
+		//println("problemSize:" + problemSize + "    maxMutationPercent:" + maxMutationPercent);
+		int maximumAmountOfMutatedBits = Math.max(1, (int)Math.round(((double) problemSize) * this.maxMutationPercent));
+		int randomUniformAmountOfMutatedValues = Random.nextIntegerInRange(1,maximumAmountOfMutatedBits + 1);
+		
+		//println("max:" + maximumAmountOfMutatedBits + "   actual:" + randomUniformAmountOfMutatedValues);
+		TreeSet<Integer> mutationLocation = new TreeSet<Integer>(); //sortedSet
+		//Choose the location to mutate
+		for(int i = 0; i< randomUniformAmountOfMutatedValues; i++) {
+			boolean success = mutationLocation.add(Random.nextIntegerInRange(0, problemSize));
+			if(!success) i--; //can be add up to some series long loops if maximumAmountOfMutatedBits get closed to problemsize.
+		}
+		//println("Set:" + mutationLocation);
+		ListIterator<Integer> iter = child.position.listIterator();
+		if(mutationLocation.isEmpty()) return;
+		int firstindex = mutationLocation.pollFirst();
+		while(iter.hasNext()) {
+			int index = iter.nextIndex();
+			int intValue = iter.next();
+			if(index == firstindex) {
+				iter.set(Random.nextIntegerInRangeExcept(0, this.getMaximumIndexObjects(index), intValue));
+				//println("changed Value["+ index +"]");
+				if(mutationLocation.isEmpty()) break;
+				firstindex = mutationLocation.pollFirst();
+			}
+		}
+	}
+}

+ 326 - 340
src/algorithm/topologie/PsoAlgorithm.java

@@ -1,340 +1,326 @@
-package algorithm.topologie;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.ListIterator;
-import java.util.TreeSet;
-import java.util.stream.Collectors;
-
-import algorithm.objectiveFunction.ObjectiveFunctionByCarlos;
-import algorithm.objectiveFunction.TopologieObjectiveFunction;
-import api.TopologieAlgorithmFramework;
-import api.AlgorithmFrameworkFlex.Individual;
-import api.TopologieAlgorithmFramework.IndexCable;
-import ui.model.DecoratedState;
-import utility.Random;
-
-public class PsoAlgorithm extends TopologieAlgorithmFramework {
-
-	private int popsize = 20;
-	private int maxGenerations = 500;
-	private double dependency = 2.07; 
-	private double c1, c2, w;
-	private double maxVelocity = 10.0;
-	private double deviation = 0.5;
-	//mutation
-	private int mutationInterval = 1;
-	private boolean useIntervalMutation = false;
-	private double mutationRate = 0.005;
-	private double mutateProbabilityInterval = 0.01;
-	private double maxMutationPercent = 0.01;
-	
-	private boolean moreInformation = false;
-	
-	public PsoAlgorithm(){
-		addIntParameter("Swarmsize", popsize, intValue -> popsize = intValue, () -> popsize, 1);
-		addIntParameter("Iterations", maxGenerations, intValue -> maxGenerations = intValue, () -> maxGenerations, 1);
-		addSeperator();
-		addDoubleParameter("Deviation", deviation, doubleValue -> deviation = doubleValue, () -> deviation, 0);
-		addDoubleParameter("Dependency", dependency, doubleValue -> dependency = doubleValue, () -> dependency, true, 2.001, 2.4);
-		addDoubleParameter("Particle Max-Velocity", maxVelocity, doubleValue -> maxVelocity = doubleValue, () -> maxVelocity, 0.0);
-		addSeperator();
-		addIntParameter("Mutation Frequency (Iteration)", mutationInterval, intValue -> mutationInterval = intValue, () -> mutationInterval, 0);
-		addBooleanParameter("Use Interval Mutation", useIntervalMutation, booleanValue -> useIntervalMutation = booleanValue, Arrays.asList("Probability for Frequency Mutation", "Scope of Mutation"), Arrays.asList("Probability for Bit-wise Mutation"));
-		addDoubleParameter("Probability for Frequency Mutation", mutateProbabilityInterval, doubleValue -> mutateProbabilityInterval = doubleValue, () -> mutateProbabilityInterval, useIntervalMutation, 0.0, 1.0);
-		addDoubleParameter("Probability for Bit-wise Mutation", mutationRate, doubleValue -> mutationRate = doubleValue, () -> mutationRate, !useIntervalMutation, 0.0, 1.0);
-		addDoubleParameter("Scope of Mutation", maxMutationPercent, doubleValue -> maxMutationPercent = doubleValue, () -> maxMutationPercent, useIntervalMutation, 0.0, 1.0);
-		addSeperator();
-		addBooleanParameter("Print Auxiliary Information", moreInformation, booleanValue -> moreInformation = booleanValue, new LinkedList<String>(), new LinkedList<String>());
-	}
-	
-	
-	public static double linearInterpolate(double first, double second, double alpha) {
-		return first * (1.0 - alpha) + second * alpha;
-	}
-	public static double inverseLinearInterpolation(double min, double max, double value) {
-		if (max - min == 0) return max;
-		else return (value - min) / (max - min);
-	}
-	
-	@Override
-	protected double evaluateState(DecoratedState actualstate, int amountOfAddedSwitch, double addedCableMeters, boolean moreInformation) {
-		return TopologieObjectiveFunction.getFitnessValueForState(actualstate, amountOfAddedSwitch, addedCableMeters, moreInformation);
-	}
-
-	@Override
-	/**
-	 *  <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>
-	 *  
-	 *  
-	 */
-	protected Individual executeAlgo() {
-		resetWildcards();
-		initDependentParameter();
-		Individual globalBest = new Individual();
-		globalBest.position = extractPositionAndAccess();
-		globalBest.fitness = evaluatePosition(globalBest.position);
-		console.println("Start Value:" + globalBest.fitness);
-		int dimensions = globalBest.position.size();
-		List<Particle> swarm= initializeParticles(dimensions);
-		List<Double> runList = new ArrayList<Double>();
-		runList.add(globalBest.fitness);
-		evaluation(globalBest, swarm);
-		runList.add(globalBest.fitness);
-		for (int iteration = 0; iteration < this.maxGenerations ; iteration++) {
-			int mutationAllowed = iteration % mutationInterval;
-			double bitsFlipped = 0;
-			for (int particleNumber = 0; particleNumber < this.popsize; particleNumber++) {
-				Particle particle = swarm.get(particleNumber);		
-				
-				if(this.useIntervalMutation) {
-					boolean allowMutation = (Random.nextDouble() <  this.mutateProbabilityInterval);
-					TreeSet<Integer> mutationLocationSet = null;
-					if(allowMutation)mutationLocationSet = locationsToMutate(dimensions);
-					for(int index = 0; index < dimensions; index++) {
-						updateVelocity(particle, index, globalBest);
-						updateGenotype(particle, index);
-						if(allowMutation &&mutationAllowed == 0 && iteration != 0 && mutationLocationSet.contains(index))mutation(particle, index);
-						decode(particle, index);
-					}
-				}else {				
-					int count = 0;
-					for(int index = 0; index < dimensions; index++) {
-						updateVelocity(particle, index, globalBest);
-						updateGenotype(particle, index);
-						if(mutationAllowed == 0 && iteration != 0 && Random.nextDouble() < mutationRate) {
-							count++;
-							mutation(particle, index);
-						}
-						decode(particle, index);
-					}
-					bitsFlipped += count;
-				}
-			}
-			if(moreInformation) console.println("\t\t\t\t\t\tAvgBitsMutate: " + (bitsFlipped / (double)popsize));
-			if(cancel)return null;
-			evaluation(globalBest, swarm);
-			runList.add(globalBest.fitness);
-			if(moreInformation) console.println("------------------------");
-		}
-		console.println(" End Value:" + globalBest.fitness);
-		this.runList = runList;
-		return globalBest;
-	}
-
-	@Override
-	protected int getProgressBarMaxCount() {
-		return rounds * maxGenerations * popsize + 1;
-	}
-
-	@Override
-	protected String algoInformationToPrint() {
-		return "PsoAlgo"+ " Rounds:" + rounds 
-				+ " maxIterations:" + maxGenerations
-				+ " swarmSize:" + popsize
-				+ " dependency:" +  dependency
-				+ " mutationInterval:" +  mutationInterval
-				+ " maxVelocity: " + maxVelocity
-				+ " deviation: " + deviation
-				+ (useIntervalMutation? 
-						(" mutateProbabilityInterval:" +  mutateProbabilityInterval
-						+ " maxMutationPercent:" +  maxMutationPercent) : " mutationRate:" + mutationRate);
-	}
-
-	@Override
-	protected String plottFileName() {
-		return "pso-topologie.txt";
-	}
-	
-	
-	/**
-	 * 
-	 * @param problemSize maximum index of position in the particle
-	 * @return
-	 */
-	private List<Particle> initializeParticles(int problemSize) {
-		List<Particle> swarm = new ArrayList<Particle>();
-		//Create The Particle
-		for (int particleNumber = 0; particleNumber < popsize; particleNumber++){
-			//Create a Random position
-			List<Integer> aRandomPosition = new ArrayList<Integer>();
-			for (int index = 0; index < problemSize; index++){
-				aRandomPosition.add(Random.nextIntegerInRange(0, this.getMaximumIndexObjects(index) + 1));
-			}
-			swarm.add(new Particle(aRandomPosition));
-		}
-		return swarm;
-	}
-	/**
-	 * Calculate w, c1, c2
-	 */
-	private void initDependentParameter() {
-		w = 1.0 / (dependency - 1 + Math.sqrt(dependency * dependency - 2 * dependency));
-		c1 = c2 = dependency * w;
-	}
-	/**
-	 * Evaluate each particle and update the global Best position;
-	 * @param globalBest
-	 * @param swarm
-	 */
-	private void evaluation(Individual globalBest, List<Particle> swarm) {
-		for(Particle p: swarm) {
-			double localEvaluationValue = evaluatePosition(p.xPhenotype);
-			if(moreInformation) console.println("Fitness " + localEvaluationValue);
-			p.checkNewEvaluationValue(localEvaluationValue);
-			if(localEvaluationValue < globalBest.fitness) {
-				globalBest.fitness = localEvaluationValue;
-				globalBest.position = p.localBest.position;
-			}
-		}
-	}
-	/**
-	 * 	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, Individual globalBest) {
-		double r1 = Random.nextDouble();
-		double r2 =	Random.nextDouble();
-		double posValue = particle.xPhenotype.get(index);
-		particle.velocity.set(index, clamp(w*particle.velocity.get(index) + c1*r1*((particle.localBest.position.get(index))  - posValue) + c2*r2*((globalBest.position.get(index))- 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) {
-		double value = clamp(Random.nextGaussian(particle.xGenotype.get(index), deviation));
-		double alpha = inverseLinearInterpolation(-maxVelocity, +maxVelocity, value);
-		double result = linearInterpolate(0, this.getMaximumIndexObjects(index), alpha);
-		particle.xPhenotype.set(index, (int)Math.round(result));
-	}
-	/**
-	 * 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(-maxVelocity, Math.min(maxVelocity, value));
-	}
-	private TreeSet<Integer> locationsToMutate(int dimensions) {
-		TreeSet<Integer> mutationLocation = new TreeSet<Integer>(); //sortedSet
-		int maximumAmountOfMutatedBits = Math.max(1, (int)Math.round(((double) dimensions) * this.maxMutationPercent));
-		int randomUniformAmountOfMutatedValues = Random.nextIntegerInRange(1,maximumAmountOfMutatedBits + 1);
-		for(int i = 0; i< randomUniformAmountOfMutatedValues; i++) {
-			boolean success = mutationLocation.add(Random.nextIntegerInRange(0, dimensions));
-			if(!success) i--; //can be add up to some series long loops if maximumAmountOfMutatedBits get closed to problemsize.
-		}
-		return mutationLocation;
-	}
-	
-	
-	
-	
-	
-	
-	/**
-	 * 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<Integer> xPhenotype;
-		
-		public Individual localBest;
-		
-		Particle(List<Integer> 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 Individual();
-			localBest.fitness = Double.MAX_VALUE;
-		}
-		public void checkNewEvaluationValue(double newEvaluationValue) {
-			if(newEvaluationValue < localBest.fitness) {
-				localBest.fitness = newEvaluationValue;
-				localBest.position = xPhenotype.stream().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(", "));
-		}
-		
-	}
-	
-}
+package algorithm.topologie;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.TreeSet;
+import java.util.stream.Collectors;
+import algorithm.objectiveFunction.TopologieObjectiveFunction;
+import api.TopologieAlgorithmFramework;
+import ui.model.DecoratedState;
+import utility.Random;
+
+public class PsoAlgorithm extends TopologieAlgorithmFramework {
+
+	private int popsize = 20;
+	private int maxGenerations = 500;
+	private double dependency = 2.07; 
+	private double c1, c2, w;
+	private double maxVelocity = 10.0;
+	private double deviation = 0.5;
+	//mutation
+	private int mutationInterval = 1;
+	private boolean useIntervalMutation = false;
+	private double mutationRate = 0.005;
+	private double mutateProbabilityInterval = 0.01;
+	private double maxMutationPercent = 0.01;
+	
+	private boolean moreInformation = false;
+	
+	public PsoAlgorithm(){
+		addIntParameter("Swarmsize", popsize, intValue -> popsize = intValue, () -> popsize, 1);
+		addIntParameter("Iterations", maxGenerations, intValue -> maxGenerations = intValue, () -> maxGenerations, 1);
+		addSeperator();
+		addDoubleParameter("Deviation", deviation, doubleValue -> deviation = doubleValue, () -> deviation, 0);
+		addDoubleParameter("Dependency", dependency, doubleValue -> dependency = doubleValue, () -> dependency, true, 2.001, 2.4);
+		addDoubleParameter("Particle Max-Velocity", maxVelocity, doubleValue -> maxVelocity = doubleValue, () -> maxVelocity, 0.0);
+		addSeperator();
+		addIntParameter("Mutation Frequency (Iteration)", mutationInterval, intValue -> mutationInterval = intValue, () -> mutationInterval, 0);
+		addBooleanParameter("Use Interval Mutation", useIntervalMutation, booleanValue -> useIntervalMutation = booleanValue, Arrays.asList("Probability for Frequency Mutation", "Scope of Mutation"), Arrays.asList("Probability for Bit-wise Mutation"));
+		addDoubleParameter("Probability for Frequency Mutation", mutateProbabilityInterval, doubleValue -> mutateProbabilityInterval = doubleValue, () -> mutateProbabilityInterval, useIntervalMutation, 0.0, 1.0);
+		addDoubleParameter("Probability for Bit-wise Mutation", mutationRate, doubleValue -> mutationRate = doubleValue, () -> mutationRate, !useIntervalMutation, 0.0, 1.0);
+		addDoubleParameter("Scope of Mutation", maxMutationPercent, doubleValue -> maxMutationPercent = doubleValue, () -> maxMutationPercent, useIntervalMutation, 0.0, 1.0);
+		addSeperator();
+		addBooleanParameter("Print Auxiliary Information", moreInformation, booleanValue -> moreInformation = booleanValue, new LinkedList<String>(), new LinkedList<String>());
+	}
+	
+	
+	public static double linearInterpolate(double first, double second, double alpha) {
+		return first * (1.0 - alpha) + second * alpha;
+	}
+	public static double inverseLinearInterpolation(double min, double max, double value) {
+		if (max - min == 0) return max;
+		else return (value - min) / (max - min);
+	}
+	
+	@Override
+	protected double evaluateState(DecoratedState actualstate, int amountOfAddedSwitch, double addedCableMeters, boolean moreInformation) {
+		return TopologieObjectiveFunction.getFitnessValueForState(actualstate, amountOfAddedSwitch, addedCableMeters, moreInformation);
+	}
+
+	@Override
+	/**
+	 *  <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>
+	 *  
+	 *  
+	 */
+	protected Individual executeAlgo() {
+		resetWildcards();
+		initDependentParameter();
+		Individual globalBest = new Individual();
+		globalBest.position = extractPositionAndAccess();
+		globalBest.fitness = evaluatePosition(globalBest.position);
+		console.println("Start Value:" + globalBest.fitness);
+		int dimensions = globalBest.position.size();
+		List<Particle> swarm= initializeParticles(dimensions);
+		List<Double> runList = new ArrayList<Double>();
+		runList.add(globalBest.fitness);
+		evaluation(globalBest, swarm);
+		runList.add(globalBest.fitness);
+		for (int iteration = 0; iteration < this.maxGenerations ; iteration++) {
+			int mutationAllowed = iteration % mutationInterval;
+			double bitsFlipped = 0;
+			for (int particleNumber = 0; particleNumber < this.popsize; particleNumber++) {
+				Particle particle = swarm.get(particleNumber);		
+				
+				if(this.useIntervalMutation) {
+					boolean allowMutation = (Random.nextDouble() <  this.mutateProbabilityInterval);
+					TreeSet<Integer> mutationLocationSet = null;
+					if(allowMutation)mutationLocationSet = locationsToMutate(dimensions);
+					for(int index = 0; index < dimensions; index++) {
+						updateVelocity(particle, index, globalBest);
+						updateGenotype(particle, index);
+						if(allowMutation &&mutationAllowed == 0 && iteration != 0 && mutationLocationSet.contains(index))mutation(particle, index);
+						decode(particle, index);
+					}
+				}else {				
+					int count = 0;
+					for(int index = 0; index < dimensions; index++) {
+						updateVelocity(particle, index, globalBest);
+						updateGenotype(particle, index);
+						if(mutationAllowed == 0 && iteration != 0 && Random.nextDouble() < mutationRate) {
+							count++;
+							mutation(particle, index);
+						}
+						decode(particle, index);
+					}
+					bitsFlipped += count;
+				}
+			}
+			if(moreInformation) console.println("\t\t\t\t\t\tAvgBitsMutate: " + (bitsFlipped / (double)popsize));
+			if(cancel)return null;
+			evaluation(globalBest, swarm);
+			runList.add(globalBest.fitness);
+			if(moreInformation) console.println("------------------------");
+		}
+		console.println(" End Value:" + globalBest.fitness);
+		this.runList = runList;
+		return globalBest;
+	}
+
+	@Override
+	protected int getProgressBarMaxCount() {
+		return rounds * maxGenerations * popsize + 1;
+	}
+
+	@Override
+	protected String algoInformationToPrint() {
+		return "PsoAlgo"+ " Rounds:" + rounds 
+				+ " maxIterations:" + maxGenerations
+				+ " swarmSize:" + popsize
+				+ " dependency:" +  dependency
+				+ " mutationInterval:" +  mutationInterval
+				+ " maxVelocity: " + maxVelocity
+				+ " deviation: " + deviation
+				+ (useIntervalMutation? 
+						(" mutateProbabilityInterval:" +  mutateProbabilityInterval
+						+ " maxMutationPercent:" +  maxMutationPercent) : " mutationRate:" + mutationRate);
+	}
+
+	@Override
+	protected String plottFileName() {
+		return "pso-topologie.txt";
+	}
+	
+	
+	/**
+	 * 
+	 * @param problemSize maximum index of position in the particle
+	 * @return
+	 */
+	private List<Particle> initializeParticles(int problemSize) {
+		List<Particle> swarm = new ArrayList<Particle>();
+		//Create The Particle
+		for (int particleNumber = 0; particleNumber < popsize; particleNumber++){
+			//Create a Random position
+			List<Integer> aRandomPosition = new ArrayList<Integer>();
+			for (int index = 0; index < problemSize; index++){
+				aRandomPosition.add(Random.nextIntegerInRange(0, this.getMaximumIndexObjects(index) + 1));
+			}
+			swarm.add(new Particle(aRandomPosition));
+		}
+		return swarm;
+	}
+	/**
+	 * Calculate w, c1, c2
+	 */
+	private void initDependentParameter() {
+		w = 1.0 / (dependency - 1 + Math.sqrt(dependency * dependency - 2 * dependency));
+		c1 = c2 = dependency * w;
+	}
+	/**
+	 * Evaluate each particle and update the global Best position;
+	 * @param globalBest
+	 * @param swarm
+	 */
+	private void evaluation(Individual globalBest, List<Particle> swarm) {
+		for(Particle p: swarm) {
+			double localEvaluationValue = evaluatePosition(p.xPhenotype);
+			if(moreInformation) console.println("Fitness " + localEvaluationValue);
+			p.checkNewEvaluationValue(localEvaluationValue);
+			if(localEvaluationValue < globalBest.fitness) {
+				globalBest.fitness = localEvaluationValue;
+				globalBest.position = p.localBest.position;
+			}
+		}
+	}
+	/**
+	 * 	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, Individual globalBest) {
+		double r1 = Random.nextDouble();
+		double r2 =	Random.nextDouble();
+		double posValue = particle.xPhenotype.get(index);
+		particle.velocity.set(index, clamp(w*particle.velocity.get(index) + c1*r1*((particle.localBest.position.get(index))  - posValue) + c2*r2*((globalBest.position.get(index))- 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) {
+		double value = clamp(Random.nextGaussian(particle.xGenotype.get(index), deviation));
+		double alpha = inverseLinearInterpolation(-maxVelocity, +maxVelocity, value);
+		double result = linearInterpolate(0, this.getMaximumIndexObjects(index), alpha);
+		particle.xPhenotype.set(index, (int)Math.round(result));
+	}
+
+	/**
+	 * 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(-maxVelocity, Math.min(maxVelocity, value));
+	}
+	private TreeSet<Integer> locationsToMutate(int dimensions) {
+		TreeSet<Integer> mutationLocation = new TreeSet<Integer>(); //sortedSet
+		int maximumAmountOfMutatedBits = Math.max(1, (int)Math.round(((double) dimensions) * this.maxMutationPercent));
+		int randomUniformAmountOfMutatedValues = Random.nextIntegerInRange(1,maximumAmountOfMutatedBits + 1);
+		for(int i = 0; i< randomUniformAmountOfMutatedValues; i++) {
+			boolean success = mutationLocation.add(Random.nextIntegerInRange(0, dimensions));
+			if(!success) i--; //can be add up to some series long loops if maximumAmountOfMutatedBits get closed to problemsize.
+		}
+		return mutationLocation;
+	}
+	
+	
+	
+	
+	
+	
+	/**
+	 * 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<Integer> xPhenotype;
+		
+		public Individual localBest;
+		
+		Particle(List<Integer> 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 Individual();
+			localBest.fitness = Double.MAX_VALUE;
+		}
+		public void checkNewEvaluationValue(double newEvaluationValue) {
+			if(newEvaluationValue < localBest.fitness) {
+				localBest.fitness = newEvaluationValue;
+				localBest.position = xPhenotype.stream().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(", "));
+		}
+		
+	}
+	
+}

+ 1365 - 1364
src/api/AlgorithmFrameworkFlex.java

@@ -1,1364 +1,1365 @@
-package api;
-
-import java.awt.BorderLayout;
-import java.awt.Component;
-import java.awt.Dimension;
-import java.awt.FlowLayout;
-import java.awt.image.BufferedImage;
-import java.io.BufferedWriter;
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.OutputStreamWriter;
-import java.math.RoundingMode;
-import java.text.NumberFormat;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.DoubleSummaryStatistics;
-import java.util.HashMap;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Locale;
-import java.util.function.BiFunction;
-import java.util.function.Consumer;
-import java.util.function.Supplier;
-import java.util.stream.Collectors;
-
-import javax.swing.BorderFactory;
-import javax.swing.Box;
-import javax.swing.BoxLayout;
-import javax.swing.ImageIcon;
-import javax.swing.JButton;
-import javax.swing.JCheckBox;
-import javax.swing.JComboBox;
-import javax.swing.JFileChooser;
-import javax.swing.JFormattedTextField;
-import javax.swing.JLabel;
-import javax.swing.JOptionPane;
-import javax.swing.JPanel;
-import javax.swing.JProgressBar;
-import javax.swing.JScrollPane;
-import javax.swing.JSplitPane;
-import javax.swing.text.NumberFormatter;
-
-import algorithm.objectiveFunction.ObjectiveFunctionByCarlos;
-import algorithm.objectiveFunction.SwitchObjectiveFunction;
-import classes.AbstractCanvasObject;
-import classes.GroupNode;
-import classes.Flexibility;
-import classes.HolonElement;
-import classes.HolonObject;
-import classes.HolonSwitch;
-import classes.HolonElement.Priority;
-import ui.controller.Control;
-import ui.controller.FlexManager.FlexState;
-import ui.controller.FlexManager.FlexWrapper;
-import ui.model.DecoratedGroupNode;
-import ui.model.DecoratedState;
-import ui.model.Model;
-import ui.model.DecoratedHolonObject.HolonObjectState;
-import ui.model.DecoratedSwitch.SwitchState;
-import ui.model.DecoratedNetwork;
-import ui.view.Console;
-import utility.ImageImport;
-import utility.StringFormat;
-
-public abstract class AlgorithmFrameworkFlex implements AddOn{
-	//Algo
-	protected int rounds = 1;
-	
-	
-	
-	//Panel
-	private JPanel content = new JPanel();
-	protected Console console = new Console();
-	private JPanel borderPanel = new JPanel();
-	
-	
-	//Settings groupNode
-	private DecoratedGroupNode dGroupNode = null;
-	
-	
-	//access
-	private ArrayList<AccessWrapper> access;
-	private HashMap<HolonObject, AccessWrapper> accessKillSwitch = new HashMap<HolonObject, AccessWrapper>();
-	LinkedList<List<Boolean>> resetChain = new LinkedList<List<Boolean>>();
-	boolean algoUseElements = false, algoUseSwitches = true, algoUseFlexes = true, algoUseKillSwitch = true;
-	
-	//time
-	private long startTime;
-	
-	
-	private RunProgressBar runProgressbar = new RunProgressBar();
-	
-	
-	
-	//concurrency
-	private Thread runThread = new Thread();
-	protected boolean cancel = false;
-
-	//holeg interaction
-	protected Control  control;
-
-	
-	//printing
-	private Printer runPrinter = new Printer(plottFileName());
-	protected List<Double> runList = new LinkedList<Double>();
-	private RunAverage avg = new RunAverage();
-
-	//Parameter
-	@SuppressWarnings("rawtypes")
-	LinkedList<ParameterStepping> parameterSteppingList= new LinkedList<ParameterStepping>();
-	protected boolean useStepping = false;
-
-	//Email
-	private boolean useEmailNotification = false;
-	
-	
-	//ObjectiveFunction
-	enum ObjectiveFunction {Normal, Switch};
-	ObjectiveFunction evaluationFunction = ObjectiveFunction.Normal;
-	
-	public AlgorithmFrameworkFlex(){
-		content.setLayout(new BorderLayout());
-		JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
-				createOptionPanel() , console);
-		splitPane.setResizeWeight(0.0);
-		content.add(splitPane, BorderLayout.CENTER);
-		content.setPreferredSize(new Dimension(1200,800));
-	}
-	
-	
-	
-	
-	
-	
-	private JPanel createOptionPanel() {
-		JPanel optionPanel = new JPanel(new BorderLayout());
-		JScrollPane scrollPane = new JScrollPane(createParameterPanel());
-		scrollPane.setBorder(BorderFactory.createTitledBorder("Parameter"));
-		optionPanel.add(scrollPane,  BorderLayout.CENTER);
-		optionPanel.add(createButtonPanel(), BorderLayout.PAGE_END);
-		return optionPanel;
-	}
-	
-	private Component createParameterPanel() {
-		JPanel parameterPanel = new JPanel(null);
-		parameterPanel.setPreferredSize(new Dimension(510,300));
-		borderPanel.setLayout(new BoxLayout(borderPanel, BoxLayout.PAGE_AXIS));
-		addIntParameter("Rounds", rounds, intInput -> rounds = intInput, () -> rounds, 1);
-		JScrollPane scrollPane = new JScrollPane(borderPanel);
-		scrollPane.setBounds(10, 0, 850, 292);
-		scrollPane.setBorder(BorderFactory.createEmptyBorder());
-		parameterPanel.add(scrollPane);	
-		
-		
-		
-		JButton selectGroupNodeButton = new JButton("Select GroupNode");
-		selectGroupNodeButton.setBounds(900, 0, 185, 30);
-		selectGroupNodeButton.addActionListener(actionEvent -> selectGroupNode());
-		parameterPanel.add(selectGroupNodeButton);	
-		JProgressBar progressBar = runProgressbar.getJProgressBar();
-		progressBar.setBounds(900, 35, 185, 20);
-		progressBar.setStringPainted(true);
-		parameterPanel.add(progressBar);
-		
-		JCheckBox useElements = new JCheckBox("Elements");
-		useElements.setSelected(algoUseElements);
-		useElements.setBounds(900, 70, 185, 20);
-		useElements.addActionListener(actionEvent -> algoUseElements = useElements.isSelected());
-		parameterPanel.add(useElements);
-		
-		JCheckBox useSwitches = new JCheckBox("Switches");
-		useSwitches.setSelected(algoUseSwitches);
-		useSwitches.setBounds(900, 90, 185, 20);
-		useSwitches.addActionListener(actionEvent -> algoUseSwitches = useSwitches.isSelected());
-		parameterPanel.add(useSwitches);
-		
-		
-		JCheckBox useFlexes = new JCheckBox("Flexibilities");
-		useFlexes.setSelected(algoUseFlexes);
-		useFlexes.setBounds(900, 110, 185, 20);
-		useFlexes.addActionListener(actionEvent -> algoUseFlexes = useFlexes.isSelected());
-		parameterPanel.add(useFlexes);
-		
-		JCheckBox useKillSwitches = new JCheckBox("KillSwitch");
-		useKillSwitches.setSelected(algoUseFlexes);
-		useKillSwitches.setBounds(900, 130, 185, 20);
-		useKillSwitches.addActionListener(actionEvent -> 
-				{
-					cancel();
-					reset();
-					algoUseKillSwitch = useKillSwitches.isSelected();
-				});
-		parameterPanel.add(useKillSwitches);
-		
-		String[] objectiveFunctionStrings = { "Normal", "Switch"};
-		JLabel fitnessLabel = new JLabel("FitnessFunction:");
-		fitnessLabel.setBounds(910, 160, 90, 20);
-		parameterPanel.add(fitnessLabel);
-		JComboBox<String> ofBox = new JComboBox<String>(objectiveFunctionStrings);
-		ofBox.addActionListener(actionEvent -> 
-		{
-			boolean pickNormal = ((String)ofBox.getSelectedItem()).equals("Normal");
-			evaluationFunction = pickNormal?ObjectiveFunction.Normal:ObjectiveFunction.Switch;
-		});
-		ofBox.setBounds(1000, 160, 70, 20);
-		parameterPanel.add(ofBox);
-		
-		
-		
-		
-		JCheckBox emailNotificationCheckbox = new JCheckBox("EmailNotification");
-		emailNotificationCheckbox.setSelected(this.useEmailNotification);
-		emailNotificationCheckbox.setBounds(900, 200, 130, 20);
-		emailNotificationCheckbox.addActionListener(actionEvent -> useEmailNotification = emailNotificationCheckbox.isSelected());
-		parameterPanel.add(emailNotificationCheckbox);
-		
-		JButton emailSettingsButton = new JButton("", new ImageIcon(ImageImport.loadImage("/Images/settingsIcon.png", 16,16)));
-		emailSettingsButton.setBounds(1030, 200, 20, 20);
-		emailSettingsButton.addActionListener(event -> {
-			EmailNotification.OpenEmailSettings(content);
-		});
-		parameterPanel.add(emailSettingsButton);
-		
-		
-		
-		
-		return parameterPanel;
-	}
-	private JPanel createButtonPanel() {
-		JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
-		
-		JButton resetButton =  new JButton("Reset");
-		resetButton.setToolTipText("Resets the State to before the Algorithm has runed.");
-		resetButton.addActionListener(actionEvent -> reset());
-		buttonPanel.add(resetButton);
-		
-		JButton cancelButton =  new JButton("Cancel Run");
-		cancelButton.addActionListener(actionEvent -> cancel());
-		buttonPanel.add(cancelButton);
-		
-		JButton fitnessButton =  new JButton("Fitness");
-		fitnessButton.setToolTipText("Fitness for the current state.");
-		fitnessButton.addActionListener(actionEvent -> fitness());
-		buttonPanel.add(fitnessButton);
-		
-		JButton runButton =  new JButton("Run");
-		runButton.addActionListener(actionEvent -> {
-			Runnable task = () -> run();
-			runThread = new Thread(task);
-			runThread.start();
-		});
-		buttonPanel.add(runButton);
-		
-		
-		
-		return buttonPanel;
-	}
-	
-	
-	
-	//ParameterImports
-	
-	//int
-	protected void addIntParameter(String parameterName, int parameterValue, Consumer<Integer> setter, Supplier<Integer> getter) {
-		this.addIntParameter(parameterName, parameterValue, setter, getter, Integer.MIN_VALUE, Integer.MAX_VALUE);
-	}
-	
-	protected void addIntParameter(String parameterName, int parameterValue, Consumer<Integer> setter, Supplier<Integer> getter, int parameterMinValue) {
-		this.addIntParameter(parameterName, parameterValue, setter, getter, parameterMinValue, Integer.MAX_VALUE);
-	}
-	
-	protected void addIntParameter(String parameterName, int parameterValue, Consumer<Integer> setter, Supplier<Integer> getter, int parameterMinValue, int parameterMaxValue) {
-		JPanel singleParameterPanel = new JPanel();
-		singleParameterPanel.setLayout(new BoxLayout(singleParameterPanel, BoxLayout.LINE_AXIS));
-		singleParameterPanel.setAlignmentX(0.0f);
-		singleParameterPanel.add(new JLabel(parameterName + ": "));
-		singleParameterPanel.add(Box.createHorizontalGlue());
-		NumberFormat format = NumberFormat.getIntegerInstance();
-		format.setGroupingUsed(false);
-		format.setParseIntegerOnly(true);
-		NumberFormatter integerFormatter = new NumberFormatter(format);
-		integerFormatter.setMinimum(parameterMinValue);
-		integerFormatter.setMaximum(parameterMaxValue);
-		integerFormatter.setCommitsOnValidEdit(true);
-		JFormattedTextField singleParameterTextField = new  JFormattedTextField(integerFormatter);
-		singleParameterTextField.setValue(parameterValue);
-		String minValue = (parameterMinValue == Integer.MIN_VALUE)?"Integer.MIN_VALUE":String.valueOf(parameterMinValue);
-		String maxValue = (parameterMaxValue == Integer.MAX_VALUE)?"Integer.MAX_VALUE":String.valueOf(parameterMaxValue);
-		singleParameterTextField.setToolTipText("Only integer \u2208 [" + minValue + "," + maxValue + "]");
-		singleParameterTextField.addPropertyChangeListener(actionEvent -> setter.accept(Integer.parseInt(singleParameterTextField.getValue().toString())));
-		singleParameterTextField.setMaximumSize(new Dimension(200, 30));
-		singleParameterTextField.setPreferredSize(new Dimension(200, 30));
-		singleParameterPanel.add(singleParameterTextField);
-		
-		
-		ParameterStepping<Integer> intParameterStepping = new ParameterStepping<Integer>(setter, getter, Integer::sum , (a,b) -> a * b, 1, 1);
-		intParameterStepping.useThisParameter = false;
-		parameterSteppingList.add(intParameterStepping);
-		
-		JCheckBox useSteppingCheckBox = new JCheckBox();
-		useSteppingCheckBox.setSelected(false);
-		singleParameterPanel.add(useSteppingCheckBox);
-		
-		
-		
-		JLabel stepsLabel = new JLabel("Steps: ");
-		stepsLabel.setEnabled(false);
-		singleParameterPanel.add(stepsLabel);
-		
-		NumberFormatter stepFormatter = new NumberFormatter(format);
-		stepFormatter.setMinimum(1);
-		stepFormatter.setMaximum(Integer.MAX_VALUE);
-		stepFormatter.setCommitsOnValidEdit(true);
-		
-		
-		JFormattedTextField stepsTextField = new  JFormattedTextField(stepFormatter);
-		stepsTextField.setEnabled(false);
-		stepsTextField.setValue(1);
-		stepsTextField.setToolTipText("Only integer \u2208 [" + 1 + "," + Integer.MAX_VALUE + "]");
-		stepsTextField.addPropertyChangeListener(actionEvent -> intParameterStepping.stepps = Integer.parseInt(stepsTextField.getValue().toString()));
-		stepsTextField.setMaximumSize(new Dimension(40, 30));
-		stepsTextField.setPreferredSize(new Dimension(40, 30));
-		singleParameterPanel.add(stepsTextField);
-		
-		JLabel stepsSizeLabel = new JLabel("StepsSize: ");
-		stepsSizeLabel.setEnabled(false);
-		singleParameterPanel.add(stepsSizeLabel);
-		
-		JFormattedTextField stepsSizeTextField = new  JFormattedTextField(stepFormatter);
-		stepsSizeTextField.setEnabled(false);
-		stepsSizeTextField.setValue(1);
-		stepsSizeTextField.setToolTipText("Only integer \u2208 [" + 1 + "," + Integer.MAX_VALUE + "]");
-		stepsSizeTextField.addPropertyChangeListener(actionEvent -> intParameterStepping.stepSize = Integer.parseInt(stepsSizeTextField.getValue().toString()));
-		stepsSizeTextField.setMaximumSize(new Dimension(40, 30));
-		stepsSizeTextField.setPreferredSize(new Dimension(40, 30));
-		singleParameterPanel.add(stepsSizeTextField);
-		
-		useSteppingCheckBox.addActionListener(actionEvent -> {
-			boolean enabled = useSteppingCheckBox.isSelected();
-			intParameterStepping.useThisParameter = enabled;
-			this.useStepping = this.parameterSteppingList.stream().anyMatch(parameter -> parameter.useThisParameter);
-			stepsLabel.setEnabled(enabled);
-			stepsTextField.setEnabled(enabled);
-			stepsSizeLabel.setEnabled(enabled);
-			stepsSizeTextField.setEnabled(enabled);
-		});
-		
-		borderPanel.add(singleParameterPanel);
-	}
-	
-	
-	//double
-	protected void addDoubleParameter(String parameterName, double parameterValue, Consumer<Double> setter, Supplier<Double> getter) {
-		this.addDoubleParameter(parameterName, parameterValue, setter, getter, Double.MIN_VALUE, Double.MAX_VALUE);
-	}
-	
-	
-	protected void addDoubleParameter(String parameterName, double parameterValue, Consumer<Double> setter, Supplier<Double> getter, double parameterMinValue) {
-		this.addDoubleParameter(parameterName, parameterValue, setter, getter, parameterMinValue, Double.MAX_VALUE);
-	}
-	
-	
-	protected void addDoubleParameter(String parameterName, double parameterValue, Consumer<Double> setter, Supplier<Double> getter, double parameterMinValue, double parameterMaxValue) {
-		JPanel singleParameterPanel = new JPanel();
-		singleParameterPanel.setLayout(new BoxLayout(singleParameterPanel, BoxLayout.LINE_AXIS));
-		singleParameterPanel.setAlignmentX(0.0f);
-		singleParameterPanel.add(new JLabel(parameterName + ": "));
-		singleParameterPanel.add(Box.createHorizontalGlue());
-		NumberFormat doubleFormat = NumberFormat.getNumberInstance(Locale.US);
-		doubleFormat.setMinimumFractionDigits(1);
-		doubleFormat.setMaximumFractionDigits(10);
-		doubleFormat.setRoundingMode(RoundingMode.HALF_UP);
-		NumberFormatter doubleFormatter = new NumberFormatter(doubleFormat);
-		doubleFormatter.setMinimum(parameterMinValue);
-		doubleFormatter.setMaximum(parameterMaxValue);
-		doubleFormatter.setCommitsOnValidEdit(true);
-		JFormattedTextField singleParameterTextField = new  JFormattedTextField(doubleFormatter);
-		singleParameterTextField.setValue(parameterValue);
-		String minValue = (parameterMinValue == Double.MIN_VALUE)?"Double.MIN_VALUE":String.valueOf(parameterMinValue);
-		String maxValue = (parameterMaxValue == Double.MAX_VALUE)?"Double.MAX_VALUE":String.valueOf(parameterMaxValue);
-		singleParameterTextField.setToolTipText("Only double \u2208 [" + minValue + "," + maxValue + "]");
-		singleParameterTextField.addPropertyChangeListener(actionEvent -> setter.accept(Double.parseDouble(singleParameterTextField.getValue().toString())));
-		singleParameterTextField.setMaximumSize(new Dimension(200, 30));
-		singleParameterTextField.setPreferredSize(new Dimension(200, 30));
-		singleParameterPanel.add(singleParameterTextField);
-		
-		ParameterStepping<Double> doubleParameterStepping = new ParameterStepping<Double>(setter, getter, (a,b) -> a+b , (a,b) -> a * b, 1.0, 1);
-		doubleParameterStepping.useThisParameter = false;
-		parameterSteppingList.add(doubleParameterStepping);
-		
-		JCheckBox useSteppingCheckBox = new JCheckBox();
-		useSteppingCheckBox.setSelected(false);
-		singleParameterPanel.add(useSteppingCheckBox);
-		
-		
-		
-		JLabel stepsLabel = new JLabel("Steps: ");
-		stepsLabel.setEnabled(false);
-		singleParameterPanel.add(stepsLabel);
-		NumberFormat format = NumberFormat.getIntegerInstance();
-		format.setGroupingUsed(false);
-		format.setParseIntegerOnly(true);
-		NumberFormatter integerFormatter = new NumberFormatter(format);
-		integerFormatter.setMinimum(1);
-		integerFormatter.setMaximum(Integer.MAX_VALUE);
-		integerFormatter.setCommitsOnValidEdit(true);
-	
-		
-		
-		JFormattedTextField stepsTextField = new  JFormattedTextField(integerFormatter);
-		stepsTextField.setEnabled(false);
-		stepsTextField.setValue(1);
-		stepsTextField.setToolTipText("Only integer \u2208 [" + 1 + "," + Integer.MAX_VALUE + "]");
-		stepsTextField.addPropertyChangeListener(actionEvent -> doubleParameterStepping.stepps = Integer.parseInt(stepsTextField.getValue().toString()));
-		stepsTextField.setMaximumSize(new Dimension(40, 30));
-		stepsTextField.setPreferredSize(new Dimension(40, 30));
-		singleParameterPanel.add(stepsTextField);
-		
-		JLabel stepsSizeLabel = new JLabel("StepsSize: ");
-		stepsSizeLabel.setEnabled(false);
-		singleParameterPanel.add(stepsSizeLabel);
-		
-		NumberFormatter doubleFormatterForStepping = new NumberFormatter(doubleFormat);
-		doubleFormatterForStepping.setCommitsOnValidEdit(true);
-		JFormattedTextField stepsSizeTextField = new  JFormattedTextField(doubleFormatterForStepping);
-		stepsSizeTextField.setEnabled(false);
-		stepsSizeTextField.setValue(1.0);
-		stepsSizeTextField.setToolTipText("Only double");
-		stepsSizeTextField.addPropertyChangeListener(actionEvent -> doubleParameterStepping.stepSize = Double.parseDouble(stepsSizeTextField.getValue().toString()));
-		stepsSizeTextField.setMaximumSize(new Dimension(40, 30));
-		stepsSizeTextField.setPreferredSize(new Dimension(40, 30));
-		singleParameterPanel.add(stepsSizeTextField);
-		
-		useSteppingCheckBox.addActionListener(actionEvent -> {
-			boolean enabled = useSteppingCheckBox.isSelected();
-			doubleParameterStepping.useThisParameter = enabled;
-			this.useStepping = this.parameterSteppingList.stream().anyMatch(parameter -> parameter.useThisParameter);
-			stepsLabel.setEnabled(enabled);
-			stepsTextField.setEnabled(enabled);
-			stepsSizeLabel.setEnabled(enabled);
-			stepsSizeTextField.setEnabled(enabled);
-		});
-		
-		borderPanel.add(singleParameterPanel);
-	}
-	//boolean
-	protected void addBooleanParameter(String parameterName, boolean parameterValue, Consumer<Boolean> setter){
-		JPanel singleParameterPanel = new JPanel();
-		singleParameterPanel.setLayout(new BoxLayout(singleParameterPanel, BoxLayout.LINE_AXIS));
-		singleParameterPanel.setAlignmentX(0.0f);
-		singleParameterPanel.add(new JLabel(parameterName + ": "));
-		singleParameterPanel.add(Box.createHorizontalGlue());
-		JCheckBox useGroupNodeCheckBox = new JCheckBox();
-		useGroupNodeCheckBox.setSelected(parameterValue);
-		useGroupNodeCheckBox.addActionListener(actionEvent -> setter.accept(useGroupNodeCheckBox.isSelected()));
-		singleParameterPanel.add(useGroupNodeCheckBox);
-		borderPanel.add(singleParameterPanel);
-	}
-	
-
-	private void startTimer(){
-		startTime = System.currentTimeMillis();
-	}
-	private long printElapsedTime(){
-		long elapsedMilliSeconds = System.currentTimeMillis() - startTime;
-		console.println("Execution Time of Algo in Milliseconds:" + elapsedMilliSeconds);
-		return elapsedMilliSeconds;
-	}
-	
-	
-	
-	private void cancel() {
-		if(runThread.isAlive()) {
-			console.println("Cancel run.");
-			cancel = true;
-			runProgressbar.cancel();
-		} else {
-			console.println("Nothing to cancel.");
-		}
-	}
-	
-	
-	private void fitness() {
-		if(runThread.isAlive()) {
-			console.println("Run have to be cancelled First.");
-			return;
-		}
-		double currentFitness = evaluatePosition(extractPositionAndAccess());
-		resetChain.removeLast();
-		console.println("Actual Fitnessvalue: " + currentFitness);
-	}
-	
-	
-	private void selectGroupNode() {
-		Object[] possibilities = control.getSimManager().getActualVisualRepresentationalState().getCreatedGroupNodes().values().stream().map(aCps -> new Handle<DecoratedGroupNode>(aCps)).toArray();
-		@SuppressWarnings("unchecked")
-		Handle<DecoratedGroupNode> selected = (Handle<DecoratedGroupNode>) JOptionPane.showInputDialog(content, "Select GroupNode:", "GroupNode?",  JOptionPane.OK_OPTION,new ImageIcon(new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB)) , possibilities, "");
-		if(selected != null) {
-			console.println("Selected: " + selected);
-			dGroupNode = selected.object;
-		}
-	}
-	
-	protected double evaluatePosition(List<Boolean> positionToEvaluate) {
-		runProgressbar.step();
-		setState(positionToEvaluate); // execution time critical
-		DecoratedState actualstate = control.getSimManager().getActualDecorState();
-		double result = evaluateState(actualstate);
-		return result;
-	}
-
-	private double evaluateState(DecoratedState actualstate) {
-		switch(this.evaluationFunction) {
-		case Switch:
-			return SwitchObjectiveFunction.getFitnessValueForState(actualstate);
-		case Normal:
-		default:
-			return ObjectiveFunctionByCarlos.getFitnessValueForState(actualstate);
-		}
-		
-	}
-
-	
-	private void run() {
-		cancel = false;
-		control.guiDisable(true);
-		runPrinter.openStream();
-		runPrinter.println("");
-		runPrinter.println("Start:" + stringStatFromRunValues(getRunValuesFromActualState()));
-		runPrinter.closeStream();
-		if(this.useStepping) {
-			initParameterStepping();
-			do {
-					executeAlgoWithParameter();
-					if(cancel) break;
-					resetState();
-			}while(updateOneParameter());
-			resetParameterStepping();
-		}else {
-			executeAlgoWithParameter();
-			
-		}
-		updateVisual();
-		runProgressbar.finishedCancel();
-		control.guiDisable(false);
-		if(this.useEmailNotification && !cancel) {
-			EmailNotification.sendEmail(this.getClass().getName() + " finished", "Execution done.");
-		}
-	}
-	@SuppressWarnings("rawtypes")
-	private void initParameterStepping() {
-		for(ParameterStepping param :this.parameterSteppingList) {
-			param.init();
-		}
-		
-	}
-	@SuppressWarnings("rawtypes")
-	private void resetParameterStepping() {
-		for(ParameterStepping param :this.parameterSteppingList) {
-			param.reset();
-		}
-		
-	}
-
-
-
-
-	@SuppressWarnings("rawtypes")
-	private boolean updateOneParameter() {
-		List<ParameterStepping> parameterInUseList = this.parameterSteppingList.stream().filter(param -> param.useThisParameter).collect(Collectors.toList());
-		Collections.reverse(parameterInUseList);
-		int lastParameter = parameterInUseList.size() - 1 ;
-		int actualParameter = 0;
-		for(ParameterStepping param : parameterInUseList) {
-			
-			if(param.canUpdate()) {
-				param.update();
-				return true;
-			}else {
-				if(actualParameter == lastParameter) break;
-				param.reset();
-			}
-			actualParameter++;
-		}
-		//No Param can be updated 
-		return false;
-	}
-
-
-
-
-
-
-	private void executeAlgoWithParameter(){
-		double startFitness = evaluatePosition(extractPositionAndAccess());
-		console.println("BitLength: " + access.size());
-		resetChain.removeLast();
-		runPrinter.openStream();
-		runPrinter.println(algoInformationToPrint());
-		console.println(algoInformationToPrint());
-		runPrinter.closeStream();
-		runProgressbar.start();
-		Individual runBest = new Individual();
-		runBest.fitness = Double.MAX_VALUE;
-		this.avg = new RunAverage();
-		for(int r = 0; r < rounds; r++)
-		{	
-			startTimer();	
-			Individual  roundBest = executeAlgo();
-			if(cancel)return;
-			long executionTime = printElapsedTime();
-			setState(roundBest.position);
-			runPrinter.openStream();
-			runPrinter.println(runList.stream().map(value -> StringFormat.doubleFixedPlaces(2,value)).collect(Collectors.joining(", ")));
-			RunValues val = getRunValuesFromActualState();
-			val.result = roundBest.fitness;
-			val.executionTime = executionTime;
-			avg.addRun(val);
-			runPrinter.println("Result: " + StringFormat.doubleFixedPlaces(2,roundBest.fitness) + " ExecutionTime:" + executionTime + " " + stringStatFromRunValues(val));
-			runPrinter.closeStream();
-			resetState();
-			if(roundBest.fitness < runBest.fitness) runBest = roundBest;
-		}
-		
-		control.getSimManager().resetFlexManagerForTimeStep(control.getModel().getCurIteration());
-		this.extractPositionAndAccess();
-		setState(runBest.position);
-		updateVisual();
-		console.println("Start: " + StringFormat.doubleFixedPlaces(2,startFitness));
-		console.println("AlgoResult: " + StringFormat.doubleFixedPlaces(2,runBest.fitness));
-		if(this.algoUseFlexes)calculateAndPrintFlexInfos(control.getSimManager().getActualDecorState());
-		runPrinter.openStream();
-		if(rounds > 1) {
-			RunValues avgRun = avg.getAverage();
-			
-			runPrinter.println("Average.Result: " + StringFormat.doubleFixedPlaces(2, avgRun.result) + " Average.ExecutionTime:" + avgRun.executionTime + " "  + this.stringStatFromRunValues(avg.getAverage(), "Average."));
-		}
-		runPrinter.println("");
-		runPrinter.closeStream();
-	}
-	
-	
-	private void calculateAndPrintFlexInfos(DecoratedState state) {
-		int amountOfUsedFlex = 0;
-		int amountOfFlex = state.getFlexManager().getAllFlexWrapper().size();
-		float cost = 0;
-		int consumingFlex = 0;
-		float consumingFlexEnergy = 0.0f;
-		int producingFlex = 0;
-		float producingFlexEnergy = 0.0f;
-		int maxCooldown = 0;
-		int amountEssential = 0;
-		int amountHigh = 0;
-		int amountMedium = 0;
-		int amountLow = 0;
-		for(FlexWrapper flexWrapper :state.getFlexManager().getAllFlexWrapperWithState(FlexState.IN_USE)) {
-			amountOfUsedFlex++;
-			cost += flexWrapper.getFlex().cost;
-			float energy = flexWrapper.getFlex().bringtmir();
-			if(energy < 0) {
-				consumingFlex++;
-				consumingFlexEnergy += -energy;
-			}else {
-				producingFlex++;
-				producingFlexEnergy += energy;
-			}
-			if(flexWrapper.getFlex().getCooldown() > maxCooldown) maxCooldown = flexWrapper.getFlex().getCooldown();
-			switch(flexWrapper.getFlex().getElement().getPriority()) {
-			case Essential:
-				amountEssential++;
-				break;
-			case High:
-				amountHigh++;
-				break;
-			case Low:
-				amountLow++;
-				break;
-			case Medium:
-				amountMedium++;
-				break;
-			default:
-				break;
-			
-			}
-		}
-		
-		
-		//Total Flexibilities:
-		//Used Flexibilities:
-		console.println("Used Flex [" + amountOfUsedFlex + "/" + amountOfFlex + "]");
-		
-		//Consuming Flexibilities:
-		console.println(consumingFlex + " consuimg flexibilities that consumed " + consumingFlexEnergy + "Energy.");
-		//Producing Flexibilities
-		console.println(producingFlex + " producing flexibilities that produce " + producingFlexEnergy + "Energy.");
-		console.println("Flex in use:\t" + "Low= " + amountLow + "\tMedium= " + amountMedium + "\tHigh= " + amountHigh + "\tEssential= " + amountEssential);
-		//Total cost:
-		console.println("Total Cost: "+ cost);
-		//Longest Cooldown
-		console.println("Max Cooldown: "+ maxCooldown);
-		//
-		
-	}
-
-
-
-
-
-
-	protected abstract Individual executeAlgo();
-
-
-
-
-
-
-	private void reset() {
-		if(runThread.isAlive()) {
-			console.println("Run have to be cancelled First.");
-			return;
-		}
-		if(!resetChain.isEmpty()) {
-			console.println("Resetting..");
-			setState(resetChain.getFirst());
-			resetChain.clear();
-			control.resetSimulation();
-			control.setCurIteration(0);
-			updateVisual();
-		}else {
-			console.println("No run inistialized.");
-		}
-	}
-
-
-	/**
-	 * To let the User See the current state without touching the Canvas.
-	 */
-	private void updateVisual() {
-		control.calculateStateAndVisualForCurrentTimeStep();
-	}
-	/**
-	 * Sets the Model back to its original State before the LAST run.
-	 */
-	private void resetState() {
-		setState(resetChain.getLast());
-	}
-
-
-	/**
-	 * Sets the State out of the given position for calculation or to show the user.
-	 * @param position
-	 */
-	private void setState(List<Boolean> position) {
-		control.getSimManager().resetFlexManagerForTimeStep(control.getModel().getCurIteration());
-		int i = 0;
-		for(Boolean bool: position) {
-			access.get(i++).setState(bool);
-		}
-		control.calculateStateOnlyForCurrentTimeStep();
-}
-
-
-	/**
-	 * Method to get the current Position alias a ListOf Booleans for aktive settings on the Objects on the Canvas.
-	 * Also initialize the Access Hashmap to swap faster positions.
-	 * @param model
-	 * @return
-	 */
-	protected List<Boolean> extractPositionAndAccess() {
-		Model model = control.getModel();
-		this.accessKillSwitch = new HashMap<HolonObject, AccessWrapper>();
-		access= new ArrayList<AccessWrapper>();
-		List<Boolean> initialState = new ArrayList<Boolean>();
-		rollOutNodes((dGroupNode != null)? dGroupNode.getModel().getNodes() :model.getObjectsOnCanvas(), initialState, model.getCurIteration());			
-		resetChain.add(initialState);
-		if(algoUseFlexes) {			
-			for(FlexWrapper flex :control.getSimManager().getActualFlexManager().getAllFlexWrapperWithState(FlexState.OFFERED)){
-				//flex.getFlex().getElement().parentObject;
-				AccessWrapper killSwitchAccess = this.algoUseKillSwitch ? this.accessKillSwitch.get(flex.getFlex().getElement().parentObject): null;;
-				access.add(new AccessWrapper(flex.getFlex(), killSwitchAccess));
-				initialState.add(false);
-			}
-			for(FlexWrapper flex :control.getSimManager().getActualFlexManager().getAllFlexWrapperWithState(FlexState.IN_USE)){
-				AccessWrapper killSwitchAccess = this.algoUseKillSwitch ? this.accessKillSwitch.get(flex.getFlex().getElement().parentObject): null;
-				access.add(new AccessWrapper(flex.getFlex(), killSwitchAccess));
-				initialState.add(true);
-			}
-		}
-		//console.println(access.stream().map(Object::toString).collect(Collectors.joining(", ")));
-		return initialState;
-	}
-	
-	
-	
-
-	/**
-	 * Method to extract the Informations recursively out of the Model.
-	 * @param nodes
-	 * @param positionToInit
-	 * @param timeStep
-	 */
-	private void rollOutNodes(List<AbstractCanvasObject> nodes, List<Boolean> positionToInit, int timeStep) {
-		for(AbstractCanvasObject aCps : nodes) {
-			if (aCps instanceof HolonObject) {
-				HolonObject hObject = (HolonObject) aCps;
-				AccessWrapper killSwitchAccess = new AccessWrapper(hObject);
-				if(this.algoUseKillSwitch) {
-					positionToInit.add(false);
-					access.add(killSwitchAccess);
-					accessKillSwitch.put(hObject, killSwitchAccess);					
-				}
-				if(this.algoUseElements) {
-					for (HolonElement hE : hObject.getElements()) {
-						positionToInit.add(hE.isActive());
-						access.add(new AccessWrapper(hE, killSwitchAccess));
-					}					
-				}
-			}
-			else if (aCps instanceof HolonSwitch&& algoUseSwitches) {
-				HolonSwitch sw = (HolonSwitch) aCps;
-				positionToInit.add(sw.getState(timeStep));
-				access.add(new AccessWrapper(sw));
-			}
-			else if(aCps instanceof GroupNode) {
-				rollOutNodes(((GroupNode)aCps).getNodes(), positionToInit ,timeStep );
-			}
-		}
-	}
-	
-	
-	
-	private RunValues getRunValuesFromActualState() {
-		RunValues val = new RunValues();
-		if(dGroupNode != null)
-		{
-			//GetActualDecoratedGroupNode
-			dGroupNode = control.getSimManager().getActualVisualRepresentationalState().getCreatedGroupNodes().get(dGroupNode.getModel());
-			val.producer = dGroupNode.getAmountOfSupplier();
-			val.consumer = dGroupNode.getAmountOfConsumer();
-			val.passiv = dGroupNode.getAmountOfPassiv();
-			val.objects = val.producer + val.consumer + val.passiv;
-			val.unsupplied = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.NOT_SUPPLIED);
-			val.partiallySupplied = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.PARTIALLY_SUPPLIED);
-			val.supplied = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.SUPPLIED);
-			val.overSupplied = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.OVER_SUPPLIED);
-			
-			
-			val.activeElements = dGroupNode.getAmountOfAktiveElemntsFromHolonObjects();
-			val.elements = dGroupNode.getAmountOfElemntsFromHolonObjects();
-			//TODO what should be printed happen when only groupNode are selected
-		}
-		DecoratedState state = control.getSimManager().getActualDecorState();
-		for(DecoratedNetwork net : state.getNetworkList()) {
-			val.consumer += net.getAmountOfConsumer();
-			val.producer += net.getAmountOfSupplier();
-			val.passiv += net.getAmountOfPassiv();
-			val.unsupplied += net.getAmountOfConsumerWithState(HolonObjectState.NOT_SUPPLIED);
-			val.partiallySupplied += net.getAmountOfConsumerWithState(HolonObjectState.PARTIALLY_SUPPLIED);
-			val.supplied += net.getAmountOfConsumerWithState(HolonObjectState.SUPPLIED);
-			val.overSupplied += net.getAmountOfConsumerWithState(HolonObjectState.OVER_SUPPLIED);
-			val.elements += net.getAmountOfElements();
-			val.activeElements += net.getAmountOfActiveElements();
-			val.consumption += net.getTotalConsumption();
-			val.production += net.getTotalProduction();
-		}
-		val.objects = val.consumer + val.producer + val.passiv;
-		val.difference= Math.abs(val.production - val.consumption);
-		
-		
-		
-		List<Flexibility> flexActiveList = control.getSimManager().getActualFlexManager().getAllFlexWrapperWithState(FlexState.IN_USE).stream().map(flex -> flex.getFlex()).collect(Collectors.toList());
-		val.essentialFlex = (int)flexActiveList.stream().filter(flex -> flex.getElement().getPriority() == Priority.Essential).count();
-		val.highFlex = (int)flexActiveList.stream().filter(flex -> flex.getElement().getPriority() == Priority.High).count();
-		val.mediumFlex = (int)flexActiveList.stream().filter(flex -> flex.getElement().getPriority() == Priority.Medium).count();
-		val.lowFlex = (int)flexActiveList.stream().filter(flex -> flex.getElement().getPriority() == Priority.Low).count();
-		val.flexebilities = val.essentialFlex + val.highFlex + val.mediumFlex + val.lowFlex;
-		val.holon = state.getNetworkList().size();
-		val.switches = state.getDecoratedSwitches().size();
-		val.activeSwitches = (int)state.getDecoratedSwitches().stream().filter(dswitch -> (dswitch.getState() == SwitchState.Closed)).count();
-		
-		DoubleSummaryStatistics overStat = state.getNetworkList().stream().flatMap(net -> {
-			return net.getConsumerList().stream().filter(con -> con.getState() == HolonObjectState.OVER_SUPPLIED);
-		}).mapToDouble(con -> con.getSupplyBarPercentage()).summaryStatistics();
-		
-		DoubleSummaryStatistics partiallyStat = state.getNetworkList().stream().flatMap(net -> {
-			return net.getConsumerList().stream().filter(con -> con.getState() == HolonObjectState.PARTIALLY_SUPPLIED);
-		}).mapToDouble(con -> con.getSupplyBarPercentage()).summaryStatistics();
-		
-		val.partiallyMin = filterInf(partiallyStat.getMin());
-		val.partiallyMax = filterInf(partiallyStat.getMax());
-		val.partiallyAverage = filterInf(partiallyStat.getAverage());
-		
-		val.overMin = filterInf(overStat.getMin());
-		val.overMax = filterInf(overStat.getMax());
-		val.overAverage = filterInf(overStat.getAverage());
-
-		return val;
-		
-	}
-	
-	
-	private double filterInf(double value) {
-		if(value == Double.NEGATIVE_INFINITY || value == Double.POSITIVE_INFINITY || value == Double.NaN) {
-			return 0;
-		}else {
-			return value;
-		}
-	}
-	
-	private String stringStatFromRunValues(RunValues val){
-		return stringStatFromRunValues(val , "");
-	}
-	
-	private String stringStatFromRunValues(RunValues val, String prefix) {
-		return	prefix +"Passiv: " + percentage(val.passiv, val.objects)
-			+ " " + prefix +"Producer: " + percentage(val.producer, val.objects)
-			+ " " +	prefix +"Consumer: " + percentage(val.consumer, val.objects)
-			+ " " +	prefix +"Unsupplied: " + percentage(val.unsupplied, val.objects)
-			+ " " +	prefix +"Partially: " + percentage(val.partiallySupplied, val.objects)
-			+ " " +	prefix +"Over: " + percentage(val.overSupplied, val.objects)
-			+ " " +	prefix +"Supplied: " + percentage(val.supplied, val.objects)
-			+ " " +	prefix +"Partially.SupplyPercentage.Min: " + StringFormat.doubleFixedPlaces(2, val.partiallyMin) 
-			+ " " +	prefix +"Partially.SupplyPercentage.Max: "+ StringFormat.doubleFixedPlaces(2, val.partiallyMax) 
-			+ " " +	prefix +"Partially.SupplyPercentage.Average: " + StringFormat.doubleFixedPlaces(2, val.partiallyAverage)
-			+ " " + prefix +"Over.SupplyPercentage.Min: " + StringFormat.doubleFixedPlaces(2, val.overMin) 
-			+ " " +	prefix +"Over.SupplyPercentage.Max: "+ StringFormat.doubleFixedPlaces(2, val.overMax) 
-			+ " " +	prefix +"Over.SupplyPercentage.Average: " + StringFormat.doubleFixedPlaces(2, val.overAverage)
-			+ " " +	prefix +"HolonElemnts.Active:" + percentage(val.activeElements, val.elements)
-			+ " " +	prefix +"Flexibilities.Essential: " + percentage(val.essentialFlex, val.flexebilities)
-			+ " " + prefix +"Flexibilities.High: " + percentage(val.highFlex, val.flexebilities)
-			+ " " +	prefix +"Flexibilities.Medium: " + percentage(val.mediumFlex, val.flexebilities)
-			+ " " +	prefix +"Flexibilities.Low: " + percentage(val.lowFlex, val.flexebilities)
-			+ " " +	prefix +"Switches.Active:" + percentage(val.activeSwitches,val.switches)
-			+ " " +	prefix +"Holons: " + val.holon
-			+ " " + prefix +"TotalConsumption: " + val.consumption
-			+ " " + prefix +"TotalProduction: " + val.production
-			+ " " + prefix +"Difference: " + val.difference;
-		
-	}
-	
-	
-	private String percentage(double numerator , double denominator) {
-		if((int)denominator == 0) {
-			return "-%";
-		}
-		return  StringFormat.doubleTwoPlaces(numerator)   + "/" + StringFormat.doubleTwoPlaces(denominator) + " "+ StringFormat.doubleFixedPlaces(2,(float)numerator /(float)denominator * 100) + "%";
-	}
-	
-
-	
-	@Override
-	public JPanel getPanel() {
-		return content;
-	}
-
-	@Override
-	public void setController(Control control) {
-		this.control = control;
-	}
-	
-	
-	
-	private class RunProgressBar{
-		//progressbar
-		private JProgressBar progressBar = new JProgressBar();
-		private int count = 0;
-		private boolean isActive = false;
-		
-		public void step() {
-			if(isActive) progressBar.setValue(count++);
-		}
-		public void start() {
-			progressBar.setIndeterminate(false);
-			count = 0;
-			isActive = true;
-			progressBar.setValue(0);
-			progressBar.setMaximum(getProgressBarMaxCount());
-		}
-		public void cancel() {
-			isActive = false;
-			progressBar.setIndeterminate(true);
-		}
-		public void finishedCancel() {
-			progressBar.setIndeterminate(false);
-			progressBar.setValue(0);
-		}
-		public JProgressBar getJProgressBar(){
-			return progressBar;
-		}
-	}
-	
-	protected abstract int getProgressBarMaxCount();
-	
-	protected abstract String algoInformationToPrint();
-	protected abstract String plottFileName();
-	
-	
-	
-	public class Printer{
-		private JFileChooser fileChooser = new JFileChooser();
-		private BufferedWriter out;
-		public Printer(String filename){
-			fileChooser.setCurrentDirectory(new File(System.getProperty("user.dir")));
-			fileChooser.setSelectedFile(new File(filename));
-		}
-		public void openStream() {
-			File file = fileChooser.getSelectedFile();
-			try {
-				file.createNewFile();
-				out = new BufferedWriter(new OutputStreamWriter(
-					    new FileOutputStream(file, true), "UTF-8"));
-			} catch (IOException e) {
-				System.out.println(e.getMessage());
-			}
-		}
-		
-		
-		public void println(String stringToPrint) {
-			try {
-				out.write(stringToPrint);
-				out.newLine();
-			} catch (IOException e) {
-				System.out.println(e.getMessage());
-			}
-		}
-		public void closeStream() {
-			try {
-				out.close();
-			} catch (IOException e) {
-				System.out.println(e.getMessage());
-			}
-		}
-	}
-		
-	
-	private class RunValues{
-		public double result;
-		public double executionTime;
-		
-		public double objects;
-		public double passiv;
-		public double consumer;
-		public double supplied;
-		public double producer;
-		public double unsupplied;
-		public double partiallySupplied;
-		public double overSupplied;
-
-		public double partiallyMin;
-		public double partiallyMax;
-		public double partiallyAverage;
-		public double overMin;
-		public double overMax;
-		public double overAverage;
-		
-		public double activeElements;
-		public double elements;
-		
-		public double essentialFlex;
-		public double highFlex;
-		public double mediumFlex;
-		public double lowFlex;
-		public double flexebilities;
-		
-		public double switches;
-		public double activeSwitches;
-		
-		public double holon;
-		public double consumption;
-		public double production;
-		public double difference;
-	}
-	
-	
-	private class RunAverage{
-		private int runCount = 0;
-		//Values
-		private RunValues sum = new RunValues();
-		
-		public void addRun(RunValues val) {
-			sum.result += val.result;
-			sum.executionTime += val.executionTime;
-			sum.passiv += val.passiv;
-			sum.consumer += val.consumer;
-			sum.producer += val.producer;
-			sum.unsupplied += val.unsupplied;
-			sum.partiallySupplied += val.partiallySupplied;
-			sum.overSupplied += val.overSupplied;
-			sum.activeElements += val.activeElements;
-			sum.elements += val.elements;
-			sum.essentialFlex += val.essentialFlex;
-			sum.highFlex += val.highFlex;
-			sum.mediumFlex += val.mediumFlex;
-			sum.lowFlex += val.lowFlex;
-			sum.flexebilities += val.flexebilities;
-			sum.holon += val.holon;
-			sum.switches += val.switches;
-			sum.activeSwitches += val.activeSwitches;
-			sum.consumption += val.consumption;
-			sum.production += val.production;
-			sum.difference += val.difference;
-			sum.objects += val.objects;
-			sum.supplied += val.supplied;
-			sum.partiallyMin += val.partiallyMin;
-			sum.partiallyMax += val.partiallyMax;
-			sum.partiallyAverage += val.partiallyAverage;
-			sum.overMin += val.overMin;
-			sum.overMax += val.overMax;
-			sum.overAverage += val.overAverage;
-			
-			runCount++;
-		}
-		public RunValues getAverage() {
-			RunValues avg = new RunValues();
-			if(runCount == 0) {
-				return avg;
-			}
-			avg.result = sum.result / runCount;
-			avg.executionTime = sum.executionTime / runCount;
-			avg.passiv = sum.passiv / runCount;
-			avg.consumer = sum.consumer / runCount;
-			avg.producer = sum.producer / runCount;
-			avg.unsupplied = sum.unsupplied / runCount;
-			avg.partiallySupplied = sum.partiallySupplied / runCount;
-			avg.overSupplied = sum.overSupplied / runCount;
-			avg.activeElements = sum.activeElements / runCount;
-			avg.elements = sum.elements / runCount;
-			avg.essentialFlex = sum.essentialFlex / runCount;
-			avg.highFlex = sum.highFlex / runCount;
-			avg.mediumFlex = sum.mediumFlex / runCount;
-			avg.lowFlex = sum.lowFlex / runCount;
-			avg.flexebilities = sum.flexebilities / runCount;
-			avg.holon = sum.holon / runCount;
-			avg.switches = sum.switches / runCount;
-			avg.activeSwitches = sum.activeSwitches / runCount;
-			avg.consumption = sum.consumption / runCount;
-			avg.production = sum.production / runCount;
-			avg.difference = sum.difference / runCount;
-			avg.objects = sum.objects / runCount;
-			avg.supplied = sum.supplied / runCount;
-			avg.supplied = sum.supplied / runCount;	
-			avg.partiallyMin = sum.partiallyMin / runCount;
-			avg.partiallyMax = sum.partiallyMax / runCount;
-			avg.partiallyAverage = sum.partiallyAverage / runCount;
-			avg.overMin = sum.overMin / runCount;
-			avg.overMax = sum.overMax / runCount;
-			avg.overAverage = sum.overAverage / runCount;		
-			return avg;
-		}
-	}
-	
-	
-	private enum AccessType {None, HolonElement, Switch, Flexibility, KillSwitch};
-	/**
-	 * A Wrapper Class for Access HolonElement and HolonSwitch in one Element and not have to split the List.
-	 */
-	private class AccessWrapper {
-		private AccessType type;
-		private List<Boolean> intialStatesOfElementForKilllSwitch;
-		
-		private HolonObject hObject;
-		private HolonSwitch hSwitch;
-		
-		private HolonElement hElement;
-		private Flexibility flex;
-		private AccessWrapper correspondingKillSwitch;
-		
-		private boolean lastState;
-		
-		
-		public AccessWrapper(HolonObject hObject){
-			type = AccessType.KillSwitch;
-			this.hObject = hObject;
-			intialStatesOfElementForKilllSwitch = new ArrayList<Boolean>();
-			for(HolonElement hE: hObject.getElements()) {
-				intialStatesOfElementForKilllSwitch.add(hE.isActive());
-			}
-		}
-		public AccessWrapper(HolonSwitch hSwitch){
-			type = AccessType.Switch;
-			this.hSwitch = hSwitch;
-		}
-		public AccessWrapper(HolonElement hElement, AccessWrapper correspondingKillSwitch){
-			type = AccessType.HolonElement;
-			this.hElement = hElement;
-			this.correspondingKillSwitch = correspondingKillSwitch;
-		}
-		
-		public AccessWrapper(Flexibility flex, AccessWrapper correspondingKillSwitch){
-			type = AccessType.Flexibility;
-			this.flex = flex;
-			this.correspondingKillSwitch = correspondingKillSwitch;
-		}
-		
-		public void setState(boolean state) {
-			lastState = state;
-			switch(type) {
-				case  HolonElement:
-					if(!algoUseKillSwitch || (algoUseKillSwitch && !correspondingKillSwitch.getLastState())) {
-						hElement.setActive(state);
-					}
-					break;
-				case Switch:
-					hSwitch.setManualMode(true);
-					hSwitch.setManualState(state);
-					break;
-				case Flexibility:
-					if(state && (!algoUseKillSwitch || (algoUseKillSwitch && !correspondingKillSwitch.getLastState()))) {
-						control.getSimManager().getActualFlexManager().orderFlex(flex);
-					}
-					break;
-				case KillSwitch:
-					if(state) {
-						for (HolonElement hE : hObject.getElements()) {
-							hE.setActive(false);
-						}						
-					}else {
-						for(int i = 0; i < hObject.getElements().size(); i++) {
-							hObject.getElements().get(i).setActive(intialStatesOfElementForKilllSwitch.get(i));
-						}
-					}
-					break;
-				default:
-					break;
-				
-			}
-		}
-		
-		public boolean getLastState() {
-			return lastState;
-		}
-		
-		public String typeString() {
-			switch(type) {
-				case HolonElement:
-					return "HolonElement";
-				case Switch:
-					return "Switch";
-				case Flexibility:
-					return "Flexibility";
-				case KillSwitch:
-					return "KillSwitch";
-				default:
-					return "unknown";
-			}
-		}
-		
-		public String toString() {
-			return "[" +  typeString() + "]";
-		}
-	}
-	
-	
-	
-	
-	/**
-	* To create Random and maybe switch the random generation in the future.
-	*/
-	protected static class Random{
-		private static java.util.Random random = new java.util.Random();
-		/**
-		 * True or false
-		 * @return the random boolean.
-		 */
-		public static boolean nextBoolean(){
-			return random.nextBoolean();
-		}
-		/**
-		 * Between 0.0(inclusive) and 1.0 (exclusive)
-		 * @return the random double.
-		 */
-		public static double nextDouble() {
-			return random.nextDouble();
-		}
-		
-		/**
-		 * Random Int in Range [min;max[ with UniformDistirbution
-		 * @param min
-		 * @param max
-		 * @return
-		 */
-		public static int nextIntegerInRange(int min, int max) {
-			int result = min;
-			try {
-				result = min + random.nextInt(max - min);
-			}catch(java.lang.IllegalArgumentException e){
-				System.err.println("min : " + min + " max : " + max);
-				System.err.println("max should be more then min");
-			}
-			return result;
-		}
-	}
-	
-	private   class  Handle<T>{
-		public T object;
-		Handle(T object){
-			this.object = object;
-		}
-		public String toString() {
-			return object.toString();
-		}
-	}
-	public class Individual {
-		public double fitness;
-		public  List<Boolean> position;
-		
-		public Individual(){};
-		/**
-		 *  Copy Constructor
-		 */
-		public Individual(Individual c){
-			position = c.position.stream().collect(Collectors.toList());
-			fitness = c.fitness;
-		}
-		
-		String positionToString() {
-			return position.stream().map(bool -> (bool?"1":"0")).collect(Collectors.joining());
-		}
-	}
-	
-	protected class ParameterStepping<T>{
-		boolean useThisParameter = false;
-		String paramaterName;
-		private int count = 0;
-		int stepps;
-		T stepSize;
-		T startValue;
-		Consumer<T> setter;
-		Supplier<T> getter;
-		BiFunction<Integer,T,T> multyply;
-		BiFunction<T,T,T> add;
-		ParameterStepping(Consumer<T> setter, Supplier<T> getter, BiFunction<T,T,T> add, BiFunction<Integer,T,T> multyply, T stepSize, int stepps){
-			this.setter = setter;
-			this.getter = getter;
-			this.multyply = multyply;
-			this.add = add;
-			this.stepSize = stepSize;
-			this.stepps = stepps;
-		}
-		
-		void init() {
-			startValue = getter.get();
-		}
-		
-		boolean canUpdate() {
-			return count  < stepps;
-		}
-		
-		void update(){
-			if(canUpdate()) {
-				setter.accept(add.apply(startValue, multyply.apply(count + 1, stepSize)));
-				count ++;
-			}
-		}
-		
-		void reset() {
-			setter.accept(startValue);
-			count = 0;
-		}
-	}
-	
-	
-}
+package api;
+
+import java.awt.BorderLayout;
+import java.awt.Component;
+import java.awt.Dimension;
+import java.awt.FlowLayout;
+import java.awt.image.BufferedImage;
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStreamWriter;
+import java.math.RoundingMode;
+import java.text.NumberFormat;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.DoubleSummaryStatistics;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Locale;
+import java.util.function.BiFunction;
+import java.util.function.Consumer;
+import java.util.function.Supplier;
+import java.util.stream.Collectors;
+
+import javax.swing.BorderFactory;
+import javax.swing.Box;
+import javax.swing.BoxLayout;
+import javax.swing.ImageIcon;
+import javax.swing.JButton;
+import javax.swing.JCheckBox;
+import javax.swing.JComboBox;
+import javax.swing.JFileChooser;
+import javax.swing.JFormattedTextField;
+import javax.swing.JLabel;
+import javax.swing.JOptionPane;
+import javax.swing.JPanel;
+import javax.swing.JProgressBar;
+import javax.swing.JScrollPane;
+import javax.swing.JSplitPane;
+import javax.swing.text.NumberFormatter;
+
+import addOns.Utility.EmailNotification;
+import algorithm.objectiveFunction.ObjectiveFunctionByCarlos;
+import algorithm.objectiveFunction.SwitchObjectiveFunction;
+import classes.AbstractCanvasObject;
+import classes.GroupNode;
+import classes.Flexibility;
+import classes.HolonElement;
+import classes.HolonObject;
+import classes.HolonSwitch;
+import classes.HolonElement.Priority;
+import ui.controller.Control;
+import ui.controller.FlexManager.FlexState;
+import ui.controller.FlexManager.FlexWrapper;
+import ui.model.DecoratedGroupNode;
+import ui.model.DecoratedState;
+import ui.model.Model;
+import ui.model.DecoratedHolonObject.HolonObjectState;
+import ui.model.DecoratedSwitch.SwitchState;
+import ui.model.DecoratedNetwork;
+import ui.view.Console;
+import utility.ImageImport;
+import utility.StringFormat;
+
+public abstract class AlgorithmFrameworkFlex implements AddOn{
+	//Algo
+	protected int rounds = 1;
+	
+	
+	
+	//Panel
+	private JPanel content = new JPanel();
+	protected Console console = new Console();
+	private JPanel borderPanel = new JPanel();
+	
+	
+	//Settings groupNode
+	private DecoratedGroupNode dGroupNode = null;
+	
+	
+	//access
+	private ArrayList<AccessWrapper> access;
+	private HashMap<HolonObject, AccessWrapper> accessKillSwitch = new HashMap<HolonObject, AccessWrapper>();
+	LinkedList<List<Boolean>> resetChain = new LinkedList<List<Boolean>>();
+	boolean algoUseElements = false, algoUseSwitches = true, algoUseFlexes = true, algoUseKillSwitch = true;
+	
+	//time
+	private long startTime;
+	
+	
+	private RunProgressBar runProgressbar = new RunProgressBar();
+	
+	
+	
+	//concurrency
+	private Thread runThread = new Thread();
+	protected boolean cancel = false;
+
+	//holeg interaction
+	protected Control  control;
+
+	
+	//printing
+	private Printer runPrinter = new Printer(plottFileName());
+	protected List<Double> runList = new LinkedList<Double>();
+	private RunAverage avg = new RunAverage();
+
+	//Parameter
+	@SuppressWarnings("rawtypes")
+	LinkedList<ParameterStepping> parameterSteppingList= new LinkedList<ParameterStepping>();
+	protected boolean useStepping = false;
+
+	//Email
+	private boolean useEmailNotification = false;
+	
+	
+	//ObjectiveFunction
+	enum ObjectiveFunction {Normal, Switch};
+	ObjectiveFunction evaluationFunction = ObjectiveFunction.Normal;
+	
+	public AlgorithmFrameworkFlex(){
+		content.setLayout(new BorderLayout());
+		JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
+				createOptionPanel() , console);
+		splitPane.setResizeWeight(0.0);
+		content.add(splitPane, BorderLayout.CENTER);
+		content.setPreferredSize(new Dimension(1200,800));
+	}
+	
+	
+	
+	
+	
+	
+	private JPanel createOptionPanel() {
+		JPanel optionPanel = new JPanel(new BorderLayout());
+		JScrollPane scrollPane = new JScrollPane(createParameterPanel());
+		scrollPane.setBorder(BorderFactory.createTitledBorder("Parameter"));
+		optionPanel.add(scrollPane,  BorderLayout.CENTER);
+		optionPanel.add(createButtonPanel(), BorderLayout.PAGE_END);
+		return optionPanel;
+	}
+	
+	private Component createParameterPanel() {
+		JPanel parameterPanel = new JPanel(null);
+		parameterPanel.setPreferredSize(new Dimension(510,300));
+		borderPanel.setLayout(new BoxLayout(borderPanel, BoxLayout.PAGE_AXIS));
+		addIntParameter("Rounds", rounds, intInput -> rounds = intInput, () -> rounds, 1);
+		JScrollPane scrollPane = new JScrollPane(borderPanel);
+		scrollPane.setBounds(10, 0, 850, 292);
+		scrollPane.setBorder(BorderFactory.createEmptyBorder());
+		parameterPanel.add(scrollPane);	
+		
+		
+		
+		JButton selectGroupNodeButton = new JButton("Select GroupNode");
+		selectGroupNodeButton.setBounds(900, 0, 185, 30);
+		selectGroupNodeButton.addActionListener(actionEvent -> selectGroupNode());
+		parameterPanel.add(selectGroupNodeButton);	
+		JProgressBar progressBar = runProgressbar.getJProgressBar();
+		progressBar.setBounds(900, 35, 185, 20);
+		progressBar.setStringPainted(true);
+		parameterPanel.add(progressBar);
+		
+		JCheckBox useElements = new JCheckBox("Elements");
+		useElements.setSelected(algoUseElements);
+		useElements.setBounds(900, 70, 185, 20);
+		useElements.addActionListener(actionEvent -> algoUseElements = useElements.isSelected());
+		parameterPanel.add(useElements);
+		
+		JCheckBox useSwitches = new JCheckBox("Switches");
+		useSwitches.setSelected(algoUseSwitches);
+		useSwitches.setBounds(900, 90, 185, 20);
+		useSwitches.addActionListener(actionEvent -> algoUseSwitches = useSwitches.isSelected());
+		parameterPanel.add(useSwitches);
+		
+		
+		JCheckBox useFlexes = new JCheckBox("Flexibilities");
+		useFlexes.setSelected(algoUseFlexes);
+		useFlexes.setBounds(900, 110, 185, 20);
+		useFlexes.addActionListener(actionEvent -> algoUseFlexes = useFlexes.isSelected());
+		parameterPanel.add(useFlexes);
+		
+		JCheckBox useKillSwitches = new JCheckBox("KillSwitch");
+		useKillSwitches.setSelected(algoUseFlexes);
+		useKillSwitches.setBounds(900, 130, 185, 20);
+		useKillSwitches.addActionListener(actionEvent -> 
+				{
+					cancel();
+					reset();
+					algoUseKillSwitch = useKillSwitches.isSelected();
+				});
+		parameterPanel.add(useKillSwitches);
+		
+		String[] objectiveFunctionStrings = { "Normal", "Switch"};
+		JLabel fitnessLabel = new JLabel("FitnessFunction:");
+		fitnessLabel.setBounds(910, 160, 90, 20);
+		parameterPanel.add(fitnessLabel);
+		JComboBox<String> ofBox = new JComboBox<String>(objectiveFunctionStrings);
+		ofBox.addActionListener(actionEvent -> 
+		{
+			boolean pickNormal = ((String)ofBox.getSelectedItem()).equals("Normal");
+			evaluationFunction = pickNormal?ObjectiveFunction.Normal:ObjectiveFunction.Switch;
+		});
+		ofBox.setBounds(1000, 160, 70, 20);
+		parameterPanel.add(ofBox);
+		
+		
+		
+		
+		JCheckBox emailNotificationCheckbox = new JCheckBox("EmailNotification");
+		emailNotificationCheckbox.setSelected(this.useEmailNotification);
+		emailNotificationCheckbox.setBounds(900, 200, 130, 20);
+		emailNotificationCheckbox.addActionListener(actionEvent -> useEmailNotification = emailNotificationCheckbox.isSelected());
+		parameterPanel.add(emailNotificationCheckbox);
+		
+		JButton emailSettingsButton = new JButton("", new ImageIcon(ImageImport.loadImage("/Images/settingsIcon.png", 16,16)));
+		emailSettingsButton.setBounds(1030, 200, 20, 20);
+		emailSettingsButton.addActionListener(event -> {
+			EmailNotification.OpenEmailSettings(content);
+		});
+		parameterPanel.add(emailSettingsButton);
+		
+		
+		
+		
+		return parameterPanel;
+	}
+	private JPanel createButtonPanel() {
+		JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
+		
+		JButton resetButton =  new JButton("Reset");
+		resetButton.setToolTipText("Resets the State to before the Algorithm has runed.");
+		resetButton.addActionListener(actionEvent -> reset());
+		buttonPanel.add(resetButton);
+		
+		JButton cancelButton =  new JButton("Cancel Run");
+		cancelButton.addActionListener(actionEvent -> cancel());
+		buttonPanel.add(cancelButton);
+		
+		JButton fitnessButton =  new JButton("Fitness");
+		fitnessButton.setToolTipText("Fitness for the current state.");
+		fitnessButton.addActionListener(actionEvent -> fitness());
+		buttonPanel.add(fitnessButton);
+		
+		JButton runButton =  new JButton("Run");
+		runButton.addActionListener(actionEvent -> {
+			Runnable task = () -> run();
+			runThread = new Thread(task);
+			runThread.start();
+		});
+		buttonPanel.add(runButton);
+		
+		
+		
+		return buttonPanel;
+	}
+	
+	
+	
+	//ParameterImports
+	
+	//int
+	protected void addIntParameter(String parameterName, int parameterValue, Consumer<Integer> setter, Supplier<Integer> getter) {
+		this.addIntParameter(parameterName, parameterValue, setter, getter, Integer.MIN_VALUE, Integer.MAX_VALUE);
+	}
+	
+	protected void addIntParameter(String parameterName, int parameterValue, Consumer<Integer> setter, Supplier<Integer> getter, int parameterMinValue) {
+		this.addIntParameter(parameterName, parameterValue, setter, getter, parameterMinValue, Integer.MAX_VALUE);
+	}
+	
+	protected void addIntParameter(String parameterName, int parameterValue, Consumer<Integer> setter, Supplier<Integer> getter, int parameterMinValue, int parameterMaxValue) {
+		JPanel singleParameterPanel = new JPanel();
+		singleParameterPanel.setLayout(new BoxLayout(singleParameterPanel, BoxLayout.LINE_AXIS));
+		singleParameterPanel.setAlignmentX(0.0f);
+		singleParameterPanel.add(new JLabel(parameterName + ": "));
+		singleParameterPanel.add(Box.createHorizontalGlue());
+		NumberFormat format = NumberFormat.getIntegerInstance();
+		format.setGroupingUsed(false);
+		format.setParseIntegerOnly(true);
+		NumberFormatter integerFormatter = new NumberFormatter(format);
+		integerFormatter.setMinimum(parameterMinValue);
+		integerFormatter.setMaximum(parameterMaxValue);
+		integerFormatter.setCommitsOnValidEdit(true);
+		JFormattedTextField singleParameterTextField = new  JFormattedTextField(integerFormatter);
+		singleParameterTextField.setValue(parameterValue);
+		String minValue = (parameterMinValue == Integer.MIN_VALUE)?"Integer.MIN_VALUE":String.valueOf(parameterMinValue);
+		String maxValue = (parameterMaxValue == Integer.MAX_VALUE)?"Integer.MAX_VALUE":String.valueOf(parameterMaxValue);
+		singleParameterTextField.setToolTipText("Only integer \u2208 [" + minValue + "," + maxValue + "]");
+		singleParameterTextField.addPropertyChangeListener(actionEvent -> setter.accept(Integer.parseInt(singleParameterTextField.getValue().toString())));
+		singleParameterTextField.setMaximumSize(new Dimension(200, 30));
+		singleParameterTextField.setPreferredSize(new Dimension(200, 30));
+		singleParameterPanel.add(singleParameterTextField);
+		
+		
+		ParameterStepping<Integer> intParameterStepping = new ParameterStepping<Integer>(setter, getter, Integer::sum , (a,b) -> a * b, 1, 1);
+		intParameterStepping.useThisParameter = false;
+		parameterSteppingList.add(intParameterStepping);
+		
+		JCheckBox useSteppingCheckBox = new JCheckBox();
+		useSteppingCheckBox.setSelected(false);
+		singleParameterPanel.add(useSteppingCheckBox);
+		
+		
+		
+		JLabel stepsLabel = new JLabel("Steps: ");
+		stepsLabel.setEnabled(false);
+		singleParameterPanel.add(stepsLabel);
+		
+		NumberFormatter stepFormatter = new NumberFormatter(format);
+		stepFormatter.setMinimum(1);
+		stepFormatter.setMaximum(Integer.MAX_VALUE);
+		stepFormatter.setCommitsOnValidEdit(true);
+		
+		
+		JFormattedTextField stepsTextField = new  JFormattedTextField(stepFormatter);
+		stepsTextField.setEnabled(false);
+		stepsTextField.setValue(1);
+		stepsTextField.setToolTipText("Only integer \u2208 [" + 1 + "," + Integer.MAX_VALUE + "]");
+		stepsTextField.addPropertyChangeListener(actionEvent -> intParameterStepping.stepps = Integer.parseInt(stepsTextField.getValue().toString()));
+		stepsTextField.setMaximumSize(new Dimension(40, 30));
+		stepsTextField.setPreferredSize(new Dimension(40, 30));
+		singleParameterPanel.add(stepsTextField);
+		
+		JLabel stepsSizeLabel = new JLabel("StepsSize: ");
+		stepsSizeLabel.setEnabled(false);
+		singleParameterPanel.add(stepsSizeLabel);
+		
+		JFormattedTextField stepsSizeTextField = new  JFormattedTextField(stepFormatter);
+		stepsSizeTextField.setEnabled(false);
+		stepsSizeTextField.setValue(1);
+		stepsSizeTextField.setToolTipText("Only integer \u2208 [" + 1 + "," + Integer.MAX_VALUE + "]");
+		stepsSizeTextField.addPropertyChangeListener(actionEvent -> intParameterStepping.stepSize = Integer.parseInt(stepsSizeTextField.getValue().toString()));
+		stepsSizeTextField.setMaximumSize(new Dimension(40, 30));
+		stepsSizeTextField.setPreferredSize(new Dimension(40, 30));
+		singleParameterPanel.add(stepsSizeTextField);
+		
+		useSteppingCheckBox.addActionListener(actionEvent -> {
+			boolean enabled = useSteppingCheckBox.isSelected();
+			intParameterStepping.useThisParameter = enabled;
+			this.useStepping = this.parameterSteppingList.stream().anyMatch(parameter -> parameter.useThisParameter);
+			stepsLabel.setEnabled(enabled);
+			stepsTextField.setEnabled(enabled);
+			stepsSizeLabel.setEnabled(enabled);
+			stepsSizeTextField.setEnabled(enabled);
+		});
+		
+		borderPanel.add(singleParameterPanel);
+	}
+	
+	
+	//double
+	protected void addDoubleParameter(String parameterName, double parameterValue, Consumer<Double> setter, Supplier<Double> getter) {
+		this.addDoubleParameter(parameterName, parameterValue, setter, getter, Double.MIN_VALUE, Double.MAX_VALUE);
+	}
+	
+	
+	protected void addDoubleParameter(String parameterName, double parameterValue, Consumer<Double> setter, Supplier<Double> getter, double parameterMinValue) {
+		this.addDoubleParameter(parameterName, parameterValue, setter, getter, parameterMinValue, Double.MAX_VALUE);
+	}
+	
+	
+	protected void addDoubleParameter(String parameterName, double parameterValue, Consumer<Double> setter, Supplier<Double> getter, double parameterMinValue, double parameterMaxValue) {
+		JPanel singleParameterPanel = new JPanel();
+		singleParameterPanel.setLayout(new BoxLayout(singleParameterPanel, BoxLayout.LINE_AXIS));
+		singleParameterPanel.setAlignmentX(0.0f);
+		singleParameterPanel.add(new JLabel(parameterName + ": "));
+		singleParameterPanel.add(Box.createHorizontalGlue());
+		NumberFormat doubleFormat = NumberFormat.getNumberInstance(Locale.US);
+		doubleFormat.setMinimumFractionDigits(1);
+		doubleFormat.setMaximumFractionDigits(10);
+		doubleFormat.setRoundingMode(RoundingMode.HALF_UP);
+		NumberFormatter doubleFormatter = new NumberFormatter(doubleFormat);
+		doubleFormatter.setMinimum(parameterMinValue);
+		doubleFormatter.setMaximum(parameterMaxValue);
+		doubleFormatter.setCommitsOnValidEdit(true);
+		JFormattedTextField singleParameterTextField = new  JFormattedTextField(doubleFormatter);
+		singleParameterTextField.setValue(parameterValue);
+		String minValue = (parameterMinValue == Double.MIN_VALUE)?"Double.MIN_VALUE":String.valueOf(parameterMinValue);
+		String maxValue = (parameterMaxValue == Double.MAX_VALUE)?"Double.MAX_VALUE":String.valueOf(parameterMaxValue);
+		singleParameterTextField.setToolTipText("Only double \u2208 [" + minValue + "," + maxValue + "]");
+		singleParameterTextField.addPropertyChangeListener(actionEvent -> setter.accept(Double.parseDouble(singleParameterTextField.getValue().toString())));
+		singleParameterTextField.setMaximumSize(new Dimension(200, 30));
+		singleParameterTextField.setPreferredSize(new Dimension(200, 30));
+		singleParameterPanel.add(singleParameterTextField);
+		
+		ParameterStepping<Double> doubleParameterStepping = new ParameterStepping<Double>(setter, getter, (a,b) -> a+b , (a,b) -> a * b, 1.0, 1);
+		doubleParameterStepping.useThisParameter = false;
+		parameterSteppingList.add(doubleParameterStepping);
+		
+		JCheckBox useSteppingCheckBox = new JCheckBox();
+		useSteppingCheckBox.setSelected(false);
+		singleParameterPanel.add(useSteppingCheckBox);
+		
+		
+		
+		JLabel stepsLabel = new JLabel("Steps: ");
+		stepsLabel.setEnabled(false);
+		singleParameterPanel.add(stepsLabel);
+		NumberFormat format = NumberFormat.getIntegerInstance();
+		format.setGroupingUsed(false);
+		format.setParseIntegerOnly(true);
+		NumberFormatter integerFormatter = new NumberFormatter(format);
+		integerFormatter.setMinimum(1);
+		integerFormatter.setMaximum(Integer.MAX_VALUE);
+		integerFormatter.setCommitsOnValidEdit(true);
+	
+		
+		
+		JFormattedTextField stepsTextField = new  JFormattedTextField(integerFormatter);
+		stepsTextField.setEnabled(false);
+		stepsTextField.setValue(1);
+		stepsTextField.setToolTipText("Only integer \u2208 [" + 1 + "," + Integer.MAX_VALUE + "]");
+		stepsTextField.addPropertyChangeListener(actionEvent -> doubleParameterStepping.stepps = Integer.parseInt(stepsTextField.getValue().toString()));
+		stepsTextField.setMaximumSize(new Dimension(40, 30));
+		stepsTextField.setPreferredSize(new Dimension(40, 30));
+		singleParameterPanel.add(stepsTextField);
+		
+		JLabel stepsSizeLabel = new JLabel("StepsSize: ");
+		stepsSizeLabel.setEnabled(false);
+		singleParameterPanel.add(stepsSizeLabel);
+		
+		NumberFormatter doubleFormatterForStepping = new NumberFormatter(doubleFormat);
+		doubleFormatterForStepping.setCommitsOnValidEdit(true);
+		JFormattedTextField stepsSizeTextField = new  JFormattedTextField(doubleFormatterForStepping);
+		stepsSizeTextField.setEnabled(false);
+		stepsSizeTextField.setValue(1.0);
+		stepsSizeTextField.setToolTipText("Only double");
+		stepsSizeTextField.addPropertyChangeListener(actionEvent -> doubleParameterStepping.stepSize = Double.parseDouble(stepsSizeTextField.getValue().toString()));
+		stepsSizeTextField.setMaximumSize(new Dimension(40, 30));
+		stepsSizeTextField.setPreferredSize(new Dimension(40, 30));
+		singleParameterPanel.add(stepsSizeTextField);
+		
+		useSteppingCheckBox.addActionListener(actionEvent -> {
+			boolean enabled = useSteppingCheckBox.isSelected();
+			doubleParameterStepping.useThisParameter = enabled;
+			this.useStepping = this.parameterSteppingList.stream().anyMatch(parameter -> parameter.useThisParameter);
+			stepsLabel.setEnabled(enabled);
+			stepsTextField.setEnabled(enabled);
+			stepsSizeLabel.setEnabled(enabled);
+			stepsSizeTextField.setEnabled(enabled);
+		});
+		
+		borderPanel.add(singleParameterPanel);
+	}
+	//boolean
+	protected void addBooleanParameter(String parameterName, boolean parameterValue, Consumer<Boolean> setter){
+		JPanel singleParameterPanel = new JPanel();
+		singleParameterPanel.setLayout(new BoxLayout(singleParameterPanel, BoxLayout.LINE_AXIS));
+		singleParameterPanel.setAlignmentX(0.0f);
+		singleParameterPanel.add(new JLabel(parameterName + ": "));
+		singleParameterPanel.add(Box.createHorizontalGlue());
+		JCheckBox useGroupNodeCheckBox = new JCheckBox();
+		useGroupNodeCheckBox.setSelected(parameterValue);
+		useGroupNodeCheckBox.addActionListener(actionEvent -> setter.accept(useGroupNodeCheckBox.isSelected()));
+		singleParameterPanel.add(useGroupNodeCheckBox);
+		borderPanel.add(singleParameterPanel);
+	}
+	
+
+	private void startTimer(){
+		startTime = System.currentTimeMillis();
+	}
+	private long printElapsedTime(){
+		long elapsedMilliSeconds = System.currentTimeMillis() - startTime;
+		console.println("Execution Time of Algo in Milliseconds:" + elapsedMilliSeconds);
+		return elapsedMilliSeconds;
+	}
+	
+	
+	
+	private void cancel() {
+		if(runThread.isAlive()) {
+			console.println("Cancel run.");
+			cancel = true;
+			runProgressbar.cancel();
+		} else {
+			console.println("Nothing to cancel.");
+		}
+	}
+	
+	
+	private void fitness() {
+		if(runThread.isAlive()) {
+			console.println("Run have to be cancelled First.");
+			return;
+		}
+		double currentFitness = evaluatePosition(extractPositionAndAccess());
+		resetChain.removeLast();
+		console.println("Actual Fitnessvalue: " + currentFitness);
+	}
+	
+	
+	private void selectGroupNode() {
+		Object[] possibilities = control.getSimManager().getActualVisualRepresentationalState().getCreatedGroupNodes().values().stream().map(aCps -> new Handle<DecoratedGroupNode>(aCps)).toArray();
+		@SuppressWarnings("unchecked")
+		Handle<DecoratedGroupNode> selected = (Handle<DecoratedGroupNode>) JOptionPane.showInputDialog(content, "Select GroupNode:", "GroupNode?",  JOptionPane.OK_OPTION,new ImageIcon(new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB)) , possibilities, "");
+		if(selected != null) {
+			console.println("Selected: " + selected);
+			dGroupNode = selected.object;
+		}
+	}
+	
+	protected double evaluatePosition(List<Boolean> positionToEvaluate) {
+		runProgressbar.step();
+		setState(positionToEvaluate); // execution time critical
+		DecoratedState actualstate = control.getSimManager().getActualDecorState();
+		double result = evaluateState(actualstate);
+		return result;
+	}
+
+	private double evaluateState(DecoratedState actualstate) {
+		switch(this.evaluationFunction) {
+		case Switch:
+			return SwitchObjectiveFunction.getFitnessValueForState(actualstate);
+		case Normal:
+		default:
+			return ObjectiveFunctionByCarlos.getFitnessValueForState(actualstate);
+		}
+		
+	}
+
+	
+	private void run() {
+		cancel = false;
+		control.guiDisable(true);
+		runPrinter.openStream();
+		runPrinter.println("");
+		runPrinter.println("Start:" + stringStatFromRunValues(getRunValuesFromActualState()));
+		runPrinter.closeStream();
+		if(this.useStepping) {
+			initParameterStepping();
+			do {
+					executeAlgoWithParameter();
+					if(cancel) break;
+					resetState();
+			}while(updateOneParameter());
+			resetParameterStepping();
+		}else {
+			executeAlgoWithParameter();
+			
+		}
+		updateVisual();
+		runProgressbar.finishedCancel();
+		control.guiDisable(false);
+		if(this.useEmailNotification && !cancel) {
+			EmailNotification.sendEmail(this.getClass().getName() + " finished", "Execution done.");
+		}
+	}
+	@SuppressWarnings("rawtypes")
+	private void initParameterStepping() {
+		for(ParameterStepping param :this.parameterSteppingList) {
+			param.init();
+		}
+		
+	}
+	@SuppressWarnings("rawtypes")
+	private void resetParameterStepping() {
+		for(ParameterStepping param :this.parameterSteppingList) {
+			param.reset();
+		}
+		
+	}
+
+
+
+
+	@SuppressWarnings("rawtypes")
+	private boolean updateOneParameter() {
+		List<ParameterStepping> parameterInUseList = this.parameterSteppingList.stream().filter(param -> param.useThisParameter).collect(Collectors.toList());
+		Collections.reverse(parameterInUseList);
+		int lastParameter = parameterInUseList.size() - 1 ;
+		int actualParameter = 0;
+		for(ParameterStepping param : parameterInUseList) {
+			
+			if(param.canUpdate()) {
+				param.update();
+				return true;
+			}else {
+				if(actualParameter == lastParameter) break;
+				param.reset();
+			}
+			actualParameter++;
+		}
+		//No Param can be updated 
+		return false;
+	}
+
+
+
+
+
+
+	private void executeAlgoWithParameter(){
+		double startFitness = evaluatePosition(extractPositionAndAccess());
+		console.println("BitLength: " + access.size());
+		resetChain.removeLast();
+		runPrinter.openStream();
+		runPrinter.println(algoInformationToPrint());
+		console.println(algoInformationToPrint());
+		runPrinter.closeStream();
+		runProgressbar.start();
+		Individual runBest = new Individual();
+		runBest.fitness = Double.MAX_VALUE;
+		this.avg = new RunAverage();
+		for(int r = 0; r < rounds; r++)
+		{	
+			startTimer();	
+			Individual  roundBest = executeAlgo();
+			if(cancel)return;
+			long executionTime = printElapsedTime();
+			setState(roundBest.position);
+			runPrinter.openStream();
+			runPrinter.println(runList.stream().map(value -> StringFormat.doubleFixedPlaces(2,value)).collect(Collectors.joining(", ")));
+			RunValues val = getRunValuesFromActualState();
+			val.result = roundBest.fitness;
+			val.executionTime = executionTime;
+			avg.addRun(val);
+			runPrinter.println("Result: " + StringFormat.doubleFixedPlaces(2,roundBest.fitness) + " ExecutionTime:" + executionTime + " " + stringStatFromRunValues(val));
+			runPrinter.closeStream();
+			resetState();
+			if(roundBest.fitness < runBest.fitness) runBest = roundBest;
+		}
+		
+		control.getSimManager().resetFlexManagerForTimeStep(control.getModel().getCurIteration());
+		this.extractPositionAndAccess();
+		setState(runBest.position);
+		updateVisual();
+		console.println("Start: " + StringFormat.doubleFixedPlaces(2,startFitness));
+		console.println("AlgoResult: " + StringFormat.doubleFixedPlaces(2,runBest.fitness));
+		if(this.algoUseFlexes)calculateAndPrintFlexInfos(control.getSimManager().getActualDecorState());
+		runPrinter.openStream();
+		if(rounds > 1) {
+			RunValues avgRun = avg.getAverage();
+			
+			runPrinter.println("Average.Result: " + StringFormat.doubleFixedPlaces(2, avgRun.result) + " Average.ExecutionTime:" + avgRun.executionTime + " "  + this.stringStatFromRunValues(avg.getAverage(), "Average."));
+		}
+		runPrinter.println("");
+		runPrinter.closeStream();
+	}
+	
+	
+	private void calculateAndPrintFlexInfos(DecoratedState state) {
+		int amountOfUsedFlex = 0;
+		int amountOfFlex = state.getFlexManager().getAllFlexWrapper().size();
+		float cost = 0;
+		int consumingFlex = 0;
+		float consumingFlexEnergy = 0.0f;
+		int producingFlex = 0;
+		float producingFlexEnergy = 0.0f;
+		int maxCooldown = 0;
+		int amountEssential = 0;
+		int amountHigh = 0;
+		int amountMedium = 0;
+		int amountLow = 0;
+		for(FlexWrapper flexWrapper :state.getFlexManager().getAllFlexWrapperWithState(FlexState.IN_USE)) {
+			amountOfUsedFlex++;
+			cost += flexWrapper.getFlex().cost;
+			float energy = flexWrapper.getFlex().bringtmir();
+			if(energy < 0) {
+				consumingFlex++;
+				consumingFlexEnergy += -energy;
+			}else {
+				producingFlex++;
+				producingFlexEnergy += energy;
+			}
+			if(flexWrapper.getFlex().getCooldown() > maxCooldown) maxCooldown = flexWrapper.getFlex().getCooldown();
+			switch(flexWrapper.getFlex().getElement().getPriority()) {
+			case Essential:
+				amountEssential++;
+				break;
+			case High:
+				amountHigh++;
+				break;
+			case Low:
+				amountLow++;
+				break;
+			case Medium:
+				amountMedium++;
+				break;
+			default:
+				break;
+			
+			}
+		}
+		
+		
+		//Total Flexibilities:
+		//Used Flexibilities:
+		console.println("Used Flex [" + amountOfUsedFlex + "/" + amountOfFlex + "]");
+		
+		//Consuming Flexibilities:
+		console.println(consumingFlex + " consuimg flexibilities that consumed " + consumingFlexEnergy + "Energy.");
+		//Producing Flexibilities
+		console.println(producingFlex + " producing flexibilities that produce " + producingFlexEnergy + "Energy.");
+		console.println("Flex in use:\t" + "Low= " + amountLow + "\tMedium= " + amountMedium + "\tHigh= " + amountHigh + "\tEssential= " + amountEssential);
+		//Total cost:
+		console.println("Total Cost: "+ cost);
+		//Longest Cooldown
+		console.println("Max Cooldown: "+ maxCooldown);
+		//
+		
+	}
+
+
+
+
+
+
+	protected abstract Individual executeAlgo();
+
+
+
+
+
+
+	private void reset() {
+		if(runThread.isAlive()) {
+			console.println("Run have to be cancelled First.");
+			return;
+		}
+		if(!resetChain.isEmpty()) {
+			console.println("Resetting..");
+			setState(resetChain.getFirst());
+			resetChain.clear();
+			control.resetSimulation();
+			control.setCurIteration(0);
+			updateVisual();
+		}else {
+			console.println("No run inistialized.");
+		}
+	}
+
+
+	/**
+	 * To let the User See the current state without touching the Canvas.
+	 */
+	private void updateVisual() {
+		control.calculateStateAndVisualForCurrentTimeStep();
+	}
+	/**
+	 * Sets the Model back to its original State before the LAST run.
+	 */
+	private void resetState() {
+		setState(resetChain.getLast());
+	}
+
+
+	/**
+	 * Sets the State out of the given position for calculation or to show the user.
+	 * @param position
+	 */
+	private void setState(List<Boolean> position) {
+		control.getSimManager().resetFlexManagerForTimeStep(control.getModel().getCurIteration());
+		int i = 0;
+		for(Boolean bool: position) {
+			access.get(i++).setState(bool);
+		}
+		control.calculateStateOnlyForCurrentTimeStep();
+}
+
+
+	/**
+	 * Method to get the current Position alias a ListOf Booleans for aktive settings on the Objects on the Canvas.
+	 * Also initialize the Access Hashmap to swap faster positions.
+	 * @param model
+	 * @return
+	 */
+	protected List<Boolean> extractPositionAndAccess() {
+		Model model = control.getModel();
+		this.accessKillSwitch = new HashMap<HolonObject, AccessWrapper>();
+		access= new ArrayList<AccessWrapper>();
+		List<Boolean> initialState = new ArrayList<Boolean>();
+		rollOutNodes((dGroupNode != null)? dGroupNode.getModel().getNodes() :model.getObjectsOnCanvas(), initialState, model.getCurIteration());			
+		resetChain.add(initialState);
+		if(algoUseFlexes) {			
+			for(FlexWrapper flex :control.getSimManager().getActualFlexManager().getAllFlexWrapperWithState(FlexState.OFFERED)){
+				//flex.getFlex().getElement().parentObject;
+				AccessWrapper killSwitchAccess = this.algoUseKillSwitch ? this.accessKillSwitch.get(flex.getFlex().getElement().parentObject): null;;
+				access.add(new AccessWrapper(flex.getFlex(), killSwitchAccess));
+				initialState.add(false);
+			}
+			for(FlexWrapper flex :control.getSimManager().getActualFlexManager().getAllFlexWrapperWithState(FlexState.IN_USE)){
+				AccessWrapper killSwitchAccess = this.algoUseKillSwitch ? this.accessKillSwitch.get(flex.getFlex().getElement().parentObject): null;
+				access.add(new AccessWrapper(flex.getFlex(), killSwitchAccess));
+				initialState.add(true);
+			}
+		}
+		//console.println(access.stream().map(Object::toString).collect(Collectors.joining(", ")));
+		return initialState;
+	}
+	
+	
+	
+
+	/**
+	 * Method to extract the Informations recursively out of the Model.
+	 * @param nodes
+	 * @param positionToInit
+	 * @param timeStep
+	 */
+	private void rollOutNodes(List<AbstractCanvasObject> nodes, List<Boolean> positionToInit, int timeStep) {
+		for(AbstractCanvasObject aCps : nodes) {
+			if (aCps instanceof HolonObject) {
+				HolonObject hObject = (HolonObject) aCps;
+				AccessWrapper killSwitchAccess = new AccessWrapper(hObject);
+				if(this.algoUseKillSwitch) {
+					positionToInit.add(false);
+					access.add(killSwitchAccess);
+					accessKillSwitch.put(hObject, killSwitchAccess);					
+				}
+				if(this.algoUseElements) {
+					for (HolonElement hE : hObject.getElements()) {
+						positionToInit.add(hE.isActive());
+						access.add(new AccessWrapper(hE, killSwitchAccess));
+					}					
+				}
+			}
+			else if (aCps instanceof HolonSwitch&& algoUseSwitches) {
+				HolonSwitch sw = (HolonSwitch) aCps;
+				positionToInit.add(sw.getState(timeStep));
+				access.add(new AccessWrapper(sw));
+			}
+			else if(aCps instanceof GroupNode) {
+				rollOutNodes(((GroupNode)aCps).getNodes(), positionToInit ,timeStep );
+			}
+		}
+	}
+	
+	
+	
+	private RunValues getRunValuesFromActualState() {
+		RunValues val = new RunValues();
+		if(dGroupNode != null)
+		{
+			//GetActualDecoratedGroupNode
+			dGroupNode = control.getSimManager().getActualVisualRepresentationalState().getCreatedGroupNodes().get(dGroupNode.getModel());
+			val.producer = dGroupNode.getAmountOfSupplier();
+			val.consumer = dGroupNode.getAmountOfConsumer();
+			val.passiv = dGroupNode.getAmountOfPassiv();
+			val.objects = val.producer + val.consumer + val.passiv;
+			val.unsupplied = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.NOT_SUPPLIED);
+			val.partiallySupplied = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.PARTIALLY_SUPPLIED);
+			val.supplied = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.SUPPLIED);
+			val.overSupplied = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.OVER_SUPPLIED);
+			
+			
+			val.activeElements = dGroupNode.getAmountOfAktiveElemntsFromHolonObjects();
+			val.elements = dGroupNode.getAmountOfElemntsFromHolonObjects();
+			//TODO what should be printed happen when only groupNode are selected
+		}
+		DecoratedState state = control.getSimManager().getActualDecorState();
+		for(DecoratedNetwork net : state.getNetworkList()) {
+			val.consumer += net.getAmountOfConsumer();
+			val.producer += net.getAmountOfSupplier();
+			val.passiv += net.getAmountOfPassiv();
+			val.unsupplied += net.getAmountOfConsumerWithState(HolonObjectState.NOT_SUPPLIED);
+			val.partiallySupplied += net.getAmountOfConsumerWithState(HolonObjectState.PARTIALLY_SUPPLIED);
+			val.supplied += net.getAmountOfConsumerWithState(HolonObjectState.SUPPLIED);
+			val.overSupplied += net.getAmountOfConsumerWithState(HolonObjectState.OVER_SUPPLIED);
+			val.elements += net.getAmountOfElements();
+			val.activeElements += net.getAmountOfActiveElements();
+			val.consumption += net.getTotalConsumption();
+			val.production += net.getTotalProduction();
+		}
+		val.objects = val.consumer + val.producer + val.passiv;
+		val.difference= Math.abs(val.production - val.consumption);
+		
+		
+		
+		List<Flexibility> flexActiveList = control.getSimManager().getActualFlexManager().getAllFlexWrapperWithState(FlexState.IN_USE).stream().map(flex -> flex.getFlex()).collect(Collectors.toList());
+		val.essentialFlex = (int)flexActiveList.stream().filter(flex -> flex.getElement().getPriority() == Priority.Essential).count();
+		val.highFlex = (int)flexActiveList.stream().filter(flex -> flex.getElement().getPriority() == Priority.High).count();
+		val.mediumFlex = (int)flexActiveList.stream().filter(flex -> flex.getElement().getPriority() == Priority.Medium).count();
+		val.lowFlex = (int)flexActiveList.stream().filter(flex -> flex.getElement().getPriority() == Priority.Low).count();
+		val.flexebilities = val.essentialFlex + val.highFlex + val.mediumFlex + val.lowFlex;
+		val.holon = state.getNetworkList().size();
+		val.switches = state.getDecoratedSwitches().size();
+		val.activeSwitches = (int)state.getDecoratedSwitches().stream().filter(dswitch -> (dswitch.getState() == SwitchState.Closed)).count();
+		
+		DoubleSummaryStatistics overStat = state.getNetworkList().stream().flatMap(net -> {
+			return net.getConsumerList().stream().filter(con -> con.getState() == HolonObjectState.OVER_SUPPLIED);
+		}).mapToDouble(con -> con.getSupplyBarPercentage()).summaryStatistics();
+		
+		DoubleSummaryStatistics partiallyStat = state.getNetworkList().stream().flatMap(net -> {
+			return net.getConsumerList().stream().filter(con -> con.getState() == HolonObjectState.PARTIALLY_SUPPLIED);
+		}).mapToDouble(con -> con.getSupplyBarPercentage()).summaryStatistics();
+		
+		val.partiallyMin = filterInf(partiallyStat.getMin());
+		val.partiallyMax = filterInf(partiallyStat.getMax());
+		val.partiallyAverage = filterInf(partiallyStat.getAverage());
+		
+		val.overMin = filterInf(overStat.getMin());
+		val.overMax = filterInf(overStat.getMax());
+		val.overAverage = filterInf(overStat.getAverage());
+
+		return val;
+		
+	}
+	
+	
+	private double filterInf(double value) {
+		if(value == Double.NEGATIVE_INFINITY || value == Double.POSITIVE_INFINITY || value == Double.NaN) {
+			return 0;
+		}else {
+			return value;
+		}
+	}
+	
+	private String stringStatFromRunValues(RunValues val){
+		return stringStatFromRunValues(val , "");
+	}
+	
+	private String stringStatFromRunValues(RunValues val, String prefix) {
+		return	prefix +"Passiv: " + percentage(val.passiv, val.objects)
+			+ " " + prefix +"Producer: " + percentage(val.producer, val.objects)
+			+ " " +	prefix +"Consumer: " + percentage(val.consumer, val.objects)
+			+ " " +	prefix +"Unsupplied: " + percentage(val.unsupplied, val.objects)
+			+ " " +	prefix +"Partially: " + percentage(val.partiallySupplied, val.objects)
+			+ " " +	prefix +"Over: " + percentage(val.overSupplied, val.objects)
+			+ " " +	prefix +"Supplied: " + percentage(val.supplied, val.objects)
+			+ " " +	prefix +"Partially.SupplyPercentage.Min: " + StringFormat.doubleFixedPlaces(2, val.partiallyMin) 
+			+ " " +	prefix +"Partially.SupplyPercentage.Max: "+ StringFormat.doubleFixedPlaces(2, val.partiallyMax) 
+			+ " " +	prefix +"Partially.SupplyPercentage.Average: " + StringFormat.doubleFixedPlaces(2, val.partiallyAverage)
+			+ " " + prefix +"Over.SupplyPercentage.Min: " + StringFormat.doubleFixedPlaces(2, val.overMin) 
+			+ " " +	prefix +"Over.SupplyPercentage.Max: "+ StringFormat.doubleFixedPlaces(2, val.overMax) 
+			+ " " +	prefix +"Over.SupplyPercentage.Average: " + StringFormat.doubleFixedPlaces(2, val.overAverage)
+			+ " " +	prefix +"HolonElemnts.Active:" + percentage(val.activeElements, val.elements)
+			+ " " +	prefix +"Flexibilities.Essential: " + percentage(val.essentialFlex, val.flexebilities)
+			+ " " + prefix +"Flexibilities.High: " + percentage(val.highFlex, val.flexebilities)
+			+ " " +	prefix +"Flexibilities.Medium: " + percentage(val.mediumFlex, val.flexebilities)
+			+ " " +	prefix +"Flexibilities.Low: " + percentage(val.lowFlex, val.flexebilities)
+			+ " " +	prefix +"Switches.Active:" + percentage(val.activeSwitches,val.switches)
+			+ " " +	prefix +"Holons: " + val.holon
+			+ " " + prefix +"TotalConsumption: " + val.consumption
+			+ " " + prefix +"TotalProduction: " + val.production
+			+ " " + prefix +"Difference: " + val.difference;
+		
+	}
+	
+	
+	private String percentage(double numerator , double denominator) {
+		if((int)denominator == 0) {
+			return "-%";
+		}
+		return  StringFormat.doubleTwoPlaces(numerator)   + "/" + StringFormat.doubleTwoPlaces(denominator) + " "+ StringFormat.doubleFixedPlaces(2,(float)numerator /(float)denominator * 100) + "%";
+	}
+	
+
+	
+	@Override
+	public JPanel getPanel() {
+		return content;
+	}
+
+	@Override
+	public void setController(Control control) {
+		this.control = control;
+	}
+	
+	
+	
+	private class RunProgressBar{
+		//progressbar
+		private JProgressBar progressBar = new JProgressBar();
+		private int count = 0;
+		private boolean isActive = false;
+		
+		public void step() {
+			if(isActive) progressBar.setValue(count++);
+		}
+		public void start() {
+			progressBar.setIndeterminate(false);
+			count = 0;
+			isActive = true;
+			progressBar.setValue(0);
+			progressBar.setMaximum(getProgressBarMaxCount());
+		}
+		public void cancel() {
+			isActive = false;
+			progressBar.setIndeterminate(true);
+		}
+		public void finishedCancel() {
+			progressBar.setIndeterminate(false);
+			progressBar.setValue(0);
+		}
+		public JProgressBar getJProgressBar(){
+			return progressBar;
+		}
+	}
+	
+	protected abstract int getProgressBarMaxCount();
+	
+	protected abstract String algoInformationToPrint();
+	protected abstract String plottFileName();
+	
+	
+	
+	public class Printer{
+		private JFileChooser fileChooser = new JFileChooser();
+		private BufferedWriter out;
+		public Printer(String filename){
+			fileChooser.setCurrentDirectory(new File(System.getProperty("user.dir")));
+			fileChooser.setSelectedFile(new File(filename));
+		}
+		public void openStream() {
+			File file = fileChooser.getSelectedFile();
+			try {
+				file.createNewFile();
+				out = new BufferedWriter(new OutputStreamWriter(
+					    new FileOutputStream(file, true), "UTF-8"));
+			} catch (IOException e) {
+				System.out.println(e.getMessage());
+			}
+		}
+		
+		
+		public void println(String stringToPrint) {
+			try {
+				out.write(stringToPrint);
+				out.newLine();
+			} catch (IOException e) {
+				System.out.println(e.getMessage());
+			}
+		}
+		public void closeStream() {
+			try {
+				out.close();
+			} catch (IOException e) {
+				System.out.println(e.getMessage());
+			}
+		}
+	}
+		
+	
+	private class RunValues{
+		public double result;
+		public double executionTime;
+		
+		public double objects;
+		public double passiv;
+		public double consumer;
+		public double supplied;
+		public double producer;
+		public double unsupplied;
+		public double partiallySupplied;
+		public double overSupplied;
+
+		public double partiallyMin;
+		public double partiallyMax;
+		public double partiallyAverage;
+		public double overMin;
+		public double overMax;
+		public double overAverage;
+		
+		public double activeElements;
+		public double elements;
+		
+		public double essentialFlex;
+		public double highFlex;
+		public double mediumFlex;
+		public double lowFlex;
+		public double flexebilities;
+		
+		public double switches;
+		public double activeSwitches;
+		
+		public double holon;
+		public double consumption;
+		public double production;
+		public double difference;
+	}
+	
+	
+	private class RunAverage{
+		private int runCount = 0;
+		//Values
+		private RunValues sum = new RunValues();
+		
+		public void addRun(RunValues val) {
+			sum.result += val.result;
+			sum.executionTime += val.executionTime;
+			sum.passiv += val.passiv;
+			sum.consumer += val.consumer;
+			sum.producer += val.producer;
+			sum.unsupplied += val.unsupplied;
+			sum.partiallySupplied += val.partiallySupplied;
+			sum.overSupplied += val.overSupplied;
+			sum.activeElements += val.activeElements;
+			sum.elements += val.elements;
+			sum.essentialFlex += val.essentialFlex;
+			sum.highFlex += val.highFlex;
+			sum.mediumFlex += val.mediumFlex;
+			sum.lowFlex += val.lowFlex;
+			sum.flexebilities += val.flexebilities;
+			sum.holon += val.holon;
+			sum.switches += val.switches;
+			sum.activeSwitches += val.activeSwitches;
+			sum.consumption += val.consumption;
+			sum.production += val.production;
+			sum.difference += val.difference;
+			sum.objects += val.objects;
+			sum.supplied += val.supplied;
+			sum.partiallyMin += val.partiallyMin;
+			sum.partiallyMax += val.partiallyMax;
+			sum.partiallyAverage += val.partiallyAverage;
+			sum.overMin += val.overMin;
+			sum.overMax += val.overMax;
+			sum.overAverage += val.overAverage;
+			
+			runCount++;
+		}
+		public RunValues getAverage() {
+			RunValues avg = new RunValues();
+			if(runCount == 0) {
+				return avg;
+			}
+			avg.result = sum.result / runCount;
+			avg.executionTime = sum.executionTime / runCount;
+			avg.passiv = sum.passiv / runCount;
+			avg.consumer = sum.consumer / runCount;
+			avg.producer = sum.producer / runCount;
+			avg.unsupplied = sum.unsupplied / runCount;
+			avg.partiallySupplied = sum.partiallySupplied / runCount;
+			avg.overSupplied = sum.overSupplied / runCount;
+			avg.activeElements = sum.activeElements / runCount;
+			avg.elements = sum.elements / runCount;
+			avg.essentialFlex = sum.essentialFlex / runCount;
+			avg.highFlex = sum.highFlex / runCount;
+			avg.mediumFlex = sum.mediumFlex / runCount;
+			avg.lowFlex = sum.lowFlex / runCount;
+			avg.flexebilities = sum.flexebilities / runCount;
+			avg.holon = sum.holon / runCount;
+			avg.switches = sum.switches / runCount;
+			avg.activeSwitches = sum.activeSwitches / runCount;
+			avg.consumption = sum.consumption / runCount;
+			avg.production = sum.production / runCount;
+			avg.difference = sum.difference / runCount;
+			avg.objects = sum.objects / runCount;
+			avg.supplied = sum.supplied / runCount;
+			avg.supplied = sum.supplied / runCount;	
+			avg.partiallyMin = sum.partiallyMin / runCount;
+			avg.partiallyMax = sum.partiallyMax / runCount;
+			avg.partiallyAverage = sum.partiallyAverage / runCount;
+			avg.overMin = sum.overMin / runCount;
+			avg.overMax = sum.overMax / runCount;
+			avg.overAverage = sum.overAverage / runCount;		
+			return avg;
+		}
+	}
+	
+	
+	private enum AccessType {None, HolonElement, Switch, Flexibility, KillSwitch};
+	/**
+	 * A Wrapper Class for Access HolonElement and HolonSwitch in one Element and not have to split the List.
+	 */
+	private class AccessWrapper {
+		private AccessType type;
+		private List<Boolean> intialStatesOfElementForKilllSwitch;
+		
+		private HolonObject hObject;
+		private HolonSwitch hSwitch;
+		
+		private HolonElement hElement;
+		private Flexibility flex;
+		private AccessWrapper correspondingKillSwitch;
+		
+		private boolean lastState;
+		
+		
+		public AccessWrapper(HolonObject hObject){
+			type = AccessType.KillSwitch;
+			this.hObject = hObject;
+			intialStatesOfElementForKilllSwitch = new ArrayList<Boolean>();
+			for(HolonElement hE: hObject.getElements()) {
+				intialStatesOfElementForKilllSwitch.add(hE.isActive());
+			}
+		}
+		public AccessWrapper(HolonSwitch hSwitch){
+			type = AccessType.Switch;
+			this.hSwitch = hSwitch;
+		}
+		public AccessWrapper(HolonElement hElement, AccessWrapper correspondingKillSwitch){
+			type = AccessType.HolonElement;
+			this.hElement = hElement;
+			this.correspondingKillSwitch = correspondingKillSwitch;
+		}
+		
+		public AccessWrapper(Flexibility flex, AccessWrapper correspondingKillSwitch){
+			type = AccessType.Flexibility;
+			this.flex = flex;
+			this.correspondingKillSwitch = correspondingKillSwitch;
+		}
+		
+		public void setState(boolean state) {
+			lastState = state;
+			switch(type) {
+				case  HolonElement:
+					if(!algoUseKillSwitch || (algoUseKillSwitch && !correspondingKillSwitch.getLastState())) {
+						hElement.setActive(state);
+					}
+					break;
+				case Switch:
+					hSwitch.setManualMode(true);
+					hSwitch.setManualState(state);
+					break;
+				case Flexibility:
+					if(state && (!algoUseKillSwitch || (algoUseKillSwitch && !correspondingKillSwitch.getLastState()))) {
+						control.getSimManager().getActualFlexManager().orderFlex(flex);
+					}
+					break;
+				case KillSwitch:
+					if(state) {
+						for (HolonElement hE : hObject.getElements()) {
+							hE.setActive(false);
+						}						
+					}else {
+						for(int i = 0; i < hObject.getElements().size(); i++) {
+							hObject.getElements().get(i).setActive(intialStatesOfElementForKilllSwitch.get(i));
+						}
+					}
+					break;
+				default:
+					break;
+				
+			}
+		}
+		
+		public boolean getLastState() {
+			return lastState;
+		}
+		
+		public String typeString() {
+			switch(type) {
+				case HolonElement:
+					return "HolonElement";
+				case Switch:
+					return "Switch";
+				case Flexibility:
+					return "Flexibility";
+				case KillSwitch:
+					return "KillSwitch";
+				default:
+					return "unknown";
+			}
+		}
+		
+		public String toString() {
+			return "[" +  typeString() + "]";
+		}
+	}
+	
+	
+	
+	
+	/**
+	* To create Random and maybe switch the random generation in the future.
+	*/
+	protected static class Random{
+		private static java.util.Random random = new java.util.Random();
+		/**
+		 * True or false
+		 * @return the random boolean.
+		 */
+		public static boolean nextBoolean(){
+			return random.nextBoolean();
+		}
+		/**
+		 * Between 0.0(inclusive) and 1.0 (exclusive)
+		 * @return the random double.
+		 */
+		public static double nextDouble() {
+			return random.nextDouble();
+		}
+		
+		/**
+		 * Random Int in Range [min;max[ with UniformDistirbution
+		 * @param min
+		 * @param max
+		 * @return
+		 */
+		public static int nextIntegerInRange(int min, int max) {
+			int result = min;
+			try {
+				result = min + random.nextInt(max - min);
+			}catch(java.lang.IllegalArgumentException e){
+				System.err.println("min : " + min + " max : " + max);
+				System.err.println("max should be more then min");
+			}
+			return result;
+		}
+	}
+	
+	private   class  Handle<T>{
+		public T object;
+		Handle(T object){
+			this.object = object;
+		}
+		public String toString() {
+			return object.toString();
+		}
+	}
+	public class Individual {
+		public double fitness;
+		public  List<Boolean> position;
+		
+		public Individual(){};
+		/**
+		 *  Copy Constructor
+		 */
+		public Individual(Individual c){
+			position = c.position.stream().collect(Collectors.toList());
+			fitness = c.fitness;
+		}
+		
+		String positionToString() {
+			return position.stream().map(bool -> (bool?"1":"0")).collect(Collectors.joining());
+		}
+	}
+	
+	protected class ParameterStepping<T>{
+		boolean useThisParameter = false;
+		String paramaterName;
+		private int count = 0;
+		int stepps;
+		T stepSize;
+		T startValue;
+		Consumer<T> setter;
+		Supplier<T> getter;
+		BiFunction<Integer,T,T> multyply;
+		BiFunction<T,T,T> add;
+		ParameterStepping(Consumer<T> setter, Supplier<T> getter, BiFunction<T,T,T> add, BiFunction<Integer,T,T> multyply, T stepSize, int stepps){
+			this.setter = setter;
+			this.getter = getter;
+			this.multyply = multyply;
+			this.add = add;
+			this.stepSize = stepSize;
+			this.stepps = stepps;
+		}
+		
+		void init() {
+			startValue = getter.get();
+		}
+		
+		boolean canUpdate() {
+			return count  < stepps;
+		}
+		
+		void update(){
+			if(canUpdate()) {
+				setter.accept(add.apply(startValue, multyply.apply(count + 1, stepSize)));
+				count ++;
+			}
+		}
+		
+		void reset() {
+			setter.accept(startValue);
+			count = 0;
+		}
+	}
+	
+	
+}

+ 1289 - 1304
src/api/TopologieAlgorithmFramework.java

@@ -1,1304 +1,1289 @@
-package api;
-
-import java.awt.BorderLayout;
-import java.awt.Dimension;
-import java.awt.FlowLayout;
-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.Collections;
-import java.util.DoubleSummaryStatistics;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Locale;
-import java.util.Objects;
-import java.util.function.BiFunction;
-import java.util.function.Consumer;
-import java.util.function.Supplier;
-import java.util.stream.Collectors;
-
-import javax.swing.BorderFactory;
-import javax.swing.Box;
-import javax.swing.BoxLayout;
-import javax.swing.JButton;
-import javax.swing.JCheckBox;
-import javax.swing.JFileChooser;
-import javax.swing.JFormattedTextField;
-import javax.swing.JLabel;
-import javax.swing.JPanel;
-import javax.swing.JProgressBar;
-import javax.swing.JScrollPane;
-import javax.swing.JSeparator;
-import javax.swing.JSplitPane;
-import javax.swing.border.EmptyBorder;
-import javax.swing.text.NumberFormatter;
-
-import algorithm.objectiveFunction.TopologieObjectiveFunction;
-import classes.AbstractCanvasObject;
-import classes.Category;
-import classes.Edge;
-import classes.GroupNode;
-import classes.Flexibility;
-import classes.HolonObject;
-import classes.HolonSwitch;
-import classes.IdCounterElem;
-import classes.Node;
-import classes.HolonElement.Priority;
-import ui.controller.Control;
-import ui.controller.FlexManager.FlexState;
-import ui.model.DecoratedGroupNode;
-import ui.model.DecoratedState;
-import ui.model.Model;
-import ui.model.DecoratedHolonObject.HolonObjectState;
-import ui.model.DecoratedSwitch.SwitchState;
-import ui.model.DecoratedNetwork;
-import ui.view.Console;
-
-public abstract class TopologieAlgorithmFramework implements AddOn{
-	//Algo
-	protected int rounds = 1;
-	protected int amountOfNewCables = 20;
-	
-	
-	//Panel
-	private JPanel content = new JPanel();
-	protected Console console = new Console();
-	private JPanel borderPanel = new JPanel();
-	private HashMap<String, JPanel> panelMap = new HashMap<String, JPanel>();
-	
-	
-	
-	
-	//Settings groupNode
-	private DecoratedGroupNode dGroupNode = null;
-	
-	
-	//access
-	private ArrayList<AccessWrapper> accessWildcards = new  ArrayList<AccessWrapper>();
-	LinkedList<List<Integer>> resetChain = new LinkedList<List<Integer>>();
-	
-	
-	private HashMap<Integer, AbstractCanvasObject> accessIntToObject = new HashMap<Integer, AbstractCanvasObject>();
-	private HashMap<AbstractCanvasObject, Integer> accessObjectToInt = new HashMap<AbstractCanvasObject, Integer>();
-	private HashMap<Integer, AbstractCanvasObject> accessIntegerToWildcard = new HashMap<Integer, AbstractCanvasObject>();
-	private HashMap<AbstractCanvasObject, GroupNode> accessGroupNode = new HashMap<AbstractCanvasObject, GroupNode>(); 
-	
-	private HashSet<IndexCable> cableSet = new HashSet<IndexCable>();
-	private ArrayList<IndexCable> cableList = new ArrayList<IndexCable>();
-	private HashMap<IndexCable, Double> addedIndexCable = new HashMap<IndexCable, Double>();
-	private int countForAccessMap = 0;
-	private int amountOfExistingCables = 0;
-	private ArrayList<HolonSwitch> switchList = new ArrayList<HolonSwitch>();
-	private HashMap<HolonSwitch, GroupNode> accessSwitchGroupNode = new HashMap<HolonSwitch, GroupNode>(); 
-	private ArrayList<Edge> edgeList = new ArrayList<Edge>();
-	
-	boolean algoUseElements = false, algoUseSwitches = true, algoUseFlexes = true;
-	
-	//time
-	private long startTime;
-	
-	
-	private RunProgressBar runProgressbar = new RunProgressBar();
-	
-	
-	
-	//concurrency
-	private Thread runThread = new Thread();
-	protected boolean cancel = false;
-
-	//holeg interaction
-	protected Control  control;
-
-	
-	//printing
-	private Printer runPrinter = new Printer(plottFileName());
-	protected List<Double> runList = new LinkedList<Double>();
-
-	//Parameter
-	@SuppressWarnings("rawtypes")
-	LinkedList<ParameterStepping> parameterSteppingList= new LinkedList<ParameterStepping>();
-	protected boolean useStepping = false;
-	//SwitchButton
-	
-
-	
-	
-	public TopologieAlgorithmFramework(){
-		content.setLayout(new BorderLayout());
-		JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
-				createOptionPanel() , console);
-		splitPane.setResizeWeight(0.0);
-		content.add(splitPane, BorderLayout.CENTER);
-		content.setPreferredSize(new Dimension(1200,800));
-	}
-	
-	
-	
-	
-	
-	
-	private JPanel createOptionPanel() {
-		JPanel optionPanel = new JPanel(new BorderLayout());
-		JScrollPane scrollPane = new JScrollPane(createParameterPanel());
-		scrollPane.setBorder(BorderFactory.createTitledBorder("Parameters"));
-		optionPanel.add(scrollPane,  BorderLayout.CENTER);
-		optionPanel.add(createButtonPanel(), BorderLayout.PAGE_END);
-		return optionPanel;
-	}
-	
-	private JPanel createParameterPanel() {
-		JPanel parameterPanel = new JPanel(null);
-		parameterPanel.setPreferredSize(new Dimension(510,300));
-		borderPanel.setLayout(new BoxLayout(borderPanel, BoxLayout.PAGE_AXIS));
-		addIntParameter("Number of New Cables", amountOfNewCables, intInput -> amountOfNewCables = intInput, () -> amountOfNewCables, 0);
-		addSeperator();
-		addIntParameter("Repetitions", rounds, intInput -> rounds = intInput, () -> rounds, 1);
-		JScrollPane scrollPane = new JScrollPane(borderPanel);
-		scrollPane.setBounds(10, 0, 850, 292);
-		scrollPane.setBorder(BorderFactory.createEmptyBorder());
-		parameterPanel.add(scrollPane);	
-		
-		
-		JProgressBar progressBar = runProgressbar.getJProgressBar();
-		progressBar.setBounds(900, 35, 185, 20);
-		progressBar.setStringPainted(true);
-		parameterPanel.add(progressBar);
-		
-		JButton addCategoryButton = new JButton("Add Category");
-		addCategoryButton.setBounds(900, 65, 185, 30);
-		addCategoryButton.addActionListener(clicked -> createWildcardsCategory());
-		parameterPanel.add(addCategoryButton);
-		return parameterPanel;
-	}
-	private JPanel createButtonPanel() {
-		JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
-		
-		JButton toggleSwitchesButton =  new JButton("Toggle Switches");
-		toggleSwitchesButton.setToolTipText("Set all switches active or inactive.");
-		toggleSwitchesButton.addActionListener(actionEvent -> toggleSwitches());
-		buttonPanel.add(toggleSwitchesButton);
-		
-		
-		
-		JButton resetButton =  new JButton("Reset");
-		resetButton.setToolTipText("Resets the State to before the Algorithm has runed.");
-		resetButton.addActionListener(actionEvent -> reset());
-		buttonPanel.add(resetButton);
-		
-		JButton cancelButton =  new JButton("Cancel Run");
-		cancelButton.addActionListener(actionEvent -> cancel());
-		buttonPanel.add(cancelButton);
-		
-		JButton fitnessButton =  new JButton("Fitness");
-		fitnessButton.setToolTipText("Fitness for the current state.");
-		fitnessButton.addActionListener(actionEvent -> fitness());
-		buttonPanel.add(fitnessButton);
-		
-		JButton runButton =  new JButton("Run");
-		runButton.addActionListener(actionEvent -> {
-			if(runThread.isAlive()) {
-				return;
-			}
-			reset();
-			this.resetAllList();
-			resetChain.clear();
-			Runnable task = () -> run();
-			runThread = new Thread(task);
-			runThread.start();
-		});
-		buttonPanel.add(runButton);
-		
-		
-		
-		return buttonPanel;
-	}
-	
-	
-	
-	//ParameterImports
-	
-	private void toggleSwitches() {
-		List<HolonSwitch> allSwitchList = control.getModel().getAllSwitches();
-		if(allSwitchList.isEmpty()) return;
-		boolean set = allSwitchList.get(0).getState(control.getModel().getCurIteration());
-		allSwitchList.forEach(hSwitch -> {
-			hSwitch.setManualMode(true);
-			hSwitch.setManualState(!set);
-		});
-		updateVisual();
-	}
-
-
-
-	//addSeperator
-	protected void addSeperator() {
-		borderPanel.add(Box.createRigidArea(new Dimension(5, 5)));
-		borderPanel.add(new JSeparator());
-		borderPanel.add(Box.createRigidArea(new Dimension(5, 5)));
-	}
-
-
-	//int
-	protected void addIntParameter(String parameterName, int parameterValue, Consumer<Integer> setter, Supplier<Integer> getter) {
-		this.addIntParameter(parameterName, parameterValue, setter, getter, true, Integer.MIN_VALUE, Integer.MAX_VALUE);
-	}
-	
-	protected void addIntParameter(String parameterName, int parameterValue, Consumer<Integer> setter, Supplier<Integer> getter, int parameterMinValue) {
-		this.addIntParameter(parameterName, parameterValue, setter, getter, true, parameterMinValue, Integer.MAX_VALUE);
-	}
-	
-	protected void addIntParameter(String parameterName, int parameterValue, Consumer<Integer> setter, Supplier<Integer> getter, boolean visible, int parameterMinValue, int parameterMaxValue) {
-		JPanel singleParameterPanel = new JPanel();
-		singleParameterPanel.setLayout(new BoxLayout(singleParameterPanel, BoxLayout.LINE_AXIS));
-		singleParameterPanel.setAlignmentX(0.0f);
-		singleParameterPanel.add(new JLabel(parameterName + ": "));
-		singleParameterPanel.add(Box.createHorizontalGlue());
-		NumberFormat format = NumberFormat.getIntegerInstance();
-		format.setGroupingUsed(false);
-		format.setParseIntegerOnly(true);
-		NumberFormatter integerFormatter = new NumberFormatter(format);
-		integerFormatter.setMinimum(parameterMinValue);
-		integerFormatter.setMaximum(parameterMaxValue);
-		integerFormatter.setCommitsOnValidEdit(true);
-		JFormattedTextField singleParameterTextField = new  JFormattedTextField(integerFormatter);
-		singleParameterTextField.setValue(parameterValue);
-		String minValue = (parameterMinValue == Integer.MIN_VALUE)?"Integer.MIN_VALUE":String.valueOf(parameterMinValue);
-		String maxValue = (parameterMaxValue == Integer.MAX_VALUE)?"Integer.MAX_VALUE":String.valueOf(parameterMaxValue);
-		singleParameterTextField.setToolTipText("Only integer \u2208 [" + minValue + "," + maxValue + "]");
-		singleParameterTextField.addPropertyChangeListener(actionEvent -> setter.accept(Integer.parseInt(singleParameterTextField.getValue().toString())));
-		singleParameterTextField.setMaximumSize(new Dimension(200, 30));
-		singleParameterTextField.setPreferredSize(new Dimension(200, 30));
-		singleParameterPanel.add(singleParameterTextField);
-		
-		
-		ParameterStepping<Integer> intParameterStepping = new ParameterStepping<Integer>(setter, getter, Integer::sum , (a,b) -> a * b, 1, 1);
-		intParameterStepping.useThisParameter = false;
-		parameterSteppingList.add(intParameterStepping);
-		
-		JCheckBox useSteppingCheckBox = new JCheckBox();
-		useSteppingCheckBox.setSelected(false);
-		singleParameterPanel.add(useSteppingCheckBox);
-		
-		
-		
-		JLabel stepsLabel = new JLabel("Steps: ");
-		stepsLabel.setEnabled(false);
-		singleParameterPanel.add(stepsLabel);
-		
-		NumberFormatter stepFormatter = new NumberFormatter(format);
-		stepFormatter.setMinimum(1);
-		stepFormatter.setMaximum(Integer.MAX_VALUE);
-		stepFormatter.setCommitsOnValidEdit(true);
-		
-		
-		JFormattedTextField stepsTextField = new  JFormattedTextField(stepFormatter);
-		stepsTextField.setEnabled(false);
-		stepsTextField.setValue(1);
-		stepsTextField.setToolTipText("Only integer \u2208 [" + 1 + "," + Integer.MAX_VALUE + "]");
-		stepsTextField.addPropertyChangeListener(actionEvent -> intParameterStepping.stepps = Integer.parseInt(stepsTextField.getValue().toString()));
-		stepsTextField.setMaximumSize(new Dimension(40, 30));
-		stepsTextField.setPreferredSize(new Dimension(40, 30));
-		singleParameterPanel.add(stepsTextField);
-		
-		JLabel stepsSizeLabel = new JLabel("StepsSize: ");
-		stepsSizeLabel.setEnabled(false);
-		singleParameterPanel.add(stepsSizeLabel);
-		
-		JFormattedTextField stepsSizeTextField = new  JFormattedTextField(stepFormatter);
-		stepsSizeTextField.setEnabled(false);
-		stepsSizeTextField.setValue(1);
-		stepsSizeTextField.setToolTipText("Only integer \u2208 [" + 1 + "," + Integer.MAX_VALUE + "]");
-		stepsSizeTextField.addPropertyChangeListener(actionEvent -> intParameterStepping.stepSize = Integer.parseInt(stepsSizeTextField.getValue().toString()));
-		stepsSizeTextField.setMaximumSize(new Dimension(40, 30));
-		stepsSizeTextField.setPreferredSize(new Dimension(40, 30));
-		singleParameterPanel.add(stepsSizeTextField);
-		
-		useSteppingCheckBox.addActionListener(actionEvent -> {
-			boolean enabled = useSteppingCheckBox.isSelected();
-			intParameterStepping.useThisParameter = enabled;
-			this.useStepping = this.parameterSteppingList.stream().anyMatch(parameter -> parameter.useThisParameter);
-			stepsLabel.setEnabled(enabled);
-			stepsTextField.setEnabled(enabled);
-			stepsSizeLabel.setEnabled(enabled);
-			stepsSizeTextField.setEnabled(enabled);
-		});
-		panelMap.put(parameterName, singleParameterPanel);
-		singleParameterPanel.setVisible(visible);
-		borderPanel.add(singleParameterPanel);
-	}
-	
-	
-	//double
-	protected void addDoubleParameter(String parameterName, double parameterValue, Consumer<Double> setter, Supplier<Double> getter) {
-		this.addDoubleParameter(parameterName, parameterValue, setter, getter, true, Double.MIN_VALUE, Double.MAX_VALUE);
-	}
-	
-	
-	protected void addDoubleParameter(String parameterName, double parameterValue, Consumer<Double> setter, Supplier<Double> getter, double parameterMinValue) {
-		this.addDoubleParameter(parameterName, parameterValue, setter, getter, true, parameterMinValue, Double.MAX_VALUE);
-	}
-	
-	
-	protected void addDoubleParameter(String parameterName, double parameterValue, Consumer<Double> setter, Supplier<Double> getter, boolean visible, double parameterMinValue, double parameterMaxValue) {
-		JPanel singleParameterPanel = new JPanel();
-		singleParameterPanel.setLayout(new BoxLayout(singleParameterPanel, BoxLayout.LINE_AXIS));
-		singleParameterPanel.setAlignmentX(0.0f);
-		singleParameterPanel.add(new JLabel(parameterName + ": "));
-		singleParameterPanel.add(Box.createHorizontalGlue());
-		NumberFormat doubleFormat = NumberFormat.getNumberInstance(Locale.US);
-		doubleFormat.setMinimumFractionDigits(1);
-		doubleFormat.setMaximumFractionDigits(10);
-		doubleFormat.setRoundingMode(RoundingMode.HALF_UP);
-		NumberFormatter doubleFormatter = new NumberFormatter(doubleFormat);
-		doubleFormatter.setMinimum(parameterMinValue);
-		doubleFormatter.setMaximum(parameterMaxValue);
-		doubleFormatter.setCommitsOnValidEdit(true);
-		JFormattedTextField singleParameterTextField = new  JFormattedTextField(doubleFormatter);
-		singleParameterTextField.setValue(parameterValue);
-		String minValue = (parameterMinValue == Double.MIN_VALUE)?"Double.MIN_VALUE":String.valueOf(parameterMinValue);
-		String maxValue = (parameterMaxValue == Double.MAX_VALUE)?"Double.MAX_VALUE":String.valueOf(parameterMaxValue);
-		singleParameterTextField.setToolTipText("Only double \u2208 [" + minValue + "," + maxValue + "]");
-		singleParameterTextField.addPropertyChangeListener(actionEvent -> setter.accept(Double.parseDouble(singleParameterTextField.getValue().toString())));
-		singleParameterTextField.setMaximumSize(new Dimension(200, 30));
-		singleParameterTextField.setPreferredSize(new Dimension(200, 30));
-		singleParameterPanel.add(singleParameterTextField);
-		
-		ParameterStepping<Double> doubleParameterStepping = new ParameterStepping<Double>(setter, getter, (a,b) -> a+b , (a,b) -> a * b, 1.0, 1);
-		doubleParameterStepping.useThisParameter = false;
-		parameterSteppingList.add(doubleParameterStepping);
-		
-		JCheckBox useSteppingCheckBox = new JCheckBox();
-		useSteppingCheckBox.setSelected(false);
-		singleParameterPanel.add(useSteppingCheckBox);
-		
-		
-		
-		JLabel stepsLabel = new JLabel("Steps: ");
-		stepsLabel.setEnabled(false);
-		singleParameterPanel.add(stepsLabel);
-		NumberFormat format = NumberFormat.getIntegerInstance();
-		format.setGroupingUsed(false);
-		format.setParseIntegerOnly(true);
-		NumberFormatter integerFormatter = new NumberFormatter(format);
-		integerFormatter.setMinimum(1);
-		integerFormatter.setMaximum(Integer.MAX_VALUE);
-		integerFormatter.setCommitsOnValidEdit(true);
-	
-		
-		
-		JFormattedTextField stepsTextField = new  JFormattedTextField(integerFormatter);
-		stepsTextField.setEnabled(false);
-		stepsTextField.setValue(1);
-		stepsTextField.setToolTipText("Only integer \u2208 [" + 1 + "," + Integer.MAX_VALUE + "]");
-		stepsTextField.addPropertyChangeListener(actionEvent -> doubleParameterStepping.stepps = Integer.parseInt(stepsTextField.getValue().toString()));
-		stepsTextField.setMaximumSize(new Dimension(40, 30));
-		stepsTextField.setPreferredSize(new Dimension(40, 30));
-		singleParameterPanel.add(stepsTextField);
-		
-		JLabel stepsSizeLabel = new JLabel("StepsSize: ");
-		stepsSizeLabel.setEnabled(false);
-		singleParameterPanel.add(stepsSizeLabel);
-		
-		NumberFormatter doubleFormatterForStepping = new NumberFormatter(doubleFormat);
-		doubleFormatterForStepping.setCommitsOnValidEdit(true);
-		JFormattedTextField stepsSizeTextField = new  JFormattedTextField(doubleFormatterForStepping);
-		stepsSizeTextField.setEnabled(false);
-		stepsSizeTextField.setValue(1.0);
-		stepsSizeTextField.setToolTipText("Only double");
-		stepsSizeTextField.addPropertyChangeListener(actionEvent -> doubleParameterStepping.stepSize = Double.parseDouble(stepsSizeTextField.getValue().toString()));
-		stepsSizeTextField.setMaximumSize(new Dimension(40, 30));
-		stepsSizeTextField.setPreferredSize(new Dimension(40, 30));
-		singleParameterPanel.add(stepsSizeTextField);
-		
-		useSteppingCheckBox.addActionListener(actionEvent -> {
-			boolean enabled = useSteppingCheckBox.isSelected();
-			doubleParameterStepping.useThisParameter = enabled;
-			this.useStepping = this.parameterSteppingList.stream().anyMatch(parameter -> parameter.useThisParameter);
-			stepsLabel.setEnabled(enabled);
-			stepsTextField.setEnabled(enabled);
-			stepsSizeLabel.setEnabled(enabled);
-			stepsSizeTextField.setEnabled(enabled);
-		});
-		panelMap.put(parameterName, singleParameterPanel);
-		singleParameterPanel.setVisible(visible);
-		borderPanel.add(singleParameterPanel);
-	}
-	//boolean
-	protected void addBooleanParameter(String parameterName, boolean parameterValue, Consumer<Boolean> setter, List<String> showParameterNames, List<String> hideParameterNames){
-		JPanel singleParameterPanel = new JPanel();
-		panelMap.put(parameterName, singleParameterPanel);
-		singleParameterPanel.setLayout(new BoxLayout(singleParameterPanel, BoxLayout.LINE_AXIS));
-		singleParameterPanel.setAlignmentX(0.0f);
-		singleParameterPanel.add(new JLabel(parameterName + ": "));
-		singleParameterPanel.add(Box.createHorizontalGlue());
-		JCheckBox useGroupNodeCheckBox = new JCheckBox();
-		useGroupNodeCheckBox.addActionListener(actionEvent -> {
-			setter.accept(useGroupNodeCheckBox.isSelected());
-			showParameterNames.forEach(string -> panelMap.get(string).setVisible(useGroupNodeCheckBox.isSelected()));
-			hideParameterNames.forEach(string -> panelMap.get(string).setVisible(!useGroupNodeCheckBox.isSelected()));
-		});
-		useGroupNodeCheckBox.setSelected(parameterValue);
-		singleParameterPanel.add(useGroupNodeCheckBox);
-		borderPanel.add(singleParameterPanel);
-	}
-	
-
-	private void startTimer(){
-		startTime = System.currentTimeMillis();
-	}
-	private long printElapsedTime(){
-		long elapsedMilliSeconds = System.currentTimeMillis() - startTime;
-		console.println("Execution Time of Algo in Milliseconds:" + elapsedMilliSeconds);
-		return elapsedMilliSeconds;
-	}
-	
-	
-	
-	private void cancel() {
-		if(runThread.isAlive()) {
-			console.println("Cancel run.");
-			cancel = true;
-			runProgressbar.cancel();
-		} else {
-			console.println("Nothing to cancel.");
-		}
-	}
-	private void createWildcardsCategory() {
-		Category category = control.searchCategory("Wildcards");
-		if(category == null) {
-			try {
-				control.addCategory("Wildcards");
-			} catch (IOException e) {
-				console.println("IO Exception - Creating WIldcards Category failed.");
-				System.out.println("IO Exception - Creating WIldcards Category failed.");
-				e.printStackTrace();
-			}
-		}
-	}
-	
-	private void fitness() {
-		if(runThread.isAlive()) {
-			console.println("Run have to be cancelled First.");
-			return;
-		}
-//		reset();
-//		this.extractPositionAndAccess();
-		double currentFitness = evaluateNetworkAndPrint();
-		console.println("Actual Fitnessvalue: " + currentFitness);
-	}
-	
-	
-	protected double evaluatePosition(List<Integer> positionToEvaluate) {
-		setState(positionToEvaluate); // execution time critical
-		return evaluateNetwork();
-	}
-
-	private double evaluateNetwork() {
-		runProgressbar.step();
-		DecoratedState actualstate = control.getSimManager().getActualDecorState();
-		return evaluateState(actualstate, calculateAmountOfAddedSwitches(), addedCableMeter(), false);
-	}
-	private double evaluateNetworkAndPrint() {
-		runProgressbar.step();
-		for(HolonSwitch hSwitch: switchList) {
-			hSwitch.setManualMode(true);
-			hSwitch.setManualState(false);
-		}
-		control.calculateStateOnlyForCurrentTimeStep();
-		DecoratedState actualstate = control.getSimManager().getActualDecorState();
-		return evaluateState(actualstate, calculateAmountOfAddedSwitches(), addedCableMeter(), true);
-	}
-	
-	
-	private double addedCableMeter() {
-		return addedIndexCable.values().stream().reduce(0.0, Double::sum);
-	}
-
-	private int calculateAmountOfAddedSwitches() {
-		return (int)this.switchList.stream().filter(sw -> sw.getName().contains("AddedSwitch")).count();
-	}
-	
-	protected abstract double evaluateState(DecoratedState actualstate, int amountOfAddedSwitch, double addedCableMeter, boolean moreInfromation);
-
-	
-	private void run() {
-		cancel = false;
-		control.guiDisable(true);
-		runPrinter.openStream();
-		runPrinter.println("");
-		runPrinter.println("Start:" + stringStatFromActualState());
-		runPrinter.closeStream();
-		if(this.useStepping) {
-			initParameterStepping();
-			do {
-					executeAlgoWithParameter();
-					if(cancel) break;
-					resetState();
-			}while(updateOneParameter());
-			resetParameterStepping();
-		}else {
-			executeAlgoWithParameter();
-			
-		}
-		TopologieObjectiveFunction.log.clear();
-		updateVisual();
-		runProgressbar.finishedCancel();
-		control.guiDisable(false);
-	}
-	@SuppressWarnings("rawtypes")
-	private void initParameterStepping() {
-		for(ParameterStepping param :this.parameterSteppingList) {
-			param.init();
-		}
-		
-	}
-	@SuppressWarnings("rawtypes")
-	private void resetParameterStepping() {
-		for(ParameterStepping param :this.parameterSteppingList) {
-			param.reset();
-		}
-		
-	}
-
-
-
-
-	@SuppressWarnings("rawtypes")
-	private boolean updateOneParameter() {
-		List<ParameterStepping> parameterInUseList = this.parameterSteppingList.stream().filter(param -> param.useThisParameter).collect(Collectors.toList());
-		Collections.reverse(parameterInUseList);
-		int lastParameter = parameterInUseList.size() - 1 ;
-		int actualParameter = 0;
-		for(ParameterStepping param : parameterInUseList) {
-			
-			if(param.canUpdate()) {
-				param.update();
-				return true;
-			}else {
-				if(actualParameter == lastParameter) break;
-				param.reset();
-			}
-			actualParameter++;
-		}
-		//No Param can be updated 
-		return false;
-	}
-
-
-
-
-
-
-	private void executeAlgoWithParameter(){
-		double startFitness = evaluatePosition(extractPositionAndAccess());
-		resetChain.removeLast();
-		runPrinter.openStream();
-		runPrinter.println("");
-		runPrinter.println(algoInformationToPrint());
-		runPrinter.closeStream();
-		console.println(algoInformationToPrint());
-		runProgressbar.start();
-		Individual runBest = new Individual();
-		runBest.fitness = Double.MAX_VALUE;
-		for(int r = 0; r < rounds; r++)
-		{	
-			
-			resetState();
-			startTimer();
-			Individual  roundBest = executeAlgo();
-			if(cancel)return;
-			long executionTime = printElapsedTime();
-			setState(roundBest.position);
-			runPrinter.openStream();
-			runPrinter.println(runList.stream().map(Object::toString).collect(Collectors.joining(", ")));
-			runPrinter.println(stringStatFromActualState());
-			runPrinter.println("Result: " + roundBest.fitness + " ExecutionTime:" + executionTime);
-			runPrinter.closeStream();
-			
-			if(roundBest.fitness < runBest.fitness) runBest = roundBest;
-		}
-		
-		control.getSimManager().resetFlexManagerForTimeStep(control.getModel().getCurIteration());
-		setState(runBest.position);
-		for(HolonSwitch hSwitch: switchList) {
-			hSwitch.setManualMode(true);
-			hSwitch.setManualState(false);
-		}
-		updateVisual();
-		evaluateNetworkAndPrint();
-		console.println("Start: " + startFitness);
-		console.println("AlgoResult: " + runBest.fitness);
-	}
-	
-	
-
-
-
-
-
-
-
-	protected abstract Individual executeAlgo();
-
-
-
-
-
-
-	private void reset() {
-		if(runThread.isAlive()) {
-			console.println("Run have to be cancelled First.");
-			return;
-		}
-		if(!resetChain.isEmpty()) {
-			console.println("Resetting..");
-			setState(resetChain.getFirst());
-			resetChain.clear();
-			control.resetSimulation();
-			control.setCurIteration(0);
-			updateVisual();
-		}else {
-			console.println("No run inistialized.");
-		}
-	}
-
-
-	/**
-	 * To let the User See the current state without touching the Canvas.
-	 */
-	private void updateVisual() {
-		control.calculateStateAndVisualForCurrentTimeStep();
-	}
-	/**
-	 * Sets the Model back to its original State before the LAST run.
-	 */
-	private void resetState() {
-		if(!resetChain.isEmpty()) {
-			setState(resetChain.removeLast());			
-		}
-		resetAllList();
-	}
-
-
-	/**
-	 * Sets the State out of the given position for calculation or to show the user.
-	 * @param position
-	 */
-	private void setState(List<Integer> position) {
-		this.removeAllAddedObjects();
-		for(int i = 0; i < this.amountOfNewCables; i++) {
-			generateCable(position.get(2 * i), position.get(2 * i + 1), position.get(2 * amountOfNewCables + i) == 1);
-		}
-		//Switches new Cable
-		//Switches existing cable
-		int count = 0;
-		for(int i = 3 * amountOfNewCables; i < 3 * this.amountOfNewCables + this.amountOfExistingCables; i++) {
-			generateEdgeFromIndexCable(cableList.get(count++), position.get(i) == 1);
-		}
-		//WildCards
-		count = 0;
-		for(int i = 3 * amountOfNewCables + amountOfExistingCables; i < position.size(); i++) {
-			accessWildcards.get(count++).setState(position.get(i));
-		}
-		for(HolonSwitch hSwitch: switchList) {
-			hSwitch.setManualMode(true);
-			hSwitch.setManualState(false);
-		}
-		control.calculateStateOnlyForCurrentTimeStep();
-}
-
-
-	/**
-	 * Method to get the current Position alias a ListOf Booleans for aktive settings on the Objects on the Canvas.
-	 * Also initialize the Access Hashmap to swap faster positions.
-	 * @param model
-	 * @return
-	 */
-	protected List<Integer> extractPositionAndAccess() {
-		Model model = control.getModel();
-		
-		resetAllList();
-		Category category = control.searchCategory("Wildcards");
-		if(category != null) {
-			for(int count = 0; count < category.getObjects().size(); count++ ) {
-				accessIntegerToWildcard.put(count + 1, category.getObjects().get(count));
-			}			
-		}else {
-			console.println("No 'Wildcards' Category");
-		}
-		
-		
-		
-		List<Integer> initialState = new ArrayList<Integer>();
-		generateAccess(model.getObjectsOnCanvas(), null);			
-		addCables(model.getEdgesOnCanvas());
-		model.getEdgesOnCanvas().clear();
-		//New Cables
-		for(int i = 0; i < this.amountOfNewCables; i++) {
-			initialState.add(0);
-			initialState.add(0);
-		}
-		//switch in new Cables
-		for(int i = 0; i < this.amountOfNewCables; i++) {
-			initialState.add(0);
-		}
-		//Switch in initial Cable
-		cableSet.stream().forEach(indexCale -> initialState.add(0));
-		amountOfExistingCables = cableSet.size();
-		//wildcards
-		for(int i = 0; i < accessWildcards.size(); i++) {
-			initialState.add(0);
-		}
-		resetChain.add(initialState);
-		//console.println(accessIntToObject.values().stream().map(hO -> hO.getName()).collect(Collectors.joining(", ")));
-		//console.println(cableSet.stream().map(Object::toString).collect(Collectors.f(", ")));
-		return initialState;
-	}
-
-
-
-
-
-
-	private void resetAllList() {
-		//-->reset
-		accessWildcards.clear();
-		this.countForAccessMap = 0;
-		amountOfExistingCables = 0;
-		accessIntToObject.clear();
-		accessObjectToInt.clear();
-		cableSet.clear();
-		cableList.clear();
-		accessGroupNode.clear();
-		accessIntegerToWildcard.clear();
-		addedIndexCable.clear();
-		switchList.clear();
-		accessSwitchGroupNode.clear();
-		edgeList.clear();
-		//<---
-	}
-	
-	
-	
-	
-	/**
-	 * Method to extract the Informations recursively out of the Model.
-	 * @param nodes
-	 * @param positionToInit
-	 * @param timeStep
-	 */
-	private void generateAccess(List<AbstractCanvasObject> nodes, GroupNode groupnode) {
-		for(AbstractCanvasObject aCps : nodes) {
-			if(aCps instanceof HolonObject) {
-				HolonObject hO = (HolonObject) aCps;
-				accessIntToObject.put(++countForAccessMap, hO);
-				accessObjectToInt.put(hO, countForAccessMap);
-				if(hO.getName().contains("Wildcard")) {
-					accessWildcards.add(new AccessWrapper(hO));
-				}
-				if(groupnode != null) {
-					accessGroupNode.put(hO, groupnode);
-				}
-			}
-			if(aCps instanceof HolonSwitch) {
-				HolonSwitch hSwitch = (HolonSwitch) aCps;
-				accessIntToObject.put(++countForAccessMap, hSwitch);
-				accessObjectToInt.put(hSwitch, countForAccessMap);
-				if(groupnode != null) {
-					accessGroupNode.put(hSwitch, groupnode);
-				}
-			}
-			if(aCps instanceof Node) {
-				Node node = (Node) aCps;
-				accessIntToObject.put(++countForAccessMap, node);
-				accessObjectToInt.put(node, countForAccessMap);
-				if(groupnode != null) {
-					accessGroupNode.put(node, groupnode);
-				}
-			}
-			else if(aCps instanceof GroupNode) {
-				generateAccess(((GroupNode)aCps).getNodes(), (GroupNode) aCps);
-			}
-		}
-	}
-	
-	
-	protected void resetWildcards() {
-		this.accessWildcards.forEach(wrapper -> wrapper.resetState());
-	}
-	/**
-	 * All Nodes have to be in the access map !!
-	 * @param cables
-	 */
-	private void addCables(List<Edge> edges) {
-		
-		for (Edge edge : edges) {
-			edge.setUnlimitedCapacity(true);
-			edgeList.add(edge);
-			//console.println("Cable from " + edge.getA().getName() + " to " + edge.getB().getName());
-			if(!accessObjectToInt.containsKey(edge.getA())) {
-				console.println("Node A [" + edge.getA() + "] from Edge[" + edge + "] not exist");
-				continue;
-			} else if (!accessObjectToInt.containsKey(edge.getB())) {
-				console.println("Node B [" + edge.getB() + "]from Edge[" + edge + "] not exist");
-				continue;
-			}
-			IndexCable cable = new IndexCable(accessObjectToInt.get(edge.getA()), accessObjectToInt.get(edge.getB()));
-			boolean success = cableSet.add(cable);
-			if(success) {
-				cableList.add(cable);
-			}
-			
-		}
-	}
-	
-	
-	
-	private void generateCable(int index0, int index1, boolean switchBetween) {
-		//If cable isnt valid
-		if(index0 == 0 || index1 == 0 || index0 == index1) {
-			//console.println("Cable("+index1+","+index2+ ") isn't valid");
-			return;
-		}
-		IndexCable cable = new IndexCable(index0, index1);
-		//if cable is in existing cables
-		if(cableSet.contains(cable) || addedIndexCable.keySet().contains(cable)) {
-			return;
-		}
-		generateEdgeFromIndexCable(cable, switchBetween);
-		addedIndexCable.put(cable, cable.getLength());
-	}
-	
-	private void generateEdgeFromIndexCable(IndexCable cable, boolean switchBetween){
-		if(switchBetween) {
-			//generate Switch
-			AbstractCanvasObject fromObject =  accessIntToObject.get(cable.first);
-			AbstractCanvasObject toObject =  accessIntToObject.get(cable.second);
-			int middleX = (fromObject.getPosition().x +   toObject.getPosition().x)/2;
-			int middleY = (fromObject.getPosition().y +   toObject.getPosition().y)/2;
-			HolonSwitch newSwitch = new HolonSwitch("AddedSwitch");
-			newSwitch.setId(IdCounterElem.nextId());
-			newSwitch.setPosition(middleX, middleY);
-			//If fromObject is in Group
-			if(accessGroupNode.containsKey(fromObject)) {
-				GroupNode groupnode = accessGroupNode.get(fromObject);
-				groupnode.getNodes().add(newSwitch);
-				accessSwitchGroupNode.put(newSwitch, groupnode);
-			} else if(accessGroupNode.containsKey(toObject)) {
-				GroupNode groupnode = accessGroupNode.get(toObject);
-				groupnode.getNodes().add(newSwitch);
-				accessSwitchGroupNode.put(newSwitch, groupnode);
-			}else {
-				control.getModel().getObjectsOnCanvas().add(newSwitch);		
-			}
-			//else if toObject is in Group
-			this.switchList.add(newSwitch);
-			//Generate Cable From Object A To Switch
-			Edge edge1 = new Edge(fromObject, newSwitch);
-			edge1.setUnlimitedCapacity(true);
-			control.getModel().getEdgesOnCanvas().add(edge1);
-			edgeList.add(edge1);
-			
-			//Generate Cable From Object B To Switch
-			Edge edge = new Edge(newSwitch, toObject);
-			edge.setUnlimitedCapacity(true);
-			control.getModel().getEdgesOnCanvas().add(edge);
-			edgeList.add(edge);
-			}else {
-			Edge edge = new Edge(accessIntToObject.get(cable.first), accessIntToObject.get(cable.second));
-			edge.setUnlimitedCapacity(true);
-			control.getModel().getEdgesOnCanvas().add(edge);
-			edgeList.add(edge);
-		}
-	}
-	private void removeAllAddedObjects() {
-		control.getModel().getEdgesOnCanvas().removeAll(edgeList);
-		addedIndexCable.clear();
-		//control.getModel().getObjectsOnCanvas().removeAll(switchList);
-		for(HolonSwitch hSwitch: switchList) {
-			if(this.accessSwitchGroupNode.containsKey(hSwitch)) {
-				accessSwitchGroupNode.get(hSwitch).getNodes().remove(hSwitch);
-			}
-			else {
-				control.getModel().getObjectsOnCanvas().remove(hSwitch);
-			}
-		}
-		accessSwitchGroupNode.clear();
-		switchList.clear();
-		edgeList.clear();
-	}
-	
-	
-	private String stringStatFromActualState() {
-		if(dGroupNode != null)
-		{
-			//GetActualDecoratedGroupNode
-			dGroupNode = control.getSimManager().getActualVisualRepresentationalState().getCreatedGroupNodes().get(dGroupNode.getModel());
-			int amountOfSupplier = dGroupNode.getAmountOfSupplier();
-			int amountOfConsumer = dGroupNode.getAmountOfConsumer();
-			int amountOfPassiv = dGroupNode.getAmountOfPassiv();
-			int amountOfObjects = amountOfSupplier + amountOfConsumer + amountOfPassiv;
-			int unSuppliedConsumer = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.NOT_SUPPLIED);
-			int partiallySuppliedConsumer = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.PARTIALLY_SUPPLIED);
-			int suppliedConsumer = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.SUPPLIED);
-			int overSuppliedConsumer = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.OVER_SUPPLIED);
-			
-			
-			int activeElements = dGroupNode.getAmountOfAktiveElemntsFromHolonObjects();
-			int elements = dGroupNode.getAmountOfElemntsFromHolonObjects();
-			return	"HolonObjects["
-				+	" Producer: " + amountOfSupplier  + "/" + amountOfObjects + "("+ (float)amountOfSupplier/(float)amountOfObjects * 100 + "%)"
-				+	" Unsupplied: " + unSuppliedConsumer  + "/" + amountOfObjects + "("+ (float)unSuppliedConsumer/(float)amountOfObjects * 100 + "%)"
-				+	" PartiallySupplied: " + partiallySuppliedConsumer  + "/" + amountOfObjects + "("+ (float)partiallySuppliedConsumer/(float)amountOfObjects * 100 + "%)"
-				+	" Supplied: " + suppliedConsumer  + "/" + amountOfObjects + "("+ (float)suppliedConsumer/(float)amountOfObjects * 100 + "%)"
-				+	" Passiv: " + overSuppliedConsumer  + "/" + amountOfObjects + "("+ (float)overSuppliedConsumer/(float)amountOfObjects * 100 + "%)"
-				+  "]" + "   HolonElemnts["
-				+	" Active: " + activeElements  + "/" + elements + "("+ (float)activeElements/(float)elements * 100 + "%)"
-				+ "]";
-		}
-		DecoratedState state = control.getSimManager().getActualDecorState();
-		int amountOfSupplier = 0, amountOfConsumer = 0, amountOfPassiv = 0, unSuppliedConsumer = 0, partiallySuppliedConsumer = 0, suppliedConsumer = 0, overSuppliedConsumer = 0;
-		int activeElements = 0, amountOfelements = 0;
-		int totalConsumption = 0, totalProduction = 0;
-		for(DecoratedNetwork net : state.getNetworkList()) {
-			amountOfConsumer += net.getAmountOfConsumer();
-			amountOfSupplier += net.getAmountOfSupplier();
-			amountOfPassiv += net.getAmountOfPassiv();
-			unSuppliedConsumer += net.getAmountOfConsumerWithState(HolonObjectState.NOT_SUPPLIED);
-			partiallySuppliedConsumer += net.getAmountOfConsumerWithState(HolonObjectState.PARTIALLY_SUPPLIED);
-			suppliedConsumer += net.getAmountOfConsumerWithState(HolonObjectState.SUPPLIED);
-			overSuppliedConsumer += net.getAmountOfConsumerWithState(HolonObjectState.OVER_SUPPLIED);
-			amountOfelements += net.getAmountOfElements();
-			activeElements += net.getAmountOfActiveElements();
-			totalConsumption += net.getTotalConsumption();
-			totalProduction += net.getTotalProduction();
-		}
-		int amountOfObjects = amountOfSupplier + amountOfConsumer + amountOfPassiv;
-		int difference = Math.abs(totalProduction - totalConsumption);
-		
-		
-		
-		int amountHolons = state.getNetworkList().size();
-		int amountSwitch = state.getDecoratedSwitches().size();
-		int amountActiveSwitch = (int)state.getDecoratedSwitches().stream().filter(dswitch -> (dswitch.getState() == SwitchState.Closed)).count();
-		
-		int addedSwitches = calculateAmountOfAddedSwitches();
-		double addedCableMeters = addedCableMeter();
-		double wildcardCost = TopologieObjectiveFunction.calculateWildcardCost(state);
-		double cableCost = TopologieObjectiveFunction.calculateWildcardCost(state);
-		double switchCost = TopologieObjectiveFunction.calculateWildcardCost(state);
-		double totalCost = wildcardCost + cableCost + switchCost;
-		
-		DoubleSummaryStatistics overStat = state.getNetworkList().stream().flatMap(net -> {
-			return net.getConsumerList().stream().filter(con -> con.getState() == HolonObjectState.OVER_SUPPLIED);
-		}).mapToDouble(con -> con.getSupplyBarPercentage()).summaryStatistics();
-		
-		DoubleSummaryStatistics partiallyStat = state.getNetworkList().stream().flatMap(net -> {
-			return net.getConsumerList().stream().filter(con -> con.getState() == HolonObjectState.PARTIALLY_SUPPLIED);
-		}).mapToDouble(con -> con.getSupplyBarPercentage()).summaryStatistics();
-		
-		return	"HolonObjects["
-			+ " Passiv: " + percentage(amountOfPassiv, amountOfObjects)
-			+ " Producer: " + percentage(amountOfSupplier, amountOfObjects)
-			+ " Consumer: " + percentage(amountOfConsumer, amountOfObjects)
-			+ " Unsupplied: " + percentage(unSuppliedConsumer, amountOfConsumer)
-			+ " PartiallySupplied: " + percentage(partiallySuppliedConsumer, amountOfObjects) 
-			+ " with SupplyPercentage(Min: " + partiallyStat.getMin() 
-			+ " Max: "+ partiallyStat.getMax() 
-			+ " Average: " +partiallyStat.getAverage() +  ")"
-			+ " Supplied: " + percentage(suppliedConsumer, amountOfConsumer)
-			+ " Over: " + percentage(overSuppliedConsumer, amountOfConsumer)
-			+ " with SupplyPercentage(Min: " + overStat.getMin() 
-			+ " Max: "+ overStat.getMax() 
-			+ " Average: " + overStat.getAverage() +  ")"
-			+ "]" + "   HolonElemnts["
-			+ " Active: " + percentage(activeElements, amountOfelements)
-			+ "]" 
-			+ " activeSwitches:" + percentage(amountActiveSwitch,amountSwitch)
-			+ " Holons: " + amountHolons
-			+ " totalConsumption: " + totalConsumption
-			+ " totalProduction: " + totalProduction
-			+ " difference: " + difference
-			+ " Topologie["
-			+ " addedCableMeters:" + addedCableMeters
-			+ " addedSwitches: " + addedSwitches
-			+ " totalCost: " + totalCost + "("
-			+ " wildcardCost: " + wildcardCost
-			+ " cableCost: " + cableCost
-			+ " switchCost: " + switchCost
-			+  ")]"
-			;
-		
-	}
-	
-	
-	private String percentage(int actual, int max) {
-		return  actual  + "/" + max + "("+ (float)actual/(float)max * 100 + "%)";
-	}
-	
-
-	
-	@Override
-	public JPanel getPanel() {
-		return content;
-	}
-
-	@Override
-	public void setController(Control control) {
-		this.control = control;
-	}
-	
-	//                 | New Cable          | Switches   | Wildcards             |
-	//return index:    |  countForAccessMap | 1  		 | accessWildcards.size()|	
-	public int getMaximumIndexObjects(int index) {
-		int maximumIndex = -1;
-		//New Cables
-		if(index < 2 * amountOfNewCables) {
-			maximumIndex =  this.countForAccessMap;
-		}
-		//Switches in existing and in new Cables
-		else if (index < 3 * amountOfNewCables + this.amountOfExistingCables) {
-			maximumIndex =  1;
-		}
-		//wildcards
-		else {
-			maximumIndex =  this.accessIntegerToWildcard.size();
-		}
-		return maximumIndex;
-	}
-	
-	
-	private class RunProgressBar{
-		//progressbar
-		private JProgressBar progressBar = new JProgressBar();
-		private int count = 0;
-		private boolean isActive = false;
-		
-		public void step() {
-			if(isActive) progressBar.setValue(count++);
-		}
-		public void start() {
-			progressBar.setIndeterminate(false);
-			count = 0;
-			isActive = true;
-			progressBar.setValue(0);
-			progressBar.setMaximum(getProgressBarMaxCount());
-		}
-		public void cancel() {
-			isActive = false;
-			progressBar.setIndeterminate(true);
-		}
-		public void finishedCancel() {
-			progressBar.setIndeterminate(false);
-			progressBar.setValue(0);
-		}
-		public JProgressBar getJProgressBar(){
-			return progressBar;
-		}
-	}
-	
-	protected abstract int getProgressBarMaxCount();
-	
-	protected abstract String algoInformationToPrint();
-	protected abstract String plottFileName();
-	
-	
-	
-	public class Printer{
-		private JFileChooser fileChooser = new JFileChooser();
-		private BufferedWriter out;
-		public Printer(String filename){
-			fileChooser.setCurrentDirectory(new File(System.getProperty("user.dir")));
-			fileChooser.setSelectedFile(new File(filename));
-		}
-		public void openStream() {
-			File file = fileChooser.getSelectedFile();
-			try {
-				file.createNewFile();
-				out = new BufferedWriter(new OutputStreamWriter(
-					    new FileOutputStream(file, true), "UTF-8"));
-			} catch (IOException e) {
-				System.out.println(e.getMessage());
-			}
-		}
-		
-		
-		public void println(String stringToPrint) {
-			try {
-				out.write(stringToPrint);
-				out.newLine();
-			} catch (IOException e) {
-				System.out.println(e.getMessage());
-			}
-		}
-		public void closeStream() {
-			try {
-				out.close();
-			} catch (IOException e) {
-				System.out.println(e.getMessage());
-			}
-		}
-	}
-		
-	
-	/**
-	 * A Wrapper Class to access wildcards
-	 */
-	private class AccessWrapper {
-		int state = 0;
-		HolonObject wildcard;
-		public AccessWrapper(HolonObject wildcard) {
-			this.wildcard = wildcard;
-		}
-		
-		public void setState(int state) {
-			if(this.state !=  state) {
-				this.state = state;
-				if(state > 0) {
-					wildcard.getElements().clear();
-					HolonObject hO = (HolonObject)accessIntegerToWildcard.get(state);
-					if(hO == null) {
-						console.println("null set state(" + state + ")");
-					}else {
-						if(hO.getName().contains(":")) {
-							wildcard.setName("Wildcard" + hO.getName().substring(hO.getName().lastIndexOf(":")));
-						}else {
-							wildcard.setName("Wildcard");
-						}
-						wildcard.getElements().addAll(hO.getElements());
-						wildcard.setImage(hO.getImage());
-					}
-				}else {
-					resetState();
-				}
-			}
-		}
-		public void resetState() {
-			state = 0;
-			wildcard.setName("Wildcard");
-			wildcard.setImage("/Images/home-2.png");
-			wildcard.getElements().clear();
-		}
-		
-		public String toString() {
-			return wildcard + "have state: " + state;
-		}
-	}
-	
-	
-	
-	
-	private   class  Handle<T>{
-		public T object;
-		Handle(T object){
-			this.object = object;
-		}
-		public String toString() {
-			return object.toString();
-		}
-	}
-	public class Individual {
-		public double fitness;
-		public  List<Integer> position;
-		
-		public Individual(){};
-		/**
-		 *  Copy Constructor
-		 */
-		public Individual(Individual c){
-			position = c.position.stream().collect(Collectors.toList());
-			fitness = c.fitness;
-		}
-	}
-	
-	protected class ParameterStepping<T>{
-		boolean useThisParameter = false;
-		String paramaterName;
-		private int count = 0;
-		int stepps;
-		T stepSize;
-		T startValue;
-		Consumer<T> setter;
-		Supplier<T> getter;
-		BiFunction<Integer,T,T> multyply;
-		BiFunction<T,T,T> add;
-		ParameterStepping(Consumer<T> setter, Supplier<T> getter, BiFunction<T,T,T> add, BiFunction<Integer,T,T> multyply, T stepSize, int stepps){
-			this.setter = setter;
-			this.getter = getter;
-			this.multyply = multyply;
-			this.add = add;
-			this.stepSize = stepSize;
-			this.stepps = stepps;
-		}
-		
-		void init() {
-			startValue = getter.get();
-		}
-		
-		boolean canUpdate() {
-			return count  < stepps;
-		}
-		
-		void update(){
-			if(canUpdate()) {
-				setter.accept(add.apply(startValue, multyply.apply(count + 1, stepSize)));
-				count ++;
-			}
-		}
-		
-		void reset() {
-			setter.accept(startValue);
-			count = 0;
-		}
-	}
-	
-	
-	
-	
-	
-	public class IndexCable{
-	    public final Integer first;
-	    public final Integer second;
-
-	    public IndexCable(Integer first, Integer second) {
-	    	if(first.compareTo(second) == 0) {
-	    		throw new IllegalArgumentException("(" + first + "==" + second + ")" 
-	    							+ "Two ends of the cable are at the same Object");
-	    	} else if(first.compareTo(second) < 0) {
-	    		this.first = first;
-	    		this.second = second;	    		
-	    	}else {
-	    		this.first = second;
-	    		this.second = first;
-	    	}
-	    }
-
-	    @Override
-	    public boolean equals(Object o) {
-	        if (!(o instanceof IndexCable)) {
-	            return false;
-	        }
-	        IndexCable p = (IndexCable) o;
-	        return Objects.equals(p.first, first) && Objects.equals(p.second, second);
-	    }
-
-	    @Override
-	    public int hashCode() {
-	        return (first == null ? 0 : first.hashCode()) ^ (second == null ? 0 : second.hashCode());
-	    }
-	    @Override
-	    public String toString() {
-			return "{" + first + "," + second + "}";
-	    }
-	    public double getLength() {
-	    	return accessIntToObject.get(first).getPosition().Distance(accessIntToObject.get(second).getPosition());
-	    }
-	}
-}
+package api;
+
+import java.awt.BorderLayout;
+import java.awt.Dimension;
+import java.awt.FlowLayout;
+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.Collections;
+import java.util.DoubleSummaryStatistics;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Locale;
+import java.util.Objects;
+import java.util.function.BiFunction;
+import java.util.function.Consumer;
+import java.util.function.Supplier;
+import java.util.stream.Collectors;
+
+import javax.swing.BorderFactory;
+import javax.swing.Box;
+import javax.swing.BoxLayout;
+import javax.swing.JButton;
+import javax.swing.JCheckBox;
+import javax.swing.JFileChooser;
+import javax.swing.JFormattedTextField;
+import javax.swing.JLabel;
+import javax.swing.JPanel;
+import javax.swing.JProgressBar;
+import javax.swing.JScrollPane;
+import javax.swing.JSeparator;
+import javax.swing.JSplitPane;
+import javax.swing.text.NumberFormatter;
+
+import algorithm.objectiveFunction.TopologieObjectiveFunction;
+import classes.AbstractCanvasObject;
+import classes.Category;
+import classes.Edge;
+import classes.GroupNode;
+import classes.HolonObject;
+import classes.HolonSwitch;
+import classes.IdCounterElem;
+import classes.Node;
+import ui.controller.Control;
+import ui.model.DecoratedGroupNode;
+import ui.model.DecoratedState;
+import ui.model.Model;
+import ui.model.DecoratedHolonObject.HolonObjectState;
+import ui.model.DecoratedSwitch.SwitchState;
+import ui.model.DecoratedNetwork;
+import ui.view.Console;
+
+public abstract class TopologieAlgorithmFramework implements AddOn{
+	//Algo
+	protected int rounds = 1;
+	protected int amountOfNewCables = 20;
+	
+	
+	//Panel
+	private JPanel content = new JPanel();
+	protected Console console = new Console();
+	private JPanel borderPanel = new JPanel();
+	private HashMap<String, JPanel> panelMap = new HashMap<String, JPanel>();
+	
+	
+	
+	
+	//Settings groupNode
+	private DecoratedGroupNode dGroupNode = null;
+	
+	
+	//access
+	private ArrayList<AccessWrapper> accessWildcards = new  ArrayList<AccessWrapper>();
+	LinkedList<List<Integer>> resetChain = new LinkedList<List<Integer>>();
+	
+	
+	private HashMap<Integer, AbstractCanvasObject> accessIntToObject = new HashMap<Integer, AbstractCanvasObject>();
+	private HashMap<AbstractCanvasObject, Integer> accessObjectToInt = new HashMap<AbstractCanvasObject, Integer>();
+	private HashMap<Integer, AbstractCanvasObject> accessIntegerToWildcard = new HashMap<Integer, AbstractCanvasObject>();
+	private HashMap<AbstractCanvasObject, GroupNode> accessGroupNode = new HashMap<AbstractCanvasObject, GroupNode>(); 
+	
+	private HashSet<IndexCable> cableSet = new HashSet<IndexCable>();
+	private ArrayList<IndexCable> cableList = new ArrayList<IndexCable>();
+	private HashMap<IndexCable, Double> addedIndexCable = new HashMap<IndexCable, Double>();
+	private int countForAccessMap = 0;
+	private int amountOfExistingCables = 0;
+	private ArrayList<HolonSwitch> switchList = new ArrayList<HolonSwitch>();
+	private HashMap<HolonSwitch, GroupNode> accessSwitchGroupNode = new HashMap<HolonSwitch, GroupNode>(); 
+	private ArrayList<Edge> edgeList = new ArrayList<Edge>();
+	
+	boolean algoUseElements = false, algoUseSwitches = true, algoUseFlexes = true;
+	
+	//time
+	private long startTime;
+	
+	
+	private RunProgressBar runProgressbar = new RunProgressBar();
+	
+	
+	
+	//concurrency
+	private Thread runThread = new Thread();
+	protected boolean cancel = false;
+
+	//holeg interaction
+	protected Control  control;
+
+	
+	//printing
+	private Printer runPrinter = new Printer(plottFileName());
+	protected List<Double> runList = new LinkedList<Double>();
+
+	//Parameter
+	@SuppressWarnings("rawtypes")
+	LinkedList<ParameterStepping> parameterSteppingList= new LinkedList<ParameterStepping>();
+	protected boolean useStepping = false;
+	//SwitchButton
+	
+
+	
+	
+	public TopologieAlgorithmFramework(){
+		content.setLayout(new BorderLayout());
+		JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
+				createOptionPanel() , console);
+		splitPane.setResizeWeight(0.0);
+		content.add(splitPane, BorderLayout.CENTER);
+		content.setPreferredSize(new Dimension(1200,800));
+	}
+	
+	
+	
+	
+	
+	
+	private JPanel createOptionPanel() {
+		JPanel optionPanel = new JPanel(new BorderLayout());
+		JScrollPane scrollPane = new JScrollPane(createParameterPanel());
+		scrollPane.setBorder(BorderFactory.createTitledBorder("Parameters"));
+		optionPanel.add(scrollPane,  BorderLayout.CENTER);
+		optionPanel.add(createButtonPanel(), BorderLayout.PAGE_END);
+		return optionPanel;
+	}
+	
+	private JPanel createParameterPanel() {
+		JPanel parameterPanel = new JPanel(null);
+		parameterPanel.setPreferredSize(new Dimension(510,300));
+		borderPanel.setLayout(new BoxLayout(borderPanel, BoxLayout.PAGE_AXIS));
+		addIntParameter("Number of New Cables", amountOfNewCables, intInput -> amountOfNewCables = intInput, () -> amountOfNewCables, 0);
+		addSeperator();
+		addIntParameter("Repetitions", rounds, intInput -> rounds = intInput, () -> rounds, 1);
+		JScrollPane scrollPane = new JScrollPane(borderPanel);
+		scrollPane.setBounds(10, 0, 850, 292);
+		scrollPane.setBorder(BorderFactory.createEmptyBorder());
+		parameterPanel.add(scrollPane);	
+		
+		
+		JProgressBar progressBar = runProgressbar.getJProgressBar();
+		progressBar.setBounds(900, 35, 185, 20);
+		progressBar.setStringPainted(true);
+		parameterPanel.add(progressBar);
+		
+		JButton addCategoryButton = new JButton("Add Category");
+		addCategoryButton.setBounds(900, 65, 185, 30);
+		addCategoryButton.addActionListener(clicked -> createWildcardsCategory());
+		parameterPanel.add(addCategoryButton);
+		return parameterPanel;
+	}
+	private JPanel createButtonPanel() {
+		JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
+		
+		JButton toggleSwitchesButton =  new JButton("Toggle Switches");
+		toggleSwitchesButton.setToolTipText("Set all switches active or inactive.");
+		toggleSwitchesButton.addActionListener(actionEvent -> toggleSwitches());
+		buttonPanel.add(toggleSwitchesButton);
+		
+		
+		
+		JButton resetButton =  new JButton("Reset");
+		resetButton.setToolTipText("Resets the State to before the Algorithm has runed.");
+		resetButton.addActionListener(actionEvent -> reset());
+		buttonPanel.add(resetButton);
+		
+		JButton cancelButton =  new JButton("Cancel Run");
+		cancelButton.addActionListener(actionEvent -> cancel());
+		buttonPanel.add(cancelButton);
+		
+		JButton fitnessButton =  new JButton("Fitness");
+		fitnessButton.setToolTipText("Fitness for the current state.");
+		fitnessButton.addActionListener(actionEvent -> fitness());
+		buttonPanel.add(fitnessButton);
+		
+		JButton runButton =  new JButton("Run");
+		runButton.addActionListener(actionEvent -> {
+			if(runThread.isAlive()) {
+				return;
+			}
+			reset();
+			this.resetAllList();
+			resetChain.clear();
+			Runnable task = () -> run();
+			runThread = new Thread(task);
+			runThread.start();
+		});
+		buttonPanel.add(runButton);
+		
+		
+		
+		return buttonPanel;
+	}
+	
+	
+	
+	//ParameterImports
+	
+	private void toggleSwitches() {
+		List<HolonSwitch> allSwitchList = control.getModel().getAllSwitches();
+		if(allSwitchList.isEmpty()) return;
+		boolean set = allSwitchList.get(0).getState(control.getModel().getCurIteration());
+		allSwitchList.forEach(hSwitch -> {
+			hSwitch.setManualMode(true);
+			hSwitch.setManualState(!set);
+		});
+		updateVisual();
+	}
+
+
+
+	//addSeperator
+	protected void addSeperator() {
+		borderPanel.add(Box.createRigidArea(new Dimension(5, 5)));
+		borderPanel.add(new JSeparator());
+		borderPanel.add(Box.createRigidArea(new Dimension(5, 5)));
+	}
+
+
+	//int
+	protected void addIntParameter(String parameterName, int parameterValue, Consumer<Integer> setter, Supplier<Integer> getter) {
+		this.addIntParameter(parameterName, parameterValue, setter, getter, true, Integer.MIN_VALUE, Integer.MAX_VALUE);
+	}
+	
+	protected void addIntParameter(String parameterName, int parameterValue, Consumer<Integer> setter, Supplier<Integer> getter, int parameterMinValue) {
+		this.addIntParameter(parameterName, parameterValue, setter, getter, true, parameterMinValue, Integer.MAX_VALUE);
+	}
+	
+	protected void addIntParameter(String parameterName, int parameterValue, Consumer<Integer> setter, Supplier<Integer> getter, boolean visible, int parameterMinValue, int parameterMaxValue) {
+		JPanel singleParameterPanel = new JPanel();
+		singleParameterPanel.setLayout(new BoxLayout(singleParameterPanel, BoxLayout.LINE_AXIS));
+		singleParameterPanel.setAlignmentX(0.0f);
+		singleParameterPanel.add(new JLabel(parameterName + ": "));
+		singleParameterPanel.add(Box.createHorizontalGlue());
+		NumberFormat format = NumberFormat.getIntegerInstance();
+		format.setGroupingUsed(false);
+		format.setParseIntegerOnly(true);
+		NumberFormatter integerFormatter = new NumberFormatter(format);
+		integerFormatter.setMinimum(parameterMinValue);
+		integerFormatter.setMaximum(parameterMaxValue);
+		integerFormatter.setCommitsOnValidEdit(true);
+		JFormattedTextField singleParameterTextField = new  JFormattedTextField(integerFormatter);
+		singleParameterTextField.setValue(parameterValue);
+		String minValue = (parameterMinValue == Integer.MIN_VALUE)?"Integer.MIN_VALUE":String.valueOf(parameterMinValue);
+		String maxValue = (parameterMaxValue == Integer.MAX_VALUE)?"Integer.MAX_VALUE":String.valueOf(parameterMaxValue);
+		singleParameterTextField.setToolTipText("Only integer \u2208 [" + minValue + "," + maxValue + "]");
+		singleParameterTextField.addPropertyChangeListener(actionEvent -> setter.accept(Integer.parseInt(singleParameterTextField.getValue().toString())));
+		singleParameterTextField.setMaximumSize(new Dimension(200, 30));
+		singleParameterTextField.setPreferredSize(new Dimension(200, 30));
+		singleParameterPanel.add(singleParameterTextField);
+		
+		
+		ParameterStepping<Integer> intParameterStepping = new ParameterStepping<Integer>(setter, getter, Integer::sum , (a,b) -> a * b, 1, 1);
+		intParameterStepping.useThisParameter = false;
+		parameterSteppingList.add(intParameterStepping);
+		
+		JCheckBox useSteppingCheckBox = new JCheckBox();
+		useSteppingCheckBox.setSelected(false);
+		singleParameterPanel.add(useSteppingCheckBox);
+		
+		
+		
+		JLabel stepsLabel = new JLabel("Steps: ");
+		stepsLabel.setEnabled(false);
+		singleParameterPanel.add(stepsLabel);
+		
+		NumberFormatter stepFormatter = new NumberFormatter(format);
+		stepFormatter.setMinimum(1);
+		stepFormatter.setMaximum(Integer.MAX_VALUE);
+		stepFormatter.setCommitsOnValidEdit(true);
+		
+		
+		JFormattedTextField stepsTextField = new  JFormattedTextField(stepFormatter);
+		stepsTextField.setEnabled(false);
+		stepsTextField.setValue(1);
+		stepsTextField.setToolTipText("Only integer \u2208 [" + 1 + "," + Integer.MAX_VALUE + "]");
+		stepsTextField.addPropertyChangeListener(actionEvent -> intParameterStepping.stepps = Integer.parseInt(stepsTextField.getValue().toString()));
+		stepsTextField.setMaximumSize(new Dimension(40, 30));
+		stepsTextField.setPreferredSize(new Dimension(40, 30));
+		singleParameterPanel.add(stepsTextField);
+		
+		JLabel stepsSizeLabel = new JLabel("StepsSize: ");
+		stepsSizeLabel.setEnabled(false);
+		singleParameterPanel.add(stepsSizeLabel);
+		
+		JFormattedTextField stepsSizeTextField = new  JFormattedTextField(stepFormatter);
+		stepsSizeTextField.setEnabled(false);
+		stepsSizeTextField.setValue(1);
+		stepsSizeTextField.setToolTipText("Only integer \u2208 [" + 1 + "," + Integer.MAX_VALUE + "]");
+		stepsSizeTextField.addPropertyChangeListener(actionEvent -> intParameterStepping.stepSize = Integer.parseInt(stepsSizeTextField.getValue().toString()));
+		stepsSizeTextField.setMaximumSize(new Dimension(40, 30));
+		stepsSizeTextField.setPreferredSize(new Dimension(40, 30));
+		singleParameterPanel.add(stepsSizeTextField);
+		
+		useSteppingCheckBox.addActionListener(actionEvent -> {
+			boolean enabled = useSteppingCheckBox.isSelected();
+			intParameterStepping.useThisParameter = enabled;
+			this.useStepping = this.parameterSteppingList.stream().anyMatch(parameter -> parameter.useThisParameter);
+			stepsLabel.setEnabled(enabled);
+			stepsTextField.setEnabled(enabled);
+			stepsSizeLabel.setEnabled(enabled);
+			stepsSizeTextField.setEnabled(enabled);
+		});
+		panelMap.put(parameterName, singleParameterPanel);
+		singleParameterPanel.setVisible(visible);
+		borderPanel.add(singleParameterPanel);
+	}
+	
+	
+	//double
+	protected void addDoubleParameter(String parameterName, double parameterValue, Consumer<Double> setter, Supplier<Double> getter) {
+		this.addDoubleParameter(parameterName, parameterValue, setter, getter, true, Double.MIN_VALUE, Double.MAX_VALUE);
+	}
+	
+	
+	protected void addDoubleParameter(String parameterName, double parameterValue, Consumer<Double> setter, Supplier<Double> getter, double parameterMinValue) {
+		this.addDoubleParameter(parameterName, parameterValue, setter, getter, true, parameterMinValue, Double.MAX_VALUE);
+	}
+	
+	
+	protected void addDoubleParameter(String parameterName, double parameterValue, Consumer<Double> setter, Supplier<Double> getter, boolean visible, double parameterMinValue, double parameterMaxValue) {
+		JPanel singleParameterPanel = new JPanel();
+		singleParameterPanel.setLayout(new BoxLayout(singleParameterPanel, BoxLayout.LINE_AXIS));
+		singleParameterPanel.setAlignmentX(0.0f);
+		singleParameterPanel.add(new JLabel(parameterName + ": "));
+		singleParameterPanel.add(Box.createHorizontalGlue());
+		NumberFormat doubleFormat = NumberFormat.getNumberInstance(Locale.US);
+		doubleFormat.setMinimumFractionDigits(1);
+		doubleFormat.setMaximumFractionDigits(10);
+		doubleFormat.setRoundingMode(RoundingMode.HALF_UP);
+		NumberFormatter doubleFormatter = new NumberFormatter(doubleFormat);
+		doubleFormatter.setMinimum(parameterMinValue);
+		doubleFormatter.setMaximum(parameterMaxValue);
+		doubleFormatter.setCommitsOnValidEdit(true);
+		JFormattedTextField singleParameterTextField = new  JFormattedTextField(doubleFormatter);
+		singleParameterTextField.setValue(parameterValue);
+		String minValue = (parameterMinValue == Double.MIN_VALUE)?"Double.MIN_VALUE":String.valueOf(parameterMinValue);
+		String maxValue = (parameterMaxValue == Double.MAX_VALUE)?"Double.MAX_VALUE":String.valueOf(parameterMaxValue);
+		singleParameterTextField.setToolTipText("Only double \u2208 [" + minValue + "," + maxValue + "]");
+		singleParameterTextField.addPropertyChangeListener(actionEvent -> setter.accept(Double.parseDouble(singleParameterTextField.getValue().toString())));
+		singleParameterTextField.setMaximumSize(new Dimension(200, 30));
+		singleParameterTextField.setPreferredSize(new Dimension(200, 30));
+		singleParameterPanel.add(singleParameterTextField);
+		
+		ParameterStepping<Double> doubleParameterStepping = new ParameterStepping<Double>(setter, getter, (a,b) -> a+b , (a,b) -> a * b, 1.0, 1);
+		doubleParameterStepping.useThisParameter = false;
+		parameterSteppingList.add(doubleParameterStepping);
+		
+		JCheckBox useSteppingCheckBox = new JCheckBox();
+		useSteppingCheckBox.setSelected(false);
+		singleParameterPanel.add(useSteppingCheckBox);
+		
+		
+		
+		JLabel stepsLabel = new JLabel("Steps: ");
+		stepsLabel.setEnabled(false);
+		singleParameterPanel.add(stepsLabel);
+		NumberFormat format = NumberFormat.getIntegerInstance();
+		format.setGroupingUsed(false);
+		format.setParseIntegerOnly(true);
+		NumberFormatter integerFormatter = new NumberFormatter(format);
+		integerFormatter.setMinimum(1);
+		integerFormatter.setMaximum(Integer.MAX_VALUE);
+		integerFormatter.setCommitsOnValidEdit(true);
+	
+		
+		
+		JFormattedTextField stepsTextField = new  JFormattedTextField(integerFormatter);
+		stepsTextField.setEnabled(false);
+		stepsTextField.setValue(1);
+		stepsTextField.setToolTipText("Only integer \u2208 [" + 1 + "," + Integer.MAX_VALUE + "]");
+		stepsTextField.addPropertyChangeListener(actionEvent -> doubleParameterStepping.stepps = Integer.parseInt(stepsTextField.getValue().toString()));
+		stepsTextField.setMaximumSize(new Dimension(40, 30));
+		stepsTextField.setPreferredSize(new Dimension(40, 30));
+		singleParameterPanel.add(stepsTextField);
+		
+		JLabel stepsSizeLabel = new JLabel("StepsSize: ");
+		stepsSizeLabel.setEnabled(false);
+		singleParameterPanel.add(stepsSizeLabel);
+		
+		NumberFormatter doubleFormatterForStepping = new NumberFormatter(doubleFormat);
+		doubleFormatterForStepping.setCommitsOnValidEdit(true);
+		JFormattedTextField stepsSizeTextField = new  JFormattedTextField(doubleFormatterForStepping);
+		stepsSizeTextField.setEnabled(false);
+		stepsSizeTextField.setValue(1.0);
+		stepsSizeTextField.setToolTipText("Only double");
+		stepsSizeTextField.addPropertyChangeListener(actionEvent -> doubleParameterStepping.stepSize = Double.parseDouble(stepsSizeTextField.getValue().toString()));
+		stepsSizeTextField.setMaximumSize(new Dimension(40, 30));
+		stepsSizeTextField.setPreferredSize(new Dimension(40, 30));
+		singleParameterPanel.add(stepsSizeTextField);
+		
+		useSteppingCheckBox.addActionListener(actionEvent -> {
+			boolean enabled = useSteppingCheckBox.isSelected();
+			doubleParameterStepping.useThisParameter = enabled;
+			this.useStepping = this.parameterSteppingList.stream().anyMatch(parameter -> parameter.useThisParameter);
+			stepsLabel.setEnabled(enabled);
+			stepsTextField.setEnabled(enabled);
+			stepsSizeLabel.setEnabled(enabled);
+			stepsSizeTextField.setEnabled(enabled);
+		});
+		panelMap.put(parameterName, singleParameterPanel);
+		singleParameterPanel.setVisible(visible);
+		borderPanel.add(singleParameterPanel);
+	}
+	//boolean
+	protected void addBooleanParameter(String parameterName, boolean parameterValue, Consumer<Boolean> setter, List<String> showParameterNames, List<String> hideParameterNames){
+		JPanel singleParameterPanel = new JPanel();
+		panelMap.put(parameterName, singleParameterPanel);
+		singleParameterPanel.setLayout(new BoxLayout(singleParameterPanel, BoxLayout.LINE_AXIS));
+		singleParameterPanel.setAlignmentX(0.0f);
+		singleParameterPanel.add(new JLabel(parameterName + ": "));
+		singleParameterPanel.add(Box.createHorizontalGlue());
+		JCheckBox useGroupNodeCheckBox = new JCheckBox();
+		useGroupNodeCheckBox.addActionListener(actionEvent -> {
+			setter.accept(useGroupNodeCheckBox.isSelected());
+			showParameterNames.forEach(string -> panelMap.get(string).setVisible(useGroupNodeCheckBox.isSelected()));
+			hideParameterNames.forEach(string -> panelMap.get(string).setVisible(!useGroupNodeCheckBox.isSelected()));
+		});
+		useGroupNodeCheckBox.setSelected(parameterValue);
+		singleParameterPanel.add(useGroupNodeCheckBox);
+		borderPanel.add(singleParameterPanel);
+	}
+	
+
+	private void startTimer(){
+		startTime = System.currentTimeMillis();
+	}
+	private long printElapsedTime(){
+		long elapsedMilliSeconds = System.currentTimeMillis() - startTime;
+		console.println("Execution Time of Algo in Milliseconds:" + elapsedMilliSeconds);
+		return elapsedMilliSeconds;
+	}
+	
+	
+	
+	private void cancel() {
+		if(runThread.isAlive()) {
+			console.println("Cancel run.");
+			cancel = true;
+			runProgressbar.cancel();
+		} else {
+			console.println("Nothing to cancel.");
+		}
+	}
+	private void createWildcardsCategory() {
+		Category category = control.searchCategory("Wildcards");
+		if(category == null) {
+			try {
+				control.addCategory("Wildcards");
+			} catch (IOException e) {
+				console.println("IO Exception - Creating WIldcards Category failed.");
+				System.out.println("IO Exception - Creating WIldcards Category failed.");
+				e.printStackTrace();
+			}
+		}
+	}
+	
+	private void fitness() {
+		if(runThread.isAlive()) {
+			console.println("Run have to be cancelled First.");
+			return;
+		}
+//		reset();
+//		this.extractPositionAndAccess();
+		double currentFitness = evaluateNetworkAndPrint();
+		console.println("Actual Fitnessvalue: " + currentFitness);
+	}
+	
+	
+	protected double evaluatePosition(List<Integer> positionToEvaluate) {
+		setState(positionToEvaluate); // execution time critical
+		return evaluateNetwork();
+	}
+
+	private double evaluateNetwork() {
+		runProgressbar.step();
+		DecoratedState actualstate = control.getSimManager().getActualDecorState();
+		return evaluateState(actualstate, calculateAmountOfAddedSwitches(), addedCableMeter(), false);
+	}
+	private double evaluateNetworkAndPrint() {
+		runProgressbar.step();
+		for(HolonSwitch hSwitch: switchList) {
+			hSwitch.setManualMode(true);
+			hSwitch.setManualState(false);
+		}
+		control.calculateStateOnlyForCurrentTimeStep();
+		DecoratedState actualstate = control.getSimManager().getActualDecorState();
+		return evaluateState(actualstate, calculateAmountOfAddedSwitches(), addedCableMeter(), true);
+	}
+	
+	
+	private double addedCableMeter() {
+		return addedIndexCable.values().stream().reduce(0.0, Double::sum);
+	}
+
+	private int calculateAmountOfAddedSwitches() {
+		return (int)this.switchList.stream().filter(sw -> sw.getName().contains("AddedSwitch")).count();
+	}
+	
+	protected abstract double evaluateState(DecoratedState actualstate, int amountOfAddedSwitch, double addedCableMeter, boolean moreInfromation);
+
+	
+	private void run() {
+		cancel = false;
+		control.guiDisable(true);
+		runPrinter.openStream();
+		runPrinter.println("");
+		runPrinter.println("Start:" + stringStatFromActualState());
+		runPrinter.closeStream();
+		if(this.useStepping) {
+			initParameterStepping();
+			do {
+					executeAlgoWithParameter();
+					if(cancel) break;
+					resetState();
+			}while(updateOneParameter());
+			resetParameterStepping();
+		}else {
+			executeAlgoWithParameter();
+			
+		}
+		TopologieObjectiveFunction.log.clear();
+		updateVisual();
+		runProgressbar.finishedCancel();
+		control.guiDisable(false);
+	}
+	@SuppressWarnings("rawtypes")
+	private void initParameterStepping() {
+		for(ParameterStepping param :this.parameterSteppingList) {
+			param.init();
+		}
+		
+	}
+	@SuppressWarnings("rawtypes")
+	private void resetParameterStepping() {
+		for(ParameterStepping param :this.parameterSteppingList) {
+			param.reset();
+		}
+		
+	}
+
+
+
+
+	@SuppressWarnings("rawtypes")
+	private boolean updateOneParameter() {
+		List<ParameterStepping> parameterInUseList = this.parameterSteppingList.stream().filter(param -> param.useThisParameter).collect(Collectors.toList());
+		Collections.reverse(parameterInUseList);
+		int lastParameter = parameterInUseList.size() - 1 ;
+		int actualParameter = 0;
+		for(ParameterStepping param : parameterInUseList) {
+			
+			if(param.canUpdate()) {
+				param.update();
+				return true;
+			}else {
+				if(actualParameter == lastParameter) break;
+				param.reset();
+			}
+			actualParameter++;
+		}
+		//No Param can be updated 
+		return false;
+	}
+
+
+
+
+
+
+	private void executeAlgoWithParameter(){
+		double startFitness = evaluatePosition(extractPositionAndAccess());
+		resetChain.removeLast();
+		runPrinter.openStream();
+		runPrinter.println("");
+		runPrinter.println(algoInformationToPrint());
+		runPrinter.closeStream();
+		console.println(algoInformationToPrint());
+		runProgressbar.start();
+		Individual runBest = new Individual();
+		runBest.fitness = Double.MAX_VALUE;
+		for(int r = 0; r < rounds; r++)
+		{	
+			
+			resetState();
+			startTimer();
+			Individual  roundBest = executeAlgo();
+			if(cancel)return;
+			long executionTime = printElapsedTime();
+			setState(roundBest.position);
+			runPrinter.openStream();
+			runPrinter.println(runList.stream().map(Object::toString).collect(Collectors.joining(", ")));
+			runPrinter.println(stringStatFromActualState());
+			runPrinter.println("Result: " + roundBest.fitness + " ExecutionTime:" + executionTime);
+			runPrinter.closeStream();
+			
+			if(roundBest.fitness < runBest.fitness) runBest = roundBest;
+		}
+		
+		control.getSimManager().resetFlexManagerForTimeStep(control.getModel().getCurIteration());
+		setState(runBest.position);
+		for(HolonSwitch hSwitch: switchList) {
+			hSwitch.setManualMode(true);
+			hSwitch.setManualState(false);
+		}
+		updateVisual();
+		evaluateNetworkAndPrint();
+		console.println("Start: " + startFitness);
+		console.println("AlgoResult: " + runBest.fitness);
+	}
+	
+	
+
+
+
+
+
+
+
+	protected abstract Individual executeAlgo();
+
+
+
+
+
+
+	private void reset() {
+		if(runThread.isAlive()) {
+			console.println("Run have to be cancelled First.");
+			return;
+		}
+		if(!resetChain.isEmpty()) {
+			console.println("Resetting..");
+			setState(resetChain.getFirst());
+			resetChain.clear();
+			control.resetSimulation();
+			control.setCurIteration(0);
+			updateVisual();
+		}else {
+			console.println("No run inistialized.");
+		}
+	}
+
+
+	/**
+	 * To let the User See the current state without touching the Canvas.
+	 */
+	private void updateVisual() {
+		control.calculateStateAndVisualForCurrentTimeStep();
+	}
+	/**
+	 * Sets the Model back to its original State before the LAST run.
+	 */
+	private void resetState() {
+		if(!resetChain.isEmpty()) {
+			setState(resetChain.removeLast());			
+		}
+		resetAllList();
+	}
+
+
+	/**
+	 * Sets the State out of the given position for calculation or to show the user.
+	 * @param position
+	 */
+	private void setState(List<Integer> position) {
+		this.removeAllAddedObjects();
+		for(int i = 0; i < this.amountOfNewCables; i++) {
+			generateCable(position.get(2 * i), position.get(2 * i + 1), position.get(2 * amountOfNewCables + i) == 1);
+		}
+		//Switches new Cable
+		//Switches existing cable
+		int count = 0;
+		for(int i = 3 * amountOfNewCables; i < 3 * this.amountOfNewCables + this.amountOfExistingCables; i++) {
+			generateEdgeFromIndexCable(cableList.get(count++), position.get(i) == 1);
+		}
+		//WildCards
+		count = 0;
+		for(int i = 3 * amountOfNewCables + amountOfExistingCables; i < position.size(); i++) {
+			accessWildcards.get(count++).setState(position.get(i));
+		}
+		for(HolonSwitch hSwitch: switchList) {
+			hSwitch.setManualMode(true);
+			hSwitch.setManualState(false);
+		}
+		control.calculateStateOnlyForCurrentTimeStep();
+}
+
+
+	/**
+	 * Method to get the current Position alias a ListOf Booleans for aktive settings on the Objects on the Canvas.
+	 * Also initialize the Access Hashmap to swap faster positions.
+	 * @param model
+	 * @return
+	 */
+	protected List<Integer> extractPositionAndAccess() {
+		Model model = control.getModel();
+		
+		resetAllList();
+		Category category = control.searchCategory("Wildcards");
+		if(category != null) {
+			for(int count = 0; count < category.getObjects().size(); count++ ) {
+				accessIntegerToWildcard.put(count + 1, category.getObjects().get(count));
+			}			
+		}else {
+			console.println("No 'Wildcards' Category");
+		}
+		
+		
+		
+		List<Integer> initialState = new ArrayList<Integer>();
+		generateAccess(model.getObjectsOnCanvas(), null);			
+		addCables(model.getEdgesOnCanvas());
+		model.getEdgesOnCanvas().clear();
+		//New Cables
+		for(int i = 0; i < this.amountOfNewCables; i++) {
+			initialState.add(0);
+			initialState.add(0);
+		}
+		//switch in new Cables
+		for(int i = 0; i < this.amountOfNewCables; i++) {
+			initialState.add(0);
+		}
+		//Switch in initial Cable
+		cableSet.stream().forEach(indexCale -> initialState.add(0));
+		amountOfExistingCables = cableSet.size();
+		//wildcards
+		for(int i = 0; i < accessWildcards.size(); i++) {
+			initialState.add(0);
+		}
+		resetChain.add(initialState);
+		//console.println(accessIntToObject.values().stream().map(hO -> hO.getName()).collect(Collectors.joining(", ")));
+		//console.println(cableSet.stream().map(Object::toString).collect(Collectors.f(", ")));
+		return initialState;
+	}
+
+
+
+
+
+
+	private void resetAllList() {
+		//-->reset
+		accessWildcards.clear();
+		this.countForAccessMap = 0;
+		amountOfExistingCables = 0;
+		accessIntToObject.clear();
+		accessObjectToInt.clear();
+		cableSet.clear();
+		cableList.clear();
+		accessGroupNode.clear();
+		accessIntegerToWildcard.clear();
+		addedIndexCable.clear();
+		switchList.clear();
+		accessSwitchGroupNode.clear();
+		edgeList.clear();
+		//<---
+	}
+	
+	
+	
+	
+	/**
+	 * Method to extract the Informations recursively out of the Model.
+	 * @param nodes
+	 * @param positionToInit
+	 * @param timeStep
+	 */
+	private void generateAccess(List<AbstractCanvasObject> nodes, GroupNode groupnode) {
+		for(AbstractCanvasObject aCps : nodes) {
+			if(aCps instanceof HolonObject) {
+				HolonObject hO = (HolonObject) aCps;
+				accessIntToObject.put(++countForAccessMap, hO);
+				accessObjectToInt.put(hO, countForAccessMap);
+				if(hO.getName().contains("Wildcard")) {
+					accessWildcards.add(new AccessWrapper(hO));
+				}
+				if(groupnode != null) {
+					accessGroupNode.put(hO, groupnode);
+				}
+			}
+			if(aCps instanceof HolonSwitch) {
+				HolonSwitch hSwitch = (HolonSwitch) aCps;
+				accessIntToObject.put(++countForAccessMap, hSwitch);
+				accessObjectToInt.put(hSwitch, countForAccessMap);
+				if(groupnode != null) {
+					accessGroupNode.put(hSwitch, groupnode);
+				}
+			}
+			if(aCps instanceof Node) {
+				Node node = (Node) aCps;
+				accessIntToObject.put(++countForAccessMap, node);
+				accessObjectToInt.put(node, countForAccessMap);
+				if(groupnode != null) {
+					accessGroupNode.put(node, groupnode);
+				}
+			}
+			else if(aCps instanceof GroupNode) {
+				generateAccess(((GroupNode)aCps).getNodes(), (GroupNode) aCps);
+			}
+		}
+	}
+	
+	
+	protected void resetWildcards() {
+		this.accessWildcards.forEach(wrapper -> wrapper.resetState());
+	}
+	/**
+	 * All Nodes have to be in the access map !!
+	 * @param cables
+	 */
+	private void addCables(List<Edge> edges) {
+		
+		for (Edge edge : edges) {
+			edge.setUnlimitedCapacity(true);
+			edgeList.add(edge);
+			//console.println("Cable from " + edge.getA().getName() + " to " + edge.getB().getName());
+			if(!accessObjectToInt.containsKey(edge.getA())) {
+				console.println("Node A [" + edge.getA() + "] from Edge[" + edge + "] not exist");
+				continue;
+			} else if (!accessObjectToInt.containsKey(edge.getB())) {
+				console.println("Node B [" + edge.getB() + "]from Edge[" + edge + "] not exist");
+				continue;
+			}
+			IndexCable cable = new IndexCable(accessObjectToInt.get(edge.getA()), accessObjectToInt.get(edge.getB()));
+			boolean success = cableSet.add(cable);
+			if(success) {
+				cableList.add(cable);
+			}
+			
+		}
+	}
+	
+	
+	
+	private void generateCable(int index0, int index1, boolean switchBetween) {
+		//If cable isnt valid
+		if(index0 == 0 || index1 == 0 || index0 == index1) {
+			//console.println("Cable("+index1+","+index2+ ") isn't valid");
+			return;
+		}
+		IndexCable cable = new IndexCable(index0, index1);
+		//if cable is in existing cables
+		if(cableSet.contains(cable) || addedIndexCable.keySet().contains(cable)) {
+			return;
+		}
+		generateEdgeFromIndexCable(cable, switchBetween);
+		addedIndexCable.put(cable, cable.getLength());
+	}
+	
+	private void generateEdgeFromIndexCable(IndexCable cable, boolean switchBetween){
+		if(switchBetween) {
+			//generate Switch
+			AbstractCanvasObject fromObject =  accessIntToObject.get(cable.first);
+			AbstractCanvasObject toObject =  accessIntToObject.get(cable.second);
+			int middleX = (fromObject.getPosition().x +   toObject.getPosition().x)/2;
+			int middleY = (fromObject.getPosition().y +   toObject.getPosition().y)/2;
+			HolonSwitch newSwitch = new HolonSwitch("AddedSwitch");
+			newSwitch.setId(IdCounterElem.nextId());
+			newSwitch.setPosition(middleX, middleY);
+			//If fromObject is in Group
+			if(accessGroupNode.containsKey(fromObject)) {
+				GroupNode groupnode = accessGroupNode.get(fromObject);
+				groupnode.getNodes().add(newSwitch);
+				accessSwitchGroupNode.put(newSwitch, groupnode);
+			} else if(accessGroupNode.containsKey(toObject)) {
+				GroupNode groupnode = accessGroupNode.get(toObject);
+				groupnode.getNodes().add(newSwitch);
+				accessSwitchGroupNode.put(newSwitch, groupnode);
+			}else {
+				control.getModel().getObjectsOnCanvas().add(newSwitch);		
+			}
+			//else if toObject is in Group
+			this.switchList.add(newSwitch);
+			//Generate Cable From Object A To Switch
+			Edge edge1 = new Edge(fromObject, newSwitch);
+			edge1.setUnlimitedCapacity(true);
+			control.getModel().getEdgesOnCanvas().add(edge1);
+			edgeList.add(edge1);
+			
+			//Generate Cable From Object B To Switch
+			Edge edge = new Edge(newSwitch, toObject);
+			edge.setUnlimitedCapacity(true);
+			control.getModel().getEdgesOnCanvas().add(edge);
+			edgeList.add(edge);
+			}else {
+			Edge edge = new Edge(accessIntToObject.get(cable.first), accessIntToObject.get(cable.second));
+			edge.setUnlimitedCapacity(true);
+			control.getModel().getEdgesOnCanvas().add(edge);
+			edgeList.add(edge);
+		}
+	}
+	private void removeAllAddedObjects() {
+		control.getModel().getEdgesOnCanvas().removeAll(edgeList);
+		addedIndexCable.clear();
+		//control.getModel().getObjectsOnCanvas().removeAll(switchList);
+		for(HolonSwitch hSwitch: switchList) {
+			if(this.accessSwitchGroupNode.containsKey(hSwitch)) {
+				accessSwitchGroupNode.get(hSwitch).getNodes().remove(hSwitch);
+			}
+			else {
+				control.getModel().getObjectsOnCanvas().remove(hSwitch);
+			}
+		}
+		accessSwitchGroupNode.clear();
+		switchList.clear();
+		edgeList.clear();
+	}
+	
+	
+	private String stringStatFromActualState() {
+		if(dGroupNode != null)
+		{
+			//GetActualDecoratedGroupNode
+			dGroupNode = control.getSimManager().getActualVisualRepresentationalState().getCreatedGroupNodes().get(dGroupNode.getModel());
+			int amountOfSupplier = dGroupNode.getAmountOfSupplier();
+			int amountOfConsumer = dGroupNode.getAmountOfConsumer();
+			int amountOfPassiv = dGroupNode.getAmountOfPassiv();
+			int amountOfObjects = amountOfSupplier + amountOfConsumer + amountOfPassiv;
+			int unSuppliedConsumer = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.NOT_SUPPLIED);
+			int partiallySuppliedConsumer = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.PARTIALLY_SUPPLIED);
+			int suppliedConsumer = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.SUPPLIED);
+			int overSuppliedConsumer = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.OVER_SUPPLIED);
+			
+			
+			int activeElements = dGroupNode.getAmountOfAktiveElemntsFromHolonObjects();
+			int elements = dGroupNode.getAmountOfElemntsFromHolonObjects();
+			return	"HolonObjects["
+				+	" Producer: " + amountOfSupplier  + "/" + amountOfObjects + "("+ (float)amountOfSupplier/(float)amountOfObjects * 100 + "%)"
+				+	" Unsupplied: " + unSuppliedConsumer  + "/" + amountOfObjects + "("+ (float)unSuppliedConsumer/(float)amountOfObjects * 100 + "%)"
+				+	" PartiallySupplied: " + partiallySuppliedConsumer  + "/" + amountOfObjects + "("+ (float)partiallySuppliedConsumer/(float)amountOfObjects * 100 + "%)"
+				+	" Supplied: " + suppliedConsumer  + "/" + amountOfObjects + "("+ (float)suppliedConsumer/(float)amountOfObjects * 100 + "%)"
+				+	" Passiv: " + overSuppliedConsumer  + "/" + amountOfObjects + "("+ (float)overSuppliedConsumer/(float)amountOfObjects * 100 + "%)"
+				+  "]" + "   HolonElemnts["
+				+	" Active: " + activeElements  + "/" + elements + "("+ (float)activeElements/(float)elements * 100 + "%)"
+				+ "]";
+		}
+		DecoratedState state = control.getSimManager().getActualDecorState();
+		int amountOfSupplier = 0, amountOfConsumer = 0, amountOfPassiv = 0, unSuppliedConsumer = 0, partiallySuppliedConsumer = 0, suppliedConsumer = 0, overSuppliedConsumer = 0;
+		int activeElements = 0, amountOfelements = 0;
+		int totalConsumption = 0, totalProduction = 0;
+		for(DecoratedNetwork net : state.getNetworkList()) {
+			amountOfConsumer += net.getAmountOfConsumer();
+			amountOfSupplier += net.getAmountOfSupplier();
+			amountOfPassiv += net.getAmountOfPassiv();
+			unSuppliedConsumer += net.getAmountOfConsumerWithState(HolonObjectState.NOT_SUPPLIED);
+			partiallySuppliedConsumer += net.getAmountOfConsumerWithState(HolonObjectState.PARTIALLY_SUPPLIED);
+			suppliedConsumer += net.getAmountOfConsumerWithState(HolonObjectState.SUPPLIED);
+			overSuppliedConsumer += net.getAmountOfConsumerWithState(HolonObjectState.OVER_SUPPLIED);
+			amountOfelements += net.getAmountOfElements();
+			activeElements += net.getAmountOfActiveElements();
+			totalConsumption += net.getTotalConsumption();
+			totalProduction += net.getTotalProduction();
+		}
+		int amountOfObjects = amountOfSupplier + amountOfConsumer + amountOfPassiv;
+		int difference = Math.abs(totalProduction - totalConsumption);
+		
+		
+		
+		int amountHolons = state.getNetworkList().size();
+		int amountSwitch = state.getDecoratedSwitches().size();
+		int amountActiveSwitch = (int)state.getDecoratedSwitches().stream().filter(dswitch -> (dswitch.getState() == SwitchState.Closed)).count();
+		
+		int addedSwitches = calculateAmountOfAddedSwitches();
+		double addedCableMeters = addedCableMeter();
+		double wildcardCost = TopologieObjectiveFunction.calculateWildcardCost(state);
+		double cableCost = TopologieObjectiveFunction.calculateWildcardCost(state);
+		double switchCost = TopologieObjectiveFunction.calculateWildcardCost(state);
+		double totalCost = wildcardCost + cableCost + switchCost;
+		
+		DoubleSummaryStatistics overStat = state.getNetworkList().stream().flatMap(net -> {
+			return net.getConsumerList().stream().filter(con -> con.getState() == HolonObjectState.OVER_SUPPLIED);
+		}).mapToDouble(con -> con.getSupplyBarPercentage()).summaryStatistics();
+		
+		DoubleSummaryStatistics partiallyStat = state.getNetworkList().stream().flatMap(net -> {
+			return net.getConsumerList().stream().filter(con -> con.getState() == HolonObjectState.PARTIALLY_SUPPLIED);
+		}).mapToDouble(con -> con.getSupplyBarPercentage()).summaryStatistics();
+		
+		return	"HolonObjects["
+			+ " Passiv: " + percentage(amountOfPassiv, amountOfObjects)
+			+ " Producer: " + percentage(amountOfSupplier, amountOfObjects)
+			+ " Consumer: " + percentage(amountOfConsumer, amountOfObjects)
+			+ " Unsupplied: " + percentage(unSuppliedConsumer, amountOfConsumer)
+			+ " PartiallySupplied: " + percentage(partiallySuppliedConsumer, amountOfObjects) 
+			+ " with SupplyPercentage(Min: " + partiallyStat.getMin() 
+			+ " Max: "+ partiallyStat.getMax() 
+			+ " Average: " +partiallyStat.getAverage() +  ")"
+			+ " Supplied: " + percentage(suppliedConsumer, amountOfConsumer)
+			+ " Over: " + percentage(overSuppliedConsumer, amountOfConsumer)
+			+ " with SupplyPercentage(Min: " + overStat.getMin() 
+			+ " Max: "+ overStat.getMax() 
+			+ " Average: " + overStat.getAverage() +  ")"
+			+ "]" + "   HolonElemnts["
+			+ " Active: " + percentage(activeElements, amountOfelements)
+			+ "]" 
+			+ " activeSwitches:" + percentage(amountActiveSwitch,amountSwitch)
+			+ " Holons: " + amountHolons
+			+ " totalConsumption: " + totalConsumption
+			+ " totalProduction: " + totalProduction
+			+ " difference: " + difference
+			+ " Topologie["
+			+ " addedCableMeters:" + addedCableMeters
+			+ " addedSwitches: " + addedSwitches
+			+ " totalCost: " + totalCost + "("
+			+ " wildcardCost: " + wildcardCost
+			+ " cableCost: " + cableCost
+			+ " switchCost: " + switchCost
+			+  ")]"
+			;
+		
+	}
+	
+	
+	private String percentage(int actual, int max) {
+		return  actual  + "/" + max + "("+ (float)actual/(float)max * 100 + "%)";
+	}
+	
+
+	
+	@Override
+	public JPanel getPanel() {
+		return content;
+	}
+
+	@Override
+	public void setController(Control control) {
+		this.control = control;
+	}
+	
+	//                 | New Cable          | Switches   | Wildcards             |
+	//return index:    |  countForAccessMap | 1  		 | accessWildcards.size()|	
+	public int getMaximumIndexObjects(int index) {
+		int maximumIndex = -1;
+		//New Cables
+		if(index < 2 * amountOfNewCables) {
+			maximumIndex =  this.countForAccessMap;
+		}
+		//Switches in existing and in new Cables
+		else if (index < 3 * amountOfNewCables + this.amountOfExistingCables) {
+			maximumIndex =  1;
+		}
+		//wildcards
+		else {
+			maximumIndex =  this.accessIntegerToWildcard.size();
+		}
+		return maximumIndex;
+	}
+	
+	
+	private class RunProgressBar{
+		//progressbar
+		private JProgressBar progressBar = new JProgressBar();
+		private int count = 0;
+		private boolean isActive = false;
+		
+		public void step() {
+			if(isActive) progressBar.setValue(count++);
+		}
+		public void start() {
+			progressBar.setIndeterminate(false);
+			count = 0;
+			isActive = true;
+			progressBar.setValue(0);
+			progressBar.setMaximum(getProgressBarMaxCount());
+		}
+		public void cancel() {
+			isActive = false;
+			progressBar.setIndeterminate(true);
+		}
+		public void finishedCancel() {
+			progressBar.setIndeterminate(false);
+			progressBar.setValue(0);
+		}
+		public JProgressBar getJProgressBar(){
+			return progressBar;
+		}
+	}
+	
+	protected abstract int getProgressBarMaxCount();
+	
+	protected abstract String algoInformationToPrint();
+	protected abstract String plottFileName();
+	
+	
+	
+	public class Printer{
+		private JFileChooser fileChooser = new JFileChooser();
+		private BufferedWriter out;
+		public Printer(String filename){
+			fileChooser.setCurrentDirectory(new File(System.getProperty("user.dir")));
+			fileChooser.setSelectedFile(new File(filename));
+		}
+		public void openStream() {
+			File file = fileChooser.getSelectedFile();
+			try {
+				file.createNewFile();
+				out = new BufferedWriter(new OutputStreamWriter(
+					    new FileOutputStream(file, true), "UTF-8"));
+			} catch (IOException e) {
+				System.out.println(e.getMessage());
+			}
+		}
+		
+		
+		public void println(String stringToPrint) {
+			try {
+				out.write(stringToPrint);
+				out.newLine();
+			} catch (IOException e) {
+				System.out.println(e.getMessage());
+			}
+		}
+		public void closeStream() {
+			try {
+				out.close();
+			} catch (IOException e) {
+				System.out.println(e.getMessage());
+			}
+		}
+	}
+		
+	
+	/**
+	 * A Wrapper Class to access wildcards
+	 */
+	private class AccessWrapper {
+		int state = 0;
+		HolonObject wildcard;
+		public AccessWrapper(HolonObject wildcard) {
+			this.wildcard = wildcard;
+		}
+		
+		public void setState(int state) {
+			if(this.state !=  state) {
+				this.state = state;
+				if(state > 0) {
+					wildcard.getElements().clear();
+					HolonObject hO = (HolonObject)accessIntegerToWildcard.get(state);
+					if(hO == null) {
+						console.println("null set state(" + state + ")");
+					}else {
+						if(hO.getName().contains(":")) {
+							wildcard.setName("Wildcard" + hO.getName().substring(hO.getName().lastIndexOf(":")));
+						}else {
+							wildcard.setName("Wildcard");
+						}
+						wildcard.getElements().addAll(hO.getElements());
+						wildcard.setImage(hO.getImage());
+					}
+				}else {
+					resetState();
+				}
+			}
+		}
+		public void resetState() {
+			state = 0;
+			wildcard.setName("Wildcard");
+			wildcard.setImage("/Images/home-2.png");
+			wildcard.getElements().clear();
+		}
+		
+		public String toString() {
+			return wildcard + "have state: " + state;
+		}
+	}
+	
+	
+	public class Individual {
+		public double fitness;
+		public  List<Integer> position;
+		
+		public Individual(){};
+		/**
+		 *  Copy Constructor
+		 */
+		public Individual(Individual c){
+			position = c.position.stream().collect(Collectors.toList());
+			fitness = c.fitness;
+		}
+	}
+	
+	protected class ParameterStepping<T>{
+		boolean useThisParameter = false;
+		String paramaterName;
+		private int count = 0;
+		int stepps;
+		T stepSize;
+		T startValue;
+		Consumer<T> setter;
+		Supplier<T> getter;
+		BiFunction<Integer,T,T> multyply;
+		BiFunction<T,T,T> add;
+		ParameterStepping(Consumer<T> setter, Supplier<T> getter, BiFunction<T,T,T> add, BiFunction<Integer,T,T> multyply, T stepSize, int stepps){
+			this.setter = setter;
+			this.getter = getter;
+			this.multyply = multyply;
+			this.add = add;
+			this.stepSize = stepSize;
+			this.stepps = stepps;
+		}
+		
+		void init() {
+			startValue = getter.get();
+		}
+		
+		boolean canUpdate() {
+			return count  < stepps;
+		}
+		
+		void update(){
+			if(canUpdate()) {
+				setter.accept(add.apply(startValue, multyply.apply(count + 1, stepSize)));
+				count ++;
+			}
+		}
+		
+		void reset() {
+			setter.accept(startValue);
+			count = 0;
+		}
+	}
+	
+	
+	
+	
+	
+	public class IndexCable{
+	    public final Integer first;
+	    public final Integer second;
+
+	    public IndexCable(Integer first, Integer second) {
+	    	if(first.compareTo(second) == 0) {
+	    		throw new IllegalArgumentException("(" + first + "==" + second + ")" 
+	    							+ "Two ends of the cable are at the same Object");
+	    	} else if(first.compareTo(second) < 0) {
+	    		this.first = first;
+	    		this.second = second;	    		
+	    	}else {
+	    		this.first = second;
+	    		this.second = first;
+	    	}
+	    }
+
+	    @Override
+	    public boolean equals(Object o) {
+	        if (!(o instanceof IndexCable)) {
+	            return false;
+	        }
+	        IndexCable p = (IndexCable) o;
+	        return Objects.equals(p.first, first) && Objects.equals(p.second, second);
+	    }
+
+	    @Override
+	    public int hashCode() {
+	        return (first == null ? 0 : first.hashCode()) ^ (second == null ? 0 : second.hashCode());
+	    }
+	    @Override
+	    public String toString() {
+			return "{" + first + "," + second + "}";
+	    }
+	    public double getLength() {
+	    	return accessIntToObject.get(first).getPosition().Distance(accessIntToObject.get(second).getPosition());
+	    }
+	}
+}

+ 0 - 2
src/classes/AbstractCanvasObject.java

@@ -2,10 +2,8 @@ package classes;
 
 import com.google.gson.annotations.Expose;
 
-import java.awt.Color;
 import java.util.ArrayList;
 import java.util.HashSet;
-import java.util.List;
 import java.util.Set;
 
 /**

+ 13 - 25
src/classes/HolonBattery.java

@@ -1,10 +1,6 @@
 package classes;
-import ui.model.Model;
-
 import com.google.gson.annotations.Expose;
 
-import ui.controller.*;
-
 public class HolonBattery extends AbstractCanvasObject{
 	
 	@Expose
@@ -123,28 +119,11 @@ public class HolonBattery extends AbstractCanvasObject{
 	public String toString()
 	{
 		return "HolonBattery" + this.getId();
-		/*
-		return "HolonBattery ID:" + this.getId() + " State:" + getState().name() 
-				+ " InRatio:" + getInRatio() + " OutRatio:" + getOutRatio() 
-				+ " Akku: " + getStateOfChargeAtTimeStep(SingletonControl.getInstance().getControl().getModel().getCurIteration()) + "/" + getCapacity();
-	    */
-	}
-	public void setStateOfChargeAtTimeStep(float newStateOfCharge, int x) {
-		if(iterations != SingletonControl.getInstance().getControl().getModel().getIterations())
-		{
-			stateOfChargeLevels = new float[SingletonControl.getInstance().getControl().getModel().getIterations()];
-			iterations = SingletonControl.getInstance().getControl().getModel().getIterations();
-		}
-		
-	
+	}
+	public void setStateOfChargeAtTimeStep(float newStateOfCharge, int x) { 	
 		stateOfChargeLevels[x] = validStateOfCharge(newStateOfCharge);
 	}
 	public float getStateOfChargeAtTimeStep(int x) {
-		if(iterations != SingletonControl.getInstance().getControl().getModel().getIterations())
-		{
-			stateOfChargeLevels = new float[SingletonControl.getInstance().getControl().getModel().getIterations()];
-			iterations = SingletonControl.getInstance().getControl().getModel().getIterations();
-		}
 		if(x < 0)
 		{
 			return initialStateOfCharge;
@@ -157,6 +136,15 @@ public class HolonBattery extends AbstractCanvasObject{
 	public void setInitialStateOfCharge(float initialStateOfCharge) {
 		this.initialStateOfCharge = validStateOfCharge(initialStateOfCharge);
 	}
+	
+	public void checkBuffer(int maximumIterations){
+		if(iterations <= maximumIterations)
+		{
+			stateOfChargeLevels = new float[maximumIterations];
+			iterations = maximumIterations;
+		}
+	}
+	
 	/** Correct if a state of charge is to big or to less
 	 * @return a valid State of charge
 	 */
@@ -175,10 +163,10 @@ public class HolonBattery extends AbstractCanvasObject{
 			return stateOfChargeToValid;
 		}
 	}
-	public String getImageBattery() {
+	public String getImageBattery(int timestep) {
 		//HardCoded Image selection
 		
-		float actualStateOfCharge = getStateOfChargeAtTimeStep(SingletonControl.getInstance().getControl().getModel().getCurIteration() - 1 );
+		float actualStateOfCharge = getStateOfChargeAtTimeStep(timestep - 1 );
 		int whichOne = (int)(actualStateOfCharge/capacity * 4);
 		String battery = "/Images/battery"+ whichOne + ".png";
 		setImage(battery);

+ 0 - 2
src/classes/HolonElement.java

@@ -5,8 +5,6 @@ import com.google.gson.annotations.Expose;
 import interfaces.GraphEditable;
 import interfaces.LocalMode;
 import ui.controller.FlexManager;
-import ui.controller.SingletonControl;
-import ui.model.Model;
 import ui.view.IndexTranslator;
 
 import java.awt.*;

+ 0 - 1
src/classes/HolonObject.java

@@ -1,6 +1,5 @@
 package classes;
 
-import com.google.gson.annotations.Expose;
 
 import ui.controller.FlexManager;
 

+ 0 - 2
src/classes/HolonSwitch.java

@@ -9,9 +9,7 @@ import java.util.ListIterator;
 import com.google.gson.annotations.Expose;
 import interfaces.GraphEditable;
 import interfaces.LocalMode;
-import ui.controller.SingletonControl;
 import ui.view.IndexTranslator;
-import ui.view.UnitGraph;
 
 /**
  * The class HolonSwitch represents a Switch, which can be turned on and off.

+ 1 - 0
src/classes/IdCounter.java

@@ -3,6 +3,7 @@ package classes;
 import com.google.gson.annotations.Expose;
 
 /**
+ * Static counter
  * ID-Counter for all Cps Objects.
  * 
  * @author Gruppe14

+ 8 - 4
src/classes/Pair.java

@@ -3,7 +3,9 @@ package classes;
 import java.io.Serializable;
 
 public class Pair<K, V> implements Serializable {
-
+	private static final long serialVersionUID = 111222333444555666L;
+	
+	
 	private K key;
 	private V value;
 
@@ -32,10 +34,12 @@ public class Pair<K, V> implements Serializable {
 
 	@Override
 	public boolean equals(Object o) {
-		if (this == o)
-			return true;
+		if (this == o) {
+			return true;			
+		}
+		
 		if (o instanceof Pair) {
-			Pair pair = (Pair) o;
+			Pair<?, ?> pair = (Pair<?, ?>) o;
 			if (key != null ? !key.equals(pair.key) : pair.key != null)
 				return false;
 			if (value != null ? !value.equals(pair.value) : pair.value != null)

+ 0 - 105
src/classes/SubNet.java

@@ -1,105 +0,0 @@
-package classes;
-
-import java.util.ArrayList;
-
-/**
- * The class "subNet" represents ....
- * 
- * @author Gruppe14
- *
- */
-public class SubNet {
-	private ArrayList<HolonObject> subNetObjects;
-	private ArrayList<Edge> subNetEdges;
-	private ArrayList<HolonSwitch> subNetSwitches;
-	private ArrayList<HolonBattery> subNetBatteries;
-	/**
-	 * Constructor for a Subnet.
-	 * 
-	 * @param objects
-	 *            Objects in the Subnet
-	 * @param edges
-	 *            Edges in the Subnet
-	 * @param switches
-	 *            Switches in the Subnet
-	 */
-	public SubNet(ArrayList<HolonObject> objects, ArrayList<Edge> edges, ArrayList<HolonSwitch> switches, ArrayList<HolonBattery> batteries) {
-		subNetObjects = objects;
-		subNetEdges = edges;
-		subNetSwitches = switches;
-		subNetBatteries = batteries;
-	}
-
-	/**
-	 * Return all Objects in the Subnet.
-	 * 
-	 * @return all Objects in the Subnet
-	 */
-	public ArrayList<HolonObject> getObjects() {
-		return subNetObjects;
-	}
-	/**
-	 * Return all Edges in the Subnet.
-	 * 
-	 * @return all Edges in the Subnet
-	 */
-	public ArrayList<Edge> getEdges() {
-		return subNetEdges;
-	}
-
-	/**
-	 * Return all Switches in the Subnet.
-	 * 
-	 * @return all Switches in the Subnet
-	 */
-	public ArrayList<HolonSwitch> getSwitches() {
-		return subNetSwitches;
-	}
-	public ArrayList<HolonBattery> getBatteries() {
-		return subNetBatteries;
-	}
-
-    public String toString(int timeStep) {
-        StringBuilder sb = new StringBuilder();
-
-        sb.append("  Objects:");
-        for (int j = 0; j < getObjects().size(); j++) {
-            HolonObject hl = getObjects().get(j);
-            sb.append("    " + hl.getName() + " " + hl.getId());
-        }
-        sb.append("  Edges:");
-        for (int j = 0; j < getEdges().size(); j++) {
-            Edge edge = getEdges().get(j);
-            sb.append("     " + edge.getA().getName() + " connected To " + edge.getB().getName());
-        }
-        sb.append("  Switches:");
-        for (int j = 0; j < getSwitches().size(); j++) {
-            HolonSwitch sw = getSwitches().get(j);
-            sb.append("    " + sw.getName() + " " + sw.getId() + " State:" + sw.getState(timeStep));
-        }
-
-        return sb.toString();
-    }
-
-    public String toString() {
-        StringBuilder sb = new StringBuilder();
-
-        sb.append("\nObjects:");
-        for (HolonObject hl: getObjects()) {
-            sb.append("    " + hl.getName() + "[ID:" + hl.getId()+ "]");
-        }
-        sb.append("\nEdges:");
-        for (Edge edge :getEdges()) {
-            sb.append("     " + edge.getA().getName() + " connected To " + edge.getB().getName());
-        }
-        sb.append("\nSwitches:");
-        for (HolonSwitch sw : getSwitches()) {
-            sb.append("    " + sw.getName() + "[ID:" + sw.getId()+ "]");
-        }
-        sb.append("\nBatteries:");
-        for (HolonBattery hB: getBatteries()) {
-            sb.append("    " + hB.getName() + "[ID:" + hB.getId()+ "]");
-        }
-        return sb.toString();
-    }
-}

+ 0 - 105
src/classes/TrackedDataSet.java

@@ -1,105 +0,0 @@
-package classes;
-
-import com.google.gson.annotations.Expose;
-
-import ui.controller.SingletonControl;
-
-import java.awt.*;
-
-public class TrackedDataSet {
-
-	//Property Integers
-	public static final int CONSUMPTION = 0;
-	public static final int PRODUCTION = 1;
-	public static final int ACTIVATED_ELEMENTS = 2;
-	public static final int ON_OFF = 3;
-	public static final int TOTAL_PRODUCTION = 4;
-	public static final int TOTAL_CONSUMPTION = 5;
-	public static final int PERCENT_SUPPLIED = 6;
-	public static final int PERCENT_NOT_SUPPLIED = 7;
-	public static final int PERCENT_PARTIAL_SUPPLIED = 8;
-	public static final int GROUP_PRODUCTION = 9;
-	public static final int GROUP_CONSUMPTION = 10;
-	public static final int AMOUNT_HOLONS = 11;
-	public static final int AMOUNT_CLOSED_SWITCHES = 12;
-	public static final int AVG_AMOUNT_OBJECTS_IN_HOLONS = 13;
-	public static final int AVG_AMOUNT_ELEMENTS_IN_HOLONS = 14;
-	public static final int AVG_AMOUNT_PRODUCERS_IN_HOLONS = 15;
-	public static final int AVG_CONSUMED_ENERGY_IN_HOLONS = 16;
-	public static final int AVG_WASTED_ENERGY_IN_HOLONS = 17;
-	public static final int AMOUNT_BROKEN_EDGES = 18;
-	public static final int RATIO_PRODUCERS_CONSUMERS = 19;
-	public static final int AVG_AMOUNT_CLOSED_SWITCHES_IN_HOLONS = 20;
-	public static final int AVG_AMOUNT_ACTIVE_ELEMENTS_IN_HOLONS = 21;
-	public static final int AVG_AMOUNT_INACTIVE_ELEMENTS_IN_HOLONS = 22;
-	public static final int AVG_PRODUCED_ENERGY_IN_HOLONS = 23;
-	public static final int WASTED_ENERGY = 24;
-	
-	//Variables of the Data Set
-	private AbstractCanvasObject cps;
-	@Expose
-	private int property;
-	@Expose
-	private Color color;
-
-	//Value for each timeStep
-	
-	private float values[];
-	
-	/**
-	 * Data Set for the StatisticGraoh
-	 * 
-	 * @param cps
-	 *            the cps Object
-	 * @param property
-	 *            which value should be tracked
-	 * @param color
-	 *            color of the line in the graph
-	 * @param timeStep
-	 * 			  The time steps at the moment this object is created
-	 */
-	public TrackedDataSet(AbstractCanvasObject cps, int property, Color color, int timeSteps) {
-		this.cps = cps;
-		this.property = property;
-		this.color = color;
-		this.values = new float[timeSteps];
-		resetValues();
-	}
-
-	public AbstractCanvasObject getCpsObject() {
-		return this.cps;
-	}
-
-	public int getProperty() {
-		return this.property;
-	}
-
-	public Color getColor() {
-		return this.color;
-	}
-	
-	public float[] getValues() {
-		return this.values;
-	}
-	
-	public void setValAt(float val, int at){
-		this.values[at] = val;
-	}
-	
-	/**
-	 * Resets all values.
-	 */
-	public void resetValues(){
-		for (int i = 0; i < values.length; i++) {
-			values[i] = -1;
-		}
-	}
-
-	public void updateIterations() {
-		float[] tmp=new float[
-		                      SingletonControl.getInstance().getControl().getModel().getIterations()
-		                     ];
-		for(int i=0;i<tmp.length;i++)tmp[i]=(i<values.length)?values[i]:-1;
-		values=tmp;
-	}
-}

+ 0 - 19
src/interfaces/CategoryListener.java

@@ -1,19 +0,0 @@
-package interfaces;
-
-import java.util.ArrayList;
-
-/**
- * Listener for Categories.
- * 
- * @author Gruppe14
- */
-public interface CategoryListener {
-
-	/**
-	 * Constructor.
-	 * 
-	 * @param categories
-	 *            AbstractCpsObject
-	 */
-	public void onChange(ArrayList<classes.Category> categories);
-}

+ 3 - 23
src/ui/controller/CanvasController.java

@@ -1,7 +1,6 @@
 package ui.controller;
 
 import java.awt.Point;
-import java.util.ArrayDeque;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.ListIterator;
@@ -238,13 +237,14 @@ public class CanvasController {
 					AbstractCanvasObject b = tempList.get(model.getClipboradObjects().indexOf(e.getB()));
 					// was this Edge created or not?
 					for (Edge et : tempList.get(model.getClipboradObjects().indexOf(cps)).getConnectedTo()) {
+						//TODO Changed et to etA is this right?
 						for (Edge etA : et.getA().getConnectedTo()) {
-							if (et.getA() == a && et.getB() == b) {
+							if (etA.getA() == a && etA.getB() == b) {
 								newEdge = false;
 							}
 						}
 						for (Edge etB : et.getB().getConnectedTo()) {
-							if (et.getA() == a && et.getB() == b) {
+							if (etB.getA() == a && etB.getB() == b) {
 								newEdge = false;
 							}
 						}
@@ -306,26 +306,6 @@ public class CanvasController {
 	}
 	
 	
-	/**
-	 * Deletes all Connections to Objects inside the to deleting UpperNode
-	 * 
-	 * @param obj
-	 */
-	private void deleteConnections(AbstractCanvasObject obj) {
-
-		ArrayDeque<Edge> queue = new ArrayDeque<>();
-		Edge e = null;
-
-		for (Edge edge : obj.getConnections()) {
-			queue.add(edge);
-		}
-		while (!queue.isEmpty()) {
-			e = queue.pop();
-			e.getA().getConnections().remove(e);
-			e.getB().getConnections().remove(e);
-		}
-
-	}
 	
 	/**
 	 * Set the Background Image;

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

@@ -8,9 +8,7 @@ import classes.AbstractCanvasObject;
 import classes.HolonElement;
 import classes.HolonObject;
 import classes.HolonSwitch;
-import classes.HolonTransformer;
 import classes.Pair;
-import interfaces.CategoryListener;
 import ui.model.Model;
 
 /**
@@ -67,7 +65,6 @@ public class CategoryController {
 		}
 		model.getCgIdx().put(category.getName(), model.getCategories().size());
 		model.getCategories().add(category);
-		notifyCatListeners();
 	}
 
 	/**
@@ -92,7 +89,6 @@ public class CategoryController {
 		model.getCgIdx().remove(c.getName());
 		model.getCategories().remove(c);
 
-		notifyCatListeners();
 	}
 	
 	/**
@@ -144,7 +140,6 @@ public class CategoryController {
 		}
 		category.getObjIdx().put(object.getObjName(), category.getObjects().size());
 		category.getObjects().add(object);
-		notifyCatListeners();
 	}
 
 	/**
@@ -220,7 +215,6 @@ public class CategoryController {
 		category.getObjIdx().remove(cps.getObjName());
 		category.getObjects().remove(cps);
 
-		notifyCatListeners();
 	}
 
 	/**
@@ -236,24 +230,4 @@ public class CategoryController {
 		removeObject(cat, mpC.searchCatObj(cat, obj));
 	}
 
-	/**
-	 * Init the CategoryListener.
-	 * 
-	 * @param catLis
-	 *            the CategoryListener
-	 */
-	public void addCategoryListener(CategoryListener catLis) {
-		model.getCategoryListeners().add(catLis);
-	}
-
-	/**
-	 * notifies all listeners about changes in the Categories.
-	 */
-	public void notifyCatListeners() {
-		ArrayList<Category> categories =  model.getCategories();
-		for (CategoryListener l : model.getCategoryListeners()) {
-			l.onChange(categories);
-		}
-	}
-
 }

+ 18 - 136
src/ui/controller/Control.java

@@ -1,32 +1,29 @@
 package ui.controller;
+import java.awt.Point;
+import java.awt.datatransfer.UnsupportedFlavorException;
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.stream.Collectors;
 
-import api.CpsAlgorithm;
-import classes.*;
-
-import com.google.gson.JsonParseException;
-
-import interfaces.CategoryListener;
+import javax.swing.JFrame;
 
 import org.apache.commons.compress.archivers.ArchiveException;
 
+import com.google.gson.JsonParseException;
+
+import classes.AbstractCanvasObject;
+import classes.Category;
+import classes.Edge;
+import classes.GroupNode;
+import classes.HolonBattery;
+import classes.HolonElement;
+import classes.HolonObject;
+import classes.Node;
 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.*;
-import java.awt.datatransfer.UnsupportedFlavorException;
-import java.io.File;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Hashtable;
-import java.util.stream.Collectors;
-
-import javax.swing.JFrame;
 
 /**
  * The Class represents the controller in the model, controller view Pattern.
@@ -43,7 +40,6 @@ public class Control {
     private final SaveController saveController;
     private final LoadController loadController;
     private final AutoSaveController autoSaveController;
-    private final StatsController statsController;
     private final NodeController nodeController;
     private final ClipboardController clipboardController;
     private final HolonCanvasController holonCanvasController;
@@ -75,7 +71,6 @@ public class Control {
                 nodeController, multiPurposeController);
         this.simulationManager = new SimulationManager(model);
         this.autoSaveController = new AutoSaveController(model);
-        this.statsController = new StatsController(model);
         this.clipboardController = new ClipboardController(model, saveController, loadController, canvasController,
                 objectController, nodeController, multiPurposeController);
         this.holonCanvasController = new HolonCanvasController(model);
@@ -441,18 +436,6 @@ public class Control {
             e.printStackTrace();
         }
     }
-
-	/* Global Operations */
-
-    /**
-     * Add a SubNetColor.
-     *
-     * @param c the Color
-     */
-    public void addSubNetColor(Color c) {
-        globalController.addSubNetColor(c);
-    }
-
     /**
      * Returns SCALE.
      *
@@ -532,15 +515,6 @@ public class Control {
         }
     }
 
-    /**
-     * Init the CategoryListener.
-     *
-     * @param catLis the CategoryListener
-     */
-    public void initListener(CategoryListener catLis) {
-        categoryController.addCategoryListener(catLis);
-    }
-
     /**
      * calculates the flow of the edges and the supply for objects for the
      * current Timestep.
@@ -569,7 +543,6 @@ public class Control {
      * to the default "is working" state
      */
     public void resetSimulation() {
-      setIsSimRunning(false);
       simulationManager.resetFlexManager();
     }
 
@@ -716,51 +689,8 @@ public class Control {
         globalController.setMaxCapacity(cap);
     }
 
-    /**
-     * Set the Algorithm.
-     *
-     * @param obj the Algorithm
-     */
-    public void setAlgorithm(Object obj) {
-        multiPurposeController.setAlgorithm(obj);
-    }
-
-    /**
-     * Run the Algorithm.
-     */
-    public void runAlgorithm(Model model, Control controller) {
-        if (model.getAlgorithm() != null) {
-            ((CpsAlgorithm) model.getAlgorithm()).runAlgorithm(model, controller);
-        }
-    }
-
-    // ========================= MANAGING TRACKED OBJECTS ====================
-
-    public ArrayList<AbstractCanvasObject> getTrackingObj() {
-        return statsController.getTrackingObj();
-    }
-
-    public void setTrackingObj(ArrayList<AbstractCanvasObject> objArr) {
-        statsController.setTrackingObj(objArr);
-    }
+   
 
-    public void addTrackingObj(AbstractCanvasObject obj) {
-        statsController.addTrackingObj(obj);
-        try {
-            autoSave();
-        } catch (IOException e) {
-            e.printStackTrace();
-        }
-    }
-
-    public void removeTrackingObj(AbstractCanvasObject obj) {
-        statsController.removeTrackingObj(obj);
-        try {
-            autoSave();
-        } catch (IOException e) {
-            e.printStackTrace();
-        }
-    }
 
     // ========================== MANAGING TRACKED OBJECTS END ================
 
@@ -847,34 +777,6 @@ public class Control {
         return objectController.getAllHolonObjects(list);
     }
 
-
-    /**
-     * Returns HolonBodySCALE.
-     *
-     * @return SCALE
-     */
-    public int getHolonBodyScale() {
-        return globalController.getHolonBodyScale();
-    }
-
-    /**
-     * Changes the value of HolonBodySCALE
-     *
-     * @param s HolonBodyScale
-     */
-    public void setHolonBodyScale(int s) {
-        globalController.setHolonBodyScale(s);
-    }
-
-    /**
-     * Sets the ID of the selected HolonBody
-     *
-     * @param i ID of the selected HolonBody
-     */
-    public void addSelectedHolonBody(int i) {
-        objectController.addSelectedHolonBody(i);
-    }
-
     /**
      * Copy all Selected Objects.
      */
@@ -947,26 +849,6 @@ public class Control {
         canvasController.setBackgroundImage(imagePath, mode, width, height);
     }
 
-    public void setFlexiblePane(FlexiblePane fp) {
-        simulationManager.setFlexiblePane(fp);
-    }
-
-    public Hashtable<String, StatisticGraphPanel> getGraphTable() {
-        return model.getGraphTable();
-    }
-
-    public void setGraphTable(Hashtable<String, StatisticGraphPanel> gT) {
-        model.setGraphTable(gT);
-    }
-
-    /**
-     * Sets if the Simulation is running
-     */
-    public void setIsSimRunning(boolean isRunning) {
-        globalController.setIsSimRunning(isRunning);
-    }
-
-
     /**
      * Sets show
      * @param showSupplyBars wether the bars should be shown

+ 0 - 44
src/ui/controller/GlobalController.java

@@ -1,10 +1,7 @@
 package ui.controller;
 
-import java.awt.Color;
-
 import ui.model.Model;
 import ui.model.Model.FairnessModel;
-import ui.view.StatisticGraphPanel;
 
 /**
  * Controller for the Global Variables.
@@ -111,53 +108,12 @@ public class GlobalController {
 		model.setCanvasY(canvasY);
 	}
 	
-	/**
-	 * Add a SubNetColor.
-	 * 
-	 * @param c
-	 *            the Color
-	 */
-	public void addSubNetColor(Color c) {
-		model.addSubNetColor(c);
-	}
 	
 	
 	public void setMaxCapacity(float cap) {
 		model.setMaxCapacity(cap);
 	}
 
-	/**
-	 * Changes the value of HolonBodySCALE 
-	 * 
-	 * @param s
-	 *            HolonBodyScale
-	 */
-	public void setHolonBodyScale(int s) {
-		model.setHolonBodyScale(s);
-	}
-
-	/**
-	 * Returns HolonBodySCALE.
-	 * 
-	 * @return HolonBodySCALE
-	 */
-	public int getHolonBodyScale() {
-		return model.getHolonBodyScale();
-	}
-	
-	/**
-	 * Sets if the Simulation is running
-	 */
-	public void setIsSimRunning(boolean isRunning){
-		model.setIsSimRunning(isRunning);
-		//Reset the Graph if isRunning == true
-		if (isRunning) {
-			for (StatisticGraphPanel sg : model.getGraphTable().values()) {
-				sg.resetGraph();
-			}
-		}
-	}
-	
 
 	
 	/**

+ 0 - 31
src/ui/controller/HolonCanvasController.java

@@ -49,37 +49,6 @@ public class HolonCanvasController {
 		}
 	}
 
-	// updates the bodies according to the changes of subnets
-	public void addNewBodies(int subCount, ArrayList<SubNet> subnets, Dimension center, int HolonBodyScale) {
-		this.subCount = subCount;
-		this.center = center;
-		// find correct color for existing HolonBodys
-		ArrayList<HolonBody> newBodies = new ArrayList<>();
-		for (int i = 0; i < subCount; i++) {
-			Color subNetColor = model.getSubNetColors().get(i);			
-			for (int j = 0; j < bodies.size(); j++) {
-				if (subNetColor == bodies.get(j).getColor()) {
-					int objectsSize = subnets.get(i).getObjects().size();
-					bodies.get(j).setRadius((objectsSize * 5 + 10) * HolonBodyScale / 100);
-					bodies.get(j).setMass((float) Math.pow((objectsSize + 1) * 5, 3));
-					newBodies.add(bodies.get(j));
-					newBodies.get(i).setId(i);
-					break;
-				}
-			}
-		}
-
-		bodies = newBodies;
-		// adding new HolonBodys
-		for (int i = bodies.size(); i < subCount; i++) {
-			float radius = (subnets.get(i).getObjects().size() * 5 + 10) * HolonBodyScale / 100;
-			HolonBody temp = new HolonBody((float) (center.width + Math.pow(-1, i)), (float)(center.height + Math.pow(-1, i)), radius,
-					(float) Math.pow((subnets.get(i).getObjects().size() + 1) * 5, 3), model.getSubNetColors().get(i));
-			temp.setId(i);
-			bodies.add(temp);
-		}
-	}
-
 	public int getActiveElements(ArrayList<AbstractCanvasObject> objects) {
 		int val = 0;
 		for (AbstractCanvasObject obj : objects) {

+ 0 - 13
src/ui/controller/LoadController.java

@@ -15,7 +15,6 @@ import org.apache.commons.compress.utils.IOUtils;
 
 import ui.model.Model;
 
-import java.awt.*;
 import java.awt.geom.Point2D;
 import java.io.*;
 import java.nio.file.Files;
@@ -175,8 +174,6 @@ public class LoadController {
                 loadUnitGraph(GRAPHTYPE.TESTELEMENT, json.get(key), null, eleDispatch);
             if (key.contains("TRACKED"))
                 loadTracked(json.get(key), objDispatch);
-            if (key.contains("STATSGRAPH"))
-                loadStatisticGraph(json.get(key));
         }
 
     }
@@ -191,8 +188,6 @@ public class LoadController {
                 model.setCvsObjIdx(new HashMap<>());
                 model.setObjectsOnCanvas(new ArrayList<>());
                 model.setEdgesOnCanvas(new ArrayList<>());
-                model.setTrackingObj(new ArrayList<>());
-                model.setStatisticData(new ArrayList<>());
                 model.setHashcodeMap(new HashMap<>());
                 model.setCanvasX(json.get("CANVAS_SIZE_X").getAsInt());
                 model.setCanvasX(json.get("CANVAS_SIZE_Y").getAsInt());
@@ -385,20 +380,12 @@ public class LoadController {
         }
     }
 
-    private void loadStatisticGraph(JsonElement jsonElement) {
-        JsonObject object = jsonElement.getAsJsonObject();
-        model.getGraphTable().clear();
-        model.getStatisticData().add(object);
-    }
-
     private void loadTracked(JsonElement jsonElement, HashMap<Integer, AbstractCanvasObject> objDispatch) {
         JsonObject object = jsonElement.getAsJsonObject();
         List<String> keys = getKeys(object);
 
         for (String k : keys) {
             int id = object.get(k).getAsInt();
-            model.getTrackingObj().add(objDispatch.get(id));
-            model.addObjectsToGraphListeners();
             if (objDispatch.get(id) instanceof HolonObject) {
                 ((HolonObject) objDispatch.get(id)).updateTrackingInfo();
             }

+ 1 - 24
src/ui/controller/MultiPurposeController.java

@@ -113,20 +113,6 @@ public class MultiPurposeController {
 		return object.searchElementById(idEle);
 	}
 
-	/**
-	 * 
-	 * @param id
-	 * @return
-	 */
-	public AbstractCanvasObject searchTracked(int id) {
-
-		for (AbstractCanvasObject cps : model.getTrackingObj()) {
-			if (cps.getId() == id)
-				return cps;
-		}
-		return null;
-	}
-
 	/**
 	 * Search Edge between 2 Objects.
 	 * 
@@ -216,7 +202,7 @@ public class MultiPurposeController {
 	 *            type
 	 * @return Copy of the HashMap
 	 */
-	public static <T, Integer> HashMap<T, Integer> copyHashMap(HashMap<T, Integer> map) {
+	public static <T> HashMap<T, Integer> copyHashMap(HashMap<T, Integer> map) {
 
 		HashMap<T, Integer> newMap = new HashMap<>();
 		for (Entry<T, Integer> i : map.entrySet()) {
@@ -225,14 +211,5 @@ public class MultiPurposeController {
 		return newMap;
 	}
 
-	/**
-	 * Set the Algorithm.
-	 * 
-	 * @param obj
-	 *            the Algorithm
-	 */
-	public void setAlgorithm(Object obj) {
-		model.setAlgorithm(obj);
-	}
 
 }

+ 1 - 46
src/ui/controller/NodeController.java

@@ -5,12 +5,10 @@ import classes.Edge;
 import classes.Node;
 import classes.GroupNode;
 import classes.Position;
-import classes.IntermediateCalculationCable;
 import ui.model.Model;
 
 import java.awt.*;
 import java.util.ArrayList;
-import java.util.Iterator;
 import java.util.LinkedList;
 
 
@@ -33,7 +31,6 @@ class NodeController {
     void doUpperNode(String nodeName, GroupNode upperNode, ArrayList<AbstractCanvasObject> toGroup) {
 		GroupNode node = new GroupNode(nodeName);
 		node.setPosition(calculatePos(toGroup));
-		makeAdjacent(node, upperNode, toGroup);
 		makeNodeOfNodes(node, upperNode, toGroup);
 		if (upperNode == null)
 			cvs.addNewObject(node);
@@ -65,8 +62,6 @@ class NodeController {
 	 * Put selected Nodes inside the Upper Node
 	 */
 	private void makeNodeOfNodes(GroupNode node, GroupNode upperNode, ArrayList<AbstractCanvasObject> toGroup) {
-
-		ArrayList<AbstractCanvasObject> nodes = node.getNodes();
 	
 
 		// Put all selected Nodes into the Upper Node
@@ -115,17 +110,6 @@ class NodeController {
 
 	}
 
-	/**
-	 * Look for adjacent Nodes connected with the new CpsUpperNode and make
-	 * Connections
-	 */
-	private void makeAdjacent(GroupNode node, GroupNode upperNode, ArrayList<AbstractCanvasObject> toGroup) {
-
-		ArrayList<AbstractCanvasObject> adj = new ArrayList<>();
-		ArrayList<Float> maxCapacity = new ArrayList<>();
-
-		
-	}
 
 	/**
 	 * Just checking if an Egde already exists
@@ -169,36 +153,7 @@ class NodeController {
 		(upperNode == null ? model.getObjectsOnCanvas() : upperNode.getNodes()).remove(obj);
 	}
 
-	/**
-	 * Search Lost Nodes by Backtracking by looking for edges
-	 * 
-	 * @param object
-	 *            actual object which we are looking at
-	 * @param find
-	 *            one part of the Edge
-	 * @param lost
-	 *            other part of the Edge
-	 * @return boolean if found
-	 */
-	private boolean backtrackLostChild(AbstractCanvasObject object, AbstractCanvasObject find, AbstractCanvasObject lost) {
-		//if not instance of CpsUpperNode
-		if (!(object instanceof GroupNode)) {
-			//forEach connection look if lost and found inside
-			for (Edge edge : object.getConnections()) {
-				if (edge.getA().equals(find) && edge.getB().equals(lost)
-						|| edge.getA().equals(lost) && edge.getB().equals(find))
-					return true;
-			}
-			return false;
-		} else {
-			//if instance of Uppernode Call again
-			for (AbstractCanvasObject cps : ((GroupNode) object).getNodes()) {
-				if (backtrackLostChild(cps, find, lost))
-					return true;
-			}
-			return false;
-		}
-	}
+
 
 
 	/**

+ 0 - 9
src/ui/controller/ObjectController.java

@@ -196,13 +196,4 @@ public class ObjectController {
     	return allObj;
     }
    
-
-    /**
-     * add the ID of a HolonBody.
-     *
-     * @param i int
-     */
-    public void addSelectedHolonBody(int i) {
-        model.setSelectedHolonBody(i);
-    }
 }

+ 0 - 42
src/ui/controller/SaveController.java

@@ -11,8 +11,6 @@ import org.apache.commons.compress.archivers.ArchiveStreamFactory;
 import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
 import org.apache.commons.compress.utils.IOUtils;
 import ui.model.Model;
-
-import java.awt.*;
 import java.awt.geom.Point2D;
 import java.io.*;
 import java.util.*;
@@ -60,7 +58,6 @@ public class SaveController {
         initialize(MODE.COMPLETE, file);
         storeCategory(file);
         storeCanvas(file);
-        storeStatistics(file);
         storeData(stream);
 
         FileWriter writer = new FileWriter(holonFile);
@@ -228,11 +225,6 @@ public class SaveController {
 
     }
 
-    private void storeStatistics(JsonObject file) {
-        trackedToJson(file);
-        statisticgraphToJson(file);
-    }
-
     /**
      * Save wanted Data
      */
@@ -367,41 +359,7 @@ public class SaveController {
 
     }
 
-    private void trackedToJson(JsonObject file) {
-        JsonObject temp = new JsonObject();
-        String key = "TRACKED";
-        // forall points add them
-        for (int i = 0; i < model.getTrackingObj().size(); i++) {
-            temp.add("" + i, new JsonPrimitive(model.getTrackingObj().get(i).getId()));
-        }
-
-        file.add(key, model.getGson().toJsonTree(temp));
-    }
 
-    private void statisticgraphToJson(JsonObject file) {
-        JsonObject temp = new JsonObject();
-
-        List<String> keys = new ArrayList<>(model.getGraphTable().keySet());
-
-        for (String k : keys) {
-            JsonObject dataSet = new JsonObject();
-            for (int i = 0; i < model.getGraphTable().get(k).getStatGraph().getDataSets().size(); i++) {
-                TrackedDataSet set = model.getGraphTable().get(k).getStatGraph().getDataSets().get(i);
-                AbstractCanvasObject cps = set.getCpsObject();
-
-                dataSet.add("ID", (cps == null ? null : new JsonPrimitive(cps.getId())));
-                dataSet.add("COLOR", model.getGson().toJsonTree(set.getColor(), Color.class));
-                dataSet.add("PROPERTY", new JsonPrimitive(set.getProperty()));
-                temp.add("" + i, model.getGson().toJsonTree(dataSet));
-                dataSet = new JsonObject();
-            }
-            temp.add("KEY", new JsonPrimitive(k));
-
-            file.add("STATSGRAPH" + getNumerator(NUMTYPE.STATSGRAPH), model.getGson().toJsonTree(temp));
-            temp = new JsonObject();
-        }
-
-    }
 
     /**
      * Differs Between Single file or whole Directory to Store

+ 0 - 35
src/ui/controller/SimulationManager.java

@@ -1,11 +1,7 @@
 package ui.controller;
 
 import classes.*;
-import classes.comparator.EnergyMinToMaxComparator;
-import classes.comparator.MinEnergyComparator;
-import classes.comparator.WeakestBattery;
 import ui.model.IntermediateCableWithState;
-import ui.controller.FlexManager.FlexState;
 import ui.model.DecoratedCable;
 import ui.model.DecoratedCable.CableState;
 import ui.model.DecoratedSwitch.SwitchState;
@@ -17,20 +13,12 @@ import ui.model.MinimumNetwork;
 import ui.model.Model;
 import ui.model.Model.FairnessModel;
 import ui.model.VisualRepresentationalState;
-import ui.view.FlexiblePane;
-import ui.view.GUI;
-import ui.view.MyCanvas;
-import ui.view.Outliner;
 
 import java.util.ArrayList;
-import java.util.Collections;
 import java.util.HashMap;
 import java.util.LinkedList;
-import java.util.List;
 import java.util.ListIterator;
 
-import javax.swing.JPanel;
-
 
 /**
  * Controller for Simulation.
@@ -44,10 +32,8 @@ public class SimulationManager {
 	private HashMap<Integer, VisualRepresentationalState> savesVisual = new HashMap<Integer, VisualRepresentationalState>();
 	
 	private HashMap<Integer, FlexManager> savesFlexManger = new HashMap<Integer, FlexManager>();
-	private List<Flexibility> actualOrders = new ArrayList<Flexibility>();
 	
 	private int timeStep;
-	private FlexiblePane flexPane;
 
 	/**
 	 * Constructor.
@@ -252,27 +238,6 @@ public class SimulationManager {
 			}
 		}
 	}
-
-	/**
-	 * Get all Subnets.Not functional.
-	 *
-	 * @return all Subnets
-	 */
-	@Deprecated
-	public ArrayList<SubNet> getSubNets() {
-		return new ArrayList<SubNet>();
-	}
-
-
-
-	public FlexiblePane getFlexiblePane() {
-		return flexPane;
-	}
-
-	void setFlexiblePane(FlexiblePane fp) {
-		flexPane = fp;
-	}
-
 	
 	public DecoratedState getActualDecorState() {
 		return getDecorState(timeStep);

+ 0 - 21
src/ui/controller/SingletonControl.java

@@ -1,21 +0,0 @@
-package ui.controller;
-
-
-public class SingletonControl {
-	  private Control control;
-	  private static final class InstanceHolder {
-	    static final SingletonControl INSTANCE = new SingletonControl();
-	  }
-	  private SingletonControl () {}
-	  public static SingletonControl getInstance () {
-	    return InstanceHolder.INSTANCE;
-	  }
-	  public Control getControl()
-	  {
-		return control;
-	  }
-	  public void setControl(Control control)
-	  {
-		this.control = control;
-	  }
-}

+ 0 - 53
src/ui/controller/StatsController.java

@@ -1,53 +0,0 @@
-package ui.controller;
-
-import java.util.ArrayList;
-
-import classes.AbstractCanvasObject;
-import classes.TrackedDataSet;
-import ui.model.Model;
-import ui.view.StatisticGraphPanel;
-
-public class StatsController {
-
-	private Model model;
-
-	public StatsController(Model mod) {
-		this.model = mod;
-
-	}
-
-	public void setTrackingObj(ArrayList<AbstractCanvasObject> objArr) {
-		model.setTrackingObj(objArr);
-	}
-
-	public ArrayList<AbstractCanvasObject> getTrackingObj() {
-		return model.getTrackingObj();
-	}
-
-	public void addTrackingObj(AbstractCanvasObject obj) {
-		model.getTrackingObj().add(obj);
-		model.addObjectsToGraphListeners();
-	}
-
-	public void removeTrackingObj(AbstractCanvasObject obj) {
-		ArrayList<AbstractCanvasObject> objArr = model.getTrackingObj();
-		objArr.remove(obj);
-		model.setTrackingObj(objArr);
-		model.addObjectsToGraphListeners();
-		//Remove the Object from the graph and the LegendPanel
-		for (StatisticGraphPanel sg : model.getGraphTable().values()) {
-			ArrayList<Integer> indexList = new ArrayList<>();
-			for (TrackedDataSet set: sg.getStatGraph().getDataSets()) {
-				if (obj == set.getCpsObject()) {
-					indexList.add(sg.getStatGraph().getDataSets().indexOf(set));
-				}
-			}
-			for (int i = indexList.size()-1; i >= 0; i--) {
-				sg.getLegendPanel().remove(sg.getLegendPanel().getComponent(indexList.get(i)));
-				sg.getStatGraph().removeObject(indexList.get(i));
-				sg.updateUI();
-				
-			}
-		}
-	}
-}

+ 0 - 40
src/ui/controller/UpdateController.java

@@ -7,7 +7,6 @@ import classes.comparator.elementComparator.ElemCompOnId;
 import classes.comparator.elementComparator.ElemCompOnIsActivated;
 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;
@@ -17,7 +16,6 @@ import ui.view.PropertyTable;
 import ui.view.GroupNodeCanvas;
 
 import java.util.ArrayList;
-import java.util.Comparator;
 import java.util.HashMap;
 import java.util.LinkedList;
 
@@ -478,44 +476,6 @@ public class UpdateController {
 		return obj;
 	}
 
-	/**
-	 * fills the table when HolonCanvas is open
-	 * 
-	 * @param id
-	 *            ID of the selected HolonBody
-	 */
-	public void paintHolonBody(int id) {
-		if (id != -1) {
-			
-			ArrayList<SubNet> subs = controller.getSimManager().getSubNets();
-			if (!subs.isEmpty()) {
-				SubNet sub = subs.get(id);
-				Object[] tempId = { "ID", id };
-				model.getPropertyTable().addRow(tempId);
-				Object[] tempObj = { "Nr. of Objects", sub.getObjects().size() };
-				model.getPropertyTable().addRow(tempObj);
-				Object[] tempEdg = { "Nr. of Edges", sub.getEdges().size() };
-				model.getPropertyTable().addRow(tempEdg);
-				Object[] tempSwi = { "Nr. of Switches", sub.getSwitches().size() };
-				model.getPropertyTable().addRow(tempSwi);
-				Object[] tempProd = { "Total Production",
-						"" + controller.getTotalProduction(new ArrayList<AbstractCanvasObject>(sub.getObjects())) };
-				model.getPropertyTable().addRow(tempProd);
-				Object[] tempCons = { "Total Consumption",
-						"" + controller.getTotalConsumption(new ArrayList<AbstractCanvasObject>(sub.getObjects())) };
-				model.getPropertyTable().addRow(tempCons);
-				Object[] tempEle = { "Nr. of Elements",
-						"" + controller.getTotalElements(new ArrayList<AbstractCanvasObject>(sub.getObjects())) };
-				model.getPropertyTable().addRow(tempEle);
-				Object[] tempProds = { "Nr. of Producers",
-						"" + controller.getTotalProducers(new ArrayList<AbstractCanvasObject>(sub.getObjects())) };
-				model.getPropertyTable().addRow(tempProds);
-				Object[] tempAct = { "Nr. of active Elements",
-						"" + controller.getActiveElements(new ArrayList<AbstractCanvasObject>(sub.getObjects())) };
-				model.getPropertyTable().addRow(tempAct);
-			}
-		}
-	}
 
 	/**
 	 * 

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

@@ -1,15 +1,10 @@
 package ui.model;
 
 import java.util.ArrayList;
-import java.util.List;
-import java.util.stream.Collector;
-import java.util.stream.Collectors;
 
 import classes.Node;
 import classes.GroupNode;
-import classes.IntermediateCalculationCable;
 import ui.model.DecoratedHolonObject.HolonObjectState;
-import classes.ExitCable;
 /**
  * For the @VisualRepresentationalState only.
  * @author Tom

+ 2 - 2
src/classes/ExitCable.java → src/ui/model/ExitCable.java

@@ -1,6 +1,6 @@
-package classes;
+package ui.model;
 
-import ui.model.DecoratedCable;
+import classes.AbstractCanvasObject;
 /**
  * For the Visual State.
  * @author Tom

+ 4 - 2
src/classes/IntermediateCalculationCable.java → src/ui/model/IntermediateCalculationCable.java

@@ -1,6 +1,8 @@
-package classes;
+package ui.model;
 
-import ui.model.DecoratedCable;
+import classes.AbstractCanvasObject;
+import classes.Edge;
+import classes.GroupNode;
 
 /**
  * A VisualRepresentation to represent a connection from a UpperNode to a AbstactCpsObject, but actually the UpperNode is not connected.

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

@@ -3,7 +3,6 @@ package ui.model;
 import java.util.ArrayList;
 
 import classes.AbstractCanvasObject;
-import classes.AbstractCpsObject;
 import classes.HolonObject;
 
 public class MinimumNetwork {

+ 27 - 240
src/ui/model/Model.java

@@ -1,26 +1,35 @@
 package ui.model;
 
-import TypeAdapter.AbstractCpsObjectAdapter;
-import TypeAdapter.ColorAdapter;
-import TypeAdapter.PairAdapter;
-import TypeAdapter.PositionAdapter;
-import classes.*;
+import java.awt.Color;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.stream.Collectors;
+
+import javax.swing.JTable;
 
 import com.google.gson.Gson;
 import com.google.gson.GsonBuilder;
-import com.google.gson.JsonObject;
 
-import interfaces.CategoryListener;
+import TypeAdapter.AbstractCpsObjectAdapter;
+import TypeAdapter.ColorAdapter;
+import TypeAdapter.PairAdapter;
+import TypeAdapter.PositionAdapter;
+import classes.AbstractCanvasObject;
+import classes.Category;
+import classes.Edge;
+import classes.GroupNode;
+import classes.HolonElement;
+import classes.HolonObject;
+import classes.HolonSwitch;
+import classes.Node;
+import classes.Pair;
+import classes.Position;
 import interfaces.GraphListener;
 import interfaces.ObjectListener;
-import ui.view.*;
-
-import javax.swing.*;
-
-import java.awt.*;
-import java.util.*;
-import java.util.List;
-import java.util.stream.Collectors;
+import ui.view.DefaulTable;
+import ui.view.PropertyTable;
 
 /**
  * The Class Model is the class where everything is saved. All changes made to
@@ -35,7 +44,6 @@ public class Model {
     // Global Variables
     private static int sCALE = 50; // Picture Scale
     private static int sCALEdIV2 = sCALE / 2;
-    private static int holonBodysCALE = 100; // Picture Scale
     public String[] colNames = {"Field", "Information"};
     // Canvas Attributes
     private String imgPath = "";
@@ -45,7 +53,6 @@ public class Model {
     private int canvasX = 3000;
     private int canvasY = 3000;
     private int curIteration = 0;
-    private LinkedList<Color> subNetColors = new LinkedList<>();
     // ID of the Selected Object
     private AbstractCanvasObject selectedCpsObject = null;
     private HolonElement selectedHolonElement;
@@ -68,12 +75,6 @@ public class Model {
     private int autoSaveNr = -1;
     // number of max simultaneous autosaves
     private int numberOfSaves = 35;
-    // whether the simulation is running and has not been reseted
-    private boolean isSimRunning = false;
-    // whether the console log of the program should be displayed
-    private boolean showConsoleLog = true;
-    // whether the console log of the program should be displayed
-    private boolean useFlexibleDevices = true;
     /** whether the supplyBars should be shown or not */
     private boolean showSupplyBars = true;
     //TODO:
@@ -104,11 +105,7 @@ public class Model {
      * categories ENERGY, BUILDINGS and COMPONENTS
      */
     private ArrayList<Category> categories;
-    /*
-     * Array of all HolonObj and HolonSwitches, that should be tracked through
-     * out the statistics tab
-     */
-    private ArrayList<AbstractCanvasObject> trackedObjects;
+
     /*
      * Array of all CpsObjects in our canvas. It is set by default as an empty
      * list.
@@ -127,36 +124,14 @@ public class Model {
     private ArrayList<Node> nodesOnCanvas= new ArrayList<Node>();
     private ArrayList<HolonSwitch> switchsOnCanvas= new ArrayList<HolonSwitch>();
     
-    
-    
-    
-    
-    
-    
-    
-    
-    /*
-     * Array for all Listeners
-     */
-    private List<CategoryListener> categoryListeners;
     private List<ObjectListener> objectListeners;
     private PropertyTable tableModelHolonElementMulti;
     private PropertyTable tableModelHolonElementSingle;
     private DefaulTable tableModelProperties;
-    /*
-     * Object that runs the Algorithm
-     */
-    private Object algorithm = null;
-    private int selectedHolonBody;
-
-    // Statistic Graph Data
-    private Hashtable<String, StatisticGraphPanel> statisticGraphTable = new Hashtable<>();
     private HashMap<Integer, GroupNode> hashcodeMap = new HashMap<>();
-    private ArrayList<JsonObject> statisticData = new ArrayList<>();
 
-    private Gson gson;
 
-    private StatisticPanel statPanel;
+    private Gson gson;
 
     /**
      * Constructor for the model. It initializes the categories and
@@ -167,12 +142,10 @@ public class Model {
         setCategories(new ArrayList<>());
         setObjectsOnCanvas(new ArrayList<>());
         setEdgesOnCanvas(new ArrayList<>());
-        setCategoryListeners(new LinkedList<>());
         setObjectListeners(new LinkedList<>());
         setCgIdx(new HashMap<>());
         setCvsObjIdx(new HashMap<>());
         setClipboradObjects(new ArrayList<>());
-        setTrackingObj(new ArrayList<>());
         setEleToDelete(new HashMap<>());
         setSingleTable(new PropertyTable());
         setMultiTable(new PropertyTable());
@@ -290,24 +263,6 @@ public class Model {
         this.objectListeners = linkedList;
     }
 
-    /**
-     * Returns the CategorieListener.
-     *
-     * @return the categoryListeners
-     */
-    public List<CategoryListener> getCategoryListeners() {
-        return categoryListeners;
-    }
-
-    /**
-     * Sets the CategorieListener.
-     *
-     * @param linkedList the categoryListeners to set
-     */
-    public void setCategoryListeners(LinkedList<CategoryListener> linkedList) {
-        this.categoryListeners = linkedList;
-    }
-
     /**
      * Returns the ID of the selected Object 0 = no Object is selected.
      *
@@ -412,7 +367,7 @@ public class Model {
     }
 
     /**
-     * Returns ITERATIONS.
+     * Returns the maximum ITERATIONS.
      *
      * @return ITERATIONS
      */
@@ -623,55 +578,6 @@ public class Model {
         this.canvasY = canvasY;
     }
 
-    /**
-     * get the Algorithm.
-     *
-     * @return the Algorithm
-     */
-    public Object getAlgorithm() {
-        return algorithm;
-    }
-
-    /**
-     * Set the Algorithm.
-     *
-     * @param obj the Algorithm
-     */
-    public void setAlgorithm(Object obj) {
-        this.algorithm = null;
-        this.algorithm = obj;
-    }
-
-    /**
-     * Add a SubNetColor.
-     *
-     * @param c the Color
-     */
-    public void addSubNetColor(Color c) {
-        this.subNetColors.add(c);
-    }
-
-    /**
-     * Get the SubNetColors.
-     *
-     * @return SubNetColors
-     */
-    public LinkedList<Color> getSubNetColors() {
-        return this.subNetColors;
-    }
-
-    public ArrayList<AbstractCanvasObject> getTrackingObj() {
-        return trackedObjects;
-    }
-
-    public void setTrackingObj(ArrayList<AbstractCanvasObject> toTrack) {
-        trackedObjects = toTrack;
-    }
-
-    public void addGraphListener(GraphListener gl) {
-        graphListeners.add(gl);
-    }
-
     public HashMap<Integer, ArrayList<HolonElement>> getEleToDelete() {
         return this.eleToDelete;
     }
@@ -696,12 +602,6 @@ public class Model {
         this.tableModelHolonElementMulti = pt;
     }
 
-    public void addObjectsToGraphListeners() {
-        for (GraphListener gl : graphListeners) {
-            gl.addTrackedObject(trackedObjects);
-            gl.repaintTree();
-        }
-    }
 
     public DefaulTable getPropertyTable() {
         return this.tableModelProperties;
@@ -733,42 +633,6 @@ public class Model {
 		this.propertyTable = propertyTable;
 	}
 
-    /**
-     * Returns the sCale (Scale for the Images).
-     *
-     * @return sCALE
-     */
-    public int getHolonBodyScale() {
-        return holonBodysCALE;
-    }
-
-    /**
-     * Sets the HolonBody Scale.
-     *
-     * @param scale for the HolonBody
-     */
-    public void setHolonBodyScale(int scale) {
-        holonBodysCALE = scale;
-    }
-
-    /**
-     * Returns the ID of the selected HolonBody
-     *
-     * @return selectedHolonBody
-     */
-    public int getSelectedHolonBody() {
-        return selectedHolonBody;
-    }
-
-    /**
-     * Sets the ID of the selected HolonBody
-     *
-     * @param i int
-     */
-    public void setSelectedHolonBody(int i) {
-        selectedHolonBody = i;
-    }
-
     public List<HolonElement> getAllHolonElemnts() {
     	return getAllHolonObjectsOnCanvas().stream().flatMap(hO -> hO.getElements().stream()).collect(Collectors.toList());
     }
@@ -900,75 +764,6 @@ public class Model {
         backgroundHeight = height;
     }
 
-    /**
-     * Returns the graphtable for Statistic Graphs.
-     */
-    public Hashtable<String, StatisticGraphPanel> getGraphTable() {
-        return statisticGraphTable;
-    }
-
-    /**
-     * Set the graphtable for Statistic Graphs
-     */
-    public void setGraphTable(Hashtable<String, StatisticGraphPanel> gT) {
-        statisticGraphTable = gT;
-    }
-
-    /**
-     * Returns if the Simulation is running.
-     */
-    public boolean getIsSimRunning() {
-        return isSimRunning;
-    }
-
-    /**
-     * Sets isSimRunning.
-     *
-     * @param isRunning
-     */
-    public void setIsSimRunning(boolean isRunning) {
-        isSimRunning = isRunning;
-    }
-
-    /**
-     * @return the statisticData
-     */
-    public ArrayList<JsonObject> getStatisticData() {
-        return statisticData;
-    }
-
-    /**
-     * @param statisticData the statisticData to set
-     */
-    public void setStatisticData(ArrayList<JsonObject> statisticData) {
-        this.statisticData = statisticData;
-    }
-
-    /**
-     * Returns showConsoleLog.
-     */
-    public boolean getShowConsoleLog() {
-        return this.showConsoleLog;
-    }
-
-    /**
-     * Sets showConsoleLog.
-     *
-     * @param showConsoleLog
-     */
-    public void setShowConsoleLog(boolean showConsoleLog) {
-        this.showConsoleLog = showConsoleLog;
-    }
-
-
-    public boolean useFlexibleDevices() {
-        return this.useFlexibleDevices;
-    }
-
-    public void setUseFlexibleDevices(boolean useFlexibleDevices) {
-        this.useFlexibleDevices = useFlexibleDevices;
-    }
-
     /**
 	 * @return true if SupplyBars should be shown
 	 */
@@ -1039,14 +834,6 @@ public class Model {
         this.gson = gson;
     }
 
-    public StatisticPanel getStatPanel() {
-        return statPanel;
-    }
-
-    public void setStatPanel(StatisticPanel sP) {
-        statPanel = sP;
-    }
-
     /**
      * @return the hashcodeMap
      */

+ 1 - 20
src/ui/model/VisualRepresentationalState.java

@@ -10,10 +10,8 @@ import java.util.stream.Collectors;
 import classes.AbstractCanvasObject;
 import classes.Edge;
 import classes.Node;
+import ui.model.ExitCable.ExitCableState;
 import classes.GroupNode;
-import classes.IntermediateCalculationCable;
-import classes.ExitCable;
-import classes.ExitCable.ExitCableState;
 
 public class VisualRepresentationalState {
 	private ArrayList<Supplier> supplierList = new ArrayList<Supplier>();
@@ -257,23 +255,6 @@ public class VisualRepresentationalState {
 	}
 
 
-	private void addCable(HashMap<AbstractCanvasObject, GroupNode> 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 void addCable(DecoratedCable cable, HashMap<Edge, ArrayList<GroupNode>> inGroupEdges, HashMap<AbstractCanvasObject, GroupNode> inGroupObjects,
 			HashMap<GroupNode, DecoratedGroupNode> createdGroupNodes, ArrayList<IntermediateCalculationCable> exitCables) {
 		boolean isInGroup = false;

+ 445 - 432
src/ui/view/AbstractCanvas.java

@@ -1,433 +1,446 @@
-package ui.view;
-
-import classes.*;
-import ui.controller.Control;
-import ui.controller.UpdateController;
-import ui.model.Model;
-
-import javax.swing.*;
-import javax.swing.table.JTableHeader;
-
-import java.awt.*;
-import java.awt.event.MouseEvent;
-import java.io.File;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.TimerTask;
-
-/**
- * Collection of methods and values needed in both <code>MyCanvas</code> and
- * <code>UpperNodeCanvas</code>
- * <p>
- * Although Java works on references we chose to add explicit return values for
- * clearer code understanding in most cases
- *
- * @author: I. Dix
- */
-public abstract class AbstractCanvas extends JPanel {
-	/**
-	 * Version
-	 */
-	private static final long serialVersionUID = 1L;
-	
-	final JMenuItem itemDelete = new JMenuItem(Languages.getLanguage()[98]);
-	final JMenuItem itemCut = new JMenuItem(Languages.getLanguage()[95]);
-	final JMenuItem itemCopy = new JMenuItem(Languages.getLanguage()[96]);
-	final JMenuItem itemPaste = new JMenuItem(Languages.getLanguage()[97]);
-	final JMenuItem itemGroup = new JMenuItem(Languages.getLanguage()[99]);
-	final JMenuItem itemUngroup = new JMenuItem(Languages.getLanguage()[100]);
-	final JMenuItem itemTrack = new JMenuItem(Languages.getLanguage()[101]);
-	final JMenuItem itemUntrack = new JMenuItem(Languages.getLanguage()[102]);
-	final JMenuItem itemAlign = new JMenuItem("Align selected");
-	final JMenuItem itemCreateTemplate = new JMenuItem(Languages.getLanguage()[Languages.right_click_create_template]);
-	
-	final int ANIMTIME = 500; // animation Time
-	private final int animFPS = 60;
-	final int animDelay = 1000 / animFPS; // animation Delay
-	protected Model model;
-	protected Control controller;
-	protected int x = 0;
-	protected int y = 0;
-	// Selection
-	AbstractCanvasObject tempCps = null;
-	UpdateController updCon;
-	
-	//Replacement
-	/**
-	 * the CpsObject that might be replaced by drag&drop
-	 */
-	protected AbstractCanvasObject mayBeReplaced = null;
-	
-	// PopUpMenu
-	JPopupMenu popmenu = new JPopupMenu();
-	// Tooltip
-	boolean toolTip; // Tooltip on or off
-	Position toolTipPos = new Position(); // Tooltip Position
-	String toolTipText = "";
-	ArrayList<HolonElement> dataSelected = new ArrayList<>();
-	ArrayList<AbstractCanvasObject> tempSelected = new ArrayList<>();
-	boolean[] showedInformation = new boolean[5];
-	boolean showConnectionInformation;
-	boolean dragging = false; // for dragging
-	boolean dragged = false; // if an object/objects was/were dragged
-	boolean drawEdge = false; // for drawing edges
-	boolean doMark = false; // for double click
-	Edge edgeHighlight = null;
-	Point mousePosition = new Point(); // Mouse Position when
-	ArrayList<Position> savePos;
-	// edge Object Start Point
-	int cx, cy;
-	int sx, sy; // Mark Coords
-	Position unPos;
-	// Animation
-	Timer animT; // animation Timer
-	int animDuration = ANIMTIME; // animation Duration
-	int animSteps = animDuration / animDelay; // animation Steps;
-	ArrayList<AbstractCanvasObject> animCps = null;
-	// Graphics
-	Image img = null; // Contains the image to draw on the Canvas
-	Graphics2D g2; // For Painting
-	float scalediv20;
-	// Mouse
-	private boolean click = false;
-
-	// ------------------------------------------ METHODS
-	// ------------------------------------------
-	
-
-	
-	
-
-	class ACpsHandle{
-		public AbstractCanvasObject object;
-		ACpsHandle(AbstractCanvasObject object){
-			this.object = object;
-		}
-		public String toString() {
-			return object.toString();
-		}
-	}
-
-	void drawMarker() {
-		if (sx > x && sy > y) {
-			g2.drawRect(x, y, sx - x, sy - y);
-		} else if (sx < x && sy < y) {
-			g2.drawRect(sx, sy, x - sx, y - sy);
-		} else if (sx >= x) {
-			g2.drawRect(x, sy, sx - x, y - sy);
-		} else if (sy >= y) {
-			g2.drawRect(sx, y, x - sx, sy - y);
-		}
-	}
-	/**
-	 * @deprecated
-	 * @param g
-	 */
-	void showTooltip(Graphics g) {
-		if (toolTip) {
-			g2.setColor(new Color(255, 225, 150));
-			g2.setStroke(new BasicStroke(1));
-			int textWidth = g.getFontMetrics().stringWidth(toolTipText) + 2; // Text
-			// width
-
-			// fixed x and y Position to the screen
-			int fixXPos = toolTipPos.x - (textWidth >> 1) + model.getScaleDiv2();
-			int fixYPos = toolTipPos.y;
-
-			if (fixXPos < 0) {
-				fixXPos = 0;
-			} else if (fixXPos + textWidth + 1 > this.getWidth()) {
-				fixXPos -= (fixXPos + textWidth + 1) - this.getWidth();
-			}
-			if (fixYPos + 16 > this.getHeight()) {
-				fixYPos -= (fixYPos + 16) - this.getHeight();
-			}
-			g2.fillRect(fixXPos, fixYPos, textWidth, 15);
-			g2.setColor(Color.BLACK);
-			g2.drawRect(fixXPos, fixYPos, textWidth, 15);
-			g2.drawString(toolTipText, fixXPos + 2, fixYPos + 12);
-		}
-	}
-
-
-
-	void setRightClickMenu(MouseEvent e) {
-		if (e.getButton() == MouseEvent.BUTTON3) {
-			itemPaste.setEnabled(true);
-			if (tempCps != null) {
-				itemPaste.setEnabled(true);
-				itemDelete.setEnabled(true);
-				itemCut.setEnabled(true);
-				itemCopy.setEnabled(true);
-				itemAlign.setEnabled(true);
-				// tracking
-				if (tempCps != null) {
-					itemGroup.setEnabled(true);
-					itemTrack.setEnabled(true);
-					itemUntrack.setEnabled(true);
-				}
-				// ungrouping
-				if (tempCps instanceof GroupNode)
-					itemUngroup.setEnabled(true);
-				else
-					itemUngroup.setEnabled(false);
-				if (model.getSelectedCpsObjects().size() == 0) {
-					controller.addSelectedObject(tempCps);
-				}
-				if (tempCps instanceof HolonObject) {
-					itemCreateTemplate.setEnabled(true);
-				} else {
-					itemCreateTemplate.setEnabled(false);
-				}
-			} else {
-				itemAlign.setEnabled(false);
-				itemCut.setEnabled(false);
-				itemCopy.setEnabled(false);
-				itemGroup.setEnabled(false);
-				itemUngroup.setEnabled(false);
-				itemTrack.setEnabled(false);
-				itemUntrack.setEnabled(false);
-				itemCreateTemplate.setEnabled(false);
-				if (edgeHighlight != null) {
-					itemDelete.setEnabled(true);
-					itemPaste.setEnabled(false);
-				} else {
-					itemDelete.setEnabled(false);
-					itemPaste.setEnabled(true);
-				}
-			}
-			mousePosition = this.getMousePosition();
-			popmenu.show(e.getComponent(), e.getX(), e.getY());
-		}
-	}
-
-	void markObjects() {
-		if (doMark) {
-			doMark = false;
-			for (AbstractCanvasObject cps : tempSelected) {
-				if (!model.getSelectedCpsObjects().contains(cps)) {
-					controller.addSelectedObject(cps);
-				}
-			}
-			controller.getObjectsInDepth();
-			tempSelected.clear();
-		}
-	}
-
-
-	int[] determineMousePositionOnEdge(Edge p) {
-		int lx, ly, hx, hy;
-
-		if (p.getA().getPosition().x > p.getB().getPosition().x) {
-			hx = p.getA().getPosition().x + model.getScaleDiv2() + 7;
-			lx = p.getB().getPosition().x + model.getScaleDiv2() - 7;
-		} else {
-			lx = p.getA().getPosition().x + model.getScaleDiv2() - 7;
-			hx = p.getB().getPosition().x + model.getScaleDiv2() + 7;
-		}
-		if (p.getA().getPosition().y > p.getB().getPosition().y) {
-			hy = p.getA().getPosition().y + model.getScaleDiv2() + 7;
-			ly = p.getB().getPosition().y + model.getScaleDiv2() - 7;
-		} else {
-			ly = p.getA().getPosition().y + model.getScaleDiv2() - 7;
-			hy = p.getB().getPosition().y + model.getScaleDiv2() + 7;
-		}
-
-		return new int[] { lx, ly, hx, hy };
-	}
-
-	/**
-	 * Checks if a double click was made.
-	 *
-	 * @return true if doublecklick, false if not
-	 */
-	boolean doubleClick() {
-		if (click) {
-			click = false;
-			return true;
-		} else {
-			click = true;
-			java.util.Timer t = new java.util.Timer("doubleclickTimer", false);
-			t.schedule(new TimerTask() {
-				@Override
-				public void run() {
-					click = false;
-				}
-			}, 500);
-		}
-		return false;
-	}
-
-	boolean setToolTipInfoAndPosition(boolean on, AbstractCanvasObject cps) {
-		if (x - controller.getScale() <= cx && y - controller.getScale() <= cy && x >= cx && y >= cy) {
-			on = true;
-			toolTipPos.x = cps.getPosition().x - controller.getScaleDiv2();
-			toolTipPos.y = cps.getPosition().y + controller.getScaleDiv2();
-			toolTipText = cps.getName() + ", " + cps.getId();
-		}
-
-		return on;
-	}
-
-	abstract void drawDeleteEdge();
-
-	void triggerUpdateController() {
-		updCon.paintProperties(tempCps);
-		updCon.refreshTableHolonElement(model.getMultiTable(), model.getSingleTable());
-		updCon.refreshTableProperties(model.getPropertyTable());
-	}
-	
-	
-	/**
-	 * Checks if {@code draggedCps} or a new cpsObject at Position (x,y) could replace exactly one object
-	 * in {@code objects}.
-	 * Saves the object that would be replaced in {@link AbstractCanvas}.{@code MayBeReplaced}
-	 * @param objects list of objects that could be replaced
-	 * @param draggedCps Object that might replace
-	 * @param x Position of the objects that might replace
-	 * @param y Position of the objects that might replace
-	 * @return true if exactly one Object could be replaced 
-	 */
-	protected boolean checkForReplacement(ArrayList<AbstractCanvasObject> objects, AbstractCanvasObject draggedCps, int x, int y){
-		
-		/** distance treshold for replacement */
-		int treshhold = controller.getScale()/2;
-						
-		/** number of Objects that might be replaced (should be 1) */
-		int replaceCounter = 0;
-		
-		/** last object that could be replaced */
-		AbstractCanvasObject toBeReplaced = null;
-		
-		/** Position of object that might be replaced */
-		Position p;
-		
-		/** for each cps on Canvas */
-		if(draggedCps == null || !(draggedCps instanceof Node) && !(draggedCps instanceof Node)){
-			for (AbstractCanvasObject cps : objects){
-				/** same object -> ignore */
-				if(cps == draggedCps)continue;
-						
-				/** set Position of object that might be replaced */
-				p = cps.getPosition();
-				
-				/** if near enough */
-				if(Math.abs(x-p.x)<treshhold && Math.abs(y-p.y)<treshhold){
-					replaceCounter++;
-					toBeReplaced = cps;
-					
-					/**
-					 * if too many Objects could be replaced:
-					 * stop searching, because it would not be clear which one should
-					 * be replaced
-					 */
-					if(replaceCounter>1)break;
-				}
-			}
-		}
-		/**
-		 * return true if exactly one obect would be replaced
-		 */
-		if( replaceCounter == 1 && toBeReplaced != null){
-			mayBeReplaced = toBeReplaced;
-			return true;
-		}else{
-			mayBeReplaced = null;
-			return false;
-		}
-	}
-	
-	/**
-	 * Checks if an inserted new Object could replace exactly one object on the canvas.
-	 * Saves the object that would be replaced in {@link AbstractCanvas}.{@code MayBeReplaced}
-	 * @param x Position of the objects that might replace
-	 * @param y Position of the objects that might replace
-	 * @return true if exactly one Object could be replaced 
-	 */
-	public abstract boolean checkForReplacement(int x, int y);
-	
-		
-	/**
-	 * highlights the object that mayBeReplaced
-	 * @param g2
-	 */
-	protected void highlightMayBeReplaced(Graphics2D g2) {
-		if(mayBeReplaced != null){
-			g2.setColor(Color.RED);
-			g2.fillRect(
-					(int) (mayBeReplaced.getPosition().x
-							- controller.getScaleDiv2() - (scalediv20 + 3)),
-					(int) (mayBeReplaced.getPosition().y
-							- controller.getScaleDiv2() - (scalediv20 + 3)),
-					(int) (controller.getScale() + ((scalediv20 + 3) * 2)),
-					(int) (controller.getScale() + ((scalediv20 + 3) * 2)));
-		}
-	}
-	
-	/**
-	 * Align alle Objects on the Canvas to a Grid with objects every 10 pixels
-	 */
-	public abstract void tryToAlignObjects();
-
-	/**
-	 * Aligns the Object the a grid
-	 * @param cps Object that should be aligned
-	 * @param distance distance between the AlignmentGrid Lines. (objects every 'distance' pixels
-	 */
-	protected void align(AbstractCanvasObject cps, int distance) {
-		/** Position of the AbstractCpsObject which should be aligned */
-		Position p = cps.getPosition();
-		
-		//calculate how many pixels the cps should be decreased to align
-		/** x offset relative to a grid with lines every distance pixels */
-		int x_off = cps.getPosition().x % distance;
-		
-		/** y offset relative to a grid with lines every distance pixels */
-		int y_off = cps.getPosition().y % distance;
-		
-		//align to the other Line, if it is nearer
-		if(x_off > distance/2)
-			x_off -= distance;
-		if(y_off > distance/2)
-			y_off -= distance;
-		
-		/** set new Position */
-		cps.setPosition(p.x-x_off, p.y-y_off);
-	}
-	
-	/**
-	 * Stops Editing in HolonElementTable and PropertyTable
-	 */
-	protected void stopEditing() {
-		/**
-		 * Stop Editing, if mouse exits the Table
-		 */
-		JTable holElem = model.getTableHolonElement();
-		CellEditor cellEditor = holElem.getCellEditor();
-		if (cellEditor != null) {
-		    if (cellEditor.getCellEditorValue() != null) {
-		    	/** TODO: Maybe try to save current Data */
-		        cellEditor.stopCellEditing();
-		    } else {
-		        cellEditor.cancelCellEditing();
-		    }
-		}
-		
-		JTable propertys = model.getTableProperties();
-		cellEditor = propertys.getCellEditor();
-		if (cellEditor != null) {
-		    if (cellEditor.getCellEditorValue() != null) {
-		    	/** TODO: Maybe try to save current Data */
-		        cellEditor.stopCellEditing();
-		    } else {
-		        cellEditor.cancelCellEditing();
-		    }
-		}
-	}
-
-	/**
-	 * Closes a tab of the UpperNode with ID upperNodeID
-	 * @param upperNodeId
-	 */
-	public abstract void closeUpperNodeTab(int upperNodeId);
+package ui.view;
+
+import java.awt.BasicStroke;
+import java.awt.Color;
+import java.awt.Graphics;
+import java.awt.Graphics2D;
+import java.awt.Image;
+import java.awt.Point;
+import java.awt.event.MouseEvent;
+import java.util.ArrayList;
+import java.util.TimerTask;
+
+import javax.swing.CellEditor;
+import javax.swing.JMenuItem;
+import javax.swing.JPanel;
+import javax.swing.JPopupMenu;
+import javax.swing.JTable;
+import javax.swing.Timer;
+
+import classes.AbstractCanvasObject;
+import classes.Edge;
+import classes.GroupNode;
+import classes.HolonElement;
+import classes.HolonObject;
+import classes.Node;
+import classes.Position;
+import ui.controller.Control;
+import ui.controller.UpdateController;
+import ui.model.Model;
+
+/**
+ * Collection of methods and values needed in both <code>MyCanvas</code> and
+ * <code>UpperNodeCanvas</code>
+ * <p>
+ * Although Java works on references we chose to add explicit return values for
+ * clearer code understanding in most cases
+ *
+ * @author: I. Dix
+ */
+public abstract class AbstractCanvas extends JPanel {
+	/**
+	 * Version
+	 */
+	private static final long serialVersionUID = 1L;
+	
+	final JMenuItem itemDelete = new JMenuItem(Languages.getLanguage()[98]);
+	final JMenuItem itemCut = new JMenuItem(Languages.getLanguage()[95]);
+	final JMenuItem itemCopy = new JMenuItem(Languages.getLanguage()[96]);
+	final JMenuItem itemPaste = new JMenuItem(Languages.getLanguage()[97]);
+	final JMenuItem itemGroup = new JMenuItem(Languages.getLanguage()[99]);
+	final JMenuItem itemUngroup = new JMenuItem(Languages.getLanguage()[100]);
+	final JMenuItem itemTrack = new JMenuItem(Languages.getLanguage()[101]);
+	final JMenuItem itemUntrack = new JMenuItem(Languages.getLanguage()[102]);
+	final JMenuItem itemAlign = new JMenuItem("Align selected");
+	final JMenuItem itemCreateTemplate = new JMenuItem(Languages.getLanguage()[Languages.right_click_create_template]);
+	
+	final int ANIMTIME = 500; // animation Time
+	private final int animFPS = 60;
+	final int animDelay = 1000 / animFPS; // animation Delay
+	protected Model model;
+	protected Control controller;
+	protected int x = 0;
+	protected int y = 0;
+	// Selection
+	AbstractCanvasObject tempCps = null;
+	UpdateController updCon;
+	
+	//Replacement
+	/**
+	 * the CpsObject that might be replaced by drag&drop
+	 */
+	protected AbstractCanvasObject mayBeReplaced = null;
+	
+	// PopUpMenu
+	JPopupMenu popmenu = new JPopupMenu();
+	// Tooltip
+	boolean toolTip; // Tooltip on or off
+	Position toolTipPos = new Position(); // Tooltip Position
+	String toolTipText = "";
+	ArrayList<HolonElement> dataSelected = new ArrayList<>();
+	ArrayList<AbstractCanvasObject> tempSelected = new ArrayList<>();
+	boolean[] showedInformation = new boolean[5];
+	boolean showConnectionInformation;
+	boolean dragging = false; // for dragging
+	boolean dragged = false; // if an object/objects was/were dragged
+	boolean drawEdge = false; // for drawing edges
+	boolean doMark = false; // for double click
+	Edge edgeHighlight = null;
+	Point mousePosition = new Point(); // Mouse Position when
+	ArrayList<Position> savePos;
+	// edge Object Start Point
+	int cx, cy;
+	int sx, sy; // Mark Coords
+	Position unPos;
+	// Animation
+	Timer animT; // animation Timer
+	int animDuration = ANIMTIME; // animation Duration
+	int animSteps = animDuration / animDelay; // animation Steps;
+	ArrayList<AbstractCanvasObject> animCps = null;
+	// Graphics
+	Image img = null; // Contains the image to draw on the Canvas
+	Graphics2D g2; // For Painting
+	float scalediv20;
+	// Mouse
+	private boolean click = false;
+
+	// ------------------------------------------ METHODS
+	// ------------------------------------------
+	
+
+	
+	
+
+	class ACpsHandle{
+		public AbstractCanvasObject object;
+		ACpsHandle(AbstractCanvasObject object){
+			this.object = object;
+		}
+		public String toString() {
+			return object.toString();
+		}
+	}
+
+	void drawMarker() {
+		if (sx > x && sy > y) {
+			g2.drawRect(x, y, sx - x, sy - y);
+		} else if (sx < x && sy < y) {
+			g2.drawRect(sx, sy, x - sx, y - sy);
+		} else if (sx >= x) {
+			g2.drawRect(x, sy, sx - x, y - sy);
+		} else if (sy >= y) {
+			g2.drawRect(sx, y, x - sx, sy - y);
+		}
+	}
+	/**
+	 * @deprecated
+	 * @param g
+	 */
+	void showTooltip(Graphics g) {
+		if (toolTip) {
+			g2.setColor(new Color(255, 225, 150));
+			g2.setStroke(new BasicStroke(1));
+			int textWidth = g.getFontMetrics().stringWidth(toolTipText) + 2; // Text
+			// width
+
+			// fixed x and y Position to the screen
+			int fixXPos = toolTipPos.x - (textWidth >> 1) + model.getScaleDiv2();
+			int fixYPos = toolTipPos.y;
+
+			if (fixXPos < 0) {
+				fixXPos = 0;
+			} else if (fixXPos + textWidth + 1 > this.getWidth()) {
+				fixXPos -= (fixXPos + textWidth + 1) - this.getWidth();
+			}
+			if (fixYPos + 16 > this.getHeight()) {
+				fixYPos -= (fixYPos + 16) - this.getHeight();
+			}
+			g2.fillRect(fixXPos, fixYPos, textWidth, 15);
+			g2.setColor(Color.BLACK);
+			g2.drawRect(fixXPos, fixYPos, textWidth, 15);
+			g2.drawString(toolTipText, fixXPos + 2, fixYPos + 12);
+		}
+	}
+
+
+
+	void setRightClickMenu(MouseEvent e) {
+		if (e.getButton() == MouseEvent.BUTTON3) {
+			itemPaste.setEnabled(true);
+			if (tempCps != null) {
+				itemPaste.setEnabled(true);
+				itemDelete.setEnabled(true);
+				itemCut.setEnabled(true);
+				itemCopy.setEnabled(true);
+				itemAlign.setEnabled(true);
+				// tracking
+				if (tempCps != null) {
+					itemGroup.setEnabled(true);
+					itemTrack.setEnabled(true);
+					itemUntrack.setEnabled(true);
+				}
+				// ungrouping
+				if (tempCps instanceof GroupNode)
+					itemUngroup.setEnabled(true);
+				else
+					itemUngroup.setEnabled(false);
+				if (model.getSelectedCpsObjects().size() == 0) {
+					controller.addSelectedObject(tempCps);
+				}
+				if (tempCps instanceof HolonObject) {
+					itemCreateTemplate.setEnabled(true);
+				} else {
+					itemCreateTemplate.setEnabled(false);
+				}
+			} else {
+				itemAlign.setEnabled(false);
+				itemCut.setEnabled(false);
+				itemCopy.setEnabled(false);
+				itemGroup.setEnabled(false);
+				itemUngroup.setEnabled(false);
+				itemTrack.setEnabled(false);
+				itemUntrack.setEnabled(false);
+				itemCreateTemplate.setEnabled(false);
+				if (edgeHighlight != null) {
+					itemDelete.setEnabled(true);
+					itemPaste.setEnabled(false);
+				} else {
+					itemDelete.setEnabled(false);
+					itemPaste.setEnabled(true);
+				}
+			}
+			mousePosition = this.getMousePosition();
+			popmenu.show(e.getComponent(), e.getX(), e.getY());
+		}
+	}
+
+	void markObjects() {
+		if (doMark) {
+			doMark = false;
+			for (AbstractCanvasObject cps : tempSelected) {
+				if (!model.getSelectedCpsObjects().contains(cps)) {
+					controller.addSelectedObject(cps);
+				}
+			}
+			controller.getObjectsInDepth();
+			tempSelected.clear();
+		}
+	}
+
+
+	int[] determineMousePositionOnEdge(Edge p) {
+		int lx, ly, hx, hy;
+
+		if (p.getA().getPosition().x > p.getB().getPosition().x) {
+			hx = p.getA().getPosition().x + model.getScaleDiv2() + 7;
+			lx = p.getB().getPosition().x + model.getScaleDiv2() - 7;
+		} else {
+			lx = p.getA().getPosition().x + model.getScaleDiv2() - 7;
+			hx = p.getB().getPosition().x + model.getScaleDiv2() + 7;
+		}
+		if (p.getA().getPosition().y > p.getB().getPosition().y) {
+			hy = p.getA().getPosition().y + model.getScaleDiv2() + 7;
+			ly = p.getB().getPosition().y + model.getScaleDiv2() - 7;
+		} else {
+			ly = p.getA().getPosition().y + model.getScaleDiv2() - 7;
+			hy = p.getB().getPosition().y + model.getScaleDiv2() + 7;
+		}
+
+		return new int[] { lx, ly, hx, hy };
+	}
+
+	/**
+	 * Checks if a double click was made.
+	 *
+	 * @return true if doublecklick, false if not
+	 */
+	boolean doubleClick() {
+		if (click) {
+			click = false;
+			return true;
+		} else {
+			click = true;
+			java.util.Timer t = new java.util.Timer("doubleclickTimer", false);
+			t.schedule(new TimerTask() {
+				@Override
+				public void run() {
+					click = false;
+				}
+			}, 500);
+		}
+		return false;
+	}
+
+	boolean setToolTipInfoAndPosition(boolean on, AbstractCanvasObject cps) {
+		if (x - controller.getScale() <= cx && y - controller.getScale() <= cy && x >= cx && y >= cy) {
+			on = true;
+			toolTipPos.x = cps.getPosition().x - controller.getScaleDiv2();
+			toolTipPos.y = cps.getPosition().y + controller.getScaleDiv2();
+			toolTipText = cps.getName() + ", " + cps.getId();
+		}
+
+		return on;
+	}
+
+	abstract void drawDeleteEdge();
+
+	void triggerUpdateController() {
+		updCon.paintProperties(tempCps);
+		updCon.refreshTableHolonElement(model.getMultiTable(), model.getSingleTable());
+		updCon.refreshTableProperties(model.getPropertyTable());
+	}
+	
+	
+	/**
+	 * Checks if {@code draggedCps} or a new cpsObject at Position (x,y) could replace exactly one object
+	 * in {@code objects}.
+	 * Saves the object that would be replaced in {@link AbstractCanvas}.{@code MayBeReplaced}
+	 * @param objects list of objects that could be replaced
+	 * @param draggedCps Object that might replace
+	 * @param x Position of the objects that might replace
+	 * @param y Position of the objects that might replace
+	 * @return true if exactly one Object could be replaced 
+	 */
+	protected boolean checkForReplacement(ArrayList<AbstractCanvasObject> objects, AbstractCanvasObject draggedCps, int x, int y){
+		
+		/** distance treshold for replacement */
+		int treshhold = controller.getScale()/2;
+						
+		/** number of Objects that might be replaced (should be 1) */
+		int replaceCounter = 0;
+		
+		/** last object that could be replaced */
+		AbstractCanvasObject toBeReplaced = null;
+		
+		/** Position of object that might be replaced */
+		Position p;
+		
+		/** for each cps on Canvas */
+		if(draggedCps == null || !(draggedCps instanceof Node) && !(draggedCps instanceof Node)){
+			for (AbstractCanvasObject cps : objects){
+				/** same object -> ignore */
+				if(cps == draggedCps)continue;
+						
+				/** set Position of object that might be replaced */
+				p = cps.getPosition();
+				
+				/** if near enough */
+				if(Math.abs(x-p.x)<treshhold && Math.abs(y-p.y)<treshhold){
+					replaceCounter++;
+					toBeReplaced = cps;
+					
+					/**
+					 * if too many Objects could be replaced:
+					 * stop searching, because it would not be clear which one should
+					 * be replaced
+					 */
+					if(replaceCounter>1)break;
+				}
+			}
+		}
+		/**
+		 * return true if exactly one obect would be replaced
+		 */
+		if( replaceCounter == 1 && toBeReplaced != null){
+			mayBeReplaced = toBeReplaced;
+			return true;
+		}else{
+			mayBeReplaced = null;
+			return false;
+		}
+	}
+	
+	/**
+	 * Checks if an inserted new Object could replace exactly one object on the canvas.
+	 * Saves the object that would be replaced in {@link AbstractCanvas}.{@code MayBeReplaced}
+	 * @param x Position of the objects that might replace
+	 * @param y Position of the objects that might replace
+	 * @return true if exactly one Object could be replaced 
+	 */
+	public abstract boolean checkForReplacement(int x, int y);
+	
+		
+	/**
+	 * highlights the object that mayBeReplaced
+	 * @param g2
+	 */
+	protected void highlightMayBeReplaced(Graphics2D g2) {
+		if(mayBeReplaced != null){
+			g2.setColor(Color.RED);
+			g2.fillRect(
+					(int) (mayBeReplaced.getPosition().x
+							- controller.getScaleDiv2() - (scalediv20 + 3)),
+					(int) (mayBeReplaced.getPosition().y
+							- controller.getScaleDiv2() - (scalediv20 + 3)),
+					(int) (controller.getScale() + ((scalediv20 + 3) * 2)),
+					(int) (controller.getScale() + ((scalediv20 + 3) * 2)));
+		}
+	}
+	
+	/**
+	 * Align alle Objects on the Canvas to a Grid with objects every 10 pixels
+	 */
+	public abstract void tryToAlignObjects();
+
+	/**
+	 * Aligns the Object the a grid
+	 * @param cps Object that should be aligned
+	 * @param distance distance between the AlignmentGrid Lines. (objects every 'distance' pixels
+	 */
+	protected void align(AbstractCanvasObject cps, int distance) {
+		/** Position of the AbstractCpsObject which should be aligned */
+		Position p = cps.getPosition();
+		
+		//calculate how many pixels the cps should be decreased to align
+		/** x offset relative to a grid with lines every distance pixels */
+		int x_off = cps.getPosition().x % distance;
+		
+		/** y offset relative to a grid with lines every distance pixels */
+		int y_off = cps.getPosition().y % distance;
+		
+		//align to the other Line, if it is nearer
+		if(x_off > distance/2)
+			x_off -= distance;
+		if(y_off > distance/2)
+			y_off -= distance;
+		
+		/** set new Position */
+		cps.setPosition(p.x-x_off, p.y-y_off);
+	}
+	
+	/**
+	 * Stops Editing in HolonElementTable and PropertyTable
+	 */
+	protected void stopEditing() {
+		/**
+		 * Stop Editing, if mouse exits the Table
+		 */
+		JTable holElem = model.getTableHolonElement();
+		CellEditor cellEditor = holElem.getCellEditor();
+		if (cellEditor != null) {
+		    if (cellEditor.getCellEditorValue() != null) {
+		    	/** TODO: Maybe try to save current Data */
+		        cellEditor.stopCellEditing();
+		    } else {
+		        cellEditor.cancelCellEditing();
+		    }
+		}
+		
+		JTable propertys = model.getTableProperties();
+		cellEditor = propertys.getCellEditor();
+		if (cellEditor != null) {
+		    if (cellEditor.getCellEditorValue() != null) {
+		    	/** TODO: Maybe try to save current Data */
+		        cellEditor.stopCellEditing();
+		    } else {
+		        cellEditor.cancelCellEditing();
+		    }
+		}
+	}
+
+	/**
+	 * Closes a tab of the UpperNode with ID upperNodeID
+	 * @param upperNodeId
+	 */
+	public abstract void closeUpperNodeTab(int upperNodeId);
 }

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

@@ -3,7 +3,6 @@ package ui.view;
 import classes.AbstractCanvasObject;
 import classes.HolonElement;
 import classes.HolonObject;
-import ui.model.Model;
 import utility.ImageImport;
 
 import javax.swing.*;
@@ -46,14 +45,12 @@ public class AddElementPopUp extends JDialog {
 	private JTextField flexibleEnergy;
 	/** Flexible if checkbox is checked */
 	JCheckBox checkboxFlexible;
-	/** Model which is used */
-	private Model model;
 
 	/**
 	 * Create the AddElementPopup Dialog
 	 * @param parentFrame
 	 */
-	AddElementPopUp(JFrame parentFrame, Model model) {
+	AddElementPopUp(JFrame parentFrame) {
 		super((java.awt.Frame) null, true);
 		this.setIconImage(ImageImport.loadImage("/Images/Holeg.png", 30, 30));
 		setModalityType(java.awt.Dialog.ModalityType.APPLICATION_MODAL);

+ 539 - 522
src/ui/view/AddObjectPopUp.java

@@ -1,523 +1,540 @@
-package ui.view;
-
-import classes.AbstractCanvasObject;
-import classes.HolonBattery;
-import classes.HolonElement;
-import classes.HolonObject;
-import classes.Pair;
-import ui.controller.Control;
-import java.lang.NumberFormatException;
-import ui.model.Model;
-import utility.ImageImport;
-
-import javax.swing.*;
-import javax.swing.border.EmptyBorder;
-import javax.swing.filechooser.FileNameExtensionFilter;
-import java.awt.*;
-import java.awt.event.KeyEvent;
-import java.awt.event.KeyListener;
-import java.awt.event.MouseAdapter;
-import java.awt.event.MouseEvent;
-import java.io.*;
-import java.util.ArrayList;
-
-/**
- * Popup for adding a Holon Object to a Category.
- * 
- * @author Gruppe14
- */
-public class AddObjectPopUp extends JDialog {
-
-	private static final long serialVersionUID = 1L;
-	private AddElementPopUp addElement;
-	private JTextField objectName;
-	private JTextField sourcePath;
-	private ArrayList<HolonElement> hElements;
-	private DefaultListModel listModel;
-	private JList list;
-	private String imagePath;
-	//	private HolonObject theObject;
-	private Control controller;
-	private File selectedFile = null;
-	private String filePath = " ";
-	private String givenCategory;
-	private JLabel lblImagePreview;
-	private AbstractCanvasObject toEdit;
-	private boolean editState;
-	private boolean imageChanged = false;
-	private Model model;
-
-	/**
-	 * Launch the application.
-	 *
-	 * @param args
-	 *            standard
-	 */
-	public static void main(String[] args) {
-		try {
-			AddObjectPopUp dialog = new AddObjectPopUp(false,new HolonBattery("jo") , "hei", null);
-			dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
-			dialog.setVisible(true);
-		} catch (Exception e) {
-			e.printStackTrace();
-		}
-	}
-
-	/**
-	 * Create the dialog.
-	 * 
-	 * @param edit
-	 *            true if edit
-	 * @param obj
-	 *            the object
-	 * @param cat
-	 *            the categorie
-	 */
-    AddObjectPopUp(boolean edit, AbstractCanvasObject obj, String cat, JFrame parentFrame) {
-    	if(obj  instanceof HolonBattery)
-    	{
-    		BatteryPopUp(edit, obj, cat, parentFrame);
-    		return;
-    	}
-        toEdit = obj;
-		editState = edit;
-		this.model=model;
-		this.setIconImage(ImageImport.loadImage("/Images/Holeg.png",30,30));
-		setBounds(100, 100, 450, 342);
-        setLocationRelativeTo(parentFrame);
-        getContentPane().setLayout(new BorderLayout());
-		JPanel contentPanel = new JPanel();
-		contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
-		getContentPane().add(contentPanel, BorderLayout.CENTER);
-		contentPanel.setLayout(null);
-		hElements = new ArrayList<>();
-		this.setTitle(Languages.getLanguage()[58]);
-		{
-			JLabel lblName = new JLabel(Languages.getLanguage()[59]);
-			lblName.setHorizontalAlignment(SwingConstants.CENTER);
-			lblName.setBounds(28, 21, 76, 14);
-			contentPanel.add(lblName);
-		}
-		{
-			objectName = new JTextField();
-			objectName.addKeyListener(new KeyListener() {
-				@Override
-				public void keyPressed(KeyEvent arg0) {
-
-				}
-
-				@Override
-				public void keyReleased(KeyEvent e) {
-
-				}
-
-				@Override
-				public void keyTyped(KeyEvent e) {
-					objectName.setBackground(Color.WHITE);
-				}
-			});
-			if (edit) {
-				objectName.setText(obj.getName());
-			}
-			objectName.setBounds(98, 18, 172, 20);
-			contentPanel.add(objectName);
-			objectName.setColumns(10);
-		}
-		{
-			JButton btnBrowseImage = new JButton(Languages.getLanguage()[60]);
-			btnBrowseImage.setBounds(10, 75, 134, 23);
-			contentPanel.add(btnBrowseImage);
-			btnBrowseImage.addMouseListener(new MouseAdapter() {
-				public void mouseClicked(MouseEvent e) {
-					fileChooser();
-				}
-			});
-
-		}
-		{
-			lblImagePreview = new JLabel("");
-			lblImagePreview.setBounds(295, 3, 50, 50);
-			contentPanel.add(lblImagePreview);
-		}
-		{
-			sourcePath = new JTextField();
-			sourcePath.addKeyListener(new KeyListener() {
-				@Override
-				public void keyPressed(KeyEvent arg0) {
-				}
-
-				@Override
-				public void keyReleased(KeyEvent e) {
-				}
-
-				@Override
-				public void keyTyped(KeyEvent e) {
-					sourcePath.setBackground(Color.WHITE);
-				}
-			});
-			if (edit) {
-				lblImagePreview.setIcon(new ImageIcon(ImageImport.loadImage(obj.getImage(), 50, 50)));
-			}
-			sourcePath.setBounds(148, 77, 271, 20);
-			if(edit) {
-				this.filePath = obj.getImage();
-				sourcePath.setText(filePath);
-			}
-			contentPanel.add(sourcePath);
-			
-			sourcePath.setColumns(10);
-		}
-		{
-			JButton btnAddDefaultElement = new JButton(Languages.getLanguage()[61]);
-			btnAddDefaultElement.addActionListener(actionEvent -> {
-                addElement = new AddElementPopUp(parentFrame, model);
-                addElement.setActualCps(toEdit);
-				addElement.setVisible(true);
-				HolonElement hl = addElement.getElement();
-				hl.setSaving(new Pair<>(givenCategory, objectName.getText()));
-				// if (hl != null) {
-				// hl.setSav(givenCategory);
-				// }
-				// hl.setObj(objectName.getText());
-				addElement(hl);
-			});
-
-			btnAddDefaultElement.setBounds(270, 144, 142, 23);
-			contentPanel.add(btnAddDefaultElement);
-		}
-		{
-			JScrollPane scrollPane = new JScrollPane();
-			scrollPane.setBounds(10, 114, 236, 150);
-			contentPanel.add(scrollPane);
-			{
-
-				listModel = new DefaultListModel();
-
-				/*
-				 * HolonElement hel = new HolonElement("Test", 100, 5); String
-				 * name = hel.getEleName(); for (int i = 0; i < 11; i++) {
-				 * hel.setEleName(name + i); addElement(hel); }
-				 */
-				list = new JList(listModel);
-				scrollPane.setViewportView(list);
-			}
-		}
-		if (edit) {
-			for (HolonElement e : ((HolonObject) obj).getElements()) {
-				addElement(e);
-			}
-		}
-		{
-			JButton btnNewButton = new JButton(Languages.getLanguage()[62]);
-			btnNewButton.addActionListener(actionEvent -> {
-				int selectedIndex = list.getSelectedIndex();
-				if (selectedIndex != -1) {
-					listModel.remove(selectedIndex);
-					hElements.remove(selectedIndex);
-				}
-			});
-			btnNewButton.setBounds(270, 182, 142, 27);
-			contentPanel.add(btnNewButton);
-		}
-
-		{
-			JPanel buttonPane = new JPanel();
-			buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
-			getContentPane().add(buttonPane, BorderLayout.SOUTH);
-			{
-				JButton okButton = new JButton("OK");
-				okButton.addMouseListener(new MouseAdapter() {
-					public void mouseClicked(MouseEvent e) {
-//						Component frame = null;
-						if (objectName.getText().length() > 0) {
-							if (sourcePath.getText().equals(filePath)) {
-								imagePath = filePath;
-								if (imageChanged)
-									copieFile();
-								imageChanged = false;
-								// theObject = new
-								// HolonObject(objectName.getText());
-								// theObject.setElements(hElements);
-								// theObject.setImage(imagePath);// TODO Auto-generated catch block
-								try {
-									if (editState) {
-										controller.delObjectCategory(givenCategory, toEdit.getName());
-										hElements.forEach(ele -> ele
-												.setSaving(new Pair<>(ele.getSaving().getKey(), objectName.getText())));
-										controller.addObject(controller.searchCategory(givenCategory),
-												objectName.getText(), hElements, imagePath);
-
-									} else {
-										controller.addObject(controller.searchCategory(givenCategory),
-												objectName.getText(), hElements, imagePath);
-									}
-								} catch (Exception e2) {
-								}
-
-								// controller.addObjectCategory(controller.searchCategory(givenCategory),
-								// theObject);
-								//
-								// System.out.println(theObject.getImage());
-
-								dispose();
-							} else {
-								sourcePath.setBackground(new Color(255, 50, 50));
-							}
-						} else {
-							objectName.setBackground(new Color(255, 50, 50));
-							if (!sourcePath.getText().equals(filePath))
-								sourcePath.setBackground(new Color(255, 50, 50));
-
-						}
-					}
-				});
-				okButton.setActionCommand("OK");
-				buttonPane.add(okButton);
-				getRootPane().setDefaultButton(okButton);
-			}
-			{
-				JButton cancelButton = new JButton(Languages.getLanguage()[63]);
-				cancelButton.setActionCommand("Cancel");
-				buttonPane.add(cancelButton);
-				cancelButton.addActionListener(e -> dispose());
-			}
-		}
-	}
-    protected void BatteryPopUp(boolean edit, AbstractCanvasObject obj, String cat, JFrame parentFrame) {
-    	//TODO: Click mich <3 
-    	HolonBattery editBat = (HolonBattery) obj;
-    	//Window Settings
-    	this.setIconImage(ImageImport.loadImage("/Images/battery.png",30,30));
-    	this.setTitle("Edit Battery");
-    	setBounds(0, 0, 285, 290);
-        setLocationRelativeTo(parentFrame);
-		
-        //Labels, TextFiels, Buttons
-        JPanel myPanel = new JPanel();
-        myPanel.setLayout(null);
-        int beginBoxX = 140, beginLabelX = 30;
-        int beginColumAtY = 20, newColumY = 40;
-        JLabel batteryNameLabel = new JLabel("Name:");
-        JTextField batteryNameBox = new JTextField(10);
-        batteryNameBox.setText(editBat.getName());
-        JLabel batteryInRateLabel = new JLabel("In ratio:");
-        JTextField batteryInRateBox = new JTextField(10);
-        batteryInRateBox.setText(Float.toString(editBat.getInRatio()));
-        JLabel batteryOutRateLabel = new JLabel("Out ratio:");
-        JTextField batteryOutRateBox = new JTextField(10);
-        batteryOutRateBox.setText(Float.toString(editBat.getOutRatio()));
-        JLabel batteryCapasityLabel = new JLabel("Capacity:");
-        JTextField batteryCapasityBox = new JTextField(10);
-        batteryCapasityBox.setText(Float.toString(editBat.getCapacity()));
-        JLabel batterySOCLabel = new JLabel("State of charge:"); 
-        JTextField batterySOCBox = new JTextField(10);
-        batterySOCBox.setText(Float.toString(editBat.getInitialStateOfCharge()));
-        
-    
-        batteryNameLabel.setBounds(beginLabelX, beginColumAtY, 200, 20);
-        batteryNameBox.setBounds(beginBoxX, beginColumAtY, 100, 20);
-        myPanel.add(batteryNameLabel);
-        myPanel.add(batteryNameBox);
-        beginColumAtY += newColumY;      
-    
-        batteryInRateLabel.setBounds(beginLabelX, beginColumAtY, 200, 20);
-        batteryInRateBox.setBounds(beginBoxX, beginColumAtY, 100, 20);
-        myPanel.add(batteryInRateLabel);
-        myPanel.add(batteryInRateBox);
-        beginColumAtY += newColumY;
-		
-        batteryOutRateLabel.setBounds(beginLabelX, beginColumAtY, 200, 20);
-        batteryOutRateBox.setBounds(beginBoxX, beginColumAtY, 100, 20);
-        myPanel.add(batteryOutRateLabel);
-        myPanel.add(batteryOutRateBox);
-        beginColumAtY += newColumY;
-        
-        batteryCapasityLabel.setBounds(beginLabelX, beginColumAtY, 200, 20);
-        batteryCapasityBox.setBounds(beginBoxX, beginColumAtY, 100, 20);
-        myPanel.add(batteryCapasityLabel);
-        myPanel.add(batteryCapasityBox);
-        beginColumAtY += newColumY;
-        
-        batterySOCLabel.setBounds(beginLabelX, beginColumAtY, 200, 20);
-        batterySOCBox.setBounds(beginBoxX, beginColumAtY, 100, 20);
-        myPanel.add(batterySOCLabel);
-        myPanel.add(batterySOCBox);
-        
-        //Save , Cancel
-        JPanel bottomPanel = new JPanel();
-        bottomPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
-        
-        JButton saveButton = new JButton("Save");
-        bottomPanel.add(saveButton);
-        
-        saveButton.addActionListener(e -> {
-        	//SaveButten Event:
-        	if(batteryNameBox.getText().isEmpty()){ //Check for valid name
-        		JOptionPane.showMessageDialog(getContentPane(), "Name is empty." , "Wrong input" , JOptionPane.WARNING_MESSAGE);
-        	}else{
-        		editBat.setName(batteryNameBox.getText());
-        		try{//Check for floats inputs
-        			float changedInRatio = Float.valueOf(batteryInRateBox.getText());
-        			float changedOutRatio = Float.valueOf(batteryOutRateBox.getText());
-        			float changedCapasity = Float.valueOf(batteryCapasityBox.getText());
-        			float changedSOC = Float.valueOf(batterySOCBox.getText());
-        			//Saving:
-        			editBat.setInRatio(changedInRatio);
-        			editBat.setOutRatio(changedOutRatio);
-        			editBat.setCapacity(changedCapasity);
-        			editBat.setInitialStateOfCharge(changedSOC);
-					try {
-						controller.saveCategory();
-						controller.notifyAll();
-					} catch (Exception e1) { //Controller Exceptions
-					}
-        			dispose();
-        		}catch(NumberFormatException FloatException){
-        			String wrong= FloatException.getMessage();
-        			String message;
-        			if(wrong.startsWith("empty")){
-        				message = "A field is empty.";
-        			}else{
-        				message = wrong.substring(18) + " is not a valid Number.";
-        			}
-        			JOptionPane.showMessageDialog(getContentPane(), message, "Wrong input" , JOptionPane.WARNING_MESSAGE);
-        		}
-        	}
-        });
-        
-        JButton cancelButton = new JButton("Cancel");
-        bottomPanel.add(cancelButton);
-		cancelButton.addActionListener(e -> dispose());
-		
-		
-		
-        getContentPane().setLayout(new BorderLayout());
-		getContentPane().add(myPanel, BorderLayout.CENTER);
-		getContentPane().add(bottomPanel, BorderLayout.SOUTH);
-    }
-//	/**
-//	 * Get Jar Containing Folder.
-//	 *
-//	 * @param aclass aClass
-//	 * @return String
-//	 * @throws Exception Exception
-//	 */
-//	public static String getJarContainingFolder(Class aclass) throws Exception {
-//		CodeSource codeSource = aclass.getProtectionDomain().getCodeSource();
-//
-//		File jarFile;
-//
-//		if (codeSource.getLocation() != null) {
-//			jarFile = new File(codeSource.getLocation().toURI());
-//		} else {
-//			String path = aclass.getResource(aclass.getSimpleName() + ".class").getPath();
-//			String jarFilePath = path.substring(path.indexOf(":") + 1, path.indexOf("!"));
-//			jarFilePath = URLDecoder.decode(jarFilePath, "UTF-8");
-//			jarFile = new File(jarFilePath);
-//		}
-//		return jarFile.getParentFile().getAbsolutePath();
-//	}
-
-	/**
-	 * adds a Holon Element.
-	 *
-	 * @param hl
-	 *            the HolonElement
-	 */
-	private void addElement(HolonElement hl) {
-		hElements.add(hl);
-		listModel.addElement(hl.getAmount() + "x: " + hl.getEleName() + " " + hl.getEnergyPerElement() + "U");
-	}
-
-	/**
-	 * Choose the file.
-	 */
-	private void fileChooser() {
-		JFileChooser fileChooser = new JFileChooser();
-		FileNameExtensionFilter filter = new FileNameExtensionFilter("png, jpg or jpeg", "png", "jpg", "jpeg");
-		fileChooser.setFileFilter(filter);
-		int returnValue = fileChooser.showOpenDialog(null);
-		if (returnValue == JFileChooser.APPROVE_OPTION) {
-			selectedFile = fileChooser.getSelectedFile();
-			filePath = selectedFile.getAbsolutePath();
-			sourcePath.setText(filePath);
-			ImageIcon icon = new ImageIcon(//TODO: ugly
-					
-					new ImageIcon(filePath).getImage().getScaledInstance(50, 50, Image.SCALE_SMOOTH));
-			lblImagePreview.setIcon(icon);
-			imageChanged = true;
-		} else {
-			System.out.println("Failed to Load");
-		}
-
-	}
-
-	/**
-	 * Copies the File.
-	 */
-	private void copieFile() {
-		InputStream inStream;
-		OutputStream outStream;
-		try {
-			File source = new File(filePath);
-			File dest = new File(System.getProperty("user.home") + "/.config/HolonGUI/Images/");
-			dest.mkdirs();
-			dest = new File(dest, selectedFile.getName());
-			imagePath = "" + dest;
-
-			inStream = new FileInputStream(source);
-			outStream = new FileOutputStream(dest);
-			byte[] buffer = new byte[1024];
-
-			int length;
-			while ((length = inStream.read(buffer)) > 0) {
-				outStream.write(buffer, 0, length);
-			}
-
-			inStream.close();
-			outStream.close();
-			System.out.println("File Copied..");
-		} catch (IOException eex) {
-			eex.printStackTrace();
-		}
-	}
-
-//	/**
-//	 * Edit the Information.
-//	 *
-//	 * @param obj
-//	 *            the CpsObject
-//	 */
-//	public void editInformation(HolonObject obj) {
-//		objectName.setText(obj.getName());
-//	}
-
-//	/**
-//	 * Return the Object.
-//	 *
-//	 * @return the CpsObject
-//	 */
-//	public HolonObject getObject() {
-//		return theObject;
-//	}
-
-	/**
-	 * Sets the Controller.
-	 * 
-	 * @param controller
-	 *            the controller
-	 */
-	public void setController(Control controller) {
-		this.controller = controller;
-	}
-
-	/**
-	 * Set the Category.
-	 * 
-	 * @param cat
-	 *            the Category
-	 */
-	public void setCategory(String cat) {
-		givenCategory = cat;
-	}
+package ui.view;
+
+import java.awt.BorderLayout;
+import java.awt.Color;
+import java.awt.FlowLayout;
+import java.awt.Image;
+import java.awt.event.KeyEvent;
+import java.awt.event.KeyListener;
+import java.awt.event.MouseAdapter;
+import java.awt.event.MouseEvent;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.ArrayList;
+
+import javax.swing.DefaultListModel;
+import javax.swing.ImageIcon;
+import javax.swing.JButton;
+import javax.swing.JDialog;
+import javax.swing.JFileChooser;
+import javax.swing.JFrame;
+import javax.swing.JLabel;
+import javax.swing.JList;
+import javax.swing.JOptionPane;
+import javax.swing.JPanel;
+import javax.swing.JScrollPane;
+import javax.swing.JTextField;
+import javax.swing.SwingConstants;
+import javax.swing.border.EmptyBorder;
+import javax.swing.filechooser.FileNameExtensionFilter;
+
+import classes.AbstractCanvasObject;
+import classes.HolonBattery;
+import classes.HolonElement;
+import classes.HolonObject;
+import classes.Pair;
+import ui.controller.Control;
+import utility.ImageImport;
+
+/**
+ * Popup for adding a Holon Object to a Category.
+ * 
+ * @author Gruppe14
+ */
+public class AddObjectPopUp extends JDialog {
+
+	private static final long serialVersionUID = 1L;
+	private AddElementPopUp addElement;
+	private JTextField objectName;
+	private JTextField sourcePath;
+	private ArrayList<HolonElement> hElements;
+	private DefaultListModel<String> listModel;
+	private JList<String> list;
+	private String imagePath;
+	//	private HolonObject theObject;
+	private Control controller;
+	private File selectedFile = null;
+	private String filePath = " ";
+	private String givenCategory;
+	private JLabel lblImagePreview;
+	private AbstractCanvasObject toEdit;
+	private boolean editState;
+	private boolean imageChanged = false;
+
+	/**
+	 * Launch the application.
+	 *
+	 * @param args
+	 *            standard
+	 */
+	public static void main(String[] args) {
+		try {
+			AddObjectPopUp dialog = new AddObjectPopUp(false,new HolonBattery("jo") , "hei", null);
+			dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
+			dialog.setVisible(true);
+		} catch (Exception e) {
+			e.printStackTrace();
+		}
+	}
+
+	/**
+	 * Create the dialog.
+	 * 
+	 * @param edit
+	 *            true if edit
+	 * @param obj
+	 *            the object
+	 * @param cat
+	 *            the categorie
+	 */
+    AddObjectPopUp(boolean edit, AbstractCanvasObject obj, String cat, JFrame parentFrame) {
+    	if(obj  instanceof HolonBattery)
+    	{
+    		BatteryPopUp(edit, obj, cat, parentFrame);
+    		return;
+    	}
+        toEdit = obj;
+		editState = edit;
+		this.setIconImage(ImageImport.loadImage("/Images/Holeg.png",30,30));
+		setBounds(100, 100, 450, 342);
+        setLocationRelativeTo(parentFrame);
+        getContentPane().setLayout(new BorderLayout());
+		JPanel contentPanel = new JPanel();
+		contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
+		getContentPane().add(contentPanel, BorderLayout.CENTER);
+		contentPanel.setLayout(null);
+		hElements = new ArrayList<>();
+		this.setTitle(Languages.getLanguage()[58]);
+		{
+			JLabel lblName = new JLabel(Languages.getLanguage()[59]);
+			lblName.setHorizontalAlignment(SwingConstants.CENTER);
+			lblName.setBounds(28, 21, 76, 14);
+			contentPanel.add(lblName);
+		}
+		{
+			objectName = new JTextField();
+			objectName.addKeyListener(new KeyListener() {
+				@Override
+				public void keyPressed(KeyEvent arg0) {
+
+				}
+
+				@Override
+				public void keyReleased(KeyEvent e) {
+
+				}
+
+				@Override
+				public void keyTyped(KeyEvent e) {
+					objectName.setBackground(Color.WHITE);
+				}
+			});
+			if (edit) {
+				objectName.setText(obj.getName());
+			}
+			objectName.setBounds(98, 18, 172, 20);
+			contentPanel.add(objectName);
+			objectName.setColumns(10);
+		}
+		{
+			JButton btnBrowseImage = new JButton(Languages.getLanguage()[60]);
+			btnBrowseImage.setBounds(10, 75, 134, 23);
+			contentPanel.add(btnBrowseImage);
+			btnBrowseImage.addMouseListener(new MouseAdapter() {
+				public void mouseClicked(MouseEvent e) {
+					fileChooser();
+				}
+			});
+
+		}
+		{
+			lblImagePreview = new JLabel("");
+			lblImagePreview.setBounds(295, 3, 50, 50);
+			contentPanel.add(lblImagePreview);
+		}
+		{
+			sourcePath = new JTextField();
+			sourcePath.addKeyListener(new KeyListener() {
+				@Override
+				public void keyPressed(KeyEvent arg0) {
+				}
+
+				@Override
+				public void keyReleased(KeyEvent e) {
+				}
+
+				@Override
+				public void keyTyped(KeyEvent e) {
+					sourcePath.setBackground(Color.WHITE);
+				}
+			});
+			if (edit) {
+				lblImagePreview.setIcon(new ImageIcon(ImageImport.loadImage(obj.getImage(), 50, 50)));
+			}
+			sourcePath.setBounds(148, 77, 271, 20);
+			if(edit) {
+				this.filePath = obj.getImage();
+				sourcePath.setText(filePath);
+			}
+			contentPanel.add(sourcePath);
+			
+			sourcePath.setColumns(10);
+		}
+		{
+			JButton btnAddDefaultElement = new JButton(Languages.getLanguage()[61]);
+			btnAddDefaultElement.addActionListener(actionEvent -> {
+                addElement = new AddElementPopUp(parentFrame);
+                addElement.setActualCps(toEdit);
+				addElement.setVisible(true);
+				HolonElement hl = addElement.getElement();
+				hl.setSaving(new Pair<>(givenCategory, objectName.getText()));
+				// if (hl != null) {
+				// hl.setSav(givenCategory);
+				// }
+				// hl.setObj(objectName.getText());
+				addElement(hl);
+			});
+
+			btnAddDefaultElement.setBounds(270, 144, 142, 23);
+			contentPanel.add(btnAddDefaultElement);
+		}
+		{
+			JScrollPane scrollPane = new JScrollPane();
+			scrollPane.setBounds(10, 114, 236, 150);
+			contentPanel.add(scrollPane);
+			{
+
+				listModel = new DefaultListModel<String>();
+
+				/*
+				 * HolonElement hel = new HolonElement("Test", 100, 5); String
+				 * name = hel.getEleName(); for (int i = 0; i < 11; i++) {
+				 * hel.setEleName(name + i); addElement(hel); }
+				 */
+				list = new JList<String>(listModel);
+				scrollPane.setViewportView(list);
+			}
+		}
+		if (edit) {
+			for (HolonElement e : ((HolonObject) obj).getElements()) {
+				addElement(e);
+			}
+		}
+		{
+			JButton btnNewButton = new JButton(Languages.getLanguage()[62]);
+			btnNewButton.addActionListener(actionEvent -> {
+				int selectedIndex = list.getSelectedIndex();
+				if (selectedIndex != -1) {
+					listModel.remove(selectedIndex);
+					hElements.remove(selectedIndex);
+				}
+			});
+			btnNewButton.setBounds(270, 182, 142, 27);
+			contentPanel.add(btnNewButton);
+		}
+
+		{
+			JPanel buttonPane = new JPanel();
+			buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
+			getContentPane().add(buttonPane, BorderLayout.SOUTH);
+			{
+				JButton okButton = new JButton("OK");
+				okButton.addMouseListener(new MouseAdapter() {
+					public void mouseClicked(MouseEvent e) {
+//						Component frame = null;
+						if (objectName.getText().length() > 0) {
+							if (sourcePath.getText().equals(filePath)) {
+								imagePath = filePath;
+								if (imageChanged)
+									copieFile();
+								imageChanged = false;
+								// theObject = new
+								// HolonObject(objectName.getText());
+								// theObject.setElements(hElements);
+								// theObject.setImage(imagePath);// TODO Auto-generated catch block
+								try {
+									if (editState) {
+										controller.delObjectCategory(givenCategory, toEdit.getName());
+										hElements.forEach(ele -> ele
+												.setSaving(new Pair<>(ele.getSaving().getKey(), objectName.getText())));
+										controller.addObject(controller.searchCategory(givenCategory),
+												objectName.getText(), hElements, imagePath);
+
+									} else {
+										controller.addObject(controller.searchCategory(givenCategory),
+												objectName.getText(), hElements, imagePath);
+									}
+								} catch (Exception e2) {
+								}
+
+								// controller.addObjectCategory(controller.searchCategory(givenCategory),
+								// theObject);
+								//
+								// System.out.println(theObject.getImage());
+
+								dispose();
+							} else {
+								sourcePath.setBackground(new Color(255, 50, 50));
+							}
+						} else {
+							objectName.setBackground(new Color(255, 50, 50));
+							if (!sourcePath.getText().equals(filePath))
+								sourcePath.setBackground(new Color(255, 50, 50));
+
+						}
+					}
+				});
+				okButton.setActionCommand("OK");
+				buttonPane.add(okButton);
+				getRootPane().setDefaultButton(okButton);
+			}
+			{
+				JButton cancelButton = new JButton(Languages.getLanguage()[63]);
+				cancelButton.setActionCommand("Cancel");
+				buttonPane.add(cancelButton);
+				cancelButton.addActionListener(e -> dispose());
+			}
+		}
+	}
+    protected void BatteryPopUp(boolean edit, AbstractCanvasObject obj, String cat, JFrame parentFrame) {
+    	//TODO: Click mich <3 
+    	HolonBattery editBat = (HolonBattery) obj;
+    	//Window Settings
+    	this.setIconImage(ImageImport.loadImage("/Images/battery.png",30,30));
+    	this.setTitle("Edit Battery");
+    	setBounds(0, 0, 285, 290);
+        setLocationRelativeTo(parentFrame);
+		
+        //Labels, TextFiels, Buttons
+        JPanel myPanel = new JPanel();
+        myPanel.setLayout(null);
+        int beginBoxX = 140, beginLabelX = 30;
+        int beginColumAtY = 20, newColumY = 40;
+        JLabel batteryNameLabel = new JLabel("Name:");
+        JTextField batteryNameBox = new JTextField(10);
+        batteryNameBox.setText(editBat.getName());
+        JLabel batteryInRateLabel = new JLabel("In ratio:");
+        JTextField batteryInRateBox = new JTextField(10);
+        batteryInRateBox.setText(Float.toString(editBat.getInRatio()));
+        JLabel batteryOutRateLabel = new JLabel("Out ratio:");
+        JTextField batteryOutRateBox = new JTextField(10);
+        batteryOutRateBox.setText(Float.toString(editBat.getOutRatio()));
+        JLabel batteryCapasityLabel = new JLabel("Capacity:");
+        JTextField batteryCapasityBox = new JTextField(10);
+        batteryCapasityBox.setText(Float.toString(editBat.getCapacity()));
+        JLabel batterySOCLabel = new JLabel("State of charge:"); 
+        JTextField batterySOCBox = new JTextField(10);
+        batterySOCBox.setText(Float.toString(editBat.getInitialStateOfCharge()));
+        
+    
+        batteryNameLabel.setBounds(beginLabelX, beginColumAtY, 200, 20);
+        batteryNameBox.setBounds(beginBoxX, beginColumAtY, 100, 20);
+        myPanel.add(batteryNameLabel);
+        myPanel.add(batteryNameBox);
+        beginColumAtY += newColumY;      
+    
+        batteryInRateLabel.setBounds(beginLabelX, beginColumAtY, 200, 20);
+        batteryInRateBox.setBounds(beginBoxX, beginColumAtY, 100, 20);
+        myPanel.add(batteryInRateLabel);
+        myPanel.add(batteryInRateBox);
+        beginColumAtY += newColumY;
+		
+        batteryOutRateLabel.setBounds(beginLabelX, beginColumAtY, 200, 20);
+        batteryOutRateBox.setBounds(beginBoxX, beginColumAtY, 100, 20);
+        myPanel.add(batteryOutRateLabel);
+        myPanel.add(batteryOutRateBox);
+        beginColumAtY += newColumY;
+        
+        batteryCapasityLabel.setBounds(beginLabelX, beginColumAtY, 200, 20);
+        batteryCapasityBox.setBounds(beginBoxX, beginColumAtY, 100, 20);
+        myPanel.add(batteryCapasityLabel);
+        myPanel.add(batteryCapasityBox);
+        beginColumAtY += newColumY;
+        
+        batterySOCLabel.setBounds(beginLabelX, beginColumAtY, 200, 20);
+        batterySOCBox.setBounds(beginBoxX, beginColumAtY, 100, 20);
+        myPanel.add(batterySOCLabel);
+        myPanel.add(batterySOCBox);
+        
+        //Save , Cancel
+        JPanel bottomPanel = new JPanel();
+        bottomPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
+        
+        JButton saveButton = new JButton("Save");
+        bottomPanel.add(saveButton);
+        
+        saveButton.addActionListener(e -> {
+        	//SaveButten Event:
+        	if(batteryNameBox.getText().isEmpty()){ //Check for valid name
+        		JOptionPane.showMessageDialog(getContentPane(), "Name is empty." , "Wrong input" , JOptionPane.WARNING_MESSAGE);
+        	}else{
+        		editBat.setName(batteryNameBox.getText());
+        		try{//Check for floats inputs
+        			float changedInRatio = Float.valueOf(batteryInRateBox.getText());
+        			float changedOutRatio = Float.valueOf(batteryOutRateBox.getText());
+        			float changedCapasity = Float.valueOf(batteryCapasityBox.getText());
+        			float changedSOC = Float.valueOf(batterySOCBox.getText());
+        			//Saving:
+        			editBat.setInRatio(changedInRatio);
+        			editBat.setOutRatio(changedOutRatio);
+        			editBat.setCapacity(changedCapasity);
+        			editBat.setInitialStateOfCharge(changedSOC);
+					try {
+						controller.saveCategory();
+						controller.notifyAll();
+					} catch (Exception e1) { //Controller Exceptions
+					}
+        			dispose();
+        		}catch(NumberFormatException FloatException){
+        			String wrong= FloatException.getMessage();
+        			String message;
+        			if(wrong.startsWith("empty")){
+        				message = "A field is empty.";
+        			}else{
+        				message = wrong.substring(18) + " is not a valid Number.";
+        			}
+        			JOptionPane.showMessageDialog(getContentPane(), message, "Wrong input" , JOptionPane.WARNING_MESSAGE);
+        		}
+        	}
+        });
+        
+        JButton cancelButton = new JButton("Cancel");
+        bottomPanel.add(cancelButton);
+		cancelButton.addActionListener(e -> dispose());
+		
+		
+		
+        getContentPane().setLayout(new BorderLayout());
+		getContentPane().add(myPanel, BorderLayout.CENTER);
+		getContentPane().add(bottomPanel, BorderLayout.SOUTH);
+    }
+//	/**
+//	 * Get Jar Containing Folder.
+//	 *
+//	 * @param aclass aClass
+//	 * @return String
+//	 * @throws Exception Exception
+//	 */
+//	public static String getJarContainingFolder(Class aclass) throws Exception {
+//		CodeSource codeSource = aclass.getProtectionDomain().getCodeSource();
+//
+//		File jarFile;
+//
+//		if (codeSource.getLocation() != null) {
+//			jarFile = new File(codeSource.getLocation().toURI());
+//		} else {
+//			String path = aclass.getResource(aclass.getSimpleName() + ".class").getPath();
+//			String jarFilePath = path.substring(path.indexOf(":") + 1, path.indexOf("!"));
+//			jarFilePath = URLDecoder.decode(jarFilePath, "UTF-8");
+//			jarFile = new File(jarFilePath);
+//		}
+//		return jarFile.getParentFile().getAbsolutePath();
+//	}
+
+	/**
+	 * adds a Holon Element.
+	 *
+	 * @param hl
+	 *            the HolonElement
+	 */
+	private void addElement(HolonElement hl) {
+		hElements.add(hl);
+		listModel.addElement(hl.getAmount() + "x: " + hl.getEleName() + " " + hl.getEnergyPerElement() + "U");
+	}
+
+	/**
+	 * Choose the file.
+	 */
+	private void fileChooser() {
+		JFileChooser fileChooser = new JFileChooser();
+		FileNameExtensionFilter filter = new FileNameExtensionFilter("png, jpg or jpeg", "png", "jpg", "jpeg");
+		fileChooser.setFileFilter(filter);
+		int returnValue = fileChooser.showOpenDialog(null);
+		if (returnValue == JFileChooser.APPROVE_OPTION) {
+			selectedFile = fileChooser.getSelectedFile();
+			filePath = selectedFile.getAbsolutePath();
+			sourcePath.setText(filePath);
+			ImageIcon icon = new ImageIcon(//TODO: ugly
+					
+					new ImageIcon(filePath).getImage().getScaledInstance(50, 50, Image.SCALE_SMOOTH));
+			lblImagePreview.setIcon(icon);
+			imageChanged = true;
+		} else {
+			System.out.println("Failed to Load");
+		}
+
+	}
+
+	/**
+	 * Copies the File.
+	 */
+	private void copieFile() {
+		InputStream inStream;
+		OutputStream outStream;
+		try {
+			File source = new File(filePath);
+			File dest = new File(System.getProperty("user.home") + "/.config/HolonGUI/Images/");
+			dest.mkdirs();
+			dest = new File(dest, selectedFile.getName());
+			imagePath = "" + dest;
+
+			inStream = new FileInputStream(source);
+			outStream = new FileOutputStream(dest);
+			byte[] buffer = new byte[1024];
+
+			int length;
+			while ((length = inStream.read(buffer)) > 0) {
+				outStream.write(buffer, 0, length);
+			}
+
+			inStream.close();
+			outStream.close();
+			System.out.println("File Copied..");
+		} catch (IOException eex) {
+			eex.printStackTrace();
+		}
+	}
+
+//	/**
+//	 * Edit the Information.
+//	 *
+//	 * @param obj
+//	 *            the CpsObject
+//	 */
+//	public void editInformation(HolonObject obj) {
+//		objectName.setText(obj.getName());
+//	}
+
+//	/**
+//	 * Return the Object.
+//	 *
+//	 * @return the CpsObject
+//	 */
+//	public HolonObject getObject() {
+//		return theObject;
+//	}
+
+	/**
+	 * Sets the Controller.
+	 * 
+	 * @param controller
+	 *            the controller
+	 */
+	public void setController(Control controller) {
+		this.controller = controller;
+	}
+
+	/**
+	 * Set the Category.
+	 * 
+	 * @param cat
+	 *            the Category
+	 */
+	public void setCategory(String cat) {
+		givenCategory = cat;
+	}
 }

+ 4 - 9
src/ui/view/AddOnWindow.java

@@ -5,29 +5,23 @@ import java.awt.Dimension;
 import java.awt.Font;
 import java.io.File;
 import java.io.FileNotFoundException;
-import java.io.FileReader;
+import java.lang.reflect.InvocationTargetException;
 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;
 
@@ -35,7 +29,6 @@ import api.AddOn;
 import ui.controller.Control;
 import utility.ImageImport;
 
-@SuppressWarnings("serial")
 public class AddOnWindow extends JFrame{
 	private AddOn actual;
 	private Control control;
@@ -159,7 +152,7 @@ public class AddOnWindow extends JFrame{
 		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();
+		Object object = cls.getDeclaredConstructor().newInstance();
 		if(!(object instanceof AddOn)) {
 			generateErrorDialog("Class does not implement CpsAlgorithm!");
 		}else {
@@ -176,6 +169,8 @@ public class AddOnWindow extends JFrame{
 			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());
+		}	catch (IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) {
+			e.printStackTrace();
 		}
 	}
 	/**

+ 0 - 1
src/ui/view/BackgroundPopUp.java

@@ -24,7 +24,6 @@ public class BackgroundPopUp extends JDialog {
     /**
      *
      */
-	private static final long serialVersionUID = 1L;
 	private final JTextField textPath = new JTextField("");
 	private final JButton btnBrowse = new JButton("Browse");
 	private final JPanel panelBrowse = new JPanel();

+ 0 - 5
src/ui/view/CanvasResizePopUp.java

@@ -10,11 +10,6 @@ import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;
 
 public class CanvasResizePopUp extends JDialog {
-
-    /**
-     *
-     */
-    private static final long serialVersionUID = 1L;
     private final JButton btnOk = new JButton("OK");
 	private final JButton btnCancel = new JButton("Cancel");
 	JTabbedPane tabbedPane;

+ 71 - 73
src/ui/view/Console.java

@@ -1,73 +1,71 @@
-package ui.view;
-
-import java.awt.BorderLayout;
-import java.awt.Component;
-import java.awt.FlowLayout;
-
-import javax.swing.Box;
-import javax.swing.ImageIcon;
-import javax.swing.JButton;
-import javax.swing.JPanel;
-import javax.swing.JScrollPane;
-import javax.swing.JTextArea;
-import javax.swing.JToolBar;
-import javax.swing.text.DefaultCaret;
-
-import utility.ImageImport;
-/**
- * Little new swing object to print data to a console.
- * @author tom
- *
- */
-public class Console extends JPanel {
-	private JTextArea textArea = new JTextArea();
-	private JScrollPane scrollPane;
-	
-	public Console() {
-		super();
-		this.setLayout(new BorderLayout());
-		textArea.setEditable(false);
-		DefaultCaret caret = (DefaultCaret)textArea.getCaret();
-		caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
-		scrollPane = new JScrollPane(textArea);
-		this.add(scrollPane, BorderLayout.CENTER);
-		JToolBar toolBar = new JToolBar();
-		toolBar.setFloatable(false);
-		JButton clearButton  = new JButton("", new ImageIcon(ImageImport.loadImage("/Button_Images/Clear.png", 24, 24)));
-		clearButton.setToolTipText("Clear Console");
-		clearButton.addActionListener(actionEvent -> clear());
-		toolBar.add(clearButton);
-		toolBar.add(Box.createHorizontalGlue());
-		JButton topButton = new JButton("", new ImageIcon(ImageImport.loadImage("/Button_Images/Top.png", 24, 24)));
-		topButton.setToolTipText("Scroll to top");
-		topButton.addActionListener(actionEvent -> scrollToTop());
-		toolBar.add(topButton);
-		JButton botButton = new JButton("", new ImageIcon(ImageImport.loadImage("/Button_Images/Bottom.png", 24, 24)));
-		botButton.setToolTipText("Scroll to bottom");
-		botButton.addActionListener(actionEvent -> scrollToBottom());
-		toolBar.add(botButton);
-		scrollPane.setColumnHeaderView(toolBar);
-	}
-	private void scrollToTop() {
-		textArea.setCaretPosition(0);
-	}
-	private void scrollToBottom() {
-		textArea.setCaretPosition(textArea.getDocument().getLength());
-	}
-	
-	
-	
-	
-	
-	
-	public void clear() {
-		textArea.setText("");
-	}
-	public void print(String message) {
-		textArea.append(message);
-		
-	}
-	public void println(String message) {
-		textArea.append(message  + "\n");
-	}
-}
+package ui.view;
+
+import java.awt.BorderLayout;
+
+import javax.swing.Box;
+import javax.swing.ImageIcon;
+import javax.swing.JButton;
+import javax.swing.JPanel;
+import javax.swing.JScrollPane;
+import javax.swing.JTextArea;
+import javax.swing.JToolBar;
+import javax.swing.text.DefaultCaret;
+
+import utility.ImageImport;
+/**
+ * Little new swing object to print data to a console.
+ * @author tom
+ *
+ */
+public class Console extends JPanel {
+	private JTextArea textArea = new JTextArea();
+	private JScrollPane scrollPane;
+	
+	public Console() {
+		super();
+		this.setLayout(new BorderLayout());
+		textArea.setEditable(false);
+		DefaultCaret caret = (DefaultCaret)textArea.getCaret();
+		caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
+		scrollPane = new JScrollPane(textArea);
+		this.add(scrollPane, BorderLayout.CENTER);
+		JToolBar toolBar = new JToolBar();
+		toolBar.setFloatable(false);
+		JButton clearButton  = new JButton("", new ImageIcon(ImageImport.loadImage("/Button_Images/Clear.png", 24, 24)));
+		clearButton.setToolTipText("Clear Console");
+		clearButton.addActionListener(actionEvent -> clear());
+		toolBar.add(clearButton);
+		toolBar.add(Box.createHorizontalGlue());
+		JButton topButton = new JButton("", new ImageIcon(ImageImport.loadImage("/Button_Images/Top.png", 24, 24)));
+		topButton.setToolTipText("Scroll to top");
+		topButton.addActionListener(actionEvent -> scrollToTop());
+		toolBar.add(topButton);
+		JButton botButton = new JButton("", new ImageIcon(ImageImport.loadImage("/Button_Images/Bottom.png", 24, 24)));
+		botButton.setToolTipText("Scroll to bottom");
+		botButton.addActionListener(actionEvent -> scrollToBottom());
+		toolBar.add(botButton);
+		scrollPane.setColumnHeaderView(toolBar);
+	}
+	private void scrollToTop() {
+		textArea.setCaretPosition(0);
+	}
+	private void scrollToBottom() {
+		textArea.setCaretPosition(textArea.getDocument().getLength());
+	}
+	
+	
+	
+	
+	
+	
+	public void clear() {
+		textArea.setText("");
+	}
+	public void print(String message) {
+		textArea.append(message);
+		
+	}
+	public void println(String message) {
+		textArea.append(message  + "\n");
+	}
+}

+ 3 - 3
src/ui/view/NewPopUp.java → src/ui/view/CreateNewDialog.java

@@ -21,7 +21,7 @@ import ui.controller.Control;
 
 
 
-public class NewPopUp extends JDialog{
+public class CreateNewDialog extends JDialog{
 	//DefaultConstructor
 	String[] optionStrings = { "","Category", "Object", "Battery", "Switch"};
 	public static enum Option {
@@ -47,7 +47,7 @@ public class NewPopUp extends JDialog{
 	
 	
 	
-	NewPopUp(Control controller, JFrame parentFrame){
+	CreateNewDialog(Control controller, JFrame parentFrame){
 		super((JFrame)parentFrame, "Create a..");
 		actualController = controller;
 		setVisible(true);
@@ -82,7 +82,7 @@ public class NewPopUp extends JDialog{
 	}
 
 
-	NewPopUp(Control controller, Option aOption, JFrame parentFrame){
+	CreateNewDialog(Control controller, Option aOption, JFrame parentFrame){
 		super((JFrame)parentFrame, "Create a " + aOption.name());
 		actualController = controller;
 		if(aOption == Option.None)

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

@@ -1,6 +1,24 @@
 package ui.view;
 
-import classes.AbstractCanvasObject;
+import java.awt.BorderLayout;
+import java.awt.Choice;
+import java.io.File;
+import java.io.IOException;
+
+import javax.swing.DefaultListModel;
+import javax.swing.ImageIcon;
+import javax.swing.JButton;
+import javax.swing.JDialog;
+import javax.swing.JFileChooser;
+import javax.swing.JFrame;
+import javax.swing.JLabel;
+import javax.swing.JList;
+import javax.swing.JPanel;
+import javax.swing.JScrollPane;
+import javax.swing.JTextField;
+import javax.swing.border.EmptyBorder;
+import javax.swing.filechooser.FileNameExtensionFilter;
+
 import classes.Category;
 import classes.HolonElement;
 import classes.HolonObject;
@@ -9,20 +27,6 @@ import ui.controller.Control;
 import ui.model.Model;
 import utility.ImageImport;
 
-import javax.swing.*;
-import javax.swing.border.EmptyBorder;
-import javax.swing.filechooser.FileNameExtensionFilter;
-
-import java.awt.*;
-import java.awt.event.KeyEvent;
-import java.awt.event.KeyListener;
-import java.awt.event.MouseAdapter;
-import java.awt.event.MouseEvent;
-import java.io.*;
-import java.util.ArrayList;
-import java.awt.event.ActionListener;
-import java.awt.event.ActionEvent;
-
 /**
  * PopUp for creating Holon Object Template.
  * 
@@ -80,9 +84,6 @@ public class CreateTemplatePopUp extends JDialog {
 	/**
 	 * parent Frame
 	 */
-	
-	private Model model;
-	
 	JFrame parent;
 	/**
 	 * Create the dialog.
@@ -108,7 +109,6 @@ public class CreateTemplatePopUp extends JDialog {
 		template = new HolonObject(obj);
 		this.parent = parentFrame;
 		this.controller = controller;
-		this.model=model;//Thankfully that was in the ctor already.
 		/*
 		 * create Frame and GUI
 		 */
@@ -316,7 +316,7 @@ public class CreateTemplatePopUp extends JDialog {
 	 * Add an Holon Element to the template
 	 */
 	private void addElement() {
-		AddElementPopUp popUp = new AddElementPopUp(parent, model);
+		AddElementPopUp popUp = new AddElementPopUp(parent);
 		popUp.setActualCps(template);
 		popUp.setVisible(true);
 		HolonElement he = popUp.getElement();
@@ -347,7 +347,7 @@ public class CreateTemplatePopUp extends JDialog {
 		if (index == -1)
 			return;
 		
-		AddElementPopUp popUp = new AddElementPopUp(parent, model);
+		AddElementPopUp popUp = new AddElementPopUp(parent);
 		popUp.setActualCps(template);
 		popUp.setElement(template.getElements().get(index));
 		popUp.setVisible(true);

+ 0 - 99
src/ui/view/DisplayedInformationPopUp.java

@@ -1,99 +0,0 @@
-package ui.view;
-
-import ui.controller.Control;
-
-import javax.swing.*;
-import javax.swing.border.EmptyBorder;
-import java.awt.*;
-
-/**
- * This Class represents a Popup to edit the shown Information.
- * 
- * @author Gruppe14
- */
-public class DisplayedInformationPopUp extends JDialog {
-
-	private static final long serialVersionUID = 1L;
-	private final JPanel contentPanel = new JPanel();
-	private final JButton btnOk = new JButton("OK");
-	private MyCanvas canvas;
-	private Control controller;
-	private JCheckBox objectEnergyCheckbox;
-	private JCheckBox connectionCheckbox;
-	private JCheckBox colorizedBorderCheckbox;
-	private JCheckBox nodeOfnodeConnectionCheckbox;
-	private JPanel toUpdate;
-
-	/**
-	 * Constructor.
-	 * 
-	 * @param canvas
-	 *            the Canvas
-	 */
-    public DisplayedInformationPopUp(MyCanvas canvas, JPanel update, Control cont, JFrame parentFrame) {
-        super((java.awt.Frame) null, true);
-		setModalityType(java.awt.Dialog.ModalityType.APPLICATION_MODAL);
-		this.setTitle("Edit Displayed Informations");
-		setBounds(100, 100, 400, 276);
-        setLocationRelativeTo(parentFrame);
-        getContentPane().setLayout(new BorderLayout());
-		contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
-		getContentPane().add(contentPanel, BorderLayout.CENTER);
-		contentPanel.setLayout(null);
-		this.canvas = canvas;
-		this.toUpdate = update;
-		controller = cont;
-
-		objectEnergyCheckbox = new JCheckBox("Display Total Energy of Objects");
-		objectEnergyCheckbox.setBounds(19, 19, 300, 23);
-		contentPanel.add(objectEnergyCheckbox);
-
-		connectionCheckbox = new JCheckBox("Display Connection Properties");
-		connectionCheckbox.setBounds(19, 57, 300, 23);
-		connectionCheckbox.setSelected(true);
-		contentPanel.add(connectionCheckbox);
-
-		objectEnergyCheckbox.setSelected(canvas.getShowedInformation()[1]);
-		connectionCheckbox.setSelected(canvas.getShowedInformation()[0]);
-		btnOk.addActionListener(actionEvent -> {
-			setInformation(connectionCheckbox.isSelected(), objectEnergyCheckbox.isSelected(),
-					colorizedBorderCheckbox.isSelected(), nodeOfnodeConnectionCheckbox.isSelected());
-			controller.getSimManager().getFlexiblePane().recalculate();
-			dispose();
-		});
-		btnOk.setBounds(174, 193, 82, 23);
-		contentPanel.add(btnOk);
-
-		JButton btnCancel = new JButton(Languages.getLanguage()[34]);
-		btnCancel.setActionCommand(Languages.getLanguage()[34]);
-		btnCancel.addActionListener(actionEvent -> dispose());
-		btnCancel.setBounds(69, 193, 89, 23);
-		contentPanel.add(btnCancel);
-		
-		colorizedBorderCheckbox = new JCheckBox("Display colorized Border for Objects");
-		colorizedBorderCheckbox.setBounds(19, 96, 369, 23);
-		contentPanel.add(colorizedBorderCheckbox);
-		colorizedBorderCheckbox.setSelected(canvas.getShowedInformation()[3]);
-		
-		nodeOfnodeConnectionCheckbox = new JCheckBox("Display outside Connections in gouped Nodes");
-		nodeOfnodeConnectionCheckbox.setBounds(19, 133, 369, 23);
-		contentPanel.add(nodeOfnodeConnectionCheckbox);
-		nodeOfnodeConnectionCheckbox.setSelected(canvas.getShowedInformation()[4]);
-	}
-
-	/**
-	 * Set the Information true or false.
-	 * 
-	 * @param connection
-	 *            conection Information
-	 * @param object
-	 *            Object Information
-	 * @param nodeOfnode 
-	 */
-	private void setInformation(boolean connection, boolean object, boolean borders, boolean nodeOfnode) {
-		canvas.setShowedInformation(connection, object, borders, nodeOfnode);
-		canvas.repaint();
-		toUpdate.updateUI();
-		
-	}
-}

+ 16 - 9
src/ui/view/EditEdgesPopUp.java

@@ -1,16 +1,24 @@
 package ui.view;
 
-import classes.AbstractCanvasObject;
-import classes.Edge;
-import classes.GroupNode;
-import ui.controller.Control;
-
-import javax.swing.*;
-import javax.swing.border.EmptyBorder;
-import java.awt.*;
+import java.awt.BorderLayout;
+import java.awt.Font;
 import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;
 
+import javax.swing.ButtonGroup;
+import javax.swing.JButton;
+import javax.swing.JDialog;
+import javax.swing.JFrame;
+import javax.swing.JLabel;
+import javax.swing.JOptionPane;
+import javax.swing.JPanel;
+import javax.swing.JRadioButton;
+import javax.swing.JTextField;
+import javax.swing.border.EmptyBorder;
+
+import classes.Edge;
+import ui.controller.Control;
+
 /**
  * Popup for Editing Edges.
  * 
@@ -27,7 +35,6 @@ public class EditEdgesPopUp extends JDialog {
 	private JRadioButton rdbtnChangeForAll1;
 	private Control controller;
 	private MyCanvas canvas;
-	private JLabel lblenterinfiniteFor;
 
 	/**
 	 * Launch the application.

+ 0 - 102
src/ui/view/FlexSubData.java

@@ -1,102 +0,0 @@
-package ui.view;
-
-import javax.swing.JSplitPane;
-import javax.swing.JPanel;
-import javax.swing.BoxLayout;
-import javax.swing.JButton;
-
-import java.awt.Dimension;
-import java.awt.event.ActionEvent;
-import java.awt.event.ActionListener;
-import java.awt.event.ItemEvent;
-import java.awt.event.ItemListener;
-
-import javax.swing.JToggleButton;
-import java.awt.Component;
-
-public class FlexSubData extends JSplitPane {
-	public static final String HIDE = "Hide Objects";
-	public static final String SHOW = "Show Objects";
-	private JPanel subnetInfo;
-	private JPanel objectInfo;
-	private JPanel currentObj;
-	private JButton btnShowObjects;
-	private FlexiblePane listener;
-	private boolean shown; // 0 = Hide, 1= Show
-	public FlexSubData(FlexibleData fD) {
-		setDividerSize(0);
-		setAlignmentY(Component.CENTER_ALIGNMENT);
-		setAlignmentX(Component.CENTER_ALIGNMENT);
-		setOrientation(JSplitPane.VERTICAL_SPLIT);
-		
-		//subnetInfo = new FlexibleData("test" , 0, 0);
-		subnetInfo = fD;
-		subnetInfo.setMinimumSize(new Dimension(600, 100));
-		setLeftComponent(subnetInfo);
-		subnetInfo.setLayout(null);
-		shown = true;
-		btnShowObjects = new JButton(SHOW);
-		btnShowObjects.setBounds(135, 13, 99, 23);
-		btnShowObjects.addActionListener(new ActionListener(){
-			public void actionPerformed(ActionEvent e){
-				if(shown){
-					objectInfo.removeAll();
-					objectInfo.add(currentObj);
-					objectInfo.revalidate();
-					objectInfo.updateUI();
-					listener.revalidate();
-					btnShowObjects.setText(HIDE);
-					shown = false;
-				}else{
-					objectInfo.removeAll();
-					objectInfo.revalidate();
-					objectInfo.updateUI();
-					listener.revalidate();
-					btnShowObjects.setText(SHOW);
-					shown = true;
-				}
-			}
-		});
-		subnetInfo.add(btnShowObjects);
-
-		objectInfo = new JPanel();
-		setRightComponent(objectInfo);
-		objectInfo.setLayout(new BoxLayout(objectInfo, BoxLayout.X_AXIS));
-	}
-	
-	public void setObjects(JPanel obj){
-		objectInfo.removeAll();
-		currentObj = obj;
-	}
-	
-	public void setListener(FlexiblePane fP){
-		listener = fP;
-	}
-	
-	public JPanel getSubInfo(){
-		return subnetInfo;
-	}
-	
-	public void repaint(){
-		super.repaint();
-	}
-	
-	public void showAction(){
-		objectInfo.removeAll();
-		objectInfo.add(currentObj);
-		objectInfo.revalidate();
-		objectInfo.updateUI();
-		listener.revalidate();
-		shown = false;
-		btnShowObjects.setText(HIDE);
-	}
-	
-	public void hideAction(){
-		objectInfo.removeAll();
-		objectInfo.revalidate();
-		objectInfo.updateUI();
-		listener.revalidate();
-		shown = true;
-		btnShowObjects.setText(SHOW);
-	}
-}

+ 0 - 115
src/ui/view/FlexibleData.java

@@ -1,115 +0,0 @@
-package ui.view;
-
-import javax.swing.JPanel;
-import javax.swing.JProgressBar;
-import javax.swing.JLabel;
-import java.awt.Font;
-import java.awt.Dimension;
-import java.awt.Color;
-import javax.swing.JSplitPane;
-import javax.swing.border.EmptyBorder;
-
-
-
-@Deprecated
-public class FlexibleData extends JPanel {
-	private JLabel name_lbl;
-	private JProgressBar prodVal;
-	private JProgressBar consVal;
-	private JLabel lblProdConsVal;
-	private JPanel subnetColorPanel;
-	public FlexibleData(String name, float prod, float cons, float maxProd, float maxCons) {
-		setPreferredSize(new Dimension(570, 100));
-		setMinimumSize(new Dimension(550, 100));
-		setLayout(null);
-		
-		name_lbl = new JLabel();
-		name_lbl.setFont(new Font("Tahoma", Font.PLAIN, 11));
-		name_lbl.setBounds(10, 11, 85, 27);
-		setlblName(name);
-		add(name_lbl);
-		
-		JLabel lblFlProd = new JLabel("Flex. Prod.:");
-		lblFlProd.setForeground(new Color(0, 204, 51));
-		lblFlProd.setBounds(10, 46, 85, 27);
-		add(lblFlProd);
-		
-		JLabel lblFlexCons = new JLabel("Flex. Cons.:\r\n");
-		lblFlexCons.setForeground(new Color(255, 0, 0));
-		lblFlexCons.setBounds(188, 46, 85, 27);
-		add(lblFlexCons);
-		
-		JLabel lblProdCons = new JLabel("Prod./Cons.:");
-		lblProdCons.setForeground(new Color(218, 165, 32));
-		lblProdCons.setBounds(365, 46, 113, 27);
-		add(lblProdCons);
-		
-		prodVal = new JProgressBar();
-		setProd(maxProd, prod);
-		prodVal.setBounds(94, 48, 85, 24);
-		prodVal.setBorder(new EmptyBorder(0, 0, 0, 0));
-		prodVal.setStringPainted(true);
-		prodVal.setForeground(new Color(0, 204, 51));
-		add(prodVal);
-		
-		consVal = new JProgressBar();
-		setCons(maxCons, cons);
-		consVal.setBounds(270, 46, 85, 24);
-		consVal.setBorder(new EmptyBorder(0, 0, 0, 0));
-		consVal.setStringPainted(true);
-		consVal.setForeground(Color.RED);
-		add(consVal);
-		
-		lblProdConsVal = new JLabel();
-		setProdConsVal(prod, cons);
-		lblProdConsVal.setBounds(453, 46, 103, 24);
-		add(lblProdConsVal);
-		
-		subnetColorPanel = new JPanel();
-		subnetColorPanel.setBackground(new Color(255, 255, 255));
-		subnetColorPanel.setForeground(new Color(0, 0, 0));
-		subnetColorPanel.setBounds(94, 11, 31, 27);
-		add(subnetColorPanel);
-	}
-	
-	public void setProd(float max, float current){
-		int val = prodVal.getMaximum();
-		if(max != 0){
-		val = Math.round((current/max)*prodVal.getMaximum());
-		}
-		prodVal.setValue(val);
-		prodVal.setString(Float.toString(current));
-	}
-	
-	public void setCons(float max, float current){
-		int val = prodVal.getMaximum();
-		if(max != 0){
-		val = Math.round((current/max)*prodVal.getMaximum());
-		}
-		consVal.setValue(val);
-		consVal.setString(Float.toString(current));
-	}
-	
-	public void setProdConsVal(float prod, float cons){
-		if(cons != 0){
-			lblProdConsVal.setText(Float.toString((prod/cons)*(-1)));
-		}else if(prod == 0){
-			lblProdConsVal.setText(Float.toString(0));
-		}
-		else{
-			lblProdConsVal.setText(Character.toString('\u221e'));
-		}
-	}
-	
-	public void setlblName(String name){
-		name_lbl.setText(name);
-	}
-	
-	public JPanel getColorPanel(){
-		return subnetColorPanel;
-	}
-	
-	public JLabel getNamelbl(){
-		return name_lbl;
-	}
-}

+ 0 - 113
src/ui/view/FlexiblePane.java

@@ -1,113 +0,0 @@
-package ui.view;
-
-import java.awt.Color;
-import java.awt.Component;
-import java.awt.Font;
-import java.awt.event.ComponentAdapter;
-import java.awt.event.ComponentEvent;
-import java.util.ArrayList;
-import java.util.LinkedList;
-
-import javax.swing.BoxLayout;
-import javax.swing.JPanel;
-import javax.swing.JScrollPane;
-
-import classes.AbstractCanvasObject;
-import classes.HolonObject;
-import classes.SubNet;
-import interfaces.ObjectListener;
-import ui.controller.Control;
-
-public class FlexiblePane extends JScrollPane implements ObjectListener {
-	private JPanel flexPanel;
-	private Control controller;
-	
-	public FlexiblePane(Control controller) {
-		this.controller = controller;
-		flexPanel = new JPanel();
-		flexPanel.setLayout(new BoxLayout(flexPanel, BoxLayout.Y_AXIS));
-		setViewportView(flexPanel);
-		class ResizeListener extends ComponentAdapter{
-			public void componentResized(ComponentEvent e){
-				flexPanel.requestFocusInWindow();
-			}
-		}
-		this.addComponentListener(new ResizeListener());
-	}
-	
-	public void recalculate(){
-		LinkedList<Color> netColors = controller.getModel().getSubNetColors();
-		flexPanel.removeAll();
-		ArrayList<Float> maxVals = calcMax(controller.getSimManager().getSubNets());
-		float gridProd = maxVals.get(0);
-		float gridCons = maxVals.get(1);
-		FlexibleData maingrid = new FlexibleData("Main Grid", gridProd, gridCons, gridProd, gridCons);
-		maingrid.getColorPanel().setVisible(false);
-		maingrid.getNamelbl().setFont(new Font("Tahoma", Font.BOLD, 11));
-		flexPanel.add(maingrid);
-		int counter = 0;
-		int colorCounter = 0;
-		ArrayList<SubNet> subnets = controller.getSimManager().getSubNets(); 
-		for(SubNet sn: subnets){
-			if(netColors.size() < subnets.size()){
-				netColors.add(new Color((int)(Math.random()*255), (int)(Math.random()*255), (int)(Math.random()*255)));
-			}
-			JPanel objects = new JPanel();
-			objects.setLayout(new BoxLayout(objects, BoxLayout.Y_AXIS));
-			int index = flexPanel.getComponentCount();
-			float subProd = 0;
-			float subCons = 0;
-			Color subColor = netColors.get(colorCounter);
-			for(HolonObject hl: sn.getObjects()){
-				System.out.println("Delete Me");
-				FlexibleData tmp = new FlexibleData(hl.getName()+" "+hl.getId(),
-						666.f, 666.f, gridProd, gridCons);
-				tmp.getColorPanel().setBackground(subColor);
-				objects.add(tmp);
-			}
-			FlexibleData subnet = new FlexibleData("Subnet "+ counter, subProd, subCons, gridProd, gridCons);
-			subnet.getNamelbl().setFont(new Font("Tahoma", Font.BOLD, 11));
-			subnet.getColorPanel().setBackground(subColor);
-			FlexSubData wholeSubnet = new FlexSubData(subnet);
-			wholeSubnet.setObjects(objects);
-			wholeSubnet.setListener(this);
-			flexPanel.add(wholeSubnet, index);
-			counter++;
-			colorCounter++;
-		}
-		flexPanel.revalidate();
-		flexPanel.repaint();
-		flexPanel.updateUI();
-	}
-	
-	public JPanel getPanel(){
-		return flexPanel;
-	}
-	
-	public ArrayList<Float> calcMax(ArrayList<SubNet> sn){
-		ArrayList<Float> result = new ArrayList<Float>();
-		float prod = 0;
-		float cons = 0;
-		if(sn != null){
-			for(SubNet s: sn){
-				for(HolonObject h: s.getObjects()){
-					prod += 666.f;
-					cons += 666.f;
-				}
-			}
-			result.add(prod);
-			result.add(cons);
-			return result;
-		}else{
-			result.add(prod);
-			result.add(cons);
-			return result;
-		}
-	}
-
-	@Override
-	public void onChange(ArrayList<AbstractCanvasObject> objects) {
-		recalculate();
-	}
-
-}

+ 106 - 289
src/ui/view/GUI.java

@@ -1,63 +1,107 @@
 package ui.view;
 
-import classes.*;
-
-import com.google.gson.JsonNull;
-import com.google.gson.JsonObject;
-import com.google.gson.JsonParseException;
-
-import interfaces.CategoryListener;
-import interfaces.GraphEditable;
-import interfaces.LocalMode;
-
-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 utility.ImageImport;
-
-import javax.swing.*;
-import javax.swing.border.Border;
-import javax.swing.border.LineBorder;
-import javax.swing.event.AncestorEvent;
-import javax.swing.event.AncestorListener;
-import javax.swing.filechooser.FileNameExtensionFilter;
-import javax.swing.plaf.ColorUIResource;
-import javax.swing.table.DefaultTableModel;
-import javax.swing.table.JTableHeader;
-import javax.swing.table.TableCellEditor;
-import javax.swing.table.TableCellRenderer;
-import javax.swing.tree.DefaultMutableTreeNode;
-import javax.swing.tree.DefaultTreeModel;
-import javax.swing.tree.TreeCellRenderer;
-
-import java.awt.*;
+import java.awt.BorderLayout;
+import java.awt.Color;
+import java.awt.Component;
+import java.awt.Cursor;
+import java.awt.Dimension;
+import java.awt.GraphicsDevice;
+import java.awt.GraphicsEnvironment;
+import java.awt.HeadlessException;
+import java.awt.Image;
+import java.awt.Point;
+import java.awt.Rectangle;
+import java.awt.Toolkit;
 import java.awt.datatransfer.UnsupportedFlavorException;
-import java.awt.event.*;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.awt.event.ComponentAdapter;
+import java.awt.event.ComponentEvent;
+import java.awt.event.ItemEvent;
+import java.awt.event.KeyAdapter;
+import java.awt.event.KeyEvent;
+import java.awt.event.MouseAdapter;
+import java.awt.event.MouseEvent;
+import java.awt.event.MouseMotionAdapter;
 import java.io.File;
 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;
+
+import javax.swing.AbstractAction;
+import javax.swing.ActionMap;
+import javax.swing.Box;
+import javax.swing.BoxLayout;
+import javax.swing.CellEditor;
+import javax.swing.GrayFilter;
+import javax.swing.ImageIcon;
+import javax.swing.InputMap;
+import javax.swing.JButton;
+import javax.swing.JCheckBoxMenuItem;
+import javax.swing.JComboBox;
+import javax.swing.JComponent;
+import javax.swing.JDialog;
+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.JPopupMenu;
+import javax.swing.JScrollPane;
+import javax.swing.JSlider;
+import javax.swing.JSplitPane;
+import javax.swing.JTabbedPane;
+import javax.swing.JTable;
+import javax.swing.JTextField;
+import javax.swing.JToolBar;
+import javax.swing.JTree;
+import javax.swing.KeyStroke;
+import javax.swing.SwingUtilities;
+import javax.swing.filechooser.FileNameExtensionFilter;
+import javax.swing.table.DefaultTableModel;
+import javax.swing.table.JTableHeader;
+import javax.swing.table.TableCellEditor;
+import javax.swing.table.TableCellRenderer;
+import javax.swing.tree.DefaultMutableTreeNode;
+import javax.swing.tree.DefaultTreeModel;
+import javax.swing.tree.TreeCellRenderer;
+
+import org.apache.commons.compress.archivers.ArchiveException;
+import com.google.gson.JsonParseException;
+
+import classes.AbstractCanvasObject;
+import classes.Category;
+import classes.Edge;
+import classes.GroupNode;
+import classes.HolonBattery;
+import classes.HolonElement;
+import classes.HolonObject;
+import classes.HolonSwitch;
+import classes.IdCounter;
+import classes.IdCounterElem;
+import interfaces.GraphEditable;
+import ui.controller.Control;
+import ui.controller.UpdateController;
+import ui.model.DecoratedState;
+import ui.model.Model;
+import ui.model.Model.FairnessModel;
+import ui.view.CreateNewDialog.Option;
+import utility.ImageImport;
 
 /**
  * Graphical User Interface.
  *
  * @author Gruppe14
  */
-public class GUI implements CategoryListener {
+public class GUI{
 	
 	static final Color PALE_RED=new Color(255, 192, 192);
 	
@@ -93,13 +137,6 @@ public class GUI implements CategoryListener {
 	
 	/** Help -> AboutUs */
 	private final JMenuItem mntmAboutUs = new JMenuItem("About Us");
-	
-	
-	
-	private final JCheckBoxMenuItem consoleLogCheckBox = new JCheckBoxMenuItem(
-			"Show program console log");
-	private final JCheckBoxMenuItem useFlexibleDevicesCheckBox = new JCheckBoxMenuItem(
-			"Automatically use flexible devices");
 	/** checked if supplyBars should be shown */
 	private final JCheckBoxMenuItem showSupplyBarsCheckBox = new JCheckBoxMenuItem(
 			"Show supply bars.");
@@ -140,8 +177,6 @@ public class GUI implements CategoryListener {
 	private final JTabbedPane tabbedPaneSplit = new JTabbedPane(JTabbedPane.TOP);
 	private final JPopupMenu popmenuEdit = new JPopupMenu();
 	private final JMenuItem editItem = new JMenuItem("Edit Object");
-	private final StatisticPanel statSplitPane;
-	private final JScrollPane statScrollPane;
 	private final JLabel maxGraph = new JLabel("100%");
 	private final JLabel medGraph = new JLabel("50%");
 	private final JLabel minGraph = new JLabel("0%");
@@ -169,8 +204,6 @@ public class GUI implements CategoryListener {
 	// Cell(3,1) is editable by Edges
 	private final JTable tableProperties = new JTable() {
 
-		private static final long serialVersionUID = 1L;
-
 		@Override
 		public TableCellRenderer getCellRenderer(int row, int column) {
 			if (getValueAt(row, column) instanceof Boolean) {
@@ -236,7 +269,6 @@ public class GUI implements CategoryListener {
 	private final JMenuItem czechBtn = new JMenuItem("CZ");
 	private final JMenuItem chineseBtn = new JMenuItem("ZH");
 	private final MyCanvas canvas;
-	private final HolonCanvas holonCanvas;
 	private final UnitGraph unitGraph;
 	/** Textfield to show the period of an element */
 	private final JTextField unitGraphLocalPeriod = new JTextField(6);
@@ -258,12 +290,9 @@ public class GUI implements CategoryListener {
 	private final String[] columnNamesSingle = { "Nr.", "Device", "Energy",
 			"Flexibility active", "Quantity", "Activated" };
 	private final ArrayList<PropertyTable> tables = new ArrayList<>();
-	private final String[] comboBoxCat = { "Category", "Object", "Switch", "Battery" };
 	private final UpdateController updCon;
 	private final JSplitPane splitPane_1 = new JSplitPane();
-	private final JSlider holonBodySizeSlider = new JSlider();
 	private final JLabel lblHolonBodySize = new JLabel("HolonBody SIze");
-	private final JLabel lblSelectedElement = new JLabel("Selected Element: ");
 	// for doubleclick
 	private boolean click = false;
 	private JFrame holegJFrame;
@@ -324,15 +353,8 @@ public class GUI implements CategoryListener {
 		this.controller = control;
 		this.model = control.getModel();
 		control.setGui(this);
-		statSplitPane = new StatisticPanel(controller);
-		model.addGraphListener(statSplitPane);
-		model.setStatPanel(statSplitPane);
-		statScrollPane = new JScrollPane(statSplitPane);
 		this.unitGraph = new UnitGraph(model, control);
 		this.canvas = new MyCanvas(model, control, unitGraph);
-		this.holonCanvas = new HolonCanvas(model, control);
-
-		control.initListener(this);
 		model.setTableProperties(tableProperties);
 		initialize();
 		updateCategories(model.getCategories());
@@ -343,7 +365,6 @@ public class GUI implements CategoryListener {
 	/**
 	 * Initialize the contents of the frame.
 	 */
-	@SuppressWarnings({ "serial", "unchecked" })
 	private void initialize() {
 		holegJFrame = new JFrame();
 		holegJFrame.setTitle("HOLEG Simulator");
@@ -414,7 +435,6 @@ public class GUI implements CategoryListener {
 					
 					controller.calculateStateAndVisualForCurrentTimeStep();
 					canvas.repaint();
-					unitGraph.update(model.getObjectsOnCanvas());
 					updateUpperNodes();
 				} catch (IOException eex) {
 					eex.printStackTrace();
@@ -437,7 +457,6 @@ public class GUI implements CategoryListener {
 					
 					controller.calculateStateAndVisualForCurrentTimeStep();
 					canvas.repaint();
-					unitGraph.update(model.getObjectsOnCanvas());
 					updateUpperNodes();
 				} catch (IOException ex) {
 					ex.printStackTrace();
@@ -503,9 +522,6 @@ public class GUI implements CategoryListener {
 				if (canvasOrUpperNodeCanvas instanceof GroupNodeCanvas) {
 					GroupNodeCanvas uNC = (GroupNodeCanvas) canvasOrUpperNodeCanvas;
 					for (AbstractCanvasObject cps : model.getSelectedCpsObjects()) {
-
-
-						controller.removeTrackingObj(cps);
 						if (uNC.upperNode.getNodes().contains(cps)) {
 							controller.delObjUpperNode(cps, uNC.upperNode);
 							unc.setToolTip(false);
@@ -528,10 +544,6 @@ public class GUI implements CategoryListener {
 					for (int j = 0; j < model.getSelectedCpsObjects().size(); j++) {
 						AbstractCanvasObject cps = model.getSelectedCpsObjects()
 								.get(j);
-
-					
-
-						controller.removeTrackingObj(cps);
 						if (j < model.getSelectedCpsObjects().size() - 1)
 							save = true;
 						controller.delCanvasObject(cps, save);
@@ -622,12 +634,10 @@ public class GUI implements CategoryListener {
 								.paste(((GroupNodeCanvas) canvasOrUpperNodeCanvas).upperNode,
 										canvasOrUpperNodeCanvas
 												.getMousePosition());
-						unitGraph.update(model.getSelectedCpsObjects());
 						controller.calculateStateAndVisualForCurrentTimeStep();
 						scrollPane.getViewport().getComponent(0).repaint();
 					} else {
 						controller.paste(null, canvas.getMousePosition());
-						unitGraph.update(model.getSelectedCpsObjects());
 						controller.calculateStateAndVisualForCurrentTimeStep();
 						canvas.repaint();
 					}
@@ -725,21 +735,6 @@ public class GUI implements CategoryListener {
 		});
 
 		mnNewMenuEdit.add(mntmFindReplace);
-		mntmEditShowedInformation
-				.addActionListener(actionEvent -> {
-					try {
-						DisplayedInformationPopUp dialog = new DisplayedInformationPopUp(
-								canvas, contentPane, controller,
-								holegJFrame);
-						dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
-						dialog.setVisible(true);
-					} catch (Exception ex) {
-						ex.printStackTrace();
-					}
-				});
-	
-		
-		mnNewMenuEdit.add(mntmEditShowedInformation);
 		mnNewMenuEdit.add(mntmEditEdges);
 		mntmEditEdges.addActionListener(actionEvent -> {
 			EditEdgesPopUp edgePopUp = new EditEdgesPopUp(holegJFrame);
@@ -781,13 +776,6 @@ public class GUI implements CategoryListener {
 		});
 
 
-		mnNewMenuOptions.add(useFlexibleDevicesCheckBox);
-		useFlexibleDevicesCheckBox.setSelected(true);
-		useFlexibleDevicesCheckBox
-				.addActionListener(actionEvent -> model
-						.setUseFlexibleDevices(useFlexibleDevicesCheckBox
-								.isSelected()));
-
 		/**
 		 * Add Fairness Model Option to the option Menu
 		 */
@@ -906,15 +894,7 @@ public class GUI implements CategoryListener {
 						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);
@@ -962,16 +942,6 @@ public class GUI implements CategoryListener {
 		splitPane3.setLeftComponent(lblImageSize);
 
 		mnNewMenuView.add(splitPane_1);
-		holonBodySizeSlider.setValue(100);
-		holonBodySizeSlider.setMinimum(1);
-
-		holonBodySizeSlider.addChangeListener(changeEvent -> {
-			controller.setHolonBodyScale(holonBodySizeSlider.getValue());
-			tree.setRowHeight(50);
-			canvas.repaint();
-		});
-
-		splitPane_1.setRightComponent(holonBodySizeSlider);
 
 		splitPane_1.setLeftComponent(lblHolonBodySize);
 
@@ -1041,10 +1011,6 @@ public class GUI implements CategoryListener {
 		canvas.setBackground(Color.WHITE);
 		canvas.setPreferredSize(new Dimension(model.getCanvasX(), model
 				.getCanvasY()));
-		holonCanvas.setBackground(Color.WHITE);
-		holonCanvas.setPreferredSize(new Dimension(model.getCanvasX(), model
-				.getCanvasY()));
-
 		/********************
 		 * RIGHT CONTAINER (INFORMATION)
 		 **********************/
@@ -1184,7 +1150,7 @@ public class GUI implements CategoryListener {
 				if (tempCpsObject != null
 						&& tempCpsObject.getClass() == HolonObject.class
 						&& tempCpsObject.getId() != 0) {
-					addElementPopUp = new AddElementPopUp(holegJFrame, model);//TODO: I didn't even check
+					addElementPopUp = new AddElementPopUp(holegJFrame);
 					addElementPopUp.setActualCps(updCon.getActualCps());
 					addElementPopUp.setVisible(true);
 					HolonElement ele = addElementPopUp.getElement();
@@ -1382,7 +1348,6 @@ public class GUI implements CategoryListener {
 								// For activeFlex column (boolean with a
 								// checkbox)
 								else if (selectedValueBX == 7) {
-									System.out.println("selectedValueBX == 7");
 									HolonElement eleBTemp = updCon
 											.getActualHolonElement(null,
 													yBMouse, 0, tables);
@@ -1394,6 +1359,7 @@ public class GUI implements CategoryListener {
 											.parseBoolean(newBStuff);
 									eleBTemp.setActive(bTemp);
 								} else {
+									//TODO: check all possible fields.
 									// Update of HolonElement
 									HolonElement eleTemp = updCon
 											.getActualHolonElement(null,
@@ -1402,22 +1368,22 @@ public class GUI implements CategoryListener {
 											.getMultiTable()
 											.getValueAt(selectedValueY,
 													selectedValueX).toString();
+									
 									// Name update
 									if (selectedValueX == 2) {
 										eleTemp.setEleName(newStuff);
 									}
 									// Energy Update
 									else if (selectedValueX == 3) {
-										System.out.println("selectedValueX == 3");
 										Float ftemp = Float
 												.parseFloat(newStuff);
 										eleTemp.setEnergyPerElement(ftemp);
 									}
 									// Flexibility
 									else if (selectedValueX == 4) {
-										Float ftemp = Float
-												.parseFloat(newStuff);
-										//TODO and here
+										
+										
+										
 									}
 									// Amount of Elements update
 									else if (selectedValueX == 5) {
@@ -1426,7 +1392,6 @@ public class GUI implements CategoryListener {
 										eleTemp.setAmount(iTemp);
 									}
 									else if (selectedValueX == 6) {
-										System.out.println("Test");
 									}
 								}
 							}
@@ -1468,12 +1433,11 @@ public class GUI implements CategoryListener {
 											.getSingleTable()
 											.getValueAt(selectedValueBY,
 													selectedValueBX -1).toString();
-									Boolean bTemp = Boolean
-											.parseBoolean(newBStuff);
-									eleTemp.setActive(bTemp);
-									//TODO: delete Boolean bTemp = Boolean.parseBoolean(newBStuff);
+									eleTemp.setActive(Boolean
+											.parseBoolean(newBStuff));
 
 								} else {
+									//TODO check all possible assignements.
 									// Update of HolonElement
 									eleTemp = updCon.getActualHolonElement(
 											(HolonObject) updCon.getActualCps(),
@@ -1492,15 +1456,6 @@ public class GUI implements CategoryListener {
 										eleTemp.setEnergyPerElement(ftemp);
 									} // Flexibility
 									else if (selectedValueX == 3) {
-										Float ftemp = Float
-												.parseFloat(newStuff);
-										//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
 									}
 									// Amount of Elements update
 									else if (selectedValueX == 4) {
@@ -1641,10 +1596,6 @@ public class GUI implements CategoryListener {
 					}
 					model.getSelectedEdge().setCapacity(ftemp);
 				}
-				// Status edition through a check box
-				if (selValueYBool == 3) {
-					Boolean bbTemp = Boolean.parseBoolean(btemp.toString());
-				}
 			}
 			canvas.repaint();
 		} catch (Exception e) {
@@ -2009,24 +1960,24 @@ public class GUI implements CategoryListener {
 		panel.add(toolBar);
 		btnAddPopUp.add(mItemNew);
 		mItemNew.addActionListener(actionEvent -> {
-			new NewPopUp(controller, holegJFrame);
+			new CreateNewDialog(controller, holegJFrame);
 		});
 		btnAddPopUp.addSeparator();
 		btnAddPopUp.add(mItemCategory);
 		mItemCategory.addActionListener(actionEvent -> {
-			new NewPopUp(controller,Option.Category, holegJFrame);
+			new CreateNewDialog(controller,Option.Category, holegJFrame);
 		});
 		btnAddPopUp.add(mItemObject);
 		mItemObject.addActionListener(actionEvent -> {
-			new NewPopUp(controller,Option.Object, holegJFrame);
+			new CreateNewDialog(controller,Option.Object, holegJFrame);
 		});
 		btnAddPopUp.add(mItemSwitch);
 		mItemSwitch.addActionListener(actionEvent -> {
-			new NewPopUp(controller,Option.Switch, holegJFrame);
+			new CreateNewDialog(controller,Option.Switch, holegJFrame);
 		});
 		btnAddPopUp.add(mItemBattery);
 		mItemBattery.addActionListener(actionEvent -> {
-			new NewPopUp(controller,Option.Battery, holegJFrame);
+			new CreateNewDialog(controller,Option.Battery, holegJFrame);
 		});
 		btnAdd.addActionListener(actionEvent -> btnAddPopUp.show(btnAdd, -1, +20));
 		btnAdd.setToolTipText("Add a new Category or Item to the library.");
@@ -2147,21 +2098,6 @@ public class GUI implements CategoryListener {
 
 		});
 
-		holonCanvas.addMouseListener(new MouseAdapter() {
-			@Override
-			public void mousePressed(MouseEvent e) {
-				hideScrollGraph();
-				elementGraph.setText(Languages.getLanguage()[25]);
-				if (model.getPropertyTable().getRowCount() > 0) {
-					for (int i = model.getPropertyTable().getRowCount() - 1; i > -1; i--) {
-						model.getPropertyTable().removeRow(i);
-					}
-				}
-				updCon.deleteRows(model.getMultiTable());
-				updCon.deleteRows(model.getSingleTable());
-				updCon.paintHolonBody(model.getSelectedHolonBody());
-			}
-		});
 
 		
 
@@ -2250,12 +2186,8 @@ public class GUI implements CategoryListener {
 					try {
 						controller.loadFile(file.getAbsolutePath());
 						canvas.repaint();
-						unitGraph.update(model.getObjectsOnCanvas());
 						tree.repaint();
 						controller.calculateStateAndVisualForCurrentTimeStep();
-						for (JsonObject json : model.getStatisticData()) {
-							readStatistics(json);
-						}
 					} catch (IOException | ArchiveException e) {
 						e.printStackTrace();
 						JLabel message = new JLabel(
@@ -2356,8 +2288,6 @@ public class GUI implements CategoryListener {
 					
 					controller.calculateStateAndVisualForCurrentTimeStep();
 					canvas.repaint();
-
-					repaintGraphAfterUndoRedo();
 					hideScrollGraph();
 				} catch (IOException e) {
 					e.printStackTrace();
@@ -2379,8 +2309,6 @@ public class GUI implements CategoryListener {
 					
 					controller.calculateStateAndVisualForCurrentTimeStep();
 					canvas.repaint();
-
-					repaintGraphAfterUndoRedo();
 					hideScrollGraph();
 				} catch (IOException e) {
 					e.printStackTrace();
@@ -2388,17 +2316,13 @@ public class GUI implements CategoryListener {
 			}
 		});
 
-		timePanel = new TimePanel(this,controller);
+		timePanel = new TimePanel(controller);
 		timePanel.setBorder(null);
 		timePanel.getTimeSlider()
 				.addChangeListener(changeEvent -> {
 					//TimeSliderChanged event
 					controller.calculateStateAndVisualForTimeStep(timePanel.getTimeSlider().getValue());
 					unitGraph.repaint();
-					if (model.getIsSimRunning()) {
-						controller.runAlgorithm(model, controller);
-						statSplitPane.repaintGraphs();
-					}
 					contentPane.updateUI();
 				});
 		splitPane1.setMinimumSize(new Dimension(0, 25));
@@ -2417,12 +2341,6 @@ public class GUI implements CategoryListener {
 		
 		
 		tabbedPaneInnerOriginal.addTab("Main Grid", myPanel);
-		tabbedPaneOriginal.addTab("Statistics", statScrollPane);
-		tabbedPaneOriginal.addTab("Holon", holonCanvas);
-		FlexiblePane flexPane = new FlexiblePane(controller);
-		controller.setFlexiblePane(flexPane);
-		controller.getModel().getObjectListeners().add(flexPane);
-		tabbedPaneOriginal.addTab("Flexibility", flexPane);
 		splitPane1.setLeftComponent(tabbedPaneOriginal);
 		splitPane1.setRightComponent(splitHolonElPro);
 
@@ -2510,21 +2428,21 @@ public class GUI implements CategoryListener {
 		openMenu.addActionListener(actionEvent -> {
 			new AddOnWindow(holegJFrame, controller);
 		});
-		openMenu.setAccelerator(KeyStroke.getKeyStroke('N', Toolkit.getDefaultToolkit ().getMenuShortcutKeyMask()));
+		openMenu.setAccelerator(KeyStroke.getKeyStroke('N', Toolkit.getDefaultToolkit ().getMenuShortcutKeyMaskEx()));
 		menuWindow.add(openMenu);
 		//Outliner
 		JMenuItem openOutliner =  new JMenuItem("Open Outliner", new ImageIcon(ImageImport.loadImage("/Button_Images/iconOutliner.png").getScaledInstance(20, 20, java.awt.Image.SCALE_SMOOTH)));
 		openOutliner.addActionListener(actionEvent -> {
 			outlinerList.add(new Outliner(holegJFrame, model, controller));
 		});
-		openOutliner.setAccelerator(KeyStroke.getKeyStroke('O', Toolkit.getDefaultToolkit ().getMenuShortcutKeyMask()));
+		openOutliner.setAccelerator(KeyStroke.getKeyStroke('O', Toolkit.getDefaultToolkit ().getMenuShortcutKeyMaskEx()));
 		menuWindow.add(openOutliner);
 		//FlexWindow
 		JMenuItem openFlexMenuItem =  new JMenuItem("Open Flexibility Panel", new ImageIcon(ImageImport.loadImage("/Button_Images/iconAlgo.png").getScaledInstance(20, 20, java.awt.Image.SCALE_SMOOTH)));
 		openFlexMenuItem.addActionListener(actionEvent -> {
 			flexList.add(new FlexWindow(holegJFrame, controller));
 		});
-		openFlexMenuItem.setAccelerator(KeyStroke.getKeyStroke('L', Toolkit.getDefaultToolkit ().getMenuShortcutKeyMask()));
+		openFlexMenuItem.setAccelerator(KeyStroke.getKeyStroke('L', Toolkit.getDefaultToolkit ().getMenuShortcutKeyMaskEx()));
 		menuWindow.add(openFlexMenuItem);
 	}
 
@@ -2608,53 +2526,6 @@ public class GUI implements CategoryListener {
 		}
 	}
 
-	/**
-	 * adds a specific object type to selected Category also handles input
-	 * windows and illegal inputs.
-	 *
-	 * @param objType
-	 *            type of the Object
-	 * @param selectedNode
-	 *            The selected Node
-	 */
-	private void addObjectAction(String objType,
-			DefaultMutableTreeNode selectedNode) {
-		if (selectedNode == null) {
-			JOptionPane.showMessageDialog(holegJFrame,
-					"Please select a Category first before adding " + objType
-							+ ".");
-		}
-		// if selected node is a directory for Categories
-		else {
-			if (selectedNode.getLevel() == 1) {
-				String objname = JOptionPane.showInputDialog(holegJFrame,
-						"Please enter a Name for the " + objType);
-				Category cat = controller.searchCategory(selectedNode
-						.getUserObject().toString());
-
-				if (objname.length() != 0) {
-					try {
-						switch (objType) {
-
-						case "Switch":
-							controller.addSwitch(cat, objname);
-							break;
-						case "Battery":
-							controller.addBattery(cat, objname);
-							break;
-						}
-					} catch (Exception e) {
-					}
-
-				}
-			} else {
-				JOptionPane
-						.showMessageDialog(holegJFrame,
-								"Objects can not be added to Objects. Please select a Category.");
-			}
-		}
-	}
-
 	/**
 	 * reloads the Categories from Model.
 	 *
@@ -2958,32 +2829,6 @@ public class GUI implements CategoryListener {
 		}
 	}
 
-	private void readStatistics(JsonObject json) {
-		List<String> keys = json.entrySet().stream().map(i -> i.getKey())
-				.collect(Collectors.toCollection(ArrayList::new));
-
-		// Saved Values
-		JsonObject obj;
-		AbstractCanvasObject cps;
-		int prop;
-		Color color;
-
-		StatisticGraphPanel stat = new StatisticGraphPanel(model, controller,//TODO
-				json.get("KEY").getAsString(), model.getGraphTable());
-
-		for (String k : keys) {
-			if (!k.equals("KEY")) {
-				obj = json.get(k).getAsJsonObject();
-				cps = (obj.get("ID") == JsonNull.INSTANCE ? null : controller
-						.searchTracked(obj.get("ID").getAsInt()));
-				prop = obj.get("PROPERTY").getAsInt();
-				color = model.getGson().fromJson(obj.get("COLOR"), Color.class);
-				stat.addObject(new TrackedDataSet(cps, prop, color, model.getIterations()));
-			}
-			model.getGraphTable().put(json.get("KEY").getAsString(), stat);
-			model.getStatPanel().getGraphPanel().add(stat);
-		}
-	}
 
 	/**
 	 * chooses whether to set the tabTemp to tabbedPaneOriginal or
@@ -2999,16 +2844,6 @@ public class GUI implements CategoryListener {
 		}
 	}
 
-	private JScrollPane getScrollPaneFromTabbedPane(JTabbedPane tabbedPane,
-			int index) {
-		tabTemp = tabbedPane;
-		return getScrollPaneFromTabbedPane(index);
-	}
-
-	// private JScrollPane getScrollPaneFromTabbedPane(JTabbedPane tabbedPane) {
-	// return getScrollPaneFromTabbedPane(tabbedPane, -1);
-	// }
-
 	private JScrollPane getScrollPaneFromTabbedPane() {
 		return getScrollPaneFromTabbedPane(-1);
 	}
@@ -3038,11 +2873,6 @@ public class GUI implements CategoryListener {
 		}
 	}
 
-	private void repaintGraphAfterUndoRedo() {
-		for (AbstractCanvasObject cps : model.getObjectsOnCanvas()) {
-			unitGraph.repaintGraph(cps);
-		}
-	}
 
 	/**
 	 * if flexibility was turned on, then active needs to be turned off, the
@@ -3078,16 +2908,6 @@ public class GUI implements CategoryListener {
 		updCon.refreshTableProperties(model.getPropertyTable());
 	}
 
-	/**
-	 * Custom Mouse adapter makes contentPane gain focus once mouse leaves this
-	 * component so copy/paste/cut and "select all" works
-	 */
-	private class FocusCanvasMouseAdapter extends MouseAdapter {
-		@Override
-		public void mouseExited(MouseEvent e) {
-			contentPane.requestFocus();
-		}
-	}
 	/**
 	 * This Method updates the UnitGraph, saves the old LocalModeState and load the new LocalModeState.
 	 * @param element The new Element to load the UnitGraph
@@ -3135,10 +2955,7 @@ public class GUI implements CategoryListener {
 		}
 		unitGraph.setLocalPeriod(localPeriodInputValue);
 	}
-	
-	public void updateIterations() {
-		this.statSplitPane.updateIterations();
-	}
+
 	
 	private void openWebpage(String URL){
 		try {

+ 36 - 88
src/ui/view/GroupNodeCanvas.java

@@ -1,38 +1,55 @@
 package ui.view;
 
-import classes.*;
+import java.awt.BasicStroke;
+import java.awt.Color;
+import java.awt.Component;
+import java.awt.Font;
+import java.awt.Graphics;
+import java.awt.Graphics2D;
+import java.awt.RenderingHints;
+import java.awt.datatransfer.UnsupportedFlavorException;
+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.IOException;
+import java.util.ArrayList;
+import java.util.HashSet;
+
+import javax.swing.ImageIcon;
+import javax.swing.JFrame;
+import javax.swing.JLabel;
+import javax.swing.JOptionPane;
+import javax.swing.JScrollPane;
+import javax.swing.JTabbedPane;
+import javax.swing.SwingUtilities;
 
 import com.google.gson.JsonParseException;
 
+import classes.AbstractCanvasObject;
+import classes.Edge;
+import classes.GroupNode;
+import classes.HolonObject;
+import classes.HolonSwitch;
+import classes.Node;
+import classes.Position;
+import classes.Vector2d;
 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.DecoratedHolonObject.HolonObjectState;
 import ui.model.DecoratedSwitch;
+import ui.model.ExitCable;
+import ui.model.DecoratedSwitch.SwitchState;
 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 utility.ImageImport;
 
-import javax.swing.*;
-
-import java.awt.*;
-import java.awt.datatransfer.UnsupportedFlavorException;
-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
  *
@@ -46,10 +63,6 @@ public class GroupNodeCanvas extends AbstractCanvas implements MouseListener, Mo
     // Path
     protected String path;
     int code;
-    private JLabel breadCrumb;
-    private int upperNodeID;
-    private Component parent;
-    private BufferedImage parentPreview;
     public boolean disable = false;
     /**
      * Constructor.
@@ -64,13 +77,8 @@ public class GroupNodeCanvas extends AbstractCanvas implements MouseListener, Mo
         this.controller = control;
         this.model = mod;
         this.upperNode = UpperNode;
-        upperNodeID = UpperNode.getId();
         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
@@ -210,60 +218,13 @@ public class GroupNodeCanvas extends AbstractCanvas implements MouseListener, Mo
             animT.start();
         });
 
-        itemTrack.addActionListener(actionEvent -> {
-            for (AbstractCanvasObject o : model.getSelectedCpsObjects()) {
-                if (o instanceof HolonObject) {
-                    boolean found = false;
-                    if (controller.getTrackingObj() != null) {
-                        for (AbstractCanvasObject obj : controller.getTrackingObj()) {
-                            if (obj instanceof HolonObject) {
-                                if (obj.getId() == o.getId()) {
-                                    found = true;
-                                }
-                            }
-                        }
-                    }
-                    if (!found) {
-                        controller.addTrackingObj(o);
-                        ((HolonObject) o).updateTrackingInfo();
-                    }
-                }
-            }
-        });
-
-        itemUntrack.addActionListener(actionEvent -> {
-            for (AbstractCanvasObject o : model.getSelectedCpsObjects()) {
-                if (o instanceof HolonObject) {
-                    boolean found = false;
-                    if (controller.getTrackingObj() != null) {
-                        for (AbstractCanvasObject obj : controller.getTrackingObj()) {
-                            if (obj instanceof HolonObject) {
-                                if (obj.getId() == o.getId()) {
-                                    found = true;
-                                }
-                            }
-                        }
-                    }
-                    if (found) {
-                        // Removed from tracking array and tracking
-                        // information reseted
-                        controller.removeTrackingObj(o);
-                        ((HolonObject) o).setTrackingProd(new float[100]);
-                        ((HolonObject) o).setTrackingCons(new float[100]);
-                    }
-                }
-            }
-            System.out.println(controller.getTrackingObj());
-        });
+        
 
         itemDelete.addActionListener(actionEvent -> {
             // Remove the selected Object objects
             for (AbstractCanvasObject cps : model.getSelectedCpsObjects()) {
                 if (upperNode.getNodes().contains(cps)) {
                     controller.delObjUpperNode(cps, upperNode);
-                    // Removes the object from the tracked objects, in case
-                    // it was tracked
-                    controller.removeTrackingObj(cps);
                     // Remove UpperNodeTab if UpperNode deleted
                     if (cps instanceof GroupNode) {
                         JTabbedPane tabbedPane = (JTabbedPane) getParent().getParent().getParent().getParent();
@@ -304,7 +265,6 @@ public class GroupNodeCanvas extends AbstractCanvas implements MouseListener, Mo
         itemPaste.addActionListener(actionEvent -> {
             try {
                 controller.paste(upperNode, mousePosition);
-                unitGraph.update(model.getSelectedCpsObjects());
             } catch (JsonParseException | UnsupportedFlavorException | IOException e1) {
                 JLabel message = new JLabel("The Clipboard information cannot be pastet into Application.");
                 JOptionPane.showMessageDialog(null, message, "", JOptionPane.ERROR_MESSAGE);
@@ -548,18 +508,6 @@ public class GroupNodeCanvas extends AbstractCanvas implements MouseListener, Mo
 			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;

+ 0 - 244
src/ui/view/HolonCanvas.java

@@ -1,244 +0,0 @@
-package ui.view;
-
-import classes.HolonBody;
-import classes.SubNet;
-import classes.Vector2d;
-import ui.controller.Control;
-import ui.controller.HolonCanvasController;
-import ui.model.Model;
-
-import javax.swing.*;
-import java.awt.*;
-import java.awt.event.*;
-import java.util.ArrayList;
-
-public class HolonCanvas extends JPanel implements MouseWheelListener, MouseListener, MouseMotionListener {
-
-	/**
-	 * 
-	 */
-	private static final long serialVersionUID = 1L;
-
-	// Ball objects
-	private ArrayList<HolonBody> bodies = new ArrayList<>();
-	private int subCount;
-
-	private long previousTime = System.currentTimeMillis();
-	private long currentTime = previousTime;
-	private long totalElapsedTime = 0;
-	private int frameCount = 0;
-	private Dimension center;
-	private ArrayList<SubNet> subnets;
-	private HolonCanvasController hCController;
-
-	private Control controller;
-	private Model model;
-	private JComboBox<String> combo = new JComboBox<>();
-	private int comboChoice = 0;
-	private JCheckBox chckbxSort = new JCheckBox("sort by size");
-	private boolean sizeChange = false;
-	private HolonBody toDrag;
-
-    HolonCanvas(Model mod, Control control) {
-        // Wire up Events
-		this.controller = control;
-		this.model = mod;
-		
-		hCController = new HolonCanvasController(mod);
-
-        JLabel lblBodyInfo = new JLabel("Holon Info:");
-        add(lblBodyInfo);
-		this.add(combo);
-		subnets = controller.getSimManager().getSubNets();
-		subCount = subnets.size();
-		previousTime = System.currentTimeMillis();
-		currentTime = previousTime;
-		totalElapsedTime = 0;
-		frameCount = 0;
-		this.addMouseWheelListener(this);
-		combo.addItem("ID");
-		combo.addItem("Nr. of Objects");
-		combo.addItem("Nr. of Edges");
-		combo.addItem("Nr. of Switches");
-		combo.addItem("Total Production");
-		combo.addItem("Total Consumption");
-		combo.addItem("Nr. of Elements");
-		combo.addItem("Nr. of Producers");
-		combo.addItem("Nr. of active Elements");
-
-        combo.addActionListener(e -> comboChoice = combo.getSelectedIndex());
-        this.addMouseListener(this);
-		this.addMouseMotionListener(this);
-
-        chckbxSort.addChangeListener(e -> sizeChange = true);
-        add(chckbxSort);
-	}
-
-	// Start Render and Update Threads
-	public void paintComponent(Graphics g) {
-		super.paintComponent(g);
-
-		// add new colors if necessary
-		for (int i = 0; i < controller.getSimManager().getSubNets().size(); i++) {
-			if (model.getSubNetColors().size() - 1 < i) {
-				controller.addSubNetColor(new Color((int) (Math.random() * 255), (int) (Math.random() * 255),
-						(int) (Math.random() * 255)));
-			}
-		}
-		// check if subnets have changed
-		if (!controller.getSimManager().getSubNets().equals(subnets)) {
-			subnets = controller.getSimManager().getSubNets();
-			subCount = subnets.size();
-			calcCenter();
-			hCController.addNewBodies(subCount,subnets, center, controller.getHolonBodyScale());
-			sizeChange = true;
-		}
-
-		currentTime = System.currentTimeMillis();
-        long elapsedTime = (currentTime - previousTime);
-        totalElapsedTime += elapsedTime;
-
-		if (totalElapsedTime > 1000) {
-//			int currentFrameRate = frameCount;
-            frameCount = 0;
-			totalElapsedTime = 0;
-		}
-
-		// check if HolonBodys should be sorted after size
-		if (chckbxSort.isSelected() && sizeChange) {
-			hCController.rearrangeAfterSize();
-			sizeChange = false;
-		}
-		hCController.updateBodies(elapsedTime / 1000f);
-
-		render(g);
-
-		try {
-			// Thread.sleep(getFpsDelay(maxFrameRate));
-			Thread.sleep(5);
-		} catch (Exception e) {
-			e.printStackTrace();
-		}
-
-		previousTime = currentTime;
-		frameCount++;
-		repaint();
-	}
-
-    private void render(Graphics g) {
-        Graphics2D g2 = (Graphics2D) g;
-        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
-
-		// Render Background
-        g2.setColor(Color.WHITE);
-        g2.fillRect(0, 0, getWidth(), getHeight());
-
-		bodies = hCController.getBodies();
-		// Render Objects
-		for (int i = 0; i < subCount; i++) {
-            int bodyNr = bodies.get(i).getId();
-            String info;
-            switch (comboChoice) {
-			case 0:
-				info = "" + bodyNr;
-				break;
-			case 1:
-				info = "" + subnets.get(bodyNr).getObjects().size();
-				break;
-			case 2:
-				info = "" + subnets.get(bodyNr).getEdges().size();
-				break;
-			case 3:
-				info = "" + subnets.get(bodyNr).getSwitches().size();
-				break;
-			case 4:
-                info = "" + hCController.getTotalProduction(new ArrayList<>(subnets.get(bodyNr).getObjects()));
-                break;
-			case 5:
-                info = "" + hCController.getTotalConsumption(new ArrayList<>(subnets.get(bodyNr).getObjects()));
-                break;
-			case 6:
-                info = "" + hCController.getTotalElements(new ArrayList<>(subnets.get(bodyNr).getObjects()));
-                break;
-			case 7:
-                info = "" + hCController.getTotalProducers(new ArrayList<>(subnets.get(bodyNr).getObjects()));
-                break;
-			case 8:
-                info = "" + hCController.getActiveElements(new ArrayList<>(subnets.get(bodyNr).getObjects()));
-                break;
-			default:
-				info = "" + bodyNr;
-				break;
-			}
-			bodies.get(i).setRadius((subnets.get(bodies.get(i).getId()).getObjects().size() * 5 + 10)
-					* controller.getHolonBodyScale() / 100);
-            bodies.get(i).draw(g2, info);
-        }
-	}
-
-	
-	// calc the center of the canvas
-    private void calcCenter() {
-        center = this.getSize();
-		center.height /= 2;
-		center.width /= 2;
-	}
-
-	@Override
-	public void mouseWheelMoved(MouseWheelEvent e) {
-		controller.setHolonBodyScale(model.getHolonBodyScale() + (-e.getScrollAmount() * e.getWheelRotation()));
-	}
-
-	@Override
-	public void mouseClicked(MouseEvent e) {
-
-	}
-
-	@Override
-	public void mouseEntered(MouseEvent e) {
-
-	}
-
-	@Override
-	public void mouseExited(MouseEvent e) {
-
-	}
-
-	@Override
-	public void mousePressed(MouseEvent e) {
-		// Body Selection
-		for (int i = 0; i < subCount; i++) {
-			float cx = bodies.get(i).position.getX();
-			float cy = bodies.get(i).position.getY();
-			float cr = bodies.get(i).getRadius();
-			if (e.getX() - cr <= cx && e.getY() - cr <= cy && e.getX() + cr >= cx && e.getY() + cr >= cy) {
-				controller.addSelectedHolonBody(bodies.get(i).getId());
-				hCController.setBodyToDrag(bodies.get(i).getId());
-				toDrag = bodies.get(i);
-				break;
-			} else {
-				controller.addSelectedHolonBody(-1);
-				toDrag = null;
-			}
-			hCController.setBodyToDrag(-1);
-		}
-	}
-
-	@Override
-	public void mouseReleased(MouseEvent e) {
-		hCController.setDrag(false);
-	}
-
-	@Override
-	public void mouseDragged(MouseEvent e) {
-		hCController.setDrag(true);
-		if (toDrag != null) {
-			toDrag.position = new Vector2d(e.getX(), e.getY());
-		}
-		repaint();
-	}
-
-	@Override
-	public void mouseMoved(MouseEvent e) {
-	}
-}

+ 9 - 20
src/ui/view/IndexTranslator.java

@@ -1,12 +1,14 @@
 package ui.view;
 
 import interfaces.LocalMode;
-import ui.controller.SingletonControl;
 import ui.model.Model;
 
 
 public class IndexTranslator {
 	public static int STANDARD_GRAPH_ACCURACY = 100;
+	// TODO assign model
+	// this refrence should be updated with the model
+	public static Model model;
 	   /**
      * Determines the index of the internal value array
      * of an element that should be used, since elements only save 100 values,
@@ -17,25 +19,12 @@ public class IndexTranslator {
      * @param timeStep the iteration for which the calculation should be made.
      * @return
      */
-    public static int getEffectiveIndex(Model m, LocalMode e, int timeStep){
-    	if(e.isUsingLocalPeriod())return timeStep%e.getLocalPeriod()*100/e.getLocalPeriod();
-    	else return timeStep*100/(m==null?STANDARD_GRAPH_ACCURACY:m.getIterations());
-    }
-    
-    /**
-     * Same as getEffectiveIndex(Model, IGraphedElement, int),
-     * but using the Model obtained from the singleton controller
-     * to determine the total number of iterations(for "use global").
-     */
     public static int getEffectiveIndex(LocalMode e, int timeStep){
-    	return getEffectiveIndex(SingletonControl.getInstance().getControl()==null ? null : SingletonControl.getInstance().getControl().getModel(),e,timeStep);
-    }
-    
-    /**
-     * Same as getEffectiveIndex(Model, IGraphedElement),
-     * but the current iteration is also obtained from the standard model.
-     */
-    public static int getEffectiveIndex(LocalMode e){
-    	return getEffectiveIndex(e,SingletonControl.getInstance().getControl().getModel().getCurIteration());
+    	if(e.isUsingLocalPeriod()) {
+    		return timeStep % e.getLocalPeriod()* 100 /e.getLocalPeriod();
+    	}
+    	else {
+    		return timeStep * 100 / (model == null?STANDARD_GRAPH_ACCURACY:model.getIterations());
+    	}
     }
 }

+ 0 - 74
src/ui/view/LabelHint.java

@@ -1,74 +0,0 @@
-package ui.view;
-
-import javax.swing.JLabel;
-
-public class LabelHint implements Runnable {
-
-	private JLabel label;
-	private String original;
-	private int remainingTime, defaultTime;
-	private static final int DEFAULT_TIME=1000,//milliseconds
-							 DELAY=50;
-	private boolean running=false,
-					keepLength=true;
-	
-	public LabelHint(JLabel label){
-		this(label, DEFAULT_TIME);
-	}
-	
-	public LabelHint(JLabel label, int ms){
-		this.label=label;
-		original=label.getText();
-		this.defaultTime=ms;
-		setRemaining(ms);
-	}
-	
-	public void go(String hint){
-		//the keepLengthStuff should maybe be done by the caller
-		if(keepLength&&hint.length()<original.length()){
-			boolean right=true;
-			while(hint.length()<original.length()){
-				if(right)hint=hint+' ';
-				else hint=' '+hint;
-				right=!right;
-			}
-		}
-		label.setText(hint);
-		setRemaining(defaultTime);
-		if(!running){
-			running=true;
-			new Thread(this).start();
-		}
-	}
-	
-	public void go(String hint, int ms){
-		setRemaining(ms);
-		go(hint);
-	}
-	private void setRemaining(int ms) {
-		remainingTime=ms/DELAY;
-	}
-	
-	public void setKeepLength(boolean b){
-		keepLength=b;
-	}
-
-	@Override
-	public void run() {
-		while(running){
-			remainingTime--;
-			if(remainingTime==0)running=false;
-			try {
-				Thread.sleep(DELAY);
-			} catch (InterruptedException e) {}
-		}
-		//This is supposed to catch one-in-a-million
-		//cases of Thread anomalies.
-		if(remainingTime!=0)go(label.getText());
-		else label.setText(original);
-	}
-
-	public void reset() {
-		label.setText(original);
-	}
-}

+ 2 - 2
src/ui/view/Languages.java

@@ -1,12 +1,12 @@
 package ui.view;
 import java.io.BufferedReader;
-import java.io.FileReader;
-import java.io.IOException;
 import java.io.InputStreamReader;
 import java.nio.charset.Charset;
 
 import utility.ImageImport;
 
+
+//TODO remove this
 public class Languages {
 
 	static int languageVar = 0;

+ 1 - 3
src/ui/view/Main.java

@@ -1,7 +1,6 @@
 package ui.view;
 
 import ui.controller.Control;
-import ui.controller.SingletonControl;
 import ui.model.Model;
 
 import javax.swing.*;
@@ -31,9 +30,8 @@ public class Main {
             try {
                 Model model = new Model();
                 Control control = new Control(model);
-                SingletonControl.getInstance().setControl(control);
                 GUI view = new GUI(control);
-
+                IndexTranslator.model = model;
                 view.getFrmCyberPhysical().setVisible(true);
 
             } catch (Exception e) {

+ 32 - 60
src/ui/view/MyCanvas.java

@@ -1,44 +1,53 @@
 package ui.view;
 
-import classes.*;
+import java.awt.BasicStroke;
+import java.awt.Color;
+import java.awt.Font;
+import java.awt.Graphics;
+import java.awt.Graphics2D;
+import java.awt.RenderingHints;
+import java.awt.datatransfer.UnsupportedFlavorException;
+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.IOException;
+import java.util.ArrayList;
+import java.util.HashSet;
+
+import javax.swing.ImageIcon;
+import javax.swing.JFrame;
+import javax.swing.JLabel;
+import javax.swing.JOptionPane;
+import javax.swing.JScrollPane;
+import javax.swing.JTabbedPane;
+import javax.swing.SwingUtilities;
 
 import com.google.gson.JsonParseException;
 
+import classes.AbstractCanvasObject;
+import classes.Edge;
+import classes.GroupNode;
+import classes.HolonObject;
+import classes.HolonSwitch;
+import classes.Node;
+import classes.Position;
 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.ExitCable;
 import ui.model.DecoratedSwitch.SwitchState;
-import utility.ImageImport;
 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;
+import utility.ImageImport;
 
 /**
  * This Class is the Canvas. All Objects will be visualized here
@@ -203,41 +212,6 @@ public class MyCanvas extends AbstractCanvas implements MouseListener,
 				});
 
 		// adds the selected object(s) to the statistic panel
-		itemTrack.addActionListener(actionEvent -> {
-			for (AbstractCanvasObject o : model.getSelectedCpsObjects()) {
-				if (!((controller.getTrackingObj() != null) && (controller.getTrackingObj().contains(o)))) {
-					controller.addTrackingObj(o);
-					if (o instanceof HolonObject) {
-						((HolonObject) o).updateTrackingInfo();
-					}
-				}
-			}
-		});
-
-		itemUntrack.addActionListener(actionEvent -> {
-			for (AbstractCanvasObject o : model.getSelectedCpsObjects()) {
-				if (o instanceof HolonObject) {
-					boolean found = false;
-					if (controller.getTrackingObj() != null) {
-						for (AbstractCanvasObject obj : controller
-								.getTrackingObj()) {
-							if (obj instanceof HolonObject) {
-								if (obj.getId() == o.getId()) {
-									found = true;
-								}
-							}
-						}
-					}
-					if (found) {
-						// Removed from tracking array and tracking
-						// information reseted
-				controller.removeTrackingObj(o);
-				((HolonObject) o).setTrackingProd(new float[100]);
-				((HolonObject) o).setTrackingCons(new float[100]);
-			}
-		}
-	}
-})		;
 
 		itemDelete.addActionListener(actionEvent -> {
 			// Remove the selected Object objects
@@ -260,7 +234,6 @@ public class MyCanvas extends AbstractCanvas implements MouseListener,
 					if (j == model.getSelectedCpsObjects().size() - 1)
 						save = true;
 					controller.delCanvasObject(cps, save);
-					controller.removeTrackingObj(cps);
 					// Remove UpperNodeTab if UpperNode deleted
 				if (cps instanceof GroupNode) {
 					JTabbedPane tabbedPane = (JTabbedPane)getParent().getParent()
@@ -309,7 +282,6 @@ public class MyCanvas extends AbstractCanvas implements MouseListener,
 				.addActionListener(actionEvent -> {
 					try {
 						controller.paste(null, mousePosition);
-						unitGraph.update(model.getSelectedCpsObjects());
 
 					} catch (JsonParseException | UnsupportedFlavorException
 							| IOException e1) {

+ 1 - 8
src/ui/view/Outliner.java

@@ -3,11 +3,9 @@ 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;
@@ -18,15 +16,10 @@ import javax.swing.tree.DefaultMutableTreeNode;
 import javax.swing.tree.DefaultTreeCellRenderer;
 
 import classes.AbstractCanvasObject;
-
-import classes.Node;
-
 import ui.controller.Control;
-
 import ui.model.Consumer;
 import ui.model.DecoratedCable;
 import ui.model.DecoratedHolonObject.HolonObjectState;
-import utility.ImageImport;
 import ui.model.DecoratedNetwork;
 import ui.model.DecoratedState;
 import ui.model.DecoratedSwitch;
@@ -34,6 +27,7 @@ import ui.model.MinimumNetwork;
 import ui.model.Model;
 import ui.model.Passiv;
 import ui.model.Supplier;
+import utility.ImageImport;
 
 
 
@@ -214,7 +208,6 @@ public class Outliner extends JFrame {
 	}
 	
 	
-	@SuppressWarnings("serial")
 	class ColoredTreeNode extends DefaultMutableTreeNode{
 		private Color color;
 		public ColoredTreeNode(String string, String state, Color color) {

+ 0 - 759
src/ui/view/StatisticGraph.java

@@ -1,759 +0,0 @@
-package ui.view;
-
-import classes.*;
-import ui.controller.Control;
-import ui.model.Model;
-
-import javax.swing.*;
-import java.awt.*;
-import java.awt.geom.GeneralPath;
-import java.util.ArrayList;
-
-public class StatisticGraph extends JPanel {
-
-    /**
-     *
-     */
-    private static final long serialVersionUID = 1L;
-
-    // Maximum y Value
-    private float maximum = 0;
-
-    // is the Simulation running?
-//	private boolean isSimRunning;
-    private GeneralPath path = new GeneralPath();
-    // model and controller
-    private Model model;
-    private Control controller;
-    // Graphics2D
-    private Graphics2D g2;
-
-    // Data
-    private ArrayList<TrackedDataSet> dataSets = new ArrayList<>();
-
-    private boolean showGrid = true;
-
-    private float DISTANCE_IN_GRAPH = 1.0f;
-
-//	private JTable table = new JTable();
-//	private ArrayList<Line2D> gridLines = new ArrayList<>();
-
-    /**
-     * Constructor.
-     *
-     * @param model   the Model
-     * @param control the Controller
-     */
-    StatisticGraph(final Model model, Control control) {
-        this.controller = control;
-        this.model = model;
-        this.setBackground(Color.WHITE);
-    }
-
-    /**
-     * Paints all Components on the Canvas.
-     *
-     * @param g Graphics
-     */
-    public void paintComponent(Graphics g) {
-        super.paintComponent(g);
-
-        // Graphics2D init
-        g2 = (Graphics2D) g;
-        RenderingHints rh = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
-        g2.setRenderingHints(rh);
-
-        // Paint the Grid if it should currently be shown
-        if (showGrid) {
-            g2.setStroke(new BasicStroke(0));
-
-            g2.setColor(Color.BLACK);
-            for (int i = 0; i <= this.getWidth(); i += 10) {
-                g2.drawLine(i, 0, i, this.getHeight());
-            }
-            for (int i = 0; i <= this.getHeight(); i += 5) {
-                g2.drawLine(0, i, this.getWidth(), i);
-            }
-        }
-
-        g2.setStroke(new BasicStroke(3));
-
-        // Calculate the Maximum
-        // calcMaximum();
-
-        // Calculate values for each set and add them
-        // addValues();
-
-        // Create Paths and draw them
-        for (TrackedDataSet set : dataSets) {
-            path.reset();
-            switch (set.getProperty()) {
-                case TrackedDataSet.CONSUMPTION:
-                case TrackedDataSet.PRODUCTION:
-                case TrackedDataSet.ACTIVATED_ELEMENTS:
-                case TrackedDataSet.TOTAL_PRODUCTION:
-                case TrackedDataSet.TOTAL_CONSUMPTION:
-                case TrackedDataSet.WASTED_ENERGY:
-                case TrackedDataSet.AMOUNT_HOLONS:
-                case TrackedDataSet.GROUP_CONSUMPTION:
-                case TrackedDataSet.GROUP_PRODUCTION:
-                case TrackedDataSet.AMOUNT_CLOSED_SWITCHES:
-                case TrackedDataSet.AVG_AMOUNT_OBJECTS_IN_HOLONS:
-                case TrackedDataSet.AVG_AMOUNT_ELEMENTS_IN_HOLONS:
-                case TrackedDataSet.AVG_AMOUNT_PRODUCERS_IN_HOLONS:
-                case TrackedDataSet.AVG_CONSUMED_ENERGY_IN_HOLONS:
-                case TrackedDataSet.AVG_WASTED_ENERGY_IN_HOLONS:
-                case TrackedDataSet.AMOUNT_BROKEN_EDGES:
-                case TrackedDataSet.AVG_AMOUNT_CLOSED_SWITCHES_IN_HOLONS:
-                case TrackedDataSet.AVG_AMOUNT_ACTIVE_ELEMENTS_IN_HOLONS:
-                case TrackedDataSet.AVG_AMOUNT_INACTIVE_ELEMENTS_IN_HOLONS:
-                case TrackedDataSet.AVG_PRODUCED_ENERGY_IN_HOLONS:
-                    createPathFloats(set);
-                    break;
-                case TrackedDataSet.ON_OFF:
-                    createPathBooleans(set);
-                    break;
-                case TrackedDataSet.PERCENT_SUPPLIED:
-                case TrackedDataSet.PERCENT_NOT_SUPPLIED:
-                case TrackedDataSet.PERCENT_PARTIAL_SUPPLIED:
-                case TrackedDataSet.RATIO_PRODUCERS_CONSUMERS:
-                    createPathPercent(set);
-                    break;
-                default:
-                    break;
-            }
-            g2.setColor(set.getColor());
-            g2.draw(path);
-        }
-    }
-
-    /**
-     * Add an Object to the Graph if the maximum has not reached yet.
-     *
-     * @param set the Object to add
-     */
-    public void addObject(TrackedDataSet set) {
-        dataSets.add(set);
-    }
-
-    /**
-     * Removes an Object from the Graph.
-     *
-     * @param id the id of the Object to remove
-     */
-    public void removeObject(int id) {
-        dataSets.remove(id);
-    }
-
-    /**
-     * converts the number to fit the canvas.
-     *
-     * @param d the number to convert
-     * @return the converted number
-     */
-    private double convertToCanvasY(float d) {
-        return Math.abs((this.getHeight() - (d * (this.getHeight() / maximum))));
-    }
-
-    /**
-     * Does take into account which timestep is watched, calculates the max
-     * values.
-     *
-     * @return the currentEnergy
-     */
-    public float getEnergyAtCurrentTimeStep(HolonObject obj) {
-        float temp = 0;
-        for (HolonElement e : obj.getElements()) {
-            if (e.isActive()) {
-                temp = temp + e.getEnergyAtTimeStep(model.getCurIteration());
-            }
-        }
-        return temp;
-    }
-
-    /**
-     * Calculate the Max Value of the Graph
-     */
-    void calcMaximum() {
-        maximum = 0;
-        for (TrackedDataSet set : dataSets) {
-            float val = 0;
-            switch (set.getProperty()) {
-                case TrackedDataSet.CONSUMPTION:
-                    for (HolonElement h : ((HolonObject) set.getCpsObject()).getElements()) {
-                        if (h.getEnergyPerElement() < 0) {
-                            val += (h.getEnergyPerElement() ) * h.getAmount();
-                        }
-                    }
-                    val *= -1;
-                    break;
-                case TrackedDataSet.PRODUCTION:
-                    for (HolonElement h : ((HolonObject) set.getCpsObject()).getElements()) {
-                        if (h.getEnergyPerElement() > 0) {
-                            val += (h.getEnergyPerElement() ) * h.getAmount();
-                        }
-                    }
-                    break;
-                case TrackedDataSet.ACTIVATED_ELEMENTS:
-                    for (HolonElement h : ((HolonObject) set.getCpsObject()).getElements()) {
-                        val += h.getAmount();
-                    }
-                    break;
-                case TrackedDataSet.ON_OFF:
-                    val = 1;
-                    break;
-                case TrackedDataSet.TOTAL_PRODUCTION:
-                    val = getMaxTotalProduction(model.getObjectsOnCanvas());
-                    break;
-                case TrackedDataSet.TOTAL_CONSUMPTION:
-                    val = getMaxTotalConsumption(model.getObjectsOnCanvas());
-                    val *= -1;
-                    break;
-                case TrackedDataSet.WASTED_ENERGY:
-                    val = getMaxWastedEnergy(model.getObjectsOnCanvas());
-                    break;
-                case TrackedDataSet.PERCENT_SUPPLIED:
-                case TrackedDataSet.PERCENT_NOT_SUPPLIED:
-                case TrackedDataSet.PERCENT_PARTIAL_SUPPLIED:
-                    val = 1;
-                    break;
-                case TrackedDataSet.GROUP_PRODUCTION:
-                    val = getMaxTotalProduction(((GroupNode) set.getCpsObject()).getNodes());
-                    break;
-                case TrackedDataSet.GROUP_CONSUMPTION:
-                    val = getMaxTotalConsumption(((GroupNode) set.getCpsObject()).getNodes());
-                    val *= -1;
-                    break;
-                case TrackedDataSet.AMOUNT_HOLONS:
-                    val = controller.getSimManager().getSubNets().size();
-                    for (int i = 0; i < model.getCurIteration(); i++) {
-                        if (val < set.getValues()[i]) {
-                            val = set.getValues()[i];
-                        }
-                    }
-                    break;
-                case TrackedDataSet.AMOUNT_CLOSED_SWITCHES:
-                    val = model.getAllSwitches().size();
-                    break;
-                case TrackedDataSet.AVG_AMOUNT_OBJECTS_IN_HOLONS:
-                    for (SubNet sub : controller.getSimManager().getSubNets()) {
-                        if (val < sub.getObjects().size()) {
-                            val = sub.getObjects().size();
-                        }
-                    }
-                    break;
-                case TrackedDataSet.AVG_AMOUNT_ELEMENTS_IN_HOLONS:
-                case TrackedDataSet.AVG_AMOUNT_ACTIVE_ELEMENTS_IN_HOLONS:
-                case TrackedDataSet.AVG_AMOUNT_INACTIVE_ELEMENTS_IN_HOLONS:
-                    float eCount = 0;
-                    for (SubNet sub : controller.getSimManager().getSubNets()) {
-                        for (HolonObject obj : sub.getObjects()) {
-                            eCount += obj.getElements().size();
-                        }
-                        if (val < eCount) {
-                            val = eCount;
-                        }
-                        eCount = 0;
-                    }
-                    break;
-                case TrackedDataSet.AVG_AMOUNT_PRODUCERS_IN_HOLONS:
-                    for (SubNet sub : controller.getSimManager().getSubNets()) {
-                        if (val < sub.getObjects().size()) {
-                            val = sub.getObjects().size();
-                        }
-                    }
-                    break;
-                case TrackedDataSet.AVG_CONSUMED_ENERGY_IN_HOLONS:
-                    for (SubNet sub : controller.getSimManager().getSubNets()) {
-                        float tempVal = -getMaxTotalConsumption(new ArrayList<>(sub.getObjects()));
-                        if (val < tempVal) {
-                            val = tempVal;
-                        }
-                    }
-                    break;
-                case TrackedDataSet.AVG_WASTED_ENERGY_IN_HOLONS:
-                    for (SubNet sub : controller.getSimManager().getSubNets()) {
-                        float tempVal = getMaxTotalProduction(new ArrayList<>(sub.getObjects()));
-                        if (val < tempVal) {
-                            val = tempVal;
-                        }
-                    }
-                    break;
-                case TrackedDataSet.AMOUNT_BROKEN_EDGES:
-                    for (SubNet sub : controller.getSimManager().getSubNets()) {
-                        val += sub.getSwitches().size();
-                    }
-                    break;
-                case TrackedDataSet.RATIO_PRODUCERS_CONSUMERS:
-                    val = 1;
-                    break;
-                case TrackedDataSet.AVG_AMOUNT_CLOSED_SWITCHES_IN_HOLONS:
-                    for (SubNet sub : controller.getSimManager().getSubNets()) {
-                        float tempVal = sub.getSwitches().size();
-                        if (val < tempVal) {
-                            val = tempVal;
-                        }
-                    }
-                    break;
-                case TrackedDataSet.AVG_PRODUCED_ENERGY_IN_HOLONS:
-                    for (SubNet sub : controller.getSimManager().getSubNets()) {
-                        float tempVal = getMaxTotalProduction(new ArrayList<>(sub.getObjects()));
-                        if (val < tempVal) {
-                            val = tempVal;
-                        }
-                    }
-                    break;
-                default:
-                    maximum = 0;
-                    break;
-            }
-            if (val > maximum) {
-                maximum = val;
-            }
-        }
-        ((StatisticGraphPanel) this.getParent().getParent()).setMaximumLabel(maximum);
-    }
-
-    /**
-     * Add the Current Values to each set
-     */
-    void addValues() {
-        for (TrackedDataSet set : dataSets) {
-            float val = 0;
-            switch (set.getProperty()) {
-                case TrackedDataSet.CONSUMPTION:
-                    for (HolonElement h : ((HolonObject) set.getCpsObject()).getElements()) {
-                        if (h.isActive() && h.getOverallEnergyAtTimeStep(model.getCurIteration()) < 0 ) {
-                            val += Math.abs(h.getOverallEnergyAtTimeStep(model.getCurIteration()));
-                        }
-                        set.setValAt(val, model.getCurIteration());
-                    }
-                    break;
-                case TrackedDataSet.PRODUCTION:
-                    for (HolonElement h : ((HolonObject) set.getCpsObject()).getElements()) {
-                        if (h.isActive()&& h.getOverallEnergyAtTimeStep(model.getCurIteration()) > 0) {
-                            val += Math.abs(h.getOverallEnergyAtTimeStep(model.getCurIteration()));
-                        }
-                        set.setValAt(val, model.getCurIteration());
-                    }
-
-                    break;
-                case TrackedDataSet.ACTIVATED_ELEMENTS:
-                    for (HolonElement h : ((HolonObject) set.getCpsObject()).getElements()) {
-                        if (h.isActive()) {
-                            val += h.getAmount();
-                        }
-                        set.setValAt(val, model.getCurIteration());
-                    }
-                    break;
-                case TrackedDataSet.ON_OFF:
-                    if (((HolonSwitch) set.getCpsObject()).getManualMode()) {
-                        if (((HolonSwitch) set.getCpsObject()).getManualState()) {
-                            set.setValAt(1, model.getCurIteration());
-                        } else {
-                            set.setValAt(0, model.getCurIteration());
-                        }
-                    } else {
-                        if (((HolonSwitch) set.getCpsObject()).getState(model.getCurIteration())) {
-                            set.setValAt(1, model.getCurIteration());
-                        } else {
-                            set.setValAt(0, model.getCurIteration());
-                        }
-                    }
-                    break;
-                case TrackedDataSet.TOTAL_PRODUCTION:
-                    set.setValAt(getTotalProductionAt(model.getObjectsOnCanvas(), model.getCurIteration()),
-                            model.getCurIteration());
-                    break;
-                case TrackedDataSet.TOTAL_CONSUMPTION:
-                    set.setValAt(-getTotalConsumptionAt(model.getObjectsOnCanvas(), model.getCurIteration()),
-                            model.getCurIteration());
-                    break;
-                case TrackedDataSet.WASTED_ENERGY:
-                    float wasted = getTotalWastedEnergyAt(model.getObjectsOnCanvas(), model.getCurIteration());
-                    set.setValAt(wasted, model.getCurIteration());
-                    break;
-               
-              
-                case TrackedDataSet.GROUP_PRODUCTION:
-                    set.setValAt(
-                            getTotalProductionAt(((GroupNode) set.getCpsObject()).getNodes(), model.getCurIteration()),
-                            model.getCurIteration());
-                    break;
-                case TrackedDataSet.GROUP_CONSUMPTION:
-                    set.setValAt(
-                            -getTotalConsumptionAt(((GroupNode) set.getCpsObject()).getNodes(), model.getCurIteration()),
-                            model.getCurIteration());
-                    break;
-                case TrackedDataSet.AMOUNT_HOLONS:
-                    set.setValAt(controller.getSimManager().getSubNets().size(), model.getCurIteration());
-                    break;
-                case TrackedDataSet.AMOUNT_CLOSED_SWITCHES:
-                    for (HolonSwitch s : model.getAllSwitches()) {
-                        if (s.getState(model.getCurIteration())) {
-                            val++;
-                        }
-                    }
-                    set.setValAt(val, model.getCurIteration());
-                    break;
-                case TrackedDataSet.AVG_AMOUNT_OBJECTS_IN_HOLONS:
-                    for (SubNet sub : controller.getSimManager().getSubNets()) {
-                        val += sub.getObjects().size();
-                    }
-                    val /= controller.getSimManager().getSubNets().size();
-                    set.setValAt(val, model.getCurIteration());
-                    break;
-                case TrackedDataSet.AVG_AMOUNT_ELEMENTS_IN_HOLONS:
-                    for (SubNet sub : controller.getSimManager().getSubNets()) {
-                        for (HolonObject obj : sub.getObjects()) {
-                            val += obj.getElements().size();
-                        }
-                    }
-                    val /= controller.getSimManager().getSubNets().size();
-                    set.setValAt(val, model.getCurIteration());
-                    break;
-                case TrackedDataSet.AVG_AMOUNT_PRODUCERS_IN_HOLONS:
-                    for (SubNet sub : controller.getSimManager().getSubNets()) {
-                        for (HolonObject obj : sub.getObjects()) {
-                            if (obj.getEnergyAtTimeStep(model.getCurIteration()) > 0) {
-                                val++;
-                            }
-                        }
-                    }
-                    val /= controller.getSimManager().getSubNets().size();
-                    set.setValAt(val, model.getCurIteration());
-                    break;
-                case TrackedDataSet.AVG_CONSUMED_ENERGY_IN_HOLONS:
-                    for (SubNet sub : controller.getSimManager().getSubNets()) {
-                        val += -getTotalConsumptionAt(new ArrayList<>(sub.getObjects()),
-                                model.getCurIteration());
-                    }
-                    val /= controller.getSimManager().getSubNets().size();
-                    set.setValAt(val, model.getCurIteration());
-                    break;
-                case TrackedDataSet.AVG_WASTED_ENERGY_IN_HOLONS:
-                    for (SubNet sub : controller.getSimManager().getSubNets()) {
-                        val += (getTotalProductionAt(new ArrayList<>(sub.getObjects()),
-                                model.getCurIteration())
-                                + getTotalConsumptionAt(new ArrayList<>(sub.getObjects()),
-                                model.getCurIteration()));
-                    }
-                    val /= controller.getSimManager().getSubNets().size();
-                    set.setValAt(val, model.getCurIteration());
-                    break;
-                case TrackedDataSet.AMOUNT_BROKEN_EDGES:
-                    for (SubNet sub : controller.getSimManager().getSubNets()) {
-                        for (HolonSwitch s : sub.getSwitches()) {
-                            if (s.getManualMode()?s.getManualState():s.getAutoActive()) {
-                                val++;
-                            }
-                        }
-                    }
-                    set.setValAt(val, model.getCurIteration());
-                    break;
-                case TrackedDataSet.RATIO_PRODUCERS_CONSUMERS:
-                    float prod = 0;
-                    float cons = 0;
-                    for (SubNet sub : controller.getSimManager().getSubNets()) {
-                        for (HolonObject obj : sub.getObjects()) {
-                            if (obj.getEnergyAtTimeStep(model.getCurIteration()) > 0) {
-                                prod++;
-                            } else if (obj.getEnergyAtTimeStep(model.getCurIteration()) < 0) {
-                                cons++;
-                            }
-                        }
-                    }
-                    val = prod / (prod + cons);
-                    set.setValAt(val, model.getCurIteration());
-                    break;
-                case TrackedDataSet.AVG_AMOUNT_CLOSED_SWITCHES_IN_HOLONS:
-                    for (SubNet sub : controller.getSimManager().getSubNets()) {
-                        val += sub.getSwitches().size();
-                    }
-                    val /= controller.getSimManager().getSubNets().size();
-                    set.setValAt(val, model.getCurIteration());
-                    break;
-                case TrackedDataSet.AVG_AMOUNT_ACTIVE_ELEMENTS_IN_HOLONS:
-                    for (SubNet sub : controller.getSimManager().getSubNets()) {
-                        for (HolonObject obj : sub.getObjects()) {
-                            for (HolonElement ele : obj.getElements()) {
-                                if (ele.isActive()) {
-                                    val++;
-                                }
-                            }
-                        }
-                    }
-                    val /= controller.getSimManager().getSubNets().size();
-                    set.setValAt(val, model.getCurIteration());
-                    break;
-                case TrackedDataSet.AVG_AMOUNT_INACTIVE_ELEMENTS_IN_HOLONS:
-                    for (SubNet sub : controller.getSimManager().getSubNets()) {
-                        for (HolonObject obj : sub.getObjects()) {
-                            for (HolonElement ele : obj.getElements()) {
-                                if (!ele.isActive()) {
-                                    val++;
-                                }
-                            }
-                        }
-                    }
-                    val /= controller.getSimManager().getSubNets().size();
-                    set.setValAt(val, model.getCurIteration());
-                    break;
-                case TrackedDataSet.AVG_PRODUCED_ENERGY_IN_HOLONS:
-                    for (SubNet sub : controller.getSimManager().getSubNets()) {
-                        val += getTotalProductionAt(new ArrayList<>(sub.getObjects()),
-                                model.getCurIteration());
-                    }
-                    val /= controller.getSimManager().getSubNets().size();
-                    set.setValAt(val, model.getCurIteration());
-                    break;
-                default:
-                    break;
-            }
-        }
-    }
-
-    /**
-     * create Path with floats
-     *
-     * @param set tracked data
-     */
-    private void createPathFloats(TrackedDataSet set) {
-        int range = model.getCurIteration(); //to which iteration
-        if (!model.getIsSimRunning()) {
-            range = model.getIterations() - 1;
-        }
-        if (set.getValues()[0] != -1) {
-            path.moveTo(0, convertToCanvasY(set.getValues()[0]));
-        } else {
-            path.moveTo(DISTANCE_IN_GRAPH * this.getWidth() / model.getIterations(), convertToCanvasY(set.getValues()[1]));
-        }
-        for (int i = 0; i < range; i++) {
-            if (set.getValues()[i + 1] != -1) {
-                path.lineTo((i + 1) * this.getWidth() / model.getIterations(),
-                        convertToCanvasY(set.getValues()[i + 1]));
-            } else {
-                if (i + 2 < range) {
-                    path.moveTo((i + 2) * this.getWidth() / model.getIterations(),
-                            convertToCanvasY(set.getValues()[i + 2]));
-                }
-            }
-        }
-    }
-
-    /**
-     * create Path with booleans(0 and 1)
-     *
-     * @param set tracked data
-     */
-    private void createPathBooleans(TrackedDataSet set) {
-        if (set.getValues()[0] != -1) {
-            path.moveTo(0, convertToCanvasY((set.getValues()[0] * (maximum / 3 * 2)) + (maximum / 6)));
-        } else {
-            path.moveTo(DISTANCE_IN_GRAPH * this.getWidth() / model.getIterations(),
-                    convertToCanvasY((set.getValues()[1] * (maximum / 3 * 2)) + (maximum / 6)));
-        }
-        for (int i = 0; i < model.getCurIteration(); 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)));
-            } else {
-                if (i + 2 < model.getCurIteration()) {
-                    path.moveTo((i + 2) * this.getWidth() / model.getIterations(),
-                            convertToCanvasY((set.getValues()[i + 2] * (maximum / 3 * 2)) + (maximum / 6)));
-                }
-            }
-        }
-    }
-
-    /**
-     * create Path for percent values
-     *
-     * @param set tracked data
-     */
-    private void createPathPercent(TrackedDataSet set) {
-        if (set.getValues()[0] != -1) {
-            path.moveTo(0, convertToCanvasY(set.getValues()[0] * maximum));
-        } else {
-            path.moveTo(DISTANCE_IN_GRAPH * this.getWidth() / model.getIterations(), convertToCanvasY(set.getValues()[1] * maximum));
-        }
-        for (int i = 0; i < model.getCurIteration(); i++) {
-            if (set.getValues()[i + 1] != -1) {
-                path.lineTo((i + 1) * this.getWidth() / model.getIterations(),
-                        convertToCanvasY(set.getValues()[i + 1] * maximum));
-            } else {
-                if (i + 2 < model.getCurIteration()) {
-                    path.moveTo((i + 2) * this.getWidth() / model.getIterations(),
-                            convertToCanvasY(set.getValues()[i + 2] * maximum));
-                }
-            }
-
-        }
-    }
-
-    /**
-     * get the max total production of the given Objects
-     */
-    private float getMaxTotalProduction(ArrayList<AbstractCanvasObject> objects) {
-        float val = 0;
-
-        for (AbstractCanvasObject obj : objects) {
-            if (obj instanceof HolonObject) {
-                for (HolonElement ele : ((HolonObject) obj).getElements()) {
-                    if (ele.getEnergyPerElement() > 0) {
-                        val += (ele.getEnergyPerElement() ) * ele.getAmount();
-                    }
-                }
-            } else if (obj instanceof GroupNode) {
-                val += getMaxTotalProduction(((GroupNode) obj).getNodes());
-            }
-        }
-        return val;
-    }
-
-    /**
-     * get the max total consumption of the given Objects
-     */
-    private float getMaxTotalConsumption(ArrayList<AbstractCanvasObject> objects) {
-        float val = 0;
-
-        for (AbstractCanvasObject obj : objects) {
-            if (obj instanceof HolonObject) {
-                for (HolonElement ele : ((HolonObject) obj).getElements()) {
-                    if (ele.getEnergyPerElement() < 0) {
-                        val += (ele.getEnergyPerElement() ) * ele.getAmount();
-                    }
-                }
-            } else if (obj instanceof GroupNode) {
-                val += getMaxTotalConsumption(((GroupNode) obj).getNodes());
-            }
-        }
-        return val;
-    }
-
-
-    /**
-     * get the max total wasted energy of the given Objects
-     * if it is smaller than 0, return 0
-     */
-    private float getMaxWastedEnergy(ArrayList<AbstractCanvasObject> objects) {
-        float val = 0;
-
-        for (AbstractCanvasObject obj : objects) {
-            if (obj instanceof HolonObject) {
-                for (HolonElement ele : ((HolonObject) obj).getElements()) {
-                    val += (ele.getEnergyPerElement() ) * ele.getAmount();
-                }
-            } else if (obj instanceof GroupNode) {
-                val += getMaxWastedEnergy(((GroupNode) obj).getNodes());
-            }
-        }
-
-        return val < 0 ? 0 : val;
-    }
-
-
-    /**
-     * get the max total production of the given objects at the given timestep
-     */
-    private float getTotalProductionAt(ArrayList<AbstractCanvasObject> objects, int tStep) {
-        float val = 0;
-
-        for (AbstractCanvasObject obj : objects) {
-            if (obj instanceof HolonObject) {
-                for (HolonElement ele : ((HolonObject) obj).getElements()) {
-                    if (ele.isActive() && ele.getOverallEnergyAtTimeStep(tStep) > 0 ) {
-                        val += ele.getOverallEnergyAtTimeStep(tStep);
-                    }
-                }
-            } else if (obj instanceof GroupNode) {
-                val += getTotalProductionAt(((GroupNode) obj).getNodes(), tStep);
-            }
-        }
-        return val;
-    }
-
-    /**
-     * get the total consumption of the given objects at the given timestep
-     */
-    private float getTotalConsumptionAt(ArrayList<AbstractCanvasObject> objects, int tStep) {
-        float val = 0;
-
-        for (AbstractCanvasObject obj : objects) {
-            if (obj instanceof HolonObject) {
-                for (HolonElement ele : ((HolonObject) obj).getElements()) {
-                    if (ele.isActive() && ele.getEnergyAtTimeStep(tStep) < 0 ) {
-                        val += ele.getOverallEnergyAtTimeStep(tStep);
-                    }
-                }
-            } else if (obj instanceof GroupNode) {
-                val += getTotalConsumptionAt(((GroupNode) obj).getNodes(), tStep);
-            }
-        }
-        return val;
-    }
-
-    /**
-     * get the total wasted energy of the given objects at the given timestep
-     */
-    private float getTotalWastedEnergyAt(ArrayList<AbstractCanvasObject> objects, int tStep) {
-        float val = 0;
-
-        for (AbstractCanvasObject obj : objects) {
-            if (obj instanceof HolonObject) {
-                for (HolonElement ele : ((HolonObject) obj).getElements()) {
-                    if (ele.isActive()) {
-                        val += ele.getOverallEnergyAtTimeStep(tStep);
-                    }
-                }
-            } else if (obj instanceof GroupNode) {
-                val += getTotalWastedEnergyAt(((GroupNode) obj).getNodes(), tStep);
-            }
-        }
-
-        return val;
-    }
-
-
-  
-
-    /**
-     * Return all TrackedDataSets
-     *
-     * @return ArrayList of TrackedDataSet
-     */
-    public ArrayList<TrackedDataSet> getDataSets() {
-        return dataSets;
-    }
-
-    /**
-     * Reset the Graph. Delete all calculated values.
-     */
-    void resetGraph() {
-        for (TrackedDataSet s : dataSets) {
-            s.resetValues();
-        }
-    }
-
-    void hideGrid() {
-        Graphics g = this.getGraphics();
-        showGrid = false;
-        // clear the area
-        g.clearRect(0, 0, this.getWidth(), this.getHeight());
-        paintComponent(g);
-    }
-
-    void showGrid() {
-        Graphics g = this.getGraphics();
-        showGrid = true;
-        paintComponent(g);
-    }
-
-	void updateIterations() {
-		for(TrackedDataSet dataSet:dataSets){
-			dataSet.updateIterations();
-		}
-	}
-
-
-}

+ 0 - 349
src/ui/view/StatisticGraphPanel.java

@@ -1,349 +0,0 @@
-package ui.view;
-
-import classes.TrackedDataSet;
-import ui.controller.Control;
-import ui.model.Model;
-
-import javax.imageio.ImageIO;
-import javax.swing.*;
-import javax.swing.border.EmptyBorder;
-import java.awt.*;
-import java.awt.event.MouseAdapter;
-import java.awt.event.MouseEvent;
-import java.awt.image.BufferedImage;
-import java.io.File;
-import java.io.IOException;
-import java.util.Hashtable;
-
-public class StatisticGraphPanel extends JSplitPane {
-
-    private static final long serialVersionUID = 1L;
-
-    private final JLabel maximumLabel = new JLabel("0");
-    private final JPanel legendPanel = new JPanel();
-    private String[] backgroundColors = {"White", "Dark", "Red", "Blue"};
-    // Variables
-    private String graphName;
-    // Components
-    private StatisticGraph sGraph;
-    private JToggleButton toggleGridButton = new JToggleButton("Hide Grid");
-    private JComboBox backgroundColorSelector = new JComboBox(backgroundColors);
-    private JSplitPane that;
-    private Hashtable<String, StatisticGraphPanel> graphHashtable;
-
-    /**
-     * Constructor.
-     *
-     * @param mod  the Model
-     * @param cont the Controller
-     */
-    StatisticGraphPanel(Model mod, Control cont, String name, Hashtable<String, StatisticGraphPanel> gHt) {
-        super();
-        setDividerSize(0);
-        setPreferredSize(new Dimension(600, 300));
-        setContinuousLayout(true);
-        setMinimumSize(new Dimension(600, 300));
-        setOrientation(JSplitPane.VERTICAL_SPLIT);
-        setBorder(new EmptyBorder(0, 0, 0, 0));
-//        this.model = mod;
-//        this.controller = cont;
-        this.sGraph = new StatisticGraph(mod, cont);
-        this.graphName = name;
-        this.graphHashtable = gHt;
-        JPanel topContainer = new JPanel();
-        topContainer.setLayout(new BorderLayout(0, 0));
-        JPanel buttomContainer = new JPanel();
-        buttomContainer.setPreferredSize(new Dimension(0, 0));
-        buttomContainer.setMinimumSize(new Dimension(0, 0));
-        buttomContainer.setAlignmentX(Component.LEFT_ALIGNMENT);
-        buttomContainer.setAlignmentY(Component.TOP_ALIGNMENT);
-        buttomContainer.setLayout(new BorderLayout(0, 0));
-        this.setTopComponent(topContainer);
-        this.setBottomComponent(buttomContainer);
-
-        // ******************** Component Propertys ***************//
-        // Graph
-        sGraph.setPreferredSize(new Dimension(200, 200));
-        sGraph.setMinimumSize(new Dimension(100, 150));
-
-        // Graph Name
-        JLabel graphNameLabel = new JLabel(graphName);
-        graphNameLabel.setHorizontalTextPosition(JLabel.CENTER);
-        // set font bold and font size slightly bigger than the rest
-        graphNameLabel.setFont(new Font(graphNameLabel.getFont().getName(), Font.BOLD, 14));
-
-        toggleGridButton.addActionListener(actionEvent -> {
-            boolean currentState = toggleGridButton.isSelected();
-            if (currentState) {
-                sGraph.hideGrid();
-                toggleGridButton.setText("Show Grid");
-            } else {
-                sGraph.showGrid();
-                toggleGridButton.setText("Hide Grid");
-            }
-        });
-
-        // Panel on top (Name and Close Button)
-        JPanel topPanel = new JPanel();
-        topPanel.setLayout(new BorderLayout(0, 0));
-        JPanel topPanelHelp = new JPanel(new BorderLayout(0, 0));
-        topPanelHelp.add(graphNameLabel, BorderLayout.CENTER);
-        // graph options
-        JPanel graphOptionsContainer = new JPanel();
-        graphOptionsContainer.add(toggleGridButton);
-        graphOptionsContainer.add(new JLabel("  "));    // spacer
-        JLabel backgroundColorLabel = new JLabel("Background: ");
-        graphOptionsContainer.add(backgroundColorLabel);
-        graphOptionsContainer.add(backgroundColorSelector);
-        graphOptionsContainer.add(new JLabel("  "));    // spacer
-        JButton savImgButton = new JButton("Save as Image");
-        graphOptionsContainer.add(savImgButton);
-        topPanelHelp.add(graphOptionsContainer, BorderLayout.EAST);
-        //
-        topPanel.add(topPanelHelp, BorderLayout.CENTER);
-        JButton closeButton = new JButton("X");
-        topPanel.add(closeButton, BorderLayout.EAST);
-        savImgButton.addActionListener(actionEvent -> {
-            BufferedImage img = new BufferedImage(that.getWidth(), that.getHeight(), BufferedImage.TYPE_INT_RGB);
-            that.print(img.getGraphics());
-            try {
-                JFileChooser fileChooser = new JFileChooser();
-                if (fileChooser.showSaveDialog(new JFrame()) == JFileChooser.APPROVE_OPTION) {
-                    String file = fileChooser.getSelectedFile().getPath();
-                    ImageIO.write(img, "jpg", new File(file + ".jpg"));
-                }
-            } catch (IOException e1) {
-                e1.printStackTrace();
-            }
-
-        });
-        topPanel.setBorder(null);
-
-        // background-color selector
-        backgroundColorSelector.addActionListener(actionEvent -> {
-            String selectedBackgroundString = (String) backgroundColorSelector.getSelectedItem();
-            switch (selectedBackgroundString) {
-                case "White":
-                    sGraph.setBackground(Color.WHITE);
-                    break;
-                case "Dark":
-                    sGraph.setBackground(Color.DARK_GRAY);
-                    break;
-                case "Red":
-                    sGraph.setBackground(Color.RED);
-                    break;
-                case "Blue":
-                    sGraph.setBackground(Color.BLUE);
-                    break;
-            }
-        });
-
-        // Maximum Label
-        maximumLabel.setVerticalAlignment(SwingConstants.TOP);
-        maximumLabel.setMinimumSize(new Dimension(30, 10));
-        legendPanel.setAlignmentY(Component.BOTTOM_ALIGNMENT);
-
-        // Legend Panel
-        legendPanel.setLayout(new GridLayout(0, 5, 0, 0));
-
-        // ******************** Component Listener ****************//
-
-        that = this;
-        closeButton.addActionListener(actionEvent -> {
-            JPanel parent = (JPanel) that.getParent();
-            for (int i = 0; i < parent.getComponentCount(); i++) {
-                if (parent.getComponent(i).equals(that)) {
-                    if (parent.getComponentCount() > i + 1) {
-                        parent.remove(parent.getComponent(i + 1));
-                    }
-                    break;
-                }
-            }
-            graphHashtable.remove(graphName);
-            parent.remove(that);
-            parent.updateUI();
-        });
-
-        // ******************** add everything ********************//
-        topContainer.add(sGraph);
-        topContainer.add(topPanel, BorderLayout.NORTH);
-        topContainer.add(maximumLabel, BorderLayout.WEST);
-        buttomContainer.add(legendPanel, BorderLayout.NORTH);
-        this.setEnabled(false);
-
-    }
-
-    /**
-     * Adds the Set to the Graph.
-     */
-
-    public void addObject(TrackedDataSet set) {
-        if (legendPanel.getComponentCount() >= 20) {
-            JOptionPane.showMessageDialog(null, "You can not add more than 20 Properties to a Graph");
-            return;
-        }
-        sGraph.addObject(set);
-        String property;
-        switch (set.getProperty()) {
-            case TrackedDataSet.CONSUMPTION:
-            case TrackedDataSet.GROUP_CONSUMPTION:
-                property = "consumption";
-                break;
-            case TrackedDataSet.PRODUCTION:
-            case TrackedDataSet.WASTED_ENERGY:
-                property = "wasted energy";
-                break;
-            case TrackedDataSet.GROUP_PRODUCTION:
-                property = "production";
-                break;
-            case TrackedDataSet.ACTIVATED_ELEMENTS:
-                property = "active elements";
-                break;
-            case TrackedDataSet.ON_OFF:
-                property = "on//off";
-                break;
-            case TrackedDataSet.TOTAL_PRODUCTION:
-                property = "total production";
-                break;
-            case TrackedDataSet.TOTAL_CONSUMPTION:
-                property = "total consumption";
-                break;
-            case TrackedDataSet.PERCENT_SUPPLIED:
-                property = "Percentage of supplied";
-                break;
-            case TrackedDataSet.PERCENT_NOT_SUPPLIED:
-                property = "Percentage of not supplied";
-                break;
-            case TrackedDataSet.PERCENT_PARTIAL_SUPPLIED:
-                property = "Percentage of partial supplied";
-                break;
-            case TrackedDataSet.AMOUNT_HOLONS:
-                property = "Amount of holons";
-                break;
-            case TrackedDataSet.AMOUNT_CLOSED_SWITCHES:
-                property = "Amount of Closed Switches";
-                break;
-            case TrackedDataSet.AVG_AMOUNT_OBJECTS_IN_HOLONS:
-                property = "Avg. Amount of Objects in Holons";
-                break;
-            case TrackedDataSet.AVG_AMOUNT_ELEMENTS_IN_HOLONS:
-                property = "Avg. Amount of Elements in Holons";
-                break;
-            case TrackedDataSet.AVG_AMOUNT_PRODUCERS_IN_HOLONS:
-                property = "Avg. Amount Producers in Holons";
-                break;
-            case TrackedDataSet.AVG_CONSUMED_ENERGY_IN_HOLONS:
-                property = "Avg. Consumed Energy in Holons";
-                break;
-            case TrackedDataSet.AVG_WASTED_ENERGY_IN_HOLONS:
-                property = "Avg. Wasted Energy in Holons";
-                break;
-            case TrackedDataSet.AMOUNT_BROKEN_EDGES:
-                property = "Amount of Broken Edged";
-                break;
-            case TrackedDataSet.RATIO_PRODUCERS_CONSUMERS:
-                property = "Ratio Producers:Consumers";
-                break;
-            case TrackedDataSet.AVG_AMOUNT_CLOSED_SWITCHES_IN_HOLONS:
-                property = "Avg. Amount of Closed Switches in Holons";
-                break;
-            case TrackedDataSet.AVG_AMOUNT_ACTIVE_ELEMENTS_IN_HOLONS:
-                property = "Avg. Amount of Active Elements in Holons";
-                break;
-            case TrackedDataSet.AVG_AMOUNT_INACTIVE_ELEMENTS_IN_HOLONS:
-                property = "Avg. Amount of Inactive Elements in Holons";
-                break;
-            case TrackedDataSet.AVG_PRODUCED_ENERGY_IN_HOLONS:
-                property = "Avg. Produced Energy in Holons";
-                break;
-            default:
-                property = "null";
-                break;
-        }
-        JLabel b;
-        if (set.getCpsObject() != null) {
-            b = new JLabel(set.getCpsObject().getId() + ", " + set.getCpsObject().getName() + ": " + property);
-        } else {
-            b = new JLabel(property);
-        }
-        // b.setBackground(set.getColor());
-        b.setBorder(BorderFactory.createLineBorder(set.getColor(), 2));
-        b.setHorizontalAlignment(SwingConstants.CENTER);
-//        int color = Math.max(Math.max(set.getColor().getRed(), set.getColor().getGreen()), set.getColor().getBlue());
-
-        b.setOpaque(true);
-        b.addMouseListener(new MouseAdapter() {
-
-            @Override
-            public void mousePressed(MouseEvent e) {
-                if (MouseEvent.BUTTON3 == e.getButton()) {
-                    for (int i = 0; i < legendPanel.getComponentCount(); i++) {
-                        if (legendPanel.getComponent(i).equals(e.getComponent())) {
-                            legendPanel.remove(i);
-                            sGraph.removeObject(i);
-                            that.updateUI();
-                        }
-                    }
-                }
-            }
-        });
-        legendPanel.add(b);
-        sGraph.calcMaximum();
-        that.updateUI();
-    }
-
-    /**
-     * Set the Maximum Label
-     */
-    void setMaximumLabel(double max) {
-        maximumLabel.setText(Double.toString(max));
-    }
-
-//    /**
-//     * Get the name of the Graph.
-//     *
-//     * @return the name of the Graph
-//     */
-//    public String getGraphName() {
-//        return this.graphName;
-//    }
-
-    /**
-     * Calls the addValue function of the sGraph
-     */
-    void addValues() {
-        sGraph.addValues();
-    }
-
-    /**
-     * Calls the calcMaximum function of the sGraph
-     */
-    void calcMaximum() {
-        sGraph.calcMaximum();
-    }
-
-    public StatisticGraph getStatGraph() {
-        return sGraph;
-    }
-
-//    public void setStatisticGraph(StatisticGraph sG) {
-//        this.sGraph = sG;
-//    }
-
-    /**
-     * Reset the Graph. Delete all calculated values.
-     */
-    public void resetGraph() {
-        sGraph.resetGraph();
-    }
-
-    /**
-     * Returns the Legend Panel.
-     *
-     * @return legendPanel
-     */
-    public JPanel getLegendPanel() {
-        return legendPanel;
-    }
-
-}

部分文件因文件數量過多而無法顯示