Search in sources :

Example 1 with TimeLocation

use of org.cpsolver.coursett.model.TimeLocation in project cpsolver by UniTime.

the class InstructorSchedulingModel method load.

/**
     * Load the problem (and its solution) from an XML format
     * @param document XML document
     * @param assignment current assignment
     * @return true, if the problem was successfully loaded in
     */
public boolean load(Document document, Assignment<TeachingRequest.Variable, TeachingAssignment> assignment) {
    boolean loadInitial = getProperties().getPropertyBoolean("Xml.LoadInitial", true);
    boolean loadBest = getProperties().getPropertyBoolean("Xml.LoadBest", true);
    boolean loadSolution = getProperties().getPropertyBoolean("Xml.LoadSolution", true);
    String defaultBtb = getProperties().getProperty("Defaults.BackToBack", "0");
    String defaultSameDays = getProperties().getProperty("Defaults.SameDays", "0");
    String defaultSameRoom = getProperties().getProperty("Defaults.SameRoom", "0");
    String defaultConjunctive = getProperties().getProperty("Defaults.Conjunctive", "false");
    String defaultRequired = getProperties().getProperty("Defaults.Required", "false");
    String defaultSameCourse = getProperties().getProperty("Defaults.SameCourse", "R");
    String defaultSameCommon = getProperties().getProperty("Defaults.SameCommon", "R");
    Element root = document.getRootElement();
    if (!"instructor-schedule".equals(root.getName()))
        return false;
    Map<String, Attribute.Type> types = new HashMap<String, Attribute.Type>();
    Map<Long, Attribute> attributes = new HashMap<Long, Attribute>();
    Map<Long, Long> parents = new HashMap<Long, Long>();
    if (root.element("attributes") != null) {
        for (Iterator<?> i = root.element("attributes").elementIterator("type"); i.hasNext(); ) {
            Element typeEl = (Element) i.next();
            Attribute.Type type = new Attribute.Type(Long.parseLong(typeEl.attributeValue("id")), typeEl.attributeValue("name"), "true".equalsIgnoreCase(typeEl.attributeValue("conjunctive", defaultConjunctive)), "true".equalsIgnoreCase(typeEl.attributeValue("required", defaultRequired)));
            addAttributeType(type);
            if (type.getTypeName() != null)
                types.put(type.getTypeName(), type);
            for (Iterator<?> j = typeEl.elementIterator("attribute"); j.hasNext(); ) {
                Element attributeEl = (Element) j.next();
                Attribute attribute = new Attribute(Long.parseLong(attributeEl.attributeValue("id")), attributeEl.attributeValue("name"), type);
                attributes.put(attribute.getAttributeId(), attribute);
                if (attributeEl.attributeValue("parent") != null)
                    parents.put(attribute.getAttributeId(), Long.parseLong(attributeEl.attributeValue("parent")));
            }
        }
    }
    Map<Long, Course> courses = new HashMap<Long, Course>();
    if (root.element("courses") != null) {
        for (Iterator<?> i = root.element("courses").elementIterator("course"); i.hasNext(); ) {
            Element courseEl = (Element) i.next();
            Course course = new Course(Long.parseLong(courseEl.attributeValue("id")), courseEl.attributeValue("name"));
            courses.put(course.getCourseId(), course);
        }
    }
    Map<Long, Instructor> instructors = new HashMap<Long, Instructor>();
    for (Iterator<?> i = root.element("instructors").elementIterator("instructor"); i.hasNext(); ) {
        Element instructorEl = (Element) i.next();
        Instructor instructor = new Instructor(Long.parseLong(instructorEl.attributeValue("id")), instructorEl.attributeValue("externalId"), instructorEl.attributeValue("name"), string2preference(instructorEl.attributeValue("preference")), Float.parseFloat(instructorEl.attributeValue("maxLoad", "0")));
        instructor.setBackToBackPreference(Integer.valueOf(instructorEl.attributeValue("btb", defaultBtb)));
        instructor.setSameDaysPreference(Integer.valueOf(instructorEl.attributeValue("same-days", defaultSameDays)));
        instructor.setSameRoomPreference(Integer.valueOf(instructorEl.attributeValue("same-room", defaultSameRoom)));
        for (Iterator<?> j = instructorEl.elementIterator("attribute"); j.hasNext(); ) {
            Element f = (Element) j.next();
            Long attributeId = Long.valueOf(f.attributeValue("id"));
            Attribute attribute = attributes.get(attributeId);
            if (attribute == null) {
                Attribute.Type type = types.get(f.attributeValue("type"));
                if (type == null) {
                    type = new Attribute.Type(types.size(), f.attributeValue("type"), "true".equalsIgnoreCase(f.attributeValue("conjunctive", defaultConjunctive)), "true".equalsIgnoreCase(f.attributeValue("required", defaultRequired)));
                    types.put(type.getTypeName(), type);
                }
                attribute = new Attribute(attributeId, f.attributeValue("name"), type);
                attributes.put(attributeId, attribute);
                if (f.attributeValue("parent") != null)
                    parents.put(attribute.getAttributeId(), Long.parseLong(f.attributeValue("parent")));
            }
            instructor.addAttribute(attribute);
        }
        for (Iterator<?> j = instructorEl.elementIterator("time"); j.hasNext(); ) {
            Element f = (Element) j.next();
            Element classEl = f.element("section");
            Element courseEl = f.element("course");
            TimeLocation time = null;
            if (classEl != null) {
                time = new EnrolledClass(courseEl == null || courseEl.attributeValue("id") == null ? null : Long.valueOf(courseEl.attributeValue("id")), classEl.attributeValue("id") == null ? null : Long.valueOf(classEl.attributeValue("id")), courseEl == null ? null : courseEl.attributeValue("name"), classEl.attributeValue("type"), classEl.attributeValue("name"), classEl.attributeValue("externalId"), Integer.parseInt(f.attributeValue("days"), 2), Integer.parseInt(f.attributeValue("start")), Integer.parseInt(f.attributeValue("length")), f.attributeValue("datePattern") == null ? null : Long.valueOf(f.attributeValue("datePattern")), f.attributeValue("datePatternName", ""), createBitSet(f.attributeValue("dates")), Integer.parseInt(f.attributeValue("breakTime", "0")), classEl.attributeValue("room"), "instructor".equalsIgnoreCase(classEl.attributeValue("role", "instructor")));
            } else {
                time = new TimeLocation(Integer.parseInt(f.attributeValue("days"), 2), Integer.parseInt(f.attributeValue("start")), Integer.parseInt(f.attributeValue("length")), 0, 0, f.attributeValue("datePattern") == null ? null : Long.valueOf(f.attributeValue("datePattern")), f.attributeValue("datePatternName", ""), createBitSet(f.attributeValue("dates")), Integer.parseInt(f.attributeValue("breakTime", "0")));
            }
            if (f.attributeValue("pattern") != null)
                time.setTimePatternId(Long.valueOf(f.attributeValue("pattern")));
            instructor.addTimePreference(new Preference<TimeLocation>(time, string2preference(f.attributeValue("preference"))));
        }
        for (Iterator<?> j = instructorEl.elementIterator("course"); j.hasNext(); ) {
            Element f = (Element) j.next();
            instructor.addCoursePreference(new Preference<Course>(new Course(Long.parseLong(f.attributeValue("id")), f.attributeValue("name")), string2preference(f.attributeValue("preference"))));
        }
        addInstructor(instructor);
        instructors.put(instructor.getInstructorId(), instructor);
    }
    Map<Long, TeachingRequest> requests = new HashMap<Long, TeachingRequest>();
    Map<TeachingRequest, Map<Integer, Instructor>> current = new HashMap<TeachingRequest, Map<Integer, Instructor>>();
    Map<TeachingRequest, Map<Integer, Instructor>> best = new HashMap<TeachingRequest, Map<Integer, Instructor>>();
    Map<TeachingRequest, Map<Integer, Instructor>> initial = new HashMap<TeachingRequest, Map<Integer, Instructor>>();
    for (Iterator<?> i = root.element("teaching-requests").elementIterator("request"); i.hasNext(); ) {
        Element requestEl = (Element) i.next();
        Element courseEl = requestEl.element("course");
        Course course = null;
        if (courseEl != null) {
            Long courseId = Long.valueOf(courseEl.attributeValue("id"));
            course = courses.get(courseId);
            if (course == null) {
                course = new Course(courseId, courseEl.attributeValue("name"));
            }
        } else {
            course = courses.get(Long.valueOf(requestEl.attributeValue("course")));
        }
        List<Section> sections = new ArrayList<Section>();
        for (Iterator<?> j = requestEl.elementIterator("section"); j.hasNext(); ) {
            Element f = (Element) j.next();
            TimeLocation time = null;
            Element timeEl = f.element("time");
            if (timeEl != null) {
                time = new TimeLocation(Integer.parseInt(timeEl.attributeValue("days"), 2), Integer.parseInt(timeEl.attributeValue("start")), Integer.parseInt(timeEl.attributeValue("length")), 0, 0, timeEl.attributeValue("datePattern") == null ? null : Long.valueOf(timeEl.attributeValue("datePattern")), timeEl.attributeValue("datePatternName", ""), createBitSet(timeEl.attributeValue("dates")), Integer.parseInt(timeEl.attributeValue("breakTime", "0")));
                if (timeEl.attributeValue("pattern") != null)
                    time.setTimePatternId(Long.valueOf(timeEl.attributeValue("pattern")));
            }
            Section section = new Section(Long.valueOf(f.attributeValue("id")), f.attributeValue("externalId"), f.attributeValue("type"), f.attributeValue("name"), time, f.attributeValue("room"), "true".equalsIgnoreCase(f.attributeValue("canOverlap", "false")), "true".equalsIgnoreCase(f.attributeValue("common", "false")));
            sections.add(section);
        }
        TeachingRequest request = new TeachingRequest(Long.parseLong(requestEl.attributeValue("id")), Integer.parseInt(requestEl.attributeValue("nrInstructors", "1")), course, Float.valueOf(requestEl.attributeValue("load", "0")), sections, Constants.preference2preferenceLevel(requestEl.attributeValue("sameCourse", defaultSameCourse)), Constants.preference2preferenceLevel(requestEl.attributeValue("sameCommon", defaultSameCommon)));
        requests.put(request.getRequestId(), request);
        for (Iterator<?> j = requestEl.elementIterator("attribute"); j.hasNext(); ) {
            Element f = (Element) j.next();
            Long attributeId = Long.valueOf(f.attributeValue("id"));
            Attribute attribute = attributes.get(attributeId);
            if (attribute == null) {
                Attribute.Type type = types.get(f.attributeValue("type"));
                if (type == null) {
                    type = new Attribute.Type(types.size(), f.attributeValue("type"), "true".equalsIgnoreCase(f.attributeValue("conjunctive", defaultConjunctive)), "true".equalsIgnoreCase(f.attributeValue("required", defaultRequired)));
                    types.put(type.getTypeName(), type);
                }
                attribute = new Attribute(attributeId, f.attributeValue("name"), type);
                attributes.put(attributeId, attribute);
                if (f.attributeValue("parent") != null)
                    parents.put(attribute.getAttributeId(), Long.parseLong(f.attributeValue("parent")));
            }
            request.addAttributePreference(new Preference<Attribute>(attribute, string2preference(f.attributeValue("preference"))));
        }
        for (Iterator<?> j = requestEl.elementIterator("instructor"); j.hasNext(); ) {
            Element f = (Element) j.next();
            Long instructorId = Long.valueOf(f.attributeValue("id"));
            Instructor instructor = instructors.get(instructorId);
            if (instructor != null)
                request.addInstructorPreference(new Preference<Instructor>(instructor, string2preference(f.attributeValue("preference"))));
        }
        if (loadBest) {
            for (Iterator<?> j = requestEl.elementIterator("best-instructor"); j.hasNext(); ) {
                Element f = (Element) j.next();
                Map<Integer, Instructor> idx2inst = best.get(request);
                if (idx2inst == null) {
                    idx2inst = new HashMap<Integer, Instructor>();
                    best.put(request, idx2inst);
                }
                int index = 1 + Integer.parseInt(f.attributeValue("index", String.valueOf(idx2inst.size())));
                Instructor instructor = instructors.get(Long.valueOf(f.attributeValue("id")));
                if (instructor != null)
                    idx2inst.put(index, instructor);
            }
        }
        if (loadInitial) {
            for (Iterator<?> j = requestEl.elementIterator("initial-instructor"); j.hasNext(); ) {
                Element f = (Element) j.next();
                Map<Integer, Instructor> idx2inst = initial.get(request);
                if (idx2inst == null) {
                    idx2inst = new HashMap<Integer, Instructor>();
                    initial.put(request, idx2inst);
                }
                int index = 1 + Integer.parseInt(f.attributeValue("index", String.valueOf(idx2inst.size())));
                Instructor instructor = instructors.get(Long.valueOf(f.attributeValue("id")));
                if (instructor != null)
                    idx2inst.put(index, instructor);
            }
        }
        if (loadSolution) {
            for (Iterator<?> j = requestEl.elementIterator("assigned-instructor"); j.hasNext(); ) {
                Element f = (Element) j.next();
                Map<Integer, Instructor> idx2inst = current.get(request);
                if (idx2inst == null) {
                    idx2inst = new HashMap<Integer, Instructor>();
                    current.put(request, idx2inst);
                }
                int index = Integer.parseInt(f.attributeValue("index", String.valueOf(idx2inst.size())));
                Instructor instructor = instructors.get(Long.valueOf(f.attributeValue("id")));
                if (instructor != null)
                    idx2inst.put(index, instructor);
            }
        }
        addRequest(request);
    }
    if (root.element("constraints") != null) {
        for (Iterator<?> i = root.element("constraints").elementIterator(); i.hasNext(); ) {
            Element constraintEl = (Element) i.next();
            Constraint<TeachingRequest.Variable, TeachingAssignment> constraint = null;
            if ("same-link".equals(constraintEl.getName())) {
                constraint = new SameLinkConstraint((constraintEl.attributeValue("id") == null ? null : Long.valueOf(constraintEl.attributeValue("id"))), constraintEl.attributeValue("name"), constraintEl.attributeValue("preference"));
            } else if ("same-instructor".equals(constraintEl.getName())) {
                constraint = new SameInstructorConstraint((constraintEl.attributeValue("id") == null ? null : Long.valueOf(constraintEl.attributeValue("id"))), constraintEl.attributeValue("name"), constraintEl.attributeValue("preference"));
            }
            if (constraint != null) {
                for (Iterator<?> j = constraintEl.elementIterator("request"); j.hasNext(); ) {
                    Element f = (Element) j.next();
                    TeachingRequest request = requests.get(Long.valueOf(f.attributeValue("id")));
                    if (request != null) {
                        int index = Integer.valueOf(f.attributeValue("index", "0"));
                        if (index >= 0 && index < request.getNrInstructors())
                            constraint.addVariable(request.getVariables()[index]);
                    }
                }
                addConstraint(constraint);
            }
        }
    }
    for (Map.Entry<Long, Long> e : parents.entrySet()) attributes.get(e.getKey()).setParentAttribute(attributes.get(e.getValue()));
    for (Map.Entry<TeachingRequest, Map<Integer, Instructor>> e1 : best.entrySet()) for (Map.Entry<Integer, Instructor> e2 : e1.getValue().entrySet()) if (e2.getKey() >= 0 && e2.getKey() < e1.getKey().getNrInstructors()) {
        TeachingRequest.Variable variable = e1.getKey().getVariables()[e2.getKey()];
        variable.setBestAssignment(new TeachingAssignment(variable, e2.getValue()), 0l);
    }
    for (Map.Entry<TeachingRequest, Map<Integer, Instructor>> e1 : initial.entrySet()) for (Map.Entry<Integer, Instructor> e2 : e1.getValue().entrySet()) if (e2.getKey() >= 0 && e2.getKey() < e1.getKey().getNrInstructors()) {
        TeachingRequest.Variable variable = e1.getKey().getVariables()[e2.getKey()];
        variable.setInitialAssignment(new TeachingAssignment(variable, e2.getValue()));
    }
    if (!current.isEmpty()) {
        for (Map.Entry<TeachingRequest, Map<Integer, Instructor>> e1 : current.entrySet()) for (Map.Entry<Integer, Instructor> e2 : e1.getValue().entrySet()) if (e2.getKey() >= 0 && e2.getKey() < e1.getKey().getNrInstructors()) {
            TeachingRequest.Variable variable = e1.getKey().getVariables()[e2.getKey()];
            TeachingAssignment ta = new TeachingAssignment(variable, e2.getValue());
            Set<TeachingAssignment> conf = conflictValues(assignment, ta);
            if (conf.isEmpty()) {
                assignment.assign(0, ta);
            } else {
                sLog.error("Unable to assign " + ta.getName() + " to " + variable.getName());
                sLog.error("Conflicts:" + ToolBox.dict2string(conflictConstraints(assignment, ta), 2));
            }
        }
    }
    return true;
}
Also used : TimeLocation(org.cpsolver.coursett.model.TimeLocation) HashMap(java.util.HashMap) Element(org.dom4j.Element) SameInstructor(org.cpsolver.instructor.criteria.SameInstructor) OriginalInstructor(org.cpsolver.instructor.criteria.OriginalInstructor) ArrayList(java.util.ArrayList) SameLinkConstraint(org.cpsolver.instructor.constraints.SameLinkConstraint) SameCourse(org.cpsolver.instructor.criteria.SameCourse) SameInstructorConstraint(org.cpsolver.instructor.constraints.SameInstructorConstraint) InstructorConstraint(org.cpsolver.instructor.constraints.InstructorConstraint) SameLinkConstraint(org.cpsolver.instructor.constraints.SameLinkConstraint) Constraint(org.cpsolver.ifs.model.Constraint) SameInstructorConstraint(org.cpsolver.instructor.constraints.SameInstructorConstraint) HashMap(java.util.HashMap) Map(java.util.Map)

