    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.log4j.Logger sLogger = org.apache.log4j.Logger.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        for (Iterator<?> i = root.element("rooms").elementIterator("room"); i.hasNext();) {
    253            Element roomEl = (Element) i.next();
    254            iProgress.incProgress();
    255            roomElements.put(roomEl.attributeValue("id"), roomEl);
    256            if ("false".equals(roomEl.attributeValue("constraint")))
    257                continue;
    258            RoomSharingModel sharingModel = null;
    259            Element sharingEl = roomEl.element("sharing");
    260            if (sharingEl != null) {
    261                Character freeForAllPrefChar = null;
    262                Element freeForAllEl = sharingEl.element("freeForAll");
    263                if (freeForAllEl != null)
    264                    freeForAllPrefChar = freeForAllEl.attributeValue("value", "F").charAt(0);
    265                Character notAvailablePrefChar = null;
    266                Element notAvailableEl = sharingEl.element("notAvailable");
    267                if (notAvailableEl != null)
    268                    notAvailablePrefChar = notAvailableEl.attributeValue("value", "X").charAt(0);
    269                String pattern = sharingEl.element("pattern").getText();
    270                int unit = Integer.parseInt(sharingEl.element("pattern").attributeValue("unit", "1"));
    271                Map<Character, Long> departments = new HashMap<Character, Long>();
    272                for (Iterator<?> j = sharingEl.elementIterator("department"); j.hasNext(); ) {
    273                    Element deptEl = (Element)j.next();
    274                    char value = deptEl.attributeValue("value", String.valueOf((char)('0' + departments.size()))).charAt(0);
    275                    Long id = Long.valueOf(deptEl.attributeValue("id"));
    276                    departments.put(value, id);
    277                }
    278                sharingModel = new RoomSharingModel(unit, departments, pattern, freeForAllPrefChar, notAvailablePrefChar);
    279            }
    280            boolean ignoreTooFar = false;
    281            if ("true".equals(roomEl.attributeValue("ignoreTooFar")))
    282                ignoreTooFar = true;
    283            boolean fake = false;
    284            if ("true".equals(roomEl.attributeValue("fake")))
    285                fake = true;
    286            Double posX = null, posY = null;
    287            if (roomEl.attributeValue("location") != null) {
    288                String loc = roomEl.attributeValue("location");
    289                posX = Double.valueOf(loc.substring(0, loc.indexOf(',')));
    290                posY = Double.valueOf(loc.substring(loc.indexOf(',') + 1));
    291            }
    292            boolean discouraged = "true".equals(roomEl.attributeValue("discouraged"));
    293            RoomConstraint constraint = (discouraged ? new DiscouragedRoomConstraint(
    294                    getModel().getProperties(),
    295                    Long.valueOf(roomEl.attributeValue("id")),
    296                    (roomEl.attributeValue("name") != null ? roomEl.attributeValue("name") : "r"
    297                            + roomEl.attributeValue("id")),
    298                    (roomEl.attributeValue("building") == null ? null : Long.valueOf(roomEl.attributeValue("building"))),
    299                    Integer.parseInt(roomEl.attributeValue("capacity")), sharingModel, posX, posY, ignoreTooFar, !fake)
    300                    : new RoomConstraint(Long.valueOf(roomEl.attributeValue("id")),
    301                            (roomEl.attributeValue("name") != null ? roomEl.attributeValue("name") : "r"
    302                                    + roomEl.attributeValue("id")), (roomEl.attributeValue("building") == null ? null
    303                                    : Long.valueOf(roomEl.attributeValue("building"))), Integer.parseInt(roomEl
    304                                    .attributeValue("capacity")), sharingModel, posX, posY, ignoreTooFar, !fake));
    305            if (roomEl.attributeValue("type") != null)
    306                constraint.setType(Long.valueOf(roomEl.attributeValue("type")));
    307            getModel().addConstraint(constraint);
    308            roomConstraints.put(roomEl.attributeValue("id"), constraint);
    309
    310            for (Iterator<?> j = roomEl.elementIterator("travel-time"); j.hasNext();) {
    311                Element travelTimeEl = (Element)j.next();
    312                getModel().getDistanceMetric().addTravelTime(constraint.getResourceId(),
    313                        Long.valueOf(travelTimeEl.attributeValue("id")),
    314                        Integer.valueOf(travelTimeEl.attributeValue("minutes")));
    315            }
    316        }
    317
    318        HashMap<String, InstructorConstraint> instructorConstraints = new HashMap<String, InstructorConstraint>();
    319        if (root.element("instructors") != null) {
    320            for (Iterator<?> i = root.element("instructors").elementIterator("instructor"); i.hasNext();) {
    321                Element instructorEl = (Element) i.next();
    322                InstructorConstraint instructorConstraint = null;
    323                if ("true".equalsIgnoreCase(instructorEl.attributeValue("soft", "false"))) {
    324                    instructorConstraint = new SoftInstructorConstraint(Long.valueOf(instructorEl
    325                            .attributeValue("id")), instructorEl.attributeValue("puid"), (instructorEl
    326                            .attributeValue("name") != null ? instructorEl.attributeValue("name") : "i"
    327                            + instructorEl.attributeValue("id")), "true".equals(instructorEl.attributeValue("ignDist")));
    328                } else {
    329                    instructorConstraint = new InstructorConstraint(Long.valueOf(instructorEl
    330                        .attributeValue("id")), instructorEl.attributeValue("puid"), (instructorEl
    331                        .attributeValue("name") != null ? instructorEl.attributeValue("name") : "i"
    332                        + instructorEl.attributeValue("id")), "true".equals(instructorEl.attributeValue("ignDist")));
    333                }
    334                if (instructorEl.attributeValue("type") != null)
    335                    instructorConstraint.setType(Long.valueOf(instructorEl.attributeValue("type")));
    336                instructorConstraints.put(instructorEl.attributeValue("id"), instructorConstraint);
    337
    338                getModel().addConstraint(instructorConstraint);
    339            }
    340        }
    341        HashMap<Long, String> depts = new HashMap<Long, String>();
    342        if (root.element("departments") != null) {
    343            for (Iterator<?> i = root.element("departments").elementIterator("department"); i.hasNext();) {
    344                Element deptEl = (Element) i.next();
    345                depts.put(Long.valueOf(deptEl.attributeValue("id")), (deptEl.attributeValue("name") != null ? deptEl
    346                        .attributeValue("name") : "d" + deptEl.attributeValue("id")));
    347            }
    348        }
    349
    350        HashMap<Long, Configuration> configs = new HashMap<Long, Configuration>();
    351        HashMap<Long, List<Configuration>> alternativeConfigurations = new HashMap<Long, List<Configuration>>();
    352        if (root.element("configurations") != null) {
    353            for (Iterator<?> i = root.element("configurations").elementIterator("config"); i.hasNext();) {
    354                Element configEl = (Element) i.next();
    355                Long configId = Long.valueOf(configEl.attributeValue("id"));
    356                int limit = Integer.parseInt(configEl.attributeValue("limit"));
    357                Long offeringId = Long.valueOf(configEl.attributeValue("offering"));
    358                Configuration config = new Configuration(offeringId, configId, limit);
    359                configs.put(configId, config);
    360                List<Configuration> altConfigs = alternativeConfigurations.get(offeringId);
    361                if (altConfigs == null) {
    362                    altConfigs = new ArrayList<Configuration>();
    363                    alternativeConfigurations.put(offeringId, altConfigs);
    364                }
    365                altConfigs.add(config);
    366                config.setAltConfigurations(altConfigs);
    367            }
    368        }
    369
    370        iProgress.setPhase("Creating variables ...", root.element("classes").elements("class").size());
    371
    372        HashMap<String, Element> classElements = new HashMap<String, Element>();
    373        HashMap<String, Lecture> lectures = new HashMap<String, Lecture>();
    374        HashMap<Lecture, Placement> assignedPlacements = new HashMap<Lecture, Placement>();
    375        HashMap<Lecture, String> parents = new HashMap<Lecture, String>();
    376        int ord = 0;
    377        for (Iterator<?> i1 = root.element("classes").elementIterator("class"); i1.hasNext();) {
    378            Element classEl = (Element) i1.next();
    379
    380            Configuration config = null;
    381            if (classEl.attributeValue("config") != null) {
    382                config = configs.get(Long.valueOf(classEl.attributeValue("config")));
    383            }
    384            if (config == null && classEl.attributeValue("offering") != null) {
    385                Long offeringId = Long.valueOf(classEl.attributeValue("offering"));
    386                Long configId = Long.valueOf(classEl.attributeValue("config"));
    387                List<Configuration> altConfigs = alternativeConfigurations.get(offeringId);
    388                if (altConfigs == null) {
    389                    altConfigs = new ArrayList<Configuration>();
    390                    alternativeConfigurations.put(offeringId, altConfigs);
    391                }
    392                for (Configuration c : altConfigs) {
    393                    if (c.getConfigId().equals(configId)) {
    394                        config = c;
    395                        break;
    396                    }
    397                }
    398                if (config == null) {
    399                    config = new Configuration(offeringId, configId, -1);
    400                    altConfigs.add(config);
    401                    config.setAltConfigurations(altConfigs);
    402                    configs.put(config.getConfigId(), config);
    403                }
    404            }
    405
    406            DatePattern defaultDatePattern = new DatePattern();
    407            if (classEl.attributeValue("dates") == null) {
    408                int startDay = Integer.parseInt(classEl.attributeValue("startDay", "0"));
    409                int endDay = Integer.parseInt(classEl.attributeValue("endDay", "1"));
    410                defaultDatePattern.setPattern(startDay, endDay);
    411                defaultDatePattern.setName(sDF.format(getDate(getModel().getYear(), startDay)) + "-" + sDF.format(getDate(getModel().getYear(), endDay)));
    412            } else {
    413                defaultDatePattern.setId(classEl.attributeValue("datePattern") == null ? null : Long.valueOf(classEl.attributeValue("datePattern")));
    414                defaultDatePattern.setName(classEl.attributeValue("datePatternName"));
    415                defaultDatePattern.setPattern(classEl.attributeValue("dates"));
    416            }
    417            Hashtable<Long, DatePattern> datePatterns = new Hashtable<Long, TimetableXMLLoader.DatePattern>();
    418            for (Iterator<?> i2 = classEl.elementIterator("date"); i2.hasNext();) {
    419                Element dateEl = (Element) i2.next();
    420                Long id = Long.valueOf(dateEl.attributeValue("id"));
    421                datePatterns.put(id, new DatePattern(
    422                        id,
    423                        dateEl.attributeValue("name"),
    424                        dateEl.attributeValue("pattern")));
    425            }
    426            classElements.put(classEl.attributeValue("id"), classEl);
    427            List<InstructorConstraint> ics = new ArrayList<InstructorConstraint>();
    428            for (Iterator<?> i2 = classEl.elementIterator("instructor"); i2.hasNext();) {
    429                Element instructorEl = (Element) i2.next();
    430                InstructorConstraint instructorConstraint = instructorConstraints
    431                        .get(instructorEl.attributeValue("id"));
    432                if (instructorConstraint == null) {
    433                    instructorConstraint = new InstructorConstraint(Long.valueOf(instructorEl.attributeValue("id")),
    434                            instructorEl.attributeValue("puid"),
    435                            (instructorEl.attributeValue("name") != null ? instructorEl.attributeValue("name") : "i"
    436                                    + instructorEl.attributeValue("id")), "true".equals(instructorEl
    437                                    .attributeValue("ignDist")));
    438                    instructorConstraints.put(instructorEl.attributeValue("id"), instructorConstraint);
    439                    getModel().addConstraint(instructorConstraint);
    440                }
    441                ics.add(instructorConstraint);
    442            }
    443            List<RoomLocation> roomLocations = new ArrayList<RoomLocation>();
    444            List<RoomConstraint> roomConstraintsThisClass = new ArrayList<RoomConstraint>();
    445            List<RoomLocation> initialRoomLocations = new ArrayList<RoomLocation>();
    446            List<RoomLocation> assignedRoomLocations = new ArrayList<RoomLocation>();
    447            List<RoomLocation> bestRoomLocations = new ArrayList<RoomLocation>();
    448            for (Iterator<?> i2 = classEl.elementIterator("room"); i2.hasNext();) {
    449                Element roomLocationEl = (Element) i2.next();
    450                Element roomEl = roomElements.get(roomLocationEl.attributeValue("id"));
    451                RoomConstraint roomConstraint = roomConstraints.get(roomLocationEl.attributeValue("id"));
    452
    453                Long roomId = null;
    454                String roomName = null;
    455                Long bldgId = null;
    456
    457                if (roomConstraint != null) {
    458                    roomConstraintsThisClass.add(roomConstraint);
    459                    roomId = roomConstraint.getResourceId();
    460                    roomName = roomConstraint.getRoomName();
    461                    bldgId = roomConstraint.getBuildingId();
    462                } else {
    463                    roomId = Long.valueOf(roomEl.attributeValue("id"));
    464                    roomName = (roomEl.attributeValue("name") != null ? roomEl.attributeValue("name") : "r"
    465                            + roomEl.attributeValue("id"));
    466                    bldgId = (roomEl.attributeValue("building") == null ? null : Long.valueOf(roomEl
    467                            .attributeValue("building")));
    468                }
    469
    470                boolean ignoreTooFar = false;
    471                if ("true".equals(roomEl.attributeValue("ignoreTooFar")))
    472                    ignoreTooFar = true;
    473                Double posX = null, posY = null;
    474                if (roomEl.attributeValue("location") != null) {
    475                    String loc = roomEl.attributeValue("location");
    476                    posX = Double.valueOf(loc.substring(0, loc.indexOf(',')));
    477                    posY = Double.valueOf(loc.substring(loc.indexOf(',') + 1));
    478                }
    479                RoomLocation rl = new RoomLocation(roomId, roomName, bldgId, Integer.parseInt(roomLocationEl
    480                        .attributeValue("pref")), Integer.parseInt(roomEl.attributeValue("capacity")), posX, posY,
    481                        ignoreTooFar, roomConstraint);
    482                if ("true".equals(roomLocationEl.attributeValue("initial")))
    483                    initialRoomLocations.add(rl);
    484                if ("true".equals(roomLocationEl.attributeValue("solution")))
    485                    assignedRoomLocations.add(rl);
    486                if ("true".equals(roomLocationEl.attributeValue("best")))
    487                    bestRoomLocations.add(rl);
    488                roomLocations.add(rl);
    489            }
    490            List<TimeLocation> timeLocations = new ArrayList<TimeLocation>();
    491            TimeLocation initialTimeLocation = null;
    492            TimeLocation assignedTimeLocation = null;
    493            TimeLocation bestTimeLocation = null;
    494            TimeLocation prohibitedTime = perts.get(Long.valueOf(classEl.attributeValue("id")));
    495
    496            for (Iterator<?> i2 = classEl.elementIterator("time"); i2.hasNext();) {
    497                Element timeLocationEl = (Element) i2.next();
    498                DatePattern dp = defaultDatePattern;
    499                if (timeLocationEl.attributeValue("date") != null)
    500                    dp = datePatterns.get(Long.valueOf(timeLocationEl.attributeValue("date")));
    501                TimeLocation tl = new TimeLocation(
    502                        Integer.parseInt(timeLocationEl.attributeValue("days"), 2),
    503                        Integer.parseInt(timeLocationEl.attributeValue("start")),
    504                        Integer.parseInt(timeLocationEl.attributeValue("length")),
    505                        (int) Double.parseDouble(timeLocationEl.attributeValue("pref")),
    506                        Double.parseDouble(timeLocationEl.attributeValue("npref", timeLocationEl.attributeValue("pref"))),
    507                        Integer.parseInt(timeLocationEl.attributeValue("datePref", "0")),
    508                        dp.getId(), dp.getName(), dp.getPattern(),
    509                        Integer.parseInt(timeLocationEl.attributeValue("breakTime") == null ? "-1" : timeLocationEl.attributeValue("breakTime")));
    510                if (tl.getBreakTime() < 0) tl.setBreakTime(tl.getLength() == 18 ? 15 : 10);
    511                if (timeLocationEl.attributeValue("pattern") != null)
    512                    tl.setTimePatternId(Long.valueOf(timeLocationEl.attributeValue("pattern")));
    513                /*
    514                 * if (timePatternTransform) tl =
    515                 * transformTimePattern(Long.valueOf
    516                 * (classEl.attributeValue("id")),tl);
    517                 */
    518                if (prohibitedTime != null && prohibitedTime.getDayCode() == tl.getDayCode()
    519                        && prohibitedTime.getStartSlot() == tl.getStartSlot()
    520                        && prohibitedTime.getLength() == tl.getLength()) {
    521                    sLogger.info("Time " + tl.getLongName(true) + " is prohibited for class " + classEl.attributeValue("id"));
    522                    continue;
    523                }
    524                if ("true".equals(timeLocationEl.attributeValue("solution")))
    525                    assignedTimeLocation = tl;
    526                if ("true".equals(timeLocationEl.attributeValue("initial")))
    527                    initialTimeLocation = tl;
    528                if ("true".equals(timeLocationEl.attributeValue("best")))
    529                    bestTimeLocation = tl;
    530                timeLocations.add(tl);
    531            }
    532            if (timeLocations.isEmpty()) {
    533                sLogger.error("  ERROR: No time.");
    534                continue;
    535            }
    536
    537            int minClassLimit = 0;
    538            int maxClassLimit = 0;
    539            float room2limitRatio = 1.0f;
    540            if (!"true".equals(classEl.attributeValue("committed"))) {
    541                if (classEl.attributeValue("expectedCapacity") != null) {
    542                    minClassLimit = maxClassLimit = Integer.parseInt(classEl.attributeValue("expectedCapacity"));
    543                    int roomCapacity = Integer.parseInt(classEl.attributeValue("roomCapacity", classEl
    544                            .attributeValue("expectedCapacity")));
    545                    if (minClassLimit == 0)
    546                        minClassLimit = maxClassLimit = roomCapacity;
    547                    room2limitRatio = (minClassLimit == 0 ? 1.0f : ((float) roomCapacity) / minClassLimit);
    548                } else {
    549                    if (classEl.attribute("classLimit") != null) {
    550                        minClassLimit = maxClassLimit = Integer.parseInt(classEl.attributeValue("classLimit"));
    551                    } else {
    552                        minClassLimit = Integer.parseInt(classEl.attributeValue("minClassLimit"));
    553                        maxClassLimit = Integer.parseInt(classEl.attributeValue("maxClassLimit"));
    554                    }
    555                    room2limitRatio = Float.parseFloat(classEl.attributeValue("roomToLimitRatio", "1.0"));
    556                }
    557            }
    558
    559            Lecture lecture = new Lecture(Long.valueOf(classEl.attributeValue("id")),
    560                    (classEl.attributeValue("solverGroup") != null ? Long
    561                            .valueOf(classEl.attributeValue("solverGroup")) : null), Long.valueOf(classEl
    562                            .attributeValue("subpart", classEl.attributeValue("course", "-1"))), (classEl
    563                            .attributeValue("name") != null ? classEl.attributeValue("name") : "c"
    564                            + classEl.attributeValue("id")), timeLocations, roomLocations, Integer.parseInt(classEl
    565                            .attributeValue("nrRooms", roomLocations.isEmpty() ? "0" : "1")), null, minClassLimit, maxClassLimit, room2limitRatio);
    566            lecture.setNote(classEl.attributeValue("note"));
    567
    568            if ("true".equals(classEl.attributeValue("committed")))
    569                lecture.setCommitted(true);
    570
    571            if (!lecture.isCommitted() && classEl.attributeValue("ord") != null)
    572                lecture.setOrd(Integer.parseInt(classEl.attributeValue("ord")));
    573            else
    574                lecture.setOrd(ord++);
    575
    576            lecture.setWeight(Double.parseDouble(classEl.attributeValue("weight", "1.0")));
    577
    578            if (lecture.getNrRooms() > 1)
    579                lecture.setMaxRoomCombinations(Integer.parseInt(classEl.attributeValue("maxRoomCombinations", "-1")));
    580
    581            if (config != null)
    582                lecture.setConfiguration(config);
    583
    584            if (initialTimeLocation != null && initialRoomLocations.size() == lecture.getNrRooms()) {
    585                lecture.setInitialAssignment(new Placement(lecture, initialTimeLocation, initialRoomLocations));
    586            }
    587            if (assignedTimeLocation != null && assignedRoomLocations.size() == lecture.getNrRooms()) {
    588                assignedPlacements.put(lecture, new Placement(lecture, assignedTimeLocation, assignedRoomLocations));
    589            } else if (lecture.getInitialAssignment() != null) {
    590                // assignedPlacements.put(lecture, lecture.getInitialAssignment());
    591            }
    592            if (bestTimeLocation != null && bestRoomLocations.size() == lecture.getNrRooms()) {
    593                lecture.setBestAssignment(new Placement(lecture, bestTimeLocation, bestRoomLocations), 0);
    594            } else if (assignedTimeLocation != null && assignedRoomLocations.size() == lecture.getNrRooms()) {
    595                // lecture.setBestAssignment(assignedPlacements.get(lecture), 0);
    596            }
    597
    598            lectures.put(classEl.attributeValue("id"), lecture);
    599            if (classEl.attributeValue("department") != null)
    600                lecture.setDepartment(Long.valueOf(classEl.attributeValue("department")));
    601            if (classEl.attribute("scheduler") != null)
    602                lecture.setScheduler(Long.valueOf(classEl.attributeValue("scheduler")));
    603            if ((sectionWholeCourse || !lecture.isCommitted()) && classEl.attributeValue("subpart", classEl.attributeValue("course")) != null) {
    604                Long subpartId = Long.valueOf(classEl.attributeValue("subpart", classEl.attributeValue("course")));
    605                List<Lecture> sames = sameLectures.get(subpartId);
    606                if (sames == null) {
    607                    sames = new ArrayList<Lecture>();
    608                    sameLectures.put(subpartId, sames);
    609                }
    610                sames.add(lecture);
    611            }
    612            String parent = classEl.attributeValue("parent");
    613            if (parent != null)
    614                parents.put(lecture, parent);
    615
    616            getModel().addVariable(lecture);
    617
    618            if (lecture.isCommitted()) {
    619                Placement placement = assignedPlacements.get(lecture);
    620                if (classEl.attribute("assignment") != null)
    621                    placement.setAssignmentId(Long.valueOf(classEl.attributeValue("assignment")));
    622                for (InstructorConstraint ic : ics)
    623                    ic.setNotAvailable(placement);
    624                for (RoomConstraint rc : roomConstraintsThisClass)
    625                    if (rc.getConstraint())
    626                        rc.setNotAvailable(placement);
    627            } else {
    628                for (InstructorConstraint ic : ics)
    629                    ic.addVariable(lecture);
    630                for (RoomConstraint rc : roomConstraintsThisClass)
    631                    rc.addVariable(lecture);
    632            }
    633
    634            iProgress.incProgress();
    635        }
    636
    637        for (Map.Entry<Lecture, String> entry : parents.entrySet()) {
    638            Lecture lecture = entry.getKey();
    639            Lecture parent = lectures.get(entry.getValue());
    640            if (parent == null) {
    641                iProgress.warn("Parent class " + entry.getValue() + " does not exists.");
    642            } else {
    643                lecture.setParent(parent);
    644            }
    645        }
    646
    647        iProgress.setPhase("Creating constraints ...", root.element("groupConstraints").elements("constraint").size());
    648        HashMap<String, Element> grConstraintElements = new HashMap<String, Element>();
    649        HashMap<String, Constraint<Lecture, Placement>> groupConstraints = new HashMap<String, Constraint<Lecture, Placement>>();
    650        for (Iterator<?> i1 = root.element("groupConstraints").elementIterator("constraint"); i1.hasNext();) {
    651            Element grConstraintEl = (Element) i1.next();
    652            Constraint<Lecture, Placement> c = null;
    653            if ("SPREAD".equals(grConstraintEl.attributeValue("type"))) {
    654                c = new SpreadConstraint(getModel().getProperties(), grConstraintEl.attributeValue("name", "spread"));
    655            } else if ("MIN_ROOM_USE".equals(grConstraintEl.attributeValue("type"))) {
    656                c = new MinimizeNumberOfUsedRoomsConstraint(getModel().getProperties());
    657            } else if ("CLASS_LIMIT".equals(grConstraintEl.attributeValue("type"))) {
    658                if (grConstraintEl.element("parentClass") == null) {
    659                    c = new ClassLimitConstraint(Integer.parseInt(grConstraintEl.attributeValue("courseLimit")),
    660                            grConstraintEl.attributeValue("name", "class-limit"));
    661                } else {
    662                    String classId = grConstraintEl.element("parentClass").attributeValue("id");
    663                    c = new ClassLimitConstraint(lectures.get(classId), grConstraintEl.attributeValue("name",
    664                            "class-limit"));
    665                }
    666                if (grConstraintEl.attributeValue("delta") != null)
    667                    ((ClassLimitConstraint) c).setClassLimitDelta(Integer.parseInt(grConstraintEl
    668                            .attributeValue("delta")));
    669            } else if ("MIN_GRUSE(10x1h)".equals(grConstraintEl.attributeValue("type"))) {
    670                c = new MinimizeNumberOfUsedGroupsOfTime(getModel().getProperties(), "10x1h",
    671                        MinimizeNumberOfUsedGroupsOfTime.sGroups10of1h);
    672            } else if ("MIN_GRUSE(5x2h)".equals(grConstraintEl.attributeValue("type"))) {
    673                c = new MinimizeNumberOfUsedGroupsOfTime(getModel().getProperties(), "5x2h",
    674                        MinimizeNumberOfUsedGroupsOfTime.sGroups5of2h);
    675            } else if ("MIN_GRUSE(3x3h)".equals(grConstraintEl.attributeValue("type"))) {
    676                c = new MinimizeNumberOfUsedGroupsOfTime(getModel().getProperties(), "3x3h",
    677                        MinimizeNumberOfUsedGroupsOfTime.sGroups3of3h);
    678            } else if ("MIN_GRUSE(2x5h)".equals(grConstraintEl.attributeValue("type"))) {
    679                c = new MinimizeNumberOfUsedGroupsOfTime(getModel().getProperties(), "2x5h",
    680                        MinimizeNumberOfUsedGroupsOfTime.sGroups2of5h);
    681            } else if (IgnoreStudentConflictsConstraint.REFERENCE.equals(grConstraintEl.attributeValue("type"))) {
    682                c = new IgnoreStudentConflictsConstraint();
    683            } else {
    684                try {
    685                    FlexibleConstraintType f = FlexibleConstraintType.valueOf(grConstraintEl.attributeValue("type"));
    686                    try {
    687                        c = f.create(
    688                                Long.valueOf(grConstraintEl.attributeValue("id")),
    689                                grConstraintEl.attributeValue("owner"),
    690                                grConstraintEl.attributeValue("pref"),
    691                                grConstraintEl.attributeValue("reference"));
    692                    } catch (IllegalArgumentException e) {
    693                            iProgress.warn("Failed to create flexible constraint " + grConstraintEl.attributeValue("type") + ": " + e.getMessage(), e);
    694                            continue;
    695                    }
    696                } catch (IllegalArgumentException e) {
    697                    // type did not match, continue with group constraint types
    698                    c = new GroupConstraint(
    699                            Long.valueOf(grConstraintEl.attributeValue("id")),
    700                            GroupConstraint.getConstraintType(grConstraintEl.attributeValue("type")),
    701                            grConstraintEl.attributeValue("pref"));
    702                }
    703            }
    704            getModel().addConstraint(c);
    705            for (Iterator<?> i2 = grConstraintEl.elementIterator("class"); i2.hasNext();) {
    706                String classId = ((Element) i2.next()).attributeValue("id");
    707                Lecture other = lectures.get(classId);
    708                if (other != null)
    709                    c.addVariable(other);
    710                else
    711                    iProgress.warn("Class " + classId + " does not exists, but it is referred from group constraint " + c.getId() + " (" + c.getName() + ")");
    712            }
    713            grConstraintElements.put(grConstraintEl.attributeValue("id"), grConstraintEl);
    714            groupConstraints.put(grConstraintEl.attributeValue("id"), c);
    715            iProgress.incProgress();
    716        }
    717
    718        iProgress.setPhase("Loading students ...", root.element("students").elements("student").size());
    719        boolean initialSectioning = true;
    720        HashMap<Long, Student> students = new HashMap<Long, Student>();
    721        HashMap<Long, Set<Student>> offering2students = new HashMap<Long, Set<Student>>();
    722        for (Iterator<?> i1 = root.element("students").elementIterator("student"); i1.hasNext();) {
    723            Element studentEl = (Element) i1.next();
    724            List<Lecture> lecturesThisStudent = new ArrayList<Lecture>();
    725            Long studentId = Long.valueOf(studentEl.attributeValue("id"));
    726            Student student = students.get(studentId);
    727            if (student == null) {
    728                student = new Student(studentId);
    729                students.put(studentId, student);
    730                getModel().addStudent(student);
    731            }
    732            student.setAcademicArea(studentEl.attributeValue("area"));
    733            student.setAcademicClassification(studentEl.attributeValue("classification"));
    734            student.setMajor(studentEl.attributeValue("major"));
    735            student.setCurriculum(studentEl.attributeValue("curriculum"));
    736            for (Iterator<?> i2 = studentEl.elementIterator("offering"); i2.hasNext();) {
    737                Element ofEl = (Element) i2.next();
    738                Long offeringId = Long.valueOf(ofEl.attributeValue("id"));
    739                String priority = ofEl.attributeValue("priority");
    740                student.addOffering(offeringId, Double.parseDouble(ofEl.attributeValue("weight", "1.0")), priority == null ? null : Double.valueOf(priority));
    741                Set<Student> studentsThisOffering = offering2students.get(offeringId);
    742                if (studentsThisOffering == null) {
    743                    studentsThisOffering = new HashSet<Student>();
    744                    offering2students.put(offeringId, studentsThisOffering);
    745                }
    746                studentsThisOffering.add(student);
    747                String altId = ofEl.attributeValue("alternative");
    748                if (altId != null)
    749                    student.addAlternatives(Long.valueOf(altId), offeringId);
    750            }
    751            for (Iterator<?> i2 = studentEl.elementIterator("class"); i2.hasNext();) {
    752                String classId = ((Element) i2.next()).attributeValue("id");
    753                Lecture lecture = lectures.get(classId);
    754                if (lecture == null) {
    755                    iProgress.warn("Class " + classId + " does not exists, but it is referred from student " + student.getId());
    756                    continue;
    757                }
    758                if (lecture.isCommitted()) {
    759                    if (sectionWholeCourse && (lecture.getParent() != null || lecture.getConfiguration() != null)) {
    760                        // committed, but with course structure -- sectioning can be used
    761                        student.addLecture(lecture);
    762                        student.addConfiguration(lecture.getConfiguration());
    763                        lecture.addStudent(getAssignment(), student);
    764                        lecturesThisStudent.add(lecture);
    765                        initialSectioning = false;
    766                    } else {
    767                        Placement placement = assignedPlacements.get(lecture);
    768                        student.addCommitedPlacement(placement);
    769                    }
    770                } else {
    771                    student.addLecture(lecture);
    772                    student.addConfiguration(lecture.getConfiguration());
    773                    lecture.addStudent(getAssignment(), student);
    774                    lecturesThisStudent.add(lecture);
    775                    initialSectioning = false;
    776                }
    777            }
    778
    779            for (Iterator<?> i2 = studentEl.elementIterator("prohibited-class"); i2.hasNext();) {
    780                String classId = ((Element) i2.next()).attributeValue("id");
    781                Lecture lecture = lectures.get(classId);
    782                if (lecture != null)
    783                    student.addCanNotEnroll(lecture);
    784                else
    785                    iProgress.warn("Class " + classId + " does not exists, but it is referred from student " + student.getId());
    786            }
    787
    788            if (studentEl.attributeValue("instructor") != null)
    789                student.setInstructor(instructorConstraints.get(studentEl.attributeValue("instructor")));
    790
    791            iProgress.incProgress();
    792        }
    793
    794        if (root.element("groups") != null) {
    795            iProgress.setPhase("Loading student groups ...", root.element("groups").elements("group").size());
    796            for (Iterator<?> i1 = root.element("groups").elementIterator("group"); i1.hasNext();) {
    797                Element groupEl = (Element)i1.next();
    798                long groupId = Long.parseLong(groupEl.attributeValue("id"));
    799                StudentGroup group = new StudentGroup(groupId, Double.parseDouble(groupEl.attributeValue("weight", "1.0")), groupEl.attributeValue("name", "Group-" + groupId));
    800                getModel().addStudentGroup(group);
    801                for (Iterator<?> i2 = groupEl.elementIterator("student"); i2.hasNext();) {
    802                    Element studentEl = (Element)i2.next();
    803                    Student student = students.get(Long.valueOf(studentEl.attributeValue("id")));
    804                    if (student != null) {
    805                        group.addStudent(student); student.addGroup(group);
    806                    }
    807                }
    808            }
    809        }
    810
    811        for (List<Lecture> sames: sameLectures.values()) {
    812            for (Lecture lect : sames) {
    813                lect.setSameSubpartLectures(sames);
    814            }
    815        }
    816
    817        if (initialSectioning) {
    818            iProgress.setPhase("Initial sectioning ...", offering2students.size());
    819            for (Map.Entry<Long, Set<Student>> entry : offering2students.entrySet()) {
    820                Long offeringId = entry.getKey();
    821                Set<Student> studentsThisOffering = entry.getValue();
    822                List<Configuration> altConfigs = alternativeConfigurations.get(offeringId);
    823                getModel().getStudentSectioning().initialSectioning(getAssignment(), offeringId, String.valueOf(offeringId), studentsThisOffering, altConfigs);
    824                iProgress.incProgress();
    825            }
    826            for (Student student: students.values()) {
    827                student.clearDistanceCache();
    828                if (student.getInstructor() != null)
    829                    for (Lecture lecture: student.getInstructor().variables()) {
    830                        student.addLecture(lecture);
    831                        student.addConfiguration(lecture.getConfiguration());
    832                        lecture.addStudent(getAssignment(), student);
    833                    }
    834            }
    835        }
    836
    837        iProgress.setPhase("Computing jenrl ...", students.size());
    838        HashMap<Lecture, HashMap<Lecture, JenrlConstraint>> jenrls = new HashMap<Lecture, HashMap<Lecture, JenrlConstraint>>();
    839        for (Iterator<Student> i1 = students.values().iterator(); i1.hasNext();) {
    840            Student st = i1.next();
    841            for (Iterator<Lecture> i2 = st.getLectures().iterator(); i2.hasNext();) {
    842                Lecture l1 = i2.next();
    843                for (Iterator<Lecture> i3 = st.getLectures().iterator(); i3.hasNext();) {
    844                    Lecture l2 = i3.next();
    845                    if (l1.getId() >= l2.getId())
    846                        continue;
    847                    HashMap<Lecture, JenrlConstraint> x = jenrls.get(l1);
    848                    if (x == null) {
    849                        x = new HashMap<Lecture, JenrlConstraint>();
    850                        jenrls.put(l1, x);
    851                    }
    852                    JenrlConstraint jenrl = x.get(l2);
    853                    if (jenrl == null) {
    854                        jenrl = new JenrlConstraint();
    855                        jenrl.addVariable(l1);
    856                        jenrl.addVariable(l2);
    857                        getModel().addConstraint(jenrl);
    858                        x.put(l2, jenrl);
    859                    }
    860                    jenrl.incJenrl(getAssignment(), st);
    861                }
    862            }
    863            iProgress.incProgress();
    864        }
    865
    866        if (iDeptBalancing) {
    867            iProgress.setPhase("Creating dept. spread constraints ...", getModel().variables().size());
    868            HashMap<Long, DepartmentSpreadConstraint> depSpreadConstraints = new HashMap<Long, DepartmentSpreadConstraint>();
    869            for (Lecture lecture : getModel().variables()) {
    870                if (lecture.getDepartment() == null)
    871                    continue;
    872                DepartmentSpreadConstraint deptConstr = depSpreadConstraints.get(lecture.getDepartment());
    873                if (deptConstr == null) {
    874                    String name = depts.get(lecture.getDepartment());
    875                    deptConstr = new DepartmentSpreadConstraint(getModel().getProperties(), lecture.getDepartment(),
    876                            (name != null ? name : "d" + lecture.getDepartment()));
    877                    depSpreadConstraints.put(lecture.getDepartment(), deptConstr);
    878                    getModel().addConstraint(deptConstr);
    879                }
    880                deptConstr.addVariable(lecture);
    881                iProgress.incProgress();
    882            }
    883        }
    884
    885        if (getModel().getProperties().getPropertyBoolean("General.PurgeInvalidPlacements", true)) {
    886            iProgress.setPhase("Purging invalid placements ...", getModel().variables().size());
    887            for (Lecture lecture : getModel().variables()) {
    888                lecture.purgeInvalidValues(iInteractiveMode);
    889                iProgress.incProgress();
    890            }
    891        }
    892
    893        if (getModel().hasConstantVariables() && getModel().constantVariables().size() > 0) {
    894            iProgress.setPhase("Assigning committed classes ...", assignedPlacements.size());
    895            for (Map.Entry<Lecture, Placement> entry : assignedPlacements.entrySet()) {
    896                Lecture lecture = entry.getKey();
    897                Placement placement = entry.getValue();
    898                if (!lecture.isCommitted()) { iProgress.incProgress(); continue; }
    899                lecture.setConstantValue(placement);
    900                getModel().weaken(getAssignment(), placement);
    901                Map<Constraint<Lecture, Placement>, Set<Placement>> conflictConstraints = getModel().conflictConstraints(getAssignment(), placement);
    902                if (conflictConstraints.isEmpty()) {
    903                    getAssignment().assign(0, placement);
    904                } else {
    905                    iProgress.warn("WARNING: Unable to assign " + lecture.getName() + " := " + placement.getName());
    906                    iProgress.debug("  Reason:");
    907                    for (Constraint<Lecture, Placement> c : conflictConstraints.keySet()) {
    908                        Set<Placement> vals = conflictConstraints.get(c);
    909                        for (Placement v : vals) {
    910                            iProgress.debug("    " + v.variable().getName() + " = " + v.getName());
    911                        }
    912                        iProgress.debug("    in constraint " + c);
    913                    }
    914                }
    915                iProgress.incProgress();
    916            }
    917        }
    918
    919        if (currentSolution != null) {
    920            iProgress.setPhase("Creating best assignment ...", 2 * getModel().variables().size());
    921            for (Lecture lecture : getModel().variables()) {
    922                iProgress.incProgress();
    923                Placement placement = lecture.getBestAssignment();
    924                if (placement == null) continue;
    925                getModel().weaken(getAssignment(), placement);
    926                getAssignment().assign(0, placement);
    927            }
    928
    929            currentSolution.saveBest();
    930            for (Lecture lecture : getModel().variables()) {
    931                iProgress.incProgress();
    932                getAssignment().unassign(0, lecture);
    933            }
    934        }
    935
    936        iProgress.setPhase("Creating initial assignment ...", assignedPlacements.size());
    937        for (Map.Entry<Lecture, Placement> entry : assignedPlacements.entrySet()) {
    938            Lecture lecture = entry.getKey();
    939            Placement placement = entry.getValue();
    940            if (lecture.isCommitted()) { iProgress.incProgress(); continue; }
    941            getModel().weaken(getAssignment(), placement);
    942            Map<Constraint<Lecture, Placement>, Set<Placement>> conflictConstraints = getModel().conflictConstraints(getAssignment(), placement);
    943            if (conflictConstraints.isEmpty()) {
    944                if (!placement.isValid()) {
    945                    iProgress.warn("WARNING: Lecture " + lecture.getName() + " does not contain assignment "
    946                            + placement.getLongName(true) + " in its domain (" + placement.getNotValidReason(getAssignment(), true) + ").");
    947                } else
    948                    getAssignment().assign(0, placement);
    949            } else {
    950                iProgress.warn("WARNING: Unable to assign " + lecture.getName() + " := " + placement.getName());
    951                iProgress.debug("  Reason:");
    952                for (Constraint<Lecture, Placement> c : conflictConstraints.keySet()) {
    953                    Set<Placement> vals = conflictConstraints.get(c);
    954                    for (Placement v : vals) {
    955                        iProgress.debug("    " + v.variable().getName() + " = " + v.getName());
    956                    }
    957                    iProgress.debug("    in constraint " + c);
    958                }
    959            }
    960            iProgress.incProgress();
    961        }
    962
    963        if (initialSectioning && getAssignment().nrAssignedVariables() != 0 && !getModel().getProperties().getPropertyBoolean("Global.LoadStudentEnrlsFromSolution", false))
    964            getModel().switchStudents(getAssignment());
    965
    966        if (iForcedPerturbances > 0) {
    967            iProgress.setPhase("Forcing perturbances", iForcedPerturbances);
    968            for (int i = 0; i < iForcedPerturbances; i++) {
    969                iProgress.setProgress(i);
    970                Lecture var = null;
    971                do {
    972                    var = ToolBox.random(getModel().variables());
    973                } while (var.getInitialAssignment() == null || var.values(getAssignment()).size() <= 1);
    974                var.removeInitialValue();
    975            }
    976        }
    977
    978        /*
    979        for (Constraint<Lecture, Placement> c : getModel().constraints()) {
    980            if (c instanceof SpreadConstraint)
    981                ((SpreadConstraint) c).init();
    982            if (c instanceof DiscouragedRoomConstraint)
    983                ((DiscouragedRoomConstraint) c).setEnabled(true);
    984            if (c instanceof MinimizeNumberOfUsedRoomsConstraint)
    985                ((MinimizeNumberOfUsedRoomsConstraint) c).setEnabled(true);
    986            if (c instanceof MinimizeNumberOfUsedGroupsOfTime)
    987                ((MinimizeNumberOfUsedGroupsOfTime) c).setEnabled(true);
    988        }
    989         */
    990    }
    991
    992    public static Date getDate(int year, int dayOfYear) {
    993        Calendar c = Calendar.getInstance(Locale.US);
    994        c.set(year, 1, 1, 0, 0, 0);
    995        c.set(Calendar.DAY_OF_YEAR, dayOfYear);
    996        return c.getTime();
    997    }
    998
    999    public static class DatePattern {
    1000        Long iId;
    1001        String iName;
    1002        BitSet iPattern;
    1003        public DatePattern() {}
    1004        public DatePattern(Long id, String name, BitSet pattern) {
    1005            setId(id); setName(name); setPattern(pattern);
    1006        }
    1007        public DatePattern(Long id, String name, String pattern) {
    1008            setId(id); setName(name); setPattern(pattern);
    1009        }
    1010        public Long getId() { return iId; }
    1011        public void setId(Long id) { iId = id; }
    1012        public String getName() { return iName; }
    1013        public void setName(String name) { iName = name; }
    1014        public BitSet getPattern() { return iPattern; }
    1015        public void setPattern(BitSet pattern) { iPattern = pattern; }
    1016        public void setPattern(String pattern) {
    1017            iPattern = new BitSet(pattern.length());
    1018            for (int i = 0; i < pattern.length(); i++)
    1019                if (pattern.charAt(i) == '1')
    1020                    iPattern.set(i);
    1021        }
    1022        public void setPattern(int startDay, int endDay) {
    1023            iPattern = new BitSet(366);
    1024            for (int d = startDay; d <= endDay; d++)
    1025                iPattern.set(d);
    1026        }
    1027    }
    1028}