In [1]:
%lsmagic
In [2]:
n_taxa = 10
for (i in 1:n_taxa) {
taxa[i] = taxon("T"+i, 0.0)
}
phy ~ dnBDP(lambda=1, rootAge=1, taxa=taxa)
writeNexus(data=phy, filename="example/output/magic_test.tre")
tracer
Let's view the tree in FigTree. Launch terminal commands using the magic function %shell
In [3]:
%shell figtree example/output/magic_test.tre
Of course, this example relies on figtree
existing in the user's environment PATH
variable.
In [4]:
%%python
# python packages
import dendropy
from Bio import Phylo
# the tree's filename
phy_fn = 'example/output/magic_test.tre'
# visualize a tree in Dendropy
dtree = dendropy.Tree.get(path=phy_fn,schema='nexus')
print('Dendropy\n'+dtree.as_ascii_plot())
# visualize a tree in Biopython
bptree = Phylo.read(phy_fn, 'nexus')
Phylo.draw(bptree)
This draws the tree in a pyplot window.
Full-featured kernels enable inline figure presentation through the magic command "%matplotlib inline
".
Unfortunately, this is not currently supported in metakernel (link).
I've made no progress so far on a workaround.
In [5]:
%%python
# python packages
from rpy2.robjects import r
import dendropy
# read tree into dendropy
phy_fn = 'example/output/magic_test.tre'
dtree = dendropy.Tree.get(path=phy_fn,schema='nexus')
# extract Newick string from file
phy_str = dtree.as_string("newick")
# parse Newick string in R
rtree = r("""
library('ape')
phy_r=read.tree(text='%s')
""" % phy_str)
# read the R object from the global rpy2 environment
rtree=r['phy_r']
print("ape tree as rpy2 object:")
print(rtree)
# store R values into python
tip_labels = rtree[ rtree.names.index('tip.label') ]
print("Tip labels as rpy2 object:")
print(tip_labels)