001package org.cpsolver.coursett; 002 003import java.io.File; 004import java.text.SimpleDateFormat; 005import java.util.ArrayList; 006import java.util.BitSet; 007import java.util.Calendar; 008import java.util.Date; 009import java.util.HashSet; 010import java.util.HashMap; 011import java.util.Hashtable; 012import java.util.Iterator; 013import java.util.List; 014import java.util.Locale; 015import java.util.Map; 016import java.util.Set; 017 018 019import org.cpsolver.coursett.constraint.ClassLimitConstraint; 020import org.cpsolver.coursett.constraint.DepartmentSpreadConstraint; 021import org.cpsolver.coursett.constraint.DiscouragedRoomConstraint; 022import org.cpsolver.coursett.constraint.GroupConstraint; 023import org.cpsolver.coursett.constraint.IgnoreStudentConflictsConstraint; 024import org.cpsolver.coursett.constraint.InstructorConstraint; 025import org.cpsolver.coursett.constraint.JenrlConstraint; 026import org.cpsolver.coursett.constraint.MinimizeNumberOfUsedGroupsOfTime; 027import org.cpsolver.coursett.constraint.MinimizeNumberOfUsedRoomsConstraint; 028import org.cpsolver.coursett.constraint.RoomConstraint; 029import org.cpsolver.coursett.constraint.SpreadConstraint; 030import org.cpsolver.coursett.constraint.FlexibleConstraint.FlexibleConstraintType; 031import org.cpsolver.coursett.model.Configuration; 032import org.cpsolver.coursett.model.Lecture; 033import org.cpsolver.coursett.model.Placement; 034import org.cpsolver.coursett.model.RoomLocation; 035import org.cpsolver.coursett.model.RoomSharingModel; 036import org.cpsolver.coursett.model.Student; 037import org.cpsolver.coursett.model.TimeLocation; 038import org.cpsolver.coursett.model.TimetableModel; 039import org.cpsolver.ifs.assignment.Assignment; 040import org.cpsolver.ifs.model.Constraint; 041import org.cpsolver.ifs.solution.Solution; 042import org.cpsolver.ifs.solver.Solver; 043import org.cpsolver.ifs.util.Progress; 044import org.cpsolver.ifs.util.ToolBox; 045import org.dom4j.Document; 046import org.dom4j.Element; 047import org.dom4j.io.SAXReader; 048 049/** 050 * This class loads the input model from XML file. <br> 051 * <br> 052 * Parameters: 053 * <table border='1' summary='Related Solver Parameters'> 054 * <tr> 055 * <th>Parameter</th> 056 * <th>Type</th> 057 * <th>Comment</th> 058 * </tr> 059 * <tr> 060 * <td>General.Input</td> 061 * <td>{@link String}</td> 062 * <td>Input XML file</td> 063 * </tr> 064 * <tr> 065 * <td>General.DeptBalancing</td> 066 * <td>{@link Boolean}</td> 067 * <td>Use {@link DepartmentSpreadConstraint}</td> 068 * </tr> 069 * <tr> 070 * <td>General.InteractiveMode</td> 071 * <td>{@link Boolean}</td> 072 * <td>Interactive mode (see {@link Lecture#purgeInvalidValues(boolean)})</td> 073 * </tr> 074 * <tr> 075 * <td>General.ForcedPerturbances</td> 076 * <td>{@link Integer}</td> 077 * <td>For testing of MPP: number of input perturbations, i.e., classes with 078 * prohibited intial assignment</td> 079 * </tr> 080 * <tr> 081 * <td>General.UseDistanceConstraints</td> 082 * <td>{@link Boolean}</td> 083 * <td>Consider distances between buildings</td> 084 * </tr> 085 * </table> 086 * 087 * @version CourseTT 1.3 (University Course Timetabling)<br> 088 * Copyright (C) 2006 - 2014 Tomas Muller<br> 089 * <a href="mailto:muller@unitime.org">muller@unitime.org</a><br> 090 * <a href="http://muller.unitime.org">http://muller.unitime.org</a><br> 091 * <br> 092 * This library is free software; you can redistribute it and/or modify 093 * it under the terms of the GNU Lesser General Public License as 094 * published by the Free Software Foundation; either version 3 of the 095 * License, or (at your option) any later version. <br> 096 * <br> 097 * This library is distributed in the hope that it will be useful, but 098 * WITHOUT ANY WARRANTY; without even the implied warranty of 099 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 100 * Lesser General Public License for more details. <br> 101 * <br> 102 * You should have received a copy of the GNU Lesser General Public 103 * License along with this library; if not see 104 * <a href='http://www.gnu.org/licenses/'>http://www.gnu.org/licenses/</a>. 105 */ 106 107public class TimetableXMLLoader extends TimetableLoader { 108 private static org.apache.log4j.Logger sLogger = org.apache.log4j.Logger.getLogger(TimetableXMLLoader.class); 109 private static SimpleDateFormat sDF = new SimpleDateFormat("MM/dd"); 110 111 private boolean iDeptBalancing = true; 112 private int iForcedPerturbances = 0; 113 114 private boolean iInteractiveMode = false; 115 private File iInputFile; 116 117 private Progress iProgress = null; 118 119 public TimetableXMLLoader(TimetableModel model, Assignment<Lecture, Placement> assignment) { 120 super(model, assignment); 121 iProgress = Progress.getInstance(getModel()); 122 iInputFile = new File(getModel().getProperties().getProperty("General.Input", 123 "." + File.separator + "solution.xml")); 124 iForcedPerturbances = getModel().getProperties().getPropertyInt("General.ForcedPerturbances", 0); 125 iDeptBalancing = getModel().getProperties().getPropertyBoolean("General.DeptBalancing", true); 126 iInteractiveMode = getModel().getProperties().getPropertyBoolean("General.InteractiveMode", iInteractiveMode); 127 } 128 129 private Solver<Lecture, Placement> iSolver = null; 130 131 public void setSolver(Solver<Lecture, Placement> solver) { 132 iSolver = solver; 133 } 134 135 public Solver<Lecture, Placement> getSolver() { 136 return iSolver; 137 } 138 139 public void setInputFile(File inputFile) { 140 iInputFile = inputFile; 141 } 142 143 @Override 144 public void load() throws Exception { 145 load(null); 146 } 147 148 public void load(Solution<Lecture, Placement> currentSolution) throws Exception { 149 sLogger.debug("Reading XML data from " + iInputFile); 150 iProgress.setPhase("Reading " + iInputFile.getName() + " ..."); 151 152 Document document = (new SAXReader()).read(iInputFile); 153 Element root = document.getRootElement(); 154 sLogger.debug("Root element: " + root.getName()); 155 if (!"llrt".equals(root.getName()) && !"timetable".equals(root.getName())) { 156 sLogger.error("Given XML file is not large lecture room timetabling problem."); 157 return; 158 } 159 160 iProgress.load(root, true); 161 iProgress.message(Progress.MSGLEVEL_STAGE, "Restoring from backup ..."); 162 163 if (root.element("input") != null) 164 root = root.element("input"); 165 166 if (root.attributeValue("term") != null) 167 getModel().getProperties().setProperty("Data.Term", root.attributeValue("term")); 168 if (root.attributeValue("year") != null) 169 getModel().setYear(Integer.parseInt(root.attributeValue("year"))); 170 else if (root.attributeValue("term") != null) 171 getModel().setYear(Integer.parseInt(root.attributeValue("term").substring(0, 4))); 172 if (root.attributeValue("initiative") != null) 173 getModel().getProperties().setProperty("Data.Initiative", root.attributeValue("initiative")); 174 if (root.attributeValue("semester") != null && root.attributeValue("year") != null) 175 getModel().getProperties().setProperty("Data.Term", 176 root.attributeValue("semester") + root.attributeValue("year")); 177 if (root.attributeValue("session") != null) 178 getModel().getProperties().setProperty("General.SessionId", root.attributeValue("session")); 179 if (root.attributeValue("solverGroup") != null) 180 getModel().getProperties().setProperty("General.SolverGroupId", root.attributeValue("solverGroup")); 181 String version = root.attributeValue("version"); 182 183 // Student sectioning considers the whole course (including committed classes), since 2.5 184 boolean sectionWholeCourse = true; 185 186 if (version != null && version.indexOf('.') >= 0) { 187 int majorVersion = Integer.parseInt(version.substring(0, version.indexOf('.'))); 188 int minorVersion = Integer.parseInt(version.substring(1 + version.indexOf('.'))); 189 190 sectionWholeCourse = (majorVersion == 2 && minorVersion >= 5) || majorVersion > 2; 191 } 192 193 HashMap<Long, TimeLocation> perts = new HashMap<Long, TimeLocation>(); 194 if (getModel().getProperties().getPropertyInt("MPP.TimePert", 0) > 0) { 195 int nrChanges = getModel().getProperties().getPropertyInt("MPP.TimePert", 0); 196 int idx = 0; 197 for (Iterator<?> i = root.element("perturbations").elementIterator("class"); i.hasNext() && idx < nrChanges; idx++) { 198 Element pertEl = (Element) i.next(); 199 Long classId = Long.valueOf(pertEl.attributeValue("id")); 200 TimeLocation tl = new TimeLocation(Integer.parseInt(pertEl.attributeValue("days"), 2), Integer 201 .parseInt(pertEl.attributeValue("start")), Integer.parseInt(pertEl.attributeValue("length")), 202 0, 0.0, 0, null, null, null, 0); 203 perts.put(classId, tl); 204 } 205 } 206 207 iProgress.setPhase("Creating rooms ...", root.element("rooms").elements("room").size()); 208 HashMap<String, Element> roomElements = new HashMap<String, Element>(); 209 HashMap<String, RoomConstraint> roomConstraints = new HashMap<String, RoomConstraint>(); 210 HashMap<Long, List<Lecture>> sameLectures = new HashMap<Long, List<Lecture>>(); 211 for (Iterator<?> i = root.element("rooms").elementIterator("room"); i.hasNext();) { 212 Element roomEl = (Element) i.next(); 213 iProgress.incProgress(); 214 roomElements.put(roomEl.attributeValue("id"), roomEl); 215 if ("false".equals(roomEl.attributeValue("constraint"))) 216 continue; 217 RoomSharingModel sharingModel = null; 218 Element sharingEl = roomEl.element("sharing"); 219 if (sharingEl != null) { 220 Character freeForAllPrefChar = null; 221 Element freeForAllEl = sharingEl.element("freeForAll"); 222 if (freeForAllEl != null) 223 freeForAllPrefChar = freeForAllEl.attributeValue("value", "F").charAt(0); 224 Character notAvailablePrefChar = null; 225 Element notAvailableEl = sharingEl.element("notAvailable"); 226 if (notAvailableEl != null) 227 notAvailablePrefChar = notAvailableEl.attributeValue("value", "X").charAt(0); 228 String pattern = sharingEl.element("pattern").getText(); 229 int unit = Integer.parseInt(sharingEl.element("pattern").attributeValue("unit", "1")); 230 Map<Character, Long> departments = new HashMap<Character, Long>(); 231 for (Iterator<?> j = sharingEl.elementIterator("department"); j.hasNext(); ) { 232 Element deptEl = (Element)j.next(); 233 char value = deptEl.attributeValue("value", String.valueOf((char)('0' + departments.size()))).charAt(0); 234 Long id = Long.valueOf(deptEl.attributeValue("id")); 235 departments.put(value, id); 236 } 237 sharingModel = new RoomSharingModel(unit, departments, pattern, freeForAllPrefChar, notAvailablePrefChar); 238 } 239 boolean ignoreTooFar = false; 240 if ("true".equals(roomEl.attributeValue("ignoreTooFar"))) 241 ignoreTooFar = true; 242 boolean fake = false; 243 if ("true".equals(roomEl.attributeValue("fake"))) 244 fake = true; 245 Double posX = null, posY = null; 246 if (roomEl.attributeValue("location") != null) { 247 String loc = roomEl.attributeValue("location"); 248 posX = Double.valueOf(loc.substring(0, loc.indexOf(','))); 249 posY = Double.valueOf(loc.substring(loc.indexOf(',') + 1)); 250 } 251 boolean discouraged = "true".equals(roomEl.attributeValue("discouraged")); 252 RoomConstraint constraint = (discouraged ? new DiscouragedRoomConstraint( 253 getModel().getProperties(), 254 Long.valueOf(roomEl.attributeValue("id")), 255 (roomEl.attributeValue("name") != null ? roomEl.attributeValue("name") : "r" 256 + roomEl.attributeValue("id")), 257 (roomEl.attributeValue("building") == null ? null : Long.valueOf(roomEl.attributeValue("building"))), 258 Integer.parseInt(roomEl.attributeValue("capacity")), sharingModel, posX, posY, ignoreTooFar, !fake) 259 : new RoomConstraint(Long.valueOf(roomEl.attributeValue("id")), 260 (roomEl.attributeValue("name") != null ? roomEl.attributeValue("name") : "r" 261 + roomEl.attributeValue("id")), (roomEl.attributeValue("building") == null ? null 262 : Long.valueOf(roomEl.attributeValue("building"))), Integer.parseInt(roomEl 263 .attributeValue("capacity")), sharingModel, posX, posY, ignoreTooFar, !fake)); 264 if (roomEl.attributeValue("type") != null) 265 constraint.setType(Long.valueOf(roomEl.attributeValue("type"))); 266 getModel().addConstraint(constraint); 267 roomConstraints.put(roomEl.attributeValue("id"), constraint); 268 269 for (Iterator<?> j = roomEl.elementIterator("travel-time"); j.hasNext();) { 270 Element travelTimeEl = (Element)j.next(); 271 getModel().getDistanceMetric().addTravelTime(constraint.getResourceId(), 272 Long.valueOf(travelTimeEl.attributeValue("id")), 273 Integer.valueOf(travelTimeEl.attributeValue("minutes"))); 274 } 275 } 276 277 HashMap<String, InstructorConstraint> instructorConstraints = new HashMap<String, InstructorConstraint>(); 278 if (root.element("instructors") != null) { 279 for (Iterator<?> i = root.element("instructors").elementIterator("instructor"); i.hasNext();) { 280 Element instructorEl = (Element) i.next(); 281 InstructorConstraint instructorConstraint = new InstructorConstraint(Long.valueOf(instructorEl 282 .attributeValue("id")), instructorEl.attributeValue("puid"), (instructorEl 283 .attributeValue("name") != null ? instructorEl.attributeValue("name") : "i" 284 + instructorEl.attributeValue("id")), "true".equals(instructorEl.attributeValue("ignDist"))); 285 if (instructorEl.attributeValue("type") != null) 286 instructorConstraint.setType(Long.valueOf(instructorEl.attributeValue("type"))); 287 instructorConstraints.put(instructorEl.attributeValue("id"), instructorConstraint); 288 289 getModel().addConstraint(instructorConstraint); 290 } 291 } 292 HashMap<Long, String> depts = new HashMap<Long, String>(); 293 if (root.element("departments") != null) { 294 for (Iterator<?> i = root.element("departments").elementIterator("department"); i.hasNext();) { 295 Element deptEl = (Element) i.next(); 296 depts.put(Long.valueOf(deptEl.attributeValue("id")), (deptEl.attributeValue("name") != null ? deptEl 297 .attributeValue("name") : "d" + deptEl.attributeValue("id"))); 298 } 299 } 300 301 HashMap<Long, Configuration> configs = new HashMap<Long, Configuration>(); 302 HashMap<Long, List<Configuration>> alternativeConfigurations = new HashMap<Long, List<Configuration>>(); 303 if (root.element("configurations") != null) { 304 for (Iterator<?> i = root.element("configurations").elementIterator("config"); i.hasNext();) { 305 Element configEl = (Element) i.next(); 306 Long configId = Long.valueOf(configEl.attributeValue("id")); 307 int limit = Integer.parseInt(configEl.attributeValue("limit")); 308 Long offeringId = Long.valueOf(configEl.attributeValue("offering")); 309 Configuration config = new Configuration(offeringId, configId, limit); 310 configs.put(configId, config); 311 List<Configuration> altConfigs = alternativeConfigurations.get(offeringId); 312 if (altConfigs == null) { 313 altConfigs = new ArrayList<Configuration>(); 314 alternativeConfigurations.put(offeringId, altConfigs); 315 } 316 altConfigs.add(config); 317 config.setAltConfigurations(altConfigs); 318 } 319 } 320 321 iProgress.setPhase("Creating variables ...", root.element("classes").elements("class").size()); 322 323 HashMap<String, Element> classElements = new HashMap<String, Element>(); 324 HashMap<String, Lecture> lectures = new HashMap<String, Lecture>(); 325 HashMap<Lecture, Placement> assignedPlacements = new HashMap<Lecture, Placement>(); 326 HashMap<Lecture, String> parents = new HashMap<Lecture, String>(); 327 int ord = 0; 328 for (Iterator<?> i1 = root.element("classes").elementIterator("class"); i1.hasNext();) { 329 Element classEl = (Element) i1.next(); 330 331 Configuration config = null; 332 if (classEl.attributeValue("config") != null) { 333 config = configs.get(Long.valueOf(classEl.attributeValue("config"))); 334 } 335 if (config == null && classEl.attributeValue("offering") != null) { 336 Long offeringId = Long.valueOf(classEl.attributeValue("offering")); 337 Long configId = Long.valueOf(classEl.attributeValue("config")); 338 List<Configuration> altConfigs = alternativeConfigurations.get(offeringId); 339 if (altConfigs == null) { 340 altConfigs = new ArrayList<Configuration>(); 341 alternativeConfigurations.put(offeringId, altConfigs); 342 } 343 for (Configuration c : altConfigs) { 344 if (c.getConfigId().equals(configId)) { 345 config = c; 346 break; 347 } 348 } 349 if (config == null) { 350 config = new Configuration(offeringId, configId, -1); 351 altConfigs.add(config); 352 config.setAltConfigurations(altConfigs); 353 } 354 } 355 356 DatePattern defaultDatePattern = new DatePattern(); 357 if (classEl.attributeValue("dates") == null) { 358 int startDay = Integer.parseInt(classEl.attributeValue("startDay", "0")); 359 int endDay = Integer.parseInt(classEl.attributeValue("endDay", "1")); 360 defaultDatePattern.setPattern(startDay, endDay); 361 defaultDatePattern.setName(sDF.format(getDate(getModel().getYear(), startDay)) + "-" + sDF.format(getDate(getModel().getYear(), endDay))); 362 } else { 363 defaultDatePattern.setId(classEl.attributeValue("datePattern") == null ? null : Long.valueOf(classEl.attributeValue("datePattern"))); 364 defaultDatePattern.setName(classEl.attributeValue("datePatternName")); 365 defaultDatePattern.setPattern(classEl.attributeValue("dates")); 366 } 367 Hashtable<Long, DatePattern> datePatterns = new Hashtable<Long, TimetableXMLLoader.DatePattern>(); 368 for (Iterator<?> i2 = classEl.elementIterator("date"); i2.hasNext();) { 369 Element dateEl = (Element) i2.next(); 370 Long id = Long.valueOf(dateEl.attributeValue("id")); 371 datePatterns.put(id, new DatePattern( 372 id, 373 dateEl.attributeValue("name"), 374 dateEl.attributeValue("pattern"))); 375 } 376 classElements.put(classEl.attributeValue("id"), classEl); 377 List<InstructorConstraint> ics = new ArrayList<InstructorConstraint>(); 378 for (Iterator<?> i2 = classEl.elementIterator("instructor"); i2.hasNext();) { 379 Element instructorEl = (Element) i2.next(); 380 InstructorConstraint instructorConstraint = instructorConstraints 381 .get(instructorEl.attributeValue("id")); 382 if (instructorConstraint == null) { 383 instructorConstraint = new InstructorConstraint(Long.valueOf(instructorEl.attributeValue("id")), 384 instructorEl.attributeValue("puid"), 385 (instructorEl.attributeValue("name") != null ? instructorEl.attributeValue("name") : "i" 386 + instructorEl.attributeValue("id")), "true".equals(instructorEl 387 .attributeValue("ignDist"))); 388 instructorConstraints.put(instructorEl.attributeValue("id"), instructorConstraint); 389 getModel().addConstraint(instructorConstraint); 390 } 391 ics.add(instructorConstraint); 392 } 393 List<RoomLocation> roomLocations = new ArrayList<RoomLocation>(); 394 List<RoomConstraint> roomConstraintsThisClass = new ArrayList<RoomConstraint>(); 395 List<RoomLocation> initialRoomLocations = new ArrayList<RoomLocation>(); 396 List<RoomLocation> assignedRoomLocations = new ArrayList<RoomLocation>(); 397 List<RoomLocation> bestRoomLocations = new ArrayList<RoomLocation>(); 398 for (Iterator<?> i2 = classEl.elementIterator("room"); i2.hasNext();) { 399 Element roomLocationEl = (Element) i2.next(); 400 Element roomEl = roomElements.get(roomLocationEl.attributeValue("id")); 401 RoomConstraint roomConstraint = roomConstraints.get(roomLocationEl.attributeValue("id")); 402 403 Long roomId = null; 404 String roomName = null; 405 Long bldgId = null; 406 407 if (roomConstraint != null) { 408 roomConstraintsThisClass.add(roomConstraint); 409 roomId = roomConstraint.getResourceId(); 410 roomName = roomConstraint.getRoomName(); 411 bldgId = roomConstraint.getBuildingId(); 412 } else { 413 roomId = Long.valueOf(roomEl.attributeValue("id")); 414 roomName = (roomEl.attributeValue("name") != null ? roomEl.attributeValue("name") : "r" 415 + roomEl.attributeValue("id")); 416 bldgId = (roomEl.attributeValue("building") == null ? null : Long.valueOf(roomEl 417 .attributeValue("building"))); 418 } 419 420 boolean ignoreTooFar = false; 421 if ("true".equals(roomEl.attributeValue("ignoreTooFar"))) 422 ignoreTooFar = true; 423 Double posX = null, posY = null; 424 if (roomEl.attributeValue("location") != null) { 425 String loc = roomEl.attributeValue("location"); 426 posX = Double.valueOf(loc.substring(0, loc.indexOf(','))); 427 posY = Double.valueOf(loc.substring(loc.indexOf(',') + 1)); 428 } 429 RoomLocation rl = new RoomLocation(roomId, roomName, bldgId, Integer.parseInt(roomLocationEl 430 .attributeValue("pref")), Integer.parseInt(roomEl.attributeValue("capacity")), posX, posY, 431 ignoreTooFar, roomConstraint); 432 if ("true".equals(roomLocationEl.attributeValue("initial"))) 433 initialRoomLocations.add(rl); 434 if ("true".equals(roomLocationEl.attributeValue("solution"))) 435 assignedRoomLocations.add(rl); 436 if ("true".equals(roomLocationEl.attributeValue("best"))) 437 bestRoomLocations.add(rl); 438 roomLocations.add(rl); 439 } 440 List<TimeLocation> timeLocations = new ArrayList<TimeLocation>(); 441 TimeLocation initialTimeLocation = null; 442 TimeLocation assignedTimeLocation = null; 443 TimeLocation bestTimeLocation = null; 444 TimeLocation prohibitedTime = perts.get(Long.valueOf(classEl.attributeValue("id"))); 445 446 for (Iterator<?> i2 = classEl.elementIterator("time"); i2.hasNext();) { 447 Element timeLocationEl = (Element) i2.next(); 448 DatePattern dp = defaultDatePattern; 449 if (timeLocationEl.attributeValue("date") != null) 450 dp = datePatterns.get(Long.valueOf(timeLocationEl.attributeValue("date"))); 451 TimeLocation tl = new TimeLocation( 452 Integer.parseInt(timeLocationEl.attributeValue("days"), 2), 453 Integer.parseInt(timeLocationEl.attributeValue("start")), 454 Integer.parseInt(timeLocationEl.attributeValue("length")), 455 (int) Double.parseDouble(timeLocationEl.attributeValue("pref")), 456 Double.parseDouble(timeLocationEl.attributeValue("npref", timeLocationEl.attributeValue("pref"))), 457 Integer.parseInt(timeLocationEl.attributeValue("datePref", "0")), 458 dp.getId(), dp.getName(), dp.getPattern(), 459 Integer.parseInt(timeLocationEl.attributeValue("breakTime") == null ? "-1" : timeLocationEl.attributeValue("breakTime"))); 460 if (tl.getBreakTime() < 0) tl.setBreakTime(tl.getLength() == 18 ? 15 : 10); 461 if (timeLocationEl.attributeValue("pattern") != null) 462 tl.setTimePatternId(Long.valueOf(timeLocationEl.attributeValue("pattern"))); 463 /* 464 * if (timePatternTransform) tl = 465 * transformTimePattern(Long.valueOf 466 * (classEl.attributeValue("id")),tl); 467 */ 468 if (prohibitedTime != null && prohibitedTime.getDayCode() == tl.getDayCode() 469 && prohibitedTime.getStartSlot() == tl.getStartSlot() 470 && prohibitedTime.getLength() == tl.getLength()) { 471 sLogger.info("Time " + tl.getLongName(true) + " is prohibited for class " + classEl.attributeValue("id")); 472 continue; 473 } 474 if ("true".equals(timeLocationEl.attributeValue("solution"))) 475 assignedTimeLocation = tl; 476 if ("true".equals(timeLocationEl.attributeValue("initial"))) 477 initialTimeLocation = tl; 478 if ("true".equals(timeLocationEl.attributeValue("best"))) 479 bestTimeLocation = tl; 480 timeLocations.add(tl); 481 } 482 if (timeLocations.isEmpty()) { 483 sLogger.error(" ERROR: No time."); 484 continue; 485 } 486 487 int minClassLimit = 0; 488 int maxClassLimit = 0; 489 float room2limitRatio = 1.0f; 490 if (!"true".equals(classEl.attributeValue("committed"))) { 491 if (classEl.attributeValue("expectedCapacity") != null) { 492 minClassLimit = maxClassLimit = Integer.parseInt(classEl.attributeValue("expectedCapacity")); 493 int roomCapacity = Integer.parseInt(classEl.attributeValue("roomCapacity", classEl 494 .attributeValue("expectedCapacity"))); 495 if (minClassLimit == 0) 496 minClassLimit = maxClassLimit = roomCapacity; 497 room2limitRatio = (minClassLimit == 0 ? 1.0f : ((float) roomCapacity) / minClassLimit); 498 } else { 499 if (classEl.attribute("classLimit") != null) { 500 minClassLimit = maxClassLimit = Integer.parseInt(classEl.attributeValue("classLimit")); 501 } else { 502 minClassLimit = Integer.parseInt(classEl.attributeValue("minClassLimit")); 503 maxClassLimit = Integer.parseInt(classEl.attributeValue("maxClassLimit")); 504 } 505 room2limitRatio = Float.parseFloat(classEl.attributeValue("roomToLimitRatio", "1.0")); 506 } 507 } 508 509 Lecture lecture = new Lecture(Long.valueOf(classEl.attributeValue("id")), 510 (classEl.attributeValue("solverGroup") != null ? Long 511 .valueOf(classEl.attributeValue("solverGroup")) : null), Long.valueOf(classEl 512 .attributeValue("subpart", classEl.attributeValue("course", "-1"))), (classEl 513 .attributeValue("name") != null ? classEl.attributeValue("name") : "c" 514 + classEl.attributeValue("id")), timeLocations, roomLocations, Integer.parseInt(classEl 515 .attributeValue("nrRooms", roomLocations.isEmpty() ? "0" : "1")), null, minClassLimit, maxClassLimit, room2limitRatio); 516 lecture.setNote(classEl.attributeValue("note")); 517 518 if ("true".equals(classEl.attributeValue("committed"))) 519 lecture.setCommitted(true); 520 521 if (!lecture.isCommitted() && classEl.attributeValue("ord") != null) 522 lecture.setOrd(Integer.parseInt(classEl.attributeValue("ord"))); 523 else 524 lecture.setOrd(ord++); 525 526 lecture.setWeight(Double.parseDouble(classEl.attributeValue("weight", "1.0"))); 527 528 if (lecture.getNrRooms() > 1) 529 lecture.setMaxRoomCombinations(Integer.parseInt(classEl.attributeValue("maxRoomCombinations", "-1"))); 530 531 if (config != null) 532 lecture.setConfiguration(config); 533 534 if (initialTimeLocation != null && initialRoomLocations.size() == lecture.getNrRooms()) { 535 lecture.setInitialAssignment(new Placement(lecture, initialTimeLocation, initialRoomLocations)); 536 } 537 if (assignedTimeLocation != null && assignedRoomLocations.size() == lecture.getNrRooms()) { 538 assignedPlacements.put(lecture, new Placement(lecture, assignedTimeLocation, assignedRoomLocations)); 539 } else if (lecture.getInitialAssignment() != null) { 540 assignedPlacements.put(lecture, lecture.getInitialAssignment()); 541 } 542 if (bestTimeLocation != null && bestRoomLocations.size() == lecture.getNrRooms()) { 543 lecture.setBestAssignment(new Placement(lecture, bestTimeLocation, bestRoomLocations), 0); 544 } else if (assignedTimeLocation != null && assignedRoomLocations.size() == lecture.getNrRooms()) { 545 lecture.setBestAssignment(assignedPlacements.get(lecture), 0); 546 } 547 548 lectures.put(classEl.attributeValue("id"), lecture); 549 if (classEl.attributeValue("department") != null) 550 lecture.setDepartment(Long.valueOf(classEl.attributeValue("department"))); 551 if (classEl.attribute("scheduler") != null) 552 lecture.setScheduler(Long.valueOf(classEl.attributeValue("scheduler"))); 553 if ((sectionWholeCourse || !lecture.isCommitted()) && classEl.attributeValue("subpart", classEl.attributeValue("course")) != null) { 554 Long subpartId = Long.valueOf(classEl.attributeValue("subpart", classEl.attributeValue("course"))); 555 List<Lecture> sames = sameLectures.get(subpartId); 556 if (sames == null) { 557 sames = new ArrayList<Lecture>(); 558 sameLectures.put(subpartId, sames); 559 } 560 sames.add(lecture); 561 } 562 String parent = classEl.attributeValue("parent"); 563 if (parent != null) 564 parents.put(lecture, parent); 565 566 getModel().addVariable(lecture); 567 568 if (lecture.isCommitted()) { 569 Placement placement = assignedPlacements.get(lecture); 570 if (classEl.attribute("assignment") != null) 571 placement.setAssignmentId(Long.valueOf(classEl.attributeValue("assignment"))); 572 for (InstructorConstraint ic : ics) 573 ic.setNotAvailable(placement); 574 for (RoomConstraint rc : roomConstraintsThisClass) 575 rc.setNotAvailable(placement); 576 } else { 577 for (InstructorConstraint ic : ics) 578 ic.addVariable(lecture); 579 for (RoomConstraint rc : roomConstraintsThisClass) 580 rc.addVariable(lecture); 581 } 582 583 iProgress.incProgress(); 584 } 585 586 for (Map.Entry<Lecture, String> entry : parents.entrySet()) { 587 Lecture lecture = entry.getKey(); 588 Lecture parent = lectures.get(entry.getValue()); 589 if (parent == null) { 590 iProgress.warn("Parent class " + entry.getValue() + " does not exists."); 591 } else { 592 lecture.setParent(parent); 593 } 594 } 595 596 iProgress.setPhase("Creating constraints ...", root.element("groupConstraints").elements("constraint").size()); 597 HashMap<String, Element> grConstraintElements = new HashMap<String, Element>(); 598 HashMap<String, Constraint<Lecture, Placement>> groupConstraints = new HashMap<String, Constraint<Lecture, Placement>>(); 599 for (Iterator<?> i1 = root.element("groupConstraints").elementIterator("constraint"); i1.hasNext();) { 600 Element grConstraintEl = (Element) i1.next(); 601 Constraint<Lecture, Placement> c = null; 602 if ("SPREAD".equals(grConstraintEl.attributeValue("type"))) { 603 c = new SpreadConstraint(getModel().getProperties(), grConstraintEl.attributeValue("name", "spread")); 604 } else if ("MIN_ROOM_USE".equals(grConstraintEl.attributeValue("type"))) { 605 c = new MinimizeNumberOfUsedRoomsConstraint(getModel().getProperties()); 606 } else if ("CLASS_LIMIT".equals(grConstraintEl.attributeValue("type"))) { 607 if (grConstraintEl.element("parentClass") == null) { 608 c = new ClassLimitConstraint(Integer.parseInt(grConstraintEl.attributeValue("courseLimit")), 609 grConstraintEl.attributeValue("name", "class-limit")); 610 } else { 611 String classId = grConstraintEl.element("parentClass").attributeValue("id"); 612 c = new ClassLimitConstraint(lectures.get(classId), grConstraintEl.attributeValue("name", 613 "class-limit")); 614 } 615 if (grConstraintEl.attributeValue("delta") != null) 616 ((ClassLimitConstraint) c).setClassLimitDelta(Integer.parseInt(grConstraintEl 617 .attributeValue("delta"))); 618 } else if ("MIN_GRUSE(10x1h)".equals(grConstraintEl.attributeValue("type"))) { 619 c = new MinimizeNumberOfUsedGroupsOfTime(getModel().getProperties(), "10x1h", 620 MinimizeNumberOfUsedGroupsOfTime.sGroups10of1h); 621 } else if ("MIN_GRUSE(5x2h)".equals(grConstraintEl.attributeValue("type"))) { 622 c = new MinimizeNumberOfUsedGroupsOfTime(getModel().getProperties(), "5x2h", 623 MinimizeNumberOfUsedGroupsOfTime.sGroups5of2h); 624 } else if ("MIN_GRUSE(3x3h)".equals(grConstraintEl.attributeValue("type"))) { 625 c = new MinimizeNumberOfUsedGroupsOfTime(getModel().getProperties(), "3x3h", 626 MinimizeNumberOfUsedGroupsOfTime.sGroups3of3h); 627 } else if ("MIN_GRUSE(2x5h)".equals(grConstraintEl.attributeValue("type"))) { 628 c = new MinimizeNumberOfUsedGroupsOfTime(getModel().getProperties(), "2x5h", 629 MinimizeNumberOfUsedGroupsOfTime.sGroups2of5h); 630 } else if (IgnoreStudentConflictsConstraint.REFERENCE.equals(grConstraintEl.attributeValue("type"))) { 631 c = new IgnoreStudentConflictsConstraint(); 632 } else { 633 try { 634 FlexibleConstraintType f = FlexibleConstraintType.valueOf(grConstraintEl.attributeValue("type")); 635 try { 636 c = f.create( 637 Long.valueOf(grConstraintEl.attributeValue("id")), 638 grConstraintEl.attributeValue("owner"), 639 grConstraintEl.attributeValue("pref"), 640 grConstraintEl.attributeValue("reference")); 641 } catch (IllegalArgumentException e) { 642 iProgress.warn("Failed to create flexible constraint " + grConstraintEl.attributeValue("type") + ": " + e.getMessage(), e); 643 continue; 644 } 645 } catch (IllegalArgumentException e) { 646 // type did not match, continue with group constraint types 647 c = new GroupConstraint( 648 Long.valueOf(grConstraintEl.attributeValue("id")), 649 GroupConstraint.ConstraintType.get(grConstraintEl.attributeValue("type")), 650 grConstraintEl.attributeValue("pref")); 651 } 652 } 653 getModel().addConstraint(c); 654 for (Iterator<?> i2 = grConstraintEl.elementIterator("class"); i2.hasNext();) { 655 String classId = ((Element) i2.next()).attributeValue("id"); 656 Lecture other = lectures.get(classId); 657 if (other != null) 658 c.addVariable(other); 659 else 660 iProgress.warn("Class " + classId + " does not exists, but it is referred from group constraint " + c.getId() + " (" + c.getName() + ")"); 661 } 662 grConstraintElements.put(grConstraintEl.attributeValue("id"), grConstraintEl); 663 groupConstraints.put(grConstraintEl.attributeValue("id"), c); 664 iProgress.incProgress(); 665 } 666 667 iProgress.setPhase("Loading students ...", root.element("students").elements("student").size()); 668 boolean initialSectioning = true; 669 HashMap<Long, Student> students = new HashMap<Long, Student>(); 670 HashMap<Long, Set<Student>> offering2students = new HashMap<Long, Set<Student>>(); 671 for (Iterator<?> i1 = root.element("students").elementIterator("student"); i1.hasNext();) { 672 Element studentEl = (Element) i1.next(); 673 List<Lecture> lecturesThisStudent = new ArrayList<Lecture>(); 674 Long studentId = Long.valueOf(studentEl.attributeValue("id")); 675 Student student = students.get(studentId); 676 if (student == null) { 677 student = new Student(studentId); 678 students.put(studentId, student); 679 getModel().addStudent(student); 680 } 681 student.setAcademicArea(studentEl.attributeValue("area")); 682 student.setAcademicClassification(studentEl.attributeValue("classification")); 683 student.setMajor(studentEl.attributeValue("major")); 684 student.setCurriculum(studentEl.attributeValue("curriculum")); 685 for (Iterator<?> i2 = studentEl.elementIterator("offering"); i2.hasNext();) { 686 Element ofEl = (Element) i2.next(); 687 Long offeringId = Long.valueOf(ofEl.attributeValue("id")); 688 String priority = ofEl.attributeValue("priority"); 689 student.addOffering(offeringId, Double.parseDouble(ofEl.attributeValue("weight", "1.0")), priority == null ? null : Double.valueOf(priority)); 690 Set<Student> studentsThisOffering = offering2students.get(offeringId); 691 if (studentsThisOffering == null) { 692 studentsThisOffering = new HashSet<Student>(); 693 offering2students.put(offeringId, studentsThisOffering); 694 } 695 studentsThisOffering.add(student); 696 } 697 for (Iterator<?> i2 = studentEl.elementIterator("class"); i2.hasNext();) { 698 String classId = ((Element) i2.next()).attributeValue("id"); 699 Lecture lecture = lectures.get(classId); 700 if (lecture == null) { 701 iProgress.warn("Class " + classId + " does not exists, but it is referred from student " + student.getId()); 702 continue; 703 } 704 if (lecture.isCommitted()) { 705 if (sectionWholeCourse && (lecture.getParent() != null || lecture.getConfiguration() != null)) { 706 // committed, but with course structure -- sectioning can be used 707 student.addLecture(lecture); 708 lecture.addStudent(getAssignment(), student); 709 lecturesThisStudent.add(lecture); 710 initialSectioning = false; 711 } else { 712 Placement placement = assignedPlacements.get(lecture); 713 student.addCommitedPlacement(placement); 714 } 715 } else { 716 student.addLecture(lecture); 717 lecture.addStudent(getAssignment(), student); 718 lecturesThisStudent.add(lecture); 719 initialSectioning = false; 720 } 721 } 722 723 for (Iterator<?> i2 = studentEl.elementIterator("prohibited-class"); i2.hasNext();) { 724 String classId = ((Element) i2.next()).attributeValue("id"); 725 Lecture lecture = lectures.get(classId); 726 if (lecture != null) 727 student.addCanNotEnroll(lecture); 728 else 729 iProgress.warn("Class " + classId + " does not exists, but it is referred from student " + student.getId()); 730 } 731 732 if (studentEl.attributeValue("instructor") != null) 733 student.setInstructor(instructorConstraints.get(studentEl.attributeValue("instructor"))); 734 735 iProgress.incProgress(); 736 } 737 738 for (List<Lecture> sames: sameLectures.values()) { 739 for (Lecture lect : sames) { 740 lect.setSameSubpartLectures(sames); 741 } 742 } 743 744 if (initialSectioning) { 745 iProgress.setPhase("Initial sectioning ...", offering2students.size()); 746 for (Map.Entry<Long, Set<Student>> entry : offering2students.entrySet()) { 747 Long offeringId = entry.getKey(); 748 Set<Student> studentsThisOffering = entry.getValue(); 749 List<Configuration> altConfigs = alternativeConfigurations.get(offeringId); 750 getModel().getStudentSectioning().initialSectioning(getAssignment(), offeringId, String.valueOf(offeringId), studentsThisOffering, altConfigs); 751 iProgress.incProgress(); 752 } 753 for (Student student: students.values()) { 754 student.clearDistanceCache(); 755 if (student.getInstructor() != null) 756 for (Lecture lecture: student.getInstructor().variables()) { 757 student.addLecture(lecture); 758 lecture.addStudent(getAssignment(), student); 759 } 760 } 761 } 762 763 iProgress.setPhase("Computing jenrl ...", students.size()); 764 HashMap<Lecture, HashMap<Lecture, JenrlConstraint>> jenrls = new HashMap<Lecture, HashMap<Lecture, JenrlConstraint>>(); 765 for (Iterator<Student> i1 = students.values().iterator(); i1.hasNext();) { 766 Student st = i1.next(); 767 for (Iterator<Lecture> i2 = st.getLectures().iterator(); i2.hasNext();) { 768 Lecture l1 = i2.next(); 769 for (Iterator<Lecture> i3 = st.getLectures().iterator(); i3.hasNext();) { 770 Lecture l2 = i3.next(); 771 if (l1.getId() >= l2.getId()) 772 continue; 773 HashMap<Lecture, JenrlConstraint> x = jenrls.get(l1); 774 if (x == null) { 775 x = new HashMap<Lecture, JenrlConstraint>(); 776 jenrls.put(l1, x); 777 } 778 JenrlConstraint jenrl = x.get(l2); 779 if (jenrl == null) { 780 jenrl = new JenrlConstraint(); 781 jenrl.addVariable(l1); 782 jenrl.addVariable(l2); 783 getModel().addConstraint(jenrl); 784 x.put(l2, jenrl); 785 } 786 jenrl.incJenrl(getAssignment(), st); 787 } 788 } 789 iProgress.incProgress(); 790 } 791 792 if (iDeptBalancing) { 793 iProgress.setPhase("Creating dept. spread constraints ...", getModel().variables().size()); 794 HashMap<Long, DepartmentSpreadConstraint> depSpreadConstraints = new HashMap<Long, DepartmentSpreadConstraint>(); 795 for (Lecture lecture : getModel().variables()) { 796 if (lecture.getDepartment() == null) 797 continue; 798 DepartmentSpreadConstraint deptConstr = depSpreadConstraints.get(lecture.getDepartment()); 799 if (deptConstr == null) { 800 String name = depts.get(lecture.getDepartment()); 801 deptConstr = new DepartmentSpreadConstraint(getModel().getProperties(), lecture.getDepartment(), 802 (name != null ? name : "d" + lecture.getDepartment())); 803 depSpreadConstraints.put(lecture.getDepartment(), deptConstr); 804 getModel().addConstraint(deptConstr); 805 } 806 deptConstr.addVariable(lecture); 807 iProgress.incProgress(); 808 } 809 } 810 811 if (getModel().getProperties().getPropertyBoolean("General.PurgeInvalidPlacements", true)) { 812 iProgress.setPhase("Purging invalid placements ...", getModel().variables().size()); 813 for (Lecture lecture : getModel().variables()) { 814 lecture.purgeInvalidValues(iInteractiveMode); 815 iProgress.incProgress(); 816 } 817 } 818 819 if (getModel().hasConstantVariables() && getModel().constantVariables().size() > 0) { 820 iProgress.setPhase("Assigning committed classes ...", assignedPlacements.size()); 821 for (Map.Entry<Lecture, Placement> entry : assignedPlacements.entrySet()) { 822 Lecture lecture = entry.getKey(); 823 Placement placement = entry.getValue(); 824 if (!lecture.isCommitted()) { iProgress.incProgress(); continue; } 825 lecture.setConstantValue(placement); 826 getModel().weaken(getAssignment(), placement); 827 Map<Constraint<Lecture, Placement>, Set<Placement>> conflictConstraints = getModel().conflictConstraints(getAssignment(), placement); 828 if (conflictConstraints.isEmpty()) { 829 getAssignment().assign(0, placement); 830 } else { 831 sLogger.warn("WARNING: Unable to assign " + lecture.getName() + " := " + placement.getName()); 832 sLogger.debug(" Reason:"); 833 for (Constraint<Lecture, Placement> c : conflictConstraints.keySet()) { 834 Set<Placement> vals = conflictConstraints.get(c); 835 for (Placement v : vals) { 836 sLogger.debug(" " + v.variable().getName() + " = " + v.getName()); 837 } 838 sLogger.debug(" in constraint " + c); 839 } 840 } 841 iProgress.incProgress(); 842 } 843 } 844 845 if (currentSolution != null) { 846 iProgress.setPhase("Creating best assignment ...", 2 * getModel().variables().size()); 847 for (Lecture lecture : getModel().variables()) { 848 iProgress.incProgress(); 849 Placement placement = lecture.getBestAssignment(); 850 if (placement == null) continue; 851 getModel().weaken(getAssignment(), placement); 852 getAssignment().assign(0, placement); 853 } 854 855 currentSolution.saveBest(); 856 for (Lecture lecture : getModel().variables()) { 857 iProgress.incProgress(); 858 getAssignment().unassign(0, lecture); 859 } 860 } 861 862 iProgress.setPhase("Creating initial assignment ...", assignedPlacements.size()); 863 for (Map.Entry<Lecture, Placement> entry : assignedPlacements.entrySet()) { 864 Lecture lecture = entry.getKey(); 865 Placement placement = entry.getValue(); 866 if (lecture.isCommitted()) { iProgress.incProgress(); continue; } 867 getModel().weaken(getAssignment(), placement); 868 Map<Constraint<Lecture, Placement>, Set<Placement>> conflictConstraints = getModel().conflictConstraints(getAssignment(), placement); 869 if (conflictConstraints.isEmpty()) { 870 if (!placement.isValid()) { 871 sLogger.warn("WARNING: Lecture " + lecture.getName() + " does not contain assignment " 872 + placement.getLongName(true) + " in its domain (" + placement.getNotValidReason(getAssignment(), true) + ")."); 873 } else 874 getAssignment().assign(0, placement); 875 } else { 876 sLogger.warn("WARNING: Unable to assign " + lecture.getName() + " := " + placement.getName()); 877 sLogger.debug(" Reason:"); 878 for (Constraint<Lecture, Placement> c : conflictConstraints.keySet()) { 879 Set<Placement> vals = conflictConstraints.get(c); 880 for (Placement v : vals) { 881 sLogger.debug(" " + v.variable().getName() + " = " + v.getName()); 882 } 883 sLogger.debug(" in constraint " + c); 884 } 885 } 886 iProgress.incProgress(); 887 } 888 889 if (initialSectioning && getAssignment().nrAssignedVariables() != 0 && !getModel().getProperties().getPropertyBoolean("Global.LoadStudentEnrlsFromSolution", false)) 890 getModel().switchStudents(getAssignment()); 891 892 if (iForcedPerturbances > 0) { 893 iProgress.setPhase("Forcing perturbances", iForcedPerturbances); 894 for (int i = 0; i < iForcedPerturbances; i++) { 895 iProgress.setProgress(i); 896 Lecture var = null; 897 do { 898 var = ToolBox.random(getModel().variables()); 899 } while (var.getInitialAssignment() == null || var.values(getAssignment()).size() <= 1); 900 var.removeInitialValue(); 901 } 902 } 903 904 /* 905 for (Constraint<Lecture, Placement> c : getModel().constraints()) { 906 if (c instanceof SpreadConstraint) 907 ((SpreadConstraint) c).init(); 908 if (c instanceof DiscouragedRoomConstraint) 909 ((DiscouragedRoomConstraint) c).setEnabled(true); 910 if (c instanceof MinimizeNumberOfUsedRoomsConstraint) 911 ((MinimizeNumberOfUsedRoomsConstraint) c).setEnabled(true); 912 if (c instanceof MinimizeNumberOfUsedGroupsOfTime) 913 ((MinimizeNumberOfUsedGroupsOfTime) c).setEnabled(true); 914 } 915 */ 916 917 try { 918 getSolver().getClass().getMethod("load", new Class[] { Element.class }).invoke(getSolver(), new Object[] { root }); 919 } catch (Exception e) { 920 } 921 922 iProgress.setPhase("Done", 1); 923 iProgress.incProgress(); 924 925 sLogger.debug("Model successfully loaded."); 926 iProgress.info("Model successfully loaded."); 927 } 928 929 public static Date getDate(int year, int dayOfYear) { 930 Calendar c = Calendar.getInstance(Locale.US); 931 c.set(year, 1, 1, 0, 0, 0); 932 c.set(Calendar.DAY_OF_YEAR, dayOfYear); 933 return c.getTime(); 934 } 935 936 public static class DatePattern { 937 Long iId; 938 String iName; 939 BitSet iPattern; 940 public DatePattern() {} 941 public DatePattern(Long id, String name, BitSet pattern) { 942 setId(id); setName(name); setPattern(pattern); 943 } 944 public DatePattern(Long id, String name, String pattern) { 945 setId(id); setName(name); setPattern(pattern); 946 } 947 public Long getId() { return iId; } 948 public void setId(Long id) { iId = id; } 949 public String getName() { return iName; } 950 public void setName(String name) { iName = name; } 951 public BitSet getPattern() { return iPattern; } 952 public void setPattern(BitSet pattern) { iPattern = pattern; } 953 public void setPattern(String pattern) { 954 iPattern = new BitSet(pattern.length()); 955 for (int i = 0; i < pattern.length(); i++) 956 if (pattern.charAt(i) == '1') 957 iPattern.set(i); 958 } 959 public void setPattern(int startDay, int endDay) { 960 iPattern = new BitSet(366); 961 for (int d = startDay; d <= endDay; d++) 962 iPattern.set(d); 963 } 964 } 965}