Well, this code works fine for me (after commenting out the non-code bits).
In fact, all of the following work as well:
```
import dendropy
def f1():
"""
This works, but the problem is that the new taxon is not added
to the taxon namespace.
"""
print("\n## f1")
T = dendropy.Tree.get_from_string("((A,B),(C,D));", schema="newick")
node_to_change = T.find_node_with_taxon_label("B")
# This works, but does not add the new taxon to the taxon namespace
(i.e.
# taxon set)
new_Taxon = dendropy.Taxon(label="Z")
node_to_change.taxon = new_Taxon
print(T.as_string("newick"))
print("Taxon namespace: {}".format(", ".join(taxon.label for taxon
in T.taxon_set)))
def f2():
"""
This works and the taxon is added to the taxon namespace, but the
old taxon
is still there.
"""
print("\n## f2")
T = dendropy.Tree.get_from_string("((A,B),(C,D));", schema="newick")
node_to_change = T.find_node_with_taxon_label("B")
# Add a new taxon to the taxon namespace
new_Taxon = T.taxon_set.new_taxon("Z")
node_to_change.taxon = new_Taxon
print(T.as_string("newick"))
print("Taxon namespace: {}".format(", ".join(taxon.label for taxon
in T.taxon_set)))
def f3():
"""
This works and the taxon is added to the taxon namespace and the
old taxon
is removed. A little tedious though ...
"""
print("\n## f3")
T = dendropy.Tree.get_from_string("((A,B),(C,D));", schema="newick")
node_to_change = T.find_node_with_taxon_label("B")
# delete old taxon and add new one
T.taxon_set.remove(node_to_change.taxon)
new_Taxon = T.taxon_set.new_taxon("Z")
node_to_change.taxon = new_Taxon
print(T.as_string("newick"))
print("Taxon namespace: {}".format(", ".join(taxon.label for taxon
in T.taxon_set)))
def f4():
"""
This is the most efficient if all you want to do is change the
label of the
taxon instead of the the entire taxon. It is also propagates the change
across all data that reference the same taxon namespace.
"""
print("\n## f4")
T = dendropy.Tree.get_from_string("((A,B),(C,D));", schema="newick")
node_to_change = T.find_node_with_taxon_label("B")
# Change label of taxon in-situ
node_to_change.taxon.label = "Z"
print(T.as_string("newick"))
print("Taxon namespace: {}".format(", ".join(taxon.label for taxon
in T.taxon_set)))
f1()
f2()
f3()
f4()
```
On 11/22/14, 8:28 AM,
yann.b...@dpes.gu.se wrote:
> say I have a tree "((A,B),(C,D))" and want to output "((A,Z),(C,D))"
> T = dendropy.Tree.get_from_string("((A,B),(C,D))", schema="newick")
> So I start to find node with taxon labelled "B"
> node_to_change = T.find_node_with_taxon_label("B")
>
> Then create a new taxon object with the right label and attached it to
> the targetted node.
> new_Taxon = dendropy.Taxon(label="Z")
> node_to_change.taxon = new_Taxon