def triangulate(self): junction_tree = JunctionTree() vertices = list(self) eliminated = set() while len(vertices) > 0: vertices.sort() # based on number of neighbours node = vertices.pop() for neighbour1, neighbour2 in subsets_of_len_two(node.neighbours): if neighbour1 in eliminated or neighbour2 in eliminated: continue link = neighbour1.add_neighbour(neighbour2) clique = Clique(neighbour1, node, neighbour2, junction_tree) clique.connect_link(link) eliminated.add(self.pop(node)) for node in eliminated: node.revert() self.add(node) return junction_tree
def moralise(self): for node in self: for parent1, parent2 in subsets_of_len_two(node.parents): parent1.add_neighbour(parent2)