本文整理汇总了Python中treelib.Tree.expand_tree方法的典型用法代码示例。如果您正苦于以下问题:Python Tree.expand_tree方法的具体用法?Python Tree.expand_tree怎么用?Python Tree.expand_tree使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类treelib.Tree
的用法示例。
在下文中一共展示了Tree.expand_tree方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: AcquisitionChain
# 需要导入模块: from treelib import Tree [as 别名]
# 或者: from treelib.Tree import expand_tree [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)
示例2: AcquisitionChain
# 需要导入模块: from treelib import Tree [as 别名]
# 或者: from treelib.Tree import expand_tree [as 别名]
class AcquisitionChain(object):
def __init__(self, parallel_prepare=False):
self._tree = Tree()
self._root_node = self._tree.create_node("acquisition chain", "root")
self._device_to_node = dict()
self._presets_list = list()
self._parallel_prepare = parallel_prepare
self._device2one_shot_flag = weakref.WeakKeyDictionary()
@property
def nodes_list(self):
nodes_gen = self._tree.expand_tree()
nodes_gen.next() # first node is 'root'
return list(nodes_gen)
def add(self, master, slave):
self._device2one_shot_flag.setdefault(slave, False)
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, master)
slave.parent = master
def add_preset(self, preset):
self._presets_list.append(preset)
def set_stopper(self, device, stop_flag):
"""
By default any top master device will stop the scan.
In case of several top master, you can define which one won't
stop the scan
"""
self._device2one_shot_flag[device] = not stop_flag
def __iter__(self):
if len(self._tree) > 1:
return AcquisitionChainIter(self, parallel_prepare=self._parallel_prepare)
else:
return iter(())
示例3: print
# 需要导入模块: from treelib import Tree [as 别名]
# 或者: from treelib.Tree import expand_tree [as 别名]
tree.create_node("Harry", "harry") # root node
tree.create_node("Jane", "jane", parent="harry")
tree.create_node("Bill", "bill", parent="harry")
tree.create_node("Diane", "diane", parent="jane")
tree.create_node("George", "george", parent="diane")
tree.create_node("Mary", "mary", parent="diane")
tree.create_node("Jill", "jill", parent="george")
tree.create_node("Mark", "mark", parent="jane")
sep = "-" * 20 + "\n"
print(sep + "Tree of the whole family:")
tree.show(key=lambda x: x.tag, reverse=True)
print(sep + "All family members in DEPTH mode:")
for node in tree.expand_tree(mode=Tree.DEPTH):
print(tree[node].tag)
print(sep + "All family members without Diane sub-family:")
tree.show(idhidden=False, filter=lambda x: x.identifier != "diane")
# for node in tree.expand_tree(filter=lambda x: x.identifier != 'diane', mode=Tree.DEPTH):
# print tree[node].tag
print(sep + "Let me introduce Diane family only:")
sub_t = tree.subtree("diane")
sub_t.show()
print(sep + "Children of Diane")
for child in tree.is_branch("diane"):
print(tree[child].tag)
示例4: Tree
# 需要导入模块: from treelib import Tree [as 别名]
# 或者: from treelib.Tree import expand_tree [as 别名]
tree = Tree()
tree.create_node("Harry", "harry") # root node
tree.create_node("Jane", "jane", parent="harry")
tree.create_node("Bill", "bill", parent="harry")
tree.create_node("Diane", "diane", parent="jane")
tree.create_node("George", "george", parent="diane")
tree.create_node("Mary", "mary", parent="diane")
tree.create_node("Jill", "jill", parent="george")
tree.create_node("Mark", "mark", parent="jane")
print("#"*4 + "Breakdown of out family")
tree.show()
print('\n')
print("#"*4 + "All family members in DEPTH mode")
for node in tree.expand_tree(mode=Tree.DEPTH):
print tree[node].tag
print('\n')
print("#"*4 + "All family members without Diane sub-family")
for node in tree.expand_tree(filter=lambda x: x != 'diane', mode=Tree.DEPTH):
print tree[node].tag
print('\n')
print("#"*4 + "Let me introduce Diane family only")
sub_t = tree.subtree('diane')
sub_t.show()
print('\n')
print("#"*4 + "Children of Diane")
print tree.is_branch('diane')
示例5: print
# 需要导入模块: from treelib import Tree [as 别名]
# 或者: from treelib.Tree import expand_tree [as 别名]
tree.create_node("Harry", "harry") # root node
tree.create_node("Jane", "jane", parent="harry")
tree.create_node("Bill", "bill", parent="harry")
tree.create_node("Diane", "diane", parent="jane")
tree.create_node("George", "george", parent="diane")
tree.create_node("Mary", "mary", parent="diane")
tree.create_node("Jill", "jill", parent="george")
tree.create_node("Mark", "mark", parent="jane")
sep = "-"*20 + '\n'
print(sep + "Tree of the whole family:")
tree.show(key=lambda x: x.tag, reverse=True)
print(sep + "All family members in DEPTH mode:")
for node in tree.expand_tree(mode=Tree.ZIGZAG):
print(tree[node].tag)
print(sep + "All family members without Diane sub-family:")
tree.show(idhidden=False, filter=lambda x: x.identifier != 'diane')
# for node in tree.expand_tree(filter=lambda x: x.identifier != 'diane', mode=Tree.DEPTH):
# print tree[node].tag
print(sep + "Let me introduce Diane family only:")
sub_t = tree.subtree('diane')
sub_t.show()
print(sep + "Children of Diane")
for child in tree.is_branch('diane'):
print(tree[child].tag)
示例6: AcquisitionChainIter
# 需要导入模块: from treelib import Tree [as 别名]
# 或者: from treelib.Tree import expand_tree [as 别名]
class AcquisitionChainIter(object):
def __init__(self, acquisition_chain, parallel_prepare=True):
self.__sequence_index = -1
self._parallel_prepare = parallel_prepare
self.__acquisition_chain_ref = weakref.ref(acquisition_chain)
# set all slaves into master
for master in (x for x in acquisition_chain._tree.expand_tree() if isinstance(x, AcquisitionMaster)):
del master.slaves[:]
master.slaves.extend(
acquisition_chain._tree.get_node(master).fpointer)
# create iterators tree
self._tree = Tree()
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:
#.........这里部分代码省略.........
示例7: __init__
# 需要导入模块: from treelib import Tree [as 别名]
# 或者: from treelib.Tree import expand_tree [as 别名]
class DependencyReader:
"""DependencyReader object"""
def __init__(self):
self.tempDirectoryPath = mkdtemp(dir=".")
self.tree = Tree()
self.dependencies = {}
self.graphRelationships = []
def getPom(self, pomPath):
shutil.copy(pomPath, self.tempDirectoryPath)
os.chdir(self.tempDirectoryPath)
def getDependencies(self):
mavenTreeOutput = subprocess.Popen('mvn org.apache.maven.plugins:maven-dependency-plugin:RELEASE:tree -DoutputType=tgf', stdout=subprocess.PIPE, shell=True)
while True:
line = mavenTreeOutput.stdout.readline().rstrip()
if not line or re.search(r"BUILD SUCCESS", line):
break
match = re.match(r"\[INFO\]\s(\d*)\s*(.*):(.*):(\w+):([0-9\.]*)", line)
if match:
if not match.group(1) in self.dependencies.keys():
self.dependencies[match.group(1)] = DependencyNode(match.group(2), match.group(3), match.group(5), match.group(1))
if not self.tree.leaves():
self.tree.create_node(match.group(1), match.group(1), data=self.dependencies[match.group(1)])
self.dependencies[match.group(1)].get('jar', self.tempDirectoryPath)
match = re.match(r"\[INFO\]\s(\d*)\s(\d*)", line)
if match and match.group(2):
self.graphRelationships.append((match.group(1), match.group(2)))
def relateDependencies(self):
while self.graphRelationships:
for item in self.graphRelationships:
node = self.tree.get_node(item[0])
if node is not None:
parent = self.dependencies[item[0]]
child = self.dependencies[item[1]]
self.tree.create_node(child.referenceId, child.referenceId, parent=parent.referenceId, data=child)
self.graphRelationships.remove(item)
def scanDependencies(self):
# Need to run on each package with oneshot to get identifiers
# unless update dosocsv2 to create identifiers on scan
# or fix up dosocsv2 to create identifiers on scan instead
for node in self.tree.expand_tree(mode=Tree.DEPTH):
treeNode = self.tree.get_node(node)
subprocess.call('dosocs2 oneshot ' + treeNode.data.jarName, shell=True)
def createRelationships(self):
# Pass packages as relationships to new dosocsv2 command created
self.recursiveRelationship(self.tree.root)
def recursiveRelationship(self, parent):
for node in self.tree.is_branch(parent):
parentNode = self.tree.get_node(parent)
childNode = self.tree.get_node(node)
subprocess.call('dosocs2 packagerelate ' + parentNode.data.jarName + ' ' + childNode.data.jarName, shell=True)
self.recursiveRelationship(node)
def retrieve_dependencies(self, jarName):
if jarName is None:
root = self.tree.get_node(self.tree.root)
root = root.data.jarName
else:
root = jarName
tgfOutput = subprocess.Popen('dosocs2 dependencies ' + root, stdout=subprocess.PIPE, shell=True)
count = 0
tree = Tree()
dependencies = []
relationships = []
while True:
line = tgfOutput.stdout.readline()
if not line:
break
match = re.match(r"(\d+) - (.*)", line)
if match:
if count == 0:
count = count + 1
tree.create_node(match.group(2), match.group(1))
else:
dependencies.append((match.group(2), match.group(1)))
match = re.match(r"(\d+) (\d+)", line)
if match:
relationships.append((match.group(1), match.group(2)))
if not relationships:
#.........这里部分代码省略.........
示例8: Route
# 需要导入模块: from treelib import Tree [as 别名]
# 或者: from treelib.Tree import expand_tree [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()