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