Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
if not keys:
for key in tmp:
meta[key] = tmp[key]
elif keys:
meta[keys["id"]] = {}
for k in tmp:
meta[keys["id"]][k] = tmp[k]
elif dtype in ['tre', 'nwk']:
if "trees" not in meta:
meta["trees"] = {}
if not keys:
keys["id"] = "1"
# XXX consider switching to Tree here XXX
meta['trees'][keys["id"]] = cg.LoadTree(treestring=tmp)
elif dtype in ['csv']:
meta[keys["id"]] = {}
ncol = int(keys.get('ncol', 2))
if "dtype" in keys:
transf = eval(keys["dtype"])
else:
transf = str
# split tmp into lines
tmp = tmp.split('\n')
for l in tmp:
if ncol == 2:
a, b = l.split('\t')
b = transf(b)
else:
xA, xB = xvals[0], xvals[-1]
# calculate the new coordinates, the radius is simply decreased by 1
y = min([n[1] for n in nodes]) - 1
# the theta-value is calculated by the following formula
x = (xA + abs(xA - xB) / 2)
return x, y
# get the tree
if type(treestring) == text_type:
try:
tree = cg.LoadTree(treestring)
except:
tree = cg.LoadTree(treestring=treestring)
else:
tree = treestring
# get the leaves
leaves = tree.getTipNames()
# get the paths in order to find out the radius of the tree
paths = {}
for l in leaves:
path = tree.getConnectingEdges(root, l)
try:
paths[len(path)] += [l]
except:
paths[len(path)] = [l]
clusters = {i[0]: [i[1]] for i in zip(range(self.height), range(self.height))}
# create the tree matrix
self.tree_matrix = []
# carry out the clustering
if tree_calc == 'upgma':
cluster._upgma(clusters, self.matrix, self.tree_matrix)
elif tree_calc == 'neighbor':
cluster._neighbor(clusters, self.matrix, self.tree_matrix)
else:
raise ValueError(
'Method <' + tree_calc + '> for tree calculation not available.')
# create a newick-representation of the string
self.tree = LoadTree(cluster._tree2nwk(
self.tree_matrix, [''.join(c) for c in self._classes], False))
def __init__(self, tree, **keywords):
# this is an absolutely nasty hack, but it helps us to maintain
# lingpy-specific aspects of cogent's trees and allows us to include
# them in our documentation
if type(tree) == str:
if tree[-4:] not in ['.nwk', '.txt']:
tmp = LoadTree(treestring=tree)
else:
tmp = LoadTree(tree)
else:
if type(tree) == list:
tmp = LoadTree(treestring=random_tree(tree, **keywords))
else:
tmp = LoadTree(tree)
for key, val in tmp.__dict__.items():
self.__dict__[key] = val
self._edge_len = len(self.getNodeNames()) - 1
Returns
-------
graph : networkx.Graph
"""
# create an empty graph
graph = nx.DiGraph()
# load the tree
if type(treefile) == text_type:
try:
tree = cg.LoadTree(treefile)
except:
tree = cg.LoadTree(treestring=treefile)
else:
tree = treefile
# get the node names of the tree
nodes = tree.getNodeNames()
# get taxa for convenience
taxa = tree.getTipNames()
# iterate over the nodes and add them and the edges to the graph
for node in nodes:
# add the node (just as a precaution)
if node in taxa:
graph.add_node(node, tip=True)
else:
Returns
-------
tree : ~lingpy.thirdparty.cogent.tree.PhyloNode
A ~lingpy.thirdparty.cogent.tree.PhyloNode object for handling tree
files.
"""
if tree_calc == 'upgma':
algorithm = cluster.upgma
elif tree_calc == 'neighbor':
algorithm = cluster.neighbor
else:
raise ValueError(tree_calc)
tree = cg.LoadTree(treestring=algorithm(matrix, taxa, distances))
if not filename:
return tree
util.write_text_file(filename + '.nwk', text_type(tree))
def nwk2guidetree(
newick
):
"""
Build a tree matrix for a guide tree given in Newick format.
Input is a binary tree with zero-based integer names at the leaves.
"""
#assumption: a binary tree with integer names starting with 0 at the leaves
tree = cg.LoadTree(treestring=newick)
nodeIndex = {}
nextIdx = len(tree.tips())
#generate virtual cluster IDs for the tree nodes, store them in nodeIndex
for node in tree.postorder():
if not node.isTip():
nodeIndex[node] = nextIdx
nextIdx += 1
else:
nodeIndex[node] = int(node.Name)
#construct tree matrix by another postorder traversal
tree_matrix = []
queue = deque(tree.postorder())
while len(queue) > 0:
curNode = queue.popleft()
if not curNode.isTip():
leftChild = curNode.Children[0]
def nwk2tree_matrix(newick):
"""
Convert a newick file to a tree matrix.
Notes
-----
This is an additional function that can be used for plots with help of
matplotlibs functions. The tree_matrix is compatible with those matrices
that scipy's linkage functions create.
"""
if type(newick) == str:
tree = cg.LoadTree(treestring=newick)
elif hasattr(newick, 'root'):
tree = newick
taxa = [t for t in sorted(
tree.taxa,
key=lambda x: len(tree.getConnectingEdges('root', x)),
reverse=True
)]
tax2id = dict(zip(taxa, range(len(taxa))))
nodes = [t for t in tree.getNodeNames() if t not in taxa]
nodes = sorted(
nodes,
key=lambda x: len(tree.getNodeMatchingName(x).tips()),
)
ax_linewidth=0,
filename=rcParams['filename']
)
for k in defaults:
if k not in keywords:
keywords[k] = defaults[k]
# set filename as variabel for convenience
filename = keywords['filename']
try:
tree = cg.LoadTree(treestring=treestring)
except:
try:
tree = cg.LoadTree(treestring)
except:
tree = treestring
tgraph = radial_layout(treestring, degree=degree)
graph = gls2gml(
gls,
tgraph,
tree
)
nodes = []
# assign nodes and edges
for n, d in graph.nodes(data=True):
g = d['graphics']
loss_color='black',
gain_linestyle='dotted',
loss_linestyle='solid',
ax_linewidth=0,
filename=rcParams['filename']
)
for k in defaults:
if k not in keywords:
keywords[k] = defaults[k]
# set filename as variabel for convenience
filename = keywords['filename']
try:
tree = cg.LoadTree(treestring=treestring)
except:
try:
tree = cg.LoadTree(treestring)
except:
tree = treestring
tgraph = radial_layout(treestring, degree=degree)
graph = gls2gml(
gls,
tgraph,
tree
)
nodes = []