aboutsummaryrefslogtreecommitdiff
path: root/src/dk.biks.bachelorizer/dk/biks/bachelorizer/Graph.java
blob: 2d36d14da7e936fcea545bc0e7dca8261d808b6a (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. /// @return list of disjoint sets
  103. public ArrayList<Set<Vertex>> disjoint() {
  104. // get all subject modules
  105. //
  106. // TODO: optionally seed this, to enable ranking control
  107. List<Vertex> modules = new ArrayList<>(g.vertices());
  108. Collections.shuffle(modules);
  109. return disjoint(modules);
  110. }
  111. /// groups of disjoint choices seeded by priority list of choices
  112. ///
  113. /// @param vip Ordered list of subject modules to prioritize
  114. /// @return List of sets of disjoint choices
  115. public ArrayList<Set<Vertex>> disjoint(final List<Vertex> vip) {
  116. ArrayList<Set<Vertex>> sets = new ArrayList<>();
  117. // track done subject modules as extendable set
  118. //
  119. // HashList used for efficient addition and lookup
  120. Set<Vertex> done = new HashSet<>();
  121. // convert module list to a set
  122. //
  123. // defined once outside loop as a slight optimization
  124. Set<Vertex> all_set = new HashSet<>(vip);
  125. // iterate over subject modules
  126. for (Vertex current : vip) {
  127. if (done.contains(current)) {
  128. continue;
  129. }
  130. // add set of current and any unconnected modules
  131. Set<Vertex> isolated = new HashSet<>();
  132. isolated.add(current);
  133. for (Vertex compared: vip) {
  134. // skip if already done
  135. if (compared.equals(current)
  136. || done.contains(compared)) {
  137. continue;
  138. }
  139. if (isolated.stream().allMatch(u ->
  140. g.getWeight(u,compared) == null)
  141. ) {
  142. isolated.add(compared);
  143. }
  144. }
  145. // add as set and omit from future iterations
  146. sets.add(isolated);
  147. done.addAll(isolated);
  148. }
  149. return sets;
  150. }
  151. /// sum of students' selections as a graph
  152. ///
  153. /// @param sets list of disjoint choices
  154. /// @return groups of disjoint choices as a graph
  155. private AbstractGraph moduleGroups(
  156. final ArrayList<Set<Vertex>> sets
  157. ) {
  158. AbstractGraph h = new AdjListGraph();
  159. Map<Set<Vertex>, String> groupLabel = new HashMap<>();
  160. for (Set<Vertex> groupSet : sets) {
  161. // stringify each group of module selections
  162. String name = groupSet.stream()
  163. .map(Vertex::toString)
  164. // avoid differently sorted duplicates
  165. .sorted()
  166. // formatting of groups as vertices
  167. .collect(Collectors.joining(
  168. ", ", "{", "}"));
  169. // map group to name of group
  170. groupLabel.put(groupSet, name);
  171. }
  172. for (Set<Vertex> s: sets) {
  173. for (Set<Vertex> t: sets) {
  174. if (t == s) {
  175. continue;
  176. }
  177. // process each pair only once
  178. if (s.hashCode() > t.hashCode()) {
  179. continue;
  180. }
  181. // accumulate student count across set
  182. int sum = 0;
  183. for (Vertex v: s) {
  184. // students with this choice
  185. for (Vertex w: t) {
  186. Integer weight =
  187. g.getWeight(v, w);
  188. if (weight != null) {
  189. sum += weight;
  190. }
  191. }
  192. }
  193. // ensure h is treated as undirected
  194. h.insertEdge(
  195. groupLabel.get(s),
  196. groupLabel.get(t),
  197. sum);
  198. h.insertEdge(
  199. groupLabel.get(t),
  200. groupLabel.get(s),
  201. sum);
  202. }
  203. }
  204. return h;
  205. }
  206. /// loop through random combinations of sets of modules
  207. ///
  208. /// @param g sets of disjoint choices as a graph
  209. /// @return best path among many random ones
  210. private static long[] solveManyTimes(final AbstractGraph g) {
  211. // number higher than total students
  212. long[] bestSolution = solve(g);
  213. for (int i = 1; i < DEMO_ITERATIONS; i++) {
  214. long[] solution = solve(g);
  215. if (solution[0] < bestSolution[0]) {
  216. // store shortest path
  217. bestSolution = solution;
  218. }
  219. }
  220. return bestSolution;
  221. }
  222. /// find total weight of random path through disjoint choice sets
  223. ///
  224. /// @param g sets of disjoint choices as a graph
  225. /// @return total weight of random path
  226. private static long[] solve(final AbstractGraph g) {
  227. /// parameters for solution
  228. long[] solution = new long[] {0};
  229. List<Vertex> path = new ArrayList<>(g.vertices());
  230. // order of list contents becomes path order
  231. Collections.shuffle(path);
  232. for (int i = 0; i < path.size() - 1; i++) {
  233. solution[0] += g.getWeight(
  234. path.get(i), path.get(i + 1));
  235. }
  236. return solution;
  237. }
  238. /// Demo function to solve assignment
  239. private void demo() {
  240. System.out.println("\n\nGraph of choices constructed:");
  241. GraphAlgorithms.printGraph(g);
  242. // ensure the graph is connected
  243. assertConnected();
  244. System.out.println(
  245. "\n\nGraph is connected"
  246. + " (otherwise an exception was thrown)");
  247. // collect disjoint choice sets
  248. ArrayList<Set<Vertex>> s = disjoint();
  249. System.out.printf(
  250. "\n\n%d disjoint choice sets collected:\n",
  251. s.size());
  252. for (Set<Vertex> verticeSet: s) {
  253. System.out.print(
  254. "set(" + verticeSet.size() + "):");
  255. for (Vertex v: GraphAlgorithms.sortVertex(
  256. verticeSet)
  257. ) {
  258. System.out.print(" " + v.toString());
  259. }
  260. System.out.println();
  261. }
  262. // construct graph of disjoint choices
  263. AbstractGraph h = moduleGroups(s);
  264. System.out.println(
  265. "\n\nGraph of disjoint choices constructed:");
  266. GraphAlgorithms.printGraph(h);
  267. // find path through disjoint choice graph
  268. System.out.print(
  269. "\n\nSolution with disjoint choices found: ");
  270. System.out.println(
  271. solveManyTimes(h)[0]);
  272. }
  273. }