def draw(self, name, dname, draw_branches=True):
from pydot import Dot, Edge
g = Dot()
g.set_node_defaults(color='lightgray', style='filled', shape='box',
fontname='Courier', fontsize='10')
for node in sorted(self.nodes, key=lambda x: x.num):
if draw_branches and node.type.is_cond:
g.add_edge(Edge(str(node), str(node.true), color='green'))
g.add_edge(Edge(str(node), str(node.false), color='red'))
else:
for suc in self.sucs(node):
g.add_edge(Edge(str(node), str(suc), color='blue'))
for except_node in self.catch_edges.get(node, []):
g.add_edge(Edge(str(node), str(except_node),
color='black', style='dashed'))
g.write_png('%s/%s.png' % (dname, name))
python类Dot()的实例源码
def execute(cls, ids, data):
import pydot
pool = Pool()
Model = pool.get('ir.model')
ActionReport = pool.get('ir.action.report')
if not data['filter']:
filter = None
else:
filter = re.compile(data['filter'], re.VERBOSE)
action_report_ids = ActionReport.search([
('report_name', '=', cls.__name__)
])
if not action_report_ids:
raise Exception('Error', 'Report (%s) not find!' % cls.__name__)
action_report = ActionReport(action_report_ids[0])
models = Model.browse(ids)
graph = pydot.Dot(fontsize="8")
graph.set('center', '1')
graph.set('ratio', 'auto')
cls.fill_graph(models, graph, level=data['level'], filter=filter)
data = graph.create(prog='dot', format='png')
return ('png', fields.Binary.cast(data), False, action_report.name)
def draw(self, name, dname, draw_branches=True):
from pydot import Dot, Edge
g = Dot()
g.set_node_defaults(color='lightgray', style='filled', shape='box',
fontname='Courier', fontsize='10')
for node in sorted(self.nodes, key=lambda x: x.num):
if draw_branches and node.type.is_cond:
g.add_edge(Edge(str(node), str(node.true), color='green'))
g.add_edge(Edge(str(node), str(node.false), color='red'))
else:
for suc in self.sucs(node):
g.add_edge(Edge(str(node), str(suc), color='blue'))
for except_node in self.catch_edges.get(node, []):
g.add_edge(Edge(str(node), str(except_node),
color='black', style='dashed'))
g.write_png('%s/%s.png' % (dname, name))
def debugPlot(self, outfile):
graph = pydot.Dot(graph_type='digraph')
nodes = dict()
for layerCfg in self.layerCfgs:
node = pydot.Node(layerCfg.name)
graph.add_node(node)
nodes[layerCfg.name] = node
for inp in layerCfg._inputs:
if isinstance(inp,int):
node = pydot.Node("input[{}]".format(inp))
graph.add_node(node)
nodes[str(inp)] = node
for layerCfg in self.layerCfgs:
for inp in layerCfg._inputs:
if isinstance(inp,int):
inp = str(inp)
edge = pydot.Edge(nodes[inp],nodes[layerCfg.name])
graph.add_edge(edge)
graph.write_png(outfile)
def make_corenlp_tree(data_in_path, data_out_path, num_sentence):
tree = ET.parse(data_in_path)
root = tree.getroot()
i = 0
for dependencies in root.findall(".//dependencies"):
if dependencies.get('type') != 'collapsed-dependencies':
continue
i += 1
if i != num_sentence:
continue
graph = pydot.Dot()
graph.set_type('digraph')
for dep in dependencies.findall('dep'):
from_edge = dep.find('governor').text + ' _ ' + dep.find('governor').get('idx')
to_edge = dep.find('dependent').text + ' _ ' + dep.find('dependent').get('idx')
if to_edge in ',':
to_edge = r'\,'
graph.add_edge(pydot.Edge(from_edge, to_edge))
graph.write_jpeg(data_out_path)
break
def graph_from_idx_edges(edges):
graph = pydot.Dot(graph_type = 'digraph')
for edge in edges:
idx1 = str(edge[0][0])
label1 = str(edge[0][1])
idx2 = str(edge[1][0])
label2 = str(edge[1][1])
graph.add_node(pydot.Node(idx1, label=label1))
graph.add_node(pydot.Node(idx2, label=label2))
graph.add_edge(pydot.Edge(idx1, idx2))
return graph
def draw(self, name, dname, draw_branches=True):
from pydot import Dot, Edge
g = Dot()
g.set_node_defaults(color='lightgray', style='filled', shape='box',
fontname='Courier', fontsize='10')
for node in sorted(self.nodes, key=lambda x: x.num):
if draw_branches and node.type.is_cond:
g.add_edge(Edge(str(node), str(node.true), color='green'))
g.add_edge(Edge(str(node), str(node.false), color='red'))
else:
for suc in self.sucs(node):
g.add_edge(Edge(str(node), str(suc), color='blue'))
for except_node in self.catch_edges.get(node, []):
g.add_edge(Edge(str(node), str(except_node),
color='black', style='dashed'))
g.write_png('%s/%s.png' % (dname, name))
def draw(self, name, dname, draw_branches=True):
from pydot import Dot, Edge
g = Dot()
g.set_node_defaults(color='lightgray', style='filled', shape='box',
fontname='Courier', fontsize='10')
for node in sorted(self.nodes, key=lambda x: x.num):
if draw_branches and node.type.is_cond:
g.add_edge(Edge(str(node), str(node.true), color='green'))
g.add_edge(Edge(str(node), str(node.false), color='red'))
else:
for suc in self.sucs(node):
g.add_edge(Edge(str(node), str(suc), color='blue'))
for except_node in self.catch_edges.get(node, []):
g.add_edge(Edge(str(node), str(except_node),
color='black', style='dashed'))
g.write_png('%s/%s.png' % (dname, name))
def render_graph_graphviz (self):
'''
Render the graphviz graph structure.
@rtype: pydot.Dot
@return: Pydot object representing entire graph
'''
import pydot
dot_graph = pydot.Dot()
for node in self.nodes.values():
dot_graph.add_node(node.render_node_graphviz(self))
for edge in self.edges.values():
dot_graph.add_edge(edge.render_edge_graphviz(self))
return dot_graph
####################################################################################################################
def to_pydot(self):
"""Return a pydot digraph from a StepTree."""
graph = pydot.Dot(graph_type='digraph')
# make sure Root shows up in single node trees
if self.root_name:
graph.add_node(pydot.Node(self._step_graph_label(self.root_name)))
for parent, children in self.children.items():
for child in children:
graph.add_edge(pydot.Edge(
self._step_graph_label(parent),
self._step_graph_label(child)
))
return graph
textFeatureExtraction.py 文件源码
项目:pyOpenAireTextClassifier
作者: tyiannak
项目源码
文件源码
阅读 24
收藏 0
点赞 0
评论 0
def drawGraphFromSM2(SM, names, outFile, Cut):
graph = pydot.Dot(graph_type='graph')
# THRESHOLD SM:
nonZeroMean = np.mean(SM[SM.nonzero()])
if Cut:
T = 5.0 * nonZeroMean
else:
T = 0.0;
for i in range(SM.shape[0]):
for j in range(SM.shape[0]):
if SM[i,j] <= T:
SM[i,j] = 0.0
else:
SM[i,j] = 1.0
numOfConnections = sum(SM, axis = 0)
#fig = plt.figure(1)
#plot1 = plt.imshow(SM, origin='upper', cmap=cm.gray, interpolation='nearest')
#plt.show()
numOfConnections = 9*numOfConnections / max(numOfConnections)
for i,f in enumerate(names):
if sum(SM[i,:])>0:
fillColorCurrent = "{0:d}".format(int(ceil(numOfConnections[i])))
# NOTE: SEE http://www.graphviz.org/doc/info/colors.html for color schemes
node = pydot.Node(f, style="filled", fontsize="8", shape="egg", fillcolor=fillColorCurrent, colorscheme = "reds9")
graph.add_node(node)
for i in range(len(names)):
for j in range(len(names)):
if i<j:
if SM[i][j] > 0:
#gr.add_edge((names[i], names[j]))
edge = pydot.Edge(names[i], names[j])
graph.add_edge(edge)
graph.write_png(outFile)
def __init__(self):
self.seen = set()
self.dot = pydot.Dot("resnet", graph_type="digraph", rankdir="TB")
self.style_params = {"shape": "octagon",
"fillcolor": "gray",
"style": "filled",
"label": "",
"color": "none"}
self.style_layers = {"shape": "box",
"fillcolor": "blue",
"style": "filled",
"label": "",
"color": "none"}
def writeDotImage(self, filename):
""" Writes a image representation of the individual
:param filename: the output file image
"""
if not HAVE_PYDOT:
utils.raiseException("You must install Pydot to use this feature !")
graph = pydot.Dot()
self.writeDotGraph(graph)
graph.write_jpeg(filename, prog='dot')
# -----------------------------------------------------------------
def writeDotRaw(self, filename):
""" Writes the raw dot file (text-file used by dot/neato) with the
representation of the individual
:param filename: the output file, ex: individual.dot
"""
if not HAVE_PYDOT:
utils.raiseException("You must install Pydot to use this feature !")
graph = pydot.Dot(graph_type="digraph")
self.writeDotGraph(graph)
graph.write(filename, prog='dot', format="raw")
# -----------------------------------------------------------------
def writePopulationDot(ga_engine, filename, format="jpeg", start=0, end=0):
""" Writes to a graphical file using pydot, the population of trees
Example:
>>> GTreeGP.writePopulationDot(ga_engine, "pop.jpg", "jpeg", 0, 10)
This example will draw the first ten individuals of the population into
the file called "pop.jpg".
:param ga_engine: the GA Engine
:param filename: the filename, ie. population.jpg
:param start: the start index of individuals
:param end: the end index of individuals
"""
if not HAVE_PYDOT:
utils.raiseException("You must install Pydot to use this feature !")
pop = ga_engine.get_population()
graph = pydot.Dot(graph_type="digraph")
if not isinstance(pop[0], GTreeGP):
utils.raiseException("The population must have individuals of the GTreeGP chromosome !")
n = 0
end_index = len(pop) if end == 0 else end
for i in xrange(start, end_index):
ind = pop[i]
subg = pydot.Cluster(
"cluster_%d" % i,
label="\"Ind. #%d - Score Raw/Fit.: %.4f/%.4f\"" % (i, ind.getRawScore(), ind.getFitnessScore())
)
n = ind.writeDotGraph(subg, n)
graph.add_subgraph(subg)
graph.write(filename, prog='dot', format=format)
# -----------------------------------------------------------------
def writePopulationDotRaw(ga_engine, filename, start=0, end=0):
""" Writes to a raw dot file using pydot, the population of trees
Example:
>>> GTreeGP.writePopulationDotRaw(ga_engine, "pop.dot", 0, 10)
This example will draw the first ten individuals of the population into
the file called "pop.dot".
:param ga_engine: the GA Engine
:param filename: the filename, ie. population.dot
:param start: the start index of individuals
:param end: the end index of individuals
"""
if not HAVE_PYDOT:
utils.raiseException("You must install Pydot to use this feature !")
pop = ga_engine.get_population()
graph = pydot.Dot(graph_type="digraph")
if not isinstance(pop[0], GTreeGP):
utils.raiseException("The population must have individuals of the GTreeGP chromosome !")
n = 0
end_index = len(pop) if end == 0 else end
for i in xrange(start, end_index):
ind = pop[i]
subg = pydot.Cluster(
"cluster_%d" % i,
label="\"Ind. #%d - Score Raw/Fit.: %.4f/%.4f\"" % (i, ind.getRawScore(), ind.getFitnessScore())
)
n = ind.writeDotGraph(subg, n)
graph.add_subgraph(subg)
graph.write(filename, prog='dot', format="raw")
# -----------------------------------------------------------------
def writeDotImage(self, filename):
""" Writes a image representation of the individual
:param filename: the output file image
"""
if not HAVE_PYDOT:
utils.raiseException("You must install Pydot to use this feature !")
graph = pydot.Dot()
self.writeDotGraph(graph)
graph.write_jpeg(filename, prog='dot')
# -----------------------------------------------------------------
def writePopulationDot(ga_engine, filename, format="jpeg", start=0, end=0):
""" Writes to a graphical file using pydot, the population of trees
Example:
>>> GTreeGP.writePopulationDot(ga_engine, "pop.jpg", "jpeg", 0, 10)
This example will draw the first ten individuals of the population into
the file called "pop.jpg".
:param ga_engine: the GA Engine
:param filename: the filename, ie. population.jpg
:param start: the start index of individuals
:param end: the end index of individuals
"""
if not HAVE_PYDOT:
utils.raiseException("You must install Pydot to use this feature !")
pop = ga_engine.get_population()
graph = pydot.Dot(graph_type="digraph")
if not isinstance(pop[0], GTreeGP):
utils.raiseException("The population must have individuals of the GTreeGP chromosome !")
n = 0
end_index = len(pop) if end == 0 else end
for i in xrange(start, end_index):
ind = pop[i]
subg = pydot.Cluster(
"cluster_%d" % i,
label="\"Ind. #%d - Score Raw/Fit.: %.4f/%.4f\"" % (i, ind.getRawScore(), ind.getFitnessScore())
)
n = ind.writeDotGraph(subg, n)
graph.add_subgraph(subg)
graph.write(filename, prog='dot', format=format)
# -----------------------------------------------------------------
def writePopulationDotRaw(ga_engine, filename, start=0, end=0):
""" Writes to a raw dot file using pydot, the population of trees
Example:
>>> GTreeGP.writePopulationDotRaw(ga_engine, "pop.dot", 0, 10)
This example will draw the first ten individuals of the population into
the file called "pop.dot".
:param ga_engine: the GA Engine
:param filename: the filename, ie. population.dot
:param start: the start index of individuals
:param end: the end index of individuals
"""
if not HAVE_PYDOT:
utils.raiseException("You must install Pydot to use this feature !")
pop = ga_engine.get_population()
graph = pydot.Dot(graph_type="digraph")
if not isinstance(pop[0], GTreeGP):
utils.raiseException("The population must have individuals of the GTreeGP chromosome !")
n = 0
end_index = len(pop) if end == 0 else end
for i in xrange(start, end_index):
ind = pop[i]
subg = pydot.Cluster(
"cluster_%d" % i,
label="\"Ind. #%d - Score Raw/Fit.: %.4f/%.4f\"" % (i, ind.getRawScore(), ind.getFitnessScore())
)
n = ind.writeDotGraph(subg, n)
graph.add_subgraph(subg)
graph.write(filename, prog='dot', format="raw")
# -----------------------------------------------------------------
def plot(self, model, to_file):
"""
creates a graph visualizing the structure of `model` and writes it to `to_file`
"""
graph = pydot.Dot(graph_type='graph')
self.add_model(model, graph)
graph.write_png(to_file)
def to_png_with_pydot(self, filename):
import pydot
graph = pydot.Dot(graph_type='digraph', rankdir="LR")
self._to_pydot(graph)
graph.write_png(filename)
def graph_from_edges_ex(edge_list, title, directed=False):
if directed:
graph = pydot.Dot(graph_type='digraph')
else:
graph = pydot.Dot(graph_type='graph')
for edge in edge_list:
id1 = str(edge[0][0])
label1 = str(edge[0][1])
id2 = str(edge[1][0])
label2 = str(edge[1][1])
# add node
graph.add_node(pydot.Node(id1, label=label1))
graph.add_node(pydot.Node(id2, label=label2))
# add edege
graph.add_edge(pydot.Edge(id1, id2))
graph.set_label( title )
return graph
def knock_44(Sent):
tree_graph=pydot.Dot(graph_type='digraph',fontname="Microsoft YaHei")
nodes=[]
for ind, p in enumerate(Sent.phrases):
nodes.append(pydot.Node(p.str,fontname="Microsoft YaHei"))
tree_graph.add_node(nodes[ind])
for ind, p in enumerate(Sent.phrases):
if p.father!=-1:
tree_graph.add_edge(pydot.Edge(nodes[ind],nodes[p.father]))
tree_graph.write_png("knock_44.png")
# In[152]:
def knock_44(Sent):
tree_graph=pydot.Dot(graph_type='digraph',fontname="Microsoft YaHei")
nodes=[]
for ind, p in enumerate(Sent.phrases):
nodes.append(pydot.Node(p.str,fontname="Microsoft YaHei"))
tree_graph.add_node(nodes[ind])
for ind, p in enumerate(Sent.phrases):
if p.father!=-1:
tree_graph.add_edge(pydot.Edge(nodes[ind],nodes[p.father]))
tree_graph.write_png("knock_44.png")
# In[152]:
def knock_44(Sent):
tree_graph=pydot.Dot(graph_type='digraph',fontname="Microsoft YaHei")
nodes=[]
for ind, p in enumerate(Sent.phrases):
nodes.append(pydot.Node(p.str,fontname="Microsoft YaHei"))
tree_graph.add_node(nodes[ind])
for ind, p in enumerate(Sent.phrases):
if p.father!=-1:
tree_graph.add_edge(pydot.Edge(nodes[ind],nodes[p.father]))
tree_graph.write_png("knock_44.png")
# In[152]:
def knock_44(Sent):
tree_graph=pydot.Dot(graph_type='digraph',fontname="Microsoft YaHei")
nodes=[]
for ind, p in enumerate(Sent.phrases):
nodes.append(pydot.Node(p.str,fontname="Microsoft YaHei"))
tree_graph.add_node(nodes[ind])
for ind, p in enumerate(Sent.phrases):
if p.father!=-1:
tree_graph.add_edge(pydot.Edge(nodes[ind],nodes[p.father]))
tree_graph.write_png("knock_44.png")
# In[152]:
def knock_44(Sent):
tree_graph=pydot.Dot(graph_type='digraph',fontname="Microsoft YaHei")
nodes=[]
for ind, p in enumerate(Sent.phrases):
nodes.append(pydot.Node(p.str,fontname="Microsoft YaHei"))
tree_graph.add_node(nodes[ind])
for ind, p in enumerate(Sent.phrases):
if p.father!=-1:
tree_graph.add_edge(pydot.Edge(nodes[ind],nodes[p.father]))
tree_graph.write_png("knock_44.png")
# In[152]:
def knock_44(Sent):
tree_graph=pydot.Dot(graph_type='digraph',fontname="Microsoft YaHei")
nodes=[]
for ind, p in enumerate(Sent.phrases):
nodes.append(pydot.Node(p.str,fontname="Microsoft YaHei"))
tree_graph.add_node(nodes[ind])
for ind, p in enumerate(Sent.phrases):
if p.father!=-1:
tree_graph.add_edge(pydot.Edge(nodes[ind],nodes[p.father]))
tree_graph.write_png("knock_44.png")
# In[152]:
def knock_44(Sent):
tree_graph=pydot.Dot(graph_type='digraph',fontname="Microsoft YaHei")
nodes=[]
for ind, p in enumerate(Sent.phrases):
nodes.append(pydot.Node(p.str,fontname="Microsoft YaHei"))
tree_graph.add_node(nodes[ind])
for ind, p in enumerate(Sent.phrases):
if p.father!=-1:
tree_graph.add_edge(pydot.Edge(nodes[ind],nodes[p.father]))
tree_graph.write_png("knock_44.png")
# In[152]:
def knock_44(Sent):
tree_graph=pydot.Dot(graph_type='digraph',fontname="Microsoft YaHei")
nodes=[]
for ind, p in enumerate(Sent.phrases):
nodes.append(pydot.Node(p.str,fontname="Microsoft YaHei"))
tree_graph.add_node(nodes[ind])
for ind, p in enumerate(Sent.phrases):
if p.father!=-1:
tree_graph.add_edge(pydot.Edge(nodes[ind],nodes[p.father]))
tree_graph.write_png("knock_44.png")
# In[152]: