GraphMetrics.java 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. package algorithm.objective_function;
  2. import java.util.ArrayList;
  3. import java.util.Arrays;
  4. import java.util.HashMap;
  5. import java.util.HashSet;
  6. import java.util.LinkedList;
  7. import java.util.List;
  8. import java.util.Map.Entry;
  9. import model.AbstractCanvasObject;
  10. import model.HolonSwitch;
  11. import java.util.Set;
  12. import ui.model.Consumer;
  13. import ui.model.DecoratedNetwork;
  14. import ui.model.Passiv;
  15. import ui.model.Supplier;
  16. public class GraphMetrics {
  17. public static class Vertex{
  18. public int id = 0;
  19. public Vertex(int id){
  20. this.id = id;
  21. }
  22. public String toString() {
  23. return "" + id;
  24. }
  25. }
  26. private static class Edge{
  27. public int idA, idB;
  28. public double weight;
  29. public Edge(int idA, int idB, double weight){
  30. this.idA = idA;
  31. this.idB = idB;
  32. this.weight = weight;
  33. }
  34. }
  35. public static class Graph{
  36. Vertex[] V;
  37. Edge[] E;
  38. /**Only the Sources/Trains for disjoint Path no Switch or Node**/
  39. Vertex[] S;
  40. public String toString() {
  41. String vList = "V" + Arrays.toString(V);
  42. String sList = "S" + Arrays.toString(S);
  43. return vList + ", " + sList;
  44. }
  45. }
  46. /**
  47. * Convert a DecoratedNetwork to a Graph
  48. * @param net
  49. * @return a equivalent Graph to the DecoratedNetwork
  50. */
  51. public static Graph convertDecoratedNetworkToGraph(DecoratedNetwork net) {
  52. Graph G = new Graph();
  53. HashMap<AbstractCanvasObject, Integer> objectToId = new HashMap<>();
  54. List<Integer> sourcesList = new ArrayList<Integer>();
  55. int count = 0;
  56. for(Consumer con: net.getConsumerList()) {
  57. objectToId.put(con.getModel(), count);
  58. sourcesList.add(count);
  59. count++;
  60. }
  61. for(Consumer con: net.getConsumerSelfSuppliedList()) {
  62. objectToId.put(con.getModel(), count);
  63. sourcesList.add(count);
  64. count++;
  65. }
  66. for(Passiv pas: net.getPassivNoEnergyList()) {
  67. objectToId.put(pas.getModel(), count);
  68. sourcesList.add(count);
  69. count++;
  70. }
  71. for(Supplier sup: net.getSupplierList()) {
  72. objectToId.put(sup.getModel(), count);
  73. sourcesList.add(count);
  74. count++;
  75. }
  76. //Generate EdgeList
  77. List<Edge> edgeList = new ArrayList<Edge>();
  78. for(model.Edge cable : net.getDecoratedCableList()){
  79. AbstractCanvasObject objectA = cable.getA();
  80. AbstractCanvasObject objectB = cable.getB();
  81. if(objectA == null) {
  82. System.out.println("Edge: " + cable + "objectA == null");
  83. continue;
  84. }
  85. if(objectB == null) {
  86. System.out.println("Edge: " + cable + "objectB == null");
  87. continue;
  88. }
  89. //SpecialCase for open switches
  90. if(objectA instanceof HolonSwitch sw && !sw.getManualState()) {
  91. continue;
  92. }
  93. if(objectB instanceof HolonSwitch sw && !sw.getManualState()) {
  94. continue;
  95. }
  96. int idA = -1;
  97. if(objectToId.containsKey(objectA)) {
  98. idA = objectToId.get(objectA);
  99. }else {
  100. idA = count;
  101. objectToId.put(objectA, count++);
  102. }
  103. int idB = -1;
  104. if(objectToId.containsKey(objectB)) {
  105. idB = objectToId.get(objectB);
  106. }else {
  107. idB = count;
  108. objectToId.put(objectB, count++);
  109. }
  110. double length = cable.getLength();
  111. edgeList.add(new Edge(idA, idB, length));
  112. }
  113. //Generate EdgeArray
  114. G.E = new Edge[edgeList.size()];
  115. for(int i=0;i<edgeList.size();i++)
  116. {
  117. G.E[i] = edgeList.get(i);
  118. }
  119. //Generate VertexArray
  120. G.V = new Vertex[objectToId.size()];
  121. int entryCount = 0;
  122. for(Entry<AbstractCanvasObject, Integer> entry : objectToId.entrySet()) {
  123. G.V[entryCount] = new Vertex(entry.getValue());
  124. entryCount++;
  125. }
  126. //Generate Sources Array
  127. int sourceCount = 0;
  128. G.S = new Vertex[sourcesList.size()];
  129. for(int source : sourcesList) {
  130. G.S[sourceCount] = new Vertex(source);
  131. sourceCount++;
  132. }
  133. return G;
  134. }
  135. // Example Test
  136. public static void main(String[] args){
  137. Graph G = new Graph();
  138. G.V = new Vertex[4];
  139. for(int i=0;i<G.V.length;i++)
  140. {
  141. G.V[i] = new Vertex(i);
  142. }
  143. G.E = new Edge[4];
  144. G.E[0] = new Edge(0, 1, 1);
  145. G.E[1] = new Edge(1, 2, 1);
  146. G.E[2] = new Edge(2, 3, 1);
  147. G.E[3] = new Edge(3, 0, 1);
  148. G.S = new Vertex[4];
  149. G.S[0] = new Vertex(0);
  150. G.S[1] = new Vertex(1);
  151. G.S[2] = new Vertex(2);
  152. G.S[3] = new Vertex(3);
  153. System.out.println(G);
  154. System.out.println("minimumCut: " + minimumCut(G.V, G.E));
  155. System.out.println("AvgShortestDistance " + averageShortestDistance(G));
  156. System.out.println("DisjointPath " + averageEdgeDisjointPathProblem(G));
  157. }
  158. static int[][] generateDisjointWeightMatrix(Vertex[] V, Edge[] E){
  159. int[][] L = new int[V.length][V.length];
  160. for(int i = 0; i < E.length; i++) {
  161. L[E[i].idA][E[i].idB] = 1;
  162. L[E[i].idB][E[i].idA] = 1;
  163. }
  164. return L;
  165. }
  166. /** find the average s_t disjoint paths between all pairs of s and t **/
  167. static double averageEdgeDisjointPathProblem(Graph G) {
  168. //This matrix indicates if a Edge is existent between two vertices
  169. int[][] L = generateDisjointWeightMatrix(G.V, G.E);
  170. double disjointPathSum = 0.0;
  171. for(int s = 0; s < G.S.length; s++) {
  172. for(int t = s; t < G.S.length; t++) {
  173. disjointPathSum += s_t_EdgeDisjointPath(G.S[s].id, G.S[t].id, L);
  174. }
  175. }
  176. //Returns the Average
  177. return disjointPathSum / ((G.S.length * (G.S.length - 1)) / 2);
  178. }
  179. /** find the amount of s_t disjoint paths between s and t **/
  180. private static double s_t_EdgeDisjointPath(int s, int t, int[][] L_input) {
  181. if(s == t) return 0;
  182. //Make Copy of L
  183. int [][] L = makeCopyOfMatrix(L_input);
  184. double foundPaths = 0;
  185. //RepeatBreathFirst search till no path is found
  186. boolean b_foundpath = true;
  187. while(b_foundpath) {
  188. b_foundpath = breathFirstSearch(s,t,L);
  189. if(b_foundpath) {
  190. foundPaths++;
  191. }
  192. }
  193. return foundPaths;
  194. }
  195. /** execute one breathFirstSearch to find a path between s and t **/
  196. private static boolean breathFirstSearch(int s, int t, int[][] L) {
  197. //Visited Notes
  198. Set<Integer> visitedNotes = new HashSet<Integer>();
  199. //Queue to check which node to search next
  200. LinkedList<Integer> queue = new LinkedList<Integer>();
  201. //Map to traverse the path back when found a path
  202. HashMap<Integer,Integer> noteBeforeMap = new HashMap<Integer,Integer>();
  203. //Add starting Point
  204. queue.add(s);
  205. //Visit all neighbours of the next point in queue
  206. while(!queue.isEmpty()) {
  207. int id = queue.pollFirst();
  208. visitedNotes.add(id);
  209. //For all neighbors add to queue
  210. for(int i = 0; i < L[id].length; i++) {
  211. //Check if edge exist and not visited before
  212. if(L[id][i] != 0 && !visitedNotes.contains(i)) {
  213. queue.add(i);
  214. noteBeforeMap.putIfAbsent(i, id);
  215. //check if train is found
  216. if(i == t) {
  217. //update connectionMatrix l and remove the found path
  218. int actualID = t;
  219. while(actualID != s) {
  220. int nextID = noteBeforeMap.get(actualID);
  221. //remove edge
  222. L[nextID][actualID] = 0;
  223. L[actualID][nextID] = 0;
  224. actualID = nextID;
  225. }
  226. return true;
  227. }
  228. }
  229. }
  230. }
  231. //if last queue element is searched but t is not reachable
  232. return false;
  233. }
  234. /**
  235. * Makes a deep Copy of a Integer Matrix
  236. * @param l_input
  237. * @return
  238. */
  239. private static int[][] makeCopyOfMatrix(int[][] matrix) {
  240. int[][] copyMatrix = new int[matrix.length][matrix[0].length];
  241. for(int i = 0; i < matrix.length; i++) {
  242. for(int j = 0; j < matrix[0].length; j++) {
  243. copyMatrix[i][j] = matrix[i][j];
  244. }
  245. }
  246. return copyMatrix;
  247. }
  248. /**
  249. * Stoer Wagner Minimal Cut Algo
  250. * Source from
  251. * <a href="https://github.com/hunglvosu/algorithm/blob/master/algorithm/src/Stoer-Wagner.c">
  252. * https://github.com/hunglvosu/algorithm/blob/master/algorithm/src/Stoer-Wagner.c</a> <br>
  253. * in C formatted written in java
  254. * @param V Vertex Array
  255. * @param E Edge Array
  256. * @return
  257. */
  258. static int minimumCut(Vertex[] V, Edge[] E) {
  259. int[][] W = generateDisjointWeightMatrix(V, E);
  260. boolean[] Del = new boolean[V.length];
  261. int n = V.length; // the number of veritces
  262. int m = E.length;
  263. return StoerWagner(n, m, W, Del);
  264. }
  265. static int StoerWagner(int n, int m, int[][] W, boolean[] Del){
  266. int C = Integer.MAX_VALUE;
  267. for(int V = n; V > 1; V--){
  268. int cutValue = minCutPhase(V, W, Del, n, m);
  269. C = (C < cutValue ? C: cutValue);
  270. }
  271. return C;
  272. }
  273. static int minCutPhase(int V, int[][] W, boolean[] Del, int n, int m){
  274. int i = 0, j = 0;
  275. int[] s = new int[2];
  276. if(V == 2) {
  277. for( i = 0; i < n; i++){
  278. if(Del[i] == false){
  279. s[j] = i; j++;
  280. }
  281. }
  282. return W[s[0]][s[1]];
  283. }
  284. int[] L = new int[n];
  285. boolean[] T = new boolean[n];
  286. i = 1; // the number of vertices in the tree T
  287. j = 0;
  288. int v,u;
  289. while( i <= V){
  290. v = maxStickiness(T,L, Del, n);
  291. T[v] = true;
  292. for(u = 0; u < n; u++){
  293. if(W[v][u] != 0 && Del[u] == false && T[u] == false){
  294. L[u] = L[u] + W[u][v];
  295. }
  296. }
  297. if( i >= V-1){
  298. s[j] = v; j++;
  299. }
  300. i++;
  301. }
  302. merge(s[0], s[1], n, W, Del);
  303. return L[s[1]];
  304. }
  305. static int maxStickiness(boolean[] T, int[] L, boolean[] Del, int n){
  306. int i = 0;
  307. int v = 0;
  308. int max = 0;
  309. for(i = 0; i < n; i++){
  310. if(Del[i] == false && T[i] == false && max < L[i]){
  311. v = i;
  312. max = L[i];
  313. }
  314. }
  315. return v;
  316. }
  317. static void merge(int s, int t, int n, int[][] W, boolean[] Del){
  318. int v = 0;
  319. for(v = 0; v < n; v++){
  320. if(Del[v] == false && v != s && v!= t){
  321. W[s][v] = W[s][v] + W[v][t];
  322. W[v][s] = W[s][v];
  323. }
  324. }
  325. Del[t] = true;
  326. }
  327. static double[][] basicAllPairsShortestPath(Vertex[] V, Edge[] E){
  328. double[][] L = generateWeightMatrix(V, E);
  329. double[][] D = generateDistanceMatrix(V);
  330. boolean[] flag = generateFlagList(V);
  331. for(int i=0;i<V.length;i++) {
  332. modifiedDikstra(V[i].id, L, D, flag);
  333. }
  334. return D;
  335. }
  336. static double averageShortestDistance(Graph G) {
  337. if(G.V.length <= 1) return 0.0;
  338. double[][] D = basicAllPairsShortestPath(G.V, G.E);
  339. double sum = 0.0;
  340. for(int s = 0; s < G.S.length; s++) {
  341. for(int t = s; t < G.S.length; t++) {
  342. sum += D[G.S[s].id][G.S[t].id];
  343. }
  344. }
  345. //Returns the Average
  346. return sum / ((G.S.length * (G.S.length - 1)) / 2);
  347. }
  348. /**
  349. * @return Updated Distance Matrix D and flag List
  350. */
  351. static void modifiedDikstra(int source, double[][] L, double[][] D, boolean[] flag) {
  352. D[source][source] = 0;
  353. LinkedList<Integer> visitedNotes = new LinkedList<Integer>();
  354. LinkedList<Integer> minPriorityQueue = new LinkedList<Integer>();
  355. minPriorityQueue.add(source);
  356. while(!minPriorityQueue.isEmpty()) {
  357. minPriorityQueue.sort((a,b) -> Double.compare(D[source][a], D[source][b]));
  358. int target = minPriorityQueue.pop();
  359. if(flag[source] == true) {
  360. for(int outgoingID = 0; outgoingID < L.length; outgoingID++) {
  361. if(D[source][target] + L[target][outgoingID] < D[source][outgoingID]) {
  362. D[source][outgoingID] = D[source][target] + L[target][outgoingID];
  363. }
  364. }
  365. }else {
  366. for(int outgoingID = 0; outgoingID < L.length; outgoingID++) {
  367. if(L[target][outgoingID] == Double.POSITIVE_INFINITY) continue;
  368. if(D[source][target] + L[target][outgoingID] < D[source][outgoingID]) {
  369. D[source][outgoingID] = D[source][target] + L[target][outgoingID];
  370. if(!visitedNotes.contains(outgoingID)) {
  371. minPriorityQueue.add(outgoingID);
  372. }
  373. }
  374. }
  375. }
  376. visitedNotes.add(target);
  377. }
  378. flag[source] = true;
  379. }
  380. static void printMatrix(int[][] matrix) {
  381. for(int i=0;i<matrix.length;i++)
  382. {
  383. for(int j=0;j<matrix.length;j++)
  384. {
  385. System.out.print(matrix[i][j] + " ");
  386. }
  387. System.out.println();
  388. }
  389. }
  390. static void printMatrix(double[][] matrix) {
  391. for(int i=0;i<matrix.length;i++)
  392. {
  393. for(int j=0;j<matrix.length;j++)
  394. {
  395. System.out.print(matrix[i][j] + " ");
  396. }
  397. System.out.println();
  398. }
  399. }
  400. static double[][] generateWeightMatrix(Vertex[] V, Edge[] E){
  401. double[][] L = new double[V.length][V.length];
  402. for(int i = 0; i < E.length; i++) {
  403. try {
  404. L[E[i].idA][E[i].idB] = E[i].weight;
  405. L[E[i].idB][E[i].idA] = E[i].weight;
  406. }catch(java.lang.NullPointerException e) {
  407. System.out.println("E[i].idA:" + E[i].idA + " E[i].idB:" + E[i].idB + " E[i].weight:" + E[i].weight);
  408. }
  409. }
  410. for(int i=0;i<L.length;i++)
  411. {
  412. for(int j=0;j<L.length;j++)
  413. {
  414. if(L[i][j]==0.0) L[i][j] = Double.POSITIVE_INFINITY;
  415. }
  416. }
  417. for(int i=0;i<L.length;i++)
  418. {
  419. L[i][i] = 0.0;
  420. }
  421. return L;
  422. }
  423. static double[][] generateDistanceMatrix(Vertex[] V) {
  424. double[][] D = new double[V.length][V.length];
  425. for(int i=0;i<D.length;i++)
  426. {
  427. for(int j=0;j<D.length;j++)
  428. {
  429. D[i][j] = Double.POSITIVE_INFINITY;
  430. }
  431. }
  432. return D;
  433. }
  434. private static boolean[] generateFlagList(Vertex[] V) {
  435. boolean[] flag = new boolean[V.length];
  436. return flag;
  437. }
  438. }