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, config, 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, config, 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                        } else if (!r.areRestrictionsInclusive()) {
371                            hasReservation = true;
372                        }
373                    }
374                    if (!hasConfigReservation && config.getTotalUnreservedSpace() < getWeight())
375                        return;
376                    if (!hasReservation && config.getOffering().getTotalUnreservedSpace() < getWeight())
377                        return;
378                    if (availableOnly && !hasReservation && config.getOffering().getUnreservedSpace(assignment, this) < getWeight())
379                        return;
380                    if (availableOnly && !hasConfigReservation && config.getUnreservedSpace(assignment, this) < getWeight())
381                        return;
382                    if (!hasReservation && reservationMustBeUsed)
383                        return;
384                }
385            }
386        }
387        if (config.getSubparts().size() == idx) {
388            if (skipSameTime && sSameTimePrecise) {
389                boolean waitListedOrSelected = false;
390                if (!getSelectedChoices().isEmpty() || !getWaitlistedChoices().isEmpty()) {
391                    for (Section section : sections) {
392                        if (isWaitlisted(section) || isSelected(section)) {
393                            waitListedOrSelected = true;
394                            break;
395                        }
396                    }
397                }
398                if (!waitListedOrSelected) {
399                    for (Enrollment enrollment : enrollments) {
400                        if (sameTimes(enrollment.getSections(), sections))
401                            return;
402                    }
403                }
404            }
405            Enrollment e = new Enrollment(this, priority, course, config, new HashSet<SctAssignment>(sections), null);
406            if (isNotAllowed(e)) {
407            } else if (!config.getOffering().hasReservations()) {
408                enrollments.add(e);
409            } else {
410                boolean mustHaveReservation = config.getOffering().getTotalUnreservedSpace() < getWeight();
411                boolean mustHaveConfigReservation = config.getTotalUnreservedSpace() < getWeight();
412                boolean mustHaveSectionReservation = false;
413                boolean containDisabledSection = false;
414                for (Section s: sections) {
415                    if (s.getTotalUnreservedSpace() < getWeight()) {
416                        mustHaveSectionReservation = true;
417                    }
418                    if (!getStudent().isAllowDisabled() && !s.isEnabled(getStudent())) {
419                        containDisabledSection = true;
420                    }
421                }
422                boolean canOverLimit = false;
423                if (availableOnly) {
424                    for (Reservation r: getReservations(course)) {
425                        if (!r.canBatchAssignOverLimit() || !r.isIncluded(e)) continue;
426                        if (r.getReservedAvailableSpace(assignment, config, this) < getWeight()) continue;
427                        if (containDisabledSection && !r.isAllowDisabled()) continue;
428                        enrollments.add(new Enrollment(this, priority, null, config, new HashSet<SctAssignment>(sections), r));
429                        canOverLimit = true;
430                    }
431                }
432                if (!canOverLimit) {
433                    boolean reservationMustBeUsed = false;
434                    reservations: for (Reservation r: (availableOnly ? getSortedReservations(assignment, course) : getReservations(course))) {
435                        if (r.mustBeUsed()) reservationMustBeUsed = true;
436                        if (!r.isIncluded(e)) continue;
437                        if (availableOnly && r.getReservedAvailableSpace(assignment, config, this) < getWeight()) continue;
438                        if (mustHaveConfigReservation && r.getConfigs().isEmpty()) continue;
439                        if (mustHaveSectionReservation)
440                            for (Section s: sections)
441                                if (r.getSections(s.getSubpart()) == null && s.getTotalUnreservedSpace() < getWeight()) continue reservations;
442                        if (containDisabledSection && !r.isAllowDisabled()) continue;
443                        enrollments.add(new Enrollment(this, priority, null, config, new HashSet<SctAssignment>(sections), r));
444                        if (availableOnly) return; // only one available reservation suffice (the best matching one)
445                    }
446                    // a case w/o reservation
447                    if (!(mustHaveReservation || mustHaveConfigReservation || mustHaveSectionReservation) &&
448                        !(availableOnly && config.getOffering().getUnreservedSpace(assignment, this) < getWeight()) &&
449                        !reservationMustBeUsed && !containDisabledSection) {
450                        enrollments.add(new Enrollment(this, priority, !getReservations(course).isEmpty(), null, config, new HashSet<SctAssignment>(sections), null));
451                    }
452                }
453            }
454        } else {
455            Subpart subpart = config.getSubparts().get(idx);
456            HashSet<TimeLocation> times = (skipSameTime ? new HashSet<TimeLocation>() : null);
457            List<Section> sectionsThisSubpart = subpart.getSections();
458            if (skipSameTime) {
459                sectionsThisSubpart = new ArrayList<Section>(subpart.getSections());
460                Collections.sort(sectionsThisSubpart, new AssignmentComparator<Section, Request, Enrollment>(assignment));
461            }
462            List<Section> matchingSectionsThisSubpart = new ArrayList<Section>(subpart.getSections().size());
463            boolean hasChildren = !subpart.getChildren().isEmpty();
464            for (Section section : sectionsThisSubpart) {
465                if (section.isCancelled())
466                    continue;
467                if (!isRequired(section))
468                    continue;
469                if (getInitialAssignment() != null && (getModel() != null && ((StudentSectioningModel)getModel()).getKeepInitialAssignments()) &&
470                        !getInitialAssignment().getAssignments().contains(section))
471                    continue;
472                if (isFixed() && !getFixedValue().getAssignments().contains(section))
473                    continue;
474                if (section.getParent() != null && !sections.contains(section.getParent()))
475                    continue;
476                if (section.isOverlapping(sections))
477                    continue;
478                if (selectedOnly && hasSelection(section) && !isSelected(section))
479                    continue;
480                if (isNotAllowed(course, section))
481                    continue;
482                if (!getStudent().isAvailable(section)) {
483                    boolean canOverlap = false;
484                    for (Reservation r: getReservations(course)) {
485                        if (!r.isAllowOverlap()) continue;
486                        if (r.getSections(subpart) != null && !r.getSections(subpart).contains(section)) continue;
487                        if (r.getReservedAvailableSpace(assignment, config, this) < getWeight()) continue;
488                        canOverlap = true; break;
489                    }
490                    if (!canOverlap) continue;
491                }
492                boolean canOverLimit = false;
493                if (availableOnly) {
494                    for (Reservation r: getReservations(course)) {
495                        if (!r.canBatchAssignOverLimit()) continue;
496                        if (r.getSections(subpart) != null && !r.getSections(subpart).contains(section)) continue;
497                        if (r.getReservedAvailableSpace(assignment, config, this) < getWeight()) continue;
498                        canOverLimit = true; break;
499                    }
500                }
501                if (!canOverLimit) {
502                    if (availableOnly && section.getLimit() >= 0
503                            && SectionLimit.getEnrollmentWeight(assignment, section, this) > section.getLimit())
504                        continue;
505                    if (config.getOffering().hasReservations()) {
506                        boolean hasReservation = false, hasSectionReservation = false, reservationMustBeUsed = false;
507                        for (Reservation r: getReservations(course)) {
508                            if (r.mustBeUsed()) reservationMustBeUsed = true;
509                            if (availableOnly && r.getReservedAvailableSpace(assignment, config, this) < getWeight()) continue;
510                            if (r.getSections(subpart) == null) {
511                                hasReservation = true;
512                            } else if (r.getSections(subpart).contains(section)) {
513                                hasReservation = true;
514                                hasSectionReservation = true;
515                            }
516                        }
517                        if (!hasSectionReservation && section.getTotalUnreservedSpace() < getWeight())
518                            continue;
519                        if (availableOnly && !hasSectionReservation && section.getUnreservedSpace(assignment, this) < getWeight())
520                            continue;
521                        if (!hasReservation && reservationMustBeUsed)
522                            continue;
523                    }
524                }
525                if (!getStudent().isAllowDisabled() && !section.isEnabled(getStudent())) {
526                    boolean allowDisabled = false;
527                    for (Reservation r: getReservations(course)) {
528                        if (!r.isAllowDisabled()) continue;
529                        if (r.getSections(subpart) != null && !r.getSections(subpart).contains(section)) continue;
530                        if (!r.getConfigs().isEmpty() && !r.getConfigs().contains(config)) continue;
531                        allowDisabled = true; break;
532                    }
533                    if (!allowDisabled) continue;
534                }
535                if (skipSameTime && section.getTime() != null && !hasChildren && !times.add(section.getTime()) && !isSelected(section) && !isWaitlisted(section) && 
536                        (section.getIgnoreConflictWithSectionIds() == null || section.getIgnoreConflictWithSectionIds().isEmpty()))
537                    continue;
538                matchingSectionsThisSubpart.add(section);
539            }
540            if (random || limit > 0) {
541                sectionsThisSubpart = new ArrayList<Section>(sectionsThisSubpart);
542                Collections.shuffle(sectionsThisSubpart);
543            }
544            int i = 0;
545            for (Section section: matchingSectionsThisSubpart) {
546                sections.add(section);
547                computeEnrollments(assignment, enrollments, priority, penalty + section.getPenalty(), course, config, sections, idx + 1,
548                        availableOnly, skipSameTime, selectedOnly, random,
549                        limit < 0 ? limit : Math.max(1, limit * (1 + i) / matchingSectionsThisSubpart.size()));
550                sections.remove(section);
551                i++;
552            }
553        }
554    }
555
556    /** Return all enrollments that are available 
557     * @param assignment current assignment
558     * @return all available enrollments
559     **/
560    public List<Enrollment> getAvaiableEnrollments(Assignment<Request, Enrollment> assignment) {
561        List<Enrollment> ret = new ArrayList<Enrollment>();
562        if (isFixed()) {
563            ret.add(getFixedValue());
564            return ret;
565        }
566        if (getInitialAssignment() != null && getModel() != null && ((StudentSectioningModel)getModel()).isMPP() && ((StudentSectioningModel)getModel()).getKeepInitialAssignments()) {
567            ret.add(getInitialAssignment());
568            return ret;
569        }
570        int idx = 0;
571        for (Course course : iCourses) {
572            for (Config config : course.getOffering().getConfigs()) {
573                computeEnrollments(assignment, ret, idx, 0, course, config, new HashSet<Section>(), 0, true, false, false, false,
574                        getMaxDomainSize() <= 0 ? -1 : ret.size() + getMaxDomainSize());
575            }
576            idx++;
577        }
578        return ret;
579    }
580
581    /**
582     * Return all enrollments of the first course that are selected (
583     * {@link CourseRequest#isSelected(Section)} is true)
584     * 
585     * @param assignment current assignment
586     * @param availableOnly
587     *            pick only available sections
588     * @return selected enrollments
589     */
590    public List<Enrollment> getSelectedEnrollments(Assignment<Request, Enrollment> assignment, boolean availableOnly) {
591        if (getSelectedChoices().isEmpty())
592            return null;
593        List<Enrollment> enrollments = new ArrayList<Enrollment>();
594        if (isFixed()) return enrollments;
595        if (getInitialAssignment() != null && getModel() != null && ((StudentSectioningModel)getModel()).isMPP() && ((StudentSectioningModel)getModel()).getKeepInitialAssignments())
596            return enrollments;
597        for (Course course : iCourses) {
598            boolean hasChoice = false;
599            for (Choice choice: getSelectedChoices())
600                if (course.getOffering().equals(choice.getOffering())) { hasChoice = true; break; }
601            if (hasChoice)
602                for (Config config : course.getOffering().getConfigs()) {
603                    computeEnrollments(assignment, enrollments, 0, 0, course, config, new HashSet<Section>(), 0, availableOnly, false, true, false, -1);
604                }
605            break;
606        }
607        return enrollments;
608    }
609
610    /**
611     * Return all enrollments that are available, pick only the first section of
612     * the sections with the same time (of each subpart, {@link Section}
613     * comparator is used)
614     * @param assignment current assignment
615     * @return available enrollments 
616     */
617    public List<Enrollment> getAvaiableEnrollmentsSkipSameTime(Assignment<Request, Enrollment> assignment) {
618        List<Enrollment> ret = new ArrayList<Enrollment>();
619        if (isFixed()) {
620            ret.add(getFixedValue());
621            return ret;
622        }
623        if (getInitialAssignment() != null) {
624            ret.add(getInitialAssignment());
625            if (getModel() != null && ((StudentSectioningModel)getModel()).isMPP() && ((StudentSectioningModel)getModel()).getKeepInitialAssignments())
626                return ret;
627        }
628        int idx = 0;
629        for (Course course : iCourses) {
630            boolean skipSameTime = true;
631            for (LinkedSections link: getStudent().getLinkedSections())
632                if (link.getOfferings().contains(course.getOffering())) { skipSameTime = false; break; }
633            for (Config config : course.getOffering().getConfigs()) {
634                computeEnrollments(assignment, ret, idx, 0, course, config, new HashSet<Section>(), 0, true, skipSameTime, false, false,
635                        getMaxDomainSize() <= 0 ? -1 : ret.size() + getMaxDomainSize());
636            }
637            idx++;
638        }
639        return ret;
640    }
641
642    /**
643     * Return all possible enrollments, but pick only the first section of
644     * the sections with the same time (of each subpart, {@link Section}
645     * comparator is used).
646     * @param assignment current assignment
647     * @return computed enrollments 
648     */
649    public List<Enrollment> getEnrollmentsSkipSameTime(Assignment<Request, Enrollment> assignment) {
650        List<Enrollment> ret = new ArrayList<Enrollment>();
651        if (isFixed()) {
652            ret.add(getFixedValue());
653            return ret;
654        }
655        if (getInitialAssignment() != null) {
656            ret.add(getInitialAssignment());
657            if (getModel() != null && ((StudentSectioningModel)getModel()).isMPP() && ((StudentSectioningModel)getModel()).getKeepInitialAssignments())
658                return ret;
659        }
660        int idx = 0;
661        for (Course course : iCourses) {
662            for (Config config : course.getOffering().getConfigs()) {
663                boolean skipSameTime = true;
664                for (LinkedSections link: getStudent().getLinkedSections())
665                    if (link.getOfferings().contains(course.getOffering())) { skipSameTime = false; break; }
666                computeEnrollments(assignment, ret, idx, 0, course, config, new HashSet<Section>(), 0, false, skipSameTime, false, false,
667                        getMaxDomainSize() <= 0 ? -1 : ret.size() + getMaxDomainSize());
668            }
669            idx++;
670        }
671        return ret;
672    }
673
674    /** Wait-listed choices 
675     * @return wait-listed choices
676     **/
677    public Set<Choice> getWaitlistedChoices() {
678        return iWaitlistedChoices;
679    }
680
681    /**
682     * Return true when the given section is wait-listed (i.e., its choice is
683     * among wait-listed choices)
684     * @param section given section
685     * @return true if the given section matches the wait-listed choices
686     */
687    public boolean isWaitlisted(Section section) {
688        for (Choice choice: iWaitlistedChoices)
689            if (choice.sameChoice(section)) return true;
690        return false;
691    }
692
693    /** Selected choices 
694     * @return selected choices
695     **/
696    public Set<Choice> getSelectedChoices() {
697        return iSelectedChoices;
698    }
699    
700    /**
701     * Return true when the given section is selected (i.e., its choice is among
702     * selected choices)
703     * @param section given section
704     * @return true if the given section matches the selected choices
705     */
706    public boolean isSelected(Section section) {
707        for (Choice choice: iSelectedChoices)
708            if (choice.sameSection(section) || choice.sameConfiguration(section)) return true;
709        return false;
710    }
711    
712    /**
713     * Return true when the given section has a preference (i.e., there is a matching selection),
714     * or when there is a section preference for a different configuration
715     * @param section given section
716     * @return true if the there is a matching choice for the given section that is of the same offering
717     */
718    public boolean hasSelection(Section section) {
719        boolean hasSectionChoices = false, hasSectionChoicesThisConfig = false;
720        for (Choice choice: iSelectedChoices) {
721            if (choice.sameOffering(section)) {
722                if (choice.isMatching(section)) return true;
723                if (choice.getSubpartId() != null) {
724                    hasSectionChoices = true;
725                    for (Subpart subpart: section.getSubpart().getConfig().getSubparts()) {
726                        if (choice.getSubpartId().equals(subpart.getId())) { hasSectionChoicesThisConfig = true; }
727                    }
728                }
729            }
730        }
731        return (hasSectionChoices && !hasSectionChoicesThisConfig);
732    }
733    
734    /**
735     * Required choices
736     * @return required choices
737     */
738    public Set<Choice> getRequiredChoices() {
739        return iRequiredChoices;
740    }
741    
742    /**
743     * Return true when the given section is required (i.e., its choice is among required choices, or there are no requirements)
744     * @param section given section
745     * @return true if the given section matches the required choices
746     */
747    public boolean isRequired(Section section) {
748        if (iRequiredChoices.isEmpty()) return true;
749        boolean hasConfig = false, hasMatchingConfig = false;
750        boolean hasSubpart = false, hasMatchingSection = false;
751        boolean hasSectionReq = false;
752        for (Choice choice: iRequiredChoices) {
753            // different offering -> skip
754            if (!choice.getOffering().equals(section.getSubpart().getConfig().getOffering())) continue;
755            // has config -> check config
756            if (choice.getConfigId() != null) {
757                hasConfig = true;
758                if (choice.sameConfiguration(section)) hasMatchingConfig = true;
759            }
760            // has section of the matching subpart -> check section
761            if (choice.getSubpartId() != null) {
762                hasSectionReq = true;
763                if (choice.getSubpartId().equals(section.getSubpart().getId())) {
764                    hasSubpart = true;
765                    if (choice.sameSection(section)) hasMatchingSection = true;
766                } else if (!hasMatchingConfig) {
767                    for (Subpart subpart: section.getSubpart().getConfig().getSubparts()) {
768                        if (choice.getSubpartId().equals(subpart.getId())) {
769                            hasMatchingConfig = true;
770                            break;
771                        }
772                    }
773                }
774            }
775        }
776        if (hasConfig && !hasMatchingConfig) return false;
777        if (hasSubpart && !hasMatchingSection) return false;
778        // no match, but there are section requirements for a different config -> not satisfied 
779        if (!hasMatchingConfig && !hasMatchingSection && hasSectionReq) return false;
780        return true;
781    }
782
783    /**
784     * Request name: A for alternative, 1 + priority, (w) when wait-list, list of
785     * course names
786     */
787    @Override
788    public String getName() {
789        String ret = (isAlternative() ? "A" : "")
790                + (1 + getPriority() + (isAlternative() ? -getStudent().nrRequests() : 0)) + ". "
791                + (getRequestPriority() != RequestPriority.Normal ?
792                  (isWaitlist() ? "(" + getRequestPriority().getAbbreviation() + "w) " : "(" + getRequestPriority().getAbbreviation() + ") ")
793                  : isWaitlist() ? "(w) " : "");
794        int idx = 0;
795        for (Course course : iCourses) {
796            if (idx == 0)
797                ret += course.getName();
798            else
799                ret += ", " + idx + ". alt " + course.getName();
800            idx++;
801        }
802        return ret;
803    }
804
805    /**
806     * True if the student can be put on a wait-list (no alternative course
807     * request will be given instead)
808     * @return true if the request can be wait-listed
809     */
810    public boolean isWaitlist() {
811        return iWaitlist;
812    }
813    
814    /**
815     * True if the student can be put on a wait-list (no alternative course
816     * request will be given instead)
817     * @param waitlist true if the request can be wait-listed
818     */
819    public void setWaitlist(boolean waitlist) {
820        iWaitlist = waitlist;
821    }
822    
823    /**
824     * True if the course request is critical for the student in order to move forward in their degree 
825     * @param critical true if the request is critical
826     */
827    @Deprecated
828    public void setCritical(boolean critical) {
829        iPriority = (critical ? RequestPriority.Critical : RequestPriority.Normal);
830    }
831    
832    /**
833     * Time stamp of the request
834     * @return request time stamp
835     */
836    public Long getTimeStamp() {
837        return iTimeStamp;
838    }
839
840    @Override
841    public String toString() {
842        return getName() + (getWeight() != 1.0 ? " (W:" + sDF.format(getWeight()) + ")" : "");
843    }
844
845    /** Return course of the requested courses with the given id 
846     * @param courseId course offering id
847     * @return course of the given id
848     **/
849    public Course getCourse(long courseId) {
850        for (Course course : iCourses) {
851            if (course.getId() == courseId)
852                return course;
853        }
854        return null;
855    }
856
857    /** Return configuration of the requested courses with the given id 
858     * @param configId instructional offering configuration unique id
859     * @return config of the given id
860     **/
861    public Config getConfig(long configId) {
862        for (Course course : iCourses) {
863            for (Config config : course.getOffering().getConfigs()) {
864                if (config.getId() == configId)
865                    return config;
866            }
867        }
868        return null;
869    }
870
871    /** Return subpart of the requested courses with the given id 
872     * @param subpartId scheduling subpart unique id
873     * @return subpart of the given id
874     **/
875    public Subpart getSubpart(long subpartId) {
876        for (Course course : iCourses) {
877            for (Config config : course.getOffering().getConfigs()) {
878                for (Subpart subpart : config.getSubparts()) {
879                    if (subpart.getId() == subpartId)
880                        return subpart;
881                }
882            }
883        }
884        return null;
885    }
886
887    /** Return section of the requested courses with the given id 
888     * @param sectionId class unique id
889     * @return section of the given id
890     **/
891    public Section getSection(long sectionId) {
892        for (Course course : iCourses) {
893            for (Config config : course.getOffering().getConfigs()) {
894                for (Subpart subpart : config.getSubparts()) {
895                    for (Section section : subpart.getSections()) {
896                        if (section.getId() == sectionId)
897                            return section;
898                    }
899                }
900            }
901        }
902        return null;
903    }
904
905    /**
906     * Minimal penalty (minimum of {@link Offering#getMinPenalty()} among
907     * requested courses)
908     * @return minimal penalty
909     */
910    public double getMinPenalty() {
911        if (iCachedMinPenalty == null) {
912            double min = Double.MAX_VALUE;
913            for (Course course : iCourses) {
914                min = Math.min(min, course.getOffering().getMinPenalty());
915            }
916            iCachedMinPenalty = Double.valueOf(min);
917        }
918        return iCachedMinPenalty.doubleValue();
919    }
920
921    /**
922     * Maximal penalty (maximum of {@link Offering#getMaxPenalty()} among
923     * requested courses)
924     * @return maximal penalty
925     */
926    public double getMaxPenalty() {
927        if (iCachedMaxPenalty == null) {
928            double max = Double.MIN_VALUE;
929            for (Course course : iCourses) {
930                max = Math.max(max, course.getOffering().getMaxPenalty());
931            }
932            iCachedMaxPenalty = Double.valueOf(max);
933        }
934        return iCachedMaxPenalty.doubleValue();
935    }
936
937    /** Clear cached min/max penalties and cached bound */
938    public void clearCache() {
939        iCachedMaxPenalty = null;
940        iCachedMinPenalty = null;
941    }
942
943    /**
944     * Estimated bound for this request -- it estimates the smallest value among
945     * all possible enrollments
946     */
947    @Override
948    public double getBound() {
949        return - getWeight() * ((StudentSectioningModel)getModel()).getStudentWeights().getBound(this);
950        /*
951        if (iCachedBound == null) {
952            iCachedBound = Double.valueOf(-Math.pow(Enrollment.sPriorityWeight, getPriority())
953                    * (isAlternative() ? Enrollment.sAlterativeWeight : 1.0)
954                    * Math.pow(Enrollment.sInitialWeight, (getInitialAssignment() == null ? 0 : 1))
955                    * Math.pow(Enrollment.sSelectedWeight, (iSelectedChoices.isEmpty() ? 0 : 1))
956                    * Math.pow(Enrollment.sWaitlistedWeight, (iWaitlistedChoices.isEmpty() ? 0 : 1))
957                    *
958                    // Math.max(Enrollment.sMinWeight,getWeight()) *
959                    (getStudent().isDummy() ? Student.sDummyStudentWeight : 1.0)
960                    * Enrollment.normalizePenalty(getMinPenalty()));
961        }
962        return iCachedBound.doubleValue();
963        */
964    }
965
966    /** Return true if request is assigned. */
967    @Override
968    public boolean isAssigned(Assignment<Request, Enrollment> assignment) {
969        Enrollment e = assignment.getValue(this);
970        return e != null && !e.getAssignments().isEmpty();
971    }
972
973    @Override
974    public boolean equals(Object o) {
975        return super.equals(o) && (o instanceof CourseRequest);
976    }
977    
978    /**
979     * Get reservations for this course requests
980     * @param course given course
981     * @return reservations for this course requests and the given course
982     */
983    public synchronized List<Reservation> getReservations(Course course) {
984        if (iReservations == null)
985            iReservations = new HashMap<Course, List<Reservation>>();
986        List<Reservation> reservations = iReservations.get(course);
987        if (reservations == null) {
988            reservations = new ArrayList<Reservation>();
989            boolean mustBeUsed = false;
990            for (Reservation r: course.getOffering().getReservations()) {
991                if (!r.isApplicable(getStudent())) continue;
992                if (!mustBeUsed && r.mustBeUsed()) { reservations.clear(); mustBeUsed = true; }
993                if (mustBeUsed && !r.mustBeUsed()) continue;
994                reservations.add(r);
995            }
996            iReservations.put(course, reservations);
997        }
998        return reservations;
999    }
1000    private Map<Course, List<Reservation>> iReservations = null;
1001    
1002    /**
1003     * Get reservations for this course requests ordered using {@link Reservation#compareTo(Assignment, Reservation)}
1004     * @param course given course
1005     * @return reservations for this course requests and the given course
1006     */
1007    public TreeSet<Reservation> getSortedReservations(Assignment<Request, Enrollment> assignment, Course course) {
1008        TreeSet<Reservation> reservations = new TreeSet<Reservation>(new AssignmentComparator<Reservation, Request, Enrollment>(assignment));
1009        reservations.addAll(getReservations(course));
1010        return reservations;
1011    }
1012    
1013    /**
1014     * Return true if there is a reservation for a course of this request
1015     * @return true if there is a reservation for a course of this request
1016     */
1017    public boolean hasReservations() {
1018        for (Course course: getCourses())
1019            if (!getReservations(course).isEmpty())
1020                return true;
1021        return false;
1022    }
1023    
1024    /**
1025     * Clear reservation information that was cached on this section
1026     */
1027    public synchronized void clearReservationCache() {
1028        if (iReservations != null) iReservations.clear();
1029    }
1030    
1031    /**
1032     * Get restrictions for this course requests
1033     * @param course given course
1034     * @return restrictions for this course requests and the given course
1035     */
1036    public synchronized List<Restriction> getRestrictions(Course course) {
1037        if (iRestrictions == null)
1038            iRestrictions = new HashMap<Course, List<Restriction>>();
1039        List<Restriction> restrictions = iRestrictions.get(course);
1040        if (restrictions == null) {
1041            restrictions = new ArrayList<Restriction>();
1042            for (Restriction r: course.getOffering().getRestrictions()) {
1043                if (r.isApplicable(getStudent()))
1044                    restrictions.add(r);
1045            }
1046            iRestrictions.put(course, restrictions);
1047        }
1048        return restrictions;
1049    }
1050    private Map<Course, List<Restriction>> iRestrictions = null;
1051    
1052    /**
1053     * Return true if there is a restriction for a course of this request
1054     * @return true if there is a restriction for a course of this request
1055     */
1056    public boolean hasRestrictions(Course course) {
1057        return !getRestrictions(course).isEmpty();
1058    }
1059    
1060    /**
1061     * Return true when there are restrictions for a course of this course request and the given config does not meet any of them
1062     */
1063    public boolean isNotAllowed(Course course, Config config) {
1064        List<Restriction> restrictions = getRestrictions(course);
1065        if (restrictions.isEmpty()) return false;
1066        for (Restriction r: restrictions)
1067            if (r.isIncluded(config)) return false;
1068        return true;
1069    }
1070    
1071    /**
1072     * Return true when there are restrictions for a course of this course request and the given section does not meet any of them
1073     */
1074    public boolean isNotAllowed(Course course, Section section) {
1075        List<Restriction> restrictions = getRestrictions(course);
1076        if (restrictions.isEmpty()) return false;
1077        for (Restriction r: restrictions)
1078            if (r.isIncluded(section)) return false;
1079        return true;
1080    }
1081    
1082    /**
1083     * Return true when there are restrictions for a course of this course request and the given enrollment does not meet any of them
1084     */
1085    public boolean isNotAllowed(Enrollment e) {
1086        List<Restriction> restrictions = getRestrictions(e.getCourse());
1087        if (restrictions.isEmpty()) return false;
1088        for (Restriction r: restrictions)
1089            if (r.isIncluded(e)) return false;
1090        return true;
1091    }
1092    
1093    /**
1094     * Clear restriction information that was cached on this request
1095     */
1096    public synchronized void clearRestrictionCache() {
1097        if (iRestrictions != null) iRestrictions.clear();
1098    }
1099    
1100    /**
1101     * Return true if this request can track MPP
1102     * @return true if the request is course request and it either has an initial enrollment
1103     */
1104    @Override
1105    public boolean isMPP() {
1106        StudentSectioningModel model = (StudentSectioningModel) getModel();
1107        if (model == null || !model.isMPP()) return false;
1108        return !getStudent().isDummy() && getInitialAssignment() != null; 
1109    }
1110    
1111    /**
1112     * Return true if this request has any selection
1113     * @return true if the request is course request and has some selected choices.
1114     */
1115    @Override
1116    public boolean hasSelection() {
1117        if (getStudent().isDummy() || getSelectedChoices().isEmpty()) return false;
1118        for (Choice choice: getSelectedChoices())
1119            if (choice.getSectionId() != null || choice.getConfigId() != null) return true;
1120        return false;
1121    }
1122    
1123    /**
1124     * Add request group to this request.
1125     * @param group request group to be added
1126     */
1127    public void addRequestGroup(RequestGroup group) {
1128        iRequestGroups.add(group);
1129        group.addRequest(this);
1130    }
1131    
1132    /**
1133     * Removed request group from this request.
1134     * @param group request group to be removed
1135     */
1136    public void removeRequestGroup(RequestGroup group) {
1137        iRequestGroups.remove(group);
1138        group.removeRequest(this);
1139    }
1140
1141    /**
1142     * Lists request groups of this request
1143     * @return request groups of this course requests
1144     */
1145    public Set<RequestGroup> getRequestGroups() {
1146        return iRequestGroups;
1147    }
1148    
1149    @Override
1150    public void variableAssigned(Assignment<Request, Enrollment> assignment, long iteration, Enrollment enrollment) {
1151        super.variableAssigned(assignment, iteration, enrollment);
1152        for (RequestGroup g: getRequestGroups())
1153            if (g.getCourse().equals(enrollment.getCourse()))
1154                g.assigned(assignment, enrollment);
1155    }
1156
1157    @Override
1158    public void variableUnassigned(Assignment<Request, Enrollment> assignment, long iteration, Enrollment enrollment) {
1159        super.variableUnassigned(assignment, iteration, enrollment);
1160        for (RequestGroup g: getRequestGroups())
1161            if (g.getCourse().equals(enrollment.getCourse()))
1162                g.unassigned(assignment, enrollment);
1163    }
1164
1165    @Override
1166    public float getMinCredit() {
1167        Float credit = null;
1168        for (Course course: getCourses()) {
1169            if (course.hasCreditValue() && (credit == null || credit > course.getCreditValue()))
1170                    credit = course.getCreditValue();
1171            for (Config config: course.getOffering().getConfigs()) {
1172                Float configCredit = config.getCreditValue();
1173                if (configCredit != null && (credit == null || credit > configCredit))
1174                        credit = configCredit;
1175            }
1176        }
1177        return (credit == null ? 0 : credit.floatValue());
1178    }
1179
1180    @Override
1181    public RequestPriority getRequestPriority() {
1182        return iPriority;
1183    }
1184    
1185    public void setRequestPriority(RequestPriority priority) {
1186        iPriority = priority;
1187    }
1188
1189    public boolean isFixed() { return iFixed != null; }
1190    public Enrollment getFixedValue() { return iFixed; }
1191    public void setFixedValue(Enrollment constant) { iFixed = constant; }
1192}