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


Python Tree.depth方法代码示例

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


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

示例1: __init__

# 需要导入模块: from treelib import Tree [as 别名]
# 或者: from treelib.Tree import depth [as 别名]
class Conversation:
    def __init__(self, tweet):
        self.root_tweet = tweet
        self.conversation_tree = Tree()
        self.conversation_tree.create_node(tweet, tweet)
        self.depth = int()
        self.tweets_id = list()
        self.tweets_id.append(tweet)
        self.width = int()

    def add_replay(self, tweet, parent_tweet):
        self.conversation_tree.create_node(tweet, tweet, parent=parent_tweet)
        self.tweets_id.append(tweet)

    def set_depth(self):
        self.depth = self.conversation_tree.depth() + 1

    def find_depth(self):
        return self.depth

    def get_tweets_id(self):
        return self.tweets_id

    def set_width(self):
        self.width = len(self.tweets_id)

    def find_width(self):
        return self.width

    def get_conversation_tree(self):
        return self.conversation_tree
开发者ID:anukat2015,项目名称:Twitter_DA_Recognition,代码行数:33,代码来源:conversation.py

示例2: AcquisitionChain

# 需要导入模块: from treelib import Tree [as 别名]
# 或者: from treelib.Tree import depth [as 别名]
class AcquisitionChain(object):
    def __init__(self):
        self._tree = Tree()
        self._root_node = self._tree.create_node("acquisition chain", "root")
        self._device_to_node = dict()

    def add(self, master, slave):
        slave_node = self._tree.get_node(slave)
        master_node = self._tree.get_node(master)
        if slave_node is not None and isinstance(slave, AcquisitionDevice):
            if slave_node.bpointer is not self._root_node and master_node is not slave_node.bpointer:
                raise RuntimeError(
                    "Cannot add acquisition device %s to multiple masters, current master is %s"
                    % (slave, slave_node._bpointer)
                )
            else:  # user error, multiple add, ignore for now
                return

        if master_node is None:
            master_node = self._tree.create_node(tag=master.name, identifier=master, parent="root")
        if slave_node is None:
            slave_node = self._tree.create_node(tag=slave.name, identifier=slave, parent=master)
        else:
            self._tree.move_node(slave_node, master_node)

    def _execute(self, func_name):
        tasks = list()

        prev_level = None
        for dev in reversed(list(self._tree.expand_tree(mode=Tree.WIDTH))[1:]):
            node = self._tree.get_node(dev)
            level = self._tree.depth(node)
            if prev_level != level:
                gevent.joinall(tasks)
                tasks = list()
            func = getattr(dev, func_name)
            tasks.append(gevent.spawn(func))
        gevent.joinall(tasks)

    def prepare(self, dm, scan_info):
        # self._devices_tree = self._get_devices_tree()
        for master in (x for x in self._tree.expand_tree() if isinstance(x, AcquisitionMaster)):
            del master.slaves[:]
            for dev in self._tree.get_node(master).fpointer:
                master.slaves.append(dev)

        dm_prepare_task = gevent.spawn(dm.prepare, scan_info, self._tree)

        self._execute("_prepare")

        dm_prepare_task.join()

    def start(self):
        self._execute("_start")
        for acq_dev in (x for x in self._tree.expand_tree() if isinstance(x, AcquisitionDevice)):
            acq_dev.wait_reading()
            dispatcher.send("end", acq_dev)
开发者ID:mguijarr,项目名称:bliss,代码行数:59,代码来源:continuous_scan.py

示例3: conversation_regarding_language

