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


Python Tree类代码示例

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


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

示例1: check_perms

def check_perms(s, set, handles, **kwargs):
    ask_flag = kwargs.get('Ask', True)
    if not ask_flag:
        if not MyUtil.get_yn('!!! Warning !!! ask = False: Will not ask to make changes, okay? Enter N to Exit, Y to Continue:'):
            print('exiting...')
            sys.exit(0)
    for handle in handles:
        if 'Document-' in handle:
            fd = DCC.prop_get(s, handle, InfoSet = 'DocBasic')
        elif 'Collection-' in handle:
            fd = DCC.prop_get(s, handle, InfoSet = 'CollData')
        else:
            fd = DCC.prop_get(s, handle, InfoSet = 'Title')    
        fd['permissions'] = DCC.prop_get(s, handle, InfoSet = 'Perms')
#         print(fd['handle'], ':', fd['title'])    
        
        print('\n>>>>>>>>>>>>>>       DCC Information       <<<<<<<<<<<<<<')
        if 'Document-' in handle:
            DCC.print_doc_basic(fd)
        elif 'Collection-' in handle:
            DCC.print_coll_data(fd)
        else:
            print('Not Document or Collection:', handle, ':', fd['title'])   
        print('\n\tDoc Properties URL: ',Tree.url_view(handle))
        print('\tPermissions URL: ',Tree.url_perm(handle))
        print('\tGet Document URL: ',Tree.url_access(handle))

        
        print()
    
        fix_objact(s, fd, handle, set, **kwargs)
        fix_permact(s, fd, handle, set, **kwargs)
开发者ID:TMTSystemsEngineering,项目名称:Library,代码行数:32,代码来源:PERM.py

示例2: background

def background():
    """Creates the general background scenery"""
    #Creates random clouds in the sky
    for r in range(0,cloudNum):
        #Initialize variables
        x = randint(-100,1200)
        y = randint(-20,100)
        width = randint(60,90)
        height = randint(20,50)
        cloudColor = choice(["gray92","gray95","gray98"])
        
        #Create lots of ovals to represent clouds
        for i in range(0,20):
            x1 = x - randint(1, width)
            y1 = y - randint(1, height)
            x2 = x + randint(1, width)
            y2 = y + randint(1, height)
            oval = screen.create_oval(x1, y1, x2, y2, fill=cloudColor, outline=cloudColor)
        
    #Ground behind the trees
    screen.create_oval(-100,320,1100,600, fill ="gainsboro", outline ="gainsboro")

    #Trees from Tree.py
    Tree.tree(screen)
    
    #Snowy Ground
    screen.create_rectangle (0,500,1000,800,fill="snow",outline="snow")
    screen.create_polygon (0,500,50,500,100,450,250,470,400,430,500,450,650,420,700,450,800,460,1020,470,1000,600, fill="snow",outline="snow",smooth="true")

    #Scorebox
    screen.create_rectangle( 320,100,680,350, fill="#80d5ff", outline="white", width="8")
开发者ID:Advait-M,项目名称:Snowball-Duel,代码行数:31,代码来源:Graphical+Game+App_1.py

示例3: isBalanced

def isBalanced(bt):
    if bt is None:
        return True
    d = Tree.getHeight(bt.left) - Tree.getHeight(bt.right)
    if abs(d) > 1:
        return False
    else:
        return isBalanced(bt.left) and isBalanced(bt.right)
开发者ID:YuSheng05631,项目名称:CrackingInterview,代码行数:8,代码来源:4.1.py

示例4: check_perms

def check_perms(s, set, handle, treename, **kwargs):
    ask_flag = kwargs.get('Ask', True)
    if not ask_flag:
        if not MyUtil.get_yn('!!! Warning !!! ask = False: Will not ask to make changes, okay? Enter N to Exit, Y to Continue:'):
            print('exiting...')
            sys.exit(0)
    tr = Tree.return_tree(s, handle, treename)
    handles = Tree.get_flat_tree(tr)
    for handle in handles:
        fix_set(s, handle, set, **kwargs)
开发者ID:pbbarnes,项目名称:Library1,代码行数:10,代码来源:PERM.py

示例5: makeParseTreeNode

