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