当前位置: 首页>>代码示例>>Python>>正文


Python cogent.LoadTree类代码示例

本文整理汇总了Python中cogent.LoadTree的典型用法代码示例。如果您正苦于以下问题:Python LoadTree类的具体用法?Python LoadTree怎么用?Python LoadTree使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了LoadTree类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_making_from_list

 def test_making_from_list(self):
     tipnames_with_spaces = ['a_b','a b',"T'lk"]
     tipnames_with_spaces.sort()
     t = LoadTree(tip_names=tipnames_with_spaces)
     result = t.getTipNames()
     result.sort()
     assert result == tipnames_with_spaces
开发者ID:carze,项目名称:clovr-base,代码行数:7,代码来源:test_tree2.py

示例2: MatchNodes

 def MatchNodes(self):
     #print "YAY"
     self.correctForFastMLNameChanges() #performs the correction on the output string if necessary
     #print "NAY"
     TerminiStringToNodeName_D = {}
     #a termini string is prepared for each internal node, that is, all termini under the internal node sorted an placed into a single string
     
     for NodeKey in self.UpperKey_L:
         TerminiStringToNodeName_D['-'.join(sorted(self.Nodes_D[NodeKey]['terminal']))] = NodeKey
     
     #prepares a cogent tree object for the fastML output
     FH = getInputTempFile(self.FastMLOutputTreeString)
     
     FastMLCogentTree = LoadTree(FH.name)
     
     
     self.FastMLToOriginalMatchedNodes_D = {}
     
     #for each cogent node in the FastML cogent tree
     for FastMLCogentNodeKey in FastMLCogentTree.getNodeNames():
         
         #a termini string is prepared for the fastML node
         FastMLCogentNode = FastMLCogentTree.getNodeMatchingName(FastMLCogentNodeKey)
         FastMLTermini_L = [tip.Name for tip in FastMLCogentNode.iterTips()]
         
         #if it has more than 0 termini under the node
         if len(FastMLTermini_L) > 0:
             #A fastML termini string is prepared, and this termini string will be the same termini string as the equivalent cogent node
             FastMLTerminiString = '-'.join(sorted(FastMLTermini_L))
             self.FastMLToOriginalMatchedNodes_D[FastMLCogentNodeKey] = TerminiStringToNodeName_D[FastMLTerminiString]
             
         #if it has no termini under it, then the node itself is a terminus and has the same name in FastML and Cogent
         else:
             self.FastMLToOriginalMatchedNodes_D[FastMLCogentNodeKey] = FastMLCogentNodeKey
开发者ID:JeremyBAdams,项目名称:Adaptation3D,代码行数:34,代码来源:fastmltree.py

示例3: _test_tree

 def _test_tree(self, method, treestring):
     t = LoadTree(treestring=treestring)
     t_distances = t.getDistances()
     reconstructed = method(t_distances)
     distances = reconstructed.getDistances()
     for key in t_distances:
         self.assertAlmostEqual(t_distances[key], distances[key])
开发者ID:alenajk,项目名称:cogent_rnj,代码行数:7,代码来源:test_rnj.py

示例4: test_getsetParamValue

 def test_getsetParamValue(self):
     """test getting, setting of param values"""
     t = LoadTree(treestring='((((a:.2,b:.3)ab:.1,c:.3)abc:.4),d:.6)')
     self.assertEqual(t.getParamValue('length', 'ab'), 0.1, 2)
     t.setParamValue('zz', 'ab', 4.321)
     node = t.getNodeMatchingName('ab')
     self.assertEqual(4.321, node.params['zz'], 4)
开发者ID:carze,项目名称:clovr-base,代码行数:7,代码来源:test_tree2.py

示例5: BigTreeSingleTests

