Exemplo n.º 1
0
def main():
    c = CompetitionDictReader()
    data = c.readInstance(1)
    t = TimeTableFactory.getTimeTable(data)


    initialSolution(t, data)
Exemplo n.º 2
0
 def setUp(self):
     self.c = CompetitionDictReader()
     self.data = self.c.readInstance(1)
     self.t = TimeTableFactory.getTimeTable(self.data)
     "Create sorted list of rooms (sorted by capacity)"
     self.sortedRoomIdList = sorted(self.data.getAllRooms(),
                                    key=lambda room: room.capacity,
                                    reverse=True)
Exemplo n.º 3
0
def main():
    c = CompetitionDictReader()
    numberOfInstance = 22
    data = c.readInstance(numberOfInstance)
    a = AdaptiveTabuSearch(data, 2400)

    bestSolution = a.run()
    o = file('result' + str(numberOfInstance) + str('add'), 'w')
    for slot in bestSolution.getTimeTable():
        for lecture in bestSolution.getTimeTable()[slot]:
            tuple = (slot / data.periodsPerDay, slot % data.periodsPerDay)
            line = lecture[0] + ' ' + lecture[1] + ' ' + str(tuple[0])+ ' ' + \
                str(tuple[1]) + '\n'
            o.write(line)
    o.close()
Exemplo n.º 4
0
def main():
    c= CompetitionDictReader()
    numberOfInstance = 22
    data = c.readInstance(numberOfInstance)
    a = AdaptiveTabuSearch(data, 2400)

    bestSolution = a.run()
    o = file('result'+str(numberOfInstance ) + str('add'), 'w')
    for slot in bestSolution.getTimeTable():
        for lecture in bestSolution.getTimeTable()[slot]:
            tuple = (slot/data.periodsPerDay, slot % data.periodsPerDay)
            line = lecture[0] + ' ' + lecture[1] + ' ' + str(tuple[0])+ ' ' + \
                str(tuple[1]) + '\n'
            o.write(line)
    o.close()
Exemplo n.º 5
0
class BasicNeighborhoodTest(unittest.TestCase):
    def setUp(self):
        self.c = CompetitionDictReader()
        self.data = self.c.readInstance(1)
        self.t = TimeTableFactory.getTimeTable(self.data)


    def test_simpeSwap(self):
        assignedList = [(0, 'c0001', 'B'), (0, 'c0014', 'B'), (2, 'c0030', 'B'), (2, 'c0001', 'B')]
        self.t.addDataToTimetable(assignedList)
        basicNeighborHood = BasicNeighborhood(self.data)
        basicNeighborHood.simpleSwap(self.t.timeTable, self.t.neighbourhoodList, 6)
        self.assertEqual(len(basicNeighborHood.getBasicList()), 103)

    def test_simpeSwap2(self):
        path = u"data/TabuSearchDataTests/simpleSwapMove"
        self.t.readLecturesToTimetable(path)
        basicNeighborHood = BasicNeighborhood(self.data)
        basicNeighborHood.simpleSwap(self.t.timeTable, self.t.neighbourhoodList, 6)
        self.assertEqual(len(basicNeighborHood.getPossibleSwapsForCourse('c0001', 0)), 20)
        self.assertEqual(len(basicNeighborHood.getPossibleSwapsForCourse('c0014', 0)), 27)
        self.assertEqual(len(basicNeighborHood.getPossibleSwapsForCourse('c0005', 1)), 26)
        self.assertEqual(len(basicNeighborHood.getPossibleSwapsForCourse('c0016', 5)), 28)
        #for x in basicNeighborHood.getPossibleSwapsForCourse('c0030', 2):
         #   print("PARA")
          #  print(x[0].courseId, x[0].period, x[0].index)
           # print(x[1].courseId, x[1].period, x[1].index)
        self.assertEqual(len(basicNeighborHood.getPossibleSwapsForCourse('c0030', 2)), 31)


    def test_basicList(self):
        initialSolution(self.t, self.data)
        tabuList = TabuList(self.data.getAllCourses(), self.t.neighbourhoodList)
        tabuList.addTabuMove("c0001", 1, "a", 1)
        self.assertTrue(tabuList.isTabuMove("c0001", 1, "a",2, 10))
