-
Notifications
You must be signed in to change notification settings - Fork 0
/
crossover.js
403 lines (363 loc) · 22.2 KB
/
crossover.js
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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
import fs from 'fs';
import { fitness_func_generation } from './fitness_func.js';
import validate_timetable from './validate_timetable.js';
import config from './config.js';
import teacher_room_clash_map_generator from './teacher_room_clash_map_generator.js';
let showstats = config.showstats;
const check_teacher_overload = (j, k, teacherid, type, teacher_room_clash_map) => {
let curr_index = k + 1;
let streak = 1;
if (type == 'practical') {
k++;
streak++;
}
let local_stream = 0;
while (curr_index <= 9) {
let teacher_overload_checker = 'teacher' + ';' + j + ';' + curr_index + ';' + teacherid;
if (teacher_room_clash_map[teacher_overload_checker] == true) {
local_stream++;
} else {
break;
}
curr_index++;
}
streak += local_stream;
local_stream = 0;
curr_index = k--;
while (curr_index >= 0) {
let teacher_overload_checker = 'teacher' + ';' + j + ';' + curr_index + ';' + teacherid;
if (teacher_room_clash_map[teacher_overload_checker] == true) {
local_stream++;
} else {
break;
}
curr_index--;
}
streak += local_stream;
if (streak > 4) {
// console.log(streak>4 ? false : true);
}
return streak > 4 ? false : true;
}
const find_new_slot_or_room = (timetable, day, slot, teacherid, roomid, type, teacher_room_clash_map, room) => {
if (showstats) {
console.log("\n============= " + type + "\t || Initial slot : " + day + " " + slot + " ====================")
}
let room_type = (type === 'practical') ? 'lab' : 'room';
let min = config.min, max = config.max;
let temp_total_forward = (day * 10) + slot;
let temp_total_backward = (day * 10) + slot;
let slotsubjectid = timetable[day][slot].subjectid;
let slottype = timetable[day][slot].type;
// Clear the current slot for the conflicting class
if (timetable[day][slot].teacherid === teacherid && timetable[day][slot].roomid === roomid) {
timetable[day][slot].teacherid = "";
timetable[day][slot].roomid = "";
timetable[day][slot].subjectid = "";
timetable[day][slot].type = "";
if (type === 'practical') {
if (slot < 9 && timetable[day][slot + 1].teacherid === teacherid && timetable[day][slot + 1].roomid === roomid) {
timetable[day][slot + 1].teacherid = "";
timetable[day][slot + 1].roomid = "";
timetable[day][slot + 1].subjectid = "";
timetable[day][slot + 1].type = "";
} else if (slot > 0 && timetable[day][slot - 1].teacherid === teacherid && timetable[day][slot - 1].roomid === roomid) {
timetable[day][slot - 1].teacherid = "";
timetable[day][slot - 1].roomid = "";
timetable[day][slot - 1].subjectid = "";
timetable[day][slot - 1].type = "";
temp_total_forward--;
temp_total_backward--;
}
}
}
let flag1 = true, flag2 = true;
while (flag1 || flag2) {
let temp_day_forward = Math.floor(temp_total_forward / 10);
let temp_slot_forward = temp_total_forward % 10;
let temp_day_backward = Math.floor(temp_total_backward / 10);
let temp_slot_backward = temp_total_backward % 10;
// Create conflict keys for forward and backward checking (teacher and room availability)
let teacher_checker_forward = "teacher" + ";" + temp_day_forward + ";" + temp_slot_forward + ";" + teacherid;
let teacher_checker_backward = "teacher" + ";" + temp_day_backward + ";" + temp_slot_backward + ";" + teacherid;
// For practical classes, also check the next slot
let teacher_checker_forward_practical = "teacher" + ";" + temp_day_forward + ";" + (temp_slot_forward + 1) + ";" + teacherid;
let teacher_checker_backward_practical = "teacher" + ";" + temp_day_backward + ";" + (temp_slot_backward + 1) + ";" + teacherid;
// Check forward for practical subjects
if (type === 'practical' && temp_slot_forward < 9 &&
(!teacher_room_clash_map[teacher_checker_forward] && !teacher_room_clash_map[teacher_checker_forward_practical]) &&
timetable[temp_day_forward][temp_slot_forward].teacherid === "" &&
timetable[temp_day_forward][temp_slot_forward + 1].teacherid === "" &&
check_teacher_overload(temp_day_forward, temp_slot_forward, teacherid, type, teacher_room_clash_map)) {
// Check room availability for the practical class in two consecutive slots
if (showstats)
process.stdout.write("Slot : " + temp_day_forward + " " + temp_slot_forward + " || Room : ");
for (let i = 0; i < room[room_type].length; i++) {
if (showstats)
process.stdout.write(room[room_type][i].roomid + " ");
let room_checker_forward = "room" + ";" + temp_day_forward + ";" + temp_slot_forward + ";" + room[room_type][i].roomid;
let room_checker_forward_practical = "room" + ";" + temp_day_forward + ";" + (temp_slot_forward + 1) + ";" + room[room_type][i].roomid;
if (!teacher_room_clash_map[room_checker_forward] && !teacher_room_clash_map[room_checker_forward_practical]) {
// Assign the new slot to the practical class
timetable[temp_day_forward][temp_slot_forward].teacherid = teacherid;
timetable[temp_day_forward][temp_slot_forward + 1].teacherid = teacherid;
timetable[temp_day_forward][temp_slot_forward].roomid = room[room_type][i].roomid;
timetable[temp_day_forward][temp_slot_forward + 1].roomid = room[room_type][i].roomid;
timetable[temp_day_forward][temp_slot_forward].subjectid = slotsubjectid;
timetable[temp_day_forward][temp_slot_forward + 1].subjectid = slotsubjectid;
timetable[temp_day_forward][temp_slot_forward].type = slottype;
timetable[temp_day_forward][temp_slot_forward + 1].type = slottype;
// Update the clash map
teacher_room_clash_map[room_checker_forward] = true;
teacher_room_clash_map[room_checker_forward_practical] = true;
teacher_room_clash_map[teacher_checker_forward] = true;
teacher_room_clash_map[teacher_checker_forward_practical] = true;
if (showstats) {
process.stdout.write(" || slot found at " + temp_day_forward + " " + temp_slot_forward);
console.log("\n===================================================================")
}
return { timetable, teacher_room_clash_map };
}
}
if (showstats)
process.stdout.write(" || NA\n");
} else if (type === 'theory' && !teacher_room_clash_map[teacher_checker_forward] &&
check_teacher_overload(temp_day_forward, temp_slot_forward, teacherid, type, teacher_room_clash_map) &&
timetable[temp_day_forward][temp_slot_forward].teacherid === "") {
if (showstats)
process.stdout.write("Slot : " + temp_day_forward + " " + temp_slot_forward + " || Room : ");
// Check room availability for theory class
for (let i = 0; i < room[room_type].length; i++) {
if (showstats)
process.stdout.write(room[room_type][i].roomid + " ");
let room_checker_forward = "room" + ";" + temp_day_forward + ";" + temp_slot_forward + ";" + room[room_type][i].roomid;
if (!teacher_room_clash_map[room_checker_forward]) {
// Assign the new slot to the theory class
timetable[temp_day_forward][temp_slot_forward].teacherid = teacherid;
timetable[temp_day_forward][temp_slot_forward].roomid = room[room_type][i].roomid;
timetable[temp_day_forward][temp_slot_forward].subjectid = slotsubjectid;
timetable[temp_day_forward][temp_slot_forward].type = slottype;
// Update the clash map
teacher_room_clash_map[room_checker_forward] = true;
teacher_room_clash_map[teacher_checker_forward] = true;
if (showstats) {
process.stdout.write(" || slot found at " + temp_day_forward + " " + temp_slot_forward);
console.log("\n===================================================================")
}
return { timetable, teacher_room_clash_map };
}
}
if (showstats)
process.stdout.write(" || NA\n");
}
// Check backward for practical subjects
if (type === 'practical' && temp_slot_backward < 9 &&
(!teacher_room_clash_map[teacher_checker_backward] && !teacher_room_clash_map[teacher_checker_backward_practical]) &&
timetable[temp_day_backward][temp_slot_backward].teacherid === "" &&
timetable[temp_day_backward][temp_slot_backward + 1].teacherid === "" &&
check_teacher_overload(temp_day_forward, temp_slot_forward, teacherid, type, teacher_room_clash_map)) {
if (showstats)
process.stdout.write("Slot : " + temp_day_backward + " " + temp_slot_backward + " || Room : ");
for (let i = 0; i < room[room_type].length; i++) {
if (showstats)
process.stdout.write(room[room_type][i].roomid + " ");
let room_checker_backward = "room" + ";" + temp_day_backward + ";" + temp_slot_backward + ";" + room[room_type][i].roomid;
let room_checker_backward_practical = "room" + ";" + temp_day_backward + ";" + (temp_slot_backward + 1) + ";" + room[room_type][i].roomid;
if (!teacher_room_clash_map[room_checker_backward] && !teacher_room_clash_map[room_checker_backward_practical]) {
// Assign the new slot to the practical class
timetable[temp_day_backward][temp_slot_backward].teacherid = teacherid;
timetable[temp_day_backward][temp_slot_backward + 1].teacherid = teacherid;
timetable[temp_day_backward][temp_slot_backward].roomid = room[room_type][i].roomid;
timetable[temp_day_backward][temp_slot_backward + 1].roomid = room[room_type][i].roomid;
timetable[temp_day_backward][temp_slot_backward].subjectid = slotsubjectid;
timetable[temp_day_backward][temp_slot_backward + 1].subjectid = slotsubjectid;
timetable[temp_day_backward][temp_slot_backward].type = slottype;
timetable[temp_day_backward][temp_slot_backward + 1].type = slottype;
// Update the clash map
teacher_room_clash_map[room_checker_backward] = true;
teacher_room_clash_map[room_checker_backward_practical] = true;
teacher_room_clash_map[teacher_checker_backward] = true;
teacher_room_clash_map[teacher_checker_backward_practical] = true;
if (showstats) {
process.stdout.write(" || slot found at " + temp_day_backward + " " + temp_slot_backward);
console.log("\n===================================================================")
}
return { timetable, teacher_room_clash_map };
}
}
if (showstats)
process.stdout.write(" || NA\n");
} else if (type === 'theory' && !teacher_room_clash_map[teacher_checker_backward] &&
check_teacher_overload(temp_day_forward, temp_slot_forward, teacherid, type, teacher_room_clash_map) &&
timetable[temp_day_backward][temp_slot_backward].teacherid === "") {
if (showstats)
process.stdout.write("Slot : " + temp_day_backward + " " + temp_slot_backward + " || Room : ");
// Check room availability for theory class
for (let i = 0; i < room[room_type].length; i++) {
if (showstats)
process.stdout.write(room[room_type][i].roomid + " ");
let room_checker_backward = "room" + ";" + temp_day_backward + ";" + temp_slot_backward + ";" + room[room_type][i].roomid;
if (!teacher_room_clash_map[room_checker_backward]) {
// Assign the new slot to the theory class
timetable[temp_day_backward][temp_slot_backward].teacherid = teacherid;
timetable[temp_day_backward][temp_slot_backward].roomid = room[room_type][i].roomid;
timetable[temp_day_backward][temp_slot_backward].subjectid = slotsubjectid;
timetable[temp_day_backward][temp_slot_backward].type = slottype;
// Update the clash map
teacher_room_clash_map[room_checker_backward] = true;
teacher_room_clash_map[teacher_checker_backward] = true;
if (showstats) {
process.stdout.write(" || slot found at " + temp_day_backward + " " + temp_slot_backward);
console.log("\n===================================================================")
}
return { timetable, teacher_room_clash_map };
}
}
if (showstats)
process.stdout.write(" || NA\n");
}
// Move forward and backward in time
temp_total_forward++;
temp_total_backward--;
if (type === 'practical') {
temp_total_forward++;
temp_total_backward--;
}
if (temp_total_forward > max) {
flag1 = false;
temp_total_forward = min;
}
if (temp_total_backward < min) {
flag2 = false;
temp_total_backward = max;
}
}
if (showstats) {
console.log("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
console.log("===================================================================")
}
// If no free slot was found, return null
return null;
};
// Function to resolve conflicts (teacher/room clashes) in a timetable
const resolveConflicts = (offspring, room) => {
let teacher_room_clash_map = {};
for (let i = 0; i < offspring['data'].length; i++) {
for (let j = 0; j < 7; j++) {
for (let k = 0; k < 10; k++) {
if (offspring['data'][i]['timetable'][j][k].teacherid == "" && offspring['data'][i]['timetable'][j][k].roomid == "") { // if class is empty
continue;
}
else if (offspring['data'][i]['timetable'][j][k].teacherid && offspring['data'][i]['timetable'][j][k].roomid) {
if (teacher_room_clash_map[("teacher" + ";" + j + ";" + k + ";" + offspring['data'][i]['timetable'][j][k].teacherid)] || teacher_room_clash_map[("room" + ";" + j + ";" + k + ";" + offspring['data'][i]['timetable'][j][k].roomid)]) {
let newslottedtt;
if (offspring['data'][i]['timetable'][j][k].type === 'practical' && k < 9 &&
offspring['data'][i]['timetable'][j][k + 1].teacherid === offspring['data'][i]['timetable'][j][k].teacherid) {
newslottedtt = find_new_slot_or_room(offspring['data'][i]['timetable'], j, k, offspring['data'][i]['timetable'][j][k].teacherid, offspring['data'][i]['timetable'][j][k].roomid, offspring['data'][i]['timetable'][j][k].type, teacher_room_clash_map, room);
} else if (offspring['data'][i]['timetable'][j][k].type === 'practical' && k > 0 &&
offspring['data'][i]['timetable'][j][k - 1].teacherid === offspring['data'][i]['timetable'][j][k].teacherid) {
newslottedtt = find_new_slot_or_room(offspring['data'][i]['timetable'], j, (k - 1), offspring['data'][i]['timetable'][j][k].teacherid, offspring['data'][i]['timetable'][j][k].roomid, offspring['data'][i]['timetable'][j][k].type, teacher_room_clash_map, room);
} else {
newslottedtt = find_new_slot_or_room(offspring['data'][i]['timetable'], j, k, offspring['data'][i]['timetable'][j][k].teacherid, offspring['data'][i]['timetable'][j][k].roomid, offspring['data'][i]['timetable'][j][k].type, teacher_room_clash_map, room);
}
// newslottedtt = find_new_slot_or_room(offspring['data'][i]['timetable'], j, k, offspring['data'][i]['timetable'][j][k].teacherid, offspring['data'][i]['timetable'][j][k].roomid, offspring['data'][i]['timetable'][j][k].type, teacher_room_clash_map, room);
if (newslottedtt == null) {
if (showstats)
console.log("TraahiMaam TraahiMaam, PaahiMaam PaahiMaam Jagat-Srishti-Pralay Vishva, Sankat tav Naashitaam");
return false;
} else {
offspring['data'][i]['timetable'] = newslottedtt.timetable;
teacher_room_clash_map = newslottedtt.teacher_room_clash_map;
}
}
else {
teacher_room_clash_map[("teacher" + ";" + j + ";" + k + ";" + offspring['data'][i]['timetable'][j][k].teacherid)] = true;
teacher_room_clash_map[("room" + ";" + j + ";" + k + ";" + offspring['data'][i]['timetable'][j][k].roomid)] = true;
}
}
}
}
}
return offspring;
};
// Function to perform crossover between two timetables (parents)
const crossover = (parent1, parent2, room) => {
// Deep copy parent timetables to avoid modifying the original ones
let offspring1 = JSON.parse(JSON.stringify(parent1));
let offspring2 = JSON.parse(JSON.stringify(parent2));
// Select a random crossover point (section, day, time slot)
let crossoverPoint = Math.floor(Math.random() * offspring1['data'].length); // Cross over between sections
// Perform crossover by swapping timetables after the crossover point
for (let i = crossoverPoint; i < offspring1['data'].length; i++) {
let teacher_room_clash_map = offspring1['data'][i].timetable;
offspring1['data'][i].timetable = offspring2['data'][i].timetable;
offspring2['data'][i].timetable = teacher_room_clash_map;
}
offspring1 = resolveConflicts(offspring1, room);
offspring2 = resolveConflicts(offspring2, room);
let res = [];
if (offspring1 !== false) {
res.push(offspring1);
}
if (offspring2 !== false) {
res.push(offspring2);
}
return res;
};
const crossoverGeneration = (population, room) => {
population = fitness_func_generation(population);
let newGeneration = [];
const eliteCount = Math.ceil(population.length * config.eliteRate);
let elites = population.slice(0, eliteCount); // Perform elitism (preserve the best solutions)
let nonElites = population.slice(eliteCount); // Remove the elites from the population
let selectedForCrossover = population;
let crossover_map = {};
newGeneration.push(...elites); // Add the elites to the new generation (deep copy)
while (newGeneration.length < population.length) {
let random1, random2;
while (true) {
random1 = Math.floor(Math.random() * selectedForCrossover.length);
random2 = Math.floor(Math.random() * selectedForCrossover.length);
if (random1 != random2 && !crossover_map[random1 + ";" + random2] && !crossover_map[random2 + ";" + random1]) {
crossover_map[(random1 + ";" + random2)] = true;
crossover_map[(random2 + ";" + random1)] = true;
break;
}
}
let parent1 = selectedForCrossover[random1];
let parent2 = selectedForCrossover[random2];
let child = crossover(parent1, parent2, room);
newGeneration.push(...child);
if (Object.keys(crossover_map).length >= (population.length * (population.length - 1) / 2)) {
console.log("All possible crossovers have been done");
break;
}
}
if (newGeneration.length > population.length) {
newGeneration = newGeneration.slice(0, population.length);
} else if (newGeneration.length == eliteCount) {
// *************************** Logic Missing here ***************************
// generate new random timetables to fill the population as the crossover did not generate enough timetables and
// old population will generate the same results again and again if we keep using the same population
console.log("Population size is less than expected after crossover logic to handle this is missing");
} else if (newGeneration.length < population.length) {
console.log("Population size is less than expected after crossover");
newGeneration.push(...nonElites.slice(0, population.length - newGeneration.length));
}
newGeneration = fitness_func_generation(newGeneration);
newGeneration = teacher_room_clash_map_generator(newGeneration,showstats = false);
newGeneration = newGeneration.sort(function (a, b) { return b.fitness - a.fitness; });
console.log(population.length, newGeneration.length);
if (config.showstats) {
for (let i = 0; i < newGeneration.length; i++) {
console.log("======== [ Validation : " + validate_timetable(newGeneration[i]) + " ] ========= [ Fitness : " + newGeneration[i]['fitness'] + " ] ==========");
}
}
return newGeneration;
};
export default crossoverGeneration;
// Example usage:
// let population = JSON.parse(fs.readFileSync('population_selected.json', 'utf8'));
// let room = JSON.parse(fs.readFileSync('room.json', 'utf8'));
// population = crossoverGeneration(population, room); // Apply elitism and roulette selection to the population
// fs.writeFileSync('population_selected.json', JSON.stringify(population, null, 4), 'utf8'); // Save the new population