# 需要导入模块: from treelib import Tree [as 别名]
# 或者: from treelib.Tree import depth [as 别名]
def conversation_regarding_language(cursor):
    conversation_amount = postgres_queries.find_conversation_number(cursor)
    conversation_list = list()
    depth_dict = dict()
    depth_dict_long = dict()
    depth_dict_short = dict()
    number_of_tweets_dict = dict()
    test_i = 0
    for i in range(0, conversation_amount + 1, 1):
        conversation_tree = Tree()
        conversation = postgres_queries.find_conversation(i, cursor)
        test_i += len(conversation)
        for tweet in conversation:
            if tweet[2] is None and tweet[5] is True:
                conversation_tree.create_node(tweet[0], tweet[0])
                tweets_in_conversation = list()
                build_conversation_lang(tweet[0], conversation, conversation_tree, tweets_in_conversation)
                depth = conversation_tree.depth() + 1
                number_of_tweets = len(conversation_tree.all_nodes())
                #short/long
                if number_of_tweets >=20:
                    if depth in depth_dict_long:
                        depth_dict_long[depth] += 1
                    else:
                        depth_dict_long[depth] = 1
                else:
                    if depth in depth_dict_short:
                        depth_dict_short[depth] += 1
                    else:
                        depth_dict_short[depth] = 1

                if number_of_tweets in number_of_tweets_dict:
                    number_of_tweets_dict[number_of_tweets] += 1
                else:
                     number_of_tweets_dict[number_of_tweets] = 1
                if depth in depth_dict:
                    depth_dict[depth] += 1
                else:
                    depth_dict[depth] = 1
        # check if conversation_tree is null- dont add
        if len(conversation_tree.all_nodes())!=0:
            conversation_list.append(conversation_tree)
    # number = 0
    new_tweet_list_id = list()
    for con in conversation_list:
        nodes = con.all_nodes()
        for node in nodes:
            new_tweet_list_id.append(int(node.tag))
        # number += len(con.all_nodes())
    # print len(new_tweet_list_id)
    # for tweet_id in new_tweet_list_id:
    #     print tweet_id
    return new_tweet_list_id, conversation_list
开发者ID:anukat2015,项目名称:Twitter_DA_Recognition,代码行数:55,代码来源:rebuild_conversations.py

示例4: types_of_conversation

# 需要导入模块: from treelib import Tree [as 别名]
# 或者: from treelib.Tree import depth [as 别名]
def types_of_conversation():
    conversation_amount = postgres_queries.find_annotated_conversation_number()
    conversation_list = list()
    depth_dict = dict()
    depth_dict_long = dict()
    depth_dict_short = dict()
    number_of_tweets_dict = dict()
    for i in range (0, conversation_amount + 1, 1):
        conversation_tree = Tree()
        converastion = postgres_queries.find_conversation(i)
        for tweet in converastion:
            if tweet[1] is None:
                conversation_tree.create_node(tweet[0], tweet[0])
                build_conversation(tweet[0], converastion, conversation_tree)
                depth = conversation_tree.depth() + 1
                number_of_tweets = len(conversation_tree.all_nodes())
                #short/long
                if number_of_tweets >=20:
                    if depth in depth_dict_long:
                        depth_dict_long[depth] += 1
                    else:
                        depth_dict_long[depth] = 1
                else:
                    if depth in depth_dict_short:
                        depth_dict_short[depth] += 1
                    else:
                        depth_dict_short[depth] = 1

                if number_of_tweets in number_of_tweets_dict:
                    number_of_tweets_dict[number_of_tweets] += 1
                else:
                     number_of_tweets_dict[number_of_tweets] = 1
                if depth in depth_dict:
                    depth_dict[depth] += 1
                else:
                    depth_dict[depth] = 1
        conversation_list.append(conversation_tree)
    #print depth_dict
    print 'Depth of a conversation'
    for depth, count in depth_dict.iteritems():
        print depth, '\t', count
    print 'Number of tweets in a conversation'
    for number, count in number_of_tweets_dict.iteritems():
        print number, '\t', count
    print 'Depth of a long conversation'
    for depth, count in depth_dict_long.iteritems():
        print depth, '\t', count
    print 'Depth of a short conversation'
    for depth, count in depth_dict_short.iteritems():
        print depth, '\t', count

    return conversation_list
开发者ID:imclab,项目名称:Twitter_DA_Recognition,代码行数:54,代码来源:test.py

示例5: conversation_regarding_language

