コード例 #1
0
def make_plots(srcdir, outdir, include_subdir=False, level=3):
    """
    Create plots of module dependencies.

    """
    srcfiles = get_ordered_srcfiles(srcdir, include_subdir)
    nodelist = get_f_nodelist(srcfiles)
    for n in nodelist:
        print(os.path.basename(n.name))
        for m in n.dependencies:
            print('  ' + os.path.basename(m.name))
        print('')

    if not os.path.isdir(outdir):
        raise Exception('output directory does not exist')

    for n in nodelist:
        filename = os.path.join(outdir, os.path.basename(n.name) + '.png')
        print('Creating ' + filename)
        graph = pydot.Dot(graph_type='digraph')
        node_dict = {}
        ilev = 0
        add_pydot_nodes(graph, node_dict, n, ilev, level)
        edge_set = set()
        ilev = 1
        add_pydot_edges(graph, node_dict, edge_set, n, ilev, level)
        graph.write_png(filename)

    return
コード例 #2
0
def DrawPNG(root, out_file):
    try:
        from pydotplus import graphviz
    except ImportError:
        print("module pydotplus.graphviz not found")

    g = graphviz.Dot()  # generation of new dot

    TreeToGraph(0, g, root)
    g2 = graphviz.graph_from_dot_data(g.to_string())

    g2.write_png(out_file)
コード例 #3
0
def DrawPNG(root, out_file):
    '''
    @param root: 根节点
    @param out_file: 
    '''
    # generation of new dot
    g = graphviz.Dot()

    TreeToGraph(0, g, root)
    g2 = graphviz.graph_from_dot_data(g.to_string())

    g2.write_png(out_file)
コード例 #4
0
def DrawPNG(root, out_file):
    '''visualization of decision tree from root
	@param root: the root node
	@param out_file: str,name and path of output file'''
    try:
        from pydotplus import graphviz
    except ImportError:
        print("module pydotplus.graphviz not found")

    g = graphviz.Dot()  #generation of new dot
    TreeToGraph(0, g, root)
    g2 = graphviz.graph_from_dot_data(g.to_string())
    g2.write_png(out_file)
コード例 #5
0
ファイル: ID3.py プロジェクト: Amorness/Pytorch
def DrawPNG(root, out_file):
    '''
    visualization of decision tree from root.
    @param root: Node, the root node for tree.
    @param out_file: str, name and path of output file
    '''

    from pydotplus import graphviz

    g = graphviz.Dot()  # generation of new dot

    TreeToGraph(0, g, root)
    g2 = graphviz.graph_from_dot_data(g.to_string())

    g2.write_png(out_file)
コード例 #6
0
ファイル: visualize.py プロジェクト: Hofer-Julian/pymake
def to_pydot(dag, filename='mygraph.png'):
    # Create the graph
    graph = pydot.Dot(graph_type='digraph')

    # Add the nodes
    node_dict = {}
    for n in dag.nodelist:
        pydotnode = pydot.Node(n.name, style="filled", fillcolor="red")
        node_dict[n] = pydotnode
        graph.add_node(pydotnode)

    # Add the edges
    for n in dag.nodelist:
        for m in n.dependencies:
            graph.add_edge(pydot.Edge(node_dict[n], node_dict[m]))

    graph.write_png(filename)
    return
コード例 #7
0
def draw_tree(root, out_file):
    '''
    visualization of decision tree.
    Inputs:
            root: Node, the root node for tree.
            out_file: str, file path
    '''
    try:
        from pydotplus import graphviz
    except ImportError:
        print("module pydotplus.graphviz not found")

    g = graphviz.Dot()  # generation of new dot

    tree2graph(0, g, root)
    g2 = graphviz.graph_from_dot_data(g.to_string())

    g2.write_png(out_file)
