GraphMetrics.java 13 KB

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