def makeParseTreeNode(p, value):
    '''Returns a Tree object containing
         as children p[1:] and a value of value'''
    toReturn = Tree()
    for element in p[1:]:
        if type(element) == type(toReturn):
            toReturn.children.append(element)
            toReturn.errors += element.errors
        else:
            # the element is not a tree. wrap it in a tree
            newElement = Tree()
            if isinstance(element, tuple):
                newElement.value = element[0]
                newElement.type = element[1]
            else:
                newElement.value = element
            toReturn.children.append(newElement)

    if isinstance(value, tuple):
        toReturn.value = value[0]
        toReturn.type = value[1]
    else:
        toReturn.value = value
    if value == "error":
        errorMessage = str(p[1][2]) + ": " + p[1][0]
        toReturn.errors.append(errorMessage)

    return toReturn
开发者ID:MDSilber,项目名称:RacecarLanguage,代码行数:28,代码来源:Parser.py

示例6: NNI

def NNI(t):
	"""
	Randomly select an internal node to do NNI
	alters the tree <t>

	Returns: t, (new) order
	"""
	while True:
		parent = random.choice(t.internal_nodes())
		# choose one of the kids as target
		# and another as sibling
		target, sibling = random.sample(parent.child_nodes(), 2)
		if target.is_leaf():
			continue
		else:
			# select one children from target to swap w/ sibling
			child = random.choice(target.child_nodes())
			break

	print >> sys.stderr, "NNI: parent {0}, target {1}, sibling {2}, child {3}".format(\
			parent.label, target.label, sibling.label, child.label)

	# swap child & sibling in tree
	new_child_branch = child.edge_length + target.edge_length
	new_sibling_branch = sibling.edge_length - target.edge_length
	parent.remove_child(sibling)
	target.remove_child(child)
	parent.add_child(child, new_child_branch)
	target.add_child(sibling, new_sibling_branch)

	# obtain new order via postorder traversal (should be fast enough)
	order = Tree.postorder_assign_then_traverse(t, None, do_assign=False)

	return t, order
开发者ID:pombredanne,项目名称:gbpML,代码行数:34,代码来源:Subtree.py

示例7: optimize_branch_fast

def optimize_branch_fast(tlobj, tprime, children_index_list):
	"""
	Quick optimization of subset of branches (indicated by <children_index_list>)
	 in tprime while using tlobj for parameters

	children_index_list --- list of (i, j) indicating that we want to iteratively 
	         refine the branch of node label i --- node label j

	Most likely will be the 3 local branches at the new insertion point of a subtree.
	For fast optimization, relax the branch length variation to 0.1.

	Returns: final (positive) log likelihood of tprime

	NOTE: this only changes branch lengths in tprime. tlobj not affected!!
	NOTE: reversible_subtree_func currently cheats by only recalc-ing the
	      entries of parent and up, to ensure this works, I think making sure
		  copy_{S|P} are correct is important and therefore the two g() calls.
	"""
	g = MyMat.calc_likelihood
	meat = scipy.optimize.fmin_l_bfgs_b

	def reversible_subtree_func(copy_S, copy_P, parent, child, t_a):
		#assert len(t_a) == 1

		child.edge_length = t_a[0]
		order = Tree.postorder_cheat_traverse(parent)

		L_single = g(tlobj.single_model.gtr.R, copy_S, tlobj.log_freq_single, \
				order, range(tlobj.ncol), tlobj.nnode, tlobj.ncol, tlobj.nbase)
		L_paired = g(tlobj.paired_model.gtr.R, copy_P, tlobj.log_freq_paired, \
				order, range(tlobj.ncol_p), tlobj.nnode_p, tlobj.ncol_p, tlobj.nbase_p)

		ans = -(L_single.sum() + L_paired.sum())
		return ans

	# TODO: make this more efficient!
	copy_S = tlobj.S.copy()
	copy_P = tlobj.P.copy() 
	order = Tree.postorder_assign_then_traverse(tprime, None, False)
	g(tlobj.single_model.gtr.R, copy_S, tlobj.log_freq_single, \
		order, range(tlobj.ncol), tlobj.nnode, tlobj.ncol, tlobj.nbase)
	g(tlobj.paired_model.gtr.R, copy_P, tlobj.log_freq_paired, \
		order, range(tlobj.ncol_p), tlobj.nnode_p, tlobj.ncol_p, tlobj.nbase_p)

	changed = True
	while changed:
		changed = False
		for i, j in children_index_list:
			parent = tprime.find_node_with_label(i)
			child = tprime.find_node_with_label(j)
			old_t_a = child.edge_length
			func = lambda x: reversible_subtree_func(copy_S, copy_P, parent, child, x)
			x, fx, d = meat(func, [old_t_a], approx_grad=True, \
					bounds=[(1e-3, 10)], pgtol=1e-2)
