aboutsummaryrefslogtreecommitdiff
path: root/src/dk.biks.bachelorizer/dk/biks/bachelorizer/Graph.java
blob: f24264c144e463f0e4badc5764a4cedab3bf69f1 (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. /// @param g choices as weights in graph
  155. /// @return groups of disjoint choices as a graph
  156. public static AbstractGraph moduleGroups(
  157. final ArrayList<Set<Vertex>> sets, final AbstractGraph g
  158. ) {
  159. AbstractGraph h = new AdjListGraph();
  160. Map<Set<Vertex>, String> groupLabel = new HashMap<>();
  161. for (Set<Vertex> groupSet : sets) {
  162. // stringify each group of module selections
  163. String name = groupSet.stream()
  164. .map(Vertex::toString)
  165. // avoid differently sorted duplicates
  166. .sorted()
  167. // formatting of groups as vertices
  168. .collect(Collectors.joining(
  169. ", ", "{", "}"));
  170. // map group to name of group
  171. groupLabel.put(groupSet, name);
  172. }
  173. for (Set<Vertex> s: sets) {
  174. for (Set<Vertex> t: sets) {
  175. if (t == s) {
  176. continue;
  177. }
  178. // process each pair only once
  179. if (s.hashCode() > t.hashCode()) {
  180. continue;
  181. }
  182. // accumulate student count across set
  183. int sum = 0;
  184. for (Vertex v: s) {
  185. // students with this choice
  186. for (Vertex w: t) {
  187. Integer weight =
  188. g.getWeight(v, w);
  189. if (weight != null) {
  190. sum += weight;
  191. }
  192. }
  193. }
  194. // ensure h is treated as undirected
  195. h.insertEdge(
  196. groupLabel.get(s),
  197. groupLabel.get(t),
  198. sum);
  199. h.insertEdge(
  200. groupLabel.get(t),
  201. groupLabel.get(s),
  202. sum);
  203. }
  204. }
  205. return h;
  206. }
  207. /// loop through random combinations of sets of modules
  208. ///
  209. /// @param g sets of disjoint choices as a graph
  210. /// @return best path among many random ones
  211. public static int goodSolution(final AbstractGraph g) {
  212. // number higher than total students
  213. int bestPathCost = Integer.MAX_VALUE;
  214. for (int i = 0; i < DEMO_ITERATIONS; i++) {
  215. int cost = solution(g);
  216. if (cost < bestPathCost) {
  217. // store shortest path
  218. bestPathCost = cost;
  219. }
  220. }
  221. return bestPathCost;
  222. }
  223. /// finds lengh of random path through disjoint module choices
  224. ///
  225. /// @param g sets of disjoint choices as a graph
  226. /// @return weight of final random path
  227. private static int solution(final AbstractGraph g) {
  228. List<Vertex> path = new ArrayList<>(g.vertices());
  229. // order of list contents becomes path order
  230. Collections.shuffle(path);
  231. int cost = 0;
  232. for (int i = 0; i < path.size() - 1; i++) {
  233. cost += g.getWeight(path.get(i), path.get(i + 1));
  234. }
  235. return cost;
  236. }
  237. /// Demo function to solve assignment
  238. public void demo() {
  239. System.out.println("\n\nGraph of choices constructed:");
  240. GraphAlgorithms.printGraph(g);
  241. // ensure the graph is connected
  242. assertConnected();
  243. System.out.println(
  244. "\n\nGraph is connected"
  245. + " (otherwise an exception was thrown)");
  246. // collect disjoint choice sets
  247. ArrayList<Set<Vertex>> s = disjoint();
  248. System.out.printf(
  249. "\n\n%d disjoint choice sets collected:\n",
  250. s.size());
  251. for (Set<Vertex> verticeSet: s) {
  252. System.out.print(
  253. "set(" + verticeSet.size() + "):");
  254. for (Vertex v: GraphAlgorithms.sortVertex(
  255. verticeSet)
  256. ) {
  257. System.out.print(" " + v.toString());
  258. }
  259. System.out.println();
  260. }
  261. // construct graph of disjoint choices
  262. AbstractGraph h = moduleGroups(s, g);
  263. System.out.println(
  264. "\n\nGraph of disjoint choices constructed:");
  265. GraphAlgorithms.printGraph(h);
  266. // find path through disjoint choice graph
  267. System.out.print(
  268. "\n\nSolution with disjoint choices found: ");
  269. System.out.println(
  270. goodSolution(h));
  271. }
  272. }