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