Search in sources :

Example 96 with Comparator

use of java.util.Comparator in project cpsolver by UniTime.

the class InevitableStudentConflicts method enrollment2string.

/**
     * Convert given enrollment to a string (comma separated list of subpart
     * names and time assignments only)
     */
private static String enrollment2string(Enrollment enrollment) {
    StringBuffer sb = new StringBuffer();
    Collection<SctAssignment> assignments = enrollment.getAssignments();
    if (enrollment.isCourseRequest()) {
        assignments = new TreeSet<SctAssignment>(new Comparator<SctAssignment>() {

            @Override
            public int compare(SctAssignment a1, SctAssignment a2) {
                Section s1 = (Section) a1;
                Section s2 = (Section) a2;
                return s1.getSubpart().compareTo(s2.getSubpart());
            }
        });
        assignments.addAll(enrollment.getAssignments());
    }
    for (Iterator<? extends SctAssignment> i = assignments.iterator(); i.hasNext(); ) {
        SctAssignment a = i.next();
        if (a instanceof Section)
            sb.append(((Section) a).getSubpart().getName() + " ");
        if (a.getTime() != null)
            sb.append(a.getTime().getLongName(true));
        if (i.hasNext())
            sb.append(", ");
    }
    return sb.toString();
}
Also used : SctAssignment(org.cpsolver.studentsct.model.SctAssignment) Section(org.cpsolver.studentsct.model.Section) Comparator(java.util.Comparator)

Example 97 with Comparator

use of java.util.Comparator in project cpsolver by UniTime.

the class CourseConflictTable method createTable.

/**
     * Create report
     * 
     * @param assignment current assignment
     * @param includeLastLikeStudents
     *            true, if last-like students should be included (i.e.,
     *            {@link Student#isDummy()} is true)
     * @param includeRealStudents
     *            true, if real students should be included (i.e.,
     *            {@link Student#isDummy()} is false)
     * @param useAmPm use 12-hour format
     * @return report as comma separated text file
     */
