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