本文整理汇总了Python中graph.Vertex.color方法的典型用法代码示例。如果您正苦于以下问题:Python Vertex.color方法的具体用法?Python Vertex.color怎么用?Python Vertex.color使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类graph.Vertex
的用法示例。
在下文中一共展示了Vertex.color方法的4个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: load
# 需要导入模块: from graph import Vertex [as 别名]
# 或者: from graph.Vertex import color [as 别名]
def load(graph, fobj, queryCallback=None, warningCallback=None):
"""Load .gml file
Arguments:
graph -- the graph to be created from the loaded file
fobj -- a file object of the GML file to be read
queryCallback -- function to display a default query dialog (default None)
warningCallback -- function to display a default warning dialog
(default None)
"""
try:
root = GMLList(Stream(fobj))
except EOF:
raise ImportError, "Premature end of file"
except Unbalanced:
raise ImportError, "Unbalanced delimiters in file"
except TypeMismatch:
raise ImportError, "Unintelligible value in file"
except EOList:
#!!! shouldn't happen
raise ImportError, "Internal error"
#XXX#
#XXX# Debugging print the tree
#XXX#
def traverse(a, i=0):
if i <= 0:
print ""
print ""
if isinstance(a, GMLList):
print (" " * i) + repr(a)
for k, v in a.data.items():
print " " * i + " " + repr(k)
for x in v:
traverse(x.data, i=i + 1)
else:
print (" " * i) + repr(a)
#XXX#
#XXX#
#XXX#
if 'graph' not in root.data:
raise ImportError, "No graphs in file." % str(root.data)
# We only load the first graph in the file.
if len(root.data['graph']) > 1 and warningCallback:
warningCallback("GLuskap does not support multiple graphs per file. "
"The first graph in the file will be processed.")
# Check GML version if it is supported
if 'version' in root.data and root.data['version'][0].data != 1:
if queryCallback:
result = queryCallback("Unsupported GML version %s."
"\n\nWould you like to continue?" % str(root.data['version'][0].data),
override=True,
buttons=['Yes', 'No'])
if result == CustomButtonDialog.ID['Yes']:
pass
else:
raise ImportError, "Import aborted."
else:
raise ImportError, "Unsupported GML version %s." % str(root.data['version'][0].data)
graphbranch = root.data['graph'][0].data
if not isinstance(graphbranch, GMLList):
raise ImportError, "GML format error: graph is not a List"
if 'directed' in graphbranch.data and graphbranch.data['directed'] != 0 and warningCallback:
warningCallback("GLuskap does not support directed graphs. "
"All edges will be processed as undirected.")
# Boolean variables to control if the rest of the import errors are handled
# automatically
yestoall = False
yesall_duplicate_vert = False
yesall_duplicate_edge = False
yesall_degenerate_edge = False
yesall_color = False
yesall_nonexist_vert = False
yesall_invalid_bends = False
#
# Vertices (Nodes)
#
vertexIndex = {}
for vxb in graphbranch.data['node']:
vxbranch = vxb.data
if not isinstance(vxbranch, GMLList):
raise ImportError, ("GML format error: node '%s' is not a List" %
(str(vxbranch)))
if 'id' not in vxbranch.data:
raise ImportError, "GML format error: node without ID"
#
# Extension - we allow node IDs of type String as well as
# integer.
#.........这里部分代码省略.........
示例2: load
# 需要导入模块: from graph import Vertex [as 别名]
# 或者: from graph.Vertex import color [as 别名]
def load(graph, fobj, queryCallback=None, warningCallback=None):
"""Load .gv or .dot file
Arguments:
graph -- the graph to be created from the loaded file
fobj -- a file object of the DOT file to be read
queryCallback -- function to display a default query dialog (default None)
warningCallback -- function to display a default warning dialog
(default None)
"""
# Set global variables to in DOTGraph for automatically replacing
# attributes of duplicate nodes and edges
global _yestoall_nodes
global _yestoall_edges
_yestoall_nodes = None
_yestoall_edges = None
try:
dotgraph = DOTGraph(Stream(fobj), queryCallback=queryCallback,
warningCallback=warningCallback)
except EOF:
raise ImportError, "Premature end of file"
except Unbalanced:
raise ImportError, "Unbalanced delimiters in file"
# Boolean variables to control if the rest of the import errors are handled
# automatically
yestoall = False
yesall_color = False
yesall_degenerate_edge = False
def getColor(color):
"""Retun an RGB float triple of a color string. Return False if invalid
Arguments:
color -- a string representing a color
"""
# Hex color
if color[0] == '#' and len(color) == 7:
fillstr = color
r = fillstr[1:3]
g = fillstr[3:5]
b = fillstr[5:7]
try:
color = [x / 255.0 for x in (int(r, 16), int(g, 16), int(b, 16))]
return color
except:
return False
# HSV float triple
elif ',' in color or ' ' in color:
color = color.replace(" ", "").split(',', 3)
try:
color = [float(x) for x in color]
color = colorsys.hsv_to_rgb(color[0], color[1], color[2])
return color
except:
return False
# X11 Color Name
else:
try:
color = colorByName(color)
return color
except UnknownColor:
return False
# Add all the vertices in the dotgraph to the context graph
for vertex, attributes in dotgraph.nodes.items():
v = Vertex(id=vertex)
if 'label' in attributes:
v.name = attributes['label']
if 'width' in attributes:
v.radius = float(attributes['width'])
if 'pos' in attributes:
# remove ! and spaces, then split numbers
pos = attributes['pos'][:-1].replace(" ", "").split(',', 3)
if len(pos) < 3:
pos.append(0.0)
v.pos = (float(pos[0]), float(pos[1]), float(pos[2]))
if 'color' in attributes:
color = getColor(attributes['color'])
if color != False:
v.color = tuple(color)
elif not yesall_color and not yestoall:
# Invalid color
if queryCallback:
result = queryCallback("Invalid vertex color %s for %s. "
"Assign default color?" %
(attributes['color'], vertex), True)
if result == CustomButtonDialog.ID['Yes']:
pass
elif result == CustomButtonDialog.ID['Yes to similar errors']:
yesall_color = True
elif result == CustomButtonDialog.ID['Yes to all errors']:
yestoall = True
else:
raise ImportError, "Import aborted."
#.........这里部分代码省略.........
示例3: load
# 需要导入模块: from graph import Vertex [as 别名]
# 或者: from graph.Vertex import color [as 别名]
def load(graph, fobj, queryCallback=None, warningCallback=None):
""" Load a TLP file and create a graph from it
Arguments:
graph -- the graph to be created from the loaded file
fobj -- a file object of the TLP file to be read
queryCallback -- function to display a default query dialog (default None)
warningCallback -- function to display a default warning dialog
(default None)
"""
try:
tlpgraph = TLPGraph(Stream(fobj))
except Unbalanced:
raise ImportError, "Unbalanced delimiters in file"
except TypeMismatch:
raise ImportError, "Unintelligible value in file"
except EOF:
raise ImportError, "Premature end of file"
# Boolean variables to control if the rest of the import errors are handled
# automatically
yestoall = False
yesall_duplicate_edge = False
yesall_degenerate_edge = False
yesall_nonexist_vert = False
# Make vertices and apply properties
for vertex, properties in tlpgraph.nodes.items():
v = Vertex(vertex)
if "viewLabel" in properties:
v.name = properties["viewLabel"]
if "viewLayout" in properties:
pos = string_to_tuple(properties["viewLayout"])
v.pos = tuple([float(x) for x in pos])
if "viewSize" in properties:
v.radius = float(string_to_tuple(properties["viewSize"])[0])
if "viewColor" in properties:
color = string_to_tuple(properties["viewColor"])[:3]
v.color = tuple([float(x) / 255 for x in color])
graph.addVertex(v)
# Make edges and apply properties
edges = tlpgraph.edges.values()
edges.extend(tlpgraph.lost_edges)
for properties in edges:
source = properties["source"]
target = properties["target"]
# Raise an error if edge is degenerate, or source or target vertices
# are non existent. Automatically handle errors if yes all is selected
if source == target:
# Degenerate Edge
if yesall_degenerate_edge or yestoall:
continue
if queryCallback:
result = queryCallback("Degenerate edge detected: %s -> %s" % (source, target))
if result == CustomButtonDialog.ID["Yes"]:
continue
elif result == CustomButtonDialog.ID["Yes to similar errors"]:
yesall_degenerate_edge = True
continue
elif result == CustomButtonDialog.ID["Yes to all errors"]:
yestoall = True
continue
else:
raise ImportError, "Import aborted."
else:
raise ImportError("Degenerate edge detected: %s -> %s" % (source, target))
if source not in tlpgraph.nodes.keys():
# Nonexistent vertex
if yesall_nonexist_vert or yestoall:
continue
if queryCallback:
result = queryCallback("Edge specifies nonexistent " "source vertex %s" % (source))
if result == CustomButtonDialog.ID["Yes"]:
continue
elif result == CustomButtonDialog.ID["Yes to similar errors"]:
yesall_nonexist_vert = True
continue
elif result == CustomButtonDialog.ID["Yes to all errors"]:
yestoall = True
continue
else:
raise ImportError, "Import aborted."
else:
raise ImportError, ("Edge specifies nonexistent source vertex" " %s" % (source))
if target not in tlpgraph.nodes.keys():
# Nonexistent vertex
if yesall_nonexist_vert or yestoall:
continue
if queryCallback:
result = queryCallback("Edge specifies nonexistent " "target vertex %s" % (target))
if result == CustomButtonDialog.ID["Yes"]:
continue
elif result == CustomButtonDialog.ID["Yes to similar errors"]:
yesall_nonexist_vert = True
continue
#.........这里部分代码省略.........
示例4: load
# 需要导入模块: from graph import Vertex [as 别名]
# 或者: from graph.Vertex import color [as 别名]
def load(graph, fobj, queryCallback=None, warningCallback=None):
""" Load a GraphML file and create a graph from it
Arguments:
graph -- the graph to be created from the loaded file
fobj -- a file object of the GraphML file to be read
queryCallback -- function to display a default query dialog (default None)
warningCallback -- function to display a default warning dialog
(default None)
"""
from xml.dom.minidom import parse
grml_dom = parse(fobj)
GraphML = grml_dom.documentElement
typeTable = {
'int': int,
'long': long,
'float': float,
'double': float,
'string': str,
'boolean': bool,
}
#
# Read the keys part of the GraphML file
#
keyInfo = {}
defaults = {}
# Boolean variables to control if the rest of the import errors are handled
# automatically
yestoall = False
yesall_duplicate_vert = False
yesall_duplicate_edge = False
yesall_degenerate_edge = False
yesall_color = False
yesall_nonexist_vert = False
# Store the graph attributes in a dictionary named keyInfo,
# and storing any defaults in the dictionary named defaults
for keyNode in GraphML.getElementsByTagName("key"):
attrs = dict(
[(str(a), str(b)) for a, b in keyNode.attributes.items()]
)
id = attrs.pop('id')
if 'for' in attrs and attrs['for'] not in defaults:
defaults[attrs['for']] = {}
# Add the desc to the info for this key
desc = keyNode.getElementsByTagName("desc")
if len(desc) > 0:
attrs['desc'] = str(desc[0].childNodes[0].wholeText).strip()
# Convert the type to a python native type
if 'attr.type' in attrs.keys():
attrs['attr.type'] = typeTable[attrs['attr.type']]
# If there's a default, store it
default = keyNode.getElementsByTagName("default")
if len(default) > 0:
defaults[attrs['for']][id] = attrs['attr.type'](default[0].childNodes[0].wholeText.strip())
# Dupicate id's are mapped depending on 'for' type
if id not in keyInfo:
keyInfo[id] = {}
if 'for' in attrs:
keyInfo[id][attrs['for']] = attrs
else:
keyInfo[id]['forNotSpecified'] = attrs
# We read only the first graph in a GraphML file.
graphs = GraphML.getElementsByTagName('graph')
if len(graphs) < 1:
raise ImportError, "No graphs in this file!"
if len(graphs) > 1 and warningCallback:
warningCallback("Multiple graphs per file are not supported. "
"The first graph in the file will be processed.")
graphNode = graphs[0]
attrs = dict(
[(str(a), str(b)) for a, b in graphNode.attributes.items()]
)
if 'edgedefault' not in attrs:
raise ImportError, "No edge default directedness found!"
if attrs['edgedefault'] != 'undirected' and warningCallback:
warningCallback("Directed graphs are not supported. "
"Directed edges will be converted.")
#
# Set up an index of vertex IDs and edge tuples - this allows
# us to check uniqueness and also eliminates costly
# findVertexByID calls.
#
vertexIndex = {}
edgeIndex = {}
#.........这里部分代码省略.........