Exemplo n.º 6
0
class TabuSearchTest(unittest.TestCase):
    def setUp(self):
        self.c = CompetitionDictReader()
        self.data = self.c.readInstance(1)
        self.t = TimeTableFactory.getTimeTable(self.data)
        "Create sorted list of rooms (sorted by capacity)"
        self.sortedRoomIdList = sorted(self.data.getAllRooms(),
                                       key=lambda room: room.capacity,
                                       reverse=True)

    def test_matchRoomAllocation(self):
        path = u"data/TabuSearchDataTests/matchingRooms"
        self.t.readLecturesToTimetable(path)
        slot = 0
        coursesId = [
            'c0001', 'c0002', 'c0004', 'c0030', 'c0005', 'c0014', 'c0015',
            'c0016'
        ]
        self.t.timeTable[slot] = tabuSearch.matchingRoomAllocations(
            self.t.getTimeTable(), slot, self.data, self.sortedRoomIdList)
        listOfAssignedRooms = [x[1] for x in self.t.timeTable[slot]]
        self.assertEqual(listOfAssignedRooms, ['B', 'S', 'C', 'G', 'F'])
        penalty = softConstraints2.softConstraintsPenalty(
            self.t.getTimeTable(), self.data)['penaltyRoomCapacity']
        self.assertEqual(penalty, 340)

        slot = 1
        self.t.timeTable[slot] = tabuSearch.matchingRoomAllocations(
            self.t.getTimeTable(), slot, self.data, self.sortedRoomIdList)
        listOfAssignedRooms = [x[1] for x in self.t.timeTable[slot]]
        self.assertEqual(listOfAssignedRooms, ['G', 'S', 'E', 'B', 'C', 'F'])
        penalty = softConstraints2.softConstraintsPenalty(
            self.t.getTimeTable(), self.data)['penaltyRoomCapacity']

        self.assertEqual(penalty, 305)

    def test_coeficientTabuTenure(self):
        tabu = tabuSearch.TabuList(self.data.getAllCourses(),
                                   self.t.neighbourhoodList)
        courseIds = ['c0070', 'c0001', 'c0004']
        result = sum(
            map(lambda y: tabu.parameter[y][0],
                filter(lambda x: x in courseIds, tabu.parameter)))
        self.assertTrue(format(result, '.2f'), 0.43)

    def test_tabuTenure(self):
        tabu = tabuLists.TabuList(self.data.getAllCourses(),
                                  self.t.neighbourhoodList)
        assignedList = [(0, 'c0001', 'E'), (1, 'c0001', 'B'),
                        (4, 'c0001', 'C'), (7, 'c0002', 'G'),
                        (9, 'c0072', 'E')]
        self.t.addDataToTimetable(assignedList)
        tabu.addTabuMove('c0001', 10, 'E', 1)
        tabu.addTabuMove('c0001', 12, 'E', 1)
        result = tabu.tabuTenure('c0001', self.t.getTimeTable(), self.data)
        self.assertEqual(result, 733.4)
Exemplo n.º 7
0
    def setUp(self):
        self.c = CompetitionDictReader()
        self.data = self.c.readInstance(1)
        self.t = TimeTableFactory.getTimeTable(self.data)
        assigned = [(0, 'c0030', 'B'),\
                    (0, 'c0033', 'B'),\
                    (1, 'c0031', 'B'),\
                    (1, 'c0032', 'B'),\
                    (0, 'c0065', 'B'),\
                    (0, 'c0062', 'B'),\
                    (0, 'c0058', 'B'),\
                    (0, 'c0057', 'B'),\
                    (1, 'c0059', 'B'),\
                    (1, 'c0067', 'B'),\
                    (1, 'c0061', 'B'),\
                    (1, 'c0071', 'B'),\

            ]
        self.t.addDataToTimetable(assigned)
Exemplo n.º 8
0
class LittleTest(object):
    def __init__(self):
        self.c = CompetitionDictReader()
        self.data = self.c.readInstance(22)

    def Run(self):
        #for course in self.data.getAllCourses():
        #    print "Course", course.id, course.typeOfRoom

        for i in range(10):
            courseId = random.choice(self.data.getAllCourseIds())
            print "C.id", courseId
            rooms = filter(lambda x : x.type == self.data.getCourse(courseId).typeOfRoom, self.data.getAllRooms())
            for room in rooms:
                print room.id, room.type
Exemplo n.º 9
0
class LittleTest(object):
    def __init__(self):
        self.c = CompetitionDictReader()
        self.data = self.c.readInstance(22)

    def Run(self):
        #for course in self.data.getAllCourses():
        #    print "Course", course.id, course.typeOfRoom

        for i in range(10):
            courseId = random.choice(self.data.getAllCourseIds())
            print "C.id", courseId
            rooms = filter(
                lambda x: x.type == self.data.getCourse(courseId).typeOfRoom,
                self.data.getAllRooms())
            for room in rooms:
                print room.id, room.type
Exemplo n.º 10
0
    def setUp(self):
        self.c = CompetitionDictReader()
        self.data = self.c.readInstance(1)
        self.t = TimeTableFactory.getTimeTable(self.data)
        assigned = [(0, 'c0030', 'B'),\
                    (0, 'c0033', 'B'),\
                    (1, 'c0031', 'B'),\
                    (1, 'c0032', 'B'),\
                    (0, 'c0065', 'B'),\
                    (0, 'c0062', 'B'),\
                    (0, 'c0058', 'B'),\
                    (0, 'c0057', 'B'),\
                    (1, 'c0059', 'B'),\
                    (1, 'c0067', 'B'),\
                    (1, 'c0061', 'B'),\
                    (1, 'c0071', 'B'),\

            ]
        self.t.addDataToTimetable(assigned)
