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