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