Exemplo n.º 11
0
class BasicNeighborhoodTest(unittest.TestCase):
    def setUp(self):
        self.c = CompetitionDictReader()
        self.data = self.c.readInstance(1)
        self.t = TimeTableFactory.getTimeTable(self.data)

    def test_simpeSwap(self):
        assignedList = [(0, 'c0001', 'B'), (0, 'c0014', 'B'),
                        (2, 'c0030', 'B'), (2, 'c0001', 'B')]
        self.t.addDataToTimetable(assignedList)
        basicNeighborHood = BasicNeighborhood(self.data)
        basicNeighborHood.simpleSwap(self.t.timeTable,
                                     self.t.neighbourhoodList, 6)
        self.assertEqual(len(basicNeighborHood.getBasicList()), 103)

    def test_simpeSwap2(self):
        path = u"data/TabuSearchDataTests/simpleSwapMove"
        self.t.readLecturesToTimetable(path)
        basicNeighborHood = BasicNeighborhood(self.data)
        basicNeighborHood.simpleSwap(self.t.timeTable,
                                     self.t.neighbourhoodList, 6)
        self.assertEqual(
            len(basicNeighborHood.getPossibleSwapsForCourse('c0001', 0)), 20)
        self.assertEqual(
            len(basicNeighborHood.getPossibleSwapsForCourse('c0014', 0)), 27)
        self.assertEqual(
            len(basicNeighborHood.getPossibleSwapsForCourse('c0005', 1)), 26)
        self.assertEqual(
            len(basicNeighborHood.getPossibleSwapsForCourse('c0016', 5)), 28)
        #for x in basicNeighborHood.getPossibleSwapsForCourse('c0030', 2):
        #   print("PARA")
        #  print(x[0].courseId, x[0].period, x[0].index)
        # print(x[1].courseId, x[1].period, x[1].index)
        self.assertEqual(
            len(basicNeighborHood.getPossibleSwapsForCourse('c0030', 2)), 31)

    def test_basicList(self):
        initialSolution(self.t, self.data)
        tabuList = TabuList(self.data.getAllCourses(),
                            self.t.neighbourhoodList)
        tabuList.addTabuMove("c0001", 1, "a", 1)
        self.assertTrue(tabuList.isTabuMove("c0001", 1, "a", 2, 10))
Exemplo n.º 12
0
class TabuSearchTest(unittest.TestCase):
    def setUp(self):
        self.c = CompetitionDictReader()
        self.data = self.c.readInstance(1)
        self.t = TimeTableFactory.getTimeTable(self.data)
        "Create sorted list of rooms (sorted by capacity)"
        self.sortedRoomIdList = sorted(self.data.getAllRooms(), key=lambda room: room.capacity, reverse=True)

    def test_matchRoomAllocation(self):
        path = u"data/TabuSearchDataTests/matchingRooms"
        self.t.readLecturesToTimetable(path)
        slot = 0
        coursesId = ['c0001', 'c0002', 'c0004', 'c0030', 'c0005', 'c0014', 'c0015', 'c0016']
        self.t.timeTable[slot] = tabuSearch.matchingRoomAllocations(self.t.getTimeTable(), slot, self.data, self.sortedRoomIdList)
        listOfAssignedRooms = [x[1] for x in self.t.timeTable[slot]]
        self.assertEqual(listOfAssignedRooms, ['B', 'S', 'C', 'G', 'F'])
        penalty =  softConstraints2.softConstraintsPenalty(self.t.getTimeTable(), self.data)['penaltyRoomCapacity']
        self.assertEqual(penalty, 340)

        slot = 1
        self.t.timeTable[slot] = tabuSearch.matchingRoomAllocations(self.t.getTimeTable(), slot, self.data, self.sortedRoomIdList)
        listOfAssignedRooms = [x[1] for x in self.t.timeTable[slot]]
        self.assertEqual(listOfAssignedRooms, ['G', 'S', 'E', 'B', 'C', 'F'])
        penalty = softConstraints2.softConstraintsPenalty(self.t.getTimeTable(), self.data)['penaltyRoomCapacity']

        self.assertEqual(penalty, 305)

    def test_coeficientTabuTenure(self):
        tabu = tabuSearch.TabuList(self.data.getAllCourses(), self.t.neighbourhoodList)
        courseIds = ['c0070', 'c0001', 'c0004']
        result = sum(map(lambda y: tabu.parameter[y][0], filter(lambda x: x in courseIds, tabu.parameter)))
        self.assertTrue(format(result, '.2f'), 0.43)

    def test_tabuTenure(self):
        tabu = tabuLists.TabuList(self.data.getAllCourses(), self.t.neighbourhoodList)
        assignedList = [(0, 'c0001', 'E'), (1, 'c0001', 'B'), (4, 'c0001', 'C'), (7, 'c0002', 'G'), (9, 'c0072', 'E')]
        self.t.addDataToTimetable(assignedList)
        tabu.addTabuMove('c0001', 10, 'E', 1)
        tabu.addTabuMove('c0001', 12, 'E', 1)
        result = tabu.tabuTenure('c0001', self.t.getTimeTable(), self.data)
        self.assertEqual(result, 733.4)
Exemplo n.º 13
0
class PerturbationTest(unittest.TestCase):
    def setUp(self):
        self.c = CompetitionDictReader()
        self.data = self.c.readInstance(1)
        self.t = TimeTableFactory.getTimeTable(self.data)
        "Create sorted list of rooms (sorted by capacity)"
        self.sortedRoomIdList = sorted(self.data.getAllRooms(), key=lambda room: room.capacity, reverse=True)

    def testSelectRandom(self):
        listItems = [('c5', 0), ('c1', 1), ('c6', 3), ('c4', 2), ('c4', 9), ('c2', 8)]
        selectedValues = selectRandom(listItems, 5)
        selectedValuesSet = set(selectedValues)
        self.assertEqual(len(selectedValues), 5)
        self.assertEqual(len(selectedValuesSet), 5)

    def testRankingOfLectures(self):
        path = u"data/TabuSearchDataTests/softConstraintsLectures"
        self.t.readLecturesToTimetable(path)
        n = 4
        q = 13
        selectedValues = rankingOfLectures(self.t.getTimeTable(), self.data, n, q)
        uniqueSelectedValues = set(selectedValues)
        self.assertEqual(len(uniqueSelectedValues), len(selectedValues))
