• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python pydot.graph_from_dot_file函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了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函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
开发者ID:ftn-tim2,项目名称:jsd-project,代码行数:26,代码来源:execute.py


示例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)
开发者ID:wyh136,项目名称:iotex-core,代码行数:28,代码来源:plot.py


示例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')
开发者ID:mjota,项目名称:Dijkstra-Scholten,代码行数:28,代码来源:main.py


示例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")
开发者ID:kmax12,项目名称:867-final-project,代码行数:34,代码来源:decision_tree.py


示例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')
开发者ID:rding0731,项目名称:rding.github.io,代码行数:28,代码来源:hw3_tester.py


示例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')
开发者ID:kmax12,项目名称:867-final-project,代码行数:26,代码来源:decision_tree.py


示例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
开发者ID:yosh7of9,项目名称:pydot,代码行数:7,代码来源:pydot_unittest.py


示例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()
开发者ID:capocchi,项目名称:DEVSimPy-plugin-activity-tracking,代码行数:27,代码来源:activity-tracking.py


示例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')
开发者ID:a367,项目名称:Lexcial,代码行数:25,代码来源:LR.py


示例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)
开发者ID:markkampe,项目名称:MarkovAvailability,代码行数:59,代码来源:MarkovAvail.py


示例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')
开发者ID:danacton,项目名称:datascience,代码行数:9,代码来源:titanic-survivors.py


示例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,
开发者ID:Aurametrix,项目名称:Alg,代码行数:9,代码来源:sci_genealogy.py


示例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')
开发者ID:a367,项目名称:Lexcial,代码行数:9,代码来源:NFAtoDFA.py


示例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)
开发者ID:ze42,项目名称:salt-state-graph,代码行数:9,代码来源:salt-state-check-graph.py


示例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"))
开发者ID:Aki92,项目名称:thug,代码行数:10,代码来源:Mapper.py


示例16: process_graphs

    def process_graphs(self, file_names, squash_versions=False, analyze=False):
    
        graphs = []
        for x in file_names:
            xg = pydot.graph_from_dot_file(x)
            graphs.append(xg)
        
        final_graph = graphs[0]

        if len(graphs) > 1:

            if squash_versions:
                for g in graphs:
                    GraphProcessor.do_squash_versions(g)
        
            final_graph = GraphProcessor.merge_graphs(graphs)    

            # we're a little broken here, because the version squashing 
            # plus merging does some implicit analysis of version conflicts
            if analyze:

                per_graph_node_sets, intersection = GraphProcessor.intersecting_nodes(graphs)

                style=NodeStyleRule.globalRule({'fillcolor': GraphProcessor.DEFAULT_COLORS['intersect'], 'style':'filled'}) 

                for x in intersection:        
                    style.apply_node(final_graph, x)

                non_intersect = GraphProcessor.non_intersecting_nodes_per_graph(graphs, per_graph_node_sets)

                for x in non_intersect:

                    color = GraphProcessor.DEFAULT_COLORS['non_intersect_list'].pop(0)
                    style = NodeStyleRule.globalRule({'fillcolor':color, 'style':'filled'})

                    for y in non_intersect[x]:
                        style.apply_node(final_graph, y)


        if squash_versions:
            # necessary because we wedged a non-standard
            # attribute into the nodes marking their versions
            for n in final_graph.get_nodes():
                SquashVersionRule.clean_version_tag(n)

        for rule in self.style_rules:
            for e in final_graph.get_edges():
                rule.apply(final_graph, e)

        # otherwise it's unreadable
        final_graph.set('rankdir', 'LR')

        return final_graph
开发者ID:willgage,项目名称:graph-scripts,代码行数:53,代码来源:mvndepgraph.py


示例17: gf_dependencies

def gf_dependencies(path, unlink=True):
	from subprocess import Popen, PIPE
	from tempfile import TemporaryFile
	import os 
	dotFile = "_gfdepgraph.dot"
	with TemporaryFile() as f:
		f.write('dg\n')
		f.seek(0)
		p = Popen(('gf', '-s', '-retain', path), stdin=f, stdout=PIPE)
	p.wait()
	dot = pydot.graph_from_dot_file(dotFile)
	if unlink: os.unlink(dotFile)
	return dot