# 需要导入模块: from treelib import Tree [as 别名]
# 或者: from treelib.Tree import depth [as 别名]
def conversation_regarding_language(): # with width and depth
    conversation_amount = postgres_queries.find_annotated_conversation_number()
    conversation_list = list()
    depth_dict = dict()
    depth_dict_long = dict()
    depth_dict_short = dict()
    number_of_tweets_dict = dict()
    test_i = 0
    for i in range(0, conversation_amount + 1, 1):
        conversation_tree = Tree()
        converastion = postgres_queries.find_conversation(i)
        test_i += len(converastion)
        for tweet in converastion:
            if tweet[1] is None and tweet[5] is True:
                conversation_tree.create_node(tweet[0], tweet[0])
                build_conversation_lang(tweet[0], converastion, conversation_tree)
                depth = conversation_tree.depth() + 1
                number_of_tweets = len(conversation_tree.all_nodes())
                #short/long
                if number_of_tweets >=20:
                    if depth in depth_dict_long:
                        depth_dict_long[depth] += 1
                    else:
                        depth_dict_long[depth] = 1
                else:
                    if depth in depth_dict_short:
                        depth_dict_short[depth] += 1
                    else:
                        depth_dict_short[depth] = 1

                if number_of_tweets in number_of_tweets_dict:
                    number_of_tweets_dict[number_of_tweets] += 1
                else:
                     number_of_tweets_dict[number_of_tweets] = 1
                if depth in depth_dict:
                    depth_dict[depth] += 1
                else:
                    depth_dict[depth] = 1
        conversation_list.append(conversation_tree)
    number = 0
    new_tweet_list_id = list()
    for con in conversation_list:
        nodes = con.all_nodes()
        for node in nodes:
            new_tweet_list_id.append(node.tag)
        number += len(con.all_nodes())

    return new_tweet_list_id, conversation_list
开发者ID:imclab,项目名称:Twitter_DA_Recognition,代码行数:50,代码来源:rebuild_conversations.py

示例6: len

# 需要导入模块: from treelib import Tree [as 别名]
# 或者: from treelib.Tree import depth [as 别名]
	if len(tree.get_node(root).fpointer) == 2:
		left = get_LCA(tree.get_node(root).fpointer[0],n1,n2)
		right = get_LCA(tree.get_node(root).fpointer[1],n1,n2)

	if left is not None and right is not None: return root
	if left is not None: return left
	if right is not None:return right

	return None


LCA = get_LCA(tree.root, s.index(entity), s.index(opinionw))

# Calculate distance between two nodes
distance = tree.depth(tree.get_node(s.index(entity))) + tree.depth(tree.get_node(s.index(opinionw)))
distance = distance - 2 * tree.depth(tree.get_node(LCA))

print "Looking for words:", entity, opinionw
print "LCA is", tree.get_node(LCA).tag
print "Distance is", distance





def get_distance(word1, word2, tree):
	pass


开发者ID:ninaholm,项目名称:Discourse-Machine,代码行数:29,代码来源:tree_tester.py

示例7: SentenceTree

# 需要导入模块: from treelib import Tree [as 别名]
# 或者: from treelib.Tree import depth [as 别名]