Exemplo n.º 14
0
class AdvancedNeighborhoodTest(TestCase):
    def setUp(self):
        self.c = CompetitionDictReader()
        self.data = self.c.readInstance(1)
        self.t = TimeTableFactory.getTimeTable(self.data)
        assigned = [(0, 'c0030', 'B'),\
                    (0, 'c0033', 'B'),\
                    (1, 'c0031', 'B'),\
                    (1, 'c0032', 'B'),\
                    (0, 'c0065', 'B'),\
                    (0, 'c0062', 'B'),\
                    (0, 'c0058', 'B'),\
                    (0, 'c0057', 'B'),\
                    (1, 'c0059', 'B'),\
                    (1, 'c0067', 'B'),\
                    (1, 'c0061', 'B'),\
                    (1, 'c0071', 'B'),\

            ]
        self.t.addDataToTimetable(assigned)

    def testGenerateChain(self):

        a = AdvancedNeighborhood()
        chains = a.generateChains(self.t, 0, 1)
        expected = {
            1: ["c0030", "c0031", "c0032", "c0033"],
            2: ["c0057", "c0059", "c0065"],
            3: ["c0061", "c0062", "c0071"],
            4: ["c0058"],
            5: ["c0067"]
        }
        for a in chains:
            self.assertSequenceEqual(sorted(chains[a]), sorted(expected[a]))

    def testGeneratePairs(self):
        a = AdvancedNeighborhood()
        chains = a.generateChains(self.t, 0, 1)
        pairs = a.generatePossibleSwappingPairs(self.t, chains)

    def testKempeSwap(self):
        a = AdvancedNeighborhood()
        chains = a.generateChains(self.t, 0, 1)
        n = a.kempeSwap(self.t, 0, 1 ,\
                        (chains[2], chains[3])\
        )
        expectedChain1 = ["c0059", "c0033", "c0061", "c0030", "c0058", "c0071"]
        expectedChain2 = ["c0065", "c0032", "c0062", "c0031", "c0067", "c0057"]

        self.assertSequenceEqual(
            sorted(map(lambda x: x[0], n["newPeriods"][0])),
            sorted(expectedChain1))
        self.assertSequenceEqual(
            sorted(map(lambda x: x[0], n["newPeriods"][1])),
            sorted(expectedChain2))
        # TODO: tests for single swap
        m = a.kempeSwap(self.t, 0, 1, (chains[1], set()))

        expectedSingle1 = sorted(
            ["c0031", "c0032", "c0065", "c0062", "c0058", "c0057"])
        expectedSingle2 = sorted(
            ["c0030", "c0033", "c0059", "c0067", "c0061", "c0071"])

        self.assertSequenceEqual(
            sorted(map(lambda x: x[0], m["newPeriods"][0])), expectedSingle1)
        self.assertSequenceEqual(
            sorted(map(lambda x: x[0], m["newPeriods"][1])), expectedSingle2)

        for a in m["moves"]:
            print a[0], a[1]

    def testExploreNeighborhood(self):
        a = AdvancedNeighborhood()
Exemplo n.º 15
0
 def setUp(self):
     self.c = CompetitionDictReader()
     self.data = self.c.readInstance(1)
     self.t = TimeTableFactory.getTimeTable(self.data)
     "Create sorted list of rooms (sorted by capacity)"
     self.sortedRoomIdList = sorted(self.data.getAllRooms(), key=lambda room: room.capacity, reverse=True)