Example 2 with TimeLocation

use of org.cpsolver.coursett.model.TimeLocation in project cpsolver by UniTime.

the class InstructorSchedulingModel method save.

/**
     * Store the problem (together with its solution) in an XML format
     * @param assignment current assignment
     * @return XML document with the problem
     */
public Document save(Assignment<TeachingRequest.Variable, TeachingAssignment> assignment) {
    DecimalFormat sDF7 = new DecimalFormat("0000000");
    boolean saveInitial = getProperties().getPropertyBoolean("Xml.SaveInitial", false);
    boolean saveBest = getProperties().getPropertyBoolean("Xml.SaveBest", false);
    boolean saveSolution = getProperties().getPropertyBoolean("Xml.SaveSolution", true);
    Document document = DocumentHelper.createDocument();
    if (assignment != null && assignment.nrAssignedVariables() > 0) {
        StringBuffer comments = new StringBuffer("Solution Info:\n");
        Map<String, String> solutionInfo = (getProperties().getPropertyBoolean("Xml.ExtendedInfo", true) ? getExtendedInfo(assignment) : getInfo(assignment));
        for (String key : new TreeSet<String>(solutionInfo.keySet())) {
            String value = solutionInfo.get(key);
            comments.append("    " + key + ": " + value + "\n");
        }
        document.addComment(comments.toString());
    }
    Element root = document.addElement("instructor-schedule");
    root.addAttribute("version", "1.0");
    root.addAttribute("created", String.valueOf(new Date()));
    Element typesEl = root.addElement("attributes");
    for (Attribute.Type type : getAttributeTypes()) {
        Element typeEl = typesEl.addElement("type");
        if (type.getTypeId() != null)
            typeEl.addAttribute("id", String.valueOf(type.getTypeId()));
        typeEl.addAttribute("name", type.getTypeName());
        typeEl.addAttribute("conjunctive", type.isConjunctive() ? "true" : "false");
        typeEl.addAttribute("required", type.isRequired() ? "true" : "false");
        Set<Attribute> attributes = new HashSet<Attribute>();
        for (TeachingRequest request : getRequests()) {
            for (Preference<Attribute> pref : request.getAttributePreferences()) {
                Attribute attribute = pref.getTarget();
                if (type.equals(attribute.getType()) && attributes.add(attribute)) {
                    Element attributeEl = typeEl.addElement("attribute");
                    if (attribute.getAttributeId() != null)
                        attributeEl.addAttribute("id", String.valueOf(attribute.getAttributeId()));
                    attributeEl.addAttribute("name", attribute.getAttributeName());
                    if (attribute.getParentAttribute() != null && attribute.getParentAttribute().getAttributeId() != null)
                        attributeEl.addAttribute("parent", String.valueOf(attribute.getParentAttribute().getAttributeId()));
                }
            }
            for (Instructor instructor : getInstructors()) {
                for (Attribute attribute : instructor.getAttributes()) {
                    if (type.equals(attribute.getType()) && attributes.add(attribute)) {
                        Element attributeEl = typeEl.addElement("attribute");
                        if (attribute.getAttributeId() != null)
                            attributeEl.addAttribute("id", String.valueOf(attribute.getAttributeId()));
                        attributeEl.addAttribute("name", attribute.getAttributeName());
                        if (attribute.getParentAttribute() != null && attribute.getParentAttribute().getAttributeId() != null)
                            attributeEl.addAttribute("parent", String.valueOf(attribute.getParentAttribute().getAttributeId()));
                    }
                }
            }
        }
    }
    Element requestsEl = root.addElement("teaching-requests");
    for (TeachingRequest request : getRequests()) {
        Element requestEl = requestsEl.addElement("request");
        requestEl.addAttribute("id", String.valueOf(request.getRequestId()));
        if (request.getNrInstructors() != 1)
            requestEl.addAttribute("nrInstructors", String.valueOf(request.getNrInstructors()));
        Course course = request.getCourse();
        Element courseEl = requestEl.addElement("course");
        if (course.getCourseId() != null)
            courseEl.addAttribute("id", String.valueOf(course.getCourseId()));
        if (course.getCourseName() != null)
            courseEl.addAttribute("name", String.valueOf(course.getCourseName()));
        for (Section section : request.getSections()) {
            Element sectionEl = requestEl.addElement("section");
            sectionEl.addAttribute("id", String.valueOf(section.getSectionId()));
            if (section.getExternalId() != null && !section.getExternalId().isEmpty())
                sectionEl.addAttribute("externalId", section.getExternalId());
            if (section.getSectionType() != null && !section.getSectionType().isEmpty())
                sectionEl.addAttribute("type", section.getSectionType());
            if (section.getSectionName() != null && !section.getSectionName().isEmpty())
                sectionEl.addAttribute("name", section.getSectionName());
            if (section.hasTime()) {
                TimeLocation tl = section.getTime();
                Element timeEl = sectionEl.addElement("time");
                timeEl.addAttribute("days", sDF7.format(Long.parseLong(Integer.toBinaryString(tl.getDayCode()))));
                timeEl.addAttribute("start", String.valueOf(tl.getStartSlot()));
                timeEl.addAttribute("length", String.valueOf(tl.getLength()));
                if (tl.getBreakTime() != 0)
                    timeEl.addAttribute("breakTime", String.valueOf(tl.getBreakTime()));
                if (tl.getTimePatternId() != null)
                    timeEl.addAttribute("pattern", tl.getTimePatternId().toString());
                if (tl.getDatePatternId() != null)
                    timeEl.addAttribute("datePattern", tl.getDatePatternId().toString());
                if (tl.getDatePatternName() != null && !tl.getDatePatternName().isEmpty())
                    timeEl.addAttribute("datePatternName", tl.getDatePatternName());
                if (tl.getWeekCode() != null)
                    timeEl.addAttribute("dates", bitset2string(tl.getWeekCode()));
                timeEl.setText(tl.getLongName(false));
            }
            if (section.hasRoom())
                sectionEl.addAttribute("room", section.getRoom());
            if (section.isAllowOverlap())
                sectionEl.addAttribute("canOverlap", "true");
            if (section.isCommon())
                sectionEl.addAttribute("common", "true");
        }
        requestEl.addAttribute("load", sDoubleFormat.format(request.getLoad()));
        requestEl.addAttribute("sameCourse", Constants.preferenceLevel2preference(request.getSameCoursePreference()));
        requestEl.addAttribute("sameCommon", Constants.preferenceLevel2preference(request.getSameCommonPreference()));
        for (Preference<Attribute> pref : request.getAttributePreferences()) {
            Element attributeEl = requestEl.addElement("attribute");
            if (pref.getTarget().getAttributeId() != null)
                attributeEl.addAttribute("id", String.valueOf(pref.getTarget().getAttributeId()));
            attributeEl.addAttribute("name", pref.getTarget().getAttributeName());
            attributeEl.addAttribute("type", pref.getTarget().getType().getTypeName());
            attributeEl.addAttribute("preference", (pref.isRequired() ? "R" : pref.isProhibited() ? "P" : String.valueOf(pref.getPreference())));
            if (pref.getTarget().getParentAttribute() != null && pref.getTarget().getParentAttribute().getAttributeId() != null)
                attributeEl.addAttribute("parent", String.valueOf(pref.getTarget().getParentAttribute().getAttributeId()));
        }
        for (Preference<Instructor> pref : request.getInstructorPreferences()) {
            Element instructorEl = requestEl.addElement("instructor");
            instructorEl.addAttribute("id", String.valueOf(pref.getTarget().getInstructorId()));
            if (pref.getTarget().hasExternalId())
                instructorEl.addAttribute("externalId", pref.getTarget().getExternalId());
            if (pref.getTarget().hasName())
                instructorEl.addAttribute("name", pref.getTarget().getName());
            instructorEl.addAttribute("preference", (pref.isRequired() ? "R" : pref.isProhibited() ? "P" : String.valueOf(pref.getPreference())));
        }
        if (saveBest)
            for (TeachingRequest.Variable variable : request.getVariables()) {
                if (variable.getBestAssignment() != null) {
                    Instructor instructor = variable.getBestAssignment().getInstructor();
                    Element instructorEl = requestEl.addElement("best-instructor");
                    instructorEl.addAttribute("id", String.valueOf(instructor.getInstructorId()));
                    if (request.getNrInstructors() != 1)
                        instructorEl.addAttribute("index", String.valueOf(variable.getInstructorIndex()));
                    if (instructor.hasExternalId())
                        instructorEl.addAttribute("externalId", instructor.getExternalId());
                    if (instructor.hasName())
                        instructorEl.addAttribute("name", instructor.getName());
                }
            }
        if (saveInitial)
            for (TeachingRequest.Variable variable : request.getVariables()) {
                if (variable.getInitialAssignment() != null) {
                    Instructor instructor = variable.getInitialAssignment().getInstructor();
                    Element instructorEl = requestEl.addElement("initial-instructor");
                    instructorEl.addAttribute("id", String.valueOf(instructor.getInstructorId()));
                    if (request.getNrInstructors() != 1)
                        instructorEl.addAttribute("index", String.valueOf(variable.getInstructorIndex()));
                    if (instructor.hasExternalId())
                        instructorEl.addAttribute("externalId", instructor.getExternalId());
                    if (instructor.hasName())
                        instructorEl.addAttribute("name", instructor.getName());
                }
            }
        if (saveSolution)
            for (TeachingRequest.Variable variable : request.getVariables()) {
                TeachingAssignment ta = assignment.getValue(variable);
                if (ta != null) {
                    Instructor instructor = ta.getInstructor();
                    Element instructorEl = requestEl.addElement("assigned-instructor");
                    instructorEl.addAttribute("id", String.valueOf(instructor.getInstructorId()));
                    if (request.getNrInstructors() != 1)
                        instructorEl.addAttribute("index", String.valueOf(variable.getInstructorIndex()));
                    if (instructor.hasExternalId())
                        instructorEl.addAttribute("externalId", instructor.getExternalId());
                    if (instructor.hasName())
                        instructorEl.addAttribute("name", instructor.getName());
                }
            }
    }
    Element instructorsEl = root.addElement("instructors");
    for (Instructor instructor : getInstructors()) {
        Element instructorEl = instructorsEl.addElement("instructor");
        instructorEl.addAttribute("id", String.valueOf(instructor.getInstructorId()));
        if (instructor.hasExternalId())
            instructorEl.addAttribute("externalId", instructor.getExternalId());
        if (instructor.hasName())
            instructorEl.addAttribute("name", instructor.getName());
        if (instructor.getPreference() != 0)
            instructorEl.addAttribute("preference", String.valueOf(instructor.getPreference()));
        if (instructor.getBackToBackPreference() != 0)
            instructorEl.addAttribute("btb", String.valueOf(instructor.getBackToBackPreference()));
        if (instructor.getSameDaysPreference() != 0)
            instructorEl.addAttribute("same-days", String.valueOf(instructor.getSameDaysPreference()));
        if (instructor.getSameRoomPreference() != 0)
            instructorEl.addAttribute("same-room", String.valueOf(instructor.getSameRoomPreference()));
        for (Attribute attribute : instructor.getAttributes()) {
            Element attributeEl = instructorEl.addElement("attribute");
            if (attribute.getAttributeId() != null)
                attributeEl.addAttribute("id", String.valueOf(attribute.getAttributeId()));
            attributeEl.addAttribute("name", attribute.getAttributeName());
            attributeEl.addAttribute("type", attribute.getType().getTypeName());
            if (attribute.getParentAttribute() != null && attribute.getParentAttribute().getAttributeId() != null)
                attributeEl.addAttribute("parent", String.valueOf(attribute.getParentAttribute().getAttributeId()));
        }
        instructorEl.addAttribute("maxLoad", sDoubleFormat.format(instructor.getMaxLoad()));
        for (Preference<TimeLocation> tp : instructor.getTimePreferences()) {
            Element timeEl = instructorEl.addElement("time");
            TimeLocation tl = tp.getTarget();
            timeEl.addAttribute("days", sDF7.format(Long.parseLong(Integer.toBinaryString(tl.getDayCode()))));
            timeEl.addAttribute("start", String.valueOf(tl.getStartSlot()));
            timeEl.addAttribute("length", String.valueOf(tl.getLength()));
            if (tl.getBreakTime() != 0)
                timeEl.addAttribute("breakTime", String.valueOf(tl.getBreakTime()));
            if (tl.getTimePatternId() != null)
                timeEl.addAttribute("pattern", tl.getTimePatternId().toString());
            if (tl.getDatePatternId() != null)
                timeEl.addAttribute("datePattern", tl.getDatePatternId().toString());
            if (tl.getDatePatternName() != null && !tl.getDatePatternName().isEmpty())
                timeEl.addAttribute("datePatternName", tl.getDatePatternName());
            if (tl.getWeekCode() != null)
                timeEl.addAttribute("dates", bitset2string(tl.getWeekCode()));
            timeEl.addAttribute("preference", tp.isProhibited() ? "P" : tp.isRequired() ? "R" : String.valueOf(tp.getPreference()));
            if (tp.getTarget() instanceof EnrolledClass) {
                Element classEl = timeEl.addElement("section");
                Element courseEl = null;
                EnrolledClass ec = (EnrolledClass) tp.getTarget();
                if (ec.getCourseId() != null || ec.getCourse() != null) {
                    courseEl = timeEl.addElement("course");
                    if (ec.getCourseId() != null)
                        courseEl.addAttribute("id", String.valueOf(ec.getCourseId()));
                    if (ec.getCourse() != null)
                        courseEl.addAttribute("name", ec.getCourse());
                }
                if (ec.getClassId() != null)
                    classEl.addAttribute("id", String.valueOf(ec.getClassId()));
                if (ec.getType() != null)
                    classEl.addAttribute("type", ec.getType());
                if (ec.getSection() != null)
                    classEl.addAttribute("name", ec.getSection());
                if (ec.getExternalId() != null)
                    classEl.addAttribute("externalId", ec.getExternalId());
                if (ec.getRoom() != null)
                    classEl.addAttribute("room", ec.getRoom());
                classEl.addAttribute("role", ec.isInstructor() ? "instructor" : "student");
            } else {
                timeEl.setText(tl.getLongName(false));
            }
        }
        for (Preference<Course> cp : instructor.getCoursePreferences()) {
            Element courseEl = instructorEl.addElement("course");
            Course course = cp.getTarget();
            if (course.getCourseId() != null)
                courseEl.addAttribute("id", String.valueOf(course.getCourseId()));
            if (course.getCourseName() != null)
                courseEl.addAttribute("name", String.valueOf(course.getCourseName()));
            courseEl.addAttribute("preference", cp.isProhibited() ? "P" : cp.isRequired() ? "R" : String.valueOf(cp.getPreference()));
        }
    }
    Element constraintsEl = root.addElement("constraints");
    for (Constraint<TeachingRequest.Variable, TeachingAssignment> c : constraints()) {
        if (c instanceof SameInstructorConstraint) {
            SameInstructorConstraint si = (SameInstructorConstraint) c;
            Element sameInstEl = constraintsEl.addElement("same-instructor");
            if (si.getConstraintId() != null)
                sameInstEl.addAttribute("id", String.valueOf(si.getConstraintId()));
            if (si.getName() != null)
                sameInstEl.addAttribute("name", si.getName());
            sameInstEl.addAttribute("preference", Constants.preferenceLevel2preference(si.getPreference()));
            for (TeachingRequest.Variable request : c.variables()) {
                Element assignmentEl = sameInstEl.addElement("request");
                assignmentEl.addAttribute("id", String.valueOf(request.getRequest().getRequestId()));
                if (request.getRequest().getNrInstructors() != 1)
                    assignmentEl.addAttribute("index", String.valueOf(request.getInstructorIndex()));
            }
        } else if (c instanceof SameLinkConstraint) {
            SameLinkConstraint si = (SameLinkConstraint) c;
            Element sameInstEl = constraintsEl.addElement("same-link");
            if (si.getConstraintId() != null)
                sameInstEl.addAttribute("id", String.valueOf(si.getConstraintId()));
            if (si.getName() != null)
                sameInstEl.addAttribute("name", si.getName());
            sameInstEl.addAttribute("preference", Constants.preferenceLevel2preference(si.getPreference()));
            for (TeachingRequest.Variable request : c.variables()) {
                Element assignmentEl = sameInstEl.addElement("request");
                assignmentEl.addAttribute("id", String.valueOf(request.getRequest().getRequestId()));
                if (request.getRequest().getNrInstructors() != 1)
                    assignmentEl.addAttribute("index", String.valueOf(request.getInstructorIndex()));
            }
        }
    }
    return document;
}
Also used : TimeLocation(org.cpsolver.coursett.model.TimeLocation) DecimalFormat(java.text.DecimalFormat) Element(org.dom4j.Element) SameInstructor(org.cpsolver.instructor.criteria.SameInstructor) OriginalInstructor(org.cpsolver.instructor.criteria.OriginalInstructor) Document(org.dom4j.Document) SameLinkConstraint(org.cpsolver.instructor.constraints.SameLinkConstraint) TreeSet(java.util.TreeSet) SameCourse(org.cpsolver.instructor.criteria.SameCourse) HashSet(java.util.HashSet) SameInstructorConstraint(org.cpsolver.instructor.constraints.SameInstructorConstraint) Date(java.util.Date)

