001package org.cpsolver.coursett.constraint; 002 003import java.util.ArrayList; 004import java.util.BitSet; 005import java.util.HashSet; 006import java.util.HashMap; 007import java.util.Iterator; 008import java.util.List; 009import java.util.Set; 010 011import org.cpsolver.coursett.Constants; 012import org.cpsolver.coursett.criteria.DistributionPreferences; 013import org.cpsolver.coursett.model.Lecture; 014import org.cpsolver.coursett.model.Placement; 015import org.cpsolver.coursett.model.TimeLocation; 016import org.cpsolver.coursett.model.TimetableModel; 017import org.cpsolver.ifs.assignment.Assignment; 018import org.cpsolver.ifs.assignment.context.AssignmentConstraintContext; 019import org.cpsolver.ifs.assignment.context.ConstraintWithContext; 020import org.cpsolver.ifs.model.Constraint; 021import org.cpsolver.ifs.model.GlobalConstraint; 022import org.cpsolver.ifs.model.Model; 023import org.cpsolver.ifs.model.WeakeningConstraint; 024import org.cpsolver.ifs.util.DataProperties; 025import org.cpsolver.ifs.util.DistanceMetric; 026import org.cpsolver.ifs.util.ToolBox; 027 028 029/** 030 * Group constraint. <br> 031 * This constraint expresses relations between several classes, e.g., that two 032 * sections of the same lecture can not be taught at the same time, or that some 033 * classes have to be taught one immediately after another. It can be either 034 * hard or soft. <br> 035 * <br> 036 * Following constraints are now supported: 037 * <table border='1' summary='Related Solver Parameters'> 038 * <tr> 039 * <th>Constraint</th> 040 * <th>Comment</th> 041 * </tr> 042 * <tr> 043 * <td>SAME_TIME</td> 044 * <td>Same time: given classes have to be taught in the same hours. If the 045 * classes are of different length, the smaller one cannot start before the 046 * longer one and it cannot end after the longer one.</td> 047 * </tr> 048 * <tr> 049 * <td>SAME_DAYS</td> 050 * <td>Same days: given classes have to be taught in the same day. If the 051 * classes are of different time patterns, the days of one class have to form a 052 * subset of the days of the other class.</td> 053 * </tr> 054 * <tr> 055 * <td>BTB</td> 056 * <td>Back-to-back constraint: given classes have to be taught in the same room 057 * and they have to follow one strictly after another.</td> 058 * </tr> 059 * <tr> 060 * <td>BTB_TIME</td> 061 * <td>Back-to-back constraint: given classes have to follow one strictly after 062 * another, but they can be taught in different rooms.</td> 063 * </tr> 064 * <tr> 065 * <td>DIFF_TIME</td> 066 * <td>Different time: given classes cannot overlap in time.</td> 067 * </tr> 068 * <tr> 069 * <td>NHB(1), NHB(1.5), NHB(2), ... NHB(8)</td> 070 * <td>Number of hours between: between the given classes, the exact number of 071 * hours have to be kept.</td> 072 * </tr> 073 * <tr> 074 * <td>SAME_START</td> 075 * <td>Same starting hour: given classes have to start in the same hour.</td> 076 * </tr> 077 * <tr> 078 * <td>SAME_ROOM</td> 079 * <td>Same room: given classes have to be placed in the same room.</td> 080 * </tr> 081 * <tr> 082 * <td>NHB_GTE(1)</td> 083 * <td>Greater than or equal to 1 hour between: between the given classes, the 084 * number of hours have to be one or more.</td> 085 * </tr> 086 * <tr> 087 * <td>NHB_LT(6)</td> 088 * <td>Less than 6 hours between: between the given classes, the number of hours 089 * have to be less than six.</td> 090 * </tr> 091 * </table> 092 * 093 * @version CourseTT 1.3 (University Course Timetabling)<br> 094 * Copyright (C) 2006 - 2014 Tomas Muller<br> 095 * <a href="mailto:muller@unitime.org">muller@unitime.org</a><br> 096 * <a href="http://muller.unitime.org">http://muller.unitime.org</a><br> 097 * <br> 098 * This library is free software; you can redistribute it and/or modify 099 * it under the terms of the GNU Lesser General Public License as 100 * published by the Free Software Foundation; either version 3 of the 101 * License, or (at your option) any later version. <br> 102 * <br> 103 * This library is distributed in the hope that it will be useful, but 104 * WITHOUT ANY WARRANTY; without even the implied warranty of 105 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 106 * Lesser General Public License for more details. <br> 107 * <br> 108 * You should have received a copy of the GNU Lesser General Public 109 * License along with this library; if not see 110 * <a href='http://www.gnu.org/licenses/'>http://www.gnu.org/licenses/</a>. 111 */ 112 113public class GroupConstraint extends ConstraintWithContext<Lecture, Placement, GroupConstraint.GroupConstraintContext> { 114 private Long iConstraintId; 115 private int iPreference; 116 private ConstraintType iType; 117 private boolean iIsRequired; 118 private boolean iIsProhibited; 119 private int iDayOfWeekOffset = 0; 120 private boolean iPrecedenceConsiderDatePatterns = true; 121 private boolean iMaxNHoursADayConsiderDatePatterns = true; 122 private int iForwardCheckMaxDepth = 2; 123 private int iForwardCheckMaxDomainSize = 1000; 124 private int iNrWorkDays = 5; 125 private int iFirstWorkDay = 0; 126 127 /** 128 * Group constraints that can be checked on pairs of classes (e.g., same room means any two classes are in the same room), 129 * only need to implement this interface. 130 */ 131 public static interface PairCheck { 132 /** 133 * Check whether the constraint is satisfied for the given two assignments (required / preferred case) 134 * @param gc Calling group constraint 135 * @param plc1 First placement 136 * @param plc2 Second placement 137 * @return true if constraint is satisfied 138 */ 139 public boolean isSatisfied(GroupConstraint gc, Placement plc1, Placement plc2); 140 /** 141 * Check whether the constraint is satisfied for the given two assignments (prohibited / discouraged case) 142 * @param gc Calling group constraint 143 * @param plc1 First placement 144 * @param plc2 Second placement 145 * @return true if constraint is satisfied 146 */ 147 public boolean isViolated(GroupConstraint gc, Placement plc1, Placement plc2); 148 } 149 150 /** 151 * Group constraints that can be checked on pairs of classes (e.g., same room means any two classes are in the same room), 152 * only need to implement this interface. Unlike {@link PairCheck}, this check is also given current assignment. 153 */ 154 public static interface AssignmentPairCheck { 155 /** 156 * Check whether the constraint is satisfied for the given two assignments (required / preferred case) 157 * @param assignment current assignment 158 * @param gc Calling group constraint 159 * @param plc1 First placement 160 * @param plc2 Second placement 161 * @return true if constraint is satisfied 162 */ 163 public boolean isSatisfied(Assignment<Lecture, Placement> assignment, GroupConstraint gc, Placement plc1, Placement plc2); 164 /** 165 * Check whether the constraint is satisfied for the given two assignments (prohibited / discouraged case) 166 * @param assignment current assignment 167 * @param gc Calling group constraint 168 * @param plc1 First placement 169 * @param plc2 Second placement 170 * @return true if constraint is satisfied 171 */ 172 public boolean isViolated(Assignment<Lecture, Placement> assignment, GroupConstraint gc, Placement plc1, Placement plc2); 173 } 174 175 /** 176 * Group constraint building blocks (individual constraints that need more than {@link PairCheck}) 177 */ 178 public static enum Flag { 179 /** Back-to-back constraint (sequence check) */ 180 BACK_TO_BACK, 181 /** Can share room flag */ 182 CAN_SHARE_ROOM, 183 /** Maximum hours a day (number of slots a day check) */ 184 MAX_HRS_DAY, 185 /** Children cannot overlap */ 186 CH_NOTOVERLAP; 187 /** Bit number (to combine flags) */ 188 int flag() { return 1 << ordinal(); } 189 } 190 191 /** 192 * Group constraint type. 193 */ 194 public static enum ConstraintType { 195 /** 196 * Same Time: Given classes must be taught at the same time of day (independent of the actual day the classes meet). 197 * For the classes of the same length, this is the same constraint as same start. For classes of different length, 198 * the shorter one cannot start before, nor end after, the longer one.<BR> 199 * When prohibited or (strongly) discouraged: one class may not meet on any day at a time of day that overlaps with 200 * that of the other. For example, one class can not meet M 7:30 while the other meets F 7:30. Note the difference 201 * here from the different time constraint that only prohibits the actual class meetings from overlapping. 202 */ 203 SAME_TIME("SAME_TIME", "Same Time", new PairCheck() { 204 @Override 205 public boolean isSatisfied(GroupConstraint gc, Placement plc1, Placement plc2) { 206 return sameHours(plc1.getTimeLocation().getStartSlot(), plc1.getTimeLocation().getLength(), 207 plc2.getTimeLocation().getStartSlot(), plc2.getTimeLocation().getLength()); 208 } 209 @Override 210 public boolean isViolated(GroupConstraint gc, Placement plc1, Placement plc2) { 211 return !(plc1.getTimeLocation().shareHours(plc2.getTimeLocation())); 212 }}), 213 /** 214 * Same Days: Given classes must be taught on the same days. In case of classes of different time patterns, a class 215 * with fewer meetings must meet on a subset of the days used by the class with more meetings. For example, if one 216 * class pattern is 3x50, all others given in the constraint can only be taught on Monday, Wednesday, or Friday. 217 * For a 2x100 class MW, MF, WF is allowed but TTh is prohibited.<BR> 218 * When prohibited or (strongly) discouraged: any pair of classes classes cannot be taught on the same days (cannot 219 * overlap in days). For instance, if one class is MFW, the second has to be TTh. 220 */ 221 SAME_DAYS("SAME_DAYS", "Same Days", new PairCheck() { 222 @Override 223 public boolean isSatisfied(GroupConstraint gc, Placement plc1, Placement plc2) { 224 return sameDays(plc1.getTimeLocation().getDaysArray(), plc2.getTimeLocation().getDaysArray()); 225 } 226 @Override 227 public boolean isViolated(GroupConstraint gc, Placement plc1, Placement plc2) { 228 return !plc1.getTimeLocation().shareDays(plc2.getTimeLocation()); 229 }}), 230 /** 231 * Back-To-Back & Same Room: Classes must be offered in adjacent time segments and must be placed in the same room. 232 * Given classes must also be taught on the same days.<BR> 233 * When prohibited or (strongly) discouraged: classes cannot be back-to-back. There must be at least half-hour 234 * between these classes, and they must be taught on the same days and in the same room. 235 */ 236 BTB("BTB", "Back-To-Back & Same Room", new PairCheck() { 237 @Override 238 public boolean isSatisfied(GroupConstraint gc, Placement plc1, Placement plc2) { 239 return 240 plc1.sameRooms(plc2) && 241 sameDays(plc1.getTimeLocation().getDaysArray(), plc2.getTimeLocation().getDaysArray()); 242 } 243 @Override 244 public boolean isViolated(GroupConstraint gc, Placement plc1, Placement plc2) { 245 return 246 plc1.sameRooms(plc2) && 247 sameDays(plc1.getTimeLocation().getDaysArray(), plc2.getTimeLocation().getDaysArray()); 248 }}, Flag.BACK_TO_BACK), 249 /** 250 * Back-To-Back: Classes must be offered in adjacent time segments but may be placed in different rooms. Given classes 251 * must also be taught on the same days.<BR> 252 * When prohibited or (strongly) discouraged: no pair of classes can be taught back-to-back. They may not overlap in time, 253 * but must be taught on the same days. This means that there must be at least half-hour between these classes. 254 */ 255 BTB_TIME("BTB_TIME", "Back-To-Back", new PairCheck() { 256 @Override 257 public boolean isSatisfied(GroupConstraint gc, Placement plc1, Placement plc2) { 258 return sameDays(plc1.getTimeLocation().getDaysArray(), plc2.getTimeLocation().getDaysArray()); 259 } 260 @Override 261 public boolean isViolated(GroupConstraint gc, Placement plc1, Placement plc2) { 262 return sameDays(plc1.getTimeLocation().getDaysArray(), plc2.getTimeLocation().getDaysArray()); 263 }}, Flag.BACK_TO_BACK), 264 /** 265 * Different Time: Given classes cannot overlap in time. They may be taught at the same time of day if they are on 266 * different days. For instance, MF 7:30 is compatible with TTh 7:30.<BR> 267 * When prohibited or (strongly) discouraged: every pair of classes in the constraint must overlap in time. 268 */ 269 DIFF_TIME("DIFF_TIME", "Different Time", new PairCheck() { 270 @Override 271 public boolean isSatisfied(GroupConstraint gc, Placement plc1, Placement plc2) { 272 return !plc1.getTimeLocation().hasIntersection(plc2.getTimeLocation()); 273 } 274 @Override 275 public boolean isViolated(GroupConstraint gc, Placement plc1, Placement plc2) { 276 return plc1.getTimeLocation().hasIntersection(plc2.getTimeLocation()); 277 }}), 278 /** 279 * 1 Hour Between: Given classes must have exactly 1 hour in between the end of one and the beginning of another. 280 * As with the <i>back-to-back time</i> constraint, given classes must be taught on the same days.<BR> 281 * When prohibited or (strongly) discouraged: classes can not have 1 hour in between. They may not overlap in time 282 * but must be taught on the same days. 283 */ 284 NHB_1("NHB(1)", "1 Hour Between", 10, 12, BTB_TIME.check(), Flag.BACK_TO_BACK), 285 /** 286 * 2 Hours Between: Given classes must have exactly 2 hours in between the end of one and the beginning of another. 287 * As with the <i>back-to-back time</i> constraint, given classes must be taught on the same days.<BR> 288 * When prohibited or (strongly) discouraged: classes can not have 2 hours in between. They may not overlap in time 289 * but must be taught on the same days. 290 */ 291 NHB_2("NHB(2)", "2 Hours Between", 20, 24, BTB_TIME.check(), Flag.BACK_TO_BACK), 292 /** 293 * 3 Hours Between: Given classes must have exactly 3 hours in between the end of one and the beginning of another. 294 * As with the <i>back-to-back time</i> constraint, given classes must be taught on the same days.<BR> 295 * When prohibited or (strongly) discouraged: classes can not have 3 hours in between. They may not overlap in time 296 * but must be taught on the same days. 297 */ 298 NHB_3("NHB(3)", "3 Hours Between", 30, 36, BTB_TIME.check(), Flag.BACK_TO_BACK), 299 /** 300 * 4 Hours Between: Given classes must have exactly 4 hours in between the end of one and the beginning of another. 301 * As with the <i>back-to-back time</i> constraint, given classes must be taught on the same days.<BR> 302 * When prohibited or (strongly) discouraged: classes can not have 4 hours in between. They may not overlap in time 303 * but must be taught on the same days. 304 */ 305 NHB_4("NHB(4)", "4 Hours Between", 40, 48, BTB_TIME.check(), Flag.BACK_TO_BACK), 306 /** 307 * 5 Hours Between: Given classes must have exactly 5 hours in between the end of one and the beginning of another. 308 * As with the <i>back-to-back time</i> constraint, given classes must be taught on the same days.<BR> 309 * When prohibited or (strongly) discouraged: classes can not have 5 hours in between. They may not overlap in time 310 * but must be taught on the same days. 311 */ 312 NHB_5("NHB(5)", "5 Hours Between", 50, 60, BTB_TIME.check(), Flag.BACK_TO_BACK), 313 /** 314 * 6 Hours Between: Given classes must have exactly 6 hours in between the end of one and the beginning of another. 315 * As with the <i>back-to-back time</i> constraint, given classes must be taught on the same days.<BR> 316 * When prohibited or (strongly) discouraged: classes can not have 6 hours in between. They may not overlap in time 317 * but must be taught on the same days. 318 */ 319 NHB_6("NHB(6)", "6 Hours Between", 60, 72, BTB_TIME.check(), Flag.BACK_TO_BACK), 320 /** 321 * 7 Hours Between: Given classes must have exactly 7 hours in between the end of one and the beginning of another. 322 * As with the <i>back-to-back time</i> constraint, given classes must be taught on the same days.<BR> 323 * When prohibited or (strongly) discouraged: classes can not have 7 hours in between. They may not overlap in time 324 * but must be taught on the same days. 325 */ 326 NHB_7("NHB(7)", "7 Hours Between", 70, 84, BTB_TIME.check(), Flag.BACK_TO_BACK), 327 /** 328 * 8 Hours Between: Given classes must have exactly 8 hours in between the end of one and the beginning of another. 329 * As with the <i>back-to-back time</i> constraint, given classes must be taught on the same days.<BR> 330 * When prohibited or (strongly) discouraged: classes can not have 8 hours in between. They may not overlap in time 331 * but must be taught on the same days. 332 */ 333 NHB_8("NHB(8)", "8 Hours Between", 80, 96, BTB_TIME.check(), Flag.BACK_TO_BACK), 334 /** 335 * Same Start Time: Given classes must start during the same half-hour period of a day (independent of the actual 336 * day the classes meet). For instance, MW 7:30 is compatible with TTh 7:30 but not with MWF 8:00.<BR> 337 * When prohibited or (strongly) discouraged: any pair of classes in the given constraint cannot start during the 338 * same half-hour period of any day of the week. 339 */ 340 SAME_START("SAME_START", "Same Start Time", new PairCheck() { 341 @Override 342 public boolean isSatisfied(GroupConstraint gc, Placement plc1, Placement plc2) { 343 return 344 (plc1.getTimeLocation().getStartSlot() % Constants.SLOTS_PER_DAY) == 345 (plc2.getTimeLocation().getStartSlot() % Constants.SLOTS_PER_DAY); 346 } 347 @Override 348 public boolean isViolated(GroupConstraint gc, Placement plc1, Placement plc2) { 349 return 350 (plc1.getTimeLocation().getStartSlot() % Constants.SLOTS_PER_DAY) != 351 (plc2.getTimeLocation().getStartSlot() % Constants.SLOTS_PER_DAY); 352 }}), 353 /** 354 * Same Room: Given classes must be taught in the same room.<BR> 355 * When prohibited or (strongly) discouraged: any pair of classes in the constraint cannot be taught in the same room. 356 */ 357 SAME_ROOM("SAME_ROOM", "Same Room", new PairCheck() { 358 @Override 359 public boolean isSatisfied(GroupConstraint gc, Placement plc1, Placement plc2) { 360 return plc1.sameRooms(plc2); 361 } 362 @Override 363 public boolean isViolated(GroupConstraint gc, Placement plc1, Placement plc2) { 364 return !plc1.sameRooms(plc2); 365 }}), 366 /** 367 * At Least 1 Hour Between: Given classes have to have 1 hour or more in between.<BR> 368 * When prohibited or (strongly) discouraged: given classes have to have less than 1 hour in between. 369 */ 370 NHB_GTE_1("NHB_GTE(1)", "At Least 1 Hour Between", 6, 288, BTB_TIME.check(), Flag.BACK_TO_BACK), 371 /** 372 * Less Than 6 Hours Between: Given classes must have less than 6 hours from end of first class to the beginning of 373 * the next. Given classes must also be taught on the same days.<BR> 374 * When prohibited or (strongly) discouraged: given classes must have 6 or more hours between. This constraint does 375 * not carry over from classes taught at the end of one day to the beginning of the next. 376 */ 377 NHB_LT_6("NHB_LT(6)", "Less Than 6 Hours Between", 0, 72, BTB_TIME.check(), Flag.BACK_TO_BACK), 378 /** 379 * 1.5 Hour Between: Given classes must have exactly 90 minutes in between the end of one and the beginning of another. 380 * As with the <i>back-to-back time</i> constraint, given classes must be taught on the same days.<BR> 381 * When prohibited or (strongly) discouraged: classes can not have 90 minutes in between. They may not overlap in time 382 * but must be taught on the same days. 383 */ 384 NHB_1_5("NHB(1.5)", "1.5 Hour Between", 15, 18, BTB_TIME.check(), Flag.BACK_TO_BACK), 385 /** 386 * 4.5 Hours Between: Given classes must have exactly 4.5 hours in between the end of one and the beginning of another. 387 * As with the <i>back-to-back time</i> constraint, given classes must be taught on the same days.<BR> 388 * When prohibited or (strongly) discouraged: classes can not have 4.5 hours in between. They may not overlap in time 389 * but must be taught on the same days. 390 */ 391 NHB_4_5("NHB(4.5)", "4.5 Hours Between", 45, 54, BTB_TIME.check(), Flag.BACK_TO_BACK), 392 /** 393 * Same Students: Given classes are treated as they are attended by the same students, i.e., they cannot overlap in time 394 * and if they are back-to-back the assigned rooms cannot be too far (student limit is used). 395 */ 396 SAME_STUDENTS("SAME_STUDENTS", "Same Students", new PairCheck() { 397 @Override 398 public boolean isSatisfied(GroupConstraint gc, Placement plc1, Placement plc2) { 399 return !JenrlConstraint.isInConflict(plc1, plc2, ((TimetableModel)gc.getModel()).getDistanceMetric()); 400 } 401 @Override 402 public boolean isViolated(GroupConstraint gc, Placement plc1, Placement plc2) { 403 return true; 404 }}), 405 /** 406 * Same Instructor: Given classes are treated as they are taught by the same instructor, i.e., they cannot overlap in time 407 * and if they are back-to-back the assigned rooms cannot be too far (instructor limit is used).<BR> 408 * If the constraint is required and the classes are back-to-back, discouraged and strongly discouraged distances between 409 * assigned rooms are also considered. 410 */ 411 SAME_INSTR("SAME_INSTR", "Same Instructor", new PairCheck() { 412 @Override 413 public boolean isSatisfied(GroupConstraint gc, Placement plc1, Placement plc2) { 414 TimeLocation t1 = plc1.getTimeLocation(), t2 = plc2.getTimeLocation(); 415 if (t1.shareDays(t2) && t1.shareWeeks(t2)) { 416 if (t1.shareHours(t2)) return false; // overlap 417 DistanceMetric m = ((TimetableModel)gc.getModel()).getDistanceMetric(); 418 if ((t1.getStartSlot() + t1.getLength() == t2.getStartSlot() || t2.getStartSlot() + t2.getLength() == t1.getStartSlot())) { 419 if (Placement.getDistanceInMeters(m, plc1, plc2) > m.getInstructorProhibitedLimit()) 420 return false; 421 } else if (m.doComputeDistanceConflictsBetweenNonBTBClasses()) { 422 if (t1.getStartSlot() + t1.getLength() < t2.getStartSlot() && 423 Placement.getDistanceInMinutes(m, plc1, plc2) > t1.getBreakTime() + Constants.SLOT_LENGTH_MIN * (t2.getStartSlot() - t1.getStartSlot() - t1.getLength())) 424 return false; 425 if (t2.getStartSlot() + t2.getLength() < t1.getStartSlot() && 426 Placement.getDistanceInMinutes(m, plc1, plc2) > t2.getBreakTime() + Constants.SLOT_LENGTH_MIN * (t1.getStartSlot() - t2.getStartSlot() - t2.getLength())) 427 return false; 428 } 429 } 430 return true; 431 } 432 @Override 433 public boolean isViolated(GroupConstraint gc, Placement plc1, Placement plc2) { 434 return true; 435 }}), 436 /** 437 * Can Share Room: Given classes can share the room (use the room in the same time) if the room is big enough. 438 */ 439 CAN_SHARE_ROOM("CAN_SHARE_ROOM", "Can Share Room", Flag.CAN_SHARE_ROOM), 440 /** 441 * Precedence: Given classes have to be taught in the given order (the first meeting of the first class has to end before 442 * the first meeting of the second class etc.)<BR> 443 * When prohibited or (strongly) discouraged: classes have to be taught in the order reverse to the given one. 444 */ 445 PRECEDENCE("PRECEDENCE", "Precedence", new PairCheck() { 446 @Override 447 public boolean isSatisfied(GroupConstraint gc, Placement plc1, Placement plc2) { 448 return gc.isPrecedence(plc1, plc2, true, true); 449 } 450 @Override 451 public boolean isViolated(GroupConstraint gc, Placement plc1, Placement plc2) { 452 return gc.isPrecedence(plc1, plc2, false, true); 453 }}), 454 /** 455 * Back-To-Back Day: Classes must be offered on adjacent days and may be placed in different rooms.<BR> 456 * When prohibited or (strongly) discouraged: classes can not be taught on adjacent days. They also can not be taught 457 * on the same days. This means that there must be at least one day between these classes. 458 */ 459 BTB_DAY("BTB_DAY", "Back-To-Back Day", new PairCheck() { 460 @Override 461 public boolean isSatisfied(GroupConstraint gc, Placement plc1, Placement plc2) { 462 return 463 !sameDays(plc1.getTimeLocation().getDaysArray(), plc2.getTimeLocation().getDaysArray()) && 464 gc.isBackToBackDays(plc1.getTimeLocation(), plc2.getTimeLocation()); 465 } 466 @Override 467 public boolean isViolated(GroupConstraint gc, Placement plc1, Placement plc2) { 468 return 469 !sameDays(plc1.getTimeLocation().getDaysArray(), plc2.getTimeLocation().getDaysArray()) && 470 !gc.isBackToBackDays(plc1.getTimeLocation(), plc2.getTimeLocation()); 471 }}), 472 /** 473 * Meet Together: Given classes are meeting together (same as if the given classes require constraints Can Share Room, 474 * Same Room, Same Time and Same Days all together). 475 */ 476 MEET_WITH("MEET_WITH", "Meet Together", new PairCheck() { 477 @Override 478 public boolean isSatisfied(GroupConstraint gc, Placement plc1, Placement plc2) { 479 return 480 plc1.sameRooms(plc2) && 481 sameHours(plc1.getTimeLocation().getStartSlot(), plc1.getTimeLocation().getLength(), 482 plc2.getTimeLocation().getStartSlot(), plc2.getTimeLocation().getLength()) && 483 sameDays(plc1.getTimeLocation().getDaysArray(), plc2.getTimeLocation().getDaysArray()); 484 485 } 486 @Override 487 public boolean isViolated(GroupConstraint gc, Placement plc1, Placement plc2) { 488 return true; 489 }}, Flag.CAN_SHARE_ROOM), 490 /** 491 * More Than 1 Day Between: Given classes must have two or more days in between.<br> 492 * When prohibited or (strongly) discouraged: given classes must be offered on adjacent days or with at most one day in between. 493 */ 494 NDB_GT_1("NDB_GT_1", "More Than 1 Day Between", new PairCheck() { 495 @Override 496 public boolean isSatisfied(GroupConstraint gc, Placement plc1, Placement plc2) { 497 return 498 !sameDays(plc1.getTimeLocation().getDaysArray(), plc2.getTimeLocation().getDaysArray()) && 499 gc.isNrDaysBetweenGreaterThanOne(plc1.getTimeLocation(), plc2.getTimeLocation()); 500 } 501 @Override 502 public boolean isViolated(GroupConstraint gc, Placement plc1, Placement plc2) { 503 return 504 !sameDays(plc1.getTimeLocation().getDaysArray(), plc2.getTimeLocation().getDaysArray()) && 505 !gc.isNrDaysBetweenGreaterThanOne(plc1.getTimeLocation(), plc2.getTimeLocation()); 506 }}), 507 /** 508 * Children Cannot Overlap: If parent classes do not overlap in time, children classes can not overlap in time as well.<BR> 509 * Note: This constraint only needs to be put on the parent classes. Preferred configurations are Required All Classes 510 * or Pairwise (Strongly) Preferred. 511 */ 512 CH_NOTOVERLAP("CH_NOTOVERLAP", "Children Cannot Overlap", new AssignmentPairCheck() { 513 @Override 514 public boolean isSatisfied(Assignment<Lecture, Placement> assignment, GroupConstraint gc, Placement plc1, Placement plc2) { 515 return gc.isChildrenNotOverlap(assignment, plc1.variable(), plc1, plc2.variable(), plc2); 516 } 517 @Override 518 public boolean isViolated(Assignment<Lecture, Placement> assignment, GroupConstraint gc, Placement plc1, Placement plc2) { 519 return true; 520 }}), 521 /** 522 * Next Day: The second class has to be placed on the following day of the first class (if the first class is on Friday, 523 * second class have to be on Monday).<br> 524 * When prohibited or (strongly) discouraged: The second class has to be placed on the previous day of the first class 525 * (if the first class is on Monday, second class have to be on Friday).<br> 526 * Note: This constraint works only between pairs of classes. 527 */ 528 FOLLOWING_DAY("FOLLOWING_DAY", "Next Day", new PairCheck() { 529 @Override 530 public boolean isSatisfied(GroupConstraint gc, Placement plc1, Placement plc2) { 531 return gc.isFollowingDay(plc1, plc2, true); 532 } 533 @Override 534 public boolean isViolated(GroupConstraint gc, Placement plc1, Placement plc2) { 535 return gc.isFollowingDay(plc1, plc2, false); 536 }}), 537 /** 538 * Two Days After: The second class has to be placed two days after the first class (Monday → Wednesday, Tuesday → 539 * Thurday, Wednesday → Friday, Thursday → Monday, Friday → Tuesday).<br> 540 * When prohibited or (strongly) discouraged: The second class has to be placed two days before the first class (Monday → 541 * Thursday, Tuesday → Friday, Wednesday → Monday, Thursday → Tuesday, Friday → Wednesday).<br> 542 * Note: This constraint works only between pairs of classes. 543 */ 544 EVERY_OTHER_DAY("EVERY_OTHER_DAY", "Two Days After", new PairCheck() { 545 @Override 546 public boolean isSatisfied(GroupConstraint gc, Placement plc1, Placement plc2) { 547 return gc.isEveryOtherDay(plc1, plc2, true); 548 } 549 @Override 550 public boolean isViolated(GroupConstraint gc, Placement plc1, Placement plc2) { 551 return gc.isEveryOtherDay(plc1, plc2, false); 552 }}), 553 /** 554 * At Most 3 Hours A Day: Classes are to be placed in a way that there is no more than three hours in any day. 555 */ 556 MAX_HRS_DAY_3("MAX_HRS_DAY(3)", "At Most 3 Hours A Day", 36, null, Flag.MAX_HRS_DAY), 557 /** 558 * At Most 4 Hours A Day: Classes are to be placed in a way that there is no more than four hours in any day. 559 */ 560 MAX_HRS_DAY_4("MAX_HRS_DAY(4)", "At Most 4 Hours A Day", 48, null, Flag.MAX_HRS_DAY), 561 /** 562 * At Most 5 Hours A Day: Classes are to be placed in a way that there is no more than five hours in any day. 563 */ 564 MAX_HRS_DAY_5("MAX_HRS_DAY(5)", "At Most 5 Hours A Day", 60, null, Flag.MAX_HRS_DAY), 565 /** 566 * At Most 6 Hours A Day: Classes are to be placed in a way that there is no more than six hours in any day. 567 */ 568 MAX_HRS_DAY_6("MAX_HRS_DAY(6)", "At Most 6 Hours A Day", 72, null, Flag.MAX_HRS_DAY), 569 /** 570 * At Most 7 Hours A Day: Classes are to be placed in a way that there is no more than seven hours in any day. 571 */ 572 MAX_HRS_DAY_7("MAX_HRS_DAY(7)", "At Most 7 Hours A Day", 84, null, Flag.MAX_HRS_DAY), 573 /** 574 * At Most 8 Hours A Day: Classes are to be placed in a way that there is no more than eight hours in any day. 575 */ 576 MAX_HRS_DAY_8("MAX_HRS_DAY(8)", "At Most 8 Hours A Day", 96, null, Flag.MAX_HRS_DAY), 577 /** 578 * At Most 9 Hours A Day: Classes are to be placed in a way that there is no more than nine hours in any day. 579 */ 580 MAX_HRS_DAY_9("MAX_HRS_DAY(9)", "At Most 9 Hours A Day", 108, null, Flag.MAX_HRS_DAY), 581 /** 582 * At Most 10 Hours A Day: Classes are to be placed in a way that there is no more than ten hours in any day. 583 */ 584 MAX_HRS_DAY_10("MAX_HRS_DAY(10)", "At Most 10 Hours A Day", 120, null, Flag.MAX_HRS_DAY), 585 /** 586 * Given classes must be taught during the same weeks (i.e., must have the same date pattern).<br> 587 * When prohibited or (strongly) discouraged: any two classes must have non overlapping date patterns. 588 */ 589 SAME_WEEKS("SAME_WEEKS", "Same Weeks", new PairCheck() { 590 @Override 591 public boolean isSatisfied(GroupConstraint gc, Placement plc1, Placement plc2) { 592 return plc1.getTimeLocation().getWeekCode().equals(plc2.getTimeLocation().getWeekCode()); 593 } 594 @Override 595 public boolean isViolated(GroupConstraint gc, Placement plc1, Placement plc2) { 596 return !plc1.getTimeLocation().shareWeeks(plc2.getTimeLocation()); 597 }}), 598 /** 599 * Classes (of different courses) are to be attended by the same students. For instance, 600 * if class A1 (of a course A) and class B1 (of a course B) are linked, a student requesting 601 * both courses must attend A1 if and only if he also attends B1. This is a student sectioning 602 * constraint that is interpreted as Same Students constraint during course timetabling. 603 */ 604 LINKED_SECTIONS("LINKED_SECTIONS", "Linked Classes", SAME_STUDENTS.check()), 605 /** 606 * Back-To-Back Precedence: Given classes have to be taught in the given order, on the same days, 607 * and in adjacent time segments. 608 * When prohibited or (strongly) discouraged: Given classes have to be taught in the given order, 609 * on the same days, but cannot be back-to-back. 610 */ 611 BTB_PRECEDENCE("BTB_PRECEDENCE", "Back-To-Back Precedence", new PairCheck() { 612 @Override 613 public boolean isSatisfied(GroupConstraint gc, Placement plc1, Placement plc2) { 614 return gc.isPrecedence(plc1, plc2, true, false) && sameDays(plc1.getTimeLocation().getDaysArray(), plc2.getTimeLocation().getDaysArray()); 615 } 616 @Override 617 public boolean isViolated(GroupConstraint gc, Placement plc1, Placement plc2) { 618 return gc.isPrecedence(plc1, plc2, true, false) && sameDays(plc1.getTimeLocation().getDaysArray(), plc2.getTimeLocation().getDaysArray()); 619 }}, Flag.BACK_TO_BACK), 620 621 /** 622 * Same Days-Time: Given classes must be taught at the same time of day and on the same days. 623 * It is the combination of Same Days and Same Time distribution preferences. 624 * When prohibited or (strongly) discouraged: Any pair of classes classes cannot be taught on the same days 625 * during the same time. 626 */ 627 SAME_DAYS_TIME("SAME_D_T", "Same Days-Time", new PairCheck() { 628 @Override 629 public boolean isSatisfied(GroupConstraint gc, Placement plc1, Placement plc2) { 630 return sameHours(plc1.getTimeLocation().getStartSlot(), plc1.getTimeLocation().getLength(), 631 plc2.getTimeLocation().getStartSlot(), plc2.getTimeLocation().getLength()) && 632 sameDays(plc1.getTimeLocation().getDaysArray(), plc2.getTimeLocation().getDaysArray()); 633 } 634 @Override 635 public boolean isViolated(GroupConstraint gc, Placement plc1, Placement plc2) { 636 return !plc1.getTimeLocation().shareHours(plc2.getTimeLocation()) || 637 !plc1.getTimeLocation().shareDays(plc2.getTimeLocation()); 638 }}), 639 /** 640 * Same Days-Room-Time: Given classes must be taught at the same time of day, on the same days and in the same room. 641 * It is the combination of Same Days, Same Time and Same Room distribution preferences. 642 * Note that this constraint is the same as Meet Together constraint, except it does not allow room sharing. In other words, 643 * it is only useful when these classes are taught during non-overlapping date patterns. 644 * When prohibited or (strongly) discouraged: Any pair of classes classes cannot be taught on the same days 645 * during the same time in the same room. 646 */ 647 SAME_DAYS_ROOM_TIME("SAME_D_R_T", "Same Days-Room-Time", new PairCheck() { 648 @Override 649 public boolean isSatisfied(GroupConstraint gc, Placement plc1, Placement plc2) { 650 return sameHours(plc1.getTimeLocation().getStartSlot(), plc1.getTimeLocation().getLength(), 651 plc2.getTimeLocation().getStartSlot(), plc2.getTimeLocation().getLength()) && 652 sameDays(plc1.getTimeLocation().getDaysArray(), plc2.getTimeLocation().getDaysArray()) && 653 plc1.sameRooms(plc2); 654 } 655 @Override 656 public boolean isViolated(GroupConstraint gc, Placement plc1, Placement plc2) { 657 return !plc1.getTimeLocation().shareHours(plc2.getTimeLocation()) || 658 !plc1.getTimeLocation().shareDays(plc2.getTimeLocation()) || 659 !plc1.sameRooms(plc2); 660 }}), 661 /** 662 * 6 Hour Work Day: Classes are to be placed in a way that there is no more than six hours between the start of the first class and the end of the class one on any day. 663 */ 664 WORKDAY_6("WORKDAY(6)", "6 Hour Work Day", 72, new PairCheck() { 665 @Override 666 public boolean isSatisfied(GroupConstraint gc, Placement plc1, Placement plc2) { 667 TimeLocation t1 = plc1.getTimeLocation(), t2 = plc2.getTimeLocation(); 668 if (t1 == null || t2 == null || !t1.shareDays(t2) || !t1.shareWeeks(t2)) return true; 669 return Math.max(t1.getStartSlot() + t1.getLength(), t2.getStartSlot() + t2.getLength()) - Math.min(t1.getStartSlot(), t2.getStartSlot()) <= gc.getType().getMax(); 670 } 671 @Override 672 public boolean isViolated(GroupConstraint gc, Placement plc1, Placement plc2) { return true; } 673 }), 674 /** 675 * 7 Hour Work Day: Classes are to be placed in a way that there is no more than seven hours between the start of the first class and the end of the class one on any day. 676 */ 677 WORKDAY_7("WORKDAY(7)", "7 Hour Work Day", 84, WORKDAY_6.check()), 678 /** 679 * 8 Hour Work Day: Classes are to be placed in a way that there is no more than eight hours between the start of the first class and the end of the class one on any day. 680 */ 681 WORKDAY_8("WORKDAY(8)", "8 Hour Work Day", 96, WORKDAY_6.check()), 682 /** 683 * 9 Hour Work Day: Classes are to be placed in a way that there is no more than nine hours between the start of the first class and the end of the class one on any day. 684 */ 685 WORKDAY_9("WORKDAY(9)", "9 Hour Work Day", 108, WORKDAY_6.check()), 686 /** 687 * 10 Hour Work Day: Classes are to be placed in a way that there is no more than ten hours between the start of the first class and the end of the class one on any day. 688 */ 689 WORKDAY_10("WORKDAY(10)", "10 Hour Work Day", 120, WORKDAY_6.check()), 690 /** 691 * 11 Hour Work Day: Classes are to be placed in a way that there is no more than eleven hours between the start of the first class and the end of the class one on any day. 692 */ 693 WORKDAY_11("WORKDAY(11)", "11 Hour Work Day", 132, WORKDAY_6.check()), 694 /** 695 * 12 Hour Work Day: Classes are to be placed in a way that there is no more than twelve hours between the start of the first class and the end of the class one on any day. 696 */ 697 WORKDAY_12("WORKDAY(12)", "12 Hour Work Day", 144, WORKDAY_6.check()), 698 /** 699 * Meet Together & Same Weeks: Given classes are meeting together (same as if the given classes require constraints Can Share Room, 700 * Same Room, Same Time, Same Days and Same Weeks all together). 701 */ 702 MEET_WITH_WEEKS("MEET_WITH_WEEKS", "Meet Together & Same Weeks", new PairCheck() { 703 @Override 704 public boolean isSatisfied(GroupConstraint gc, Placement plc1, Placement plc2) { 705 return 706 plc1.sameRooms(plc2) && 707 sameHours(plc1.getTimeLocation().getStartSlot(), plc1.getTimeLocation().getLength(), plc2.getTimeLocation().getStartSlot(), plc2.getTimeLocation().getLength()) && 708 sameDays(plc1.getTimeLocation().getDaysArray(), plc2.getTimeLocation().getDaysArray()) && 709 plc1.getTimeLocation().getWeekCode().equals(plc2.getTimeLocation().getWeekCode()); 710 } 711 @Override 712 public boolean isViolated(GroupConstraint gc, Placement plc1, Placement plc2) { 713 return true; 714 }}, Flag.CAN_SHARE_ROOM), 715 ; 716 717 String iReference, iName; 718 int iFlag = 0; 719 Flag[] iFlags = null; 720 int iMin = 0, iMax = 0; 721 PairCheck iCheck = null; 722 AssignmentPairCheck iAssignmentCheck = null; 723 ConstraintType(String reference, String name, Flag... flags) { 724 iReference = reference; 725 iName = name; 726 iFlags = flags; 727 for (Flag f: flags) 728 iFlag |= f.flag(); 729 } 730 ConstraintType(String reference, String name, PairCheck check, Flag... flags) { 731 this(reference, name, flags); 732 iCheck = check; 733 } 734 ConstraintType(String reference, String name, AssignmentPairCheck check, Flag... flags) { 735 this(reference, name, flags); 736 iAssignmentCheck = check; 737 } 738 ConstraintType(String reference, String name, int limit, PairCheck check, Flag... flags) { 739 this(reference, name, check, flags); 740 iMin = iMax = limit; 741 } 742 ConstraintType(String reference, String name, int min, int max, PairCheck check, Flag... flags) { 743 this(reference, name, check, flags); 744 iMin = min; 745 iMax = max; 746 } 747 748 /** Constraint reference 749 * @return constraint reference 750 **/ 751 public String reference() { return iReference; } 752 /** Constraint name 753 * @return constraint name 754 **/ 755 public String getName() { return iName; } 756 /** Minimum (gap) parameter 757 * @return minimum gap (first constraint parameter) 758 **/ 759 public int getMin() { return iMin; } 760 /** Maximum (gap, hours a day) parameter 761 * @return maximum gap (second constraint parameter) 762 **/ 763 public int getMax() { return iMax; } 764 765 /** Flag check (true if contains given flag) 766 * @param f a flag to check 767 * @return true if present 768 **/ 769 public boolean is(Flag f) { return (iFlag & f.flag()) != 0; } 770 771 /** Constraint type from reference 772 * @param reference constraint reference 773 * @return constraint of the reference 774 **/ 775 public static ConstraintType get(String reference) { 776 for (ConstraintType t: ConstraintType.values()) 777 if (t.reference().equals(reference)) return t; 778 return null; 779 } 780 781 /** True if a required or preferred constraint is satisfied between a pair of placements 782 * @param assignment current assignment 783 * @param gc current constraint 784 * @param plc1 first placement 785 * @param plc2 second placement 786 * @return true if the two placements are consistent with the constraint if preferred or required 787 **/ 788 public boolean isSatisfied(Assignment<Lecture, Placement> assignment, GroupConstraint gc, Placement plc1, Placement plc2) { 789 if (iCheck != null && !iCheck.isSatisfied(gc, plc1, plc2)) 790 return false; 791 if (iAssignmentCheck != null && assignment != null && !iAssignmentCheck.isSatisfied(assignment, gc, plc1, plc2)) 792 return false; 793 return true; 794 } 795 /** True if a prohibited or discouraged constraint is satisfied between a pair of placements 796 * @param assignment current assignment 797 * @param gc current constraint 798 * @param plc1 first placement 799 * @param plc2 second placement 800 * @return true if the two placements are consistent with the constraint if discouraged or prohibited 801 **/ 802 public boolean isViolated(Assignment<Lecture, Placement> assignment, GroupConstraint gc, Placement plc1, Placement plc2) { 803 if (iCheck != null && !iCheck.isViolated(gc, plc1, plc2)) 804 return false; 805 if (iAssignmentCheck != null && assignment != null && !iAssignmentCheck.isViolated(assignment, gc, plc1, plc2)) 806 return false; 807 return true; 808 } 809 /** Pair check */ 810 private PairCheck check() { return iCheck; } 811 } 812 813 public GroupConstraint() { 814 } 815 816 @Override 817 public void setModel(Model<Lecture, Placement> model) { 818 super.setModel(model); 819 if (model != null) { 820 DataProperties config = ((TimetableModel)model).getProperties(); 821 iDayOfWeekOffset = config.getPropertyInt("DatePattern.DayOfWeekOffset", 0); 822 iPrecedenceConsiderDatePatterns = config.getPropertyBoolean("Precedence.ConsiderDatePatterns", true); 823 iForwardCheckMaxDepth = config.getPropertyInt("ForwardCheck.MaxDepth", iForwardCheckMaxDepth); 824 iForwardCheckMaxDomainSize = config.getPropertyInt("ForwardCheck.MaxDomainSize", iForwardCheckMaxDomainSize); 825 iMaxNHoursADayConsiderDatePatterns = config.getPropertyBoolean("MaxNHoursADay.ConsiderDatePatterns", iMaxNHoursADayConsiderDatePatterns); 826 iNrWorkDays = (config.getPropertyInt("General.LastWorkDay", 4) - config.getPropertyInt("General.FirstWorkDay", 0) + 1); 827 if (iNrWorkDays <= 0) iNrWorkDays += 7; 828 if (iNrWorkDays > 7) iNrWorkDays -= 7; 829 iFirstWorkDay = config.getPropertyInt("General.FirstWorkDay", 0); 830 } 831 } 832 833 @Override 834 public void addVariable(Lecture lecture) { 835 if (!variables().contains(lecture)) 836 super.addVariable(lecture); 837 if (getType().is(Flag.CH_NOTOVERLAP)) { 838 if (lecture.getChildrenSubpartIds() != null) { 839 for (Long subpartId: lecture.getChildrenSubpartIds()) { 840 for (Lecture ch : lecture.getChildren(subpartId)) { 841 if (!variables().contains(ch)) 842 super.addVariable(ch); 843 } 844 } 845 } 846 } 847 } 848 849 @Override 850 public void removeVariable(Lecture lecture) { 851 if (variables().contains(lecture)) 852 super.removeVariable(lecture); 853 if (getType().is(Flag.CH_NOTOVERLAP)) { 854 if (lecture.getChildrenSubpartIds() != null) { 855 for (Long subpartId: lecture.getChildrenSubpartIds()) { 856 for (Lecture ch : lecture.getChildren(subpartId)) { 857 if (variables().contains(ch)) 858 super.removeVariable(ch); 859 } 860 } 861 } 862 } 863 } 864 865 /** 866 * Constructor 867 * 868 * @param id 869 * constraint id 870 * @param type 871 * constraString type (e.g, {@link ConstraintType#SAME_TIME}) 872 * @param preference 873 * time preference ("R" for required, "P" for prohibited, "-2", 874 * "-1", "1", "2" for soft preference) 875 */ 876 public GroupConstraint(Long id, ConstraintType type, String preference) { 877 iConstraintId = id; 878 iType = type; 879 iIsRequired = preference.equals(Constants.sPreferenceRequired); 880 iIsProhibited = preference.equals(Constants.sPreferenceProhibited); 881 iPreference = Constants.preference2preferenceLevel(preference); 882 } 883 884 /** Constraint id 885 * @return constraint unique id 886 **/ 887 public Long getConstraintId() { 888 return iConstraintId; 889 } 890 891 @Override 892 public long getId() { 893 return (iConstraintId == null ? -1 : iConstraintId.longValue()); 894 } 895 896 /** Generated unique id 897 * @return generated unique id 898 **/ 899 protected long getGeneratedId() { 900 return iId; 901 } 902 903 /** Return constraint type (e.g, {@link ConstraintType#SAME_TIME}) 904 * @return constraint type 905 **/ 906 public ConstraintType getType() { 907 return iType; 908 } 909 910 /** 911 * Set constraint type 912 * @param type constraint type 913 */ 914 public void setType(ConstraintType type) { 915 iType = type; 916 } 917 918 /** Is constraint required 919 * @return true if required 920 **/ 921 public boolean isRequired() { 922 return iIsRequired; 923 } 924 925 /** Is constraint prohibited 926 * @return true if prohibited 927 **/ 928 public boolean isProhibited() { 929 return iIsProhibited; 930 } 931 932 /** 933 * Prolog reference: "R" for required, "P" for prohibited", "-2",.."2" for 934 * preference 935 * @return prolog preference 936 */ 937 public String getPrologPreference() { 938 return Constants.preferenceLevel2preference(iPreference); 939 } 940 941 @Override 942 public boolean isConsistent(Placement value1, Placement value2) { 943 if (!isHard()) 944 return true; 945 if (!isSatisfiedPair(null, value1, value2)) 946 return false; 947 if (getType().is(Flag.BACK_TO_BACK)) { 948 HashMap<Lecture, Placement> assignments = new HashMap<Lecture, Placement>(); 949 assignments.put(value1.variable(), value1); 950 assignments.put(value2.variable(), value2); 951 if (!isSatisfiedSeq(null, assignments, null)) 952 return false; 953 } 954 if (getType().is(Flag.MAX_HRS_DAY)) { 955 HashMap<Lecture, Placement> assignments = new HashMap<Lecture, Placement>(); 956 assignments.put(value1.variable(), value1); 957 assignments.put(value2.variable(), value2); 958 for (int dayCode: Constants.DAY_CODES) { 959 if (iMaxNHoursADayConsiderDatePatterns) { 960 for (BitSet week: ((TimetableModel)getModel()).getWeeks()) { 961 if (!value1.getTimeLocation().shareWeeks(week) && !value2.getTimeLocation().shareWeeks(week)) continue; 962 if (nrSlotsADay(null, dayCode, week, assignments, null) > getType().getMax()) return false; 963 } 964 } else { 965 if (nrSlotsADay(null, dayCode, null, assignments, null) > getType().getMax()) return false; 966 } 967 } 968 } 969 return true; 970 } 971 972 @Override 973 public void computeConflicts(Assignment<Lecture, Placement> assignment, Placement value, Set<Placement> conflicts) { 974 computeConflicts(assignment, value, conflicts, true); 975 } 976 977 @Override 978 public void computeConflictsNoForwardCheck(Assignment<Lecture, Placement> assignment, Placement value, Set<Placement> conflicts) { 979 computeConflicts(assignment, value, conflicts, false); 980 } 981 982 public void computeConflicts(Assignment<Lecture, Placement> assignment, Placement value, Set<Placement> conflicts, boolean fwdCheck) { 983 if (!isHard()) 984 return; 985 for (Lecture v : variables()) { 986 if (v.equals(value.variable())) 987 continue; // ignore this variable 988 Placement p = assignment.getValue(v); 989 if (p == null) 990 continue; // there is an unassigned variable -- great, still a chance to get violated 991 if (!isSatisfiedPair(assignment, p, value)) 992 conflicts.add(p); 993 } 994 if (getType().is(Flag.BACK_TO_BACK)) { 995 HashMap<Lecture, Placement> assignments = new HashMap<Lecture, Placement>(); 996 assignments.put(value.variable(), value); 997 if (!isSatisfiedSeq(assignment, assignments, conflicts)) 998 conflicts.add(value); 999 } 1000 if (getType().is(Flag.MAX_HRS_DAY)) { 1001 HashMap<Lecture, Placement> assignments = new HashMap<Lecture, Placement>(); 1002 assignments.put(value.variable(), value); 1003 for (int dayCode: Constants.DAY_CODES) { 1004 if (iMaxNHoursADayConsiderDatePatterns) { 1005 for (BitSet week: ((TimetableModel)getModel()).getWeeks()) { 1006 if (!value.getTimeLocation().shareWeeks(week)) continue; 1007 if (nrSlotsADay(assignment, dayCode, week, assignments, conflicts) > getType().getMax()) { 1008 List<Placement> adepts = new ArrayList<Placement>(); 1009 for (Lecture l: variables()) { 1010 if (l.equals(value.variable()) || l.isConstant()) continue; 1011 Placement p = assignment.getValue(l); 1012 if (p == null || conflicts.contains(p) || p.getTimeLocation() == null) continue; 1013 if ((p.getTimeLocation().getDayCode() & dayCode) == 0 || !p.getTimeLocation().shareWeeks(week)) continue; 1014 adepts.add(p); 1015 } 1016 do { 1017 if (adepts.isEmpty()) { conflicts.add(value); break; } 1018 Placement conflict = ToolBox.random(adepts); 1019 adepts.remove(conflict); 1020 conflicts.add(conflict); 1021 } while (nrSlotsADay(assignment, dayCode, week, assignments, conflicts) > getType().getMax()); 1022 } 1023 } 1024 } else { 1025 if (nrSlotsADay(assignment, dayCode, null, assignments, conflicts) > getType().getMax()) { 1026 List<Placement> adepts = new ArrayList<Placement>(); 1027 for (Lecture l: variables()) { 1028 if (l.equals(value.variable()) || l.isConstant()) continue; 1029 Placement p = assignment.getValue(l); 1030 if (p == null || conflicts.contains(p) || p.getTimeLocation() == null) continue; 1031 if ((p.getTimeLocation().getDayCode() & dayCode) == 0) continue; 1032 adepts.add(p); 1033 } 1034 do { 1035 if (adepts.isEmpty()) { conflicts.add(value); break; } 1036 Placement conflict = ToolBox.random(adepts); 1037 adepts.remove(conflict); 1038 conflicts.add(conflict); 1039 } while (nrSlotsADay(assignment, dayCode, null, assignments, conflicts) > getType().getMax()); 1040 } 1041 } 1042 } 1043 } 1044 1045 // Forward checking 1046 if (fwdCheck) forwardCheck(assignment, value, conflicts, new HashSet<GroupConstraint>(), iForwardCheckMaxDepth - 1); 1047 } 1048 1049 public void forwardCheck(Assignment<Lecture, Placement> assignment, Placement value, Set<Placement> conflicts, Set<GroupConstraint> ignore, int depth) { 1050 try { 1051 if (depth < 0) return; 1052 ignore.add(this); 1053 1054 int neededSize = value.variable().maxRoomUse(); 1055 1056 for (Lecture lecture: variables()) { 1057 if (conflicts.contains(value)) break; // already conflicting 1058 1059 if (lecture.equals(value.variable())) continue; // Skip this lecture 1060 Placement current = assignment.getValue(lecture); 1061 if (current != null) { // Has assignment, check whether it is conflicting 1062 if (isSatisfiedPair(assignment, value, current)) { 1063 // Increase needed size if the assignment is of the same room and overlapping in time 1064 if (canShareRoom() && sameRoomAndOverlaps(value, current)) { 1065 neededSize += lecture.maxRoomUse(); 1066 } 1067 continue; 1068 } 1069 conflicts.add(current); 1070 } 1071 1072 // Look for supporting assignments assignment 1073 boolean shareRoomAndOverlaps = canShareRoom(); 1074 Placement support = null; 1075 int nrSupports = 0; 1076 if (lecture.nrValues() >= iForwardCheckMaxDomainSize) { 1077 // ignore variables with large domains 1078 return; 1079 } 1080 List<Placement> values = lecture.values(assignment); 1081 if (values.isEmpty()) { 1082 // ignore variables with empty domain 1083 return; 1084 } 1085 for (Placement other: values) { 1086 if (nrSupports < 2) { 1087 if (isSatisfiedPair(assignment, value, other)) { 1088 if (support == null) support = other; 1089 nrSupports ++; 1090 if (shareRoomAndOverlaps && !sameRoomAndOverlaps(value, other)) 1091 shareRoomAndOverlaps = false; 1092 } 1093 } else if (shareRoomAndOverlaps && !sameRoomAndOverlaps(value, other) && isSatisfiedPair(assignment, value, other)) { 1094 shareRoomAndOverlaps = false; 1095 } 1096 if (nrSupports > 1 && !shareRoomAndOverlaps) 1097 break; 1098 } 1099 1100 // No supporting assignment -> fail 1101 if (nrSupports == 0) { 1102 conflicts.add(value); // other class cannot be assigned with this value 1103 return; 1104 } 1105 // Increase needed size if all supporters are of the same room and in overlapping times 1106 if (shareRoomAndOverlaps) { 1107 neededSize += lecture.maxRoomUse(); 1108 } 1109 1110 // Only one supporter -> propagate the new assignment over other hard constraints of the lecture 1111 if (nrSupports == 1) { 1112 for (Constraint<Lecture, Placement> other: lecture.hardConstraints()) { 1113 if (other instanceof WeakeningConstraint) continue; 1114 if (other instanceof GroupConstraint) { 1115 GroupConstraint gc = (GroupConstraint)other; 1116 if (depth > 0 && !ignore.contains(gc)) 1117 gc.forwardCheck(assignment, support, conflicts, ignore, depth - 1); 1118 } else { 1119 other.computeConflicts(assignment, support, conflicts); 1120 } 1121 } 1122 for (GlobalConstraint<Lecture, Placement> other: getModel().globalConstraints()) { 1123 if (other instanceof WeakeningConstraint) continue; 1124 other.computeConflicts(assignment, support, conflicts); 1125 } 1126 1127 if (conflicts.contains(support)) 1128 conflicts.add(value); 1129 } 1130 } 1131 1132 if (canShareRoom() && neededSize > value.getRoomSize()) { 1133 // room is too small to fit all meet with classes 1134 conflicts.add(value); 1135 } 1136 1137 } finally { 1138 ignore.remove(this); 1139 } 1140 } 1141 1142 @Override 1143 public boolean inConflict(Assignment<Lecture, Placement> assignment, Placement value) { 1144 if (!isHard()) 1145 return false; 1146 for (Lecture v : variables()) { 1147 if (v.equals(value.variable())) 1148 continue; // ignore this variable 1149 Placement p = assignment.getValue(v); 1150 if (p == null) 1151 continue; // there is an unassigned variable -- great, still a chance to get violated 1152 if (!isSatisfiedPair(assignment, p, value)) 1153 return true; 1154 } 1155 if (getType().is(Flag.BACK_TO_BACK)) { 1156 HashMap<Lecture, Placement> assignments = new HashMap<Lecture, Placement>(); 1157 assignments.put(value.variable(), value); 1158 if (!isSatisfiedSeq(assignment, assignments, null)) 1159 return true; 1160 } 1161 if (getType().is(Flag.MAX_HRS_DAY)) { 1162 HashMap<Lecture, Placement> assignments = new HashMap<Lecture, Placement>(); 1163 assignments.put(value.variable(), value); 1164 for (int dayCode: Constants.DAY_CODES) { 1165 if (iMaxNHoursADayConsiderDatePatterns) { 1166 for (BitSet week: ((TimetableModel)getModel()).getWeeks()) { 1167 if (!value.getTimeLocation().shareWeeks(week)) continue; 1168 if (nrSlotsADay(assignment, dayCode, week, assignments, null) > getType().getMax()) 1169 return true; 1170 } 1171 } else { 1172 if (nrSlotsADay(assignment, dayCode, null, assignments, null) > getType().getMax()) return true; 1173 } 1174 } 1175 } 1176 1177 if (!forwardCheck(assignment, value, new HashSet<GroupConstraint>(), iForwardCheckMaxDepth - 1)) return true; 1178 1179 return false; 1180 } 1181 1182 public boolean forwardCheck(Assignment<Lecture, Placement> assignment, Placement value, Set<GroupConstraint> ignore, int depth) { 1183 try { 1184 if (depth < 0) return true; 1185 ignore.add(this); 1186 1187 int neededSize = value.variable().maxRoomUse(); 1188 1189 for (Lecture lecture: variables()) { 1190 if (lecture.equals(value.variable())) continue; // Skip this lecture 1191 Placement current = assignment.getValue(lecture); 1192 if (current != null) { // Has assignment, check whether it is conflicting 1193 if (isSatisfiedPair(assignment, value, current)) { 1194 // Increase needed size if the assignment is of the same room and overlapping in time 1195 if (canShareRoom() && sameRoomAndOverlaps(value, current)) { 1196 neededSize += lecture.maxRoomUse(); 1197 } 1198 continue; 1199 } 1200 return false; 1201 } 1202 1203 // Look for supporting assignments assignment 1204 boolean shareRoomAndOverlaps = canShareRoom(); 1205 Placement support = null; 1206 int nrSupports = 0; 1207 if (lecture.nrValues() >= iForwardCheckMaxDomainSize) { 1208 // ignore variables with large domains 1209 return true; 1210 } 1211 List<Placement> values = lecture.values(assignment); 1212 if (values.isEmpty()) { 1213 // ignore variables with empty domain 1214 return true; 1215 } 1216 for (Placement other: lecture.values(assignment)) { 1217 if (nrSupports < 2) { 1218 if (isSatisfiedPair(assignment, value, other)) { 1219 if (support == null) support = other; 1220 nrSupports ++; 1221 if (shareRoomAndOverlaps && !sameRoomAndOverlaps(value, other)) 1222 shareRoomAndOverlaps = false; 1223 } 1224 } else if (shareRoomAndOverlaps && !sameRoomAndOverlaps(value, other) && isSatisfiedPair(assignment, value, other)) { 1225 shareRoomAndOverlaps = false; 1226 } 1227 if (nrSupports > 1 && !shareRoomAndOverlaps) 1228 break; 1229 } 1230 1231 // No supporting assignment -> fail 1232 if (nrSupports == 0) { 1233 return false; // other class cannot be assigned with this value 1234 } 1235 // Increase needed size if all supporters are of the same room and in overlapping times 1236 if (shareRoomAndOverlaps) { 1237 neededSize += lecture.maxRoomUse(); 1238 } 1239 1240 // Only one supporter -> propagate the new assignment over other hard constraints of the lecture 1241 if (nrSupports == 1) { 1242 for (Constraint<Lecture, Placement> other: lecture.hardConstraints()) { 1243 if (other instanceof WeakeningConstraint) continue; 1244 if (other instanceof GroupConstraint) { 1245 GroupConstraint gc = (GroupConstraint)other; 1246 if (depth > 0 && !ignore.contains(gc) && !gc.forwardCheck(assignment, support, ignore, depth - 1)) return false; 1247 } else { 1248 if (other.inConflict(assignment, support)) return false; 1249 } 1250 } 1251 for (GlobalConstraint<Lecture, Placement> other: getModel().globalConstraints()) { 1252 if (other instanceof WeakeningConstraint) continue; 1253 if (other.inConflict(assignment, support)) return false; 1254 } 1255 } 1256 } 1257 1258 if (canShareRoom() && neededSize > value.getRoomSize()) { 1259 // room is too small to fit all meet with classes 1260 return false; 1261 } 1262 1263 return true; 1264 } finally { 1265 ignore.remove(this); 1266 } 1267 } 1268 1269 /** Constraint preference (0 if prohibited or required) 1270 * @return constraint preference (if soft) 1271 **/ 1272 public int getPreference() { 1273 return iPreference; 1274 } 1275 1276 /** 1277 * Current constraint preference (0 if prohibited or required, depends on 1278 * current satisfaction of the constraint) 1279 * @param assignment current assignment 1280 * @return current preference 1281 */ 1282 public int getCurrentPreference(Assignment<Lecture, Placement> assignment) { 1283 if (isHard()) return 0; // no preference 1284 if (countAssignedVariables(assignment) < 2) return - Math.abs(iPreference); // not enough variable 1285 if (getType().is(Flag.MAX_HRS_DAY)) { // max hours a day 1286 int over = 0; 1287 for (int dayCode: Constants.DAY_CODES) { 1288 if (iMaxNHoursADayConsiderDatePatterns) { 1289 for (BitSet week: ((TimetableModel)getModel()).getWeeks()) 1290 over += Math.max(0, nrSlotsADay(assignment, dayCode, week, null, null) - getType().getMax()); 1291 } else { 1292 over += Math.max(0, nrSlotsADay(assignment, dayCode, null, null, null) - getType().getMax()); 1293 } 1294 } 1295 return (over > 0 ? Math.abs(iPreference) * over / 12 : - Math.abs(iPreference)); 1296 } 1297 int nrViolatedPairs = 0; 1298 for (Lecture v1 : variables()) { 1299 Placement p1 = assignment.getValue(v1); 1300 if (p1 == null) continue; 1301 for (Lecture v2 : variables()) { 1302 Placement p2 = assignment.getValue(v2); 1303 if (p2 == null || v1.getId() >= v2.getId()) continue; 1304 if (!isSatisfiedPair(assignment, p1, p2)) nrViolatedPairs++; 1305 } 1306 } 1307 if (getType().is(Flag.BACK_TO_BACK)) { 1308 Set<Placement> conflicts = new HashSet<Placement>(); 1309 if (isSatisfiedSeq(assignment, new HashMap<Lecture, Placement>(), conflicts)) 1310 nrViolatedPairs += conflicts.size(); 1311 else 1312 nrViolatedPairs = variables().size(); 1313 } 1314 return (nrViolatedPairs > 0 ? Math.abs(iPreference) * nrViolatedPairs : - Math.abs(iPreference)); 1315 } 1316 1317 /** Current constraint preference change (if given placement is assigned) 1318 * @param assignment current assignment 1319 * @param placement placement that is being considered 1320 * @return change in the current preference, if assigned 1321 **/ 1322 public int getCurrentPreference(Assignment<Lecture, Placement> assignment, Placement placement) { 1323 if (isHard()) return 0; // no preference 1324 if (countAssignedVariables(assignment) + (assignment.getValue(placement.variable()) == null ? 1 : 0) < 2) return 0; // not enough variable 1325 if (getType().is(Flag.MAX_HRS_DAY)) { 1326 HashMap<Lecture, Placement> assignments = new HashMap<Lecture, Placement>(); 1327 assignments.put(placement.variable(), placement); 1328 HashMap<Lecture, Placement> unassignments = new HashMap<Lecture, Placement>(); 1329 unassignments.put(placement.variable(), null); 1330 int after = 0; 1331 int before = 0; 1332 for (int dayCode: Constants.DAY_CODES) { 1333 if (iMaxNHoursADayConsiderDatePatterns) { 1334 for (BitSet week: ((TimetableModel)getModel()).getWeeks()) { 1335 after += Math.max(0, nrSlotsADay(assignment, dayCode, week, assignments, null) - getType().getMax()); 1336 before += Math.max(0, nrSlotsADay(assignment, dayCode, week, unassignments, null) - getType().getMax()); 1337 } 1338 } else { 1339 after += Math.max(0, nrSlotsADay(assignment, dayCode, null, assignments, null) - getType().getMax()); 1340 before += Math.max(0, nrSlotsADay(assignment, dayCode, null, unassignments, null) - getType().getMax()); 1341 } 1342 } 1343 return (after > 0 ? Math.abs(iPreference) * after / 12 : - Math.abs(iPreference)) - (before > 0 ? Math.abs(iPreference) * before / 12 : - Math.abs(iPreference)); 1344 } 1345 1346 int nrViolatedPairsAfter = 0; 1347 int nrViolatedPairsBefore = 0; 1348 for (Lecture v1 : variables()) { 1349 for (Lecture v2 : variables()) { 1350 if (v1.getId() >= v2.getId()) continue; 1351 Placement p1 = (v1.equals(placement.variable()) ? null : assignment.getValue(v1)); 1352 Placement p2 = (v2.equals(placement.variable()) ? null : assignment.getValue(v2)); 1353 if (p1 != null && p2 != null && !isSatisfiedPair(assignment, p1, p2)) 1354 nrViolatedPairsBefore ++; 1355 if (v1.equals(placement.variable())) p1 = placement; 1356 if (v2.equals(placement.variable())) p2 = placement; 1357 if (p1 != null && p2 != null && !isSatisfiedPair(assignment, p1, p2)) 1358 nrViolatedPairsAfter ++; 1359 } 1360 } 1361 1362 if (getType().is(Flag.BACK_TO_BACK)) { 1363 HashMap<Lecture, Placement> assignments = new HashMap<Lecture, Placement>(); 1364 assignments.put(placement.variable(), placement); 1365 Set<Placement> conflicts = new HashSet<Placement>(); 1366 if (isSatisfiedSeq(assignment, assignments, conflicts)) 1367 nrViolatedPairsAfter += conflicts.size(); 1368 else 1369 nrViolatedPairsAfter = variables().size(); 1370 1371 HashMap<Lecture, Placement> unassignments = new HashMap<Lecture, Placement>(); 1372 unassignments.put(placement.variable(), null); 1373 Set<Placement> previous = new HashSet<Placement>(); 1374 if (isSatisfiedSeq(assignment, unassignments, previous)) 1375 nrViolatedPairsBefore += previous.size(); 1376 else 1377 nrViolatedPairsBefore = variables().size(); 1378 } 1379 1380 return (nrViolatedPairsAfter > 0 ? Math.abs(iPreference) * nrViolatedPairsAfter : - Math.abs(iPreference)) - 1381 (nrViolatedPairsBefore > 0 ? Math.abs(iPreference) * nrViolatedPairsBefore : - Math.abs(iPreference)); 1382 } 1383 1384 @Override 1385 public String toString() { 1386 StringBuffer sb = new StringBuffer(); 1387 sb.append(getName()); 1388 sb.append(" between "); 1389 for (Iterator<Lecture> e = variables().iterator(); e.hasNext();) { 1390 Lecture v = e.next(); 1391 sb.append(v.getName()); 1392 if (e.hasNext()) 1393 sb.append(", "); 1394 } 1395 return sb.toString(); 1396 } 1397 1398 @Override 1399 public boolean isHard() { 1400 return iIsRequired || iIsProhibited; 1401 } 1402 1403 @Override 1404 public String getName() { 1405 return getType().getName(); 1406 } 1407 1408 1409 private boolean isPrecedence(Placement p1, Placement p2, boolean firstGoesFirst, boolean considerDatePatterns) { 1410 int ord1 = variables().indexOf(p1.variable()); 1411 int ord2 = variables().indexOf(p2.variable()); 1412 TimeLocation t1 = null, t2 = null; 1413 if (ord1 < ord2) { 1414 if (firstGoesFirst) { 1415 t1 = p1.getTimeLocation(); 1416 t2 = p2.getTimeLocation(); 1417 } else { 1418 t2 = p1.getTimeLocation(); 1419 t1 = p2.getTimeLocation(); 1420 } 1421 } else { 1422 if (!firstGoesFirst) { 1423 t1 = p1.getTimeLocation(); 1424 t2 = p2.getTimeLocation(); 1425 } else { 1426 t2 = p1.getTimeLocation(); 1427 t1 = p2.getTimeLocation(); 1428 } 1429 } 1430 if (considerDatePatterns && iPrecedenceConsiderDatePatterns) { 1431 boolean sameDatePattern = (t1.getDatePatternId() != null ? t1.getDatePatternId().equals(t2.getDatePatternId()) : t1.getWeekCode().equals(t2.getWeekCode())); 1432 if (!sameDatePattern) { 1433 int m1 = t1.getFirstMeeting(iDayOfWeekOffset), m2 = t2.getFirstMeeting(iDayOfWeekOffset); 1434 if (m1 != m2) return m1 < m2; 1435 } 1436 } 1437 if (iFirstWorkDay != 0) { 1438 for (int i = 0; i < Constants.DAY_CODES.length; i++) { 1439 int idx = (i + iFirstWorkDay) % 7; 1440 boolean a = (t1.getDayCode() & Constants.DAY_CODES[idx]) != 0; 1441 boolean b = (t2.getDayCode() & Constants.DAY_CODES[idx]) != 0; 1442 if (b && !a) return false; // second start first 1443 if (a && !b) return true; // first start first 1444 if (a && b) return t1.getStartSlot() + t1.getLength() <= t2.getStartSlot(); // same day: check times 1445 } 1446 } 1447 return t1.getStartSlots().nextElement() + t1.getLength() <= t2.getStartSlots().nextElement(); 1448 } 1449 1450 private boolean isBackToBackDays(TimeLocation t1, TimeLocation t2) { 1451 int f1 = -1, f2 = -1, e1 = -1, e2 = -1; 1452 for (int i = 0; i < Constants.DAY_CODES.length; i++) { 1453 int idx = (i + iFirstWorkDay) % 7; 1454 if ((t1.getDayCode() & Constants.DAY_CODES[idx]) != 0) { 1455 if (f1 < 0) 1456 f1 = i; 1457 e1 = i; 1458 } 1459 if ((t2.getDayCode() & Constants.DAY_CODES[idx]) != 0) { 1460 if (f2 < 0) 1461 f2 = i; 1462 e2 = i; 1463 } 1464 } 1465 return (e1 + 1 == f2) || (e2 + 1 == f1); 1466 } 1467 1468 private boolean isNrDaysBetweenGreaterThanOne(TimeLocation t1, TimeLocation t2) { 1469 int f1 = -1, f2 = -1, e1 = -1, e2 = -1; 1470 for (int i = 0; i < Constants.DAY_CODES.length; i++) { 1471 int idx = (i + iFirstWorkDay) % 7; 1472 if ((t1.getDayCode() & Constants.DAY_CODES[idx]) != 0) { 1473 if (f1 < 0) 1474 f1 = i; 1475 e1 = i; 1476 } 1477 if ((t2.getDayCode() & Constants.DAY_CODES[idx]) != 0) { 1478 if (f2 < 0) 1479 f2 = i; 1480 e2 = i; 1481 } 1482 } 1483 return (e1 - f2 > 2) || (e2 - f1 > 2); 1484 } 1485 1486 private boolean isFollowingDay(Placement p1, Placement p2, boolean firstGoesFirst) { 1487 int ord1 = variables().indexOf(p1.variable()); 1488 int ord2 = variables().indexOf(p2.variable()); 1489 TimeLocation t1 = null, t2 = null; 1490 if (ord1 < ord2) { 1491 if (firstGoesFirst) { 1492 t1 = p1.getTimeLocation(); 1493 t2 = p2.getTimeLocation(); 1494 } else { 1495 t2 = p1.getTimeLocation(); 1496 t1 = p2.getTimeLocation(); 1497 } 1498 } else { 1499 if (!firstGoesFirst) { 1500 t1 = p1.getTimeLocation(); 1501 t2 = p2.getTimeLocation(); 1502 } else { 1503 t2 = p1.getTimeLocation(); 1504 t1 = p2.getTimeLocation(); 1505 } 1506 } 1507 int f1 = -1, f2 = -1, e1 = -1; 1508 for (int i = 0; i < Constants.DAY_CODES.length; i++) { 1509 int idx = (i + iFirstWorkDay) % 7; 1510 if ((t1.getDayCode() & Constants.DAY_CODES[idx]) != 0) { 1511 if (f1 < 0) 1512 f1 = i; 1513 e1 = i; 1514 } 1515 if ((t2.getDayCode() & Constants.DAY_CODES[idx]) != 0) { 1516 if (f2 < 0) 1517 f2 = i; 1518 } 1519 } 1520 return ((e1 + 1) % iNrWorkDays == f2); 1521 } 1522 1523 private boolean isEveryOtherDay(Placement p1, Placement p2, boolean firstGoesFirst) { 1524 int ord1 = variables().indexOf(p1.variable()); 1525 int ord2 = variables().indexOf(p2.variable()); 1526 TimeLocation t1 = null, t2 = null; 1527 if (ord1 < ord2) { 1528 if (firstGoesFirst) { 1529 t1 = p1.getTimeLocation(); 1530 t2 = p2.getTimeLocation(); 1531 } else { 1532 t2 = p1.getTimeLocation(); 1533 t1 = p2.getTimeLocation(); 1534 } 1535 } else { 1536 if (!firstGoesFirst) { 1537 t1 = p1.getTimeLocation(); 1538 t2 = p2.getTimeLocation(); 1539 } else { 1540 t2 = p1.getTimeLocation(); 1541 t1 = p2.getTimeLocation(); 1542 } 1543 } 1544 int f1 = -1, f2 = -1, e1 = -1; 1545 for (int i = 0; i < Constants.DAY_CODES.length; i++) { 1546 int idx = (i + iFirstWorkDay) % 7; 1547 if ((t1.getDayCode() & Constants.DAY_CODES[idx]) != 0) { 1548 if (f1 < 0) 1549 f1 = i; 1550 e1 = i; 1551 } 1552 if ((t2.getDayCode() & Constants.DAY_CODES[idx]) != 0) { 1553 if (f2 < 0) 1554 f2 = i; 1555 } 1556 } 1557 return ((e1 + 2) % iNrWorkDays == f2); 1558 } 1559 1560 private static boolean sameDays(int[] days1, int[] days2) { 1561 if (days2.length < days1.length) 1562 return sameDays(days2, days1); 1563 int i2 = 0; 1564 for (int i1 = 0; i1 < days1.length; i1++) { 1565 int d1 = days1[i1]; 1566 while (true) { 1567 if (i2 == days2.length) 1568 return false; 1569 int d2 = days2[i2]; 1570 if (d1 == d2) 1571 break; 1572 i2++; 1573 if (i2 == days2.length) 1574 return false; 1575 } 1576 i2++; 1577 } 1578 return true; 1579 } 1580 1581 private static boolean sameRoomAndOverlaps(Placement p1, Placement p2) { 1582 return p1.shareRooms(p2) && p1.getTimeLocation() != null && p2.getTimeLocation() != null && p1.getTimeLocation().hasIntersection(p2.getTimeLocation()); 1583 } 1584 1585 private static boolean sameHours(int start1, int len1, int start2, int len2) { 1586 if (len1 > len2) 1587 return sameHours(start2, len2, start1, len1); 1588 start1 %= Constants.SLOTS_PER_DAY; 1589 start2 %= Constants.SLOTS_PER_DAY; 1590 return (start1 >= start2 && start1 + len1 <= start2 + len2); 1591 } 1592 1593 private static boolean canFill(int totalGap, int gapMin, int gapMax, List<Integer> lengths) { 1594 if (gapMin <= totalGap && totalGap <= gapMax) 1595 return true; 1596 if (totalGap < 2 * gapMin) 1597 return false; 1598 for (int i = 0; i < lengths.size(); i++) { 1599 int length = lengths.get(i); 1600 lengths.remove(i); 1601 for (int gap = gapMin; gap <= gapMax; gap++) 1602 if (canFill(totalGap - gap - length, gapMin, gapMax, lengths)) 1603 return true; 1604 lengths.add(i, length); 1605 } 1606 return false; 1607 } 1608 1609 private boolean isSatisfiedSeq(Assignment<Lecture, Placement> assignment, HashMap<Lecture, Placement> assignments, Set<Placement> conflicts) { 1610 if (conflicts == null) 1611 return isSatisfiedSeqCheck(assignment, assignments, conflicts); 1612 else { 1613 Set<Placement> bestConflicts = isSatisfiedRecursive(assignment, 0, assignments, conflicts, 1614 new HashSet<Placement>(), null); 1615 if (bestConflicts == null) 1616 return false; 1617 conflicts.addAll(bestConflicts); 1618 return true; 1619 } 1620 } 1621 1622 private Set<Placement> isSatisfiedRecursive(Assignment<Lecture, Placement> assignment, int idx, HashMap<Lecture, Placement> assignments, 1623 Set<Placement> conflicts, Set<Placement> newConflicts, Set<Placement> bestConflicts) { 1624 if (idx == variables().size() && newConflicts.isEmpty()) 1625 return bestConflicts; 1626 if (isSatisfiedSeqCheck(assignment, assignments, conflicts)) { 1627 if (bestConflicts == null) { 1628 return new HashSet<Placement>(newConflicts); 1629 } else { 1630 int b = 0, n = 0; 1631 for (Placement value: assignments.values()) { 1632 if (value != null && bestConflicts.contains(value)) b++; 1633 if (value != null && newConflicts.contains(value)) n++; 1634 } 1635 if (n < b || (n == b && newConflicts.size() < bestConflicts.size())) 1636 return new HashSet<Placement>(newConflicts); 1637 } 1638 return bestConflicts; 1639 } 1640 if (idx == variables().size()) 1641 return bestConflicts; 1642 bestConflicts = isSatisfiedRecursive(assignment, idx + 1, assignments, conflicts, newConflicts, 1643 bestConflicts); 1644 Lecture lecture = variables().get(idx); 1645 //if (assignments != null && assignments.containsKey(lecture)) 1646 // return bestConflicts; 1647 Placement placement = null; 1648 if (assignments != null && assignments.containsKey(lecture)) 1649 placement = assignments.get(lecture); 1650 else if (assignment != null) 1651 placement = assignment.getValue(lecture); 1652 if (placement == null) 1653 return bestConflicts; 1654 if (conflicts != null && conflicts.contains(placement)) 1655 return bestConflicts; 1656 conflicts.add(placement); 1657 newConflicts.add(placement); 1658 bestConflicts = isSatisfiedRecursive(assignment, idx + 1, assignments, conflicts, newConflicts, bestConflicts); 1659 newConflicts.remove(placement); 1660 conflicts.remove(placement); 1661 return bestConflicts; 1662 } 1663 1664 private boolean isSatisfiedSeqCheck(Assignment<Lecture, Placement> assignment, HashMap<Lecture, Placement> assignments, Set<Placement> conflicts) { 1665 if (!getType().is(Flag.BACK_TO_BACK)) return true; 1666 int gapMin = getType().getMin(); 1667 int gapMax = getType().getMax(); 1668 1669 List<Integer> lengths = new ArrayList<Integer>(); 1670 1671 Placement[] res = new Placement[Constants.SLOTS_PER_DAY]; 1672 for (int i = 0; i < Constants.SLOTS_PER_DAY; i++) 1673 res[i] = null; 1674 1675 int nrLectures = 0; 1676 1677 for (Lecture lecture : variables()) { 1678 Placement placement = null; 1679 if (assignments != null && assignments.containsKey(lecture)) 1680 placement = assignments.get(lecture); 1681 else if (assignment != null) 1682 placement = assignment.getValue(lecture); 1683 if (placement == null) { 1684 if (!lecture.timeLocations().isEmpty()) 1685 lengths.add(lecture.timeLocations().get(0).getLength()); 1686 } else if (conflicts != null && conflicts.contains(placement)) { 1687 if (!lecture.timeLocations().isEmpty()) 1688 lengths.add(lecture.timeLocations().get(0).getLength()); 1689 } else { 1690 int pos = placement.getTimeLocation().getStartSlot(); 1691 int length = placement.getTimeLocation().getLength(); 1692 for (int j = pos; j < pos + length; j++) { 1693 if (res[j] != null) { 1694 if (conflicts == null) 1695 return false; 1696 if (!assignments.containsKey(lecture)) 1697 conflicts.add(placement); 1698 else if (!assignments.containsKey(res[j].variable())) 1699 conflicts.add(res[j]); 1700 } 1701 } 1702 for (int j = pos; j < pos + length; j++) 1703 res[j] = placement; 1704 nrLectures++; 1705 } 1706 } 1707 if (nrLectures <= 1) 1708 return true; 1709 1710 if (iIsRequired || (!iIsProhibited && iPreference < 0)) { 1711 int i = 0; 1712 Placement p = res[i]; 1713 while (p == null) 1714 p = res[++i]; 1715 i = res[i].getTimeLocation().getStartSlot() + res[i].getTimeLocation().getLength(); 1716 nrLectures--; 1717 while (nrLectures > 0) { 1718 int gap = 0; 1719 while (i < Constants.SLOTS_PER_DAY && res[i] == null) { 1720 gap++; 1721 i++; 1722 } 1723 if (i == Constants.SLOTS_PER_DAY) 1724 break; 1725 if (!canFill(gap, gapMin, gapMax, lengths)) 1726 return false; 1727 p = res[i]; 1728 i = res[i].getTimeLocation().getStartSlot() + res[i].getTimeLocation().getLength(); 1729 nrLectures--; 1730 } 1731 } else if (iIsProhibited || (!iIsRequired && iPreference > 0)) { 1732 int i = 0; 1733 Placement p = res[i]; 1734 while (p == null) 1735 p = res[++i]; 1736 i = res[i].getTimeLocation().getStartSlot() + res[i].getTimeLocation().getLength(); 1737 nrLectures--; 1738 while (nrLectures > 0) { 1739 int gap = 0; 1740 while (i < Constants.SLOTS_PER_DAY && res[i] == null) { 1741 gap++; 1742 i++; 1743 } 1744 if (i == Constants.SLOTS_PER_DAY) 1745 break; 1746 if ((gapMin == 0 || !canFill(gap, 0, gapMin - 1, lengths)) 1747 && (gapMax >= Constants.SLOTS_PER_DAY || !canFill(gap, gapMax + 1, Constants.SLOTS_PER_DAY, 1748 lengths))) { 1749 return false; 1750 } 1751 p = res[i]; 1752 i = res[i].getTimeLocation().getStartSlot() + res[i].getTimeLocation().getLength(); 1753 nrLectures--; 1754 } 1755 } 1756 return true; 1757 } 1758 1759 public boolean isSatisfied(Assignment<Lecture, Placement> assignment) { 1760 if (isHard()) return true; 1761 if (countAssignedVariables(assignment) < 2) return true; 1762 if (getPreference() == 0) return true; 1763 return isHard() || countAssignedVariables(assignment) < 2 || getPreference() == 0 || getCurrentPreference(assignment) < 0; 1764 } 1765 1766 public boolean isChildrenNotOverlap(Assignment<Lecture, Placement> assignment, Lecture lec1, Placement plc1, Lecture lec2, Placement plc2) { 1767 if (lec1.getSchedulingSubpartId().equals(lec2.getSchedulingSubpartId())) { 1768 // same subpart 1769 boolean overlap = plc1.getTimeLocation().hasIntersection(plc2.getTimeLocation()); 1770 1771 if (overlap && lec1.getParent() != null && variables().contains(lec1.getParent()) 1772 && lec2.getParent() != null && variables().contains(lec2.getParent())) { 1773 // children overlaps 1774 Placement p1 = assignment.getValue(lec1.getParent()); 1775 Placement p2 = assignment.getValue(lec2.getParent()); 1776 // parents not overlap, but children do 1777 if (p1 != null && p2 != null && !p1.getTimeLocation().hasIntersection(p2.getTimeLocation())) 1778 return false; 1779 } 1780 1781 if (!overlap && lec1.getChildrenSubpartIds() != null && lec2.getChildrenSubpartIds() != null) { 1782 // parents not overlap 1783 for (Long subpartId: lec1.getChildrenSubpartIds()) { 1784 for (Lecture c1 : lec1.getChildren(subpartId)) { 1785 Placement p1 = assignment.getValue(c1); 1786 if (p1 == null) continue; 1787 for (Lecture c2 : lec2.getChildren(subpartId)) { 1788 Placement p2 = assignment.getValue(c2); 1789 if (p2 == null) continue; 1790 if (!c1.getSchedulingSubpartId().equals(c2.getSchedulingSubpartId())) continue; 1791 // parents not overlap, but children do 1792 if (p1.getTimeLocation().hasIntersection(p2.getTimeLocation())) 1793 return false; 1794 } 1795 } 1796 } 1797 } 1798 } else { 1799 // different subpart 1800 } 1801 return true; 1802 } 1803 1804 public boolean isSatisfiedPair(Assignment<Lecture, Placement> assignment, Placement plc1, Placement plc2) { 1805 if (iIsRequired || (!iIsProhibited && iPreference <= 0)) 1806 return getType().isSatisfied(assignment, this, plc1, plc2); 1807 else if (iIsProhibited || (!iIsRequired && iPreference > 0)) 1808 return getType().isViolated(assignment, this, plc1, plc2); 1809 return true; 1810 } 1811 1812 public boolean canShareRoom() { 1813 return getType().is(Flag.CAN_SHARE_ROOM); 1814 } 1815 1816 private int nrSlotsADay(Assignment<Lecture, Placement> assignment, int dayCode, BitSet week, HashMap<Lecture, Placement> assignments, Set<Placement> conflicts) { 1817 Set<Integer> slots = new HashSet<Integer>(); 1818 for (Lecture lecture: variables()) { 1819 Placement placement = null; 1820 if (assignments != null && assignments.containsKey(lecture)) 1821 placement = assignments.get(lecture); 1822 else if (assignment != null) 1823 placement = assignment.getValue(lecture); 1824 if (placement == null || placement.getTimeLocation() == null) continue; 1825 if (conflicts != null && conflicts.contains(placement)) continue; 1826 TimeLocation t = placement.getTimeLocation(); 1827 if (t == null || (t.getDayCode() & dayCode) == 0 || (week != null && !t.shareWeeks(week))) continue; 1828 for (int i = 0; i < t.getLength(); i++) 1829 slots.add(i + t.getStartSlot()); 1830 } 1831 return slots.size(); 1832 } 1833 1834 @Override 1835 public boolean equals(Object o) { 1836 if (o == null || !(o instanceof GroupConstraint)) return false; 1837 return getGeneratedId() == ((GroupConstraint) o).getGeneratedId(); 1838 } 1839 1840 @Override 1841 public GroupConstraintContext createAssignmentContext(Assignment<Lecture, Placement> assignment) { 1842 return new GroupConstraintContext(assignment); 1843 } 1844 1845 public class GroupConstraintContext implements AssignmentConstraintContext<Lecture, Placement> { 1846 private int iLastPreference = 0; 1847 1848 public GroupConstraintContext(Assignment<Lecture, Placement> assignment) { 1849 updateCriterion(assignment); 1850 } 1851 1852 @Override 1853 public void assigned(Assignment<Lecture, Placement> assignment, Placement value) { 1854 updateCriterion(assignment); 1855 } 1856 1857 @Override 1858 public void unassigned(Assignment<Lecture, Placement> assignment, Placement value) { 1859 updateCriterion(assignment); 1860 } 1861 1862 private void updateCriterion(Assignment<Lecture, Placement> assignment) { 1863 if (!isHard()) { 1864 getModel().getCriterion(DistributionPreferences.class).inc(assignment, -iLastPreference); 1865 iLastPreference = getCurrentPreference(assignment) + Math.abs(iPreference); 1866 getModel().getCriterion(DistributionPreferences.class).inc(assignment, iLastPreference); 1867 } 1868 } 1869 1870 public int getPreference() { return iLastPreference; } 1871 } 1872}