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            int unavConfs = getStudentQuality().getTotalPenalty(StudentQuality.Type.UnavailabilityDistance, assignment);
460            if (confs > 0 || shortConfs > 0) {
461                info.put("Student distance conflicts", confs + (shortConfs == 0 ? "" : " (" + getDistanceMetric().getShortDistanceAccommodationReference() + ": " + shortConfs + ")"));
462            }
463            if (unavConfs > 0) {
464                info.put("Unavailabilities: Distance conflicts", String.valueOf(unavConfs));
465            }
466        } else if (getDistanceConflict() != null) {
467            int confs = getDistanceConflict().getTotalNrConflicts(assignment);
468            if (confs > 0) {
469                int shortConfs = getDistanceConflict().getTotalNrShortConflicts(assignment);
470                info.put("Student distance conflicts", confs + (shortConfs == 0 ? "" : " (" + getDistanceConflict().getDistanceMetric().getShortDistanceAccommodationReference() + ": " + shortConfs + ")"));
471            }
472        }
473        if (getStudentQuality() != null) {
474            int shareCR = getStudentQuality().getContext(assignment).countTotalPenalty(StudentQuality.Type.CourseTimeOverlap, assignment);
475            int shareFT = getStudentQuality().getContext(assignment).countTotalPenalty(StudentQuality.Type.FreeTimeOverlap, assignment);
476            int shareUN = getStudentQuality().getContext(assignment).countTotalPenalty(StudentQuality.Type.Unavailability, assignment);
477            if (shareCR + shareFT + shareUN > 0)
478                info.put("Time overlapping conflicts", sDoubleFormat.format((5.0 * (shareCR + shareFT + shareUN)) / iStudents.size()) + " mins per student\n" + 
479                        "(" + sDoubleFormat.format(5.0 * shareCR / iStudents.size()) + " between courses, " + sDoubleFormat.format(5.0 * shareFT / iStudents.size()) + " free time" +
480                        (shareUN == 0 ? "" : ", " + sDoubleFormat.format(5.0 * shareUN / iStudents.size()) + " teaching assignments & unavailabilities") + "; " + sDoubleFormat.format((shareCR + shareFT + shareUN) / 12.0) + " hours total)");
481        } else if (getTimeOverlaps() != null && getTimeOverlaps().getTotalNrConflicts(assignment) != 0) {
482            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)");
483        }
484        if (getStudentQuality() != null) {
485            int confLunch = getStudentQuality().getTotalPenalty(StudentQuality.Type.LunchBreak, assignment);
486            if (confLunch > 0)
487                info.put("Schedule Quality: Lunch conflicts", sDoubleFormat.format(20.0 * confLunch / getNrRealStudents(false)) + "% (" + confLunch + ")");
488            int confTravel = getStudentQuality().getTotalPenalty(StudentQuality.Type.TravelTime, assignment);
489            if (confTravel > 0)
490                info.put("Schedule Quality: Travel time", sDoubleFormat.format(((double)confTravel) / getNrRealStudents(false)) + " mins per student (" + sDecimalFormat.format(confTravel / 60.0) + " hours total)");
491            int confBtB = getStudentQuality().getTotalPenalty(StudentQuality.Type.BackToBack, assignment);
492            if (confBtB != 0)
493                info.put("Schedule Quality: Back-to-back classes", sDoubleFormat.format(((double)confBtB) / getNrRealStudents(false)) + " per student (" + confBtB + ")");
494            int confMod = getStudentQuality().getTotalPenalty(StudentQuality.Type.Modality, assignment);
495            if (confMod > 0)
496                info.put("Schedule Quality: Online class preference", sDoubleFormat.format(((double)confMod) / getNrRealStudents(false)) + " per student (" + confMod + ")");
497            int confWorkDay = getStudentQuality().getTotalPenalty(StudentQuality.Type.WorkDay, assignment);
498            if (confWorkDay > 0)
499                info.put("Schedule Quality: Work day", sDoubleFormat.format(5.0 * confWorkDay / getNrRealStudents(false)) + " mins over " +
500                        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)");
501            int early = getStudentQuality().getTotalPenalty(StudentQuality.Type.TooEarly, assignment);
502            if (early > 0) {
503                int min = getProperties().getPropertyInt("WorkDay.EarlySlot", 102) * Constants.SLOT_LENGTH_MIN + Constants.FIRST_SLOT_TIME_MIN;
504                int h = min / 60;
505                int m = min % 60;
506                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);
507                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)");
508            }
509            int late = getStudentQuality().getTotalPenalty(StudentQuality.Type.TooLate, assignment);
510            if (late > 0) {
511                int min = getProperties().getPropertyInt("WorkDay.LateSlot", 210) * Constants.SLOT_LENGTH_MIN + Constants.FIRST_SLOT_TIME_MIN;
512                int h = min / 60;
513                int m = min % 60;
514                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);
515                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)");
516            }
517            int accFT = getStudentQuality().getTotalPenalty(StudentQuality.Type.AccFreeTimeOverlap, assignment);
518            if (accFT > 0) {
519                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");
520            }
521            int accBtB = getStudentQuality().getTotalPenalty(StudentQuality.Type.AccBackToBack, assignment);
522            if (accBtB > 0) {
523                info.put("Accommodations: Back-to-back classes", sDoubleFormat.format(((double)accBtB) / getStudentsWithAccommodation(getStudentQuality().getStudentQualityContext().getBackToBackAccommodation())) + " non-BTB classes per student, " + accBtB + " total");
524            }
525            int accBbc = getStudentQuality().getTotalPenalty(StudentQuality.Type.AccBreaksBetweenClasses, assignment);
526            if (accBbc > 0) {
527                info.put("Accommodations: Break between classes", sDoubleFormat.format(((double)accBbc) / getStudentsWithAccommodation(getStudentQuality().getStudentQualityContext().getBreakBetweenClassesAccommodation())) + " BTB classes per student, " + accBbc + " total");
528            }
529            int shortConfs = getStudentQuality().getTotalPenalty(StudentQuality.Type.ShortDistance, assignment);
530            if (shortConfs > 0) {
531                info.put("Accommodations: Distance conflicts", sDoubleFormat.format(((double)shortConfs) / getStudentsWithAccommodation(getStudentQuality().getDistanceMetric().getShortDistanceAccommodationReference())) + " short distance conflicts per student, " + shortConfs + " total");
532            }
533        }
534        int nrLastLikeStudents = getNrLastLikeStudents(false);
535        if (nrLastLikeStudents != 0 && nrLastLikeStudents != getStudents().size()) {
536            int nrRealStudents = getStudents().size() - nrLastLikeStudents;
537            int nrLastLikeCompleteStudents = getNrCompleteLastLikeStudents(assignment, false);
538            int nrRealCompleteStudents = context.nrComplete() - nrLastLikeCompleteStudents;
539            if (nrLastLikeStudents > 0)
540                info.put("Projected students with complete schedule", sDecimalFormat.format(100.0
541                        * nrLastLikeCompleteStudents / nrLastLikeStudents)
542                        + "% (" + nrLastLikeCompleteStudents + "/" + nrLastLikeStudents + ")");
543            if (nrRealStudents > 0)
544                info.put("Real students with complete schedule", sDecimalFormat.format(100.0 * nrRealCompleteStudents
545                        / nrRealStudents)
546                        + "% (" + nrRealCompleteStudents + "/" + nrRealStudents + ")");
547            int nrLastLikeRequests = getNrLastLikeRequests(false);
548            int nrRealRequests = variables().size() - nrLastLikeRequests;
549            int nrLastLikeAssignedRequests = context.getNrAssignedLastLikeRequests();
550            int nrRealAssignedRequests = assignment.nrAssignedVariables() - nrLastLikeAssignedRequests;
551            if (nrLastLikeRequests > 0)
552                info.put("Projected assigned requests", sDecimalFormat.format(100.0 * nrLastLikeAssignedRequests / nrLastLikeRequests)
553                        + "% (" + nrLastLikeAssignedRequests + "/" + nrLastLikeRequests + ")");
554            if (nrRealRequests > 0)
555                info.put("Real assigned requests", sDecimalFormat.format(100.0 * nrRealAssignedRequests / nrRealRequests)
556                        + "% (" + nrRealAssignedRequests + "/" + nrRealRequests + ")");
557        }
558        context.getInfo(assignment, info);
559        
560        double groupSpread = 0.0; double groupCount = 0;
561        for (Offering offering: iOfferings) {
562            for (Course course: offering.getCourses()) {
563                for (RequestGroup group: course.getRequestGroups()) {
564                    groupSpread += group.getAverageSpread(assignment) * group.getEnrollmentWeight(assignment, null);
565                    groupCount += group.getEnrollmentWeight(assignment, null);
566                }
567            }
568        }
569        if (groupCount > 0)
570            info.put("Same group", sDecimalFormat.format(100.0 * groupSpread / groupCount) + "%");
571
572        return info;
573    }
574
575    /**
576     * Overall solution value
577     * @param assignment current assignment
578     * @param precise true if should be computed
579     * @return solution value
580     */
581    public double getTotalValue(Assignment<Request, Enrollment> assignment, boolean precise) {
582        if (precise) {
583            double total = 0;
584            for (Request r: assignment.assignedVariables())
585                total += r.getWeight() * iStudentWeights.getWeight(assignment, assignment.getValue(r));
586            if (iDistanceConflict != null)
587                for (DistanceConflict.Conflict c: iDistanceConflict.computeAllConflicts(assignment))
588                    total -= avg(c.getR1().getWeight(), c.getR2().getWeight()) * iStudentWeights.getDistanceConflictWeight(assignment, c);
589            if (iTimeOverlaps != null)
590                for (TimeOverlapsCounter.Conflict c: iTimeOverlaps.getContext(assignment).computeAllConflicts(assignment)) {
591                    if (c.getR1() != null) total -= c.getR1Weight() * iStudentWeights.getTimeOverlapConflictWeight(assignment, c.getE1(), c);
592                    if (c.getR2() != null) total -= c.getR2Weight() * iStudentWeights.getTimeOverlapConflictWeight(assignment, c.getE2(), c);
593                }
594            if (iStudentQuality != null)
595                for (StudentQuality.Type t: StudentQuality.Type.values()) {
596                    for (StudentQuality.Conflict c: iStudentQuality.getContext(assignment).computeAllConflicts(t, assignment)) {
597                        switch (c.getType().getType()) {
598                            case REQUEST:
599                                if (c.getR1() instanceof CourseRequest)
600                                    total -= c.getR1Weight() * iStudentWeights.getStudentQualityConflictWeight(assignment, c.getE1(), c);
601                                else
602                                    total -= c.getR2Weight() * iStudentWeights.getStudentQualityConflictWeight(assignment, c.getE2(), c);
603                                break;
604                            case BOTH:
605                                total -= c.getR1Weight() * iStudentWeights.getStudentQualityConflictWeight(assignment, c.getE1(), c);  
606                                total -= c.getR2Weight() * iStudentWeights.getStudentQualityConflictWeight(assignment, c.getE2(), c);
607                                break;
608                            case LOWER:
609                                total -= avg(c.getR1().getWeight(), c.getR2().getWeight()) * iStudentWeights.getStudentQualityConflictWeight(assignment, c.getE1(), c);
610                                break;
611                            case HIGHER:
612                                total -= avg(c.getR1().getWeight(), c.getR2().getWeight()) * iStudentWeights.getStudentQualityConflictWeight(assignment, c.getE1(), c);
613                                break;
614                        }
615                    }    
616                }
617            return -total;
618        }
619        return getContext(assignment).getTotalValue();
620    }
621    
622    /**
623     * Overall solution value
624     */
625    @Override
626    public double getTotalValue(Assignment<Request, Enrollment> assignment) {
627        return getContext(assignment).getTotalValue();
628    }
629
630    /**
631     * Configuration
632     * @return solver configuration
633     */
634    public DataProperties getProperties() {
635        return iProperties;
636    }
637
638    /**
639     * Empty online student sectioning infos for all sections (see
640     * {@link Section#getSpaceExpected()} and {@link Section#getSpaceHeld()}).
641     */
642    public void clearOnlineSectioningInfos() {
643        for (Offering offering : iOfferings) {
644            for (Config config : offering.getConfigs()) {
645                for (Subpart subpart : config.getSubparts()) {
646                    for (Section section : subpart.getSections()) {
647                        section.setSpaceExpected(0);
648                        section.setSpaceHeld(0);
649                    }
650                }
651            }
652        }
653    }
654
655    /**
656     * Compute online student sectioning infos for all sections (see
657     * {@link Section#getSpaceExpected()} and {@link Section#getSpaceHeld()}).
658     * @param assignment current assignment
659     */
660    public void computeOnlineSectioningInfos(Assignment<Request, Enrollment> assignment) {
661        clearOnlineSectioningInfos();
662        for (Student student : getStudents()) {
663            if (!student.isDummy())
664                continue;
665            for (Request request : student.getRequests()) {
666                if (!(request instanceof CourseRequest))
667                    continue;
668                CourseRequest courseRequest = (CourseRequest) request;
669                Enrollment enrollment = assignment.getValue(courseRequest);
670                if (enrollment != null) {
671                    for (Section section : enrollment.getSections()) {
672                        section.setSpaceHeld(courseRequest.getWeight() + section.getSpaceHeld());
673                    }
674                }
675                List<Enrollment> feasibleEnrollments = new ArrayList<Enrollment>();
676                int totalLimit = 0;
677                for (Enrollment enrl : courseRequest.values(assignment)) {
678                    boolean overlaps = false;
679                    for (Request otherRequest : student.getRequests()) {
680                        if (otherRequest.equals(courseRequest) || !(otherRequest instanceof CourseRequest))
681                            continue;
682                        Enrollment otherErollment = assignment.getValue(otherRequest);
683                        if (otherErollment == null)
684                            continue;
685                        if (enrl.isOverlapping(otherErollment)) {
686                            overlaps = true;
687                            break;
688                        }
689                    }
690                    if (!overlaps) {
691                        feasibleEnrollments.add(enrl);
692                        if (totalLimit >= 0) {
693                            int limit = enrl.getLimit();
694                            if (limit < 0) totalLimit = -1;
695                            else totalLimit += limit;
696                        }
697                    }
698                }
699                double increment = courseRequest.getWeight() / (totalLimit > 0 ? totalLimit : feasibleEnrollments.size());
700                for (Enrollment feasibleEnrollment : feasibleEnrollments) {
701                    for (Section section : feasibleEnrollment.getSections()) {
702                        if (totalLimit > 0) {
703                            section.setSpaceExpected(section.getSpaceExpected() + increment * feasibleEnrollment.getLimit());
704                        } else {
705                            section.setSpaceExpected(section.getSpaceExpected() + increment);
706                        }
707                    }
708                }
709            }
710        }
711    }
712
713    /**
714     * Sum of weights of all requests that are not assigned (see
715     * {@link Request#getWeight()}).
716     * @param assignment current assignment
717     * @return unassigned request weight
718     */
719    public double getUnassignedRequestWeight(Assignment<Request, Enrollment> assignment) {
720        double weight = 0.0;
721        for (Request request : assignment.unassignedVariables(this)) {
722            weight += request.getWeight();
723        }
724        return weight;
725    }
726
727    /**
728     * Sum of weights of all requests (see {@link Request#getWeight()}).
729     * @return total request weight
730     */
731    public double getTotalRequestWeight() {
732        double weight = 0.0;
733        for (Request request : variables()) {
734            weight += request.getWeight();
735        }
736        return weight;
737    }
738
739    /**
740     * Set distance conflict extension
741     * @param dc distance conflicts extension
742     */
743    public void setDistanceConflict(DistanceConflict dc) {
744        iDistanceConflict = dc;
745    }
746
747    /**
748     * Return distance conflict extension
749     * @return distance conflicts extension
750     */
751    public DistanceConflict getDistanceConflict() {
752        return iDistanceConflict;
753    }
754
755    /**
756     * Set time overlaps extension
757     * @param toc time overlapping conflicts extension
758     */
759    public void setTimeOverlaps(TimeOverlapsCounter toc) {
760        iTimeOverlaps = toc;
761    }
762
763    /**
764     * Return time overlaps extension
765     * @return time overlapping conflicts extension
766     */
767    public TimeOverlapsCounter getTimeOverlaps() {
768        return iTimeOverlaps;
769    }
770    
771    public StudentQuality getStudentQuality() { return iStudentQuality; }
772    public void setStudentQuality(StudentQuality q, boolean register) {
773        if (iStudentQuality != null)
774            getInfoProviders().remove(iStudentQuality);
775        iStudentQuality = q;
776        if (iStudentQuality != null)
777            getInfoProviders().add(iStudentQuality);
778        if (register) {
779            iStudentQuality.setAssignmentContextReference(createReference(iStudentQuality));
780            iStudentQuality.register(this);
781        }
782    }
783    
784    public void setStudentQuality(StudentQuality q) {
785        setStudentQuality(q, true);
786    }
787
788    /**
789     * Average priority of unassigned requests (see
790     * {@link Request#getPriority()})
791     * @param assignment current assignment
792     * @return average priority of unassigned requests
793     */
794    public double avgUnassignPriority(Assignment<Request, Enrollment> assignment) {
795        double totalPriority = 0.0;
796        for (Request request : assignment.unassignedVariables(this)) {
797            if (request.isAlternative())
798                continue;
799            totalPriority += request.getPriority();
800        }
801        return 1.0 + totalPriority / assignment.nrUnassignedVariables(this);
802    }
803
804    /**
805     * Average number of requests per student (see {@link Student#getRequests()}
806     * )
807     * @return average number of requests per student
808     */
809    public double avgNrRequests() {
810        double totalRequests = 0.0;
811        int totalStudents = 0;
812        for (Student student : getStudents()) {
813            if (student.nrRequests() == 0)
814                continue;
815            totalRequests += student.nrRequests();
816            totalStudents++;
817        }
818        return totalRequests / totalStudents;
819    }
820
821    /** Number of last like ({@link Student#isDummy()} equals true) students. 
822     * @param precise true if to be computed
823     * @return number of last like (projected) students
824     **/
825    public int getNrLastLikeStudents(boolean precise) {
826        if (!precise)
827            return iNrDummyStudents;
828        int nrLastLikeStudents = 0;
829        for (Student student : getStudents()) {
830            if (student.isDummy())
831                nrLastLikeStudents++;
832        }
833        return nrLastLikeStudents;
834    }
835
836    /** Number of real ({@link Student#isDummy()} equals false) students. 
837     * @param precise true if to be computed
838     * @return number of real students
839     **/
840    public int getNrRealStudents(boolean precise) {
841        if (!precise)
842            return getStudents().size() - iNrDummyStudents;
843        int nrRealStudents = 0;
844        for (Student student : getStudents()) {
845            if (!student.isDummy())
846                nrRealStudents++;
847        }
848        return nrRealStudents;
849    }
850    
851    /**
852     * Count students with given accommodation
853     */
854    public int getStudentsWithAccommodation(String acc) {
855        int nrAccStudents = 0;
856        for (Student student : getStudents()) {
857            if (student.hasAccommodation(acc))
858                nrAccStudents++;
859        }
860        return nrAccStudents;
861    }
862
863    /**
864     * Number of last like ({@link Student#isDummy()} equals true) students with
865     * a complete schedule ({@link Student#isComplete(Assignment)} equals true).
866     * @param assignment current assignment
867     * @param precise true if to be computed
868     * @return number of last like (projected) students with a complete schedule
869     */
870    public int getNrCompleteLastLikeStudents(Assignment<Request, Enrollment> assignment, boolean precise) {
871        if (!precise)
872            return getContext(assignment).getNrCompleteLastLikeStudents();
873        int nrLastLikeStudents = 0;
874        for (Student student : getStudents()) {
875            if (student.isComplete(assignment) && student.isDummy())
876                nrLastLikeStudents++;
877        }
878        return nrLastLikeStudents;
879    }
880
881    /**
882     * Number of real ({@link Student#isDummy()} equals false) students with a
883     * complete schedule ({@link Student#isComplete(Assignment)} equals true).
884     * @param assignment current assignment
885     * @param precise true if to be computed
886     * @return number of real students with a complete schedule
887     */
888    public int getNrCompleteRealStudents(Assignment<Request, Enrollment> assignment, boolean precise) {
889        if (!precise)
890            return getContext(assignment).nrComplete() - getContext(assignment).getNrCompleteLastLikeStudents();
891        int nrRealStudents = 0;
892        for (Student student : getStudents()) {
893            if (student.isComplete(assignment) && !student.isDummy())
894                nrRealStudents++;
895        }
896        return nrRealStudents;
897    }
898
899    /**
900     * Number of requests from projected ({@link Student#isDummy()} equals true)
901     * students.
902     * @param precise true if to be computed
903     * @return number of requests from projected students 
904     */
905    public int getNrLastLikeRequests(boolean precise) {
906        if (!precise)
907            return iNrDummyRequests;
908        int nrLastLikeRequests = 0;
909        for (Request request : variables()) {
910            if (request.getStudent().isDummy())
911                nrLastLikeRequests++;
912        }
913        return nrLastLikeRequests;
914    }
915
916    /**
917     * Number of requests from real ({@link Student#isDummy()} equals false)
918     * students.
919     * @param precise true if to be computed
920     * @return number of requests from real students 
921     */
922    public int getNrRealRequests(boolean precise) {
923        if (!precise)
924            return variables().size() - iNrDummyRequests;
925        int nrRealRequests = 0;
926        for (Request request : variables()) {
927            if (!request.getStudent().isDummy())
928                nrRealRequests++;
929        }
930        return nrRealRequests;
931    }
932
933    /**
934     * Number of requests from projected ({@link Student#isDummy()} equals true)
935     * students that are assigned.
936     * @param assignment current assignment
937     * @param precise true if to be computed
938     * @return number of requests from projected students that are assigned
939     */
940    public int getNrAssignedLastLikeRequests(Assignment<Request, Enrollment> assignment, boolean precise) {
941        if (!precise)
942            return getContext(assignment).getNrAssignedLastLikeRequests();
943        int nrLastLikeRequests = 0;
944        for (Request request : assignment.assignedVariables()) {
945            if (request.getStudent().isDummy())
946                nrLastLikeRequests++;
947        }
948        return nrLastLikeRequests;
949    }
950
951    /**
952     * Number of requests from real ({@link Student#isDummy()} equals false)
953     * students that are assigned.
954     * @param assignment current assignment
955     * @param precise true if to be computed
956     * @return number of requests from real students that are assigned
957     */
958    public int getNrAssignedRealRequests(Assignment<Request, Enrollment> assignment, boolean precise) {
959        if (!precise)
960            return assignment.nrAssignedVariables() - getContext(assignment).getNrAssignedLastLikeRequests();
961        int nrRealRequests = 0;
962        for (Request request : assignment.assignedVariables()) {
963            if (!request.getStudent().isDummy())
964                nrRealRequests++;
965        }
966        return nrRealRequests;
967    }
968
969    /**
970     * Model extended info. Some more information (that is more expensive to
971     * compute) is added to an ordinary {@link Model#getInfo(Assignment)}.
972     */
973    @Override
974    public Map<String, String> getExtendedInfo(Assignment<Request, Enrollment> assignment) {
975        Map<String, String> info = getInfo(assignment);
976        /*
977        int nrLastLikeStudents = getNrLastLikeStudents(true);
978        if (nrLastLikeStudents != 0 && nrLastLikeStudents != getStudents().size()) {
979            int nrRealStudents = getStudents().size() - nrLastLikeStudents;
980            int nrLastLikeCompleteStudents = getNrCompleteLastLikeStudents(true);
981            int nrRealCompleteStudents = getCompleteStudents().size() - nrLastLikeCompleteStudents;
982            info.put("Projected students with complete schedule", sDecimalFormat.format(100.0
983                    * nrLastLikeCompleteStudents / nrLastLikeStudents)
984                    + "% (" + nrLastLikeCompleteStudents + "/" + nrLastLikeStudents + ")");
985            info.put("Real students with complete schedule", sDecimalFormat.format(100.0 * nrRealCompleteStudents
986                    / nrRealStudents)
987                    + "% (" + nrRealCompleteStudents + "/" + nrRealStudents + ")");
988            int nrLastLikeRequests = getNrLastLikeRequests(true);
989            int nrRealRequests = variables().size() - nrLastLikeRequests;
990            int nrLastLikeAssignedRequests = getNrAssignedLastLikeRequests(true);
991            int nrRealAssignedRequests = assignedVariables().size() - nrLastLikeAssignedRequests;
992            info.put("Projected assigned requests", sDecimalFormat.format(100.0 * nrLastLikeAssignedRequests
993                    / nrLastLikeRequests)
994                    + "% (" + nrLastLikeAssignedRequests + "/" + nrLastLikeRequests + ")");
995            info.put("Real assigned requests", sDecimalFormat.format(100.0 * nrRealAssignedRequests / nrRealRequests)
996                    + "% (" + nrRealAssignedRequests + "/" + nrRealRequests + ")");
997        }
998        */
999        // info.put("Average unassigned priority", sDecimalFormat.format(avgUnassignPriority()));
1000        // info.put("Average number of requests", sDecimalFormat.format(avgNrRequests()));
1001        
1002        /*
1003        double total = 0;
1004        for (Request r: variables())
1005            if (r.getAssignment() != null)
1006                total += r.getWeight() * iStudentWeights.getWeight(r.getAssignment());
1007        */
1008        /*
1009        double dc = 0;
1010        if (getDistanceConflict() != null && getDistanceConflict().getTotalNrConflicts(assignment) != 0) {
1011            Set<DistanceConflict.Conflict> conf = getDistanceConflict().getAllConflicts(assignment);
1012            int sdc = 0;
1013            for (DistanceConflict.Conflict c: conf) {
1014                dc += avg(c.getR1().getWeight(), c.getR2().getWeight()) * iStudentWeights.getDistanceConflictWeight(assignment, c);
1015                if (c.getStudent().isNeedShortDistances()) sdc ++;
1016            }
1017            if (!conf.isEmpty())
1018                info.put("Student distance conflicts", conf.size() + (sdc > 0 ? " (" + getDistanceConflict().getDistanceMetric().getShortDistanceAccommodationReference() + ": " + sdc + ", weighted: " : " (weighted: ") + sDecimalFormat.format(dc) + ")");
1019        }
1020        */
1021        if (getStudentQuality() == null && getTimeOverlaps() != null && getTimeOverlaps().getTotalNrConflicts(assignment) != 0) {
1022            Set<TimeOverlapsCounter.Conflict> conf = getTimeOverlaps().getContext(assignment).computeAllConflicts(assignment);
1023            int share = 0, crShare = 0;
1024            for (TimeOverlapsCounter.Conflict c: conf) {
1025                share += c.getShare();
1026                if (c.getR1() instanceof CourseRequest && c.getR2() instanceof CourseRequest)
1027                    crShare += c.getShare();
1028            }
1029            if (share > 0)
1030                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)");
1031        }
1032        if (getStudentQuality() != null) {
1033            int confBtB = getStudentQuality().getTotalPenalty(StudentQuality.Type.BackToBack, assignment);
1034            if (confBtB != 0) {
1035                int prefBtb = 0, discBtb = 0;
1036                int prefStd = 0, discStd = 0;
1037                int prefPairs = 0, discPairs = 0;
1038                for (Student s: getStudents()) {
1039                    if (s.isDummy() || s.getBackToBackPreference() == BackToBackPreference.NO_PREFERENCE) continue;
1040                    int[] classesPerDay = new int[] {0, 0, 0, 0, 0, 0, 0};
1041                    for (Request r: s.getRequests()) {
1042                        Enrollment e = r.getAssignment(assignment);
1043                        if (e == null || !e.isCourseRequest()) continue;
1044                        for (Section x: e.getSections()) {
1045                            if (x.getTime() != null)
1046                                for (int i = 0; i < Constants.DAY_CODES.length; i++)
1047                                    if ((x.getTime().getDayCode() & Constants.DAY_CODES[i]) != 0)
1048                                        classesPerDay[i] ++;
1049                        }
1050                    }
1051                    int max = 0;
1052                    for (int c: classesPerDay)
1053                        if (c > 1) max += c - 1;
1054                    int btb = getStudentQuality().getContext(assignment).allPenalty(StudentQuality.Type.BackToBack, assignment, s);
1055                    if (s.getBackToBackPreference() == BackToBackPreference.BTB_PREFERRED) {
1056                        prefStd ++;
1057                        prefBtb += btb;
1058                        prefPairs += Math.max(btb, max);
1059                    } else if (s.getBackToBackPreference() == BackToBackPreference.BTB_DISCOURAGED) {
1060                        discStd ++;
1061                        discBtb -= btb;
1062                        discPairs += Math.max(btb, max);
1063                    }
1064                }
1065                if (prefStd > 0)
1066                    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)");
1067                if (discStd > 0)
1068                    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)");
1069            }
1070            int confMod = getStudentQuality().getTotalPenalty(StudentQuality.Type.Modality, assignment);
1071            if (confMod > 0) {
1072                int prefOnl = 0, discOnl = 0;
1073                int prefStd = 0, discStd = 0;
1074                int prefCls = 0, discCls = 0;
1075                for (Student s: getStudents()) {
1076                    if (s.isDummy()) continue;
1077                    if (s.isDummy() || s.getModalityPreference() == ModalityPreference.NO_PREFERENCE || s.getModalityPreference() == ModalityPreference.ONLINE_REQUIRED) continue;
1078                    int classes = 0;
1079                    for (Request r: s.getRequests()) {
1080                        Enrollment e = r.getAssignment(assignment);
1081                        if (e == null || !e.isCourseRequest()) continue;
1082                        classes += e.getSections().size();
1083                    }
1084                    if (s.getModalityPreference() == ModalityPreference.ONLINE_PREFERRED) {
1085                        prefStd ++;
1086                        prefOnl += getStudentQuality().getContext(assignment).allPenalty(StudentQuality.Type.Modality, assignment, s);
1087                        prefCls += classes;
1088                    } else if (s.getModalityPreference() == ModalityPreference.ONILNE_DISCOURAGED) {
1089                        discStd ++;
1090                        discOnl += getStudentQuality().getContext(assignment).allPenalty(StudentQuality.Type.Modality, assignment, s);
1091                        discCls += classes;
1092                    }
1093                }
1094                if (prefStd > 0)
1095                    info.put("Schedule Quality: Online preferred", sDoubleFormat.format(100.0 - (100.0 * prefOnl) / prefCls) + "% online classes on average (" + prefOnl + "/" + prefCls + " classes for " + prefStd + " students)");
1096                if (discStd > 0)
1097                    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)");
1098            }
1099        }
1100        /*
1101        info.put("Overall solution value", sDecimalFormat.format(total - dc - toc) + (dc == 0.0 && toc == 0.0 ? "" :
1102            " (" + (dc != 0.0 ? "distance: " + sDecimalFormat.format(dc): "") + (dc != 0.0 && toc != 0.0 ? ", " : "") + 
1103            (toc != 0.0 ? "overlap: " + sDecimalFormat.format(toc) : "") + ")")
1104            );
1105        */
1106        
1107        double disbWeight = 0;
1108        int disbSections = 0;
1109        int disb10Sections = 0;
1110        int disb10Limit = getProperties().getPropertyInt("Info.ListDisbalancedSections", 0);
1111        Set<String> disb10SectionList = (disb10Limit == 0 ? null : new TreeSet<String>()); 
1112        for (Offering offering: getOfferings()) {
1113            for (Config config: offering.getConfigs()) {
1114                double enrl = config.getEnrollmentTotalWeight(assignment, null);
1115                for (Subpart subpart: config.getSubparts()) {
1116                    if (subpart.getSections().size() <= 1) continue;
1117                    if (subpart.getLimit() > 0) {
1118                        // sections have limits -> desired size is section limit x (total enrollment / total limit)
1119                        double ratio = enrl / subpart.getLimit();
1120                        for (Section section: subpart.getSections()) {
1121                            double desired = ratio * section.getLimit();
1122                            disbWeight += Math.abs(section.getEnrollmentTotalWeight(assignment, null) - desired);
1123                            disbSections ++;
1124                            if (Math.abs(desired - section.getEnrollmentTotalWeight(assignment, null)) >= Math.max(1.0, 0.1 * section.getLimit())) {
1125                                disb10Sections++;
1126                                if (disb10SectionList != null)
1127                                        disb10SectionList.add(section.getSubpart().getConfig().getOffering().getName() + " " + section.getSubpart().getName() + " " + section.getName()); 
1128                            }
1129                        }
1130                    } else {
1131                        // unlimited sections -> desired size is total enrollment / number of sections
1132                        for (Section section: subpart.getSections()) {
1133                            double desired = enrl / subpart.getSections().size();
1134                            disbWeight += Math.abs(section.getEnrollmentTotalWeight(assignment, null) - desired);
1135                            disbSections ++;
1136                            if (Math.abs(desired - section.getEnrollmentTotalWeight(assignment, null)) >= Math.max(1.0, 0.1 * desired)) {
1137                                disb10Sections++;
1138                                if (disb10SectionList != null)
1139                                        disb10SectionList.add(section.getSubpart().getConfig().getOffering().getName() + " " + section.getSubpart().getName() + " " + section.getName());
1140                            }
1141                        }
1142                    }
1143                }
1144            }
1145        }
1146        if (disbSections != 0) {
1147            double assignedCRWeight = getContext(assignment).getAssignedCourseRequestWeight();
1148            info.put("Average disbalance", sDecimalFormat.format(assignedCRWeight == 0 ? 0.0 : 100.0 * disbWeight / assignedCRWeight) + "% (" + sDecimalFormat.format(disbWeight / disbSections) + ")");
1149            String list = "";
1150            if (disb10SectionList != null) {
1151                int i = 0;
1152                for (String section: disb10SectionList) {
1153                    if (i == disb10Limit) {
1154                        list += "\n...";
1155                        break;
1156                    }
1157                    list += "\n" + section;
1158                    i++;
1159                }
1160            }
1161            info.put("Sections disbalanced by 10% or more", sDecimalFormat.format(disbSections == 0 ? 0.0 : 100.0 * disb10Sections / disbSections) + "% (" + disb10Sections + ")" + (list.isEmpty() ? "" : "\n" + list));
1162        }
1163        
1164        int assCR = 0, priCR = 0;
1165        for (Request r: variables()) {
1166            if (r instanceof CourseRequest && !r.getStudent().isDummy()) {
1167                CourseRequest cr = (CourseRequest)r;
1168                Enrollment e = assignment.getValue(cr);
1169                if (e != null) {
1170                    assCR ++;
1171                    if (!cr.isAlternative() && cr.getCourses().get(0).equals(e.getCourse())) priCR ++;
1172                }
1173            }
1174        }
1175        if (assCR > 0)
1176            info.put("Assigned priority course requests", sDoubleFormat.format(100.0 * priCR / assCR) + "% (" + priCR + "/" + assCR + ")");
1177        int[] missing = new int[] {0, 0, 0, 0, 0};
1178        int incomplete = 0;
1179        for (Student student: getStudents()) {
1180            if (student.isDummy()) continue;
1181            int nrRequests = 0;
1182            int nrAssignedRequests = 0;
1183            for (Request r : student.getRequests()) {
1184                if (!(r instanceof CourseRequest)) continue; // ignore free times
1185                if (!r.isAlternative()) nrRequests++;
1186                if (r.isAssigned(assignment)) nrAssignedRequests++;
1187            }
1188            if (nrAssignedRequests < nrRequests) {
1189                missing[Math.min(nrRequests - nrAssignedRequests, missing.length) - 1] ++;
1190                incomplete ++;
1191            }
1192        }
1193
1194        for (int i = 0; i < missing.length; i++)
1195            if (missing[i] > 0)
1196                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] + ")");
1197
1198        info.put("Overall solution value", sDoubleFormat.format(getTotalValue(assignment)));// + " [precise: " + sDoubleFormat.format(getTotalValue(assignment, true)) + "]");
1199        
1200        int nrStudentsBelowMinCredit = 0, nrStudents = 0;
1201        for (Student student: getStudents()) {
1202            if (student.isDummy()) continue;
1203            if (student.hasMinCredit()) {
1204                nrStudents++;
1205                float credit = student.getAssignedCredit(assignment); 
1206                if (credit < student.getMinCredit() && !student.isComplete(assignment))
1207                    nrStudentsBelowMinCredit ++;
1208            }
1209        }
1210        if (nrStudentsBelowMinCredit > 0)
1211            info.put("Students below min credit", sDoubleFormat.format(100.0 * nrStudentsBelowMinCredit / nrStudents) + "% (" + nrStudentsBelowMinCredit + "/" + nrStudents + ")");
1212        
1213        int[] notAssignedPriority = new int[] {0, 0, 0, 0, 0, 0, 0};
1214        int[] assignedChoice = new int[] {0, 0, 0, 0, 0};
1215        int notAssignedTotal = 0, assignedChoiceTotal = 0;
1216        int avgPriority = 0, avgChoice = 0;
1217        for (Student student: getStudents()) {
1218            if (student.isDummy()) continue;
1219            for (Request r : student.getRequests()) {
1220                if (!(r instanceof CourseRequest)) continue; // ignore free times
1221                Enrollment e = r.getAssignment(assignment);
1222                if (e == null) {
1223                    if (!r.isAlternative()) {
1224                        notAssignedPriority[Math.min(r.getPriority(), notAssignedPriority.length - 1)] ++;
1225                        notAssignedTotal ++;
1226                        avgPriority += r.getPriority();
1227                    }
1228                } else {
1229                    assignedChoice[Math.min(e.getTruePriority(), assignedChoice.length - 1)] ++;
1230                    assignedChoiceTotal ++;
1231                    avgChoice += e.getTruePriority();
1232                }
1233            }
1234        }
1235        for (int i = 0; i < notAssignedPriority.length; i++)
1236            if (notAssignedPriority[i] > 0)
1237                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] + ")");
1238        if (notAssignedTotal > 0)
1239            info.put("Priority: Average not-assigned priority", sDecimalFormat.format(1.0 + ((double)avgPriority) / notAssignedTotal));
1240        for (int i = 0; i < assignedChoice.length; i++)
1241            if (assignedChoice[i] > 0)
1242                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] + ")");
1243        if (assignedChoiceTotal > 0)
1244            info.put("Choice: Average assigned choice", sDecimalFormat.format(1.0 + ((double)avgChoice) / assignedChoiceTotal));
1245        
1246        int nbrSections = 0, nbrFullSections = 0, nbrSections98 = 0, nbrSections95 = 0, nbrSections90 = 0, nbrSectionsDis = 0;
1247        int enrlSections = 0, enrlFullSections = 0, enrlSections98 = 0, enrlSections95 = 0, enrlSections90 = 0, enrlSectionsDis = 0;
1248        int nbrOfferings = 0, nbrFullOfferings = 0, nbrOfferings98 = 0, nbrOfferings95 = 0, nbrOfferings90 = 0;
1249        int enrlOfferings = 0, enrlOfferingsFull = 0, enrlOfferings98 = 0, enrlOfferings95 = 0, enrlOfferings90 = 0;
1250        for (Offering offering: getOfferings()) {
1251            int offeringLimit = 0, offeringEnrollment = 0;
1252            for (Config config: offering.getConfigs()) {
1253                int configLimit = config.getLimit();
1254                for (Subpart subpart: config.getSubparts()) {
1255                    int subpartLimit = 0;
1256                    for (Section section: subpart.getSections()) {
1257                        if (section.isCancelled()) continue;
1258                        int enrl = section.getEnrollments(assignment).size();
1259                        if (section.getLimit() < 0 || subpartLimit < 0)
1260                            subpartLimit = -1;
1261                        else
1262                            subpartLimit += (section.isEnabled() ? section.getLimit() : enrl);
1263                        nbrSections ++;
1264                        enrlSections += enrl;
1265                        if (section.getLimit() >= 0 && section.getLimit() <= enrl) {
1266                            nbrFullSections ++;
1267                            enrlFullSections += enrl;
1268                        }
1269                        if (!section.isEnabled() && (enrl > 0 || section.getLimit() >= 0)) {
1270                            nbrSectionsDis ++;
1271                            enrlSectionsDis += enrl;
1272                        }
1273                        if (section.getLimit() >= 0 && (section.getLimit() - enrl) <= Math.round(0.02 * section.getLimit())) {
1274                            nbrSections98 ++;
1275                            enrlSections98 += enrl;
1276                        }
1277                        if (section.getLimit() >= 0 && (section.getLimit() - enrl) <= Math.round(0.05 * section.getLimit())) {
1278                            nbrSections95 ++;
1279                            enrlSections95 += enrl;
1280                        }
1281                        if (section.getLimit() >= 0 && (section.getLimit() - enrl) <= Math.round(0.10 * section.getLimit())) {
1282                            nbrSections90 ++;
1283                            enrlSections90 += enrl;
1284                        }
1285                    }
1286                    if (configLimit < 0 || subpartLimit < 0)
1287                        configLimit = -1;
1288                    else
1289                        configLimit = Math.min(configLimit, subpartLimit);
1290                }
1291                if (offeringLimit < 0 || configLimit < 0)
1292                    offeringLimit = -1;
1293                else
1294                    offeringLimit += configLimit;
1295                offeringEnrollment += config.getEnrollments(assignment).size();
1296            }
1297            nbrOfferings ++;
1298            enrlOfferings += offeringEnrollment;
1299            
1300            if (offeringLimit >=0 && offeringEnrollment >= offeringLimit) {
1301                nbrFullOfferings ++;
1302                enrlOfferingsFull += offeringEnrollment;
1303            }
1304            if (offeringLimit >= 0 && (offeringLimit - offeringEnrollment) <= Math.round(0.02 * offeringLimit)) {
1305                nbrOfferings98++;
1306                enrlOfferings98 += offeringEnrollment;
1307            }
1308            if (offeringLimit >= 0 && (offeringLimit - offeringEnrollment) <= Math.round(0.05 * offeringLimit)) {
1309                nbrOfferings95++;
1310                enrlOfferings95 += offeringEnrollment;
1311            }
1312            if (offeringLimit >= 0 && (offeringLimit - offeringEnrollment) <= Math.round(0.10 * offeringLimit)) {
1313                nbrOfferings90++;
1314                enrlOfferings90 += offeringEnrollment;
1315            }
1316        }
1317        if (enrlOfferings90 > 0 && enrlOfferings > 0) 
1318            info.put("Full Offerings", (nbrFullOfferings > 0 ? nbrFullOfferings + " with no space (" + sDecimalFormat.format(100.0 * nbrFullOfferings / nbrOfferings) + "% of all offerings, " +
1319                    sDecimalFormat.format(100.0 * enrlOfferingsFull / enrlOfferings) + "% assignments)\n" : "")+
1320                    (nbrOfferings98 > nbrFullOfferings ? nbrOfferings98 + " with &leq; 2% available (" + sDecimalFormat.format(100.0 * nbrOfferings98 / nbrOfferings) + "% of all offerings, " +
1321                    sDecimalFormat.format(100.0 * enrlOfferings98 / enrlOfferings) + "% assignments)\n" : "")+
1322                    (nbrOfferings95 > nbrOfferings98 ? nbrOfferings95 + " with &leq; 5% available (" + sDecimalFormat.format(100.0 * nbrOfferings95 / nbrOfferings) + "% of all offerings, " +
1323                    sDecimalFormat.format(100.0 * enrlOfferings95 / enrlOfferings) + "% assignments)\n" : "")+
1324                    (nbrOfferings90 > nbrOfferings95 ? nbrOfferings90 + " with &leq; 10% available (" + sDecimalFormat.format(100.0 * nbrOfferings90 / nbrOfferings) + "% of all offerings, " +
1325                    sDecimalFormat.format(100.0 * enrlOfferings90 / enrlOfferings) + "% assignments)" : ""));
1326        if ((enrlSections90 > 0 || nbrSectionsDis > 0) && enrlSections > 0)
1327            info.put("Full Sections", (nbrFullSections > 0 ? nbrFullSections + " with no space (" + sDecimalFormat.format(100.0 * nbrFullSections / nbrSections) + "% of all sections, "+
1328                    sDecimalFormat.format(100.0 * enrlFullSections / enrlSections) + "% assignments)\n" : "") +
1329                    (nbrSectionsDis > 0 ? nbrSectionsDis + " disabled (" + sDecimalFormat.format(100.0 * nbrSectionsDis / nbrSections) + "% of all sections, "+
1330                    sDecimalFormat.format(100.0 * enrlSectionsDis / enrlSections) + "% assignments)\n" : "") +
1331                    (enrlSections98 > nbrFullSections ? nbrSections98 + " with &leq; 2% available (" + sDecimalFormat.format(100.0 * nbrSections98 / nbrSections) + "% of all sections, " +
1332                    sDecimalFormat.format(100.0 * enrlSections98 / enrlSections) + "% assignments)\n" : "") +
1333                    (nbrSections95 > enrlSections98 ? nbrSections95 + " with &leq; 5% available (" + sDecimalFormat.format(100.0 * nbrSections95 / nbrSections) + "% of all sections, " +
1334                    sDecimalFormat.format(100.0 * enrlSections95 / enrlSections) + "% assignments)\n" : "") +
1335                    (nbrSections90 > nbrSections95 ? nbrSections90 + " with &leq; 10% available (" + sDecimalFormat.format(100.0 * nbrSections90 / nbrSections) + "% of all sections, " +
1336                    sDecimalFormat.format(100.0 * enrlSections90 / enrlSections) + "% assignments)" : ""));
1337        if (getStudentQuality() != null) {
1338            int shareCR = getStudentQuality().getContext(assignment).countTotalPenalty(StudentQuality.Type.CourseTimeOverlap, assignment);
1339            int shareFT = getStudentQuality().getContext(assignment).countTotalPenalty(StudentQuality.Type.FreeTimeOverlap, assignment);
1340            int shareUN = getStudentQuality().getContext(assignment).countTotalPenalty(StudentQuality.Type.Unavailability, assignment);
1341            int shareUND = getStudentQuality().getContext(assignment).countTotalPenalty(StudentQuality.Type.UnavailabilityDistance, assignment);
1342            if (shareCR > 0) {
1343                Set<Student> students = new HashSet<Student>();
1344                for (StudentQuality.Conflict c: getStudentQuality().getContext(assignment).computeAllConflicts(StudentQuality.Type.CourseTimeOverlap, assignment)) {
1345                    students.add(c.getStudent());
1346                }
1347                info.put("Time overlaps: courses", students.size() + " students (avg " + sDoubleFormat.format(5.0 * shareCR / students.size()) + " mins)");
1348            }
1349            if (shareFT > 0) {
1350                Set<Student> students = new HashSet<Student>();
1351                for (StudentQuality.Conflict c: getStudentQuality().getContext(assignment).computeAllConflicts(StudentQuality.Type.FreeTimeOverlap, assignment)) {
1352                    students.add(c.getStudent());
1353                }
1354                info.put("Time overlaps: free times", students.size() + " students (avg " + sDoubleFormat.format(5.0 * shareFT / students.size()) + " mins)");
1355            }
1356            if (shareUN > 0) {
1357                Set<Student> students = new HashSet<Student>();
1358                for (StudentQuality.Conflict c: getStudentQuality().getContext(assignment).computeAllConflicts(StudentQuality.Type.Unavailability, assignment)) {
1359                    students.add(c.getStudent());
1360                }
1361                info.put("Unavailabilities: Time conflicts", students.size() + " students (avg " + sDoubleFormat.format(5.0 * shareUN / students.size()) + " mins)");
1362            }
1363            if (shareUND > 0) {
1364                Set<Student> students = new HashSet<Student>();
1365                for (StudentQuality.Conflict c: getStudentQuality().getContext(assignment).computeAllConflicts(StudentQuality.Type.UnavailabilityDistance, assignment)) {
1366                    students.add(c.getStudent());
1367                }
1368                info.put("Unavailabilities: Distance conflicts", students.size() + " students (avg " + sDoubleFormat.format(shareUND / students.size()) + " travels)");
1369            }
1370        } else if (getTimeOverlaps() != null && getTimeOverlaps().getTotalNrConflicts(assignment) != 0) {
1371            Set<TimeOverlapsCounter.Conflict> conf = getTimeOverlaps().getContext(assignment).computeAllConflicts(assignment);
1372            int shareCR = 0, shareFT = 0, shareUN = 0;
1373            Set<Student> studentsCR = new HashSet<Student>();
1374            Set<Student> studentsFT = new HashSet<Student>();
1375            Set<Student> studentsUN = new HashSet<Student>();
1376            for (TimeOverlapsCounter.Conflict c: conf) {
1377                if (c.getR1() instanceof CourseRequest && c.getR2() instanceof CourseRequest) {
1378                    shareCR += c.getShare(); studentsCR.add(c.getStudent());
1379                } else if (c.getS2() instanceof Unavailability) {
1380                    shareUN += c.getShare(); studentsUN.add(c.getStudent());
1381                } else {
1382                    shareFT += c.getShare(); studentsFT.add(c.getStudent());
1383                }
1384            }
1385            if (shareCR > 0)
1386                info.put("Time overlaps: courses", studentsCR.size() + " students (avg " + sDoubleFormat.format(5.0 * shareCR / studentsCR.size()) + " mins)");
1387            if (shareFT > 0)
1388                info.put("Time overlaps: free times", studentsFT.size() + " students (avg " + sDoubleFormat.format(5.0 * shareFT / studentsFT.size()) + " mins)");
1389            if (shareUN > 0)
1390                info.put("Time overlaps: teaching assignments", studentsUN.size() + " students (avg " + sDoubleFormat.format(5.0 * shareUN / studentsUN.size()) + " mins)");
1391        }
1392
1393        
1394        return info;
1395    }
1396    
1397    @Override
1398    public void restoreBest(Assignment<Request, Enrollment> assignment) {
1399        restoreBest(assignment, new Comparator<Request>() {
1400            @Override
1401            public int compare(Request r1, Request r2) {
1402                Enrollment e1 = r1.getBestAssignment();
1403                Enrollment e2 = r2.getBestAssignment();
1404                // Reservations first
1405                if (e1.getReservation() != null && e2.getReservation() == null) return -1;
1406                if (e1.getReservation() == null && e2.getReservation() != null) return 1;
1407                // Then assignment iteration (i.e., order in which assignments were made)
1408                if (r1.getBestAssignmentIteration() != r2.getBestAssignmentIteration())
1409                    return (r1.getBestAssignmentIteration() < r2.getBestAssignmentIteration() ? -1 : 1);
1410                // Then student and priority
1411                return r1.compareTo(r2);
1412            }
1413        });
1414        recomputeTotalValue(assignment);
1415    }
1416    
1417    public void recomputeTotalValue(Assignment<Request, Enrollment> assignment) {
1418        getContext(assignment).iTotalValue = getTotalValue(assignment, true);
1419    }
1420    
1421    @Override
1422    public void saveBest(Assignment<Request, Enrollment> assignment) {
1423        recomputeTotalValue(assignment);
1424        iBestAssignedCourseRequestWeight = getContext(assignment).getAssignedCourseRequestWeight();
1425        super.saveBest(assignment);
1426    }
1427    
1428    public double getBestAssignedCourseRequestWeight() {
1429        return iBestAssignedCourseRequestWeight;
1430    }
1431        
1432    @Override
1433    public String toString(Assignment<Request, Enrollment> assignment) {
1434        double groupSpread = 0.0; double groupCount = 0;
1435        for (Offering offering: iOfferings) {
1436            for (Course course: offering.getCourses()) {
1437                for (RequestGroup group: course.getRequestGroups()) {
1438                    groupSpread += group.getAverageSpread(assignment) * group.getEnrollmentWeight(assignment, null);
1439                    groupCount += group.getEnrollmentWeight(assignment, null);
1440                }
1441            }
1442        }
1443        String priority = "";
1444        for (StudentPriority sp: StudentPriority.values()) {
1445            if (sp.ordinal() < StudentPriority.Normal.ordinal()) {
1446                if (iTotalPriorityCRWeight[sp.ordinal()] > 0.0)
1447                    priority += sp.code() + "PCR:" + sDecimalFormat.format(100.0 * getContext(assignment).iAssignedPriorityCRWeight[sp.ordinal()] / iTotalPriorityCRWeight[sp.ordinal()]) + "%, ";
1448                if (iTotalPriorityCriticalCRWeight[RequestPriority.LC.ordinal()][sp.ordinal()] > 0.0)
1449                    priority += sp.code() + "PCL:" + sDecimalFormat.format(100.0 * getContext(assignment).iAssignedPriorityCriticalCRWeight[RequestPriority.LC.ordinal()][sp.ordinal()] / iTotalPriorityCriticalCRWeight[RequestPriority.LC.ordinal()][sp.ordinal()]) + "%, ";
1450                if (iTotalPriorityCriticalCRWeight[RequestPriority.Critical.ordinal()][sp.ordinal()] > 0.0)
1451                    priority += sp.code() + "PCC:" + sDecimalFormat.format(100.0 * getContext(assignment).iAssignedPriorityCriticalCRWeight[RequestPriority.Critical.ordinal()][sp.ordinal()] / iTotalPriorityCriticalCRWeight[RequestPriority.Critical.ordinal()][sp.ordinal()]) + "%, ";
1452                if (iTotalPriorityCriticalCRWeight[RequestPriority.Important.ordinal()][sp.ordinal()] > 0.0)
1453                    priority += sp.code() + "PCI:" + sDecimalFormat.format(100.0 * getContext(assignment).iAssignedPriorityCriticalCRWeight[RequestPriority.Important.ordinal()][sp.ordinal()] / iTotalPriorityCriticalCRWeight[RequestPriority.Important.ordinal()][sp.ordinal()]) + "%, ";
1454                if (iTotalPriorityCriticalCRWeight[RequestPriority.Vital.ordinal()][sp.ordinal()] > 0.0)
1455                    priority += sp.code() + "PCV:" + sDecimalFormat.format(100.0 * getContext(assignment).iAssignedPriorityCriticalCRWeight[RequestPriority.Vital.ordinal()][sp.ordinal()] / iTotalPriorityCriticalCRWeight[RequestPriority.Vital.ordinal()][sp.ordinal()]) + "%, ";
1456            }
1457        }
1458        return   (getNrRealStudents(false) > 0 ? "RRq:" + getNrAssignedRealRequests(assignment, false) + "/" + getNrRealRequests(false) + ", " : "")
1459                + (getNrLastLikeStudents(false) > 0 ? "DRq:" + getNrAssignedLastLikeRequests(assignment, false) + "/" + getNrLastLikeRequests(false) + ", " : "")
1460                + (getNrRealStudents(false) > 0 ? "RS:" + getNrCompleteRealStudents(assignment, false) + "/" + getNrRealStudents(false) + ", " : "")
1461                + (getNrLastLikeStudents(false) > 0 ? "DS:" + getNrCompleteLastLikeStudents(assignment, false) + "/" + getNrLastLikeStudents(false) + ", " : "")
1462                + (iTotalCRWeight > 0.0 ? "CR:" + sDecimalFormat.format(100.0 * getContext(assignment).getAssignedCourseRequestWeight() / iTotalCRWeight) + "%, " : "")
1463                + (iTotalSelCRWeight > 0.0 ? "S:" + sDoubleFormat.format(100.0 * (0.3 * getContext(assignment).iAssignedSelectedConfigWeight + 0.7 * getContext(assignment).iAssignedSelectedSectionWeight) / iTotalSelCRWeight) + "%, ": "")
1464                + (iTotalCriticalCRWeight[RequestPriority.LC.ordinal()] > 0.0 ? "LC:" + sDecimalFormat.format(100.0 * getContext(assignment).getAssignedCriticalCourseRequestWeight(RequestPriority.LC) / iTotalCriticalCRWeight[RequestPriority.LC.ordinal()]) + "%, " : "")
1465                + (iTotalCriticalCRWeight[RequestPriority.Critical.ordinal()] > 0.0 ? "CC:" + sDecimalFormat.format(100.0 * getContext(assignment).getAssignedCriticalCourseRequestWeight(RequestPriority.Critical) / iTotalCriticalCRWeight[RequestPriority.Critical.ordinal()]) + "%, " : "")
1466                + (iTotalCriticalCRWeight[RequestPriority.Important.ordinal()] > 0.0 ? "IC:" + sDecimalFormat.format(100.0 * getContext(assignment).getAssignedCriticalCourseRequestWeight(RequestPriority.Important) / iTotalCriticalCRWeight[RequestPriority.Important.ordinal()]) + "%, " : "")
1467                + (iTotalCriticalCRWeight[RequestPriority.Vital.ordinal()] > 0.0 ? "VC:" + sDecimalFormat.format(100.0 * getContext(assignment).getAssignedCriticalCourseRequestWeight(RequestPriority.Vital) / iTotalCriticalCRWeight[RequestPriority.Vital.ordinal()]) + "%, " : "")
1468                + priority
1469                + "V:" + sDecimalFormat.format(-getTotalValue(assignment))
1470                + (getDistanceConflict() == null ? "" : ", DC:" + getDistanceConflict().getTotalNrConflicts(assignment))
1471                + (getTimeOverlaps() == null ? "" : ", TOC:" + getTimeOverlaps().getTotalNrConflicts(assignment))
1472                + (iMPP ? ", IS:" + sDecimalFormat.format(100.0 * getContext(assignment).iAssignedSameSectionWeight / iTotalMPPCRWeight) + "%" : "")
1473                + (iMPP ? ", IT:" + sDecimalFormat.format(100.0 * getContext(assignment).iAssignedSameTimeWeight / iTotalMPPCRWeight) + "%" : "")
1474                + ", %:" + sDecimalFormat.format(-100.0 * getTotalValue(assignment) / (getStudents().size() - iNrDummyStudents + 
1475                        (iProjectedStudentWeight < 0.0 ? iNrDummyStudents * (iTotalDummyWeight / iNrDummyRequests) :iProjectedStudentWeight * iTotalDummyWeight)))
1476                + (groupCount > 0 ? ", SG:" + sDecimalFormat.format(100.0 * groupSpread / groupCount) + "%" : "")
1477                + (getStudentQuality() == null ? "" : ", SQ:{" + getStudentQuality().toString(assignment) + "}");
1478    }
1479    
1480    /**
1481     * Quadratic average of two weights.
1482     * @param w1 first weight
1483     * @param w2 second weight
1484     * @return average of the two weights
1485     */
1486    public double avg(double w1, double w2) {
1487        return Math.sqrt(w1 * w2);
1488    }
1489
1490    /**
1491     * Maximal domain size (i.e., number of enrollments of a course request), -1 if there is no limit.
1492     * @return maximal domain size, -1 if unlimited
1493     */
1494    public int getMaxDomainSize() { return iMaxDomainSize; }
1495
1496    /**
1497     * Maximal domain size (i.e., number of enrollments of a course request), -1 if there is no limit.
1498     * @param maxDomainSize maximal domain size, -1 if unlimited
1499     */
1500    public void setMaxDomainSize(int maxDomainSize) { iMaxDomainSize = maxDomainSize; }
1501    
1502    public int getDayOfWeekOffset() { return iDayOfWeekOffset; }
1503    public void setDayOfWeekOffset(int dayOfWeekOffset) {
1504        iDayOfWeekOffset = dayOfWeekOffset;
1505        if (iProperties != null)
1506            iProperties.setProperty("DatePattern.DayOfWeekOffset", Integer.toString(dayOfWeekOffset));
1507    }
1508
1509    @Override
1510    public StudentSectioningModelContext createAssignmentContext(Assignment<Request, Enrollment> assignment) {
1511        return new StudentSectioningModelContext(assignment);
1512    }
1513    
1514    public class StudentSectioningModelContext implements AssignmentConstraintContext<Request, Enrollment>, InfoProvider<Request, Enrollment>{
1515        private Set<Student> iCompleteStudents = new HashSet<Student>();
1516        private double iTotalValue = 0.0;
1517        private int iNrAssignedDummyRequests = 0, iNrCompleteDummyStudents = 0;
1518        private double iAssignedCRWeight = 0.0, iAssignedDummyCRWeight = 0.0;
1519        private double[] iAssignedCriticalCRWeight;
1520        private double[][] iAssignedPriorityCriticalCRWeight;
1521        private double iReservedSpace = 0.0, iTotalReservedSpace = 0.0;
1522        private double iAssignedSameSectionWeight = 0.0, iAssignedSameChoiceWeight = 0.0, iAssignedSameTimeWeight = 0.0;
1523        private double iAssignedSelectedSectionWeight = 0.0, iAssignedSelectedConfigWeight = 0.0;
1524        private double iAssignedNoTimeSectionWeight = 0.0;
1525        private double iAssignedOnlineSectionWeight = 0.0;
1526        private double iAssignedPastSectionWeight = 0.0;
1527        private int[] iNrCompletePriorityStudents = null;
1528        private double[] iAssignedPriorityCRWeight = null;
1529        
1530        public StudentSectioningModelContext(StudentSectioningModelContext parent) {
1531            iCompleteStudents = new HashSet<Student>(parent.iCompleteStudents);
1532            iTotalValue = parent.iTotalValue;
1533            iNrAssignedDummyRequests = parent.iNrAssignedDummyRequests;
1534            iNrCompleteDummyStudents = parent.iNrCompleteDummyStudents;
1535            iAssignedCRWeight = parent.iAssignedCRWeight;
1536            iAssignedDummyCRWeight = parent.iAssignedDummyCRWeight;
1537            iReservedSpace = parent.iReservedSpace;
1538            iTotalReservedSpace = parent.iTotalReservedSpace;
1539            iAssignedSameSectionWeight = parent.iAssignedSameSectionWeight;
1540            iAssignedSameChoiceWeight = parent.iAssignedSameChoiceWeight;
1541            iAssignedSameTimeWeight = parent.iAssignedSameTimeWeight;
1542            iAssignedSelectedSectionWeight = parent.iAssignedSelectedSectionWeight;
1543            iAssignedSelectedConfigWeight = parent.iAssignedSelectedConfigWeight;
1544            iAssignedNoTimeSectionWeight = parent.iAssignedNoTimeSectionWeight;
1545            iAssignedOnlineSectionWeight = parent.iAssignedOnlineSectionWeight;
1546            iAssignedPastSectionWeight = parent.iAssignedPastSectionWeight;
1547            iAssignedCriticalCRWeight = new double[RequestPriority.values().length];
1548            iAssignedPriorityCriticalCRWeight = new double[RequestPriority.values().length][StudentPriority.values().length];
1549            for (int i = 0; i < RequestPriority.values().length; i++) {
1550                iAssignedCriticalCRWeight[i] = parent.iAssignedCriticalCRWeight[i];
1551                for (int j = 0; j < StudentPriority.values().length; j++) {
1552                    iAssignedPriorityCriticalCRWeight[i][j] = parent.iAssignedPriorityCriticalCRWeight[i][j];
1553                }
1554            }   
1555            iNrCompletePriorityStudents = new int[StudentPriority.values().length];
1556            iAssignedPriorityCRWeight = new double[StudentPriority.values().length];
1557            for (int i = 0; i < StudentPriority.values().length; i++) {
1558                iNrCompletePriorityStudents[i] = parent.iNrCompletePriorityStudents[i];
1559                iAssignedPriorityCRWeight[i] = parent.iAssignedPriorityCRWeight[i];
1560            }
1561        }
1562
1563        public StudentSectioningModelContext(Assignment<Request, Enrollment> assignment) {
1564            iAssignedCriticalCRWeight = new double[RequestPriority.values().length];
1565            iAssignedPriorityCriticalCRWeight = new double[RequestPriority.values().length][StudentPriority.values().length];
1566            for (int i = 0; i < RequestPriority.values().length; i++) {
1567                iAssignedCriticalCRWeight[i] = 0.0;
1568                for (int j = 0; j < StudentPriority.values().length; j++) {
1569                    iAssignedPriorityCriticalCRWeight[i][j] = 0.0;
1570                }
1571            }
1572            iNrCompletePriorityStudents = new int[StudentPriority.values().length];
1573            iAssignedPriorityCRWeight = new double[StudentPriority.values().length];
1574            for (int i = 0; i < StudentPriority.values().length; i++) {
1575                iNrCompletePriorityStudents[i] = 0;
1576                iAssignedPriorityCRWeight[i] = 0.0;
1577            }
1578            for (Request request: variables()) {
1579                Enrollment enrollment = assignment.getValue(request);
1580                if (enrollment != null)
1581                    assigned(assignment, enrollment);
1582            }
1583        }
1584
1585        /**
1586         * Called after an enrollment was assigned to a request. The list of
1587         * complete students and the overall solution value are updated.
1588         */
1589        @Override
1590        public void assigned(Assignment<Request, Enrollment> assignment, Enrollment enrollment) {
1591            Student student = enrollment.getStudent();
1592            if (student.isComplete(assignment) && iCompleteStudents.add(student)) {
1593                if (student.isDummy()) iNrCompleteDummyStudents++;
1594                iNrCompletePriorityStudents[student.getPriority().ordinal()]++;
1595            }
1596            double value = enrollment.getRequest().getWeight() * iStudentWeights.getWeight(assignment, enrollment);
1597            iTotalValue -= value;
1598            enrollment.variable().getContext(assignment).setLastWeight(value);
1599            if (enrollment.isCourseRequest())
1600                iAssignedCRWeight += enrollment.getRequest().getWeight();
1601            if (enrollment.isCourseRequest() && enrollment.getRequest().getRequestPriority() != RequestPriority.Normal && !enrollment.getStudent().isDummy() && !enrollment.getRequest().isAlternative())
1602                iAssignedCriticalCRWeight[enrollment.getRequest().getRequestPriority().ordinal()] += enrollment.getRequest().getWeight();
1603            if (enrollment.isCourseRequest() && enrollment.getRequest().getRequestPriority() != RequestPriority.Normal && !enrollment.getRequest().isAlternative())
1604                iAssignedPriorityCriticalCRWeight[enrollment.getRequest().getRequestPriority().ordinal()][enrollment.getStudent().getPriority().ordinal()] += enrollment.getRequest().getWeight();
1605            if (enrollment.getRequest().isMPP()) {
1606                iAssignedSameSectionWeight += enrollment.getRequest().getWeight() * enrollment.percentInitial();
1607                iAssignedSameChoiceWeight += enrollment.getRequest().getWeight() * enrollment.percentSelected();
1608                iAssignedSameTimeWeight += enrollment.getRequest().getWeight() * enrollment.percentSameTime();
1609            }
1610            if (enrollment.getRequest().hasSelection()) {
1611                iAssignedSelectedSectionWeight += enrollment.getRequest().getWeight() * enrollment.percentSelectedSameSection();
1612                iAssignedSelectedConfigWeight += enrollment.getRequest().getWeight() * enrollment.percentSelectedSameConfig();
1613            }
1614            if (enrollment.getReservation() != null)
1615                iReservedSpace += enrollment.getRequest().getWeight();
1616            if (enrollment.isCourseRequest() && ((CourseRequest)enrollment.getRequest()).hasReservations())
1617                iTotalReservedSpace += enrollment.getRequest().getWeight();
1618            if (student.isDummy()) {
1619                iNrAssignedDummyRequests++;
1620                if (enrollment.isCourseRequest())
1621                    iAssignedDummyCRWeight += enrollment.getRequest().getWeight();
1622            }
1623            if (enrollment.isCourseRequest())
1624                iAssignedPriorityCRWeight[enrollment.getStudent().getPriority().ordinal()] += enrollment.getRequest().getWeight();
1625            if (enrollment.isCourseRequest()) {
1626                int noTime = 0;
1627                int online = 0;
1628                int past = 0;
1629                for (Section section: enrollment.getSections()) {
1630                    if (!section.hasTime()) noTime ++;
1631                    if (section.isOnline()) online ++;
1632                    if (section.isPast()) past ++;
1633                }
1634                if (noTime > 0)
1635                    iAssignedNoTimeSectionWeight += enrollment.getRequest().getWeight() * noTime / enrollment.getSections().size();
1636                if (online > 0)
1637                    iAssignedOnlineSectionWeight += enrollment.getRequest().getWeight() * online / enrollment.getSections().size();
1638                if (past > 0)
1639                    iAssignedPastSectionWeight += enrollment.getRequest().getWeight() * past / enrollment.getSections().size();
1640            }
1641        }
1642
1643        /**
1644         * Called before an enrollment was unassigned from a request. The list of
1645         * complete students and the overall solution value are updated.
1646         */
1647        @Override
1648        public void unassigned(Assignment<Request, Enrollment> assignment, Enrollment enrollment) {
1649            Student student = enrollment.getStudent();
1650            if (enrollment.isCourseRequest() && iCompleteStudents.contains(student)) {
1651                iCompleteStudents.remove(student);
1652                if (student.isDummy())
1653                    iNrCompleteDummyStudents--;
1654                iNrCompletePriorityStudents[student.getPriority().ordinal()]--;
1655            }
1656            Request.RequestContext cx = enrollment.variable().getContext(assignment);
1657            Double value = cx.getLastWeight();
1658            if (value == null)
1659                value = enrollment.getRequest().getWeight() * iStudentWeights.getWeight(assignment, enrollment);
1660            iTotalValue += value;
1661            cx.setLastWeight(null);
1662            if (enrollment.isCourseRequest())
1663                iAssignedCRWeight -= enrollment.getRequest().getWeight();
1664            if (enrollment.isCourseRequest() && enrollment.getRequest().getRequestPriority() != RequestPriority.Normal && !enrollment.getStudent().isDummy() && !enrollment.getRequest().isAlternative())
1665                iAssignedCriticalCRWeight[enrollment.getRequest().getRequestPriority().ordinal()] -= enrollment.getRequest().getWeight();
1666            if (enrollment.isCourseRequest() && enrollment.getRequest().getRequestPriority() != RequestPriority.Normal && !enrollment.getRequest().isAlternative())
1667                iAssignedPriorityCriticalCRWeight[enrollment.getRequest().getRequestPriority().ordinal()][enrollment.getStudent().getPriority().ordinal()] -= enrollment.getRequest().getWeight();
1668            if (enrollment.getRequest().isMPP()) {
1669                iAssignedSameSectionWeight -= enrollment.getRequest().getWeight() * enrollment.percentInitial();
1670                iAssignedSameChoiceWeight -= enrollment.getRequest().getWeight() * enrollment.percentSelected();
1671                iAssignedSameTimeWeight -= enrollment.getRequest().getWeight() * enrollment.percentSameTime();
1672            }
1673            if (enrollment.getRequest().hasSelection()) {
1674                iAssignedSelectedSectionWeight -= enrollment.getRequest().getWeight() * enrollment.percentSelectedSameSection();
1675                iAssignedSelectedConfigWeight -= enrollment.getRequest().getWeight() * enrollment.percentSelectedSameConfig();
1676            }
1677            if (enrollment.getReservation() != null)
1678                iReservedSpace -= enrollment.getRequest().getWeight();
1679            if (enrollment.isCourseRequest() && ((CourseRequest)enrollment.getRequest()).hasReservations())
1680                iTotalReservedSpace -= enrollment.getRequest().getWeight();
1681            if (student.isDummy()) {
1682                iNrAssignedDummyRequests--;
1683                if (enrollment.isCourseRequest())
1684                    iAssignedDummyCRWeight -= enrollment.getRequest().getWeight();
1685            }
1686            if (enrollment.isCourseRequest())
1687                iAssignedPriorityCRWeight[enrollment.getStudent().getPriority().ordinal()] -= enrollment.getRequest().getWeight();
1688            if (enrollment.isCourseRequest()) {
1689                int noTime = 0;
1690                int online = 0;
1691                int past = 0;
1692                for (Section section: enrollment.getSections()) {
1693                    if (!section.hasTime()) noTime ++;
1694                    if (section.isOnline()) online ++;
1695                    if (section.isPast()) past ++;
1696                }
1697                if (noTime > 0)
1698                    iAssignedNoTimeSectionWeight -= enrollment.getRequest().getWeight() * noTime / enrollment.getSections().size();
1699                if (online > 0)
1700                    iAssignedOnlineSectionWeight -= enrollment.getRequest().getWeight() * online / enrollment.getSections().size();
1701                if (past > 0)
1702                    iAssignedPastSectionWeight -= enrollment.getRequest().getWeight() * past / enrollment.getSections().size();
1703            }
1704        }
1705        
1706        public void add(Assignment<Request, Enrollment> assignment, DistanceConflict.Conflict c) {
1707            iTotalValue += avg(c.getR1().getWeight(), c.getR2().getWeight()) * iStudentWeights.getDistanceConflictWeight(assignment, c);
1708        }
1709
1710        public void remove(Assignment<Request, Enrollment> assignment, DistanceConflict.Conflict c) {
1711            iTotalValue -= avg(c.getR1().getWeight(), c.getR2().getWeight()) * iStudentWeights.getDistanceConflictWeight(assignment, c);
1712        }
1713        
1714        public void add(Assignment<Request, Enrollment> assignment, TimeOverlapsCounter.Conflict c) {
1715            if (c.getR1() != null) iTotalValue += c.getR1Weight() * iStudentWeights.getTimeOverlapConflictWeight(assignment, c.getE1(), c);
1716            if (c.getR2() != null) iTotalValue += c.getR2Weight() * iStudentWeights.getTimeOverlapConflictWeight(assignment, c.getE2(), c);
1717        }
1718
1719        public void remove(Assignment<Request, Enrollment> assignment, TimeOverlapsCounter.Conflict c) {
1720            if (c.getR1() != null) iTotalValue -= c.getR1Weight() * iStudentWeights.getTimeOverlapConflictWeight(assignment, c.getE1(), c);
1721            if (c.getR2() != null) iTotalValue -= c.getR2Weight() * iStudentWeights.getTimeOverlapConflictWeight(assignment, c.getE2(), c);
1722        }
1723        
1724        public void add(Assignment<Request, Enrollment> assignment, StudentQuality.Conflict c) {
1725            switch (c.getType().getType()) {
1726                case REQUEST:
1727                    if (c.getR1() instanceof CourseRequest)
1728                        iTotalValue += c.getR1Weight() * iStudentWeights.getStudentQualityConflictWeight(assignment, c.getE1(), c);
1729                    else
1730                        iTotalValue += c.getR2Weight() * iStudentWeights.getStudentQualityConflictWeight(assignment, c.getE2(), c);
1731                    break;
1732                case BOTH:
1733                    iTotalValue += c.getR1Weight() * iStudentWeights.getStudentQualityConflictWeight(assignment, c.getE1(), c);  
1734                    iTotalValue += c.getR2Weight() * iStudentWeights.getStudentQualityConflictWeight(assignment, c.getE2(), c);
1735                    break;
1736                case LOWER:
1737                    iTotalValue += avg(c.getR1().getWeight(), c.getR2().getWeight()) * iStudentWeights.getStudentQualityConflictWeight(assignment, c.getE1(), c);
1738                    break;
1739                case HIGHER:
1740                    iTotalValue += avg(c.getR1().getWeight(), c.getR2().getWeight()) * iStudentWeights.getStudentQualityConflictWeight(assignment, c.getE1(), c);
1741                    break;
1742            }
1743        }
1744
1745        public void remove(Assignment<Request, Enrollment> assignment, StudentQuality.Conflict c) {
1746            switch (c.getType().getType()) {
1747                case REQUEST:
1748                    if (c.getR1() instanceof CourseRequest)
1749                        iTotalValue -= c.getR1Weight() * iStudentWeights.getStudentQualityConflictWeight(assignment, c.getE1(), c);
1750                    else
1751                        iTotalValue -= c.getR2Weight() * iStudentWeights.getStudentQualityConflictWeight(assignment, c.getE2(), c);
1752                    break;
1753                case BOTH:
1754                    iTotalValue -= c.getR1Weight() * iStudentWeights.getStudentQualityConflictWeight(assignment, c.getE1(), c);  
1755                    iTotalValue -= c.getR2Weight() * iStudentWeights.getStudentQualityConflictWeight(assignment, c.getE2(), c);
1756                    break;
1757                case LOWER:
1758                    iTotalValue -= avg(c.getR1().getWeight(), c.getR2().getWeight()) * iStudentWeights.getStudentQualityConflictWeight(assignment, c.getE1(), c);
1759                    break;
1760                case HIGHER:
1761                    iTotalValue -= avg(c.getR1().getWeight(), c.getR2().getWeight()) * iStudentWeights.getStudentQualityConflictWeight(assignment, c.getE1(), c);
1762                    break;
1763            }
1764        }
1765        
1766        /**
1767         * Students with complete schedules (see {@link Student#isComplete(Assignment)})
1768         * @return students with complete schedule
1769         */
1770        public Set<Student> getCompleteStudents() {
1771            return iCompleteStudents;
1772        }
1773        
1774        /**
1775         * Number of students with complete schedule
1776         * @return number of students with complete schedule
1777         */
1778        public int nrComplete() {
1779            return getCompleteStudents().size();
1780        }
1781        
1782        /** 
1783         * Recompute cached request weights
1784         * @param assignment curent assignment
1785         */
1786        public void requestWeightsChanged(Assignment<Request, Enrollment> assignment) {
1787            iTotalCRWeight = 0.0;
1788            iTotalDummyWeight = 0.0; iTotalDummyCRWeight = 0.0;
1789            iTotalPriorityCRWeight = new double[StudentPriority.values().length];
1790            iAssignedCRWeight = 0.0;
1791            iAssignedDummyCRWeight = 0.0;
1792            iAssignedCriticalCRWeight = new double[RequestPriority.values().length];
1793            iAssignedPriorityCriticalCRWeight = new double[RequestPriority.values().length][StudentPriority.values().length];
1794            for (int i = 0; i < RequestPriority.values().length; i++) {
1795                iAssignedCriticalCRWeight[i] = 0.0;
1796                for (int j = 0; j < StudentPriority.values().length; j++) {
1797                    iAssignedPriorityCriticalCRWeight[i][j] = 0.0;
1798                }
1799            }
1800            iAssignedPriorityCRWeight = new double[StudentPriority.values().length];
1801            for (int i = 0; i < StudentPriority.values().length; i++) {
1802                iAssignedPriorityCRWeight[i] = 0.0;
1803            }
1804            iNrDummyRequests = 0; iNrAssignedDummyRequests = 0;
1805            iTotalReservedSpace = 0.0; iReservedSpace = 0.0;
1806            iTotalMPPCRWeight = 0.0;
1807            iTotalSelCRWeight = 0.0;
1808            iAssignedNoTimeSectionWeight = 0.0;
1809            iAssignedOnlineSectionWeight = 0.0;
1810            iAssignedPastSectionWeight = 0.0;
1811            for (Request request: variables()) {
1812                boolean cr = (request instanceof CourseRequest);
1813                if (cr && !request.isAlternative())
1814                    iTotalCRWeight += request.getWeight();
1815                if (request.getStudent().isDummy()) {
1816                    iTotalDummyWeight += request.getWeight();
1817                    iNrDummyRequests ++;
1818                    if (cr && !request.isAlternative())
1819                        iTotalDummyCRWeight += request.getWeight();
1820                }
1821                if (cr && !request.isAlternative()) {
1822                    iTotalPriorityCRWeight[request.getStudent().getPriority().ordinal()] += request.getWeight();
1823                }
1824                if (request.isMPP())
1825                    iTotalMPPCRWeight += request.getWeight();
1826                if (request.hasSelection())
1827                    iTotalSelCRWeight += request.getWeight();
1828                Enrollment e = assignment.getValue(request);
1829                if (e != null) {
1830                    if (cr)
1831                        iAssignedCRWeight += request.getWeight();
1832                    if (cr && request.getRequestPriority() != RequestPriority.Normal && !request.getStudent().isDummy() && !request.isAlternative())
1833                        iAssignedCriticalCRWeight[request.getRequestPriority().ordinal()] += request.getWeight();
1834                    if (cr && request.getRequestPriority() != RequestPriority.Normal && !request.isAlternative())
1835                        iAssignedPriorityCriticalCRWeight[request.getRequestPriority().ordinal()][request.getStudent().getPriority().ordinal()] += request.getWeight();
1836                    if (request.isMPP()) {
1837                        iAssignedSameSectionWeight += request.getWeight() * e.percentInitial();
1838                        iAssignedSameChoiceWeight += request.getWeight() * e.percentSelected();
1839                        iAssignedSameTimeWeight += request.getWeight() * e.percentSameTime();
1840                    }
1841                    if (request.hasSelection()) {
1842                        iAssignedSelectedSectionWeight += request.getWeight() * e.percentSelectedSameSection();
1843                        iAssignedSelectedConfigWeight += request.getWeight() * e.percentSelectedSameConfig();
1844                    }
1845                    if (e.getReservation() != null)
1846                        iReservedSpace += request.getWeight();
1847                    if (cr && ((CourseRequest)request).hasReservations())
1848                        iTotalReservedSpace += request.getWeight();
1849                    if (request.getStudent().isDummy()) {
1850                        iNrAssignedDummyRequests ++;
1851                        if (cr)
1852                            iAssignedDummyCRWeight += request.getWeight();
1853                    }
1854                    if (cr) {
1855                        iAssignedPriorityCRWeight[request.getStudent().getPriority().ordinal()] += request.getWeight();
1856                    }
1857                    if (cr) {
1858                        int noTime = 0;
1859                        int online = 0;
1860                        int past = 0;
1861                        for (Section section: e.getSections()) {
1862                            if (!section.hasTime()) noTime ++;
1863                            if (section.isOnline()) online ++;
1864                            if (section.isPast()) past ++;
1865                        }
1866                        if (noTime > 0)
1867                            iAssignedNoTimeSectionWeight += request.getWeight() * noTime / e.getSections().size();
1868                        if (online > 0)
1869                            iAssignedOnlineSectionWeight += request.getWeight() * online / e.getSections().size();
1870                        if (past > 0)
1871                            iAssignedPastSectionWeight += request.getWeight() * past / e.getSections().size();
1872                    }
1873                }
1874            }
1875        }
1876        
1877        /**
1878         * Overall solution value
1879         * @return solution value
1880         */
1881        public double getTotalValue() {
1882            return iTotalValue;
1883        }
1884        
1885        /**
1886         * Number of last like ({@link Student#isDummy()} equals true) students with
1887         * a complete schedule ({@link Student#isComplete(Assignment)} equals true).
1888         * @return number of last like (projected) students with a complete schedule
1889         */
1890        public int getNrCompleteLastLikeStudents() {
1891            return iNrCompleteDummyStudents;
1892        }
1893        
1894        /**
1895         * Number of requests from projected ({@link Student#isDummy()} equals true)
1896         * students that are assigned.
1897         * @return number of real students with a complete schedule
1898         */
1899        public int getNrAssignedLastLikeRequests() {
1900            return iNrAssignedDummyRequests;
1901        }
1902
1903        @Override
1904        public void getInfo(Assignment<Request, Enrollment> assignment, Map<String, String> info) {
1905            if (iTotalCRWeight > 0.0) {
1906                info.put("Assigned course requests", sDecimalFormat.format(100.0 * iAssignedCRWeight / iTotalCRWeight) + "% (" + (int)Math.round(iAssignedCRWeight) + "/" + (int)Math.round(iTotalCRWeight) + ")");
1907                if (iNrDummyStudents > 0 && iNrDummyStudents != getStudents().size() && iTotalCRWeight != iTotalDummyCRWeight) {
1908                    if (iTotalDummyCRWeight > 0.0)
1909                        info.put("Projected assigned course requests", sDecimalFormat.format(100.0 * iAssignedDummyCRWeight / iTotalDummyCRWeight) + "% (" + (int)Math.round(iAssignedDummyCRWeight) + "/" + (int)Math.round(iTotalDummyCRWeight) + ")");
1910                    info.put("Real assigned course requests", sDecimalFormat.format(100.0 * (iAssignedCRWeight - iAssignedDummyCRWeight) / (iTotalCRWeight - iTotalDummyCRWeight)) +
1911                            "% (" + (int)Math.round(iAssignedCRWeight - iAssignedDummyCRWeight) + "/" + (int)Math.round(iTotalCRWeight - iTotalDummyCRWeight) + ")");
1912                }
1913                if (iAssignedNoTimeSectionWeight > 0.0) {
1914                    info.put("Using classes w/o time", sDecimalFormat.format(100.0 * iAssignedNoTimeSectionWeight / iAssignedCRWeight) + "% (" + sDecimalFormat.format(iAssignedNoTimeSectionWeight) + ")"); 
1915                }
1916                if (iAssignedOnlineSectionWeight > 0.0) {
1917                    info.put("Using online classes", sDecimalFormat.format(100.0 * iAssignedOnlineSectionWeight / iAssignedCRWeight) + "% (" + sDecimalFormat.format(iAssignedOnlineSectionWeight) + ")"); 
1918                }
1919                if (iAssignedPastSectionWeight > 0.0) {
1920                    info.put("Using past classes", sDecimalFormat.format(100.0 * iAssignedPastSectionWeight / iAssignedCRWeight) + "% (" + sDecimalFormat.format(iAssignedPastSectionWeight) + ")");
1921                }
1922            }
1923            String priorityAssignedCR = "";
1924            for (StudentPriority sp: StudentPriority.values()) {
1925                if (sp != StudentPriority.Dummy && iTotalPriorityCRWeight[sp.ordinal()] > 0.0) {
1926                    priorityAssignedCR += (priorityAssignedCR.isEmpty() ? "" : "\n") +
1927                            sp.name() + ": " + sDecimalFormat.format(100.0 * iAssignedPriorityCRWeight[sp.ordinal()] / iTotalPriorityCRWeight[sp.ordinal()]) + "% (" + (int)Math.round(iAssignedPriorityCRWeight[sp.ordinal()]) + "/" + (int)Math.round(iTotalPriorityCRWeight[sp.ordinal()]) + ")";
1928                }
1929            }
1930            if (!priorityAssignedCR.isEmpty())
1931                info.put("Assigned course requests (priority students)", priorityAssignedCR);
1932            for (RequestPriority rp: RequestPriority.values()) {
1933                if (rp == RequestPriority.Normal) continue;
1934                if (iTotalCriticalCRWeight[rp.ordinal()] > 0.0) {
1935                    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()]) + ")");
1936                }
1937                priorityAssignedCR = "";
1938                for (StudentPriority sp: StudentPriority.values()) {
1939                    if (sp != StudentPriority.Dummy && iTotalPriorityCriticalCRWeight[rp.ordinal()][sp.ordinal()] > 0.0) {
1940                        priorityAssignedCR += (priorityAssignedCR.isEmpty() ? "" : "\n") +
1941                                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()]) + ")";
1942                    }
1943                }
1944                if (!priorityAssignedCR.isEmpty())
1945                    info.put("Assigned " + rp.name().toLowerCase() + " course requests (priority students)", priorityAssignedCR);
1946            }
1947            if (iTotalReservedSpace > 0.0)
1948                info.put("Reservations", sDoubleFormat.format(100.0 * iReservedSpace / iTotalReservedSpace) + "% (" + Math.round(iReservedSpace) + "/" + Math.round(iTotalReservedSpace) + ")");
1949            if (iMPP && iTotalMPPCRWeight > 0.0) {
1950                info.put("Perturbations: same section", sDoubleFormat.format(100.0 * iAssignedSameSectionWeight / iTotalMPPCRWeight) + "% (" + Math.round(iAssignedSameSectionWeight) + "/" + Math.round(iTotalMPPCRWeight) + ")");
1951                if (iAssignedSameChoiceWeight > iAssignedSameSectionWeight)
1952                    info.put("Perturbations: same choice",sDoubleFormat.format(100.0 * iAssignedSameChoiceWeight / iTotalMPPCRWeight) + "% (" + Math.round(iAssignedSameChoiceWeight) + "/" + Math.round(iTotalMPPCRWeight) + ")");
1953                if (iAssignedSameTimeWeight > iAssignedSameChoiceWeight)
1954                    info.put("Perturbations: same time", sDoubleFormat.format(100.0 * iAssignedSameTimeWeight / iTotalMPPCRWeight) + "% (" + Math.round(iAssignedSameTimeWeight) + "/" + Math.round(iTotalMPPCRWeight) + ")");
1955            }
1956            if (iTotalSelCRWeight > 0.0) {
1957                info.put("Selection",sDoubleFormat.format(100.0 * (0.3 * iAssignedSelectedConfigWeight + 0.7 * iAssignedSelectedSectionWeight) / iTotalSelCRWeight) +
1958                        "% (" + Math.round(0.3 * iAssignedSelectedConfigWeight + 0.7 * iAssignedSelectedSectionWeight) + "/" + Math.round(iTotalSelCRWeight) + ")");
1959            }
1960        }
1961
1962        @Override
1963        public void getInfo(Assignment<Request, Enrollment> assignment, Map<String, String> info, Collection<Request> variables) {
1964        }
1965        
1966        public double getAssignedCourseRequestWeight() {
1967            return iAssignedCRWeight;
1968        }
1969        
1970        public double getAssignedCriticalCourseRequestWeight(RequestPriority rp) {
1971            return iAssignedCriticalCRWeight[rp.ordinal()];
1972        }
1973    }
1974    
1975    @Override
1976    public InheritedAssignment<Request, Enrollment> createInheritedAssignment(Solution<Request, Enrollment> solution, int index) {
1977        return new OptimisticInheritedAssignment<Request, Enrollment>(solution, index);
1978    }
1979    
1980    public DistanceMetric getDistanceMetric() {
1981        return (iStudentQuality != null ? iStudentQuality.getDistanceMetric() : iDistanceConflict != null ? iDistanceConflict.getDistanceMetric() : null);
1982    }
1983
1984    @Override
1985    public StudentSectioningModelContext inheritAssignmentContext(Assignment<Request, Enrollment> assignment, StudentSectioningModelContext parentContext) {
1986        return new StudentSectioningModelContext(parentContext);
1987    }
1988
1989}