コード例 #8
0
def to_pydot(dag, filename="mygraph.png"):
    """Create a png file of a Directed Acyclic Graph

    Parameters
    ----------
    dag : object
        directed acyclic graph
    filename : str
        path of the graph png

    Returns
    -------

    """
    # evaluate if pydot plus is installed
    if pydot is None:
        msg = "pydotplus must be installed to use " + "{}".format(
            make_plots.__module__ + "." + make_plots.__name__)
        raise ModuleNotFoundError(msg)

    # Create the graph
    graph = pydot.Dot(graph_type="digraph")

    # Add the nodes
    node_dict = {}
    for n in dag.nodelist:
        pydotnode = pydot.Node(n.name, style="filled", fillcolor="red")
        node_dict[n] = pydotnode
        graph.add_node(pydotnode)

    # Add the edges
    for n in dag.nodelist:
        for m in n.dependencies:
            graph.add_edge(pydot.Edge(node_dict[n], node_dict[m]))

    graph.write_png(filename)
    return
コード例 #9
0
with open('D:\\Desktop\西瓜数据集3.0.csv') as data_file:
    df = pd.read_csv(data_file)
    print(df)

train_index = [0, 1, 2, 5, 6, 9, 13, 14, 15, 16]
test_index = [3, 4, 7, 8, 10, 11, 12]
df_train = df.loc[train_index, :].reset_index(drop=True)
df_test = df.loc[test_index, :].reset_index(drop=True)
print(df_test)
# Tree = Preprune(df_train, df_test)
Tree = TreeGenerate(df_train)
Tree = postpurn(Tree, df_test)
node_plies = node_plie({}, 0, Tree)

from pydotplus import graphviz
g = graphviz.Dot()  # 创建一个Dot图对象
TreeToGraph(0, Tree, g)
g2 = graphviz.graph_from_dot_data(g.to_string())  # 将Dot对象输出为字符串g.to_string()
# 并通过graphviz解码
g2.write_png('D:\\Desktop\postpurn_test.png')