#.........这里部分代码省略.........

				# Create left child as node (plus extra word node if leaf)
				cid = self._nnid()
				self.tree.create_node(left_child[0], cid, parent=pid)
				if left_child[2] is None: #If left_child is a leaf node, append a word node
					nid = left_coord[1]-1
					word = self.matrix[left_coord[0]-1][left_coord[1]][0]
					word = word.decode('utf-8', "ignore")
					self.tree.create_node(word, nid, parent=cid)
				else:
					self._create_children(left_child, cid) # Create children of left_child

				# Create right child as node (plus extra word node if leaf)
				cid = self._nnid()
				self.tree.create_node(right_child[0], cid, parent=pid)
				if right_child[2] is None: #If right_child is a leaf node, append a word node
					nid = right_coord[1]-1
					word = self.matrix[right_coord[0]-1][right_coord[1]][0]
					word = word.decode('utf-8', "ignore")
					self.tree.create_node(word, nid, parent=cid)
				else:
					self._create_children(right_child, cid) # Create children of right_child



	# Returns the sentence's sentiment score
	def get_sentiment_score(self, sentimentDict, term):
		total_score = 0

		# negation dictionary
		negationList = ["ikke", "ej"]

		# Check the term against every sentiment word
		n1 = self.sentence.index(term)
		for word in sentimentDict:
			if term==word: continue # If topic term is an opinion word, ignore.
			n2 = self._in_sentence(word)
			if n2 is not False:
				d = self._get_distance(n1, n2)
				if d == 0: score = float(sentimentDict[word])
				score = float(sentimentDict[word]) / float(d)

				# If SentWord is negated, flip the score derived from it
				if self._is_negated(word, negationList):
					score = score * -1

				print "Term: %s | SentWord: %s | Distance: %s | Score: %s" % (term, word, d,score)
				total_score += score

		print "Total score:", total_score
		return total_score


	# Checks whether a word is within a specified threshold distance of a negation word
	def _is_negated(self, w, negationList):
		negationThreshold = 3
		n1 = self._in_sentence(w)
		if n1 is None: return False
		for nw in negationList:
			n2 = self._in_sentence(nw)
			if n2 is not None:
				if (self._get_distance(n1, n2)) < negationThreshold:
					print "negating word", w
					return True
		return False


	# Checks whether word w exists in the ST's sentence
	def _in_sentence(self, w):
		if w in self.sentence:
			return self.sentence.index(w)
		return False


	# Returns distance between two nodes n1 and n2
	def _get_distance(self, n1, n2):
		LCA = self._get_LCA(self.tree.root, n1, n2)
		distance = self.tree.depth(self.tree.get_node(n1)) + self.tree.depth(self.tree.get_node(n2))
		distance = distance - 2 * self.tree.depth(self.tree.get_node(LCA))
		return abs(distance)


	# Returns lowest common ancestor of two nodes n1 and n2
	# Supporting method of _get_distance()
	def _get_LCA(self, current_node, n1, n2):
		if current_node is None: return None
		if current_node == n1 or current_node == n2: return current_node
		if len(self.tree.get_node(current_node).fpointer) == 0: return None #if leaf, return None
		if len(self.tree.get_node(current_node).fpointer) == 1: #if terminal node, check its single leaf node
			return self._get_LCA(self.tree.get_node(current_node).fpointer[0], n1, n2)

		if len(self.tree.get_node(current_node).fpointer) == 2:
			left = self._get_LCA(self.tree.get_node(current_node).fpointer[0],n1,n2)
			right = self._get_LCA(self.tree.get_node(current_node).fpointer[1],n1,n2)

		if left is not None and right is not None: return current_node
		if left is not None: return left
		if right is not None:return right

		return None
开发者ID:ninaholm,项目名称:Discourse-Machine,代码行数:104,代码来源:SentenceTree.py

示例8: AcquisitionChainIter

# 需要导入模块: from treelib import Tree [as 别名]
# 或者: from treelib.Tree import depth [as 别名]

