def siblingMatch(parent, treeList, index): subtrees = [] siblingTrees = [] #if there is a next sibling if (index + 1 < len(treeList)): #get all of the permutations of the siblings to the right siblingTrees = siblingMatch(parent, treeList, index + 1) subtrees.extend(siblingTrees) #go through all the subtrees of this child for graph in treeList[index]: #add this permutation with no siblings subtrees.append(ImmutableTree(parent, [graph])) for siblings in siblingTrees: #combine this permutation with each of the sibling permutations combined = [graph] combined.extend([sibling for sibling in siblings]) subtrees.append(ImmutableTree(parent, combined)) return subtrees
def getSubgraphsList(tree): #sometimes leaves are represented as strings instead of trees if type(tree) is str: allGraphList = [] topGraphList = [] #turn the string into a tree parent = ImmutableTree(tree, []) #add to the lists and return allGraphList.append(parent) topGraphList.append(parent) return (allGraphList, topGraphList) #if the leaf is actually a tree, it will have no children elif len(tree) < 1: #return lists with the leaf allGraphList = [] topGraphList = [] allGraphList.append(ImmutableTree(tree, [])) topGraphList.append(ImmutableTree(tree, [])) return (allGraphList, topGraphList) else: #otherwise, if it does have children allGraphList = [] topGraphList = [] topChildGraphs = [] #go through each of its children for i in range(len(tree)): #recursively find all of the subtrees of the children allChild, topChild = getSubgraphsList(tree[i]) #add these subgraphs to the allgraphs list allGraphList.extend(allChild) #keep track of the top subtrees of each child topChildGraphs.append(topChild) #permute together all of the possibile subtrees for each child with their siblings siblings = siblingMatch(tree.label(), topChildGraphs, 0) #also add the root parent parent = ImmutableTree(tree.label(), []) #add these to the lists and return topGraphList.append(parent) allGraphList.append(parent) topGraphList.extend(siblings) allGraphList.extend(siblings) return (allGraphList, topGraphList)
def make_tree(tree): if isinstance(tree, tuple) and len(tree) > 2: return ImmutableTree(tree[0], [make_tree(tree[i]) for i in range(2, len(tree))]) else: return tree