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()) || l.isConstant()) 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                                if (adepts.isEmpty()) { conflicts.add(value); break; }
996                                Placement conflict = ToolBox.random(adepts);
997                                adepts.remove(conflict);
998                                conflicts.add(conflict);
999                            } while (nrSlotsADay(assignment, dayCode, week, assignments, conflicts) > getType().getMax());
1000                        }
1001                    }
1002                } else {
1003                    if (nrSlotsADay(assignment, dayCode, null, assignments, conflicts) > getType().getMax()) {
1004                        List<Placement> adepts = new ArrayList<Placement>();
1005                        for (Lecture l: variables()) {
1006                            if (l.equals(value.variable()) || l.isConstant()) continue;
1007                            Placement p = assignment.getValue(l);
1008                            if (p == null || conflicts.contains(p) || p.getTimeLocation() == null) continue;
1009                            if ((p.getTimeLocation().getDayCode() & dayCode) == 0) continue;
1010                            adepts.add(p);
1011                        }
1012                        do {
1013                            if (adepts.isEmpty()) { conflicts.add(value); break; }
1014                            Placement conflict = ToolBox.random(adepts);
1015                            adepts.remove(conflict);
1016                            conflicts.add(conflict);
1017                        } while (nrSlotsADay(assignment, dayCode, null, assignments, conflicts) > getType().getMax());
1018                    }
1019                }
1020            }
1021        }
1022        
1023        // Forward checking
1024        if (fwdCheck) forwardCheck(assignment, value, conflicts, new HashSet<GroupConstraint>(), iForwardCheckMaxDepth - 1);
1025    }
1026    
1027    public void forwardCheck(Assignment<Lecture, Placement> assignment, Placement value, Set<Placement> conflicts, Set<GroupConstraint> ignore, int depth) {
1028        try {
1029            if (depth < 0) return;
1030            ignore.add(this);
1031            
1032            int neededSize = value.variable().maxRoomUse();
1033            
1034            for (Lecture lecture: variables()) {
1035                if (conflicts.contains(value)) break; // already conflicting
1036
1037                if (lecture.equals(value.variable())) continue; // Skip this lecture
1038                Placement current = assignment.getValue(lecture);
1039                if (current != null) { // Has assignment, check whether it is conflicting
1040                    if (isSatisfiedPair(assignment, value, current)) {
1041                        // Increase needed size if the assignment is of the same room and overlapping in time
1042                        if (canShareRoom() && sameRoomAndOverlaps(value, current)) {
1043                            neededSize += lecture.maxRoomUse();
1044                        }
1045                        continue;
1046                    }
1047                    conflicts.add(current);
1048                }
1049                
1050                // Look for supporting assignments assignment
1051                boolean shareRoomAndOverlaps = canShareRoom();
1052                Placement support = null;
1053                int nrSupports = 0;
1054                if (lecture.nrValues() >= iForwardCheckMaxDomainSize) {
1055                    // ignore variables with large domains
1056                    return;
1057                }
1058                List<Placement> values = lecture.values(assignment);
1059                if (values.isEmpty()) {
1060                    // ignore variables with empty domain
1061                    return;
1062                }
1063                for (Placement other: values) {
1064                    if (nrSupports < 2) {
1065                        if (isSatisfiedPair(assignment, value, other)) {
1066                            if (support == null) support = other;
1067                            nrSupports ++;
1068                            if (shareRoomAndOverlaps && !sameRoomAndOverlaps(value, other))
1069                                shareRoomAndOverlaps = false;
1070                        }
1071                    } else if (shareRoomAndOverlaps && !sameRoomAndOverlaps(value, other) && isSatisfiedPair(assignment, value, other)) {
1072                        shareRoomAndOverlaps = false;
1073                    }
1074                    if (nrSupports > 1 && !shareRoomAndOverlaps)
1075                        break;
1076                }
1077                
1078                // No supporting assignment -> fail
1079                if (nrSupports == 0) {
1080                    conflicts.add(value); // other class cannot be assigned with this value
1081                    return;
1082                }
1083                // Increase needed size if all supporters are of the same room and in overlapping times
1084                if (shareRoomAndOverlaps) {
1085                    neededSize += lecture.maxRoomUse();
1086                }
1087
1088                // Only one supporter -> propagate the new assignment over other hard constraints of the lecture
1089                if (nrSupports == 1) {
1090                    for (Constraint<Lecture, Placement> other: lecture.hardConstraints()) {
1091                        if (other instanceof WeakeningConstraint) continue;
1092                        if (other instanceof GroupConstraint) {
1093                            GroupConstraint gc = (GroupConstraint)other;
1094                            if (depth > 0 && !ignore.contains(gc))
1095                                gc.forwardCheck(assignment, support, conflicts, ignore, depth - 1);
1096                        } else {
1097                            other.computeConflicts(assignment, support, conflicts);
1098                        }
1099                    }
1100                    for (GlobalConstraint<Lecture, Placement> other: getModel().globalConstraints()) {
1101                        if (other instanceof WeakeningConstraint) continue;
1102                        other.computeConflicts(assignment, support, conflicts);
1103                    }
1104
1105                    if (conflicts.contains(support))
1106                        conflicts.add(value);
1107                }
1108            }
1109            
1110            if (canShareRoom() && neededSize > value.getRoomSize()) {
1111                // room is too small to fit all meet with classes
1112                conflicts.add(value);
1113            }
1114            
1115        } finally {
1116            ignore.remove(this);
1117        }
1118    }
1119
1120    @Override
1121    public boolean inConflict(Assignment<Lecture, Placement> assignment, Placement value) {
1122        if (!isHard())
1123            return false;
1124        for (Lecture v : variables()) {
1125            if (v.equals(value.variable()))
1126                continue; // ignore this variable
1127            Placement p = assignment.getValue(v);
1128            if (p == null)
1129                continue; // there is an unassigned variable -- great, still a chance to get violated
1130            if (!isSatisfiedPair(assignment, p, value))
1131                return true;
1132        }
1133        if (getType().is(Flag.BACK_TO_BACK)) {
1134            HashMap<Lecture, Placement> assignments = new HashMap<Lecture, Placement>();
1135            assignments.put(value.variable(), value);
1136            if (!isSatisfiedSeq(assignment, assignments, null))
1137                return true;
1138        }
1139        if (getType().is(Flag.MAX_HRS_DAY)) {
1140            HashMap<Lecture, Placement> assignments = new HashMap<Lecture, Placement>();
1141            assignments.put(value.variable(), value);
1142            for (int dayCode: Constants.DAY_CODES) {
1143                if (iMaxNHoursADayConsiderDatePatterns) {
1144                    for (BitSet week: ((TimetableModel)getModel()).getWeeks()) {
1145                        if (!value.getTimeLocation().shareWeeks(week)) continue;
1146                        if (nrSlotsADay(assignment, dayCode, week, assignments, null) > getType().getMax())
1147                            return true;
1148                    }
1149                } else {
1150                    if (nrSlotsADay(assignment, dayCode, null, assignments, null) > getType().getMax()) return true;
1151                }
1152            }
1153        }
1154        
1155        if (!forwardCheck(assignment, value, new HashSet<GroupConstraint>(), iForwardCheckMaxDepth - 1)) return true;
1156        
1157        return false;
1158    }
1159    
1160    public boolean forwardCheck(Assignment<Lecture, Placement> assignment, Placement value, Set<GroupConstraint> ignore, int depth) {
1161        try {
1162            if (depth < 0) return true;
1163            ignore.add(this);
1164            
1165            int neededSize = value.variable().maxRoomUse();
1166            
1167            for (Lecture lecture: variables()) {
1168                if (lecture.equals(value.variable())) continue; // Skip this lecture
1169                Placement current = assignment.getValue(lecture);
1170                if (current != null) { // Has assignment, check whether it is conflicting
1171                    if (isSatisfiedPair(assignment, value, current)) {
1172                        // Increase needed size if the assignment is of the same room and overlapping in time
1173                        if (canShareRoom() && sameRoomAndOverlaps(value, current)) {
1174                            neededSize += lecture.maxRoomUse();
1175                        }
1176                        continue;
1177                    }
1178                    return false;
1179                }
1180                
1181                // Look for supporting assignments assignment
1182                boolean shareRoomAndOverlaps = canShareRoom();
1183                Placement support = null;
1184                int nrSupports = 0;
1185                if (lecture.nrValues() >= iForwardCheckMaxDomainSize) {
1186                    // ignore variables with large domains
1187                    return true;
1188                }
1189                List<Placement> values = lecture.values(assignment);
1190                if (values.isEmpty()) {
1191                    // ignore variables with empty domain
1192                    return true;
1193                }
1194                for (Placement other: lecture.values(assignment)) {
1195                    if (nrSupports < 2) {
1196                        if (isSatisfiedPair(assignment, value, other)) {
1197                            if (support == null) support = other;
1198                            nrSupports ++;
1199                            if (shareRoomAndOverlaps && !sameRoomAndOverlaps(value, other))
1200                                shareRoomAndOverlaps = false;
1201                        }
1202                    } else if (shareRoomAndOverlaps && !sameRoomAndOverlaps(value, other) && isSatisfiedPair(assignment, value, other)) {
1203                        shareRoomAndOverlaps = false;
1204                    }
1205                    if (nrSupports > 1 && !shareRoomAndOverlaps)
1206                        break;
1207                }
1208
1209                // No supporting assignment -> fail
1210                if (nrSupports == 0) {
1211                    return false; // other class cannot be assigned with this value
1212                }
1213                // Increase needed size if all supporters are of the same room and in overlapping times
1214                if (shareRoomAndOverlaps) {
1215                    neededSize += lecture.maxRoomUse();
1216                }
1217
1218                // Only one supporter -> propagate the new assignment over other hard constraints of the lecture
1219                if (nrSupports == 1) {
1220                    for (Constraint<Lecture, Placement> other: lecture.hardConstraints()) {
1221                        if (other instanceof WeakeningConstraint) continue;
1222                        if (other instanceof GroupConstraint) {
1223                            GroupConstraint gc = (GroupConstraint)other;
1224                            if (depth > 0 && !ignore.contains(gc) && !gc.forwardCheck(assignment, support, ignore, depth - 1)) return false;
1225                        } else {
1226                            if (other.inConflict(assignment, support)) return false;
1227                        }
1228                    }
1229                    for (GlobalConstraint<Lecture, Placement> other: getModel().globalConstraints()) {
1230                        if (other instanceof WeakeningConstraint) continue;
1231                        if (other.inConflict(assignment, support)) return false;
1232                    }
1233                }
1234            }
1235            
1236            if (canShareRoom() && neededSize > value.getRoomSize()) {
1237                // room is too small to fit all meet with classes
1238                return false;
1239            }
1240         
1241            return true;
1242        } finally {
1243            ignore.remove(this);
1244        }
1245    }
1246
1247    /** Constraint preference (0 if prohibited or required) 
1248     * @return constraint preference (if soft)
1249     **/
1250    public int getPreference() {
1251        return iPreference;
1252    }
1253
1254    /**
1255     * Current constraint preference (0 if prohibited or required, depends on
1256     * current satisfaction of the constraint)
1257     * @param assignment current assignment
1258     * @return current preference
1259     */
1260    public int getCurrentPreference(Assignment<Lecture, Placement> assignment) {
1261        if (isHard()) return 0; // no preference
1262        if (countAssignedVariables(assignment) < 2) return - Math.abs(iPreference); // not enough variable
1263        if (getType().is(Flag.MAX_HRS_DAY)) { // max hours a day
1264            int over = 0;
1265            for (int dayCode: Constants.DAY_CODES) {
1266                if (iMaxNHoursADayConsiderDatePatterns) {
1267                    for (BitSet week: ((TimetableModel)getModel()).getWeeks())
1268                        over += Math.max(0, nrSlotsADay(assignment, dayCode, week, null, null) - getType().getMax());
1269                } else {
1270                    over += Math.max(0, nrSlotsADay(assignment, dayCode, null, null, null) - getType().getMax());
1271                }
1272            }
1273            return (over > 0 ? Math.abs(iPreference) * over / 12 : - Math.abs(iPreference));
1274        }
1275        int nrViolatedPairs = 0;
1276        for (Lecture v1 : variables()) {
1277            Placement p1 = assignment.getValue(v1);
1278            if (p1 == null) continue;
1279            for (Lecture v2 : variables()) {
1280                Placement p2 = assignment.getValue(v2);
1281                if (p2 == null || v1.getId() >= v2.getId()) continue;
1282                if (!isSatisfiedPair(assignment, p1, p2)) nrViolatedPairs++;
1283            }
1284        }
1285        if (getType().is(Flag.BACK_TO_BACK)) {
1286            Set<Placement> conflicts = new HashSet<Placement>();
1287            if (isSatisfiedSeq(assignment, new HashMap<Lecture, Placement>(), conflicts))
1288                nrViolatedPairs += conflicts.size();
1289            else
1290                nrViolatedPairs = variables().size();
1291        }
1292        return (nrViolatedPairs > 0 ? Math.abs(iPreference) * nrViolatedPairs : - Math.abs(iPreference));
1293    }
1294
1295    /** Current constraint preference change (if given placement is assigned) 
1296     * @param assignment current assignment
1297     * @param placement placement that is being considered
1298     * @return change in the current preference, if assigned 
1299     **/
1300    public int getCurrentPreference(Assignment<Lecture, Placement> assignment, Placement placement) {
1301        if (isHard()) return 0; // no preference
1302        if (countAssignedVariables(assignment) + (assignment.getValue(placement.variable()) == null ? 1 : 0) < 2) return 0; // not enough variable
1303        if (getType().is(Flag.MAX_HRS_DAY)) {
1304            HashMap<Lecture, Placement> assignments = new HashMap<Lecture, Placement>();
1305            assignments.put(placement.variable(), placement);
1306            HashMap<Lecture, Placement> unassignments = new HashMap<Lecture, Placement>();
1307            unassignments.put(placement.variable(), null);
1308            int after = 0;
1309            int before = 0;
1310            for (int dayCode: Constants.DAY_CODES) {
1311                if (iMaxNHoursADayConsiderDatePatterns) {
1312                    for (BitSet week: ((TimetableModel)getModel()).getWeeks()) {
1313                        after += Math.max(0, nrSlotsADay(assignment, dayCode, week, assignments, null) - getType().getMax());
1314                        before += Math.max(0, nrSlotsADay(assignment, dayCode, week, unassignments, null) - getType().getMax());
1315                    }
1316                } else {
1317                    after += Math.max(0, nrSlotsADay(assignment, dayCode, null, assignments, null) - getType().getMax());
1318                    before += Math.max(0, nrSlotsADay(assignment, dayCode, null, unassignments, null) - getType().getMax());
1319                }
1320            }
1321            return (after > 0 ? Math.abs(iPreference) * after / 12 : - Math.abs(iPreference)) - (before > 0 ? Math.abs(iPreference) * before / 12 : - Math.abs(iPreference));
1322        }
1323        
1324        int nrViolatedPairsAfter = 0;
1325        int nrViolatedPairsBefore = 0;
1326        for (Lecture v1 : variables()) {
1327            for (Lecture v2 : variables()) {
1328                if (v1.getId() >= v2.getId()) continue;
1329                Placement p1 = (v1.equals(placement.variable()) ? null : assignment.getValue(v1));
1330                Placement p2 = (v2.equals(placement.variable()) ? null : assignment.getValue(v2));
1331                if (p1 != null && p2 != null && !isSatisfiedPair(assignment, p1, p2))
1332                    nrViolatedPairsBefore ++;
1333                if (v1.equals(placement.variable())) p1 = placement;
1334                if (v2.equals(placement.variable())) p2 = placement;
1335                if (p1 != null && p2 != null && !isSatisfiedPair(assignment, p1, p2))
1336                    nrViolatedPairsAfter ++;
1337            }
1338        }
1339        
1340        if (getType().is(Flag.BACK_TO_BACK)) {
1341            HashMap<Lecture, Placement> assignments = new HashMap<Lecture, Placement>();
1342            assignments.put(placement.variable(), placement);
1343            Set<Placement> conflicts = new HashSet<Placement>();
1344            if (isSatisfiedSeq(assignment, assignments, conflicts))
1345                nrViolatedPairsAfter += conflicts.size();
1346            else
1347                nrViolatedPairsAfter = variables().size();
1348            
1349            HashMap<Lecture, Placement> unassignments = new HashMap<Lecture, Placement>();
1350            unassignments.put(placement.variable(), null);
1351            Set<Placement> previous = new HashSet<Placement>();
1352            if (isSatisfiedSeq(assignment, unassignments, previous))
1353                nrViolatedPairsBefore += previous.size();
1354            else
1355                nrViolatedPairsBefore = variables().size();
1356        }
1357        
1358        return (nrViolatedPairsAfter > 0 ? Math.abs(iPreference) * nrViolatedPairsAfter : - Math.abs(iPreference)) -
1359                (nrViolatedPairsBefore > 0 ? Math.abs(iPreference) * nrViolatedPairsBefore : - Math.abs(iPreference));
1360    }
1361
1362    @Override
1363    public String toString() {
1364        StringBuffer sb = new StringBuffer();
1365        sb.append(getName());
1366        sb.append(" between ");
1367        for (Iterator<Lecture> e = variables().iterator(); e.hasNext();) {
1368            Lecture v = e.next();
1369            sb.append(v.getName());
1370            if (e.hasNext())
1371                sb.append(", ");
1372        }
1373        return sb.toString();
1374    }
1375
1376    @Override
1377    public boolean isHard() {
1378        return iIsRequired || iIsProhibited;
1379    }
1380
1381    @Override
1382    public String getName() {
1383        return getType().getName();
1384    }
1385
1386
1387    private boolean isPrecedence(Placement p1, Placement p2, boolean firstGoesFirst, boolean considerDatePatterns) {
1388        int ord1 = variables().indexOf(p1.variable());
1389        int ord2 = variables().indexOf(p2.variable());
1390        TimeLocation t1 = null, t2 = null;
1391        if (ord1 < ord2) {
1392            if (firstGoesFirst) {
1393                t1 = p1.getTimeLocation();
1394                t2 = p2.getTimeLocation();
1395            } else {
1396                t2 = p1.getTimeLocation();
1397                t1 = p2.getTimeLocation();
1398            }
1399        } else {
1400            if (!firstGoesFirst) {
1401                t1 = p1.getTimeLocation();
1402                t2 = p2.getTimeLocation();
1403            } else {
1404                t2 = p1.getTimeLocation();
1405                t1 = p2.getTimeLocation();
1406            }
1407        }
1408        if (considerDatePatterns && iPrecedenceConsiderDatePatterns) {
1409            boolean sameDatePattern = (t1.getDatePatternId() != null ? t1.getDatePatternId().equals(t2.getDatePatternId()) : t1.getWeekCode().equals(t2.getWeekCode()));
1410            if (!sameDatePattern) {
1411                int m1 = t1.getFirstMeeting(iDayOfWeekOffset), m2 = t2.getFirstMeeting(iDayOfWeekOffset);
1412                if (m1 != m2) return m1 < m2;
1413            }
1414        }
1415        return t1.getStartSlots().nextElement() + t1.getLength() <= t2.getStartSlots().nextElement();
1416    }
1417
1418    private static boolean isBackToBackDays(TimeLocation t1, TimeLocation t2) {
1419        int f1 = -1, f2 = -1, e1 = -1, e2 = -1;
1420        for (int i = 0; i < Constants.DAY_CODES.length; i++) {
1421            if ((t1.getDayCode() & Constants.DAY_CODES[i]) != 0) {
1422                if (f1 < 0)
1423                    f1 = i;
1424                e1 = i;
1425            }
1426            if ((t2.getDayCode() & Constants.DAY_CODES[i]) != 0) {
1427                if (f2 < 0)
1428                    f2 = i;
1429                e2 = i;
1430            }
1431        }
1432        return (e1 + 1 == f2) || (e2 + 1 == f1);
1433    }
1434    
1435    private static boolean isNrDaysBetweenGreaterThanOne(TimeLocation t1, TimeLocation t2) {
1436        int f1 = -1, f2 = -1, e1 = -1, e2 = -1;
1437        for (int i = 0; i < Constants.DAY_CODES.length; i++) {
1438            if ((t1.getDayCode() & Constants.DAY_CODES[i]) != 0) {
1439                if (f1 < 0)
1440                    f1 = i;
1441                e1 = i;
1442            }
1443            if ((t2.getDayCode() & Constants.DAY_CODES[i]) != 0) {
1444                if (f2 < 0)
1445                    f2 = i;
1446                e2 = i;
1447            }
1448        }
1449        return (e1 - f2 > 2) || (e2 - f1 > 2);
1450    }
1451
1452    private boolean isFollowingDay(Placement p1, Placement p2, boolean firstGoesFirst) {
1453        int ord1 = variables().indexOf(p1.variable());
1454        int ord2 = variables().indexOf(p2.variable());
1455        TimeLocation t1 = null, t2 = null;
1456        if (ord1 < ord2) {
1457            if (firstGoesFirst) {
1458                t1 = p1.getTimeLocation();
1459                t2 = p2.getTimeLocation();
1460            } else {
1461                t2 = p1.getTimeLocation();
1462                t1 = p2.getTimeLocation();
1463            }
1464        } else {
1465            if (!firstGoesFirst) {
1466                t1 = p1.getTimeLocation();
1467                t2 = p2.getTimeLocation();
1468            } else {
1469                t2 = p1.getTimeLocation();
1470                t1 = p2.getTimeLocation();
1471            }
1472        }
1473        int f1 = -1, f2 = -1, e1 = -1;
1474        for (int i = 0; i < Constants.DAY_CODES.length; i++) {
1475            if ((t1.getDayCode() & Constants.DAY_CODES[i]) != 0) {
1476                if (f1 < 0)
1477                    f1 = i;
1478                e1 = i;
1479            }
1480            if ((t2.getDayCode() & Constants.DAY_CODES[i]) != 0) {
1481                if (f2 < 0)
1482                    f2 = i;
1483            }
1484        }
1485        return ((e1 + 1) % iNrWorkDays == f2);
1486    }
1487
1488    private boolean isEveryOtherDay(Placement p1, Placement p2, boolean firstGoesFirst) {
1489        int ord1 = variables().indexOf(p1.variable());
1490        int ord2 = variables().indexOf(p2.variable());
1491        TimeLocation t1 = null, t2 = null;
1492        if (ord1 < ord2) {
1493            if (firstGoesFirst) {
1494                t1 = p1.getTimeLocation();
1495                t2 = p2.getTimeLocation();
1496            } else {
1497                t2 = p1.getTimeLocation();
1498                t1 = p2.getTimeLocation();
1499            }
1500        } else {
1501            if (!firstGoesFirst) {
1502                t1 = p1.getTimeLocation();
1503                t2 = p2.getTimeLocation();
1504            } else {
1505                t2 = p1.getTimeLocation();
1506                t1 = p2.getTimeLocation();
1507            }
1508        }
1509        int f1 = -1, f2 = -1, e1 = -1;
1510        for (int i = 0; i < Constants.DAY_CODES.length; i++) {
1511            if ((t1.getDayCode() & Constants.DAY_CODES[i]) != 0) {
1512                if (f1 < 0)
1513                    f1 = i;
1514                e1 = i;
1515            }
1516            if ((t2.getDayCode() & Constants.DAY_CODES[i]) != 0) {
1517                if (f2 < 0)
1518                    f2 = i;
1519            }
1520        }
1521        return ((e1 + 2) % iNrWorkDays == f2);
1522    }
1523
1524    private static boolean sameDays(int[] days1, int[] days2) {
1525        if (days2.length < days1.length)
1526            return sameDays(days2, days1);
1527        int i2 = 0;
1528        for (int i1 = 0; i1 < days1.length; i1++) {
1529            int d1 = days1[i1];
1530            while (true) {
1531                if (i2 == days2.length)
1532                    return false;
1533                int d2 = days2[i2];
1534                if (d1 == d2)
1535                    break;
1536                i2++;
1537                if (i2 == days2.length)
1538                    return false;
1539            }
1540            i2++;
1541        }
1542        return true;
1543    }
1544    
1545    private static boolean sameRoomAndOverlaps(Placement p1, Placement p2) {
1546        return p1.shareRooms(p2) && p1.getTimeLocation() != null && p2.getTimeLocation() != null && p1.getTimeLocation().hasIntersection(p2.getTimeLocation());
1547    }
1548
1549    private static boolean sameHours(int start1, int len1, int start2, int len2) {
1550        if (len1 > len2)
1551            return sameHours(start2, len2, start1, len1);
1552        start1 %= Constants.SLOTS_PER_DAY;
1553        start2 %= Constants.SLOTS_PER_DAY;
1554        return (start1 >= start2 && start1 + len1 <= start2 + len2);
1555    }
1556    
1557    private static boolean canFill(int totalGap, int gapMin, int gapMax, List<Integer> lengths) {
1558        if (gapMin <= totalGap && totalGap <= gapMax)
1559            return true;
1560        if (totalGap < 2 * gapMin)
1561            return false;
1562        for (int i = 0; i < lengths.size(); i++) {
1563            int length = lengths.get(i);
1564            lengths.remove(i);
1565            for (int gap = gapMin; gap <= gapMax; gap++)
1566                if (canFill(totalGap - gap - length, gapMin, gapMax, lengths))
1567                    return true;
1568            lengths.add(i, length);
1569        }
1570        return false;
1571    }
1572
1573    private boolean isSatisfiedSeq(Assignment<Lecture, Placement> assignment, HashMap<Lecture, Placement> assignments, Set<Placement> conflicts) {
1574        if (conflicts == null)
1575            return isSatisfiedSeqCheck(assignment, assignments, conflicts);
1576        else {
1577            Set<Placement> bestConflicts = isSatisfiedRecursive(assignment, 0, assignments, conflicts,
1578                    new HashSet<Placement>(), null);
1579            if (bestConflicts == null)
1580                return false;
1581            conflicts.addAll(bestConflicts);
1582            return true;
1583        }
1584    }
1585
1586    private Set<Placement> isSatisfiedRecursive(Assignment<Lecture, Placement> assignment, int idx, HashMap<Lecture, Placement> assignments,
1587            Set<Placement> conflicts, Set<Placement> newConflicts, Set<Placement> bestConflicts) {
1588        if (idx == variables().size() && newConflicts.isEmpty())
1589            return bestConflicts;
1590        if (isSatisfiedSeqCheck(assignment, assignments, conflicts)) {
1591            if (bestConflicts == null) {
1592                return new HashSet<Placement>(newConflicts);
1593            } else {
1594                int b = 0, n = 0;
1595                for (Placement value: assignments.values()) {
1596                    if (value != null && bestConflicts.contains(value)) b++;
1597                    if (value != null && newConflicts.contains(value)) n++;
1598                }
1599                if (n < b || (n == b && newConflicts.size() < bestConflicts.size()))
1600                    return new HashSet<Placement>(newConflicts);
1601            }
1602            return bestConflicts;
1603        }
1604        if (idx == variables().size())
1605            return bestConflicts;
1606        bestConflicts = isSatisfiedRecursive(assignment, idx + 1, assignments, conflicts, newConflicts,
1607                bestConflicts);
1608        Lecture lecture = variables().get(idx);
1609        //if (assignments != null && assignments.containsKey(lecture))
1610        //    return bestConflicts;
1611        Placement placement = null;
1612        if (assignments != null && assignments.containsKey(lecture))
1613            placement = assignments.get(lecture);
1614        else if (assignment != null)
1615            placement = assignment.getValue(lecture);
1616        if (placement == null)
1617            return bestConflicts;
1618        if (conflicts != null && conflicts.contains(placement))
1619            return bestConflicts;
1620        conflicts.add(placement);
1621        newConflicts.add(placement);
1622        bestConflicts = isSatisfiedRecursive(assignment, idx + 1, assignments, conflicts, newConflicts, bestConflicts);
1623        newConflicts.remove(placement);
1624        conflicts.remove(placement);
1625        return bestConflicts;
1626    }
1627
1628    private boolean isSatisfiedSeqCheck(Assignment<Lecture, Placement> assignment, HashMap<Lecture, Placement> assignments, Set<Placement> conflicts) {
1629        if (!getType().is(Flag.BACK_TO_BACK)) return true;
1630        int gapMin = getType().getMin();
1631        int gapMax = getType().getMax();
1632
1633        List<Integer> lengths = new ArrayList<Integer>();
1634
1635        Placement[] res = new Placement[Constants.SLOTS_PER_DAY];
1636        for (int i = 0; i < Constants.SLOTS_PER_DAY; i++)
1637            res[i] = null;
1638
1639        int nrLectures = 0;
1640
1641        for (Lecture lecture : variables()) {
1642            Placement placement = null;
1643            if (assignments != null && assignments.containsKey(lecture))
1644                placement = assignments.get(lecture);
1645            else if (assignment != null)
1646                placement = assignment.getValue(lecture);
1647            if (placement == null) {
1648                if (!lecture.timeLocations().isEmpty())
1649                        lengths.add(lecture.timeLocations().get(0).getLength());
1650            } else if (conflicts != null && conflicts.contains(placement)) {
1651                if (!lecture.timeLocations().isEmpty())
1652                        lengths.add(lecture.timeLocations().get(0).getLength());
1653            } else {
1654                int pos = placement.getTimeLocation().getStartSlot();
1655                int length = placement.getTimeLocation().getLength();
1656                for (int j = pos; j < pos + length; j++) {
1657                    if (res[j] != null) {
1658                        if (conflicts == null)
1659                            return false;
1660                        if (!assignments.containsKey(lecture))
1661                            conflicts.add(placement);
1662                        else if (!assignments.containsKey(res[j].variable()))
1663                            conflicts.add(res[j]);
1664                    }
1665                }
1666                for (int j = pos; j < pos + length; j++)
1667                    res[j] = placement;
1668                nrLectures++;
1669            }
1670        }
1671        if (nrLectures <= 1)
1672            return true;
1673
1674        if (iIsRequired || (!iIsProhibited && iPreference < 0)) {
1675            int i = 0;
1676            Placement p = res[i];
1677            while (p == null)
1678                p = res[++i];
1679            i = res[i].getTimeLocation().getStartSlot() + res[i].getTimeLocation().getLength();
1680            nrLectures--;
1681            while (nrLectures > 0) {
1682                int gap = 0;
1683                while (i < Constants.SLOTS_PER_DAY && res[i] == null) {
1684                    gap++;
1685                    i++;
1686                }
1687                if (i == Constants.SLOTS_PER_DAY)
1688                    break;
1689                if (!canFill(gap, gapMin, gapMax, lengths))
1690                    return false;
1691                p = res[i];
1692                i = res[i].getTimeLocation().getStartSlot() + res[i].getTimeLocation().getLength();
1693                nrLectures--;
1694            }
1695        } else if (iIsProhibited || (!iIsRequired && iPreference > 0)) {
1696            int i = 0;
1697            Placement p = res[i];
1698            while (p == null)
1699                p = res[++i];
1700            i = res[i].getTimeLocation().getStartSlot() + res[i].getTimeLocation().getLength();
1701            nrLectures--;
1702            while (nrLectures > 0) {
1703                int gap = 0;
1704                while (i < Constants.SLOTS_PER_DAY && res[i] == null) {
1705                    gap++;
1706                    i++;
1707                }
1708                if (i == Constants.SLOTS_PER_DAY)
1709                    break;
1710                if ((gapMin == 0 || !canFill(gap, 0, gapMin - 1, lengths))
1711                        && (gapMax >= Constants.SLOTS_PER_DAY || !canFill(gap, gapMax + 1, Constants.SLOTS_PER_DAY,
1712                                lengths))) {
1713                    return false;
1714                }
1715                p = res[i];
1716                i = res[i].getTimeLocation().getStartSlot() + res[i].getTimeLocation().getLength();
1717                nrLectures--;
1718            }
1719        }
1720        return true;
1721    }
1722
1723    public boolean isSatisfied(Assignment<Lecture, Placement> assignment) {
1724        if (isHard()) return true;
1725        if (countAssignedVariables(assignment) < 2) return true;
1726        if (getPreference() == 0) return true;
1727        return isHard() || countAssignedVariables(assignment) < 2 || getPreference() == 0 || getCurrentPreference(assignment) < 0;
1728    }
1729
1730    public boolean isChildrenNotOverlap(Assignment<Lecture, Placement> assignment, Lecture lec1, Placement plc1, Lecture lec2, Placement plc2) {
1731        if (lec1.getSchedulingSubpartId().equals(lec2.getSchedulingSubpartId())) {
1732            // same subpart
1733            boolean overlap = plc1.getTimeLocation().hasIntersection(plc2.getTimeLocation());
1734
1735            if (overlap && lec1.getParent() != null && variables().contains(lec1.getParent())
1736                    && lec2.getParent() != null && variables().contains(lec2.getParent())) {
1737                // children overlaps
1738                Placement p1 = assignment.getValue(lec1.getParent());
1739                Placement p2 = assignment.getValue(lec2.getParent());
1740                // parents not overlap, but children do
1741                if (p1 != null && p2 != null && !p1.getTimeLocation().hasIntersection(p2.getTimeLocation()))
1742                    return false;
1743            }
1744
1745            if (!overlap && lec1.getChildrenSubpartIds() != null && lec2.getChildrenSubpartIds() != null) {
1746                // parents not overlap
1747                for (Long subpartId: lec1.getChildrenSubpartIds()) {
1748                    for (Lecture c1 : lec1.getChildren(subpartId)) {
1749                        Placement p1 = assignment.getValue(c1);
1750                        if (p1 == null) continue;
1751                        for (Lecture c2 : lec2.getChildren(subpartId)) {
1752                            Placement p2 = assignment.getValue(c2);
1753                            if (p2 == null) continue;
1754                            if (!c1.getSchedulingSubpartId().equals(c2.getSchedulingSubpartId())) continue;
1755                            // parents not overlap, but children do
1756                            if (p1.getTimeLocation().hasIntersection(p2.getTimeLocation()))
1757                                return false;
1758                        }
1759                    }
1760                }
1761            }
1762        } else {
1763            // different subpart
1764        }
1765        return true;
1766    }
1767
1768    public boolean isSatisfiedPair(Assignment<Lecture, Placement> assignment, Placement plc1, Placement plc2) {
1769        if (iIsRequired || (!iIsProhibited && iPreference <= 0))
1770            return getType().isSatisfied(assignment, this, plc1, plc2);
1771        else if (iIsProhibited || (!iIsRequired && iPreference > 0))
1772            return getType().isViolated(assignment, this, plc1, plc2);
1773        return true;
1774    }
1775    
1776    public boolean canShareRoom() {
1777        return getType().is(Flag.CAN_SHARE_ROOM);
1778    }
1779    
1780    private int nrSlotsADay(Assignment<Lecture, Placement> assignment, int dayCode, BitSet week, HashMap<Lecture, Placement> assignments, Set<Placement> conflicts) {
1781        Set<Integer> slots = new HashSet<Integer>();
1782        for (Lecture lecture: variables()) {
1783            Placement placement = null;
1784            if (assignments != null && assignments.containsKey(lecture))
1785                placement = assignments.get(lecture);
1786            else if (assignment != null)
1787                placement = assignment.getValue(lecture);
1788            if (placement == null || placement.getTimeLocation() == null) continue;
1789            if (conflicts != null && conflicts.contains(placement)) continue;
1790            TimeLocation t = placement.getTimeLocation();
1791            if (t == null || (t.getDayCode() & dayCode) == 0 || (week != null && !t.shareWeeks(week))) continue;
1792            for (int i = 0; i < t.getLength(); i++)
1793                slots.add(i + t.getStartSlot());
1794        }
1795        return slots.size();
1796    }
1797
1798    @Override
1799    public boolean equals(Object o) {
1800        if (o == null || !(o instanceof GroupConstraint)) return false;
1801        return getGeneratedId() == ((GroupConstraint) o).getGeneratedId();
1802    }
1803    
1804    @Override
1805    public GroupConstraintContext createAssignmentContext(Assignment<Lecture, Placement> assignment) {
1806        return new GroupConstraintContext(assignment);
1807    }
1808
1809    public class GroupConstraintContext implements AssignmentConstraintContext<Lecture, Placement> {
1810        private int iLastPreference = 0;
1811        
1812        public GroupConstraintContext(Assignment<Lecture, Placement> assignment) {
1813            updateCriterion(assignment);
1814        }
1815
1816        @Override
1817        public void assigned(Assignment<Lecture, Placement> assignment, Placement value) {
1818            updateCriterion(assignment);
1819        }
1820
1821        @Override
1822        public void unassigned(Assignment<Lecture, Placement> assignment, Placement value) {
1823            updateCriterion(assignment);
1824        }
1825        
1826        private void updateCriterion(Assignment<Lecture, Placement> assignment) {
1827            if (!isHard()) {
1828                getModel().getCriterion(DistributionPreferences.class).inc(assignment, -iLastPreference);
1829                iLastPreference = getCurrentPreference(assignment) + Math.abs(iPreference);
1830                getModel().getCriterion(DistributionPreferences.class).inc(assignment, iLastPreference);
1831            }
1832        }
1833        
1834        public int getPreference() { return iLastPreference; }
1835    }
1836}