#.........这里部分代码省略.........
        self._root_node = self._tree.create_node("acquisition chain", "root")
        device2iter = dict()
        for dev in acquisition_chain._tree.expand_tree():
            if not isinstance(dev, (AcquisitionDevice, AcquisitionMaster)):
                continue
            dev_node = acquisition_chain._tree.get_node(dev)
            parent = device2iter.get(dev_node.bpointer, "root")
            try:
                it = iter(dev)
            except TypeError:
                one_shot = self.acquisition_chain._device2one_shot_flag.get(
                    dev, True)
                dev_iter = DeviceIterator(dev, one_shot)
            else:
                dev_iter = DeviceIteratorWrapper(it)
            device2iter[dev] = dev_iter
            self._tree.create_node(
                tag=dev.name, identifier=dev_iter, parent=parent)

    @property
    def acquisition_chain(self):
        return self.__acquisition_chain_ref()

    def prepare(self, scan, scan_info):
        preset_tasks = list()
        if self.__sequence_index == 0:
            preset_tasks.extend([gevent.spawn(preset.prepare)
                                 for preset in self.acquisition_chain._presets_list])
            scan.prepare(scan_info, self.acquisition_chain._tree)

        self._execute(
            "_prepare", wait_between_levels=not self._parallel_prepare)

        if self.__sequence_index == 0:
            gevent.joinall(preset_tasks, raise_error=True)

    def start(self):
        if self.__sequence_index == 0:
            preset_tasks = [gevent.spawn(
                preset.start) for preset in self.acquisition_chain._presets_list]
            gevent.joinall(preset_tasks, raise_error=True)

        self._execute("_start")

    def stop(self):
        self._execute("stop", master_to_slave=True, wait_all_tasks=True)

        preset_tasks = [gevent.spawn(preset.stop)
                        for preset in self.acquisition_chain._presets_list]

        gevent.joinall(preset_tasks)  # wait to call all stop on preset
        gevent.joinall(preset_tasks, raise_error=True)

    def next(self):
        self.__sequence_index += 1
        gevent.joinall([gevent.spawn(dev_iter.wait_ready) for dev_iter in self._tree.expand_tree()
                        if dev_iter is not 'root'],
                       raise_error=True)
        try:
            if self.__sequence_index:
                for dev_iter in self._tree.expand_tree():
                    if dev_iter is 'root':
                        continue
                    dev_iter.next()
        except StopIteration:                # should we stop all devices?
            for acq_dev_iter in (x for x in self._tree.expand_tree() if x is not 'root' and
                                 isinstance(x.device, (AcquisitionDevice, AcquisitionMaster))):
                if hasattr(acq_dev_iter, 'wait_reading'):
                    acq_dev_iter.wait_reading()
                dispatcher.send("end", acq_dev_iter.device)
            raise
        return self

    def _execute(self, func_name,
                 master_to_slave=False, wait_between_levels=True,
                 wait_all_tasks=False):
        tasks = list()

        prev_level = None

        if master_to_slave:
            devs = list(self._tree.expand_tree(mode=Tree.WIDTH))[1:]
        else:
            devs = reversed(list(self._tree.expand_tree(mode=Tree.WIDTH))[1:])

        for dev in devs:
            node = self._tree.get_node(dev)
            level = self._tree.depth(node)
            if wait_between_levels and prev_level != level:
                gevent.joinall(tasks, raise_error=True)
                tasks = list()
                prev_level = level
            func = getattr(dev, func_name)
            tasks.append(gevent.spawn(func))
        # ensure that all tasks are executed
        # (i.e: don't raise the first exception on stop)
        if wait_all_tasks:
            gevent.joinall(tasks)

        gevent.joinall(tasks, raise_error=True)
开发者ID:tiagocoutinho,项目名称:bliss,代码行数:104,代码来源:chain.py

示例9: __init__

# 需要导入模块: from treelib import Tree [as 别名]
# 或者: from treelib.Tree import depth [as 别名]