Example 3 with TimeLocation

use of org.cpsolver.coursett.model.TimeLocation in project cpsolver by UniTime.

the class StudentSectioningXMLSaver method saveFreeTimeRequest.

/**
     * Save free time request
     * @param requestEl request element to be populated
     * @param request free time request to be saved 
     */
protected void saveFreeTimeRequest(Element requestEl, FreeTimeRequest request) {
    requestEl.addAttribute("id", getId("request", request.getId()));
    requestEl.addAttribute("priority", String.valueOf(request.getPriority()));
    if (request.isAlternative())
        requestEl.addAttribute("alternative", "true");
    if (request.getWeight() != 1.0)
        requestEl.addAttribute("weight", sStudentWeightFormat.format(request.getWeight()));
    TimeLocation tl = request.getTime();
    if (tl != null) {
        requestEl.addAttribute("days", sDF[7].format(Long.parseLong(Integer.toBinaryString(tl.getDayCode()))));
        requestEl.addAttribute("start", String.valueOf(tl.getStartSlot()));
        requestEl.addAttribute("length", String.valueOf(tl.getLength()));
        if (iShowNames && tl.getDatePatternId() != null)
            requestEl.addAttribute("datePattern", tl.getDatePatternId().toString());
        requestEl.addAttribute("dates", bitset2string(tl.getWeekCode()));
        if (iShowNames)
            requestEl.setText(tl.getLongName(true));
    }
    if (iSaveInitial && request.getInitialAssignment() != null) {
        requestEl.addElement("initial");
    }
    if (iSaveCurrent && getAssignment().getValue(request) != null) {
        requestEl.addElement("current");
    }
    if (iSaveBest && request.getBestAssignment() != null) {
        requestEl.addElement("best");
    }
}
Also used : TimeLocation(org.cpsolver.coursett.model.TimeLocation)

Example 4 with TimeLocation

use of org.cpsolver.coursett.model.TimeLocation in project cpsolver by UniTime.

the class TimetableXMLLoader method doLoad.