@SuppressWarnings("unchecked")
public CSVFile createTable(Assignment<Request, Enrollment> assignment, boolean includeLastLikeStudents, boolean includeRealStudents, boolean useAmPm) {
    CSVFile csv = new CSVFile();
    csv.setHeader(new CSVFile.CSVField[] { new CSVFile.CSVField("UnasgnCrs"), new CSVFile.CSVField("ConflCrs"), new CSVFile.CSVField("NrStud"), new CSVFile.CSVField("StudWeight"), new CSVFile.CSVField("NoAlt"), new CSVFile.CSVField("Reason") });
    HashMap<Course, HashMap<Course, Object[]>> unassignedCourseTable = new HashMap<Course, HashMap<Course, Object[]>>();
    for (Request request : new ArrayList<Request>(getModel().unassignedVariables(assignment))) {
        if (request.getStudent().isDummy() && !includeLastLikeStudents)
            continue;
        if (!request.getStudent().isDummy() && !includeRealStudents)
            continue;
        if (request instanceof CourseRequest) {
            CourseRequest courseRequest = (CourseRequest) request;
            if (courseRequest.getStudent().isComplete(assignment))
                continue;
            List<Enrollment> values = courseRequest.values(assignment);
            SectionLimit limitConstraint = null;
            for (GlobalConstraint<Request, Enrollment> c : getModel().globalConstraints()) {
                if (c instanceof SectionLimit) {
                    limitConstraint = (SectionLimit) c;
                    break;
                }
            }
            if (limitConstraint == null) {
                limitConstraint = new SectionLimit(new DataProperties());
                limitConstraint.setModel(getModel());
            }
            List<Enrollment> availableValues = new ArrayList<Enrollment>(values.size());
            for (Enrollment enrollment : values) {
                if (!limitConstraint.inConflict(assignment, enrollment))
                    availableValues.add(enrollment);
            }
            if (availableValues.isEmpty()) {
                Course course = courseRequest.getCourses().get(0);
                HashMap<Course, Object[]> conflictCourseTable = unassignedCourseTable.get(course);
                if (conflictCourseTable == null) {
                    conflictCourseTable = new HashMap<Course, Object[]>();
                    unassignedCourseTable.put(course, conflictCourseTable);
                }
                Object[] weight = conflictCourseTable.get(course);
                double nrStud = (weight == null ? 0.0 : ((Double) weight[0]).doubleValue()) + 1.0;
                double nrStudW = (weight == null ? 0.0 : ((Double) weight[1]).doubleValue()) + request.getWeight();
                boolean noAlt = (weight == null ? true : ((Boolean) weight[2]).booleanValue());
                HashSet<String> expl = (weight == null ? new HashSet<String>() : (HashSet<String>) weight[3]);
                expl.add(course.getName() + " n/a");
                conflictCourseTable.put(course, new Object[] { new Double(nrStud), new Double(nrStudW), new Boolean(noAlt), expl });
            }
            for (Enrollment enrollment : availableValues) {
                Set<Enrollment> conflicts = getModel().conflictValues(assignment, enrollment);
                if (conflicts.isEmpty()) {
                    sLog.warn("Request " + courseRequest + " of student " + courseRequest.getStudent() + " not assigned, however, no conflicts were returned.");
                    assignment.assign(0, enrollment);
                    break;
                }
                Course course = null;
                for (Course c : courseRequest.getCourses()) {
                    if (c.getOffering().equals(enrollment.getConfig().getOffering())) {
                        course = c;
                        break;
                    }
                }
                if (course == null) {
                    sLog.warn("Course not found for request " + courseRequest + " of student " + courseRequest.getStudent() + ".");
                    continue;
                }
                HashMap<Course, Object[]> conflictCourseTable = unassignedCourseTable.get(course);
                if (conflictCourseTable == null) {
                    conflictCourseTable = new HashMap<Course, Object[]>();
                    unassignedCourseTable.put(course, conflictCourseTable);
                }
                for (Enrollment conflict : conflicts) {
                    if (conflict.variable() instanceof CourseRequest) {
                        CourseRequest conflictCourseRequest = (CourseRequest) conflict.variable();
                        Course conflictCourse = null;
                        for (Course c : conflictCourseRequest.getCourses()) {
                            if (c.getOffering().equals(conflict.getConfig().getOffering())) {
                                conflictCourse = c;
                                break;
                            }
                        }
                        if (conflictCourse == null) {
                            sLog.warn("Course not found for request " + conflictCourseRequest + " of student " + conflictCourseRequest.getStudent() + ".");
                            continue;
                        }
                        double weightThisConflict = request.getWeight() / availableValues.size() / conflicts.size();
                        double partThisConflict = 1.0 / availableValues.size() / conflicts.size();
                        Object[] weight = conflictCourseTable.get(conflictCourse);
                        double nrStud = (weight == null ? 0.0 : ((Double) weight[0]).doubleValue()) + partThisConflict;
                        double nrStudW = (weight == null ? 0.0 : ((Double) weight[1]).doubleValue()) + weightThisConflict;
                        boolean noAlt = (weight == null ? areInHardConfict(assignment, request, conflict.getRequest()) : ((Boolean) weight[2]).booleanValue());
                        HashSet<String> expl = (weight == null ? new HashSet<String>() : (HashSet<String>) weight[3]);
                        expl.addAll(explanations(assignment, enrollment, conflict, useAmPm));
                        conflictCourseTable.put(conflictCourse, new Object[] { new Double(nrStud), new Double(nrStudW), new Boolean(noAlt), expl });
                    }
                }
            }
        }
    }
    for (Map.Entry<Course, HashMap<Course, Object[]>> entry : unassignedCourseTable.entrySet()) {
        Course unassignedCourse = entry.getKey();
        HashMap<Course, Object[]> conflictCourseTable = entry.getValue();
        for (Map.Entry<Course, Object[]> entry2 : conflictCourseTable.entrySet()) {
            Course conflictCourse = entry2.getKey();
            Object[] weight = entry2.getValue();
            HashSet<String> expl = (HashSet<String>) weight[3];
            String explStr = "";
            for (Iterator<String> k = new TreeSet<String>(expl).iterator(); k.hasNext(); ) explStr += k.next() + (k.hasNext() ? "\n" : "");
            csv.addLine(new CSVFile.CSVField[] { new CSVFile.CSVField(unassignedCourse.getName()), new CSVFile.CSVField(conflictCourse.getName()), new CSVFile.CSVField(sDF.format(weight[0])), new CSVFile.CSVField(sDF.format(weight[1])), new CSVFile.CSVField(((Boolean) weight[2]).booleanValue() ? "Y" : "N"), new CSVFile.CSVField(explStr) });
        }
    }
    if (csv.getLines() != null)
        Collections.sort(csv.getLines(), new Comparator<CSVFile.CSVLine>() {

            @Override
            public int compare(CSVFile.CSVLine l1, CSVFile.CSVLine l2) {
                // int cmp =
                // l2.getField(3).toString().compareTo(l1.getField(3).toString());
                // if (cmp!=0) return cmp;
                int cmp = Double.compare(l2.getField(2).toDouble(), l1.getField(2).toDouble());
                if (cmp != 0)
                    return cmp;
                cmp = l1.getField(0).toString().compareTo(l2.getField(0).toString());
                if (cmp != 0)
                    return cmp;
                return l1.getField(1).toString().compareTo(l2.getField(1).toString());
            }
        });
    return csv;
}
Also used : CSVFile(org.cpsolver.ifs.util.CSVFile) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) DataProperties(org.cpsolver.ifs.util.DataProperties) Comparator(java.util.Comparator) Enrollment(org.cpsolver.studentsct.model.Enrollment) Course(org.cpsolver.studentsct.model.Course) HashSet(java.util.HashSet) Request(org.cpsolver.studentsct.model.Request) CourseRequest(org.cpsolver.studentsct.model.CourseRequest) GlobalConstraint(org.cpsolver.ifs.model.GlobalConstraint) CourseRequest(org.cpsolver.studentsct.model.CourseRequest) SectionLimit(org.cpsolver.studentsct.constraint.SectionLimit) HashMap(java.util.HashMap) Map(java.util.Map)