Exemplo n.º 16
0
class softConstraintsTest(unittest.TestCase):
    def setUp(self):
        self.c = CompetitionDictReader()
        self.data = self.c.readInstance(1)
        self.t = TimeTableFactory.getTimeTable(self.data)

    """Test for soft constraints function counting minimum working days"""
    def testSoftConstraintsMinimumWorkingDays(self):
        assignedList = [(0, 'c0001', 'E'), (1, 'c0001', 'B'), (2, 'c0001', 'B'), (3, 'c0001', 'B'), (0, 'c0004', 'B'), (1, 'c0004', 'B'), (2, 'c0004', 'B')]
        self.t.addDataToTimetable(assignedList)
        penalty = softConstraints2.softConstraintsPenalty(self.t.getTimeTable(), self.data)['penaltyMinWorkingDays']
        self.assertEqual(penalty, 520)
        assignedList = [(3, 'c0004', 'B'), (4, 'c0004', 'B'), (5, 'c0004', 'B')]
        self.t.addDataToTimetable(assignedList)
        penalty = softConstraints2.softConstraintsPenalty(self.t.getTimeTable(), self.data)['penaltyMinWorkingDays']
        self.assertEqual(penalty, 520)
        assignedList = [(12, 'c0004', 'B'), (4, 'c0001', 'B'), (5, 'c0001', 'B')]
        self.t.addDataToTimetable(assignedList)
        penalty = softConstraints2.softConstraintsPenalty(self.t.getTimeTable(), self.data)['penaltyMinWorkingDays']
        self.assertEqual(penalty, 515)

    """Test for soft constraints function counting penalty for room stability"""
    def testSoftConstraintsRoomStability(self):
        assignedList = [(0, 'c0001', 'E'), (1, 'c0001', 'B'), (2, 'c0001', 'C'), (3, 'c0001', 'G'), (0, 'c0004', 'B'), (1, 'c0004', 'B'), (2, 'c0004', 'B')]
        self.t.addDataToTimetable(assignedList)
        penalty = softConstraints2.softConstraintsPenalty(self.t.getTimeTable(), self.data)['penaltyRoomStability']
        self.assertEqual(penalty, 3)


    """Test for soft constraints penalty for curriculum compactness"""
    def testSoftConstraintsCurriculumCompactness(self):
        assignedList = [(0, 'c0001', 'E'), (1, 'c0001', 'B'), (4, 'c0001', 'C'), (7, 'c0002', 'G'), (9, 'c0072', 'E')]
        self.t.addDataToTimetable(assignedList)
        penalty = softConstraints2.softConstraintsPenalty(self.t.getTimeTable(), self.data)['penaltyCurriculumCompactness']
        self.assertEqual(penalty, 10)

    """Test for helper function to count curriculum compactness"""
    def testCountPenaltyForCurriculumCompactness(self):
        penalty = softConstraints2.countPenaltyForCurriculumCompactness([0, 1, 4, 7], 6)
        self.assertEqual(penalty, 2)
        penalty = softConstraints2.countPenaltyForCurriculumCompactness([0, 1, 4, 7, 8, 20, 29], 6)
        self.assertEqual(penalty, 3)
        penalty = softConstraints2.countPenaltyForCurriculumCompactness([0, 1, 2, 4, 5, 6, 7], 4)
        self.assertEqual(penalty, 0)
        penalty = softConstraints2.countPenaltyForCurriculumCompactness([0, 1, 3, 4, 5, 6, 7], 4)
        self.assertEqual(penalty, 1)

    def testTotalSoftConstrainsPenalty(self):
        assignedList = [(0, 'c0001', 'E'), (1, 'c0001', 'B'), (4, 'c0001', 'C'), (7, 'c0002', 'G'), (9, 'c0072', 'E')]
        self.t.addDataToTimetable(assignedList)
        penalty = softConstraints2.softConstraintsPenalty(self.t.getTimeTable(), self.data)['penaltyCurriculumCompactness']
        self.assertEqual(penalty, 10)


    def testTotalSoftConstraintsPenalty2(self):
        expectedResult = reduce(lambda x, y: x + y, map(lambda z: z.minWorkingDays, self.data.getAllCourses())) * 5
        penalty = softConstraints2.softConstraintsPenalty(self.t.getTimeTable(), self.data)['penaltyMinWorkingDays']
        self.assertEqual(penalty, expectedResult)

        path = u"data/TabuSearchDataTests/softConstraintsLectures"
        self.t.readLecturesToTimetable(path)
        penalty = softConstraints2.softConstraintsPenalty(self.t.getTimeTable(), self.data)['penaltyRoomStability']
        self.assertEqual(penalty, 4)
        penalty = softConstraints2.softConstraintsPenalty(self.t.getTimeTable(), self.data)['penaltyRoomCapacity']
        self.assertEqual(penalty, 440)
        penalty = softConstraints2.softConstraintsPenalty(self.t.getTimeTable(), self.data)['penaltyMinWorkingDays']
        self.assertEqual(penalty, 490)
        penalty = softConstraints2.softConstraintsPenalty(self.t.getTimeTable(), self.data)['penaltyCurriculumCompactness']
        self.assertEqual(penalty, 24)
        penalty = softConstraints2.softConstraintsPenalty(self.t.getTimeTable(), self.data)['totalPenalty']
        self.assertEqual(penalty, 958)


    """Perturbation penalty"""
    def testSoftConstraintsRoomStability22(self):
        assignedList = [(0, 'c0001', 'E'), (1, 'c0001', 'B'), (2, 'c0001', 'C'), (3, 'c0001', 'G'), (0, 'c0004', 'B'), (1, 'c0004', 'B'), (2, 'c0004', 'B')]
        self.t.addDataToTimetable(assignedList)
        result = softConstraints2.softConstraintsPenalty(self.t.getTimeTable(), self.data, "perturbation")
        penaltyRoomStability = result['penaltyRoomStability']
        self.assertEqual(penaltyRoomStability, 3)
        self.assertEqual(len(result['perturbationPenalty']), len((assignedList)))


    """Perturbation"""
    def testSoftConstraintsPerturbation(self):
        assignedList = [(0, 'c0001', 'E'), (1, 'c0001', 'B'), (4, 'c0001', 'C'), (7, 'c0002', 'G'), (9, 'c0072', 'E')]
        self.t.addDataToTimetable(assignedList)
        result = softConstraints2.softConstraintsPenalty(self.t.getTimeTable(), self.data, "perturbation")
        self.assertEqual(sum(map(lambda x: result['perturbationPenalty'][x], result['perturbationPenalty'])), 896)
Exemplo n.º 17
0
class DataSchoolTest(unittest.TestCase):
    def setUp(self):
        self.c = CompetitionDictReader()
        self.data = self.c.readInstance(22)

        self.t = TimeTableFactory.getTimeTable(self.data)
