本文整理汇总了Python中pydot.graph_from_dot_file函数的典型用法代码示例。如果您正苦于以下问题:Python graph_from_dot_file函数的具体用法?Python graph_from_dot_file怎么用?Python graph_from_dot_file使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了graph_from_dot_file函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: execute
def execute(path, grammar_file_name, example_file_name, export_dot, export_png):
"""U svrhe brzeg testiranja, metoda koja prima putanju do foldera, naziv fajla gde je gramatika i naziv fajla gde je
primer programa u nasem jeziku i indikator da li da se eksportuju .dot i .png fajlovi"""
meta_path = os.path.join(SRC_DIR, 'model', grammar_file_name)
meta_name = os.path.splitext(meta_path)[0]
metamodel = metamodel_from_file(meta_path)
if export_dot:
metamodel_export(metamodel, meta_name + '.dot')
if export_png:
graph = pydot.graph_from_dot_file(meta_name + '.dot')
graph.write_png(meta_name + '.png')
model_path = os.path.join(path, example_file_name)
model_name = os.path.splitext(model_path)[0]
model = metamodel.model_from_file(model_path)
if export_dot:
model_export(model, model_name + '.dot')
if export_png:
graph = pydot.graph_from_dot_file(model_name + '.dot')
graph.write_png(model_name + '.png')
return model
示例2: makeGraph
def makeGraph(n, nNodes, connections, messages, label):
filename = "out%d"%n
file = open("%s.dot"%filename, "w")
file.write("digraph G {\nlayout=\"neato\"\n")
file.write("graph [dpi = 300];")
radius = nNodes*0.2
for i in range(1, nNodes+1):
angle = 2*math.pi*i/nNodes
x = radius*math.cos(angle)
y = radius*math.sin(angle)
file.write(" %d[pos=\"%f,%f!\",shape=circle];\n"%(i-1, x, y))
for i in range(len(connections)):
for j in connections[i]:
if j not in messages[i]: file.write("%d->%d\n"%(i, j))
for j in messages[i]:
file.write("%d->%d[color=\"red\"];\n"%(i, j))
file.write("labelloc=\"t\";\n")
file.write("label=\"%s\";\n"%label)
file.write("}\n")
file.close()
(graph,) = pydot.graph_from_dot_file("%s.dot"%filename)
graph.write_png('%s.png'%filename)
示例3: open_file
def open_file(self):
"""Abre el fichero .csv o .dot indicado en el primer argumento del
terminal.
Formato del fichero CSV: el número de línea-1 marca el número de nodo
Separados por comas los nodos destino"""
try:
fileR = open(sys.argv[1], "r")
except IOError:
print("Imposible abrir fichero")
except:
print("Introduce nombre de fichero")
else:
#Se ha seleccionado un fichero CSV
if re.match(".*(\.csv)$", sys.argv[1]):
fileC = csv.reader(fileR, delimiter=',')
filecsv = [n for n in fileC]
self.create_nodes(filecsv)
#Se ha seleccionado un fichero DOT
elif re.match(".*(\.dot)$", sys.argv[1]):
filedot = [[] for n in range(0, 15)]
graph = pydot.graph_from_dot_file(sys.argv[1])
res = graph.get_edges()
for n in res:
filedot[int(n.get_source())].append(int(n.get_destination()))
self.create_nodes(filedot)
else:
print('Extensión de fichero no válida')
示例4: max_tree
def max_tree(max_depth=None, out_file=None):
"""
Creates decision tree of max_depth. If max_depth is None the tree's depth won't be bounded.
If out_file is specificed, function will make a dot file and png of generated tree
prints training and testing error to stdout
"""
data = np.loadtxt("fourier/energy.txt", delimiter=",")
X = []
y = []
for row in data:
y.append(int(row[1]))
X.append(map(int, row[2:]))
X_train, X_test, y_train, y_test = cross_validation.train_test_split(X, y, test_size=0.4, random_state=0)
print X_train
clf = tree.DecisionTreeClassifier(max_depth=max_depth)
clf = clf.fit(X_train, y_train)
print "trained tree of depth %s" % (max_depth)
print "training error: %f" % (1 - clf.score(X_train, y_train))
print "testing error: %f" % (1 - clf.score(X_test, y_test))
if out_file:
with open(out_file + ".dot", "w") as f:
f = tree.export_graphviz(clf, out_file=f)
graph = pydot.graph_from_dot_file(out_file + ".dot")
graph.write_png(out_file + ".png")
示例5: visualize_mdp
def visualize_mdp(mdp, filename):
log.info('in the visualize_mdp function')
import pydot
import networkx as nx
from networkx.drawing.nx_agraph import write_dot
G=nx.DiGraph()
for s in mdp['states']:
for a in s['actions']:
for t in a['transitions']:
ecolor='red' if a['id'] else 'green'
elabel='p={}, r={}'.format(t['probability'], t['reward'])
G.add_edge(s['id'], t['to'],
color=ecolor,
label=elabel)
log.info('writing dot file')
write_dot(G, filename.replace('.json', '.dot'))
g = pydot.graph_from_dot_file(filename.replace('.json', '.dot'))[0]
log.info('writing png from dot file')
g.write_png(filename.replace('.json', '.png'))
log.info('removing intermediate dot file')
os.remove(filename.replace('.json', '.dot'))
return filename.replace('.json', '.png')
示例6: max_tree
def max_tree(X, y, max_depth = None, out_file = None):
"""
Creates decision tree of max_depth. If max_depth is None the tree's depth won't be bounded.
If out_file is specificed, function will make a dot file and png of generated tree
prints training and testing error to stdout
"""
X_train, X_test, y_train, y_test = cross_validation.train_test_split(X, y, test_size=.4, random_state=0)
clf = tree.DecisionTreeClassifier(max_depth=max_depth)
clf = clf.fit(X_train, y_train)
print "trained tree of depth %s" % (max_depth)
print "training error: %f" % (1-clf.score(X_train, y_train))
print "testing error: %f" % (1-clf.score(X_test, y_test))
out_file = None
if out_file:
with open(out_file+".dot", 'w') as f:
f = tree.export_graphviz(clf, out_file=f)
graph = pydot.graph_from_dot_file(out_file+".dot")
graph.write_png(out_file+'.png')
示例7: _render_with_pydot
def _render_with_pydot(self, filename, encoding):
c = pydot.graph_from_dot_file(filename, encoding=encoding)
sha = ''
for g in c:
jpe_data = g.create(format='jpe')
sha += sha256(jpe_data).hexdigest()
return sha
示例8: OnPopupItemGraph
def OnPopupItemGraph(self, event):
for row in self.ReportGrid.GetSelectedRows():
label = self.ReportGrid.GetCellValue(row,0)
id = self.ReportGrid.GetCellValue(row,1)
### plot the graph
### TODO link with properties frame
for fct in ('extTransition','intTransition', 'outputFnc', 'timeAdvance'):
filename = "%s(%s)_%s.dot"%(label,str(id),fct)
path = os.path.join(tempfile.gettempdir(), filename)
### if path exist
if os.path.exists(path):
graph = pydot.graph_from_dot_file(path)
filename_png = os.path.join(tempfile.gettempdir(),"%s(%s)_%s.png"%(label,str(id),fct))
graph.write_png(filename_png, prog='dot')
pylab.figure()
img = pylab.imread(filename_png)
pylab.imshow(img)
fig = pylab.gcf()
fig.canvas.set_window_title(filename)
pylab.axis('off')
pylab.show()
示例9: draw
def draw(self):
g = nx.MultiDiGraph()
lr_content = {}
for k,v in self.progress_present.iteritems():
label = 'I %d\n'%k
count = 0
for rule in v:
break
label += rule[0] + ' --> '
for r in rule[1]:
if r == u'dot':
label += '^ '
else:
label += r + ' '
label += '\n'
lr_content[k] = label
for k,v in self.state_present.iteritems():
for edge, to in v.iteritems():
g.add_edge(lr_content[k], lr_content[to], label = edge)
name = 'goto'
nx.write_dot(g, name + '.dot')
g = pydot.graph_from_dot_file(name+'.dot')
g.write_jpg(name+'.jpg')
示例10: processFile
def processFile(filename, dictionary=None, debug=0):
"""
parse a file, solve the model, return the results
This is a useful function in its own right, as well as an example
of how to use the MarkovAvail class and make sense of the results.
Args:
filename (string): name of dot format input file
dictionary (string): name of transition rates file
space/tab separated <name,value> pairs, w/comments
debug (int): level of desired debug output
0: none
1: parsed and interpreted parameters
2: painful for code (not model) debugging
Returns:
MarkovAvail: parameters and solutions
list: sorted (state #, occupancy) tupples
"""
# process the input file
g = pydot.graph_from_dot_file(filename)
# process the dictionary
valueDict = {}
if dictionary is not None:
if debug > 1:
print("Using value dictionary: %s" % (dictionary))
with open(dictionary) as f:
for line in f:
# skip comment lines
if line.startswith('#') or line.startswith('/'):
continue
# a value line needs at least two fields
parts = line.split()
if len(parts) >= 2:
key = parts[0]
value = parts[1]
valueDict[key] = value
if debug > 1:
print(" dictionary[%s]:\t%s" % (key, value))
# process the model
m = MarkovAvail(g, valueDict, debug)
# solve the model and print the results
m.solve()
# create a list of states, sorted by decreasing occupancy
stateOccupancies = {}
for i in range(m.numstates):
o = m.occupancy[i]
stateOccupancies[i] = o
sortedStates = sorted(stateOccupancies.iteritems(),
key=operator.itemgetter(1),
reverse=True)
# return the solution and the sorted state/occupancy list
return (m, sortedStates)
示例11: write_image_of_decision_tree
def write_image_of_decision_tree(filename, decision_tree, columns):
"""Create an image visualising a decision tree."""
dot_filename = str(filename) + '.dot'
dotfile = open(dot_filename, 'w')
tree.export_graphviz(decision_tree, out_file = dotfile, feature_names = columns)
dotfile.close()
graph = pydot.graph_from_dot_file(dot_filename)
graph.write_png(str(filename) + '.png')
示例12: make_graph
def make_graph(sciid,outfmt='pdf'):
gc = graph_from_dot_file(TMP+'{}.dot'.format(sciid))
gc.set_overlap(0)
if 'png' in outfmt:
gc.write_png('{}.png'.format(sciid), prog='dot')
if 'pdf' in outfmt:
gc.write_pdf('{}.pdf'.format(sciid), prog='dot') #fdp, dot,
示例13: draw
def draw(self):
g = nx.MultiDiGraph()
for id,path in self.s_DFA.iteritems():
for label, to_id in path.iteritems():
g.add_edge(id,to_id,label=label)
name = 'dfa'
nx.write_dot(g, name + '.dot')
g = pydot.graph_from_dot_file(name+'.dot')
g.write_jpg(name+'.jpg')
示例14: main
def main(infilename):
"""
Get all graph info, and then search for cycle, sources and sinks
"""
graph = pydot.graph_from_dot_file(infilename)
nodes = get_nodes_info(graph)
load_links(graph, nodes)
propagate_lineage(nodes)
dump_status(nodes)
示例15: write_svg
def write_svg(self):
"""
Create SVG out of the dotfile
@dotfile: In-dotfile
"""
self._write_stop()
graph = pydot.graph_from_dot_file(self.dotfile)
svg = graph.write_svg(os.path.join(self.resdir, "map.svg"))