001package org.cpsolver.studentsct.online;
002
003import java.io.File;
004import java.io.FileWriter;
005import java.io.IOException;
006import java.io.PrintWriter;
007import java.text.DecimalFormat;
008import java.util.ArrayList;
009import java.util.Collections;
010import java.util.HashMap;
011import java.util.HashSet;
012import java.util.Hashtable;
013import java.util.Iterator;
014import java.util.List;
015import java.util.Map;
016import java.util.NoSuchElementException;
017import java.util.Set;
018import java.util.TreeSet;
019
020import org.apache.logging.log4j.Logger;
021import org.cpsolver.ifs.assignment.Assignment;
022import org.cpsolver.ifs.assignment.AssignmentMap;
023import org.cpsolver.ifs.assignment.DefaultSingleAssignment;
024import org.cpsolver.ifs.solver.Solver;
025import org.cpsolver.ifs.util.DataProperties;
026import org.cpsolver.ifs.util.DistanceMetric;
027import org.cpsolver.ifs.util.JProf;
028import org.cpsolver.ifs.util.ToolBox;
029import org.cpsolver.studentsct.StudentPreferencePenalties;
030import org.cpsolver.studentsct.StudentSectioningModel;
031import org.cpsolver.studentsct.StudentSectioningXMLLoader;
032import org.cpsolver.studentsct.StudentSectioningXMLSaver;
033import org.cpsolver.studentsct.constraint.LinkedSections;
034import org.cpsolver.studentsct.extension.DistanceConflict;
035import org.cpsolver.studentsct.extension.StudentQuality;
036import org.cpsolver.studentsct.extension.TimeOverlapsCounter;
037import org.cpsolver.studentsct.heuristics.selection.BranchBoundSelection.BranchBoundNeighbour;
038import org.cpsolver.studentsct.heuristics.studentord.StudentChoiceOrder;
039import org.cpsolver.studentsct.model.Config;
040import org.cpsolver.studentsct.model.Course;
041import org.cpsolver.studentsct.model.CourseRequest;
042import org.cpsolver.studentsct.model.Enrollment;
043import org.cpsolver.studentsct.model.FreeTimeRequest;
044import org.cpsolver.studentsct.model.Offering;
045import org.cpsolver.studentsct.model.Request;
046import org.cpsolver.studentsct.model.Section;
047import org.cpsolver.studentsct.model.Student;
048import org.cpsolver.studentsct.model.Subpart;
049import org.cpsolver.studentsct.online.expectations.AvoidUnbalancedWhenNoExpectations;
050import org.cpsolver.studentsct.online.expectations.FractionallyOverExpected;
051import org.cpsolver.studentsct.online.expectations.FractionallyUnbalancedWhenNoExpectations;
052import org.cpsolver.studentsct.online.expectations.PercentageOverExpected;
053import org.cpsolver.studentsct.online.selection.MultiCriteriaBranchAndBoundSelection;
054import org.cpsolver.studentsct.online.selection.MultiCriteriaBranchAndBoundSuggestions;
055import org.cpsolver.studentsct.online.selection.OnlineSectioningSelection;
056import org.cpsolver.studentsct.online.selection.StudentSchedulingAssistantWeights;
057import org.cpsolver.studentsct.online.selection.SuggestionSelection;
058import org.cpsolver.studentsct.online.selection.SuggestionsBranchAndBound;
059import org.cpsolver.studentsct.reservation.CourseReservation;
060import org.cpsolver.studentsct.reservation.Reservation;
061
062/**
063 * An online student sectioning test. It loads the given problem (passed as the only argument) with no assignments. It sections all
064 * students in the given order (given by -Dsort parameter, values shuffle, choice, reverse). Multiple threads can be used to section
065 * students in parallel (given by -DnrConcurrent parameter). If parameter -Dsuggestions is set to true, the test also asks for suggestions
066 * for each of the assigned class, preferring mid-day times. Over-expected criterion can be defined by the -Doverexp parameter (see the
067 * examples bellow). Multi-criteria selection can be enabled by -DStudentWeights.MultiCriteria=true and equal weighting can be set by
068 * -DStudentWeights.PriorityWeighting=equal).
069 * 
070 * <br><br>
071 * Usage:<ul>
072 *      java -Xmx1g -cp studentsct-1.3.jar [parameters] org.cpsolver.studentsct.online.Test data/pu-sect-fal07.xml<br>
073 * </ul>
074 * Parameters:<ul>
075 *      <li>-Dsort=shuffle|choice|reverse ... for taking students in random order, more choices first, or more choices last (defaults to shuffle)
076 *      <li>-DnrConcurrent=N ... for the number of threads (concurrent computations of student schedules, defaults to 10)
077 *      <li>-Dsuggestions=true|false ... true to use suggestions (to simulate students preferring mid-day, defaults to false)
078 *      <li>-Doverexp=<i>x<sub>over</sub></i>|b<i>x<sub>over</sub></i>-<i>x<sub>disb</sub></i>%|<i>x<sub>over</sub></i>-<i>x<sub>max</sub></i>|b<i>x<sub>over</sub></i>-<i>x<sub>max</sub></i>-<i>x<sub>disb</sub></i>% for over-expected criterion, examples:<ul>
079 *              <li>1.1 ... {@link PercentageOverExpected} with OverExpected.Percentage set to 1.1 (<i>x<sub>over</sub></i>)
080 *              <li>b1-10 ... {@link AvoidUnbalancedWhenNoExpectations} with OverExpected.Percentage set to 1 and General.BalanceUnlimited set to 10/100 (<i>x<sub>disb</sub></i>%)
081 *              <li>0.85-5 ... {@link FractionallyOverExpected} with OverExpected.Percentage set to 0.85 and OverExpected.Maximum set to 5 (<i>x<sub>max</sub></i>)
082 *              <li>1.1-5-1 ... {@link FractionallyUnbalancedWhenNoExpectations} with OverExpected.Percentage set to 1.1, General.BalanceUnlimited set to 5/100, and OverExpected.Maximum set to 1
083 *      </ul>
084 *      <li>-DStudentWeights.PriorityWeighting=priority|equal ... priority or equal weighting (defaults to priority)
085 *      <li>-DStudentWeights.MultiCriteria=true|false ... true for multi-criteria (lexicographic ordering), false for a weighted sum (default to true)
086 *      <li>-DNeighbour.BranchAndBoundTimeout=M ... time limit for each student in milliseconds (CPU time, defaults to 1000)
087 * </ul>
088 * 
089 * @version StudentSct 1.3 (Student Sectioning)<br>
090 *          Copyright (C) 2014 Tomáš Müller<br>
091 *          <a href="mailto:muller@unitime.org">muller@unitime.org</a><br>
092 *          <a href="http://muller.unitime.org">http://muller.unitime.org</a><br>
093 * <br>
094 *          This library is free software; you can redistribute it and/or modify
095 *          it under the terms of the GNU Lesser General Public License as
096 *          published by the Free Software Foundation; either version 3 of the
097 *          License, or (at your option) any later version. <br>
098 * <br>
099 *          This library is distributed in the hope that it will be useful, but
100 *          WITHOUT ANY WARRANTY; without even the implied warranty of
101 *          MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
102 *          Lesser General Public License for more details. <br>
103 * <br>
104 *          You should have received a copy of the GNU Lesser General Public
105 *          License along with this library; if not see <a href='http://www.gnu.org/licenses'>http://www.gnu.org/licenses</a>.
106 * 
107 */
108public class Test {
109    public static DecimalFormat sDF = new DecimalFormat("0.00000");
110    public static Logger sLog = org.apache.logging.log4j.LogManager.getLogger(Test.class);
111
112    private OnlineSectioningModel iModel;
113    private Assignment<Request, Enrollment> iAssignment;
114    private boolean iSuggestions = false;
115
116    private Map<String, Counter> iCounters = new HashMap<String, Counter>();
117
118    public Test(DataProperties config) {
119        iModel = new TestModel(config);
120        iModel.setDistanceConflict(new DistanceConflict(new DistanceMetric(iModel.getProperties()), iModel.getProperties()));
121        iModel.getDistanceConflict().register(iModel);
122        iModel.getDistanceConflict().setAssignmentContextReference(iModel.createReference(iModel.getDistanceConflict()));
123        iModel.setTimeOverlaps(new TimeOverlapsCounter(null, iModel.getProperties()));
124        iModel.getTimeOverlaps().register(iModel);
125        iModel.getTimeOverlaps().setAssignmentContextReference(iModel.createReference(iModel.getTimeOverlaps()));
126        iModel.setStudentQuality(new StudentQuality(new DistanceMetric(iModel.getProperties()), iModel.getProperties()));
127        iModel.getStudentQuality().register(iModel);
128        iModel.getStudentQuality().setAssignmentContextReference(iModel.createReference(iModel.getStudentQuality()));
129        iModel.setStudentWeights(new StudentSchedulingAssistantWeights(iModel.getProperties()));
130        iAssignment = new DefaultSingleAssignment<Request, Enrollment>();
131        iSuggestions = "true".equals(System.getProperty("suggestions", iSuggestions ? "true" : "false"));
132
133        String overexp = System.getProperty("overexp");
134        if (overexp != null) {
135            boolean bal = false;
136            if (overexp.startsWith("b")) {
137                bal = true;
138                overexp = overexp.substring(1);
139            }
140            String[] x = overexp.split("[/\\-]");
141            if (x.length == 1) {
142                iModel.setOverExpectedCriterion(new PercentageOverExpected(Double.valueOf(x[0])));
143            } else if (x.length == 2) {
144                iModel.setOverExpectedCriterion(bal ? new AvoidUnbalancedWhenNoExpectations(Double.valueOf(x[0]), Double.valueOf(x[1]) / 100.0) :
145                    new FractionallyOverExpected(Double.valueOf(x[0]), Double.valueOf(x[1])));
146            } else {
147                iModel.setOverExpectedCriterion(new FractionallyUnbalancedWhenNoExpectations(Double.valueOf(x[0]),
148                        Double.valueOf(x[1]), Double.valueOf(x[2]) / 100.0));
149            }
150        }
151
152        sLog.info("Using " + (config.getPropertyBoolean("StudentWeights.MultiCriteria", true) ? "multi-criteria " : "")
153                + (config.getPropertyBoolean("StudentWeights.PriorityWeighting", true) ? "priority" : "equal")
154                + " weighting model" + " with over-expected " + iModel.getOverExpectedCriterion()
155                + (iSuggestions ? ", suggestions" : "") + ", " + System.getProperty("sort", "shuffle") + " order"
156                + " and " + config.getPropertyInt("Neighbour.BranchAndBoundTimeout", 1000) + " ms time limit.");
157    }
158
159    public OnlineSectioningModel model() {
160        return iModel;
161    }
162
163    public Assignment<Request, Enrollment> assignment() {
164        return iAssignment;
165    }
166
167    public void inc(String name, double value) {
168        synchronized (iCounters) {
169            Counter c = iCounters.get(name);
170            if (c == null) {
171                c = new Counter();
172                iCounters.put(name, c);
173            }
174            c.inc(value);
175        }
176    }
177
178    public void inc(String name) {
179        inc(name, 1.0);
180    }
181
182    public Counter get(String name) {
183        synchronized (iCounters) {
184            Counter c = iCounters.get(name);
185            if (c == null) {
186                c = new Counter();
187                iCounters.put(name, c);
188            }
189            return c;
190        }
191    }
192
193    public double getPercDisbalancedSections(Assignment<Request, Enrollment> assignment, double perc) {
194        boolean balanceUnlimited = model().getProperties().getPropertyBoolean("General.BalanceUnlimited", false);
195        double disb10Sections = 0, nrSections = 0;
196        for (Offering offering : model().getOfferings()) {
197            for (Config config : offering.getConfigs()) {
198                double enrl = config.getEnrollmentTotalWeight(assignment, null);
199                for (Subpart subpart : config.getSubparts()) {
200                    if (subpart.getSections().size() <= 1)
201                        continue;
202                    nrSections += subpart.getSections().size();
203                    if (subpart.getLimit() > 0) {
204                        // sections have limits -> desired size is section limit
205                        // x (total enrollment / total limit)
206                        double ratio = enrl / subpart.getLimit();
207                        for (Section section : subpart.getSections()) {
208                            double desired = ratio * section.getLimit();
209                            if (Math.abs(desired - section.getEnrollmentTotalWeight(assignment, null)) >= Math.max(1.0, perc * section.getLimit()))
210                                disb10Sections++;
211                        }
212                    } else if (balanceUnlimited) {
213                        // unlimited sections -> desired size is total
214                        // enrollment / number of sections
215                        for (Section section : subpart.getSections()) {
216                            double desired = enrl / subpart.getSections().size();
217                            if (Math.abs(desired - section.getEnrollmentTotalWeight(assignment, null)) >= Math.max(1.0, perc * desired))
218                                disb10Sections++;
219                        }
220                    }
221                }
222            }
223        }
224        return 100.0 * disb10Sections / nrSections;
225    }
226
227    protected Course clone(Course course, long studentId, Student originalStudent, Map<Long, Section> classTable, StudentSectioningModel model) {
228        Offering clonedOffering = new Offering(course.getOffering().getId(), course.getOffering().getName());
229        clonedOffering.setModel(model);
230        int courseLimit = course.getLimit();
231        if (courseLimit >= 0) {
232            courseLimit -= course.getEnrollments(assignment()).size();
233            if (courseLimit < 0)
234                courseLimit = 0;
235            for (Iterator<Enrollment> i = course.getEnrollments(assignment()).iterator(); i.hasNext();) {
236                Enrollment enrollment = i.next();
237                if (enrollment.getStudent().getId() == studentId) {
238                    courseLimit++;
239                    break;
240                }
241            }
242        }
243        Course clonedCourse = new Course(course.getId(), course.getSubjectArea(), course.getCourseNumber(),
244                clonedOffering, courseLimit, course.getProjected());
245        clonedCourse.setNote(course.getNote());
246        Hashtable<Config, Config> configs = new Hashtable<Config, Config>();
247        Hashtable<Subpart, Subpart> subparts = new Hashtable<Subpart, Subpart>();
248        Hashtable<Section, Section> sections = new Hashtable<Section, Section>();
249        for (Iterator<Config> e = course.getOffering().getConfigs().iterator(); e.hasNext();) {
250            Config config = e.next();
251            int configLimit = config.getLimit();
252            int configEnrollment = config.getEnrollments(assignment()).size();
253            if (configLimit >= 0) {
254                configLimit -= config.getEnrollments(assignment()).size();
255                if (configLimit < 0)
256                    configLimit = 0;
257                for (Iterator<Enrollment> i = config.getEnrollments(assignment()).iterator(); i.hasNext();) {
258                    Enrollment enrollment = i.next();
259                    if (enrollment.getStudent().getId() == studentId) {
260                        configLimit++;
261                        configEnrollment--;
262                        break;
263                    }
264                }
265            }
266            OnlineConfig clonedConfig = new OnlineConfig(config.getId(), configLimit, config.getName(), clonedOffering);
267            clonedConfig.setInstructionalMethodId(config.getInstructionalMethodId());
268            clonedConfig.setInstructionalMethodName(config.getInstructionalMethodName());
269            clonedConfig.setInstructionalMethodReference(config.getInstructionalMethodReference());
270            clonedConfig.setEnrollment(configEnrollment);
271            configs.put(config, clonedConfig);
272            for (Iterator<Subpart> f = config.getSubparts().iterator(); f.hasNext();) {
273                Subpart subpart = f.next();
274                Subpart clonedSubpart = new Subpart(subpart.getId(), subpart.getInstructionalType(), subpart.getName(),
275                        clonedConfig, (subpart.getParent() == null ? null : subparts.get(subpart.getParent())));
276                clonedSubpart.setAllowOverlap(subpart.isAllowOverlap());
277                clonedSubpart.setCredit(subpart.getCredit());
278                subparts.put(subpart, clonedSubpart);
279                for (Iterator<Section> g = subpart.getSections().iterator(); g.hasNext();) {
280                    Section section = g.next();
281                    int limit = section.getLimit();
282                    int enrl = section.getEnrollments(assignment()).size();
283                    if (limit >= 0) {
284                        // limited section, deduct enrollments
285                        limit -= section.getEnrollments(assignment()).size();
286                        if (limit < 0)
287                            limit = 0; // over-enrolled, but not unlimited
288                        if (studentId >= 0)
289                            for (Enrollment enrollment : section.getEnrollments(assignment()))
290                                if (enrollment.getStudent().getId() == studentId) {
291                                    limit++;
292                                    enrl--;
293                                    break;
294                                }
295                    }
296                    OnlineSection clonedSection = new OnlineSection(section.getId(), limit,
297                            section.getName(course .getId()), clonedSubpart, section.getPlacement(), section.getInstructors(), (section.getParent() == null ? null : sections.get(section.getParent())));
298                    clonedSection.setName(-1l, section.getName(-1l));
299                    clonedSection.setNote(section.getNote());
300                    clonedSection.setSpaceExpected(section.getSpaceExpected());
301                    clonedSection.setSpaceHeld(section.getSpaceHeld());
302                    clonedSection.setEnrollment(enrl);
303                    clonedSection.setCancelled(section.isCancelled());
304                    clonedSection.setEnabled(section.isEnabled());
305                    clonedSection.setPast(section.isPast());
306                    clonedSection.setOnline(section.isOnline());
307                    if (section.getIgnoreConflictWithSectionIds() != null)
308                        for (Long id : section.getIgnoreConflictWithSectionIds())
309                            clonedSection.addIgnoreConflictWith(id);
310                    if (limit > 0) {
311                        double available = Math.round(section.getSpaceExpected() - limit);
312                        clonedSection.setPenalty(available / section.getLimit());
313                    }
314                    sections.put(section, clonedSection);
315                    classTable.put(section.getId(), clonedSection);
316                }
317            }
318        }
319        if (course.getOffering().hasReservations()) {
320            for (Reservation reservation : course.getOffering().getReservations()) {
321                int reservationLimit = (int) Math.round(reservation.getLimit());
322                if (reservationLimit >= 0) {
323                    reservationLimit -= reservation.getEnrollments(assignment()).size();
324                    if (reservationLimit < 0)
325                        reservationLimit = 0;
326                    for (Iterator<Enrollment> i = reservation.getEnrollments(assignment()).iterator(); i.hasNext();) {
327                        Enrollment enrollment = i.next();
328                        if (enrollment.getStudent().getId() == studentId) {
329                            reservationLimit++;
330                            break;
331                        }
332                    }
333                    if (reservationLimit <= 0 && !reservation.mustBeUsed())
334                        continue;
335                }
336                boolean applicable = originalStudent != null && reservation.isApplicable(originalStudent);
337                if (reservation instanceof CourseReservation)
338                    applicable = (course.getId() == ((CourseReservation) reservation).getCourse().getId());
339                if (reservation instanceof org.cpsolver.studentsct.reservation.DummyReservation) {
340                    // Ignore by reservation only flag (dummy reservation) when
341                    // the student is already enrolled in the course
342                    for (Enrollment enrollment : course.getEnrollments(assignment()))
343                        if (enrollment.getStudent().getId() == studentId) {
344                            applicable = true;
345                            break;
346                        }
347                }
348                Reservation clonedReservation = new OnlineReservation(0, reservation.getId(), clonedOffering,
349                        reservation.getPriority(), reservation.canAssignOverLimit(), reservationLimit, applicable,
350                        reservation.mustBeUsed(), reservation.isAllowOverlap(), reservation.isExpired());
351                for (Config config : reservation.getConfigs())
352                    clonedReservation.addConfig(configs.get(config));
353                for (Map.Entry<Subpart, Set<Section>> entry : reservation.getSections().entrySet()) {
354                    Set<Section> clonedSections = new HashSet<Section>();
355                    for (Section section : entry.getValue())
356                        clonedSections.add(sections.get(section));
357                    clonedReservation.getSections().put(subparts.get(entry.getKey()), clonedSections);
358                }
359            }
360        }
361        return clonedCourse;
362    }
363
364    protected Request addRequest(Student student, Student original, Request request, Map<Long, Section> classTable,
365            StudentSectioningModel model) {
366        if (request instanceof FreeTimeRequest) {
367            return new FreeTimeRequest(student.getRequests().size() + 1, student.getRequests().size(),
368                    request.isAlternative(), student, ((FreeTimeRequest) request).getTime());
369        } else if (request instanceof CourseRequest) {
370            List<Course> courses = new ArrayList<Course>();
371            for (Course course : ((CourseRequest) request).getCourses())
372                courses.add(clone(course, student.getId(), original, classTable, model));
373            CourseRequest clonnedRequest = new CourseRequest(student.getRequests().size() + 1, student.getRequests().size(),
374                    request.isAlternative(), student, courses, ((CourseRequest) request).isWaitlist(), request.getRequestPriority(), null);
375            for (Request originalRequest : original.getRequests()) {
376                Enrollment originalEnrollment = assignment().getValue(originalRequest);
377                for (Course clonnedCourse : clonnedRequest.getCourses()) {
378                    if (!clonnedCourse.getOffering().hasReservations())
379                        continue;
380                    if (originalEnrollment != null && clonnedCourse.equals(originalEnrollment.getCourse())) {
381                        boolean needReservation = clonnedCourse.getOffering().getUnreservedSpace(assignment(), clonnedRequest) < 1.0;
382                        if (!needReservation) {
383                            boolean configChecked = false;
384                            for (Section originalSection : originalEnrollment.getSections()) {
385                                Section clonnedSection = classTable.get(originalSection.getId());
386                                if (clonnedSection.getUnreservedSpace(assignment(), clonnedRequest) < 1.0) {
387                                    needReservation = true;
388                                    break;
389                                }
390                                if (!configChecked
391                                        && clonnedSection.getSubpart().getConfig()
392                                                .getUnreservedSpace(assignment(), clonnedRequest) < 1.0) {
393                                    needReservation = true;
394                                    break;
395                                }
396                                configChecked = true;
397                            }
398                        }
399                        if (needReservation) {
400                            Reservation reservation = new OnlineReservation(0, -original.getId(),
401                                    clonnedCourse.getOffering(), 5, false, 1, true, false, false, true);
402                            for (Section originalSection : originalEnrollment.getSections())
403                                reservation.addSection(classTable.get(originalSection.getId()));
404                        }
405                        break;
406                    }
407                }
408            }
409            return clonnedRequest;
410        } else {
411            return null;
412        }
413    }
414
415    public boolean section(Student original) {
416        OnlineSectioningModel model = new TestModel(iModel.getProperties());
417        model.setOverExpectedCriterion(iModel.getOverExpectedCriterion());
418        Student student = new Student(original.getId());
419        Hashtable<CourseRequest, Set<Section>> preferredSectionsForCourse = new Hashtable<CourseRequest, Set<Section>>();
420        Map<Long, Section> classTable = new HashMap<Long, Section>();
421
422        synchronized (iModel) {
423            for (Request request : original.getRequests()) {
424                Request clonnedRequest = addRequest(student, original, request, classTable, model);
425                Enrollment enrollment = assignment().getValue(request);
426                if (enrollment != null && enrollment.isCourseRequest()) {
427                    Set<Section> sections = new HashSet<Section>();
428                    for (Section section : enrollment.getSections())
429                        sections.add(classTable.get(section.getId()));
430                    preferredSectionsForCourse.put((CourseRequest) clonnedRequest, sections);
431                }
432            }
433        }
434
435        model.addStudent(student);
436        model.setDistanceConflict(new DistanceConflict(iModel.getDistanceConflict().getDistanceMetric(), model.getProperties()));
437        model.setTimeOverlaps(new TimeOverlapsCounter(null, model.getProperties()));
438        for (LinkedSections link : iModel.getLinkedSections()) {
439            List<Section> sections = new ArrayList<Section>();
440            for (Offering offering : link.getOfferings())
441                for (Subpart subpart : link.getSubparts(offering))
442                    for (Section section : link.getSections(subpart)) {
443                        Section x = classTable.get(section.getId());
444                        if (x != null)
445                            sections.add(x);
446                    }
447            if (sections.size() >= 2)
448                model.addLinkedSections(link.isMustBeUsed(), sections);
449        }
450        OnlineSectioningSelection selection = null;
451        if (model.getProperties().getPropertyBoolean("StudentWeights.MultiCriteria", true)) {
452            selection = new MultiCriteriaBranchAndBoundSelection(iModel.getProperties());
453        } else {
454            selection = new SuggestionSelection(model.getProperties());
455        }
456
457        selection.setModel(model);
458        selection.setPreferredSections(preferredSectionsForCourse);
459        selection.setRequiredSections(new Hashtable<CourseRequest, Set<Section>>());
460        selection.setRequiredFreeTimes(new HashSet<FreeTimeRequest>());
461
462        long t0 = JProf.currentTimeMillis();
463        Assignment<Request, Enrollment> newAssignment = new AssignmentMap<Request, Enrollment>();
464        BranchBoundNeighbour neighbour = selection.select(newAssignment, student);
465        long time = JProf.currentTimeMillis() - t0;
466        inc("[C] CPU Time", time);
467        if (neighbour == null) {
468            inc("[F] Failure");
469        } else {
470            if (iSuggestions) {
471                StudentPreferencePenalties penalties = new StudentPreferencePenalties(StudentPreferencePenalties.sDistTypePreference);
472                double maxOverExpected = 0;
473                int assigned = 0;
474                double penalty = 0.0;
475                Hashtable<CourseRequest, Set<Section>> enrollments = new Hashtable<CourseRequest, Set<Section>>();
476                List<RequestSectionPair> pairs = new ArrayList<RequestSectionPair>();
477
478                for (int i = 0; i < neighbour.getAssignment().length; i++) {
479                    Enrollment enrl = neighbour.getAssignment()[i];
480                    if (enrl != null && enrl.isCourseRequest() && enrl.getAssignments() != null) {
481                        assigned++;
482                        for (Section section : enrl.getSections()) {
483                            maxOverExpected += model.getOverExpected(newAssignment, section, enrl.getRequest());
484                            pairs.add(new RequestSectionPair(enrl.variable(), section));
485                        }
486                        enrollments.put((CourseRequest) enrl.variable(), enrl.getSections());
487                        penalty += penalties.getPenalty(enrl);
488                    }
489                }
490                penalty /= assigned;
491                inc("[S] Initial Penalty", penalty);
492                double nrSuggestions = 0.0, nrAccepted = 0.0, totalSuggestions = 0.0, nrTries = 0.0;
493                for (int i = 0; i < pairs.size(); i++) {
494                    RequestSectionPair pair = pairs.get(i);
495                    SuggestionsBranchAndBound suggestionBaB = null;
496                    if (model.getProperties().getPropertyBoolean("StudentWeights.MultiCriteria", true)) {
497                        suggestionBaB = new MultiCriteriaBranchAndBoundSuggestions(model.getProperties(), student,
498                                newAssignment, new Hashtable<CourseRequest, Set<Section>>(),
499                                new HashSet<FreeTimeRequest>(), enrollments, pair.getRequest(), pair.getSection(),
500                                null, maxOverExpected, iModel.getProperties().getPropertyBoolean(
501                                        "StudentWeights.PriorityWeighting", true));
502                    } else {
503                        suggestionBaB = new SuggestionsBranchAndBound(model.getProperties(), student, newAssignment,
504                                new Hashtable<CourseRequest, Set<Section>>(), new HashSet<FreeTimeRequest>(),
505                                enrollments, pair.getRequest(), pair.getSection(), null, maxOverExpected);
506                    }
507
508                    long x0 = JProf.currentTimeMillis();
509                    TreeSet<SuggestionsBranchAndBound.Suggestion> suggestions = suggestionBaB.computeSuggestions();
510                    inc("[S] Suggestion CPU Time", JProf.currentTimeMillis() - x0);
511                    totalSuggestions += suggestions.size();
512                    if (!suggestions.isEmpty())
513                        nrSuggestions += 1.0;
514                    nrTries += 1.0;
515
516                    SuggestionsBranchAndBound.Suggestion best = null;
517                    for (SuggestionsBranchAndBound.Suggestion suggestion : suggestions) {
518                        int a = 0;
519                        double p = 0.0;
520                        for (int j = 0; j < suggestion.getEnrollments().length; j++) {
521                            Enrollment e = suggestion.getEnrollments()[j];
522                            if (e != null && e.isCourseRequest() && e.getAssignments() != null) {
523                                p += penalties.getPenalty(e);
524                                a++;
525                            }
526                        }
527                        p /= a;
528                        if (a > assigned || (assigned == a && p < penalty)) {
529                            best = suggestion;
530                        }
531                    }
532                    if (best != null) {
533                        nrAccepted += 1.0;
534                        Enrollment[] e = best.getEnrollments();
535                        for (int j = 0; j < e.length; j++)
536                            if (e[j] != null && e[j].getAssignments() == null)
537                                e[j] = null;
538                        neighbour = new BranchBoundNeighbour(student, best.getValue(), e);
539                        assigned = 0;
540                        penalty = 0.0;
541                        enrollments.clear();
542                        pairs.clear();
543                        for (int j = 0; j < neighbour.getAssignment().length; j++) {
544                            Enrollment enrl = neighbour.getAssignment()[j];
545                            if (enrl != null && enrl.isCourseRequest() && enrl.getAssignments() != null) {
546                                assigned++;
547                                for (Section section : enrl.getSections())
548                                    pairs.add(new RequestSectionPair(enrl.variable(), section));
549                                enrollments.put((CourseRequest) enrl.variable(), enrl.getSections());
550                                penalty += penalties.getPenalty(enrl);
551                            }
552                        }
553                        penalty /= assigned;
554                        inc("[S] Improved Penalty", penalty);
555                    }
556                }
557                inc("[S] Final Penalty", penalty);
558                if (nrSuggestions > 0) {
559                    inc("[S] Classes with suggestion", nrSuggestions);
560                    inc("[S] Avg. # of suggestions", totalSuggestions / nrSuggestions);
561                    inc("[S] Suggestion acceptance rate [%]", nrAccepted / nrSuggestions);
562                } else {
563                    inc("[S] Student with no suggestions available", 1.0);
564                }
565                if (!pairs.isEmpty())
566                    inc("[S] Probability that a class has suggestions [%]", nrSuggestions / nrTries);
567            }
568
569            List<Enrollment> enrollments = new ArrayList<Enrollment>();
570            i: for (int i = 0; i < neighbour.getAssignment().length; i++) {
571                Request request = original.getRequests().get(i);
572                Enrollment clonnedEnrollment = neighbour.getAssignment()[i];
573                if (clonnedEnrollment != null && clonnedEnrollment.getAssignments() != null) {
574                    if (request instanceof FreeTimeRequest) {
575                        enrollments.add(((FreeTimeRequest) request).createEnrollment());
576                    } else {
577                        for (Course course : ((CourseRequest) request).getCourses())
578                            if (course.getId() == clonnedEnrollment.getCourse().getId())
579                                for (Config config : course.getOffering().getConfigs())
580                                    if (config.getId() == clonnedEnrollment.getConfig().getId()) {
581                                        Set<Section> assignments = new HashSet<Section>();
582                                        for (Subpart subpart : config.getSubparts())
583                                            for (Section section : subpart.getSections()) {
584                                                if (clonnedEnrollment.getSections().contains(section)) {
585                                                    assignments.add(section);
586                                                }
587                                            }
588                                        Reservation reservation = null;
589                                        if (clonnedEnrollment.getReservation() != null) {
590                                            for (Reservation r : course.getOffering().getReservations())
591                                                if (r.getId() == clonnedEnrollment.getReservation().getId()) {
592                                                    reservation = r;
593                                                    break;
594                                                }
595                                        }
596                                        enrollments.add(new Enrollment(request, clonnedEnrollment.getPriority(),
597                                                course, config, assignments, reservation));
598                                        continue i;
599                                    }
600                    }
601                }
602            }
603            synchronized (iModel) {
604                for (Request r : original.getRequests()) {
605                    Enrollment e = assignment().getValue(r);
606                    r.setInitialAssignment(e);
607                    if (e != null)
608                        updateSpace(assignment(), e, true);
609                }
610                for (Request r : original.getRequests())
611                    if (assignment().getValue(r) != null)
612                        assignment().unassign(0, r);
613                boolean fail = false;
614                for (Enrollment enrl : enrollments) {
615                    if (iModel.conflictValues(assignment(), enrl).isEmpty()) {
616                        assignment().assign(0, enrl);
617                    } else {
618                        fail = true;
619                        break;
620                    }
621                }
622                if (fail) {
623                    for (Request r : original.getRequests())
624                        if (assignment().getValue(r) != null)
625                            assignment().unassign(0, r);
626                    for (Request r : original.getRequests())
627                        if (r.getInitialAssignment() != null)
628                            assignment().assign(0, r.getInitialAssignment());
629                    for (Request r : original.getRequests())
630                        if (assignment().getValue(r) != null)
631                            updateSpace(assignment(), assignment().getValue(r), false);
632                } else {
633                    for (Enrollment enrl : enrollments)
634                        updateSpace(assignment(), enrl, false);
635                }
636                if (fail)
637                    return false;
638            }
639            neighbour.assign(newAssignment, 0);
640            int a = 0, u = 0, np = 0, zp = 0, pp = 0, cp = 0;
641            double over = 0;
642            double p = 0.0;
643            for (Request r : student.getRequests()) {
644                if (r instanceof CourseRequest) {
645                    Enrollment e = newAssignment.getValue(r);
646                    if (e != null) {
647                        for (Section s : e.getSections()) {
648                            if (s.getPenalty() < 0.0)
649                                np++;
650                            if (s.getPenalty() == 0.0)
651                                zp++;
652                            if (s.getPenalty() > 0.0)
653                                pp++;
654                            if (s.getLimit() > 0) {
655                                p += s.getPenalty();
656                                cp++;
657                            }
658                            over += model.getOverExpected(newAssignment, s, r);
659                        }
660                        a++;
661                    } else {
662                        u++;
663                    }
664                }
665            }
666            inc("[A] Student");
667            if (over > 0.0)
668                inc("[O] Over", over);
669            if (a > 0)
670                inc("[A] Assigned", a);
671            if (u > 0)
672                inc("[A] Not Assigned", u);
673            inc("[V] Value", neighbour.value(newAssignment));
674            if (zp > 0)
675                inc("[P] Zero penalty", zp);
676            if (np > 0)
677                inc("[P] Negative penalty", np);
678            if (pp > 0)
679                inc("[P] Positive penalty", pp);
680            if (cp > 0)
681                inc("[P] Average penalty", p / cp);
682        }
683        inc("[T0] Time <10ms", time < 10 ? 1 : 0);
684        inc("[T1] Time <100ms", time < 100 ? 1 : 0);
685        inc("[T2] Time <250ms", time < 250 ? 1 : 0);
686        inc("[T3] Time <500ms", time < 500 ? 1 : 0);
687        inc("[T4] Time <1s", time < 1000 ? 1 : 0);
688        inc("[T5] Time >=1s", time >= 1000 ? 1 : 0);
689        return true;
690    }
691
692    public static void updateSpace(Assignment<Request, Enrollment> assignment, Enrollment enrollment, boolean increment) {
693        if (enrollment == null || !enrollment.isCourseRequest())
694            return;
695        for (Section section : enrollment.getSections())
696            section.setSpaceHeld(section.getSpaceHeld() + (increment ? 1.0 : -1.0));
697        List<Enrollment> feasibleEnrollments = new ArrayList<Enrollment>();
698        int totalLimit = 0;
699        for (Enrollment enrl : enrollment.getRequest().values(assignment)) {
700            if (!enrl.getCourse().equals(enrollment.getCourse()))
701                continue;
702            boolean overlaps = false;
703            for (Request otherRequest : enrollment.getRequest().getStudent().getRequests()) {
704                if (otherRequest.equals(enrollment.getRequest()) || !(otherRequest instanceof CourseRequest))
705                    continue;
706                Enrollment otherErollment = assignment.getValue(otherRequest);
707                if (otherErollment == null)
708                    continue;
709                if (enrl.isOverlapping(otherErollment)) {
710                    overlaps = true;
711                    break;
712                }
713            }
714            if (!overlaps) {
715                feasibleEnrollments.add(enrl);
716                if (totalLimit >= 0) {
717                    int limit = enrl.getLimit();
718                    if (limit < 0)
719                        totalLimit = -1;
720                    else
721                        totalLimit += limit;
722                }
723            }
724        }
725        double change = enrollment.getRequest().getWeight()
726                / (totalLimit > 0 ? totalLimit : feasibleEnrollments.size());
727        for (Enrollment feasibleEnrollment : feasibleEnrollments)
728            for (Section section : feasibleEnrollment.getSections()) {
729                if (totalLimit > 0) {
730                    section.setSpaceExpected(section.getSpaceExpected() + (increment ? +change : -change)
731                            * feasibleEnrollment.getLimit());
732                } else {
733                    section.setSpaceExpected(section.getSpaceExpected() + (increment ? +change : -change));
734                }
735            }
736    }
737
738    public void run() {
739        sLog.info("Input: " + ToolBox.dict2string(model().getExtendedInfo(assignment()), 2));
740
741        List<Student> students = new ArrayList<Student>(model().getStudents());
742        String sort = System.getProperty("sort", "shuffle");
743        if ("shuffle".equals(sort)) {
744            Collections.shuffle(students);
745        } else if ("choice".equals(sort)) {
746            StudentChoiceOrder ord = new StudentChoiceOrder(model().getProperties());
747            ord.setReverse(false);
748            Collections.sort(students, ord);
749        } else if ("referse".equals(sort)) {
750            StudentChoiceOrder ord = new StudentChoiceOrder(model().getProperties());
751            ord.setReverse(true);
752            Collections.sort(students, ord);
753        }
754
755        Iterator<Student> iterator = students.iterator();
756        int nrThreads = Integer.parseInt(System.getProperty("nrConcurrent", "10"));
757        List<Executor> executors = new ArrayList<Executor>();
758        for (int i = 0; i < nrThreads; i++) {
759            Executor executor = new Executor(iterator);
760            executor.start();
761            executors.add(executor);
762        }
763
764        long t0 = System.currentTimeMillis();
765        while (iterator.hasNext()) {
766            try {
767                Thread.sleep(60000);
768            } catch (InterruptedException e) {
769            }
770            long time = System.currentTimeMillis() - t0;
771            synchronized (iModel) {
772                sLog.info("Progress [" + (time / 60000) + "m]: " + ToolBox.dict2string(model().getExtendedInfo(assignment()), 2));
773            }
774        }
775
776        for (Executor executor : executors) {
777            try {
778                executor.join();
779            } catch (InterruptedException e) {
780            }
781        }
782
783        sLog.info("Output: " + ToolBox.dict2string(model().getExtendedInfo(assignment()), 2));
784        long time = System.currentTimeMillis() - t0;
785        inc("[T] Run Time [m]", time / 60000.0);
786
787    }
788
789    public class Executor extends Thread {
790        private Iterator<Student> iStudents = null;
791
792        public Executor(Iterator<Student> students) {
793            iStudents = students;
794        }
795
796        @Override
797        public void run() {
798            try {
799                for (;;) {
800                    Student student = iStudents.next();
801                    int attempt = 1;
802                    while (!section(student)) {
803                        sLog.warn(attempt + ". attempt failed for " + student.getId());
804                        inc("[F] Failed attempt", attempt);
805                        attempt++;
806                        if (attempt == 101)
807                            break;
808                        if (attempt > 10) {
809                            try {
810                                Thread.sleep(ToolBox.random(100 * attempt));
811                            } catch (InterruptedException e) {
812                            }
813                        }
814                    }
815                    if (attempt > 100)
816                        inc("[F] Failed enrollment (all 100 attempts)");
817                }
818            } catch (NoSuchElementException e) {
819            }
820        }
821
822    }
823
824    public class TestModel extends OnlineSectioningModel {
825        public TestModel(DataProperties config) {
826            super(config);
827        }
828
829        @Override
830        public Map<String, String> getExtendedInfo(Assignment<Request, Enrollment> assignment) {
831            Map<String, String> ret = super.getExtendedInfo(assignment);
832            for (Map.Entry<String, Counter> e : iCounters.entrySet())
833                ret.put(e.getKey(), e.getValue().toString());
834            ret.put("Weighting model",
835                    (model().getProperties().getPropertyBoolean("StudentWeights.MultiCriteria", true) ? "multi-criteria " : "") +
836                    (model().getProperties().getPropertyBoolean("StudentWeights.PriorityWeighting", true) ? "priority" : "equal"));
837            ret.put("B&B time limit", model().getProperties().getPropertyInt("Neighbour.BranchAndBoundTimeout", 1000) + " ms");
838            if (iSuggestions) {
839                ret.put("Suggestion time limit", model().getProperties().getPropertyInt("Suggestions.Timeout", 1000) + " ms");
840            }
841            return ret;
842        }
843    }
844
845    private static class RequestSectionPair {
846        private Request iRequest;
847        private Section iSection;
848
849        RequestSectionPair(Request request, Section section) {
850            iRequest = request;
851            iSection = section;
852        }
853
854        Request getRequest() {
855            return iRequest;
856        }
857
858        Section getSection() {
859            return iSection;
860        }
861    }
862
863    private void stats(File input) throws IOException {
864        File file = new File(input.getParentFile(), "stats.csv");
865        DecimalFormat df = new DecimalFormat("0.0000");
866        boolean ex = file.exists();
867        PrintWriter pw = new PrintWriter(new FileWriter(file, true));
868        if (!ex) {
869            pw.println("Input File,Run Time [m],Model,Sort,Over Expected,Not Assigned,Disb. Sections [%],Distance Confs.,Time Confs. [m],"
870                    + "CPU Assignment [ms],Has Suggestions [%],Nbr Suggestions,Acceptance [%],CPU Suggestions [ms]");
871        }
872        pw.print(input.getName() + ",");
873        pw.print(df.format(get("[T] Run Time [m]").sum()) + ",");
874        pw.print(model().getProperties().getPropertyBoolean("StudentWeights.MultiCriteria", true) ? "multi-criteria " : "");
875        pw.print(model().getProperties().getPropertyBoolean("StudentWeights.PriorityWeighting", true) ? "priority" : "equal");
876        pw.print(iSuggestions ? " with suggestions" : "");
877        pw.print(",");
878        pw.print(System.getProperty("sort", "shuffle") + ",");
879        pw.print("\"" + model().getOverExpectedCriterion() + "\",");
880
881        pw.print(get("[A] Not Assigned").sum() + ",");
882        pw.print(df.format(getPercDisbalancedSections(assignment(), 0.1)) + ",");
883        if (model().getStudentQuality() != null) {
884            pw.print(df.format(((double) model().getStudentQuality().getTotalPenalty(assignment(), StudentQuality.Type.Distance, StudentQuality.Type.ShortDistance)) / model().getStudents().size()) + ",");
885            pw.print(df.format(5.0 * model().getStudentQuality().getTotalPenalty(assignment(), StudentQuality.Type.CourseTimeOverlap, StudentQuality.Type.FreeTimeOverlap, StudentQuality.Type.Unavailability) / model().getStudents().size()) + ",");
886        } else {
887            pw.print(df.format(((double) model().getDistanceConflict().getTotalNrConflicts(assignment())) / model().getStudents().size()) + ",");
888            pw.print(df.format(5.0 * model().getTimeOverlaps().getTotalNrConflicts(assignment()) / model().getStudents().size()) + ",");
889        }
890        pw.print(df.format(get("[C] CPU Time").avg()) + ",");
891        if (iSuggestions) {
892            pw.print(df.format(get("[S] Probability that a class has suggestions [%]").avg()) + ",");
893            pw.print(df.format(get("[S] Avg. # of suggestions").avg()) + ",");
894            pw.print(df.format(get("[S] Suggestion acceptance rate [%]").avg()) + ",");
895            pw.print(df.format(get("[S] Suggestion CPU Time").avg()));
896        }
897        pw.println();
898
899        pw.flush();
900        pw.close();
901    }
902
903    public static void main(String[] args) {
904        try {
905            System.setProperty("jprof", "cpu");
906            ToolBox.configureLogging();
907
908            DataProperties cfg = new DataProperties();
909            cfg.setProperty("Neighbour.BranchAndBoundTimeout", "5000");
910            cfg.setProperty("Suggestions.Timeout", "1000");
911            cfg.setProperty("Extensions.Classes", DistanceConflict.class.getName() + ";" + TimeOverlapsCounter.class.getName());
912            cfg.setProperty("StudentWeights.Class", StudentSchedulingAssistantWeights.class.getName());
913            cfg.setProperty("StudentWeights.PriorityWeighting", "true");
914            cfg.setProperty("StudentWeights.LeftoverSpread", "true");
915            cfg.setProperty("StudentWeights.BalancingFactor", "0.0");
916            cfg.setProperty("Reservation.CanAssignOverTheLimit", "true");
917            cfg.setProperty("Distances.Ellipsoid", DistanceMetric.Ellipsoid.WGS84.name());
918            cfg.setProperty("StudentWeights.MultiCriteria", "true");
919            cfg.setProperty("CourseRequest.SameTimePrecise", "true");
920
921            cfg.setProperty("Xml.LoadBest", "false");
922            cfg.setProperty("Xml.LoadCurrent", "false");
923
924            cfg.putAll(System.getProperties());
925
926            final Test test = new Test(cfg);
927
928            final File input = new File(args[0]);
929            StudentSectioningXMLLoader loader = new StudentSectioningXMLLoader(test.model(), test.assignment());
930            loader.setInputFile(input);
931            loader.load();
932
933            test.run();
934
935            Solver<Request, Enrollment> s = new Solver<Request, Enrollment>(cfg);
936            s.setInitalSolution(test.model());
937            StudentSectioningXMLSaver saver = new StudentSectioningXMLSaver(s);
938            File output = new File(input.getParentFile(), input.getName().substring(0, input.getName().lastIndexOf('.')) +
939                    "-" + cfg.getProperty("run", "r0") + ".xml");
940            saver.save(output);
941
942            test.stats(input);
943        } catch (Exception e) {
944            sLog.error("Test failed: " + e.getMessage(), e);
945        }
946    }
947
948    private static class Counter {
949        private double iTotal = 0.0, iMin = 0.0, iMax = 0.0, iTotalSquare = 0.0;
950        private int iCount = 0;
951
952        void inc(double value) {
953            if (iCount == 0) {
954                iTotal = value;
955                iMin = value;
956                iMax = value;
957                iTotalSquare = value * value;
958            } else {
959                iTotal += value;
960                iMin = Math.min(iMin, value);
961                iMax = Math.max(iMax, value);
962                iTotalSquare += value * value;
963            }
964            iCount++;
965        }
966
967        int count() {
968            return iCount;
969        }
970
971        double sum() {
972            return iTotal;
973        }
974
975        double min() {
976            return iMin;
977        }
978
979        double max() {
980            return iMax;
981        }
982
983        double rms() {
984            return (iCount == 0 ? 0.0 : Math.sqrt(iTotalSquare / iCount));
985        }
986
987        double avg() {
988            return (iCount == 0 ? 0.0 : iTotal / iCount);
989        }
990
991        @Override
992        public String toString() {
993            return sDF.format(sum()) + " (min: " + sDF.format(min()) + ", max: " + sDF.format(max()) +
994                    ", avg: " + sDF.format(avg()) + ", rms: " + sDF.format(rms()) + ", cnt: " + count() + ")";
995        }
996    }
997
998}