protected void doLoad(Solution<Lecture, Placement> currentSolution, Element root) {
    if (root.attributeValue("term") != null)
        getModel().getProperties().setProperty("Data.Term", root.attributeValue("term"));
    if (root.attributeValue("year") != null)
        getModel().setYear(Integer.parseInt(root.attributeValue("year")));
    else if (root.attributeValue("term") != null)
        getModel().setYear(Integer.parseInt(root.attributeValue("term").substring(0, 4)));
    if (root.attributeValue("initiative") != null)
        getModel().getProperties().setProperty("Data.Initiative", root.attributeValue("initiative"));
    if (root.attributeValue("semester") != null && root.attributeValue("year") != null)
        getModel().getProperties().setProperty("Data.Term", root.attributeValue("semester") + root.attributeValue("year"));
    if (root.attributeValue("session") != null)
        getModel().getProperties().setProperty("General.SessionId", root.attributeValue("session"));
    if (root.attributeValue("solverGroup") != null)
        getModel().getProperties().setProperty("General.SolverGroupId", root.attributeValue("solverGroup"));
    String version = root.attributeValue("version");
    // Student sectioning considers the whole course (including committed classes), since 2.5
    boolean sectionWholeCourse = true;
    if (version != null && version.indexOf('.') >= 0) {
        int majorVersion = Integer.parseInt(version.substring(0, version.indexOf('.')));
        int minorVersion = Integer.parseInt(version.substring(1 + version.indexOf('.')));
        sectionWholeCourse = (majorVersion == 2 && minorVersion >= 5) || majorVersion > 2;
    }
    HashMap<Long, TimeLocation> perts = new HashMap<Long, TimeLocation>();
    if (getModel().getProperties().getPropertyInt("MPP.TimePert", 0) > 0) {
        int nrChanges = getModel().getProperties().getPropertyInt("MPP.TimePert", 0);
        int idx = 0;
        for (Iterator<?> i = root.element("perturbations").elementIterator("class"); i.hasNext() && idx < nrChanges; idx++) {
            Element pertEl = (Element) i.next();
            Long classId = Long.valueOf(pertEl.attributeValue("id"));
            TimeLocation tl = new TimeLocation(Integer.parseInt(pertEl.attributeValue("days"), 2), Integer.parseInt(pertEl.attributeValue("start")), Integer.parseInt(pertEl.attributeValue("length")), 0, 0.0, 0, null, null, null, 0);
            perts.put(classId, tl);
        }
    }
    iProgress.setPhase("Creating rooms ...", root.element("rooms").elements("room").size());
    HashMap<String, Element> roomElements = new HashMap<String, Element>();
    HashMap<String, RoomConstraint> roomConstraints = new HashMap<String, RoomConstraint>();
    HashMap<Long, List<Lecture>> sameLectures = new HashMap<Long, List<Lecture>>();
    for (Iterator<?> i = root.element("rooms").elementIterator("room"); i.hasNext(); ) {
        Element roomEl = (Element) i.next();
        iProgress.incProgress();
        roomElements.put(roomEl.attributeValue("id"), roomEl);
        if ("false".equals(roomEl.attributeValue("constraint")))
            continue;
        RoomSharingModel sharingModel = null;
        Element sharingEl = roomEl.element("sharing");
        if (sharingEl != null) {
            Character freeForAllPrefChar = null;
            Element freeForAllEl = sharingEl.element("freeForAll");
            if (freeForAllEl != null)
                freeForAllPrefChar = freeForAllEl.attributeValue("value", "F").charAt(0);
            Character notAvailablePrefChar = null;
            Element notAvailableEl = sharingEl.element("notAvailable");
            if (notAvailableEl != null)
                notAvailablePrefChar = notAvailableEl.attributeValue("value", "X").charAt(0);
            String pattern = sharingEl.element("pattern").getText();
            int unit = Integer.parseInt(sharingEl.element("pattern").attributeValue("unit", "1"));
            Map<Character, Long> departments = new HashMap<Character, Long>();
            for (Iterator<?> j = sharingEl.elementIterator("department"); j.hasNext(); ) {
                Element deptEl = (Element) j.next();
                char value = deptEl.attributeValue("value", String.valueOf((char) ('0' + departments.size()))).charAt(0);
                Long id = Long.valueOf(deptEl.attributeValue("id"));
                departments.put(value, id);
            }
            sharingModel = new RoomSharingModel(unit, departments, pattern, freeForAllPrefChar, notAvailablePrefChar);
        }
        boolean ignoreTooFar = false;
        if ("true".equals(roomEl.attributeValue("ignoreTooFar")))
            ignoreTooFar = true;
        boolean fake = false;
        if ("true".equals(roomEl.attributeValue("fake")))
            fake = true;
        Double posX = null, posY = null;
        if (roomEl.attributeValue("location") != null) {
            String loc = roomEl.attributeValue("location");
            posX = Double.valueOf(loc.substring(0, loc.indexOf(',')));
            posY = Double.valueOf(loc.substring(loc.indexOf(',') + 1));
        }
        boolean discouraged = "true".equals(roomEl.attributeValue("discouraged"));
        RoomConstraint constraint = (discouraged ? new DiscouragedRoomConstraint(getModel().getProperties(), Long.valueOf(roomEl.attributeValue("id")), (roomEl.attributeValue("name") != null ? roomEl.attributeValue("name") : "r" + roomEl.attributeValue("id")), (roomEl.attributeValue("building") == null ? null : Long.valueOf(roomEl.attributeValue("building"))), Integer.parseInt(roomEl.attributeValue("capacity")), sharingModel, posX, posY, ignoreTooFar, !fake) : new RoomConstraint(Long.valueOf(roomEl.attributeValue("id")), (roomEl.attributeValue("name") != null ? roomEl.attributeValue("name") : "r" + roomEl.attributeValue("id")), (roomEl.attributeValue("building") == null ? null : Long.valueOf(roomEl.attributeValue("building"))), Integer.parseInt(roomEl.attributeValue("capacity")), sharingModel, posX, posY, ignoreTooFar, !fake));
        if (roomEl.attributeValue("type") != null)
            constraint.setType(Long.valueOf(roomEl.attributeValue("type")));
        getModel().addConstraint(constraint);
        roomConstraints.put(roomEl.attributeValue("id"), constraint);
        for (Iterator<?> j = roomEl.elementIterator("travel-time"); j.hasNext(); ) {
            Element travelTimeEl = (Element) j.next();
            getModel().getDistanceMetric().addTravelTime(constraint.getResourceId(), Long.valueOf(travelTimeEl.attributeValue("id")), Integer.valueOf(travelTimeEl.attributeValue("minutes")));
        }
    }
    HashMap<String, InstructorConstraint> instructorConstraints = new HashMap<String, InstructorConstraint>();
    if (root.element("instructors") != null) {
        for (Iterator<?> i = root.element("instructors").elementIterator("instructor"); i.hasNext(); ) {
            Element instructorEl = (Element) i.next();
            InstructorConstraint instructorConstraint = new InstructorConstraint(Long.valueOf(instructorEl.attributeValue("id")), instructorEl.attributeValue("puid"), (instructorEl.attributeValue("name") != null ? instructorEl.attributeValue("name") : "i" + instructorEl.attributeValue("id")), "true".equals(instructorEl.attributeValue("ignDist")));
            if (instructorEl.attributeValue("type") != null)
                instructorConstraint.setType(Long.valueOf(instructorEl.attributeValue("type")));
            instructorConstraints.put(instructorEl.attributeValue("id"), instructorConstraint);
            getModel().addConstraint(instructorConstraint);
        }
    }
    HashMap<Long, String> depts = new HashMap<Long, String>();
    if (root.element("departments") != null) {
        for (Iterator<?> i = root.element("departments").elementIterator("department"); i.hasNext(); ) {
            Element deptEl = (Element) i.next();
            depts.put(Long.valueOf(deptEl.attributeValue("id")), (deptEl.attributeValue("name") != null ? deptEl.attributeValue("name") : "d" + deptEl.attributeValue("id")));
        }
    }
    HashMap<Long, Configuration> configs = new HashMap<Long, Configuration>();
    HashMap<Long, List<Configuration>> alternativeConfigurations = new HashMap<Long, List<Configuration>>();
    if (root.element("configurations") != null) {
        for (Iterator<?> i = root.element("configurations").elementIterator("config"); i.hasNext(); ) {
            Element configEl = (Element) i.next();
            Long configId = Long.valueOf(configEl.attributeValue("id"));
            int limit = Integer.parseInt(configEl.attributeValue("limit"));
            Long offeringId = Long.valueOf(configEl.attributeValue("offering"));
            Configuration config = new Configuration(offeringId, configId, limit);
            configs.put(configId, config);
            List<Configuration> altConfigs = alternativeConfigurations.get(offeringId);
            if (altConfigs == null) {
                altConfigs = new ArrayList<Configuration>();
                alternativeConfigurations.put(offeringId, altConfigs);
            }
            altConfigs.add(config);
            config.setAltConfigurations(altConfigs);
        }
    }
    iProgress.setPhase("Creating variables ...", root.element("classes").elements("class").size());
    HashMap<String, Element> classElements = new HashMap<String, Element>();
    HashMap<String, Lecture> lectures = new HashMap<String, Lecture>();
    HashMap<Lecture, Placement> assignedPlacements = new HashMap<Lecture, Placement>();
    HashMap<Lecture, String> parents = new HashMap<Lecture, String>();
    int ord = 0;
    for (Iterator<?> i1 = root.element("classes").elementIterator("class"); i1.hasNext(); ) {
        Element classEl = (Element) i1.next();
        Configuration config = null;
        if (classEl.attributeValue("config") != null) {
            config = configs.get(Long.valueOf(classEl.attributeValue("config")));
        }
        if (config == null && classEl.attributeValue("offering") != null) {
            Long offeringId = Long.valueOf(classEl.attributeValue("offering"));
            Long configId = Long.valueOf(classEl.attributeValue("config"));
            List<Configuration> altConfigs = alternativeConfigurations.get(offeringId);
            if (altConfigs == null) {
                altConfigs = new ArrayList<Configuration>();
                alternativeConfigurations.put(offeringId, altConfigs);
            }
            for (Configuration c : altConfigs) {
                if (c.getConfigId().equals(configId)) {
                    config = c;
                    break;
                }
            }
            if (config == null) {
                config = new Configuration(offeringId, configId, -1);
                altConfigs.add(config);
                config.setAltConfigurations(altConfigs);
                configs.put(config.getConfigId(), config);
            }
        }
        DatePattern defaultDatePattern = new DatePattern();
        if (classEl.attributeValue("dates") == null) {
            int startDay = Integer.parseInt(classEl.attributeValue("startDay", "0"));
            int endDay = Integer.parseInt(classEl.attributeValue("endDay", "1"));
            defaultDatePattern.setPattern(startDay, endDay);
            defaultDatePattern.setName(sDF.format(getDate(getModel().getYear(), startDay)) + "-" + sDF.format(getDate(getModel().getYear(), endDay)));
        } else {
            defaultDatePattern.setId(classEl.attributeValue("datePattern") == null ? null : Long.valueOf(classEl.attributeValue("datePattern")));
            defaultDatePattern.setName(classEl.attributeValue("datePatternName"));
            defaultDatePattern.setPattern(classEl.attributeValue("dates"));
        }
        Hashtable<Long, DatePattern> datePatterns = new Hashtable<Long, TimetableXMLLoader.DatePattern>();
        for (Iterator<?> i2 = classEl.elementIterator("date"); i2.hasNext(); ) {
            Element dateEl = (Element) i2.next();
            Long id = Long.valueOf(dateEl.attributeValue("id"));
            datePatterns.put(id, new DatePattern(id, dateEl.attributeValue("name"), dateEl.attributeValue("pattern")));
        }
        classElements.put(classEl.attributeValue("id"), classEl);
        List<InstructorConstraint> ics = new ArrayList<InstructorConstraint>();
        for (Iterator<?> i2 = classEl.elementIterator("instructor"); i2.hasNext(); ) {
            Element instructorEl = (Element) i2.next();
            InstructorConstraint instructorConstraint = instructorConstraints.get(instructorEl.attributeValue("id"));
            if (instructorConstraint == null) {
                instructorConstraint = new InstructorConstraint(Long.valueOf(instructorEl.attributeValue("id")), instructorEl.attributeValue("puid"), (instructorEl.attributeValue("name") != null ? instructorEl.attributeValue("name") : "i" + instructorEl.attributeValue("id")), "true".equals(instructorEl.attributeValue("ignDist")));
                instructorConstraints.put(instructorEl.attributeValue("id"), instructorConstraint);
                getModel().addConstraint(instructorConstraint);
            }
            ics.add(instructorConstraint);
        }
        List<RoomLocation> roomLocations = new ArrayList<RoomLocation>();
        List<RoomConstraint> roomConstraintsThisClass = new ArrayList<RoomConstraint>();
        List<RoomLocation> initialRoomLocations = new ArrayList<RoomLocation>();
        List<RoomLocation> assignedRoomLocations = new ArrayList<RoomLocation>();
        List<RoomLocation> bestRoomLocations = new ArrayList<RoomLocation>();
        for (Iterator<?> i2 = classEl.elementIterator("room"); i2.hasNext(); ) {
            Element roomLocationEl = (Element) i2.next();
            Element roomEl = roomElements.get(roomLocationEl.attributeValue("id"));
            RoomConstraint roomConstraint = roomConstraints.get(roomLocationEl.attributeValue("id"));
            Long roomId = null;
            String roomName = null;
            Long bldgId = null;
            if (roomConstraint != null) {
                roomConstraintsThisClass.add(roomConstraint);
                roomId = roomConstraint.getResourceId();
                roomName = roomConstraint.getRoomName();
                bldgId = roomConstraint.getBuildingId();
            } else {
                roomId = Long.valueOf(roomEl.attributeValue("id"));
                roomName = (roomEl.attributeValue("name") != null ? roomEl.attributeValue("name") : "r" + roomEl.attributeValue("id"));
                bldgId = (roomEl.attributeValue("building") == null ? null : Long.valueOf(roomEl.attributeValue("building")));
            }
            boolean ignoreTooFar = false;
            if ("true".equals(roomEl.attributeValue("ignoreTooFar")))
                ignoreTooFar = true;
            Double posX = null, posY = null;
            if (roomEl.attributeValue("location") != null) {
                String loc = roomEl.attributeValue("location");
                posX = Double.valueOf(loc.substring(0, loc.indexOf(',')));
                posY = Double.valueOf(loc.substring(loc.indexOf(',') + 1));
            }
            RoomLocation rl = new RoomLocation(roomId, roomName, bldgId, Integer.parseInt(roomLocationEl.attributeValue("pref")), Integer.parseInt(roomEl.attributeValue("capacity")), posX, posY, ignoreTooFar, roomConstraint);
            if ("true".equals(roomLocationEl.attributeValue("initial")))
                initialRoomLocations.add(rl);
            if ("true".equals(roomLocationEl.attributeValue("solution")))
                assignedRoomLocations.add(rl);
            if ("true".equals(roomLocationEl.attributeValue("best")))
                bestRoomLocations.add(rl);
            roomLocations.add(rl);
        }
        List<TimeLocation> timeLocations = new ArrayList<TimeLocation>();
        TimeLocation initialTimeLocation = null;
        TimeLocation assignedTimeLocation = null;
        TimeLocation bestTimeLocation = null;
        TimeLocation prohibitedTime = perts.get(Long.valueOf(classEl.attributeValue("id")));
        for (Iterator<?> i2 = classEl.elementIterator("time"); i2.hasNext(); ) {
            Element timeLocationEl = (Element) i2.next();
            DatePattern dp = defaultDatePattern;
            if (timeLocationEl.attributeValue("date") != null)
                dp = datePatterns.get(Long.valueOf(timeLocationEl.attributeValue("date")));
            TimeLocation tl = new TimeLocation(Integer.parseInt(timeLocationEl.attributeValue("days"), 2), Integer.parseInt(timeLocationEl.attributeValue("start")), Integer.parseInt(timeLocationEl.attributeValue("length")), (int) Double.parseDouble(timeLocationEl.attributeValue("pref")), Double.parseDouble(timeLocationEl.attributeValue("npref", timeLocationEl.attributeValue("pref"))), Integer.parseInt(timeLocationEl.attributeValue("datePref", "0")), dp.getId(), dp.getName(), dp.getPattern(), Integer.parseInt(timeLocationEl.attributeValue("breakTime") == null ? "-1" : timeLocationEl.attributeValue("breakTime")));
            if (tl.getBreakTime() < 0)
                tl.setBreakTime(tl.getLength() == 18 ? 15 : 10);
            if (timeLocationEl.attributeValue("pattern") != null)
                tl.setTimePatternId(Long.valueOf(timeLocationEl.attributeValue("pattern")));
            /*
                 * if (timePatternTransform) tl =
                 * transformTimePattern(Long.valueOf
                 * (classEl.attributeValue("id")),tl);
                 */
            if (prohibitedTime != null && prohibitedTime.getDayCode() == tl.getDayCode() && prohibitedTime.getStartSlot() == tl.getStartSlot() && prohibitedTime.getLength() == tl.getLength()) {
                sLogger.info("Time " + tl.getLongName(true) + " is prohibited for class " + classEl.attributeValue("id"));
                continue;
            }
            if ("true".equals(timeLocationEl.attributeValue("solution")))
                assignedTimeLocation = tl;
            if ("true".equals(timeLocationEl.attributeValue("initial")))
                initialTimeLocation = tl;
            if ("true".equals(timeLocationEl.attributeValue("best")))
                bestTimeLocation = tl;
            timeLocations.add(tl);
        }
        if (timeLocations.isEmpty()) {
            sLogger.error("  ERROR: No time.");
            continue;
        }
        int minClassLimit = 0;
        int maxClassLimit = 0;
        float room2limitRatio = 1.0f;
        if (!"true".equals(classEl.attributeValue("committed"))) {
            if (classEl.attributeValue("expectedCapacity") != null) {
                minClassLimit = maxClassLimit = Integer.parseInt(classEl.attributeValue("expectedCapacity"));
                int roomCapacity = Integer.parseInt(classEl.attributeValue("roomCapacity", classEl.attributeValue("expectedCapacity")));
                if (minClassLimit == 0)
                    minClassLimit = maxClassLimit = roomCapacity;
                room2limitRatio = (minClassLimit == 0 ? 1.0f : ((float) roomCapacity) / minClassLimit);
            } else {
                if (classEl.attribute("classLimit") != null) {
                    minClassLimit = maxClassLimit = Integer.parseInt(classEl.attributeValue("classLimit"));
                } else {
                    minClassLimit = Integer.parseInt(classEl.attributeValue("minClassLimit"));
                    maxClassLimit = Integer.parseInt(classEl.attributeValue("maxClassLimit"));
                }
                room2limitRatio = Float.parseFloat(classEl.attributeValue("roomToLimitRatio", "1.0"));
            }
        }
        Lecture lecture = new Lecture(Long.valueOf(classEl.attributeValue("id")), (classEl.attributeValue("solverGroup") != null ? Long.valueOf(classEl.attributeValue("solverGroup")) : null), Long.valueOf(classEl.attributeValue("subpart", classEl.attributeValue("course", "-1"))), (classEl.attributeValue("name") != null ? classEl.attributeValue("name") : "c" + classEl.attributeValue("id")), timeLocations, roomLocations, Integer.parseInt(classEl.attributeValue("nrRooms", roomLocations.isEmpty() ? "0" : "1")), null, minClassLimit, maxClassLimit, room2limitRatio);
        lecture.setNote(classEl.attributeValue("note"));
        if ("true".equals(classEl.attributeValue("committed")))
            lecture.setCommitted(true);
        if (!lecture.isCommitted() && classEl.attributeValue("ord") != null)
            lecture.setOrd(Integer.parseInt(classEl.attributeValue("ord")));
        else
            lecture.setOrd(ord++);
        lecture.setWeight(Double.parseDouble(classEl.attributeValue("weight", "1.0")));
        if (lecture.getNrRooms() > 1)
            lecture.setMaxRoomCombinations(Integer.parseInt(classEl.attributeValue("maxRoomCombinations", "-1")));
        if (config != null)
            lecture.setConfiguration(config);
        if (initialTimeLocation != null && initialRoomLocations.size() == lecture.getNrRooms()) {
            lecture.setInitialAssignment(new Placement(lecture, initialTimeLocation, initialRoomLocations));
        }
        if (assignedTimeLocation != null && assignedRoomLocations.size() == lecture.getNrRooms()) {
            assignedPlacements.put(lecture, new Placement(lecture, assignedTimeLocation, assignedRoomLocations));
        } else if (lecture.getInitialAssignment() != null) {
            assignedPlacements.put(lecture, lecture.getInitialAssignment());
        }
        if (bestTimeLocation != null && bestRoomLocations.size() == lecture.getNrRooms()) {
            lecture.setBestAssignment(new Placement(lecture, bestTimeLocation, bestRoomLocations), 0);
        } else if (assignedTimeLocation != null && assignedRoomLocations.size() == lecture.getNrRooms()) {
            lecture.setBestAssignment(assignedPlacements.get(lecture), 0);
        }
        lectures.put(classEl.attributeValue("id"), lecture);
        if (classEl.attributeValue("department") != null)
            lecture.setDepartment(Long.valueOf(classEl.attributeValue("department")));
        if (classEl.attribute("scheduler") != null)
            lecture.setScheduler(Long.valueOf(classEl.attributeValue("scheduler")));
        if ((sectionWholeCourse || !lecture.isCommitted()) && classEl.attributeValue("subpart", classEl.attributeValue("course")) != null) {
            Long subpartId = Long.valueOf(classEl.attributeValue("subpart", classEl.attributeValue("course")));
            List<Lecture> sames = sameLectures.get(subpartId);
            if (sames == null) {
                sames = new ArrayList<Lecture>();
                sameLectures.put(subpartId, sames);
            }
            sames.add(lecture);
        }
        String parent = classEl.attributeValue("parent");
        if (parent != null)
            parents.put(lecture, parent);
        getModel().addVariable(lecture);
        if (lecture.isCommitted()) {
            Placement placement = assignedPlacements.get(lecture);
            if (classEl.attribute("assignment") != null)
                placement.setAssignmentId(Long.valueOf(classEl.attributeValue("assignment")));
            for (InstructorConstraint ic : ics) ic.setNotAvailable(placement);
            for (RoomConstraint rc : roomConstraintsThisClass) rc.setNotAvailable(placement);
        } else {
            for (InstructorConstraint ic : ics) ic.addVariable(lecture);
            for (RoomConstraint rc : roomConstraintsThisClass) rc.addVariable(lecture);
        }
        iProgress.incProgress();
    }
    for (Map.Entry<Lecture, String> entry : parents.entrySet()) {
        Lecture lecture = entry.getKey();
        Lecture parent = lectures.get(entry.getValue());
        if (parent == null) {
            iProgress.warn("Parent class " + entry.getValue() + " does not exists.");
        } else {
            lecture.setParent(parent);
        }
    }
    iProgress.setPhase("Creating constraints ...", root.element("groupConstraints").elements("constraint").size());
    HashMap<String, Element> grConstraintElements = new HashMap<String, Element>();
    HashMap<String, Constraint<Lecture, Placement>> groupConstraints = new HashMap<String, Constraint<Lecture, Placement>>();
    for (Iterator<?> i1 = root.element("groupConstraints").elementIterator("constraint"); i1.hasNext(); ) {
        Element grConstraintEl = (Element) i1.next();
        Constraint<Lecture, Placement> c = null;
        if ("SPREAD".equals(grConstraintEl.attributeValue("type"))) {
            c = new SpreadConstraint(getModel().getProperties(), grConstraintEl.attributeValue("name", "spread"));
        } else if ("MIN_ROOM_USE".equals(grConstraintEl.attributeValue("type"))) {
            c = new MinimizeNumberOfUsedRoomsConstraint(getModel().getProperties());
        } else if ("CLASS_LIMIT".equals(grConstraintEl.attributeValue("type"))) {
            if (grConstraintEl.element("parentClass") == null) {
                c = new ClassLimitConstraint(Integer.parseInt(grConstraintEl.attributeValue("courseLimit")), grConstraintEl.attributeValue("name", "class-limit"));
            } else {
                String classId = grConstraintEl.element("parentClass").attributeValue("id");
                c = new ClassLimitConstraint(lectures.get(classId), grConstraintEl.attributeValue("name", "class-limit"));
            }
            if (grConstraintEl.attributeValue("delta") != null)
                ((ClassLimitConstraint) c).setClassLimitDelta(Integer.parseInt(grConstraintEl.attributeValue("delta")));
        } else if ("MIN_GRUSE(10x1h)".equals(grConstraintEl.attributeValue("type"))) {
            c = new MinimizeNumberOfUsedGroupsOfTime(getModel().getProperties(), "10x1h", MinimizeNumberOfUsedGroupsOfTime.sGroups10of1h);
        } else if ("MIN_GRUSE(5x2h)".equals(grConstraintEl.attributeValue("type"))) {
            c = new MinimizeNumberOfUsedGroupsOfTime(getModel().getProperties(), "5x2h", MinimizeNumberOfUsedGroupsOfTime.sGroups5of2h);
        } else if ("MIN_GRUSE(3x3h)".equals(grConstraintEl.attributeValue("type"))) {
            c = new MinimizeNumberOfUsedGroupsOfTime(getModel().getProperties(), "3x3h", MinimizeNumberOfUsedGroupsOfTime.sGroups3of3h);
        } else if ("MIN_GRUSE(2x5h)".equals(grConstraintEl.attributeValue("type"))) {
            c = new MinimizeNumberOfUsedGroupsOfTime(getModel().getProperties(), "2x5h", MinimizeNumberOfUsedGroupsOfTime.sGroups2of5h);
        } else if (IgnoreStudentConflictsConstraint.REFERENCE.equals(grConstraintEl.attributeValue("type"))) {
            c = new IgnoreStudentConflictsConstraint();
        } else {
            try {
                FlexibleConstraintType f = FlexibleConstraintType.valueOf(grConstraintEl.attributeValue("type"));
                try {
                    c = f.create(Long.valueOf(grConstraintEl.attributeValue("id")), grConstraintEl.attributeValue("owner"), grConstraintEl.attributeValue("pref"), grConstraintEl.attributeValue("reference"));
                } catch (IllegalArgumentException e) {
                    iProgress.warn("Failed to create flexible constraint " + grConstraintEl.attributeValue("type") + ": " + e.getMessage(), e);
                    continue;
                }
            } catch (IllegalArgumentException e) {
                // type did not match, continue with group constraint types
                c = new GroupConstraint(Long.valueOf(grConstraintEl.attributeValue("id")), GroupConstraint.ConstraintType.get(grConstraintEl.attributeValue("type")), grConstraintEl.attributeValue("pref"));
            }
        }
        getModel().addConstraint(c);
        for (Iterator<?> i2 = grConstraintEl.elementIterator("class"); i2.hasNext(); ) {
            String classId = ((Element) i2.next()).attributeValue("id");
            Lecture other = lectures.get(classId);
            if (other != null)
                c.addVariable(other);
            else
                iProgress.warn("Class " + classId + " does not exists, but it is referred from group constraint " + c.getId() + " (" + c.getName() + ")");
        }
        grConstraintElements.put(grConstraintEl.attributeValue("id"), grConstraintEl);
        groupConstraints.put(grConstraintEl.attributeValue("id"), c);
        iProgress.incProgress();
    }
    iProgress.setPhase("Loading students ...", root.element("students").elements("student").size());
    boolean initialSectioning = true;
    HashMap<Long, Student> students = new HashMap<Long, Student>();
    HashMap<Long, Set<Student>> offering2students = new HashMap<Long, Set<Student>>();
    for (Iterator<?> i1 = root.element("students").elementIterator("student"); i1.hasNext(); ) {
        Element studentEl = (Element) i1.next();
        List<Lecture> lecturesThisStudent = new ArrayList<Lecture>();
        Long studentId = Long.valueOf(studentEl.attributeValue("id"));
        Student student = students.get(studentId);
        if (student == null) {
            student = new Student(studentId);
            students.put(studentId, student);
            getModel().addStudent(student);
        }
        student.setAcademicArea(studentEl.attributeValue("area"));
        student.setAcademicClassification(studentEl.attributeValue("classification"));
        student.setMajor(studentEl.attributeValue("major"));
        student.setCurriculum(studentEl.attributeValue("curriculum"));
        for (Iterator<?> i2 = studentEl.elementIterator("offering"); i2.hasNext(); ) {
            Element ofEl = (Element) i2.next();
            Long offeringId = Long.valueOf(ofEl.attributeValue("id"));
            String priority = ofEl.attributeValue("priority");
            student.addOffering(offeringId, Double.parseDouble(ofEl.attributeValue("weight", "1.0")), priority == null ? null : Double.valueOf(priority));
            Set<Student> studentsThisOffering = offering2students.get(offeringId);
            if (studentsThisOffering == null) {
                studentsThisOffering = new HashSet<Student>();
                offering2students.put(offeringId, studentsThisOffering);
            }
            studentsThisOffering.add(student);
        }
        for (Iterator<?> i2 = studentEl.elementIterator("class"); i2.hasNext(); ) {
            String classId = ((Element) i2.next()).attributeValue("id");
            Lecture lecture = lectures.get(classId);
            if (lecture == null) {
                iProgress.warn("Class " + classId + " does not exists, but it is referred from student " + student.getId());
                continue;
            }
            if (lecture.isCommitted()) {
                if (sectionWholeCourse && (lecture.getParent() != null || lecture.getConfiguration() != null)) {
                    // committed, but with course structure -- sectioning can be used
                    student.addLecture(lecture);
                    student.addConfiguration(lecture.getConfiguration());
                    lecture.addStudent(getAssignment(), student);
                    lecturesThisStudent.add(lecture);
                    initialSectioning = false;
                } else {
                    Placement placement = assignedPlacements.get(lecture);
                    student.addCommitedPlacement(placement);
                }
            } else {
                student.addLecture(lecture);
                student.addConfiguration(lecture.getConfiguration());
                lecture.addStudent(getAssignment(), student);
                lecturesThisStudent.add(lecture);
                initialSectioning = false;
            }
        }
        for (Iterator<?> i2 = studentEl.elementIterator("prohibited-class"); i2.hasNext(); ) {
            String classId = ((Element) i2.next()).attributeValue("id");
            Lecture lecture = lectures.get(classId);
            if (lecture != null)
                student.addCanNotEnroll(lecture);
            else
                iProgress.warn("Class " + classId + " does not exists, but it is referred from student " + student.getId());
        }
        if (studentEl.attributeValue("instructor") != null)
            student.setInstructor(instructorConstraints.get(studentEl.attributeValue("instructor")));
        iProgress.incProgress();
    }
    if (root.element("groups") != null) {
        iProgress.setPhase("Loading student groups ...", root.element("groups").elements("group").size());
        for (Iterator<?> i1 = root.element("groups").elementIterator("group"); i1.hasNext(); ) {
            Element groupEl = (Element) i1.next();
            long groupId = Long.parseLong(groupEl.attributeValue("id"));
            StudentGroup group = new StudentGroup(groupId, Double.parseDouble(groupEl.attributeValue("weight", "1.0")), groupEl.attributeValue("name", "Group-" + groupId));
            getModel().addStudentGroup(group);
            for (Iterator<?> i2 = groupEl.elementIterator("student"); i2.hasNext(); ) {
                Element studentEl = (Element) i2.next();
                Student student = students.get(Long.valueOf(studentEl.attributeValue("id")));
                if (student != null) {
                    group.addStudent(student);
                    student.addGroup(group);
                }
            }
        }
    }
    for (List<Lecture> sames : sameLectures.values()) {
        for (Lecture lect : sames) {
            lect.setSameSubpartLectures(sames);
        }
    }
    if (initialSectioning) {
        iProgress.setPhase("Initial sectioning ...", offering2students.size());
        for (Map.Entry<Long, Set<Student>> entry : offering2students.entrySet()) {
            Long offeringId = entry.getKey();
            Set<Student> studentsThisOffering = entry.getValue();
            List<Configuration> altConfigs = alternativeConfigurations.get(offeringId);
            getModel().getStudentSectioning().initialSectioning(getAssignment(), offeringId, String.valueOf(offeringId), studentsThisOffering, altConfigs);
            iProgress.incProgress();
        }
        for (Student student : students.values()) {
            student.clearDistanceCache();
            if (student.getInstructor() != null)
                for (Lecture lecture : student.getInstructor().variables()) {
                    student.addLecture(lecture);
                    student.addConfiguration(lecture.getConfiguration());
                    lecture.addStudent(getAssignment(), student);
                }
        }
    }
    iProgress.setPhase("Computing jenrl ...", students.size());
    HashMap<Lecture, HashMap<Lecture, JenrlConstraint>> jenrls = new HashMap<Lecture, HashMap<Lecture, JenrlConstraint>>();
    for (Iterator<Student> i1 = students.values().iterator(); i1.hasNext(); ) {
        Student st = i1.next();
        for (Iterator<Lecture> i2 = st.getLectures().iterator(); i2.hasNext(); ) {
            Lecture l1 = i2.next();
            for (Iterator<Lecture> i3 = st.getLectures().iterator(); i3.hasNext(); ) {
                Lecture l2 = i3.next();
                if (l1.getId() >= l2.getId())
                    continue;
                HashMap<Lecture, JenrlConstraint> x = jenrls.get(l1);
                if (x == null) {
                    x = new HashMap<Lecture, JenrlConstraint>();
                    jenrls.put(l1, x);
                }
                JenrlConstraint jenrl = x.get(l2);
                if (jenrl == null) {
                    jenrl = new JenrlConstraint();
                    jenrl.addVariable(l1);
                    jenrl.addVariable(l2);
                    getModel().addConstraint(jenrl);
                    x.put(l2, jenrl);
                }
                jenrl.incJenrl(getAssignment(), st);
            }
        }
        iProgress.incProgress();
    }
    if (iDeptBalancing) {
        iProgress.setPhase("Creating dept. spread constraints ...", getModel().variables().size());
        HashMap<Long, DepartmentSpreadConstraint> depSpreadConstraints = new HashMap<Long, DepartmentSpreadConstraint>();
        for (Lecture lecture : getModel().variables()) {
            if (lecture.getDepartment() == null)
                continue;
            DepartmentSpreadConstraint deptConstr = depSpreadConstraints.get(lecture.getDepartment());
            if (deptConstr == null) {
                String name = depts.get(lecture.getDepartment());
                deptConstr = new DepartmentSpreadConstraint(getModel().getProperties(), lecture.getDepartment(), (name != null ? name : "d" + lecture.getDepartment()));
                depSpreadConstraints.put(lecture.getDepartment(), deptConstr);
                getModel().addConstraint(deptConstr);
            }
            deptConstr.addVariable(lecture);
            iProgress.incProgress();
        }
    }
    if (getModel().getProperties().getPropertyBoolean("General.PurgeInvalidPlacements", true)) {
        iProgress.setPhase("Purging invalid placements ...", getModel().variables().size());
        for (Lecture lecture : getModel().variables()) {
            lecture.purgeInvalidValues(iInteractiveMode);
            iProgress.incProgress();
        }
    }
    if (getModel().hasConstantVariables() && getModel().constantVariables().size() > 0) {
        iProgress.setPhase("Assigning committed classes ...", assignedPlacements.size());
        for (Map.Entry<Lecture, Placement> entry : assignedPlacements.entrySet()) {
            Lecture lecture = entry.getKey();
            Placement placement = entry.getValue();
            if (!lecture.isCommitted()) {
                iProgress.incProgress();
                continue;
            }
            lecture.setConstantValue(placement);
            getModel().weaken(getAssignment(), placement);
            Map<Constraint<Lecture, Placement>, Set<Placement>> conflictConstraints = getModel().conflictConstraints(getAssignment(), placement);
            if (conflictConstraints.isEmpty()) {
                getAssignment().assign(0, placement);
            } else {
                sLogger.warn("WARNING: Unable to assign " + lecture.getName() + " := " + placement.getName());
                sLogger.debug("  Reason:");
                for (Constraint<Lecture, Placement> c : conflictConstraints.keySet()) {
                    Set<Placement> vals = conflictConstraints.get(c);
                    for (Placement v : vals) {
                        sLogger.debug("    " + v.variable().getName() + " = " + v.getName());
                    }
                    sLogger.debug("    in constraint " + c);
                }
            }
            iProgress.incProgress();
        }
    }
    if (currentSolution != null) {
        iProgress.setPhase("Creating best assignment ...", 2 * getModel().variables().size());
        for (Lecture lecture : getModel().variables()) {
            iProgress.incProgress();
            Placement placement = lecture.getBestAssignment();
            if (placement == null)
                continue;
            getModel().weaken(getAssignment(), placement);
            getAssignment().assign(0, placement);
        }
        currentSolution.saveBest();
        for (Lecture lecture : getModel().variables()) {
            iProgress.incProgress();
            getAssignment().unassign(0, lecture);
        }
    }
    iProgress.setPhase("Creating initial assignment ...", assignedPlacements.size());
    for (Map.Entry<Lecture, Placement> entry : assignedPlacements.entrySet()) {
        Lecture lecture = entry.getKey();
        Placement placement = entry.getValue();
        if (lecture.isCommitted()) {
            iProgress.incProgress();
            continue;
        }
        getModel().weaken(getAssignment(), placement);
        Map<Constraint<Lecture, Placement>, Set<Placement>> conflictConstraints = getModel().conflictConstraints(getAssignment(), placement);
        if (conflictConstraints.isEmpty()) {
            if (!placement.isValid()) {
                sLogger.warn("WARNING: Lecture " + lecture.getName() + " does not contain assignment " + placement.getLongName(true) + " in its domain (" + placement.getNotValidReason(getAssignment(), true) + ").");
            } else
                getAssignment().assign(0, placement);
        } else {
            sLogger.warn("WARNING: Unable to assign " + lecture.getName() + " := " + placement.getName());
            sLogger.debug("  Reason:");
            for (Constraint<Lecture, Placement> c : conflictConstraints.keySet()) {
                Set<Placement> vals = conflictConstraints.get(c);
                for (Placement v : vals) {
                    sLogger.debug("    " + v.variable().getName() + " = " + v.getName());
                }
                sLogger.debug("    in constraint " + c);
            }
        }
        iProgress.incProgress();
    }
    if (initialSectioning && getAssignment().nrAssignedVariables() != 0 && !getModel().getProperties().getPropertyBoolean("Global.LoadStudentEnrlsFromSolution", false))
        getModel().switchStudents(getAssignment());
    if (iForcedPerturbances > 0) {
        iProgress.setPhase("Forcing perturbances", iForcedPerturbances);
        for (int i = 0; i < iForcedPerturbances; i++) {
            iProgress.setProgress(i);
            Lecture var = null;
            do {
                var = ToolBox.random(getModel().variables());
            } while (var.getInitialAssignment() == null || var.values(getAssignment()).size() <= 1);
            var.removeInitialValue();
        }
    }
/*
        for (Constraint<Lecture, Placement> c : getModel().constraints()) {
            if (c instanceof SpreadConstraint)
                ((SpreadConstraint) c).init();
            if (c instanceof DiscouragedRoomConstraint)
                ((DiscouragedRoomConstraint) c).setEnabled(true);
            if (c instanceof MinimizeNumberOfUsedRoomsConstraint)
                ((MinimizeNumberOfUsedRoomsConstraint) c).setEnabled(true);
            if (c instanceof MinimizeNumberOfUsedGroupsOfTime)
                ((MinimizeNumberOfUsedGroupsOfTime) c).setEnabled(true);
        }
         */
}
Also used : DiscouragedRoomConstraint(org.cpsolver.coursett.constraint.DiscouragedRoomConstraint) RoomConstraint(org.cpsolver.coursett.constraint.RoomConstraint) Lecture(org.cpsolver.coursett.model.Lecture) Configuration(org.cpsolver.coursett.model.Configuration) HashMap(java.util.HashMap) DepartmentSpreadConstraint(org.cpsolver.coursett.constraint.DepartmentSpreadConstraint) DiscouragedRoomConstraint(org.cpsolver.coursett.constraint.DiscouragedRoomConstraint) ClassLimitConstraint(org.cpsolver.coursett.constraint.ClassLimitConstraint) IgnoreStudentConflictsConstraint(org.cpsolver.coursett.constraint.IgnoreStudentConflictsConstraint) InstructorConstraint(org.cpsolver.coursett.constraint.InstructorConstraint) MinimizeNumberOfUsedRoomsConstraint(org.cpsolver.coursett.constraint.MinimizeNumberOfUsedRoomsConstraint) SpreadConstraint(org.cpsolver.coursett.constraint.SpreadConstraint) GroupConstraint(org.cpsolver.coursett.constraint.GroupConstraint) Constraint(org.cpsolver.ifs.model.Constraint) RoomConstraint(org.cpsolver.coursett.constraint.RoomConstraint) JenrlConstraint(org.cpsolver.coursett.constraint.JenrlConstraint) DepartmentSpreadConstraint(org.cpsolver.coursett.constraint.DepartmentSpreadConstraint) ArrayList(java.util.ArrayList) DepartmentSpreadConstraint(org.cpsolver.coursett.constraint.DepartmentSpreadConstraint) SpreadConstraint(org.cpsolver.coursett.constraint.SpreadConstraint) Placement(org.cpsolver.coursett.model.Placement) ArrayList(java.util.ArrayList) List(java.util.List) IgnoreStudentConflictsConstraint(org.cpsolver.coursett.constraint.IgnoreStudentConflictsConstraint) Student(org.cpsolver.coursett.model.Student) ClassLimitConstraint(org.cpsolver.coursett.constraint.ClassLimitConstraint) GroupConstraint(org.cpsolver.coursett.constraint.GroupConstraint) HashMap(java.util.HashMap) Map(java.util.Map) MinimizeNumberOfUsedGroupsOfTime(org.cpsolver.coursett.constraint.MinimizeNumberOfUsedGroupsOfTime) HashSet(java.util.HashSet) Set(java.util.Set) BitSet(java.util.BitSet) TimeLocation(org.cpsolver.coursett.model.TimeLocation) Element(org.dom4j.Element) DiscouragedRoomConstraint(org.cpsolver.coursett.constraint.DiscouragedRoomConstraint) RoomSharingModel(org.cpsolver.coursett.model.RoomSharingModel) MinimizeNumberOfUsedRoomsConstraint(org.cpsolver.coursett.constraint.MinimizeNumberOfUsedRoomsConstraint) JenrlConstraint(org.cpsolver.coursett.constraint.JenrlConstraint) RoomLocation(org.cpsolver.coursett.model.RoomLocation) Hashtable(java.util.Hashtable) DepartmentSpreadConstraint(org.cpsolver.coursett.constraint.DepartmentSpreadConstraint) DiscouragedRoomConstraint(org.cpsolver.coursett.constraint.DiscouragedRoomConstraint) ClassLimitConstraint(org.cpsolver.coursett.constraint.ClassLimitConstraint) IgnoreStudentConflictsConstraint(org.cpsolver.coursett.constraint.IgnoreStudentConflictsConstraint) InstructorConstraint(org.cpsolver.coursett.constraint.InstructorConstraint) MinimizeNumberOfUsedRoomsConstraint(org.cpsolver.coursett.constraint.MinimizeNumberOfUsedRoomsConstraint) SpreadConstraint(org.cpsolver.coursett.constraint.SpreadConstraint) GroupConstraint(org.cpsolver.coursett.constraint.GroupConstraint) Constraint(org.cpsolver.ifs.model.Constraint) RoomConstraint(org.cpsolver.coursett.constraint.RoomConstraint) JenrlConstraint(org.cpsolver.coursett.constraint.JenrlConstraint) InstructorConstraint(org.cpsolver.coursett.constraint.InstructorConstraint) FlexibleConstraintType(org.cpsolver.coursett.constraint.FlexibleConstraint.FlexibleConstraintType) StudentGroup(org.cpsolver.coursett.model.StudentGroup)