Exemplo n.º 18
0
class AdvancedNeighborhoodTest(TestCase):
    def setUp(self):
        self.c = CompetitionDictReader()
        self.data = self.c.readInstance(1)
        self.t = TimeTableFactory.getTimeTable(self.data)
        assigned = [(0, 'c0030', 'B'),\
                    (0, 'c0033', 'B'),\
                    (1, 'c0031', 'B'),\
                    (1, 'c0032', 'B'),\
                    (0, 'c0065', 'B'),\
                    (0, 'c0062', 'B'),\
                    (0, 'c0058', 'B'),\
                    (0, 'c0057', 'B'),\
                    (1, 'c0059', 'B'),\
                    (1, 'c0067', 'B'),\
                    (1, 'c0061', 'B'),\
                    (1, 'c0071', 'B'),\

            ]
        self.t.addDataToTimetable(assigned)


    def testGenerateChain(self):


        a = AdvancedNeighborhood()
        chains = a.generateChains(self.t, 0, 1)
        expected = {
            1: ["c0030", "c0031", "c0032", "c0033"],
            2: ["c0057", "c0059", "c0065"],
            3: ["c0061", "c0062", "c0071"],
            4: ["c0058"],
            5: ["c0067"]
        }
        for a in chains:
            self.assertSequenceEqual(sorted(chains[a]), sorted(expected[a]))

    def testGeneratePairs(self):
        a = AdvancedNeighborhood()
        chains = a.generateChains(self.t, 0, 1)
        pairs = a.generatePossibleSwappingPairs(self.t, chains)


    def testKempeSwap(self):
        a = AdvancedNeighborhood()
        chains = a.generateChains(self.t, 0, 1)
        n = a.kempeSwap(self.t, 0, 1 ,\
                        (chains[2], chains[3])\
        )
        expectedChain1 = ["c0059", "c0033", "c0061", "c0030", "c0058", "c0071"]
        expectedChain2 = ["c0065", "c0032", "c0062", "c0031", "c0067", "c0057"]

        self.assertSequenceEqual(sorted(map(lambda x: x[0], n["newPeriods"][0])), sorted(expectedChain1))
        self.assertSequenceEqual(sorted(map(lambda x: x[0], n["newPeriods"][1])), sorted(expectedChain2))
        # TODO: tests for single swap
        m = a.kempeSwap(self.t, 0,1,(chains[1], set()))

        expectedSingle1 = sorted(["c0031", "c0032", "c0065", "c0062", "c0058", "c0057"])
        expectedSingle2 = sorted(["c0030", "c0033", "c0059", "c0067", "c0061", "c0071"])

        self.assertSequenceEqual(sorted(map(lambda x: x[0], m["newPeriods"][0])), expectedSingle1)
        self.assertSequenceEqual(sorted(map(lambda x: x[0], m["newPeriods"][1])), expectedSingle2)

        for a in m["moves"]:
            print a[0], a[1]


    def testExploreNeighborhood(self):
        a = AdvancedNeighborhood()
Exemplo n.º 19
0
class GATest(object):
    def Run(self):
        self.c = CompetitionDictReader()
        self.data = self.c.readInstance(22)
        self.ga = GeneticAlgorithm(self.data)
Exemplo n.º 20
0
class GATest(object):
    def Run(self):
        self.c = CompetitionDictReader()
        self.data = self.c.readInstance(3)
        self.ga = GeneticAlgorithm(self.data)
Exemplo n.º 21
0
 def __init__(self):
     self.c = CompetitionDictReader()
     self.data = self.c.readInstance(22)
