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