Example 5 with TimeLocation

use of org.cpsolver.coursett.model.TimeLocation in project cpsolver by UniTime.

the class TimetableXMLSaver method doSave.

protected void doSave(Element root) {
    root.addAttribute("version", "2.5");
    root.addAttribute("initiative", getModel().getProperties().getProperty("Data.Initiative"));
    root.addAttribute("term", getModel().getProperties().getProperty("Data.Term"));
    root.addAttribute("year", String.valueOf(getModel().getYear()));
    root.addAttribute("created", String.valueOf(new Date()));
    root.addAttribute("nrDays", String.valueOf(Constants.DAY_CODES.length));
    root.addAttribute("slotsPerDay", String.valueOf(Constants.SLOTS_PER_DAY));
    if (!iConvertIds && getModel().getProperties().getProperty("General.SessionId") != null)
        root.addAttribute("session", getModel().getProperties().getProperty("General.SessionId"));
    if (iShowNames && !iConvertIds && getModel().getProperties().getProperty("General.SolverGroupId") != null)
        root.addAttribute("solverGroup", getId("solverGroup", getModel().getProperties().getProperty("General.SolverGroupId")));
    HashMap<String, Element> roomElements = new HashMap<String, Element>();
    Element roomsEl = root.addElement("rooms");
    for (RoomConstraint roomConstraint : getModel().getRoomConstraints()) {
        Element roomEl = roomsEl.addElement("room").addAttribute("id", getId("room", roomConstraint.getResourceId()));
        roomEl.addAttribute("constraint", "true");
        if (roomConstraint instanceof DiscouragedRoomConstraint)
            roomEl.addAttribute("discouraged", "true");
        if (iShowNames) {
            roomEl.addAttribute("name", roomConstraint.getRoomName());
        }
        if (!iConvertIds && roomConstraint.getBuildingId() != null)
            roomEl.addAttribute("building", getId("bldg", roomConstraint.getBuildingId()));
        roomElements.put(getId("room", roomConstraint.getResourceId()), roomEl);
        roomEl.addAttribute("capacity", String.valueOf(roomConstraint.getCapacity()));
        if (roomConstraint.getPosX() != null && roomConstraint.getPosY() != null)
            roomEl.addAttribute("location", roomConstraint.getPosX() + "," + roomConstraint.getPosY());
        if (roomConstraint.getIgnoreTooFar())
            roomEl.addAttribute("ignoreTooFar", "true");
        if (!roomConstraint.getConstraint())
            roomEl.addAttribute("fake", "true");
        if (roomConstraint.getSharingModel() != null) {
            RoomSharingModel sharingModel = roomConstraint.getSharingModel();
            Element sharingEl = roomEl.addElement("sharing");
            sharingEl.addElement("pattern").addAttribute("unit", String.valueOf(sharingModel.getStep())).setText(sharingModel.getPreferences());
            sharingEl.addElement("freeForAll").addAttribute("value", String.valueOf(sharingModel.getFreeForAllPrefChar()));
            sharingEl.addElement("notAvailable").addAttribute("value", String.valueOf(sharingModel.getNotAvailablePrefChar()));
            for (Long id : sharingModel.getDepartmentIds()) {
                sharingEl.addElement("department").addAttribute("value", String.valueOf(sharingModel.getCharacter(id))).addAttribute("id", getId("dept", id));
            }
        }
        if (roomConstraint.getType() != null && iShowNames)
            roomEl.addAttribute("type", roomConstraint.getType().toString());
        Map<Long, Integer> travelTimes = getModel().getDistanceMetric().getTravelTimes().get(roomConstraint.getResourceId());
        if (travelTimes != null)
            for (Map.Entry<Long, Integer> time : travelTimes.entrySet()) roomEl.addElement("travel-time").addAttribute("id", getId("room", time.getKey())).addAttribute("minutes", time.getValue().toString());
    }
    Element instructorsEl = root.addElement("instructors");
    Element departmentsEl = root.addElement("departments");
    HashMap<Long, String> depts = new HashMap<Long, String>();
    Element configsEl = (iShowNames ? root.addElement("configurations") : null);
    HashSet<Configuration> configs = new HashSet<Configuration>();
    Element classesEl = root.addElement("classes");
    HashMap<Long, Element> classElements = new HashMap<Long, Element>();
    List<Lecture> vars = new ArrayList<Lecture>(getModel().variables());
    if (getModel().hasConstantVariables())
        vars.addAll(getModel().constantVariables());
    for (Lecture lecture : vars) {
        Placement placement = getAssignment().getValue(lecture);
        if (lecture.isCommitted() && placement == null)
            placement = lecture.getInitialAssignment();
        Placement initialPlacement = lecture.getInitialAssignment();
        // if (initialPlacement==null) initialPlacement =
        // (Placement)lecture.getAssignment();
        Placement bestPlacement = lecture.getBestAssignment();
        Element classEl = classesEl.addElement("class").addAttribute("id", getId("class", lecture.getClassId()));
        classElements.put(lecture.getClassId(), classEl);
        if (iShowNames && lecture.getNote() != null)
            classEl.addAttribute("note", lecture.getNote());
        if (iShowNames && !lecture.isCommitted())
            classEl.addAttribute("ord", String.valueOf(lecture.getOrd()));
        if (lecture.getWeight() != 1.0)
            classEl.addAttribute("weight", String.valueOf(lecture.getWeight()));
        if (iShowNames && lecture.getSolverGroupId() != null)
            classEl.addAttribute("solverGroup", getId("solverGroup", lecture.getSolverGroupId()));
        if (lecture.getParent() == null && lecture.getConfiguration() != null) {
            if (!iShowNames)
                classEl.addAttribute("offering", getId("offering", lecture.getConfiguration().getOfferingId().toString()));
            classEl.addAttribute("config", getId("config", lecture.getConfiguration().getConfigId().toString()));
            if (iShowNames && configs.add(lecture.getConfiguration())) {
                configsEl.addElement("config").addAttribute("id", getId("config", lecture.getConfiguration().getConfigId().toString())).addAttribute("limit", String.valueOf(lecture.getConfiguration().getLimit())).addAttribute("offering", getId("offering", lecture.getConfiguration().getOfferingId().toString()));
            }
        }
        classEl.addAttribute("committed", (lecture.isCommitted() ? "true" : "false"));
        if (lecture.getParent() != null)
            classEl.addAttribute("parent", getId("class", lecture.getParent().getClassId()));
        if (lecture.getSchedulingSubpartId() != null)
            classEl.addAttribute("subpart", getId("subpart", lecture.getSchedulingSubpartId()));
        if (iShowNames && lecture.isCommitted() && placement != null && placement.getAssignmentId() != null) {
            classEl.addAttribute("assignment", getId("assignment", placement.getAssignmentId()));
        }
        if (!lecture.isCommitted()) {
            if (lecture.minClassLimit() == lecture.maxClassLimit()) {
                classEl.addAttribute("classLimit", String.valueOf(lecture.maxClassLimit()));
            } else {
                classEl.addAttribute("minClassLimit", String.valueOf(lecture.minClassLimit()));
                classEl.addAttribute("maxClassLimit", String.valueOf(lecture.maxClassLimit()));
            }
            if (lecture.roomToLimitRatio() != 1.0f)
                classEl.addAttribute("roomToLimitRatio", sStudentWeightFormat.format(lecture.roomToLimitRatio()));
        }
        if (lecture.getNrRooms() != 1)
            classEl.addAttribute("nrRooms", String.valueOf(lecture.getNrRooms()));
        if (lecture.getNrRooms() > 1 && lecture.getMaxRoomCombinations() > 0)
            classEl.addAttribute("maxRoomCombinations", String.valueOf(lecture.getMaxRoomCombinations()));
        if (iShowNames)
            classEl.addAttribute("name", lecture.getName());
        if (lecture.getDeptSpreadConstraint() != null) {
            classEl.addAttribute("department", getId("dept", lecture.getDeptSpreadConstraint().getDepartmentId()));
            depts.put(lecture.getDeptSpreadConstraint().getDepartmentId(), lecture.getDeptSpreadConstraint().getName());
        }
        if (lecture.getScheduler() != null)
            classEl.addAttribute("scheduler", getId("dept", lecture.getScheduler()));
        for (InstructorConstraint ic : lecture.getInstructorConstraints()) {
            Element instrEl = classEl.addElement("instructor").addAttribute("id", getId("inst", ic.getResourceId()));
            if ((lecture.isCommitted() || iSaveCurrent) && placement != null)
                instrEl.addAttribute("solution", "true");
            if (iSaveInitial && initialPlacement != null)
                instrEl.addAttribute("initial", "true");
            if (iSaveBest && bestPlacement != null && !bestPlacement.equals(placement))
                instrEl.addAttribute("best", "true");
        }
        for (RoomLocation rl : lecture.roomLocations()) {
            Element roomLocationEl = classEl.addElement("room");
            roomLocationEl.addAttribute("id", getId("room", rl.getId()));
            roomLocationEl.addAttribute("pref", String.valueOf(rl.getPreference()));
            if ((lecture.isCommitted() || iSaveCurrent) && placement != null && placement.hasRoomLocation(rl.getId()))
                roomLocationEl.addAttribute("solution", "true");
            if (iSaveInitial && initialPlacement != null && initialPlacement.hasRoomLocation(rl.getId()))
                roomLocationEl.addAttribute("initial", "true");
            if (iSaveBest && bestPlacement != null && !bestPlacement.equals(placement) && bestPlacement.hasRoomLocation(rl.getId()))
                roomLocationEl.addAttribute("best", "true");
            if (!roomElements.containsKey(getId("room", rl.getId()))) {
                // room location without room constraint
                Element roomEl = roomsEl.addElement("room").addAttribute("id", getId("room", rl.getId()));
                roomEl.addAttribute("constraint", "false");
                if (!iConvertIds && rl.getBuildingId() != null)
                    roomEl.addAttribute("building", getId("bldg", rl.getBuildingId()));
                if (iShowNames) {
                    roomEl.addAttribute("name", rl.getName());
                }
                roomElements.put(getId("room", rl.getId()), roomEl);
                roomEl.addAttribute("capacity", String.valueOf(rl.getRoomSize()));
                if (rl.getPosX() != null && rl.getPosY() != null)
                    roomEl.addAttribute("location", rl.getPosX() + "," + rl.getPosY());
                if (rl.getIgnoreTooFar())
                    roomEl.addAttribute("ignoreTooFar", "true");
            }
        }
        boolean first = true;
        Set<Long> dp = new HashSet<Long>();
        for (TimeLocation tl : lecture.timeLocations()) {
            Element timeLocationEl = classEl.addElement("time");
            timeLocationEl.addAttribute("days", sDF[7].format(Long.parseLong(Integer.toBinaryString(tl.getDayCode()))));
            timeLocationEl.addAttribute("start", String.valueOf(tl.getStartSlot()));
            timeLocationEl.addAttribute("length", String.valueOf(tl.getLength()));
            timeLocationEl.addAttribute("breakTime", String.valueOf(tl.getBreakTime()));
            if (iShowNames) {
                timeLocationEl.addAttribute("pref", String.valueOf(tl.getPreference()));
                timeLocationEl.addAttribute("npref", String.valueOf(tl.getNormalizedPreference()));
            } else {
                timeLocationEl.addAttribute("pref", String.valueOf(tl.getNormalizedPreference()));
            }
            if (!iConvertIds && tl.getTimePatternId() != null)
                timeLocationEl.addAttribute("pattern", getId("pat", tl.getTimePatternId()));
            if (tl.getDatePatternId() != null && dp.add(tl.getDatePatternId())) {
                Element dateEl = classEl.addElement("date");
                dateEl.addAttribute("id", getId("dpat", String.valueOf(tl.getDatePatternId())));
                if (iShowNames)
                    dateEl.addAttribute("name", tl.getDatePatternName());
                dateEl.addAttribute("pattern", bitset2string(tl.getWeekCode()));
            }
            if (tl.getDatePatternPreference() != 0)
                timeLocationEl.addAttribute("datePref", String.valueOf(tl.getDatePatternPreference()));
            if (tl.getTimePatternId() == null && first) {
                if (iShowNames)
                    classEl.addAttribute("datePatternName", tl.getDatePatternName());
                classEl.addAttribute("dates", bitset2string(tl.getWeekCode()));
                first = false;
            }
            if (tl.getDatePatternId() != null) {
                timeLocationEl.addAttribute("date", getId("dpat", String.valueOf(tl.getDatePatternId())));
            }
            if ((lecture.isCommitted() || iSaveCurrent) && placement != null && placement.getTimeLocation().equals(tl))
                timeLocationEl.addAttribute("solution", "true");
            if (iSaveInitial && initialPlacement != null && initialPlacement.getTimeLocation().equals(tl))
                timeLocationEl.addAttribute("initial", "true");
            if (iSaveBest && bestPlacement != null && !bestPlacement.equals(placement) && bestPlacement.getTimeLocation().equals(tl))
                timeLocationEl.addAttribute("best", "true");
        }
    }
    for (InstructorConstraint ic : getModel().getInstructorConstraints()) {
        if (iShowNames || ic.isIgnoreDistances()) {
            Element instrEl = instructorsEl.addElement("instructor").addAttribute("id", getId("inst", ic.getResourceId()));
            if (iShowNames) {
                if (ic.getPuid() != null && ic.getPuid().length() > 0)
                    instrEl.addAttribute("puid", ic.getPuid());
                instrEl.addAttribute("name", ic.getName());
                if (ic.getType() != null && iShowNames)
                    instrEl.addAttribute("type", ic.getType().toString());
            }
            if (ic.isIgnoreDistances()) {
                instrEl.addAttribute("ignDist", "true");
            }
        }
        if (ic.getUnavailabilities() != null) {
            for (Placement placement : ic.getUnavailabilities()) {
                Lecture lecture = placement.variable();
                Element classEl = classElements.get(lecture.getClassId());
                classEl.addElement("instructor").addAttribute("id", getId("inst", ic.getResourceId())).addAttribute("solution", "true");
            }
        }
    }
    if (instructorsEl.elements().isEmpty())
        root.remove(instructorsEl);
    Element grConstraintsEl = root.addElement("groupConstraints");
    for (GroupConstraint gc : getModel().getGroupConstraints()) {
        Element grEl = grConstraintsEl.addElement("constraint").addAttribute("id", getId("gr", String.valueOf(gc.getId())));
        grEl.addAttribute("type", gc.getType().reference());
        grEl.addAttribute("pref", gc.getPrologPreference());
        for (Lecture l : gc.variables()) {
            grEl.addElement("class").addAttribute("id", getId("class", l.getClassId()));
        }
    }
    for (SpreadConstraint spread : getModel().getSpreadConstraints()) {
        Element grEl = grConstraintsEl.addElement("constraint").addAttribute("id", getId("gr", String.valueOf(spread.getId())));
        grEl.addAttribute("type", "SPREAD");
        grEl.addAttribute("pref", Constants.sPreferenceRequired);
        if (iShowNames)
            grEl.addAttribute("name", spread.getName());
        for (Lecture l : spread.variables()) {
            grEl.addElement("class").addAttribute("id", getId("class", l.getClassId()));
        }
    }
    for (Constraint<Lecture, Placement> c : getModel().constraints()) {
        if (c instanceof MinimizeNumberOfUsedRoomsConstraint) {
            Element grEl = grConstraintsEl.addElement("constraint").addAttribute("id", getId("gr", String.valueOf(c.getId())));
            grEl.addAttribute("type", "MIN_ROOM_USE");
            grEl.addAttribute("pref", Constants.sPreferenceRequired);
            for (Lecture l : c.variables()) {
                grEl.addElement("class").addAttribute("id", getId("class", l.getClassId()));
            }
        }
        if (c instanceof MinimizeNumberOfUsedGroupsOfTime) {
            Element grEl = grConstraintsEl.addElement("constraint").addAttribute("id", getId("gr", String.valueOf(c.getId())));
            grEl.addAttribute("type", ((MinimizeNumberOfUsedGroupsOfTime) c).getConstraintName());
            grEl.addAttribute("pref", Constants.sPreferenceRequired);
            for (Lecture l : c.variables()) {
                grEl.addElement("class").addAttribute("id", getId("class", l.getClassId()));
            }
        }
        if (c instanceof IgnoreStudentConflictsConstraint) {
            Element grEl = grConstraintsEl.addElement("constraint").addAttribute("id", getId("gr", String.valueOf(c.getId())));
            grEl.addAttribute("type", IgnoreStudentConflictsConstraint.REFERENCE);
            grEl.addAttribute("pref", Constants.sPreferenceRequired);
            for (Lecture l : c.variables()) {
                grEl.addElement("class").addAttribute("id", getId("class", l.getClassId()));
            }
        }
    }
    for (ClassLimitConstraint clc : getModel().getClassLimitConstraints()) {
        Element grEl = grConstraintsEl.addElement("constraint").addAttribute("id", getId("gr", String.valueOf(clc.getId())));
        grEl.addAttribute("type", "CLASS_LIMIT");
        grEl.addAttribute("pref", Constants.sPreferenceRequired);
        if (clc.getParentLecture() != null) {
            grEl.addElement("parentClass").addAttribute("id", getId("class", clc.getParentLecture().getClassId()));
        } else
            grEl.addAttribute("courseLimit", String.valueOf(clc.classLimit() - clc.getClassLimitDelta()));
        if (clc.getClassLimitDelta() != 0)
            grEl.addAttribute("delta", String.valueOf(clc.getClassLimitDelta()));
        if (iShowNames)
            grEl.addAttribute("name", clc.getName());
        for (Lecture l : clc.variables()) {
            grEl.addElement("class").addAttribute("id", getId("class", l.getClassId()));
        }
    }
    for (FlexibleConstraint gc : getModel().getFlexibleConstraints()) {
        Element flEl = grConstraintsEl.addElement("constraint").addAttribute("id", getId("gr", String.valueOf(gc.getId())));
        flEl.addAttribute("reference", gc.getReference());
        flEl.addAttribute("owner", gc.getOwner());
        flEl.addAttribute("pref", gc.getPrologPreference());
        flEl.addAttribute("type", gc.getType().toString());
        for (Lecture l : gc.variables()) {
            flEl.addElement("class").addAttribute("id", getId("class", l.getClassId()));
        }
    }
    HashMap<Student, List<String>> students = new HashMap<Student, List<String>>();
    for (Lecture lecture : vars) {
        for (Student student : lecture.students()) {
            List<String> enrls = students.get(student);
            if (enrls == null) {
                enrls = new ArrayList<String>();
                students.put(student, enrls);
            }
            enrls.add(getId("class", lecture.getClassId()));
        }
    }
    Element studentsEl = root.addElement("students");
    Element groupsEl = root.addElement("groups");
    Map<StudentGroup, Element> groups = new HashMap<StudentGroup, Element>();
    for (Student student : new TreeSet<Student>(students.keySet())) {
        Element stEl = studentsEl.addElement("student").addAttribute("id", getId("student", student.getId()));
        if (iShowNames) {
            if (student.getAcademicArea() != null)
                stEl.addAttribute("area", student.getAcademicArea());
            if (student.getAcademicClassification() != null)
                stEl.addAttribute("classification", student.getAcademicClassification());
            if (student.getMajor() != null)
                stEl.addAttribute("major", student.getMajor());
            if (student.getCurriculum() != null)
                stEl.addAttribute("curriculum", student.getCurriculum());
        }
        for (Map.Entry<Long, Double> entry : student.getOfferingsMap().entrySet()) {
            Long offeringId = entry.getKey();
            Double weight = entry.getValue();
            Element offEl = stEl.addElement("offering").addAttribute("id", getId("offering", offeringId.toString()));
            if (weight.doubleValue() != 1.0)
                offEl.addAttribute("weight", sStudentWeightFormat.format(weight));
            Double priority = student.getPriority(offeringId);
            if (priority != null)
                offEl.addAttribute("priority", priority.toString());
        }
        if (iExportStudentSectioning || getModel().nrUnassignedVariables(getAssignment()) == 0 || student.getOfferingsMap().isEmpty()) {
            List<String> lectures = students.get(student);
            Collections.sort(lectures);
            for (String classId : lectures) {
                stEl.addElement("class").addAttribute("id", classId);
            }
        }
        Map<Long, Set<Lecture>> canNotEnroll = student.canNotEnrollSections();
        if (canNotEnroll != null) {
            for (Set<Lecture> canNotEnrollLects : canNotEnroll.values()) {
                for (Iterator<Lecture> i3 = canNotEnrollLects.iterator(); i3.hasNext(); ) {
                    stEl.addElement("prohibited-class").addAttribute("id", getId("class", (i3.next()).getClassId()));
                }
            }
        }
        if (student.getCommitedPlacements() != null) {
            for (Placement placement : student.getCommitedPlacements()) {
                stEl.addElement("class").addAttribute("id", getId("class", placement.variable().getClassId()));
            }
        }
        if (student.getInstructor() != null)
            stEl.addAttribute("instructor", getId("inst", student.getInstructor().getResourceId()));
        for (StudentGroup group : student.getGroups()) {
            Element groupEl = groups.get(group);
            if (groupEl == null) {
                groupEl = groupsEl.addElement("group");
                groupEl.addAttribute("id", getId("group", group.getId()));
                if (group.getWeight() != 1.0)
                    groupEl.addAttribute("weight", String.valueOf(group.getWeight()));
                if (iShowNames && group.getName() != null)
                    groupEl.addAttribute("name", group.getName());
                groups.put(group, groupEl);
            }
            groupEl.addElement("student").addAttribute("id", getId("student", student.getId()));
        }
    }
    if (getModel().getProperties().getPropertyInt("MPP.GenTimePert", 0) > 0) {
        Element perturbationsEl = root.addElement("perturbations");
        int nrChanges = getModel().getProperties().getPropertyInt("MPP.GenTimePert", 0);
        List<Lecture> lectures = new ArrayList<Lecture>();
        while (lectures.size() < nrChanges) {
            Lecture lecture = ToolBox.random(getAssignment().assignedVariables());
            if (lecture.isCommitted() || lecture.timeLocations().size() <= 1 || lectures.contains(lecture))
                continue;
            Placement placement = getAssignment().getValue(lecture);
            TimeLocation tl = placement.getTimeLocation();
            perturbationsEl.addElement("class").addAttribute("id", getId("class", lecture.getClassId())).addAttribute("days", sDF[7].format(Long.parseLong(Integer.toBinaryString(tl.getDayCode())))).addAttribute("start", String.valueOf(tl.getStartSlot())).addAttribute("length", String.valueOf(tl.getLength()));
            lectures.add(lecture);
        }
    }
    for (Map.Entry<Long, String> entry : depts.entrySet()) {
        Long id = entry.getKey();
        String name = entry.getValue();
        if (iShowNames) {
            departmentsEl.addElement("department").addAttribute("id", getId("dept", id.toString())).addAttribute("name", name);
        }
    }
    if (departmentsEl.elements().isEmpty())
        root.remove(departmentsEl);
}
Also used : DiscouragedRoomConstraint(org.cpsolver.coursett.constraint.DiscouragedRoomConstraint) RoomConstraint(org.cpsolver.coursett.constraint.RoomConstraint) Lecture(org.cpsolver.coursett.model.Lecture) Configuration(org.cpsolver.coursett.model.Configuration) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) SpreadConstraint(org.cpsolver.coursett.constraint.SpreadConstraint) FlexibleConstraint(org.cpsolver.coursett.constraint.FlexibleConstraint) Placement(org.cpsolver.coursett.model.Placement) TreeSet(java.util.TreeSet) ArrayList(java.util.ArrayList) List(java.util.List) IgnoreStudentConflictsConstraint(org.cpsolver.coursett.constraint.IgnoreStudentConflictsConstraint) HashSet(java.util.HashSet) Student(org.cpsolver.coursett.model.Student) ClassLimitConstraint(org.cpsolver.coursett.constraint.ClassLimitConstraint) GroupConstraint(org.cpsolver.coursett.constraint.GroupConstraint) HashMap(java.util.HashMap) Map(java.util.Map) MinimizeNumberOfUsedGroupsOfTime(org.cpsolver.coursett.constraint.MinimizeNumberOfUsedGroupsOfTime) TreeSet(java.util.TreeSet) HashSet(java.util.HashSet) Set(java.util.Set) BitSet(java.util.BitSet) TimeLocation(org.cpsolver.coursett.model.TimeLocation) Element(org.dom4j.Element) DiscouragedRoomConstraint(org.cpsolver.coursett.constraint.DiscouragedRoomConstraint) RoomSharingModel(org.cpsolver.coursett.model.RoomSharingModel) MinimizeNumberOfUsedRoomsConstraint(org.cpsolver.coursett.constraint.MinimizeNumberOfUsedRoomsConstraint) RoomLocation(org.cpsolver.coursett.model.RoomLocation) Date(java.util.Date) InstructorConstraint(org.cpsolver.coursett.constraint.InstructorConstraint) DiscouragedRoomConstraint(org.cpsolver.coursett.constraint.DiscouragedRoomConstraint) ClassLimitConstraint(org.cpsolver.coursett.constraint.ClassLimitConstraint) IgnoreStudentConflictsConstraint(org.cpsolver.coursett.constraint.IgnoreStudentConflictsConstraint) InstructorConstraint(org.cpsolver.coursett.constraint.InstructorConstraint) MinimizeNumberOfUsedRoomsConstraint(org.cpsolver.coursett.constraint.MinimizeNumberOfUsedRoomsConstraint) SpreadConstraint(org.cpsolver.coursett.constraint.SpreadConstraint) GroupConstraint(org.cpsolver.coursett.constraint.GroupConstraint) Constraint(org.cpsolver.ifs.model.Constraint) FlexibleConstraint(org.cpsolver.coursett.constraint.FlexibleConstraint) RoomConstraint(org.cpsolver.coursett.constraint.RoomConstraint) StudentGroup(org.cpsolver.coursett.model.StudentGroup)

Aggregations

TimeLocation (org.cpsolver.coursett.model.TimeLocation)36 Placement (org.cpsolver.coursett.model.Placement)17 Lecture (org.cpsolver.coursett.model.Lecture)14 HashSet (java.util.HashSet)12 RoomLocation (org.cpsolver.coursett.model.RoomLocation)9 Constraint (org.cpsolver.ifs.model.Constraint)9 ArrayList (java.util.ArrayList)8 BitSet (java.util.BitSet)7 HashMap (java.util.HashMap)7 Element (org.dom4j.Element)7 WeakeningConstraint (org.cpsolver.ifs.model.WeakeningConstraint)6 DecimalFormat (java.text.DecimalFormat)5 List (java.util.List)4 Map (java.util.Map)4 TreeSet (java.util.TreeSet)4 RoomConstraint (org.cpsolver.coursett.constraint.RoomConstraint)4 GroupConstraint (org.cpsolver.coursett.constraint.GroupConstraint)3 InstructorConstraint (org.cpsolver.coursett.constraint.InstructorConstraint)3 SpreadConstraint (org.cpsolver.coursett.constraint.SpreadConstraint)3 Student (org.cpsolver.coursett.model.Student)3