001package org.cpsolver.coursett; 002 003import java.io.File; 004import java.io.FileWriter; 005import java.io.IOException; 006import java.io.PrintWriter; 007import java.text.DecimalFormat; 008import java.util.ArrayList; 009import java.util.Collection; 010import java.util.Date; 011import java.util.HashSet; 012import java.util.HashMap; 013import java.util.List; 014import java.util.Locale; 015import java.util.Map; 016import java.util.TreeSet; 017 018import org.apache.log4j.ConsoleAppender; 019import org.apache.log4j.FileAppender; 020import org.apache.log4j.Level; 021import org.apache.log4j.Logger; 022import org.apache.log4j.PatternLayout; 023import org.cpsolver.coursett.constraint.DepartmentSpreadConstraint; 024import org.cpsolver.coursett.constraint.GroupConstraint; 025import org.cpsolver.coursett.constraint.InstructorConstraint; 026import org.cpsolver.coursett.constraint.JenrlConstraint; 027import org.cpsolver.coursett.constraint.RoomConstraint; 028import org.cpsolver.coursett.constraint.SpreadConstraint; 029import org.cpsolver.coursett.criteria.BackToBackInstructorPreferences; 030import org.cpsolver.coursett.criteria.BrokenTimePatterns; 031import org.cpsolver.coursett.criteria.DepartmentBalancingPenalty; 032import org.cpsolver.coursett.criteria.DistributionPreferences; 033import org.cpsolver.coursett.criteria.Perturbations; 034import org.cpsolver.coursett.criteria.RoomPreferences; 035import org.cpsolver.coursett.criteria.SameSubpartBalancingPenalty; 036import org.cpsolver.coursett.criteria.StudentCommittedConflict; 037import org.cpsolver.coursett.criteria.StudentConflict; 038import org.cpsolver.coursett.criteria.StudentDistanceConflict; 039import org.cpsolver.coursett.criteria.StudentHardConflict; 040import org.cpsolver.coursett.criteria.TimePreferences; 041import org.cpsolver.coursett.criteria.TooBigRooms; 042import org.cpsolver.coursett.criteria.UselessHalfHours; 043import org.cpsolver.coursett.heuristics.UniversalPerturbationsCounter; 044import org.cpsolver.coursett.model.Lecture; 045import org.cpsolver.coursett.model.Placement; 046import org.cpsolver.coursett.model.RoomLocation; 047import org.cpsolver.coursett.model.Student; 048import org.cpsolver.coursett.model.TimeLocation; 049import org.cpsolver.coursett.model.TimetableModel; 050import org.cpsolver.ifs.assignment.Assignment; 051import org.cpsolver.ifs.assignment.DefaultParallelAssignment; 052import org.cpsolver.ifs.assignment.DefaultSingleAssignment; 053import org.cpsolver.ifs.extension.ConflictStatistics; 054import org.cpsolver.ifs.extension.Extension; 055import org.cpsolver.ifs.extension.MacPropagation; 056import org.cpsolver.ifs.model.Constraint; 057import org.cpsolver.ifs.solution.Solution; 058import org.cpsolver.ifs.solution.SolutionListener; 059import org.cpsolver.ifs.solver.ParallelSolver; 060import org.cpsolver.ifs.solver.Solver; 061import org.cpsolver.ifs.util.DataProperties; 062import org.cpsolver.ifs.util.Progress; 063import org.cpsolver.ifs.util.ProgressWriter; 064import org.cpsolver.ifs.util.ToolBox; 065 066 067/** 068 * A main class for running of the solver from command line. <br> 069 * <br> 070 * Usage:<br> 071 * java -Xmx1024m -jar coursett1.1.jar config.properties [input_file] 072 * [output_folder]<br> 073 * <br> 074 * See http://www.unitime.org for example configuration files and banchmark data 075 * sets.<br> 076 * <br> 077 * 078 * The test does the following steps: 079 * <ul> 080 * <li>Provided property file is loaded (see {@link DataProperties}). 081 * <li>Output folder is created (General.Output property) and loggings is setup 082 * (using log4j). 083 * <li>Input data are loaded (calling {@link TimetableLoader#load()}). 084 * <li>Solver is executed (see {@link Solver}). 085 * <li>Resultant solution is saved (calling {@link TimetableSaver#save()}, when 086 * General.Save property is set to true. 087 * </ul> 088 * Also, a log and a CSV (comma separated text file) is created in the output 089 * folder. 090 * 091 * @version CourseTT 1.3 (University Course Timetabling)<br> 092 * Copyright (C) 2006 - 2014 Tomas Muller<br> 093 * <a href="mailto:muller@unitime.org">muller@unitime.org</a><br> 094 * <a href="http://muller.unitime.org">http://muller.unitime.org</a><br> 095 * <br> 096 * This library is free software; you can redistribute it and/or modify 097 * it under the terms of the GNU Lesser General Public License as 098 * published by the Free Software Foundation; either version 3 of the 099 * License, or (at your option) any later version. <br> 100 * <br> 101 * This library is distributed in the hope that it will be useful, but 102 * WITHOUT ANY WARRANTY; without even the implied warranty of 103 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 104 * Lesser General Public License for more details. <br> 105 * <br> 106 * You should have received a copy of the GNU Lesser General Public 107 * License along with this library; if not see 108 * <a href='http://www.gnu.org/licenses/'>http://www.gnu.org/licenses/</a>. 109 */ 110 111public class Test implements SolutionListener<Lecture, Placement> { 112 private static java.text.SimpleDateFormat sDateFormat = new java.text.SimpleDateFormat("yyMMdd_HHmmss", 113 java.util.Locale.US); 114 private static java.text.DecimalFormat sDoubleFormat = new java.text.DecimalFormat("0.000", 115 new java.text.DecimalFormatSymbols(Locale.US)); 116 private static org.apache.log4j.Logger sLogger = org.apache.log4j.Logger.getLogger(Test.class); 117 118 private PrintWriter iCSVFile = null; 119 120 private MacPropagation<Lecture, Placement> iProp = null; 121 private ConflictStatistics<Lecture, Placement> iStat = null; 122 private int iLastNotified = -1; 123 124 private boolean initialized = false; 125 private Solver<Lecture, Placement> iSolver = null; 126 127 /** Current version 128 * @return version string 129 **/ 130 public static String getVersionString() { 131 return "IFS Timetable Solver v" + Constants.getVersion() + " build" + Constants.getBuildNumber() + ", " 132 + Constants.getReleaseDate(); 133 } 134 135 /** Solver initialization 136 * @param solver current solver 137 **/ 138 public void init(Solver<Lecture, Placement> solver) { 139 iSolver = solver; 140 solver.currentSolution().addSolutionListener(this); 141 } 142 143 /** 144 * Setup log4j logging 145 * 146 * @param logFile log file 147 * @param debug true if debug messages should be logged (use -Ddebug=true to enable debug message) 148 */ 149 public static void setupLogging(File logFile, boolean debug) { 150 Logger root = Logger.getRootLogger(); 151 ConsoleAppender console = new ConsoleAppender(new PatternLayout("[%t] %m%n")); 152 console.setThreshold(Level.INFO); 153 root.addAppender(console); 154 if (logFile != null) { 155 try { 156 FileAppender file = new FileAppender(new PatternLayout("%d{dd-MMM-yy HH:mm:ss.SSS} [%t] %-5p %c{2}> %m%n"), logFile.getPath(), false); 157 file.setThreshold(Level.DEBUG); 158 root.addAppender(file); 159 } catch (IOException e) { 160 sLogger.fatal("Unable to configure logging, reason: " + e.getMessage(), e); 161 } 162 } 163 if (!debug) 164 root.setLevel(Level.INFO); 165 } 166 167 /** 168 * Return name of the class that is used for loading the data. This class 169 * needs to extend class {@link TimetableLoader}. It can be also defined in 170 * configuration, using TimetableLoader property. 171 **/ 172 private String getTimetableLoaderClass(DataProperties properties) { 173 String loader = properties.getProperty("TimetableLoader"); 174 if (loader != null) 175 return loader; 176 if (properties.getPropertyInt("General.InputVersion", -1) >= 0) 177 return "org.unitime.timetable.solver.TimetableDatabaseLoader"; 178 else 179 return "org.cpsolver.coursett.TimetableXMLLoader"; 180 } 181 182 /** 183 * Return name of the class that is used for loading the data. This class 184 * needs to extend class {@link TimetableSaver}. It can be also defined in 185 * configuration, using TimetableSaver property. 186 **/ 187 private String getTimetableSaverClass(DataProperties properties) { 188 String saver = properties.getProperty("TimetableSaver"); 189 if (saver != null) 190 return saver; 191 if (properties.getPropertyInt("General.InputVersion", -1) >= 0) 192 return "org.unitime.timetable.solver.TimetableDatabaseSaver"; 193 else 194 return "org.cpsolver.coursett.TimetableXMLSaver"; 195 } 196 197 /** 198 * Solver Test 199 * 200 * @param args 201 * command line arguments 202 */ 203 public Test(String[] args) { 204 try { 205 DataProperties properties = ToolBox.loadProperties(new java.io.File(args[0])); 206 properties.putAll(System.getProperties()); 207 properties.setProperty("General.Output", properties.getProperty("General.Output", ".") + File.separator + sDateFormat.format(new Date())); 208 if (args.length > 1) 209 properties.setProperty("General.Input", args[1]); 210 if (args.length > 2) 211 properties.setProperty("General.Output", args[2] + File.separator + (sDateFormat.format(new Date()))); 212 System.out.println("Output folder: " + properties.getProperty("General.Output")); 213 File outDir = new File(properties.getProperty("General.Output", ".")); 214 outDir.mkdirs(); 215 setupLogging(new File(outDir, "debug.log"), "true".equals(System.getProperty("debug", "false"))); 216 217 TimetableModel model = new TimetableModel(properties); 218 int nrSolvers = properties.getPropertyInt("Parallel.NrSolvers", 1); 219 Assignment<Lecture, Placement> assignment = (nrSolvers <= 1 ? new DefaultSingleAssignment<Lecture, Placement>() : new DefaultParallelAssignment<Lecture, Placement>()); 220 Progress.getInstance(model).addProgressListener(new ProgressWriter(System.out)); 221 Solver<Lecture, Placement> solver = (nrSolvers == 1 ? new Solver<Lecture, Placement>(properties) : new ParallelSolver<Lecture, Placement>(properties)); 222 223 TimetableLoader loader = null; 224 try { 225 loader = (TimetableLoader) Class.forName(getTimetableLoaderClass(properties)) 226 .getConstructor(new Class[] { TimetableModel.class, Assignment.class }).newInstance(new Object[] { model, assignment }); 227 } catch (ClassNotFoundException e) { 228 System.err.println(e.getClass().getSimpleName() + ": " + e.getMessage()); 229 loader = new TimetableXMLLoader(model, assignment); 230 } 231 loader.load(); 232 233 solver.setInitalSolution(new Solution<Lecture, Placement>(model, assignment)); 234 init(solver); 235 236 iCSVFile = new PrintWriter(new FileWriter(outDir.toString() + File.separator + "stat.csv")); 237 String colSeparator = ";"; 238 iCSVFile.println("Assigned" 239 + colSeparator 240 + "Assigned[%]" 241 + colSeparator 242 + "Time[min]" 243 + colSeparator 244 + "Iter" 245 + colSeparator 246 + "IterYield[%]" 247 + colSeparator 248 + "Speed[it/s]" 249 + colSeparator 250 + "AddedPert" 251 + colSeparator 252 + "AddedPert[%]" 253 + colSeparator 254 + "HardStudentConf" 255 + colSeparator 256 + "StudentConf" 257 + colSeparator 258 + "DistStudentConf" 259 + colSeparator 260 + "CommitStudentConf" 261 + colSeparator 262 + "TimePref" 263 + colSeparator 264 + "RoomPref" 265 + colSeparator 266 + "DistInstrPref" 267 + colSeparator 268 + "GrConstPref" 269 + colSeparator 270 + "UselessHalfHours" 271 + colSeparator 272 + "BrokenTimePat" 273 + colSeparator 274 + "TooBigRooms" 275 + (iProp != null ? colSeparator + "GoodVars" + colSeparator + "GoodVars[%]" + colSeparator 276 + "GoodVals" + colSeparator + "GoodVals[%]" : "")); 277 iCSVFile.flush(); 278 279 Runtime.getRuntime().addShutdownHook(new ShutdownHook(solver)); 280 281 solver.start(); 282 try { 283 solver.getSolverThread().join(); 284 } catch (InterruptedException e) { 285 } 286 } catch (Throwable t) { 287 sLogger.error("Test failed.", t); 288 } 289 } 290 291 public static void main(String[] args) { 292 new Test(args); 293 } 294 295 @Override 296 public void bestCleared(Solution<Lecture, Placement> solution) { 297 } 298 299 @Override 300 public void bestRestored(Solution<Lecture, Placement> solution) { 301 } 302 303 @Override 304 public void bestSaved(Solution<Lecture, Placement> solution) { 305 notify(solution); 306 if (sLogger.isInfoEnabled()) 307 sLogger.info("**BEST[" + solution.getIteration() + "]** " + ((TimetableModel)solution.getModel()).toString(solution.getAssignment()) + 308 (solution.getFailedIterations() > 0 ? ", F:" + sDoubleFormat.format(100.0 * solution.getFailedIterations() / solution.getIteration()) + "%" : "")); 309 } 310 311 @Override 312 public void getInfo(Solution<Lecture, Placement> solution, Map<String, String> info) { 313 } 314 315 @Override 316 public void getInfo(Solution<Lecture, Placement> solution, Map<String, String> info, Collection<Lecture> variables) { 317 } 318 319 @Override 320 public void solutionUpdated(Solution<Lecture, Placement> solution) { 321 if (!initialized) { 322 for (Extension<Lecture, Placement> extension : iSolver.getExtensions()) { 323 if (MacPropagation.class.isInstance(extension)) 324 iProp = (MacPropagation<Lecture, Placement>) extension; 325 if (ConflictStatistics.class.isInstance(extension)) { 326 iStat = (ConflictStatistics<Lecture, Placement>) extension; 327 } 328 } 329 } 330 } 331 332 /** Add a line into the output CSV file when a enw best solution is found. 333 * @param solution current solution 334 **/ 335 public void notify(Solution<Lecture, Placement> solution) { 336 String colSeparator = ";"; 337 Assignment<Lecture, Placement> assignment = solution.getAssignment(); 338 if (assignment.nrAssignedVariables() < solution.getModel().countVariables() && iLastNotified == assignment.nrAssignedVariables()) 339 return; 340 iLastNotified = assignment.nrAssignedVariables(); 341 if (iCSVFile != null) { 342 TimetableModel model = (TimetableModel) solution.getModel(); 343 iCSVFile.print(model.variables().size() - model.nrUnassignedVariables(assignment)); 344 iCSVFile.print(colSeparator); 345 iCSVFile.print(sDoubleFormat.format(100.0 * assignment.nrAssignedVariables() / model.variables().size())); 346 iCSVFile.print(colSeparator); 347 iCSVFile.print(sDoubleFormat.format((solution.getTime()) / 60.0)); 348 iCSVFile.print(colSeparator); 349 iCSVFile.print(solution.getIteration()); 350 iCSVFile.print(colSeparator); 351 iCSVFile.print(sDoubleFormat.format(100.0 * assignment.nrAssignedVariables() / solution.getIteration())); 352 iCSVFile.print(colSeparator); 353 iCSVFile.print(sDoubleFormat.format((solution.getIteration()) / solution.getTime())); 354 iCSVFile.print(colSeparator); 355 iCSVFile.print(model.perturbVariables(assignment).size()); 356 iCSVFile.print(colSeparator); 357 iCSVFile.print(sDoubleFormat.format(100.0 * model.perturbVariables(assignment).size() / model.variables().size())); 358 iCSVFile.print(colSeparator); 359 iCSVFile.print(Math.round(solution.getModel().getCriterion(StudentHardConflict.class).getValue(assignment))); 360 iCSVFile.print(colSeparator); 361 iCSVFile.print(Math.round(solution.getModel().getCriterion(StudentConflict.class).getValue(assignment))); 362 iCSVFile.print(colSeparator); 363 iCSVFile.print(Math.round(solution.getModel().getCriterion(StudentDistanceConflict.class).getValue(assignment))); 364 iCSVFile.print(colSeparator); 365 iCSVFile.print(Math.round(solution.getModel().getCriterion(StudentCommittedConflict.class).getValue(assignment))); 366 iCSVFile.print(colSeparator); 367 iCSVFile.print(sDoubleFormat.format(solution.getModel().getCriterion(TimePreferences.class).getValue(assignment))); 368 iCSVFile.print(colSeparator); 369 iCSVFile.print(Math.round(solution.getModel().getCriterion(RoomPreferences.class).getValue(assignment))); 370 iCSVFile.print(colSeparator); 371 iCSVFile.print(Math.round(solution.getModel().getCriterion(BackToBackInstructorPreferences.class).getValue(assignment))); 372 iCSVFile.print(colSeparator); 373 iCSVFile.print(Math.round(solution.getModel().getCriterion(DistributionPreferences.class).getValue(assignment))); 374 iCSVFile.print(colSeparator); 375 iCSVFile.print(Math.round(solution.getModel().getCriterion(UselessHalfHours.class).getValue(assignment))); 376 iCSVFile.print(colSeparator); 377 iCSVFile.print(Math.round(solution.getModel().getCriterion(BrokenTimePatterns.class).getValue(assignment))); 378 iCSVFile.print(colSeparator); 379 iCSVFile.print(Math.round(solution.getModel().getCriterion(TooBigRooms.class).getValue(assignment))); 380 if (iProp != null) { 381 if (solution.getModel().nrUnassignedVariables(assignment) > 0) { 382 int goodVariables = 0; 383 long goodValues = 0; 384 long allValues = 0; 385 for (Lecture variable : ((TimetableModel) solution.getModel()).unassignedVariables(assignment)) { 386 goodValues += iProp.goodValues(assignment, variable).size(); 387 allValues += variable.values(solution.getAssignment()).size(); 388 if (!iProp.goodValues(assignment, variable).isEmpty()) 389 goodVariables++; 390 } 391 iCSVFile.print(colSeparator); 392 iCSVFile.print(goodVariables); 393 iCSVFile.print(colSeparator); 394 iCSVFile.print(sDoubleFormat.format(100.0 * goodVariables / solution.getModel().nrUnassignedVariables(assignment))); 395 iCSVFile.print(colSeparator); 396 iCSVFile.print(goodValues); 397 iCSVFile.print(colSeparator); 398 iCSVFile.print(sDoubleFormat.format(100.0 * goodValues / allValues)); 399 } else { 400 iCSVFile.print(colSeparator); 401 iCSVFile.print(colSeparator); 402 iCSVFile.print(colSeparator); 403 iCSVFile.print(colSeparator); 404 } 405 } 406 iCSVFile.println(); 407 iCSVFile.flush(); 408 } 409 } 410 411 /** Print room utilization 412 * @param pw writer 413 * @param model problem model 414 * @param assignment current assignment 415 **/ 416 public static void printRoomInfo(PrintWriter pw, TimetableModel model, Assignment<Lecture, Placement> assignment) { 417 pw.println("Room info:"); 418 pw.println("id, name, size, used_day, used_total"); 419 int firstDaySlot = model.getProperties().getPropertyInt("General.FirstDaySlot", Constants.DAY_SLOTS_FIRST); 420 int lastDaySlot = model.getProperties().getPropertyInt("General.LastDaySlot", Constants.DAY_SLOTS_LAST); 421 int firstWorkDay = model.getProperties().getPropertyInt("General.FirstWorkDay", 0); 422 int lastWorkDay = model.getProperties().getPropertyInt("General.LastWorkDay", Constants.NR_DAYS_WEEK - 1); 423 if (lastWorkDay < firstWorkDay) lastWorkDay += 7; 424 for (RoomConstraint rc : model.getRoomConstraints()) { 425 int used_day = 0; 426 int used_total = 0; 427 for (int day = firstWorkDay; day <= lastWorkDay; day++) { 428 for (int time = firstDaySlot; time <= lastDaySlot; time++) { 429 if (!rc.getContext(assignment).getPlacements((day % 7) * Constants.SLOTS_PER_DAY + time).isEmpty()) 430 used_day++; 431 } 432 } 433 for (int day = 0; day < Constants.DAY_CODES.length; day++) { 434 for (int time = 0; time < Constants.SLOTS_PER_DAY; time++) { 435 if (!rc.getContext(assignment).getPlacements((day % 7) * Constants.SLOTS_PER_DAY + time).isEmpty()) 436 used_total++; 437 } 438 } 439 pw.println(rc.getResourceId() + "," + rc.getName() + "," + rc.getCapacity() + "," + used_day + "," + used_total); 440 } 441 } 442 443 /** Class information 444 * @param pw writer 445 * @param model problem model 446 **/ 447 public static void printClassInfo(PrintWriter pw, TimetableModel model) { 448 pw.println("Class info:"); 449 pw.println("id, name, min_class_limit, max_class_limit, room2limit_ratio, half_hours"); 450 for (Lecture lecture : model.variables()) { 451 TimeLocation time = lecture.timeLocations().get(0); 452 pw.println(lecture.getClassId() + "," + lecture.getName() + "," + lecture.minClassLimit() + "," 453 + lecture.maxClassLimit() + "," + lecture.roomToLimitRatio() + "," 454 + (time.getNrSlotsPerMeeting() * time.getNrMeetings())); 455 } 456 } 457 458 /** Create info.txt with some more information about the problem 459 * @param solution current solution 460 * @throws IOException an exception that may be thrown 461 **/ 462 public static void printSomeStuff(Solution<Lecture, Placement> solution) throws IOException { 463 TimetableModel model = (TimetableModel) solution.getModel(); 464 Assignment<Lecture, Placement> assignment = solution.getAssignment(); 465 File outDir = new File(model.getProperties().getProperty("General.Output", ".")); 466 PrintWriter pw = new PrintWriter(new FileWriter(outDir.toString() + File.separator + "info.txt")); 467 PrintWriter pwi = new PrintWriter(new FileWriter(outDir.toString() + File.separator + "info.csv")); 468 String name = new File(model.getProperties().getProperty("General.Input")).getName(); 469 pwi.println("Instance," + name.substring(0, name.lastIndexOf('.'))); 470 pw.println("Solution info: " + ToolBox.dict2string(solution.getInfo(), 1)); 471 pw.println("Bounds: " + ToolBox.dict2string(model.getBounds(assignment), 1)); 472 Map<String, String> info = solution.getInfo(); 473 for (String key : new TreeSet<String>(info.keySet())) { 474 if (key.equals("Memory usage")) 475 continue; 476 if (key.equals("Iteration")) 477 continue; 478 if (key.equals("Time")) 479 continue; 480 String value = info.get(key); 481 if (value.indexOf(' ') > 0) 482 value = value.substring(0, value.indexOf(' ')); 483 pwi.println(key + "," + value); 484 } 485 printRoomInfo(pw, model, assignment); 486 printClassInfo(pw, model); 487 long nrValues = 0; 488 long nrTimes = 0; 489 long nrRooms = 0; 490 double totalMaxNormTimePref = 0.0; 491 double totalMinNormTimePref = 0.0; 492 double totalNormTimePref = 0.0; 493 int totalMaxRoomPref = 0; 494 int totalMinRoomPref = 0; 495 int totalRoomPref = 0; 496 long nrStudentEnrls = 0; 497 long nrInevitableStudentConflicts = 0; 498 long nrJenrls = 0; 499 int nrHalfHours = 0; 500 int nrMeetings = 0; 501 int totalMinLimit = 0; 502 int totalMaxLimit = 0; 503 long nrReqRooms = 0; 504 int nrSingleValueVariables = 0; 505 int nrSingleTimeVariables = 0; 506 int nrSingleRoomVariables = 0; 507 long totalAvailableMinRoomSize = 0; 508 long totalAvailableMaxRoomSize = 0; 509 long totalRoomSize = 0; 510 long nrOneOrMoreRoomVariables = 0; 511 long nrOneRoomVariables = 0; 512 HashSet<Student> students = new HashSet<Student>(); 513 HashSet<Long> offerings = new HashSet<Long>(); 514 HashSet<Long> configs = new HashSet<Long>(); 515 HashSet<Long> subparts = new HashSet<Long>(); 516 int[] sizeLimits = new int[] { 0, 25, 50, 75, 100, 150, 200, 400 }; 517 int[] nrRoomsOfSize = new int[sizeLimits.length]; 518 int[] minRoomOfSize = new int[sizeLimits.length]; 519 int[] maxRoomOfSize = new int[sizeLimits.length]; 520 int[] totalUsedSlots = new int[sizeLimits.length]; 521 int[] totalUsedSeats = new int[sizeLimits.length]; 522 int[] totalUsedSeats2 = new int[sizeLimits.length]; 523 int firstDaySlot = model.getProperties().getPropertyInt("General.FirstDaySlot", Constants.DAY_SLOTS_FIRST); 524 int lastDaySlot = model.getProperties().getPropertyInt("General.LastDaySlot", Constants.DAY_SLOTS_LAST); 525 int firstWorkDay = model.getProperties().getPropertyInt("General.FirstWorkDay", 0); 526 int lastWorkDay = model.getProperties().getPropertyInt("General.LastWorkDay", Constants.NR_DAYS_WEEK - 1); 527 if (lastWorkDay < firstWorkDay) lastWorkDay += 7; 528 for (Lecture lect : model.variables()) { 529 if (lect.getConfiguration() != null) { 530 offerings.add(lect.getConfiguration().getOfferingId()); 531 configs.add(lect.getConfiguration().getConfigId()); 532 } 533 subparts.add(lect.getSchedulingSubpartId()); 534 nrStudentEnrls += (lect.students() == null ? 0 : lect.students().size()); 535 students.addAll(lect.students()); 536 nrValues += lect.values(solution.getAssignment()).size(); 537 nrReqRooms += lect.getNrRooms(); 538 for (RoomLocation room: lect.roomLocations()) 539 if (room.getPreference() < Constants.sPreferenceLevelProhibited / 2) 540 nrRooms++; 541 for (TimeLocation time: lect.timeLocations()) 542 if (time.getPreference() < Constants.sPreferenceLevelProhibited / 2) 543 nrTimes ++; 544 totalMinLimit += lect.minClassLimit(); 545 totalMaxLimit += lect.maxClassLimit(); 546 if (!lect.values(solution.getAssignment()).isEmpty()) { 547 Placement p = lect.values(solution.getAssignment()).get(0); 548 nrMeetings += p.getTimeLocation().getNrMeetings(); 549 nrHalfHours += p.getTimeLocation().getNrMeetings() * p.getTimeLocation().getNrSlotsPerMeeting(); 550 totalMaxNormTimePref += lect.getMinMaxTimePreference()[1]; 551 totalMinNormTimePref += lect.getMinMaxTimePreference()[0]; 552 totalNormTimePref += Math.abs(lect.getMinMaxTimePreference()[1] - lect.getMinMaxTimePreference()[0]); 553 totalMaxRoomPref += lect.getMinMaxRoomPreference()[1]; 554 totalMinRoomPref += lect.getMinMaxRoomPreference()[0]; 555 totalRoomPref += Math.abs(lect.getMinMaxRoomPreference()[1] - lect.getMinMaxRoomPreference()[0]); 556 TimeLocation time = p.getTimeLocation(); 557 boolean hasRoomConstraint = false; 558 for (RoomLocation roomLocation : lect.roomLocations()) { 559 if (roomLocation.getRoomConstraint().getConstraint()) 560 hasRoomConstraint = true; 561 } 562 if (hasRoomConstraint && lect.getNrRooms() > 0) { 563 for (int d = firstWorkDay; d <= lastWorkDay; d++) { 564 if ((time.getDayCode() & Constants.DAY_CODES[d % 7]) == 0) 565 continue; 566 for (int t = Math.max(time.getStartSlot(), firstDaySlot); t <= Math.min(time.getStartSlot() + time.getLength() - 1, lastDaySlot); t++) { 567 for (int l = 0; l < sizeLimits.length; l++) { 568 if (sizeLimits[l] <= lect.minRoomSize()) { 569 totalUsedSlots[l] += lect.getNrRooms(); 570 totalUsedSeats[l] += lect.classLimit(assignment); 571 totalUsedSeats2[l] += lect.minRoomSize() * lect.getNrRooms(); 572 } 573 } 574 } 575 } 576 } 577 } 578 if (lect.values(solution.getAssignment()).size() == 1) { 579 nrSingleValueVariables++; 580 } 581 if (lect.timeLocations().size() == 1) { 582 nrSingleTimeVariables++; 583 } 584 if (lect.roomLocations().size() == 1) { 585 nrSingleRoomVariables++; 586 } 587 if (lect.getNrRooms() == 1) { 588 nrOneRoomVariables++; 589 } 590 if (lect.getNrRooms() > 0) { 591 nrOneOrMoreRoomVariables++; 592 } 593 if (!lect.roomLocations().isEmpty()) { 594 int minRoomSize = Integer.MAX_VALUE; 595 int maxRoomSize = Integer.MIN_VALUE; 596 for (RoomLocation rl : lect.roomLocations()) { 597 minRoomSize = Math.min(minRoomSize, rl.getRoomSize()); 598 maxRoomSize = Math.max(maxRoomSize, rl.getRoomSize()); 599 totalRoomSize += rl.getRoomSize(); 600 } 601 totalAvailableMinRoomSize += minRoomSize; 602 totalAvailableMaxRoomSize += maxRoomSize; 603 } 604 } 605 for (JenrlConstraint jenrl : model.getJenrlConstraints()) { 606 nrJenrls += jenrl.getJenrl(); 607 if ((jenrl.first()).timeLocations().size() == 1 && (jenrl.second()).timeLocations().size() == 1) { 608 TimeLocation t1 = jenrl.first().timeLocations().get(0); 609 TimeLocation t2 = jenrl.second().timeLocations().get(0); 610 if (t1.hasIntersection(t2)) { 611 nrInevitableStudentConflicts += jenrl.getJenrl(); 612 pw.println("Inevitable " + jenrl.getJenrl() + " student conflicts between " + jenrl.first() + " " 613 + t1 + " and " + jenrl.second() + " " + t2); 614 } else if (jenrl.first().values(solution.getAssignment()).size() == 1 && jenrl.second().values(solution.getAssignment()).size() == 1) { 615 Placement p1 = jenrl.first().values(solution.getAssignment()).get(0); 616 Placement p2 = jenrl.second().values(solution.getAssignment()).get(0); 617 if (JenrlConstraint.isInConflict(p1, p2, ((TimetableModel)p1.variable().getModel()).getDistanceMetric(), ((TimetableModel)p1.variable().getModel()).getStudentWorkDayLimit())) { 618 nrInevitableStudentConflicts += jenrl.getJenrl(); 619 pw.println("Inevitable " + jenrl.getJenrl() 620 + (p1.getTimeLocation().hasIntersection(p2.getTimeLocation()) ? "" : " distance") 621 + " student conflicts between " + p1 + " and " + p2); 622 } 623 } 624 } 625 } 626 int totalCommitedPlacements = 0; 627 for (Student student : students) { 628 if (student.getCommitedPlacements() != null) 629 totalCommitedPlacements += student.getCommitedPlacements().size(); 630 } 631 pw.println("Total number of classes: " + model.variables().size()); 632 pwi.println("Number of classes," + model.variables().size()); 633 pw.println("Total number of instructional offerings: " + offerings.size() + " (" 634 + sDoubleFormat.format(100.0 * offerings.size() / model.variables().size()) + "%)"); 635 // pwi.println("Number of instructional offerings,"+offerings.size()); 636 pw.println("Total number of configurations: " + configs.size() + " (" 637 + sDoubleFormat.format(100.0 * configs.size() / model.variables().size()) + "%)"); 638 pw.println("Total number of scheduling subparts: " + subparts.size() + " (" 639 + sDoubleFormat.format(100.0 * subparts.size() / model.variables().size()) + "%)"); 640 // pwi.println("Number of scheduling subparts,"+subparts.size()); 641 pw.println("Average number classes per subpart: " 642 + sDoubleFormat.format(1.0 * model.variables().size() / subparts.size())); 643 pwi.println("Avg. classes per instruction," 644 + sDoubleFormat.format(1.0 * model.variables().size() / subparts.size())); 645 pw.println("Average number classes per config: " 646 + sDoubleFormat.format(1.0 * model.variables().size() / configs.size())); 647 pw.println("Average number classes per offering: " 648 + sDoubleFormat.format(1.0 * model.variables().size() / offerings.size())); 649 pw.println("Total number of classes with only one value: " + nrSingleValueVariables + " (" 650 + sDoubleFormat.format(100.0 * nrSingleValueVariables / model.variables().size()) + "%)"); 651 pw.println("Total number of classes with only one time: " + nrSingleTimeVariables + " (" 652 + sDoubleFormat.format(100.0 * nrSingleTimeVariables / model.variables().size()) + "%)"); 653 pw.println("Total number of classes with only one room: " + nrSingleRoomVariables + " (" 654 + sDoubleFormat.format(100.0 * nrSingleRoomVariables / model.variables().size()) + "%)"); 655 pwi.println("Classes with single value," + nrSingleValueVariables); 656 // pwi.println("Classes with only one time/room,"+nrSingleTimeVariables+"/"+nrSingleRoomVariables); 657 pw.println("Total number of classes requesting no room: " 658 + (model.variables().size() - nrOneOrMoreRoomVariables) 659 + " (" 660 + sDoubleFormat.format(100.0 * (model.variables().size() - nrOneOrMoreRoomVariables) 661 / model.variables().size()) + "%)"); 662 pw.println("Total number of classes requesting one room: " + nrOneRoomVariables + " (" 663 + sDoubleFormat.format(100.0 * nrOneRoomVariables / model.variables().size()) + "%)"); 664 pw.println("Total number of classes requesting one or more rooms: " + nrOneOrMoreRoomVariables + " (" 665 + sDoubleFormat.format(100.0 * nrOneOrMoreRoomVariables / model.variables().size()) + "%)"); 666 // pwi.println("% classes requesting no room,"+sDoubleFormat.format(100.0*(model.variables().size()-nrOneOrMoreRoomVariables)/model.variables().size())+"%"); 667 // pwi.println("% classes requesting one room,"+sDoubleFormat.format(100.0*nrOneRoomVariables/model.variables().size())+"%"); 668 // pwi.println("% classes requesting two or more rooms,"+sDoubleFormat.format(100.0*(nrOneOrMoreRoomVariables-nrOneRoomVariables)/model.variables().size())+"%"); 669 pw.println("Average number of requested rooms: " 670 + sDoubleFormat.format(1.0 * nrReqRooms / model.variables().size())); 671 pw.println("Average minimal class limit: " 672 + sDoubleFormat.format(1.0 * totalMinLimit / model.variables().size())); 673 pw.println("Average maximal class limit: " 674 + sDoubleFormat.format(1.0 * totalMaxLimit / model.variables().size())); 675 // pwi.println("Average class limit,"+sDoubleFormat.format(1.0*(totalMinLimit+totalMaxLimit)/(2*model.variables().size()))); 676 pw.println("Average number of placements: " + sDoubleFormat.format(1.0 * nrValues / model.variables().size())); 677 // pwi.println("Average domain size,"+sDoubleFormat.format(1.0*nrValues/model.variables().size())); 678 pwi.println("Avg. domain size," + sDoubleFormat.format(1.0 * nrValues / model.variables().size())); 679 pw.println("Average number of time locations: " 680 + sDoubleFormat.format(1.0 * nrTimes / model.variables().size())); 681 pwi.println("Avg. number of avail. times/rooms," 682 + sDoubleFormat.format(1.0 * nrTimes / model.variables().size()) + "/" 683 + sDoubleFormat.format(1.0 * nrRooms / model.variables().size())); 684 pw.println("Average number of room locations: " 685 + sDoubleFormat.format(1.0 * nrRooms / model.variables().size())); 686 pw.println("Average minimal requested room size: " 687 + sDoubleFormat.format(1.0 * totalAvailableMinRoomSize / nrOneOrMoreRoomVariables)); 688 pw.println("Average maximal requested room size: " 689 + sDoubleFormat.format(1.0 * totalAvailableMaxRoomSize / nrOneOrMoreRoomVariables)); 690 pw.println("Average requested room sizes: " + sDoubleFormat.format(1.0 * totalRoomSize / nrRooms)); 691 pwi.println("Average requested room size," + sDoubleFormat.format(1.0 * totalRoomSize / nrRooms)); 692 pw.println("Average maximum normalized time preference: " 693 + sDoubleFormat.format(totalMaxNormTimePref / model.variables().size())); 694 pw.println("Average minimum normalized time preference: " 695 + sDoubleFormat.format(totalMinNormTimePref / model.variables().size())); 696 pw.println("Average normalized time preference," 697 + sDoubleFormat.format(totalNormTimePref / model.variables().size())); 698 pw.println("Average maximum room preferences: " 699 + sDoubleFormat.format(1.0 * totalMaxRoomPref / nrOneOrMoreRoomVariables)); 700 pw.println("Average minimum room preferences: " 701 + sDoubleFormat.format(1.0 * totalMinRoomPref / nrOneOrMoreRoomVariables)); 702 pw.println("Average room preferences," + sDoubleFormat.format(1.0 * totalRoomPref / nrOneOrMoreRoomVariables)); 703 pw.println("Total number of students:" + students.size()); 704 pwi.println("Number of students," + students.size()); 705 pwi.println("Number of inevitable student conflicts," + nrInevitableStudentConflicts); 706 pw.println("Total amount of student enrollments: " + nrStudentEnrls); 707 pwi.println("Number of student enrollments," + nrStudentEnrls); 708 pw.println("Total amount of joined enrollments: " + nrJenrls); 709 pwi.println("Number of joint student enrollments," + nrJenrls); 710 pw.println("Average number of students: " 711 + sDoubleFormat.format(1.0 * students.size() / model.variables().size())); 712 pw.println("Average number of enrollemnts (per student): " 713 + sDoubleFormat.format(1.0 * nrStudentEnrls / students.size())); 714 pwi.println("Avg. number of classes per student," 715 + sDoubleFormat.format(1.0 * nrStudentEnrls / students.size())); 716 pwi.println("Avg. number of committed classes per student," 717 + sDoubleFormat.format(1.0 * totalCommitedPlacements / students.size())); 718 pw.println("Total amount of inevitable student conflicts: " + nrInevitableStudentConflicts + " (" 719 + sDoubleFormat.format(100.0 * nrInevitableStudentConflicts / nrStudentEnrls) + "%)"); 720 pw.println("Average number of meetings (per class): " 721 + sDoubleFormat.format(1.0 * nrMeetings / model.variables().size())); 722 pw.println("Average number of hours per class: " 723 + sDoubleFormat.format(1.0 * nrHalfHours / model.variables().size() / 12.0)); 724 pwi.println("Avg. number of meetings per class," 725 + sDoubleFormat.format(1.0 * nrMeetings / model.variables().size())); 726 pwi.println("Avg. number of hours per class," 727 + sDoubleFormat.format(1.0 * nrHalfHours / model.variables().size() / 12.0)); 728 int minRoomSize = Integer.MAX_VALUE; 729 int maxRoomSize = Integer.MIN_VALUE; 730 int nrDistancePairs = 0; 731 double maxRoomDistance = Double.MIN_VALUE; 732 double totalRoomDistance = 0.0; 733 int[] totalAvailableSlots = new int[sizeLimits.length]; 734 int[] totalAvailableSeats = new int[sizeLimits.length]; 735 int nrOfRooms = 0; 736 totalRoomSize = 0; 737 for (RoomConstraint rc : model.getRoomConstraints()) { 738 if (rc.variables().isEmpty()) continue; 739 nrOfRooms++; 740 minRoomSize = Math.min(minRoomSize, rc.getCapacity()); 741 maxRoomSize = Math.max(maxRoomSize, rc.getCapacity()); 742 for (int l = 0; l < sizeLimits.length; l++) { 743 if (sizeLimits[l] <= rc.getCapacity() 744 && (l + 1 == sizeLimits.length || rc.getCapacity() < sizeLimits[l + 1])) { 745 nrRoomsOfSize[l]++; 746 if (minRoomOfSize[l] == 0) 747 minRoomOfSize[l] = rc.getCapacity(); 748 else 749 minRoomOfSize[l] = Math.min(minRoomOfSize[l], rc.getCapacity()); 750 if (maxRoomOfSize[l] == 0) 751 maxRoomOfSize[l] = rc.getCapacity(); 752 else 753 maxRoomOfSize[l] = Math.max(maxRoomOfSize[l], rc.getCapacity()); 754 } 755 } 756 totalRoomSize += rc.getCapacity(); 757 if (rc.getPosX() != null && rc.getPosY() != null) { 758 for (RoomConstraint rc2 : model.getRoomConstraints()) { 759 if (rc2.getResourceId().compareTo(rc.getResourceId()) > 0 && rc2.getPosX() != null && rc2.getPosY() != null) { 760 double distance = ((TimetableModel)solution.getModel()).getDistanceMetric().getDistanceInMinutes(rc.getId(), rc.getPosX(), rc.getPosY(), rc2.getId(), rc2.getPosX(), rc2.getPosY()); 761 totalRoomDistance += distance; 762 nrDistancePairs++; 763 maxRoomDistance = Math.max(maxRoomDistance, distance); 764 } 765 } 766 } 767 for (int d = firstWorkDay; d <= lastWorkDay; d++) { 768 for (int t = firstDaySlot; t <= lastDaySlot; t++) { 769 if (rc.isAvailable((d % 7) * Constants.SLOTS_PER_DAY + t)) { 770 for (int l = 0; l < sizeLimits.length; l++) { 771 if (sizeLimits[l] <= rc.getCapacity()) { 772 totalAvailableSlots[l]++; 773 totalAvailableSeats[l] += rc.getCapacity(); 774 } 775 } 776 } 777 } 778 } 779 } 780 pw.println("Total number of rooms: " + nrOfRooms); 781 pwi.println("Number of rooms," + nrOfRooms); 782 pw.println("Minimal room size: " + minRoomSize); 783 pw.println("Maximal room size: " + maxRoomSize); 784 pwi.println("Room size min/max," + minRoomSize + "/" + maxRoomSize); 785 pw.println("Average room size: " 786 + sDoubleFormat.format(1.0 * totalRoomSize / model.getRoomConstraints().size())); 787 pw.println("Maximal distance between two rooms: " + sDoubleFormat.format(maxRoomDistance)); 788 pw.println("Average distance between two rooms: " 789 + sDoubleFormat.format(totalRoomDistance / nrDistancePairs)); 790 pwi.println("Average distance between two rooms [min]," 791 + sDoubleFormat.format(totalRoomDistance / nrDistancePairs)); 792 pwi.println("Maximal distance between two rooms [min]," + sDoubleFormat.format(maxRoomDistance)); 793 for (int l = 0; l < sizeLimits.length; l++) {// sizeLimits.length;l++) { 794 pwi.println("\"Room frequency (size>=" + sizeLimits[l] + ", used/avaiable times)\"," 795 + sDoubleFormat.format(100.0 * totalUsedSlots[l] / totalAvailableSlots[l]) + "%"); 796 pwi.println("\"Room utilization (size>=" + sizeLimits[l] + ", used/available seats)\"," 797 + sDoubleFormat.format(100.0 * totalUsedSeats[l] / totalAvailableSeats[l]) + "%"); 798 pwi.println("\"Number of rooms (size>=" + sizeLimits[l] + ")\"," + nrRoomsOfSize[l]); 799 pwi.println("\"Min/max room size (size>=" + sizeLimits[l] + ")\"," + minRoomOfSize[l] + "-" 800 + maxRoomOfSize[l]); 801 // pwi.println("\"Room utilization (size>="+sizeLimits[l]+", minRoomSize)\","+sDoubleFormat.format(100.0*totalUsedSeats2[l]/totalAvailableSeats[l])+"%"); 802 } 803 pw.println("Average hours available: " 804 + sDoubleFormat.format(1.0 * totalAvailableSlots[0] / nrOfRooms / 12.0)); 805 int totalInstructedClasses = 0; 806 for (InstructorConstraint ic : model.getInstructorConstraints()) { 807 totalInstructedClasses += ic.variables().size(); 808 } 809 pw.println("Total number of instructors: " + model.getInstructorConstraints().size()); 810 pwi.println("Number of instructors," + model.getInstructorConstraints().size()); 811 pw.println("Total class-instructor assignments: " + totalInstructedClasses + " (" 812 + sDoubleFormat.format(100.0 * totalInstructedClasses / model.variables().size()) + "%)"); 813 pwi.println("Number of class-instructor assignments," + totalInstructedClasses); 814 pw.println("Average classes per instructor: " 815 + sDoubleFormat.format(1.0 * totalInstructedClasses / model.getInstructorConstraints().size())); 816 pwi.println("Average classes per instructor," 817 + sDoubleFormat.format(1.0 * totalInstructedClasses / model.getInstructorConstraints().size())); 818 // pw.println("Average hours available: "+sDoubleFormat.format(1.0*totalAvailableSlots/model.getInstructorConstraints().size()/12.0)); 819 // pwi.println("Instructor availability [h],"+sDoubleFormat.format(1.0*totalAvailableSlots/model.getInstructorConstraints().size()/12.0)); 820 int nrGroupConstraints = model.getGroupConstraints().size() + model.getSpreadConstraints().size(); 821 int nrHardGroupConstraints = 0; 822 int nrVarsInGroupConstraints = 0; 823 for (GroupConstraint gc : model.getGroupConstraints()) { 824 if (gc.isHard()) 825 nrHardGroupConstraints++; 826 nrVarsInGroupConstraints += gc.variables().size(); 827 } 828 for (SpreadConstraint sc : model.getSpreadConstraints()) { 829 nrVarsInGroupConstraints += sc.variables().size(); 830 } 831 pw.println("Total number of group constraints: " + nrGroupConstraints + " (" 832 + sDoubleFormat.format(100.0 * nrGroupConstraints / model.variables().size()) + "%)"); 833 // pwi.println("Number of group constraints,"+nrGroupConstraints); 834 pw.println("Total number of hard group constraints: " + nrHardGroupConstraints + " (" 835 + sDoubleFormat.format(100.0 * nrHardGroupConstraints / model.variables().size()) + "%)"); 836 // pwi.println("Number of hard group constraints,"+nrHardGroupConstraints); 837 pw.println("Average classes per group constraint: " 838 + sDoubleFormat.format(1.0 * nrVarsInGroupConstraints / nrGroupConstraints)); 839 // pwi.println("Average classes per group constraint,"+sDoubleFormat.format(1.0*nrVarsInGroupConstraints/nrGroupConstraints)); 840 pwi.println("Avg. number distribution constraints per class," 841 + sDoubleFormat.format(1.0 * nrVarsInGroupConstraints / model.variables().size())); 842 pwi.println("Joint enrollment constraints," + model.getJenrlConstraints().size()); 843 pw.flush(); 844 pw.close(); 845 pwi.flush(); 846 pwi.close(); 847 } 848 849 public static void saveOutputCSV(Solution<Lecture, Placement> s, File file) { 850 try { 851 DecimalFormat dx = new DecimalFormat("000"); 852 PrintWriter w = new PrintWriter(new FileWriter(file)); 853 TimetableModel m = (TimetableModel) s.getModel(); 854 int firstDaySlot = m.getProperties().getPropertyInt("General.FirstDaySlot", Constants.DAY_SLOTS_FIRST); 855 int lastDaySlot = m.getProperties().getPropertyInt("General.LastDaySlot", Constants.DAY_SLOTS_LAST); 856 int firstWorkDay = m.getProperties().getPropertyInt("General.FirstWorkDay", 0); 857 int lastWorkDay = m.getProperties().getPropertyInt("General.LastWorkDay", Constants.NR_DAYS_WEEK - 1); 858 if (lastWorkDay < firstWorkDay) lastWorkDay += 7; 859 Assignment<Lecture, Placement> a = s.getAssignment(); 860 int idx = 1; 861 w.println("000." + dx.format(idx++) + " Assigned variables," + a.nrAssignedVariables()); 862 w.println("000." + dx.format(idx++) + " Time [sec]," + sDoubleFormat.format(s.getBestTime())); 863 w.println("000." + dx.format(idx++) + " Hard student conflicts," + Math.round(m.getCriterion(StudentHardConflict.class).getValue(a))); 864 if (m.getProperties().getPropertyBoolean("General.UseDistanceConstraints", true)) 865 w.println("000." + dx.format(idx++) + " Distance student conf.," + Math.round(m.getCriterion(StudentDistanceConflict.class).getValue(a))); 866 w.println("000." + dx.format(idx++) + " Student conflicts," + Math.round(m.getCriterion(StudentConflict.class).getValue(a))); 867 w.println("000." + dx.format(idx++) + " Committed student conflicts," + Math.round(m.getCriterion(StudentCommittedConflict.class).getValue(a))); 868 w.println("000." + dx.format(idx++) + " All Student conflicts," 869 + Math.round(m.getCriterion(StudentConflict.class).getValue(a) + m.getCriterion(StudentCommittedConflict.class).getValue(a))); 870 w.println("000." + dx.format(idx++) + " Time preferences," 871 + sDoubleFormat.format( m.getCriterion(TimePreferences.class).getValue(a))); 872 w.println("000." + dx.format(idx++) + " Room preferences," + Math.round(m.getCriterion(RoomPreferences.class).getValue(a))); 873 w.println("000." + dx.format(idx++) + " Useless half-hours," + Math.round(m.getCriterion(UselessHalfHours.class).getValue(a))); 874 w.println("000." + dx.format(idx++) + " Broken time patterns," + Math.round(m.getCriterion(BrokenTimePatterns.class).getValue(a))); 875 w.println("000." + dx.format(idx++) + " Too big room," + Math.round(m.getCriterion(TooBigRooms.class).getValue(a))); 876 w.println("000." + dx.format(idx++) + " Distribution preferences," + sDoubleFormat.format(m.getCriterion(DistributionPreferences.class).getValue(a))); 877 if (m.getProperties().getPropertyBoolean("General.UseDistanceConstraints", true)) 878 w.println("000." + dx.format(idx++) + " Back-to-back instructor pref.," + Math.round(m.getCriterion(BackToBackInstructorPreferences.class).getValue(a))); 879 if (m.getProperties().getPropertyBoolean("General.DeptBalancing", true)) { 880 w.println("000." + dx.format(idx++) + " Dept. balancing penalty," + sDoubleFormat.format(m.getCriterion(DepartmentBalancingPenalty.class).getValue(a))); 881 } 882 w.println("000." + dx.format(idx++) + " Same subpart balancing penalty," + sDoubleFormat.format(m.getCriterion(SameSubpartBalancingPenalty.class).getValue(a))); 883 if (m.getProperties().getPropertyBoolean("General.MPP", false)) { 884 Map<String, Double> mppInfo = ((UniversalPerturbationsCounter)((Perturbations)m.getCriterion(Perturbations.class)).getPerturbationsCounter()).getCompactInfo(a, m, false, false); 885 int pidx = 51; 886 w.println("000." + dx.format(pidx++) + " Perturbation penalty," + sDoubleFormat.format(m.getCriterion(Perturbations.class).getValue(a))); 887 w.println("000." + dx.format(pidx++) + " Additional perturbations," + m.perturbVariables(a).size()); 888 int nrPert = 0, nrStudentPert = 0; 889 for (Lecture lecture : m.variables()) { 890 if (lecture.getInitialAssignment() != null) 891 continue; 892 nrPert++; 893 nrStudentPert += lecture.classLimit(a); 894 } 895 w.println("000." + dx.format(pidx++) + " Given perturbations," + nrPert); 896 w.println("000." + dx.format(pidx++) + " Given student perturbations," + nrStudentPert); 897 for (String key : new TreeSet<String>(mppInfo.keySet())) { 898 Double value = mppInfo.get(key); 899 w.println("000." + dx.format(pidx++) + " " + key + "," + sDoubleFormat.format(value)); 900 } 901 } 902 HashSet<Student> students = new HashSet<Student>(); 903 int enrls = 0; 904 int minRoomPref = 0, maxRoomPref = 0; 905 int minGrPref = 0, maxGrPref = 0; 906 int minTimePref = 0, maxTimePref = 0; 907 int worstInstrPref = 0; 908 HashSet<Constraint<Lecture, Placement>> used = new HashSet<Constraint<Lecture, Placement>>(); 909 for (Lecture lecture : m.variables()) { 910 enrls += (lecture.students() == null ? 0 : lecture.students().size()); 911 students.addAll(lecture.students()); 912 913 int[] minMaxRoomPref = lecture.getMinMaxRoomPreference(); 914 maxRoomPref += minMaxRoomPref[1] - minMaxRoomPref[0]; 915 916 double[] minMaxTimePref = lecture.getMinMaxTimePreference(); 917 maxTimePref += minMaxTimePref[1] - minMaxTimePref[0]; 918 for (Constraint<Lecture, Placement> c : lecture.constraints()) { 919 if (!used.add(c)) 920 continue; 921 922 if (c instanceof InstructorConstraint) { 923 InstructorConstraint ic = (InstructorConstraint) c; 924 worstInstrPref += ic.getWorstPreference(); 925 } 926 927 if (c instanceof GroupConstraint) { 928 GroupConstraint gc = (GroupConstraint) c; 929 if (gc.isHard()) 930 continue; 931 maxGrPref += Math.abs(gc.getPreference()) * (1 + (gc.variables().size() * (gc.variables().size() - 1)) / 2); 932 } 933 } 934 } 935 int totalCommitedPlacements = 0; 936 for (Student student : students) { 937 if (student.getCommitedPlacements() != null) 938 totalCommitedPlacements += student.getCommitedPlacements().size(); 939 } 940 HashMap<Long, List<Lecture>> subs = new HashMap<Long, List<Lecture>>(); 941 for (Lecture lecture : m.variables()) { 942 if (lecture.isCommitted() || lecture.getScheduler() == null) 943 continue; 944 List<Lecture> vars = subs.get(lecture.getScheduler()); 945 if (vars == null) { 946 vars = new ArrayList<Lecture>(); 947 subs.put(lecture.getScheduler(), vars); 948 } 949 vars.add(lecture); 950 } 951 int bidx = 101; 952 w.println("000." + dx.format(bidx++) + " Assigned variables max," + m.variables().size()); 953 w.println("000." + dx.format(bidx++) + " Student enrollments," + enrls); 954 w.println("000." + dx.format(bidx++) + " Student commited enrollments," + totalCommitedPlacements); 955 w.println("000." + dx.format(bidx++) + " All student enrollments," + (enrls + totalCommitedPlacements)); 956 w.println("000." + dx.format(bidx++) + " Time preferences min," + minTimePref); 957 w.println("000." + dx.format(bidx++) + " Time preferences max," + maxTimePref); 958 w.println("000." + dx.format(bidx++) + " Room preferences min," + minRoomPref); 959 w.println("000." + dx.format(bidx++) + " Room preferences max," + maxRoomPref); 960 w.println("000." + dx.format(bidx++) + " Useless half-hours max," + 961 (Constants.sPreferenceLevelStronglyDiscouraged * m.getRoomConstraints().size() * (lastDaySlot - firstDaySlot + 1) * (lastWorkDay - firstWorkDay + 1))); 962 w.println("000." + dx.format(bidx++) + " Too big room max," + (Constants.sPreferenceLevelStronglyDiscouraged * m.variables().size())); 963 w.println("000." + dx.format(bidx++) + " Distribution preferences min," + minGrPref); 964 w.println("000." + dx.format(bidx++) + " Distribution preferences max," + maxGrPref); 965 w.println("000." + dx.format(bidx++) + " Back-to-back instructor pref max," + worstInstrPref); 966 TooBigRooms tbr = (TooBigRooms)m.getCriterion(TooBigRooms.class); 967 for (Long scheduler: new TreeSet<Long>(subs.keySet())) { 968 List<Lecture> vars = subs.get(scheduler); 969 idx = 001; 970 bidx = 101; 971 int nrAssg = 0; 972 enrls = 0; 973 int roomPref = 0; 974 minRoomPref = 0; 975 maxRoomPref = 0; 976 double timePref = 0; 977 minTimePref = 0; 978 maxTimePref = 0; 979 double grPref = 0; 980 minGrPref = 0; 981 maxGrPref = 0; 982 long allSC = 0, hardSC = 0, distSC = 0; 983 int instPref = 0; 984 worstInstrPref = 0; 985 int spreadPen = 0, deptSpreadPen = 0; 986 int tooBigRooms = 0; 987 int rcs = 0, uselessSlots = 0; 988 used = new HashSet<Constraint<Lecture, Placement>>(); 989 for (Lecture lecture : vars) { 990 if (lecture.isCommitted()) 991 continue; 992 enrls += lecture.students().size(); 993 Placement placement = a.getValue(lecture); 994 if (placement != null) { 995 nrAssg++; 996 } 997 998 int[] minMaxRoomPref = lecture.getMinMaxRoomPreference(); 999 minRoomPref += minMaxRoomPref[0]; 1000 maxRoomPref += minMaxRoomPref[1]; 1001 1002 double[] minMaxTimePref = lecture.getMinMaxTimePreference(); 1003 minTimePref += minMaxTimePref[0]; 1004 maxTimePref += minMaxTimePref[1]; 1005 1006 if (placement != null) { 1007 roomPref += placement.getRoomPreference(); 1008 timePref += placement.getTimeLocation().getNormalizedPreference(); 1009 if (tbr != null) tooBigRooms += tbr.getPreference(placement); 1010 } 1011 1012 for (Constraint<Lecture, Placement> c : lecture.constraints()) { 1013 if (!used.add(c)) 1014 continue; 1015 1016 if (c instanceof InstructorConstraint) { 1017 InstructorConstraint ic = (InstructorConstraint) c; 1018 instPref += ic.getPreference(a); 1019 worstInstrPref += ic.getWorstPreference(); 1020 } 1021 1022 if (c instanceof DepartmentSpreadConstraint) { 1023 DepartmentSpreadConstraint dsc = (DepartmentSpreadConstraint) c; 1024 deptSpreadPen += dsc.getPenalty(a); 1025 } else if (c instanceof SpreadConstraint) { 1026 SpreadConstraint sc = (SpreadConstraint) c; 1027 spreadPen += sc.getPenalty(a); 1028 } 1029 1030 if (c instanceof GroupConstraint) { 1031 GroupConstraint gc = (GroupConstraint) c; 1032 if (gc.isHard()) 1033 continue; 1034 minGrPref -= Math.abs(gc.getPreference()); 1035 maxGrPref += 0; 1036 grPref += Math.min(0, gc.getCurrentPreference(a)); 1037 // minGrPref += Math.min(gc.getPreference(), 0); 1038 // maxGrPref += Math.max(gc.getPreference(), 0); 1039 // grPref += gc.getCurrentPreference(); 1040 } 1041 1042 if (c instanceof JenrlConstraint) { 1043 JenrlConstraint jc = (JenrlConstraint) c; 1044 if (!jc.isInConflict(a) || !jc.isOfTheSameProblem()) 1045 continue; 1046 Lecture l1 = jc.first(); 1047 Lecture l2 = jc.second(); 1048 allSC += jc.getJenrl(); 1049 if (l1.areStudentConflictsHard(l2)) 1050 hardSC += jc.getJenrl(); 1051 Placement p1 = a.getValue(l1); 1052 Placement p2 = a.getValue(l2); 1053 if (!p1.getTimeLocation().hasIntersection(p2.getTimeLocation())) 1054 distSC += jc.getJenrl(); 1055 } 1056 1057 if (c instanceof RoomConstraint) { 1058 RoomConstraint rc = (RoomConstraint) c; 1059 uselessSlots += UselessHalfHours.countUselessSlotsHalfHours(rc.getContext(a)) + BrokenTimePatterns.countUselessSlotsBrokenTimePatterns(rc.getContext(a)); 1060 rcs++; 1061 } 1062 } 1063 } 1064 w.println(dx.format(scheduler) + "." + dx.format(idx++) + " Assigned variables," + nrAssg); 1065 w.println(dx.format(scheduler) + "." + dx.format(bidx++) + " Assigned variables max," + vars.size()); 1066 w.println(dx.format(scheduler) + "." + dx.format(idx++) + " Hard student conflicts," + hardSC); 1067 w.println(dx.format(scheduler) + "." + dx.format(bidx++) + " Student enrollments," + enrls); 1068 if (m.getProperties().getPropertyBoolean("General.UseDistanceConstraints", true)) 1069 w.println(dx.format(scheduler) + "." + dx.format(idx++) + " Distance student conf.," + distSC); 1070 w.println(dx.format(scheduler) + "." + dx.format(idx++) + " Student conflicts," + allSC); 1071 w.println(dx.format(scheduler) + "." + dx.format(idx++) + " Time preferences," + timePref); 1072 w.println(dx.format(scheduler) + "." + dx.format(bidx++) + " Time preferences min," + minTimePref); 1073 w.println(dx.format(scheduler) + "." + dx.format(bidx++) + " Time preferences max," + maxTimePref); 1074 w.println(dx.format(scheduler) + "." + dx.format(idx++) + " Room preferences," + roomPref); 1075 w.println(dx.format(scheduler) + "." + dx.format(bidx++) + " Room preferences min," + minRoomPref); 1076 w.println(dx.format(scheduler) + "." + dx.format(bidx++) + " Room preferences max," + maxRoomPref); 1077 w.println(dx.format(scheduler) + "." + dx.format(idx++) + " Useless half-hours," + uselessSlots); 1078 w.println(dx.format(scheduler) + "." + dx.format(bidx++) + " Useless half-hours max," + 1079 (Constants.sPreferenceLevelStronglyDiscouraged * rcs * (lastDaySlot - firstDaySlot + 1) * (lastWorkDay - firstWorkDay + 1))); 1080 w.println(dx.format(scheduler) + "." + dx.format(idx++) + " Too big room," + tooBigRooms); 1081 w.println(dx.format(scheduler) + "." + dx.format(bidx++) + " Too big room max," + (Constants.sPreferenceLevelStronglyDiscouraged * vars.size())); 1082 w.println(dx.format(scheduler) + "." + dx.format(idx++) + " Distribution preferences," + grPref); 1083 w.println(dx.format(scheduler) + "." + dx.format(bidx++) + " Distribution preferences min," + minGrPref); 1084 w.println(dx.format(scheduler) + "." + dx.format(bidx++) + " Distribution preferences max," + maxGrPref); 1085 if (m.getProperties().getPropertyBoolean("General.UseDistanceConstraints", true)) 1086 w.println(dx.format(scheduler) + "." + dx.format(idx++) + " Back-to-back instructor pref," + instPref); 1087 w.println(dx.format(scheduler) + "." + dx.format(bidx++) + " Back-to-back instructor pref max," + worstInstrPref); 1088 if (m.getProperties().getPropertyBoolean("General.DeptBalancing", true)) { 1089 w.println(dx.format(scheduler) + "." + dx.format(idx++) + " Department balancing penalty," + sDoubleFormat.format((deptSpreadPen) / 12.0)); 1090 } 1091 w.println(dx.format(scheduler) + "." + dx.format(idx++) + " Same subpart balancing penalty," + sDoubleFormat.format((spreadPen) / 12.0)); 1092 } 1093 w.flush(); 1094 w.close(); 1095 } catch (java.io.IOException io) { 1096 sLogger.error(io.getMessage(), io); 1097 } 1098 } 1099 1100 private class ShutdownHook extends Thread { 1101 Solver<Lecture, Placement> iSolver = null; 1102 1103 private ShutdownHook(Solver<Lecture, Placement> solver) { 1104 setName("ShutdownHook"); 1105 iSolver = solver; 1106 } 1107 1108 @Override 1109 public void run() { 1110 try { 1111 if (iSolver.isRunning()) iSolver.stopSolver(); 1112 Solution<Lecture, Placement> solution = iSolver.lastSolution(); 1113 long lastIt = solution.getIteration(); 1114 double lastTime = solution.getTime(); 1115 DataProperties properties = iSolver.getProperties(); 1116 TimetableModel model = (TimetableModel) solution.getModel(); 1117 File outDir = new File(properties.getProperty("General.Output", ".")); 1118 1119 if (solution.getBestInfo() != null) { 1120 Solution<Lecture, Placement> bestSolution = solution;// .cloneBest(); 1121 sLogger.info("Last solution: " + ToolBox.dict2string(bestSolution.getExtendedInfo(), 1)); 1122 sLogger.info("Best solution (before restore): " + ToolBox.dict2string(bestSolution.getBestInfo(), 1)); 1123 bestSolution.restoreBest(); 1124 sLogger.info("Best solution: " + ToolBox.dict2string(bestSolution.getExtendedInfo(), 1)); 1125 if (properties.getPropertyBoolean("General.SwitchStudents", true)) 1126 ((TimetableModel) bestSolution.getModel()).switchStudents(bestSolution.getAssignment()); 1127 sLogger.info("Best solution: " + ToolBox.dict2string(bestSolution.getExtendedInfo(), 1)); 1128 saveOutputCSV(bestSolution, new File(outDir, "output.csv")); 1129 1130 printSomeStuff(bestSolution); 1131 1132 if (properties.getPropertyBoolean("General.Save", true)) { 1133 TimetableSaver saver = null; 1134 try { 1135 saver = (TimetableSaver) Class.forName(getTimetableSaverClass(properties)) 1136 .getConstructor(new Class[] { Solver.class }).newInstance(new Object[] { iSolver }); 1137 } catch (ClassNotFoundException e) { 1138 System.err.println(e.getClass().getSimpleName() + ": " + e.getMessage()); 1139 saver = new TimetableXMLSaver(iSolver); 1140 } 1141 if ((saver instanceof TimetableXMLSaver) && properties.getProperty("General.SolutionFile") != null) 1142 ((TimetableXMLSaver) saver).save(new File(properties.getProperty("General.SolutionFile"))); 1143 else 1144 saver.save(); 1145 } 1146 } else { 1147 sLogger.info("Last solution:" + ToolBox.dict2string(solution.getExtendedInfo(), 1)); 1148 } 1149 1150 iCSVFile.close(); 1151 1152 sLogger.info("Total number of done iteration steps:" + lastIt); 1153 sLogger.info("Achieved speed: " + sDoubleFormat.format(lastIt / lastTime) + " iterations/second"); 1154 1155 PrintWriter out = new PrintWriter(new FileWriter(new File(outDir, "solver.html"))); 1156 out.println("<html><title>Save log</title><body>"); 1157 out.println(Progress.getInstance(model).getHtmlLog(Progress.MSGLEVEL_TRACE, true)); 1158 out.println("</html>"); 1159 out.flush(); 1160 out.close(); 1161 Progress.removeInstance(model); 1162 1163 if (iStat != null) { 1164 PrintWriter cbs = new PrintWriter(new FileWriter(new File(outDir, "cbs.txt"))); 1165 cbs.println(iStat.toString()); 1166 cbs.flush(); cbs.close(); 1167 } 1168 1169 System.out.println("Unassigned variables: " + model.nrUnassignedVariables(solution.getAssignment())); 1170 } catch (Throwable t) { 1171 sLogger.error("Test failed.", t); 1172 } 1173 } 1174 } 1175}