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