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)
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.hasRoomLocation(rl.getId()))
414                    roomLocationEl.addAttribute("best", "true");
415                if (rl.hasPreferenceByIndex()) {
416                    for (Map.Entry<Integer, Integer> e: rl.getPreferenceByIndex().entrySet()) {
417                        roomLocationEl.addElement("preference").addAttribute("index", e.getKey().toString()).addAttribute("pref", e.getValue().toString());
418                    }
419                }
420                if (!roomElements.containsKey(getId("room", rl.getId()))) {
421                    // room location without room constraint
422                    Element roomEl = roomsEl.addElement("room").addAttribute("id", getId("room", rl.getId()));
423                    roomEl.addAttribute("constraint", "false");
424                    if (!iConvertIds && rl.getBuildingId() != null)
425                        roomEl.addAttribute("building", getId("bldg", rl.getBuildingId()));
426                    if (rl.getRoomConstraint() != null && rl.getRoomConstraint().getParentRoom() != null)
427                        roomEl.addAttribute("parentId", getId("room", rl.getRoomConstraint().getParentRoom().getResourceId()));
428                    if (iShowNames) {
429                        roomEl.addAttribute("name", rl.getName());
430                    }
431                    roomElements.put(getId("room", rl.getId()), roomEl);
432                    roomEl.addAttribute("capacity", String.valueOf(rl.getRoomSize()));
433                    if (rl.getPosX() != null && rl.getPosY() != null)
434                        roomEl.addAttribute("location", rl.getPosX() + "," + rl.getPosY());
435                    if (rl.getIgnoreTooFar())
436                        roomEl.addAttribute("ignoreTooFar", "true");
437                }
438            }
439            boolean first = true;
440            Set<Long> dp = new HashSet<Long>();
441            for (TimeLocation tl : lecture.timeLocations()) {
442                Element timeLocationEl = classEl.addElement("time");
443                timeLocationEl.addAttribute("days", sDF[7].format(Long.parseLong(Integer
444                        .toBinaryString(tl.getDayCode()))));
445                timeLocationEl.addAttribute("start", String.valueOf(tl.getStartSlot()));
446                timeLocationEl.addAttribute("length", String.valueOf(tl.getLength()));
447                timeLocationEl.addAttribute("breakTime", String.valueOf(tl.getBreakTime()));
448                if (iShowNames) {
449                    timeLocationEl.addAttribute("pref", String.valueOf(tl.getPreference()));
450                    timeLocationEl.addAttribute("npref", String.valueOf(tl.getNormalizedPreference()));
451                } else {
452                    timeLocationEl.addAttribute("pref", String.valueOf(tl.getNormalizedPreference()));
453                }
454                if (!iConvertIds && tl.getTimePatternId() != null)
455                    timeLocationEl.addAttribute("pattern", getId("pat", tl.getTimePatternId()));
456                if (tl.getDatePatternId() != null && dp.add(tl.getDatePatternId())) {
457                    Element dateEl = classEl.addElement("date");
458                    dateEl.addAttribute("id", getId("dpat", String.valueOf(tl.getDatePatternId())));
459                    if (iShowNames)
460                        dateEl.addAttribute("name", tl.getDatePatternName());
461                    dateEl.addAttribute("pattern", bitset2string(tl.getWeekCode()));
462                }
463                if (tl.getDatePatternPreference() != 0)
464                    timeLocationEl.addAttribute("datePref", String.valueOf(tl.getDatePatternPreference()));
465                if (tl.getTimePatternId() == null && first) {
466                    if (iShowNames)
467                        classEl.addAttribute("datePatternName", tl.getDatePatternName());
468                    classEl.addAttribute("dates", bitset2string(tl.getWeekCode()));
469                    first = false;
470                }
471                if (tl.getDatePatternId() != null) {
472                    timeLocationEl.addAttribute("date", getId("dpat", String.valueOf(tl.getDatePatternId())));
473                }
474                if ((lecture.isCommitted() || iSaveCurrent) && placement != null
475                        && placement.getTimeLocation().equals(tl))
476                    timeLocationEl.addAttribute("solution", "true");
477                if (iSaveInitial && initialPlacement != null && initialPlacement.getTimeLocation().equals(tl))
478                    timeLocationEl.addAttribute("initial", "true");
479                if (iSaveBest && bestPlacement != null && bestPlacement.getTimeLocation().equals(tl))
480                    timeLocationEl.addAttribute("best", "true");
481            }
482        }
483
484        for (InstructorConstraint ic : getModel().getInstructorConstraints()) {
485            if (iShowNames || ic.isIgnoreDistances() || ic instanceof SoftInstructorConstraint) {
486                Element instrEl = instructorsEl.addElement("instructor").addAttribute("id",
487                        getId("inst", ic.getResourceId()));
488                if (iShowNames) {
489                    if (ic.getPuid() != null && ic.getPuid().length() > 0)
490                        instrEl.addAttribute("puid", ic.getPuid());
491                    instrEl.addAttribute("name", ic.getName());
492                    if (ic.getType() != null && iShowNames)
493                        instrEl.addAttribute("type", ic.getType().toString());
494                }
495                if (ic.isIgnoreDistances()) {
496                    instrEl.addAttribute("ignDist", "true");
497                }
498                if (ic instanceof SoftInstructorConstraint) instrEl.addAttribute("soft", "true");
499            }
500            if (ic.getUnavailabilities() != null) {
501                for (Placement placement: ic.getUnavailabilities()) {
502                    Lecture lecture = placement.variable();
503                    Element classEl = classElements.get(lecture.getClassId());
504                    classEl.addElement("instructor").addAttribute("id", getId("inst", ic.getResourceId())).addAttribute("solution", "true");
505                }
506            }
507        }
508        if (instructorsEl.elements().isEmpty())
509            root.remove(instructorsEl);
510
511        Element grConstraintsEl = root.addElement("groupConstraints");
512        for (GroupConstraint gc : getModel().getGroupConstraints()) {
513            Element grEl = grConstraintsEl.addElement("constraint").addAttribute("id",
514                    getId("gr", String.valueOf(gc.getId())));
515            grEl.addAttribute("type", gc.getType().reference());
516            grEl.addAttribute("pref", gc.getPrologPreference());
517            for (Lecture l : gc.variables()) {
518                grEl.addElement("class").addAttribute("id", getId("class", l.getClassId()));
519            }
520        }       
521        for (SpreadConstraint spread : getModel().getSpreadConstraints()) {
522            Element grEl = grConstraintsEl.addElement("constraint").addAttribute("id",
523                    getId("gr", String.valueOf(spread.getId())));
524            grEl.addAttribute("type", "SPREAD");
525            grEl.addAttribute("pref", Constants.sPreferenceRequired);
526            if (iShowNames)
527                grEl.addAttribute("name", spread.getName());
528            for (Lecture l : spread.variables()) {
529                grEl.addElement("class").addAttribute("id", getId("class", l.getClassId()));
530            }
531        }
532        for (Constraint<Lecture, Placement> c : getModel().constraints()) {
533            if (c instanceof MinimizeNumberOfUsedRoomsConstraint) {
534                Element grEl = grConstraintsEl.addElement("constraint").addAttribute("id",
535                        getId("gr", String.valueOf(c.getId())));
536                grEl.addAttribute("type", "MIN_ROOM_USE");
537                grEl.addAttribute("pref", Constants.sPreferenceRequired);
538                for (Lecture l : c.variables()) {
539                    grEl.addElement("class").addAttribute("id", getId("class", l.getClassId()));
540                }
541            }
542            if (c instanceof MinimizeNumberOfUsedGroupsOfTime) {
543                Element grEl = grConstraintsEl.addElement("constraint").addAttribute("id",
544                        getId("gr", String.valueOf(c.getId())));
545                grEl.addAttribute("type", ((MinimizeNumberOfUsedGroupsOfTime) c).getConstraintName());
546                grEl.addAttribute("pref", Constants.sPreferenceRequired);
547                for (Lecture l : c.variables()) {
548                    grEl.addElement("class").addAttribute("id", getId("class", l.getClassId()));
549                }
550            }
551            if (c instanceof IgnoreStudentConflictsConstraint) {
552                Element grEl = grConstraintsEl.addElement("constraint").addAttribute("id", getId("gr", String.valueOf(c.getId())));
553                grEl.addAttribute("type", IgnoreStudentConflictsConstraint.REFERENCE);
554                grEl.addAttribute("pref", Constants.sPreferenceRequired);
555                for (Lecture l : c.variables()) {
556                    grEl.addElement("class").addAttribute("id", getId("class", l.getClassId()));
557                }
558            }
559        }
560        for (ClassLimitConstraint clc : getModel().getClassLimitConstraints()) {
561            Element grEl = grConstraintsEl.addElement("constraint").addAttribute("id",
562                    getId("gr", String.valueOf(clc.getId())));
563            grEl.addAttribute("type", "CLASS_LIMIT");
564            grEl.addAttribute("pref", Constants.sPreferenceRequired);
565            if (clc.getParentLecture() != null) {
566                grEl.addElement("parentClass").addAttribute("id", getId("class", clc.getParentLecture().getClassId()));
567            } else
568                grEl.addAttribute("courseLimit", String.valueOf(clc.classLimit() - clc.getClassLimitDelta()));
569            if (clc.getClassLimitDelta() != 0)
570                grEl.addAttribute("delta", String.valueOf(clc.getClassLimitDelta()));
571            if (iShowNames)
572                grEl.addAttribute("name", clc.getName());
573            for (Lecture l : clc.variables()) {
574                grEl.addElement("class").addAttribute("id", getId("class", l.getClassId()));
575            }
576        }
577        for (FlexibleConstraint gc : getModel().getFlexibleConstraints()) {
578            Element flEl = grConstraintsEl.addElement("constraint").addAttribute("id",
579                    getId("gr", String.valueOf(gc.getId())));
580            flEl.addAttribute("reference", gc.getReference());
581            flEl.addAttribute("owner", gc.getOwner());
582            flEl.addAttribute("pref", gc.getPrologPreference());  
583            flEl.addAttribute("type", gc.getType().toString());  
584            for (Lecture l : gc.variables()) {
585                flEl.addElement("class").addAttribute("id", getId("class", l.getClassId()));
586            }
587        }
588
589        HashMap<Student, List<String>> students = new HashMap<Student, List<String>>();
590        for (Lecture lecture : vars) {
591            for (Student student : lecture.students()) {
592                List<String> enrls = students.get(student);
593                if (enrls == null) {
594                    enrls = new ArrayList<String>();
595                    students.put(student, enrls);
596                }
597                enrls.add(getId("class", lecture.getClassId()));
598            }
599        }
600
601        Element studentsEl = root.addElement("students");
602        Element groupsEl = root.addElement("groups");
603        Map<StudentGroup, Element> groups = new HashMap<StudentGroup, Element>();
604        for (Student student: new TreeSet<Student>(students.keySet())) {
605            Element stEl = studentsEl.addElement("student").addAttribute("id", getId("student", student.getId()));
606            if (iShowNames) {
607                if (student.getAcademicArea() != null)
608                    stEl.addAttribute("area", student.getAcademicArea());
609                if (student.getAcademicClassification() != null)
610                    stEl.addAttribute("classification", student.getAcademicClassification());
611                if (student.getMajor() != null)
612                    stEl.addAttribute("major", student.getMajor());
613                if (student.getCurriculum() != null)
614                    stEl.addAttribute("curriculum", student.getCurriculum());
615            }
616            for (Map.Entry<Long, Double> entry : student.getOfferingsMap().entrySet()) {
617                Long offeringId = entry.getKey();
618                Double weight = entry.getValue();
619                Element offEl = stEl.addElement("offering")
620                        .addAttribute("id", getId("offering", offeringId.toString()));
621                if (weight.doubleValue() != 1.0)
622                    offEl.addAttribute("weight", sStudentWeightFormat.format(weight));
623                Double priority = student.getPriority(offeringId);
624                if (priority != null)
625                    offEl.addAttribute("priority", priority.toString());
626                Long altId = student.getAlternative(offeringId);
627                if (altId != null)
628                    offEl.addAttribute("alternative", altId.toString());
629            }
630            if (iExportStudentSectioning || getModel().nrUnassignedVariables(getAssignment()) == 0 || student.getOfferingsMap().isEmpty()) {
631                List<String> lectures = students.get(student);
632                Collections.sort(lectures);
633                for (String classId : lectures) {
634                    stEl.addElement("class").addAttribute("id", classId);
635                }
636            }
637            Map<Long, Set<Lecture>> canNotEnroll = student.canNotEnrollSections();
638            if (canNotEnroll != null) {
639                for (Set<Lecture> canNotEnrollLects: canNotEnroll.values()) {
640                    for (Iterator<Lecture> i3 = canNotEnrollLects.iterator(); i3.hasNext();) {
641                        stEl.addElement("prohibited-class")
642                                .addAttribute("id", getId("class", (i3.next()).getClassId()));
643                    }
644                }
645            }
646
647            if (student.getCommitedPlacements() != null) {
648                for (Placement placement : student.getCommitedPlacements()) {
649                    stEl.addElement("class").addAttribute("id", getId("class", placement.variable().getClassId()));
650                }
651            }
652            
653            if (student.getInstructor() != null)
654                stEl.addAttribute("instructor", getId("inst", student.getInstructor().getResourceId()));
655            
656            for (StudentGroup group: student.getGroups()) {
657                Element groupEl = groups.get(group);
658                if (groupEl == null) {
659                    groupEl = groupsEl.addElement("group");
660                    groupEl.addAttribute("id", getId("group", group.getId()));
661                    if (group.getWeight() != 1.0)
662                        groupEl.addAttribute("weight", String.valueOf(group.getWeight()));
663                    if (iShowNames && group.getName() != null)
664                        groupEl.addAttribute("name", group.getName());
665                    groups.put(group, groupEl);
666                }
667                groupEl.addElement("student").addAttribute("id", getId("student", student.getId()));
668            }
669        }
670
671        if (getModel().getProperties().getPropertyInt("MPP.GenTimePert", 0) > 0) {
672            Element perturbationsEl = root.addElement("perturbations");
673            int nrChanges = getModel().getProperties().getPropertyInt("MPP.GenTimePert", 0);
674            List<Lecture> lectures = new ArrayList<Lecture>();
675            while (lectures.size() < nrChanges) {
676                Lecture lecture = ToolBox.random(getAssignment().assignedVariables());
677                if (lecture.isCommitted() || lecture.timeLocations().size() <= 1 || lectures.contains(lecture))
678                    continue;
679                Placement placement = getAssignment().getValue(lecture);
680                TimeLocation tl = placement.getTimeLocation();
681                perturbationsEl.addElement("class").addAttribute("id", getId("class", lecture.getClassId()))
682                        .addAttribute("days", sDF[7].format(Long.parseLong(Integer.toBinaryString(tl.getDayCode()))))
683                        .addAttribute("start", String.valueOf(tl.getStartSlot())).addAttribute("length",
684                                String.valueOf(tl.getLength()));
685                lectures.add(lecture);
686            }
687        }
688
689        for (Map.Entry<Long, String> entry : depts.entrySet()) {
690            Long id = entry.getKey();
691            String name = entry.getValue();
692            if (iShowNames) {
693                departmentsEl.addElement("department").addAttribute("id", getId("dept", id.toString())).addAttribute(
694                        "name", name);
695            }
696        }
697        if (departmentsEl.elements().isEmpty())
698            root.remove(departmentsEl);
699    }
700}