class BigTreeSingleTests(TestTree):
    """using the big-tree for single-tree tests"""
    def setUp(self):
        self.name = 'big tree - '
        self.otu_names = ['Horse', 'TombBat', 'Rhino', 'Pig', 'AsianElep',
                     'SpermWhal', 'Cat', 'Gorilla', 'Orangutan',
                     'bandicoot', 'Hedgehog', 'Sloth', 'HairyArma',
                     'Manatee', 'GoldenMol', 'Pangolin']
        self.otu_names.sort()
        self.newick = '((((((((FlyingFox,DogFaced),((FreeTaile,LittleBro),(TombBat,RoundEare))),(FalseVamp,LeafNose)),(((Horse,Rhino),(Pangolin,(Cat,Dog))),(Llama,(Pig,(Cow,(Hippo,(SpermWhal,HumpbackW))))))),(Mole,Hedgehog)),(TreeShrew,(FlyingLem,((Jackrabbit,(FlyingSqu,(OldWorld,(Mouse,Rat)))),(Galago,(HowlerMon,(Rhesus,(Orangutan,(Gorilla,(Human,Chimpanzee)))))))))),(((NineBande,HairyArma),(Anteater,Sloth)),(((Dugong,Manatee),((AfricanEl,AsianElep),(RockHyrax,TreeHyrax))),(Aardvark,((GoldenMol,(Madagascar,Tenrec)),(LesserEle,GiantElep)))))),(caenolest,(phascogale,(wombat,bandicoot))));'
        self.newick_reduced = '(((((TombBat,(((Horse,Rhino),(Pangolin,Cat)),(Pig,SpermWhal))),Hedgehog),(Orangutan,Gorilla)),((HairyArma,Sloth),((Manatee,AsianElep),GoldenMol))),bandicoot);'
        self.tree = LoadTree(treestring = self.newick)
    
    def test_getEdgeNames(self):
        """testing (well, exercising at least), getedgenames"""
        # Fell over on small tree because "stem descended from root
        # joiner was a tip"
        a,b = self.otu_names[:2]
        clade = self.tree.getEdgeNames(a, b, True, False)
    
    def test_getTipNames(self):
        """testing (well, exercising at least), getTipNames"""
        a,b = self.otu_names[:2]
        tips = self.tree.getTipNames()
        self.assertEqual(len(tips), 55)
开发者ID:carze,项目名称:clovr-base,代码行数:25,代码来源:test_tree2.py

示例6: test_sameShape

 def test_sameShape(self):
     """test topology assessment"""
     t1 = LoadTree(treestring="(((s1,s5),s3),s2,s4);")
     t2 = LoadTree(treestring="((s1,s5),(s2,s4),s3);")
     t3 = LoadTree(treestring="((s1,s4),(s2,s5),s3);")
     assert t1.sameTopology(t2), (t1, t2)
     assert not t1.sameTopology(t3), (t1, t3)
     assert not t2.sameTopology(t3), (t2, t3)
开发者ID:carze,项目名称:clovr-base,代码行数:8,代码来源:test_tree2.py

示例7: test_params_merge

 def test_params_merge(self):
     t = LoadTree(treestring='((((a,b)ab,c)abc),d)')
     for (label, length, beta) in [('a',1, 20),('b',3,2.0),('ab',4,5.0),]:
         t.getNodeMatchingName(label).params = {'length':length, 'beta':beta}
     t = t.getSubTree(['b', 'c', 'd'])
     self.assertEqual(t.getNodeMatchingName('b').params,
                             {'length':7, 'beta':float(2*3+4*5)/(3+4)})
     self.assertRaises(ValueError, t.getSubTree, ['b','c','xxx'])
     self.assertEqual(str(t.getSubTree(['b','c','xxx'],ignore_missing=True)),
         '(b:7,c)root;')
开发者ID:carze,项目名称:clovr-base,代码行数:10,代码来源:test_tree2.py

