001package org.cpsolver.studentsct.report;
002
003import java.text.DecimalFormat;
004import java.util.ArrayList;
005import java.util.Comparator;
006import java.util.HashMap;
007import java.util.HashSet;
008import java.util.List;
009import java.util.Map;
010import java.util.Set;
011import java.util.TreeSet;
012
013import org.cpsolver.ifs.assignment.Assignment;
014import org.cpsolver.ifs.util.CSVFile;
015import org.cpsolver.ifs.util.DataProperties;
016import org.cpsolver.studentsct.StudentSectioningModel;
017import org.cpsolver.studentsct.extension.TimeOverlapsCounter;
018import org.cpsolver.studentsct.extension.TimeOverlapsCounter.Conflict;
019import org.cpsolver.studentsct.model.Course;
020import org.cpsolver.studentsct.model.Enrollment;
021import org.cpsolver.studentsct.model.FreeTimeRequest;
022import org.cpsolver.studentsct.model.Request;
023import org.cpsolver.studentsct.model.SctAssignment;
024import org.cpsolver.studentsct.model.Section;
025
026
027/**
028 * This class lists time overlapping conflicts in a {@link CSVFile} comma
029 * separated text file. Only sections that allow overlaps
030 * (see {@link SctAssignment#isAllowOverlap()}) can overlap. See {@link TimeOverlapsCounter} for more
031 * details. <br>
032 * <br>
033 * 
034 * Each line represent a pair if classes that overlap in time and have one
035 * or more students in common.
036 * 
037 * <br>
038 * <br>
039 * 
040 * Usage: new DistanceConflictTable(model),createTable(true, true).save(aFile);
041 * 
042 * <br>
043 * <br>
044 * 
045 * @version StudentSct 1.3 (Student Sectioning)<br>
046 *          Copyright (C) 2013 - 2014 Tomáš Müller<br>
047 *          <a href="mailto:muller@unitime.org">muller@unitime.org</a><br>
048 *          <a href="http://muller.unitime.org">http://muller.unitime.org</a><br>
049 * <br>
050 *          This library is free software; you can redistribute it and/or modify
051 *          it under the terms of the GNU Lesser General Public License as
052 *          published by the Free Software Foundation; either version 3 of the
053 *          License, or (at your option) any later version. <br>
054 * <br>
055 *          This library is distributed in the hope that it will be useful, but
056 *          WITHOUT ANY WARRANTY; without even the implied warranty of
057 *          MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
058 *          Lesser General Public License for more details. <br>
059 * <br>
060 *          You should have received a copy of the GNU Lesser General Public
061 *          License along with this library; if not see
062 *          <a href='http://www.gnu.org/licenses/'>http://www.gnu.org/licenses/</a>.
063 */
064public class TimeOverlapConflictTable extends AbstractStudentSectioningReport {
065    private static DecimalFormat sDF1 = new DecimalFormat("0.####");
066    private static DecimalFormat sDF2 = new DecimalFormat("0.0000");
067
068    private TimeOverlapsCounter iTOC = null;
069
070    /**
071     * Constructor
072     * 
073     * @param model
074     *            student sectioning model
075     */
076    public TimeOverlapConflictTable(StudentSectioningModel model) {
077        super(model);
078        iTOC = model.getTimeOverlaps();
079        if (iTOC == null) {
080            iTOC = new TimeOverlapsCounter(null, model.getProperties());
081        }
082    }
083
084    /**
085     * Create report
086     * 
087     * @param assignment current assignment
088     * @return report as comma separated text file
089     */
090    @Override
091    public CSVFile createTable(Assignment<Request, Enrollment> assignment, DataProperties properties) {
092        CSVFile csv = new CSVFile();
093        csv.setHeader(new CSVFile.CSVField[] { new CSVFile.CSVField("Course"), new CSVFile.CSVField("Total\nConflicts"),
094                new CSVFile.CSVField("Class"), new CSVFile.CSVField("Meeting Time"),
095                new CSVFile.CSVField("Time\nConflicts"), new CSVFile.CSVField("% of Total\nConflicts"),
096                new CSVFile.CSVField("Conflicting\nClass"), new CSVFile.CSVField("Conflicting\nMeeting Time"),
097                new CSVFile.CSVField("Overlap [min]"), new CSVFile.CSVField("Joined\nConflicts"), new CSVFile.CSVField("% of Total\nConflicts")
098                });
099        
100        Set<Conflict> confs = new HashSet<Conflict>();
101        for (Request r1 : getModel().variables()) {
102            Enrollment e1 = assignment.getValue(r1);
103            if (e1 == null || r1 instanceof FreeTimeRequest)
104                continue;
105            for (Request r2 : r1.getStudent().getRequests()) {
106                Enrollment e2 = assignment.getValue(r2);
107                if (r2 instanceof FreeTimeRequest) {
108                    FreeTimeRequest ft = (FreeTimeRequest)r2;
109                    confs.addAll(iTOC.conflicts(e1, ft.createEnrollment()));
110                } else if (e2 != null && r1.getId() < r2.getId()) {
111                    confs.addAll(iTOC.conflicts(e1, e2));
112                }
113            }
114        }
115        
116        HashMap<Course, Set<Long>> totals = new HashMap<Course, Set<Long>>();
117        HashMap<CourseSection, Map<CourseSection, Double>> conflictingPairs = new HashMap<CourseSection, Map<CourseSection,Double>>();
118        HashMap<CourseSection, Set<Long>> sectionOverlaps = new HashMap<CourseSection, Set<Long>>();        
119        
120        for (Conflict conflict : confs) {
121            if (!matches(conflict.getR1(), conflict.getE1())) continue;
122            if (conflict.getR1() == null || conflict.getR1() instanceof FreeTimeRequest || conflict.getR2() == null || conflict.getR2() instanceof FreeTimeRequest) continue;
123            Section s1 = (Section)conflict.getS1(), s2 = (Section)conflict.getS2();
124            Request r1 = conflict.getR1();
125            Course c1 = assignment.getValue(conflict.getR1()).getCourse();
126            Request r2 = conflict.getR2();
127            Course c2 = assignment.getValue(conflict.getR2()).getCourse();
128            CourseSection a = new CourseSection(c1, s1);
129            CourseSection b = new CourseSection(c2, s2);
130            
131            Set<Long> students = totals.get(c1);
132            if (students == null) {
133                students = new HashSet<Long>();
134                totals.put(c1, students);
135            }
136            students.add(r1.getStudent().getId());
137            students = totals.get(c2);
138            if (students == null) {
139                students = new HashSet<Long>();
140                totals.put(c2, students);
141            }
142            students.add(r2.getStudent().getId());
143            
144            Set<Long> total = sectionOverlaps.get(a);
145            if (total == null) {
146                total = new HashSet<Long>();
147                sectionOverlaps.put(a, total);
148            }
149            total.add(r1.getStudent().getId());
150            Map<CourseSection, Double> pair = conflictingPairs.get(a);
151            if (pair == null) {
152                pair = new HashMap<CourseSection, Double>();
153                conflictingPairs.put(a, pair);
154            }
155            Double prev = pair.get(b);
156            pair.put(b, r2.getWeight() + (prev == null ? 0.0 : prev.doubleValue()));
157            
158            total = sectionOverlaps.get(b);
159            if (total == null) {
160                total = new HashSet<Long>();
161                sectionOverlaps.put(b, total);
162            }
163            total.add(r2.getStudent().getId());
164            pair = conflictingPairs.get(b);
165            if (pair == null) {
166                pair = new HashMap<CourseSection, Double>();
167                conflictingPairs.put(b, pair);
168            }
169            prev = pair.get(a);
170            pair.put(a, r1.getWeight() + (prev == null ? 0.0 : prev.doubleValue()));
171        }
172        
173        Comparator<Course> courseComparator = new Comparator<Course>() {
174            @Override
175            public int compare(Course a, Course b) {
176                int cmp = a.getName().compareTo(b.getName());
177                if (cmp != 0) return cmp;
178                return a.getId() < b.getId() ? -1 : a.getId() == b.getId() ? 0 : 1;
179            }
180        };
181        Comparator<Section> sectionComparator = new Comparator<Section>() {
182            @Override
183            public int compare(Section a, Section b) {
184                int cmp = a.getSubpart().getConfig().getOffering().getName().compareTo(b.getSubpart().getConfig().getOffering().getName());
185                if (cmp != 0) return cmp;
186                cmp = a.getSubpart().getInstructionalType().compareTo(b.getSubpart().getInstructionalType());
187                // if (cmp != 0) return cmp;
188                // cmp = a.getName().compareTo(b.getName());
189                if (cmp != 0) return cmp;
190                return a.getId() < b.getId() ? -1 : a.getId() == b.getId() ? 0 : 1;
191            }
192        };
193        
194        TreeSet<Course> courses = new TreeSet<Course>(courseComparator);
195        courses.addAll(totals.keySet());
196        for (Course course: courses) {
197            Set<Long> total = totals.get(course);
198            
199            TreeSet<Section> sections = new TreeSet<Section>(sectionComparator);
200            for (Map.Entry<CourseSection, Set<Long>> entry: sectionOverlaps.entrySet())
201                if (course.equals(entry.getKey().getCourse()))
202                    sections.add(entry.getKey().getSection());
203            
204            boolean firstCourse = true;
205            for (Section section: sections) {
206                Set<Long> sectionOverlap = sectionOverlaps.get(new CourseSection(course, section));
207                Map<CourseSection, Double> pair = conflictingPairs.get(new CourseSection(course, section));
208                boolean firstClass = true;
209                
210                for (CourseSection other: new TreeSet<CourseSection>(pair.keySet())) {
211                    List<CSVFile.CSVField> line = new ArrayList<CSVFile.CSVField>();
212                    line.add(new CSVFile.CSVField(firstCourse && firstClass ? course.getName() : ""));
213                    line.add(new CSVFile.CSVField(firstCourse && firstClass ? total.size() : ""));
214                    
215                    line.add(new CSVFile.CSVField(firstClass ? section.getSubpart().getName() + " " + section.getName(course.getId()): ""));
216                    line.add(new CSVFile.CSVField(firstClass ? section.getTime() == null ? "" : section.getTime().getDayHeader() + " " + section.getTime().getStartTimeHeader(isUseAmPm()) + " - " + section.getTime().getEndTimeHeader(isUseAmPm()): ""));
217                        
218                    line.add(new CSVFile.CSVField(firstClass && sectionOverlap != null ? String.valueOf(sectionOverlap.size()): ""));
219                    line.add(new CSVFile.CSVField(firstClass && sectionOverlap != null ? sDF2.format(((double)sectionOverlap.size()) / total.size()) : ""));
220
221                    line.add(new CSVFile.CSVField(other.getCourse().getName() + " " + other.getSection().getSubpart().getName() + " " + other.getSection().getName(other.getCourse().getId())));
222                    line.add(new CSVFile.CSVField(other.getSection().getTime().getDayHeader() + " " + other.getSection().getTime().getStartTimeHeader(isUseAmPm()) + " - " + other.getSection().getTime().getEndTimeHeader(isUseAmPm())));
223                    
224                    line.add(new CSVFile.CSVField(sDF1.format(5 * iTOC.share(section, other.getSection()))));
225                    line.add(new CSVFile.CSVField(sDF1.format(pair.get(other))));
226                    line.add(new CSVFile.CSVField(sDF2.format(pair.get(other) / total.size())));
227                    
228                    csv.addLine(line);
229                    firstClass = false;
230                }                    
231                firstCourse = false;
232            }
233            
234            csv.addLine();
235        }
236        
237        
238        return csv;
239    }
240}