def hopkroft(graph, structure):
    transformed_graph = {}

    supervisors = graph.getEdges()
    students = graph.getStuEdges()
    correspondence = {}
    sup_name = 0
    list_supervisors = [supervisor for supervisor in supervisors]
    list_students = [student for student in students]
    random.shuffle(list_supervisors)
    random.shuffle(list_students)
    a_to_b = {}
    for i in range(len(list_students)):
        a_to_b[list_students[i]] = 'stu' + str(i)

    for supervisor in list_supervisors:
        cardinality = structure[supervisor]
        for i in range(cardinality):
            for stu in supervisors[supervisor]:
                transformed_graph.setdefault(sup_name, set()).add(a_to_b[stu])
            correspondence[sup_name] = supervisor
            sup_name = sup_name + 1
    m = HopcroftKarp(transformed_graph).maximum_matching()

    result = BipartiteGraph()
    for student in students:
        sup_code = m[a_to_b[student]]
        result.addEdge(correspondence[sup_code], student)
    return result
    def test_case18(self):
        """Testing the isValid function - passing a null graph"""

        graph = BipartiteGraph()
        solution = Solution(graph)
        
        result = solution.isValid(self.students,self.supervisors)

        self.assertFalse(result)
Ejemplo n.º 3
0
    def test_case3(self):
        """Testing addEdge function when adding an edge that already exists"""

        graph = BipartiteGraph()
        graph.addEdge("supervisor1", "student1")
        graph.addEdge("supervisor1", "student1")

        val1 = graph.getSupervisorDegree("supervisor1")
        val2 = graph.getStudentDegree("student1")

        self.assertEqual((val1, val2), (1, 1))
Ejemplo n.º 4
0
    def test_case6(self):
        """Testing the removeEdge function in a graph with existing nodes and edges"""

        graph = BipartiteGraph()

        graph.addEdge("supervisor1", "student1")
        graph.removeEdge("supervisor1", "student1")

        val1 = graph.getStudentDegree("student1")
        val2 = graph.getSupervisorDegree("supervisor1")

        self.assertEqual((val1, val2), (0, 0))
    def test_case20(self):
        """Testing the isValid function - when number of students less than actual"""

        graph = BipartiteGraph()
        
        graph.addEdge("supervisor1","student1")
        graph.addEdge("supervisor3","student3")
        graph.addEdge("supervisor2","student2")

        solution = Solution(graph)

        result = solution.isValid(self.students,self.supervisors)

        self.assertFalse(result)
Ejemplo n.º 6
0
    def test_case1(self):
        """Testing addEdge function in an empty graph"""

        graph = BipartiteGraph()

        graph.addEdge("supervisor1", "student1")

        val1 = graph.getStudents("supervisor1")
        val2 = graph.getSupervisors("student1")

        expected1 = ["student1"]
        expected2 = ["supervisor1"]

        self.assertEqual((val1, val2), (expected1, expected2))
Ejemplo n.º 7
0
    def test_case2(self):
        """Testing addEdge function in a graph with existing nodes and edges"""

        graph = BipartiteGraph()

        graph.addEdge("supervisor1", "student1")
        graph.addEdge("supervisor2", "student4")
        graph.addEdge("supervisor3", "student3")

        val1 = graph.getSupervisorDegree("supervisor1")

        graph.addEdge("supervisor1", "student2")

        curr = graph.getSupervisorDegree("supervisor1")
        val2 = graph.getSupervisors("student2")
        expected2 = ["supervisor1"]

        self.assertEqual((curr - 1, expected2), (val1, val2))
