GraphMetrics.java 13 KB

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