aboutsummaryrefslogtreecommitdiff
path: root/src/dk.biks.bachelorizer/dk/biks/bachelorizer/Graph.java
blob: a7689f8ed39ee92d5720e6c510914ddddc341a1e (plain)
  1. // SPDX-FileCopyrightText: 2025 <Ian Valentin Christensen stud-ianc@ruc.dk>
  2. // SPDX-FileCopyrightText: 2025 Jonas Smedegaard <dr@jones.dk>
  3. // SPDX-License-Identifier: GPL-3.0-or-later
  4. package dk.biks.bachelorizer;
  5. import java.util.ArrayList;
  6. import java.util.Collection;
  7. import java.util.Collections;
  8. import java.util.HashSet;
  9. import java.util.HashMap;
  10. import java.util.Map;
  11. import java.util.List;
  12. import java.util.Set;
  13. import java.util.stream.Collectors;
  14. import com.example.portfolio3.AdjListGraph;
  15. import com.example.portfolio3.AbstractGraph;
  16. import com.example.portfolio3.GraphAlgorithms;
  17. import com.example.portfolio3.MatrixGraph;
  18. import com.example.portfolio3.Vertex;
  19. /// Bachelorizer - database model
  20. ///
  21. /// Slurps and parses data from upstream-provided comma-separated file.
  22. ///
  23. /// @version 0.0.1
  24. /// @see <https://moodle.ruc.dk/mod/assign/view.php?id=523186>
  25. public final class Graph extends Storage {
  26. /// amount of iterations in demo
  27. private static final int DEMO_ITERATIONS = 1000000;
  28. /// path to source file for graph
  29. private String path = "combi.txt";
  30. /// data about combinations as a Graph
  31. private AbstractGraph g;
  32. /// Default constructor
  33. // to silence javadoc
  34. private Graph() {}
  35. /// constructor with custom file source
  36. ///
  37. /// @param path path to source file for graph
  38. private Graph(String path) {
  39. this.path = path;
  40. }
  41. /// JVM entry point
  42. ///
  43. /// @param args command-line arguments
  44. public static void main(final String[] args) {
  45. Graph g;
  46. // first argument, if provided, is the data file path;
  47. // else use upstream named file in current directory.
  48. g = (args.length > 0)
  49. ? new Graph(args[0])
  50. : new Graph();
  51. g.initialize();
  52. g.demo();
  53. }
  54. /// load graph from file
  55. void initialize() {
  56. // read into temporary graph to resolve vertice count
  57. //
  58. // use Adjacency List Representation:
  59. // * cheap to bootstrap (done once)
  60. // * simple to count vertices (done once): O(1)
  61. AbstractGraph _g = new AdjListGraph();
  62. GraphAlgorithms.readGraph(_g, path);
  63. Integer _vertice_count = _g.vertices().size();
  64. // read into final graph
  65. //
  66. // use Adjacency Matrix Representation:
  67. // * expensive to bootstrap (done once)
  68. // * simple to add edges but needs vertice count
  69. // * simple to get edges (done repeatedly): O(1)
  70. //
  71. // TODO: avoid reading and parsing file twice
  72. g = new MatrixGraph(_vertice_count);
  73. GraphAlgorithms.readGraph(g, path);
  74. }
  75. /// check that a graph is connected
  76. ///
  77. /// If check fails, throw an unchecked exception,
  78. /// since it occurs at runtime and is unrecoverable.
  79. ///
  80. /// Time complexity of the operation is O(n²)
  81. /// where n is the amount of vertices,
  82. /// since visitDepthFirst() recurses out-edges of all vertices.
  83. ///
  84. /// @throws IllegalArgumentException
  85. /// https://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html
  86. public void assertConnected() {
  87. // collect all vertices in the graph
  88. Collection<Vertex> c = g.vertices();
  89. // pick a random vertice in the graph
  90. Vertex v = g.vertices().iterator().next();
  91. // collect the set of visitable vertices
  92. Set<Vertex> visited = GraphAlgorithms.visitDepthFirst(
  93. g, v);
  94. // throw exception if not all vertices were visited
  95. if (visited.size() != c.size()) {
  96. throw new IllegalArgumentException(
  97. "graph is not connected");
  98. }
  99. }
  100. /// sets of disjoint choices
  101. ///
  102. /// @param g Graph to inspect
  103. /// @return list of disjoint sets
  104. public static ArrayList<Set<Vertex>> disjoint(
  105. final AbstractGraph g
  106. ) {
  107. // get all subject modules
  108. //
  109. // TODO: optionally seed this, to enable ranking control
  110. List<Vertex> modules = new ArrayList<>(g.vertices());
  111. Collections.shuffle(modules);
  112. return disjoint(g, modules);
  113. }
  114. /// groups of disjoint choices seeded by priority list of choices
  115. ///
  116. /// @param g Graph to inspect
  117. /// @param vip Ordered list of subject modules to prioritize
  118. /// @return List of sets of disjoint choices
  119. public static ArrayList<Set<Vertex>> disjoint(
  120. final AbstractGraph g, final List<Vertex> vip
  121. ) {
  122. ArrayList<Set<Vertex>> sets = new ArrayList<>();
  123. // track done subject modules as extendable set
  124. //
  125. // HashList used for efficient addition and lookup
  126. Set<Vertex> done = new HashSet<>();
  127. // convert module list to a set
  128. //
  129. // defined once outside loop as a slight optimization
  130. Set<Vertex> all_set = new HashSet<>(vip);
  131. // iterate over subject modules
  132. for (Vertex current : vip) {
  133. if (done.contains(current)) {
  134. continue;
  135. }
  136. // add set of current and any unconnected modules
  137. Set<Vertex> isolated = new HashSet<>();
  138. isolated.add(current);
  139. for (Vertex compared: vip) {
  140. // skip if already done
  141. if (compared.equals(current)
  142. || done.contains(compared)) {
  143. continue;
  144. }
  145. if (isolated.stream().allMatch(u ->
  146. g.getWeight(u,compared) == null)
  147. ) {
  148. isolated.add(compared);
  149. }
  150. }
  151. // add as set and omit from future iterations
  152. sets.add(isolated);
  153. done.addAll(isolated);
  154. }
  155. return sets;
  156. }
  157. /// sum of students' selections as a graph
  158. ///
  159. /// @param sets list of disjoint choices
  160. /// @param g choices as weights in graph
  161. /// @return groups of disjoint choices as a graph
  162. public static AbstractGraph moduleGroups(
  163. final ArrayList<Set<Vertex>> sets, final AbstractGraph g
  164. ) {
  165. AbstractGraph h = new AdjListGraph();
  166. Map<Set<Vertex>, String> groupLabel = new HashMap<>();
  167. for (Set<Vertex> groupSet : sets) {
  168. // stringify each group of module selections
  169. String name = groupSet.stream()
  170. .map(Vertex::toString)
  171. // avoid differently sorted duplicates
  172. .sorted()
  173. // formatting of groups as vertices
  174. .collect(Collectors.joining(
  175. ", ", "{", "}"));
  176. // map group to name of group
  177. groupLabel.put(groupSet, name);
  178. }
  179. for (Set<Vertex> s: sets) {
  180. for (Set<Vertex> t: sets) {
  181. if (t == s) {
  182. continue;
  183. }
  184. // process each pair only once
  185. if (s.hashCode() > t.hashCode()) {
  186. continue;
  187. }
  188. // accumulate student count across set
  189. int sum = 0;
  190. for (Vertex v: s) {
  191. // students with this choice
  192. for (Vertex w: t) {
  193. Integer weight =
  194. g.getWeight(v, w);
  195. if (weight != null) {
  196. sum += weight;
  197. }
  198. }
  199. }
  200. // ensure h is treated as undirected
  201. h.insertEdge(
  202. groupLabel.get(s),
  203. groupLabel.get(t),
  204. sum);
  205. h.insertEdge(
  206. groupLabel.get(t),
  207. groupLabel.get(s),
  208. sum);
  209. }
  210. }
  211. return h;
  212. }
  213. /// loop through random combinations of sets of modules
  214. ///
  215. /// @param g sets of disjoint choices as a graph
  216. /// @return best path among many random ones
  217. public static int goodSolution(final AbstractGraph g) {
  218. // number higher than total students
  219. int bestPathCost = Integer.MAX_VALUE;
  220. for (int i = 0; i < DEMO_ITERATIONS; i++) {
  221. int cost = solution(g);
  222. if (cost < bestPathCost) {
  223. // store shortest path
  224. bestPathCost = cost;
  225. }
  226. }
  227. return bestPathCost;
  228. }
  229. /// finds lengh of random path through disjoint module choices
  230. ///
  231. /// @param g sets of disjoint choices as a graph
  232. /// @return weight of final random path
  233. private static int solution(final AbstractGraph g) {
  234. List<Vertex> path = new ArrayList<>(g.vertices());
  235. // order of list contents becomes path order
  236. Collections.shuffle(path);
  237. int cost = 0;
  238. for (int i = 0; i < path.size() - 1; i++) {
  239. cost += g.getWeight(path.get(i), path.get(i + 1));
  240. }
  241. return cost;
  242. }
  243. /// Demo function to solve assignment
  244. public void demo() {
  245. System.out.println("\n\nGraph of choices constructed:");
  246. GraphAlgorithms.printGraph(g);
  247. // ensure the graph is connected
  248. assertConnected();
  249. System.out.println(
  250. "\n\nGraph is connected"
  251. + " (otherwise an exception was thrown)");
  252. // collect disjoint choice sets
  253. ArrayList<Set<Vertex>> s = disjoint(g);
  254. System.out.printf(
  255. "\n\n%d disjoint choice sets collected:\n",
  256. s.size());
  257. for (Set<Vertex> verticeSet: s) {
  258. System.out.print(
  259. "set(" + verticeSet.size() + "):");
  260. for (Vertex v: GraphAlgorithms.sortVertex(
  261. verticeSet)
  262. ) {
  263. System.out.print(" " + v.toString());
  264. }
  265. System.out.println();
  266. }
  267. // construct graph of disjoint choices
  268. AbstractGraph h = moduleGroups(s, g);
  269. System.out.println(
  270. "\n\nGraph of disjoint choices constructed:");
  271. GraphAlgorithms.printGraph(h);
  272. // find path through disjoint choice graph
  273. System.out.print(
  274. "\n\nSolution with disjoint choices found: ");
  275. System.out.println(
  276. goodSolution(h));
  277. }
  278. }