GraphMetrics.java 13 KB

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