Example 98 with Comparator

use of java.util.Comparator in project cpsolver by UniTime.

the class DistanceConflictTable method createTable.

/**
     * Create report
     * 
     * @param assignment current assignment
     * @param includeLastLikeStudents
     *            true, if last-like students should be included (i.e.,
     *            {@link Student#isDummy()} is true)
     * @param includeRealStudents
     *            true, if real students should be included (i.e.,
     *            {@link Student#isDummy()} is false)
     * @param useAmPm use 12-hour format
     * @return report as comma separated text file
     */
public CSVFile createTable(Assignment<Request, Enrollment> assignment, boolean includeLastLikeStudents, boolean includeRealStudents, boolean useAmPm) {
    CSVFile csv = new CSVFile();
    csv.setHeader(new CSVFile.CSVField[] { new CSVFile.CSVField("Course"), new CSVFile.CSVField("Total\nConflicts"), new CSVFile.CSVField("Class"), new CSVFile.CSVField("Meeting Time"), new CSVFile.CSVField("Room"), new CSVFile.CSVField("Distance\nConflicts"), new CSVFile.CSVField("% of Total\nConflicts"), new CSVFile.CSVField("Conflicting\nClass"), new CSVFile.CSVField("Conflicting\nMeeting Time"), new CSVFile.CSVField("Conflicting\nRoom"), new CSVFile.CSVField("Distance [m]"), new CSVFile.CSVField("Distance [min]"), new CSVFile.CSVField("Joined\nConflicts"), new CSVFile.CSVField("% of Total\nConflicts") });
    Set<Conflict> confs = new HashSet<Conflict>();
    for (Request r1 : getModel().variables()) {
        Enrollment e1 = assignment.getValue(r1);
        if (e1 == null || !(r1 instanceof CourseRequest))
            continue;
        confs.addAll(iDC.conflicts(e1));
        for (Request r2 : r1.getStudent().getRequests()) {
            Enrollment e2 = assignment.getValue(r2);
            if (e2 == null || r1.getId() >= r2.getId() || !(r2 instanceof CourseRequest))
                continue;
            confs.addAll(iDC.conflicts(e1, e2));
        }
    }
    HashMap<Course, Set<Long>> totals = new HashMap<Course, Set<Long>>();
    HashMap<CourseSection, Map<CourseSection, Double>> conflictingPairs = new HashMap<CourseSection, Map<CourseSection, Double>>();
    HashMap<CourseSection, Set<Long>> sectionOverlaps = new HashMap<CourseSection, Set<Long>>();
    for (Conflict conflict : confs) {
        if (conflict.getStudent().isDummy() && !includeLastLikeStudents)
            continue;
        if (!conflict.getStudent().isDummy() && !includeRealStudents)
            continue;
        Section s1 = conflict.getS1(), s2 = conflict.getS2();
        Course c1 = null, c2 = null;
        Request r1 = null, r2 = null;
        for (Request request : conflict.getStudent().getRequests()) {
            Enrollment enrollment = assignment.getValue(request);
            if (enrollment == null || !enrollment.isCourseRequest())
                continue;
            if (c1 == null && enrollment.getAssignments().contains(s1)) {
                c1 = enrollment.getCourse();
                r1 = request;
                Set<Long> total = totals.get(enrollment.getCourse());
                if (total == null) {
                    total = new HashSet<Long>();
                    totals.put(enrollment.getCourse(), total);
                }
                total.add(enrollment.getStudent().getId());
            }
            if (c2 == null && enrollment.getAssignments().contains(s2)) {
                c2 = enrollment.getCourse();
                r2 = request;
                Set<Long> total = totals.get(enrollment.getCourse());
                if (total == null) {
                    total = new HashSet<Long>();
                    totals.put(enrollment.getCourse(), total);
                }
                total.add(enrollment.getStudent().getId());
            }
        }
        if (c1 == null) {
            sLog.error("Unable to find a course for " + s1);
            continue;
        }
        if (c2 == null) {
            sLog.error("Unable to find a course for " + s2);
            continue;
        }
        CourseSection a = new CourseSection(c1, s1);
        CourseSection b = new CourseSection(c2, s2);
        Set<Long> total = sectionOverlaps.get(a);
        if (total == null) {
            total = new HashSet<Long>();
            sectionOverlaps.put(a, total);
        }
        total.add(r1.getStudent().getId());
        Map<CourseSection, Double> pair = conflictingPairs.get(a);
        if (pair == null) {
            pair = new HashMap<CourseSection, Double>();
            conflictingPairs.put(a, pair);
        }
        Double prev = pair.get(b);
        pair.put(b, r2.getWeight() + (prev == null ? 0.0 : prev.doubleValue()));
        total = sectionOverlaps.get(b);
        if (total == null) {
            total = new HashSet<Long>();
            sectionOverlaps.put(b, total);
        }
        total.add(r2.getStudent().getId());
        pair = conflictingPairs.get(b);
        if (pair == null) {
            pair = new HashMap<CourseSection, Double>();
            conflictingPairs.put(b, pair);
        }
        prev = pair.get(a);
        pair.put(a, r1.getWeight() + (prev == null ? 0.0 : prev.doubleValue()));
    }
    Comparator<Course> courseComparator = new Comparator<Course>() {

        @Override
        public int compare(Course a, Course b) {
            int cmp = a.getName().compareTo(b.getName());
            if (cmp != 0)
                return cmp;
            return a.getId() < b.getId() ? -1 : a.getId() == b.getId() ? 0 : 1;
        }
    };
    Comparator<Section> sectionComparator = new Comparator<Section>() {

        @Override
        public int compare(Section a, Section b) {
            int cmp = a.getSubpart().getConfig().getOffering().getName().compareTo(b.getSubpart().getConfig().getOffering().getName());
            if (cmp != 0)
                return cmp;
            cmp = a.getSubpart().getInstructionalType().compareTo(b.getSubpart().getInstructionalType());
            // cmp = a.getName().compareTo(b.getName());
            if (cmp != 0)
                return cmp;
            return a.getId() < b.getId() ? -1 : a.getId() == b.getId() ? 0 : 1;
        }
    };
    TreeSet<Course> courses = new TreeSet<Course>(courseComparator);
    courses.addAll(totals.keySet());
    for (Course course : courses) {
        Set<Long> total = totals.get(course);
        TreeSet<Section> sections = new TreeSet<Section>(sectionComparator);
        for (Map.Entry<CourseSection, Set<Long>> entry : sectionOverlaps.entrySet()) if (course.equals(entry.getKey().getCourse()))
            sections.add(entry.getKey().getSection());
        boolean firstCourse = true;
        for (Section section : sections) {
            Set<Long> sectionOverlap = sectionOverlaps.get(new CourseSection(course, section));
            Map<CourseSection, Double> pair = conflictingPairs.get(new CourseSection(course, section));
            boolean firstClass = true;
            String rooms = "";
            if (section.getRooms() != null)
                for (RoomLocation r : section.getRooms()) {
                    if (!rooms.isEmpty())
                        rooms += "\n";
                    rooms += r.getName();
                }
            for (CourseSection other : new TreeSet<CourseSection>(pair.keySet())) {
                List<CSVFile.CSVField> line = new ArrayList<CSVFile.CSVField>();
                line.add(new CSVFile.CSVField(firstCourse && firstClass ? course.getName() : ""));
                line.add(new CSVFile.CSVField(firstCourse && firstClass ? total.size() : ""));
                line.add(new CSVFile.CSVField(firstClass ? section.getSubpart().getName() + " " + section.getName(course.getId()) : ""));
                line.add(new CSVFile.CSVField(firstClass ? section.getTime() == null ? "" : section.getTime().getDayHeader() + " " + section.getTime().getStartTimeHeader(useAmPm) + " - " + section.getTime().getEndTimeHeader(useAmPm) : ""));
                line.add(new CSVFile.CSVField(firstClass ? rooms : ""));
                line.add(new CSVFile.CSVField(firstClass && sectionOverlap != null ? String.valueOf(sectionOverlap.size()) : ""));
                line.add(new CSVFile.CSVField(firstClass && sectionOverlap != null ? sDF2.format(((double) sectionOverlap.size()) / total.size()) : ""));
                line.add(new CSVFile.CSVField(other.getCourse().getName() + " " + other.getSection().getSubpart().getName() + " " + other.getSection().getName(other.getCourse().getId())));
                line.add(new CSVFile.CSVField(other.getSection().getTime().getDayHeader() + " " + other.getSection().getTime().getStartTimeHeader(useAmPm) + " - " + other.getSection().getTime().getEndTimeHeader(useAmPm)));
                String or = "";
                if (other.getSection().getRooms() != null)
                    for (RoomLocation r : other.getSection().getRooms()) {
                        if (!or.isEmpty())
                            or += "\n";
                        or += r.getName();
                    }
                line.add(new CSVFile.CSVField(or));
                line.add(new CSVFile.CSVField(sDF2.format(Placement.getDistanceInMeters(iDM, section.getPlacement(), other.getSection().getPlacement()))));
                line.add(new CSVFile.CSVField(String.valueOf(Placement.getDistanceInMinutes(iDM, section.getPlacement(), other.getSection().getPlacement()))));
                line.add(new CSVFile.CSVField(sDF1.format(pair.get(other))));
                line.add(new CSVFile.CSVField(sDF2.format(pair.get(other) / total.size())));
                csv.addLine(line);
                firstClass = false;
            }
            firstCourse = false;
        }
        csv.addLine();
    }
    return csv;
}
Also used : CSVFile(org.cpsolver.ifs.util.CSVFile) Set(java.util.Set) TreeSet(java.util.TreeSet) HashSet(java.util.HashSet) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Comparator(java.util.Comparator) TreeSet(java.util.TreeSet) Enrollment(org.cpsolver.studentsct.model.Enrollment) Course(org.cpsolver.studentsct.model.Course) HashSet(java.util.HashSet) RoomLocation(org.cpsolver.coursett.model.RoomLocation) CourseRequest(org.cpsolver.studentsct.model.CourseRequest) Request(org.cpsolver.studentsct.model.Request) Section(org.cpsolver.studentsct.model.Section) CourseRequest(org.cpsolver.studentsct.model.CourseRequest) Conflict(org.cpsolver.studentsct.extension.DistanceConflict.Conflict) DistanceConflict(org.cpsolver.studentsct.extension.DistanceConflict) HashMap(java.util.HashMap) Map(java.util.Map)

