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