示例8: __init__

 def __init__(self, TreePath , NeedsToBeCogentModded):
     self.Parsed = True #used to determine if the full analysis can be conducted
     
     try:
         self.TreePath = TreePath
         self.NeedsToBeCogentModded = NeedsToBeCogentModded
         
         self.CogentTree = None
         
         #if the internal nodes need to be renamed, then it is done according to the "FixUpFileForCogent" method
         if self.NeedsToBeCogentModded:
             cogentFixUp = fixUpFileForCogent(self.TreePath)
             self.CogentTreeFile = cogentFixUp[0]
             self.CogentInputTreeString = cogentFixUp[1]
             
             
             self.CogentTree = LoadTree(self.CogentTreeFile.name)
             
         else:
             
             self.CogentTree = LoadTree(self.TreePath)
         
         #prepares an input string for FastML
         self.FastMLInputTreeString = self.FixUpFileForFastML(self.CogentTree)
         
         
         #executes method to fully parse tree, then sets all returned variables as class variables
         CogentNodesLeavesBranches = completeNodesLeavesBranches(self.CogentTree)
         self.NodeKey_L = CogentNodesLeavesBranches['NodeKey_L']
         self.LeafKey_L = CogentNodesLeavesBranches['LeafKey_L']
         self.UpperKey_L = CogentNodesLeavesBranches['UpperKey_L']
         self.TopKey = CogentNodesLeavesBranches['TopKey']
         self.BranchKey_L = CogentNodesLeavesBranches['BranchKey_L']
         self.Nodes_D = CogentNodesLeavesBranches['Nodes_D']
         
         
         
         
         
         #print self.LeafKey_L
         #executes quick run of FastML to get FastML's naming convention of internal nodes
         
         self.FastMLOutputTreeString = executeFastML(self.getTempFASTAFile() , self.FastMLInputTreeString , True)
         
         
         #prepares the FastMLToOriginalMatchedNodes_D
         self.MatchNodes()
         
     except Exception as e:
         
         self.Parsed = False
开发者ID:JeremyBAdams,项目名称:Adaptation3D,代码行数:51,代码来源:fastmltree.py

示例9: main

def main():
    option_parser, opts, args =\
       parse_command_line_parameters(**script_info)
    start_time = datetime.now()

    t = LoadTree(opts.input_tree)
    translation_dict = {}
    for i,tip in enumerate(t.iterTips()):
        translation_dict[tip.Name] = i

    single_rate = False

    #Generate commands telling BayesTraits which nodes to reconstruct
    bayestraits_commands = make_bayestraits_script(t,translation_dict,comments=False,single_rate=single_rate)


    #TODO: make this dynamic
    #Temporarily assuming there is a nexus file available
    nexus_fp = opts.input_tree.rsplit(".",1)[0] +".nexus"
    command_fp = "./bayestraits_commands.txt"
    path_to_bayestraits = "../"
    outfile = "./bayestrait_reconstruction.trait_table"
    command_file = open(command_fp,"w+")
    command_file.writelines(bayestraits_commands)
    command_file.close()

    command_file = open(command_fp,"U")

    bayestraits=BayesTraits()
    bayestraits_result = bayestraits(data=(nexus_fp,opts.input_trait_data,command_fp))
    #print "StdOut:",result["StdOut"].read()
    print "StdErr:",bayestraits_result["StdErr"].read()
    print "Return code:",bayestraits_result["ExitStatus"]

    results = parse_reconstruction_output(bayestraits_result['StdOut'].readlines())
    #print "Reconstructions:",results

    #Reconstruction results
    f = open(outfile,"w+")
    f.writelines(results)
    f.close()

    end_time = datetime.now()
    print "Start time:", start_time
    print "End time:",end_time
    print "Time to reconstruct:", end_time - start_time
    bayestraits_result.cleanUp()
开发者ID:picrust,项目名称:picrust,代码行数:47,代码来源:bayestraits.py