def uniform(solution1, solution2, supervisors, students, k=None):
    """
    An implementation of uniform crossover
    """
    graph1 = solution1.getGraph()
    graph2 = solution2.getGraph()

    stuEdges1 = graph1.getStuEdges()
    stuEdges2 = graph2.getStuEdges()

    g = BipartiteGraph()
    for stu in students:
        if random.random() < 0.5:
            sup = stuEdges1[stu][0]
        else:
            sup = stuEdges2[stu][0]
        g.addEdge(sup, stu)

    fixSolution(g, supervisors, students)
    return Solution(g)
    def setUp(self):

        #Creating a list of students and supervisors

        topicNames, topicPaths, topicIDs, levels = parseFile(
            "pystsup/test/acm.txt")

        self.supervisors = {}
        self.students = {}

        stuID = "student"
        supID = "supervisor"

        stuList1 = [
            "MapReduce-based systems", "Multidimensional range search",
            "Open source software", "Data mining", "Online shopping"
        ]
        stuList2 = [
            "Heuristic function construction", "Multi-agent systems",
            "Open source software", "Data mining", "Speech recognition"
        ]
        stuList3 = [
            "Multi-agent systems", "Speech recognition",
            "Heuristic function construction", "Data mining",
            "Object identification"
        ]
        stuList4 = [
            "Multi-agent systems", "Intelligent agents", "Speech recognition",
            "Object identification", "Heuristic function construction"
        ]

        supList1 = [
            "Multi-agent systems", "Intelligent agents",
            "MapReduce-based systems", "Object identification",
            "Heuristic function construction"
        ]
        supList2 = [
            "Open source software", "Data mining", "Speech recognition",
            "Object identification", "Heuristic function construction"
        ]
        supList3 = [
            "Multi-agent systems", "Intelligent agents", "Speech recognition",
            "Object identification", "Heuristic function construction"
        ]

        supList = [supList1, supList2, supList3]
        supQuota = [2, 2, 1]
        stuList = [stuList1, stuList2, stuList3, stuList4]

        for i in range(3):
            toAdd = []
            sup_list = {}
            rank = 0
            for kw in supList[i]:
                rank += 1
                sup_list[rank] = [
                    kw, getPath(kw, topicNames, topicPaths, topicIDs)
                ]

            sup = supID + str(i + 1)
            quota = supQuota[i]

            supervisorObject = Supervisor(sup, sup_list, quota)

            self.supervisors[sup] = supervisorObject

        for i in range(4):
            toAdd = []
            stu_list = {}
            rank = 0
            for kw in stuList[i]:
                rank += 1
                stu_list[rank] = [
                    kw, getPath(kw, topicNames, topicPaths, topicIDs)
                ]

            stu = stuID + str(i + 1)
            studentObject = Student(stu, stu_list)
            self.students[stu] = studentObject

        # Generating rank weights for c = 0.5

        self.rankWeights = Solution.calcRankWeights()

        #Creating fitness cache

        self.dummySolution = Solution()

        self.fitnessCache = {}

        for sup in self.supervisors:
            supervisorKeywords = self.supervisors[sup].getKeywords()
            for stu in self.students:
                studentKeywords = self.students[stu].getKeywords()
                f_stu, f_sup = self.dummySolution.kw_similarity(
                    studentKeywords, supervisorKeywords, self.rankWeights)
                self.fitnessCache[str((stu, sup))] = (f_stu, f_sup)

        # Creating two graphs and solutions

        self.graph1 = BipartiteGraph()
        self.graph2 = BipartiteGraph()

        self.graph1.addEdge("supervisor1", "student2")
        self.graph1.addEdge("supervisor2", "student4")
        self.graph1.addEdge("supervisor3", "student1")
        self.graph1.addEdge("supervisor1", "student3")

        self.solution1 = Solution(self.graph1)

        self.graph2.addEdge("supervisor1", "student2")
        self.graph2.addEdge("supervisor2", "student1")
        self.graph2.addEdge("supervisor3", "student4")
        self.graph2.addEdge("supervisor1", "student3")

        self.solution2 = Solution(self.graph2)
Ejemplo n.º 10
0
    def setUp(self):

        self.graph1 = BipartiteGraph()
        self.graph2 = BipartiteGraph()

        self.graph1.addEdge("supervisor1", "student1")
        self.graph1.addEdge("supervisor2", "student4")
        self.graph1.addEdge("supervisor3", "student3")
        self.graph1.addEdge("supervisor1", "student2")

        self.graph2.addEdge("supervisor1", "student4")
        self.graph2.addEdge("supervisor2", "student1")
        self.graph2.addEdge("supervisor2", "student3")
        self.graph2.addEdge("supervisor3", "student2")

        #Creating a list of students and supervisors

        topicNames, topicPaths, topicIDs, levels = parseFile(
            "pystsup/test/acm.txt")

        self.supervisors = {}
        self.students = {}

        stuID = "student"
        supID = "supervisor"

        stuList1 = [
            "MapReduce-based systems", "Multidimensional range search",
            "Open source software", "Data mining", "Online shopping"
        ]
        stuList2 = [
            "Heuristic function construction", "Multi-agent systems",
            "Open source software", "Data mining", "Speech recognition"
        ]
        stuList3 = [
            "Multi-agent systems", "Speech recognition",
            "Heuristic function construction", "Data mining",
            "Object identification"
        ]
        stuList4 = [
            "Multi-agent systems", "Intelligent agents", "Speech recognition",
            "Object identification", "Heuristic function construction"
        ]

        supList1 = [
            "Multi-agent systems", "Intelligent agents",
            "MapReduce-based systems", "Object identification",
            "Heuristic function construction"
        ]
        supList2 = [
            "Open source software", "Data mining", "Speech recognition",
            "Object identification", "Heuristic function construction"
        ]
        supList3 = [
            "Multi-agent systems", "Intelligent agents", "Speech recognition",
            "Object identification", "Heuristic function construction"
        ]

        supList = [supList1, supList2, supList3]
        supQuota = [2, 2, 1]
        stuList = [stuList1, stuList2, stuList3, stuList4]

        for i in range(3):
            toAdd = []
            sup_list = {}
            rank = 0
            for kw in supList[i]:
                rank += 1
                sup_list[kw] = [
                    rank, getPath(kw, topicNames, topicPaths, topicIDs)
                ]

            sup = supID + str(i + 1)
            quota = supQuota[i]

            supervisorObject = Supervisor(sup, sup_list, quota)

            self.supervisors[sup] = supervisorObject

        for i in range(4):
            toAdd = []
            stu_list = {}
            rank = 0
            for kw in stuList[i]:
                rank += 1
                stu_list[kw] = [
                    rank, getPath(kw, topicNames, topicPaths, topicIDs)
                ]

            stu = stuID + str(i + 1)
            studentObject = Student(stu, stu_list)
            self.students[stu] = studentObject
Ejemplo n.º 11
0
    def test_case4(self):
        """Testing the remove edge function in an empty graph"""

        graph = BipartiteGraph()
        self.assertRaises(KeyError,
                          lambda: graph.removeEdge("supervisor1", "student1"))
def kPoint(solution1, solution2, supervisors, students, k=5):
    """
    An Implementation of K-Point crossover for this problem.
    """
    graph1 = solution1.getGraph()
    graph2 = solution2.getGraph()

    stuEdges1 = graph1.getStuEdges()
    stuEdges2 = graph2.getStuEdges()
    supEdges1 = graph1.getEdges()

    #Randomly getting the structure from the two graphs

    num = random.randint(1, 2)
    if num == 1:
        structure = graph1.getStructure()
    else:
        structure = graph2.getStructure()

    #Setting up the vectors

    students = list(stuEdges1.keys())
    sol1 = []
    sol2 = []
    for i in range(len(students)):
        sol1.append(stuEdges1[students[i]][0])
        sol2.append(stuEdges2[students[i]][0])

    #Dividing the both solutions into k-points

    sol1Points = []
    sol2Points = []

    points = sorted(random.sample(range(1, len(students)), k))
    curr = 0

    for i in range(k - 1):
        sol1Points.append(sol1[curr:points[i]])
        sol2Points.append(sol2[curr:points[i]])
        curr = points[i]

    sol1Points.append(sol1[curr:])
    sol2Points.append(sol2[curr:])

    #Perform the crossover

    result = []

    if k == 0:
        n = random.randint(1, 2)
        if n == 1:
            result = sol1
        else:
            result = sol2

    else:

        for point in range(k):
            n = random.randint(1, 2)
            if n == 1:
                result.extend(sol1Points[point])
            else:
                result.extend(sol2Points[point])

    graph = BipartiteGraph()
    for i in range(len(students)):
        graph.addEdge(result[i], students[i])

    fixSolution(graph, supervisors, students)
    #supEdges = graph.getEdges()
    #availableStudents = set()
    #reqSup = set(list(supEdges1.keys())).difference(set(list(supEdges.keys())))

    #sol3 = Solution(graph)
    #canTransferFrom,canTransferTo = sol3.getTransferable(supervisors)

    #for sup in supEdges:
    #    supDegree = len(supEdges[sup])
    #    supQuota = supervisors[sup].getQuota()
    #    if supDegree > supQuota:
    #        excess = supDegree - supQuota
    #        for i in random.sample(supEdges[sup],excess):
    #            availableStudents.add(i)
    #    elif supDegree == 0:
    #        reqSup.add(sup)

    #for sup in reqSup:

    #    if len(availableStudents)==0:
    #        fromSup = random.choice(list(canTransferFrom))
    #        stu = random.choice(graph.getStudents(fromSup))
    #        availableStudents.add(stu)

    #    x = random.choice(list(availableStudents))
    #    availableStudents.remove(x)
    #    oldSup = graph.getSupervisors(x)[0]
    #    graph.transferStudent1(x,oldSup,sup,supervisors)

    #sol3 = Solution(graph)
    #canTransferFrom,canTransferTo = sol3.getTransferable(supervisors)

    #for stu in availableStudents:
    #    con = False
    #    oldSup = graph.getSupervisors(stu)[0]

    #    if oldSup in canTransferTo:
    #        canTransferTo.remove(oldSup)
    #        con=True

    #    toSup = random.choice(list(canTransferTo))

    #    graph.transferStudent1(stu,oldSup,toSup,supervisors)

    #    if con:
    #        canTransferTo.add(oldSup)

    #    if not(graph.getSupervisorDegree(toSup) < supervisors[toSup].getQuota()):
    #        canTransferTo.remove(toSup)

    return Solution(graph)
