GraphMetrics.java 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. package holeg.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.logging.Logger;
  9. import holeg.model.AbstractCanvasObject;
  10. import holeg.model.Model;
  11. import java.util.Set;
  12. //TODO(Tom2022-01-13) Fix GraphMetrics
  13. public class GraphMetrics {
  14. private static final Logger log = Logger.getLogger(GraphMetrics.class.getName());
  15. public static class Vertex{
  16. public int id = 0;
  17. public Vertex(int id){
  18. this.id = id;
  19. }
  20. public String toString() {
  21. return "" + 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. public String toString() {
  39. String vList = "V" + Arrays.toString(V);
  40. String sList = "S" + Arrays.toString(S);
  41. return vList + ", " + sList;
  42. }
  43. }
  44. /**
  45. * Convert a DecoratedNetwork to a Graph
  46. * @return a equivalent Graph to the DecoratedNetwork
  47. */
  48. public static Graph convertDecoratedNetworkToGraph(Model model) {
  49. Graph G = new Graph();
  50. HashMap<AbstractCanvasObject, Integer> objectToId = new HashMap<>();
  51. List<Integer> sourcesList = new ArrayList<Integer>();
  52. int count = 0;
  53. // for(Consumer con: net.getConsumerList()) {
  54. // objectToId.put(con.getModel(), count);
  55. // sourcesList.add(count);
  56. // count++;
  57. // }
  58. // for(Consumer con: net.getConsumerSelfSuppliedList()) {
  59. // objectToId.put(con.getModel(), count);
  60. // sourcesList.add(count);
  61. // count++;
  62. // }
  63. // for(Passiv pas: net.getPassivNoEnergyList()) {
  64. // objectToId.put(pas.getModel(), count);
  65. // sourcesList.add(count);
  66. // count++;
  67. // }
  68. // for(Supplier sup: net.getSupplierList()) {
  69. // objectToId.put(sup.getModel(), count);
  70. // sourcesList.add(count);
  71. // count++;
  72. // }
  73. //
  74. //Generate EdgeList
  75. // List<Edge> edgeList = new ArrayList<Edge>();
  76. // for(holeg.model.Edge cable : net.getDecoratedCableList()){
  77. //
  78. // AbstractCanvasObject objectA = cable.getA();
  79. // AbstractCanvasObject objectB = cable.getB();
  80. // if(objectA == null) {
  81. // log.warning("Edge: " + cable + "objectA == null");
  82. // continue;
  83. // }
  84. // if(objectB == null) {
  85. // log.warning("Edge: " + cable + "objectB == null");
  86. // continue;
  87. // }
  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. //
  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.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. log.info(G.toString());
  155. log.info("minimumCut: " + minimumCut(G.V, G.E));
  156. log.info("AvgShortestDistance " + averageShortestDistance(G));
  157. log.info("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. * @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 double[][] generateWeightMatrix(Vertex[] V, Edge[] E){
  381. double[][] L = new double[V.length][V.length];
  382. for(int i = 0; i < E.length; i++) {
  383. try {
  384. L[E[i].idA][E[i].idB] = E[i].weight;
  385. L[E[i].idB][E[i].idA] = E[i].weight;
  386. }catch(java.lang.NullPointerException e) {
  387. log.info("E[i].idA:" + E[i].idA + " E[i].idB:" + E[i].idB + " E[i].weight:" + E[i].weight);
  388. }
  389. }
  390. for(int i=0;i<L.length;i++)
  391. {
  392. for(int j=0;j<L.length;j++)
  393. {
  394. if(L[i][j]==0.0) L[i][j] = Double.POSITIVE_INFINITY;
  395. }
  396. }
  397. for(int i=0;i<L.length;i++)
  398. {
  399. L[i][i] = 0.0;
  400. }
  401. return L;
  402. }
  403. static double[][] generateDistanceMatrix(Vertex[] V) {
  404. double[][] D = new double[V.length][V.length];
  405. for(int i=0;i<D.length;i++)
  406. {
  407. for(int j=0;j<D.length;j++)
  408. {
  409. D[i][j] = Double.POSITIVE_INFINITY;
  410. }
  411. }
  412. return D;
  413. }
  414. private static boolean[] generateFlagList(Vertex[] V) {
  415. boolean[] flag = new boolean[V.length];
  416. return flag;
  417. }
  418. }