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;
024
025
026/**
027 * Representation of a request of a student for one or more course. A student
028 * requests one of the given courses, preferably the first one. <br>
029 * <br>
030 * 
031 * @version StudentSct 1.3 (Student Sectioning)<br>
032 *          Copyright (C) 2007 - 2014 Tomas Muller<br>
033 *          <a href="mailto:muller@unitime.org">muller@unitime.org</a><br>
034 *          <a href="http://muller.unitime.org">http://muller.unitime.org</a><br>
035 * <br>
036 *          This library is free software; you can redistribute it and/or modify
037 *          it under the terms of the GNU Lesser General Public License as
038 *          published by the Free Software Foundation; either version 3 of the
039 *          License, or (at your option) any later version. <br>
040 * <br>
041 *          This library is distributed in the hope that it will be useful, but
042 *          WITHOUT ANY WARRANTY; without even the implied warranty of
043 *          MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
044 *          Lesser General Public License for more details. <br>
045 * <br>
046 *          You should have received a copy of the GNU Lesser General Public
047 *          License along with this library; if not see
048 *          <a href='http://www.gnu.org/licenses/'>http://www.gnu.org/licenses/</a>.
049 */
050public class CourseRequest extends Request {
051    private static DecimalFormat sDF = new DecimalFormat("0.000");
052    private List<Course> iCourses = null;
053    private Set<Choice> iWaitlistedChoices = new HashSet<Choice>();
054    private Set<Choice> iSelectedChoices = new HashSet<Choice>();
055    private boolean iWaitlist = false;
056    private Long iTimeStamp = null;
057    private Double iCachedMinPenalty = null, iCachedMaxPenalty = null;
058    public static boolean sSameTimePrecise = false;
059    private Set<RequestGroup> iRequestGroups = new HashSet<RequestGroup>();
060
061    /**
062     * Constructor
063     * 
064     * @param id
065     *            request unique id
066     * @param priority
067     *            request priority
068     * @param alternative
069     *            true if the request is alternative (alternative request can be
070     *            assigned instead of a non-alternative course requests, if it
071     *            is left unassigned)
072     * @param student
073     *            appropriate student
074     * @param courses
075     *            list of requested courses (in the correct order -- first is
076     *            the requested course, second is the first alternative, etc.)
077     * @param waitlist
078     *            time stamp of the request if the student can be put on a wait-list (no alternative
079     *            course request will be given instead)
080     * @param timeStamp request time stamp
081     */
082    public CourseRequest(long id, int priority, boolean alternative, Student student, java.util.List<Course> courses,
083            boolean waitlist, Long timeStamp) {
084        super(id, priority, alternative, student);
085        iCourses = new ArrayList<Course>(courses);
086        for (Course course: iCourses)
087            course.getRequests().add(this);
088        iWaitlist = waitlist;
089        iTimeStamp = timeStamp;
090    }
091
092    /**
093     * List of requested courses (in the correct order -- first is the requested
094     * course, second is the first alternative, etc.)
095     * @return requested course offerings
096     */
097    public List<Course> getCourses() {
098        return iCourses;
099    }
100
101    /**
102     * Create enrollment for the given list of sections. The list of sections
103     * needs to be correct, i.e., a section for each subpart of a configuration
104     * of one of the requested courses.
105     * @param sections selected sections
106     * @param reservation selected reservation
107     * @return enrollment
108     */
109    public Enrollment createEnrollment(Set<? extends SctAssignment> sections, Reservation reservation) {
110        if (sections == null || sections.isEmpty())
111            return null;
112        Config config = ((Section) sections.iterator().next()).getSubpart().getConfig();
113        Course course = null;
114        for (Course c: iCourses) {
115            if (c.getOffering().getConfigs().contains(config)) {
116                course = c;
117                break;
118            }
119        }
120        return new Enrollment(this, iCourses.indexOf(course), course, config, sections, reservation);
121    }
122
123    /**
124     * Create enrollment for the given list of sections. The list of sections
125     * needs to be correct, i.e., a section for each subpart of a configuration
126     * of one of the requested courses.
127     * @param assignment current assignment (to guess the reservation)
128     * @param sections selected sections
129     * @return enrollment
130     */
131    public Enrollment createEnrollment(Assignment<Request, Enrollment> assignment, Set<? extends SctAssignment> sections) {
132        Enrollment ret = createEnrollment(sections, null);
133        ret.guessReservation(assignment, true);
134        return ret;
135        
136    }
137    
138    /**
139     * Maximal domain size (i.e., number of enrollments of a course request), -1 if there is no limit.
140     * @return maximal domain size, -1 if unlimited
141     */
142    protected int getMaxDomainSize() {
143        StudentSectioningModel model = (StudentSectioningModel) getModel();
144        return model == null ? -1 : model.getMaxDomainSize();
145    }
146    
147    /**
148     * Return all possible enrollments.
149     */
150    @Override
151    public List<Enrollment> computeEnrollments(Assignment<Request, Enrollment> assignment) {
152        List<Enrollment> ret = new ArrayList<Enrollment>();
153        int idx = 0;
154        for (Course course : iCourses) {
155            for (Config config : course.getOffering().getConfigs()) {
156                computeEnrollments(assignment, ret, idx, 0, course, config, new HashSet<Section>(), 0, false, false,
157                        false, false, getMaxDomainSize() <= 0 ? -1 : ret.size() + getMaxDomainSize());
158            }
159            idx++;
160        }
161        return ret;
162    }
163
164    /**
165     * Return a subset of all enrollments -- randomly select only up to
166     * limitEachConfig enrollments of each config.
167     * @param assignment current assignment
168     * @param limitEachConfig maximal number of enrollments in each configuration
169     * @return computed enrollments
170     */
171    public List<Enrollment> computeRandomEnrollments(Assignment<Request, Enrollment> assignment, int limitEachConfig) {
172        List<Enrollment> ret = new ArrayList<Enrollment>();
173        int idx = 0;
174        for (Course course : iCourses) {
175            for (Config config : course.getOffering().getConfigs()) {
176                computeEnrollments(assignment, ret, idx, 0, course, config, new HashSet<Section>(), 0, false, false,
177                        false, true, (limitEachConfig <= 0 ? limitEachConfig : ret.size() + limitEachConfig));
178            }
179            idx++;
180        }
181        return ret;
182    }
183
184    /**
185     * Return true if the both sets of sections contain sections of the same
186     * subparts, and each pair of sections of the same subpart is offered at the
187     * same time.
188     */
189    private boolean sameTimes(Set<Section> sections1, Set<Section> sections2) {
190        for (Section s1 : sections1) {
191            Section s2 = null;
192            for (Section s : sections2) {
193                if (s.getSubpart().equals(s1.getSubpart())) {
194                    s2 = s;
195                    break;
196                }
197            }
198            if (s2 == null)
199                return false;
200            if (!ToolBox.equals(s1.getTime(), s2.getTime()))
201                return false;
202        }
203        return true;
204    }
205
206    /**
207     * Recursive computation of enrollments
208     * 
209     * @param enrollments
210     *            list of enrollments to be returned
211     * @param priority
212     *            zero for the course, one for the first alternative, two for the second alternative
213     * @param penalty
214     *            penalty of the selected sections
215     * @param course
216     *            selected course
217     * @param config
218     *            selected configuration
219     * @param sections
220     *            sections selected so far
221     * @param idx
222     *            index of the subparts (a section of 0..idx-1 subparts has been
223     *            already selected)
224     * @param availableOnly
225     *            only use available sections
226     * @param skipSameTime
227     *            for each possible times, pick only one section
228     * @param selectedOnly
229     *            select only sections that are selected (
230     *            {@link CourseRequest#isSelected(Section)} is true)
231     * @param random
232     *            pick sections in a random order (useful when limit is used)
233     * @param limit
234     *            when above zero, limit the number of selected enrollments to
235     *            this limit
236     * @param ignoreDisabled
237     *            are sections that are disabled for student scheduling allowed to be used
238     * @param reservations
239     *            list of applicable reservations
240     */
241    private void computeEnrollments(Assignment<Request, Enrollment> assignment, Collection<Enrollment> enrollments, int priority, double penalty, Course course, Config config,
242            HashSet<Section> sections, int idx, boolean availableOnly, boolean skipSameTime, boolean selectedOnly,
243            boolean random, int limit) {
244        if (limit > 0 && enrollments.size() >= limit)
245            return;
246        if (idx == 0) { // run only once for each configuration
247            boolean canOverLimit = false;
248            if (availableOnly) {
249                for (Reservation r: getReservations(course)) {
250                    if (!r.canBatchAssignOverLimit()) continue;
251                    if (!r.getConfigs().isEmpty() && !r.getConfigs().contains(config)) continue;
252                    if (r.getReservedAvailableSpace(assignment, this) < getWeight()) continue;
253                    canOverLimit = true; break;
254                }
255            }
256            if (!canOverLimit) {
257                if (availableOnly && config.getLimit() >= 0 && ConfigLimit.getEnrollmentWeight(assignment, config, this) > config.getLimit())
258                    return;
259                if (availableOnly && course.getLimit() >= 0 && CourseLimit.getEnrollmentWeight(assignment, course, this) > course.getLimit())
260                    return;
261                if (config.getOffering().hasReservations()) {
262                    boolean hasReservation = false, hasConfigReservation = false, reservationMustBeUsed = false;
263                    for (Reservation r: getReservations(course)) {
264                        if (r.mustBeUsed()) reservationMustBeUsed = true;
265                        if (availableOnly && r.getReservedAvailableSpace(assignment, this) < getWeight()) continue;
266                        if (r.getConfigs().isEmpty()) {
267                            hasReservation = true;
268                        } else if (r.getConfigs().contains(config)) {
269                            hasReservation = true;
270                            hasConfigReservation = true;
271                        }
272                    }
273                    if (!hasConfigReservation && config.getTotalUnreservedSpace() < getWeight())
274                        return;
275                    if (!hasReservation && config.getOffering().getTotalUnreservedSpace() < getWeight())
276                        return;
277                    if (availableOnly && !hasReservation && config.getOffering().getUnreservedSpace(assignment, this) < getWeight())
278                        return;
279                    if (availableOnly && !hasConfigReservation && config.getUnreservedSpace(assignment, this) < getWeight())
280                        return;
281                    if (!hasReservation && reservationMustBeUsed)
282                        return;
283                }
284            }
285        }
286        if (config.getSubparts().size() == idx) {
287            if (skipSameTime && sSameTimePrecise) {
288                boolean waitListedOrSelected = false;
289                if (!getSelectedChoices().isEmpty() || !getWaitlistedChoices().isEmpty()) {
290                    for (Section section : sections) {
291                        if (isWaitlisted(section) || isSelected(section)) {
292                            waitListedOrSelected = true;
293                            break;
294                        }
295                    }
296                }
297                if (!waitListedOrSelected) {
298                    for (Enrollment enrollment : enrollments) {
299                        if (sameTimes(enrollment.getSections(), sections))
300                            return;
301                    }
302                }
303            }
304            if (!config.getOffering().hasReservations()) {
305                enrollments.add(new Enrollment(this, priority, null, config, new HashSet<SctAssignment>(sections), null));
306            } else {
307                Enrollment e = new Enrollment(this, priority, null, config, new HashSet<SctAssignment>(sections), null);
308                boolean mustHaveReservation = config.getOffering().getTotalUnreservedSpace() < getWeight();
309                boolean mustHaveConfigReservation = config.getTotalUnreservedSpace() < getWeight();
310                boolean mustHaveSectionReservation = false;
311                boolean containDisabledSection = false;
312                for (Section s: sections) {
313                    if (s.getTotalUnreservedSpace() < getWeight()) {
314                        mustHaveSectionReservation = true;
315                    }
316                    if (!getStudent().isAllowDisabled() && !s.isEnabled()) {
317                        containDisabledSection = true;
318                    }
319                }
320                boolean canOverLimit = false;
321                if (availableOnly) {
322                    for (Reservation r: getReservations(course)) {
323                        if (!r.canBatchAssignOverLimit() || !r.isIncluded(e)) continue;
324                        if (r.getReservedAvailableSpace(assignment, this) < getWeight()) continue;
325                        if (containDisabledSection && !r.isAllowDisabled()) continue;
326                        enrollments.add(new Enrollment(this, priority, null, config, new HashSet<SctAssignment>(sections), r));
327                        canOverLimit = true;
328                    }
329                }
330                if (!canOverLimit) {
331                    boolean reservationMustBeUsed = false;
332                    reservations: for (Reservation r: (availableOnly ? getSortedReservations(assignment, course) : getReservations(course))) {
333                        if (r.mustBeUsed()) reservationMustBeUsed = true;
334                        if (!r.isIncluded(e)) continue;
335                        if (availableOnly && r.getReservedAvailableSpace(assignment, this) < getWeight()) continue;
336                        if (mustHaveConfigReservation && r.getConfigs().isEmpty()) continue;
337                        if (mustHaveSectionReservation)
338                            for (Section s: sections)
339                                if (r.getSections(s.getSubpart()) == null && s.getTotalUnreservedSpace() < getWeight()) continue reservations;
340                        if (containDisabledSection && !r.isAllowDisabled()) continue;
341                        enrollments.add(new Enrollment(this, priority, null, config, new HashSet<SctAssignment>(sections), r));
342                        if (availableOnly) return; // only one available reservation suffice (the best matching one)
343                    }
344                    // a case w/o reservation
345                    if (!(mustHaveReservation || mustHaveConfigReservation || mustHaveSectionReservation) &&
346                        !(availableOnly && config.getOffering().getUnreservedSpace(assignment, this) < getWeight()) &&
347                        !reservationMustBeUsed && !containDisabledSection) {
348                        enrollments.add(new Enrollment(this, (getReservations(course).isEmpty() ? 0 : 1) + priority, null, config, new HashSet<SctAssignment>(sections), null));
349                    }
350                }
351            }
352        } else {
353            Subpart subpart = config.getSubparts().get(idx);
354            HashSet<TimeLocation> times = (skipSameTime ? new HashSet<TimeLocation>() : null);
355            List<Section> sectionsThisSubpart = subpart.getSections();
356            if (skipSameTime) {
357                sectionsThisSubpart = new ArrayList<Section>(subpart.getSections());
358                Collections.sort(sectionsThisSubpart, new AssignmentComparator<Section, Request, Enrollment>(assignment));
359            }
360            List<Section> matchingSectionsThisSubpart = new ArrayList<Section>(subpart.getSections().size());
361            boolean hasChildren = !subpart.getChildren().isEmpty();
362            for (Section section : sectionsThisSubpart) {
363                if (section.isCancelled())
364                    continue;
365                if (getInitialAssignment() != null && (getModel() != null && ((StudentSectioningModel)getModel()).getKeepInitialAssignments()) &&
366                        !getInitialAssignment().getAssignments().contains(section))
367                    continue;
368                if (section.getParent() != null && !sections.contains(section.getParent()))
369                    continue;
370                if (section.isOverlapping(sections))
371                    continue;
372                if (selectedOnly && !isSelected(section))
373                    continue;
374                if (!getStudent().isAvailable(section)) {
375                    boolean canOverlap = false;
376                    for (Reservation r: getReservations(course)) {
377                        if (!r.isAllowOverlap()) continue;
378                        if (r.getSections(subpart) != null && !r.getSections(subpart).contains(section)) continue;
379                        if (r.getReservedAvailableSpace(assignment, this) < getWeight()) continue;
380                        canOverlap = true; break;
381                    }
382                    if (!canOverlap) continue;
383                }
384                boolean canOverLimit = false;
385                if (availableOnly) {
386                    for (Reservation r: getReservations(course)) {
387                        if (!r.canBatchAssignOverLimit()) continue;
388                        if (r.getSections(subpart) != null && !r.getSections(subpart).contains(section)) continue;
389                        if (r.getReservedAvailableSpace(assignment, this) < getWeight()) continue;
390                        canOverLimit = true; break;
391                    }
392                }
393                if (!canOverLimit) {
394                    if (availableOnly && section.getLimit() >= 0
395                            && SectionLimit.getEnrollmentWeight(assignment, section, this) > section.getLimit())
396                        continue;
397                    if (config.getOffering().hasReservations()) {
398                        boolean hasReservation = false, hasSectionReservation = false, reservationMustBeUsed = false;
399                        for (Reservation r: getReservations(course)) {
400                            if (r.mustBeUsed()) reservationMustBeUsed = true;
401                            if (availableOnly && r.getReservedAvailableSpace(assignment, this) < getWeight()) continue;
402                            if (r.getSections(subpart) == null) {
403                                hasReservation = true;
404                            } else if (r.getSections(subpart).contains(section)) {
405                                hasReservation = true;
406                                hasSectionReservation = true;
407                            }
408                        }
409                        if (!hasSectionReservation && section.getTotalUnreservedSpace() < getWeight())
410                            continue;
411                        if (availableOnly && !hasSectionReservation && section.getUnreservedSpace(assignment, this) < getWeight())
412                            continue;
413                        if (!hasReservation && reservationMustBeUsed)
414                            continue;
415                    }
416                }
417                if (!getStudent().isAllowDisabled() && !section.isEnabled()) {
418                    boolean allowDisabled = false;
419                    for (Reservation r: getReservations(course)) {
420                        if (!r.isAllowDisabled()) continue;
421                        if (r.getSections(subpart) != null && !r.getSections(subpart).contains(section)) continue;
422                        if (!r.getConfigs().isEmpty() && !r.getConfigs().contains(config)) continue;
423                        allowDisabled = true; break;
424                    }
425                    if (!allowDisabled) continue;
426                }
427                if (skipSameTime && section.getTime() != null && !hasChildren && !times.add(section.getTime()) && !isSelected(section) && !isWaitlisted(section) && 
428                        (section.getIgnoreConflictWithSectionIds() == null || section.getIgnoreConflictWithSectionIds().isEmpty()))
429                    continue;
430                matchingSectionsThisSubpart.add(section);
431            }
432            if (random || limit > 0) {
433                sectionsThisSubpart = new ArrayList<Section>(sectionsThisSubpart);
434                Collections.shuffle(sectionsThisSubpart);
435            }
436            int i = 0;
437            for (Section section: matchingSectionsThisSubpart) {
438                sections.add(section);
439                computeEnrollments(assignment, enrollments, priority, penalty + section.getPenalty(), course, config, sections, idx + 1,
440                        availableOnly, skipSameTime, selectedOnly, random,
441                        limit < 0 ? limit : Math.max(1, limit * (1 + i) / matchingSectionsThisSubpart.size()));
442                sections.remove(section);
443                i++;
444            }
445        }
446    }
447
448    /** Return all enrollments that are available 
449     * @param assignment current assignment
450     * @return all available enrollments
451     **/
452    public List<Enrollment> getAvaiableEnrollments(Assignment<Request, Enrollment> assignment) {
453        List<Enrollment> ret = new ArrayList<Enrollment>();
454        int idx = 0;
455        for (Course course : iCourses) {
456            for (Config config : course.getOffering().getConfigs()) {
457                computeEnrollments(assignment, ret, idx, 0, course, config, new HashSet<Section>(), 0, true, false, false, false,
458                        getMaxDomainSize() <= 0 ? -1 : ret.size() + getMaxDomainSize());
459            }
460            idx++;
461        }
462        return ret;
463    }
464
465    /**
466     * Return all enrollments that are selected (
467     * {@link CourseRequest#isSelected(Section)} is true)
468     * 
469     * @param assignment current assignment
470     * @param availableOnly
471     *            pick only available sections
472     * @return selected enrollments
473     */
474    public List<Enrollment> getSelectedEnrollments(Assignment<Request, Enrollment> assignment, boolean availableOnly) {
475        if (getSelectedChoices().isEmpty())
476            return null;
477        Choice firstChoice = getSelectedChoices().iterator().next();
478        List<Enrollment> enrollments = new ArrayList<Enrollment>();
479        for (Course course : iCourses) {
480            if (!course.getOffering().equals(firstChoice.getOffering()))
481                continue;
482            for (Config config : course.getOffering().getConfigs()) {
483                computeEnrollments(assignment, enrollments, 0, 0, course, config, new HashSet<Section>(), 0, availableOnly, false, true, false, -1);
484            }
485        }
486        return enrollments;
487    }
488
489    /**
490     * Return all enrollments that are available, pick only the first section of
491     * the sections with the same time (of each subpart, {@link Section}
492     * comparator is used)
493     * @param assignment current assignment
494     * @return available enrollments 
495     */
496    public List<Enrollment> getAvaiableEnrollmentsSkipSameTime(Assignment<Request, Enrollment> assignment) {
497        List<Enrollment> ret = new ArrayList<Enrollment>();
498        if (getInitialAssignment() != null)
499            ret.add(getInitialAssignment());
500        int idx = 0;
501        for (Course course : iCourses) {
502            boolean skipSameTime = true;
503            for (LinkedSections link: getStudent().getLinkedSections())
504                if (link.getOfferings().contains(course.getOffering())) { skipSameTime = false; break; }
505            for (Config config : course.getOffering().getConfigs()) {
506                computeEnrollments(assignment, ret, idx, 0, course, config, new HashSet<Section>(), 0, true, skipSameTime, false, false,
507                        getMaxDomainSize() <= 0 ? -1 : ret.size() + getMaxDomainSize());
508            }
509            idx++;
510        }
511        return ret;
512    }
513
514    /**
515     * Return all possible enrollments, but pick only the first section of
516     * the sections with the same time (of each subpart, {@link Section}
517     * comparator is used).
518     * @param assignment current assignment
519     * @return computed enrollments 
520     */
521    public List<Enrollment> getEnrollmentsSkipSameTime(Assignment<Request, Enrollment> assignment) {
522        List<Enrollment> ret = new ArrayList<Enrollment>();
523        int idx = 0;
524        for (Course course : iCourses) {
525            for (Config config : course.getOffering().getConfigs()) {
526                boolean skipSameTime = true;
527                for (LinkedSections link: getStudent().getLinkedSections())
528                    if (link.getOfferings().contains(course.getOffering())) { skipSameTime = false; break; }
529                computeEnrollments(assignment, ret, idx, 0, course, config, new HashSet<Section>(), 0, false, skipSameTime, false, false,
530                        getMaxDomainSize() <= 0 ? -1 : ret.size() + getMaxDomainSize());
531            }
532            idx++;
533        }
534        return ret;
535    }
536
537    /** Wait-listed choices 
538     * @return wait-listed choices
539     **/
540    public Set<Choice> getWaitlistedChoices() {
541        return iWaitlistedChoices;
542    }
543
544    /**
545     * Return true when the given section is wait-listed (i.e., its choice is
546     * among wait-listed choices)
547     * @param section given section
548     * @return true if the given section matches the wait-listed choices
549     */
550    public boolean isWaitlisted(Section section) {
551        for (Choice choice: iWaitlistedChoices)
552            if (choice.sameChoice(section)) return true;
553        return false;
554    }
555
556    /** Selected choices 
557     * @return selected choices
558     **/
559    public Set<Choice> getSelectedChoices() {
560        return iSelectedChoices;
561    }
562
563    /**
564     * Return true when the given section is selected (i.e., its choice is among
565     * selected choices)
566     * @param section given section
567     * @return true if the given section matches the selected choices
568     */
569    public boolean isSelected(Section section) {
570        boolean hasMatch = false;
571        for (Choice choice: iSelectedChoices) {
572            if (choice.sameChoice(section) || choice.sameConfiguration(section)) return true;
573            if (choice.isMatching(section)) hasMatch = true;
574        }
575        return !iSelectedChoices.isEmpty() && !hasMatch;
576    }
577
578    /**
579     * Request name: A for alternative, 1 + priority, (w) when wait-list, list of
580     * course names
581     */
582    @Override
583    public String getName() {
584        String ret = (isAlternative() ? "A" : "")
585                + (1 + getPriority() + (isAlternative() ? -getStudent().nrRequests() : 0)) + ". "
586                + (isWaitlist() ? "(w) " : "");
587        int idx = 0;
588        for (Course course : iCourses) {
589            if (idx == 0)
590                ret += course.getName();
591            else
592                ret += ", " + idx + ". alt " + course.getName();
593            idx++;
594        }
595        return ret;
596    }
597
598    /**
599     * True if the student can be put on a wait-list (no alternative course
600     * request will be given instead)
601     * @return true if the request can be wait-listed
602     */
603    public boolean isWaitlist() {
604        return iWaitlist;
605    }
606    
607    /**
608     * True if the student can be put on a wait-list (no alternative course
609     * request will be given instead)
610     * @param waitlist true if the request can be wait-listed
611     */
612    public void setWaitlist(boolean waitlist) {
613        iWaitlist = waitlist;
614    }
615    
616    /**
617     * Time stamp of the request
618     * @return request time stamp
619     */
620    public Long getTimeStamp() {
621        return iTimeStamp;
622    }
623
624    @Override
625    public String toString() {
626        return getName() + (getWeight() != 1.0 ? " (W:" + sDF.format(getWeight()) + ")" : "");
627    }
628
629    /** Return course of the requested courses with the given id 
630     * @param courseId course offering id
631     * @return course of the given id
632     **/
633    public Course getCourse(long courseId) {
634        for (Course course : iCourses) {
635            if (course.getId() == courseId)
636                return course;
637        }
638        return null;
639    }
640
641    /** Return configuration of the requested courses with the given id 
642     * @param configId instructional offering configuration unique id
643     * @return config of the given id
644     **/
645    public Config getConfig(long configId) {
646        for (Course course : iCourses) {
647            for (Config config : course.getOffering().getConfigs()) {
648                if (config.getId() == configId)
649                    return config;
650            }
651        }
652        return null;
653    }
654
655    /** Return subpart of the requested courses with the given id 
656     * @param subpartId scheduling subpart unique id
657     * @return subpart of the given id
658     **/
659    public Subpart getSubpart(long subpartId) {
660        for (Course course : iCourses) {
661            for (Config config : course.getOffering().getConfigs()) {
662                for (Subpart subpart : config.getSubparts()) {
663                    if (subpart.getId() == subpartId)
664                        return subpart;
665                }
666            }
667        }
668        return null;
669    }
670
671    /** Return section of the requested courses with the given id 
672     * @param sectionId class unique id
673     * @return section of the given id
674     **/
675    public Section getSection(long sectionId) {
676        for (Course course : iCourses) {
677            for (Config config : course.getOffering().getConfigs()) {
678                for (Subpart subpart : config.getSubparts()) {
679                    for (Section section : subpart.getSections()) {
680                        if (section.getId() == sectionId)
681                            return section;
682                    }
683                }
684            }
685        }
686        return null;
687    }
688
689    /**
690     * Minimal penalty (minimum of {@link Offering#getMinPenalty()} among
691     * requested courses)
692     * @return minimal penalty
693     */
694    public double getMinPenalty() {
695        if (iCachedMinPenalty == null) {
696            double min = Double.MAX_VALUE;
697            for (Course course : iCourses) {
698                min = Math.min(min, course.getOffering().getMinPenalty());
699            }
700            iCachedMinPenalty = new Double(min);
701        }
702        return iCachedMinPenalty.doubleValue();
703    }
704
705    /**
706     * Maximal penalty (maximum of {@link Offering#getMaxPenalty()} among
707     * requested courses)
708     * @return maximal penalty
709     */
710    public double getMaxPenalty() {
711        if (iCachedMaxPenalty == null) {
712            double max = Double.MIN_VALUE;
713            for (Course course : iCourses) {
714                max = Math.max(max, course.getOffering().getMaxPenalty());
715            }
716            iCachedMaxPenalty = new Double(max);
717        }
718        return iCachedMaxPenalty.doubleValue();
719    }
720
721    /** Clear cached min/max penalties and cached bound */
722    public void clearCache() {
723        iCachedMaxPenalty = null;
724        iCachedMinPenalty = null;
725    }
726
727    /**
728     * Estimated bound for this request -- it estimates the smallest value among
729     * all possible enrollments
730     */
731    @Override
732    public double getBound() {
733        return - getWeight() * ((StudentSectioningModel)getModel()).getStudentWeights().getBound(this);
734        /*
735        if (iCachedBound == null) {
736            iCachedBound = new Double(-Math.pow(Enrollment.sPriorityWeight, getPriority())
737                    * (isAlternative() ? Enrollment.sAlterativeWeight : 1.0)
738                    * Math.pow(Enrollment.sInitialWeight, (getInitialAssignment() == null ? 0 : 1))
739                    * Math.pow(Enrollment.sSelectedWeight, (iSelectedChoices.isEmpty() ? 0 : 1))
740                    * Math.pow(Enrollment.sWaitlistedWeight, (iWaitlistedChoices.isEmpty() ? 0 : 1))
741                    *
742                    // Math.max(Enrollment.sMinWeight,getWeight()) *
743                    (getStudent().isDummy() ? Student.sDummyStudentWeight : 1.0)
744                    * Enrollment.normalizePenalty(getMinPenalty()));
745        }
746        return iCachedBound.doubleValue();
747        */
748    }
749
750    /** Return true if request is assigned. */
751    @Override
752    public boolean isAssigned(Assignment<Request, Enrollment> assignment) {
753        Enrollment e = assignment.getValue(this);
754        return e != null && !e.getAssignments().isEmpty();
755    }
756
757    @Override
758    public boolean equals(Object o) {
759        return super.equals(o) && (o instanceof CourseRequest);
760    }
761    
762    /**
763     * Get reservations for this course requests
764     * @param course given course
765     * @return reservations for this course requests and the given course
766     */
767    public synchronized List<Reservation> getReservations(Course course) {
768        if (iReservations == null)
769            iReservations = new HashMap<Course, List<Reservation>>();
770        List<Reservation> reservations = iReservations.get(course);
771        if (reservations == null) {
772            reservations = new ArrayList<Reservation>();
773            boolean mustBeUsed = false;
774            for (Reservation r: course.getOffering().getReservations()) {
775                if (!r.isApplicable(getStudent())) continue;
776                if (!mustBeUsed && r.mustBeUsed()) { reservations.clear(); mustBeUsed = true; }
777                if (mustBeUsed && !r.mustBeUsed()) continue;
778                reservations.add(r);
779            }
780            iReservations.put(course, reservations);
781        }
782        return reservations;
783    }
784    private Map<Course, List<Reservation>> iReservations = null;
785    
786    /**
787     * Get reservations for this course requests ordered using {@link Reservation#compareTo(Assignment, Reservation)}
788     * @param course given course
789     * @return reservations for this course requests and the given course
790     */
791    public TreeSet<Reservation> getSortedReservations(Assignment<Request, Enrollment> assignment, Course course) {
792        TreeSet<Reservation> reservations = new TreeSet<Reservation>(new AssignmentComparator<Reservation, Request, Enrollment>(assignment));
793        reservations.addAll(getReservations(course));
794        return reservations;
795    }
796    
797    /**
798     * Return true if there is a reservation for a course of this request
799     * @return true if there is a reservation for a course of this request
800     */
801    public boolean hasReservations() {
802        for (Course course: getCourses())
803            if (!getReservations(course).isEmpty())
804                return true;
805        return false;
806    }
807    
808    /**
809     * Clear reservation information that was cached on this section
810     */
811    public synchronized void clearReservationCache() {
812        if (iReservations != null) iReservations.clear();
813    }
814    
815    /**
816     * Return true if this request can track MPP
817     * @return true if the request is course request and it either has an initial enrollment or some selected choices.
818     */
819    @Override
820    public boolean isMPP() {
821        StudentSectioningModel model = (StudentSectioningModel) getModel();
822        if (model == null || !model.isMPP()) return false;
823        return !getStudent().isDummy() && (getInitialAssignment() != null || !getSelectedChoices().isEmpty()); 
824    }
825    
826    /**
827     * Return true if this request has any selection
828     * @return true if the request is course request and has some selected choices.
829     */
830    @Override
831    public boolean hasSelection() {
832        if (getStudent().isDummy() || getSelectedChoices().isEmpty()) return false;
833        for (Choice choice: getSelectedChoices())
834            if (choice.getSectionId() != null || choice.getConfigId() != null) return true;
835        return false;
836    }
837    
838    /**
839     * Add request group to this request.
840     * @param group request group to be added
841     */
842    public void addRequestGroup(RequestGroup group) {
843        iRequestGroups.add(group);
844        group.addRequest(this);
845    }
846    
847    /**
848     * Removed request group from this request.
849     * @param group request group to be removed
850     */
851    public void removeRequestGroup(RequestGroup group) {
852        iRequestGroups.remove(group);
853        group.removeRequest(this);
854    }
855
856    /**
857     * Lists request groups of this request
858     * @return request groups of this course requests
859     */
860    public Set<RequestGroup> getRequestGroups() {
861        return iRequestGroups;
862    }
863    
864    @Override
865    public void variableAssigned(Assignment<Request, Enrollment> assignment, long iteration, Enrollment enrollment) {
866        super.variableAssigned(assignment, iteration, enrollment);
867        for (RequestGroup g: getRequestGroups())
868            if (g.getCourse().equals(enrollment.getCourse()))
869                g.assigned(assignment, enrollment);
870    }
871
872    @Override
873    public void variableUnassigned(Assignment<Request, Enrollment> assignment, long iteration, Enrollment enrollment) {
874        super.variableUnassigned(assignment, iteration, enrollment);
875        for (RequestGroup g: getRequestGroups())
876            if (g.getCourse().equals(enrollment.getCourse()))
877                g.unassigned(assignment, enrollment);
878    }
879}