开发者ID:saludes,项目名称:sublime-GF,代码行数:13,代码来源:dependencies.py


示例18: main

def main(args):
    if args.output.endswith('tsv'):
        if not args.perform_closure:
            graph = pydot.graph_from_dot_file(args.input)
            edges = graph.get_edges()
            with open(args.output, "wb") as f:
                for edge in edges:
                    src = edge.get_source()
                    dest = edge.get_destination()
                    edge_type = edge.get('type') # edge.type
                    f.write('%s %s %s\n'%(src, dest, edge_type))
            return

    raise NotImplementedError
开发者ID:se4u,项目名称:grafl_public,代码行数:14,代码来源:util_make_toy_graph.py


示例19: _render_with_pydot

    def _render_with_pydot(self, filename):
        #f = open(filename, 'rt')
        #graph_data = f.read()
        #f.close()

        #g = pydot.parse_from_dot_data(graph_data)
        g = pydot.graph_from_dot_file(filename)

        if not isinstance(g, list):
            g = [g]

        jpe_data = NULL_SEP.join([_g.create(format='jpe') for _g in g])

        return sha256(jpe_data).hexdigest()
开发者ID:krzysbaranski,项目名称:pydot,代码行数:14,代码来源:pydot_unittest.py


示例20: build_nodes_tree_from_amr_dot_file

def build_nodes_tree_from_amr_dot_file(amr_dot_file_path):
    # extract interactions and complex formations (including complex disintegration) from the dot file format for an amr
    amr = pd.graph_from_dot_file(cap.absolute_path + amr_dot_file_path)
    sentence = amr.get_label()
    sentence = sentence.replace("\ ", "")
    nodes = {}
    # iterate over all edges to build a tree of nodes
    edges = amr.get_edge_list()
    # print 'edges: ', edges
    for edge in edges:
        # print 'edge', edge
        # print 'edge: ', edge
        source = edge.get_source()
        # print 'source: ', source
        destination = edge.get_destination()
        # print 'destination: ', destination
        edge_label = edge.get_label()
        edge_label = constants.no_quotes_regexp.sub("", edge_label)
        # print 'edge_label: ', edge_label
        edge = None
        # source not in the nodes_list
        if not nodes.has_key(source):
            source_node = amr.get_node(source)[0]
            nodes[source] = Node(source, source_node.get_label())
            source_node = None
        if not nodes.has_key(destination):
            destination_node = amr.get_node(destination)[0]
            nodes[destination] = Node(destination, destination_node.get_label())
            destination_node = None
        if edge_label == "TOP":
            if source != destination:
                raise AssertionError
            nodes[constants.root] = nodes[source]  # source and destination are same for TOP edge
            nodes[constants.root].is_root = True
        else:
            # linking destination as child of source, there can be multiple children with a given edge_label
            if edge_label not in nodes[source].children:
                nodes[source].children[edge_label] = [nodes[destination]]
            else:
                if nodes[destination] not in nodes[source].children[edge_label]:
                    nodes[source].children[edge_label].append(nodes[destination])
            # linking source as parent of destination, there can be multiple parents with same edge_label (eg: a protein can be a catalyst for multiple interactions)
            if edge_label not in nodes[destination].parents:  # if list is empty
                nodes[destination].parents[edge_label] = [nodes[source]]
            else:
                if nodes[source] not in nodes[destination].parents[edge_label]:
                    nodes[destination].parents[edge_label].append(nodes[source])
        # print 'nodes: ', nodes
        # amr.write_pdf(cap.absolute_path+amr_dot_file_path+'.pdf')
    return nodes, sentence
开发者ID:sgarg87,项目名称:big_mech_isi_gg,代码行数:50,代码来源:read_dot_file.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python pydot.graph_from_edges函数代码示例发布时间:2022-05-25
下一篇:
Python pydot.graph_from_dot_data函数代码示例发布时间:2022-05-25
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap