001package org.cpsolver.coursett;
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.Collection;
010import java.util.Date;
011import java.util.HashSet;
012import java.util.HashMap;
013import java.util.List;
014import java.util.Locale;
015import java.util.Map;
016import java.util.TreeSet;
017
018import org.apache.log4j.ConsoleAppender;
019import org.apache.log4j.FileAppender;
020import org.apache.log4j.Level;
021import org.apache.log4j.Logger;
022import org.apache.log4j.PatternLayout;
023import org.cpsolver.coursett.constraint.DepartmentSpreadConstraint;
024import org.cpsolver.coursett.constraint.GroupConstraint;
025import org.cpsolver.coursett.constraint.InstructorConstraint;
026import org.cpsolver.coursett.constraint.JenrlConstraint;
027import org.cpsolver.coursett.constraint.RoomConstraint;
028import org.cpsolver.coursett.constraint.SpreadConstraint;
029import org.cpsolver.coursett.criteria.BackToBackInstructorPreferences;
030import org.cpsolver.coursett.criteria.BrokenTimePatterns;
031import org.cpsolver.coursett.criteria.DepartmentBalancingPenalty;
032import org.cpsolver.coursett.criteria.DistributionPreferences;
033import org.cpsolver.coursett.criteria.Perturbations;
034import org.cpsolver.coursett.criteria.RoomPreferences;
035import org.cpsolver.coursett.criteria.SameSubpartBalancingPenalty;
036import org.cpsolver.coursett.criteria.StudentCommittedConflict;
037import org.cpsolver.coursett.criteria.StudentConflict;
038import org.cpsolver.coursett.criteria.StudentDistanceConflict;
039import org.cpsolver.coursett.criteria.StudentHardConflict;
040import org.cpsolver.coursett.criteria.TimePreferences;
041import org.cpsolver.coursett.criteria.TooBigRooms;
042import org.cpsolver.coursett.criteria.UselessHalfHours;
043import org.cpsolver.coursett.heuristics.UniversalPerturbationsCounter;
044import org.cpsolver.coursett.model.Lecture;
045import org.cpsolver.coursett.model.Placement;
046import org.cpsolver.coursett.model.RoomLocation;
047import org.cpsolver.coursett.model.Student;
048import org.cpsolver.coursett.model.TimeLocation;
049import org.cpsolver.coursett.model.TimetableModel;
050import org.cpsolver.ifs.assignment.Assignment;
051import org.cpsolver.ifs.assignment.DefaultParallelAssignment;
052import org.cpsolver.ifs.assignment.DefaultSingleAssignment;
053import org.cpsolver.ifs.extension.ConflictStatistics;
054import org.cpsolver.ifs.extension.Extension;
055import org.cpsolver.ifs.extension.MacPropagation;
056import org.cpsolver.ifs.model.Constraint;
057import org.cpsolver.ifs.solution.Solution;
058import org.cpsolver.ifs.solution.SolutionListener;
059import org.cpsolver.ifs.solver.ParallelSolver;
060import org.cpsolver.ifs.solver.Solver;
061import org.cpsolver.ifs.util.DataProperties;
062import org.cpsolver.ifs.util.Progress;
063import org.cpsolver.ifs.util.ProgressWriter;
064import org.cpsolver.ifs.util.ToolBox;
065
066
067/**
068 * A main class for running of the solver from command line. <br>
069 * <br>
070 * Usage:<br>
071 * java -Xmx1024m -jar coursett1.1.jar config.properties [input_file]
072 * [output_folder]<br>
073 * <br>
074 * See http://www.unitime.org for example configuration files and banchmark data
075 * sets.<br>
076 * <br>
077 * 
078 * The test does the following steps:
079 * <ul>
080 * <li>Provided property file is loaded (see {@link DataProperties}).
081 * <li>Output folder is created (General.Output property) and loggings is setup
082 * (using log4j).
083 * <li>Input data are loaded (calling {@link TimetableLoader#load()}).
084 * <li>Solver is executed (see {@link Solver}).
085 * <li>Resultant solution is saved (calling {@link TimetableSaver#save()}, when
086 * General.Save property is set to true.
087 * </ul>
088 * Also, a log and a CSV (comma separated text file) is created in the output
089 * folder.
090 * 
091 * @version CourseTT 1.3 (University Course Timetabling)<br>
092 *          Copyright (C) 2006 - 2014 Tomas Muller<br>
093 *          <a href="mailto:muller@unitime.org">muller@unitime.org</a><br>
094 *          <a href="http://muller.unitime.org">http://muller.unitime.org</a><br>
095 * <br>
096 *          This library is free software; you can redistribute it and/or modify
097 *          it under the terms of the GNU Lesser General Public License as
098 *          published by the Free Software Foundation; either version 3 of the
099 *          License, or (at your option) any later version. <br>
100 * <br>
101 *          This library is distributed in the hope that it will be useful, but
102 *          WITHOUT ANY WARRANTY; without even the implied warranty of
103 *          MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
104 *          Lesser General Public License for more details. <br>
105 * <br>
106 *          You should have received a copy of the GNU Lesser General Public
107 *          License along with this library; if not see
108 *          <a href='http://www.gnu.org/licenses/'>http://www.gnu.org/licenses/</a>.
109 */
110
111public class Test implements SolutionListener<Lecture, Placement> {
112    private static java.text.SimpleDateFormat sDateFormat = new java.text.SimpleDateFormat("yyMMdd_HHmmss",
113            java.util.Locale.US);
114    private static java.text.DecimalFormat sDoubleFormat = new java.text.DecimalFormat("0.000",
115            new java.text.DecimalFormatSymbols(Locale.US));
116    private static org.apache.log4j.Logger sLogger = org.apache.log4j.Logger.getLogger(Test.class);
117
118    private PrintWriter iCSVFile = null;
119
120    private MacPropagation<Lecture, Placement> iProp = null;
121    private ConflictStatistics<Lecture, Placement> iStat = null;
122    private int iLastNotified = -1;
123
124    private boolean initialized = false;
125    private Solver<Lecture, Placement> iSolver = null;
126
127    /** Current version 
128     * @return version string
129     **/
130    public static String getVersionString() {
131        return "IFS Timetable Solver v" + Constants.getVersion() + " build" + Constants.getBuildNumber() + ", "
132                + Constants.getReleaseDate();
133    }
134
135    /** Solver initialization 
136     * @param solver current solver
137     **/
138    public void init(Solver<Lecture, Placement> solver) {
139        iSolver = solver;
140        solver.currentSolution().addSolutionListener(this);
141    }
142    
143    /**
144     * Setup log4j logging
145     * 
146     * @param logFile  log file
147     * @param debug true if debug messages should be logged (use -Ddebug=true to enable debug message)
148     */
149    public static void setupLogging(File logFile, boolean debug) {
150        Logger root = Logger.getRootLogger();
151        ConsoleAppender console = new ConsoleAppender(new PatternLayout("[%t] %m%n"));
152        console.setThreshold(Level.INFO);
153        root.addAppender(console);
154        if (logFile != null) {
155            try {
156                FileAppender file = new FileAppender(new PatternLayout("%d{dd-MMM-yy HH:mm:ss.SSS} [%t] %-5p %c{2}> %m%n"), logFile.getPath(), false);
157                file.setThreshold(Level.DEBUG);
158                root.addAppender(file);
159            } catch (IOException e) {
160                sLogger.fatal("Unable to configure logging, reason: " + e.getMessage(), e);
161            }
162        }
163        if (!debug)
164            root.setLevel(Level.INFO);
165    }
166
167    /**
168     * Return name of the class that is used for loading the data. This class
169     * needs to extend class {@link TimetableLoader}. It can be also defined in
170     * configuration, using TimetableLoader property.
171     **/
172    private String getTimetableLoaderClass(DataProperties properties) {
173        String loader = properties.getProperty("TimetableLoader");
174        if (loader != null)
175            return loader;
176        if (properties.getPropertyInt("General.InputVersion", -1) >= 0)
177            return "org.unitime.timetable.solver.TimetableDatabaseLoader";
178        else
179            return "org.cpsolver.coursett.TimetableXMLLoader";
180    }
181
182    /**
183     * Return name of the class that is used for loading the data. This class
184     * needs to extend class {@link TimetableSaver}. It can be also defined in
185     * configuration, using TimetableSaver property.
186     **/
187    private String getTimetableSaverClass(DataProperties properties) {
188        String saver = properties.getProperty("TimetableSaver");
189        if (saver != null)
190            return saver;
191        if (properties.getPropertyInt("General.InputVersion", -1) >= 0)
192            return "org.unitime.timetable.solver.TimetableDatabaseSaver";
193        else
194            return "org.cpsolver.coursett.TimetableXMLSaver";
195    }
196
197    /**
198     * Solver Test
199     * 
200     * @param args
201     *            command line arguments
202     */
203    public Test(String[] args) {
204        try {
205            DataProperties properties = ToolBox.loadProperties(new java.io.File(args[0]));
206            properties.putAll(System.getProperties());
207            properties.setProperty("General.Output", properties.getProperty("General.Output", ".") + File.separator + sDateFormat.format(new Date()));
208            if (args.length > 1)
209                properties.setProperty("General.Input", args[1]);
210            if (args.length > 2)
211                properties.setProperty("General.Output", args[2] + File.separator + (sDateFormat.format(new Date())));
212            System.out.println("Output folder: " + properties.getProperty("General.Output"));
213            File outDir = new File(properties.getProperty("General.Output", "."));
214            outDir.mkdirs();
215            setupLogging(new File(outDir, "debug.log"), "true".equals(System.getProperty("debug", "false")));
216
217            TimetableModel model = new TimetableModel(properties);
218            int nrSolvers = properties.getPropertyInt("Parallel.NrSolvers", 1);
219            Assignment<Lecture, Placement> assignment = (nrSolvers <= 1 ? new DefaultSingleAssignment<Lecture, Placement>() : new DefaultParallelAssignment<Lecture, Placement>());
220            Progress.getInstance(model).addProgressListener(new ProgressWriter(System.out));
221            Solver<Lecture, Placement> solver = (nrSolvers == 1 ? new Solver<Lecture, Placement>(properties) : new ParallelSolver<Lecture, Placement>(properties));
222
223            TimetableLoader loader = (TimetableLoader) Class.forName(getTimetableLoaderClass(properties))
224                    .getConstructor(new Class[] { TimetableModel.class, Assignment.class }).newInstance(new Object[] { model, assignment });
225            loader.load();
226
227            solver.setInitalSolution(new Solution<Lecture, Placement>(model, assignment));
228            init(solver);
229
230            iCSVFile = new PrintWriter(new FileWriter(outDir.toString() + File.separator + "stat.csv"));
231            String colSeparator = ";";
232            iCSVFile.println("Assigned"
233                    + colSeparator
234                    + "Assigned[%]"
235                    + colSeparator
236                    + "Time[min]"
237                    + colSeparator
238                    + "Iter"
239                    + colSeparator
240                    + "IterYield[%]"
241                    + colSeparator
242                    + "Speed[it/s]"
243                    + colSeparator
244                    + "AddedPert"
245                    + colSeparator
246                    + "AddedPert[%]"
247                    + colSeparator
248                    + "HardStudentConf"
249                    + colSeparator
250                    + "StudentConf"
251                    + colSeparator
252                    + "DistStudentConf"
253                    + colSeparator
254                    + "CommitStudentConf"
255                    + colSeparator
256                    + "TimePref"
257                    + colSeparator
258                    + "RoomPref"
259                    + colSeparator
260                    + "DistInstrPref"
261                    + colSeparator
262                    + "GrConstPref"
263                    + colSeparator
264                    + "UselessHalfHours"
265                    + colSeparator
266                    + "BrokenTimePat"
267                    + colSeparator
268                    + "TooBigRooms"
269                    + (iProp != null ? colSeparator + "GoodVars" + colSeparator + "GoodVars[%]" + colSeparator
270                            + "GoodVals" + colSeparator + "GoodVals[%]" : ""));
271            iCSVFile.flush();
272            
273            Runtime.getRuntime().addShutdownHook(new ShutdownHook(solver));
274
275            solver.start();
276            try {
277                solver.getSolverThread().join();
278            } catch (InterruptedException e) {
279            }
280        } catch (Throwable t) {
281            sLogger.error("Test failed.", t);
282        }
283    }
284
285    public static void main(String[] args) {
286        new Test(args);
287    }
288
289    @Override
290    public void bestCleared(Solution<Lecture, Placement> solution) {
291    }
292
293    @Override
294    public void bestRestored(Solution<Lecture, Placement> solution) {
295    }
296
297    @Override
298    public void bestSaved(Solution<Lecture, Placement> solution) {
299        notify(solution);
300        if (sLogger.isInfoEnabled())
301            sLogger.info("**BEST[" + solution.getIteration() + "]** " + ((TimetableModel)solution.getModel()).toString(solution.getAssignment()) +
302                    (solution.getFailedIterations() > 0 ? ", F:" + sDoubleFormat.format(100.0 * solution.getFailedIterations() / solution.getIteration()) + "%" : ""));
303    }
304
305    @Override
306    public void getInfo(Solution<Lecture, Placement> solution, Map<String, String> info) {
307    }
308
309    @Override
310    public void getInfo(Solution<Lecture, Placement> solution, Map<String, String> info, Collection<Lecture> variables) {
311    }
312
313    @Override
314    public void solutionUpdated(Solution<Lecture, Placement> solution) {
315        if (!initialized) {
316            for (Extension<Lecture, Placement> extension : iSolver.getExtensions()) {
317                if (MacPropagation.class.isInstance(extension))
318                    iProp = (MacPropagation<Lecture, Placement>) extension;
319                if (ConflictStatistics.class.isInstance(extension)) {
320                    iStat = (ConflictStatistics<Lecture, Placement>) extension;
321                }
322            }
323        }
324    }
325
326    /** Add a line into the output CSV file when a enw best solution is found. 
327     * @param solution current solution
328     **/
329    public void notify(Solution<Lecture, Placement> solution) {
330        String colSeparator = ";";
331        Assignment<Lecture, Placement> assignment = solution.getAssignment();
332        if (assignment.nrAssignedVariables() < solution.getModel().countVariables() && iLastNotified == assignment.nrAssignedVariables())
333            return;
334        iLastNotified = assignment.nrAssignedVariables();
335        if (iCSVFile != null) {
336            TimetableModel model = (TimetableModel) solution.getModel();
337            iCSVFile.print(model.variables().size() - model.nrUnassignedVariables(assignment));
338            iCSVFile.print(colSeparator);
339            iCSVFile.print(sDoubleFormat.format(100.0 * assignment.nrAssignedVariables() / model.variables().size()));
340            iCSVFile.print(colSeparator);
341            iCSVFile.print(sDoubleFormat.format((solution.getTime()) / 60.0));
342            iCSVFile.print(colSeparator);
343            iCSVFile.print(solution.getIteration());
344            iCSVFile.print(colSeparator);
345            iCSVFile.print(sDoubleFormat.format(100.0 * assignment.nrAssignedVariables() / solution.getIteration()));
346            iCSVFile.print(colSeparator);
347            iCSVFile.print(sDoubleFormat.format((solution.getIteration()) / solution.getTime()));
348            iCSVFile.print(colSeparator);
349            iCSVFile.print(model.perturbVariables(assignment).size());
350            iCSVFile.print(colSeparator);
351            iCSVFile.print(sDoubleFormat.format(100.0 * model.perturbVariables(assignment).size() / model.variables().size()));
352            iCSVFile.print(colSeparator);
353            iCSVFile.print(Math.round(solution.getModel().getCriterion(StudentHardConflict.class).getValue(assignment)));
354            iCSVFile.print(colSeparator);
355            iCSVFile.print(Math.round(solution.getModel().getCriterion(StudentConflict.class).getValue(assignment)));
356            iCSVFile.print(colSeparator);
357            iCSVFile.print(Math.round(solution.getModel().getCriterion(StudentDistanceConflict.class).getValue(assignment)));
358            iCSVFile.print(colSeparator);
359            iCSVFile.print(Math.round(solution.getModel().getCriterion(StudentCommittedConflict.class).getValue(assignment)));
360            iCSVFile.print(colSeparator);
361            iCSVFile.print(sDoubleFormat.format(solution.getModel().getCriterion(TimePreferences.class).getValue(assignment)));
362            iCSVFile.print(colSeparator);
363            iCSVFile.print(Math.round(solution.getModel().getCriterion(RoomPreferences.class).getValue(assignment)));
364            iCSVFile.print(colSeparator);
365            iCSVFile.print(Math.round(solution.getModel().getCriterion(BackToBackInstructorPreferences.class).getValue(assignment)));
366            iCSVFile.print(colSeparator);
367            iCSVFile.print(Math.round(solution.getModel().getCriterion(DistributionPreferences.class).getValue(assignment)));
368            iCSVFile.print(colSeparator);
369            iCSVFile.print(Math.round(solution.getModel().getCriterion(UselessHalfHours.class).getValue(assignment)));
370            iCSVFile.print(colSeparator);
371            iCSVFile.print(Math.round(solution.getModel().getCriterion(BrokenTimePatterns.class).getValue(assignment)));
372            iCSVFile.print(colSeparator);
373            iCSVFile.print(Math.round(solution.getModel().getCriterion(TooBigRooms.class).getValue(assignment)));
374            if (iProp != null) {
375                if (solution.getModel().nrUnassignedVariables(assignment) > 0) {
376                    int goodVariables = 0;
377                    long goodValues = 0;
378                    long allValues = 0;
379                    for (Lecture variable : ((TimetableModel) solution.getModel()).unassignedVariables(assignment)) {
380                        goodValues += iProp.goodValues(assignment, variable).size();
381                        allValues += variable.values(solution.getAssignment()).size();
382                        if (!iProp.goodValues(assignment, variable).isEmpty())
383                            goodVariables++;
384                    }
385                    iCSVFile.print(colSeparator);
386                    iCSVFile.print(goodVariables);
387                    iCSVFile.print(colSeparator);
388                    iCSVFile.print(sDoubleFormat.format(100.0 * goodVariables / solution.getModel().nrUnassignedVariables(assignment)));
389                    iCSVFile.print(colSeparator);
390                    iCSVFile.print(goodValues);
391                    iCSVFile.print(colSeparator);
392                    iCSVFile.print(sDoubleFormat.format(100.0 * goodValues / allValues));
393                } else {
394                    iCSVFile.print(colSeparator);
395                    iCSVFile.print(colSeparator);
396                    iCSVFile.print(colSeparator);
397                    iCSVFile.print(colSeparator);
398                }
399            }
400            iCSVFile.println();
401            iCSVFile.flush();
402        }
403    }
404
405    /** Print room utilization 
406     * @param pw writer
407     * @param model problem model
408     * @param assignment current assignment
409     **/
410    public static void printRoomInfo(PrintWriter pw, TimetableModel model, Assignment<Lecture, Placement> assignment) {
411        pw.println("Room info:");
412        pw.println("id, name, size, used_day, used_total");
413        int firstDaySlot = model.getProperties().getPropertyInt("General.FirstDaySlot", Constants.DAY_SLOTS_FIRST);
414        int lastDaySlot = model.getProperties().getPropertyInt("General.LastDaySlot", Constants.DAY_SLOTS_LAST);
415        int firstWorkDay = model.getProperties().getPropertyInt("General.FirstWorkDay", 0);
416        int lastWorkDay = model.getProperties().getPropertyInt("General.LastWorkDay", Constants.NR_DAYS_WEEK - 1);
417        for (RoomConstraint rc : model.getRoomConstraints()) {
418            int used_day = 0;
419            int used_total = 0;
420            for (int day = firstWorkDay; day <= lastWorkDay; day++) {
421                for (int time = firstDaySlot; time <= lastDaySlot; time++) {
422                    if (!rc.getContext(assignment).getPlacements(day * Constants.SLOTS_PER_DAY + time).isEmpty())
423                        used_day++;
424                }
425            }
426            for (int day = 0; day < Constants.DAY_CODES.length; day++) {
427                for (int time = 0; time < Constants.SLOTS_PER_DAY; time++) {
428                    if (!rc.getContext(assignment).getPlacements(day * Constants.SLOTS_PER_DAY + time).isEmpty())
429                        used_total++;
430                }
431            }
432            pw.println(rc.getResourceId() + "," + rc.getName() + "," + rc.getCapacity() + "," + used_day + "," + used_total);
433        }
434    }
435
436    /** Class information 
437     * @param pw writer
438     * @param model problem model
439     **/
440    public static void printClassInfo(PrintWriter pw, TimetableModel model) {
441        pw.println("Class info:");
442        pw.println("id, name, min_class_limit, max_class_limit, room2limit_ratio, half_hours");
443        for (Lecture lecture : model.variables()) {
444            TimeLocation time = lecture.timeLocations().get(0);
445            pw.println(lecture.getClassId() + "," + lecture.getName() + "," + lecture.minClassLimit() + ","
446                    + lecture.maxClassLimit() + "," + lecture.roomToLimitRatio() + ","
447                    + (time.getNrSlotsPerMeeting() * time.getNrMeetings()));
448        }
449    }
450
451    /** Create info.txt with some more information about the problem 
452     * @param solution current solution
453     * @throws IOException an exception that may be thrown
454     **/
455    public static void printSomeStuff(Solution<Lecture, Placement> solution) throws IOException {
456        TimetableModel model = (TimetableModel) solution.getModel();
457        Assignment<Lecture, Placement> assignment = solution.getAssignment();
458        File outDir = new File(model.getProperties().getProperty("General.Output", "."));
459        PrintWriter pw = new PrintWriter(new FileWriter(outDir.toString() + File.separator + "info.txt"));
460        PrintWriter pwi = new PrintWriter(new FileWriter(outDir.toString() + File.separator + "info.csv"));
461        String name = new File(model.getProperties().getProperty("General.Input")).getName();
462        pwi.println("Instance," + name.substring(0, name.lastIndexOf('.')));
463        pw.println("Solution info: " + ToolBox.dict2string(solution.getInfo(), 1));
464        pw.println("Bounds: " + ToolBox.dict2string(model.getBounds(assignment), 1));
465        Map<String, String> info = solution.getInfo();
466        for (String key : new TreeSet<String>(info.keySet())) {
467            if (key.equals("Memory usage"))
468                continue;
469            if (key.equals("Iteration"))
470                continue;
471            if (key.equals("Time"))
472                continue;
473            String value = info.get(key);
474            if (value.indexOf(' ') > 0)
475                value = value.substring(0, value.indexOf(' '));
476            pwi.println(key + "," + value);
477        }
478        printRoomInfo(pw, model, assignment);
479        printClassInfo(pw, model);
480        long nrValues = 0;
481        long nrTimes = 0;
482        long nrRooms = 0;
483        double totalMaxNormTimePref = 0.0;
484        double totalMinNormTimePref = 0.0;
485        double totalNormTimePref = 0.0;
486        int totalMaxRoomPref = 0;
487        int totalMinRoomPref = 0;
488        int totalRoomPref = 0;
489        long nrStudentEnrls = 0;
490        long nrInevitableStudentConflicts = 0;
491        long nrJenrls = 0;
492        int nrHalfHours = 0;
493        int nrMeetings = 0;
494        int totalMinLimit = 0;
495        int totalMaxLimit = 0;
496        long nrReqRooms = 0;
497        int nrSingleValueVariables = 0;
498        int nrSingleTimeVariables = 0;
499        int nrSingleRoomVariables = 0;
500        long totalAvailableMinRoomSize = 0;
501        long totalAvailableMaxRoomSize = 0;
502        long totalRoomSize = 0;
503        long nrOneOrMoreRoomVariables = 0;
504        long nrOneRoomVariables = 0;
505        HashSet<Student> students = new HashSet<Student>();
506        HashSet<Long> offerings = new HashSet<Long>();
507        HashSet<Long> configs = new HashSet<Long>();
508        HashSet<Long> subparts = new HashSet<Long>();
509        int[] sizeLimits = new int[] { 0, 25, 50, 75, 100, 150, 200, 400 };
510        int[] nrRoomsOfSize = new int[sizeLimits.length];
511        int[] minRoomOfSize = new int[sizeLimits.length];
512        int[] maxRoomOfSize = new int[sizeLimits.length];
513        int[] totalUsedSlots = new int[sizeLimits.length];
514        int[] totalUsedSeats = new int[sizeLimits.length];
515        int[] totalUsedSeats2 = new int[sizeLimits.length];
516        int firstDaySlot = model.getProperties().getPropertyInt("General.FirstDaySlot", Constants.DAY_SLOTS_FIRST);
517        int lastDaySlot = model.getProperties().getPropertyInt("General.LastDaySlot", Constants.DAY_SLOTS_LAST);
518        int firstWorkDay = model.getProperties().getPropertyInt("General.FirstWorkDay", 0);
519        int lastWorkDay = model.getProperties().getPropertyInt("General.LastWorkDay", Constants.NR_DAYS_WEEK - 1);
520        for (Lecture lect : model.variables()) {
521            if (lect.getConfiguration() != null) {
522                offerings.add(lect.getConfiguration().getOfferingId());
523                configs.add(lect.getConfiguration().getConfigId());
524            }
525            subparts.add(lect.getSchedulingSubpartId());
526            nrStudentEnrls += (lect.students() == null ? 0 : lect.students().size());
527            students.addAll(lect.students());
528            nrValues += lect.values(solution.getAssignment()).size();
529            nrReqRooms += lect.getNrRooms();
530            for (RoomLocation room: lect.roomLocations())
531                if (room.getPreference() < Constants.sPreferenceLevelProhibited / 2)
532                    nrRooms++;
533            for (TimeLocation time: lect.timeLocations())
534                if (time.getPreference() < Constants.sPreferenceLevelProhibited / 2)
535                    nrTimes ++;
536            totalMinLimit += lect.minClassLimit();
537            totalMaxLimit += lect.maxClassLimit();
538            if (!lect.values(solution.getAssignment()).isEmpty()) {
539                Placement p = lect.values(solution.getAssignment()).get(0);
540                nrMeetings += p.getTimeLocation().getNrMeetings();
541                nrHalfHours += p.getTimeLocation().getNrMeetings() * p.getTimeLocation().getNrSlotsPerMeeting();
542                totalMaxNormTimePref += lect.getMinMaxTimePreference()[1];
543                totalMinNormTimePref += lect.getMinMaxTimePreference()[0];
544                totalNormTimePref += Math.abs(lect.getMinMaxTimePreference()[1] - lect.getMinMaxTimePreference()[0]);
545                totalMaxRoomPref += lect.getMinMaxRoomPreference()[1];
546                totalMinRoomPref += lect.getMinMaxRoomPreference()[0];
547                totalRoomPref += Math.abs(lect.getMinMaxRoomPreference()[1] - lect.getMinMaxRoomPreference()[0]);
548                TimeLocation time = p.getTimeLocation();
549                boolean hasRoomConstraint = false;
550                for (RoomLocation roomLocation : lect.roomLocations()) {
551                    if (roomLocation.getRoomConstraint().getConstraint())
552                        hasRoomConstraint = true;
553                }
554                if (hasRoomConstraint && lect.getNrRooms() > 0) {
555                    for (int d = firstWorkDay; d <= lastWorkDay; d++) {
556                        if ((time.getDayCode() & Constants.DAY_CODES[d]) == 0)
557                            continue;
558                        for (int t = Math.max(time.getStartSlot(), firstDaySlot); t <= Math.min(time.getStartSlot() + time.getLength() - 1, lastDaySlot); t++) {
559                            for (int l = 0; l < sizeLimits.length; l++) {
560                                if (sizeLimits[l] <= lect.minRoomSize()) {
561                                    totalUsedSlots[l] += lect.getNrRooms();
562                                    totalUsedSeats[l] += lect.classLimit(assignment);
563                                    totalUsedSeats2[l] += lect.minRoomSize() * lect.getNrRooms();
564                                }
565                            }
566                        }
567                    }
568                }
569            }
570            if (lect.values(solution.getAssignment()).size() == 1) {
571                nrSingleValueVariables++;
572            }
573            if (lect.timeLocations().size() == 1) {
574                nrSingleTimeVariables++;
575            }
576            if (lect.roomLocations().size() == 1) {
577                nrSingleRoomVariables++;
578            }
579            if (lect.getNrRooms() == 1) {
580                nrOneRoomVariables++;
581            }
582            if (lect.getNrRooms() > 0) {
583                nrOneOrMoreRoomVariables++;
584            }
585            if (!lect.roomLocations().isEmpty()) {
586                int minRoomSize = Integer.MAX_VALUE;
587                int maxRoomSize = Integer.MIN_VALUE;
588                for (RoomLocation rl : lect.roomLocations()) {
589                    minRoomSize = Math.min(minRoomSize, rl.getRoomSize());
590                    maxRoomSize = Math.max(maxRoomSize, rl.getRoomSize());
591                    totalRoomSize += rl.getRoomSize();
592                }
593                totalAvailableMinRoomSize += minRoomSize;
594                totalAvailableMaxRoomSize += maxRoomSize;
595            }
596        }
597        for (JenrlConstraint jenrl : model.getJenrlConstraints()) {
598            nrJenrls += jenrl.getJenrl();
599            if ((jenrl.first()).timeLocations().size() == 1 && (jenrl.second()).timeLocations().size() == 1) {
600                TimeLocation t1 = jenrl.first().timeLocations().get(0);
601                TimeLocation t2 = jenrl.second().timeLocations().get(0);
602                if (t1.hasIntersection(t2)) {
603                    nrInevitableStudentConflicts += jenrl.getJenrl();
604                    pw.println("Inevitable " + jenrl.getJenrl() + " student conflicts between " + jenrl.first() + " "
605                            + t1 + " and " + jenrl.second() + " " + t2);
606                } else if (jenrl.first().values(solution.getAssignment()).size() == 1 && jenrl.second().values(solution.getAssignment()).size() == 1) {
607                    Placement p1 = jenrl.first().values(solution.getAssignment()).get(0);
608                    Placement p2 = jenrl.second().values(solution.getAssignment()).get(0);
609                    if (JenrlConstraint.isInConflict(p1, p2, ((TimetableModel)p1.variable().getModel()).getDistanceMetric())) {
610                        nrInevitableStudentConflicts += jenrl.getJenrl();
611                        pw.println("Inevitable " + jenrl.getJenrl()
612                                + (p1.getTimeLocation().hasIntersection(p2.getTimeLocation()) ? "" : " distance")
613                                + " student conflicts between " + p1 + " and " + p2);
614                    }
615                }
616            }
617        }
618        int totalCommitedPlacements = 0;
619        for (Student student : students) {
620            if (student.getCommitedPlacements() != null)
621                totalCommitedPlacements += student.getCommitedPlacements().size();
622        }
623        pw.println("Total number of classes: " + model.variables().size());
624        pwi.println("Number of classes," + model.variables().size());
625        pw.println("Total number of instructional offerings: " + offerings.size() + " ("
626                + sDoubleFormat.format(100.0 * offerings.size() / model.variables().size()) + "%)");
627        // pwi.println("Number of instructional offerings,"+offerings.size());
628        pw.println("Total number of configurations: " + configs.size() + " ("
629                + sDoubleFormat.format(100.0 * configs.size() / model.variables().size()) + "%)");
630        pw.println("Total number of scheduling subparts: " + subparts.size() + " ("
631                + sDoubleFormat.format(100.0 * subparts.size() / model.variables().size()) + "%)");
632        // pwi.println("Number of scheduling subparts,"+subparts.size());
633        pw.println("Average number classes per subpart: "
634                + sDoubleFormat.format(1.0 * model.variables().size() / subparts.size()));
635        pwi.println("Avg. classes per instruction,"
636                + sDoubleFormat.format(1.0 * model.variables().size() / subparts.size()));
637        pw.println("Average number classes per config: "
638                + sDoubleFormat.format(1.0 * model.variables().size() / configs.size()));
639        pw.println("Average number classes per offering: "
640                + sDoubleFormat.format(1.0 * model.variables().size() / offerings.size()));
641        pw.println("Total number of classes with only one value: " + nrSingleValueVariables + " ("
642                + sDoubleFormat.format(100.0 * nrSingleValueVariables / model.variables().size()) + "%)");
643        pw.println("Total number of classes with only one time: " + nrSingleTimeVariables + " ("
644                + sDoubleFormat.format(100.0 * nrSingleTimeVariables / model.variables().size()) + "%)");
645        pw.println("Total number of classes with only one room: " + nrSingleRoomVariables + " ("
646                + sDoubleFormat.format(100.0 * nrSingleRoomVariables / model.variables().size()) + "%)");
647        pwi.println("Classes with single value," + nrSingleValueVariables);
648        // pwi.println("Classes with only one time/room,"+nrSingleTimeVariables+"/"+nrSingleRoomVariables);
649        pw.println("Total number of classes requesting no room: "
650                + (model.variables().size() - nrOneOrMoreRoomVariables)
651                + " ("
652                + sDoubleFormat.format(100.0 * (model.variables().size() - nrOneOrMoreRoomVariables)
653                        / model.variables().size()) + "%)");
654        pw.println("Total number of classes requesting one room: " + nrOneRoomVariables + " ("
655                + sDoubleFormat.format(100.0 * nrOneRoomVariables / model.variables().size()) + "%)");
656        pw.println("Total number of classes requesting one or more rooms: " + nrOneOrMoreRoomVariables + " ("
657                + sDoubleFormat.format(100.0 * nrOneOrMoreRoomVariables / model.variables().size()) + "%)");
658        // pwi.println("% classes requesting no room,"+sDoubleFormat.format(100.0*(model.variables().size()-nrOneOrMoreRoomVariables)/model.variables().size())+"%");
659        // pwi.println("% classes requesting one room,"+sDoubleFormat.format(100.0*nrOneRoomVariables/model.variables().size())+"%");
660        // pwi.println("% classes requesting two or more rooms,"+sDoubleFormat.format(100.0*(nrOneOrMoreRoomVariables-nrOneRoomVariables)/model.variables().size())+"%");
661        pw.println("Average number of requested rooms: "
662                + sDoubleFormat.format(1.0 * nrReqRooms / model.variables().size()));
663        pw.println("Average minimal class limit: "
664                + sDoubleFormat.format(1.0 * totalMinLimit / model.variables().size()));
665        pw.println("Average maximal class limit: "
666                + sDoubleFormat.format(1.0 * totalMaxLimit / model.variables().size()));
667        // pwi.println("Average class limit,"+sDoubleFormat.format(1.0*(totalMinLimit+totalMaxLimit)/(2*model.variables().size())));
668        pw.println("Average number of placements: " + sDoubleFormat.format(1.0 * nrValues / model.variables().size()));
669        // pwi.println("Average domain size,"+sDoubleFormat.format(1.0*nrValues/model.variables().size()));
670        pwi.println("Avg. domain size," + sDoubleFormat.format(1.0 * nrValues / model.variables().size()));
671        pw.println("Average number of time locations: "
672                + sDoubleFormat.format(1.0 * nrTimes / model.variables().size()));
673        pwi.println("Avg. number of avail. times/rooms,"
674                + sDoubleFormat.format(1.0 * nrTimes / model.variables().size()) + "/"
675                + sDoubleFormat.format(1.0 * nrRooms / model.variables().size()));
676        pw.println("Average number of room locations: "
677                + sDoubleFormat.format(1.0 * nrRooms / model.variables().size()));
678        pw.println("Average minimal requested room size: "
679                + sDoubleFormat.format(1.0 * totalAvailableMinRoomSize / nrOneOrMoreRoomVariables));
680        pw.println("Average maximal requested room size: "
681                + sDoubleFormat.format(1.0 * totalAvailableMaxRoomSize / nrOneOrMoreRoomVariables));
682        pw.println("Average requested room sizes: " + sDoubleFormat.format(1.0 * totalRoomSize / nrRooms));
683        pwi.println("Average requested room size," + sDoubleFormat.format(1.0 * totalRoomSize / nrRooms));
684        pw.println("Average maximum normalized time preference: "
685                + sDoubleFormat.format(totalMaxNormTimePref / model.variables().size()));
686        pw.println("Average minimum normalized time preference: "
687                + sDoubleFormat.format(totalMinNormTimePref / model.variables().size()));
688        pw.println("Average normalized time preference,"
689                + sDoubleFormat.format(totalNormTimePref / model.variables().size()));
690        pw.println("Average maximum room preferences: "
691                + sDoubleFormat.format(1.0 * totalMaxRoomPref / nrOneOrMoreRoomVariables));
692        pw.println("Average minimum room preferences: "
693                + sDoubleFormat.format(1.0 * totalMinRoomPref / nrOneOrMoreRoomVariables));
694        pw.println("Average room preferences," + sDoubleFormat.format(1.0 * totalRoomPref / nrOneOrMoreRoomVariables));
695        pw.println("Total number of students:" + students.size());
696        pwi.println("Number of students," + students.size());
697        pwi.println("Number of inevitable student conflicts," + nrInevitableStudentConflicts);
698        pw.println("Total amount of student enrollments: " + nrStudentEnrls);
699        pwi.println("Number of student enrollments," + nrStudentEnrls);
700        pw.println("Total amount of joined enrollments: " + nrJenrls);
701        pwi.println("Number of joint student enrollments," + nrJenrls);
702        pw.println("Average number of students: "
703                + sDoubleFormat.format(1.0 * students.size() / model.variables().size()));
704        pw.println("Average number of enrollemnts (per student): "
705                + sDoubleFormat.format(1.0 * nrStudentEnrls / students.size()));
706        pwi.println("Avg. number of classes per student,"
707                + sDoubleFormat.format(1.0 * nrStudentEnrls / students.size()));
708        pwi.println("Avg. number of committed classes per student,"
709                + sDoubleFormat.format(1.0 * totalCommitedPlacements / students.size()));
710        pw.println("Total amount of inevitable student conflicts: " + nrInevitableStudentConflicts + " ("
711                + sDoubleFormat.format(100.0 * nrInevitableStudentConflicts / nrStudentEnrls) + "%)");
712        pw.println("Average number of meetings (per class): "
713                + sDoubleFormat.format(1.0 * nrMeetings / model.variables().size()));
714        pw.println("Average number of hours per class: "
715                + sDoubleFormat.format(1.0 * nrHalfHours / model.variables().size() / 12.0));
716        pwi.println("Avg. number of meetings per class,"
717                + sDoubleFormat.format(1.0 * nrMeetings / model.variables().size()));
718        pwi.println("Avg. number of hours per class,"
719                + sDoubleFormat.format(1.0 * nrHalfHours / model.variables().size() / 12.0));
720        int minRoomSize = Integer.MAX_VALUE;
721        int maxRoomSize = Integer.MIN_VALUE;
722        int nrDistancePairs = 0;
723        double maxRoomDistance = Double.MIN_VALUE;
724        double totalRoomDistance = 0.0;
725        int[] totalAvailableSlots = new int[sizeLimits.length];
726        int[] totalAvailableSeats = new int[sizeLimits.length];
727        int nrOfRooms = 0;
728        totalRoomSize = 0;
729        for (RoomConstraint rc : model.getRoomConstraints()) {
730            if (rc.variables().isEmpty()) continue;
731            nrOfRooms++;
732            minRoomSize = Math.min(minRoomSize, rc.getCapacity());
733            maxRoomSize = Math.max(maxRoomSize, rc.getCapacity());
734            for (int l = 0; l < sizeLimits.length; l++) {
735                if (sizeLimits[l] <= rc.getCapacity()
736                        && (l + 1 == sizeLimits.length || rc.getCapacity() < sizeLimits[l + 1])) {
737                    nrRoomsOfSize[l]++;
738                    if (minRoomOfSize[l] == 0)
739                        minRoomOfSize[l] = rc.getCapacity();
740                    else
741                        minRoomOfSize[l] = Math.min(minRoomOfSize[l], rc.getCapacity());
742                    if (maxRoomOfSize[l] == 0)
743                        maxRoomOfSize[l] = rc.getCapacity();
744                    else
745                        maxRoomOfSize[l] = Math.max(maxRoomOfSize[l], rc.getCapacity());
746                }
747            }
748            totalRoomSize += rc.getCapacity();
749            if (rc.getPosX() != null && rc.getPosY() != null) {
750                for (RoomConstraint rc2 : model.getRoomConstraints()) {
751                    if (rc2.getResourceId().compareTo(rc.getResourceId()) > 0 && rc2.getPosX() != null && rc2.getPosY() != null) {
752                        double distance = ((TimetableModel)solution.getModel()).getDistanceMetric().getDistanceInMinutes(rc.getId(), rc.getPosX(), rc.getPosY(), rc2.getId(), rc2.getPosX(), rc2.getPosY());
753                        totalRoomDistance += distance;
754                        nrDistancePairs++;
755                        maxRoomDistance = Math.max(maxRoomDistance, distance);
756                    }
757                }
758            }
759            for (int d = firstWorkDay; d <= lastWorkDay; d++) {
760                for (int t = firstDaySlot; t <= lastDaySlot; t++) {
761                    if (rc.isAvailable(d * Constants.SLOTS_PER_DAY + t)) {
762                        for (int l = 0; l < sizeLimits.length; l++) {
763                            if (sizeLimits[l] <= rc.getCapacity()) {
764                                totalAvailableSlots[l]++;
765                                totalAvailableSeats[l] += rc.getCapacity();
766                            }
767                        }
768                    }
769                }
770            }
771        }
772        pw.println("Total number of rooms: " + nrOfRooms);
773        pwi.println("Number of rooms," + nrOfRooms);
774        pw.println("Minimal room size: " + minRoomSize);
775        pw.println("Maximal room size: " + maxRoomSize);
776        pwi.println("Room size min/max," + minRoomSize + "/" + maxRoomSize);
777        pw.println("Average room size: "
778                + sDoubleFormat.format(1.0 * totalRoomSize / model.getRoomConstraints().size()));
779        pw.println("Maximal distance between two rooms: " + sDoubleFormat.format(maxRoomDistance));
780        pw.println("Average distance between two rooms: "
781                + sDoubleFormat.format(totalRoomDistance / nrDistancePairs));
782        pwi.println("Average distance between two rooms [min],"
783                + sDoubleFormat.format(totalRoomDistance / nrDistancePairs));
784        pwi.println("Maximal distance between two rooms [min]," + sDoubleFormat.format(maxRoomDistance));
785        for (int l = 0; l < sizeLimits.length; l++) {// sizeLimits.length;l++) {
786            pwi.println("\"Room frequency (size>=" + sizeLimits[l] + ", used/avaiable times)\","
787                    + sDoubleFormat.format(100.0 * totalUsedSlots[l] / totalAvailableSlots[l]) + "%");
788            pwi.println("\"Room utilization (size>=" + sizeLimits[l] + ", used/available seats)\","
789                    + sDoubleFormat.format(100.0 * totalUsedSeats[l] / totalAvailableSeats[l]) + "%");
790            pwi.println("\"Number of rooms (size>=" + sizeLimits[l] + ")\"," + nrRoomsOfSize[l]);
791            pwi.println("\"Min/max room size (size>=" + sizeLimits[l] + ")\"," + minRoomOfSize[l] + "-"
792                    + maxRoomOfSize[l]);
793            // pwi.println("\"Room utilization (size>="+sizeLimits[l]+", minRoomSize)\","+sDoubleFormat.format(100.0*totalUsedSeats2[l]/totalAvailableSeats[l])+"%");
794        }
795        pw.println("Average hours available: "
796                + sDoubleFormat.format(1.0 * totalAvailableSlots[0] / nrOfRooms / 12.0));
797        int totalInstructedClasses = 0;
798        for (InstructorConstraint ic : model.getInstructorConstraints()) {
799            totalInstructedClasses += ic.variables().size();
800        }
801        pw.println("Total number of instructors: " + model.getInstructorConstraints().size());
802        pwi.println("Number of instructors," + model.getInstructorConstraints().size());
803        pw.println("Total class-instructor assignments: " + totalInstructedClasses + " ("
804                + sDoubleFormat.format(100.0 * totalInstructedClasses / model.variables().size()) + "%)");
805        pwi.println("Number of class-instructor assignments," + totalInstructedClasses);
806        pw.println("Average classes per instructor: "
807                + sDoubleFormat.format(1.0 * totalInstructedClasses / model.getInstructorConstraints().size()));
808        pwi.println("Average classes per instructor,"
809                + sDoubleFormat.format(1.0 * totalInstructedClasses / model.getInstructorConstraints().size()));
810        // pw.println("Average hours available: "+sDoubleFormat.format(1.0*totalAvailableSlots/model.getInstructorConstraints().size()/12.0));
811        // pwi.println("Instructor availability [h],"+sDoubleFormat.format(1.0*totalAvailableSlots/model.getInstructorConstraints().size()/12.0));
812        int nrGroupConstraints = model.getGroupConstraints().size() + model.getSpreadConstraints().size();
813        int nrHardGroupConstraints = 0;
814        int nrVarsInGroupConstraints = 0;
815        for (GroupConstraint gc : model.getGroupConstraints()) {
816            if (gc.isHard())
817                nrHardGroupConstraints++;
818            nrVarsInGroupConstraints += gc.variables().size();
819        }
820        for (SpreadConstraint sc : model.getSpreadConstraints()) {
821            nrVarsInGroupConstraints += sc.variables().size();
822        }
823        pw.println("Total number of group constraints: " + nrGroupConstraints + " ("
824                + sDoubleFormat.format(100.0 * nrGroupConstraints / model.variables().size()) + "%)");
825        // pwi.println("Number of group constraints,"+nrGroupConstraints);
826        pw.println("Total number of hard group constraints: " + nrHardGroupConstraints + " ("
827                + sDoubleFormat.format(100.0 * nrHardGroupConstraints / model.variables().size()) + "%)");
828        // pwi.println("Number of hard group constraints,"+nrHardGroupConstraints);
829        pw.println("Average classes per group constraint: "
830                + sDoubleFormat.format(1.0 * nrVarsInGroupConstraints / nrGroupConstraints));
831        // pwi.println("Average classes per group constraint,"+sDoubleFormat.format(1.0*nrVarsInGroupConstraints/nrGroupConstraints));
832        pwi.println("Avg. number distribution constraints per class,"
833                + sDoubleFormat.format(1.0 * nrVarsInGroupConstraints / model.variables().size()));
834        pwi.println("Joint enrollment constraints," + model.getJenrlConstraints().size());
835        pw.flush();
836        pw.close();
837        pwi.flush();
838        pwi.close();
839    }
840
841    public static void saveOutputCSV(Solution<Lecture, Placement> s, File file) {
842        try {
843            DecimalFormat dx = new DecimalFormat("000");
844            PrintWriter w = new PrintWriter(new FileWriter(file));
845            TimetableModel m = (TimetableModel) s.getModel();
846            int firstDaySlot = m.getProperties().getPropertyInt("General.FirstDaySlot", Constants.DAY_SLOTS_FIRST);
847            int lastDaySlot = m.getProperties().getPropertyInt("General.LastDaySlot", Constants.DAY_SLOTS_LAST);
848            int firstWorkDay = m.getProperties().getPropertyInt("General.FirstWorkDay", 0);
849            int lastWorkDay = m.getProperties().getPropertyInt("General.LastWorkDay", Constants.NR_DAYS_WEEK - 1);
850            Assignment<Lecture, Placement> a = s.getAssignment();
851            int idx = 1;
852            w.println("000." + dx.format(idx++) + " Assigned variables," + a.nrAssignedVariables());
853            w.println("000." + dx.format(idx++) + " Time [sec]," + sDoubleFormat.format(s.getBestTime()));
854            w.println("000." + dx.format(idx++) + " Hard student conflicts," + Math.round(m.getCriterion(StudentHardConflict.class).getValue(a)));
855            if (m.getProperties().getPropertyBoolean("General.UseDistanceConstraints", true))
856                w.println("000." + dx.format(idx++) + " Distance student conf.," + Math.round(m.getCriterion(StudentDistanceConflict.class).getValue(a)));
857            w.println("000." + dx.format(idx++) + " Student conflicts," + Math.round(m.getCriterion(StudentConflict.class).getValue(a)));
858            w.println("000." + dx.format(idx++) + " Committed student conflicts," + Math.round(m.getCriterion(StudentCommittedConflict.class).getValue(a)));
859            w.println("000." + dx.format(idx++) + " All Student conflicts,"
860                    + Math.round(m.getCriterion(StudentConflict.class).getValue(a) + m.getCriterion(StudentCommittedConflict.class).getValue(a)));
861            w.println("000." + dx.format(idx++) + " Time preferences,"
862                    + sDoubleFormat.format( m.getCriterion(TimePreferences.class).getValue(a)));
863            w.println("000." + dx.format(idx++) + " Room preferences," + Math.round(m.getCriterion(RoomPreferences.class).getValue(a)));
864            w.println("000." + dx.format(idx++) + " Useless half-hours," + Math.round(m.getCriterion(UselessHalfHours.class).getValue(a)));
865            w.println("000." + dx.format(idx++) + " Broken time patterns," + Math.round(m.getCriterion(BrokenTimePatterns.class).getValue(a)));
866            w.println("000." + dx.format(idx++) + " Too big room," + Math.round(m.getCriterion(TooBigRooms.class).getValue(a)));
867            w.println("000." + dx.format(idx++) + " Distribution preferences," + sDoubleFormat.format(m.getCriterion(DistributionPreferences.class).getValue(a)));
868            if (m.getProperties().getPropertyBoolean("General.UseDistanceConstraints", true))
869                w.println("000." + dx.format(idx++) + " Back-to-back instructor pref.," + Math.round(m.getCriterion(BackToBackInstructorPreferences.class).getValue(a)));
870            if (m.getProperties().getPropertyBoolean("General.DeptBalancing", true)) {
871                w.println("000." + dx.format(idx++) + " Dept. balancing penalty," + sDoubleFormat.format(m.getCriterion(DepartmentBalancingPenalty.class).getValue(a)));
872            }
873            w.println("000." + dx.format(idx++) + " Same subpart balancing penalty," + sDoubleFormat.format(m.getCriterion(SameSubpartBalancingPenalty.class).getValue(a)));
874            if (m.getProperties().getPropertyBoolean("General.MPP", false)) {
875                Map<String, Double> mppInfo = ((UniversalPerturbationsCounter)((Perturbations)m.getCriterion(Perturbations.class)).getPerturbationsCounter()).getCompactInfo(a, m, false, false);
876                int pidx = 51;
877                w.println("000." + dx.format(pidx++) + " Perturbation penalty," + sDoubleFormat.format(m.getCriterion(Perturbations.class).getValue(a)));
878                w.println("000." + dx.format(pidx++) + " Additional perturbations," + m.perturbVariables(a).size());
879                int nrPert = 0, nrStudentPert = 0;
880                for (Lecture lecture : m.variables()) {
881                    if (lecture.getInitialAssignment() != null)
882                        continue;
883                    nrPert++;
884                    nrStudentPert += lecture.classLimit(a);
885                }
886                w.println("000." + dx.format(pidx++) + " Given perturbations," + nrPert);
887                w.println("000." + dx.format(pidx++) + " Given student perturbations," + nrStudentPert);
888                for (String key : new TreeSet<String>(mppInfo.keySet())) {
889                    Double value = mppInfo.get(key);
890                    w.println("000." + dx.format(pidx++) + " " + key + "," + sDoubleFormat.format(value));
891                }
892            }
893            HashSet<Student> students = new HashSet<Student>();
894            int enrls = 0;
895            int minRoomPref = 0, maxRoomPref = 0;
896            int minGrPref = 0, maxGrPref = 0;
897            int minTimePref = 0, maxTimePref = 0;
898            int worstInstrPref = 0;
899            HashSet<Constraint<Lecture, Placement>> used = new HashSet<Constraint<Lecture, Placement>>();
900            for (Lecture lecture : m.variables()) {
901                enrls += (lecture.students() == null ? 0 : lecture.students().size());
902                students.addAll(lecture.students());
903
904                int[] minMaxRoomPref = lecture.getMinMaxRoomPreference();
905                maxRoomPref += minMaxRoomPref[1] - minMaxRoomPref[0];
906
907                double[] minMaxTimePref = lecture.getMinMaxTimePreference();
908                maxTimePref += minMaxTimePref[1] - minMaxTimePref[0];
909                for (Constraint<Lecture, Placement> c : lecture.constraints()) {
910                    if (!used.add(c))
911                        continue;
912
913                    if (c instanceof InstructorConstraint) {
914                        InstructorConstraint ic = (InstructorConstraint) c;
915                        worstInstrPref += ic.getWorstPreference();
916                    }
917
918                    if (c instanceof GroupConstraint) {
919                        GroupConstraint gc = (GroupConstraint) c;
920                        if (gc.isHard())
921                            continue;
922                        maxGrPref += Math.abs(gc.getPreference()) * (1 + (gc.variables().size() * (gc.variables().size() - 1)) / 2);
923                    }
924                }
925            }
926            int totalCommitedPlacements = 0;
927            for (Student student : students) {
928                if (student.getCommitedPlacements() != null)
929                    totalCommitedPlacements += student.getCommitedPlacements().size();
930            }
931            HashMap<Long, List<Lecture>> subs = new HashMap<Long, List<Lecture>>();
932            for (Lecture lecture : m.variables()) {
933                if (lecture.isCommitted() || lecture.getScheduler() == null)
934                    continue;
935                List<Lecture> vars = subs.get(lecture.getScheduler());
936                if (vars == null) {
937                    vars = new ArrayList<Lecture>();
938                    subs.put(lecture.getScheduler(), vars);
939                }
940                vars.add(lecture);
941            }
942            int bidx = 101;
943            w.println("000." + dx.format(bidx++) + " Assigned variables max," + m.variables().size());
944            w.println("000." + dx.format(bidx++) + " Student enrollments," + enrls);
945            w.println("000." + dx.format(bidx++) + " Student commited enrollments," + totalCommitedPlacements);
946            w.println("000." + dx.format(bidx++) + " All student enrollments," + (enrls + totalCommitedPlacements));
947            w.println("000." + dx.format(bidx++) + " Time preferences min," + minTimePref);
948            w.println("000." + dx.format(bidx++) + " Time preferences max," + maxTimePref);
949            w.println("000." + dx.format(bidx++) + " Room preferences min," + minRoomPref);
950            w.println("000." + dx.format(bidx++) + " Room preferences max," + maxRoomPref);
951            w.println("000." + dx.format(bidx++) + " Useless half-hours max," +
952                    (Constants.sPreferenceLevelStronglyDiscouraged * m.getRoomConstraints().size() * (lastDaySlot - firstDaySlot + 1) * (lastWorkDay - firstWorkDay + 1)));
953            w.println("000." + dx.format(bidx++) + " Too big room max," + (Constants.sPreferenceLevelStronglyDiscouraged * m.variables().size()));
954            w.println("000." + dx.format(bidx++) + " Distribution preferences min," + minGrPref);
955            w.println("000." + dx.format(bidx++) + " Distribution preferences max," + maxGrPref);
956            w.println("000." + dx.format(bidx++) + " Back-to-back instructor pref max," + worstInstrPref);
957            for (Long scheduler: new TreeSet<Long>(subs.keySet())) {
958                List<Lecture> vars = subs.get(scheduler);
959                idx = 001;
960                bidx = 101;
961                int nrAssg = 0;
962                enrls = 0;
963                int roomPref = 0;
964                minRoomPref = 0;
965                maxRoomPref = 0;
966                double timePref = 0;
967                minTimePref = 0;
968                maxTimePref = 0;
969                double grPref = 0;
970                minGrPref = 0;
971                maxGrPref = 0;
972                long allSC = 0, hardSC = 0, distSC = 0;
973                int instPref = 0;
974                worstInstrPref = 0;
975                int spreadPen = 0, deptSpreadPen = 0;
976                int tooBigRooms = 0;
977                int rcs = 0, uselessSlots = 0;
978                used = new HashSet<Constraint<Lecture, Placement>>();
979                for (Lecture lecture : vars) {
980                    if (lecture.isCommitted())
981                        continue;
982                    enrls += lecture.students().size();
983                    Placement placement = a.getValue(lecture);
984                    if (placement != null) {
985                        nrAssg++;
986                    }
987
988                    int[] minMaxRoomPref = lecture.getMinMaxRoomPreference();
989                    minRoomPref += minMaxRoomPref[0];
990                    maxRoomPref += minMaxRoomPref[1];
991
992                    double[] minMaxTimePref = lecture.getMinMaxTimePreference();
993                    minTimePref += minMaxTimePref[0];
994                    maxTimePref += minMaxTimePref[1];
995
996                    if (placement != null) {
997                        roomPref += placement.getRoomPreference();
998                        timePref += placement.getTimeLocation().getNormalizedPreference();
999                        tooBigRooms += TooBigRooms.getTooBigRoomPreference(placement);
1000                    }
1001
1002                    for (Constraint<Lecture, Placement> c : lecture.constraints()) {
1003                        if (!used.add(c))
1004                            continue;
1005
1006                        if (c instanceof InstructorConstraint) {
1007                            InstructorConstraint ic = (InstructorConstraint) c;
1008                            instPref += ic.getPreference(a);
1009                            worstInstrPref += ic.getWorstPreference();
1010                        }
1011
1012                        if (c instanceof DepartmentSpreadConstraint) {
1013                            DepartmentSpreadConstraint dsc = (DepartmentSpreadConstraint) c;
1014                            deptSpreadPen += dsc.getPenalty(a);
1015                        } else if (c instanceof SpreadConstraint) {
1016                            SpreadConstraint sc = (SpreadConstraint) c;
1017                            spreadPen += sc.getPenalty(a);
1018                        }
1019
1020                        if (c instanceof GroupConstraint) {
1021                            GroupConstraint gc = (GroupConstraint) c;
1022                            if (gc.isHard())
1023                                continue;
1024                            minGrPref -= Math.abs(gc.getPreference());
1025                            maxGrPref += 0;
1026                            grPref += Math.min(0, gc.getCurrentPreference(a));
1027                            // minGrPref += Math.min(gc.getPreference(), 0);
1028                            // maxGrPref += Math.max(gc.getPreference(), 0);
1029                            // grPref += gc.getCurrentPreference();
1030                        }
1031
1032                        if (c instanceof JenrlConstraint) {
1033                            JenrlConstraint jc = (JenrlConstraint) c;
1034                            if (!jc.isInConflict(a) || !jc.isOfTheSameProblem())
1035                                continue;
1036                            Lecture l1 = jc.first();
1037                            Lecture l2 = jc.second();
1038                            allSC += jc.getJenrl();
1039                            if (l1.areStudentConflictsHard(l2))
1040                                hardSC += jc.getJenrl();
1041                            Placement p1 = a.getValue(l1);
1042                            Placement p2 = a.getValue(l2);
1043                            if (!p1.getTimeLocation().hasIntersection(p2.getTimeLocation()))
1044                                distSC += jc.getJenrl();
1045                        }
1046
1047                        if (c instanceof RoomConstraint) {
1048                            RoomConstraint rc = (RoomConstraint) c;
1049                            uselessSlots += UselessHalfHours.countUselessSlotsHalfHours(rc.getContext(a)) + BrokenTimePatterns.countUselessSlotsBrokenTimePatterns(rc.getContext(a));
1050                            rcs++;
1051                        }
1052                    }
1053                }
1054                w.println(dx.format(scheduler) + "." + dx.format(idx++) + " Assigned variables," + nrAssg);
1055                w.println(dx.format(scheduler) + "." + dx.format(bidx++) + " Assigned variables max," + vars.size());
1056                w.println(dx.format(scheduler) + "." + dx.format(idx++) + " Hard student conflicts," + hardSC);
1057                w.println(dx.format(scheduler) + "." + dx.format(bidx++) + " Student enrollments," + enrls);
1058                if (m.getProperties().getPropertyBoolean("General.UseDistanceConstraints", true))
1059                    w.println(dx.format(scheduler) + "." + dx.format(idx++) + " Distance student conf.," + distSC);
1060                w.println(dx.format(scheduler) + "." + dx.format(idx++) + " Student conflicts," + allSC);
1061                w.println(dx.format(scheduler) + "." + dx.format(idx++) + " Time preferences," + timePref);
1062                w.println(dx.format(scheduler) + "." + dx.format(bidx++) + " Time preferences min," + minTimePref);
1063                w.println(dx.format(scheduler) + "." + dx.format(bidx++) + " Time preferences max," + maxTimePref);
1064                w.println(dx.format(scheduler) + "." + dx.format(idx++) + " Room preferences," + roomPref);
1065                w.println(dx.format(scheduler) + "." + dx.format(bidx++) + " Room preferences min," + minRoomPref);
1066                w.println(dx.format(scheduler) + "." + dx.format(bidx++) + " Room preferences max," + maxRoomPref);
1067                w.println(dx.format(scheduler) + "." + dx.format(idx++) + " Useless half-hours," + uselessSlots);
1068                w.println(dx.format(scheduler) + "." + dx.format(bidx++) + " Useless half-hours max," +
1069                        (Constants.sPreferenceLevelStronglyDiscouraged * rcs * (lastDaySlot - firstDaySlot + 1) * (lastWorkDay - firstWorkDay + 1)));
1070                w.println(dx.format(scheduler) + "." + dx.format(idx++) + " Too big room," + tooBigRooms);
1071                w.println(dx.format(scheduler) + "." + dx.format(bidx++) + " Too big room max," + (Constants.sPreferenceLevelStronglyDiscouraged * vars.size()));
1072                w.println(dx.format(scheduler) + "." + dx.format(idx++) + " Distribution preferences," + grPref);
1073                w.println(dx.format(scheduler) + "." + dx.format(bidx++) + " Distribution preferences min," + minGrPref);
1074                w.println(dx.format(scheduler) + "." + dx.format(bidx++) + " Distribution preferences max," + maxGrPref);
1075                if (m.getProperties().getPropertyBoolean("General.UseDistanceConstraints", true))
1076                    w.println(dx.format(scheduler) + "." + dx.format(idx++) + " Back-to-back instructor pref," + instPref);
1077                w.println(dx.format(scheduler) + "." + dx.format(bidx++) + " Back-to-back instructor pref max," + worstInstrPref);
1078                if (m.getProperties().getPropertyBoolean("General.DeptBalancing", true)) {
1079                    w.println(dx.format(scheduler) + "." + dx.format(idx++) + " Department balancing penalty," + sDoubleFormat.format((deptSpreadPen) / 12.0));
1080                }
1081                w.println(dx.format(scheduler) + "." + dx.format(idx++) + " Same subpart balancing penalty," + sDoubleFormat.format((spreadPen) / 12.0));
1082            }
1083            w.flush();
1084            w.close();
1085        } catch (java.io.IOException io) {
1086            sLogger.error(io.getMessage(), io);
1087        }
1088    }
1089    
1090    private class ShutdownHook extends Thread {
1091        Solver<Lecture, Placement> iSolver = null;
1092
1093        private ShutdownHook(Solver<Lecture, Placement> solver) {
1094            setName("ShutdownHook");
1095            iSolver = solver;
1096        }
1097        
1098        @Override
1099        public void run() {
1100            try {
1101                if (iSolver.isRunning()) iSolver.stopSolver();
1102                Solution<Lecture, Placement> solution = iSolver.lastSolution();
1103                long lastIt = solution.getIteration();
1104                double lastTime = solution.getTime();
1105                DataProperties properties = iSolver.getProperties();
1106                TimetableModel model = (TimetableModel) solution.getModel();
1107                File outDir = new File(properties.getProperty("General.Output", "."));
1108
1109                if (solution.getBestInfo() != null) {
1110                    Solution<Lecture, Placement> bestSolution = solution;// .cloneBest();
1111                    sLogger.info("Last solution: " + ToolBox.dict2string(bestSolution.getExtendedInfo(), 1));
1112                    sLogger.info("Best solution (before restore): " + ToolBox.dict2string(bestSolution.getBestInfo(), 1));
1113                    bestSolution.restoreBest();
1114                    sLogger.info("Best solution: " + ToolBox.dict2string(bestSolution.getExtendedInfo(), 1));
1115                    if (properties.getPropertyBoolean("General.SwitchStudents", true))
1116                        ((TimetableModel) bestSolution.getModel()).switchStudents(bestSolution.getAssignment());
1117                    sLogger.info("Best solution: " + ToolBox.dict2string(bestSolution.getExtendedInfo(), 1));
1118                    saveOutputCSV(bestSolution, new File(outDir, "output.csv"));
1119
1120                    printSomeStuff(bestSolution);
1121
1122                    if (properties.getPropertyBoolean("General.Save", true)) {
1123                        TimetableSaver saver = (TimetableSaver) Class.forName(getTimetableSaverClass(properties))
1124                                .getConstructor(new Class[] { Solver.class }).newInstance(new Object[] { iSolver });
1125                        if ((saver instanceof TimetableXMLSaver) && properties.getProperty("General.SolutionFile") != null)
1126                            ((TimetableXMLSaver) saver).save(new File(properties.getProperty("General.SolutionFile")));
1127                        else
1128                            saver.save();
1129                    }
1130                } else {
1131                    sLogger.info("Last solution:" + ToolBox.dict2string(solution.getExtendedInfo(), 1));
1132                }
1133
1134                iCSVFile.close();
1135
1136                sLogger.info("Total number of done iteration steps:" + lastIt);
1137                sLogger.info("Achieved speed: " + sDoubleFormat.format(lastIt / lastTime) + " iterations/second");
1138                
1139                PrintWriter out = new PrintWriter(new FileWriter(new File(outDir, "solver.html")));
1140                out.println("<html><title>Save log</title><body>");
1141                out.println(Progress.getInstance(model).getHtmlLog(Progress.MSGLEVEL_TRACE, true));
1142                out.println("</html>");
1143                out.flush();
1144                out.close();
1145                Progress.removeInstance(model);
1146
1147                if (iStat != null) {
1148                    PrintWriter cbs = new PrintWriter(new FileWriter(new File(outDir, "cbs.txt")));
1149                    cbs.println(iStat.toString());
1150                    cbs.flush(); cbs.close();
1151                }
1152
1153                System.out.println("Unassigned variables: " + model.nrUnassignedVariables(solution.getAssignment()));
1154            } catch (Throwable t) {
1155                sLogger.error("Test failed.", t);
1156            }
1157        }
1158    }
1159}