GraphMetrics.java 12 KB

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