Example 99 with Comparator

use of java.util.Comparator in project voltdb by VoltDB.

the class TableSorter method getComparator.

protected Comparator getComparator(int column) {
    Class columnType = tableModel.getColumnClass(column);
    Comparator comparator = (Comparator) columnComparators.get(columnType);
    if (comparator != null) {
        return comparator;
    }
    if (Comparable.class.isAssignableFrom(columnType)) {
        return COMPARABLE_COMPARATOR;
    }
    return LEXICAL_COMPARATOR;
}
Also used : Comparator(java.util.Comparator)

Example 100 with Comparator

use of java.util.Comparator in project voltdb by VoltDB.

the class ImmutableSetMultimap method readObject.

// java.io.ObjectInputStream
@GwtIncompatible
// Serialization type safety is at the caller's mercy.
@SuppressWarnings("unchecked")
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
    stream.defaultReadObject();
    Comparator<Object> valueComparator = (Comparator<Object>) stream.readObject();
    int keyCount = stream.readInt();
    if (keyCount < 0) {
        throw new InvalidObjectException("Invalid key count " + keyCount);
    }
    ImmutableMap.Builder<Object, ImmutableSet<Object>> builder = ImmutableMap.builder();
    int tmpSize = 0;
    for (int i = 0; i < keyCount; i++) {
        Object key = stream.readObject();
        int valueCount = stream.readInt();
        if (valueCount <= 0) {
            throw new InvalidObjectException("Invalid value count " + valueCount);
        }
        ImmutableSet.Builder<Object> valuesBuilder = valuesBuilder(valueComparator);
        for (int j = 0; j < valueCount; j++) {
            valuesBuilder.add(stream.readObject());
        }
        ImmutableSet<Object> valueSet = valuesBuilder.build();
        if (valueSet.size() != valueCount) {
            throw new InvalidObjectException("Duplicate key-value pairs exist for key " + key);
        }
        builder.put(key, valueSet);
        tmpSize += valueCount;
    }
    ImmutableMap<Object, ImmutableSet<Object>> tmpMap;
    try {
        tmpMap = builder.build();
    } catch (IllegalArgumentException e) {
        throw (InvalidObjectException) new InvalidObjectException(e.getMessage()).initCause(e);
    }
    FieldSettersHolder.MAP_FIELD_SETTER.set(this, tmpMap);
    FieldSettersHolder.SIZE_FIELD_SETTER.set(this, tmpSize);
    FieldSettersHolder.EMPTY_SET_FIELD_SETTER.set(this, emptySet(valueComparator));
}
Also used : InvalidObjectException(java.io.InvalidObjectException) Comparator(java.util.Comparator) GwtIncompatible(com.google_voltpatches.common.annotations.GwtIncompatible)

Aggregations

Comparator (java.util.Comparator)322 ArrayList (java.util.ArrayList)123 List (java.util.List)58 Test (org.junit.Test)58 HashMap (java.util.HashMap)50 IOException (java.io.IOException)36 Map (java.util.Map)35 File (java.io.File)24 HashSet (java.util.HashSet)23 TreeSet (java.util.TreeSet)20 Set (java.util.Set)18 Iterator (java.util.Iterator)15 Method (java.lang.reflect.Method)14 Collections (java.util.Collections)14 Date (java.util.Date)14 TreeMap (java.util.TreeMap)14 ArrayMap (android.util.ArrayMap)12 Collection (java.util.Collection)11 LinkedList (java.util.LinkedList)11 SimpleDateFormat (java.text.SimpleDateFormat)10