#.........这里部分代码省略.........
    def update_node(self, node):
        """Update the node's data

        If leaf, then it was already calculated during processing, and now
        do not change it: the ev is the ev

        Minimax applied, hero pick best and foe picks min after p

        Traversed will stay the traversed_focus level for leaves, but for parent nodes
        the traversed will be the number of leaves reached from that node.
        """
        is_hero = node.data.get('seat') == self.hero
        # logger.debug('is hero? {}'.format(is_hero))

        # it will traverse back up to the root
        # root can be skipped
        if node.is_root():
            # input('hero {} node data {}'.format(self.hero, node.data.get('seat')))
            # if is_hero:
            #     self.rolling_10.append(abs(self.last_ev))
            #     self.rolling_40.append(abs(self.last_ev))
            #     logger.debug('Added {} ev to collection'.format(self.last_ev))
            #     input('Added {} ev to collection'.format(self.last_ev))
            # logger.debug('reached the root')
            # self.update_ev_change()
            return

        # fast forwarding will send here, just ignore node if leaf
        if node.is_leaf():
            # logger.debug('not updating {}: it is final game result (no leaf nodes)'.format(node.tag))
            # logger.debug('not updating {}: final data {}'.format(node.tag, node.data))
            return

        depth = self.tree.depth(node)
        # logger.info('updating node {} at depth {}'.format(node.tag, depth))
        # logger.info('node has {} before update'.format(node.data))

        if not len(node.fpointer):
            # logger.error('node {} with {} as no children...'.format(node.tag, node.data))
            raise Exception('not necessary to process leaves')
        # logger.debug('extracting data from {} children nodes...'.format(len(node.fpointer)))

        n_ev = float('-inf') if is_hero else 0
        n_traversed = 0
        for child_nid in node.fpointer:
            child_node = self.tree[child_nid]
            # logger.debug('child node {} has {}'.format(child_node.tag, child_node.data))
            dat = child_node.data
            if not dat['traversed']:
                # logger.debug('skipping untraversed {}'.format(child_node.tag))
                continue

            # get max for hero
            if is_hero:
                # todo is this +ev dampening necessary
                # todo this should be fixed when setting for hand range
                # equities = PE.showdown_equities(self.engine)
                # n_ev = max(n_ev, dat['ev'] * equities.get(self.hero, 0))
                n_ev = max(n_ev, dat['ev'])

            # get min for foe
            else:
                # ev_adj = dat['ev'] * dat['stats']
                # logger.debug('foe min between {} and {}'.format(n_ev, ev_adj))
                # n_ev = min(n_ev, ev_adj)
                n_ev += dat['ev'] * dat['stats'] / dat['divider']
开发者ID:Tjorriemorrie,项目名称:pokeraide,代码行数:70,代码来源:mc.py

示例10: SentenceTree

# 需要导入模块: from treelib import Tree [as 别名]
# 或者: from treelib.Tree import depth [as 别名]

#.........这里部分代码省略.........
		else:
			# If parse_option has children, extract those
			if parse_option.left_coord is not None:
				left_child = self.matrix[parse_option.left_coord[0]][parse_option.left_coord[1]][parse_option.left_coord[2]]
				right_child = self.matrix[parse_option.right_coord[0]][parse_option.right_coord[1]][parse_option.right_coord[2]]

				# Create left child as node (plus extra word node if leaf)
				cid = self._nnid()
				self.tree.create_node(left_child.constituent, cid, parent=pid)
				if left_child.left_coord is None: #If left_child is a leaf node, append a word node
					nid = parse_option.left_coord[1]-1
					word = self.matrix[parse_option.left_coord[0]-1][parse_option.left_coord[1]][0]
					self.tree.create_node(word, nid, parent=cid)
				else:
					self._create_children(left_child, cid) # Create children of left_child

				# Create right child as node (plus extra word node if leaf)
				cid = self._nnid()
				self.tree.create_node(right_child.constituent, cid, parent=pid)
				if right_child.right_coord is None: #If left_child is a leaf node, append a word node
					nid = parse_option.right_coord[1]-1
					word = self.matrix[parse_option.right_coord[0]-1][parse_option.right_coord[1]][0]
					self.tree.create_node(word, nid, parent=cid)
				else:
					self._create_children(right_child, cid) # Create children of right_child



	# Returns the sentence's sentiment score
	def get_sentiment_score(self, sentimentDict, term):
		total_score = 0

		# placeholder dictionaries -TESTING PURPOSES
		negationList = ["ikke", "liden"]

		# Check the term against every sentiment word
		n1 = self.sentence.index(term)
		for key in sentimentDict:
			n2 = self._in_sentence(key)
			if n2 is not False:
				d = self._get_distance(n1, n2)
				score = float(sentimentDict[key]) / float(d)

				# If SentWord is negated, flip the score derived from it
				if self._is_negated(key, negationList):
					score = score * -1

				print ">>SENTIMENTSCORE: Term: %s | SentWord: %s | Distance: %s | Score: %s" % (term, key, d,score)
				total_score += score

		return total_score


	# Checks whether a word is within a specified threshold distance of a negation word
	def _is_negated(self, w, negationList):
		negationThreshold = 3
		n1 = self._in_sentence(w)
		if n1 is None: return False
		for nw in negationList:
			n2 = self._in_sentence(nw)
			if n2 is not None:
				if (self._get_distance(n1, n2)) < negationThreshold:
					print "negating word", w
					return True
		return False


	# Checks whether word w exists in the ST's sentence
	def _in_sentence(self, w):
		if w in self.sentence:
			return self.sentence.index(w)
		return False


	# Returns distance between two nodes n1 and n2
	def _get_distance(self, n1, n2):
		LCA = self._get_LCA(self.tree.root, n1, n2)
		distance = self.tree.depth(self.tree.get_node(n1)) + self.tree.depth(self.tree.get_node(n2))
		distance = distance - 2 * self.tree.depth(self.tree.get_node(LCA))
		return distance-2


	# Returns lowest common ancestor of two nodes n1 and n2
	# Supporting method of _get_distance()
	def _get_LCA(self, root, n1, n2):
		if root is None: return None
		if root == n1 or root == n2: return root
		if len(self.tree.get_node(root).fpointer) == 0: return None #if leaf, return None
		if len(self.tree.get_node(root).fpointer) == 1: #if terminal node, check its single leaf node
			return self._get_LCA(self.tree.get_node(root).fpointer[0], n1, n2)

		if len(self.tree.get_node(root).fpointer) == 2:
			left = self._get_LCA(self.tree.get_node(root).fpointer[0],n1,n2)
			right = self._get_LCA(self.tree.get_node(root).fpointer[1],n1,n2)

		if left is not None and right is not None: return root
		if left is not None: return left
		if right is not None:return right

		return None
