    001package org.cpsolver.studentsct.model;
    002
    003import java.text.DecimalFormat;
    004import java.util.ArrayList;
    005import java.util.Collection;
    006import java.util.Collections;
    007import java.util.HashMap;
    008import java.util.HashSet;
    009import java.util.List;
    010import java.util.Map;
    011import java.util.Set;
    012import java.util.TreeSet;
    013
    014import org.cpsolver.coursett.model.TimeLocation;
    015import org.cpsolver.ifs.assignment.Assignment;
    016import org.cpsolver.ifs.assignment.AssignmentComparator;
    017import org.cpsolver.ifs.util.ToolBox;
    018import org.cpsolver.studentsct.StudentSectioningModel;
    019import org.cpsolver.studentsct.constraint.ConfigLimit;
    020import org.cpsolver.studentsct.constraint.CourseLimit;
    021import org.cpsolver.studentsct.constraint.LinkedSections;
    022import org.cpsolver.studentsct.constraint.SectionLimit;
    023import org.cpsolver.studentsct.reservation.Reservation;
    024import org.cpsolver.studentsct.reservation.Restriction;
    025
    026
    027/**
    028 * Representation of a request of a student for one or more course. A student
    029 * requests one of the given courses, preferably the first one. <br>
    030 * <br>
    031 *
    032 * @version StudentSct 1.3 (Student Sectioning)<br>
    033 *          Copyright (C) 2007 - 2014 Tomáš Müller<br>
    034 *          <a href="mailto:muller@unitime.org">muller@unitime.org</a><br>
    035 *          <a href="http://muller.unitime.org">http://muller.unitime.org</a><br>
    036 * <br>
    037 *          This library is free software; you can redistribute it and/or modify
    038 *          it under the terms of the GNU Lesser General Public License as
    039 *          published by the Free Software Foundation; either version 3 of the
    040 *          License, or (at your option) any later version. <br>
    041 * <br>
    042 *          This library is distributed in the hope that it will be useful, but
    043 *          WITHOUT ANY WARRANTY; without even the implied warranty of
    044 *          MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
    045 *          Lesser General Public License for more details. <br>
    046 * <br>
    047 *          You should have received a copy of the GNU Lesser General Public
    048 *          License along with this library; if not see
    049 *          <a href='http://www.gnu.org/licenses/'>http://www.gnu.org/licenses/</a>.
    050 */
    051public class CourseRequest extends Request {
    052    private static DecimalFormat sDF = new DecimalFormat("0.000");
    053    private List<Course> iCourses = null;
    054    private Set<Choice> iWaitlistedChoices = new HashSet<Choice>();
    055    private Set<Choice> iSelectedChoices = new HashSet<Choice>();
    056    private Set<Choice> iRequiredChoices = new HashSet<Choice>();
    057    private boolean iWaitlist = false;
    058    private Long iTimeStamp = null;
    059    private Double iCachedMinPenalty = null, iCachedMaxPenalty = null;
    060    public static boolean sSameTimePrecise = false;
    061    private Set<RequestGroup> iRequestGroups = new HashSet<RequestGroup>();
    062    private RequestPriority iPriority = RequestPriority.Normal;
    063    private Enrollment iFixed = null;
    064
    065    /**
    066     * Constructor
    067     *
    068     * @param id
    069     *            request unique id
    070     * @param priority
    071     *            request priority
    072     * @param alternative
    073     *            true if the request is alternative (alternative request can be
    074     *            assigned instead of a non-alternative course requests, if it
    075     *            is left unassigned)
    076     * @param student
    077     *            appropriate student
    078     * @param courses
    079     *            list of requested courses (in the correct order -- first is
    080     *            the requested course, second is the first alternative, etc.)
    081     * @param waitlist
    082     *            time stamp of the request if the student can be put on a wait-list (no alternative
    083     *            course request will be given instead)
    084     * @param critical
    085     *            is the course request is critical for the student in order to move forward in their degree
    086     * @param timeStamp request time stamp
    087     */
    088    public CourseRequest(long id, int priority, boolean alternative, Student student, java.util.List<Course> courses, boolean waitlist, boolean critical, Long timeStamp) {
    089        super(id, priority, alternative, student);
    090        iCourses = new ArrayList<Course>(courses);
    091        for (Course course: iCourses)
    092            course.getRequests().add(this);
    093        iWaitlist = waitlist;
    094        iPriority = (critical ? RequestPriority.Critical : RequestPriority.Normal);
    095        iTimeStamp = timeStamp;
    096    }
    097
    098    /**
    099     * Constructor
    100     *
    101     * @param id
    102     *            request unique id
    103     * @param priority
    104     *            request priority
    105     * @param alternative
    106     *            true if the request is alternative (alternative request can be
    107     *            assigned instead of a non-alternative course requests, if it
    108     *            is left unassigned)
    109     * @param student
    110     *            appropriate student
    111     * @param courses
    112     *            list of requested courses (in the correct order -- first is
    113     *            the requested course, second is the first alternative, etc.)
    114     * @param waitlist
    115     *            time stamp of the request if the student can be put on a wait-list (no alternative
    116     *            course request will be given instead)
    117     * @param importance
    118     *            request priority
    119     * @param timeStamp request time stamp
    120     */
    121    public CourseRequest(long id, int priority, boolean alternative, Student student, java.util.List<Course> courses, boolean waitlist, RequestPriority importance, Long timeStamp) {
    122        super(id, priority, alternative, student);
    123        iCourses = new ArrayList<Course>(courses);
    124        for (Course course: iCourses)
    125            course.getRequests().add(this);
    126        iWaitlist = waitlist;
    127        iPriority = importance;
    128        iTimeStamp = timeStamp;
    129    }
    130
    131    /**
    132     * Constructor
    133     *
    134     * @param id
    135     *            request unique id
    136     * @param priority
    137     *            request priority
    138     * @param alternative
    139     *            true if the request is alternative (alternative request can be
    140     *            assigned instead of a non-alternative course requests, if it
    141     *            is left unassigned)
    142     * @param student
    143     *            appropriate student
    144     * @param courses
    145     *            list of requested courses (in the correct order -- first is
    146     *            the requested course, second is the first alternative, etc.)
    147     * @param waitlist
    148     *            time stamp of the request if the student can be put on a wait-list (no alternative
    149     *            course request will be given instead)
    150     * @param timeStamp request time stamp
    151     */
    152    public CourseRequest(long id, int priority, boolean alternative, Student student, java.util.List<Course> courses, boolean waitlist, Long timeStamp) {
    153        this(id, priority, alternative, student, courses, waitlist, false, timeStamp);
    154    }
    155
    156    /**
    157     * List of requested courses (in the correct order -- first is the requested
    158     * course, second is the first alternative, etc.)
    159     * @return requested course offerings
    160     */
    161    public List<Course> getCourses() {
    162        return iCourses;
    163    }
    164
    165    /**
    166     * Create enrollment for the given list of sections. The list of sections
    167     * needs to be correct, i.e., a section for each subpart of a configuration
    168     * of one of the requested courses.
    169     * @param sections selected sections
    170     * @param reservation selected reservation
    171     * @return enrollment
    172     */
    173    public Enrollment createEnrollment(Set<? extends SctAssignment> sections, Reservation reservation) {
    174        if (sections == null || sections.isEmpty())
    175            return null;
    176        Config config = ((Section) sections.iterator().next()).getSubpart().getConfig();
    177        Course course = null;
    178        for (Course c: iCourses) {
    179            if (c.getOffering().getConfigs().contains(config)) {
    180                course = c;
    181                break;
    182            }
    183        }
    184        return new Enrollment(this, iCourses.indexOf(course), course, config, sections, reservation);
    185    }
    186
    187    /**
    188     * Create enrollment for the given list of sections. The list of sections
    189     * needs to be correct, i.e., a section for each subpart of a configuration
    190     * of one of the requested courses.
    191     * @param course selected course
    192     * @param sections selected sections
    193     * @param reservation selected reservation
    194     * @return enrollment
    195     */
    196    public Enrollment createEnrollment(Course course, Set<? extends SctAssignment> sections, Reservation reservation) {
    197        if (sections == null || sections.isEmpty())
    198            return null;
    199        Config config = ((Section) sections.iterator().next()).getSubpart().getConfig();
    200        return new Enrollment(this, iCourses.indexOf(course), course, config, sections, reservation);
    201    }
    202
    203    /**
    204     * Create enrollment for the given list of sections. The list of sections
    205     * needs to be correct, i.e., a section for each subpart of a configuration
    206     * of one of the requested courses.
    207     * @param assignment current assignment (to guess the reservation)
    208     * @param sections selected sections
    209     * @return enrollment
    210     */
    211    public Enrollment createEnrollment(Assignment<Request, Enrollment> assignment, Set<? extends SctAssignment> sections) {
    212        Enrollment ret = createEnrollment(sections, null);
    213        ret.guessReservation(assignment, true);
    214        return ret;
    215
    216    }
    217
    218    /**
    219     * Maximal domain size (i.e., number of enrollments of a course request), -1 if there is no limit.
    220     * @return maximal domain size, -1 if unlimited
    221     */
    222    protected int getMaxDomainSize() {
    223        StudentSectioningModel model = (StudentSectioningModel) getModel();
    224        return model == null ? -1 : model.getMaxDomainSize();
    225    }
    226
    227    /**
    228     * Return all possible enrollments.
    229     */
    230    @Override
    231    public List<Enrollment> computeEnrollments(Assignment<Request, Enrollment> assignment) {
    232        List<Enrollment> ret = new ArrayList<Enrollment>();
    233        if (isFixed()) {
    234            ret.add(getFixedValue());
    235            return ret;
    236        }
    237        if (getInitialAssignment() != null && getModel() != null && ((StudentSectioningModel)getModel()).isMPP() && ((StudentSectioningModel)getModel()).getKeepInitialAssignments()) {
    238            ret.add(getInitialAssignment());
    239            return ret;
    240        }
    241        int idx = 0;
    242        for (Course course : iCourses) {
    243            for (Config config : course.getOffering().getConfigs()) {
    244                computeEnrollments(assignment, ret, idx, 0, course, config, new HashSet<Section>(), 0, false, false,
    245                        false, false, getMaxDomainSize() <= 0 ? -1 : ret.size() + getMaxDomainSize());
    246            }
    247            idx++;
    248        }
    249        return ret;
    250    }
    251
    252    /**
    253     * Return a subset of all enrollments -- randomly select only up to
    254     * limitEachConfig enrollments of each config.
    255     * @param assignment current assignment
    256     * @param limitEachConfig maximal number of enrollments in each configuration
    257     * @return computed enrollments
    258     */
    259    public List<Enrollment> computeRandomEnrollments(Assignment<Request, Enrollment> assignment, int limitEachConfig) {
    260        List<Enrollment> ret = new ArrayList<Enrollment>();
    261        if (isFixed()) {
    262            ret.add(getFixedValue());
    263            return ret;
    264        }
    265        if (getInitialAssignment() != null && getModel() != null && ((StudentSectioningModel)getModel()).isMPP() && ((StudentSectioningModel)getModel()).getKeepInitialAssignments()) {
    266            ret.add(getInitialAssignment());
    267            return ret;
    268        }
    269        int idx = 0;
    270        for (Course course : iCourses) {
    271            for (Config config : course.getOffering().getConfigs()) {
    272                computeEnrollments(assignment, ret, idx, 0, course, config, new HashSet<Section>(), 0, false, false,
    273                        false, true, (limitEachConfig <= 0 ? limitEachConfig : ret.size() + limitEachConfig));
    274            }
    275            idx++;
    276        }
    277        return ret;
    278    }
    279
    280    /**
    281     * Return true if the both sets of sections contain sections of the same
    282     * subparts, and each pair of sections of the same subpart is offered at the
    283     * same time.
    284     */
    285    private boolean sameTimes(Set<Section> sections1, Set<Section> sections2) {
    286        for (Section s1 : sections1) {
    287            Section s2 = null;
    288            for (Section s : sections2) {
    289                if (s.getSubpart().equals(s1.getSubpart())) {
    290                    s2 = s;
    291                    break;
    292                }
    293            }
    294            if (s2 == null)
    295                return false;
    296            if (!ToolBox.equals(s1.getTime(), s2.getTime()))
    297                return false;
    298        }
    299        return true;
    300    }
    301
    302    /**
    303     * Recursive computation of enrollments
    304     *
    305     * @param enrollments
    306     *            list of enrollments to be returned
    307     * @param priority
    308     *            zero for the course, one for the first alternative, two for the second alternative
    309     * @param penalty
    310     *            penalty of the selected sections
    311     * @param course
    312     *            selected course
    313     * @param config
    314     *            selected configuration
    315     * @param sections
    316     *            sections selected so far
    317     * @param idx
    318     *            index of the subparts (a section of 0..idx-1 subparts has been
    319     *            already selected)
    320     * @param availableOnly
    321     *            only use available sections
    322     * @param skipSameTime
    323     *            for each possible times, pick only one section
    324     * @param selectedOnly
    325     *            select only sections that are selected (
    326     *            {@link CourseRequest#isSelected(Section)} is true)
    327     * @param random
    328     *            pick sections in a random order (useful when limit is used)
    329     * @param limit
    330     *            when above zero, limit the number of selected enrollments to
    331     *            this limit
    332     * @param ignoreDisabled
    333     *            are sections that are disabled for student scheduling allowed to be used
    334     * @param reservations
    335     *            list of applicable reservations
    336     */
    337    private void computeEnrollments(Assignment<Request, Enrollment> assignment, Collection<Enrollment> enrollments, int priority, double penalty, Course course, Config config,
    338            HashSet<Section> sections, int idx, boolean availableOnly, boolean skipSameTime, boolean selectedOnly,
    339            boolean random, int limit) {
    340        if (limit > 0 && enrollments.size() >= limit)
    341            return;
    342        if (idx == 0) { // run only once for each configuration
    343            if (isNotAllowed(course, config)) return;
    344            boolean canOverLimit = false;
    345            if (availableOnly) {
    346                for (Reservation r: getReservations(course)) {
    347                    if (!r.canBatchAssignOverLimit()) continue;
    348                    if (r.neverIncluded()) continue;
    349                    if (!r.getConfigs().isEmpty() && !r.getConfigs().contains(config)) continue;
    350                    if (r.getReservedAvailableSpace(assignment, this) < getWeight()) continue;
    351                    canOverLimit = true; break;
    352                }
    353            }
    354            if (!canOverLimit) {
    355                if (availableOnly && config.getLimit() >= 0 && ConfigLimit.getEnrollmentWeight(assignment, config, this) > config.getLimit())
    356                    return;
    357                if (availableOnly && course.getLimit() >= 0 && CourseLimit.getEnrollmentWeight(assignment, course, this) > course.getLimit())
    358                    return;
    359                if (config.getOffering().hasReservations()) {
    360                    boolean hasReservation = false, hasConfigReservation = false, reservationMustBeUsed = false;
    361                    for (Reservation r: getReservations(course)) {
    362                        if (r.mustBeUsed()) reservationMustBeUsed = true;
    363                        if (availableOnly && r.getReservedAvailableSpace(assignment, this) < getWeight()) continue;
    364                        if (r.neverIncluded()) {
    365                        } else if (r.getConfigs().isEmpty()) {
    366                            hasReservation = true;
    367                        } else if (r.getConfigs().contains(config)) {
    368                            hasReservation = true;
    369                            hasConfigReservation = true;
    370                        }
    371                    }
    372                    if (!hasConfigReservation && config.getTotalUnreservedSpace() < getWeight())
    373                        return;
    374                    if (!hasReservation && config.getOffering().getTotalUnreservedSpace() < getWeight())
    375                        return;
    376                    if (availableOnly && !hasReservation && config.getOffering().getUnreservedSpace(assignment, this) < getWeight())
    377                        return;
    378                    if (availableOnly && !hasConfigReservation && config.getUnreservedSpace(assignment, this) < getWeight())
    379                        return;
    380                    if (!hasReservation && reservationMustBeUsed)
    381                        return;
    382                }
    383            }
    384        }
    385        if (config.getSubparts().size() == idx) {
    386            if (skipSameTime && sSameTimePrecise) {
    387                boolean waitListedOrSelected = false;
    388                if (!getSelectedChoices().isEmpty() || !getWaitlistedChoices().isEmpty()) {
    389                    for (Section section : sections) {
    390                        if (isWaitlisted(section) || isSelected(section)) {
    391                            waitListedOrSelected = true;
    392                            break;
    393                        }
    394                    }
    395                }
    396                if (!waitListedOrSelected) {
    397                    for (Enrollment enrollment : enrollments) {
    398                        if (sameTimes(enrollment.getSections(), sections))
    399                            return;
    400                    }
    401                }
    402            }
    403            Enrollment e = new Enrollment(this, priority, course, config, new HashSet<SctAssignment>(sections), null);
    404            if (isNotAllowed(e)) {
    405            } else if (!config.getOffering().hasReservations()) {
    406                enrollments.add(e);
    407            } else {
    408                boolean mustHaveReservation = config.getOffering().getTotalUnreservedSpace() < getWeight();
    409                boolean mustHaveConfigReservation = config.getTotalUnreservedSpace() < getWeight();
    410                boolean mustHaveSectionReservation = false;
    411                boolean containDisabledSection = false;
    412                for (Section s: sections) {
    413                    if (s.getTotalUnreservedSpace() < getWeight()) {
    414                        mustHaveSectionReservation = true;
    415                    }
    416                    if (!getStudent().isAllowDisabled() && !s.isEnabled()) {
    417                        containDisabledSection = true;
    418                    }
    419                }
    420                boolean canOverLimit = false;
    421                if (availableOnly) {
    422                    for (Reservation r: getReservations(course)) {
    423                        if (!r.canBatchAssignOverLimit() || !r.isIncluded(e)) continue;
    424                        if (r.getReservedAvailableSpace(assignment, this) < getWeight()) continue;
    425                        if (containDisabledSection && !r.isAllowDisabled()) continue;
    426                        enrollments.add(new Enrollment(this, priority, null, config, new HashSet<SctAssignment>(sections), r));
    427                        canOverLimit = true;
    428                    }
    429                }
    430                if (!canOverLimit) {
    431                    boolean reservationMustBeUsed = false;
    432                    reservations: for (Reservation r: (availableOnly ? getSortedReservations(assignment, course) : getReservations(course))) {
    433                        if (r.mustBeUsed()) reservationMustBeUsed = true;
    434                        if (!r.isIncluded(e)) continue;
    435                        if (availableOnly && r.getReservedAvailableSpace(assignment, this) < getWeight()) continue;
    436                        if (mustHaveConfigReservation && r.getConfigs().isEmpty()) continue;
    437                        if (mustHaveSectionReservation)
    438                            for (Section s: sections)
    439                                if (r.getSections(s.getSubpart()) == null && s.getTotalUnreservedSpace() < getWeight()) continue reservations;
    440                        if (containDisabledSection && !r.isAllowDisabled()) continue;
    441                        enrollments.add(new Enrollment(this, priority, null, config, new HashSet<SctAssignment>(sections), r));
    442                        if (availableOnly) return; // only one available reservation suffice (the best matching one)
    443                    }
    444                    // a case w/o reservation
    445                    if (!(mustHaveReservation || mustHaveConfigReservation || mustHaveSectionReservation) &&
    446                        !(availableOnly && config.getOffering().getUnreservedSpace(assignment, this) < getWeight()) &&
    447                        !reservationMustBeUsed && !containDisabledSection) {
    448                        enrollments.add(new Enrollment(this, priority, !getReservations(course).isEmpty(), null, config, new HashSet<SctAssignment>(sections), null));
    449                    }
    450                }
    451            }
    452        } else {
    453            Subpart subpart = config.getSubparts().get(idx);
    454            HashSet<TimeLocation> times = (skipSameTime ? new HashSet<TimeLocation>() : null);
    455            List<Section> sectionsThisSubpart = subpart.getSections();
    456            if (skipSameTime) {
    457                sectionsThisSubpart = new ArrayList<Section>(subpart.getSections());
    458                Collections.sort(sectionsThisSubpart, new AssignmentComparator<Section, Request, Enrollment>(assignment));
    459            }
    460            List<Section> matchingSectionsThisSubpart = new ArrayList<Section>(subpart.getSections().size());
    461            boolean hasChildren = !subpart.getChildren().isEmpty();
    462            for (Section section : sectionsThisSubpart) {
    463                if (section.isCancelled())
    464                    continue;
    465                if (!isRequired(section))
    466                    continue;
    467                if (getInitialAssignment() != null && (getModel() != null && ((StudentSectioningModel)getModel()).getKeepInitialAssignments()) &&
    468                        !getInitialAssignment().getAssignments().contains(section))
    469                    continue;
    470                if (isFixed() && !getFixedValue().getAssignments().contains(section))
    471                    continue;
    472                if (section.getParent() != null && !sections.contains(section.getParent()))
    473                    continue;
    474                if (section.isOverlapping(sections))
    475                    continue;
    476                if (selectedOnly && hasSelection(section) && !isSelected(section))
    477                    continue;
    478                if (isNotAllowed(course, section))
    479                    continue;
    480                if (!getStudent().isAvailable(section)) {
    481                    boolean canOverlap = false;
    482                    for (Reservation r: getReservations(course)) {
    483                        if (!r.isAllowOverlap()) continue;
    484                        if (r.getSections(subpart) != null && !r.getSections(subpart).contains(section)) continue;
    485                        if (r.getReservedAvailableSpace(assignment, this) < getWeight()) continue;
    486                        canOverlap = true; break;
    487                    }
    488                    if (!canOverlap) continue;
    489                }
    490                boolean canOverLimit = false;
    491                if (availableOnly) {
    492                    for (Reservation r: getReservations(course)) {
    493                        if (!r.canBatchAssignOverLimit()) continue;
    494                        if (r.getSections(subpart) != null && !r.getSections(subpart).contains(section)) continue;
    495                        if (r.getReservedAvailableSpace(assignment, this) < getWeight()) continue;
    496                        canOverLimit = true; break;
    497                    }
    498                }
    499                if (!canOverLimit) {
    500                    if (availableOnly && section.getLimit() >= 0
    501                            && SectionLimit.getEnrollmentWeight(assignment, section, this) > section.getLimit())
    502                        continue;
    503                    if (config.getOffering().hasReservations()) {
    504                        boolean hasReservation = false, hasSectionReservation = false, reservationMustBeUsed = false;
    505                        for (Reservation r: getReservations(course)) {
    506                            if (r.mustBeUsed()) reservationMustBeUsed = true;
    507                            if (availableOnly && r.getReservedAvailableSpace(assignment, this) < getWeight()) continue;
    508                            if (r.getSections(subpart) == null) {
    509                                hasReservation = true;
    510                            } else if (r.getSections(subpart).contains(section)) {
    511                                hasReservation = true;
    512                                hasSectionReservation = true;
    513                            }
    514                        }
    515                        if (!hasSectionReservation && section.getTotalUnreservedSpace() < getWeight())
    516                            continue;
    517                        if (availableOnly && !hasSectionReservation && section.getUnreservedSpace(assignment, this) < getWeight())
    518                            continue;
    519                        if (!hasReservation && reservationMustBeUsed)
    520                            continue;
    521                    }
    522                }
    523                if (!getStudent().isAllowDisabled() && !section.isEnabled()) {
    524                    boolean allowDisabled = false;
    525                    for (Reservation r: getReservations(course)) {
    526                        if (!r.isAllowDisabled()) continue;
    527                        if (r.getSections(subpart) != null && !r.getSections(subpart).contains(section)) continue;
    528                        if (!r.getConfigs().isEmpty() && !r.getConfigs().contains(config)) continue;
    529                        allowDisabled = true; break;
    530                    }
    531                    if (!allowDisabled) continue;
    532                }
    533                if (skipSameTime && section.getTime() != null && !hasChildren && !times.add(section.getTime()) && !isSelected(section) && !isWaitlisted(section) &&
    534                        (section.getIgnoreConflictWithSectionIds() == null || section.getIgnoreConflictWithSectionIds().isEmpty()))
    535                    continue;
    536                matchingSectionsThisSubpart.add(section);
    537            }
    538            if (random || limit > 0) {
    539                sectionsThisSubpart = new ArrayList<Section>(sectionsThisSubpart);
    540                Collections.shuffle(sectionsThisSubpart);
    541            }
    542            int i = 0;
    543            for (Section section: matchingSectionsThisSubpart) {
    544                sections.add(section);
    545                computeEnrollments(assignment, enrollments, priority, penalty + section.getPenalty(), course, config, sections, idx + 1,
    546                        availableOnly, skipSameTime, selectedOnly, random,
    547                        limit < 0 ? limit : Math.max(1, limit * (1 + i) / matchingSectionsThisSubpart.size()));
    548                sections.remove(section);
    549                i++;
    550            }
    551        }
    552    }
    553
    554    /** Return all enrollments that are available
    555     * @param assignment current assignment
    556     * @return all available enrollments
    557     **/
    558    public List<Enrollment> getAvaiableEnrollments(Assignment<Request, Enrollment> assignment) {
    559        List<Enrollment> ret = new ArrayList<Enrollment>();
    560        if (isFixed()) {
    561            ret.add(getFixedValue());
    562            return ret;
    563        }
    564        if (getInitialAssignment() != null && getModel() != null && ((StudentSectioningModel)getModel()).isMPP() && ((StudentSectioningModel)getModel()).getKeepInitialAssignments()) {
    565            ret.add(getInitialAssignment());
    566            return ret;
    567        }
    568        int idx = 0;
    569        for (Course course : iCourses) {
    570            for (Config config : course.getOffering().getConfigs()) {
    571                computeEnrollments(assignment, ret, idx, 0, course, config, new HashSet<Section>(), 0, true, false, false, false,
    572                        getMaxDomainSize() <= 0 ? -1 : ret.size() + getMaxDomainSize());
    573            }
    574            idx++;
    575        }
    576        return ret;
    577    }
    578
    579    /**
    580     * Return all enrollments of the first course that are selected (
    581     * {@link CourseRequest#isSelected(Section)} is true)
    582     *
    583     * @param assignment current assignment
    584     * @param availableOnly
    585     *            pick only available sections
    586     * @return selected enrollments
    587     */
    588    public List<Enrollment> getSelectedEnrollments(Assignment<Request, Enrollment> assignment, boolean availableOnly) {
    589        if (getSelectedChoices().isEmpty())
    590            return null;
    591        List<Enrollment> enrollments = new ArrayList<Enrollment>();
    592        if (isFixed()) return enrollments;
    593        if (getInitialAssignment() != null && getModel() != null && ((StudentSectioningModel)getModel()).isMPP() && ((StudentSectioningModel)getModel()).getKeepInitialAssignments())
    594            return enrollments;
    595        for (Course course : iCourses) {
    596            boolean hasChoice = false;
    597            for (Choice choice: getSelectedChoices())
    598                if (course.getOffering().equals(choice.getOffering())) { hasChoice = true; break; }
    599            if (hasChoice)
    600                for (Config config : course.getOffering().getConfigs()) {
    601                    computeEnrollments(assignment, enrollments, 0, 0, course, config, new HashSet<Section>(), 0, availableOnly, false, true, false, -1);
    602                }
    603            break;
    604        }
    605        return enrollments;
    606    }
    607
    608    /**
    609     * Return all enrollments that are available, pick only the first section of
    610     * the sections with the same time (of each subpart, {@link Section}
    611     * comparator is used)
    612     * @param assignment current assignment
    613     * @return available enrollments
    614     */
    615    public List<Enrollment> getAvaiableEnrollmentsSkipSameTime(Assignment<Request, Enrollment> assignment) {
    616        List<Enrollment> ret = new ArrayList<Enrollment>();
    617        if (isFixed()) {
    618            ret.add(getFixedValue());
    619            return ret;
    620        }
    621        if (getInitialAssignment() != null) {
    622            ret.add(getInitialAssignment());
    623            if (getModel() != null && ((StudentSectioningModel)getModel()).isMPP() && ((StudentSectioningModel)getModel()).getKeepInitialAssignments())
    624                return ret;
    625        }
    626        int idx = 0;
    627        for (Course course : iCourses) {
    628            boolean skipSameTime = true;
    629            for (LinkedSections link: getStudent().getLinkedSections())
    630                if (link.getOfferings().contains(course.getOffering())) { skipSameTime = false; break; }
    631            for (Config config : course.getOffering().getConfigs()) {
    632                computeEnrollments(assignment, ret, idx, 0, course, config, new HashSet<Section>(), 0, true, skipSameTime, false, false,
    633                        getMaxDomainSize() <= 0 ? -1 : ret.size() + getMaxDomainSize());
    634            }
    635            idx++;
    636        }
    637        return ret;
    638    }
    639
    640    /**
    641     * Return all possible enrollments, but pick only the first section of
    642     * the sections with the same time (of each subpart, {@link Section}
    643     * comparator is used).
    644     * @param assignment current assignment
    645     * @return computed enrollments
    646     */
    647    public List<Enrollment> getEnrollmentsSkipSameTime(Assignment<Request, Enrollment> assignment) {
    648        List<Enrollment> ret = new ArrayList<Enrollment>();
    649        if (isFixed()) {
    650            ret.add(getFixedValue());
    651            return ret;
    652        }
    653        if (getInitialAssignment() != null) {
    654            ret.add(getInitialAssignment());
    655            if (getModel() != null && ((StudentSectioningModel)getModel()).isMPP() && ((StudentSectioningModel)getModel()).getKeepInitialAssignments())
    656                return ret;
    657        }
    658        int idx = 0;
    659        for (Course course : iCourses) {
    660            for (Config config : course.getOffering().getConfigs()) {
    661                boolean skipSameTime = true;
    662                for (LinkedSections link: getStudent().getLinkedSections())
    663                    if (link.getOfferings().contains(course.getOffering())) { skipSameTime = false; break; }
    664                computeEnrollments(assignment, ret, idx, 0, course, config, new HashSet<Section>(), 0, false, skipSameTime, false, false,
    665                        getMaxDomainSize() <= 0 ? -1 : ret.size() + getMaxDomainSize());
    666            }
    667            idx++;
    668        }
    669        return ret;
    670    }
    671
    672    /** Wait-listed choices
    673     * @return wait-listed choices
    674     **/
    675    public Set<Choice> getWaitlistedChoices() {
    676        return iWaitlistedChoices;
    677    }
    678
    679    /**
    680     * Return true when the given section is wait-listed (i.e., its choice is
    681     * among wait-listed choices)
    682     * @param section given section
    683     * @return true if the given section matches the wait-listed choices
    684     */
    685    public boolean isWaitlisted(Section section) {
    686        for (Choice choice: iWaitlistedChoices)
    687            if (choice.sameChoice(section)) return true;
    688        return false;
    689    }
    690
    691    /** Selected choices
    692     * @return selected choices
    693     **/
    694    public Set<Choice> getSelectedChoices() {
    695        return iSelectedChoices;
    696    }
    697
    698    /**
    699     * Return true when the given section is selected (i.e., its choice is among
    700     * selected choices)
    701     * @param section given section
    702     * @return true if the given section matches the selected choices
    703     */
    704    public boolean isSelected(Section section) {
    705        for (Choice choice: iSelectedChoices)
    706            if (choice.sameSection(section) || choice.sameConfiguration(section)) return true;
    707        return false;
    708    }
    709
    710    /**
    711     * Return true when the given section has a preference (i.e., there is a matching selection),
    712     * or when there is a section preference for a different configuration
    713     * @param section given section
    714     * @return true if the there is a matching choice for the given section that is of the same offering
    715     */
    716    public boolean hasSelection(Section section) {
    717        boolean hasSectionChoices = false, hasSectionChoicesThisConfig = false;
    718        for (Choice choice: iSelectedChoices) {
    719            if (choice.sameOffering(section)) {
    720                if (choice.isMatching(section)) return true;
    721                if (choice.getSubpartId() != null) {
    722                    hasSectionChoices = true;
    723                    for (Subpart subpart: section.getSubpart().getConfig().getSubparts()) {
    724                        if (choice.getSubpartId().equals(subpart.getId())) { hasSectionChoicesThisConfig = true; }
    725                    }
    726                }
    727            }
    728        }
    729        return (hasSectionChoices && !hasSectionChoicesThisConfig);
    730    }
    731
    732    /**
    733     * Required choices
    734     * @return required choices
    735     */
    736    public Set<Choice> getRequiredChoices() {
    737        return iRequiredChoices;
    738    }
    739
    740    /**
    741     * Return true when the given section is required (i.e., its choice is among required choices, or there are no requirements)
    742     * @param section given section
    743     * @return true if the given section matches the required choices
    744     */
    745    public boolean isRequired(Section section) {
    746        if (iRequiredChoices.isEmpty()) return true;
    747        boolean hasConfig = false, hasMatchingConfig = false;
    748        boolean hasSubpart = false, hasMatchingSection = false;
    749        boolean hasSectionReq = false;
    750        for (Choice choice: iRequiredChoices) {
    751            // different offering -> skip
    752            if (!choice.getOffering().equals(section.getSubpart().getConfig().getOffering())) continue;
    753            // has config -> check config
    754            if (choice.getConfigId() != null) {
    755                hasConfig = true;
    756                if (choice.sameConfiguration(section)) hasMatchingConfig = true;
    757            }
    758            // has section of the matching subpart -> check section
    759            if (choice.getSubpartId() != null) {
    760                hasSectionReq = true;
    761                if (choice.getSubpartId().equals(section.getSubpart().getId())) {
    762                    hasSubpart = true;
    763                    if (choice.sameSection(section)) hasMatchingSection = true;
    764                } else if (!hasMatchingConfig) {
    765                    for (Subpart subpart: section.getSubpart().getConfig().getSubparts()) {
    766                        if (choice.getSubpartId().equals(subpart.getId())) {
    767                            hasMatchingConfig = true;
    768                            break;
    769                        }
    770                    }
    771                }
    772            }
    773        }
    774        if (hasConfig && !hasMatchingConfig) return false;
    775        if (hasSubpart && !hasMatchingSection) return false;
    776        // no match, but there are section requirements for a different config -> not satisfied
    777        if (!hasMatchingConfig && !hasMatchingSection && hasSectionReq) return false;
    778        return true;
    779    }
    780
    781    /**
    782     * Request name: A for alternative, 1 + priority, (w) when wait-list, list of
    783     * course names
    784     */
    785    @Override
    786    public String getName() {
    787        String ret = (isAlternative() ? "A" : "")
    788                + (1 + getPriority() + (isAlternative() ? -getStudent().nrRequests() : 0)) + ". "
    789                + (getRequestPriority() != RequestPriority.Normal ?
    790                  (isWaitlist() ? "(" + getRequestPriority().getAbbreviation() + "w) " : "(" + getRequestPriority().getAbbreviation() + ") ")
    791                  : isWaitlist() ? "(w) " : "");
    792        int idx = 0;
    793        for (Course course : iCourses) {
    794            if (idx == 0)
    795                ret += course.getName();
    796            else
    797                ret += ", " + idx + ". alt " + course.getName();
    798            idx++;
    799        }
    800        return ret;
    801    }
    802
    803    /**
    804     * True if the student can be put on a wait-list (no alternative course
    805     * request will be given instead)
    806     * @return true if the request can be wait-listed
    807     */
    808    public boolean isWaitlist() {
    809        return iWaitlist;
    810    }
    811
    812    /**
    813     * True if the student can be put on a wait-list (no alternative course
    814     * request will be given instead)
    815     * @param waitlist true if the request can be wait-listed
    816     */
    817    public void setWaitlist(boolean waitlist) {
    818        iWaitlist = waitlist;
    819    }
    820
    821    /**
    822     * True if the course request is critical for the student in order to move forward in their degree
    823     * @param critical true if the request is critical
    824     */
    825    @Deprecated
    826    public void setCritical(boolean critical) {
    827        iPriority = (critical ? RequestPriority.Critical : RequestPriority.Normal);
    828    }
    829
    830    /**
    831     * Time stamp of the request
    832     * @return request time stamp
    833     */
    834    public Long getTimeStamp() {
    835        return iTimeStamp;
    836    }
    837
    838    @Override
    839    public String toString() {
    840        return getName() + (getWeight() != 1.0 ? " (W:" + sDF.format(getWeight()) + ")" : "");
    841    }
    842
    843    /** Return course of the requested courses with the given id
    844     * @param courseId course offering id
    845     * @return course of the given id
    846     **/
    847    public Course getCourse(long courseId) {
    848        for (Course course : iCourses) {
    849            if (course.getId() == courseId)
    850                return course;
    851        }
    852        return null;
    853    }
    854
    855    /** Return configuration of the requested courses with the given id
    856     * @param configId instructional offering configuration unique id
    857     * @return config of the given id
    858     **/
    859    public Config getConfig(long configId) {
    860        for (Course course : iCourses) {
    861            for (Config config : course.getOffering().getConfigs()) {
    862                if (config.getId() == configId)
    863                    return config;
    864            }
    865        }
    866        return null;
    867    }
    868
    869    /** Return subpart of the requested courses with the given id
    870     * @param subpartId scheduling subpart unique id
    871     * @return subpart of the given id
    872     **/
    873    public Subpart getSubpart(long subpartId) {
    874        for (Course course : iCourses) {
    875            for (Config config : course.getOffering().getConfigs()) {
    876                for (Subpart subpart : config.getSubparts()) {
    877                    if (subpart.getId() == subpartId)
    878                        return subpart;
    879                }
    880            }
    881        }
    882        return null;
    883    }
    884
    885    /** Return section of the requested courses with the given id
    886     * @param sectionId class unique id
    887     * @return section of the given id
    888     **/
    889    public Section getSection(long sectionId) {
    890        for (Course course : iCourses) {
    891            for (Config config : course.getOffering().getConfigs()) {
    892                for (Subpart subpart : config.getSubparts()) {
    893                    for (Section section : subpart.getSections()) {
    894                        if (section.getId() == sectionId)
    895                            return section;
    896                    }
    897                }
    898            }
    899        }
    900        return null;
    901    }
    902
    903    /**
    904     * Minimal penalty (minimum of {@link Offering#getMinPenalty()} among
    905     * requested courses)
    906     * @return minimal penalty
    907     */
    908    public double getMinPenalty() {
    909        if (iCachedMinPenalty == null) {
    910            double min = Double.MAX_VALUE;
    911            for (Course course : iCourses) {
    912                min = Math.min(min, course.getOffering().getMinPenalty());
    913            }
    914            iCachedMinPenalty = new Double(min);
    915        }
    916        return iCachedMinPenalty.doubleValue();
    917    }
    918
    919    /**
    920     * Maximal penalty (maximum of {@link Offering#getMaxPenalty()} among
    921     * requested courses)
    922     * @return maximal penalty
    923     */
    924    public double getMaxPenalty() {
    925        if (iCachedMaxPenalty == null) {
    926            double max = Double.MIN_VALUE;
    927            for (Course course : iCourses) {
    928                max = Math.max(max, course.getOffering().getMaxPenalty());
    929            }
    930            iCachedMaxPenalty = new Double(max);
    931        }
    932        return iCachedMaxPenalty.doubleValue();
    933    }
    934
    935    /** Clear cached min/max penalties and cached bound */
    936    public void clearCache() {
    937        iCachedMaxPenalty = null;
    938        iCachedMinPenalty = null;
    939    }
    940
    941    /**
    942     * Estimated bound for this request -- it estimates the smallest value among
    943     * all possible enrollments
    944     */
    945    @Override
    946    public double getBound() {
    947        return - getWeight() * ((StudentSectioningModel)getModel()).getStudentWeights().getBound(this);
    948        /*
    949        if (iCachedBound == null) {
    950            iCachedBound = new Double(-Math.pow(Enrollment.sPriorityWeight, getPriority())
    951                    * (isAlternative() ? Enrollment.sAlterativeWeight : 1.0)
    952                    * Math.pow(Enrollment.sInitialWeight, (getInitialAssignment() == null ? 0 : 1))
    953                    * Math.pow(Enrollment.sSelectedWeight, (iSelectedChoices.isEmpty() ? 0 : 1))
    954                    * Math.pow(Enrollment.sWaitlistedWeight, (iWaitlistedChoices.isEmpty() ? 0 : 1))
    955                    *
    956                    // Math.max(Enrollment.sMinWeight,getWeight()) *
    957                    (getStudent().isDummy() ? Student.sDummyStudentWeight : 1.0)
    958                    * Enrollment.normalizePenalty(getMinPenalty()));
    959        }
    960        return iCachedBound.doubleValue();
    961        */
    962    }
    963
    964    /** Return true if request is assigned. */
    965    @Override
    966    public boolean isAssigned(Assignment<Request, Enrollment> assignment) {
    967        Enrollment e = assignment.getValue(this);
    968        return e != null && !e.getAssignments().isEmpty();
    969    }
    970
    971    @Override
    972    public boolean equals(Object o) {
    973        return super.equals(o) && (o instanceof CourseRequest);
    974    }
    975
    976    /**
    977     * Get reservations for this course requests
    978     * @param course given course
    979     * @return reservations for this course requests and the given course
    980     */
    981    public synchronized List<Reservation> getReservations(Course course) {
    982        if (iReservations == null)
    983            iReservations = new HashMap<Course, List<Reservation>>();
    984        List<Reservation> reservations = iReservations.get(course);
    985        if (reservations == null) {
    986            reservations = new ArrayList<Reservation>();
    987            boolean mustBeUsed = false;
    988            for (Reservation r: course.getOffering().getReservations()) {
    989                if (!r.isApplicable(getStudent())) continue;
    990                if (!mustBeUsed && r.mustBeUsed()) { reservations.clear(); mustBeUsed = true; }
    991                if (mustBeUsed && !r.mustBeUsed()) continue;
    992                reservations.add(r);
    993            }
    994            iReservations.put(course, reservations);
    995        }
    996        return reservations;
    997    }
    998    private Map<Course, List<Reservation>> iReservations = null;
    999
    1000    /**
    1001     * Get reservations for this course requests ordered using {@link Reservation#compareTo(Assignment, Reservation)}
    1002     * @param course given course
    1003     * @return reservations for this course requests and the given course
    1004     */
    1005    public TreeSet<Reservation> getSortedReservations(Assignment<Request, Enrollment> assignment, Course course) {
    1006        TreeSet<Reservation> reservations = new TreeSet<Reservation>(new AssignmentComparator<Reservation, Request, Enrollment>(assignment));
    1007        reservations.addAll(getReservations(course));
    1008        return reservations;
    1009    }
    1010
    1011    /**
    1012     * Return true if there is a reservation for a course of this request
    1013     * @return true if there is a reservation for a course of this request
    1014     */
    1015    public boolean hasReservations() {
    1016        for (Course course: getCourses())
    1017            if (!getReservations(course).isEmpty())
    1018                return true;
    1019        return false;
    1020    }
    1021
    1022    /**
    1023     * Clear reservation information that was cached on this section
    1024     */
    1025    public synchronized void clearReservationCache() {
    1026        if (iReservations != null) iReservations.clear();
    1027    }
    1028
    1029    /**
    1030     * Get restrictions for this course requests
    1031     * @param course given course
    1032     * @return restrictions for this course requests and the given course
    1033     */
    1034    public synchronized List<Restriction> getRestrictions(Course course) {
    1035        if (iRestrictions == null)
    1036            iRestrictions = new HashMap<Course, List<Restriction>>();
    1037        List<Restriction> restrictions = iRestrictions.get(course);
    1038        if (restrictions == null) {
    1039            restrictions = new ArrayList<Restriction>();
    1040            for (Restriction r: course.getOffering().getRestrictions()) {
    1041                if (r.isApplicable(getStudent()))
    1042                    restrictions.add(r);
    1043            }
    1044            iRestrictions.put(course, restrictions);
    1045        }
    1046        return restrictions;
    1047    }
    1048    private Map<Course, List<Restriction>> iRestrictions = null;
    1049
    1050    /**
    1051     * Return true if there is a restriction for a course of this request
    1052     * @return true if there is a restriction for a course of this request
    1053     */
    1054    public boolean hasRestrictions(Course course) {
    1055        return !getRestrictions(course).isEmpty();
    1056    }
    1057
    1058    /**
    1059     * Return true when there are restrictions for a course of this course request and the given config does not meet any of them
    1060     */
    1061    public boolean isNotAllowed(Course course, Config config) {
    1062        List<Restriction> restrictions = getRestrictions(course);
    1063        if (restrictions.isEmpty()) return false;
    1064        for (Restriction r: restrictions)
    1065            if (r.isIncluded(config)) return false;
    1066        return true;
    1067    }
    1068
    1069    /**
    1070     * Return true when there are restrictions for a course of this course request and the given section does not meet any of them
    1071     */
    1072    public boolean isNotAllowed(Course course, Section section) {
    1073        List<Restriction> restrictions = getRestrictions(course);
    1074        if (restrictions.isEmpty()) return false;
    1075        for (Restriction r: restrictions)
    1076            if (r.isIncluded(section)) return false;
    1077        return true;
    1078    }
    1079
    1080    /**
    1081     * Return true when there are restrictions for a course of this course request and the given enrollment does not meet any of them
    1082     */
    1083    public boolean isNotAllowed(Enrollment e) {
    1084        List<Restriction> restrictions = getRestrictions(e.getCourse());
    1085        if (restrictions.isEmpty()) return false;
    1086        for (Restriction r: restrictions)
    1087            if (r.isIncluded(e)) return false;
    1088        return true;
    1089    }
    1090
    1091    /**
    1092     * Clear restriction information that was cached on this request
    1093     */
    1094    public synchronized void clearRestrictionCache() {
    1095        if (iRestrictions != null) iRestrictions.clear();
    1096    }
    1097
    1098    /**
    1099     * Return true if this request can track MPP
    1100     * @return true if the request is course request and it either has an initial enrollment
    1101     */
    1102    @Override
    1103    public boolean isMPP() {
    1104        StudentSectioningModel model = (StudentSectioningModel) getModel();
    1105        if (model == null || !model.isMPP()) return false;
    1106        return !getStudent().isDummy() && getInitialAssignment() != null;
    1107    }
    1108
    1109    /**
    1110     * Return true if this request has any selection
    1111     * @return true if the request is course request and has some selected choices.
    1112     */
    1113    @Override
    1114    public boolean hasSelection() {
    1115        if (getStudent().isDummy() || getSelectedChoices().isEmpty()) return false;
    1116        for (Choice choice: getSelectedChoices())
    1117            if (choice.getSectionId() != null || choice.getConfigId() != null) return true;
    1118        return false;
    1119    }
    1120
    1121    /**
    1122     * Add request group to this request.
    1123     * @param group request group to be added
    1124     */
    1125    public void addRequestGroup(RequestGroup group) {
    1126        iRequestGroups.add(group);
    1127        group.addRequest(this);
    1128    }
    1129
    1130    /**
    1131     * Removed request group from this request.
    1132     * @param group request group to be removed
    1133     */
    1134    public void removeRequestGroup(RequestGroup group) {
    1135        iRequestGroups.remove(group);
    1136        group.removeRequest(this);
    1137    }
    1138
    1139    /**
    1140     * Lists request groups of this request
    1141     * @return request groups of this course requests
    1142     */
    1143    public Set<RequestGroup> getRequestGroups() {
    1144        return iRequestGroups;
    1145    }
    1146
    1147    @Override
    1148    public void variableAssigned(Assignment<Request, Enrollment> assignment, long iteration, Enrollment enrollment) {
    1149        super.variableAssigned(assignment, iteration, enrollment);
    1150        for (RequestGroup g: getRequestGroups())
    1151            if (g.getCourse().equals(enrollment.getCourse()))
    1152                g.assigned(assignment, enrollment);
    1153    }
    1154
    1155    @Override
    1156    public void variableUnassigned(Assignment<Request, Enrollment> assignment, long iteration, Enrollment enrollment) {
    1157        super.variableUnassigned(assignment, iteration, enrollment);
    1158        for (RequestGroup g: getRequestGroups())
    1159            if (g.getCourse().equals(enrollment.getCourse()))
    1160                g.unassigned(assignment, enrollment);
    1161    }
    1162
    1163    @Override
    1164    public float getMinCredit() {
    1165        Float credit = null;
    1166        for (Course course: getCourses()) {
    1167            if (course.hasCreditValue() && (credit == null || credit > course.getCreditValue()))
    1168                    credit = course.getCreditValue();
    1169            for (Config config: course.getOffering().getConfigs()) {
    1170                Float configCredit = config.getCreditValue();
    1171                if (configCredit != null && (credit == null || credit > configCredit))
    1172                        credit = configCredit;
    1173            }
    1174        }
    1175        return (credit == null ? 0 : credit.floatValue());
    1176    }
    1177
    1178    @Override
    1179    public RequestPriority getRequestPriority() {
    1180        return iPriority;
    1181    }
    1182
    1183    public void setRequestPriority(RequestPriority priority) {
    1184        iPriority = priority;
    1185    }
    1186
    1187    public boolean isFixed() { return iFixed != null; }
    1188    public Enrollment getFixedValue() { return iFixed; }
    1189    public void setFixedValue(Enrollment constant) { iFixed = constant; }
    1190}