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