GraphMetrics.java 12 KB

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