本文整理汇总了Python中NewickIO.get_newick_string方法的典型用法代码示例。如果您正苦于以下问题:Python NewickIO.get_newick_string方法的具体用法?Python NewickIO.get_newick_string怎么用?Python NewickIO.get_newick_string使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类NewickIO
的用法示例。
在下文中一共展示了NewickIO.get_newick_string方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: do_distance_analysis
# 需要导入模块: import NewickIO [as 别名]
# 或者: from NewickIO import get_newick_string [as 别名]
def do_distance_analysis(X):
# get the matrix of squared distances
labels = list("0123")
# reconstruct the matrix of Euclidean distances from a tree
D_sqrt = np.array([[np.linalg.norm(y - x) for x in X] for y in X])
sqrt_tree = NeighborJoining.make_tree(D_sqrt, labels)
sqrt_tree_string = NewickIO.get_newick_string(sqrt_tree)
sqrt_feltree = NewickIO.parse(sqrt_tree_string, FelTree.NewickTree)
D_sqrt_reconstructed = np.array(sqrt_feltree.get_distance_matrix(labels))
# reconstruct the matrix of squared Euclidean distances from a tree
D = D_sqrt ** 2
tree = NeighborJoining.make_tree(D, labels)
tree_string = NewickIO.get_newick_string(tree)
feltree = NewickIO.parse(tree_string, FelTree.NewickTree)
D_reconstructed = np.array(feltree.get_distance_matrix(labels))
# start writing
out = StringIO()
# matrix of Euclidean distances and its reconstruction from a tree
print >> out, "matrix of Euclidean distances between tetrahedron vertices:"
print >> out, D_sqrt
print >> out, "neighbor joining tree constructed from D = non-squared Euclidean distances (unusual):"
print >> out, sqrt_tree_string
print >> out, "distance matrix implied by this tree:"
print >> out, D_sqrt_reconstructed
# matrix of squared Euclidean distances and its reconstruction from a tree
print >> out, "matrix of squared distances between tetrahedron vertices:"
print >> out, D
print >> out, "neighbor joining tree constructed from D = squared Euclidean distances (normal):"
print >> out, tree_string
print >> out, "distance matrix implied by this tree:"
print >> out, D_reconstructed
return out.getvalue().strip()
示例2: get_response_content
# 需要导入模块: import NewickIO [as 别名]
# 或者: from NewickIO import get_newick_string [as 别名]
def get_response_content(fs):
# get the newick trees.
trees = []
for tree_string in iterutils.stripped_lines(StringIO(fs.trees)):
# parse each tree and make sure that it conforms to various requirements
tree = NewickIO.parse(tree_string, FelTree.NewickTree)
tip_names = [tip.get_name() for tip in tree.gen_tips()]
if len(tip_names) < 4:
raise HandlingError('expected at least four tips but found ' + str(len(tip_names)))
if any(name is None for name in tip_names):
raise HandlingError('each terminal node must be labeled')
if len(set(tip_names)) != len(tip_names):
raise HandlingError('each terminal node label must be unique')
trees.append(tree)
# begin the response
out = StringIO()
# look at each tree
nerrors = 0
ncounterexamples = 0
for tree in trees:
# get the set of valid partitions implied by the tree
valid_parts = TreeComparison.get_partitions(tree)
ordered_tip_names = [tip.get_name() for tip in tree.gen_tips()]
# assert that the partition implied by the correct formula is valid
D = np.array(tree.get_distance_matrix(ordered_tip_names))
loadings = get_principal_coordinate(D)
nonneg_leaf_set = frozenset(tip for tip, v in zip(ordered_tip_names, loadings) if v >= 0)
neg_leaf_set = frozenset(tip for tip, v in zip(ordered_tip_names, loadings) if v < 0)
part = frozenset([nonneg_leaf_set, neg_leaf_set])
if part not in valid_parts:
nerrors += 1
print >> out, 'error: a partition that was supposed to be valid was found to be invalid'
print >> out, 'tree:', NewickIO.get_newick_string(tree)
print >> out, 'invalid partition:', partition_to_string(part)
print >> out
# check the validity of the partition implied by the incorrect formula
Q = D * D
loadings = get_principal_coordinate(Q)
nonneg_leaf_set = frozenset(tip for tip, v in zip(ordered_tip_names, loadings) if v >= 0)
neg_leaf_set = frozenset(tip for tip, v in zip(ordered_tip_names, loadings) if v < 0)
part = frozenset([nonneg_leaf_set, neg_leaf_set])
if part not in valid_parts:
ncounterexamples += 1
print >> out, 'found a counterexample!'
print >> out, 'tree:', NewickIO.get_newick_string(tree)
print >> out, 'invalid partition:', partition_to_string(part)
print >> out
print >> out, 'errors found:', nerrors
print >> out, 'counterexamples found:', ncounterexamples
# return the response
return out.getvalue()
示例3: main
# 需要导入模块: import NewickIO [as 别名]
# 或者: from NewickIO import get_newick_string [as 别名]
def main():
filename = 'counterexamples.out'
fout = open(filename, 'wt')
print 'Does monotonically transforming the pairwise leaf distances affect the compatibility'
print 'of the split found using principal coordinate analysis?'
print 'I am looking through random trees for a tree that is split incompatibly'
print 'when distances are squared.'
print 'Use control-c to stop the program when you get bored.'
try:
count = 0
ncounterexamples = 0
nerrors = 0
while True:
count += 1
# get a random tree
n_base_leaves = 4
n_expected_extra_leaves = 1
expected_branch_length = 1
tree = TreeSampler.sample_tree(n_base_leaves, n_expected_extra_leaves, expected_branch_length)
# get the set of valid partitions implied by the tree
valid_parts = TreeComparison.get_partitions(tree)
ordered_tip_names = [tip.get_name() for tip in tree.gen_tips()]
# assert that the partition implied by the correct formula is valid
D = np.array(tree.get_distance_matrix(ordered_tip_names))
loadings = get_principal_coordinate(D)
nonneg_leaf_set = frozenset(tip for tip, v in zip(ordered_tip_names, loadings) if v >= 0)
neg_leaf_set = frozenset(tip for tip, v in zip(ordered_tip_names, loadings) if v < 0)
part = frozenset([nonneg_leaf_set, neg_leaf_set])
if part not in valid_parts:
nerrors += 1
print >> fout, 'error: a partition that was supposed to be valid was found to be invalid'
print >> fout, 'tree:', NewickIO.get_newick_string(tree)
print >> fout, 'invalid partition:', partition_to_string(part)
print >> fout
# check the validity of the partition implied by the incorrect formula
Q = D * D
loadings = get_principal_coordinate(Q)
nonneg_leaf_set = frozenset(tip for tip, v in zip(ordered_tip_names, loadings) if v >= 0)
neg_leaf_set = frozenset(tip for tip, v in zip(ordered_tip_names, loadings) if v < 0)
part = frozenset([nonneg_leaf_set, neg_leaf_set])
if part not in valid_parts:
ncounterexamples += 1
print >> fout, 'found a counterexample!'
print >> fout, 'tree:', NewickIO.get_newick_string(tree)
print >> fout, 'invalid partition:', partition_to_string(part)
print >> fout
except KeyboardInterrupt, e:
print 'trees examined:', count
print 'errors:', nerrors
print 'counterexamples:', ncounterexamples
示例4: get_distance_matrix
# 需要导入模块: import NewickIO [as 别名]
# 或者: from NewickIO import get_newick_string [as 别名]
def get_distance_matrix(self, ordered_names=None):
"""
@param ordered_names: the requested order of the names
@return: a row major distance matrix
"""
# map the id of each tip to its index
if ordered_names:
tip_name_to_index = dict((name, i) for i, name in enumerate(ordered_names))
tip_id_to_index = dict((id(tip), tip_name_to_index[tip.name]) for tip in self.gen_tips())
else:
tip_id_to_index = dict((id(tip), i) for i, tip in enumerate(self.gen_tips()))
# get the number of tips
n = len(list(self.gen_tips()))
# for each tip get the distance to each other tip
distance_matrix = [[0]*n for i in range(n)]
for tip in self.gen_tips():
row = distance_matrix[tip_id_to_index[id(tip)]]
stack = []
for directed_branch in tip.gen_directed_branches():
next_target = directed_branch.get_target()
assert next_target
stack.append((tip, next_target, directed_branch.get_undirected_branch().get_branch_length()))
while stack:
source, target, distance = stack.pop()
if target.is_tip():
row[tip_id_to_index[id(target)]] = distance
else:
for next_branch in target.gen_exits(source):
branch_length = next_branch.get_undirected_branch().get_branch_length()
next_target = next_branch.get_target()
assert next_target, NewickIO.get_newick_string(self)
stack.append((target, next_target, distance + branch_length))
return distance_matrix
示例5: get_full_distance_matrix
# 需要导入模块: import NewickIO [as 别名]
# 或者: from NewickIO import get_newick_string [as 别名]
def get_full_distance_matrix(self, ordered_ids=None):
"""
@return: a row major distance matrix
@param ordered_ids: the requested row order by node id
"""
# map the id of each node to its index
if ordered_ids:
id_to_index = dict((id_, i) for i, id_ in enumerate(ordered_ids))
else:
id_to_index = dict((id(node), i) for i, node in enumerate(self.preorder()))
# get the number of nodes
n = len(list(self.preorder()))
# for each node get the distance to each other node
distance_matrix = [[0]*n for i in range(n)]
for node in self.preorder():
row = distance_matrix[id_to_index[id(node)]]
stack = []
for directed_branch in node.gen_directed_branches():
next_target = directed_branch.get_target()
assert next_target
stack.append((node, next_target, directed_branch.get_undirected_branch().get_branch_length()))
while stack:
source, target, distance = stack.pop()
row[id_to_index[id(target)]] = distance
for next_branch in target.gen_exits(source):
branch_length = next_branch.get_undirected_branch().get_branch_length()
next_target = next_branch.get_target()
assert next_target, NewickIO.get_newick_string(self)
stack.append((target, next_target, distance + branch_length))
return distance_matrix
示例6: get_tikz_lines
# 需要导入模块: import NewickIO [as 别名]
# 或者: from NewickIO import get_newick_string [as 别名]
def get_tikz_lines(newick, eigenvector_index, yaw, pitch):
"""
@param eigenvector_index: 1 is Fiedler
"""
tree = Newick.parse(newick, SpatialTree.SpatialTree)
# change the node names and get the new tree string
for node in tree.preorder():
node.name = 'n' + str(id(node))
newick = NewickIO.get_newick_string(tree)
# do the layout
layout = FastDaylightLayout.StraightBranchLayout()
layout.do_layout(tree)
tree.fit((g_xy_scale, g_xy_scale))
name_to_location = dict((
x.name, tree._layout_to_display(x.location)) for x in tree.preorder())
T, B, N = FtreeIO.newick_to_TBN(newick)
# get some vertices
leaves = Ftree.T_to_leaves(T)
internal = Ftree.T_to_internal_vertices(T)
vertices = leaves + internal
# get the locations
v_to_location = dict((v, name_to_location[N[v]]) for v in vertices)
# get the valuations
w, V = Ftree.TB_to_harmonic_extension(T, B, leaves, internal)
index_to_val = V[:, eigenvector_index-1]
v_to_val = dict(
(vertices[i], g_z_scale*val) for i, val in enumerate(index_to_val))
# get the coordinates
v_to_xyz = get_v_to_xyz(yaw, v_to_location, v_to_val)
# add intersection vertices
add_intersection_vertices(T, B, v_to_xyz)
intersection_vertices = sorted(v for v in v_to_xyz if v not in vertices)
# get lines of the tikz file
return xyz_to_tikz_lines(T, B, pitch, v_to_xyz,
leaves, internal, intersection_vertices)
示例7: get_response_content
# 需要导入模块: import NewickIO [as 别名]
# 或者: from NewickIO import get_newick_string [as 别名]
def get_response_content(fs):
# read the matrix
D = fs.matrix
if len(D) < 3:
raise HandlingError('the matrix should have at least three rows')
# read the ordered labels
ordered_labels = Util.get_stripped_lines(fs.labels.splitlines())
if len(ordered_labels) != len(D):
msg_a = 'the number of ordered labels should be the same '
msg_b = 'as the number of rows in the matrix'
raise HandlingError(msg_a + msg_b)
# create the tree building object
splitter = Clustering.StoneExactDMS()
tree_builder = NeighborhoodJoining.TreeBuilder(
D.tolist(), ordered_labels, splitter)
# Read the recourse string and set the corresponding method
# in the tree builder.
recourse_string = fs.getfirst('recourse')
if fs.njrecourse:
tree_builder.set_fallback_name('nj')
elif fs.halvingrecourse:
tree_builder.set_fallback_name('halving')
# assert that the computation will not take too long
if tree_builder.get_complexity() > 1000000:
raise HandlingError('this computation would take too long')
# build the tree
tree = tree_builder.build()
# return the response
return NewickIO.get_newick_string(tree) + '\n'
示例8: __call__
# 需要导入模块: import NewickIO [as 别名]
# 或者: from NewickIO import get_newick_string [as 别名]
def __call__(self, tree):
# get the partitions implied by the tree
valid_partitions = TreeComparison.get_partitions(tree)
# Get the partition implied by the Fiedler split
# of the graph derived from the tree.
tip_nodes = list(tree.gen_tips())
D = tree.get_partial_distance_matrix(
[id(node) for node in tip_nodes])
y = get_vector(D).tolist()
name_selection = frozenset(node.get_name()
for node, elem in zip(tip_nodes, y) if elem > 0)
name_complement = frozenset(node.get_name()
for node, elem in zip(tip_nodes, y) if elem <= 0)
name_partition = frozenset((name_selection, name_complement))
if name_partition not in valid_partitions:
msg = '\n'.join([
'invalid partition found:',
'tree:', NewickIO.get_newick_string(tree),
'invalid partition:', name_partition])
if not self.fout:
self.fout = open(self.counterexample_filename, 'wt')
print >> self.fout, msg
print msg
self.ncounterexamples += 1
# do not stop looking, even if a counterexample is found
return False
示例9: get_response_content
# 需要导入模块: import NewickIO [as 别名]
# 或者: from NewickIO import get_newick_string [as 别名]
def get_response_content(fs):
flags = get_flags(fs)
nseconds = 5
tm = time.time()
rejected_s = None
nerrors = 0
nchecked = 0
while time.time() < tm + nseconds and not rejected_s:
nchecked += 1
# Sample a Newick tree.
true_f = TreeSampler.sample_tree(fs.nleaves, 0, 1.0)
true_s = NewickIO.get_newick_string(true_f)
true_tree = Newick.parse(true_s, Newick.NewickTree)
# Get the leaf and internal vertex ids for the true tree.
internal_ids = set(id(x) for x in true_tree.gen_internal_nodes())
leaf_ids = set(id(x) for x in true_tree.gen_tips())
nleaves = len(leaf_ids)
# Get the harmonic valuations for all vertices of the tree.
id_to_full_val_list = [Harmonic.get_harmonic_valuations(
true_tree, i) for i in range(1, nleaves)]
# Check for small valuations at the leaves.
try:
for id_to_full_val in id_to_full_val_list:
for x in leaf_ids:
value = id_to_full_val[x]
if abs(value) < 1e-8:
raise CheckTreeError('the true tree is too symmetric')
except CheckTreeError as e:
nerrors += 1
continue
# Assign the leaf values and assign None to internal values.
id_to_val_list = []
for id_to_full_val in id_to_full_val_list:
d = {}
for x in leaf_ids:
s = -1 if id_to_full_val[x] < 0 else 1
d[x] = s
for x in internal_ids:
d[x] = None
id_to_val_list.append(d)
# Define the topology in a different format.
id_to_adj = get_id_to_adj(true_tree)
# Check the tree for self-compatibility under the given conditions.
id_to_vals = SeekEigenLacing.rec_eigen(
id_to_adj, id_to_val_list, flags)
if not id_to_vals:
rejected_s = true_s
# make the report
out = StringIO()
if rejected_s:
print >> out, 'rejected a true tree:'
print >> out, rejected_s
else:
print >> out, 'no true tree was rejected'
print >> out
print >> out, nchecked, 'trees were sampled total'
print >> out, nerrors, 'trees were too symmetric'
return out.getvalue()
示例10: get_response_lines
# 需要导入模块: import NewickIO [as 别名]
# 或者: from NewickIO import get_newick_string [as 别名]
def get_response_lines(self, options):
"""
Yield lines that form the result of the analysis.
@param options: a subset of strings specifying what to show
"""
preamble_lines = []
error_lines = []
if 'show_incomplete' in options and self.is_incomplete:
error_lines.append('the sequential splits defined by the eigenvectors were insufficient to reconstruct the tree')
if 'show_conflicting' in options and self.is_conflicting:
error_lines.append('the reconstructed tree has a split that is incompatible with the original tree')
if 'show_negligible' in options and self.is_negligible:
error_lines.append('during reconstruction a negligible eigenvector loading was encountered')
if 'show_all' in options or error_lines:
preamble_lines.extend(['original tree:', NewickIO.get_newick_string(self.tree)])
if self.reconstructed_tree:
preamble_lines.extend(['reconstructed tree:', NewickIO.get_newick_string(self.reconstructed_tree)])
return preamble_lines + error_lines
示例11: test_contrast_matrix_to_tree
# 需要导入模块: import NewickIO [as 别名]
# 或者: from NewickIO import get_newick_string [as 别名]
def test_contrast_matrix_to_tree(self):
original_tree = NewickIO.parse(g_felsenstein_tree_string, FelTree.NewickTree)
ordered_names = ('a', 'b', 'c', 'd', 'e')
C = get_contrast_matrix(original_tree, ordered_names)
assert_contrast_matrix(C)
reconstructed_tree = contrast_matrix_to_tree(C, ordered_names)
newick_string = NewickIO.get_newick_string(reconstructed_tree)
print
print newick_string
pass
示例12: get_response_content
# 需要导入模块: import NewickIO [as 别名]
# 或者: from NewickIO import get_newick_string [as 别名]
def get_response_content(fs):
flags_a = get_flags_a(fs)
flags_b = get_flags_b(fs)
data = CheckTreeData(flags_a, flags_b)
nseconds = 5
tm = time.time()
while time.time() < tm + nseconds:
# Sample a pair of Newick trees.
true_f = TreeSampler.sample_tree(fs.nleaves, 0, 1.0)
test_f = TreeSampler.sample_tree(fs.nleaves, 0, 1.0)
true_s = NewickIO.get_newick_string(true_f)
test_s = NewickIO.get_newick_string(test_f)
true_tree = Newick.parse(true_s, Newick.NewickTree)
test_tree = Newick.parse(test_s, Newick.NewickTree)
# Add the pairwise check to the data borg.
try:
found_difference = check_tree_pair(true_tree, test_tree, data)
except CheckTreeError as e:
data.add_error(e)
# Check to see if we should stop early.
if found_difference and fs.halt_on_difference:
break
# make the report
out = StringIO()
if data.report:
print >> out, 'found a difference in rejection power'
print >> out
print >> out, data.report
print >> out
else:
print >> out, 'failed to find a difference in rejection power'
print >> out
print >> out, 'search summary:'
m = data.acceptance_matrix
print >> out, 'A reject, B reject:', m[0, 0]
print >> out, 'A reject, B accept:', m[0, 1]
print >> out, 'A accept, B reject:', m[1, 0]
print >> out, 'A accept, B accept:', m[1, 1]
print >> out, data.nerrors, 'tree symmetry errors'
return out.getvalue()
示例13: get_response_content
# 需要导入模块: import NewickIO [as 别名]
# 或者: from NewickIO import get_newick_string [as 别名]
def get_response_content(fs):
"""
@param fs: a FieldStorage object containing the cgi arguments
@return: a (response_headers, response_text) pair
"""
out = StringIO()
# get some samples
for i in range(fs.ntrees):
tree = TreeSampler.sample_tree(fs.leafbase, fs.leafmean, fs.branchmean)
# write the tree
print >> out, NewickIO.get_newick_string(tree)
# return the response
return out.getvalue()
示例14: get_art
# 需要导入模块: import NewickIO [as 别名]
# 或者: from NewickIO import get_newick_string [as 别名]
def get_art(tree):
"""
@param tree: a FelTree
@return: a multi-line ascii art
"""
newick_string = NewickIO.get_newick_string(tree)
simple_tree = NewickIO.parse(newick_string, Newick.NewickTree)
drawer = DrawTree.DrawTree()
drawer.use_branch_lengths = True
drawer.force_ultrametric = False
drawer.vertical_spacing = 1
drawer.horizontal_spacing = 1
return drawer.draw(simple_tree)
示例15: _create_trees
# 需要导入模块: import NewickIO [as 别名]
# 或者: from NewickIO import get_newick_string [as 别名]
def _create_trees(self):
"""
Create the full tree and the pruned tree.
The full tree is a Newick.NewickTree,
and the pruned tree is a FelTree.NewickTree object.
"""
# create the full tree
self.full_tree = NewickIO.parse(self.newick_string, Newick.NewickTree)
# create the pruned tree through a temporary tree that will be modified
temp_tree = NewickIO.parse(self.newick_string, Newick.NewickTree)
remove_redundant_nodes(temp_tree)
pruned_newick_string = NewickIO.get_newick_string(temp_tree)
self.pruned_tree = NewickIO.parse(pruned_newick_string, FelTree.NewickTree)