GraphMetrics.java 13 KB

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