How do I generate all possible Newick Tree permutations for a set of species given an outgroup?
For those who don't know what Newick tree format is, a good description is available at: https://en.wikipedia.org/wiki/Newick_format
I want to create all possible Newick Tree permutations for a set of species given an outgroup. The number of leaf nodes I expect to process are most likely 4, 5, or 6 leaf nodes.
Both "Soft" and "hard" polytomies are allowed. https://en.wikipedia.org/wiki/Polytomy#Soft_polytomies_vs._hard_polytomies https://biology.stackexchange.com/questions/23667/evidence-discussions-of-hard-polytomy
Shown below is the ideal output, with "E" set as the outgroup
Ideal Output:
((("A","B","C"),("D"),("E"));
((("A","B","D"),("C"),("E"));
((("A","C","D"),("B"),("E"));
((("B","C","D"),("A"),("E"));
((("A","B")("C","D"),("E"));
((("A","C")("B","D"),("E"));
((("B","C")("A","D"),("E"));
(("A","B","C","D"),("E"));
(((("A","B"),"C"),"D"),("E"));
However, any possible solutions that I've come with using itertools, specifically itertools.permutations, have come across the problem of equivalent output. The last idea I came up with involved the equivalent output that is shown below.
Equivalent output:
((("C","B","A"),("D"),("E"));
((("C","A","B"),("D"),("E"));
((("A","C","B"),("D"),("E"));
Here is the start of my idea for a solution. However, I'm not really sure what to about this problem besides itertools for now.
import itertools
def Newick_Permutation_Generator(list_of_species, name_of_outgroup)
permutations_list =(list(itertools.permutations(["A","B","C","D","E"])))
for given_permutation in permutations_list:
process(given_permutation)
Newick_Permutation_Generator(["A","B","C","D","E"], "E")
This was a hard question! Here is the journey I took.
First observation is that the outgroup is always a single node tacked onto the end of the newick string. Let's call the rest of the species the ingroup and try to generate all the permutations of these. Then simply add the outgroup.
This returns 40 newick strings:
Some of these are duplicates, but we will get to removing the duplicates later.
As bli noted in the comments,
(((("A","B"),"C"),"D"),("E"));
and its variants should also be considered valid solutions. The comments on BioStar pointed me in the right direction that this is the same as generating all the possible groupings of a binary tree. I found a nice Python implementation in this StackOverflow answer by rici:Then,
produces the following 15 newicks:
So now we already have 40 + 15 = 55 possible newick strings and we have to remove the duplicates.
I first dead end that I tried was to create a canonical representation of each newick string so that I could use these as keys in a dictionary. The idea was to recursively sort the strings in all the nodes. But first I had to capture all the (nested) nodes. I couldn't use regular expressions, because nested structures are by definition not regular.
So I used the
pyparsing
package and come up with this:This gave for
A dictionary with 22 keys:
But closer inspection revealed some problems. Let's look for example at the newicks
'(((A, B), (C, D)),(E));
and((D, C), (A, B),(E));
. In our dictionaryd
they have a different canonical key, respectively[[[['A', 'B'], ['C', 'D']], ['E']]]
and[[['A', 'B'], ['C', 'D'], ['E']]]
. But in fact, these are duplicate trees. We can confirm this by looking at the Robinson-Foulds distance between two trees. If it is zero, the trees are identical.We use the
robinson_foulds
function from the ete3 toolkit packageOK, so Robinson-Foulds is a better way of checking for newick tree equality then my canonical tree approach. Let's wrap all newick strings in a custom
MyTree
object where equality is defined as having a Robinson-Foulds distance of zero:It would have been ideal if we could also define a
__hash__()
function that returns the same value for duplicate trees, thenset(trees)
would automatically remove all the duplicates.Unfortunately, I haven't been able to find a good way to define
__hash__()
, but with__eq__
in place, I could make use ofindex()
:So, here we are at the end of our journey. I can't fully provide proof that this is the correct solution, but I am pretty confident that the following 19 newicks are all the possible distinct permutations:
If we pairwise compare every newick to all other newicks, we get confirmation that there are no more duplicates in this list
A tree as a recursive set of sets of leaves
Let's set aside the newick representation for the moment, and think of a possible python representation of the problem.
A rooted tree can be viewed as a recursive hierarchy of sets of (sets of (sets of ...)) leaves. Sets are unordered, which is quite adapted to describe clades in a tree:
{{{"A", "B"}, {"C", "D"}}, "E"}
should be the same thing as{{{"C", "D"}, {"B", "A"}}, "E"}
.If we consider the initial set of leaves
{"A", "B", "C", "D", "E"}
, the trees with "E" as outgroup are the set of sets in the form{tree, "E"}
wheretree
s are taken from the set of trees that can be built from the set of leaves{"A", "B", "C", "D"}
. We could try to write a recursivetrees
function to generate this set of trees, and our total set of trees would be expressed as follows:(Here, I use the set comprehension notation.)
Actually, python doesn't allow sets of sets, because the elements of a set must be "hashable" (that is, python must be able to compute some "hash" values of objects to be able to check whether they belong or not to the set). It happens that python sets do not have this property. Fortunately, we can use a similar data structure named
frozenset
, which behaves quite like a set, but cannot be modified and is "hashable". Therefore, our set of trees would be:Implementing the
trees
functionNow let's focus on the
trees
function.For each possible partition (decomposition into a set of disjoint subsets, including all elements) of the set of leaves, we need to find all possible trees (through a recursive call) for each part of the partition. For a given partition, we will then make a tree for each possible combination of subtrees taken across its parts.
For instance, if a partition is
{"A", {"B", "C", "D"}}
, we will consider all possible trees that can be made from part"A"
(actually, just the leaf"A"
itself), and all possible trees that can be made from part{"B", "C", "D"}
(that is,trees({"B", "C", "D"})
). Then, the possible trees for this partition will be obtained by taking all possible pairs where one element comes from just"A"
, and the other fromtrees({"B", "C", "D"})
.This can be generalized for partitions with more than two parts, and the
product
function fromitertools
seems to be useful here.Therefore, we need a way to generate the possible partitions of a set of leaves.
Generating partitions of a set
Here I made a
partitions_of_set
function adapted from this solution:To check the obtained partitions, we make a function to make them easier to display (that will also be useful to make a newick representation of the trees later):
We test that the partitioning works:
Output:
Actual code of the
trees
functionNow we can write the
tree
function:Testing it:
Output:
I hope the result is correct.
This approach was a bit tricky to get right. It took me some time to figure out how to avoid the infinite recursion (This happens when the partition is
{{"A", "B", "C", "D"}}
).