Exemplo n.º 22
0
class TimetableTest(unittest.TestCase):
    def setUp(self):
        self.c = CompetitionDictReader()
        self.data = self.c.readInstance(1)
        self.t = TimeTableFactory.getTimeTable(self.data)

    def test_initial(self):
        self.assertEquals(len(self.t.getTimeTable()), 30)
        day = randint(0, self.data.daysNum - 1)
        day_period = randint(0, self.data.periodsPerDay - 1)
        self.assertEquals(self.t.getValueSlot(day, day_period), [])

    def test_getKeyConstraintsOfCourse(self):
        keysConstraintsOfCourse = self.t.getKeyConstraintsOfCourse(self.data.getAllConstraints(), 'c0001')

        self.assertSequenceEqual(keysConstraintsOfCourse, [24, 25, 26, 27, 28, 29])

    def test_availablePeriodsRooms1(self):
        counter = self.t.availablePeriodsRooms(self.data.getAllConstraints(), 'c0001')['availablePeriodsNum']
        self.assertEqual(counter, 24)
        counter = self.t.availablePeriodsRooms(self.data.getAllConstraints(), 'c0002')['availablePeriodsNum']
        self.assertEqual(counter, 30)

    def test_availablePeriodsRooms2(self):
        assignedList = [(0, 'c0001', 'B'), (1, 'c0002', 'B'), (2, 'c0001', 'B'), (24, 'c0001', 'B')]
        self.t.addDataToTimetable(assignedList)
        counter = self.t.availablePeriodsRooms(self.data.getAllConstraints(), 'c0001')['availablePeriodsNum']
        self.assertEqual(counter, 21)
        counter = self.t.availablePeriodsRooms(self.data.getAllConstraints(), 'c0002')['availablePeriodsNum']
        self.assertEqual(counter, 26)

    def test_availablePeriodsRooms3(self):
        assignedList = [(0, 'c0001', 'B'), (1, 'c0002', 'B'), (1, 'c0014', 'C'), (3, 'c0014', 'C'),(2, 'c0004', 'C'), (24, 'c0001', 'B') ]
        self.t.addDataToTimetable(assignedList)
        counter = self.t.availablePeriodsRooms(self.data.getAllConstraints(), 'c0001')['availablePeriodsNum']
        self.assertEqual(counter, 21)
        counter = self.t.availablePeriodsRooms(self.data.getAllConstraints(), 'c0002')['availablePeriodsNum']
        self.assertEqual(counter, 26)
        counter = self.t.availablePeriodsRooms(self.data.getAllConstraints(), 'c0014')['availablePeriodsNum']
        self.assertEqual(counter, 28)
        counter = self.t.availablePeriodsRooms(self.data.getAllConstraints(), 'c0071')['availablePeriodsNum']
        self.assertEqual(counter, 15)

    def test_createListOfRooms(self):
        listOfRooms = self.t.createListOfRooms(self.data.getAllRooms(), self.data.getCourse("c0001"))
        self.assertEqual(listOfRooms, set(['B']))
        listOfRooms = self.t.createListOfRooms(self.data.getAllRooms(), self.data.getCourse("c0002"))
        self.assertEqual(listOfRooms, set(['B', 'C']))
        listOfRooms = self.t.createListOfRooms(self.data.getAllRooms(), self.data.getCourse("c0072"))
        self.assertEqual(listOfRooms, set(['B', 'C', 'E', 'F', 'G', 'S']))

    def test_getRoomsIdForCourses(self):
        self.assertEqual(self.t.roomsIdListForCourses['c0014'], set(['B', 'C']))
        self.assertEqual(self.t.roomsIdListForCourses['c0065'], set(['B', 'C', 'E', 'F', 'G', 'S']))
        self.assertEqual(self.t.roomsIdListForCourses['c0030'], set(['B', 'C', 'F', 'G', 'S']))
        self.assertEqual(self.t.roomsIdListForCourses['c0032'], set(['B', 'C']))
        self.assertEqual(self.t.roomsIdListForCourses['c0031'], set(['B', 'C', 'F', 'G', 'S']))

    def test_createNeighbourhoodList(self):
        neighbourhoodList = self.t.createNeighbourhoodList(self.data.getAllCurricula(), self.data.getAllCourses())
        path = u"data/TabuSearchDataTests/neighbourhoodCourses"
        f = open(path, "r")
        # test commented, different key order in actual and expected
        # possible solution: serialize expected, in test compare actual and deserialized
        # self.assertEqual(str(neighbourhoodList), f.readline().strip())

    """Test for list of availablePeriods and availablePairs"""
    def test_availabeNumberOfPeriods4(self):
        periodsList = self.t.availablePeriodsRooms(self.data.getAllConstraints(), 'c0001')['availablePeriods']
        self.assertEqual(periodsList, set(range(0, 24)))

        assignedList = [(10, 'c0001', 'B'),(14, 'c0014', 'C'), (14, 'c0030', 'B'), (11, 'c0002', 'B'), (12, 'c0004', 'B') ]
        self.t.addDataToTimetable(assignedList)

        result = self.t.availablePeriodsRooms(self.data.getAllConstraints(), 'c0001')

        self.assertEqual(result['availablePeriods'], set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]))
        self.assertEqual(result['availablePairsNum'], 20)
        result = self.t.availablePeriodsRooms(self.data.getAllConstraints(), 'c0002')
        self.assertEqual(result['availablePairsNum'], 52)

        self.t.timeTable[13].append(('c0057', 'E'))
        result = self.t.availablePeriodsRooms(self.data.getAllConstraints(), 'c0002')
        self.assertEqual(result['availablePairsNum'], 52)

        self.t.timeTable[13].append(('c0066', 'B'))
        self.t.timeTable[15].append(('c0005', 'B'))
        result = self.t.availablePeriodsRooms(self.data.getAllConstraints(), 'c0002')
        self.assertEqual(result['availablePairsNum'], 49)
        self.assertEqual(result['availablePeriodsNum'], 26)

    def test_availabeNumberOfPeriods5(self):
        periodsListC33 = self.t.availablePeriodsRooms(self.data.getAllConstraints(), 'c0033')['availablePeriods']
        periodsListC30 = self.t.availablePeriodsRooms(self.data.getAllConstraints(), 'c0030')['availablePeriods']
        periodsListC32 = self.t.availablePeriodsRooms(self.data.getAllConstraints(), 'c0032')['availablePeriods']
        self.assertEqual(periodsListC33, set(range(0, 20)))
        self.assertEqual(periodsListC30, set(range(0, 30)))
        self.assertEqual(periodsListC32, set(range(0, 30)))
        self.t.timeTable[0].append(('c0001', 'B'))
        self.t.timeTable[0].append(('c0002', 'C'))
        result = self.t.availablePeriodsRooms(self.data.getAllConstraints(), 'c0033')
        self.assertEqual(result['availablePairsNum'], 38)
        self.assertEqual(result['availablePeriodsNum'], 20)
        assignedList = [(1, 'c0030', 'B'), (2, 'c0030', 'C'), (2, 'c0001', 'B'), (3, 'c0031', 'B'), (4, 'c0004', 'S') ]
        self.t.addDataToTimetable(assignedList)
        result = self.t.availablePeriodsRooms(self.data.getAllConstraints(), 'c0030')
        self.assertEqual(result['availablePairsNum'], 136)
        self.assertEqual(result['availablePeriodsNum'], 28)
        self.t.timeTable[4].append(('c0031', 'B'))
        self.t.timeTable[5].append(('c0004', 'C'))
        result = self.t.availablePeriodsRooms(self.data.getAllConstraints(), 'c0031')
        self.assertEqual(result['availablePeriodsNum'], 28)
        self.assertEqual(result['availablePairsNum'], 134)
        result = self.t.availablePeriodsRooms(self.data.getAllConstraints(), 'c0032')
        self.assertEqual(result['availablePeriodsNum'], 26)
        self.assertEqual(result['availablePairsNum'], 49)
        result = self.t.availablePeriodsRooms(self.data.getAllConstraints(), 'c0033')
        self.assertEqual(result['availablePairsNum'], 29)
        self.assertEqual(result['availablePeriodsNum'], 16)
        self.assertEqual(result['availablePeriods'], set([0, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]))
        path = u"data/TabuSearchDataTests/availablePeriodsRooms5"
        f = open(path, "r")
        self.assertEqual(str(result['availablePairs']), f.readline().strip())

    """Test for checkIfAvailable function (check unavailableRooms and if period is available)"""
    def test_checkifAvailable(self):
        self.t.timeTable[0].append(('c0001', 'B'))
        self.t.timeTable[0].append(('c0030', 'C'))
        result = self.t.checkIfAvailable(self.t.timeTable[0], 'c0033')
        self.assertEqual(result['period'], False)
        self.assertEqual(result['unavailableRooms'], set())
        result = self.t.checkIfAvailable(self.t.timeTable[0], 'c0031')
        self.assertEqual(result['period'], True)
        self.assertEqual(result['unavailableRooms'], set(['B', 'C']))

    def test_assignedLectures(self):
        assignedList = [(0, 'c0001', 'B'), (0, 'c0002', 'C'), (1, 'c0030', 'B'),(2, 'c0030', 'C'), (2, 'c0001', 'B'), (3, 'c0031', 'B'), (4, 'c0004', 'S'), (4, 'c0031', 'B'), (5, 'c0004', 'C')]
        self.t.addDataToTimetable(assignedList)
        courseId = 'c0030'
        result = self.t.assignedLectures(courseId)
        self.assertEquals(len(result), 2)
        # check if all selected assignments match courseId
        self.assertTrue(all(map(lambda x: x[0] == courseId, result)))
        self.assertSequenceEqual(map(lambda x: x[1], result), ['B', 'C'])


    """Test for function reading lectures to timetable from input file"""
    def test_readLecturesToTimetable(self):
        path = u"data/TabuSearchDataTests/lecturesToTimetable"
        self.t.readLecturesToTimetable(path)
        courseId = 'c0001'
        result = self.t.assignedLectures(courseId)
        self.assertEqual(len(result), 2)
        self.assertTrue(all(map(lambda x: x[0] == courseId, result)))
        self.assertSequenceEqual(map(lambda x: x[1], result), ['B', 'E'])
        courseId = 'c0008'
        self.assertEqual(len(self.t.getTimeTable()[0]), 2)
