001package org.cpsolver.studentsct; 002 003import java.io.BufferedReader; 004import java.io.File; 005import java.io.FileInputStream; 006import java.io.FileOutputStream; 007import java.io.FileReader; 008import java.io.FileWriter; 009import java.io.IOException; 010import java.io.PrintWriter; 011import java.text.DecimalFormat; 012import java.util.ArrayList; 013import java.util.Collection; 014import java.util.Collections; 015import java.util.Comparator; 016import java.util.Date; 017import java.util.HashSet; 018import java.util.HashMap; 019import java.util.Iterator; 020import java.util.List; 021import java.util.Map; 022import java.util.Set; 023import java.util.StringTokenizer; 024import java.util.TreeSet; 025 026import org.apache.logging.log4j.Level; 027import org.apache.logging.log4j.core.config.Configurator; 028import org.cpsolver.ifs.assignment.Assignment; 029import org.cpsolver.ifs.assignment.DefaultSingleAssignment; 030import org.cpsolver.ifs.assignment.EmptyAssignment; 031import org.cpsolver.ifs.heuristics.BacktrackNeighbourSelection; 032import org.cpsolver.ifs.model.Neighbour; 033import org.cpsolver.ifs.solution.Solution; 034import org.cpsolver.ifs.solution.SolutionListener; 035import org.cpsolver.ifs.solver.ParallelSolver; 036import org.cpsolver.ifs.solver.Solver; 037import org.cpsolver.ifs.solver.SolverListener; 038import org.cpsolver.ifs.util.DataProperties; 039import org.cpsolver.ifs.util.JProf; 040import org.cpsolver.ifs.util.Progress; 041import org.cpsolver.ifs.util.ProgressWriter; 042import org.cpsolver.ifs.util.ToolBox; 043import org.cpsolver.studentsct.check.CourseLimitCheck; 044import org.cpsolver.studentsct.check.InevitableStudentConflicts; 045import org.cpsolver.studentsct.check.OverlapCheck; 046import org.cpsolver.studentsct.check.SectionLimitCheck; 047import org.cpsolver.studentsct.extension.DistanceConflict; 048import org.cpsolver.studentsct.extension.TimeOverlapsCounter; 049import org.cpsolver.studentsct.filter.CombinedStudentFilter; 050import org.cpsolver.studentsct.filter.FreshmanStudentFilter; 051import org.cpsolver.studentsct.filter.RandomStudentFilter; 052import org.cpsolver.studentsct.filter.ReverseStudentFilter; 053import org.cpsolver.studentsct.filter.StudentFilter; 054import org.cpsolver.studentsct.heuristics.StudentSctNeighbourSelection; 055import org.cpsolver.studentsct.heuristics.selection.BranchBoundSelection; 056import org.cpsolver.studentsct.heuristics.selection.OnlineSelection; 057import org.cpsolver.studentsct.heuristics.selection.SwapStudentSelection; 058import org.cpsolver.studentsct.heuristics.selection.BranchBoundSelection.BranchBoundNeighbour; 059import org.cpsolver.studentsct.heuristics.studentord.StudentOrder; 060import org.cpsolver.studentsct.heuristics.studentord.StudentRandomOrder; 061import org.cpsolver.studentsct.model.AreaClassificationMajor; 062import org.cpsolver.studentsct.model.Course; 063import org.cpsolver.studentsct.model.CourseRequest; 064import org.cpsolver.studentsct.model.Enrollment; 065import org.cpsolver.studentsct.model.Offering; 066import org.cpsolver.studentsct.model.Request; 067import org.cpsolver.studentsct.model.Student; 068import org.cpsolver.studentsct.report.CourseConflictTable; 069import org.cpsolver.studentsct.report.DistanceConflictTable; 070import org.cpsolver.studentsct.report.RequestGroupTable; 071import org.cpsolver.studentsct.report.RequestPriorityTable; 072import org.cpsolver.studentsct.report.SectionConflictTable; 073import org.cpsolver.studentsct.report.SolutionStatsReport; 074import org.cpsolver.studentsct.report.TableauReport; 075import org.cpsolver.studentsct.report.TimeOverlapConflictTable; 076import org.cpsolver.studentsct.report.UnbalancedSectionsTable; 077import org.dom4j.Document; 078import org.dom4j.DocumentHelper; 079import org.dom4j.Element; 080import org.dom4j.io.OutputFormat; 081import org.dom4j.io.SAXReader; 082import org.dom4j.io.XMLWriter; 083 084/** 085 * A main class for running of the student sectioning solver from command line. <br> 086 * <br> 087 * Usage:<br> 088 * java -Xmx1024m -jar studentsct-1.1.jar config.properties [input_file] 089 * [output_folder] [batch|online|simple]<br> 090 * <br> 091 * Modes:<br> 092 * batch ... batch sectioning mode (default mode -- IFS solver with 093 * {@link StudentSctNeighbourSelection} is used)<br> 094 * online ... online sectioning mode (students are sectioned one by 095 * one, sectioning info (expected/held space) is used)<br> 096 * simple ... simple sectioning mode (students are sectioned one by 097 * one, sectioning info is not used)<br> 098 * See http://www.unitime.org for example configuration files and benchmark data 099 * sets.<br> 100 * <br> 101 * 102 * The test does the following steps: 103 * <ul> 104 * <li>Provided property file is loaded (see {@link DataProperties}). 105 * <li>Output folder is created (General.Output property) and logging is setup 106 * (using log4j). 107 * <li>Input data are loaded from the given XML file (calling 108 * {@link StudentSectioningXMLLoader#load()}). 109 * <li>Solver is executed (see {@link Solver}). 110 * <li>Resultant solution is saved to an XML file (calling 111 * {@link StudentSectioningXMLSaver#save()}. 112 * </ul> 113 * Also, a log and some reports (e.g., {@link CourseConflictTable} and 114 * {@link DistanceConflictTable}) are created in the output folder. 115 * 116 * <br> 117 * <br> 118 * Parameters: 119 * <table border='1'><caption>Related Solver Parameters</caption> 120 * <tr> 121 * <th>Parameter</th> 122 * <th>Type</th> 123 * <th>Comment</th> 124 * </tr> 125 * <tr> 126 * <td>Test.LastLikeCourseDemands</td> 127 * <td>{@link String}</td> 128 * <td>Load last-like course demands from the given XML file (in the format that 129 * is being used for last like course demand table in the timetabling 130 * application)</td> 131 * </tr> 132 * <tr> 133 * <td>Test.StudentInfos</td> 134 * <td>{@link String}</td> 135 * <td>Load last-like course demands from the given XML file (in the format that 136 * is being used for last like course demand table in the timetabling 137 * application)</td> 138 * </tr> 139 * <tr> 140 * <td>Test.CrsReq</td> 141 * <td>{@link String}</td> 142 * <td>Load student requests from the given semi-colon separated list files (in 143 * the format that is being used by the old MSF system)</td> 144 * </tr> 145 * <tr> 146 * <td>Test.EtrChk</td> 147 * <td>{@link String}</td> 148 * <td>Load student information (academic area, classification, major, minor) 149 * from the given semi-colon separated list files (in the format that is being 150 * used by the old MSF system)</td> 151 * </tr> 152 * <tr> 153 * <td>Sectioning.UseStudentPreferencePenalties</td> 154 * <td>{@link Boolean}</td> 155 * <td>If true, {@link StudentPreferencePenalties} are used (applicable only for 156 * online sectioning)</td> 157 * </tr> 158 * <tr> 159 * <td>Test.StudentOrder</td> 160 * <td>{@link String}</td> 161 * <td>A class that is used for ordering of students (must be an interface of 162 * {@link StudentOrder}, default is {@link StudentRandomOrder}, not applicable 163 * only for batch sectioning)</td> 164 * </tr> 165 * <tr> 166 * <td>Test.CombineStudents</td> 167 * <td>{@link File}</td> 168 * <td>If provided, students are combined from the input file (last-like 169 * students) and the provided file (real students). Real non-freshmen students 170 * are taken from real data, last-like data are loaded on top of the real data 171 * (all students, but weighted to occupy only the remaining space).</td> 172 * </tr> 173 * <tr> 174 * <td>Test.CombineStudentsLastLike</td> 175 * <td>{@link File}</td> 176 * <td>If provided (together with Test.CombineStudents), students are combined 177 * from the this file (last-like students) and Test.CombineStudents file (real 178 * students). Real non-freshmen students are taken from real data, last-like 179 * data are loaded on top of the real data (all students, but weighted to occupy 180 * only the remaining space).</td> 181 * </tr> 182 * <tr> 183 * <td>Test.CombineAcceptProb</td> 184 * <td>{@link Double}</td> 185 * <td>Used in combining students, probability of a non-freshmen real student to 186 * be taken into the combined file (default is 1.0 -- all real non-freshmen 187 * students are taken).</td> 188 * </tr> 189 * <tr> 190 * <td>Test.FixPriorities</td> 191 * <td>{@link Boolean}</td> 192 * <td>If true, course/free time request priorities are corrected (to go from 193 * zero, without holes or duplicates).</td> 194 * </tr> 195 * <tr> 196 * <td>Test.ExtraStudents</td> 197 * <td>{@link File}</td> 198 * <td>If provided, students are loaded from the given file on top of the 199 * students loaded from the ordinary input file (students with the same id are 200 * skipped).</td> 201 * </tr> 202 * </table> 203 * <br> 204 * <br> 205 * 206 * @author Tomáš Müller 207 * @version StudentSct 1.3 (Student Sectioning)<br> 208 * Copyright (C) 2007 - 2014 Tomáš Müller<br> 209 * <a href="mailto:muller@unitime.org">muller@unitime.org</a><br> 210 * <a href="http://muller.unitime.org">http://muller.unitime.org</a><br> 211 * <br> 212 * This library is free software; you can redistribute it and/or modify 213 * it under the terms of the GNU Lesser General Public License as 214 * published by the Free Software Foundation; either version 3 of the 215 * License, or (at your option) any later version. <br> 216 * <br> 217 * This library is distributed in the hope that it will be useful, but 218 * WITHOUT ANY WARRANTY; without even the implied warranty of 219 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 220 * Lesser General Public License for more details. <br> 221 * <br> 222 * You should have received a copy of the GNU Lesser General Public 223 * License along with this library; if not see 224 * <a href='http://www.gnu.org/licenses/'>http://www.gnu.org/licenses/</a>. 225 */ 226 227public class Test { 228 private static org.apache.logging.log4j.Logger sLog = org.apache.logging.log4j.LogManager.getLogger(Test.class); 229 private static java.text.SimpleDateFormat sDateFormat = new java.text.SimpleDateFormat("yyMMdd_HHmmss", 230 java.util.Locale.US); 231 private static DecimalFormat sDF = new DecimalFormat("0.000"); 232 233 /** Load student sectioning model 234 * @param cfg solver configuration 235 * @return loaded solution 236 **/ 237 public static Solution<Request, Enrollment> load(DataProperties cfg) { 238 StudentSectioningModel model = null; 239 Assignment<Request, Enrollment> assignment = null; 240 try { 241 if (cfg.getProperty("Test.CombineStudents") == null) { 242 model = new StudentSectioningModel(cfg); 243 assignment = new DefaultSingleAssignment<Request, Enrollment>(); 244 new StudentSectioningXMLLoader(model, assignment).load(); 245 } else { 246 Solution<Request, Enrollment> solution = combineStudents(cfg, 247 new File(cfg.getProperty("Test.CombineStudentsLastLike", cfg.getProperty("General.Input", "." + File.separator + "solution.xml"))), 248 new File(cfg.getProperty("Test.CombineStudents"))); 249 model = (StudentSectioningModel)solution.getModel(); 250 assignment = solution.getAssignment(); 251 } 252 if (cfg.getProperty("Test.ExtraStudents") != null) { 253 StudentSectioningXMLLoader extra = new StudentSectioningXMLLoader(model, assignment); 254 extra.setInputFile(new File(cfg.getProperty("Test.ExtraStudents"))); 255 extra.setLoadOfferings(false); 256 extra.setLoadStudents(true); 257 extra.setStudentFilter(new ExtraStudentFilter(model)); 258 extra.load(); 259 } 260 if (cfg.getProperty("Test.LastLikeCourseDemands") != null) 261 loadLastLikeCourseDemandsXml(model, new File(cfg.getProperty("Test.LastLikeCourseDemands"))); 262 if (cfg.getProperty("Test.CrsReq") != null) 263 loadCrsReqFiles(model, cfg.getProperty("Test.CrsReq")); 264 } catch (Exception e) { 265 sLog.error("Unable to load model, reason: " + e.getMessage(), e); 266 return null; 267 } 268 if (cfg.getPropertyBoolean("Debug.DistanceConflict", false)) 269 DistanceConflict.sDebug = true; 270 if (cfg.getPropertyBoolean("Debug.BranchBoundSelection", false)) 271 BranchBoundSelection.sDebug = true; 272 if (cfg.getPropertyBoolean("Debug.SwapStudentsSelection", false)) 273 SwapStudentSelection.sDebug = true; 274 if (cfg.getPropertyBoolean("Debug.TimeOverlaps", false)) 275 TimeOverlapsCounter.sDebug = true; 276 if (cfg.getProperty("CourseRequest.SameTimePrecise") != null) 277 CourseRequest.sSameTimePrecise = cfg.getPropertyBoolean("CourseRequest.SameTimePrecise", false); 278 Configurator.setLevel(BacktrackNeighbourSelection.class.getName(), 279 cfg.getPropertyBoolean("Debug.BacktrackNeighbourSelection", false) ? Level.DEBUG : Level.INFO); 280 if (cfg.getPropertyBoolean("Test.FixPriorities", false)) 281 fixPriorities(model); 282 return new Solution<Request, Enrollment>(model, assignment); 283 } 284 285 /** Batch sectioning test 286 * @param cfg solver configuration 287 * @return resultant solution 288 **/ 289 public static Solution<Request, Enrollment> batchSectioning(DataProperties cfg) { 290 Solution<Request, Enrollment> solution = load(cfg); 291 if (solution == null) 292 return null; 293 StudentSectioningModel model = (StudentSectioningModel)solution.getModel(); 294 295 if (cfg.getPropertyBoolean("Test.ComputeSectioningInfo", true)) 296 model.clearOnlineSectioningInfos(); 297 298 Progress.getInstance(model).addProgressListener(new ProgressWriter(System.out)); 299 300 solve(solution, cfg); 301 302 return solution; 303 } 304 305 /** Online sectioning test 306 * @param cfg solver configuration 307 * @return resultant solution 308 * @throws Exception thrown when the sectioning fails 309 **/ 310 public static Solution<Request, Enrollment> onlineSectioning(DataProperties cfg) throws Exception { 311 Solution<Request, Enrollment> solution = load(cfg); 312 if (solution == null) 313 return null; 314 StudentSectioningModel model = (StudentSectioningModel)solution.getModel(); 315 Assignment<Request, Enrollment> assignment = solution.getAssignment(); 316 317 solution.addSolutionListener(new TestSolutionListener()); 318 double startTime = JProf.currentTimeSec(); 319 320 Solver<Request, Enrollment> solver = new Solver<Request, Enrollment>(cfg); 321 solver.setInitalSolution(solution); 322 solver.initSolver(); 323 324 OnlineSelection onlineSelection = new OnlineSelection(cfg); 325 onlineSelection.init(solver); 326 327 double totalPenalty = 0, minPenalty = 0, maxPenalty = 0; 328 double minAvEnrlPenalty = 0, maxAvEnrlPenalty = 0; 329 double totalPrefPenalty = 0, minPrefPenalty = 0, maxPrefPenalty = 0; 330 double minAvEnrlPrefPenalty = 0, maxAvEnrlPrefPenalty = 0; 331 int nrChoices = 0, nrEnrollments = 0, nrCourseRequests = 0; 332 int chChoices = 0, chCourseRequests = 0, chStudents = 0; 333 334 int choiceLimit = model.getProperties().getPropertyInt("Test.ChoicesLimit", -1); 335 336 File outDir = new File(model.getProperties().getProperty("General.Output", ".")); 337 outDir.mkdirs(); 338 PrintWriter pw = new PrintWriter(new FileWriter(new File(outDir, "choices.csv"))); 339 340 List<Student> students = model.getStudents(); 341 try { 342 @SuppressWarnings("rawtypes") 343 Class studentOrdClass = Class.forName(model.getProperties().getProperty("Test.StudentOrder", StudentRandomOrder.class.getName())); 344 @SuppressWarnings("unchecked") 345 StudentOrder studentOrd = (StudentOrder) studentOrdClass.getConstructor(new Class[] { DataProperties.class }).newInstance(new Object[] { model.getProperties() }); 346 students = studentOrd.order(model.getStudents()); 347 } catch (Exception e) { 348 sLog.error("Unable to reorder students, reason: " + e.getMessage(), e); 349 } 350 351 ShutdownHook hook = new ShutdownHook(solver); 352 Runtime.getRuntime().addShutdownHook(hook); 353 354 for (Student student : students) { 355 if (student.nrAssignedRequests(assignment) > 0) 356 continue; // skip students with assigned courses (i.e., students 357 // already assigned by a batch sectioning process) 358 sLog.info("Sectioning student: " + student); 359 360 BranchBoundSelection.Selection selection = onlineSelection.getSelection(assignment, student); 361 BranchBoundNeighbour neighbour = selection.select(); 362 if (neighbour != null) { 363 StudentPreferencePenalties penalties = null; 364 if (selection instanceof OnlineSelection.EpsilonSelection) { 365 OnlineSelection.EpsilonSelection epsSelection = (OnlineSelection.EpsilonSelection) selection; 366 penalties = epsSelection.getPenalties(); 367 for (int i = 0; i < neighbour.getAssignment().length; i++) { 368 Request r = student.getRequests().get(i); 369 if (r instanceof CourseRequest) { 370 nrCourseRequests++; 371 chCourseRequests++; 372 int chChoicesThisRq = 0; 373 CourseRequest request = (CourseRequest) r; 374 for (Enrollment x : request.getAvaiableEnrollments(assignment)) { 375 nrEnrollments++; 376 if (epsSelection.isAllowed(i, x)) { 377 nrChoices++; 378 if (choiceLimit <= 0 || chChoicesThisRq < choiceLimit) { 379 chChoices++; 380 chChoicesThisRq++; 381 } 382 } 383 } 384 } 385 } 386 chStudents++; 387 if (chStudents == 100) { 388 pw.println(sDF.format(((double) chChoices) / chCourseRequests)); 389 pw.flush(); 390 chStudents = 0; 391 chChoices = 0; 392 chCourseRequests = 0; 393 } 394 } 395 for (int i = 0; i < neighbour.getAssignment().length; i++) { 396 if (neighbour.getAssignment()[i] == null) 397 continue; 398 Enrollment enrollment = neighbour.getAssignment()[i]; 399 if (enrollment.getRequest() instanceof CourseRequest) { 400 CourseRequest request = (CourseRequest) enrollment.getRequest(); 401 double[] avEnrlMinMax = getMinMaxAvailableEnrollmentPenalty(assignment, request); 402 minAvEnrlPenalty += avEnrlMinMax[0]; 403 maxAvEnrlPenalty += avEnrlMinMax[1]; 404 totalPenalty += enrollment.getPenalty(); 405 minPenalty += request.getMinPenalty(); 406 maxPenalty += request.getMaxPenalty(); 407 if (penalties != null) { 408 double[] avEnrlPrefMinMax = penalties.getMinMaxAvailableEnrollmentPenalty(assignment, enrollment.getRequest()); 409 minAvEnrlPrefPenalty += avEnrlPrefMinMax[0]; 410 maxAvEnrlPrefPenalty += avEnrlPrefMinMax[1]; 411 totalPrefPenalty += penalties.getPenalty(enrollment); 412 minPrefPenalty += penalties.getMinPenalty(enrollment.getRequest()); 413 maxPrefPenalty += penalties.getMaxPenalty(enrollment.getRequest()); 414 } 415 } 416 } 417 neighbour.assign(assignment, solution.getIteration()); 418 sLog.info("Student " + student + " enrolls into " + neighbour); 419 onlineSelection.updateSpace(assignment, student); 420 } else { 421 sLog.warn("No solution found."); 422 } 423 solution.update(JProf.currentTimeSec() - startTime); 424 solution.saveBest(); 425 } 426 427 if (chCourseRequests > 0) 428 pw.println(sDF.format(((double) chChoices) / chCourseRequests)); 429 430 pw.flush(); 431 pw.close(); 432 433 HashMap<String, String> extra = new HashMap<String, String>(); 434 sLog.info("Overall penalty is " + getPerc(totalPenalty, minPenalty, maxPenalty) + "% (" 435 + sDF.format(totalPenalty) + "/" + sDF.format(minPenalty) + ".." + sDF.format(maxPenalty) + ")"); 436 extra.put("Overall penalty", getPerc(totalPenalty, minPenalty, maxPenalty) + "% (" + sDF.format(totalPenalty) 437 + "/" + sDF.format(minPenalty) + ".." + sDF.format(maxPenalty) + ")"); 438 extra.put("Overall available enrollment penalty", getPerc(totalPenalty, minAvEnrlPenalty, maxAvEnrlPenalty) 439 + "% (" + sDF.format(totalPenalty) + "/" + sDF.format(minAvEnrlPenalty) + ".." + sDF.format(maxAvEnrlPenalty) + ")"); 440 if (onlineSelection.isUseStudentPrefPenalties()) { 441 sLog.info("Overall preference penalty is " + getPerc(totalPrefPenalty, minPrefPenalty, maxPrefPenalty) 442 + "% (" + sDF.format(totalPrefPenalty) + "/" + sDF.format(minPrefPenalty) + ".." + sDF.format(maxPrefPenalty) + ")"); 443 extra.put("Overall preference penalty", getPerc(totalPrefPenalty, minPrefPenalty, maxPrefPenalty) + "% (" 444 + sDF.format(totalPrefPenalty) + "/" + sDF.format(minPrefPenalty) + ".." + sDF.format(maxPrefPenalty) + ")"); 445 extra.put("Overall preference available enrollment penalty", getPerc(totalPrefPenalty, 446 minAvEnrlPrefPenalty, maxAvEnrlPrefPenalty) 447 + "% (" + sDF.format(totalPrefPenalty) + "/" + sDF.format(minAvEnrlPrefPenalty) + ".." + sDF.format(maxAvEnrlPrefPenalty) + ")"); 448 extra.put("Average number of choices", sDF.format(((double) nrChoices) / nrCourseRequests) + " (" 449 + nrChoices + "/" + nrCourseRequests + ")"); 450 extra.put("Average number of enrollments", sDF.format(((double) nrEnrollments) / nrCourseRequests) + " (" 451 + nrEnrollments + "/" + nrCourseRequests + ")"); 452 } 453 hook.setExtra(extra); 454 455 return solution; 456 } 457 458 /** 459 * Minimum and maximum enrollment penalty, i.e., 460 * {@link Enrollment#getPenalty()} of all enrollments 461 * @param request a course request 462 * @return minimum and maximum of the enrollment penalty 463 */ 464 public static double[] getMinMaxEnrollmentPenalty(CourseRequest request) { 465 List<Enrollment> enrollments = request.values(new EmptyAssignment<Request, Enrollment>()); 466 if (enrollments.isEmpty()) 467 return new double[] { 0, 0 }; 468 double min = Double.MAX_VALUE, max = Double.MIN_VALUE; 469 for (Enrollment enrollment : enrollments) { 470 double penalty = enrollment.getPenalty(); 471 min = Math.min(min, penalty); 472 max = Math.max(max, penalty); 473 } 474 return new double[] { min, max }; 475 } 476 477 /** 478 * Minimum and maximum available enrollment penalty, i.e., 479 * {@link Enrollment#getPenalty()} of all available enrollments 480 * @param assignment current assignment 481 * @param request a course request 482 * @return minimum and maximum of the available enrollment penalty 483 */ 484 public static double[] getMinMaxAvailableEnrollmentPenalty(Assignment<Request, Enrollment> assignment, CourseRequest request) { 485 List<Enrollment> enrollments = request.getAvaiableEnrollments(assignment); 486 if (enrollments.isEmpty()) 487 return new double[] { 0, 0 }; 488 double min = Double.MAX_VALUE, max = Double.MIN_VALUE; 489 for (Enrollment enrollment : enrollments) { 490 double penalty = enrollment.getPenalty(); 491 min = Math.min(min, penalty); 492 max = Math.max(max, penalty); 493 } 494 return new double[] { min, max }; 495 } 496 497 /** 498 * Compute percentage 499 * 500 * @param value 501 * current value 502 * @param min 503 * minimal bound 504 * @param max 505 * maximal bound 506 * @return (value-min)/(max-min) 507 */ 508 public static String getPerc(double value, double min, double max) { 509 if (max == min) 510 return sDF.format(100.0); 511 return sDF.format(100.0 - 100.0 * (value - min) / (max - min)); 512 } 513 514 /** 515 * Print some information about the solution 516 * 517 * @param solution 518 * given solution 519 * @param computeTables 520 * true, if reports {@link CourseConflictTable} and 521 * {@link DistanceConflictTable} are to be computed as well 522 * @param computeSectInfos 523 * true, if online sectioning infou is to be computed as well 524 * (see 525 * {@link StudentSectioningModel#computeOnlineSectioningInfos(Assignment)}) 526 * @param runChecks 527 * true, if checks {@link OverlapCheck} and 528 * {@link SectionLimitCheck} are to be performed as well 529 */ 530 public static void printInfo(Solution<Request, Enrollment> solution, boolean computeTables, boolean computeSectInfos, boolean runChecks) { 531 StudentSectioningModel model = (StudentSectioningModel) solution.getModel(); 532 533 if (computeTables) { 534 if (solution.getModel().assignedVariables(solution.getAssignment()).size() > 0) { 535 try { 536 DataProperties lastlike = new DataProperties(); 537 lastlike.setProperty("lastlike", "true"); 538 lastlike.setProperty("real", "false"); 539 lastlike.setProperty("useAmPm", "true"); 540 DataProperties real = new DataProperties(); 541 real.setProperty("lastlike", "false"); 542 real.setProperty("real", "true"); 543 real.setProperty("useAmPm", "true"); 544 545 File outDir = new File(model.getProperties().getProperty("General.Output", ".")); 546 outDir.mkdirs(); 547 CourseConflictTable cct = new CourseConflictTable((StudentSectioningModel) solution.getModel()); 548 cct.createTable(solution.getAssignment(), lastlike).save(new File(outDir, "conflicts-lastlike.csv")); 549 cct.createTable(solution.getAssignment(), real).save(new File(outDir, "conflicts-real.csv")); 550 551 DistanceConflictTable dct = new DistanceConflictTable((StudentSectioningModel) solution.getModel()); 552 dct.createTable(solution.getAssignment(), lastlike).save(new File(outDir, "distances-lastlike.csv")); 553 dct.createTable(solution.getAssignment(), real).save(new File(outDir, "distances-real.csv")); 554 555 SectionConflictTable sct = new SectionConflictTable((StudentSectioningModel) solution.getModel(), SectionConflictTable.Type.OVERLAPS); 556 sct.createTable(solution.getAssignment(), lastlike).save(new File(outDir, "time-conflicts-lastlike.csv")); 557 sct.createTable(solution.getAssignment(), real).save(new File(outDir, "time-conflicts-real.csv")); 558 559 SectionConflictTable ust = new SectionConflictTable((StudentSectioningModel) solution.getModel(), SectionConflictTable.Type.UNAVAILABILITIES); 560 ust.createTable(solution.getAssignment(), lastlike).save(new File(outDir, "availability-conflicts-lastlike.csv")); 561 ust.createTable(solution.getAssignment(), real).save(new File(outDir, "availability-conflicts-real.csv")); 562 563 SectionConflictTable ct = new SectionConflictTable((StudentSectioningModel) solution.getModel(), SectionConflictTable.Type.OVERLAPS_AND_UNAVAILABILITIES); 564 ct.createTable(solution.getAssignment(), lastlike).save(new File(outDir, "section-conflicts-lastlike.csv")); 565 ct.createTable(solution.getAssignment(), real).save(new File(outDir, "section-conflicts-real.csv")); 566 567 UnbalancedSectionsTable ubt = new UnbalancedSectionsTable((StudentSectioningModel) solution.getModel()); 568 ubt.createTable(solution.getAssignment(), lastlike).save(new File(outDir, "unbalanced-lastlike.csv")); 569 ubt.createTable(solution.getAssignment(), real).save(new File(outDir, "unbalanced-real.csv")); 570 571 TimeOverlapConflictTable toc = new TimeOverlapConflictTable((StudentSectioningModel) solution.getModel()); 572 toc.createTable(solution.getAssignment(), lastlike).save(new File(outDir, "time-overlaps-lastlike.csv")); 573 toc.createTable(solution.getAssignment(), real).save(new File(outDir, "time-overlaps-real.csv")); 574 575 RequestGroupTable rqt = new RequestGroupTable((StudentSectioningModel) solution.getModel()); 576 rqt.create(solution.getAssignment(), model.getProperties()).save(new File(outDir, "request-groups.csv")); 577 578 RequestPriorityTable rpt = new RequestPriorityTable((StudentSectioningModel) solution.getModel()); 579 rpt.create(solution.getAssignment(), model.getProperties()).save(new File(outDir, "request-priorities.csv")); 580 581 TableauReport tr = new TableauReport((StudentSectioningModel) solution.getModel()); 582 tr.create(solution.getAssignment(), model.getProperties()).save(new File(outDir, "tableau.csv")); 583 584 SolutionStatsReport st = new SolutionStatsReport((StudentSectioningModel) solution.getModel()); 585 st.create(solution.getAssignment(), model.getProperties()).save(new File(outDir, "stats.csv")); 586 } catch (IOException e) { 587 sLog.error(e.getMessage(), e); 588 } 589 } 590 591 solution.saveBest(); 592 } 593 594 if (computeSectInfos) 595 model.computeOnlineSectioningInfos(solution.getAssignment()); 596 597 if (runChecks) { 598 try { 599 if (model.getProperties().getPropertyBoolean("Test.InevitableStudentConflictsCheck", false)) { 600 InevitableStudentConflicts ch = new InevitableStudentConflicts(model); 601 if (!ch.check(solution.getAssignment())) 602 ch.getCSVFile().save( 603 new File(new File(model.getProperties().getProperty("General.Output", ".")), 604 "inevitable-conflicts.csv")); 605 } 606 } catch (IOException e) { 607 sLog.error(e.getMessage(), e); 608 } 609 new OverlapCheck(model).check(solution.getAssignment()); 610 new SectionLimitCheck(model).check(solution.getAssignment()); 611 try { 612 CourseLimitCheck ch = new CourseLimitCheck(model); 613 if (!ch.check()) 614 ch.getCSVFile().save( 615 new File(new File(model.getProperties().getProperty("General.Output", ".")), 616 "course-limits.csv")); 617 } catch (IOException e) { 618 sLog.error(e.getMessage(), e); 619 } 620 } 621 622 sLog.info("Best solution found after " + solution.getBestTime() + " seconds (" + solution.getBestIteration() 623 + " iterations)."); 624 sLog.info("Info: " + ToolBox.dict2string(solution.getExtendedInfo(), 2)); 625 } 626 627 /** Solve the student sectioning problem using IFS solver 628 * @param solution current solution 629 * @param cfg solver configuration 630 * @return resultant solution 631 **/ 632 public static Solution<Request, Enrollment> solve(Solution<Request, Enrollment> solution, DataProperties cfg) { 633 int nrSolvers = cfg.getPropertyInt("Parallel.NrSolvers", 1); 634 Solver<Request, Enrollment> solver = (nrSolvers == 1 ? new Solver<Request, Enrollment>(cfg) : new ParallelSolver<Request, Enrollment>(cfg)); 635 solver.setInitalSolution(solution); 636 if (cfg.getPropertyBoolean("Test.Verbose", false)) { 637 solver.addSolverListener(new SolverListener<Request, Enrollment>() { 638 @Override 639 public boolean variableSelected(Assignment<Request, Enrollment> assignment, long iteration, Request variable) { 640 return true; 641 } 642 643 @Override 644 public boolean valueSelected(Assignment<Request, Enrollment> assignment, long iteration, Request variable, Enrollment value) { 645 return true; 646 } 647 648 @Override 649 public boolean neighbourSelected(Assignment<Request, Enrollment> assignment, long iteration, Neighbour<Request, Enrollment> neighbour) { 650 sLog.debug("Select[" + iteration + "]: " + neighbour); 651 return true; 652 } 653 654 @Override 655 public void neighbourFailed(Assignment<Request, Enrollment> assignment, long iteration, Neighbour<Request, Enrollment> neighbour) { 656 sLog.debug("Failed[" + iteration + "]: " + neighbour); 657 } 658 }); 659 } 660 solution.addSolutionListener(new TestSolutionListener()); 661 662 Runtime.getRuntime().addShutdownHook(new ShutdownHook(solver)); 663 664 solver.start(); 665 try { 666 solver.getSolverThread().join(); 667 } catch (InterruptedException e) { 668 } 669 670 return solution; 671 } 672 673 /** 674 * Compute last-like student weight for the given course 675 * 676 * @param course 677 * given course 678 * @param real 679 * number of real students for the course 680 * @param lastLike 681 * number of last-like students for the course 682 * @return weight of a student request for the given course 683 */ 684 public static double getLastLikeStudentWeight(Course course, int real, int lastLike) { 685 int projected = course.getProjected(); 686 int limit = course.getLimit(); 687 if (course.getLimit() < 0) { 688 sLog.debug(" -- Course " + course.getName() + " is unlimited."); 689 return 1.0; 690 } 691 if (projected <= 0) { 692 sLog.warn(" -- No projected demand for course " + course.getName() + ", using course limit (" + limit 693 + ")"); 694 projected = limit; 695 } else if (limit < projected) { 696 sLog.warn(" -- Projected number of students is over course limit for course " + course.getName() + " (" 697 + Math.round(projected) + ">" + limit + ")"); 698 projected = limit; 699 } 700 if (lastLike == 0) { 701 sLog.warn(" -- No last like info for course " + course.getName()); 702 return 1.0; 703 } 704 double weight = ((double) Math.max(0, projected - real)) / lastLike; 705 sLog.debug(" -- last like student weight for " + course.getName() + " is " + weight + " (lastLike=" + lastLike 706 + ", real=" + real + ", projected=" + projected + ")"); 707 return weight; 708 } 709 710 /** 711 * Load last-like students from an XML file (the one that is used to load 712 * last like course demands table in the timetabling application) 713 * @param model problem model 714 * @param xml an XML file 715 */ 716 public static void loadLastLikeCourseDemandsXml(StudentSectioningModel model, File xml) { 717 try { 718 Document document = (new SAXReader()).read(xml); 719 Element root = document.getRootElement(); 720 HashMap<Course, List<Request>> requests = new HashMap<Course, List<Request>>(); 721 long reqId = 0; 722 for (Iterator<?> i = root.elementIterator("student"); i.hasNext();) { 723 Element studentEl = (Element) i.next(); 724 Student student = new Student(Long.parseLong(studentEl.attributeValue("externalId"))); 725 student.setDummy(true); 726 int priority = 0; 727 HashSet<Course> reqCourses = new HashSet<Course>(); 728 for (Iterator<?> j = studentEl.elementIterator("studentCourse"); j.hasNext();) { 729 Element courseEl = (Element) j.next(); 730 String subjectArea = courseEl.attributeValue("subject"); 731 String courseNbr = courseEl.attributeValue("courseNumber"); 732 Course course = null; 733 offerings: for (Offering offering : model.getOfferings()) { 734 for (Course c : offering.getCourses()) { 735 if (c.getSubjectArea().equals(subjectArea) && c.getCourseNumber().equals(courseNbr)) { 736 course = c; 737 break offerings; 738 } 739 } 740 } 741 if (course == null && courseNbr.charAt(courseNbr.length() - 1) >= 'A' 742 && courseNbr.charAt(courseNbr.length() - 1) <= 'Z') { 743 String courseNbrNoSfx = courseNbr.substring(0, courseNbr.length() - 1); 744 offerings: for (Offering offering : model.getOfferings()) { 745 for (Course c : offering.getCourses()) { 746 if (c.getSubjectArea().equals(subjectArea) 747 && c.getCourseNumber().equals(courseNbrNoSfx)) { 748 course = c; 749 break offerings; 750 } 751 } 752 } 753 } 754 if (course == null) { 755 sLog.warn("Course " + subjectArea + " " + courseNbr + " not found."); 756 } else { 757 if (!reqCourses.add(course)) { 758 sLog.warn("Course " + subjectArea + " " + courseNbr + " already requested."); 759 } else { 760 List<Course> courses = new ArrayList<Course>(1); 761 courses.add(course); 762 CourseRequest request = new CourseRequest(reqId++, priority++, false, student, courses, false, null); 763 List<Request> requestsThisCourse = requests.get(course); 764 if (requestsThisCourse == null) { 765 requestsThisCourse = new ArrayList<Request>(); 766 requests.put(course, requestsThisCourse); 767 } 768 requestsThisCourse.add(request); 769 } 770 } 771 } 772 if (!student.getRequests().isEmpty()) 773 model.addStudent(student); 774 } 775 for (Map.Entry<Course, List<Request>> entry : requests.entrySet()) { 776 Course course = entry.getKey(); 777 List<Request> requestsThisCourse = entry.getValue(); 778 double weight = getLastLikeStudentWeight(course, 0, requestsThisCourse.size()); 779 for (Request request : requestsThisCourse) { 780 request.setWeight(weight); 781 } 782 } 783 } catch (Exception e) { 784 sLog.error(e.getMessage(), e); 785 } 786 } 787 788 /** 789 * Load course request from the given files (in the format being used by the 790 * old MSF system) 791 * 792 * @param model 793 * student sectioning model (with offerings loaded) 794 * @param files 795 * semi-colon separated list of files to be loaded 796 */ 797 public static void loadCrsReqFiles(StudentSectioningModel model, String files) { 798 try { 799 boolean lastLike = model.getProperties().getPropertyBoolean("Test.CrsReqIsLastLike", true); 800 boolean shuffleIds = model.getProperties().getPropertyBoolean("Test.CrsReqShuffleStudentIds", true); 801 boolean tryWithoutSuffix = model.getProperties().getPropertyBoolean("Test.CrsReqTryWithoutSuffix", false); 802 HashMap<Long, Student> students = new HashMap<Long, Student>(); 803 long reqId = 0; 804 for (StringTokenizer stk = new StringTokenizer(files, ";"); stk.hasMoreTokens();) { 805 String file = stk.nextToken(); 806 sLog.debug("Loading " + file + " ..."); 807 BufferedReader in = new BufferedReader(new FileReader(file)); 808 String line; 809 int lineIndex = 0; 810 while ((line = in.readLine()) != null) { 811 lineIndex++; 812 if (line.length() <= 150) 813 continue; 814 char code = line.charAt(13); 815 if (code == 'H' || code == 'T') 816 continue; // skip header and tail 817 long studentId = Long.parseLong(line.substring(14, 23)); 818 Student student = students.get(Long.valueOf(studentId)); 819 if (student == null) { 820 student = new Student(studentId); 821 if (lastLike) 822 student.setDummy(true); 823 students.put(Long.valueOf(studentId), student); 824 sLog.debug(" -- loading student " + studentId + " ..."); 825 } else 826 sLog.debug(" -- updating student " + studentId + " ..."); 827 line = line.substring(150); 828 while (line.length() >= 20) { 829 String subjectArea = line.substring(0, 4).trim(); 830 String courseNbr = line.substring(4, 8).trim(); 831 if (subjectArea.length() == 0 || courseNbr.length() == 0) { 832 line = line.substring(20); 833 continue; 834 } 835 /* 836 * // UNUSED String instrSel = line.substring(8,10); 837 * //ZZ - Remove previous instructor selection char 838 * reqPDiv = line.charAt(10); //P - Personal preference; 839 * C - Conflict resolution; //0 - (Zero) used by program 840 * only, for change requests to reschedule division // 841 * (used to reschedule canceled division) String reqDiv 842 * = line.substring(11,13); //00 - Reschedule division 843 * String reqSect = line.substring(13,15); //Contains 844 * designator for designator-required courses String 845 * credit = line.substring(15,19); char nameRaise = 846 * line.charAt(19); //N - Name raise 847 */ 848 char action = line.charAt(19); // A - Add; D - Drop; C - 849 // Change 850 sLog.debug(" -- requesting " + subjectArea + " " + courseNbr + " (action:" + action 851 + ") ..."); 852 Course course = null; 853 offerings: for (Offering offering : model.getOfferings()) { 854 for (Course c : offering.getCourses()) { 855 if (c.getSubjectArea().equals(subjectArea) && c.getCourseNumber().equals(courseNbr)) { 856 course = c; 857 break offerings; 858 } 859 } 860 } 861 if (course == null && tryWithoutSuffix && courseNbr.charAt(courseNbr.length() - 1) >= 'A' 862 && courseNbr.charAt(courseNbr.length() - 1) <= 'Z') { 863 String courseNbrNoSfx = courseNbr.substring(0, courseNbr.length() - 1); 864 offerings: for (Offering offering : model.getOfferings()) { 865 for (Course c : offering.getCourses()) { 866 if (c.getSubjectArea().equals(subjectArea) 867 && c.getCourseNumber().equals(courseNbrNoSfx)) { 868 course = c; 869 break offerings; 870 } 871 } 872 } 873 } 874 if (course == null) { 875 if (courseNbr.charAt(courseNbr.length() - 1) >= 'A' 876 && courseNbr.charAt(courseNbr.length() - 1) <= 'Z') { 877 } else { 878 sLog.warn(" -- course " + subjectArea + " " + courseNbr + " not found (file " 879 + file + ", line " + lineIndex + ")"); 880 } 881 } else { 882 CourseRequest courseRequest = null; 883 for (Request request : student.getRequests()) { 884 if (request instanceof CourseRequest 885 && ((CourseRequest) request).getCourses().contains(course)) { 886 courseRequest = (CourseRequest) request; 887 break; 888 } 889 } 890 if (action == 'A') { 891 if (courseRequest == null) { 892 List<Course> courses = new ArrayList<Course>(1); 893 courses.add(course); 894 courseRequest = new CourseRequest(reqId++, student.getRequests().size(), false, student, courses, false, null); 895 } else { 896 sLog.warn(" -- request for course " + course + " is already present"); 897 } 898 } else if (action == 'D') { 899 if (courseRequest == null) { 900 sLog.warn(" -- request for course " + course 901 + " is not present -- cannot be dropped"); 902 } else { 903 student.getRequests().remove(courseRequest); 904 } 905 } else if (action == 'C') { 906 if (courseRequest == null) { 907 sLog.warn(" -- request for course " + course 908 + " is not present -- cannot be changed"); 909 } else { 910 // ? 911 } 912 } else { 913 sLog.warn(" -- unknown action " + action); 914 } 915 } 916 line = line.substring(20); 917 } 918 } 919 in.close(); 920 } 921 HashMap<Course, List<Request>> requests = new HashMap<Course, List<Request>>(); 922 Set<Long> studentIds = new HashSet<Long>(); 923 for (Student student: students.values()) { 924 if (!student.getRequests().isEmpty()) 925 model.addStudent(student); 926 if (shuffleIds) { 927 long newId = -1; 928 while (true) { 929 newId = 1 + (long) (999999999L * Math.random()); 930 if (studentIds.add(Long.valueOf(newId))) 931 break; 932 } 933 student.setId(newId); 934 } 935 if (student.isDummy()) { 936 for (Request request : student.getRequests()) { 937 if (request instanceof CourseRequest) { 938 Course course = ((CourseRequest) request).getCourses().get(0); 939 List<Request> requestsThisCourse = requests.get(course); 940 if (requestsThisCourse == null) { 941 requestsThisCourse = new ArrayList<Request>(); 942 requests.put(course, requestsThisCourse); 943 } 944 requestsThisCourse.add(request); 945 } 946 } 947 } 948 } 949 Collections.sort(model.getStudents(), new Comparator<Student>() { 950 @Override 951 public int compare(Student o1, Student o2) { 952 return Double.compare(o1.getId(), o2.getId()); 953 } 954 }); 955 for (Map.Entry<Course, List<Request>> entry : requests.entrySet()) { 956 Course course = entry.getKey(); 957 List<Request> requestsThisCourse = entry.getValue(); 958 double weight = getLastLikeStudentWeight(course, 0, requestsThisCourse.size()); 959 for (Request request : requestsThisCourse) { 960 request.setWeight(weight); 961 } 962 } 963 if (model.getProperties().getProperty("Test.EtrChk") != null) { 964 for (StringTokenizer stk = new StringTokenizer(model.getProperties().getProperty("Test.EtrChk"), ";"); stk 965 .hasMoreTokens();) { 966 String file = stk.nextToken(); 967 sLog.debug("Loading " + file + " ..."); 968 BufferedReader in = new BufferedReader(new FileReader(file)); 969 try { 970 String line; 971 while ((line = in.readLine()) != null) { 972 if (line.length() < 55) 973 continue; 974 char code = line.charAt(12); 975 if (code == 'H' || code == 'T') 976 continue; // skip header and tail 977 if (code == 'D' || code == 'K') 978 continue; // skip delete nad cancel 979 long studentId = Long.parseLong(line.substring(2, 11)); 980 Student student = students.get(Long.valueOf(studentId)); 981 if (student == null) { 982 sLog.info(" -- student " + studentId + " not found"); 983 continue; 984 } 985 sLog.info(" -- reading student " + studentId); 986 String area = line.substring(15, 18).trim(); 987 if (area.length() == 0) 988 continue; 989 String clasf = line.substring(18, 20).trim(); 990 String major = line.substring(21, 24).trim(); 991 String minor = line.substring(24, 27).trim(); 992 student.getAreaClassificationMajors().clear(); 993 student.getAreaClassificationMinors().clear(); 994 if (major.length() > 0) 995 student.getAreaClassificationMajors().add(new AreaClassificationMajor(area, clasf, major)); 996 if (minor.length() > 0) 997 student.getAreaClassificationMajors().add(new AreaClassificationMajor(area, clasf, minor)); 998 } 999 } finally { 1000 in.close(); 1001 } 1002 } 1003 } 1004 int without = 0; 1005 for (Student student: students.values()) { 1006 if (student.getAreaClassificationMajors().isEmpty()) 1007 without++; 1008 } 1009 fixPriorities(model); 1010 sLog.info("Students without academic area: " + without); 1011 } catch (Exception e) { 1012 sLog.error(e.getMessage(), e); 1013 } 1014 } 1015 1016 public static void fixPriorities(StudentSectioningModel model) { 1017 for (Student student : model.getStudents()) { 1018 Collections.sort(student.getRequests(), new Comparator<Request>() { 1019 @Override 1020 public int compare(Request r1, Request r2) { 1021 int cmp = Double.compare(r1.getPriority(), r2.getPriority()); 1022 if (cmp != 0) 1023 return cmp; 1024 return Double.compare(r1.getId(), r2.getId()); 1025 } 1026 }); 1027 int priority = 0; 1028 for (Request request : student.getRequests()) { 1029 if (priority != request.getPriority()) { 1030 sLog.debug("Change priority of " + request + " to " + priority); 1031 request.setPriority(priority); 1032 } 1033 } 1034 } 1035 } 1036 1037 /** Save solution info as XML 1038 * @param solution current solution 1039 * @param extra solution extra info 1040 * @param file file to write 1041 **/ 1042 public static void saveInfoToXML(Solution<Request, Enrollment> solution, Map<String, String> extra, File file) { 1043 FileOutputStream fos = null; 1044 try { 1045 Document document = DocumentHelper.createDocument(); 1046 document.addComment("Solution Info"); 1047 1048 Element root = document.addElement("info"); 1049 TreeSet<Map.Entry<String, String>> entrySet = new TreeSet<Map.Entry<String, String>>( 1050 new Comparator<Map.Entry<String, String>>() { 1051 @Override 1052 public int compare(Map.Entry<String, String> e1, Map.Entry<String, String> e2) { 1053 return e1.getKey().compareTo(e2.getKey()); 1054 } 1055 }); 1056 entrySet.addAll(solution.getExtendedInfo().entrySet()); 1057 if (extra != null) 1058 entrySet.addAll(extra.entrySet()); 1059 for (Map.Entry<String, String> entry : entrySet) { 1060 root.addElement("property").addAttribute("name", entry.getKey()).setText(entry.getValue()); 1061 } 1062 1063 fos = new FileOutputStream(file); 1064 (new XMLWriter(fos, OutputFormat.createPrettyPrint())).write(document); 1065 fos.flush(); 1066 fos.close(); 1067 fos = null; 1068 } catch (Exception e) { 1069 sLog.error("Unable to save info, reason: " + e.getMessage(), e); 1070 } finally { 1071 try { 1072 if (fos != null) 1073 fos.close(); 1074 } catch (IOException e) { 1075 } 1076 } 1077 } 1078 1079 private static void fixWeights(StudentSectioningModel model) { 1080 HashMap<Course, Integer> lastLike = new HashMap<Course, Integer>(); 1081 HashMap<Course, Integer> real = new HashMap<Course, Integer>(); 1082 HashSet<Long> lastLikeIds = new HashSet<Long>(); 1083 HashSet<Long> realIds = new HashSet<Long>(); 1084 for (Student student : model.getStudents()) { 1085 if (student.isDummy()) { 1086 if (!lastLikeIds.add(Long.valueOf(student.getId()))) { 1087 sLog.error("Two last-like student with id " + student.getId()); 1088 } 1089 } else { 1090 if (!realIds.add(Long.valueOf(student.getId()))) { 1091 sLog.error("Two real student with id " + student.getId()); 1092 } 1093 } 1094 for (Request request : student.getRequests()) { 1095 if (request instanceof CourseRequest) { 1096 CourseRequest courseRequest = (CourseRequest) request; 1097 Course course = courseRequest.getCourses().get(0); 1098 Integer cnt = (student.isDummy() ? lastLike : real).get(course); 1099 (student.isDummy() ? lastLike : real).put(course, Integer.valueOf( 1100 (cnt == null ? 0 : cnt.intValue()) + 1)); 1101 } 1102 } 1103 } 1104 for (Student student : new ArrayList<Student>(model.getStudents())) { 1105 if (student.isDummy() && realIds.contains(Long.valueOf(student.getId()))) { 1106 sLog.warn("There is both last-like and real student with id " + student.getId()); 1107 long newId = -1; 1108 while (true) { 1109 newId = 1 + (long) (999999999L * Math.random()); 1110 if (!realIds.contains(Long.valueOf(newId)) && !lastLikeIds.contains(Long.valueOf(newId))) 1111 break; 1112 } 1113 lastLikeIds.remove(Long.valueOf(student.getId())); 1114 lastLikeIds.add(Long.valueOf(newId)); 1115 student.setId(newId); 1116 sLog.warn(" -- last-like student id changed to " + student.getId()); 1117 } 1118 for (Request request : new ArrayList<Request>(student.getRequests())) { 1119 if (!student.isDummy()) { 1120 request.setWeight(1.0); 1121 continue; 1122 } 1123 if (request instanceof CourseRequest) { 1124 CourseRequest courseRequest = (CourseRequest) request; 1125 Course course = courseRequest.getCourses().get(0); 1126 Integer lastLikeCnt = lastLike.get(course); 1127 Integer realCnt = real.get(course); 1128 courseRequest.setWeight(getLastLikeStudentWeight(course, realCnt == null ? 0 : realCnt.intValue(), 1129 lastLikeCnt == null ? 0 : lastLikeCnt.intValue())); 1130 } else 1131 request.setWeight(1.0); 1132 if (request.getWeight() <= 0.0) { 1133 model.removeVariable(request); 1134 student.getRequests().remove(request); 1135 } 1136 } 1137 if (student.getRequests().isEmpty()) { 1138 model.getStudents().remove(student); 1139 } 1140 } 1141 } 1142 1143 /** Combine students from the provided two files 1144 * @param cfg solver configuration 1145 * @param lastLikeStudentData a file containing last-like student data 1146 * @param realStudentData a file containing real student data 1147 * @return combined solution 1148 **/ 1149 public static Solution<Request, Enrollment> combineStudents(DataProperties cfg, File lastLikeStudentData, File realStudentData) { 1150 try { 1151 RandomStudentFilter rnd = new RandomStudentFilter(1.0); 1152 1153 StudentSectioningModel model = null; 1154 Assignment<Request, Enrollment> assignment = new DefaultSingleAssignment<Request, Enrollment>(); 1155 1156 for (StringTokenizer stk = new StringTokenizer(cfg.getProperty("Test.CombineAcceptProb", "1.0"), ","); stk.hasMoreTokens();) { 1157 double acceptProb = Double.parseDouble(stk.nextToken()); 1158 sLog.info("Test.CombineAcceptProb=" + acceptProb); 1159 rnd.setProbability(acceptProb); 1160 1161 StudentFilter batchFilter = new CombinedStudentFilter(new ReverseStudentFilter( 1162 new FreshmanStudentFilter()), rnd, CombinedStudentFilter.OP_AND); 1163 1164 model = new StudentSectioningModel(cfg); 1165 StudentSectioningXMLLoader loader = new StudentSectioningXMLLoader(model, assignment); 1166 loader.setLoadStudents(false); 1167 loader.load(); 1168 1169 StudentSectioningXMLLoader lastLikeLoader = new StudentSectioningXMLLoader(model, assignment); 1170 lastLikeLoader.setInputFile(lastLikeStudentData); 1171 lastLikeLoader.setLoadOfferings(false); 1172 lastLikeLoader.setLoadStudents(true); 1173 lastLikeLoader.load(); 1174 1175 StudentSectioningXMLLoader realLoader = new StudentSectioningXMLLoader(model, assignment); 1176 realLoader.setInputFile(realStudentData); 1177 realLoader.setLoadOfferings(false); 1178 realLoader.setLoadStudents(true); 1179 realLoader.setStudentFilter(batchFilter); 1180 realLoader.load(); 1181 1182 fixWeights(model); 1183 1184 fixPriorities(model); 1185 1186 Solver<Request, Enrollment> solver = new Solver<Request, Enrollment>(model.getProperties()); 1187 solver.setInitalSolution(model); 1188 new StudentSectioningXMLSaver(solver).save(new File(new File(model.getProperties().getProperty( 1189 "General.Output", ".")), "solution-r" + ((int) (100.0 * acceptProb)) + ".xml")); 1190 1191 } 1192 1193 return model == null ? null : new Solution<Request, Enrollment>(model, assignment); 1194 1195 } catch (Exception e) { 1196 sLog.error("Unable to combine students, reason: " + e.getMessage(), e); 1197 return null; 1198 } 1199 } 1200 1201 /** Main 1202 * @param args program arguments 1203 **/ 1204 public static void main(String[] args) { 1205 try { 1206 DataProperties cfg = new DataProperties(); 1207 cfg.setProperty("Termination.Class", "org.cpsolver.ifs.termination.GeneralTerminationCondition"); 1208 cfg.setProperty("Termination.StopWhenComplete", "true"); 1209 cfg.setProperty("Termination.TimeOut", "600"); 1210 cfg.setProperty("Comparator.Class", "org.cpsolver.ifs.solution.GeneralSolutionComparator"); 1211 cfg.setProperty("Value.Class", "org.cpsolver.studentsct.heuristics.EnrollmentSelection");// org.cpsolver.ifs.heuristics.GeneralValueSelection 1212 cfg.setProperty("Value.WeightConflicts", "1.0"); 1213 cfg.setProperty("Value.WeightNrAssignments", "0.0"); 1214 cfg.setProperty("Variable.Class", "org.cpsolver.ifs.heuristics.GeneralVariableSelection"); 1215 cfg.setProperty("Neighbour.Class", "org.cpsolver.studentsct.heuristics.StudentSctNeighbourSelection"); 1216 cfg.setProperty("General.SaveBestUnassigned", "0"); 1217 cfg.setProperty("Extensions.Classes", 1218 "org.cpsolver.ifs.extension.ConflictStatistics;org.cpsolver.studentsct.extension.DistanceConflict" + 1219 ";org.cpsolver.studentsct.extension.TimeOverlapsCounter"); 1220 cfg.setProperty("Data.Initiative", "puWestLafayetteTrdtn"); 1221 cfg.setProperty("Data.Term", "Fal"); 1222 cfg.setProperty("Data.Year", "2007"); 1223 cfg.setProperty("General.Input", "pu-sectll-fal07-s.xml"); 1224 if (args.length >= 1) { 1225 cfg.load(new FileInputStream(args[0])); 1226 } 1227 cfg.putAll(System.getProperties()); 1228 1229 if (args.length >= 2) { 1230 cfg.setProperty("General.Input", args[1]); 1231 } 1232 1233 File outDir = null; 1234 if (args.length >= 3) { 1235 outDir = new File(args[2], sDateFormat.format(new Date())); 1236 } else if (cfg.getProperty("General.Output") != null) { 1237 outDir = new File(cfg.getProperty("General.Output", "."), sDateFormat.format(new Date())); 1238 } else { 1239 outDir = new File(System.getProperty("user.home", ".") + File.separator + "Sectioning-Test" + File.separator + (sDateFormat.format(new Date()))); 1240 } 1241 outDir.mkdirs(); 1242 ToolBox.setupLogging(new File(outDir, "debug.log"), "true".equals(System.getProperty("debug", "false"))); 1243 cfg.setProperty("General.Output", outDir.getAbsolutePath()); 1244 1245 if (args.length >= 4 && "online".equals(args[3])) { 1246 onlineSectioning(cfg); 1247 } else if (args.length >= 4 && "simple".equals(args[3])) { 1248 cfg.setProperty("Sectioning.UseOnlinePenalties", "false"); 1249 onlineSectioning(cfg); 1250 } else { 1251 batchSectioning(cfg); 1252 } 1253 } catch (Exception e) { 1254 sLog.error(e.getMessage(), e); 1255 e.printStackTrace(); 1256 } 1257 } 1258 1259 public static class ExtraStudentFilter implements StudentFilter { 1260 HashSet<Long> iIds = new HashSet<Long>(); 1261 1262 public ExtraStudentFilter(StudentSectioningModel model) { 1263 for (Student student : model.getStudents()) { 1264 iIds.add(Long.valueOf(student.getId())); 1265 } 1266 } 1267 1268 @Override 1269 public boolean accept(Student student) { 1270 return !iIds.contains(Long.valueOf(student.getId())); 1271 } 1272 1273 @Override 1274 public String getName() { 1275 return "Extra"; 1276 } 1277 } 1278 1279 public static class TestSolutionListener implements SolutionListener<Request, Enrollment> { 1280 @Override 1281 public void solutionUpdated(Solution<Request, Enrollment> solution) { 1282 StudentSectioningModel m = (StudentSectioningModel) solution.getModel(); 1283 if (m.getTimeOverlaps() != null && TimeOverlapsCounter.sDebug) 1284 m.getTimeOverlaps().checkTotalNrConflicts(solution.getAssignment()); 1285 if (m.getDistanceConflict() != null && DistanceConflict.sDebug) 1286 m.getDistanceConflict().checkAllConflicts(solution.getAssignment()); 1287 if (m.getStudentQuality() != null && m.getStudentQuality().isDebug()) 1288 m.getStudentQuality().checkTotalPenalty(solution.getAssignment()); 1289 } 1290 1291 @Override 1292 public void getInfo(Solution<Request, Enrollment> solution, Map<String, String> info) { 1293 } 1294 1295 @Override 1296 public void getInfo(Solution<Request, Enrollment> solution, Map<String, String> info, Collection<Request> variables) { 1297 } 1298 1299 @Override 1300 public void bestCleared(Solution<Request, Enrollment> solution) { 1301 } 1302 1303 @Override 1304 public void bestSaved(Solution<Request, Enrollment> solution) { 1305 sLog.info("**BEST** " + ((StudentSectioningModel)solution.getModel()).toString(solution.getAssignment()) + ", TM:" + sDF.format(solution.getTime() / 3600.0) + "h" + 1306 (solution.getFailedIterations() > 0 ? ", F:" + sDF.format(100.0 * solution.getFailedIterations() / solution.getIteration()) + "%" : "")); 1307 } 1308 1309 @Override 1310 public void bestRestored(Solution<Request, Enrollment> solution) { 1311 } 1312 } 1313 1314 private static class ShutdownHook extends Thread { 1315 Solver<Request, Enrollment> iSolver = null; 1316 Map<String, String> iExtra = null; 1317 1318 private ShutdownHook(Solver<Request, Enrollment> solver) { 1319 setName("ShutdownHook"); 1320 iSolver = solver; 1321 } 1322 1323 void setExtra(Map<String, String> extra) { iExtra = extra; } 1324 1325 @Override 1326 public void run() { 1327 try { 1328 if (iSolver.isRunning()) iSolver.stopSolver(); 1329 Solution<Request, Enrollment> solution = iSolver.lastSolution(); 1330 solution.restoreBest(); 1331 DataProperties cfg = iSolver.getProperties(); 1332 1333 printInfo(solution, 1334 cfg.getPropertyBoolean("Test.CreateReports", true), 1335 cfg.getPropertyBoolean("Test.ComputeSectioningInfo", true), 1336 cfg.getPropertyBoolean("Test.RunChecks", true)); 1337 1338 try { 1339 new StudentSectioningXMLSaver(iSolver).save(new File(new File(cfg.getProperty("General.Output", ".")), "solution.xml")); 1340 } catch (Exception e) { 1341 sLog.error("Unable to save solution, reason: " + e.getMessage(), e); 1342 } 1343 1344 saveInfoToXML(solution, iExtra, new File(new File(cfg.getProperty("General.Output", ".")), "info.xml")); 1345 1346 Progress.removeInstance(solution.getModel()); 1347 } catch (Throwable t) { 1348 sLog.error("Test failed.", t); 1349 } 1350 } 1351 } 1352 1353}