GraphMetrics.java 13 KB

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