# 第二种可视化实现方式(测试成功)
'''
def TreeToGraph(i, father_node, dot):
    """
    给定起始节点的名字i(用数字记录节点名)、节点、和 标签名字
    用i+1,和子节点及标签名作为递归输入
    返回的是i和子节点的名称
    将所有的节点遍历完成后返回
    :param i: 为了避免迭代时子节点重新从零开始计,这里传入参数i用来累加迭代
    :param node:根节点
コード例 #10
0
ファイル: graph-to-full.py プロジェクト: mricon/wotmate
    cmdargs = ap.parse_args()

    logger = wotmate.get_logger(cmdargs.quiet)

    dbconn = sqlite3.connect(cmdargs.dbfile)
    cursor = dbconn.cursor()

    if len(cmdargs.key_id) != 1:
        logger.critical('Please provide a single key id for path tracing')
        sys.exit(1)

    to_rowid = wotmate.get_pubrow_id(cursor, cmdargs.key_id[0])
    if to_rowid is None:
        sys.exit(1)

    key_paths = get_key_paths(cursor, to_rowid, cmdargs.maxdepth)

    graph = pd.Dot(graph_type='digraph', )
    graph.set_node_defaults(
        fontname=cmdargs.font,
        fontsize=cmdargs.fontsize,
    )

    wotmate.draw_key_paths(cursor, key_paths, graph, cmdargs.show_trust)

    chunks = cmdargs.out.split('.')
    outformat = chunks[-1]
    graph.write(cmdargs.out, format=outformat)
    logger.info('Wrote %s' % cmdargs.out)
コード例 #11
0
def make_plots(
    srcdir,
    outdir,
    include_subdir=False,
    level=3,
    extension=".png",
    verbose=False,
):
    """Create plots of module dependencies.

    Parameters
    ----------
    srcdir : str
        path for source files
    outdir : str
        path for output images
    include_subdir : bool
        boolean indicating is subdirectories in the source file directory
        should be included
    level : int
        dependency level (1 is the minimum)
    extension : str
        output extension (default is .png)
    verbose : bool
        boolean indicating if output will be printed to the terminal

    Returns
    -------

    """
    # evaluate if pydot plus is installed
    if pydot is None:
        msg = "pydotplus must be installed to use " + "{}".format(
            make_plots.__module__ + "." + make_plots.__name__)
        raise ModuleNotFoundError(msg)

    srcfiles = _get_ordered_srcfiles(_get_srcfiles(srcdir, include_subdir))
    nodelist = _get_f_nodelist(srcfiles)
    for idx, n in enumerate(nodelist):
        if verbose:
            print("{:<3d}: {}".format(idx + 1, os.path.basename(n.name)))
            for jdx, m in enumerate(n.dependencies):
                msg = "     {:<3d}: {}".format(jdx + 1,
                                               os.path.basename(m.name))
                print(msg)

    if not os.path.isdir(outdir):
        raise Exception("output directory does not exist")

    for n in nodelist:
        filename = os.path.join(outdir, os.path.basename(n.name) + extension)
        if verbose:
            print("Creating " + filename)
        graph = pydot.Dot(graph_type="digraph")
        node_dict = {}
        ilev = 0
        _add_pydot_nodes(graph, node_dict, n, ilev, level)
        edge_set = set()
        ilev = 1
        _add_pydot_edges(graph, node_dict, edge_set, n, ilev, level)
        if extension == ".png":
            graph.write_png(filename)
        elif extension == ".pdf":
            graph.write_pdf(filename)
        elif extension == ".dot":
            graph.write_dot(filename)
        else:
            raise Exception("unknown file extension: {}".format(extension))

    return
コード例 #12
0
 def graph(self, label_title=None):
     g = graphviz.Dot()
     self.__seq = 0
     self.__fill_graph(self.__root, None, "", g, label_title)
     return g.to_string()
コード例 #13
0
def draw_graph(args):
    logger.setLevel(logging.DEBUG)

    ch = logging.StreamHandler()
    formatter = logging.Formatter('%(message)s')
    ch.setFormatter(formatter)
    if args.verbose:
        ch.setLevel(logging.DEBUG)
    else:
        ch.setLevel(logging.CRITICAL)

    logger.addHandler(ch)

    with open(args.topology, 'r') as topofh:
        topology = yaml.load(topofh)
        topofh.close()

    graph = pd.Dot(graph_type='digraph', )
    graph.set('rankdir', 'LR')
    graph.set('ranksep', args.ranksep)
    graph.set_node_defaults(fontname=args.font, fontsize=args.fontsize)

    if 'subnets' in topology:
        for subnet_title, params in topology['subnets'].items():
            if 'trimdomain' not in params:
                params['trimdomain'] = ''
            subnets[subnet_title] = Subnet(subnet_title, params['cidr'],
                                           params['color'],
                                           params['trimdomain'])

    if 'clusters' in topology:
        for cluster_title, cluster_ips in topology['clusters'].items():
            rips = []
            vips = []
            if 'ips' in cluster_ips:
                rips = cluster_ips['ips']
            if 'vips' in cluster_ips:
                vips = cluster_ips['vips']
            clusters[cluster_title] = Cluster(cluster_title, rips, vips)

    load_proxies_from_yaml(topology['proxies'])

    if len(args.nmap_xml):
        for nmap_xml in args.nmap_xml:
            load_nodes_from_nmap_xml(nmap_xml)

    limit_subnets = []
    if len(args.limit_ext):
        for sublimit in args.limit_ext:
            limit_subnets.append(IPNetwork(sublimit))

    for ip, node in nodes.items():
        if node.is_src_node:
            found = False
            for sublimit in limit_subnets:
                if node.ip in sublimit:
                    found = True
                    break
            if len(limit_subnets) and not found:
                continue
            node.draw(graph, args.resolve_dns)

    # Add clusters to the graph
    for title, cluster in clusters.items():
        cluster.subgraph.set('fontname', args.font)
        cluster.subgraph.set('fontsize', args.fontsize)
        graph.add_subgraph(cluster.subgraph)

    # Guess format from the extension
    chunks = args.out.split('.')
    outformat = chunks[-1]

    graph.write(args.out, format=outformat)
コード例 #14
0
ファイル: CART.py プロジェクト: xthzhjwzyc/ML_ZhouZhiHua
def DrawPng(root, out_file):
    g = graphviz.Dot()
    TreeToGraph(root, 0, g)
    g.write("../data/tree.dot")