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