Exemplo n.º 23
0
class DataSchoolTest(unittest.TestCase):
    def setUp(self):
        self.c = CompetitionDictReader()
        self.data = self.c.readInstance(22)

        self.t = TimeTableFactory.getTimeTable(self.data)
Exemplo n.º 24
0
 def __init__(self):
     self.c = CompetitionDictReader()
     self.data = self.c.readInstance(22)
Exemplo n.º 25
0
from cats.ga.geneticAlgorithm import GeneticAlgorithm

__author__ = 'tomek'
import time
import sys


from cats.readers.competitionReader import  CompetitionDictReader


fileName = sys.argv[1]
timeLimit = float(sys.argv[2])


c = CompetitionDictReader()
data = c.read(fileName)

ga = GeneticAlgorithm(data, timeLimit)
Exemplo n.º 26
0
 def Run(self):
     self.c = CompetitionDictReader()
     self.data = self.c.readInstance(22)
     self.ga = GeneticAlgorithm(self.data)
Exemplo n.º 27
0
 def Run(self):
     self.c = CompetitionDictReader()
     self.data = self.c.readInstance(3)
     self.ga = GeneticAlgorithm(self.data)
Exemplo n.º 28
0
 def setUp(self):
     self.c = CompetitionDictReader()
     self.data = self.c.readInstance(1)
     self.t = TimeTableFactory.getTimeTable(self.data)
Exemplo n.º 29
0
from cats.ga.geneticAlgorithm import GeneticAlgorithm

__author__ = 'tomek'
import time
import sys

from cats.readers.competitionReader import CompetitionDictReader

fileName = sys.argv[1]
timeLimit = float(sys.argv[2])

c = CompetitionDictReader()
data = c.read(fileName)

ga = GeneticAlgorithm(data, timeLimit)