def crossover(solution1, solution2, supervisors=None, students=None, k=None):
    """
    Function to perfrom crossover on two solutions.

    Parameters:
    
        solution1 (Solution) - parent solution 1
        solution2 (Solution) - parent solution 2

    Returns:

        A New Solution Object - an offspring solution from both the parent solutions.
    """

    #Merging the two Graphs

    graph1 = solution1.getGraph()
    graph2 = solution2.getGraph()

    mergedGraph = graph1.merge(graph2)

    stuEdges = mergedGraph.getStuEdges()
    supEdges = mergedGraph.getEdges()

    #Randomly getting the structure from the two graphs
    stf1 = solution1.getStructuralFitness(supervisors)
    stf2 = solution2.getStructuralFitness(supervisors)

    if random.random() <= (stf1) / (stf1 + stf2):
        structure = graph1.getStructure()
    else:
        structure = graph2.getStructure()

    lockedEdges = set()
    lockedVertices = set()

    allStudents = set(list(stuEdges.keys()))

    result = BipartiteGraph()

    counts = {
    }  #stores the degree of the supervisors in the new offspring graph

    for sup in supEdges:
        counts[sup] = 0

    #Simplify first time here
    simplified = True
    prev_count = {}
    while prev_count != counts:
        prev_count = dict(counts)
        for sup in supEdges:
            supDegree = len(supEdges[sup])
            reqDegree = structure[sup]
            for stu in supEdges[sup]:

                if len(stuEdges[stu]) == 1 and not stu in lockedVertices:
                    mergedGraph.removeExcept(sup, stu)
                    result.addEdge(sup, stu)
                    lockedVertices.add(stu)
                    counts[sup] += 1

                    if counts[sup] == reqDegree:
                        toKeep = result.getStudents(sup)
                        toRemove = mergedGraph.getRemainingStu(sup, toKeep)

                        for i in toRemove:
                            mergedGraph.removeEdge(sup, i)

    prev = set()
    toContinue = False

    while len(lockedVertices) != len(stuEdges):

        for sup in supEdges:

            #If the supervisor degree is not equal to degree we want
            if counts[sup] != structure[sup]:

                supDegree = mergedGraph.getSupervisorDegree(sup)
                reqSupDegree = structure[sup]
                students = mergedGraph.getStudents(sup)

                #Pick a random student that is not locked from the supervior's list of students
                curr = random.choice(students)
                if (curr not in lockedVertices):

                    #If that edge can be locked, then lock it.
                    if mergedGraph.canLock(sup, curr, structure, counts,
                                           lockedVertices):

                        #Remove other supervisors in student's list of supervisors

                        mergedGraph.removeExcept(sup, curr)

                        #Add it to the new graph and also locked vertices
                        result.addEdge(sup, curr)
                        lockedVertices.add(curr)

                        #Increment the degree of the supervisor
                        counts[sup] += 1

                        #If the degee is the degree we want
                        if counts[sup] == reqSupDegree:

                            toKeep = result.getStudents(
                                sup)  #Get the students we want to keep
                            toRemove = mergedGraph.getRemainingStu(
                                sup,
                                toKeep)  #Get students we dont want to keep

                            #Remove those students (edges)

                            for stu in toRemove:
                                mergedGraph.removeEdge(sup, stu)

        #If we can lock any further, then we break the loop
        if len(prev) != len(lockedVertices):
            prev = set(list(lockedVertices))
        else:
            toContinue = True
            break

    #Allocate remaining students to supervisors that don't meet the required degree
    if toContinue:
        availableStudents = allStudents.difference(lockedVertices)
        for sup in supEdges:
            reqDegree = structure[sup]
            supDegree = counts[sup]
            supNeeds = reqDegree - supDegree
            if supDegree != reqDegree:
                toAdd = random.sample(availableStudents, supNeeds)
                for stu in toAdd:
                    result.addEdge(sup, stu)
                    lockedVertices.add(stu)
                    counts[sup] += supNeeds
                    availableStudents.remove(stu)

    return Solution(result)