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 reservations
237     *            list of applicable reservations
238     */
239    private void computeEnrollments(Assignment<Request, Enrollment> assignment, Collection<Enrollment> enrollments, int priority, double penalty, Course course, Config config,
240            HashSet<Section> sections, int idx, boolean availableOnly, boolean skipSameTime, boolean selectedOnly,
241            boolean random, int limit) {
242        if (limit > 0 && enrollments.size() >= limit)
243            return;
244        if (idx == 0) { // run only once for each configuration
245            boolean canOverLimit = false;
246            if (availableOnly) {
247                for (Reservation r: getReservations(course)) {
248                    if (!r.canBatchAssignOverLimit()) continue;
249                    if (!r.getConfigs().isEmpty() && !r.getConfigs().contains(config)) continue;
250                    if (r.getReservedAvailableSpace(assignment, this) < getWeight()) continue;
251                    canOverLimit = true; break;
252                }
253            }
254            if (!canOverLimit) {
255                if (availableOnly && config.getLimit() >= 0 && ConfigLimit.getEnrollmentWeight(assignment, config, this) > config.getLimit())
256                    return;
257                if (availableOnly && course.getLimit() >= 0 && CourseLimit.getEnrollmentWeight(assignment, course, this) > course.getLimit())
258                    return;
259                if (config.getOffering().hasReservations()) {
260                    boolean hasReservation = false, hasOtherReservation = false, hasConfigReservation = false, reservationMustBeUsed = false;
261                    for (Reservation r: getReservations(course)) {
262                        if (r.mustBeUsed()) reservationMustBeUsed = true;
263                        if (availableOnly && r.getReservedAvailableSpace(assignment, this) < getWeight()) continue;
264                        if (r.getConfigs().isEmpty()) {
265                            hasReservation = true;
266                        } else if (r.getConfigs().contains(config)) {
267                            hasReservation = true;
268                            hasConfigReservation = true;
269                        } else {
270                            hasOtherReservation = true;
271                        }
272                    }
273                    if (!hasConfigReservation && config.getTotalUnreservedSpace() < getWeight())
274                        return;
275                    if (!hasReservation && config.getOffering().getTotalUnreservedSpace() < getWeight())
276                        return;
277                    if (hasOtherReservation && !hasReservation)
278                        return;
279                    if (availableOnly && !hasReservation && config.getOffering().getUnreservedSpace(assignment, this) < getWeight())
280                        return;
281                    if (availableOnly && !hasConfigReservation && config.getUnreservedSpace(assignment, this) < getWeight())
282                        return;
283                    if (!hasReservation && reservationMustBeUsed)
284                        return;
285                }
286            }
287        }
288        if (config.getSubparts().size() == idx) {
289            if (skipSameTime && sSameTimePrecise) {
290                boolean waitListedOrSelected = false;
291                if (!getSelectedChoices().isEmpty() || !getWaitlistedChoices().isEmpty()) {
292                    for (Section section : sections) {
293                        if (isWaitlisted(section) || isSelected(section)) {
294                            waitListedOrSelected = true;
295                            break;
296                        }
297                    }
298                }
299                if (!waitListedOrSelected) {
300                    for (Enrollment enrollment : enrollments) {
301                        if (sameTimes(enrollment.getSections(), sections))
302                            return;
303                    }
304                }
305            }
306            if (!config.getOffering().hasReservations()) {
307                enrollments.add(new Enrollment(this, priority, null, config, new HashSet<SctAssignment>(sections), null));
308            } else {
309                Enrollment e = new Enrollment(this, priority, null, config, new HashSet<SctAssignment>(sections), null);
310                boolean mustHaveReservation = config.getOffering().getTotalUnreservedSpace() < getWeight();
311                boolean mustHaveConfigReservation = config.getTotalUnreservedSpace() < getWeight();
312                boolean mustHaveSectionReservation = false;
313                for (Section s: sections) {
314                    if (s.getTotalUnreservedSpace() < getWeight()) {
315                        mustHaveSectionReservation = true;
316                        break;
317                    }
318                }
319                boolean canOverLimit = false;
320                if (availableOnly) {
321                    for (Reservation r: getReservations(course)) {
322                        if (!r.canBatchAssignOverLimit() || !r.isIncluded(e)) continue;
323                        if (r.getReservedAvailableSpace(assignment, this) < getWeight()) continue;
324                        enrollments.add(new Enrollment(this, priority, null, config, new HashSet<SctAssignment>(sections), r));
325                        canOverLimit = true;
326                    }
327                }
328                if (!canOverLimit) {
329                    boolean reservationMustBeUsed = false;
330                    reservations: for (Reservation r: (availableOnly ? getSortedReservations(assignment, course) : getReservations(course))) {
331                        if (r.mustBeUsed()) reservationMustBeUsed = true;
332                        if (!r.isIncluded(e)) continue;
333                        if (availableOnly && r.getReservedAvailableSpace(assignment, this) < getWeight()) continue;
334                        if (mustHaveConfigReservation && r.getConfigs().isEmpty()) continue;
335                        if (mustHaveSectionReservation)
336                            for (Section s: sections)
337                                if (r.getSections(s.getSubpart()) == null && s.getTotalUnreservedSpace() < getWeight()) continue reservations;
338                        enrollments.add(new Enrollment(this, priority, null, config, new HashSet<SctAssignment>(sections), r));
339                        if (availableOnly) return; // only one available reservation suffice (the best matching one)
340                    }
341                    // a case w/o reservation
342                    if (!(mustHaveReservation || mustHaveConfigReservation || mustHaveSectionReservation) &&
343                        !(availableOnly && config.getOffering().getUnreservedSpace(assignment, this) < getWeight()) &&
344                        !reservationMustBeUsed) {
345                        enrollments.add(new Enrollment(this, (getReservations(course).isEmpty() ? 0 : 1) + priority, null, config, new HashSet<SctAssignment>(sections), null));
346                    }
347                }
348            }
349        } else {
350            Subpart subpart = config.getSubparts().get(idx);
351            HashSet<TimeLocation> times = (skipSameTime ? new HashSet<TimeLocation>() : null);
352            List<Section> sectionsThisSubpart = subpart.getSections();
353            if (skipSameTime) {
354                sectionsThisSubpart = new ArrayList<Section>(subpart.getSections());
355                Collections.sort(sectionsThisSubpart, new AssignmentComparator<Section, Request, Enrollment>(assignment));
356            }
357            List<Section> matchingSectionsThisSubpart = new ArrayList<Section>(subpart.getSections().size());
358            boolean hasChildren = !subpart.getChildren().isEmpty();
359            for (Section section : sectionsThisSubpart) {
360                if (section.isCancelled())
361                    continue;
362                if (getInitialAssignment() != null && (getModel() != null && ((StudentSectioningModel)getModel()).getKeepInitialAssignments()) &&
363                        !getInitialAssignment().getAssignments().contains(section))
364                    continue;
365                if (section.getParent() != null && !sections.contains(section.getParent()))
366                    continue;
367                if (section.isOverlapping(sections))
368                    continue;
369                if (selectedOnly && !isSelected(section))
370                    continue;
371                boolean canOverLimit = false;
372                if (availableOnly) {
373                    for (Reservation r: getReservations(course)) {
374                        if (!r.canBatchAssignOverLimit()) continue;
375                        if (r.getSections(subpart) != null && !r.getSections(subpart).contains(section)) continue;
376                        if (r.getReservedAvailableSpace(assignment, this) < getWeight()) continue;
377                        canOverLimit = true; break;
378                    }
379                }
380                if (!canOverLimit) {
381                    if (availableOnly && section.getLimit() >= 0
382                            && SectionLimit.getEnrollmentWeight(assignment, section, this) > section.getLimit())
383                        continue;
384                    if (config.getOffering().hasReservations()) {
385                        boolean hasReservation = false, hasSectionReservation = false, hasOtherReservation = false, reservationMustBeUsed = false;
386                        for (Reservation r: getReservations(course)) {
387                            if (r.mustBeUsed()) reservationMustBeUsed = true;
388                            if (availableOnly && r.getReservedAvailableSpace(assignment, this) < getWeight()) continue;
389                            if (r.getSections(subpart) == null) {
390                                hasReservation = true;
391                            } else if (r.getSections(subpart).contains(section)) {
392                                hasReservation = true;
393                                hasSectionReservation = true;
394                            } else {
395                                hasOtherReservation = true;
396                            }
397                        }
398                        if (!hasSectionReservation && section.getTotalUnreservedSpace() < getWeight())
399                            continue;
400                        if (hasOtherReservation && !hasReservation)
401                            continue;
402                        if (availableOnly && !hasSectionReservation && section.getUnreservedSpace(assignment, this) < getWeight())
403                            continue;
404                        if (!hasReservation && reservationMustBeUsed)
405                            continue;
406                    }
407                }
408                if (skipSameTime && section.getTime() != null && !hasChildren && !times.add(section.getTime()) && !isSelected(section) && !isWaitlisted(section) && 
409                        (section.getIgnoreConflictWithSectionIds() == null || section.getIgnoreConflictWithSectionIds().isEmpty()))
410                    continue;
411                matchingSectionsThisSubpart.add(section);
412            }
413            if (random || limit > 0) {
414                sectionsThisSubpart = new ArrayList<Section>(sectionsThisSubpart);
415                Collections.shuffle(sectionsThisSubpart);
416            }
417            int i = 0;
418            for (Section section: matchingSectionsThisSubpart) {
419                sections.add(section);
420                computeEnrollments(assignment, enrollments, priority, penalty + section.getPenalty(), course, config, sections, idx + 1,
421                        availableOnly, skipSameTime, selectedOnly, random,
422                        limit < 0 ? limit : Math.max(1, limit * (1 + i) / matchingSectionsThisSubpart.size())
423                        );
424                sections.remove(section);
425                i++;
426            }
427        }
428    }
429
430    /** Return all enrollments that are available 
431     * @param assignment current assignment
432     * @return all available enrollments
433     **/
434    public List<Enrollment> getAvaiableEnrollments(Assignment<Request, Enrollment> assignment) {
435        List<Enrollment> ret = new ArrayList<Enrollment>();
436        int idx = 0;
437        for (Course course : iCourses) {
438            for (Config config : course.getOffering().getConfigs()) {
439                computeEnrollments(assignment, ret, idx, 0, course, config, new HashSet<Section>(), 0, true, false, false, false,
440                        getMaxDomainSize() <= 0 ? -1 : ret.size() + getMaxDomainSize());
441            }
442            idx++;
443        }
444        return ret;
445    }
446
447    /**
448     * Return all enrollments that are selected (
449     * {@link CourseRequest#isSelected(Section)} is true)
450     * 
451     * @param assignment current assignment
452     * @param availableOnly
453     *            pick only available sections
454     * @return selected enrollments
455     */
456    public List<Enrollment> getSelectedEnrollments(Assignment<Request, Enrollment> assignment, boolean availableOnly) {
457        if (getSelectedChoices().isEmpty())
458            return null;
459        Choice firstChoice = getSelectedChoices().iterator().next();
460        List<Enrollment> enrollments = new ArrayList<Enrollment>();
461        for (Course course : iCourses) {
462            if (!course.getOffering().equals(firstChoice.getOffering()))
463                continue;
464            for (Config config : course.getOffering().getConfigs()) {
465                computeEnrollments(assignment, enrollments, 0, 0, course, config, new HashSet<Section>(), 0, availableOnly, false, true, false, -1);
466            }
467        }
468        return enrollments;
469    }
470
471    /**
472     * Return all enrollments that are available, pick only the first section of
473     * the sections with the same time (of each subpart, {@link Section}
474     * comparator is used)
475     * @param assignment current assignment
476     * @return available enrollments 
477     */
478    public List<Enrollment> getAvaiableEnrollmentsSkipSameTime(Assignment<Request, Enrollment> assignment) {
479        List<Enrollment> ret = new ArrayList<Enrollment>();
480        if (getInitialAssignment() != null)
481            ret.add(getInitialAssignment());
482        int idx = 0;
483        for (Course course : iCourses) {
484            boolean skipSameTime = true;
485            for (LinkedSections link: getStudent().getLinkedSections())
486                if (link.getOfferings().contains(course.getOffering())) { skipSameTime = false; break; }
487            for (Config config : course.getOffering().getConfigs()) {
488                computeEnrollments(assignment, ret, idx, 0, course, config, new HashSet<Section>(), 0, true, skipSameTime, false, false,
489                        getMaxDomainSize() <= 0 ? -1 : ret.size() + getMaxDomainSize());
490            }
491            idx++;
492        }
493        return ret;
494    }
495
496    /**
497     * Return all possible enrollments, but pick only the first section of
498     * the sections with the same time (of each subpart, {@link Section}
499     * comparator is used).
500     * @param assignment current assignment
501     * @return computed enrollments 
502     */
503    public List<Enrollment> getEnrollmentsSkipSameTime(Assignment<Request, Enrollment> assignment) {
504        List<Enrollment> ret = new ArrayList<Enrollment>();
505        int idx = 0;
506        for (Course course : iCourses) {
507            for (Config config : course.getOffering().getConfigs()) {
508                boolean skipSameTime = true;
509                for (LinkedSections link: getStudent().getLinkedSections())
510                    if (link.getOfferings().contains(course.getOffering())) { skipSameTime = false; break; }
511                computeEnrollments(assignment, ret, idx, 0, course, config, new HashSet<Section>(), 0, false, skipSameTime, false, false,
512                        getMaxDomainSize() <= 0 ? -1 : ret.size() + getMaxDomainSize());
513            }
514            idx++;
515        }
516        return ret;
517    }
518
519    /** Wait-listed choices 
520     * @return wait-listed choices
521     **/
522    public Set<Choice> getWaitlistedChoices() {
523        return iWaitlistedChoices;
524    }
525
526    /**
527     * Return true when the given section is wait-listed (i.e., its choice is
528     * among wait-listed choices)
529     * @param section given section
530     * @return true if the given section matches the wait-listed choices
531     */
532    public boolean isWaitlisted(Section section) {
533        return iWaitlistedChoices.contains(section.getChoice());
534    }
535
536    /** Selected choices 
537     * @return selected choices
538     **/
539    public Set<Choice> getSelectedChoices() {
540        return iSelectedChoices;
541    }
542
543    /**
544     * Return true when the given section is selected (i.e., its choice is among
545     * selected choices)
546     * @param section given section
547     * @return true if the given section matches the selected choices
548     */
549    public boolean isSelected(Section section) {
550        return iSelectedChoices.contains(section.getChoice());
551    }
552
553    /**
554     * Request name: A for alternative, 1 + priority, (w) when wait-list, list of
555     * course names
556     */
557    @Override
558    public String getName() {
559        String ret = (isAlternative() ? "A" : "")
560                + (1 + getPriority() + (isAlternative() ? -getStudent().nrRequests() : 0)) + ". "
561                + (isWaitlist() ? "(w) " : "");
562        int idx = 0;
563        for (Course course : iCourses) {
564            if (idx == 0)
565                ret += course.getName();
566            else
567                ret += ", " + idx + ". alt " + course.getName();
568            idx++;
569        }
570        return ret;
571    }
572
573    /**
574     * True if the student can be put on a wait-list (no alternative course
575     * request will be given instead)
576     * @return true if the request can be wait-listed
577     */
578    public boolean isWaitlist() {
579        return iWaitlist;
580    }
581    
582    /**
583     * True if the student can be put on a wait-list (no alternative course
584     * request will be given instead)
585     * @param waitlist true if the request can be wait-listed
586     */
587    public void setWaitlist(boolean waitlist) {
588        iWaitlist = waitlist;
589    }
590    
591    /**
592     * Time stamp of the request
593     * @return request time stamp
594     */
595    public Long getTimeStamp() {
596        return iTimeStamp;
597    }
598
599    @Override
600    public String toString() {
601        return getName() + (getWeight() != 1.0 ? " (W:" + sDF.format(getWeight()) + ")" : "");
602    }
603
604    /** Return course of the requested courses with the given id 
605     * @param courseId course offering id
606     * @return course of the given id
607     **/
608    public Course getCourse(long courseId) {
609        for (Course course : iCourses) {
610            if (course.getId() == courseId)
611                return course;
612        }
613        return null;
614    }
615
616    /** Return configuration of the requested courses with the given id 
617     * @param configId instructional offering configuration unique id
618     * @return config of the given id
619     **/
620    public Config getConfig(long configId) {
621        for (Course course : iCourses) {
622            for (Config config : course.getOffering().getConfigs()) {
623                if (config.getId() == configId)
624                    return config;
625            }
626        }
627        return null;
628    }
629
630    /** Return subpart of the requested courses with the given id 
631     * @param subpartId scheduling subpart unique id
632     * @return subpart of the given id
633     **/
634    public Subpart getSubpart(long subpartId) {
635        for (Course course : iCourses) {
636            for (Config config : course.getOffering().getConfigs()) {
637                for (Subpart subpart : config.getSubparts()) {
638                    if (subpart.getId() == subpartId)
639                        return subpart;
640                }
641            }
642        }
643        return null;
644    }
645
646    /** Return section of the requested courses with the given id 
647     * @param sectionId class unique id
648     * @return section of the given id
649     **/
650    public Section getSection(long sectionId) {
651        for (Course course : iCourses) {
652            for (Config config : course.getOffering().getConfigs()) {
653                for (Subpart subpart : config.getSubparts()) {
654                    for (Section section : subpart.getSections()) {
655                        if (section.getId() == sectionId)
656                            return section;
657                    }
658                }
659            }
660        }
661        return null;
662    }
663
664    /**
665     * Minimal penalty (minimum of {@link Offering#getMinPenalty()} among
666     * requested courses)
667     * @return minimal penalty
668     */
669    public double getMinPenalty() {
670        if (iCachedMinPenalty == null) {
671            double min = Double.MAX_VALUE;
672            for (Course course : iCourses) {
673                min = Math.min(min, course.getOffering().getMinPenalty());
674            }
675            iCachedMinPenalty = new Double(min);
676        }
677        return iCachedMinPenalty.doubleValue();
678    }
679
680    /**
681     * Maximal penalty (maximum of {@link Offering#getMaxPenalty()} among
682     * requested courses)
683     * @return maximal penalty
684     */
685    public double getMaxPenalty() {
686        if (iCachedMaxPenalty == null) {
687            double max = Double.MIN_VALUE;
688            for (Course course : iCourses) {
689                max = Math.max(max, course.getOffering().getMaxPenalty());
690            }
691            iCachedMaxPenalty = new Double(max);
692        }
693        return iCachedMaxPenalty.doubleValue();
694    }
695
696    /** Clear cached min/max penalties and cached bound */
697    public void clearCache() {
698        iCachedMaxPenalty = null;
699        iCachedMinPenalty = null;
700    }
701
702    /**
703     * Estimated bound for this request -- it estimates the smallest value among
704     * all possible enrollments
705     */
706    @Override
707    public double getBound() {
708        return - getWeight() * ((StudentSectioningModel)getModel()).getStudentWeights().getBound(this);
709        /*
710        if (iCachedBound == null) {
711            iCachedBound = new Double(-Math.pow(Enrollment.sPriorityWeight, getPriority())
712                    * (isAlternative() ? Enrollment.sAlterativeWeight : 1.0)
713                    * Math.pow(Enrollment.sInitialWeight, (getInitialAssignment() == null ? 0 : 1))
714                    * Math.pow(Enrollment.sSelectedWeight, (iSelectedChoices.isEmpty() ? 0 : 1))
715                    * Math.pow(Enrollment.sWaitlistedWeight, (iWaitlistedChoices.isEmpty() ? 0 : 1))
716                    *
717                    // Math.max(Enrollment.sMinWeight,getWeight()) *
718                    (getStudent().isDummy() ? Student.sDummyStudentWeight : 1.0)
719                    * Enrollment.normalizePenalty(getMinPenalty()));
720        }
721        return iCachedBound.doubleValue();
722        */
723    }
724
725    /** Return true if request is assigned. */
726    @Override
727    public boolean isAssigned(Assignment<Request, Enrollment> assignment) {
728        Enrollment e = assignment.getValue(this);
729        return e != null && !e.getAssignments().isEmpty();
730    }
731
732    @Override
733    public boolean equals(Object o) {
734        return super.equals(o) && (o instanceof CourseRequest);
735    }
736    
737    /**
738     * Get reservations for this course requests
739     * @param course given course
740     * @return reservations for this course requests and the given course
741     */
742    public synchronized List<Reservation> getReservations(Course course) {
743        if (iReservations == null)
744            iReservations = new HashMap<Course, List<Reservation>>();
745        List<Reservation> reservations = iReservations.get(course);
746        if (reservations == null) {
747            reservations = new ArrayList<Reservation>();
748            boolean mustBeUsed = false;
749            for (Reservation r: course.getOffering().getReservations()) {
750                if (!r.isApplicable(getStudent())) continue;
751                if (!mustBeUsed && r.mustBeUsed()) { reservations.clear(); mustBeUsed = true; }
752                if (mustBeUsed && !r.mustBeUsed()) continue;
753                reservations.add(r);
754            }
755            iReservations.put(course, reservations);
756        }
757        return reservations;
758    }
759    private Map<Course, List<Reservation>> iReservations = null;
760    
761    /**
762     * Get reservations for this course requests ordered using {@link Reservation#compareTo(Assignment, Reservation)}
763     * @param course given course
764     * @return reservations for this course requests and the given course
765     */
766    public TreeSet<Reservation> getSortedReservations(Assignment<Request, Enrollment> assignment, Course course) {
767        TreeSet<Reservation> reservations = new TreeSet<Reservation>(new AssignmentComparator<Reservation, Request, Enrollment>(assignment));
768        reservations.addAll(getReservations(course));
769        return reservations;
770    }
771    
772    /**
773     * Return true if there is a reservation for a course of this request
774     * @return true if there is a reservation for a course of this request
775     */
776    public boolean hasReservations() {
777        for (Course course: getCourses())
778            if (!getReservations(course).isEmpty())
779                return true;
780        return false;
781    }
782    
783    /**
784     * Clear reservation information that was cached on this section
785     */
786    public synchronized void clearReservationCache() {
787        if (iReservations != null) iReservations.clear();
788    }
789    
790    /**
791     * Return true if this request can track MPP
792     * @return true if the request is course request and it either has an initial enrollment or some selected choices.
793     */
794    @Override
795    public boolean isMPP() {
796        StudentSectioningModel model = (StudentSectioningModel) getModel();
797        if (model == null || !model.isMPP()) return false;
798        return !getStudent().isDummy() && (getInitialAssignment() != null || !getSelectedChoices().isEmpty()); 
799    }
800    
801    /**
802     * Add request group to this request.
803     * @param group request group to be added
804     */
805    public void addRequestGroup(RequestGroup group) {
806        iRequestGroups.add(group);
807        group.addRequest(this);
808    }
809    
810    /**
811     * Removed request group from this request.
812     * @param group request group to be removed
813     */
814    public void removeRequestGroup(RequestGroup group) {
815        iRequestGroups.remove(group);
816        group.removeRequest(this);
817    }
818
819    /**
820     * Lists request groups of this request
821     * @return request groups of this course requests
822     */
823    public Set<RequestGroup> getRequestGroups() {
824        return iRequestGroups;
825    }
826    
827    @Override
828    public void variableAssigned(Assignment<Request, Enrollment> assignment, long iteration, Enrollment enrollment) {
829        super.variableAssigned(assignment, iteration, enrollment);
830        for (RequestGroup g: getRequestGroups())
831            if (g.getCourse().equals(enrollment.getCourse()))
832                g.assigned(assignment, enrollment);
833    }
834
835    @Override
836    public void variableUnassigned(Assignment<Request, Enrollment> assignment, long iteration, Enrollment enrollment) {
837        super.variableUnassigned(assignment, iteration, enrollment);
838        for (RequestGroup g: getRequestGroups())
839            if (g.getCourse().equals(enrollment.getCourse()))
840                g.unassigned(assignment, enrollment);
841    }
842}