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.getEnrollmentTotalWeight(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.getEnrollmentTotalWeight(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.getEnrollmentTotalWeight(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.setInstructionalMethodId(config.getInstructionalMethodId());
266            clonedConfig.setInstructionalMethodName(config.getInstructionalMethodName());
267            clonedConfig.setEnrollment(configEnrollment);
268            configs.put(config, clonedConfig);
269            for (Iterator<Subpart> f = config.getSubparts().iterator(); f.hasNext();) {
270                Subpart subpart = f.next();
271                Subpart clonedSubpart = new Subpart(subpart.getId(), subpart.getInstructionalType(), subpart.getName(),
272                        clonedConfig, (subpart.getParent() == null ? null : subparts.get(subpart.getParent())));
273                clonedSubpart.setAllowOverlap(subpart.isAllowOverlap());
274                clonedSubpart.setCredit(subpart.getCredit());
275                subparts.put(subpart, clonedSubpart);
276                for (Iterator<Section> g = subpart.getSections().iterator(); g.hasNext();) {
277                    Section section = g.next();
278                    int limit = section.getLimit();
279                    int enrl = section.getEnrollments(assignment()).size();
280                    if (limit >= 0) {
281                        // limited section, deduct enrollments
282                        limit -= section.getEnrollments(assignment()).size();
283                        if (limit < 0)
284                            limit = 0; // over-enrolled, but not unlimited
285                        if (studentId >= 0)
286                            for (Enrollment enrollment : section.getEnrollments(assignment()))
287                                if (enrollment.getStudent().getId() == studentId) {
288                                    limit++;
289                                    enrl--;
290                                    break;
291                                }
292                    }
293                    OnlineSection clonedSection = new OnlineSection(section.getId(), limit,
294                            section.getName(course .getId()), clonedSubpart, section.getPlacement(), section.getInstructors(), (section.getParent() == null ? null : sections.get(section.getParent())));
295                    clonedSection.setName(-1l, section.getName(-1l));
296                    clonedSection.setNote(section.getNote());
297                    clonedSection.setSpaceExpected(section.getSpaceExpected());
298                    clonedSection.setSpaceHeld(section.getSpaceHeld());
299                    clonedSection.setEnrollment(enrl);
300                    clonedSection.setCancelled(section.isCancelled());
301                    if (section.getIgnoreConflictWithSectionIds() != null)
302                        for (Long id : section.getIgnoreConflictWithSectionIds())
303                            clonedSection.addIgnoreConflictWith(id);
304                    if (limit > 0) {
305                        double available = Math.round(section.getSpaceExpected() - limit);
306                        clonedSection.setPenalty(available / section.getLimit());
307                    }
308                    sections.put(section, clonedSection);
309                    classTable.put(section.getId(), clonedSection);
310                }
311            }
312        }
313        if (course.getOffering().hasReservations()) {
314            for (Reservation reservation : course.getOffering().getReservations()) {
315                int reservationLimit = (int) Math.round(reservation.getLimit());
316                if (reservationLimit >= 0) {
317                    reservationLimit -= reservation.getEnrollments(assignment()).size();
318                    if (reservationLimit < 0)
319                        reservationLimit = 0;
320                    for (Iterator<Enrollment> i = reservation.getEnrollments(assignment()).iterator(); i.hasNext();) {
321                        Enrollment enrollment = i.next();
322                        if (enrollment.getStudent().getId() == studentId) {
323                            reservationLimit++;
324                            break;
325                        }
326                    }
327                    if (reservationLimit <= 0 && !reservation.mustBeUsed())
328                        continue;
329                }
330                boolean applicable = originalStudent != null && reservation.isApplicable(originalStudent);
331                if (reservation instanceof CourseReservation)
332                    applicable = (course.getId() == ((CourseReservation) reservation).getCourse().getId());
333                if (reservation instanceof org.cpsolver.studentsct.reservation.DummyReservation) {
334                    // Ignore by reservation only flag (dummy reservation) when
335                    // the student is already enrolled in the course
336                    for (Enrollment enrollment : course.getEnrollments(assignment()))
337                        if (enrollment.getStudent().getId() == studentId) {
338                            applicable = true;
339                            break;
340                        }
341                }
342                Reservation clonedReservation = new OnlineReservation(0, reservation.getId(), clonedOffering,
343                        reservation.getPriority(), reservation.canAssignOverLimit(), reservationLimit, applicable,
344                        reservation.mustBeUsed(), reservation.isAllowOverlap(), reservation.isExpired());
345                for (Config config : reservation.getConfigs())
346                    clonedReservation.addConfig(configs.get(config));
347                for (Map.Entry<Subpart, Set<Section>> entry : reservation.getSections().entrySet()) {
348                    Set<Section> clonedSections = new HashSet<Section>();
349                    for (Section section : entry.getValue())
350                        clonedSections.add(sections.get(section));
351                    clonedReservation.getSections().put(subparts.get(entry.getKey()), clonedSections);
352                }
353            }
354        }
355        return clonedCourse;
356    }
357
358    protected Request addRequest(Student student, Student original, Request request, Map<Long, Section> classTable,
359            StudentSectioningModel model) {
360        if (request instanceof FreeTimeRequest) {
361            return new FreeTimeRequest(student.getRequests().size() + 1, student.getRequests().size(),
362                    request.isAlternative(), student, ((FreeTimeRequest) request).getTime());
363        } else if (request instanceof CourseRequest) {
364            List<Course> courses = new ArrayList<Course>();
365            for (Course course : ((CourseRequest) request).getCourses())
366                courses.add(clone(course, student.getId(), original, classTable, model));
367            CourseRequest clonnedRequest = new CourseRequest(student.getRequests().size() + 1, student.getRequests().size(),
368                    request.isAlternative(), student, courses, ((CourseRequest) request).isWaitlist(), null);
369            for (Request originalRequest : original.getRequests()) {
370                Enrollment originalEnrollment = assignment().getValue(originalRequest);
371                for (Course clonnedCourse : clonnedRequest.getCourses()) {
372                    if (!clonnedCourse.getOffering().hasReservations())
373                        continue;
374                    if (originalEnrollment != null && clonnedCourse.equals(originalEnrollment.getCourse())) {
375                        boolean needReservation = clonnedCourse.getOffering().getUnreservedSpace(assignment(), clonnedRequest) < 1.0;
376                        if (!needReservation) {
377                            boolean configChecked = false;
378                            for (Section originalSection : originalEnrollment.getSections()) {
379                                Section clonnedSection = classTable.get(originalSection.getId());
380                                if (clonnedSection.getUnreservedSpace(assignment(), clonnedRequest) < 1.0) {
381                                    needReservation = true;
382                                    break;
383                                }
384                                if (!configChecked
385                                        && clonnedSection.getSubpart().getConfig()
386                                                .getUnreservedSpace(assignment(), clonnedRequest) < 1.0) {
387                                    needReservation = true;
388                                    break;
389                                }
390                                configChecked = true;
391                            }
392                        }
393                        if (needReservation) {
394                            Reservation reservation = new OnlineReservation(0, -original.getId(),
395                                    clonnedCourse.getOffering(), 5, false, 1, true, false, false, true);
396                            for (Section originalSection : originalEnrollment.getSections())
397                                reservation.addSection(classTable.get(originalSection.getId()));
398                        }
399                        break;
400                    }
401                }
402            }
403            return clonnedRequest;
404        } else {
405            return null;
406        }
407    }
408
409    public boolean section(Student original) {
410        OnlineSectioningModel model = new TestModel(iModel.getProperties());
411        model.setOverExpectedCriterion(iModel.getOverExpectedCriterion());
412        Student student = new Student(original.getId());
413        Hashtable<CourseRequest, Set<Section>> preferredSectionsForCourse = new Hashtable<CourseRequest, Set<Section>>();
414        Map<Long, Section> classTable = new HashMap<Long, Section>();
415
416        synchronized (iModel) {
417            for (Request request : original.getRequests()) {
418                Request clonnedRequest = addRequest(student, original, request, classTable, model);
419                Enrollment enrollment = assignment().getValue(request);
420                if (enrollment != null && enrollment.isCourseRequest()) {
421                    Set<Section> sections = new HashSet<Section>();
422                    for (Section section : enrollment.getSections())
423                        sections.add(classTable.get(section.getId()));
424                    preferredSectionsForCourse.put((CourseRequest) clonnedRequest, sections);
425                }
426            }
427        }
428
429        model.addStudent(student);
430        model.setDistanceConflict(new DistanceConflict(iModel.getDistanceConflict().getDistanceMetric(), model.getProperties()));
431        model.setTimeOverlaps(new TimeOverlapsCounter(null, model.getProperties()));
432        for (LinkedSections link : iModel.getLinkedSections()) {
433            List<Section> sections = new ArrayList<Section>();
434            for (Offering offering : link.getOfferings())
435                for (Subpart subpart : link.getSubparts(offering))
436                    for (Section section : link.getSections(subpart)) {
437                        Section x = classTable.get(section.getId());
438                        if (x != null)
439                            sections.add(x);
440                    }
441            if (sections.size() >= 2)
442                model.addLinkedSections(link.isMustBeUsed(), sections);
443        }
444        OnlineSectioningSelection selection = null;
445        if (model.getProperties().getPropertyBoolean("StudentWeights.MultiCriteria", true)) {
446            selection = new MultiCriteriaBranchAndBoundSelection(iModel.getProperties());
447        } else {
448            selection = new SuggestionSelection(model.getProperties());
449        }
450
451        selection.setModel(model);
452        selection.setPreferredSections(preferredSectionsForCourse);
453        selection.setRequiredSections(new Hashtable<CourseRequest, Set<Section>>());
454        selection.setRequiredFreeTimes(new HashSet<FreeTimeRequest>());
455
456        long t0 = JProf.currentTimeMillis();
457        Assignment<Request, Enrollment> newAssignment = new AssignmentMap<Request, Enrollment>();
458        BranchBoundNeighbour neighbour = selection.select(newAssignment, student);
459        long time = JProf.currentTimeMillis() - t0;
460        inc("[C] CPU Time", time);
461        if (neighbour == null) {
462            inc("[F] Failure");
463        } else {
464            if (iSuggestions) {
465                StudentPreferencePenalties penalties = new StudentPreferencePenalties(StudentPreferencePenalties.sDistTypePreference);
466                double maxOverExpected = 0;
467                int assigned = 0;
468                double penalty = 0.0;
469                Hashtable<CourseRequest, Set<Section>> enrollments = new Hashtable<CourseRequest, Set<Section>>();
470                List<RequestSectionPair> pairs = new ArrayList<RequestSectionPair>();
471
472                for (int i = 0; i < neighbour.getAssignment().length; i++) {
473                    Enrollment enrl = neighbour.getAssignment()[i];
474                    if (enrl != null && enrl.isCourseRequest() && enrl.getAssignments() != null) {
475                        assigned++;
476                        for (Section section : enrl.getSections()) {
477                            maxOverExpected += model.getOverExpected(newAssignment, section, enrl.getRequest());
478                            pairs.add(new RequestSectionPair(enrl.variable(), section));
479                        }
480                        enrollments.put((CourseRequest) enrl.variable(), enrl.getSections());
481                        penalty += penalties.getPenalty(enrl);
482                    }
483                }
484                penalty /= assigned;
485                inc("[S] Initial Penalty", penalty);
486                double nrSuggestions = 0.0, nrAccepted = 0.0, totalSuggestions = 0.0, nrTries = 0.0;
487                for (int i = 0; i < pairs.size(); i++) {
488                    RequestSectionPair pair = pairs.get(i);
489                    SuggestionsBranchAndBound suggestionBaB = null;
490                    if (model.getProperties().getPropertyBoolean("StudentWeights.MultiCriteria", true)) {
491                        suggestionBaB = new MultiCriteriaBranchAndBoundSuggestions(model.getProperties(), student,
492                                newAssignment, new Hashtable<CourseRequest, Set<Section>>(),
493                                new HashSet<FreeTimeRequest>(), enrollments, pair.getRequest(), pair.getSection(),
494                                null, maxOverExpected, iModel.getProperties().getPropertyBoolean(
495                                        "StudentWeights.PriorityWeighting", true));
496                    } else {
497                        suggestionBaB = new SuggestionsBranchAndBound(model.getProperties(), student, newAssignment,
498                                new Hashtable<CourseRequest, Set<Section>>(), new HashSet<FreeTimeRequest>(),
499                                enrollments, pair.getRequest(), pair.getSection(), null, maxOverExpected);
500                    }
501
502                    long x0 = JProf.currentTimeMillis();
503                    TreeSet<SuggestionsBranchAndBound.Suggestion> suggestions = suggestionBaB.computeSuggestions();
504                    inc("[S] Suggestion CPU Time", JProf.currentTimeMillis() - x0);
505                    totalSuggestions += suggestions.size();
506                    if (!suggestions.isEmpty())
507                        nrSuggestions += 1.0;
508                    nrTries += 1.0;
509
510                    SuggestionsBranchAndBound.Suggestion best = null;
511                    for (SuggestionsBranchAndBound.Suggestion suggestion : suggestions) {
512                        int a = 0;
513                        double p = 0.0;
514                        for (int j = 0; j < suggestion.getEnrollments().length; j++) {
515                            Enrollment e = suggestion.getEnrollments()[j];
516                            if (e != null && e.isCourseRequest() && e.getAssignments() != null) {
517                                p += penalties.getPenalty(e);
518                                a++;
519                            }
520                        }
521                        p /= a;
522                        if (a > assigned || (assigned == a && p < penalty)) {
523                            best = suggestion;
524                        }
525                    }
526                    if (best != null) {
527                        nrAccepted += 1.0;
528                        Enrollment[] e = best.getEnrollments();
529                        for (int j = 0; j < e.length; j++)
530                            if (e[j] != null && e[j].getAssignments() == null)
531                                e[j] = null;
532                        neighbour = new BranchBoundNeighbour(student, best.getValue(), e);
533                        assigned = 0;
534                        penalty = 0.0;
535                        enrollments.clear();
536                        pairs.clear();
537                        for (int j = 0; j < neighbour.getAssignment().length; j++) {
538                            Enrollment enrl = neighbour.getAssignment()[j];
539                            if (enrl != null && enrl.isCourseRequest() && enrl.getAssignments() != null) {
540                                assigned++;
541                                for (Section section : enrl.getSections())
542                                    pairs.add(new RequestSectionPair(enrl.variable(), section));
543                                enrollments.put((CourseRequest) enrl.variable(), enrl.getSections());
544                                penalty += penalties.getPenalty(enrl);
545                            }
546                        }
547                        penalty /= assigned;
548                        inc("[S] Improved Penalty", penalty);
549                    }
550                }
551                inc("[S] Final Penalty", penalty);
552                if (nrSuggestions > 0) {
553                    inc("[S] Classes with suggestion", nrSuggestions);
554                    inc("[S] Avg. # of suggestions", totalSuggestions / nrSuggestions);
555                    inc("[S] Suggestion acceptance rate [%]", nrAccepted / nrSuggestions);
556                } else {
557                    inc("[S] Student with no suggestions available", 1.0);
558                }
559                if (!pairs.isEmpty())
560                    inc("[S] Probability that a class has suggestions [%]", nrSuggestions / nrTries);
561            }
562
563            List<Enrollment> enrollments = new ArrayList<Enrollment>();
564            i: for (int i = 0; i < neighbour.getAssignment().length; i++) {
565                Request request = original.getRequests().get(i);
566                Enrollment clonnedEnrollment = neighbour.getAssignment()[i];
567                if (clonnedEnrollment != null && clonnedEnrollment.getAssignments() != null) {
568                    if (request instanceof FreeTimeRequest) {
569                        enrollments.add(((FreeTimeRequest) request).createEnrollment());
570                    } else {
571                        for (Course course : ((CourseRequest) request).getCourses())
572                            if (course.getId() == clonnedEnrollment.getCourse().getId())
573                                for (Config config : course.getOffering().getConfigs())
574                                    if (config.getId() == clonnedEnrollment.getConfig().getId()) {
575                                        Set<Section> assignments = new HashSet<Section>();
576                                        for (Subpart subpart : config.getSubparts())
577                                            for (Section section : subpart.getSections()) {
578                                                if (clonnedEnrollment.getSections().contains(section)) {
579                                                    assignments.add(section);
580                                                }
581                                            }
582                                        Reservation reservation = null;
583                                        if (clonnedEnrollment.getReservation() != null) {
584                                            for (Reservation r : course.getOffering().getReservations())
585                                                if (r.getId() == clonnedEnrollment.getReservation().getId()) {
586                                                    reservation = r;
587                                                    break;
588                                                }
589                                        }
590                                        enrollments.add(new Enrollment(request, clonnedEnrollment.getPriority(),
591                                                course, config, assignments, reservation));
592                                        continue i;
593                                    }
594                    }
595                }
596            }
597            synchronized (iModel) {
598                for (Request r : original.getRequests()) {
599                    Enrollment e = assignment().getValue(r);
600                    r.setInitialAssignment(e);
601                    if (e != null)
602                        updateSpace(assignment(), e, true);
603                }
604                for (Request r : original.getRequests())
605                    if (assignment().getValue(r) != null)
606                        assignment().unassign(0, r);
607                boolean fail = false;
608                for (Enrollment enrl : enrollments) {
609                    if (iModel.conflictValues(assignment(), enrl).isEmpty()) {
610                        assignment().assign(0, enrl);
611                    } else {
612                        fail = true;
613                        break;
614                    }
615                }
616                if (fail) {
617                    for (Request r : original.getRequests())
618                        if (assignment().getValue(r) != null)
619                            assignment().unassign(0, r);
620                    for (Request r : original.getRequests())
621                        if (r.getInitialAssignment() != null)
622                            assignment().assign(0, r.getInitialAssignment());
623                    for (Request r : original.getRequests())
624                        if (assignment().getValue(r) != null)
625                            updateSpace(assignment(), assignment().getValue(r), false);
626                } else {
627                    for (Enrollment enrl : enrollments)
628                        updateSpace(assignment(), enrl, false);
629                }
630                if (fail)
631                    return false;
632            }
633            neighbour.assign(newAssignment, 0);
634            int a = 0, u = 0, np = 0, zp = 0, pp = 0, cp = 0;
635            double over = 0;
636            double p = 0.0;
637            for (Request r : student.getRequests()) {
638                if (r instanceof CourseRequest) {
639                    Enrollment e = newAssignment.getValue(r);
640                    if (e != null) {
641                        for (Section s : e.getSections()) {
642                            if (s.getPenalty() < 0.0)
643                                np++;
644                            if (s.getPenalty() == 0.0)
645                                zp++;
646                            if (s.getPenalty() > 0.0)
647                                pp++;
648                            if (s.getLimit() > 0) {
649                                p += s.getPenalty();
650                                cp++;
651                            }
652                            over += model.getOverExpected(newAssignment, s, r);
653                        }
654                        a++;
655                    } else {
656                        u++;
657                    }
658                }
659            }
660            inc("[A] Student");
661            if (over > 0.0)
662                inc("[O] Over", over);
663            if (a > 0)
664                inc("[A] Assigned", a);
665            if (u > 0)
666                inc("[A] Not Assigned", u);
667            inc("[V] Value", neighbour.value(newAssignment));
668            if (zp > 0)
669                inc("[P] Zero penalty", zp);
670            if (np > 0)
671                inc("[P] Negative penalty", np);
672            if (pp > 0)
673                inc("[P] Positive penalty", pp);
674            if (cp > 0)
675                inc("[P] Average penalty", p / cp);
676        }
677        inc("[T0] Time <10ms", time < 10 ? 1 : 0);
678        inc("[T1] Time <100ms", time < 100 ? 1 : 0);
679        inc("[T2] Time <250ms", time < 250 ? 1 : 0);
680        inc("[T3] Time <500ms", time < 500 ? 1 : 0);
681        inc("[T4] Time <1s", time < 1000 ? 1 : 0);
682        inc("[T5] Time >=1s", time >= 1000 ? 1 : 0);
683        return true;
684    }
685
686    public static void updateSpace(Assignment<Request, Enrollment> assignment, Enrollment enrollment, boolean increment) {
687        if (enrollment == null || !enrollment.isCourseRequest())
688            return;
689        for (Section section : enrollment.getSections())
690            section.setSpaceHeld(section.getSpaceHeld() + (increment ? 1.0 : -1.0));
691        List<Enrollment> feasibleEnrollments = new ArrayList<Enrollment>();
692        int totalLimit = 0;
693        for (Enrollment enrl : enrollment.getRequest().values(assignment)) {
694            if (!enrl.getCourse().equals(enrollment.getCourse()))
695                continue;
696            boolean overlaps = false;
697            for (Request otherRequest : enrollment.getRequest().getStudent().getRequests()) {
698                if (otherRequest.equals(enrollment.getRequest()) || !(otherRequest instanceof CourseRequest))
699                    continue;
700                Enrollment otherErollment = assignment.getValue(otherRequest);
701                if (otherErollment == null)
702                    continue;
703                if (enrl.isOverlapping(otherErollment)) {
704                    overlaps = true;
705                    break;
706                }
707            }
708            if (!overlaps) {
709                feasibleEnrollments.add(enrl);
710                if (totalLimit >= 0) {
711                    int limit = enrl.getLimit();
712                    if (limit < 0)
713                        totalLimit = -1;
714                    else
715                        totalLimit += limit;
716                }
717            }
718        }
719        double change = enrollment.getRequest().getWeight()
720                / (totalLimit > 0 ? totalLimit : feasibleEnrollments.size());
721        for (Enrollment feasibleEnrollment : feasibleEnrollments)
722            for (Section section : feasibleEnrollment.getSections()) {
723                if (totalLimit > 0) {
724                    section.setSpaceExpected(section.getSpaceExpected() + (increment ? +change : -change)
725                            * feasibleEnrollment.getLimit());
726                } else {
727                    section.setSpaceExpected(section.getSpaceExpected() + (increment ? +change : -change));
728                }
729            }
730    }
731
732    public void run() {
733        sLog.info("Input: " + ToolBox.dict2string(model().getExtendedInfo(assignment()), 2));
734
735        List<Student> students = new ArrayList<Student>(model().getStudents());
736        String sort = System.getProperty("sort", "shuffle");
737        if ("shuffle".equals(sort)) {
738            Collections.shuffle(students);
739        } else if ("choice".equals(sort)) {
740            StudentChoiceOrder ord = new StudentChoiceOrder(model().getProperties());
741            ord.setReverse(false);
742            Collections.sort(students, ord);
743        } else if ("referse".equals(sort)) {
744            StudentChoiceOrder ord = new StudentChoiceOrder(model().getProperties());
745            ord.setReverse(true);
746            Collections.sort(students, ord);
747        }
748
749        Iterator<Student> iterator = students.iterator();
750        int nrThreads = Integer.parseInt(System.getProperty("nrConcurrent", "10"));
751        List<Executor> executors = new ArrayList<Executor>();
752        for (int i = 0; i < nrThreads; i++) {
753            Executor executor = new Executor(iterator);
754            executor.start();
755            executors.add(executor);
756        }
757
758        long t0 = System.currentTimeMillis();
759        while (iterator.hasNext()) {
760            try {
761                Thread.sleep(60000);
762            } catch (InterruptedException e) {
763            }
764            long time = System.currentTimeMillis() - t0;
765            synchronized (iModel) {
766                sLog.info("Progress [" + (time / 60000) + "m]: " + ToolBox.dict2string(model().getExtendedInfo(assignment()), 2));
767            }
768        }
769
770        for (Executor executor : executors) {
771            try {
772                executor.join();
773            } catch (InterruptedException e) {
774            }
775        }
776
777        sLog.info("Output: " + ToolBox.dict2string(model().getExtendedInfo(assignment()), 2));
778        long time = System.currentTimeMillis() - t0;
779        inc("[T] Run Time [m]", time / 60000.0);
780
781    }
782
783    public class Executor extends Thread {
784        private Iterator<Student> iStudents = null;
785
786        public Executor(Iterator<Student> students) {
787            iStudents = students;
788        }
789
790        @Override
791        public void run() {
792            try {
793                for (;;) {
794                    Student student = iStudents.next();
795                    int attempt = 1;
796                    while (!section(student)) {
797                        sLog.warn(attempt + ". attempt failed for " + student.getId());
798                        inc("[F] Failed attempt", attempt);
799                        attempt++;
800                        if (attempt == 101)
801                            break;
802                        if (attempt > 10) {
803                            try {
804                                Thread.sleep(ToolBox.random(100 * attempt));
805                            } catch (InterruptedException e) {
806                            }
807                        }
808                    }
809                    if (attempt > 100)
810                        inc("[F] Failed enrollment (all 100 attempts)");
811                }
812            } catch (NoSuchElementException e) {
813            }
814        }
815
816    }
817
818    public class TestModel extends OnlineSectioningModel {
819        public TestModel(DataProperties config) {
820            super(config);
821        }
822
823        @Override
824        public Map<String, String> getExtendedInfo(Assignment<Request, Enrollment> assignment) {
825            Map<String, String> ret = super.getExtendedInfo(assignment);
826            for (Map.Entry<String, Counter> e : iCounters.entrySet())
827                ret.put(e.getKey(), e.getValue().toString());
828            ret.put("Weighting model",
829                    (model().getProperties().getPropertyBoolean("StudentWeights.MultiCriteria", true) ? "multi-criteria " : "") +
830                    (model().getProperties().getPropertyBoolean("StudentWeights.PriorityWeighting", true) ? "priority" : "equal"));
831            ret.put("B&B time limit", model().getProperties().getPropertyInt("Neighbour.BranchAndBoundTimeout", 1000) + " ms");
832            if (iSuggestions) {
833                ret.put("Suggestion time limit", model().getProperties().getPropertyInt("Suggestions.Timeout", 1000) + " ms");
834            }
835            return ret;
836        }
837    }
838
839    private static class RequestSectionPair {
840        private Request iRequest;
841        private Section iSection;
842
843        RequestSectionPair(Request request, Section section) {
844            iRequest = request;
845            iSection = section;
846        }
847
848        Request getRequest() {
849            return iRequest;
850        }
851
852        Section getSection() {
853            return iSection;
854        }
855    }
856
857    private void stats(File input) throws IOException {
858        File file = new File(input.getParentFile(), "stats.csv");
859        DecimalFormat df = new DecimalFormat("0.0000");
860        boolean ex = file.exists();
861        PrintWriter pw = new PrintWriter(new FileWriter(file, true));
862        if (!ex) {
863            pw.println("Input File,Run Time [m],Model,Sort,Over Expected,Not Assigned,Disb. Sections [%],Distance Confs.,Time Confs. [m],"
864                    + "CPU Assignment [ms],Has Suggestions [%],Nbr Suggestions,Acceptance [%],CPU Suggestions [ms]");
865        }
866        pw.print(input.getName() + ",");
867        pw.print(df.format(get("[T] Run Time [m]").sum()) + ",");
868        pw.print(model().getProperties().getPropertyBoolean("StudentWeights.MultiCriteria", true) ? "multi-criteria " : "");
869        pw.print(model().getProperties().getPropertyBoolean("StudentWeights.PriorityWeighting", true) ? "priority" : "equal");
870        pw.print(iSuggestions ? " with suggestions" : "");
871        pw.print(",");
872        pw.print(System.getProperty("sort", "shuffle") + ",");
873        pw.print("\"" + model().getOverExpectedCriterion() + "\",");
874
875        pw.print(get("[A] Not Assigned").sum() + ",");
876        pw.print(df.format(getPercDisbalancedSections(assignment(), 0.1)) + ",");
877        pw.print(df.format(((double) model().getDistanceConflict().getTotalNrConflicts(assignment())) / model().getStudents().size()) + ",");
878        pw.print(df.format(5.0 * model().getTimeOverlaps().getTotalNrConflicts(assignment()) / model().getStudents().size()) + ",");
879        pw.print(df.format(get("[C] CPU Time").avg()) + ",");
880        if (iSuggestions) {
881            pw.print(df.format(get("[S] Probability that a class has suggestions [%]").avg()) + ",");
882            pw.print(df.format(get("[S] Avg. # of suggestions").avg()) + ",");
883            pw.print(df.format(get("[S] Suggestion acceptance rate [%]").avg()) + ",");
884            pw.print(df.format(get("[S] Suggestion CPU Time").avg()));
885        }
886        pw.println();
887
888        pw.flush();
889        pw.close();
890    }
891
892    public static void main(String[] args) {
893        try {
894            System.setProperty("jprof", "cpu");
895            BasicConfigurator.configure();
896
897            DataProperties cfg = new DataProperties();
898            cfg.setProperty("Neighbour.BranchAndBoundTimeout", "5000");
899            cfg.setProperty("Suggestions.Timeout", "1000");
900            cfg.setProperty("Extensions.Classes", DistanceConflict.class.getName() + ";" + TimeOverlapsCounter.class.getName());
901            cfg.setProperty("StudentWeights.Class", StudentSchedulingAssistantWeights.class.getName());
902            cfg.setProperty("StudentWeights.PriorityWeighting", "true");
903            cfg.setProperty("StudentWeights.LeftoverSpread", "true");
904            cfg.setProperty("StudentWeights.BalancingFactor", "0.0");
905            cfg.setProperty("Reservation.CanAssignOverTheLimit", "true");
906            cfg.setProperty("Distances.Ellipsoid", DistanceMetric.Ellipsoid.WGS84.name());
907            cfg.setProperty("StudentWeights.MultiCriteria", "true");
908            cfg.setProperty("CourseRequest.SameTimePrecise", "true");
909
910            cfg.setProperty("log4j.rootLogger", "INFO, A1");
911            cfg.setProperty("log4j.appender.A1", "org.apache.log4j.ConsoleAppender");
912            cfg.setProperty("log4j.appender.A1.layout", "org.apache.log4j.PatternLayout");
913            cfg.setProperty("log4j.appender.A1.layout.ConversionPattern", "%-5p %c{2}: %m%n");
914            cfg.setProperty("log4j.logger.org.hibernate", "INFO");
915            cfg.setProperty("log4j.logger.org.hibernate.cfg", "WARN");
916            cfg.setProperty("log4j.logger.org.hibernate.cache.EhCacheProvider", "ERROR");
917            cfg.setProperty("log4j.logger.org.unitime.commons.hibernate", "INFO");
918            cfg.setProperty("log4j.logger.net", "INFO");
919
920            cfg.setProperty("Xml.LoadBest", "false");
921            cfg.setProperty("Xml.LoadCurrent", "false");
922
923            cfg.putAll(System.getProperties());
924
925            PropertyConfigurator.configure(cfg);
926
927            final Test test = new Test(cfg);
928
929            final File input = new File(args[0]);
930            StudentSectioningXMLLoader loader = new StudentSectioningXMLLoader(test.model(), test.assignment());
931            loader.setInputFile(input);
932            loader.load();
933
934            test.run();
935
936            Solver<Request, Enrollment> s = new Solver<Request, Enrollment>(cfg);
937            s.setInitalSolution(test.model());
938            StudentSectioningXMLSaver saver = new StudentSectioningXMLSaver(s);
939            File output = new File(input.getParentFile(), input.getName().substring(0, input.getName().lastIndexOf('.')) +
940                    "-" + cfg.getProperty("run", "r0") + ".xml");
941            saver.save(output);
942
943            test.stats(input);
944        } catch (Exception e) {
945            sLog.error("Test failed: " + e.getMessage(), e);
946        }
947    }
948
949    private static class Counter {
950        private double iTotal = 0.0, iMin = 0.0, iMax = 0.0, iTotalSquare = 0.0;
951        private int iCount = 0;
952
953        void inc(double value) {
954            if (iCount == 0) {
955                iTotal = value;
956                iMin = value;
957                iMax = value;
958                iTotalSquare = value * value;
959            } else {
960                iTotal += value;
961                iMin = Math.min(iMin, value);
962                iMax = Math.max(iMax, value);
963                iTotalSquare += value * value;
964            }
965            iCount++;
966        }
967
968        int count() {
969            return iCount;
970        }
971
972        double sum() {
973            return iTotal;
974        }
975
976        double min() {
977            return iMin;
978        }
979
980        double max() {
981            return iMax;
982        }
983
984        double rms() {
985            return (iCount == 0 ? 0.0 : Math.sqrt(iTotalSquare / iCount));
986        }
987
988        double avg() {
989            return (iCount == 0 ? 0.0 : iTotal / iCount);
990        }
991
992        @Override
993        public String toString() {
994            return sDF.format(sum()) + " (min: " + sDF.format(min()) + ", max: " + sDF.format(max()) +
995                    ", avg: " + sDF.format(avg()) + ", rms: " + sDF.format(rms()) + ", cnt: " + count() + ")";
996        }
997    }
998
999}