001package org.cpsolver.studentsct;
002
003import java.text.DecimalFormat;
004import java.util.ArrayList;
005import java.util.Collection;
006import java.util.Comparator;
007import java.util.HashSet;
008import java.util.List;
009import java.util.Map;
010import java.util.Set;
011import java.util.TreeSet;
012
013import org.apache.logging.log4j.Logger;
014import org.cpsolver.coursett.Constants;
015import org.cpsolver.ifs.assignment.Assignment;
016import org.cpsolver.ifs.assignment.InheritedAssignment;
017import org.cpsolver.ifs.assignment.OptimisticInheritedAssignment;
018import org.cpsolver.ifs.assignment.context.AssignmentConstraintContext;
019import org.cpsolver.ifs.assignment.context.CanInheritContext;
020import org.cpsolver.ifs.assignment.context.ModelWithContext;
021import org.cpsolver.ifs.model.Constraint;
022import org.cpsolver.ifs.model.ConstraintListener;
023import org.cpsolver.ifs.model.InfoProvider;
024import org.cpsolver.ifs.model.Model;
025import org.cpsolver.ifs.solution.Solution;
026import org.cpsolver.ifs.util.DataProperties;
027import org.cpsolver.ifs.util.DistanceMetric;
028import org.cpsolver.studentsct.constraint.CancelledSections;
029import org.cpsolver.studentsct.constraint.ConfigLimit;
030import org.cpsolver.studentsct.constraint.CourseLimit;
031import org.cpsolver.studentsct.constraint.DisabledSections;
032import org.cpsolver.studentsct.constraint.FixInitialAssignments;
033import org.cpsolver.studentsct.constraint.LinkedSections;
034import org.cpsolver.studentsct.constraint.RequiredReservation;
035import org.cpsolver.studentsct.constraint.RequiredRestrictions;
036import org.cpsolver.studentsct.constraint.RequiredSections;
037import org.cpsolver.studentsct.constraint.ReservationLimit;
038import org.cpsolver.studentsct.constraint.SectionLimit;
039import org.cpsolver.studentsct.constraint.StudentConflict;
040import org.cpsolver.studentsct.constraint.StudentNotAvailable;
041import org.cpsolver.studentsct.extension.DistanceConflict;
042import org.cpsolver.studentsct.extension.StudentQuality;
043import org.cpsolver.studentsct.extension.TimeOverlapsCounter;
044import org.cpsolver.studentsct.model.Config;
045import org.cpsolver.studentsct.model.Course;
046import org.cpsolver.studentsct.model.CourseRequest;
047import org.cpsolver.studentsct.model.Enrollment;
048import org.cpsolver.studentsct.model.Offering;
049import org.cpsolver.studentsct.model.Request;
050import org.cpsolver.studentsct.model.RequestGroup;
051import org.cpsolver.studentsct.model.Section;
052import org.cpsolver.studentsct.model.Student;
053import org.cpsolver.studentsct.model.Subpart;
054import org.cpsolver.studentsct.model.Unavailability;
055import org.cpsolver.studentsct.model.Request.RequestPriority;
056import org.cpsolver.studentsct.model.Student.BackToBackPreference;
057import org.cpsolver.studentsct.model.Student.ModalityPreference;
058import org.cpsolver.studentsct.model.Student.StudentPriority;
059import org.cpsolver.studentsct.reservation.Reservation;
060import org.cpsolver.studentsct.weights.PriorityStudentWeights;
061import org.cpsolver.studentsct.weights.StudentWeights;
062
063/**
064 * Student sectioning model.
065 * 
066 * <br>
067 * <br>
068 * 
069 * @version StudentSct 1.3 (Student Sectioning)<br>
070 *          Copyright (C) 2007 - 2014 Tomáš Müller<br>
071 *          <a href="mailto:muller@unitime.org">muller@unitime.org</a><br>
072 *          <a href="http://muller.unitime.org">http://muller.unitime.org</a><br>
073 * <br>
074 *          This library is free software; you can redistribute it and/or modify
075 *          it under the terms of the GNU Lesser General Public License as
076 *          published by the Free Software Foundation; either version 3 of the
077 *          License, or (at your option) any later version. <br>
078 * <br>
079 *          This library is distributed in the hope that it will be useful, but
080 *          WITHOUT ANY WARRANTY; without even the implied warranty of
081 *          MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
082 *          Lesser General Public License for more details. <br>
083 * <br>
084 *          You should have received a copy of the GNU Lesser General Public
085 *          License along with this library; if not see
086 *          <a href='http://www.gnu.org/licenses/'>http://www.gnu.org/licenses/</a>.
087 */
088public class StudentSectioningModel extends ModelWithContext<Request, Enrollment, StudentSectioningModel.StudentSectioningModelContext> implements CanInheritContext<Request, Enrollment, StudentSectioningModel.StudentSectioningModelContext> {
089    private static Logger sLog = org.apache.logging.log4j.LogManager.getLogger(StudentSectioningModel.class);
090    protected static DecimalFormat sDecimalFormat = new DecimalFormat("0.00");
091    private List<Student> iStudents = new ArrayList<Student>();
092    private List<Offering> iOfferings = new ArrayList<Offering>();
093    private List<LinkedSections> iLinkedSections = new ArrayList<LinkedSections>();
094    private DataProperties iProperties;
095    private DistanceConflict iDistanceConflict = null;
096    private TimeOverlapsCounter iTimeOverlaps = null;
097    private StudentQuality iStudentQuality = null;
098    private int iNrDummyStudents = 0, iNrDummyRequests = 0;
099    private int[] iNrPriorityStudents = null;
100    private double iTotalDummyWeight = 0.0;
101    private double iTotalCRWeight = 0.0, iTotalDummyCRWeight = 0.0;
102    private double[] iTotalPriorityCRWeight = null;
103    private double[] iTotalCriticalCRWeight;
104    private double[][] iTotalPriorityCriticalCRWeight;
105    private double iTotalMPPCRWeight = 0.0;
106    private double iTotalSelCRWeight = 0.0;
107    private double iBestAssignedCourseRequestWeight = 0.0;
108    private StudentWeights iStudentWeights = null;
109    private boolean iReservationCanAssignOverTheLimit;
110    private boolean iMPP;
111    private boolean iKeepInitials;
112    protected double iProjectedStudentWeight = 0.0100;
113    private int iMaxDomainSize = -1; 
114    private int iDayOfWeekOffset = 0;
115
116
117    /**
118     * Constructor
119     * 
120     * @param properties
121     *            configuration
122     */
123    @SuppressWarnings("unchecked")
124    public StudentSectioningModel(DataProperties properties) {
125        super();
126        iTotalCriticalCRWeight = new double[RequestPriority.values().length];
127        iTotalPriorityCriticalCRWeight = new double[RequestPriority.values().length][StudentPriority.values().length];
128        for (int i = 0; i < RequestPriority.values().length; i++) {
129            iTotalCriticalCRWeight[i] = 0.0;
130            for (int j = 0; j < StudentPriority.values().length; j++) {
131                iTotalPriorityCriticalCRWeight[i][j] = 0.0;
132            }
133        }
134        iNrPriorityStudents = new int[StudentPriority.values().length];
135        iTotalPriorityCRWeight = new double[StudentPriority.values().length];
136        for (int i = 0; i < StudentPriority.values().length; i++) {
137            iNrPriorityStudents[i] = 0;
138            iTotalPriorityCRWeight[i] = 0.0;
139        }
140        iReservationCanAssignOverTheLimit =  properties.getPropertyBoolean("Reservation.CanAssignOverTheLimit", false);
141        iMPP = properties.getPropertyBoolean("General.MPP", false);
142        iKeepInitials = properties.getPropertyBoolean("Sectioning.KeepInitialAssignments", false);
143        iStudentWeights = new PriorityStudentWeights(properties);
144        iMaxDomainSize = properties.getPropertyInt("Sectioning.MaxDomainSize", iMaxDomainSize);
145        iDayOfWeekOffset = properties.getPropertyInt("DatePattern.DayOfWeekOffset", 0);
146        if (properties.getPropertyBoolean("Sectioning.SectionLimit", true)) {
147            SectionLimit sectionLimit = new SectionLimit(properties);
148            addGlobalConstraint(sectionLimit);
149            if (properties.getPropertyBoolean("Sectioning.SectionLimit.Debug", false)) {
150                sectionLimit.addConstraintListener(new ConstraintListener<Request, Enrollment>() {
151                    @Override
152                    public void constraintBeforeAssigned(Assignment<Request, Enrollment> assignment, long iteration, Constraint<Request, Enrollment> constraint, Enrollment enrollment, Set<Enrollment> unassigned) {
153                        if (enrollment.getStudent().isDummy())
154                            for (Enrollment conflict : unassigned) {
155                                if (!conflict.getStudent().isDummy()) {
156                                    sLog.warn("Enrolment of a real student " + conflict.getStudent() + " is unassigned "
157                                            + "\n  -- " + conflict + "\ndue to an enrollment of a dummy student "
158                                            + enrollment.getStudent() + " " + "\n  -- " + enrollment);
159                                }
160                            }
161                    }
162
163                    @Override
164                    public void constraintAfterAssigned(Assignment<Request, Enrollment> assignment, long iteration, Constraint<Request, Enrollment> constraint, Enrollment assigned, Set<Enrollment> unassigned) {
165                    }
166                });
167            }
168        }
169        if (properties.getPropertyBoolean("Sectioning.ConfigLimit", true)) {
170            ConfigLimit configLimit = new ConfigLimit(properties);
171            addGlobalConstraint(configLimit);
172        }
173        if (properties.getPropertyBoolean("Sectioning.CourseLimit", true)) {
174            CourseLimit courseLimit = new CourseLimit(properties);
175            addGlobalConstraint(courseLimit);
176        }
177        if (properties.getPropertyBoolean("Sectioning.ReservationLimit", true)) {
178            ReservationLimit reservationLimit = new ReservationLimit(properties);
179            addGlobalConstraint(reservationLimit);
180        }
181        if (properties.getPropertyBoolean("Sectioning.RequiredReservations", true)) {
182            RequiredReservation requiredReservation = new RequiredReservation();
183            addGlobalConstraint(requiredReservation);
184        }
185        if (properties.getPropertyBoolean("Sectioning.CancelledSections", true)) {
186            CancelledSections cancelledSections = new CancelledSections();
187            addGlobalConstraint(cancelledSections);
188        }
189        if (properties.getPropertyBoolean("Sectioning.StudentNotAvailable", true)) {
190            StudentNotAvailable studentNotAvailable = new StudentNotAvailable();
191            addGlobalConstraint(studentNotAvailable);
192        }
193        if (properties.getPropertyBoolean("Sectioning.DisabledSections", true)) {
194            DisabledSections disabledSections = new DisabledSections();
195            addGlobalConstraint(disabledSections);
196        }
197        if (properties.getPropertyBoolean("Sectioning.RequiredSections", true)) {
198            RequiredSections requiredSections = new RequiredSections();
199            addGlobalConstraint(requiredSections);
200        }
201        if (properties.getPropertyBoolean("Sectioning.RequiredRestrictions", true)) {
202            RequiredRestrictions requiredRestrictions = new RequiredRestrictions();
203            addGlobalConstraint(requiredRestrictions);
204        }
205        if (iMPP && iKeepInitials) {
206            addGlobalConstraint(new FixInitialAssignments());
207        }
208        try {
209            Class<StudentWeights> studentWeightsClass = (Class<StudentWeights>)Class.forName(properties.getProperty("StudentWeights.Class", PriorityStudentWeights.class.getName()));
210            iStudentWeights = studentWeightsClass.getConstructor(DataProperties.class).newInstance(properties);
211        } catch (Exception e) {
212            sLog.error("Unable to create custom student weighting model (" + e.getMessage() + "), using default.", e);
213            iStudentWeights = new PriorityStudentWeights(properties);
214        }
215        iProjectedStudentWeight = properties.getPropertyDouble("StudentWeights.ProjectedStudentWeight", iProjectedStudentWeight);
216        iProperties = properties;
217    }
218    
219    /**
220     * Return true if reservation that has {@link Reservation#canAssignOverLimit()} can assign enrollments over the limit
221     * @return true if reservation that has {@link Reservation#canAssignOverLimit()} can assign enrollments over the limit
222     */
223    public boolean getReservationCanAssignOverTheLimit() {
224        return iReservationCanAssignOverTheLimit;
225    }
226    
227    /**
228     * Return true if the problem is minimal perturbation problem 
229     * @return true if MPP is enabled
230     */
231    public boolean isMPP() {
232        return iMPP;
233    }
234    
235    /**
236     * Return true if the inital assignments are to be kept unchanged 
237     * @return true if the initial assignments are to be kept at all cost
238     */
239    public boolean getKeepInitialAssignments() {
240        return iKeepInitials;
241    }
242    
243    /**
244     * Return student weighting model
245     * @return student weighting model
246     */
247    public StudentWeights getStudentWeights() {
248        return iStudentWeights;
249    }
250
251    /**
252     * Set student weighting model
253     * @param weights student weighting model
254     */
255    public void setStudentWeights(StudentWeights weights) {
256        iStudentWeights = weights;
257    }
258
259    /**
260     * Students
261     * @return all students in the problem
262     */
263    public List<Student> getStudents() {
264        return iStudents;
265    }
266
267    /**
268     * Add a student into the model
269     * @param student a student to be added into the problem
270     */
271    public void addStudent(Student student) {
272        iStudents.add(student);
273        if (student.isDummy())
274            iNrDummyStudents++;
275        iNrPriorityStudents[student.getPriority().ordinal()]++;
276        for (Request request : student.getRequests())
277            addVariable(request);
278        if (getProperties().getPropertyBoolean("Sectioning.StudentConflict", true)) {
279            addConstraint(new StudentConflict(student));
280        }
281    }
282    
283    public int getNbrStudents(StudentPriority priority) {
284        return iNrPriorityStudents[priority.ordinal()];
285    }
286    
287    @Override
288    public void addVariable(Request request) {
289        super.addVariable(request);
290        if (request instanceof CourseRequest && !request.isAlternative())
291            iTotalCRWeight += request.getWeight();
292        if (request instanceof CourseRequest && request.getRequestPriority() != RequestPriority.Normal && !request.getStudent().isDummy() && !request.isAlternative())
293            iTotalCriticalCRWeight[request.getRequestPriority().ordinal()] += request.getWeight();
294        if (request instanceof CourseRequest && request.getRequestPriority() != RequestPriority.Normal && !request.isAlternative())
295            iTotalPriorityCriticalCRWeight[request.getRequestPriority().ordinal()][request.getStudent().getPriority().ordinal()] += request.getWeight();
296        if (request.getStudent().isDummy()) {
297            iNrDummyRequests++;
298            iTotalDummyWeight += request.getWeight();
299            if (request instanceof CourseRequest && !request.isAlternative())
300                iTotalDummyCRWeight += request.getWeight();
301        }
302        if (request instanceof CourseRequest && !request.isAlternative())
303            iTotalPriorityCRWeight[request.getStudent().getPriority().ordinal()] += request.getWeight();
304        if (request.isMPP())
305            iTotalMPPCRWeight += request.getWeight();
306        if (request.hasSelection())
307            iTotalSelCRWeight += request.getWeight();
308    }
309    
310    /** 
311     * Recompute cached request weights
312     * @param assignment current assignment
313     */
314    public void requestWeightsChanged(Assignment<Request, Enrollment> assignment) {
315        getContext(assignment).requestWeightsChanged(assignment);
316    }
317
318    /**
319     * Remove a student from the model
320     * @param student a student to be removed from the problem
321     */
322    public void removeStudent(Student student) {
323        iStudents.remove(student);
324        if (student.isDummy())
325            iNrDummyStudents--;
326        iNrPriorityStudents[student.getPriority().ordinal()]--;
327        StudentConflict conflict = null;
328        for (Request request : student.getRequests()) {
329            for (Constraint<Request, Enrollment> c : request.constraints()) {
330                if (c instanceof StudentConflict) {
331                    conflict = (StudentConflict) c;
332                    break;
333                }
334            }
335            if (conflict != null) 
336                conflict.removeVariable(request);
337            removeVariable(request);
338        }
339        if (conflict != null) 
340            removeConstraint(conflict);
341    }
342    
343    @Override
344    public void removeVariable(Request request) {
345        super.removeVariable(request);
346        if (request instanceof CourseRequest) {
347            CourseRequest cr = (CourseRequest)request;
348            for (Course course: cr.getCourses())
349                course.getRequests().remove(request);
350        }
351        if (request.getStudent().isDummy()) {
352            iNrDummyRequests--;
353            iTotalDummyWeight -= request.getWeight();
354            if (request instanceof CourseRequest && !request.isAlternative())
355                iTotalDummyCRWeight -= request.getWeight();
356        }
357        if (request instanceof CourseRequest && !request.isAlternative())
358            iTotalPriorityCRWeight[request.getStudent().getPriority().ordinal()] -= request.getWeight();
359        if (request.isMPP())
360            iTotalMPPCRWeight -= request.getWeight();
361        if (request.hasSelection())
362            iTotalSelCRWeight -= request.getWeight();
363        if (request instanceof CourseRequest && !request.isAlternative())
364            iTotalCRWeight -= request.getWeight();
365        if (request instanceof CourseRequest && request.getRequestPriority() != RequestPriority.Normal && !request.getStudent().isDummy() && !request.isAlternative())
366            iTotalCriticalCRWeight[request.getRequestPriority().ordinal()] -= request.getWeight();
367        if (request instanceof CourseRequest && request.getRequestPriority() != RequestPriority.Normal && !request.isAlternative())
368            iTotalPriorityCriticalCRWeight[request.getRequestPriority().ordinal()][request.getStudent().getPriority().ordinal()] -= request.getWeight();
369    }
370
371
372    /**
373     * List of offerings
374     * @return all instructional offerings of the problem
375     */
376    public List<Offering> getOfferings() {
377        return iOfferings;
378    }
379
380    /**
381     * Add an offering into the model
382     * @param offering an instructional offering to be added into the problem
383     */
384    public void addOffering(Offering offering) {
385        iOfferings.add(offering);
386        offering.setModel(this);
387    }
388    
389    /**
390     * Link sections using {@link LinkedSections}
391     * @param mustBeUsed if true,  a pair of linked sections must be used when a student requests both courses 
392     * @param sections a linked section constraint to be added into the problem
393     */
394    public void addLinkedSections(boolean mustBeUsed, Section... sections) {
395        LinkedSections constraint = new LinkedSections(sections);
396        constraint.setMustBeUsed(mustBeUsed);
397        iLinkedSections.add(constraint);
398        constraint.createConstraints();
399    }
400    
401    /**
402     * Link sections using {@link LinkedSections}
403     * @param sections a linked section constraint to be added into the problem
404     */
405    @Deprecated
406    public void addLinkedSections(Section... sections) {
407        addLinkedSections(false, sections);
408    }
409
410    /**
411     * Link sections using {@link LinkedSections}
412     * @param mustBeUsed if true,  a pair of linked sections must be used when a student requests both courses 
413     * @param sections a linked section constraint to be added into the problem
414     */
415    public void addLinkedSections(boolean mustBeUsed, Collection<Section> sections) {
416        LinkedSections constraint = new LinkedSections(sections);
417        constraint.setMustBeUsed(mustBeUsed);
418        iLinkedSections.add(constraint);
419        constraint.createConstraints();
420    }
421    
422    /**
423     * Link sections using {@link LinkedSections}
424     * @param sections a linked section constraint to be added into the problem
425     */
426    @Deprecated
427    public void addLinkedSections(Collection<Section> sections) {
428        addLinkedSections(false, sections);
429    }
430
431    /**
432     * List of linked sections
433     * @return all linked section constraints of the problem
434     */
435    public List<LinkedSections> getLinkedSections() {
436        return iLinkedSections;
437    }
438
439    /**
440     * Model info
441     */
442    @Override
443    public Map<String, String> getInfo(Assignment<Request, Enrollment> assignment) {
444        Map<String, String> info = super.getInfo(assignment);
445        StudentSectioningModelContext context = getContext(assignment);
446        if (!getStudents().isEmpty())
447            info.put("Students with complete schedule", sDoubleFormat.format(100.0 * context.nrComplete() / getStudents().size()) + "% (" + context.nrComplete() + "/" + getStudents().size() + ")");
448        String priorityComplete = "";
449        for (StudentPriority sp: StudentPriority.values()) {
450            if (sp != StudentPriority.Dummy && iNrPriorityStudents[sp.ordinal()] > 0)
451                priorityComplete += (priorityComplete.isEmpty() ? "" : "\n") +
452                    sp.name() + ": " + sDoubleFormat.format(100.0 * context.iNrCompletePriorityStudents[sp.ordinal()] / iNrPriorityStudents[sp.ordinal()]) + "% (" + context.iNrCompletePriorityStudents[sp.ordinal()] + "/" + iNrPriorityStudents[sp.ordinal()] + ")";
453        }
454        if (!priorityComplete.isEmpty())
455            info.put("Students with complete schedule (priority students)", priorityComplete);
456        if (getStudentQuality() != null) {
457            int confs = getStudentQuality().getTotalPenalty(StudentQuality.Type.Distance, assignment);
458            int shortConfs = getStudentQuality().getTotalPenalty(StudentQuality.Type.ShortDistance, assignment);
459            if (confs > 0 || shortConfs > 0) {
460                info.put("Student distance conflicts", confs + (shortConfs == 0 ? "" : " (" + getDistanceMetric().getShortDistanceAccommodationReference() + ": " + shortConfs + ")"));
461            }
462        } else if (getDistanceConflict() != null) {
463            int confs = getDistanceConflict().getTotalNrConflicts(assignment);
464            if (confs > 0) {
465                int shortConfs = getDistanceConflict().getTotalNrShortConflicts(assignment);
466                info.put("Student distance conflicts", confs + (shortConfs == 0 ? "" : " (" + getDistanceConflict().getDistanceMetric().getShortDistanceAccommodationReference() + ": " + shortConfs + ")"));
467            }
468        }
469        if (getStudentQuality() != null) {
470            int shareCR = getStudentQuality().getContext(assignment).countTotalPenalty(StudentQuality.Type.CourseTimeOverlap, assignment);
471            int shareFT = getStudentQuality().getContext(assignment).countTotalPenalty(StudentQuality.Type.FreeTimeOverlap, assignment);
472            int shareUN = getStudentQuality().getContext(assignment).countTotalPenalty(StudentQuality.Type.Unavailability, assignment);
473            if (shareCR + shareFT + shareUN > 0)
474                info.put("Time overlapping conflicts", sDoubleFormat.format((5.0 * (shareCR + shareFT + shareUN)) / iStudents.size()) + " mins per student\n" + 
475                        "(" + sDoubleFormat.format(5.0 * shareCR / iStudents.size()) + " between courses, " + sDoubleFormat.format(5.0 * shareFT / iStudents.size()) + " free time" +
476                        (shareUN == 0 ? "" : ", " + sDoubleFormat.format(5.0 * shareUN / iStudents.size()) + " teaching assignments") + "; " + sDoubleFormat.format((shareCR + shareFT + shareUN) / 12.0) + " hours total)");
477        } else if (getTimeOverlaps() != null && getTimeOverlaps().getTotalNrConflicts(assignment) != 0) {
478            info.put("Time overlapping conflicts", sDoubleFormat.format(5.0 * getTimeOverlaps().getTotalNrConflicts(assignment) / iStudents.size()) + " mins per student (" + sDoubleFormat.format(getTimeOverlaps().getTotalNrConflicts(assignment) / 12.0) + " hours total)");
479        }
480        if (getStudentQuality() != null) {
481            int confLunch = getStudentQuality().getTotalPenalty(StudentQuality.Type.LunchBreak, assignment);
482            if (confLunch > 0)
483                info.put("Schedule Quality: Lunch conflicts", sDoubleFormat.format(20.0 * confLunch / getNrRealStudents(false)) + "% (" + confLunch + ")");
484            int confTravel = getStudentQuality().getTotalPenalty(StudentQuality.Type.TravelTime, assignment);
485            if (confTravel > 0)
486                info.put("Schedule Quality: Travel time", sDoubleFormat.format(((double)confTravel) / getNrRealStudents(false)) + " mins per student (" + sDecimalFormat.format(confTravel / 60.0) + " hours total)");
487            int confBtB = getStudentQuality().getTotalPenalty(StudentQuality.Type.BackToBack, assignment);
488            if (confBtB != 0)
489                info.put("Schedule Quality: Back-to-back classes", sDoubleFormat.format(((double)confBtB) / getNrRealStudents(false)) + " per student (" + confBtB + ")");
490            int confMod = getStudentQuality().getTotalPenalty(StudentQuality.Type.Modality, assignment);
491            if (confMod > 0)
492                info.put("Schedule Quality: Online class preference", sDoubleFormat.format(((double)confMod) / getNrRealStudents(false)) + " per student (" + confMod + ")");
493            int confWorkDay = getStudentQuality().getTotalPenalty(StudentQuality.Type.WorkDay, assignment);
494            if (confWorkDay > 0)
495                info.put("Schedule Quality: Work day", sDoubleFormat.format(5.0 * confWorkDay / getNrRealStudents(false)) + " mins over " +
496                        new DecimalFormat("0.#").format(getProperties().getPropertyInt("WorkDay.WorkDayLimit", 6*12) / 12.0) + " hours a day per student\n(from start to end, " + sDoubleFormat.format(confWorkDay / 12.0) + " hours total)");
497            int early = getStudentQuality().getTotalPenalty(StudentQuality.Type.TooEarly, assignment);
498            if (early > 0) {
499                int min = getProperties().getPropertyInt("WorkDay.EarlySlot", 102) * Constants.SLOT_LENGTH_MIN + Constants.FIRST_SLOT_TIME_MIN;
500                int h = min / 60;
501                int m = min % 60;
502                String time = (getProperties().getPropertyBoolean("General.UseAmPm", true) ? (h > 12 ? h - 12 : h) + ":" + (m < 10 ? "0" : "") + m + (h >= 12 ? "p" : "a") : h + ":" + (m < 10 ? "0" : "") + m);
503                info.put("Schedule Quality: Early classes", sDoubleFormat.format(5.0 * early / iStudents.size()) + " mins before " + time + " per student (" + sDoubleFormat.format(early / 12.0) + " hours total)");
504            }
505            int late = getStudentQuality().getTotalPenalty(StudentQuality.Type.TooLate, assignment);
506            if (late > 0) {
507                int min = getProperties().getPropertyInt("WorkDay.LateSlot", 210) * Constants.SLOT_LENGTH_MIN + Constants.FIRST_SLOT_TIME_MIN;
508                int h = min / 60;
509                int m = min % 60;
510                String time = (getProperties().getPropertyBoolean("General.UseAmPm", true) ? (h > 12 ? h - 12 : h) + ":" + (m < 10 ? "0" : "") + m + (h >= 12 ? "p" : "a") : h + ":" + (m < 10 ? "0" : "") + m);
511                info.put("Schedule Quality: Late classes", sDoubleFormat.format(5.0 * late / iStudents.size()) + " mins after " + time + " per student (" + sDoubleFormat.format(late / 12.0) + " hours total)");
512            }
513            int accFT = getStudentQuality().getTotalPenalty(StudentQuality.Type.AccFreeTimeOverlap, assignment);
514            if (accFT > 0) {
515                info.put("Accommodations: Free time conflicts", sDoubleFormat.format(5.0 * accFT / getStudentsWithAccommodation(getStudentQuality().getStudentQualityContext().getFreeTimeAccommodation())) + " mins per student, " + sDoubleFormat.format(accFT / 12.0) + " hours total");
516            }
517            int accBtB = getStudentQuality().getTotalPenalty(StudentQuality.Type.AccBackToBack, assignment);
518            if (accBtB > 0) {
519                info.put("Accommodations: Back-to-back classes", sDoubleFormat.format(((double)accBtB) / getStudentsWithAccommodation(getStudentQuality().getStudentQualityContext().getBackToBackAccommodation())) + " non-BTB classes per student, " + accBtB + " total");
520            }
521            int accBbc = getStudentQuality().getTotalPenalty(StudentQuality.Type.AccBreaksBetweenClasses, assignment);
522            if (accBbc > 0) {
523                info.put("Accommodations: Break between classes", sDoubleFormat.format(((double)accBbc) / getStudentsWithAccommodation(getStudentQuality().getStudentQualityContext().getBreakBetweenClassesAccommodation())) + " BTB classes per student, " + accBbc + " total");
524            }
525            int shortConfs = getStudentQuality().getTotalPenalty(StudentQuality.Type.ShortDistance, assignment);
526            if (shortConfs > 0) {
527                info.put("Accommodations: Distance conflicts", sDoubleFormat.format(((double)shortConfs) / getStudentsWithAccommodation(getStudentQuality().getDistanceMetric().getShortDistanceAccommodationReference())) + " short distance conflicts per student, " + shortConfs + " total");
528            }
529        }
530        int nrLastLikeStudents = getNrLastLikeStudents(false);
531        if (nrLastLikeStudents != 0 && nrLastLikeStudents != getStudents().size()) {
532            int nrRealStudents = getStudents().size() - nrLastLikeStudents;
533            int nrLastLikeCompleteStudents = getNrCompleteLastLikeStudents(assignment, false);
534            int nrRealCompleteStudents = context.nrComplete() - nrLastLikeCompleteStudents;
535            if (nrLastLikeStudents > 0)
536                info.put("Projected students with complete schedule", sDecimalFormat.format(100.0
537                        * nrLastLikeCompleteStudents / nrLastLikeStudents)
538                        + "% (" + nrLastLikeCompleteStudents + "/" + nrLastLikeStudents + ")");
539            if (nrRealStudents > 0)
540                info.put("Real students with complete schedule", sDecimalFormat.format(100.0 * nrRealCompleteStudents
541                        / nrRealStudents)
542                        + "% (" + nrRealCompleteStudents + "/" + nrRealStudents + ")");
543            int nrLastLikeRequests = getNrLastLikeRequests(false);
544            int nrRealRequests = variables().size() - nrLastLikeRequests;
545            int nrLastLikeAssignedRequests = context.getNrAssignedLastLikeRequests();
546            int nrRealAssignedRequests = assignment.nrAssignedVariables() - nrLastLikeAssignedRequests;
547            if (nrLastLikeRequests > 0)
548                info.put("Projected assigned requests", sDecimalFormat.format(100.0 * nrLastLikeAssignedRequests / nrLastLikeRequests)
549                        + "% (" + nrLastLikeAssignedRequests + "/" + nrLastLikeRequests + ")");
550            if (nrRealRequests > 0)
551                info.put("Real assigned requests", sDecimalFormat.format(100.0 * nrRealAssignedRequests / nrRealRequests)
552                        + "% (" + nrRealAssignedRequests + "/" + nrRealRequests + ")");
553        }
554        context.getInfo(assignment, info);
555        
556        double groupSpread = 0.0; double groupCount = 0;
557        for (Offering offering: iOfferings) {
558            for (Course course: offering.getCourses()) {
559                for (RequestGroup group: course.getRequestGroups()) {
560                    groupSpread += group.getAverageSpread(assignment) * group.getEnrollmentWeight(assignment, null);
561                    groupCount += group.getEnrollmentWeight(assignment, null);
562                }
563            }
564        }
565        if (groupCount > 0)
566            info.put("Same group", sDecimalFormat.format(100.0 * groupSpread / groupCount) + "%");
567
568        return info;
569    }
570
571    /**
572     * Overall solution value
573     * @param assignment current assignment
574     * @param precise true if should be computed
575     * @return solution value
576     */
577    public double getTotalValue(Assignment<Request, Enrollment> assignment, boolean precise) {
578        if (precise) {
579            double total = 0;
580            for (Request r: assignment.assignedVariables())
581                total += r.getWeight() * iStudentWeights.getWeight(assignment, assignment.getValue(r));
582            if (iDistanceConflict != null)
583                for (DistanceConflict.Conflict c: iDistanceConflict.computeAllConflicts(assignment))
584                    total -= avg(c.getR1().getWeight(), c.getR2().getWeight()) * iStudentWeights.getDistanceConflictWeight(assignment, c);
585            if (iTimeOverlaps != null)
586                for (TimeOverlapsCounter.Conflict c: iTimeOverlaps.getContext(assignment).computeAllConflicts(assignment)) {
587                    if (c.getR1() != null) total -= c.getR1Weight() * iStudentWeights.getTimeOverlapConflictWeight(assignment, c.getE1(), c);
588                    if (c.getR2() != null) total -= c.getR2Weight() * iStudentWeights.getTimeOverlapConflictWeight(assignment, c.getE2(), c);
589                }
590            if (iStudentQuality != null)
591                for (StudentQuality.Type t: StudentQuality.Type.values()) {
592                    for (StudentQuality.Conflict c: iStudentQuality.getContext(assignment).computeAllConflicts(t, assignment)) {
593                        switch (c.getType().getType()) {
594                            case REQUEST:
595                                if (c.getR1() instanceof CourseRequest)
596                                    total -= c.getR1Weight() * iStudentWeights.getStudentQualityConflictWeight(assignment, c.getE1(), c);
597                                else
598                                    total -= c.getR2Weight() * iStudentWeights.getStudentQualityConflictWeight(assignment, c.getE2(), c);
599                                break;
600                            case BOTH:
601                                total -= c.getR1Weight() * iStudentWeights.getStudentQualityConflictWeight(assignment, c.getE1(), c);  
602                                total -= c.getR2Weight() * iStudentWeights.getStudentQualityConflictWeight(assignment, c.getE2(), c);
603                                break;
604                            case LOWER:
605                                total -= avg(c.getR1().getWeight(), c.getR2().getWeight()) * iStudentWeights.getStudentQualityConflictWeight(assignment, c.getE1(), c);
606                                break;
607                            case HIGHER:
608                                total -= avg(c.getR1().getWeight(), c.getR2().getWeight()) * iStudentWeights.getStudentQualityConflictWeight(assignment, c.getE1(), c);
609                                break;
610                        }
611                    }    
612                }
613            return -total;
614        }
615        return getContext(assignment).getTotalValue();
616    }
617    
618    /**
619     * Overall solution value
620     */
621    @Override
622    public double getTotalValue(Assignment<Request, Enrollment> assignment) {
623        return getContext(assignment).getTotalValue();
624    }
625
626    /**
627     * Configuration
628     * @return solver configuration
629     */
630    public DataProperties getProperties() {
631        return iProperties;
632    }
633
634    /**
635     * Empty online student sectioning infos for all sections (see
636     * {@link Section#getSpaceExpected()} and {@link Section#getSpaceHeld()}).
637     */
638    public void clearOnlineSectioningInfos() {
639        for (Offering offering : iOfferings) {
640            for (Config config : offering.getConfigs()) {
641                for (Subpart subpart : config.getSubparts()) {
642                    for (Section section : subpart.getSections()) {
643                        section.setSpaceExpected(0);
644                        section.setSpaceHeld(0);
645                    }
646                }
647            }
648        }
649    }
650
651    /**
652     * Compute online student sectioning infos for all sections (see
653     * {@link Section#getSpaceExpected()} and {@link Section#getSpaceHeld()}).
654     * @param assignment current assignment
655     */
656    public void computeOnlineSectioningInfos(Assignment<Request, Enrollment> assignment) {
657        clearOnlineSectioningInfos();
658        for (Student student : getStudents()) {
659            if (!student.isDummy())
660                continue;
661            for (Request request : student.getRequests()) {
662                if (!(request instanceof CourseRequest))
663                    continue;
664                CourseRequest courseRequest = (CourseRequest) request;
665                Enrollment enrollment = assignment.getValue(courseRequest);
666                if (enrollment != null) {
667                    for (Section section : enrollment.getSections()) {
668                        section.setSpaceHeld(courseRequest.getWeight() + section.getSpaceHeld());
669                    }
670                }
671                List<Enrollment> feasibleEnrollments = new ArrayList<Enrollment>();
672                int totalLimit = 0;
673                for (Enrollment enrl : courseRequest.values(assignment)) {
674                    boolean overlaps = false;
675                    for (Request otherRequest : student.getRequests()) {
676                        if (otherRequest.equals(courseRequest) || !(otherRequest instanceof CourseRequest))
677                            continue;
678                        Enrollment otherErollment = assignment.getValue(otherRequest);
679                        if (otherErollment == null)
680                            continue;
681                        if (enrl.isOverlapping(otherErollment)) {
682                            overlaps = true;
683                            break;
684                        }
685                    }
686                    if (!overlaps) {
687                        feasibleEnrollments.add(enrl);
688                        if (totalLimit >= 0) {
689                            int limit = enrl.getLimit();
690                            if (limit < 0) totalLimit = -1;
691                            else totalLimit += limit;
692                        }
693                    }
694                }
695                double increment = courseRequest.getWeight() / (totalLimit > 0 ? totalLimit : feasibleEnrollments.size());
696                for (Enrollment feasibleEnrollment : feasibleEnrollments) {
697                    for (Section section : feasibleEnrollment.getSections()) {
698                        if (totalLimit > 0) {
699                            section.setSpaceExpected(section.getSpaceExpected() + increment * feasibleEnrollment.getLimit());
700                        } else {
701                            section.setSpaceExpected(section.getSpaceExpected() + increment);
702                        }
703                    }
704                }
705            }
706        }
707    }
708
709    /**
710     * Sum of weights of all requests that are not assigned (see
711     * {@link Request#getWeight()}).
712     * @param assignment current assignment
713     * @return unassigned request weight
714     */
715    public double getUnassignedRequestWeight(Assignment<Request, Enrollment> assignment) {
716        double weight = 0.0;
717        for (Request request : assignment.unassignedVariables(this)) {
718            weight += request.getWeight();
719        }
720        return weight;
721    }
722
723    /**
724     * Sum of weights of all requests (see {@link Request#getWeight()}).
725     * @return total request weight
726     */
727    public double getTotalRequestWeight() {
728        double weight = 0.0;
729        for (Request request : variables()) {
730            weight += request.getWeight();
731        }
732        return weight;
733    }
734
735    /**
736     * Set distance conflict extension
737     * @param dc distance conflicts extension
738     */
739    public void setDistanceConflict(DistanceConflict dc) {
740        iDistanceConflict = dc;
741    }
742
743    /**
744     * Return distance conflict extension
745     * @return distance conflicts extension
746     */
747    public DistanceConflict getDistanceConflict() {
748        return iDistanceConflict;
749    }
750
751    /**
752     * Set time overlaps extension
753     * @param toc time overlapping conflicts extension
754     */
755    public void setTimeOverlaps(TimeOverlapsCounter toc) {
756        iTimeOverlaps = toc;
757    }
758
759    /**
760     * Return time overlaps extension
761     * @return time overlapping conflicts extension
762     */
763    public TimeOverlapsCounter getTimeOverlaps() {
764        return iTimeOverlaps;
765    }
766    
767    public StudentQuality getStudentQuality() { return iStudentQuality; }
768    public void setStudentQuality(StudentQuality q, boolean register) {
769        if (iStudentQuality != null)
770            getInfoProviders().remove(iStudentQuality);
771        iStudentQuality = q;
772        if (iStudentQuality != null)
773            getInfoProviders().add(iStudentQuality);
774        if (register) {
775            iStudentQuality.setAssignmentContextReference(createReference(iStudentQuality));
776            iStudentQuality.register(this);
777        }
778    }
779    
780    public void setStudentQuality(StudentQuality q) {
781        setStudentQuality(q, true);
782    }
783
784    /**
785     * Average priority of unassigned requests (see
786     * {@link Request#getPriority()})
787     * @param assignment current assignment
788     * @return average priority of unassigned requests
789     */
790    public double avgUnassignPriority(Assignment<Request, Enrollment> assignment) {
791        double totalPriority = 0.0;
792        for (Request request : assignment.unassignedVariables(this)) {
793            if (request.isAlternative())
794                continue;
795            totalPriority += request.getPriority();
796        }
797        return 1.0 + totalPriority / assignment.nrUnassignedVariables(this);
798    }
799
800    /**
801     * Average number of requests per student (see {@link Student#getRequests()}
802     * )
803     * @return average number of requests per student
804     */
805    public double avgNrRequests() {
806        double totalRequests = 0.0;
807        int totalStudents = 0;
808        for (Student student : getStudents()) {
809            if (student.nrRequests() == 0)
810                continue;
811            totalRequests += student.nrRequests();
812            totalStudents++;
813        }
814        return totalRequests / totalStudents;
815    }
816
817    /** Number of last like ({@link Student#isDummy()} equals true) students. 
818     * @param precise true if to be computed
819     * @return number of last like (projected) students
820     **/
821    public int getNrLastLikeStudents(boolean precise) {
822        if (!precise)
823            return iNrDummyStudents;
824        int nrLastLikeStudents = 0;
825        for (Student student : getStudents()) {
826            if (student.isDummy())
827                nrLastLikeStudents++;
828        }
829        return nrLastLikeStudents;
830    }
831
832    /** Number of real ({@link Student#isDummy()} equals false) students. 
833     * @param precise true if to be computed
834     * @return number of real students
835     **/
836    public int getNrRealStudents(boolean precise) {
837        if (!precise)
838            return getStudents().size() - iNrDummyStudents;
839        int nrRealStudents = 0;
840        for (Student student : getStudents()) {
841            if (!student.isDummy())
842                nrRealStudents++;
843        }
844        return nrRealStudents;
845    }
846    
847    /**
848     * Count students with given accommodation
849     */
850    public int getStudentsWithAccommodation(String acc) {
851        int nrAccStudents = 0;
852        for (Student student : getStudents()) {
853            if (student.hasAccommodation(acc))
854                nrAccStudents++;
855        }
856        return nrAccStudents;
857    }
858
859    /**
860     * Number of last like ({@link Student#isDummy()} equals true) students with
861     * a complete schedule ({@link Student#isComplete(Assignment)} equals true).
862     * @param assignment current assignment
863     * @param precise true if to be computed
864     * @return number of last like (projected) students with a complete schedule
865     */
866    public int getNrCompleteLastLikeStudents(Assignment<Request, Enrollment> assignment, boolean precise) {
867        if (!precise)
868            return getContext(assignment).getNrCompleteLastLikeStudents();
869        int nrLastLikeStudents = 0;
870        for (Student student : getStudents()) {
871            if (student.isComplete(assignment) && student.isDummy())
872                nrLastLikeStudents++;
873        }
874        return nrLastLikeStudents;
875    }
876
877    /**
878     * Number of real ({@link Student#isDummy()} equals false) students with a
879     * complete schedule ({@link Student#isComplete(Assignment)} equals true).
880     * @param assignment current assignment
881     * @param precise true if to be computed
882     * @return number of real students with a complete schedule
883     */
884    public int getNrCompleteRealStudents(Assignment<Request, Enrollment> assignment, boolean precise) {
885        if (!precise)
886            return getContext(assignment).nrComplete() - getContext(assignment).getNrCompleteLastLikeStudents();
887        int nrRealStudents = 0;
888        for (Student student : getStudents()) {
889            if (student.isComplete(assignment) && !student.isDummy())
890                nrRealStudents++;
891        }
892        return nrRealStudents;
893    }
894
895    /**
896     * Number of requests from projected ({@link Student#isDummy()} equals true)
897     * students.
898     * @param precise true if to be computed
899     * @return number of requests from projected students 
900     */
901    public int getNrLastLikeRequests(boolean precise) {
902        if (!precise)
903            return iNrDummyRequests;
904        int nrLastLikeRequests = 0;
905        for (Request request : variables()) {
906            if (request.getStudent().isDummy())
907                nrLastLikeRequests++;
908        }
909        return nrLastLikeRequests;
910    }
911
912    /**
913     * Number of requests from real ({@link Student#isDummy()} equals false)
914     * students.
915     * @param precise true if to be computed
916     * @return number of requests from real students 
917     */
918    public int getNrRealRequests(boolean precise) {
919        if (!precise)
920            return variables().size() - iNrDummyRequests;
921        int nrRealRequests = 0;
922        for (Request request : variables()) {
923            if (!request.getStudent().isDummy())
924                nrRealRequests++;
925        }
926        return nrRealRequests;
927    }
928
929    /**
930     * Number of requests from projected ({@link Student#isDummy()} equals true)
931     * students that are assigned.
932     * @param assignment current assignment
933     * @param precise true if to be computed
934     * @return number of requests from projected students that are assigned
935     */
936    public int getNrAssignedLastLikeRequests(Assignment<Request, Enrollment> assignment, boolean precise) {
937        if (!precise)
938            return getContext(assignment).getNrAssignedLastLikeRequests();
939        int nrLastLikeRequests = 0;
940        for (Request request : assignment.assignedVariables()) {
941            if (request.getStudent().isDummy())
942                nrLastLikeRequests++;
943        }
944        return nrLastLikeRequests;
945    }
946
947    /**
948     * Number of requests from real ({@link Student#isDummy()} equals false)
949     * students that are assigned.
950     * @param assignment current assignment
951     * @param precise true if to be computed
952     * @return number of requests from real students that are assigned
953     */
954    public int getNrAssignedRealRequests(Assignment<Request, Enrollment> assignment, boolean precise) {
955        if (!precise)
956            return assignment.nrAssignedVariables() - getContext(assignment).getNrAssignedLastLikeRequests();
957        int nrRealRequests = 0;
958        for (Request request : assignment.assignedVariables()) {
959            if (!request.getStudent().isDummy())
960                nrRealRequests++;
961        }
962        return nrRealRequests;
963    }
964
965    /**
966     * Model extended info. Some more information (that is more expensive to
967     * compute) is added to an ordinary {@link Model#getInfo(Assignment)}.
968     */
969    @Override
970    public Map<String, String> getExtendedInfo(Assignment<Request, Enrollment> assignment) {
971        Map<String, String> info = getInfo(assignment);
972        /*
973        int nrLastLikeStudents = getNrLastLikeStudents(true);
974        if (nrLastLikeStudents != 0 && nrLastLikeStudents != getStudents().size()) {
975            int nrRealStudents = getStudents().size() - nrLastLikeStudents;
976            int nrLastLikeCompleteStudents = getNrCompleteLastLikeStudents(true);
977            int nrRealCompleteStudents = getCompleteStudents().size() - nrLastLikeCompleteStudents;
978            info.put("Projected students with complete schedule", sDecimalFormat.format(100.0
979                    * nrLastLikeCompleteStudents / nrLastLikeStudents)
980                    + "% (" + nrLastLikeCompleteStudents + "/" + nrLastLikeStudents + ")");
981            info.put("Real students with complete schedule", sDecimalFormat.format(100.0 * nrRealCompleteStudents
982                    / nrRealStudents)
983                    + "% (" + nrRealCompleteStudents + "/" + nrRealStudents + ")");
984            int nrLastLikeRequests = getNrLastLikeRequests(true);
985            int nrRealRequests = variables().size() - nrLastLikeRequests;
986            int nrLastLikeAssignedRequests = getNrAssignedLastLikeRequests(true);
987            int nrRealAssignedRequests = assignedVariables().size() - nrLastLikeAssignedRequests;
988            info.put("Projected assigned requests", sDecimalFormat.format(100.0 * nrLastLikeAssignedRequests
989                    / nrLastLikeRequests)
990                    + "% (" + nrLastLikeAssignedRequests + "/" + nrLastLikeRequests + ")");
991            info.put("Real assigned requests", sDecimalFormat.format(100.0 * nrRealAssignedRequests / nrRealRequests)
992                    + "% (" + nrRealAssignedRequests + "/" + nrRealRequests + ")");
993        }
994        */
995        // info.put("Average unassigned priority", sDecimalFormat.format(avgUnassignPriority()));
996        // info.put("Average number of requests", sDecimalFormat.format(avgNrRequests()));
997        
998        /*
999        double total = 0;
1000        for (Request r: variables())
1001            if (r.getAssignment() != null)
1002                total += r.getWeight() * iStudentWeights.getWeight(r.getAssignment());
1003        */
1004        /*
1005        double dc = 0;
1006        if (getDistanceConflict() != null && getDistanceConflict().getTotalNrConflicts(assignment) != 0) {
1007            Set<DistanceConflict.Conflict> conf = getDistanceConflict().getAllConflicts(assignment);
1008            int sdc = 0;
1009            for (DistanceConflict.Conflict c: conf) {
1010                dc += avg(c.getR1().getWeight(), c.getR2().getWeight()) * iStudentWeights.getDistanceConflictWeight(assignment, c);
1011                if (c.getStudent().isNeedShortDistances()) sdc ++;
1012            }
1013            if (!conf.isEmpty())
1014                info.put("Student distance conflicts", conf.size() + (sdc > 0 ? " (" + getDistanceConflict().getDistanceMetric().getShortDistanceAccommodationReference() + ": " + sdc + ", weighted: " : " (weighted: ") + sDecimalFormat.format(dc) + ")");
1015        }
1016        */
1017        if (getStudentQuality() == null && getTimeOverlaps() != null && getTimeOverlaps().getTotalNrConflicts(assignment) != 0) {
1018            Set<TimeOverlapsCounter.Conflict> conf = getTimeOverlaps().getContext(assignment).computeAllConflicts(assignment);
1019            int share = 0, crShare = 0;
1020            for (TimeOverlapsCounter.Conflict c: conf) {
1021                share += c.getShare();
1022                if (c.getR1() instanceof CourseRequest && c.getR2() instanceof CourseRequest)
1023                    crShare += c.getShare();
1024            }
1025            if (share > 0)
1026                info.put("Time overlapping conflicts", sDoubleFormat.format(5.0 * share / iStudents.size()) + " mins per student\n(" + sDoubleFormat.format(5.0 * crShare / iStudents.size()) + " between courses; " + sDoubleFormat.format(getTimeOverlaps().getTotalNrConflicts(assignment) / 12.0) + " hours total)");
1027        }
1028        if (getStudentQuality() != null) {
1029            int confBtB = getStudentQuality().getTotalPenalty(StudentQuality.Type.BackToBack, assignment);
1030            if (confBtB != 0) {
1031                int prefBtb = 0, discBtb = 0;
1032                int prefStd = 0, discStd = 0;
1033                int prefPairs = 0, discPairs = 0;
1034                for (Student s: getStudents()) {
1035                    if (s.isDummy() || s.getBackToBackPreference() == BackToBackPreference.NO_PREFERENCE) continue;
1036                    int[] classesPerDay = new int[] {0, 0, 0, 0, 0, 0, 0};
1037                    for (Request r: s.getRequests()) {
1038                        Enrollment e = r.getAssignment(assignment);
1039                        if (e == null || !e.isCourseRequest()) continue;
1040                        for (Section x: e.getSections()) {
1041                            if (x.getTime() != null)
1042                                for (int i = 0; i < Constants.DAY_CODES.length; i++)
1043                                    if ((x.getTime().getDayCode() & Constants.DAY_CODES[i]) != 0)
1044                                        classesPerDay[i] ++;
1045                        }
1046                    }
1047                    int max = 0;
1048                    for (int c: classesPerDay)
1049                        if (c > 1) max += c - 1;
1050                    int btb = getStudentQuality().getContext(assignment).allPenalty(StudentQuality.Type.BackToBack, assignment, s);
1051                    if (s.getBackToBackPreference() == BackToBackPreference.BTB_PREFERRED) {
1052                        prefStd ++;
1053                        prefBtb += btb;
1054                        prefPairs += Math.max(btb, max);
1055                    } else if (s.getBackToBackPreference() == BackToBackPreference.BTB_DISCOURAGED) {
1056                        discStd ++;
1057                        discBtb -= btb;
1058                        discPairs += Math.max(btb, max);
1059                    }
1060                }
1061                if (prefStd > 0)
1062                    info.put("Schedule Quality: Back-to-back preferred", sDoubleFormat.format((100.0 * prefBtb) / prefPairs) + "% back-to-backs on average (" + prefBtb + "/" + prefPairs + " BTBs for " + prefStd + " students)");
1063                if (discStd > 0)
1064                    info.put("Schedule Quality: Back-to-back discouraged", sDoubleFormat.format(100.0 - (100.0 * discBtb) / discPairs) + "% non back-to-backs on average (" + discBtb + "/" + discPairs + " BTBs for " + discStd + " students)");
1065            }
1066            int confMod = getStudentQuality().getTotalPenalty(StudentQuality.Type.Modality, assignment);
1067            if (confMod > 0) {
1068                int prefOnl = 0, discOnl = 0;
1069                int prefStd = 0, discStd = 0;
1070                int prefCls = 0, discCls = 0;
1071                for (Student s: getStudents()) {
1072                    if (s.isDummy()) continue;
1073                    if (s.isDummy() || s.getModalityPreference() == ModalityPreference.NO_PREFERENCE || s.getModalityPreference() == ModalityPreference.ONLINE_REQUIRED) continue;
1074                    int classes = 0;
1075                    for (Request r: s.getRequests()) {
1076                        Enrollment e = r.getAssignment(assignment);
1077                        if (e == null || !e.isCourseRequest()) continue;
1078                        classes += e.getSections().size();
1079                    }
1080                    if (s.getModalityPreference() == ModalityPreference.ONLINE_PREFERRED) {
1081                        prefStd ++;
1082                        prefOnl += getStudentQuality().getContext(assignment).allPenalty(StudentQuality.Type.Modality, assignment, s);
1083                        prefCls += classes;
1084                    } else if (s.getModalityPreference() == ModalityPreference.ONILNE_DISCOURAGED) {
1085                        discStd ++;
1086                        discOnl += getStudentQuality().getContext(assignment).allPenalty(StudentQuality.Type.Modality, assignment, s);
1087                        discCls += classes;
1088                    }
1089                }
1090                if (prefStd > 0)
1091                    info.put("Schedule Quality: Online preferred", sDoubleFormat.format(100.0 - (100.0 * prefOnl) / prefCls) + "% online classes on average (" + prefOnl + "/" + prefCls + " classes for " + prefStd + " students)");
1092                if (discStd > 0)
1093                    info.put("Schedule Quality: Online discouraged", sDoubleFormat.format(100.0 - (100.0 * discOnl) / discCls) + "% face-to-face classes on average (" + discOnl + "/" + discCls + " classes for " + discStd + " students)");
1094            }
1095        }
1096        /*
1097        info.put("Overall solution value", sDecimalFormat.format(total - dc - toc) + (dc == 0.0 && toc == 0.0 ? "" :
1098            " (" + (dc != 0.0 ? "distance: " + sDecimalFormat.format(dc): "") + (dc != 0.0 && toc != 0.0 ? ", " : "") + 
1099            (toc != 0.0 ? "overlap: " + sDecimalFormat.format(toc) : "") + ")")
1100            );
1101        */
1102        
1103        double disbWeight = 0;
1104        int disbSections = 0;
1105        int disb10Sections = 0;
1106        int disb10Limit = getProperties().getPropertyInt("Info.ListDisbalancedSections", 0);
1107        Set<String> disb10SectionList = (disb10Limit == 0 ? null : new TreeSet<String>()); 
1108        for (Offering offering: getOfferings()) {
1109            for (Config config: offering.getConfigs()) {
1110                double enrl = config.getEnrollmentTotalWeight(assignment, null);
1111                for (Subpart subpart: config.getSubparts()) {
1112                    if (subpart.getSections().size() <= 1) continue;
1113                    if (subpart.getLimit() > 0) {
1114                        // sections have limits -> desired size is section limit x (total enrollment / total limit)
1115                        double ratio = enrl / subpart.getLimit();
1116                        for (Section section: subpart.getSections()) {
1117                            double desired = ratio * section.getLimit();
1118                            disbWeight += Math.abs(section.getEnrollmentTotalWeight(assignment, null) - desired);
1119                            disbSections ++;
1120                            if (Math.abs(desired - section.getEnrollmentTotalWeight(assignment, null)) >= Math.max(1.0, 0.1 * section.getLimit())) {
1121                                disb10Sections++;
1122                                if (disb10SectionList != null)
1123                                        disb10SectionList.add(section.getSubpart().getConfig().getOffering().getName() + " " + section.getSubpart().getName() + " " + section.getName()); 
1124                            }
1125                        }
1126                    } else {
1127                        // unlimited sections -> desired size is total enrollment / number of sections
1128                        for (Section section: subpart.getSections()) {
1129                            double desired = enrl / subpart.getSections().size();
1130                            disbWeight += Math.abs(section.getEnrollmentTotalWeight(assignment, null) - desired);
1131                            disbSections ++;
1132                            if (Math.abs(desired - section.getEnrollmentTotalWeight(assignment, null)) >= Math.max(1.0, 0.1 * desired)) {
1133                                disb10Sections++;
1134                                if (disb10SectionList != null)
1135                                        disb10SectionList.add(section.getSubpart().getConfig().getOffering().getName() + " " + section.getSubpart().getName() + " " + section.getName());
1136                            }
1137                        }
1138                    }
1139                }
1140            }
1141        }
1142        if (disbSections != 0) {
1143            double assignedCRWeight = getContext(assignment).getAssignedCourseRequestWeight();
1144            info.put("Average disbalance", sDecimalFormat.format(assignedCRWeight == 0 ? 0.0 : 100.0 * disbWeight / assignedCRWeight) + "% (" + sDecimalFormat.format(disbWeight / disbSections) + ")");
1145            String list = "";
1146            if (disb10SectionList != null) {
1147                int i = 0;
1148                for (String section: disb10SectionList) {
1149                    if (i == disb10Limit) {
1150                        list += "\n...";
1151                        break;
1152                    }
1153                    list += "\n" + section;
1154                    i++;
1155                }
1156            }
1157            info.put("Sections disbalanced by 10% or more", sDecimalFormat.format(disbSections == 0 ? 0.0 : 100.0 * disb10Sections / disbSections) + "% (" + disb10Sections + ")" + (list.isEmpty() ? "" : "\n" + list));
1158        }
1159        
1160        int assCR = 0, priCR = 0;
1161        for (Request r: variables()) {
1162            if (r instanceof CourseRequest && !r.getStudent().isDummy()) {
1163                CourseRequest cr = (CourseRequest)r;
1164                Enrollment e = assignment.getValue(cr);
1165                if (e != null) {
1166                    assCR ++;
1167                    if (!cr.isAlternative() && cr.getCourses().get(0).equals(e.getCourse())) priCR ++;
1168                }
1169            }
1170        }
1171        if (assCR > 0)
1172            info.put("Assigned priority course requests", sDoubleFormat.format(100.0 * priCR / assCR) + "% (" + priCR + "/" + assCR + ")");
1173        int[] missing = new int[] {0, 0, 0, 0, 0};
1174        int incomplete = 0;
1175        for (Student student: getStudents()) {
1176            if (student.isDummy()) continue;
1177            int nrRequests = 0;
1178            int nrAssignedRequests = 0;
1179            for (Request r : student.getRequests()) {
1180                if (!(r instanceof CourseRequest)) continue; // ignore free times
1181                if (!r.isAlternative()) nrRequests++;
1182                if (r.isAssigned(assignment)) nrAssignedRequests++;
1183            }
1184            if (nrAssignedRequests < nrRequests) {
1185                missing[Math.min(nrRequests - nrAssignedRequests, missing.length) - 1] ++;
1186                incomplete ++;
1187            }
1188        }
1189
1190        for (int i = 0; i < missing.length; i++)
1191            if (missing[i] > 0)
1192                info.put("Students missing " + (i == 0 ? "1 course" : i + 1 == missing.length ? (i + 1) + " or more courses" : (i + 1) + " courses"), sDecimalFormat.format(100.0 * missing[i] / incomplete) + "% (" + missing[i] + ")");
1193
1194        info.put("Overall solution value", sDoubleFormat.format(getTotalValue(assignment)));// + " [precise: " + sDoubleFormat.format(getTotalValue(assignment, true)) + "]");
1195        
1196        int nrStudentsBelowMinCredit = 0, nrStudents = 0;
1197        for (Student student: getStudents()) {
1198            if (student.isDummy()) continue;
1199            if (student.hasMinCredit()) {
1200                nrStudents++;
1201                float credit = student.getAssignedCredit(assignment); 
1202                if (credit < student.getMinCredit() && !student.isComplete(assignment))
1203                    nrStudentsBelowMinCredit ++;
1204            }
1205        }
1206        if (nrStudentsBelowMinCredit > 0)
1207            info.put("Students below min credit", sDoubleFormat.format(100.0 * nrStudentsBelowMinCredit / nrStudents) + "% (" + nrStudentsBelowMinCredit + "/" + nrStudents + ")");
1208        
1209        int[] notAssignedPriority = new int[] {0, 0, 0, 0, 0, 0, 0};
1210        int[] assignedChoice = new int[] {0, 0, 0, 0, 0};
1211        int notAssignedTotal = 0, assignedChoiceTotal = 0;
1212        int avgPriority = 0, avgChoice = 0;
1213        for (Student student: getStudents()) {
1214            if (student.isDummy()) continue;
1215            for (Request r : student.getRequests()) {
1216                if (!(r instanceof CourseRequest)) continue; // ignore free times
1217                Enrollment e = r.getAssignment(assignment);
1218                if (e == null) {
1219                    if (!r.isAlternative()) {
1220                        notAssignedPriority[Math.min(r.getPriority(), notAssignedPriority.length - 1)] ++;
1221                        notAssignedTotal ++;
1222                        avgPriority += r.getPriority();
1223                    }
1224                } else {
1225                    assignedChoice[Math.min(e.getTruePriority(), assignedChoice.length - 1)] ++;
1226                    assignedChoiceTotal ++;
1227                    avgChoice += e.getTruePriority();
1228                }
1229            }
1230        }
1231        for (int i = 0; i < notAssignedPriority.length; i++)
1232            if (notAssignedPriority[i] > 0)
1233                info.put("Priority: Not-assigned priority " + (i + 1 == notAssignedPriority.length ? (i + 1) + "+" : (i + 1)) + " course requests", sDecimalFormat.format(100.0 * notAssignedPriority[i] / notAssignedTotal) + "% (" + notAssignedPriority[i] + ")");
1234        if (notAssignedTotal > 0)
1235            info.put("Priority: Average not-assigned priority", sDecimalFormat.format(1.0 + ((double)avgPriority) / notAssignedTotal));
1236        for (int i = 0; i < assignedChoice.length; i++)
1237            if (assignedChoice[i] > 0)
1238                info.put("Choice: assigned " + (i == 0 ? "1st": i == 1 ? "2nd" : i == 2 ? "3rd" : i + 1 == assignedChoice.length ? (i + 1) + "th+" : (i + 1) + "th") + " course choice", sDecimalFormat.format(100.0 * assignedChoice[i] / assignedChoiceTotal) + "% (" + assignedChoice[i] + ")");
1239        if (assignedChoiceTotal > 0)
1240            info.put("Choice: Average assigned choice", sDecimalFormat.format(1.0 + ((double)avgChoice) / assignedChoiceTotal));
1241        
1242        int nbrSections = 0, nbrFullSections = 0, nbrSections98 = 0, nbrSections95 = 0, nbrSections90 = 0, nbrSectionsDis = 0;
1243        int enrlSections = 0, enrlFullSections = 0, enrlSections98 = 0, enrlSections95 = 0, enrlSections90 = 0, enrlSectionsDis = 0;
1244        int nbrOfferings = 0, nbrFullOfferings = 0, nbrOfferings98 = 0, nbrOfferings95 = 0, nbrOfferings90 = 0;
1245        int enrlOfferings = 0, enrlOfferingsFull = 0, enrlOfferings98 = 0, enrlOfferings95 = 0, enrlOfferings90 = 0;
1246        for (Offering offering: getOfferings()) {
1247            int offeringLimit = 0, offeringEnrollment = 0;
1248            for (Config config: offering.getConfigs()) {
1249                int configLimit = config.getLimit();
1250                for (Subpart subpart: config.getSubparts()) {
1251                    int subpartLimit = 0;
1252                    for (Section section: subpart.getSections()) {
1253                        if (section.isCancelled()) continue;
1254                        int enrl = section.getEnrollments(assignment).size();
1255                        if (section.getLimit() < 0 || subpartLimit < 0)
1256                            subpartLimit = -1;
1257                        else
1258                            subpartLimit += (section.isEnabled() ? section.getLimit() : enrl);
1259                        nbrSections ++;
1260                        enrlSections += enrl;
1261                        if (section.getLimit() >= 0 && section.getLimit() <= enrl) {
1262                            nbrFullSections ++;
1263                            enrlFullSections += enrl;
1264                        }
1265                        if (!section.isEnabled() && (enrl > 0 || section.getLimit() >= 0)) {
1266                            nbrSectionsDis ++;
1267                            enrlSectionsDis += enrl;
1268                        }
1269                        if (section.getLimit() >= 0 && (section.getLimit() - enrl) <= Math.round(0.02 * section.getLimit())) {
1270                            nbrSections98 ++;
1271                            enrlSections98 += enrl;
1272                        }
1273                        if (section.getLimit() >= 0 && (section.getLimit() - enrl) <= Math.round(0.05 * section.getLimit())) {
1274                            nbrSections95 ++;
1275                            enrlSections95 += enrl;
1276                        }
1277                        if (section.getLimit() >= 0 && (section.getLimit() - enrl) <= Math.round(0.10 * section.getLimit())) {
1278                            nbrSections90 ++;
1279                            enrlSections90 += enrl;
1280                        }
1281                    }
1282                    if (configLimit < 0 || subpartLimit < 0)
1283                        configLimit = -1;
1284                    else
1285                        configLimit = Math.min(configLimit, subpartLimit);
1286                }
1287                if (offeringLimit < 0 || configLimit < 0)
1288                    offeringLimit = -1;
1289                else
1290                    offeringLimit += configLimit;
1291                offeringEnrollment += config.getEnrollments(assignment).size();
1292            }
1293            nbrOfferings ++;
1294            enrlOfferings += offeringEnrollment;
1295            
1296            if (offeringLimit >=0 && offeringEnrollment >= offeringLimit) {
1297                nbrFullOfferings ++;
1298                enrlOfferingsFull += offeringEnrollment;
1299            }
1300            if (offeringLimit >= 0 && (offeringLimit - offeringEnrollment) <= Math.round(0.02 * offeringLimit)) {
1301                nbrOfferings98++;
1302                enrlOfferings98 += offeringEnrollment;
1303            }
1304            if (offeringLimit >= 0 && (offeringLimit - offeringEnrollment) <= Math.round(0.05 * offeringLimit)) {
1305                nbrOfferings95++;
1306                enrlOfferings95 += offeringEnrollment;
1307            }
1308            if (offeringLimit >= 0 && (offeringLimit - offeringEnrollment) <= Math.round(0.10 * offeringLimit)) {
1309                nbrOfferings90++;
1310                enrlOfferings90 += offeringEnrollment;
1311            }
1312        }
1313        if (enrlOfferings90 > 0 && enrlOfferings > 0) 
1314            info.put("Full Offerings", (nbrFullOfferings > 0 ? nbrFullOfferings + " with no space (" + sDecimalFormat.format(100.0 * nbrFullOfferings / nbrOfferings) + "% of all offerings, " +
1315                    sDecimalFormat.format(100.0 * enrlOfferingsFull / enrlOfferings) + "% assignments)\n" : "")+
1316                    (nbrOfferings98 > nbrFullOfferings ? nbrOfferings98 + " with &leq; 2% available (" + sDecimalFormat.format(100.0 * nbrOfferings98 / nbrOfferings) + "% of all offerings, " +
1317                    sDecimalFormat.format(100.0 * enrlOfferings98 / enrlOfferings) + "% assignments)\n" : "")+
1318                    (nbrOfferings95 > nbrOfferings98 ? nbrOfferings95 + " with &leq; 5% available (" + sDecimalFormat.format(100.0 * nbrOfferings95 / nbrOfferings) + "% of all offerings, " +
1319                    sDecimalFormat.format(100.0 * enrlOfferings95 / enrlOfferings) + "% assignments)\n" : "")+
1320                    (nbrOfferings90 > nbrOfferings95 ? nbrOfferings90 + " with &leq; 10% available (" + sDecimalFormat.format(100.0 * nbrOfferings90 / nbrOfferings) + "% of all offerings, " +
1321                    sDecimalFormat.format(100.0 * enrlOfferings90 / enrlOfferings) + "% assignments)" : ""));
1322        if ((enrlSections90 > 0 || nbrSectionsDis > 0) && enrlSections > 0)
1323            info.put("Full Sections", (nbrFullSections > 0 ? nbrFullSections + " with no space (" + sDecimalFormat.format(100.0 * nbrFullSections / nbrSections) + "% of all sections, "+
1324                    sDecimalFormat.format(100.0 * enrlFullSections / enrlSections) + "% assignments)\n" : "") +
1325                    (nbrSectionsDis > 0 ? nbrSectionsDis + " disabled (" + sDecimalFormat.format(100.0 * nbrSectionsDis / nbrSections) + "% of all sections, "+
1326                    sDecimalFormat.format(100.0 * enrlSectionsDis / enrlSections) + "% assignments)\n" : "") +
1327                    (enrlSections98 > nbrFullSections ? nbrSections98 + " with &leq; 2% available (" + sDecimalFormat.format(100.0 * nbrSections98 / nbrSections) + "% of all sections, " +
1328                    sDecimalFormat.format(100.0 * enrlSections98 / enrlSections) + "% assignments)\n" : "") +
1329                    (nbrSections95 > enrlSections98 ? nbrSections95 + " with &leq; 5% available (" + sDecimalFormat.format(100.0 * nbrSections95 / nbrSections) + "% of all sections, " +
1330                    sDecimalFormat.format(100.0 * enrlSections95 / enrlSections) + "% assignments)\n" : "") +
1331                    (nbrSections90 > nbrSections95 ? nbrSections90 + " with &leq; 10% available (" + sDecimalFormat.format(100.0 * nbrSections90 / nbrSections) + "% of all sections, " +
1332                    sDecimalFormat.format(100.0 * enrlSections90 / enrlSections) + "% assignments)" : ""));
1333        if (getStudentQuality() != null) {
1334            int shareCR = getStudentQuality().getContext(assignment).countTotalPenalty(StudentQuality.Type.CourseTimeOverlap, assignment);
1335            int shareFT = getStudentQuality().getContext(assignment).countTotalPenalty(StudentQuality.Type.FreeTimeOverlap, assignment);
1336            int shareUN = getStudentQuality().getContext(assignment).countTotalPenalty(StudentQuality.Type.Unavailability, assignment);
1337            if (shareCR > 0) {
1338                Set<Student> students = new HashSet<Student>();
1339                for (StudentQuality.Conflict c: getStudentQuality().getContext(assignment).computeAllConflicts(StudentQuality.Type.CourseTimeOverlap, assignment)) {
1340                    students.add(c.getStudent());
1341                }
1342                info.put("Time overlaps: courses", students.size() + " students (avg " + sDoubleFormat.format(5.0 * shareCR / students.size()) + " mins)");
1343            }
1344            if (shareFT > 0) {
1345                Set<Student> students = new HashSet<Student>();
1346                for (StudentQuality.Conflict c: getStudentQuality().getContext(assignment).computeAllConflicts(StudentQuality.Type.FreeTimeOverlap, assignment)) {
1347                    students.add(c.getStudent());
1348                }
1349                info.put("Time overlaps: free times", students.size() + " students (avg " + sDoubleFormat.format(5.0 * shareFT / students.size()) + " mins)");
1350            }
1351            if (shareUN > 0) {
1352                Set<Student> students = new HashSet<Student>();
1353                for (StudentQuality.Conflict c: getStudentQuality().getContext(assignment).computeAllConflicts(StudentQuality.Type.Unavailability, assignment)) {
1354                    students.add(c.getStudent());
1355                }
1356                info.put("Time overlaps: teaching assignments", students.size() + " students (avg " + sDoubleFormat.format(5.0 * shareUN / students.size()) + " mins)");
1357            }
1358        } else if (getTimeOverlaps() != null && getTimeOverlaps().getTotalNrConflicts(assignment) != 0) {
1359            Set<TimeOverlapsCounter.Conflict> conf = getTimeOverlaps().getContext(assignment).computeAllConflicts(assignment);
1360            int shareCR = 0, shareFT = 0, shareUN = 0;
1361            Set<Student> studentsCR = new HashSet<Student>();
1362            Set<Student> studentsFT = new HashSet<Student>();
1363            Set<Student> studentsUN = new HashSet<Student>();
1364            for (TimeOverlapsCounter.Conflict c: conf) {
1365                if (c.getR1() instanceof CourseRequest && c.getR2() instanceof CourseRequest) {
1366                    shareCR += c.getShare(); studentsCR.add(c.getStudent());
1367                } else if (c.getS2() instanceof Unavailability) {
1368                    shareUN += c.getShare(); studentsUN.add(c.getStudent());
1369                } else {
1370                    shareFT += c.getShare(); studentsFT.add(c.getStudent());
1371                }
1372            }
1373            if (shareCR > 0)
1374                info.put("Time overlaps: courses", studentsCR.size() + " students (avg " + sDoubleFormat.format(5.0 * shareCR / studentsCR.size()) + " mins)");
1375            if (shareFT > 0)
1376                info.put("Time overlaps: free times", studentsFT.size() + " students (avg " + sDoubleFormat.format(5.0 * shareFT / studentsFT.size()) + " mins)");
1377            if (shareUN > 0)
1378                info.put("Time overlaps: teaching assignments", studentsUN.size() + " students (avg " + sDoubleFormat.format(5.0 * shareUN / studentsUN.size()) + " mins)");
1379        }
1380
1381        
1382        return info;
1383    }
1384    
1385    @Override
1386    public void restoreBest(Assignment<Request, Enrollment> assignment) {
1387        restoreBest(assignment, new Comparator<Request>() {
1388            @Override
1389            public int compare(Request r1, Request r2) {
1390                Enrollment e1 = r1.getBestAssignment();
1391                Enrollment e2 = r2.getBestAssignment();
1392                // Reservations first
1393                if (e1.getReservation() != null && e2.getReservation() == null) return -1;
1394                if (e1.getReservation() == null && e2.getReservation() != null) return 1;
1395                // Then assignment iteration (i.e., order in which assignments were made)
1396                if (r1.getBestAssignmentIteration() != r2.getBestAssignmentIteration())
1397                    return (r1.getBestAssignmentIteration() < r2.getBestAssignmentIteration() ? -1 : 1);
1398                // Then student and priority
1399                return r1.compareTo(r2);
1400            }
1401        });
1402        recomputeTotalValue(assignment);
1403    }
1404    
1405    public void recomputeTotalValue(Assignment<Request, Enrollment> assignment) {
1406        getContext(assignment).iTotalValue = getTotalValue(assignment, true);
1407    }
1408    
1409    @Override
1410    public void saveBest(Assignment<Request, Enrollment> assignment) {
1411        recomputeTotalValue(assignment);
1412        iBestAssignedCourseRequestWeight = getContext(assignment).getAssignedCourseRequestWeight();
1413        super.saveBest(assignment);
1414    }
1415    
1416    public double getBestAssignedCourseRequestWeight() {
1417        return iBestAssignedCourseRequestWeight;
1418    }
1419        
1420    @Override
1421    public String toString(Assignment<Request, Enrollment> assignment) {
1422        double groupSpread = 0.0; double groupCount = 0;
1423        for (Offering offering: iOfferings) {
1424            for (Course course: offering.getCourses()) {
1425                for (RequestGroup group: course.getRequestGroups()) {
1426                    groupSpread += group.getAverageSpread(assignment) * group.getEnrollmentWeight(assignment, null);
1427                    groupCount += group.getEnrollmentWeight(assignment, null);
1428                }
1429            }
1430        }
1431        String priority = "";
1432        for (StudentPriority sp: StudentPriority.values()) {
1433            if (sp.ordinal() < StudentPriority.Normal.ordinal()) {
1434                if (iTotalPriorityCRWeight[sp.ordinal()] > 0.0)
1435                    priority += sp.code() + "PCR:" + sDecimalFormat.format(100.0 * getContext(assignment).iAssignedPriorityCRWeight[sp.ordinal()] / iTotalPriorityCRWeight[sp.ordinal()]) + "%, ";
1436                if (iTotalPriorityCriticalCRWeight[RequestPriority.Critical.ordinal()][sp.ordinal()] > 0.0)
1437                    priority += sp.code() + "PCC:" + sDecimalFormat.format(100.0 * getContext(assignment).iAssignedPriorityCriticalCRWeight[RequestPriority.Critical.ordinal()][sp.ordinal()] / iTotalPriorityCriticalCRWeight[RequestPriority.Critical.ordinal()][sp.ordinal()]) + "%, ";
1438                if (iTotalPriorityCriticalCRWeight[RequestPriority.Important.ordinal()][sp.ordinal()] > 0.0)
1439                    priority += sp.code() + "PCI:" + sDecimalFormat.format(100.0 * getContext(assignment).iAssignedPriorityCriticalCRWeight[RequestPriority.Important.ordinal()][sp.ordinal()] / iTotalPriorityCriticalCRWeight[RequestPriority.Important.ordinal()][sp.ordinal()]) + "%, ";
1440                if (iTotalPriorityCriticalCRWeight[RequestPriority.Vital.ordinal()][sp.ordinal()] > 0.0)
1441                    priority += sp.code() + "PCV:" + sDecimalFormat.format(100.0 * getContext(assignment).iAssignedPriorityCriticalCRWeight[RequestPriority.Vital.ordinal()][sp.ordinal()] / iTotalPriorityCriticalCRWeight[RequestPriority.Vital.ordinal()][sp.ordinal()]) + "%, ";
1442            }
1443        }
1444        return   (getNrRealStudents(false) > 0 ? "RRq:" + getNrAssignedRealRequests(assignment, false) + "/" + getNrRealRequests(false) + ", " : "")
1445                + (getNrLastLikeStudents(false) > 0 ? "DRq:" + getNrAssignedLastLikeRequests(assignment, false) + "/" + getNrLastLikeRequests(false) + ", " : "")
1446                + (getNrRealStudents(false) > 0 ? "RS:" + getNrCompleteRealStudents(assignment, false) + "/" + getNrRealStudents(false) + ", " : "")
1447                + (getNrLastLikeStudents(false) > 0 ? "DS:" + getNrCompleteLastLikeStudents(assignment, false) + "/" + getNrLastLikeStudents(false) + ", " : "")
1448                + (iTotalCRWeight > 0.0 ? "CR:" + sDecimalFormat.format(100.0 * getContext(assignment).getAssignedCourseRequestWeight() / iTotalCRWeight) + "%, " : "")
1449                + (iTotalSelCRWeight > 0.0 ? "S:" + sDoubleFormat.format(100.0 * (0.3 * getContext(assignment).iAssignedSelectedConfigWeight + 0.7 * getContext(assignment).iAssignedSelectedSectionWeight) / iTotalSelCRWeight) + "%, ": "")
1450                + (iTotalCriticalCRWeight[RequestPriority.Critical.ordinal()] > 0.0 ? "CC:" + sDecimalFormat.format(100.0 * getContext(assignment).getAssignedCriticalCourseRequestWeight(RequestPriority.Critical) / iTotalCriticalCRWeight[RequestPriority.Critical.ordinal()]) + "%, " : "")
1451                + (iTotalCriticalCRWeight[RequestPriority.Important.ordinal()] > 0.0 ? "IC:" + sDecimalFormat.format(100.0 * getContext(assignment).getAssignedCriticalCourseRequestWeight(RequestPriority.Important) / iTotalCriticalCRWeight[RequestPriority.Important.ordinal()]) + "%, " : "")
1452                + (iTotalCriticalCRWeight[RequestPriority.Vital.ordinal()] > 0.0 ? "VC:" + sDecimalFormat.format(100.0 * getContext(assignment).getAssignedCriticalCourseRequestWeight(RequestPriority.Vital) / iTotalCriticalCRWeight[RequestPriority.Vital.ordinal()]) + "%, " : "")
1453                + priority
1454                + "V:" + sDecimalFormat.format(-getTotalValue(assignment))
1455                + (getDistanceConflict() == null ? "" : ", DC:" + getDistanceConflict().getTotalNrConflicts(assignment))
1456                + (getTimeOverlaps() == null ? "" : ", TOC:" + getTimeOverlaps().getTotalNrConflicts(assignment))
1457                + (iMPP ? ", IS:" + sDecimalFormat.format(100.0 * getContext(assignment).iAssignedSameSectionWeight / iTotalMPPCRWeight) + "%" : "")
1458                + (iMPP ? ", IT:" + sDecimalFormat.format(100.0 * getContext(assignment).iAssignedSameTimeWeight / iTotalMPPCRWeight) + "%" : "")
1459                + ", %:" + sDecimalFormat.format(-100.0 * getTotalValue(assignment) / (getStudents().size() - iNrDummyStudents + 
1460                        (iProjectedStudentWeight < 0.0 ? iNrDummyStudents * (iTotalDummyWeight / iNrDummyRequests) :iProjectedStudentWeight * iTotalDummyWeight)))
1461                + (groupCount > 0 ? ", SG:" + sDecimalFormat.format(100.0 * groupSpread / groupCount) + "%" : "")
1462                + (getStudentQuality() == null ? "" : ", SQ:{" + getStudentQuality().toString(assignment) + "}");
1463    }
1464    
1465    /**
1466     * Quadratic average of two weights.
1467     * @param w1 first weight
1468     * @param w2 second weight
1469     * @return average of the two weights
1470     */
1471    public double avg(double w1, double w2) {
1472        return Math.sqrt(w1 * w2);
1473    }
1474
1475    /**
1476     * Maximal domain size (i.e., number of enrollments of a course request), -1 if there is no limit.
1477     * @return maximal domain size, -1 if unlimited
1478     */
1479    public int getMaxDomainSize() { return iMaxDomainSize; }
1480
1481    /**
1482     * Maximal domain size (i.e., number of enrollments of a course request), -1 if there is no limit.
1483     * @param maxDomainSize maximal domain size, -1 if unlimited
1484     */
1485    public void setMaxDomainSize(int maxDomainSize) { iMaxDomainSize = maxDomainSize; }
1486    
1487    public int getDayOfWeekOffset() { return iDayOfWeekOffset; }
1488    public void setDayOfWeekOffset(int dayOfWeekOffset) {
1489        iDayOfWeekOffset = dayOfWeekOffset;
1490        if (iProperties != null)
1491            iProperties.setProperty("DatePattern.DayOfWeekOffset", Integer.toString(dayOfWeekOffset));
1492    }
1493
1494    @Override
1495    public StudentSectioningModelContext createAssignmentContext(Assignment<Request, Enrollment> assignment) {
1496        return new StudentSectioningModelContext(assignment);
1497    }
1498    
1499    public class StudentSectioningModelContext implements AssignmentConstraintContext<Request, Enrollment>, InfoProvider<Request, Enrollment>{
1500        private Set<Student> iCompleteStudents = new HashSet<Student>();
1501        private double iTotalValue = 0.0;
1502        private int iNrAssignedDummyRequests = 0, iNrCompleteDummyStudents = 0;
1503        private double iAssignedCRWeight = 0.0, iAssignedDummyCRWeight = 0.0;
1504        private double[] iAssignedCriticalCRWeight;
1505        private double[][] iAssignedPriorityCriticalCRWeight;
1506        private double iReservedSpace = 0.0, iTotalReservedSpace = 0.0;
1507        private double iAssignedSameSectionWeight = 0.0, iAssignedSameChoiceWeight = 0.0, iAssignedSameTimeWeight = 0.0;
1508        private double iAssignedSelectedSectionWeight = 0.0, iAssignedSelectedConfigWeight = 0.0;
1509        private double iAssignedNoTimeSectionWeight = 0.0;
1510        private double iAssignedOnlineSectionWeight = 0.0;
1511        private double iAssignedPastSectionWeight = 0.0;
1512        private int[] iNrCompletePriorityStudents = null;
1513        private double[] iAssignedPriorityCRWeight = null;
1514        
1515        public StudentSectioningModelContext(StudentSectioningModelContext parent) {
1516            iCompleteStudents = new HashSet<Student>(parent.iCompleteStudents);
1517            iTotalValue = parent.iTotalValue;
1518            iNrAssignedDummyRequests = parent.iNrAssignedDummyRequests;
1519            iNrCompleteDummyStudents = parent.iNrCompleteDummyStudents;
1520            iAssignedCRWeight = parent.iAssignedCRWeight;
1521            iAssignedDummyCRWeight = parent.iAssignedDummyCRWeight;
1522            iReservedSpace = parent.iReservedSpace;
1523            iTotalReservedSpace = parent.iTotalReservedSpace;
1524            iAssignedSameSectionWeight = parent.iAssignedSameSectionWeight;
1525            iAssignedSameChoiceWeight = parent.iAssignedSameChoiceWeight;
1526            iAssignedSameTimeWeight = parent.iAssignedSameTimeWeight;
1527            iAssignedSelectedSectionWeight = parent.iAssignedSelectedSectionWeight;
1528            iAssignedSelectedConfigWeight = parent.iAssignedSelectedConfigWeight;
1529            iAssignedNoTimeSectionWeight = parent.iAssignedNoTimeSectionWeight;
1530            iAssignedOnlineSectionWeight = parent.iAssignedOnlineSectionWeight;
1531            iAssignedPastSectionWeight = parent.iAssignedPastSectionWeight;
1532            iAssignedCriticalCRWeight = new double[RequestPriority.values().length];
1533            iAssignedPriorityCriticalCRWeight = new double[RequestPriority.values().length][StudentPriority.values().length];
1534            for (int i = 0; i < RequestPriority.values().length; i++) {
1535                iAssignedCriticalCRWeight[i] = parent.iAssignedCriticalCRWeight[i];
1536                for (int j = 0; j < StudentPriority.values().length; j++) {
1537                    iAssignedPriorityCriticalCRWeight[i][j] = parent.iAssignedPriorityCriticalCRWeight[i][j];
1538                }
1539            }   
1540            iNrCompletePriorityStudents = new int[StudentPriority.values().length];
1541            iAssignedPriorityCRWeight = new double[StudentPriority.values().length];
1542            for (int i = 0; i < StudentPriority.values().length; i++) {
1543                iNrCompletePriorityStudents[i] = parent.iNrCompletePriorityStudents[i];
1544                iAssignedPriorityCRWeight[i] = parent.iAssignedPriorityCRWeight[i];
1545            }
1546        }
1547
1548        public StudentSectioningModelContext(Assignment<Request, Enrollment> assignment) {
1549            iAssignedCriticalCRWeight = new double[RequestPriority.values().length];
1550            iAssignedPriorityCriticalCRWeight = new double[RequestPriority.values().length][StudentPriority.values().length];
1551            for (int i = 0; i < RequestPriority.values().length; i++) {
1552                iAssignedCriticalCRWeight[i] = 0.0;
1553                for (int j = 0; j < StudentPriority.values().length; j++) {
1554                    iAssignedPriorityCriticalCRWeight[i][j] = 0.0;
1555                }
1556            }
1557            iNrCompletePriorityStudents = new int[StudentPriority.values().length];
1558            iAssignedPriorityCRWeight = new double[StudentPriority.values().length];
1559            for (int i = 0; i < StudentPriority.values().length; i++) {
1560                iNrCompletePriorityStudents[i] = 0;
1561                iAssignedPriorityCRWeight[i] = 0.0;
1562            }
1563            for (Request request: variables()) {
1564                Enrollment enrollment = assignment.getValue(request);
1565                if (enrollment != null)
1566                    assigned(assignment, enrollment);
1567            }
1568        }
1569
1570        /**
1571         * Called after an enrollment was assigned to a request. The list of
1572         * complete students and the overall solution value are updated.
1573         */
1574        @Override
1575        public void assigned(Assignment<Request, Enrollment> assignment, Enrollment enrollment) {
1576            Student student = enrollment.getStudent();
1577            if (student.isComplete(assignment) && iCompleteStudents.add(student)) {
1578                if (student.isDummy()) iNrCompleteDummyStudents++;
1579                iNrCompletePriorityStudents[student.getPriority().ordinal()]++;
1580            }
1581            double value = enrollment.getRequest().getWeight() * iStudentWeights.getWeight(assignment, enrollment);
1582            iTotalValue -= value;
1583            enrollment.variable().getContext(assignment).setLastWeight(value);
1584            if (enrollment.isCourseRequest())
1585                iAssignedCRWeight += enrollment.getRequest().getWeight();
1586            if (enrollment.isCourseRequest() && enrollment.getRequest().getRequestPriority() != RequestPriority.Normal && !enrollment.getStudent().isDummy() && !enrollment.getRequest().isAlternative())
1587                iAssignedCriticalCRWeight[enrollment.getRequest().getRequestPriority().ordinal()] += enrollment.getRequest().getWeight();
1588            if (enrollment.isCourseRequest() && enrollment.getRequest().getRequestPriority() != RequestPriority.Normal && !enrollment.getRequest().isAlternative())
1589                iAssignedPriorityCriticalCRWeight[enrollment.getRequest().getRequestPriority().ordinal()][enrollment.getStudent().getPriority().ordinal()] += enrollment.getRequest().getWeight();
1590            if (enrollment.getRequest().isMPP()) {
1591                iAssignedSameSectionWeight += enrollment.getRequest().getWeight() * enrollment.percentInitial();
1592                iAssignedSameChoiceWeight += enrollment.getRequest().getWeight() * enrollment.percentSelected();
1593                iAssignedSameTimeWeight += enrollment.getRequest().getWeight() * enrollment.percentSameTime();
1594            }
1595            if (enrollment.getRequest().hasSelection()) {
1596                iAssignedSelectedSectionWeight += enrollment.getRequest().getWeight() * enrollment.percentSelectedSameSection();
1597                iAssignedSelectedConfigWeight += enrollment.getRequest().getWeight() * enrollment.percentSelectedSameConfig();
1598            }
1599            if (enrollment.getReservation() != null)
1600                iReservedSpace += enrollment.getRequest().getWeight();
1601            if (enrollment.isCourseRequest() && ((CourseRequest)enrollment.getRequest()).hasReservations())
1602                iTotalReservedSpace += enrollment.getRequest().getWeight();
1603            if (student.isDummy()) {
1604                iNrAssignedDummyRequests++;
1605                if (enrollment.isCourseRequest())
1606                    iAssignedDummyCRWeight += enrollment.getRequest().getWeight();
1607            }
1608            if (enrollment.isCourseRequest())
1609                iAssignedPriorityCRWeight[enrollment.getStudent().getPriority().ordinal()] += enrollment.getRequest().getWeight();
1610            if (enrollment.isCourseRequest()) {
1611                int noTime = 0;
1612                int online = 0;
1613                int past = 0;
1614                for (Section section: enrollment.getSections()) {
1615                    if (!section.hasTime()) noTime ++;
1616                    if (section.isOnline()) online ++;
1617                    if (section.isPast()) past ++;
1618                }
1619                if (noTime > 0)
1620                    iAssignedNoTimeSectionWeight += enrollment.getRequest().getWeight() * noTime / enrollment.getSections().size();
1621                if (online > 0)
1622                    iAssignedOnlineSectionWeight += enrollment.getRequest().getWeight() * online / enrollment.getSections().size();
1623                if (past > 0)
1624                    iAssignedPastSectionWeight += enrollment.getRequest().getWeight() * past / enrollment.getSections().size();
1625            }
1626        }
1627
1628        /**
1629         * Called before an enrollment was unassigned from a request. The list of
1630         * complete students and the overall solution value are updated.
1631         */
1632        @Override
1633        public void unassigned(Assignment<Request, Enrollment> assignment, Enrollment enrollment) {
1634            Student student = enrollment.getStudent();
1635            if (enrollment.isCourseRequest() && iCompleteStudents.contains(student)) {
1636                iCompleteStudents.remove(student);
1637                if (student.isDummy())
1638                    iNrCompleteDummyStudents--;
1639                iNrCompletePriorityStudents[student.getPriority().ordinal()]--;
1640            }
1641            Request.RequestContext cx = enrollment.variable().getContext(assignment);
1642            Double value = cx.getLastWeight();
1643            if (value == null)
1644                value = enrollment.getRequest().getWeight() * iStudentWeights.getWeight(assignment, enrollment);
1645            iTotalValue += value;
1646            cx.setLastWeight(null);
1647            if (enrollment.isCourseRequest())
1648                iAssignedCRWeight -= enrollment.getRequest().getWeight();
1649            if (enrollment.isCourseRequest() && enrollment.getRequest().getRequestPriority() != RequestPriority.Normal && !enrollment.getStudent().isDummy() && !enrollment.getRequest().isAlternative())
1650                iAssignedCriticalCRWeight[enrollment.getRequest().getRequestPriority().ordinal()] -= enrollment.getRequest().getWeight();
1651            if (enrollment.isCourseRequest() && enrollment.getRequest().getRequestPriority() != RequestPriority.Normal && !enrollment.getRequest().isAlternative())
1652                iAssignedPriorityCriticalCRWeight[enrollment.getRequest().getRequestPriority().ordinal()][enrollment.getStudent().getPriority().ordinal()] -= enrollment.getRequest().getWeight();
1653            if (enrollment.getRequest().isMPP()) {
1654                iAssignedSameSectionWeight -= enrollment.getRequest().getWeight() * enrollment.percentInitial();
1655                iAssignedSameChoiceWeight -= enrollment.getRequest().getWeight() * enrollment.percentSelected();
1656                iAssignedSameTimeWeight -= enrollment.getRequest().getWeight() * enrollment.percentSameTime();
1657            }
1658            if (enrollment.getRequest().hasSelection()) {
1659                iAssignedSelectedSectionWeight -= enrollment.getRequest().getWeight() * enrollment.percentSelectedSameSection();
1660                iAssignedSelectedConfigWeight -= enrollment.getRequest().getWeight() * enrollment.percentSelectedSameConfig();
1661            }
1662            if (enrollment.getReservation() != null)
1663                iReservedSpace -= enrollment.getRequest().getWeight();
1664            if (enrollment.isCourseRequest() && ((CourseRequest)enrollment.getRequest()).hasReservations())
1665                iTotalReservedSpace -= enrollment.getRequest().getWeight();
1666            if (student.isDummy()) {
1667                iNrAssignedDummyRequests--;
1668                if (enrollment.isCourseRequest())
1669                    iAssignedDummyCRWeight -= enrollment.getRequest().getWeight();
1670            }
1671            if (enrollment.isCourseRequest())
1672                iAssignedPriorityCRWeight[enrollment.getStudent().getPriority().ordinal()] -= enrollment.getRequest().getWeight();
1673            if (enrollment.isCourseRequest()) {
1674                int noTime = 0;
1675                int online = 0;
1676                int past = 0;
1677                for (Section section: enrollment.getSections()) {
1678                    if (!section.hasTime()) noTime ++;
1679                    if (section.isOnline()) online ++;
1680                    if (section.isPast()) past ++;
1681                }
1682                if (noTime > 0)
1683                    iAssignedNoTimeSectionWeight -= enrollment.getRequest().getWeight() * noTime / enrollment.getSections().size();
1684                if (online > 0)
1685                    iAssignedOnlineSectionWeight -= enrollment.getRequest().getWeight() * online / enrollment.getSections().size();
1686                if (past > 0)
1687                    iAssignedPastSectionWeight -= enrollment.getRequest().getWeight() * past / enrollment.getSections().size();
1688            }
1689        }
1690        
1691        public void add(Assignment<Request, Enrollment> assignment, DistanceConflict.Conflict c) {
1692            iTotalValue += avg(c.getR1().getWeight(), c.getR2().getWeight()) * iStudentWeights.getDistanceConflictWeight(assignment, c);
1693        }
1694
1695        public void remove(Assignment<Request, Enrollment> assignment, DistanceConflict.Conflict c) {
1696            iTotalValue -= avg(c.getR1().getWeight(), c.getR2().getWeight()) * iStudentWeights.getDistanceConflictWeight(assignment, c);
1697        }
1698        
1699        public void add(Assignment<Request, Enrollment> assignment, TimeOverlapsCounter.Conflict c) {
1700            if (c.getR1() != null) iTotalValue += c.getR1Weight() * iStudentWeights.getTimeOverlapConflictWeight(assignment, c.getE1(), c);
1701            if (c.getR2() != null) iTotalValue += c.getR2Weight() * iStudentWeights.getTimeOverlapConflictWeight(assignment, c.getE2(), c);
1702        }
1703
1704        public void remove(Assignment<Request, Enrollment> assignment, TimeOverlapsCounter.Conflict c) {
1705            if (c.getR1() != null) iTotalValue -= c.getR1Weight() * iStudentWeights.getTimeOverlapConflictWeight(assignment, c.getE1(), c);
1706            if (c.getR2() != null) iTotalValue -= c.getR2Weight() * iStudentWeights.getTimeOverlapConflictWeight(assignment, c.getE2(), c);
1707        }
1708        
1709        public void add(Assignment<Request, Enrollment> assignment, StudentQuality.Conflict c) {
1710            switch (c.getType().getType()) {
1711                case REQUEST:
1712                    if (c.getR1() instanceof CourseRequest)
1713                        iTotalValue += c.getR1Weight() * iStudentWeights.getStudentQualityConflictWeight(assignment, c.getE1(), c);
1714                    else
1715                        iTotalValue += c.getR2Weight() * iStudentWeights.getStudentQualityConflictWeight(assignment, c.getE2(), c);
1716                    break;
1717                case BOTH:
1718                    iTotalValue += c.getR1Weight() * iStudentWeights.getStudentQualityConflictWeight(assignment, c.getE1(), c);  
1719                    iTotalValue += c.getR2Weight() * iStudentWeights.getStudentQualityConflictWeight(assignment, c.getE2(), c);
1720                    break;
1721                case LOWER:
1722                    iTotalValue += avg(c.getR1().getWeight(), c.getR2().getWeight()) * iStudentWeights.getStudentQualityConflictWeight(assignment, c.getE1(), c);
1723                    break;
1724                case HIGHER:
1725                    iTotalValue += avg(c.getR1().getWeight(), c.getR2().getWeight()) * iStudentWeights.getStudentQualityConflictWeight(assignment, c.getE1(), c);
1726                    break;
1727            }
1728        }
1729
1730        public void remove(Assignment<Request, Enrollment> assignment, StudentQuality.Conflict c) {
1731            switch (c.getType().getType()) {
1732                case REQUEST:
1733                    if (c.getR1() instanceof CourseRequest)
1734                        iTotalValue -= c.getR1Weight() * iStudentWeights.getStudentQualityConflictWeight(assignment, c.getE1(), c);
1735                    else
1736                        iTotalValue -= c.getR2Weight() * iStudentWeights.getStudentQualityConflictWeight(assignment, c.getE2(), c);
1737                    break;
1738                case BOTH:
1739                    iTotalValue -= c.getR1Weight() * iStudentWeights.getStudentQualityConflictWeight(assignment, c.getE1(), c);  
1740                    iTotalValue -= c.getR2Weight() * iStudentWeights.getStudentQualityConflictWeight(assignment, c.getE2(), c);
1741                    break;
1742                case LOWER:
1743                    iTotalValue -= avg(c.getR1().getWeight(), c.getR2().getWeight()) * iStudentWeights.getStudentQualityConflictWeight(assignment, c.getE1(), c);
1744                    break;
1745                case HIGHER:
1746                    iTotalValue -= avg(c.getR1().getWeight(), c.getR2().getWeight()) * iStudentWeights.getStudentQualityConflictWeight(assignment, c.getE1(), c);
1747                    break;
1748            }
1749        }
1750        
1751        /**
1752         * Students with complete schedules (see {@link Student#isComplete(Assignment)})
1753         * @return students with complete schedule
1754         */
1755        public Set<Student> getCompleteStudents() {
1756            return iCompleteStudents;
1757        }
1758        
1759        /**
1760         * Number of students with complete schedule
1761         * @return number of students with complete schedule
1762         */
1763        public int nrComplete() {
1764            return getCompleteStudents().size();
1765        }
1766        
1767        /** 
1768         * Recompute cached request weights
1769         * @param assignment curent assignment
1770         */
1771        public void requestWeightsChanged(Assignment<Request, Enrollment> assignment) {
1772            iTotalCRWeight = 0.0;
1773            iTotalDummyWeight = 0.0; iTotalDummyCRWeight = 0.0;
1774            iTotalPriorityCRWeight = new double[StudentPriority.values().length];
1775            iAssignedCRWeight = 0.0;
1776            iAssignedDummyCRWeight = 0.0;
1777            iAssignedCriticalCRWeight = new double[RequestPriority.values().length];
1778            iAssignedPriorityCriticalCRWeight = new double[RequestPriority.values().length][StudentPriority.values().length];
1779            for (int i = 0; i < RequestPriority.values().length; i++) {
1780                iAssignedCriticalCRWeight[i] = 0.0;
1781                for (int j = 0; j < StudentPriority.values().length; j++) {
1782                    iAssignedPriorityCriticalCRWeight[i][j] = 0.0;
1783                }
1784            }
1785            iAssignedPriorityCRWeight = new double[StudentPriority.values().length];
1786            for (int i = 0; i < StudentPriority.values().length; i++) {
1787                iAssignedPriorityCRWeight[i] = 0.0;
1788            }
1789            iNrDummyRequests = 0; iNrAssignedDummyRequests = 0;
1790            iTotalReservedSpace = 0.0; iReservedSpace = 0.0;
1791            iTotalMPPCRWeight = 0.0;
1792            iTotalSelCRWeight = 0.0;
1793            iAssignedNoTimeSectionWeight = 0.0;
1794            iAssignedOnlineSectionWeight = 0.0;
1795            iAssignedPastSectionWeight = 0.0;
1796            for (Request request: variables()) {
1797                boolean cr = (request instanceof CourseRequest);
1798                if (cr && !request.isAlternative())
1799                    iTotalCRWeight += request.getWeight();
1800                if (request.getStudent().isDummy()) {
1801                    iTotalDummyWeight += request.getWeight();
1802                    iNrDummyRequests ++;
1803                    if (cr && !request.isAlternative())
1804                        iTotalDummyCRWeight += request.getWeight();
1805                }
1806                if (cr && !request.isAlternative()) {
1807                    iTotalPriorityCRWeight[request.getStudent().getPriority().ordinal()] += request.getWeight();
1808                }
1809                if (request.isMPP())
1810                    iTotalMPPCRWeight += request.getWeight();
1811                if (request.hasSelection())
1812                    iTotalSelCRWeight += request.getWeight();
1813                Enrollment e = assignment.getValue(request);
1814                if (e != null) {
1815                    if (cr)
1816                        iAssignedCRWeight += request.getWeight();
1817                    if (cr && request.getRequestPriority() != RequestPriority.Normal && !request.getStudent().isDummy() && !request.isAlternative())
1818                        iAssignedCriticalCRWeight[request.getRequestPriority().ordinal()] += request.getWeight();
1819                    if (cr && request.getRequestPriority() != RequestPriority.Normal && !request.isAlternative())
1820                        iAssignedPriorityCriticalCRWeight[request.getRequestPriority().ordinal()][request.getStudent().getPriority().ordinal()] += request.getWeight();
1821                    if (request.isMPP()) {
1822                        iAssignedSameSectionWeight += request.getWeight() * e.percentInitial();
1823                        iAssignedSameChoiceWeight += request.getWeight() * e.percentSelected();
1824                        iAssignedSameTimeWeight += request.getWeight() * e.percentSameTime();
1825                    }
1826                    if (request.hasSelection()) {
1827                        iAssignedSelectedSectionWeight += request.getWeight() * e.percentSelectedSameSection();
1828                        iAssignedSelectedConfigWeight += request.getWeight() * e.percentSelectedSameConfig();
1829                    }
1830                    if (e.getReservation() != null)
1831                        iReservedSpace += request.getWeight();
1832                    if (cr && ((CourseRequest)request).hasReservations())
1833                        iTotalReservedSpace += request.getWeight();
1834                    if (request.getStudent().isDummy()) {
1835                        iNrAssignedDummyRequests ++;
1836                        if (cr)
1837                            iAssignedDummyCRWeight += request.getWeight();
1838                    }
1839                    if (cr) {
1840                        iAssignedPriorityCRWeight[request.getStudent().getPriority().ordinal()] += request.getWeight();
1841                    }
1842                    if (cr) {
1843                        int noTime = 0;
1844                        int online = 0;
1845                        int past = 0;
1846                        for (Section section: e.getSections()) {
1847                            if (!section.hasTime()) noTime ++;
1848                            if (section.isOnline()) online ++;
1849                            if (section.isPast()) past ++;
1850                        }
1851                        if (noTime > 0)
1852                            iAssignedNoTimeSectionWeight += request.getWeight() * noTime / e.getSections().size();
1853                        if (online > 0)
1854                            iAssignedOnlineSectionWeight += request.getWeight() * online / e.getSections().size();
1855                        if (past > 0)
1856                            iAssignedPastSectionWeight += request.getWeight() * past / e.getSections().size();
1857                    }
1858                }
1859            }
1860        }
1861        
1862        /**
1863         * Overall solution value
1864         * @return solution value
1865         */
1866        public double getTotalValue() {
1867            return iTotalValue;
1868        }
1869        
1870        /**
1871         * Number of last like ({@link Student#isDummy()} equals true) students with
1872         * a complete schedule ({@link Student#isComplete(Assignment)} equals true).
1873         * @return number of last like (projected) students with a complete schedule
1874         */
1875        public int getNrCompleteLastLikeStudents() {
1876            return iNrCompleteDummyStudents;
1877        }
1878        
1879        /**
1880         * Number of requests from projected ({@link Student#isDummy()} equals true)
1881         * students that are assigned.
1882         * @return number of real students with a complete schedule
1883         */
1884        public int getNrAssignedLastLikeRequests() {
1885            return iNrAssignedDummyRequests;
1886        }
1887
1888        @Override
1889        public void getInfo(Assignment<Request, Enrollment> assignment, Map<String, String> info) {
1890            if (iTotalCRWeight > 0.0) {
1891                info.put("Assigned course requests", sDecimalFormat.format(100.0 * iAssignedCRWeight / iTotalCRWeight) + "% (" + (int)Math.round(iAssignedCRWeight) + "/" + (int)Math.round(iTotalCRWeight) + ")");
1892                if (iNrDummyStudents > 0 && iNrDummyStudents != getStudents().size() && iTotalCRWeight != iTotalDummyCRWeight) {
1893                    if (iTotalDummyCRWeight > 0.0)
1894                        info.put("Projected assigned course requests", sDecimalFormat.format(100.0 * iAssignedDummyCRWeight / iTotalDummyCRWeight) + "% (" + (int)Math.round(iAssignedDummyCRWeight) + "/" + (int)Math.round(iTotalDummyCRWeight) + ")");
1895                    info.put("Real assigned course requests", sDecimalFormat.format(100.0 * (iAssignedCRWeight - iAssignedDummyCRWeight) / (iTotalCRWeight - iTotalDummyCRWeight)) +
1896                            "% (" + (int)Math.round(iAssignedCRWeight - iAssignedDummyCRWeight) + "/" + (int)Math.round(iTotalCRWeight - iTotalDummyCRWeight) + ")");
1897                }
1898                if (iAssignedNoTimeSectionWeight > 0.0) {
1899                    info.put("Using classes w/o time", sDecimalFormat.format(100.0 * iAssignedNoTimeSectionWeight / iAssignedCRWeight) + "% (" + sDecimalFormat.format(iAssignedNoTimeSectionWeight) + ")"); 
1900                }
1901                if (iAssignedOnlineSectionWeight > 0.0) {
1902                    info.put("Using online classes", sDecimalFormat.format(100.0 * iAssignedOnlineSectionWeight / iAssignedCRWeight) + "% (" + sDecimalFormat.format(iAssignedOnlineSectionWeight) + ")"); 
1903                }
1904                if (iAssignedPastSectionWeight > 0.0) {
1905                    info.put("Using past classes", sDecimalFormat.format(100.0 * iAssignedPastSectionWeight / iAssignedCRWeight) + "% (" + sDecimalFormat.format(iAssignedPastSectionWeight) + ")");
1906                }
1907            }
1908            String priorityAssignedCR = "";
1909            for (StudentPriority sp: StudentPriority.values()) {
1910                if (sp != StudentPriority.Dummy && iTotalPriorityCRWeight[sp.ordinal()] > 0.0) {
1911                    priorityAssignedCR += (priorityAssignedCR.isEmpty() ? "" : "\n") +
1912                            sp.name() + ": " + sDecimalFormat.format(100.0 * iAssignedPriorityCRWeight[sp.ordinal()] / iTotalPriorityCRWeight[sp.ordinal()]) + "% (" + (int)Math.round(iAssignedPriorityCRWeight[sp.ordinal()]) + "/" + (int)Math.round(iTotalPriorityCRWeight[sp.ordinal()]) + ")";
1913                }
1914            }
1915            if (!priorityAssignedCR.isEmpty())
1916                info.put("Assigned course requests (priority students)", priorityAssignedCR);
1917            for (RequestPriority rp: RequestPriority.values()) {
1918                if (rp == RequestPriority.Normal) continue;
1919                if (iTotalCriticalCRWeight[rp.ordinal()] > 0.0) {
1920                    info.put("Assigned " + rp.name().toLowerCase() + " course requests", sDoubleFormat.format(100.0 * iAssignedCriticalCRWeight[rp.ordinal()] / iTotalCriticalCRWeight[rp.ordinal()]) + "% (" + (int)Math.round(iAssignedCriticalCRWeight[rp.ordinal()]) + "/" + (int)Math.round(iTotalCriticalCRWeight[rp.ordinal()]) + ")");
1921                }
1922                priorityAssignedCR = "";
1923                for (StudentPriority sp: StudentPriority.values()) {
1924                    if (sp != StudentPriority.Dummy && iTotalPriorityCriticalCRWeight[rp.ordinal()][sp.ordinal()] > 0.0) {
1925                        priorityAssignedCR += (priorityAssignedCR.isEmpty() ? "" : "\n") +
1926                                sp.name() + ": " + sDoubleFormat.format(100.0 * iAssignedPriorityCriticalCRWeight[rp.ordinal()][sp.ordinal()] / iTotalPriorityCriticalCRWeight[rp.ordinal()][sp.ordinal()]) + "% (" + (int)Math.round(iAssignedPriorityCriticalCRWeight[rp.ordinal()][sp.ordinal()]) + "/" + (int)Math.round(iTotalPriorityCriticalCRWeight[rp.ordinal()][sp.ordinal()]) + ")";
1927                    }
1928                }
1929                if (!priorityAssignedCR.isEmpty())
1930                    info.put("Assigned " + rp.name().toLowerCase() + " course requests (priority students)", priorityAssignedCR);
1931            }
1932            if (iTotalReservedSpace > 0.0)
1933                info.put("Reservations", sDoubleFormat.format(100.0 * iReservedSpace / iTotalReservedSpace) + "% (" + Math.round(iReservedSpace) + "/" + Math.round(iTotalReservedSpace) + ")");
1934            if (iMPP && iTotalMPPCRWeight > 0.0) {
1935                info.put("Perturbations: same section", sDoubleFormat.format(100.0 * iAssignedSameSectionWeight / iTotalMPPCRWeight) + "% (" + Math.round(iAssignedSameSectionWeight) + "/" + Math.round(iTotalMPPCRWeight) + ")");
1936                if (iAssignedSameChoiceWeight > iAssignedSameSectionWeight)
1937                    info.put("Perturbations: same choice",sDoubleFormat.format(100.0 * iAssignedSameChoiceWeight / iTotalMPPCRWeight) + "% (" + Math.round(iAssignedSameChoiceWeight) + "/" + Math.round(iTotalMPPCRWeight) + ")");
1938                if (iAssignedSameTimeWeight > iAssignedSameChoiceWeight)
1939                    info.put("Perturbations: same time", sDoubleFormat.format(100.0 * iAssignedSameTimeWeight / iTotalMPPCRWeight) + "% (" + Math.round(iAssignedSameTimeWeight) + "/" + Math.round(iTotalMPPCRWeight) + ")");
1940            }
1941            if (iTotalSelCRWeight > 0.0) {
1942                info.put("Selection",sDoubleFormat.format(100.0 * (0.3 * iAssignedSelectedConfigWeight + 0.7 * iAssignedSelectedSectionWeight) / iTotalSelCRWeight) +
1943                        "% (" + Math.round(0.3 * iAssignedSelectedConfigWeight + 0.7 * iAssignedSelectedSectionWeight) + "/" + Math.round(iTotalSelCRWeight) + ")");
1944            }
1945        }
1946
1947        @Override
1948        public void getInfo(Assignment<Request, Enrollment> assignment, Map<String, String> info, Collection<Request> variables) {
1949        }
1950        
1951        public double getAssignedCourseRequestWeight() {
1952            return iAssignedCRWeight;
1953        }
1954        
1955        public double getAssignedCriticalCourseRequestWeight(RequestPriority rp) {
1956            return iAssignedCriticalCRWeight[rp.ordinal()];
1957        }
1958    }
1959    
1960    @Override
1961    public InheritedAssignment<Request, Enrollment> createInheritedAssignment(Solution<Request, Enrollment> solution, int index) {
1962        return new OptimisticInheritedAssignment<Request, Enrollment>(solution, index);
1963    }
1964    
1965    public DistanceMetric getDistanceMetric() {
1966        return (iStudentQuality != null ? iStudentQuality.getDistanceMetric() : iDistanceConflict != null ? iDistanceConflict.getDistanceMetric() : null);
1967    }
1968
1969    @Override
1970    public StudentSectioningModelContext inheritAssignmentContext(Assignment<Request, Enrollment> assignment, StudentSectioningModelContext parentContext) {
1971        return new StudentSectioningModelContext(parentContext);
1972    }
1973
1974}