开发者ID:ninaholm,项目名称:Discourse-Machine,代码行数:104,代码来源:SyntacticParser.py

示例11: load

# 需要导入模块: from treelib import Tree [as 别名]
# 或者: from treelib.Tree import depth [as 别名]
class RST_DT:
    def load(self, path2file):
        self.id_EDUs = []
        self.EDU = {}
        self.treeNS = Tree()
        self.tree = Tree()
        # nombre max d'espace pour init id_parents
        with open(path2file, "r") as f:
            max_space = 0
            nb_line = 0
            for i, line in enumerate(f):
                nb_space = 0
                for c in line:
                    if c == " ":
                        nb_space += 1
                    else:
                        break
                if nb_space > max_space:
                    max_space = nb_space
                nb_line += 1
        with open(path2file, "r") as f:
            id_parents = [0] * max_space
            NS_parents = [0] * max_space
            for i, line in enumerate(f):
                # nombre d'espace détermine le parent
                nb_space = 0
                for c in line:
                    if c == " ":
                        nb_space += 1
                    else:
                        break
                space = nb_space / 2
                id_parents[space] = i
                parent = id_parents[space - 1]
                reg = "\(([\w\-\[\]]+)|(_!.+!_)"  # récupération du contenu
                match = re.findall(reg, line)[0]
                if match[0] == "":
                    content = match[1]  # feuille EDU
                    self.id_EDUs.append(i)
                    # print content
                    self.EDU[i] = re.findall("_!(.*)!_", content)
                else:
                    content = match[0]
                    reg2 = "\[(N|S)\]"  # récupération NS
                    match2 = re.findall(reg2, content)
                    NS_parents[space] = match2  # ['N','S']
                # création du noeud
                if i == 0:
                    self.tree.create_node(content, 0)
                    self.treeNS.create_node("Root", 0)
                else:
                    id_NS = len(self.tree.is_branch(parent))  # 0 ou 1 car arbre binaire
                    self.tree.create_node(content, i, parent=parent)
                    self.treeNS.create_node(NS_parents[space - 1][id_NS], i, parent=parent)

    def toDEP(self):

        ###############################
        # Etape 1 : construction du head_tree

        # parcours en largeur de tree afin de récupérer chaque id_node
        # pour chaque profondeur (init à 0) _! sans compter !_ les feuilles (EDUs)

        nodes_depth = [-1] * self.tree.size()
        for i in xrange(self.tree.size()):
            id_nodes = [0]
            depth = [999] * self.tree.size()
            while id_nodes:  # False if empty
                id_node = id_nodes.pop(0)
                node = self.tree.get_node(id_node)
                if node.bpointer != None:
                    node_parent = self.tree.get_node(node.bpointer)
                    depth[node.identifier] = depth[node_parent.identifier] + 1
                else:
                    depth[node.identifier] = 0
                if id_node == i:
                    # print 'noeud ',i,' en profondeur', depth[node.identifier]
                    if node.fpointer:
                        nodes_depth[i] = depth[i]
                    break
                if node.fpointer:
                    id_nodes.append(node.fpointer[0])
                    id_nodes.append(node.fpointer[1])
        # print nodes_depth

        id_nodes_depth = []
        for d in xrange(self.tree.depth()):
            id_nodes_depth.append([])
            for i in xrange(self.tree.size()):
                if nodes_depth[i] == d:
                    id_nodes_depth[d].append(i)
        # print id_nodes_depth

        #
        # construction du head_tree

        head_tree = [-1] * self.treeNS.size()
        # pour chaque noeud (non EDU/feuille) en partant de la plus grande profondeur dans l'arbre
        for d in range(len(id_nodes_depth) - 1, -1, -1):
            for id_node in id_nodes_depth[d]:
