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.log4j.Logger sLogger = org.apache.log4j.Logger.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            roomElements.put(getId("room", roomConstraint.getResourceId()), roomEl);
286            roomEl.addAttribute("capacity", String.valueOf(roomConstraint.getCapacity()));
287            if (roomConstraint.getPosX() != null && roomConstraint.getPosY() != null)
288                roomEl.addAttribute("location", roomConstraint.getPosX() + "," + roomConstraint.getPosY());
289            if (roomConstraint.getIgnoreTooFar())
290                roomEl.addAttribute("ignoreTooFar", "true");
291            if (!roomConstraint.getConstraint())
292                roomEl.addAttribute("fake", "true");
293            if (roomConstraint.getSharingModel() != null) {
294                RoomSharingModel sharingModel = roomConstraint.getSharingModel();
295                Element sharingEl = roomEl.addElement("sharing");
296                sharingEl.addElement("pattern").addAttribute("unit", String.valueOf(sharingModel.getStep())).setText(sharingModel.getPreferences());
297                sharingEl.addElement("freeForAll").addAttribute("value",
298                        String.valueOf(sharingModel.getFreeForAllPrefChar()));
299                sharingEl.addElement("notAvailable").addAttribute("value",
300                        String.valueOf(sharingModel.getNotAvailablePrefChar()));
301                for (Long id: sharingModel.getDepartmentIds()) {
302                    sharingEl.addElement("department")
303                        .addAttribute("value", String.valueOf(sharingModel.getCharacter(id)))
304                        .addAttribute("id", getId("dept", id));
305                }
306            }
307            if (roomConstraint.getType() != null && iShowNames)
308                roomEl.addAttribute("type", roomConstraint.getType().toString());
309            
310            Map<Long, Integer> travelTimes = getModel().getDistanceMetric().getTravelTimes().get(roomConstraint.getResourceId());
311            if (travelTimes != null)
312                for (Map.Entry<Long, Integer> time: travelTimes.entrySet())
313                    roomEl.addElement("travel-time").addAttribute("id", getId("room", time.getKey())).addAttribute("minutes", time.getValue().toString());
314        }
315
316        Element instructorsEl = root.addElement("instructors");
317
318        Element departmentsEl = root.addElement("departments");
319        HashMap<Long, String> depts = new HashMap<Long, String>();
320
321        Element configsEl = (iShowNames ? root.addElement("configurations") : null);
322        HashSet<Configuration> configs = new HashSet<Configuration>();
323
324        Element classesEl = root.addElement("classes");
325        HashMap<Long, Element> classElements = new HashMap<Long, Element>();
326        List<Lecture> vars = new ArrayList<Lecture>(getModel().variables());
327        if (getModel().hasConstantVariables())
328            vars.addAll(getModel().constantVariables());
329        for (Lecture lecture : vars) {
330            Placement placement = getAssignment().getValue(lecture);
331            if (lecture.isCommitted() && placement == null)
332                placement = lecture.getInitialAssignment();
333            Placement initialPlacement = lecture.getInitialAssignment();
334            // if (initialPlacement==null) initialPlacement =
335            // (Placement)lecture.getAssignment();
336            Placement bestPlacement = lecture.getBestAssignment();
337            Element classEl = classesEl.addElement("class").addAttribute("id", getId("class", lecture.getClassId()));
338            classElements.put(lecture.getClassId(), classEl);
339            if (iShowNames && lecture.getNote() != null)
340                classEl.addAttribute("note", lecture.getNote());
341            if (iShowNames && !lecture.isCommitted())
342                classEl.addAttribute("ord", String.valueOf(lecture.getOrd()));
343            if (lecture.getWeight() != 1.0)
344                classEl.addAttribute("weight", String.valueOf(lecture.getWeight()));
345            if (iShowNames && lecture.getSolverGroupId() != null)
346                classEl.addAttribute("solverGroup", getId("solverGroup", lecture.getSolverGroupId()));
347            if (lecture.getParent() == null && lecture.getConfiguration() != null) {
348                if (!iShowNames)
349                    classEl.addAttribute("offering", getId("offering", lecture.getConfiguration().getOfferingId()
350                            .toString()));
351                classEl.addAttribute("config", getId("config", lecture.getConfiguration().getConfigId().toString()));
352                if (iShowNames && configs.add(lecture.getConfiguration())) {
353                    configsEl.addElement("config").addAttribute("id",
354                            getId("config", lecture.getConfiguration().getConfigId().toString())).addAttribute("limit",
355                            String.valueOf(lecture.getConfiguration().getLimit())).addAttribute("offering",
356                            getId("offering", lecture.getConfiguration().getOfferingId().toString()));
357                }
358            }
359            classEl.addAttribute("committed", (lecture.isCommitted() ? "true" : "false"));
360            if (lecture.getParent() != null)
361                classEl.addAttribute("parent", getId("class", lecture.getParent().getClassId()));
362            if (lecture.getSchedulingSubpartId() != null)
363                classEl.addAttribute("subpart", getId("subpart", lecture.getSchedulingSubpartId()));
364            if (iShowNames && lecture.isCommitted() && placement != null && placement.getAssignmentId() != null) {
365                classEl.addAttribute("assignment", getId("assignment", placement.getAssignmentId()));
366            }
367            if (!lecture.isCommitted()) {
368                if (lecture.minClassLimit() == lecture.maxClassLimit()) {
369                    classEl.addAttribute("classLimit", String.valueOf(lecture.maxClassLimit()));
370                } else {
371                    classEl.addAttribute("minClassLimit", String.valueOf(lecture.minClassLimit()));
372                    classEl.addAttribute("maxClassLimit", String.valueOf(lecture.maxClassLimit()));
373                }
374                if (lecture.roomToLimitRatio() != 1.0f)
375                    classEl.addAttribute("roomToLimitRatio", sStudentWeightFormat.format(lecture.roomToLimitRatio()));
376            }
377            if (lecture.getNrRooms() != 1)
378                classEl.addAttribute("nrRooms", String.valueOf(lecture.getNrRooms()));
379            if (lecture.getNrRooms() > 1 && lecture.getMaxRoomCombinations() > 0)
380                classEl.addAttribute("maxRoomCombinations", String.valueOf(lecture.getMaxRoomCombinations()));
381            if (iShowNames)
382                classEl.addAttribute("name", lecture.getName());
383            if (lecture.getDeptSpreadConstraint() != null) {
384                classEl.addAttribute("department", getId("dept", lecture.getDeptSpreadConstraint().getDepartmentId()));
385                depts.put(lecture.getDeptSpreadConstraint().getDepartmentId(), lecture.getDeptSpreadConstraint()
386                        .getName());
387            }
388            if (lecture.getScheduler() != null)
389                classEl.addAttribute("scheduler", getId("dept", lecture.getScheduler()));
390            for (InstructorConstraint ic : lecture.getInstructorConstraints()) {
391                Element instrEl = classEl.addElement("instructor")
392                        .addAttribute("id", getId("inst", ic.getResourceId()));
393                if ((lecture.isCommitted() || iSaveCurrent) && placement != null)
394                    instrEl.addAttribute("solution", "true");
395                if (iSaveInitial && initialPlacement != null)
396                    instrEl.addAttribute("initial", "true");
397                if (iSaveBest && bestPlacement != null && !bestPlacement.equals(placement))
398                    instrEl.addAttribute("best", "true");
399            }
400            for (RoomLocation rl : lecture.roomLocations()) {
401                Element roomLocationEl = classEl.addElement("room");
402                roomLocationEl.addAttribute("id", getId("room", rl.getId()));
403                roomLocationEl.addAttribute("pref", String.valueOf(rl.getPreference()));
404                if ((lecture.isCommitted() || iSaveCurrent) && placement != null
405                        && placement.hasRoomLocation(rl.getId()))
406                    roomLocationEl.addAttribute("solution", "true");
407                if (iSaveInitial && initialPlacement != null && initialPlacement.hasRoomLocation(rl.getId()))
408                    roomLocationEl.addAttribute("initial", "true");
409                if (iSaveBest && bestPlacement != null && !bestPlacement.equals(placement)
410                        && bestPlacement.hasRoomLocation(rl.getId()))
411                    roomLocationEl.addAttribute("best", "true");
412                if (!roomElements.containsKey(getId("room", rl.getId()))) {
413                    // room location without room constraint
414                    Element roomEl = roomsEl.addElement("room").addAttribute("id", getId("room", rl.getId()));
415                    roomEl.addAttribute("constraint", "false");
416                    if (!iConvertIds && rl.getBuildingId() != null)
417                        roomEl.addAttribute("building", getId("bldg", rl.getBuildingId()));
418                    if (iShowNames) {
419                        roomEl.addAttribute("name", rl.getName());
420                    }
421                    roomElements.put(getId("room", rl.getId()), roomEl);
422                    roomEl.addAttribute("capacity", String.valueOf(rl.getRoomSize()));
423                    if (rl.getPosX() != null && rl.getPosY() != null)
424                        roomEl.addAttribute("location", rl.getPosX() + "," + rl.getPosY());
425                    if (rl.getIgnoreTooFar())
426                        roomEl.addAttribute("ignoreTooFar", "true");
427                }
428            }
429            boolean first = true;
430            Set<Long> dp = new HashSet<Long>();
431            for (TimeLocation tl : lecture.timeLocations()) {
432                Element timeLocationEl = classEl.addElement("time");
433                timeLocationEl.addAttribute("days", sDF[7].format(Long.parseLong(Integer
434                        .toBinaryString(tl.getDayCode()))));
435                timeLocationEl.addAttribute("start", String.valueOf(tl.getStartSlot()));
436                timeLocationEl.addAttribute("length", String.valueOf(tl.getLength()));
437                timeLocationEl.addAttribute("breakTime", String.valueOf(tl.getBreakTime()));
438                if (iShowNames) {
439                    timeLocationEl.addAttribute("pref", String.valueOf(tl.getPreference()));
440                    timeLocationEl.addAttribute("npref", String.valueOf(tl.getNormalizedPreference()));
441                } else {
442                    timeLocationEl.addAttribute("pref", String.valueOf(tl.getNormalizedPreference()));
443                }
444                if (!iConvertIds && tl.getTimePatternId() != null)
445                    timeLocationEl.addAttribute("pattern", getId("pat", tl.getTimePatternId()));
446                if (tl.getDatePatternId() != null && dp.add(tl.getDatePatternId())) {
447                    Element dateEl = classEl.addElement("date");
448                    dateEl.addAttribute("id", getId("dpat", String.valueOf(tl.getDatePatternId())));
449                    if (iShowNames)
450                        dateEl.addAttribute("name", tl.getDatePatternName());
451                    dateEl.addAttribute("pattern", bitset2string(tl.getWeekCode()));
452                }
453                if (tl.getDatePatternPreference() != 0)
454                    timeLocationEl.addAttribute("datePref", String.valueOf(tl.getDatePatternPreference()));
455                if (tl.getTimePatternId() == null && first) {
456                    if (iShowNames)
457                        classEl.addAttribute("datePatternName", tl.getDatePatternName());
458                    classEl.addAttribute("dates", bitset2string(tl.getWeekCode()));
459                    first = false;
460                }
461                if (tl.getDatePatternId() != null) {
462                    timeLocationEl.addAttribute("date", getId("dpat", String.valueOf(tl.getDatePatternId())));
463                }
464                if ((lecture.isCommitted() || iSaveCurrent) && placement != null
465                        && placement.getTimeLocation().equals(tl))
466                    timeLocationEl.addAttribute("solution", "true");
467                if (iSaveInitial && initialPlacement != null && initialPlacement.getTimeLocation().equals(tl))
468                    timeLocationEl.addAttribute("initial", "true");
469                if (iSaveBest && bestPlacement != null && !bestPlacement.equals(placement)
470                        && bestPlacement.getTimeLocation().equals(tl))
471                    timeLocationEl.addAttribute("best", "true");
472            }
473        }
474
475        for (InstructorConstraint ic : getModel().getInstructorConstraints()) {
476            if (iShowNames || ic.isIgnoreDistances() || ic instanceof SoftInstructorConstraint) {
477                Element instrEl = instructorsEl.addElement("instructor").addAttribute("id",
478                        getId("inst", ic.getResourceId()));
479                if (iShowNames) {
480                    if (ic.getPuid() != null && ic.getPuid().length() > 0)
481                        instrEl.addAttribute("puid", ic.getPuid());
482                    instrEl.addAttribute("name", ic.getName());
483                    if (ic.getType() != null && iShowNames)
484                        instrEl.addAttribute("type", ic.getType().toString());
485                }
486                if (ic.isIgnoreDistances()) {
487                    instrEl.addAttribute("ignDist", "true");
488                }
489                if (ic instanceof SoftInstructorConstraint) instrEl.addAttribute("soft", "true");
490            }
491            if (ic.getUnavailabilities() != null) {
492                for (Placement placement: ic.getUnavailabilities()) {
493                    Lecture lecture = placement.variable();
494                    Element classEl = classElements.get(lecture.getClassId());
495                    classEl.addElement("instructor").addAttribute("id", getId("inst", ic.getResourceId())).addAttribute("solution", "true");
496                }
497            }
498        }
499        if (instructorsEl.elements().isEmpty())
500            root.remove(instructorsEl);
501
502        Element grConstraintsEl = root.addElement("groupConstraints");
503        for (GroupConstraint gc : getModel().getGroupConstraints()) {
504            Element grEl = grConstraintsEl.addElement("constraint").addAttribute("id",
505                    getId("gr", String.valueOf(gc.getId())));
506            grEl.addAttribute("type", gc.getType().reference());
507            grEl.addAttribute("pref", gc.getPrologPreference());
508            for (Lecture l : gc.variables()) {
509                grEl.addElement("class").addAttribute("id", getId("class", l.getClassId()));
510            }
511        }       
512        for (SpreadConstraint spread : getModel().getSpreadConstraints()) {
513            Element grEl = grConstraintsEl.addElement("constraint").addAttribute("id",
514                    getId("gr", String.valueOf(spread.getId())));
515            grEl.addAttribute("type", "SPREAD");
516            grEl.addAttribute("pref", Constants.sPreferenceRequired);
517            if (iShowNames)
518                grEl.addAttribute("name", spread.getName());
519            for (Lecture l : spread.variables()) {
520                grEl.addElement("class").addAttribute("id", getId("class", l.getClassId()));
521            }
522        }
523        for (Constraint<Lecture, Placement> c : getModel().constraints()) {
524            if (c instanceof MinimizeNumberOfUsedRoomsConstraint) {
525                Element grEl = grConstraintsEl.addElement("constraint").addAttribute("id",
526                        getId("gr", String.valueOf(c.getId())));
527                grEl.addAttribute("type", "MIN_ROOM_USE");
528                grEl.addAttribute("pref", Constants.sPreferenceRequired);
529                for (Lecture l : c.variables()) {
530                    grEl.addElement("class").addAttribute("id", getId("class", l.getClassId()));
531                }
532            }
533            if (c instanceof MinimizeNumberOfUsedGroupsOfTime) {
534                Element grEl = grConstraintsEl.addElement("constraint").addAttribute("id",
535                        getId("gr", String.valueOf(c.getId())));
536                grEl.addAttribute("type", ((MinimizeNumberOfUsedGroupsOfTime) c).getConstraintName());
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 IgnoreStudentConflictsConstraint) {
543                Element grEl = grConstraintsEl.addElement("constraint").addAttribute("id", getId("gr", String.valueOf(c.getId())));
544                grEl.addAttribute("type", IgnoreStudentConflictsConstraint.REFERENCE);
545                grEl.addAttribute("pref", Constants.sPreferenceRequired);
546                for (Lecture l : c.variables()) {
547                    grEl.addElement("class").addAttribute("id", getId("class", l.getClassId()));
548                }
549            }
550        }
551        for (ClassLimitConstraint clc : getModel().getClassLimitConstraints()) {
552            Element grEl = grConstraintsEl.addElement("constraint").addAttribute("id",
553                    getId("gr", String.valueOf(clc.getId())));
554            grEl.addAttribute("type", "CLASS_LIMIT");
555            grEl.addAttribute("pref", Constants.sPreferenceRequired);
556            if (clc.getParentLecture() != null) {
557                grEl.addElement("parentClass").addAttribute("id", getId("class", clc.getParentLecture().getClassId()));
558            } else
559                grEl.addAttribute("courseLimit", String.valueOf(clc.classLimit() - clc.getClassLimitDelta()));
560            if (clc.getClassLimitDelta() != 0)
561                grEl.addAttribute("delta", String.valueOf(clc.getClassLimitDelta()));
562            if (iShowNames)
563                grEl.addAttribute("name", clc.getName());
564            for (Lecture l : clc.variables()) {
565                grEl.addElement("class").addAttribute("id", getId("class", l.getClassId()));
566            }
567        }
568        for (FlexibleConstraint gc : getModel().getFlexibleConstraints()) {
569            Element flEl = grConstraintsEl.addElement("constraint").addAttribute("id",
570                    getId("gr", String.valueOf(gc.getId())));
571            flEl.addAttribute("reference", gc.getReference());
572            flEl.addAttribute("owner", gc.getOwner());
573            flEl.addAttribute("pref", gc.getPrologPreference());  
574            flEl.addAttribute("type", gc.getType().toString());  
575            for (Lecture l : gc.variables()) {
576                flEl.addElement("class").addAttribute("id", getId("class", l.getClassId()));
577            }
578        }
579
580        HashMap<Student, List<String>> students = new HashMap<Student, List<String>>();
581        for (Lecture lecture : vars) {
582            for (Student student : lecture.students()) {
583                List<String> enrls = students.get(student);
584                if (enrls == null) {
585                    enrls = new ArrayList<String>();
586                    students.put(student, enrls);
587                }
588                enrls.add(getId("class", lecture.getClassId()));
589            }
590        }
591
592        Element studentsEl = root.addElement("students");
593        Element groupsEl = root.addElement("groups");
594        Map<StudentGroup, Element> groups = new HashMap<StudentGroup, Element>();
595        for (Student student: new TreeSet<Student>(students.keySet())) {
596            Element stEl = studentsEl.addElement("student").addAttribute("id", getId("student", student.getId()));
597            if (iShowNames) {
598                if (student.getAcademicArea() != null)
599                    stEl.addAttribute("area", student.getAcademicArea());
600                if (student.getAcademicClassification() != null)
601                    stEl.addAttribute("classification", student.getAcademicClassification());
602                if (student.getMajor() != null)
603                    stEl.addAttribute("major", student.getMajor());
604                if (student.getCurriculum() != null)
605                    stEl.addAttribute("curriculum", student.getCurriculum());
606            }
607            for (Map.Entry<Long, Double> entry : student.getOfferingsMap().entrySet()) {
608                Long offeringId = entry.getKey();
609                Double weight = entry.getValue();
610                Element offEl = stEl.addElement("offering")
611                        .addAttribute("id", getId("offering", offeringId.toString()));
612                if (weight.doubleValue() != 1.0)
613                    offEl.addAttribute("weight", sStudentWeightFormat.format(weight));
614                Double priority = student.getPriority(offeringId);
615                if (priority != null)
616                    offEl.addAttribute("priority", priority.toString());
617                Long altId = student.getAlternative(offeringId);
618                if (altId != null)
619                    offEl.addAttribute("alternative", altId.toString());
620            }
621            if (iExportStudentSectioning || getModel().nrUnassignedVariables(getAssignment()) == 0 || student.getOfferingsMap().isEmpty()) {
622                List<String> lectures = students.get(student);
623                Collections.sort(lectures);
624                for (String classId : lectures) {
625                    stEl.addElement("class").addAttribute("id", classId);
626                }
627            }
628            Map<Long, Set<Lecture>> canNotEnroll = student.canNotEnrollSections();
629            if (canNotEnroll != null) {
630                for (Set<Lecture> canNotEnrollLects: canNotEnroll.values()) {
631                    for (Iterator<Lecture> i3 = canNotEnrollLects.iterator(); i3.hasNext();) {
632                        stEl.addElement("prohibited-class")
633                                .addAttribute("id", getId("class", (i3.next()).getClassId()));
634                    }
635                }
636            }
637
638            if (student.getCommitedPlacements() != null) {
639                for (Placement placement : student.getCommitedPlacements()) {
640                    stEl.addElement("class").addAttribute("id", getId("class", placement.variable().getClassId()));
641                }
642            }
643            
644            if (student.getInstructor() != null)
645                stEl.addAttribute("instructor", getId("inst", student.getInstructor().getResourceId()));
646            
647            for (StudentGroup group: student.getGroups()) {
648                Element groupEl = groups.get(group);
649                if (groupEl == null) {
650                    groupEl = groupsEl.addElement("group");
651                    groupEl.addAttribute("id", getId("group", group.getId()));
652                    if (group.getWeight() != 1.0)
653                        groupEl.addAttribute("weight", String.valueOf(group.getWeight()));
654                    if (iShowNames && group.getName() != null)
655                        groupEl.addAttribute("name", group.getName());
656                    groups.put(group, groupEl);
657                }
658                groupEl.addElement("student").addAttribute("id", getId("student", student.getId()));
659            }
660        }
661
662        if (getModel().getProperties().getPropertyInt("MPP.GenTimePert", 0) > 0) {
663            Element perturbationsEl = root.addElement("perturbations");
664            int nrChanges = getModel().getProperties().getPropertyInt("MPP.GenTimePert", 0);
665            List<Lecture> lectures = new ArrayList<Lecture>();
666            while (lectures.size() < nrChanges) {
667                Lecture lecture = ToolBox.random(getAssignment().assignedVariables());
668                if (lecture.isCommitted() || lecture.timeLocations().size() <= 1 || lectures.contains(lecture))
669                    continue;
670                Placement placement = getAssignment().getValue(lecture);
671                TimeLocation tl = placement.getTimeLocation();
672                perturbationsEl.addElement("class").addAttribute("id", getId("class", lecture.getClassId()))
673                        .addAttribute("days", sDF[7].format(Long.parseLong(Integer.toBinaryString(tl.getDayCode()))))
674                        .addAttribute("start", String.valueOf(tl.getStartSlot())).addAttribute("length",
675                                String.valueOf(tl.getLength()));
676                lectures.add(lecture);
677            }
678        }
679
680        for (Map.Entry<Long, String> entry : depts.entrySet()) {
681            Long id = entry.getKey();
682            String name = entry.getValue();
683            if (iShowNames) {
684                departmentsEl.addElement("department").addAttribute("id", getId("dept", id.toString())).addAttribute(
685                        "name", name);
686            }
687        }
688        if (departmentsEl.elements().isEmpty())
689            root.remove(departmentsEl);
690    }
691}