/
scheduler.go
261 lines (235 loc) · 7.03 KB
/
scheduler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
package scheduler
import (
"database/sql"
"errors"
"log"
"math"
"github.com/wkschwartz/pigosat"
"github.com/kisielk/sqlstruct"
_ "github.com/lib/pq"
)
type ScheduleRequest struct {
Institution string `json:"institution"`
Term string `json:"term"`
Courses []string `json:"courses"`
ElectivesGroups []ElectivesGroup `json:"electives,omitempty"`
BusyTimes []BusyTime `json:"busy-times,omitempty"`
Preferences *Preferences `json:"preferences,omitempty"`
}
type BusyTime struct {
Days Days `json:"day"`
StartTime AmPmTime `json:"startTime"`
EndTime AmPmTime `json:"endTime"`
}
func (s ScheduleRequest) GetBusyTimetableRanges() []TimetableRange {
ttRanges := make([]TimetableRange, 0)
for _, b := range s.BusyTimes {
ttRanges = append(ttRanges, TimetableRangeFromTimes(b.Days, b.StartTime, b.EndTime))
}
return ttRanges
}
type ElectivesGroup struct {
Courses []string `json:"courses"`
}
type Preferences struct {
StartEarly float32 `json:"start-early,omitempty"`
NoMarathons float32 `json:"no-marathons,omitempty"`
CurrentStatus bool `json:"current-status,omitempty"`
ObeyStatus bool `json:"obey-status,omitempty"`
}
func Generate(req ScheduleRequest) []Schedule {
components := [][]Section{}
for _, course := range req.Courses {
courseComponents, err := getComponents(course, req.Term, req.Institution)
if err != nil {
log.Fatal(err)
}
if len(courseComponents) == 0 {
continue
}
components = append(components, courseComponents...)
}
opts := new(pigosat.Options)
opts.PropagationLimit = uint64(math.Pow10(5))
p, err := pigosat.New(opts)
if err != nil {
log.Fatal(err)
}
var clauses []pigosat.Clause
indexToSection, sectionToIndex := buildSectionIndex(components)
/*
* Constraint: MUST schedule one of each component
*/
clauses = make([]pigosat.Clause, 0)
clauseByC := make(map[string][]pigosat.Literal)
for _, section := range indexToSection {
// log.Printf("[%d] %s", sectionToIndex[section.String()], section.String())
c := section.Course.String + section.Component.String
clauseByC[c] = append(clauseByC[c], pigosat.Literal(sectionToIndex[section.String()]))
}
for _, clause := range clauseByC {
clauses = append(clauses, pigosat.Clause(clause))
}
p.AddClauses(pigosat.Formula(clauses))
// log.Printf("Clauses: %v\n", clauses)
/*
* Constraint: MUST NOT schedule conflicting sections together
* AND MUST NOT schedule sections during any busy time
* Note: sections in the same component conflict.
* Note: recall (A' + B') == (AB)'
*/
busyTimes := req.GetBusyTimetableRanges()
log.Printf("%v\n", busyTimes)
conflicts := getConflictsExt(components, busyTimes)
clauses = make([]pigosat.Clause, 0)
for _, conflict := range conflicts {
var clause []pigosat.Literal
if conflict.a.String() != conflict.b.String() {
clause = []pigosat.Literal{
pigosat.Literal(-1 * sectionToIndex[conflict.a.String()]),
pigosat.Literal(-1 * sectionToIndex[conflict.b.String()]),
}
} else {
clause = []pigosat.Literal{
pigosat.Literal(-1 * sectionToIndex[conflict.a.String()])}
}
clauses = append(clauses, pigosat.Clause(clause))
}
p.AddClauses(pigosat.Formula(clauses))
// log.Printf("Clauses: %v\n", clauses)
count := 0
schedules := make([]Schedule, 0)
for status, solution := p.Solve(); status == pigosat.Satisfiable; status, solution = p.Solve() {
solnSections := make([]Section, 0)
for i, val := range solution {
if val == false {
continue
}
if section, ok := indexToSection[int32(i)]; ok {
solnSections = append(solnSections, section)
}
}
if count < 200 {
schedules = append(schedules, Schedule{solnSections, []Conflict{}})
}
count = count + 1
}
log.Printf("Found %d schedules\n", count)
return schedules
}
type Conflict struct {
a, b Section
}
func (c Conflict) String() string {
return c.a.String() + "x" + c.b.String()
}
func getConflicts(components [][]Section) []Conflict {
conflicts := make([]Conflict, 0)
for i, ac := range components {
for j, bc := range components {
if j < i {
continue
}
// A component is a list of sections
aSections, bSections := ac, bc
// Conflict if:
// - time conflict
// - same component (i == j, here)
// - dependency not satisfied ie LEC A1->LAB A2,A3
for ii, a := range aSections {
for jj, b := range bSections {
if ii <= jj {
continue
}
if a.Conflicts(b) || ii == jj {
conflicts = append(conflicts, Conflict{a, b})
}
}
}
}
}
return conflicts
}
func getConflictsExt(components [][]Section, busyTimes []TimetableRange) []Conflict {
conflicts := getConflicts(components)
for _, sections := range components {
for _, section := range sections {
if section.TimetableRange == nil {
section.TimetableRange = TimetableRangeFrom(section)
}
for _, busyTime := range busyTimes {
if section.TimetableRange.Overlaps(busyTime) {
conflicts = append(conflicts, Conflict{section, section})
}
}
}
}
return conflicts
}
func buildSectionIndex(components [][]Section) (map[int32]Section, map[string]int32) {
indexToSection := make(map[int32]Section)
sectionToIndex := make(map[string]int32)
var idx int32 = 1
for _, sections := range components {
for _, section := range sections {
indexToSection[idx] = section
sectionToIndex[section.String()] = idx
idx = idx + 1
}
}
return indexToSection, sectionToIndex
}
var componentTypes = [...]string{"LEC", "LAB", "SEM", "LBL"}
// getComponents returns a course's sections in a given term at
// a given institution. The sections are values of a map whose
// keys are component strings ("LAB", "LEC", ...)
func getComponents(course, term, institution string) ([][]Section, error) {
db, err := sql.Open("postgres", "postgres://localhost:5432/classtime?sslmode=disable")
if err != nil {
return nil, err
}
if db == nil {
return nil, errors.New("DB connection failed")
}
defer db.Close()
var components [][]Section
query := `SELECT * FROM section
WHERE component=$1
AND course=$2
AND term=$3
AND institution=$4
ORDER BY course, component`
courseAndSectionIdToSection := make(map[string]Section)
for _, c := range componentTypes {
rows, err := db.Query(query, c, course, term, institution)
if err != nil {
log.Fatal(err)
}
defer rows.Close()
sections := []Section{}
for rows.Next() {
var section Section
if err := sqlstruct.Scan(§ion, rows); err != nil {
log.Fatal(err)
continue
}
courseAndSectionIdToSection[section.Course.String+section.Section.String] = section
sections = append(sections, section)
}
if len(sections) == 0 {
continue
}
components = append(components, sections)
}
for _, sections := range components {
for _, section := range sections {
if section.AutoEnroll.String != "" {
autoEnrollSection, ok := courseAndSectionIdToSection[section.Course.String+section.AutoEnroll.String]
if ok {
section.AutoEnrollComponent.Scan(autoEnrollSection.Component.String)
}
}
}
}
return components, nil
}