示例10: setUp

 def setUp(self):
     self.name = 'small tree - '
     self.otu_names = ['NineBande', 'Mouse', 'HowlerMon', 'DogFaced']
     self.otu_names.sort()
     self.newick = '(((Human,HowlerMon),Mouse),NineBande,DogFaced);'
     self.newick_sorted = '(DogFaced,((HowlerMon,Human),Mouse),NineBande);'
     self.newick_reduced = '((HowlerMon,Mouse),NineBande,DogFaced);'
     self.tree = LoadTree(treestring = self.newick)
开发者ID:carze,项目名称:clovr-base,代码行数:8,代码来源:test_tree2.py

示例11: main

def main():
    args = parser.parse_args()

    categories = args.categories
    map_fp = args.map_fp
    tree_fp = args.tree_fp
    output_fp = args.output_fp
    length = args.length

    map_dict = parse_mapping_file_to_dict(map_fp)[0]

    fields = categories.split(',')

    tree = LoadTree(tree_fp)

    furcated_tree = furcate_tree(tree, map_dict, fields, length=length)

    tree.writeToFile(output_fp)
开发者ID:ekopylova,项目名称:script_bin,代码行数:18,代码来源:furcate_tree.py

示例12: setUp

 def setUp(self):
     self.submodel = Nucleotide(
         do_scaling=True, model_gaps=False, equal_motif_probs=True,
         predicates = {'beta': 'transition'})
     
     self.data = LoadSeqs(
             filename = os.path.join(data_path, 'brca1_5.paml'),
             moltype = self.submodel.MolType)
     
     self.tree = LoadTree(
             filename = os.path.join(data_path, 'brca1_5.tree'))
开发者ID:chungtseng,项目名称:pycogent,代码行数:11,代码来源:test_likelihood_function.py

示例13: TestTree

class TestTree(unittest.TestCase):
    """tests for a single tree-type"""
    
    def setUp(self):
        self.name = 'small tree - '
        self.otu_names = ['NineBande', 'Mouse', 'HowlerMon', 'DogFaced']
        self.otu_names.sort()
        self.newick = '(((Human,HowlerMon),Mouse),NineBande,DogFaced);'
        self.newick_sorted = '(DogFaced,((HowlerMon,Human),Mouse),NineBande);'
        self.newick_reduced = '((HowlerMon,Mouse),NineBande,DogFaced);'
        self.tree = LoadTree(treestring = self.newick)
    
    def test_sorttree(self):
        """testing (well, exercising at least) treesort"""
        new_tree = self.tree.sorted()
        if hasattr(self, 'newick_sorted'):
            self.assertEqual(
                self.newick_sorted,
                new_tree.getNewick(with_distances=0))
    
    def test_getsubtree(self):
        """testing getting a subtree"""
        subtree = self.tree.unrooted().getSubTree(self.otu_names)
        
        new_tree = LoadTree(treestring = self.newick_reduced).unrooted()
        
        # check we get the same names
        self.assertEqual(*[len(t.Children) for t in (subtree,new_tree)])
        self.assertEqual(str(subtree), str(new_tree))
    
    def test_ascii(self):
        self.tree.asciiArt()
        # unlabeled internal node
        tr = DndParser("(B:0.2,(C:0.3,D:0.4):0.6)F;")
        tr.asciiArt(show_internal=True, compact=False)
        tr.asciiArt(show_internal=True, compact=True)
        tr.asciiArt(show_internal=False, compact=False)
开发者ID:carze,项目名称:clovr-base,代码行数:37,代码来源:test_tree2.py

示例14: load_de_numericized_newick_tree

def load_de_numericized_newick_tree(tree_in,before="'",after="'",root=False):
    from cogent.core.tree import PhyloNode
    from cogent import LoadTree
    import os.path
    
    if os.path.isfile(tree_in):
        tree = LoadTree(tree_in)
    else:
        tree = LoadTree(treestring=tree_in)
    terminals = tree.getTipNames()
    rename_dict = {}
    for tip in terminals:
        rename_dict[tip] = before + str(tip) + after
    tree.reassignNames(rename_dict)
    if root:
        tree = tree.rootAtMidpoint()
    treestring = tree.getNewick(with_distances=True)
    
    return treestring