#			print "calling func {0}--{1} done".format(i,j), x, fx, d, x[0], old_t_a, abs(x[0] - old_t_a)
			if d['warnflag'] != 0:
				return None, None # handle this appropriately!
			if abs(x[0] - old_t_a) > 0.1:
				changed = True
	return fx, tprime
开发者ID:pombredanne,项目名称:gbpML,代码行数:60,代码来源:TreeLikelihood.py

示例8: optimize_branch_func

	def optimize_branch_func(self, parent, child, t_a):
		"""
		<t_a> is the new branch length between <parent> --- <child>
		(t_a is dressed in an array...should always be just [t_a])

		We can cheat & speed up likelihood calculation
		 by re-using likelihods of subtrees below child and T'
		 where T' is the subtree under root that does not contain parent/child

		Returns: POSITIVE sum of log likelihood (so we try to minimize it)

		currently wrapped up by ::optimize_branch::
		NOTE: it is ::optimize_branch::'s responsibility to update
		      self.order and self.like when all is done!!!

		p.s. potentialy speed-up by simultaneously optimizing two child branches
		     of the same parent??
		"""
		#assert len(t_a) == 1
		g = MyMat.calc_likelihood
		
		child.edge_length = t_a[0]
		# TODO: make this more efficient!
		cheat_order = Tree.postorder_cheat_traverse(parent)

		L_single = g(self.single_model.gtr.R, self.S, self.log_freq_single, \
				cheat_order, range(self.ncol), self.nnode, self.ncol, self.nbase)
		L_paired = g(self.paired_model.gtr.R, self.P, self.log_freq_paired, \
				cheat_order, range(self.ncol_p), self.nnode_p, self.ncol_p, self.nbase_p)
		return -(L_single.sum() + L_paired.sum())
开发者ID:pombredanne,项目名称:gbpML,代码行数:30,代码来源:TreeLikelihood.py

示例9: __init__

	def __init__(self, iface,user):
		# Save reference to the QGIS interface
		self.iface = iface
		self.message=None
		self.tree=Tree(user)
		self.message="selected"
		self.progressBar=ProgressBarWindow(True,True)# apro la progress bar con due barre
		self.progressBar.setMaximumOverall(4)
		self.ui_tree=MainWindowAlbero(iface,self.tree)
开发者ID:arpho,项目名称:mmasgis5,代码行数:9,代码来源:albero.py

示例10: __init__

	def __init__(self, msa, tree, single_model, paired_model, treat_gap_as_missing):
		"""
		Input:

		msa  --- MSA object (the alignment)
		tree --- initially is the starting tree (dendropy.Tree)
		single/paired model -- EvoModel.{single|paired}model objects

		Also has the following attributes:
		single_cols --- list of unpaired positions
		paired_cols --- list of paired positions (i, j)
		order --- postorder traversal (often changes! beware!)
		like --- positive log likelihood (often changes! beware!)
		nnode, ncol, nbase for single/paired parameters...

		NOTE: ENFORCES tree TO BE BINARY
		"""
		self.msa = msa
		self.tree = tree
		self.single_model = single_model
		self.paired_model = paired_model
		self.treat_gap_as_missing = treat_gap_as_missing
		self.log_freq_single = log(self.single_model.Frequency)
		self.log_freq_paired = log(self.paired_model.Frequency)

		self.single_cols = msa.single_cols()
		self.paired_cols = msa.BP.items()
		self.paired_cols.sort()

		self.nnode = 2*msa.nseq + 1
		self.ncol = len(self.single_cols)
		self.nbase = 5
		self.nnode_p = self.nnode
		self.ncol_p = len(self.paired_cols)
		self.nbase_p = 25

		Tree.make_tree_binary(self.tree) # must preceded self.order!

		self.order = Tree.postorder_assign_then_traverse(tree, list(msa.ids))
		self.like = None # should be the positive log likelihood

		self.S = None # likelihood matrix for single positions
		self.P = None # likelihood matrix for paired positions
开发者ID:pombredanne,项目名称:gbpML,代码行数:43,代码来源:TreeLikelihood.py

