001package org.cpsolver.coursett;
002
003import java.io.File;
004import java.io.FileOutputStream;
005import java.io.IOException;
006import java.text.DecimalFormat;
007import java.text.DecimalFormatSymbols;
008import java.util.ArrayList;
009import java.util.BitSet;
010import java.util.Collections;
011import java.util.Date;
012import java.util.HashSet;
013import java.util.HashMap;
014import java.util.Iterator;
015import java.util.List;
016import java.util.Locale;
017import java.util.Map;
018import java.util.Set;
019import java.util.TreeSet;
020
021
022import org.cpsolver.coursett.constraint.ClassLimitConstraint;
023import org.cpsolver.coursett.constraint.DiscouragedRoomConstraint;
024import org.cpsolver.coursett.constraint.FlexibleConstraint;
025import org.cpsolver.coursett.constraint.GroupConstraint;
026import org.cpsolver.coursett.constraint.IgnoreStudentConflictsConstraint;
027import org.cpsolver.coursett.constraint.InstructorConstraint;
028import org.cpsolver.coursett.constraint.MinimizeNumberOfUsedGroupsOfTime;
029import org.cpsolver.coursett.constraint.MinimizeNumberOfUsedRoomsConstraint;
030import org.cpsolver.coursett.constraint.RoomConstraint;
031import org.cpsolver.coursett.constraint.SoftInstructorConstraint;
032import org.cpsolver.coursett.constraint.SpreadConstraint;
033import org.cpsolver.coursett.model.Configuration;
034import org.cpsolver.coursett.model.Lecture;
035import org.cpsolver.coursett.model.Placement;
036import org.cpsolver.coursett.model.RoomLocation;
037import org.cpsolver.coursett.model.RoomSharingModel;
038import org.cpsolver.coursett.model.Student;
039import org.cpsolver.coursett.model.StudentGroup;
040import org.cpsolver.coursett.model.TimeLocation;
041import org.cpsolver.ifs.model.Constraint;
042import org.cpsolver.ifs.solver.Solver;
043import org.cpsolver.ifs.util.Progress;
044import org.cpsolver.ifs.util.ToolBox;
045import org.dom4j.Document;
046import org.dom4j.DocumentHelper;
047import org.dom4j.Element;
048import org.dom4j.io.OutputFormat;
049import org.dom4j.io.XMLWriter;
050
051/**
052 * This class saves the resultant solution in the XML format. <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.Output</td>
063 * <td>{@link String}</td>
064 * <td>Folder with the output solution in XML format (solution.xml)</td>
065 * </tr>
066 * <tr>
067 * <td>Xml.ConvertIds</td>
068 * <td>{@link Boolean}</td>
069 * <td>If true, ids are converted (to be able to make input data public)</td>
070 * </tr>
071 * <tr>
072 * <td>Xml.ShowNames</td>
073 * <td>{@link Boolean}</td>
074 * <td>If false, names are not exported (to be able to make input data public)</td>
075 * </tr>
076 * <tr>
077 * <td>Xml.SaveBest</td>
078 * <td>{@link Boolean}</td>
079 * <td>If true, best solution is saved.</td>
080 * </tr>
081 * <tr>
082 * <td>Xml.SaveInitial</td>
083 * <td>{@link Boolean}</td>
084 * <td>If true, initial solution is saved.</td>
085 * </tr>
086 * <tr>
087 * <td>Xml.SaveCurrent</td>
088 * <td>{@link Boolean}</td>
089 * <td>If true, current solution is saved.</td>
090 * </tr>
091 * <tr>
092 * <td>Xml.ExportStudentSectioning</td>
093 * <td>{@link Boolean}</td>
094 * <td>If true, student sectioning is saved even when there is no solution.</td>
095 * </tr>
096 * </table>
097 * 
098 * @version CourseTT 1.3 (University Course Timetabling)<br>
099 *          Copyright (C) 2006 - 2014 Tomáš Müller<br>
100 *          <a href="mailto:muller@unitime.org">muller@unitime.org</a><br>
101 *          <a href="http://muller.unitime.org">http://muller.unitime.org</a><br>
102 * <br>
103 *          This library is free software; you can redistribute it and/or modify
104 *          it under the terms of the GNU Lesser General Public License as
105 *          published by the Free Software Foundation; either version 3 of the
106 *          License, or (at your option) any later version. <br>
107 * <br>
108 *          This library is distributed in the hope that it will be useful, but
109 *          WITHOUT ANY WARRANTY; without even the implied warranty of
110 *          MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
111 *          Lesser General Public License for more details. <br>
112 * <br>
113 *          You should have received a copy of the GNU Lesser General Public
114 *          License along with this library; if not see
115 *          <a href='http://www.gnu.org/licenses/'>http://www.gnu.org/licenses/</a>.
116 */
117
118public class TimetableXMLSaver extends TimetableSaver {
119    private static org.apache.logging.log4j.Logger sLogger = org.apache.logging.log4j.LogManager.getLogger(TimetableXMLSaver.class);
120    private static DecimalFormat[] sDF = { new DecimalFormat(""), new DecimalFormat("0"), new DecimalFormat("00"),
121            new DecimalFormat("000"), new DecimalFormat("0000"), new DecimalFormat("00000"),
122            new DecimalFormat("000000"), new DecimalFormat("0000000") };
123    private static DecimalFormat sStudentWeightFormat = new DecimalFormat("0.0000", new DecimalFormatSymbols(Locale.US));
124    public static boolean ANONYMISE = false;
125
126    private boolean iConvertIds = false;
127    private boolean iShowNames = false;
128    private File iOutputFolder = null;
129    private boolean iSaveBest = false;
130    private boolean iSaveInitial = false;
131    private boolean iSaveCurrent = false;
132    private boolean iExportStudentSectioning = false;
133
134    private IdConvertor iIdConvertor = null;
135
136    public TimetableXMLSaver(Solver<Lecture, Placement> solver) {
137        super(solver);
138        
139        
140        iOutputFolder = new File(getModel().getProperties().getProperty("General.Output",
141                "." + File.separator + "output"));
142        iShowNames = getModel().getProperties().getPropertyBoolean("Xml.ShowNames", false);
143        iExportStudentSectioning = getModel().getProperties().getPropertyBoolean("Xml.ExportStudentSectioning", false);
144        if (ANONYMISE) {
145            // anonymise saved XML file -- if not set otherwise in the
146            // configuration
147            iConvertIds = getModel().getProperties().getPropertyBoolean("Xml.ConvertIds", true);
148            iSaveBest = getModel().getProperties().getPropertyBoolean("Xml.SaveBest", false);
149            iSaveInitial = getModel().getProperties().getPropertyBoolean("Xml.SaveInitial", false);
150            iSaveCurrent = getModel().getProperties().getPropertyBoolean("Xml.SaveCurrent", true);
151        } else {
152            // normal operation -- if not set otherwise in the configuration
153            iConvertIds = getModel().getProperties().getPropertyBoolean("Xml.ConvertIds", false);
154            iSaveBest = getModel().getProperties().getPropertyBoolean("Xml.SaveBest", true);
155            iSaveInitial = getModel().getProperties().getPropertyBoolean("Xml.SaveInitial", true);
156            iSaveCurrent = getModel().getProperties().getPropertyBoolean("Xml.SaveCurrent", true);
157        }
158    }
159
160    private String getId(String type, String id) {
161        if (!iConvertIds)
162            return id.toString();
163        if (iIdConvertor == null)
164            iIdConvertor = new IdConvertor(getModel().getProperties().getProperty("Xml.IdConv"));
165        return iIdConvertor.convert(type, id);
166    }
167
168    private String getId(String type, Number id) {
169        return getId(type, id.toString());
170    }
171
172    private static String bitset2string(BitSet b) {
173        StringBuffer sb = new StringBuffer();
174        for (int i = 0; i < b.length(); i++)
175            sb.append(b.get(i) ? "1" : "0");
176        return sb.toString();
177    }
178
179    @Override
180    public void save() throws Exception {
181        save(null);
182    }
183    
184    public Document saveDocument() {
185        Document document = DocumentHelper.createDocument();
186        document.addComment("University Course Timetabling");
187
188        if (iSaveCurrent && getAssignment().nrAssignedVariables() != 0) {
189            StringBuffer comments = new StringBuffer("Solution Info:\n");
190            Map<String, String> solutionInfo = (getSolution() == null ? getModel().getExtendedInfo(getAssignment()) : getSolution().getExtendedInfo());
191            for (String key : new TreeSet<String>(solutionInfo.keySet())) {
192                String value = solutionInfo.get(key);
193                comments.append("    " + key + ": " + value + "\n");
194            }
195            document.addComment(comments.toString());
196        }
197
198        Element root = document.addElement("timetable");
199
200        doSave(root);
201
202        return document;
203    }
204
205    public void save(File outFile) throws Exception {
206        if (outFile == null)
207            outFile = new File(iOutputFolder, "solution.xml");
208        outFile.getParentFile().mkdirs();
209        sLogger.debug("Writting XML data to:" + outFile);
210
211        Document document = DocumentHelper.createDocument();
212        document.addComment("University Course Timetabling");
213
214        if (iSaveCurrent && getAssignment().nrAssignedVariables() != 0) {
215            StringBuffer comments = new StringBuffer("Solution Info:\n");
216            Map<String, String> solutionInfo = (getSolution() == null ? getModel().getExtendedInfo(getAssignment()) : getSolution().getExtendedInfo());
217            for (String key : new TreeSet<String>(solutionInfo.keySet())) {
218                String value = solutionInfo.get(key);
219                comments.append("    " + key + ": " + value + "\n");
220            }
221            document.addComment(comments.toString());
222        }
223
224        Element root = document.addElement("timetable");
225
226        doSave(root);
227
228        if (iShowNames) {
229            Progress.getInstance(getModel()).save(root);
230
231            try {
232                getSolver().getClass().getMethod("save", new Class[] { Element.class }).invoke(getSolver(),
233                                new Object[] { root });
234            } catch (Exception e) {
235            }
236        }
237
238        FileOutputStream fos = null;
239        try {
240            fos = new FileOutputStream(outFile);
241            (new XMLWriter(fos, OutputFormat.createPrettyPrint())).write(document);
242            fos.flush();
243            fos.close();
244            fos = null;
245        } finally {
246            try {
247                if (fos != null)
248                    fos.close();
249            } catch (IOException e) {
250            }
251        }
252
253        if (iConvertIds)
254            iIdConvertor.save();
255    }
256    
257    protected void doSave(Element root) {
258        root.addAttribute("version", "2.5");
259        root.addAttribute("initiative", getModel().getProperties().getProperty("Data.Initiative"));
260        root.addAttribute("term", getModel().getProperties().getProperty("Data.Term"));
261        root.addAttribute("year", String.valueOf(getModel().getYear()));
262        root.addAttribute("created", String.valueOf(new Date()));
263        root.addAttribute("nrDays", String.valueOf(Constants.DAY_CODES.length));
264        root.addAttribute("slotsPerDay", String.valueOf(Constants.SLOTS_PER_DAY));
265        if (!iConvertIds && getModel().getProperties().getProperty("General.SessionId") != null)
266            root.addAttribute("session", getModel().getProperties().getProperty("General.SessionId"));
267        if (iShowNames && !iConvertIds && getModel().getProperties().getProperty("General.SolverGroupId") != null)
268            root.addAttribute("solverGroup", getId("solverGroup", getModel().getProperties().getProperty(
269                    "General.SolverGroupId")));
270
271        HashMap<String, Element> roomElements = new HashMap<String, Element>();
272
273        Element roomsEl = root.addElement("rooms");
274        for (RoomConstraint roomConstraint : getModel().getRoomConstraints()) {
275            Element roomEl = roomsEl.addElement("room").addAttribute("id",
276                    getId("room", roomConstraint.getResourceId()));
277            roomEl.addAttribute("constraint", "true");
278            if (roomConstraint instanceof DiscouragedRoomConstraint)
279                roomEl.addAttribute("discouraged", "true");
280            if (iShowNames) {
281                roomEl.addAttribute("name", roomConstraint.getRoomName());
282            }
283            if (!iConvertIds && roomConstraint.getBuildingId() != null)
284                roomEl.addAttribute("building", getId("bldg", roomConstraint.getBuildingId()));
285            if (roomConstraint.getParentRoom() != null)
286                roomEl.addAttribute("parentId", getId("room", roomConstraint.getParentRoom().getResourceId()));
287            roomElements.put(getId("room", roomConstraint.getResourceId()), roomEl);
288            roomEl.addAttribute("capacity", String.valueOf(roomConstraint.getCapacity()));
289            if (roomConstraint.getPosX() != null && roomConstraint.getPosY() != null)
290                roomEl.addAttribute("location", roomConstraint.getPosX() + "," + roomConstraint.getPosY());
291            if (roomConstraint.getIgnoreTooFar())
292                roomEl.addAttribute("ignoreTooFar", "true");
293            if (!roomConstraint.getConstraint())
294                roomEl.addAttribute("fake", "true");
295            if (roomConstraint.getSharingModel() != null) {
296                RoomSharingModel sharingModel = roomConstraint.getSharingModel();
297                Element sharingEl = roomEl.addElement("sharing");
298                sharingEl.addElement("pattern").addAttribute("unit", String.valueOf(sharingModel.getStep())).setText(sharingModel.getPreferences());
299                sharingEl.addElement("freeForAll").addAttribute("value",
300                        String.valueOf(sharingModel.getFreeForAllPrefChar()));
301                sharingEl.addElement("notAvailable").addAttribute("value",
302                        String.valueOf(sharingModel.getNotAvailablePrefChar()));
303                for (Long id: sharingModel.getDepartmentIds()) {
304                    sharingEl.addElement("department")
305                        .addAttribute("value", String.valueOf(sharingModel.getCharacter(id)))
306                        .addAttribute("id", getId("dept", id));
307                }
308            }
309            if (roomConstraint.getType() != null && iShowNames)
310                roomEl.addAttribute("type", roomConstraint.getType().toString());
311            
312            Map<Long, Integer> travelTimes = getModel().getDistanceMetric().getTravelTimes().get(roomConstraint.getResourceId());
313            if (travelTimes != null)
314                for (Map.Entry<Long, Integer> time: travelTimes.entrySet())
315                    roomEl.addElement("travel-time").addAttribute("id", getId("room", time.getKey())).addAttribute("minutes", time.getValue().toString());
316        }
317
318        Element instructorsEl = root.addElement("instructors");
319
320        Element departmentsEl = root.addElement("departments");
321        HashMap<Long, String> depts = new HashMap<Long, String>();
322
323        Element configsEl = (iShowNames ? root.addElement("configurations") : null);
324        HashSet<Configuration> configs = new HashSet<Configuration>();
325
326        Element classesEl = root.addElement("classes");
327        HashMap<Long, Element> classElements = new HashMap<Long, Element>();
328        List<Lecture> vars = new ArrayList<Lecture>(getModel().variables());
329        if (getModel().hasConstantVariables())
330            vars.addAll(getModel().constantVariables());
331        for (Lecture lecture : vars) {
332            Placement placement = getAssignment().getValue(lecture);
333            if (lecture.isCommitted() && placement == null)
334                placement = lecture.getInitialAssignment();
335            Placement initialPlacement = lecture.getInitialAssignment();
336            // if (initialPlacement==null) initialPlacement =
337            // (Placement)lecture.getAssignment();
338            Placement bestPlacement = lecture.getBestAssignment();
339            Element classEl = classesEl.addElement("class").addAttribute("id", getId("class", lecture.getClassId()));
340            classElements.put(lecture.getClassId(), classEl);
341            if (iShowNames && lecture.getNote() != null)
342                classEl.addAttribute("note", lecture.getNote());
343            if (iShowNames && !lecture.isCommitted())
344                classEl.addAttribute("ord", String.valueOf(lecture.getOrd()));
345            if (lecture.getWeight() != 1.0)
346                classEl.addAttribute("weight", String.valueOf(lecture.getWeight()));
347            if (iShowNames && lecture.getSolverGroupId() != null)
348                classEl.addAttribute("solverGroup", getId("solverGroup", lecture.getSolverGroupId()));
349            if (lecture.getParent() == null && lecture.getConfiguration() != null) {
350                if (!iShowNames)
351                    classEl.addAttribute("offering", getId("offering", lecture.getConfiguration().getOfferingId()
352                            .toString()));
353                classEl.addAttribute("config", getId("config", lecture.getConfiguration().getConfigId().toString()));
354                if (iShowNames && configs.add(lecture.getConfiguration())) {
355                    configsEl.addElement("config").addAttribute("id",
356                            getId("config", lecture.getConfiguration().getConfigId().toString())).addAttribute("limit",
357                            String.valueOf(lecture.getConfiguration().getLimit())).addAttribute("offering",
358                            getId("offering", lecture.getConfiguration().getOfferingId().toString()));
359                }
360            }
361            classEl.addAttribute("committed", (lecture.isCommitted() ? "true" : "false"));
362            if (lecture.getParent() != null)
363                classEl.addAttribute("parent", getId("class", lecture.getParent().getClassId()));
364            if (lecture.getSchedulingSubpartId() != null)
365                classEl.addAttribute("subpart", getId("subpart", lecture.getSchedulingSubpartId()));
366            if (iShowNames && lecture.isCommitted() && placement != null && placement.getAssignmentId() != null) {
367                classEl.addAttribute("assignment", getId("assignment", placement.getAssignmentId()));
368            }
369            if (!lecture.isCommitted()) {
370                if (lecture.minClassLimit() == lecture.maxClassLimit()) {
371                    classEl.addAttribute("classLimit", String.valueOf(lecture.maxClassLimit()));
372                } else {
373                    classEl.addAttribute("minClassLimit", String.valueOf(lecture.minClassLimit()));
374                    classEl.addAttribute("maxClassLimit", String.valueOf(lecture.maxClassLimit()));
375                }
376                if (lecture.roomToLimitRatio() != 1.0f)
377                    classEl.addAttribute("roomToLimitRatio", sStudentWeightFormat.format(lecture.roomToLimitRatio()));
378            }
379            if (lecture.getNrRooms() != 1)
380                classEl.addAttribute("nrRooms", String.valueOf(lecture.getNrRooms()));
381            if (lecture.getNrRooms() > 1)
382                classEl.addAttribute("splitAttandance", lecture.isSplitAttendance() ? "true" : "false");
383            if (lecture.getNrRooms() > 1 && lecture.getMaxRoomCombinations() > 0)
384                classEl.addAttribute("maxRoomCombinations", String.valueOf(lecture.getMaxRoomCombinations()));
385            if (iShowNames)
386                classEl.addAttribute("name", lecture.getName());
387            if (lecture.getDeptSpreadConstraint() != null) {
388                classEl.addAttribute("department", getId("dept", lecture.getDeptSpreadConstraint().getDepartmentId()));
389                depts.put(lecture.getDeptSpreadConstraint().getDepartmentId(), lecture.getDeptSpreadConstraint()
390                        .getName());
391            }
392            if (lecture.getScheduler() != null)
393                classEl.addAttribute("scheduler", getId("dept", lecture.getScheduler()));
394            for (InstructorConstraint ic : lecture.getInstructorConstraints()) {
395                Element instrEl = classEl.addElement("instructor")
396                        .addAttribute("id", getId("inst", ic.getResourceId()));
397                if ((lecture.isCommitted() || iSaveCurrent) && placement != null)
398                    instrEl.addAttribute("solution", "true");
399                if (iSaveInitial && initialPlacement != null)
400                    instrEl.addAttribute("initial", "true");
401                if (iSaveBest && bestPlacement != null && !bestPlacement.equals(placement))
402                    instrEl.addAttribute("best", "true");
403            }
404            for (RoomLocation rl : lecture.roomLocations()) {
405                Element roomLocationEl = classEl.addElement("room");
406                roomLocationEl.addAttribute("id", getId("room", rl.getId()));
407                roomLocationEl.addAttribute("pref", String.valueOf(rl.getPreference()));
408                if ((lecture.isCommitted() || iSaveCurrent) && placement != null
409                        && placement.hasRoomLocation(rl.getId()))
410                    roomLocationEl.addAttribute("solution", "true");
411                if (iSaveInitial && initialPlacement != null && initialPlacement.hasRoomLocation(rl.getId()))
412                    roomLocationEl.addAttribute("initial", "true");
413                if (iSaveBest && bestPlacement != null && !bestPlacement.equals(placement)
414                        && bestPlacement.hasRoomLocation(rl.getId()))
415                    roomLocationEl.addAttribute("best", "true");
416                if (rl.hasPreferenceByIndex()) {
417                    for (Map.Entry<Integer, Integer> e: rl.getPreferenceByIndex().entrySet()) {
418                        roomLocationEl.addElement("preference").addAttribute("index", e.getKey().toString()).addAttribute("pref", e.getValue().toString());
419                    }
420                }
421                if (!roomElements.containsKey(getId("room", rl.getId()))) {
422                    // room location without room constraint
423                    Element roomEl = roomsEl.addElement("room").addAttribute("id", getId("room", rl.getId()));
424                    roomEl.addAttribute("constraint", "false");
425                    if (!iConvertIds && rl.getBuildingId() != null)
426                        roomEl.addAttribute("building", getId("bldg", rl.getBuildingId()));
427                    if (rl.getRoomConstraint() != null && rl.getRoomConstraint().getParentRoom() != null)
428                        roomEl.addAttribute("parentId", getId("room", rl.getRoomConstraint().getParentRoom().getResourceId()));
429                    if (iShowNames) {
430                        roomEl.addAttribute("name", rl.getName());
431                    }
432                    roomElements.put(getId("room", rl.getId()), roomEl);
433                    roomEl.addAttribute("capacity", String.valueOf(rl.getRoomSize()));
434                    if (rl.getPosX() != null && rl.getPosY() != null)
435                        roomEl.addAttribute("location", rl.getPosX() + "," + rl.getPosY());
436                    if (rl.getIgnoreTooFar())
437                        roomEl.addAttribute("ignoreTooFar", "true");
438                }
439            }
440            boolean first = true;
441            Set<Long> dp = new HashSet<Long>();
442            for (TimeLocation tl : lecture.timeLocations()) {
443                Element timeLocationEl = classEl.addElement("time");
444                timeLocationEl.addAttribute("days", sDF[7].format(Long.parseLong(Integer
445                        .toBinaryString(tl.getDayCode()))));
446                timeLocationEl.addAttribute("start", String.valueOf(tl.getStartSlot()));
447                timeLocationEl.addAttribute("length", String.valueOf(tl.getLength()));
448                timeLocationEl.addAttribute("breakTime", String.valueOf(tl.getBreakTime()));
449                if (iShowNames) {
450                    timeLocationEl.addAttribute("pref", String.valueOf(tl.getPreference()));
451                    timeLocationEl.addAttribute("npref", String.valueOf(tl.getNormalizedPreference()));
452                } else {
453                    timeLocationEl.addAttribute("pref", String.valueOf(tl.getNormalizedPreference()));
454                }
455                if (!iConvertIds && tl.getTimePatternId() != null)
456                    timeLocationEl.addAttribute("pattern", getId("pat", tl.getTimePatternId()));
457                if (tl.getDatePatternId() != null && dp.add(tl.getDatePatternId())) {
458                    Element dateEl = classEl.addElement("date");
459                    dateEl.addAttribute("id", getId("dpat", String.valueOf(tl.getDatePatternId())));
460                    if (iShowNames)
461                        dateEl.addAttribute("name", tl.getDatePatternName());
462                    dateEl.addAttribute("pattern", bitset2string(tl.getWeekCode()));
463                }
464                if (tl.getDatePatternPreference() != 0)
465                    timeLocationEl.addAttribute("datePref", String.valueOf(tl.getDatePatternPreference()));
466                if (tl.getTimePatternId() == null && first) {
467                    if (iShowNames)
468                        classEl.addAttribute("datePatternName", tl.getDatePatternName());
469                    classEl.addAttribute("dates", bitset2string(tl.getWeekCode()));
470                    first = false;
471                }
472                if (tl.getDatePatternId() != null) {
473                    timeLocationEl.addAttribute("date", getId("dpat", String.valueOf(tl.getDatePatternId())));
474                }
475                if ((lecture.isCommitted() || iSaveCurrent) && placement != null
476                        && placement.getTimeLocation().equals(tl))
477                    timeLocationEl.addAttribute("solution", "true");
478                if (iSaveInitial && initialPlacement != null && initialPlacement.getTimeLocation().equals(tl))
479                    timeLocationEl.addAttribute("initial", "true");
480                if (iSaveBest && bestPlacement != null && !bestPlacement.equals(placement)
481                        && bestPlacement.getTimeLocation().equals(tl))
482                    timeLocationEl.addAttribute("best", "true");
483            }
484        }
485
486        for (InstructorConstraint ic : getModel().getInstructorConstraints()) {
487            if (iShowNames || ic.isIgnoreDistances() || ic instanceof SoftInstructorConstraint) {
488                Element instrEl = instructorsEl.addElement("instructor").addAttribute("id",
489                        getId("inst", ic.getResourceId()));
490                if (iShowNames) {
491                    if (ic.getPuid() != null && ic.getPuid().length() > 0)
492                        instrEl.addAttribute("puid", ic.getPuid());
493                    instrEl.addAttribute("name", ic.getName());
494                    if (ic.getType() != null && iShowNames)
495                        instrEl.addAttribute("type", ic.getType().toString());
496                }
497                if (ic.isIgnoreDistances()) {
498                    instrEl.addAttribute("ignDist", "true");
499                }
500                if (ic instanceof SoftInstructorConstraint) instrEl.addAttribute("soft", "true");
501            }
502            if (ic.getUnavailabilities() != null) {
503                for (Placement placement: ic.getUnavailabilities()) {
504                    Lecture lecture = placement.variable();
505                    Element classEl = classElements.get(lecture.getClassId());
506                    classEl.addElement("instructor").addAttribute("id", getId("inst", ic.getResourceId())).addAttribute("solution", "true");
507                }
508            }
509        }
510        if (instructorsEl.elements().isEmpty())
511            root.remove(instructorsEl);
512
513        Element grConstraintsEl = root.addElement("groupConstraints");
514        for (GroupConstraint gc : getModel().getGroupConstraints()) {
515            Element grEl = grConstraintsEl.addElement("constraint").addAttribute("id",
516                    getId("gr", String.valueOf(gc.getId())));
517            grEl.addAttribute("type", gc.getType().reference());
518            grEl.addAttribute("pref", gc.getPrologPreference());
519            for (Lecture l : gc.variables()) {
520                grEl.addElement("class").addAttribute("id", getId("class", l.getClassId()));
521            }
522        }       
523        for (SpreadConstraint spread : getModel().getSpreadConstraints()) {
524            Element grEl = grConstraintsEl.addElement("constraint").addAttribute("id",
525                    getId("gr", String.valueOf(spread.getId())));
526            grEl.addAttribute("type", "SPREAD");
527            grEl.addAttribute("pref", Constants.sPreferenceRequired);
528            if (iShowNames)
529                grEl.addAttribute("name", spread.getName());
530            for (Lecture l : spread.variables()) {
531                grEl.addElement("class").addAttribute("id", getId("class", l.getClassId()));
532            }
533        }
534        for (Constraint<Lecture, Placement> c : getModel().constraints()) {
535            if (c instanceof MinimizeNumberOfUsedRoomsConstraint) {
536                Element grEl = grConstraintsEl.addElement("constraint").addAttribute("id",
537                        getId("gr", String.valueOf(c.getId())));
538                grEl.addAttribute("type", "MIN_ROOM_USE");
539                grEl.addAttribute("pref", Constants.sPreferenceRequired);
540                for (Lecture l : c.variables()) {
541                    grEl.addElement("class").addAttribute("id", getId("class", l.getClassId()));
542                }
543            }
544            if (c instanceof MinimizeNumberOfUsedGroupsOfTime) {
545                Element grEl = grConstraintsEl.addElement("constraint").addAttribute("id",
546                        getId("gr", String.valueOf(c.getId())));
547                grEl.addAttribute("type", ((MinimizeNumberOfUsedGroupsOfTime) c).getConstraintName());
548                grEl.addAttribute("pref", Constants.sPreferenceRequired);
549                for (Lecture l : c.variables()) {
550                    grEl.addElement("class").addAttribute("id", getId("class", l.getClassId()));
551                }
552            }
553            if (c instanceof IgnoreStudentConflictsConstraint) {
554                Element grEl = grConstraintsEl.addElement("constraint").addAttribute("id", getId("gr", String.valueOf(c.getId())));
555                grEl.addAttribute("type", IgnoreStudentConflictsConstraint.REFERENCE);
556                grEl.addAttribute("pref", Constants.sPreferenceRequired);
557                for (Lecture l : c.variables()) {
558                    grEl.addElement("class").addAttribute("id", getId("class", l.getClassId()));
559                }
560            }
561        }
562        for (ClassLimitConstraint clc : getModel().getClassLimitConstraints()) {
563            Element grEl = grConstraintsEl.addElement("constraint").addAttribute("id",
564                    getId("gr", String.valueOf(clc.getId())));
565            grEl.addAttribute("type", "CLASS_LIMIT");
566            grEl.addAttribute("pref", Constants.sPreferenceRequired);
567            if (clc.getParentLecture() != null) {
568                grEl.addElement("parentClass").addAttribute("id", getId("class", clc.getParentLecture().getClassId()));
569            } else
570                grEl.addAttribute("courseLimit", String.valueOf(clc.classLimit() - clc.getClassLimitDelta()));
571            if (clc.getClassLimitDelta() != 0)
572                grEl.addAttribute("delta", String.valueOf(clc.getClassLimitDelta()));
573            if (iShowNames)
574                grEl.addAttribute("name", clc.getName());
575            for (Lecture l : clc.variables()) {
576                grEl.addElement("class").addAttribute("id", getId("class", l.getClassId()));
577            }
578        }
579        for (FlexibleConstraint gc : getModel().getFlexibleConstraints()) {
580            Element flEl = grConstraintsEl.addElement("constraint").addAttribute("id",
581                    getId("gr", String.valueOf(gc.getId())));
582            flEl.addAttribute("reference", gc.getReference());
583            flEl.addAttribute("owner", gc.getOwner());
584            flEl.addAttribute("pref", gc.getPrologPreference());  
585            flEl.addAttribute("type", gc.getType().toString());  
586            for (Lecture l : gc.variables()) {
587                flEl.addElement("class").addAttribute("id", getId("class", l.getClassId()));
588            }
589        }
590
591        HashMap<Student, List<String>> students = new HashMap<Student, List<String>>();
592        for (Lecture lecture : vars) {
593            for (Student student : lecture.students()) {
594                List<String> enrls = students.get(student);
595                if (enrls == null) {
596                    enrls = new ArrayList<String>();
597                    students.put(student, enrls);
598                }
599                enrls.add(getId("class", lecture.getClassId()));
600            }
601        }
602
603        Element studentsEl = root.addElement("students");
604        Element groupsEl = root.addElement("groups");
605        Map<StudentGroup, Element> groups = new HashMap<StudentGroup, Element>();
606        for (Student student: new TreeSet<Student>(students.keySet())) {
607            Element stEl = studentsEl.addElement("student").addAttribute("id", getId("student", student.getId()));
608            if (iShowNames) {
609                if (student.getAcademicArea() != null)
610                    stEl.addAttribute("area", student.getAcademicArea());
611                if (student.getAcademicClassification() != null)
612                    stEl.addAttribute("classification", student.getAcademicClassification());
613                if (student.getMajor() != null)
614                    stEl.addAttribute("major", student.getMajor());
615                if (student.getCurriculum() != null)
616                    stEl.addAttribute("curriculum", student.getCurriculum());
617            }
618            for (Map.Entry<Long, Double> entry : student.getOfferingsMap().entrySet()) {
619                Long offeringId = entry.getKey();
620                Double weight = entry.getValue();
621                Element offEl = stEl.addElement("offering")
622                        .addAttribute("id", getId("offering", offeringId.toString()));
623                if (weight.doubleValue() != 1.0)
624                    offEl.addAttribute("weight", sStudentWeightFormat.format(weight));
625                Double priority = student.getPriority(offeringId);
626                if (priority != null)
627                    offEl.addAttribute("priority", priority.toString());
628                Long altId = student.getAlternative(offeringId);
629                if (altId != null)
630                    offEl.addAttribute("alternative", altId.toString());
631            }
632            if (iExportStudentSectioning || getModel().nrUnassignedVariables(getAssignment()) == 0 || student.getOfferingsMap().isEmpty()) {
633                List<String> lectures = students.get(student);
634                Collections.sort(lectures);
635                for (String classId : lectures) {
636                    stEl.addElement("class").addAttribute("id", classId);
637                }
638            }
639            Map<Long, Set<Lecture>> canNotEnroll = student.canNotEnrollSections();
640            if (canNotEnroll != null) {
641                for (Set<Lecture> canNotEnrollLects: canNotEnroll.values()) {
642                    for (Iterator<Lecture> i3 = canNotEnrollLects.iterator(); i3.hasNext();) {
643                        stEl.addElement("prohibited-class")
644                                .addAttribute("id", getId("class", (i3.next()).getClassId()));
645                    }
646                }
647            }
648
649            if (student.getCommitedPlacements() != null) {
650                for (Placement placement : student.getCommitedPlacements()) {
651                    stEl.addElement("class").addAttribute("id", getId("class", placement.variable().getClassId()));
652                }
653            }
654            
655            if (student.getInstructor() != null)
656                stEl.addAttribute("instructor", getId("inst", student.getInstructor().getResourceId()));
657            
658            for (StudentGroup group: student.getGroups()) {
659                Element groupEl = groups.get(group);
660                if (groupEl == null) {
661                    groupEl = groupsEl.addElement("group");
662                    groupEl.addAttribute("id", getId("group", group.getId()));
663                    if (group.getWeight() != 1.0)
664                        groupEl.addAttribute("weight", String.valueOf(group.getWeight()));
665                    if (iShowNames && group.getName() != null)
666                        groupEl.addAttribute("name", group.getName());
667                    groups.put(group, groupEl);
668                }
669                groupEl.addElement("student").addAttribute("id", getId("student", student.getId()));
670            }
671        }
672
673        if (getModel().getProperties().getPropertyInt("MPP.GenTimePert", 0) > 0) {
674            Element perturbationsEl = root.addElement("perturbations");
675            int nrChanges = getModel().getProperties().getPropertyInt("MPP.GenTimePert", 0);
676            List<Lecture> lectures = new ArrayList<Lecture>();
677            while (lectures.size() < nrChanges) {
678                Lecture lecture = ToolBox.random(getAssignment().assignedVariables());
679                if (lecture.isCommitted() || lecture.timeLocations().size() <= 1 || lectures.contains(lecture))
680                    continue;
681                Placement placement = getAssignment().getValue(lecture);
682                TimeLocation tl = placement.getTimeLocation();
683                perturbationsEl.addElement("class").addAttribute("id", getId("class", lecture.getClassId()))
684                        .addAttribute("days", sDF[7].format(Long.parseLong(Integer.toBinaryString(tl.getDayCode()))))
685                        .addAttribute("start", String.valueOf(tl.getStartSlot())).addAttribute("length",
686                                String.valueOf(tl.getLength()));
687                lectures.add(lecture);
688            }
689        }
690
691        for (Map.Entry<Long, String> entry : depts.entrySet()) {
692            Long id = entry.getKey();
693            String name = entry.getValue();
694            if (iShowNames) {
695                departmentsEl.addElement("department").addAttribute("id", getId("dept", id.toString())).addAttribute(
696                        "name", name);
697            }
698        }
699        if (departmentsEl.elements().isEmpty())
700            root.remove(departmentsEl);
701    }
702}