开发者ID:tanaes,项目名称:codiversification,代码行数:19,代码来源:annotate_nodes_with_sig_values.py

示例15: test_run_pick_de_novo_otus_muscle

 def test_run_pick_de_novo_otus_muscle(self):
     """run_pick_de_novo_otus w muscle generates expected results
     """
     self.params['assign_taxonomy'] = \
      {'id_to_taxonomy_fp':self.test_data['refseqs_tax'][0],
       'reference_seqs_fp':self.test_data['refseqs'][0]}
     self.params['align_seqs'] = {'alignment_method':'muscle'}
     self.params['filter_alignment'] = \
      {'suppress_lane_mask_filter':None,
       'entropy_threshold':'0.10'}
     
     run_pick_de_novo_otus(
      self.test_data['seqs'][0], 
      self.test_out, 
      call_commands_serially,
      self.params, 
      self.qiime_config, 
      parallel=False,
      status_update_callback=no_status_updates)
      
     input_file_basename = splitext(split(self.test_data['seqs'][0])[1])[0]
     otu_map_fp = join(self.test_out,'uclust_picked_otus',
      '%s_otus.txt' % input_file_basename)
     alignment_fp = join(self.test_out,
      'muscle_aligned_seqs','%s_rep_set_aligned.fasta' % 
       input_file_basename)
     taxonomy_assignments_fp = join(self.test_out,
      'uclust_assigned_taxonomy','%s_rep_set_tax_assignments.txt' %
      input_file_basename)
     otu_table_fp = join(self.test_out,'otu_table.biom')
     tree_fp = join(self.test_out,'rep_set.tre')
     
     input_seqs = LoadSeqs(self.test_data['seqs'][0],
                           format='fasta',
                           aligned=False)
     
     # Number of OTUs falls within a range that was manually 
     # confirmed
     otu_map_lines = list(open(otu_map_fp))
     num_otus = len(otu_map_lines)
     otu_map_otu_ids = [o.split()[0] for o in otu_map_lines]
     self.assertEqual(num_otus,14)
     
     # all otus get taxonomy assignments
     taxonomy_assignment_lines = list(open(taxonomy_assignments_fp))
     self.assertEqual(len(taxonomy_assignment_lines),num_otus)
     
     # all OTUs align
     aln = LoadSeqs(alignment_fp)
     self.assertTrue(aln.getNumSeqs(),num_otus)
     
     # all OTUs in tree
     tree = LoadTree(tree_fp)
     self.assertEqual(len(tree.tips()),num_otus)
      
     # check that the two final output files have non-zero size
     self.assertTrue(getsize(tree_fp) > 0)
     self.assertTrue(getsize(otu_table_fp) > 0)
     
     # Check that the log file is created and has size > 0
     log_fp = glob(join(self.test_out,'log*.txt'))[0]
     self.assertTrue(getsize(log_fp) > 0)
     
     # parse the otu table
     otu_table = parse_biom_table(open(otu_table_fp,'U'))
     expected_sample_ids = ['f1','f2','f3','f4','p1','p2','t1','t2','not16S.1']
     # sample IDs are as expected
     self.assertEqualItems(otu_table.SampleIds,expected_sample_ids)
     # expected OTUs
     self.assertEqualItems(otu_table.ObservationIds,otu_map_otu_ids)
     # number of sequences in the full otu table equals the number of
     # input sequences
     number_seqs_in_otu_table = sum([v.sum() for v in otu_table.iterSampleData()])
     self.assertEqual(number_seqs_in_otu_table,input_seqs.getNumSeqs())
开发者ID:rob-knight,项目名称:qiime,代码行数:74,代码来源:test_upstream.py


注:本文中的cogent.LoadTree类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。