本文整理汇总了Python中cogent.parse.tree.DndParser.tips方法的典型用法代码示例。如果您正苦于以下问题:Python DndParser.tips方法的具体用法?Python DndParser.tips怎么用?Python DndParser.tips使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类cogent.parse.tree.DndParser
的用法示例。
在下文中一共展示了DndParser.tips方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: sort_order
# 需要导入模块: from cogent.parse.tree import DndParser [as 别名]
# 或者: from cogent.parse.tree.DndParser import tips [as 别名]
def sort_order(records):
"""returns the sort order by id"""
tree = DndParser("(((nosp,sp)named,notnamed)inpref,\
((nosp,sp)named,notnamed)outpref);")
for n in tree.tips():
n.LengthsAndIds = []
lookup = {}
lookup[('named_isolate',True,True)] = \
tree.Children[0].Children[0].Children[0]
lookup[('named_isolate',True,False)] = \
tree.Children[0].Children[0].Children[1]
lookup[('clone',True,False)] = \
tree.Children[0].Children[1]
lookup[('named_isolate',False,True)] = \
tree.Children[1].Children[0].Children[0]
lookup[('named_isolate',False,False)] = \
tree.Children[1].Children[0].Children[1]
lookup[('clone',False,False)] = \
tree.Children[1].Children[1]
for k,v in records.items():
to_lookup = tuple(v[1:])
lookup[to_lookup].LengthsAndIds.append((v[0],k))
order = []
# tips go left->right
for n in tree.tips():
order.extend([i for l,i in sorted(n.LengthsAndIds)[::-1]])
return order
示例2: load_tree
# 需要导入模块: from cogent.parse.tree import DndParser [as 别名]
# 或者: from cogent.parse.tree.DndParser import tips [as 别名]
def load_tree(input, tipname_map, verbose=False):
"""Returns a PhyloNode tree decorated with helper attrs
Helper attrs include Consensus, TipStart and TipStop. Nontips and tips that
do not have consensus information will have [None] * len(RANK_ORDER) set
as Consensus
"""
if verbose:
print "loading tree..."
if isinstance(input, TreeNode):
tree = input
else:
tree = DndParser(input)
tips = tree.tips()
n_ranks = len(RANK_ORDER)
for idx, tip in enumerate(tips):
tip.TipStart = idx
tip.TipStop = idx
tip.Consensus = tipname_map.get(tip.Name, [None] * 7)
if verbose and tip.Consensus is None:
print "No consensus for %s" % tip.Name
for node in tree.postorder(include_self=True):
if node.istip():
continue
node.TipStart = node.Children[0].TipStart
node.TipStop = node.Children[-1].TipStop
node.Consensus = [None] * n_ranks
if node.Name is None:
node.Bootstrap = None
else:
try:
node.Bootstrap = float(node.Name)
node.Name = None
except:
if verbose:
print "Could not save bootstrap %s, node is root: %s" % \
(node.Name, str(node.Parent == None))
node.Bootstrap = None
for tip in tree.tips():
if tip.Name:
tip.Name = tip.Name.replace("'","")
return tree
示例3: test_score_tree
# 需要导入模块: from cogent.parse.tree import DndParser [as 别名]
# 或者: from cogent.parse.tree.DndParser import tips [as 别名]
def test_score_tree(self):
"""Determine's the tree's fmeasure score"""
# set RankNames and RankNameScores
# if name in RankNames, check score, look at tips, etc
t_str = "(((a,b),(c,d))e,(f,g),h)i;"
t = DndParser(t_str)
t.RankNames = ['i',None,None,None] # 1.0 * 6
t.RankNameScores = [1.0,None,None,None]
t.Children[0].RankNames = [None,'e','foo',None] # 0.5 * 3, 0.6 * 3
t.Children[0].RankNameScores = [None, 0.5, 0.6, None]
t.Children[0].Children[0].RankNames = [None] * 7
t.Children[0].Children[1].RankNames = [None] * 7
t.Children[1].RankNames = [None] * 7
t.Children[1].RankNameScores = [None] * 7
tips = t.tips()
tips[0].Consensus = [None] * 7
tips[1].Consensus = [1,3,None,None]
tips[2].Consensus = [2,4,5,None]
tips[3].Consensus = [None,1,None,None]
tips[4].Consensus = [None,1,None,None]
tips[5].Consensus = [2,None,3,None]
tips[6].Consensus = [None,4,None,None]
decorate_ntips(t)
exp = ((1.0 * 6) + (0.5 * 3) + (0.6 * 3)) / (6 + 3 + 3)
obs = score_tree(t)
self.assertEqual(obs, exp)
示例4: build_tree_from_alignment
# 需要导入模块: from cogent.parse.tree import DndParser [as 别名]
# 或者: from cogent.parse.tree.DndParser import tips [as 别名]
def build_tree_from_alignment(aln, moltype, best_tree=False, params=None):
"""Returns a tree from alignment
Will check MolType of aln object
"""
if params is None:
params = {}
if moltype == DNA or moltype == RNA:
params["-nt"] = True
elif moltype == PROTEIN:
params["-nt"] = False
else:
raise ValueError, "FastTree does not support moltype: %s" % moltype.label
if best_tree:
params["-slow"] = True
# Create mapping between abbreviated IDs and full IDs
int_map, int_keys = aln.getIntMap()
# Create SequenceCollection from int_map.
int_map = SequenceCollection(int_map, MolType=moltype)
app = FastTree(params=params)
result = app(int_map.toFasta())
tree = DndParser(result["Tree"].read(), constructor=PhyloNode)
# remap tip names
for tip in tree.tips():
tip.Name = int_keys[tip.Name]
return tree
示例5: build_tree_from_alignment
# 需要导入模块: from cogent.parse.tree import DndParser [as 别名]
# 或者: from cogent.parse.tree.DndParser import tips [as 别名]
def build_tree_from_alignment(aln, moltype, best_tree=False, params=None):
"""Returns a tree from Alignment object aln.
aln: an cogent.core.alignment.Alignment object, or data that can be used
to build one.
moltype: cogent.core.moltype.MolType object
best_tree: if True (default:False), uses a slower but more accurate
algorithm to build the tree.
params: dict of parameters to pass in to the Clustal app controller.
The result will be an cogent.core.tree.PhyloNode object, or None if tree
fails.
"""
# Create instance of app controller, enable tree, disable alignment
app = Clustalw(InputHandler="_input_as_multiline_string", params=params, WorkingDir="/tmp")
app.Parameters["-align"].off()
# Set params to empty dict if None.
if params is None:
params = {}
if moltype == DNA or moltype == RNA:
params["-type"] = "d"
elif moltype == PROTEIN:
params["-type"] = "p"
else:
raise ValueError, "moltype must be DNA, RNA, or PROTEIN"
# best_tree -> bootstrap
if best_tree:
if "-bootstrap" not in params:
app.Parameters["-bootstrap"].on(1000)
if "-seed" not in params:
app.Parameters["-seed"].on(randint(0, 1000))
if "-bootlabels" not in params:
app.Parameters["-bootlabels"].on("nodes")
else:
app.Parameters["-tree"].on()
# Setup mapping. Clustalw clips identifiers. We will need to remap them.
seq_collection = SequenceCollection(aln)
int_map, int_keys = seq_collection.getIntMap()
int_map = SequenceCollection(int_map)
# Collect result
result = app(int_map.toFasta())
# Build tree
tree = DndParser(result["Tree"].read(), constructor=PhyloNode)
for node in tree.tips():
node.Name = int_keys[node.Name]
# Clean up
result.cleanUp()
del (seq_collection, app, result, int_map, int_keys)
return tree
示例6: bootstrap_tree_from_alignment
# 需要导入模块: from cogent.parse.tree import DndParser [as 别名]
# 或者: from cogent.parse.tree.DndParser import tips [as 别名]
def bootstrap_tree_from_alignment(aln, seed=None, num_trees=None, params=None):
"""Returns a tree from Alignment object aln with bootstrap support values.
aln: an cogent.core.alignment.Alignment object, or data that can be used
to build one.
seed: an interger, seed value to use
num_trees: an integer, number of trees to bootstrap against
params: dict of parameters to pass in to the Clustal app controller.
The result will be an cogent.core.tree.PhyloNode object, or None if tree
fails.
If seed is not specifed in params, a random integer between 0-1000 is used.
"""
# Create instance of controllor, enable bootstrap, disable alignment,tree
app = Clustalw(InputHandler='_input_as_multiline_string', params=params, \
WorkingDir='/tmp')
app.Parameters['-align'].off()
app.Parameters['-tree'].off()
if app.Parameters['-bootstrap'].isOff():
if num_trees is None:
num_trees = 1000
app.Parameters['-bootstrap'].on(num_trees)
if app.Parameters['-seed'].isOff():
if seed is None:
seed = randint(0,1000)
app.Parameters['-seed'].on(seed)
if app.Parameters['-bootlabels'].isOff():
app.Parameters['-bootlabels'].on("node")
# Setup mapping. Clustalw clips identifiers. We will need to remap them.
seq_collection = SequenceCollection(aln)
int_map, int_keys = seq_collection.getIntMap()
int_map = SequenceCollection(int_map)
# Collect result
result = app(int_map.toFasta())
# Build tree
tree = DndParser(result['Tree'].read(), constructor=PhyloNode)
for node in tree.tips():
node.Name = int_keys[node.Name]
# Clean up
result.cleanUp()
del(seq_collection, app, result, int_map, int_keys)
return tree
示例7: build_tree_from_alignment
# 需要导入模块: from cogent.parse.tree import DndParser [as 别名]
# 或者: from cogent.parse.tree.DndParser import tips [as 别名]
def build_tree_from_alignment(aln, moltype, best_tree=False, params={}):
"""Returns a tree from Alignment object aln.
aln: an xxx.Alignment object, or data that can be used to build one.
moltype: cogent.core.moltype.MolType object
best_tree: best_tree suppport is currently not implemented
params: dict of parameters to pass in to the RAxML app controller.
The result will be an xxx.Alignment object, or None if tree fails.
"""
if best_tree:
raise NotImplementedError
if '-m' not in params:
if moltype == DNA or moltype == RNA:
#params["-m"] = 'GTRMIX'
# in version 7.2.3, GTRMIX is no longer supported but says GTRCAT
# behaves like GTRMIX (http://www.phylo.org/tools/raxmlhpc2.html)
params["-m"] = 'GTRGAMMA'
elif moltype == PROTEIN:
params["-m"] = 'PROTGAMMAmatrixName'
else:
raise ValueError("Moltype must be either DNA, RNA, or PROTEIN")
if not hasattr(aln, 'toPhylip'):
aln = Alignment(aln)
seqs, align_map = aln.toPhylip()
# generate temp filename for output
params["-w"] = "/tmp/"
params["-n"] = get_tmp_filename().split("/")[-1]
params["-k"] = True
params["-p"] = randint(1,100000)
params["-x"] = randint(1,100000)
ih = '_input_as_multiline_string'
raxml_app = Raxml(params=params,
InputHandler=ih,
WorkingDir=None,
SuppressStderr=True,
SuppressStdout=True)
raxml_result = raxml_app(seqs)
tree = DndParser(raxml_result['Bootstrap'], constructor=PhyloNode)
for node in tree.tips():
node.Name = align_map[node.Name]
raxml_result.cleanUp()
return tree
示例8: assign_tax_labels_to_tree
# 需要导入模块: from cogent.parse.tree import DndParser [as 别名]
# 或者: from cogent.parse.tree.DndParser import tips [as 别名]
def assign_tax_labels_to_tree(tree,std):
"""Puts new tip labels onto tree
tree : newick string
std : output from shorten_taxonomy_strings
"""
tree_nodes = DndParser(tree, PhyloNode)
for node in tree_nodes.tips():
label = node.Name.strip('\'') #incase there are actual quotes
tax = std[label]
new_label = str(label) + '_' + tax
node.Name = new_label
return tree_nodes
示例9: remove_taxonomy
# 需要导入模块: from cogent.parse.tree import DndParser [as 别名]
# 或者: from cogent.parse.tree.DndParser import tips [as 别名]
def remove_taxonomy(tree, regex_string):
"""Puts new tip labels onto tree
tree : LoadTree object
regex_string :
"""
tree_nodes = DndParser(tree, PhyloNode)
for node in tree_nodes.tips():
label = node.Name.strip('\'') # incase there are actual quotes
p = re.compile(regex_string)
new_label = p.sub('', label)
#print new_label
node.Name = new_label
return tree_nodes
示例10: build_tree_from_distance_matrix
# 需要导入模块: from cogent.parse.tree import DndParser [as 别名]
# 或者: from cogent.parse.tree.DndParser import tips [as 别名]
def build_tree_from_distance_matrix(matrix, best_tree=False, params={}, working_dir="/tmp"):
"""Returns a tree from a distance matrix.
matrix: a square Dict2D object (cogent.util.dict2d)
best_tree: if True (default:False), uses a slower but more accurate
algorithm to build the tree.
params: dict of parameters to pass in to the Clearcut app controller.
The result will be an cogent.core.tree.PhyloNode object, or None if tree
fails.
"""
params["--out"] = get_tmp_filename(working_dir)
# Create instance of app controller, enable tree, disable alignment
app = Clearcut(
InputHandler="_input_as_multiline_string",
params=params,
WorkingDir=working_dir,
SuppressStdout=True,
SuppressStderr=True,
)
# Turn off input as alignment
app.Parameters["-a"].off()
# Input is a distance matrix
app.Parameters["-d"].on()
if best_tree:
app.Parameters["-N"].on()
# Turn the dict2d object into the expected input format
matrix_input, int_keys = _matrix_input_from_dict2d(matrix)
# Collect result
result = app(matrix_input)
# Build tree
tree = DndParser(result["Tree"].read(), constructor=PhyloNode)
# reassign to original names
for node in tree.tips():
node.Name = int_keys[node.Name]
# Clean up
result.cleanUp()
del (app, result, params)
return tree
示例11: test_shuffle_tipnames
# 需要导入模块: from cogent.parse.tree import DndParser [as 别名]
# 或者: from cogent.parse.tree.DndParser import tips [as 别名]
def test_shuffle_tipnames(self):
"""shuffle_tipnames should return copy of tree w/ labels permuted"""
#Note: this should never fail but is technically still stochastic
#5! is 120 so repeating 5 times should fail about 1 in 10^10.
for i in range(5):
try:
t = DndParser(self.t_str)
result = shuffle_tipnames(t)
orig_names = [n.Name for n in t.tips()]
new_names = [n.Name for n in result.tips()]
self.assertIsPermutation(orig_names, new_names)
return
except AssertionError:
continue
raise AssertionError, "Produced same permutation in 5 tries: broken?"
示例12: convert_tree_tips
# 需要导入模块: from cogent.parse.tree import DndParser [as 别名]
# 或者: from cogent.parse.tree.DndParser import tips [as 别名]
def convert_tree_tips(align_map,tree_fp):
""" rename the starting tree to correspond to the new phylip names,
which are assigned to each sequence """
# flip key value pairs
tree_tip_to_seq_name={}
for i in align_map:
tree_tip_to_seq_name[align_map[i]] = i
# change the tip labels to phylip labels
open_tree=open(tree_fp)
tree=DndParser(open_tree, constructor=PhyloNode)
for node in tree.tips():
node.Name = tree_tip_to_seq_name[node.Name]
return tree
示例13: build_tree_from_alignment
# 需要导入模块: from cogent.parse.tree import DndParser [as 别名]
# 或者: from cogent.parse.tree.DndParser import tips [as 别名]
def build_tree_from_alignment(aln, moltype, best_tree=False, params=None):
"""Returns a tree from Alignment object aln.
aln: a cogent.core.alignment.Alignment object, or data that can be used
to build one.
moltype: cogent.core.moltype.MolType object
best_tree: unsupported
params: dict of parameters to pass in to the Muscle app controller.
The result will be an cogent.core.tree.PhyloNode object, or None if tree
fails.
"""
# Create instance of app controller, enable tree, disable alignment
app = Muscle(InputHandler='_input_as_multiline_string', params=params, \
WorkingDir='/tmp')
app.Parameters['-clusteronly'].on()
app.Parameters['-tree1'].on(get_tmp_filename(app.WorkingDir))
app.Parameters['-seqtype'].on(moltype.label)
seq_collection = SequenceCollection(aln, MolType=moltype)
#Create mapping between abbreviated IDs and full IDs
int_map, int_keys = seq_collection.getIntMap()
#Create SequenceCollection from int_map.
int_map = SequenceCollection(int_map,MolType=moltype)
# Collect result
result = app(int_map.toFasta())
# Build tree
tree = DndParser(result['Tree1Out'].read(), constructor=PhyloNode)
for tip in tree.tips():
tip.Name = int_keys[tip.Name]
# Clean up
result.cleanUp()
del(seq_collection, app, result)
return tree
示例14: test_decorate_ntips
# 需要导入模块: from cogent.parse.tree import DndParser [as 别名]
# 或者: from cogent.parse.tree.DndParser import tips [as 别名]
def test_decorate_ntips(self):
"""correctly decorate the tree with the NumTips param"""
input = "(((a,b)c,(d,e,f)g)h,(i,j)k)l;"
tree = DndParser(input)
tips = dict([(tip.Name, tip) for tip in tree.tips()])
tips['a'].Consensus = [1,2,3,4,5,6,7]
tips['b'].Consensus = [None,None,None,5,None,None,None]
tips['d'].Consensus = [1,2,3,4,5,6,8]
tips['e'].Consensus = [None, None,None,None,None,None,None]
tips['f'].Consensus = [1,2,3,4,5,6,8]
tips['i'].Consensus = [1,2,3,4,5,6,8]
tips['j'].Consensus = [1,2,3,4,5,6,8]
decorate_ntips(tree)
self.assertEqual(tree.NumTips, 6)
self.assertEqual(tree.Children[0].NumTips, 4)
self.assertEqual(tree.Children[1].NumTips, 2)
self.assertEqual(tree.Children[0].Children[0].NumTips, 2)
self.assertEqual(tree.Children[0].Children[1].NumTips, 2)
示例15: fast_tree_tests
# 需要导入模块: from cogent.parse.tree import DndParser [as 别名]
# 或者: from cogent.parse.tree.DndParser import tips [as 别名]
#.........这里部分代码省略.........
def test_fitch_descendants_missing_data(self):
"""fitch_descendants should work with missing data"""
#tree and envs for testing missing values
t_str = '(((a:1,b:2):4,(c:3,d:1):2):1,(e:2,f:1):3);'
env_str = """a A
b B
c D
d C
e C
f D"""
t = DndParser(t_str, UniFracTreeNode)
node_index, nodes = index_tree(t)
env_counts = count_envs(env_str.split('\n'))
count_array, unique_envs, env_to_index, node_to_index = \
index_envs(env_counts, node_index)
branch_lengths = get_branch_lengths(node_index)
#test just the AB pair
ab_counts = count_array[:, 0:2]
bindings = bind_to_array(nodes, ab_counts)
changes = fitch_descendants(bindings, counter=FitchCounter)
self.assertEqual(changes, 1)
orig_result = ab_counts.copy()
#check that the original Fitch counter gives the expected
#incorrect parsimony result
changes = fitch_descendants(bindings, counter=FitchCounterDense)
self.assertEqual(changes, 5)
new_result = ab_counts.copy()
#check that the two versions fill the array with the same values
self.assertEqual(orig_result, new_result)
def test_tip_distances(self):
"""tip_distances should set tips to correct distances."""
t = self.t
bl = self.branch_lengths.copy()[:,newaxis]
bindings = bind_to_parent_array(t, bl)
tips = []
for n in t.traverse(self_before=False, self_after=True):
if not n.Children:
tips.append(n._leaf_index)
tip_distances(bl, bindings, tips)
self.assertEqual(bl, array([5,6,6,6,6,0,0,0,0])[:,newaxis])
def test_permute_selected_rows(self):
"""permute_selected_rows should switch just the selected rows in a"""
orig = reshape(arange(8),(4,2))
new = orig.copy()
fake_permutation = lambda a: range(a)[::-1] #reverse order
permute_selected_rows([0,2], orig, new, fake_permutation)
self.assertEqual(new, array([[4,5],[2,3],[0,1],[6,7]]))
#make sure we didn't change orig
self.assertEqual(orig, reshape(arange(8), (4,2)))
def test_prep_items_for_jackknife(self):
"""prep_items_for_jackknife should expand indices of repeated counts"""
a = array([0,1,0,1,2,0,3])
# 0 1 2 3 4 5 6
result = prep_items_for_jackknife(a)
exp = array([1,3,4,4,6,6,6])
self.assertEqual(result, exp)
def test_jackknife_bool(self):
"""jackknife_bool should make a vector with right number of nonzeros"""
fake_permutation = lambda a: range(a)[::-1] #reverse order
orig_vec = array([0,0,1,0,1,1,0,1,1])