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