#.........这里部分代码省略.........
开发者ID:niki-rohani,项目名称:Automatic_summarization_using_RST_DT,代码行数:103,代码来源:rst2dep.py

示例12: Route

# 需要导入模块: from treelib import Tree [as 别名]
# 或者: from treelib.Tree import depth [as 别名]
class Route(object):
    def __init__(self, universe):
        self.route    = Tree()
        self.universe = universe
        self.max_hops = 4

    def show(self):
        self.route.show()
    
    def asString(self):
        return (','.join([self.route[node].tag for node in self.route.expand_tree(mode=Tree.DEPTH)]))

    def getRoute(self):
        return self.route
        
    def byScore_key(self, s):
        return s.score
            
    def findRoute(self, start):
        parent = self.universe.findSystem(start)
        self.route.create_node(start, start, data=parent)
        systems = self.findNextSystems(start, start) 
        self.buildRoute(systems, start)
        
        return self.route

    def buildRoute(self, systems, parent):
        for s in systems:
            n = s.name
            h = 0
            
            if (self.route.contains(n) == False):  
                self.route.create_node(n, n, parent=parent, data=s)
        
                hop = h + self.route.depth(n)
                
                if (hop < self.max_hops):
                    sub_systems = self.findNextSystems(parent, n)                        
                    self.buildRoute(sub_systems, n)
            else:
                 n = parent + ' --> ' + n
                 self.route.create_node(n, n, parent=parent, data=s)

    def getSystemId(self, name, i=0):
        if (self.route.contains(name) == False):
            return name
        else:
            i += 1
            n = name + '(' + str(i) + ')'
            return self.getSystemId(n)

    def findNextSystems(self, parent, start):
        systems = []
        optimal = self.universe.distances.findOptimalSystems(start)
        
        for s in sorted(set(optimal)):
            if (s != parent):
                i = self.universe.findSystem(s)
                if (i.permit == False):
                    systems.append(i)
            
        s = sorted(systems, key = self.byScore_key)

        return s[:self.max_hops]

# http://xiaming.me/treelib/examples.html
#
# class SystemTree(object):
#     def __init__(self):
#         self.tree = Tree()
#         
#     def addNode(self, id, o):
#         self.tree.create_node(o, id)
#         
#     def addChildNode(self, p, id, o):
#         self.tree.create_node(o, id, parent=p)
#     
#     def getNode(self, id):
#         return self.tree.subtree(id)
#         
#     def __repr__(self):
#         return self.tree.to_json(with_data=True)
# 
# 
# t = SystemTree()
# t.addNode('Aerial', 'Aerial')
# t.addChildNode('Aerial', 'Jotun', 'Jotun')
# t.addChildNode('Jotun', 'Rusani', 'Rusani')
# n = t.getNode('Jotun')
# print(n)
# n = t.tree.contains('Invalid')
# print(n)
# t.tree.show()
开发者ID:andrewdjackson,项目名称:eliterares,代码行数:95,代码来源:route.py


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