示例11: reset_trees

    def reset_trees(self):
        self.__canvas = CanvasApp(self, 6, 8)
        self.__tpa = Tree(PointerAlgorithm())
        self.__ms1 = MH(1)
        self.__ms2 = MH(2)

        fill_tree(self.__tpa, self.__canvas)

        self.__ms1.add_gui(self.__canvas.add_circle(0, 0, 0, fill="white", outline="black", width=2, name="MS 1"))
        self.__tpa.put_ms_into_node_name(self.__ms1, 7)
        self.__ms2.add_gui(self.__canvas.add_circle(0, 0, 0, fill="white", outline="black", width=2, name="MS 2"))
        self.__tpa.put_ms_into_node_name(self.__ms2, 18)
开发者ID:dntfg4,项目名称:MST6604,代码行数:12,代码来源:ProxyStrategyApp.py

示例12: setupDefaultTree

def setupDefaultTree( idx, pname, listCodeList ):
	""" 프로젝트가 생성될시 디폴트 트리를 구성합니다 """
	
	# 프로젝트 정보 트리에 등록 
	treeList = [{ "text": pname, "pos":"000", "pidx": idx, "place": "PROJECT", "ntype": "PAGE", "icon":"ico-project", "gourl": "/project/view2/"+ str(idx), "issystem": True }]
	
	# 기본 리스트 트리에 등록	  
	for nListCode in listCodeList:
		alist = gLister[nListCode]
		treeList.append({
			"text":  alist.Title, 
			"pos":	 "001", 
			"pidx":  idx,
			"place": "PROJECT", 
			"icon":  alist.IconCls,
			"ntype": "LIST", 
			"gourl": "/lister/list2/%s/%s" % (nListCode, idx),
			"issystem": True})
	
	Tree.save( treeList )
	return
开发者ID:onetera,项目名称:sp,代码行数:21,代码来源:Project.py

示例13: reversible_subtree_func

	def reversible_subtree_func(copy_S, copy_P, parent, child, t_a):
		#assert len(t_a) == 1

		child.edge_length = t_a[0]
		order = Tree.postorder_cheat_traverse(parent)

		L_single = g(tlobj.single_model.gtr.R, copy_S, tlobj.log_freq_single, \
				order, range(tlobj.ncol), tlobj.nnode, tlobj.ncol, tlobj.nbase)
		L_paired = g(tlobj.paired_model.gtr.R, copy_P, tlobj.log_freq_paired, \
				order, range(tlobj.ncol_p), tlobj.nnode_p, tlobj.ncol_p, tlobj.nbase_p)

		ans = -(L_single.sum() + L_paired.sum())
		return ans
开发者ID:pombredanne,项目名称:gbpML,代码行数:13,代码来源:TreeLikelihood.py

示例14: rearr

	def rearr(t, log_l, rL, rU):
		for target in t.postorder_node_iter():
			if target.parent_node is None:
				break
			# first make a deep copy of the tree
			t_prime = dendropy.Tree(t)
			print "finding subtree rearrangement for {0}".format(target.label)
			dest = cello.subtree_rearrangement(t_prime, target, rL, rU)
			print "inserting subtree {0} into branch above {1}".format(target.label, dest.label)
			try:
				# attach the subtree of <target> to branch above <dest>
				t_prime, affected = Subtree.move_subtree(t_prime, target.label, dest.label)
			except Exception:
				print "could not succesfully do the move, forget it! move on!"
				continue
			cheat_order = Tree.postorder_traverse_with_cheat(t_prime, affected)
			# the three local branche we need to optimize are edges of
			# target, dest, and parent of target
			lst = []
			for i, (k, bunch) in enumerate(cheat_order):
				for j, (a, t_a) in enumerate(bunch):
					if a in (target.label, dest.label, target.parent_node.label):
						lst.append((i, j))
			print 'list is', lst
			log_l_prime = MyMat.optimize_branch_fast(lst, cheat_order, msa, single_model, paired_model, S, P)
			if log_l_prime < log_l:
				print "subtree rearrangement improved log like from {0}-->{1}, keep!".format(log_l, log_l_prime)
				t = t_prime
				log_l = log_l_prime
				# put in the fastly optimized branch lengths
				for i, j in lst:
					t.find_node_with_label(cheat_order[i][1][j][0]).edge_length = cheat_order[i][1][j][1]
				raw_input("continue?")
				return
			else:
				print "subtree rearrangment made log likelihood worse. Move on"
				raw_input("continue")
				return
		return t, log_l
开发者ID:pombredanne,项目名称:gbpML,代码行数:39,代码来源:Likelihood.py

示例15: visualize

 def visualize(self, filename):
     Tree.eteVisualize(self.toEteTree(), filename)
开发者ID:jkirschner,项目名称:evolverilog,代码行数:2,代码来源:TreeOrganism.py


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