コード例 #1
0
def make_graph_dijkstra():
    g = Graph(format='png', comment='undirected graph that contains no negative weight path')
    g.attr('node', shape='circle')

    n = 10
    for i in range(n):
        g.node(str(i), label=str(i))

    edges = ((0, 1),
             (2, 0),
             (2, 3),
             (1, 4),
             (4, 5),
             (5, 2),
             (3, 6),
             (4, 7),
             (5, 8),
             (8, 9))

    edge_labels = [5, 6, 2, 2, 3, 4, 1, 7, 1, 1, 1]

    for i, e in enumerate(edges):
        g.edge(str(e[0]), str(e[1]), label=str(edge_labels[i]))

    g.render('graph_dijkstra', view=True, cleanup=True)    
コード例 #2
0
def make_bipartite_graph():
    g = Graph(format='png', comment='undirected graph that contains no negative weight path', engine='dot')
    g.attr('node', shape='circle')

    n = 10
    with g.subgraph(name='cluster_0') as c:
        c.attr(label='process #1')
        for i in range(0, n, 2):
            c.node(str(i), label=str(i), color='blue')

    with g.subgraph(name='cluster_1') as c:
        c.attr(label='process #2')
        for i in range(1, n, 2):
            c.node(str(i), label=str(i), color='red')
    
    edges = ((0, 1),
             (1, 2), (1, 4),
             (2, 9),
             (3, 4),
             (4, 5), (4, 9),
             (5, 6),
             (6, 7), (6, 9),
             (8, 9))
    
    for e in edges:
        g.edge(str(e[0]), str(e[1]))

    g.render('graph_bipartite', view=True, cleanup=True)
コード例 #3
0
 def printLinked(self):
     dl = Graph('doublylinked', node_attr={'shape': 'record'})
     if self.isEmpyty():
         pass
     else:
         self._draw(self.sentinel.next, dl)
     dl.render('doublylinked.gv', view=True)
コード例 #4
0
ファイル: main.py プロジェクト: khoihd/PlotTopology
def generate_plot(topology_file):
    graph = Graph("topology", filename='topology.gv', engine='neato')
    # graph = Graph("topology", filename='topology.gv', engine='neato', outputorder = 'breadthfirst')
    delay_re = "[0-9]+.0ms"
    server_id = ""
    # Add color to server node
    # Add color to client node
    with open(topology_file) as f:
        for line in f.readlines():
            if "large" in line:
                line = line.replace("tb-set-hardware $node", "")
                server_id = line[0]
            if line.startswith("set linkClient"):
                line = line.replace("set linkClient", "")
                node = server(line[0], server_id)
                client = "ClientPool-" + line[0]

                add_node(graph, node)
                add_node(graph, client)
                add_edge(graph, node, client, client_edge, str(1))
            elif line.startswith("set link"):
                line = line.replace("set link", "")
                node_one = server(line[0], server_id)
                node_two = server(line[1], server_id)

                add_node(graph, node_one)
                add_node(graph, node_two)

                label = re.findall(delay_re, line)[0]
                add_edge(graph, node_one, node_two, node_edge, label)
    print(graph.source)
    graph.save()
    graph.render('topology')

    return graph
コード例 #5
0
def make_graph_mst():
    g = Graph(format='png', comment='undirected graph that contains no negative weight path')
    g.attr('node', shape='circle')

    n = 9
    for i in range(n):
        g.node(str(i), label=str(i))

    edges = ((0, 1),
             (0, 7),
             (1, 2),
             (1, 7),
             (2, 3),
             (2, 5),
             (2, 8),
             (3, 4),
             (3, 5),
             (4, 5),
             (5, 6),
             (6, 7),
             (6, 8),
             (7, 8))

    edge_labels = [4, 8, 8, 11, 7, 4, 2, 9, 14, 10, 2, 1, 6, 7]

    for i, e in enumerate(edges):
        g.edge(str(e[0]), str(e[1]), label=str(edge_labels[i]))

    g.render('graph_mst', view=True, cleanup=True)
コード例 #6
0
def reporte_optimizacion():
    global listaOpt, listaAsignaciones
    cadena = ""
    print("------------REPORTE OPTIMIZACION---------------")
    SymbolT2 = Graph('g', filename='reporteOptimizacion.gv', format='png',
                     node_attr={'shape': 'plaintext', 'height': '.1'})

    print("ASIGNACIONES -- ")
    for i in listaAsignaciones:
        print(str(i.izq)+" = "+str(i.der))


    for item in listaAsignaciones:
        for asi in listaAsignaciones:
            if str(item.der) == str(asi.izq) and str(item.izq) == str(asi.der):
                print("optimiza 1")
                op = str(item.der) + "=" + str(asi.der) + "-"
                op += str(item.izq) + "=" + str(asi.izq)
                opt = str(item.der) + "=" + str(asi.der) + "- Regla: 1"
                o = Optimizacion(op, opt)
                listaOpt.append(o)
                break;


    ope  = "goto .R" + "-"+ "Label .R"
    opet = "Label .R" + "- Regla: 2"
    regla2 = Optimizacion(ope, opet)

    listaOpt.append(regla2)

    for o in listaOpt:
        cadena += '\n <TR><TD>'+o.original+'</TD><TD>'+o.optimizado+'</TD></TR>'

    SymbolT2.node('table', '<<TABLE><TR><TD>CODIGO</TD><TD>OPTIMIZACION</TD></TR>' + cadena + '</TABLE>>')
    SymbolT2.render('g', format='png', view=True)
コード例 #7
0
def visual_decoding(sent, saveto='tmp'):
    """
    Visualize multiple translation from machine translation.

    Example:
    >>> sentence = ['I have a apple',
                    'I have a dream',
                    'H have an egg']
    >>> visual_decoding(sent=sentence, saveto='demo')

    Args:
        sent: a list of str
            Multiple translations.

        saveto: str
            Graph will be saved as 'saveto.png'.

    Returns:
        None

    """
    graph = Graph(format='png',
                  node_attr={'shape':'box'},
                  graph_attr={'splines':'polyline'},
                  edge_attr={'dir':'forward'})

    graph.body.extend(['rankdir=LR'])

    for i,s in enumerate(sent):
        graph = _plot_sent(graph, s, flag=str(i))

    graph.render(filename=saveto, view=True)
コード例 #8
0
ファイル: main.py プロジェクト: kyoumaaa/HIT-Database
def show(sql, filename):
    # 优化前的树
    g = Graph(filename, format='png', node_attr={'shape': 'plaintext'})
    etree = parsesql(sql)
    showtree(etree, g)
    g.render()
    img = Image.open(filename + '.gv.png')
    plt.figure('before optim')
    plt.imshow(img)
    plt.axis('off')

    # 优化后的树
    og = Graph(filename + 'optim',
               format='png',
               node_attr={'shape': 'plaintext'})
    # 两步优化
    relation2 = []
    otree = down_select(etree, '', relation2)
    otree = down_proj(otree, '', relation2, '')
    showtree(otree, og)
    og.render()
    img = Image.open(filename + 'optim' + '.gv.png')
    plt.figure('after optim')
    plt.imshow(img)
    plt.axis('off')
    plt.show()
コード例 #9
0
ファイル: __main__.py プロジェクト: kjnh10/pcm
def viz(config: Config, directed: bool, in_index_base: int, out_index_base: int):
    from graphviz import Digraph, Graph  # type: ignore

    firstline = input().split()
    G = None
    n, m = -1, -1
    if (len(firstline) == 1):
        # this is tree
        G = Graph()
        n = int(firstline[0])
        m = n - 1
    else:
        n, m = map(int, firstline)
        if directed:
            G = Digraph()
        else:
            G = Graph()

    for i in range(n):
        G.node(str(i))

    for i in range(m):
        u, v = map(int, input().split())
        if in_index_base == 1:
            u -= 1
            v -= 1
        G.edge(str(u), str(v), cost='1')

    output_filepath = os.path.expanduser('~/Dropbox/graph')
    G.render(output_filepath, view=True)
コード例 #10
0
def visual_decoding(sent, saveto='tmp'):
    """
    Visualize multiple translation from machine translation.

    Example:
    >>> sentence = ['I have a apple',
                    'I have a dream',
                    'H have an egg']
    >>> visual_decoding(sent=sentence, saveto='demo')

    Args:
        sent: a list of str
            Multiple translations.

        saveto: str
            Graph will be saved as 'saveto.png'.

    Returns:
        None

    """
    graph = Graph(format='png',
                  node_attr={'shape': 'box'},
                  graph_attr={'splines': 'polyline'},
                  edge_attr={'dir': 'forward'})

    graph.body.extend(['rankdir=LR'])

    for i, s in enumerate(sent):
        graph = _plot_sent(graph, s, flag=str(i))

    graph.render(filename=saveto, view=True)
コード例 #11
0
ファイル: interactions_graph.py プロジェクト: michal3141/sat
def create_interactions_graph(clauses, f):
    dot = GGraph(comment='Interactions graph', engine='sfdp')
    seen_vars = set()
    edges_between_vars = defaultdict(int)

    for clause in clauses:
        for lit in clause:
            var = f(lit)
            if var not in seen_vars:
                seen_vars.add(var)
                dot.node(str(var), label=str(var))
    for clause in clauses:
        l = len(clause)
        for i in xrange(l):
            for j in xrange(i+1, l):
                edges_between_vars[(str(f(clause[i])), str(f(clause[j])))] += 1

    for interacting_vars, weight in edges_between_vars.iteritems():
        dot.edge(interacting_vars[0], interacting_vars[1], weight=str(weight))

    print edges_between_vars

    dot = _apply_styles(dot, styles)
    # print dot.source
    dot.render(os.path.join('images', 'interactions_graph.gv'), view=True)   
コード例 #12
0
ファイル: analyze.py プロジェクト: michal3141/geomedia
def visualize_countries_together_in_item(data, start_time_str=None, end_time_str=None, newspaper_str='*'):
    countries_together_dict = _get_countries_together_in_items(data)
    # print 'countries_together_dict:', countries_together_dict
    dot = Graph(comment='Countries together in item graph', engine='sfdp')
    seen_countries = set()
    edges_between_countries = defaultdict(int)

    ## Building the graph
    for ID_and_feed, countries in countries_together_dict.iteritems():
        countries_list = list(countries)
        for country in countries_list:
            if country != '' and country not in seen_countries:
                dot.node(country, label=country)
                seen_countries.add(country)
        for i in xrange(len(countries)):
            for j in xrange(i+1, len(countries)):
                fst = min(countries_list[i], countries_list[j])
                snd = max(countries_list[i], countries_list[j])
                edges_between_countries[(fst, snd)] += 1

    for edge_endpoints, edge_weight in edges_between_countries.iteritems():
        dot.edge(edge_endpoints[0], edge_endpoints[1], weight=str(edge_weight))

    print 'seen_countries:', seen_countries
    print 'edges_between_countries:', edges_between_countries

    
    dot = _apply_styles(dot, styles)
    # print dot.source
    out_dirname = newspaper_str.replace('*', '').replace('!', '').replace('[', '').replace(']', '')
    out_filename = ('countries_together_in_item_%s_%s.gv' % (start_time_str, end_time_str)).replace(':', '-')
    dot.render(os.path.join('images', out_dirname, out_filename), view=False)
コード例 #13
0
ファイル: viz_util.py プロジェクト: xinkent/mdtools
def draw_pats_tree_colored(pkl, out, col_style='contact', **kwarg):
    with open(pkl, 'rb') as f:
        var_list = pickle.load(f)
        rootnode = var_list[0]
    if col_style == 'order':
        num_state = dfs(rootnode)
        print('num_state  ' + str(num_state))
        values = np.arange(num_state)
    elif col_style == 'rmsd':
        values = None
    elif col_style == 'contact':
        native = kwarg['native']
        traj = kwarg['traj']
        values = frac_native_contacts(native, traj)
    elif col_style == 'f1':
        native = kwarg['native']
        traj = kwarg['traj']
        values = calc_f1(native, traj)
    else:
        print('Error!: you can not use such color style ' + col_style)
        exit(1)
    if values is not None:
        make_colorbar(min(values), max(values), out + '_colorbar')
    else:
        make_colorbar(0, rootnode.childNodes[0].rmsd, out + '_colorbar')
    # G = Graph(format='pdf')
    G = Graph(format='svg')
    G.attr("node", shape="circle", style="filled")
    G.graph_attr.update(size="30")
    make_graph(G, rootnode, values)
    G.render(out)
コード例 #14
0
def render_graph(graph, name=None, directory=None, fill_infected='green3'):
    """ Render a user graph to an SVG file. Infected nodes are colored
    appropriately.

    Parameters:
    -----------
    graph : UserGraph
        The graph to render.

    name : str
        A name for the graph.

    directory : str
        The directory to render to.

    fill_infected : str
        The fill color for infected nodes.

    """
    dot = Graph(name=name, format='svg', strict=True)

    for user in graph.users():
        if user.metadata.get('infected', False):
            dot.attr('node', style='filled', fillcolor=fill_infected)

        dot.node(unicode(user.tag))
        dot.attr('node', style='')

    for user in graph.users():
        for neighbor in user.neighbors:
            dot.edge(unicode(user.tag), unicode(neighbor.tag))

    dot.render(directory=directory, cleanup=True)
コード例 #15
0
ファイル: viz_util.py プロジェクト: xinkent/mdtools
def draw_pacs_tree_colored(log_file, out):
    log = pd.read_csv(log_file, header=None)
    log = np.array(log)
    n_cycles = log.shape[0]
    # G = Graph(format='pdf')
    G = Graph(format='svg')
    G.attr('node', shape='circle', style='filled')
    G.graph_attr.update(size="30")
    color_hex = value2hex(0)
    G.node('0-0', '0', fillcolor=color_hex)
    # G.node('0-0', '', fillcolor=color_hex, color='white', width='12')
    color_hex = value2hex(255 / n_cycles * 1)
    for i in range(len(log[0])):
        state = '1-' + str(i)
        G.node(state, str(state), fillcolor=color_hex)
        # G.node(state, '', fillcolor=color_hex, color='white', width='12')
        G.edge('0-0', state, color='black')
    for i in range(1, len(log) + 1):
        log_i = log[i - 1]
        color_hex = value2hex(255 / n_cycles * (i + 1))
        for j, l in enumerate(log_i):
            state = str(i + 1) + '-' + str(j)
            pstate = str(i) + '-' + str(int(l))
            G.node(state, str(state), fillcolor=color_hex)
            # G.node(state, '', fillcolor=color_hex, color='white', width='12')
            G.edge(pstate, state, color='black')
    G.render(out)
    make_colorbar(0, n_cycles * 5, out + '_colorbar')
コード例 #16
0
def generate_graph(verbose: bool, file: str):
    docker_client = docker.from_env()

    networks = get_networks(docker_client, verbose)
    containers, links = get_containers(docker_client, verbose)

    if file:
        base, ext = os.path.splitext(file)
        g = Graph(comment="Docker Network Graph",
                  engine="sfdp",
                  format=ext[1:],
                  graph_attr=dict(splines="true"))
    else:
        g = Graph(comment="Docker Network Graph",
                  engine="sfdp",
                  graph_attr=dict(splines="true"))

    for _, network in networks.items():
        draw_network(g, network)

    for container in containers:
        draw_container(g, container)

    for link in links:
        if link.network_name != "none":
            draw_link(g, networks, link)

    if file:
        g.render(base)
    else:
        print(g.source)
コード例 #17
0
    def vis_family_tree(self):
        G = Graph(format="png")
        num_nodes = len(self.result['states'][0]['node'])
        num_relations = len(self.result['relations'])
        for i in range(num_nodes):
            if i % 2 == 0:
                G.node(str(i), str(i), shape='square')
            else:
                G.node(str(i), str(i), shape='circle')

        for i in range(num_relations):
            G.node(str(i + num_nodes),
                   '',
                   shape='diamond',
                   style='filled',
                   height='0.1',
                   width='0.1')

        for i, rel in enumerate(self.result['relations']):
            c, f, m = rel
            G.edge(str(i + num_nodes), str(c))
            G.edge(str(f), str(i + num_nodes))
            G.edge(str(m), str(i + num_nodes))

        G.render('family-tree')
コード例 #18
0
    def change_graph(self, cnt, indices, restore_flg=False):
        g = Graph(format='png')

        for nnm in self.rc_name:
            g.node(nnm)

        if restore_flg:
            indices = sorted(indices, reverse=True)
            self.graph_matrix[indices[0]][indices[1]] = 1
            print('Graph Matrix : ', self.graph_matrix)
            for i in range(self.graph_matrix.shape[0]):
                for j in range(self.graph_matrix.shape[1]):
                    if i > j and self.graph_matrix[i][j] == 1:
                        g.edge(self.rc_name[i], self.rc_name[j])
            file_name = './graph_restored_' + str(
                cnt)  # 保存する画像のファイル名を指定(拡張子(.png)を除く)
        else:
            indices = sorted(indices, reverse=True)
            self.graph_matrix[indices[0]][indices[1]] = 0
            print('Graph Matrix : ', self.graph_matrix)
            for i in range(self.graph_matrix.shape[0]):
                for j in range(self.graph_matrix.shape[1]):
                    if i > j and self.graph_matrix[i][j] == 1:
                        g.edge(self.rc_name[i], self.rc_name[j])
            file_name = './graph_' + str(cnt)  # 保存する画像のファイル名を指定(拡張子(.png)を除く)
        g.render(filename=file_name,
                 format='png',
                 cleanup=True,
                 directory=None)

        im = Image.open(file_name + '.png')
        im.show()
コード例 #19
0
 def plot(self, render=False, save=False, filename=None):
     if filename is None:
         filename = "decision_tree.svg"
     dot = Graph(name="decision_tree", filename=filename, format="svg")
     dot.node(
         str(id(self)),
         self.splitting_info_to_string()
         + "\nestimate:"
         + str(round(float(self.value), 3)),
     )
     for i in range(self.depth):
         nodes = DecisionTree.get_level_in_list(self, i + 1)
         for node in nodes:
             if node.left_child is None:
                 dot.node(
                     str(id(node)),
                     "This node is not split"
                     + "\nestimate:"
                     + str(round(float(node.value), 3)),
                 )
                 dot.edge(str(id(node.parent)), str(id(node)))
             else:
                 dot.node(
                     str(id(node)),
                     node.splitting_info_to_string()
                     + "\nestimate:"
                     + str(round(float(node.value), 3)),
                 )
                 dot.edge(str(id(node.parent)), str(id(node)))
     if render:
         dot.render(view=True)
     if save:
         dot.save()
     return dot
コード例 #20
0
ファイル: graph.py プロジェクト: perepinol/ia-prac2
    def visualize(self, name="graph"):
        """Visualize graph using 'graphviz' library.

        To install graphviz you can use 'pip install graphviz'.
        Notice that graphviz should also be installed in your system.
        For ubuntu, you can install it using 'sudo apt install graphviz'

        :param name: Name of the generated file, defaults to "graph"
        :type name: str, optional
        :raises ImportError: When unable to import graphviz.
        """
        try:
            from graphviz import Graph
        except ImportError:
            msg = ("Could not import 'graphviz' module. "
                   "Make shure 'graphviz' is installed "
                   "or install it typing 'pip install graphviz'")
            raise ImportError(msg)

        # Create graph
        dot = Graph()
        # Create nodes
        for n in range(1, self.n_nodes + 1):
            dot.node(str(n))
        # Create edges
        for n1, n2 in self.edges:
            dot.edge(str(n1), str(n2))
        # Visualize
        dot.render(name, view=True, cleanup=True)
コード例 #21
0
def main():

    p = argparse.ArgumentParser(
        description='This script is for generate graph figure')
    p.add_argument('-g', '--graph', type=str,
                   help='path to graph csv file', required=True)

    p.add_argument('-o', '--out', type=str,
                   help='output_file', required=True)

    option_args = p.parse_known_args()[0]
    path = option_args.graph
    out_file = option_args.out

    if not os.path.exists(path):
        print("File not found")
        sys.exit(1)

    adj_matrix = read_graph(path)
    g = Graph(format='png')

    for i in range(len(adj_matrix)):
        for j in range(i + 1, len(adj_matrix)):
            g.edge(str(i), str(j), label=str(adj_matrix[i][j]))

    g.render(out_file)
コード例 #22
0
ファイル: visualization.py プロジェクト: npxquynh/tts4
    def visualize(self):
        l = len(self.top_result)

        connections = dict()
        tags = dict()

        for i in range(l - 1):
            for j in range(1, l):
                if i != j:
                    key = (i, j)

                    message_list = self.get_message_list_between(self.top_result[i], self.top_result[j])
                    tag_cloud = self.subject.calculate_tag_cloud(message_list)

                    tags[key] = self.get_top_tag_cloud(tag_cloud, 5)

        # DOT language
        dot = GraphV(comment = "Information Flow - Enron")
        for i in range(l):
            dot.node(str(i), self.top_result[i] + " - " + self.company.get_role(self.top_result[i]))

        for (edge, tag) in tags.iteritems():
            node_1 = edge[0]
            node_2 = edge[1]
            note = ", ".join(tag)
            print note
            dot.edge(str(node_1), str(node_2), label=note)


        dot.render('test-output/round-table.gv', view=False)
コード例 #23
0
def graph_data(pkg_name):
    if not pkg_name:
        abort(404)

    filepath = os.path.join(cache_dir, pkg_name.lower())
    if not os.path.exists(filepath + '.png'):
        nodes, edges = reqs_graph(pkg_name)

        if not nodes:
            return redirect(url_for('static', filename='img/blank.png'))

        dot = Graph()
        dot.format = 'png'
        dot.node('0', nodes[0], fillcolor='#fbb4ae', style='filled', shape='box')
        for i, pkg_name in enumerate(nodes[1:]):
            dot.node(str(i+1), pkg_name, fillcolor='#ccebc5', style='filled')

        dot.edges([
            [str(i[0]), str(i[1])]
            for i in edges
        ])

        dot.render(filepath)

    return send_file(filepath + '.png')
コード例 #24
0
 def printQueue(self):
     sl = Graph('singlylinked', node_attr={'shape': 'record'})
     if self.stack_empty():
         pass
     else:
         self._draw(self.sentinel.next, 0, sl)
     sl.render('singlylinked.gv', view=True)
コード例 #25
0
def generateCompDiagram(comp):
    tempDirPath = state.get('tempDirPath')
    filepath = join(tempDirPath, uuid.uuid4().hex + '.gv')
    indexTracker = {}
    g = Graph('G', filename=filepath)
    g.format = 'png'

    with g.subgraph(name='clusterComponent') as c:
        for group in comp.groups:
            with c.subgraph(name='cluster' + uuid.uuid4().hex) as a:
                a.attr(color='blue')
                for port in group.ports:
                    name = port.portType
                    idx = 0
                    if not (name in indexTracker):
                        indexTracker[name] = 1
                    else:
                        idx = indexTracker[name]
                        indexTracker[name] += 1
                    if (port.direction == 'in'):
                        a.node_attr.update(color='green', style='filled')
                    elif (port.direction == 'out'):
                        a.node_attr.update(color='red', style='filled')
                    else:
                        a.node_attr.update(color='orange')
                    a.node(name + '_' + str(idx), label=name, style='filled')

    g.render()
    Popen(["xdg-open", filepath + '.png'])
コード例 #26
0
def gen_img(graph: Graph,
            node_num,
            rm_ratio: float = 0.2,
            root_folder='train',
            source_folder='',
            source_file='train.txt'):
    """
    在graph上,以rm_ratio的概率随机删除一些链路,然后用随机选取的一对节点作为源宿点,判断其是否联通。并将生成的图像放到root_folder目录中,
    对应的文件名称和标签放到source_folder目录下的train.txt文件中。
    """
    # 生成原始数据
    rds = rand_edges(graph, rm_ratio)
    graph.remove_edges_from(rds)
    src, dst = gen_src_dst(0, node_num)
    label = get_label(src, dst, graph)
    # 构造graphviz对象
    name = str(time.time())
    g = Graph(format='jpeg', engine='neato')
    g.attr('node', shape='circle')
    g.attr('edge')
    for node in graph.nodes():
        g.node(name=str(node))
    g.node(name=str(src), shape='triangle')
    g.node(name=str(dst), shape='triangle')
    for edge in graph.edges():
        g.edge(str(edge[0]), str(edge[1]))
    for edge in rds:
        g.edge(str(edge[0]), str(edge[1]), color='white')
    g.render(filename=name, directory=root_folder, view=False, cleanup=True)
    # 存储到文件中去
    file = open(os.path.join(source_folder, source_file), 'a')
    file.write(name + '.jpeg ' + str(label) + '\n')
    file.flush()
    file.close()
コード例 #27
0
def display(ref, filename='temp'):
    """Render a tree to SVG format.

    *Warning:* Made for use within IPython/Jupyter only.

    Args:
        ref (Tree).
        filename (str): Temporary filename to store SVG output.

    Returns:
        SVG: IPython SVG wrapper object for tree.

    """

    # Ensure all modules are available
    try:
        from graphviz import Graph
        from IPython.display import SVG
    except:
        raise Exception("Missing module: graphviz and/or IPython.")
    # Traverse tree and generate temporary Graph object
    output_format = 'svg'
    graph = Graph(filename, format=output_format)
    q = Queue()
    q.enqueue(ref)
    while not q.isempty():
        ref = q.dequeue()
        graph.node(str(id(ref)), label=str(ref.key))
        for child in ref.children:
            graph.edge(str(id(ref)), str(id(child)))
            q.enqueue(child)
    # Render to temporary file and SVG object
    graph.render(filename=filename, cleanup=True)
    return SVG(filename + '.' + output_format)
コード例 #28
0
def createGraph(mi, names, graph_name):
    """Given dict of mutual information, print the Minimum Spanning Tree as per Chow Liu Algorithm"""

    milist = sorted(mi.items(), key=lambda f: np.fabs(f[1]))

    size = len(names)
    parents = -1 * np.ones(size, dtype=int)
    edges = []

    count = 0
    i = 0
    while count < size - 1:
        verts, val = milist[i]
        if detect_cycle(parents, verts) == False:
            temp1 = verts[0]

            while (temp1 != -1):
                temp2 = parents[temp1]
                parents[temp1] = verts[1]
                temp1 = temp2

            count += 1
            edges.append(verts)

        i += 1

    graph = Graph(comment='minimum spanning tree', format='png')
    for i in range(size):
        graph.node(names[i])

    for j in edges:
        graph.edge(names[j[0]], names[j[1]])

    graph.render(graph_name, view=True)
コード例 #29
0
def render_dungeon(dungeon: Dungeon, session_id: str, rogue_position: int):
    filename = f'./dungeons/d-{session_id}.gv'
    g = Graph('Dungeon_graph', filename=filename, format='png', engine='fdp')

    for room in dungeon.rooms:
        contains_key = any(key.room_id == room.id for key in dungeon.keys)

        shape = 'circle'
        if rogue_position == room.id:
            shape = 'triangle'
        elif contains_key:
            shape = 'doublecircle'
        elif room.id == dungeon.finish_room_id:
            shape = 'star'

        g.attr('node', color=str(room.color), shape=shape)
        g.node(str(room.id))

    for door in dungeon.doors:
        if door.is_closed:
            style = 'dashed'
        else:
            style = 'solid'
        g.attr('edge', color=str(door.color), style=style)
        g.edge(str(door.first_room_id), str(door.second_room_id))

    g.render()

    return f'{filename}.png'
コード例 #30
0
def graph_label(data, renewable):
    num_all_rows_of_state = 19

    g = Graph("all_years_clustering", engine="fdp",
              format="svg", edge_attr={"penwidth": "4"}, node_attr={"style": "filled"})

    for lab in data:
        if len(data[lab]) == 1:
            g.node(next(iter(data[lab])))
            continue
        complete_node = []
        incomplete_node = []
        for state in data[lab]:
            dist = data[lab][state]
            if dist == num_all_rows_of_state:
                complete_node += [state]
            else:
                incomplete_node += [(state, dist)]
        node_color = colors.to_hex([0, 1, 0, renewable[lab]], keep_alpha=True)
        if len(complete_node) > 0:
            g.node(str(lab), label=",".join(complete_node), fillcolor=node_color)
        else:
            g.node(str(lab), label="", width=str(0.2), height=str(0.2), fillcolor=node_color)
        for state, dist in incomplete_node:
            edge_color = [0, 0, 0, dist / num_all_rows_of_state]
            g.edge(str(lab), state, weight=str(dist),
                   color=colors.to_hex(edge_color, keep_alpha=True))
    g.render("output/all_years_clustering", view=True, cleanup=True)
コード例 #31
0
ファイル: pattern_parser.py プロジェクト: Neon22/chartmaker
 def viz(self):
     """ Build a dotmap for graphviz 
         but also constructs the connected_stitch structures
     """
     flatmap = flatten(self.stitch_map())
     if self.pattern_type == 'round':
         dot = Graph(engine="twopi",
                     graph_attr={
                         'root': 'a1',
                         'overlap': 'false'
                     },
                     node_attr={
                         'shape': 'circle',
                         'margin': '0.00001 0.0001'
                     },
                     format="png",
                     name=self.name)
     else:
         dot = Graph(format="png", name=self.name)
     # first pass nodes
     for stitch in flatmap:
         dot.node("a" + str(stitch.id), str(stitch.stitch))
     # second pass edges
     for stitch in flatmap:
         if (stitch.prev):
             dot.edge("a" + str(stitch.id), "a" + str(stitch.prev.id))
         if (stitch.bottom):
             dot.edge("a" + str(stitch.id), "a" + str(stitch.bottom.id))
     dot.render(view=True)
コード例 #32
0
    def llenarCeldas(self, var):
        eFila = self.eFilas.primero
        concatenar = '<<TABLE>'
        #print("\n**************recorrido por filas*************************")

        while eFila != None:
            concatenar = concatenar + '\n<TR>'
            actual = eFila.accesoNodo
            #print("\nfila"+str(actual.fila))
            #print("columna   valor  ")
            while actual != None:
                #print(str(actual.columna)+"      "+ actual.valor)
                if (actual.valor == '*'):
                    concatenar = concatenar + '<TD bgcolor="black">'
                if (actual.valor == '-'):
                    concatenar = concatenar + '<TD>'
                concatenar = concatenar + '</TD>'
                actual = actual.derecha
            concatenar = concatenar + '\n</TR>'
            eFila = eFila.siguiente

        concatenar = concatenar + '\n</TABLE>>'
        #print(concatenar)
        h = Graph(var, format='png')
        h.node('tab', label=concatenar)
        concatenar = ""
        h.render()
コード例 #33
0
ファイル: diagram2.py プロジェクト: trucndt/chess
class DrawGraphviz:
    """
    Draw a tree with Graphviz
    """

    m_start: int
    m_end: int
    dot: Graph

    def __init__(self, save_name, start, end):
        self.args = args
        self.m_end = end
        self.m_start = start

        self.dot = Graph(name='diagram-' + save_name, strict=True)
        self.dot.graph_attr['rankdir'] = 'LR'
        self.dot.node_attr['shape'] = 'box'

    def __draw_func(self, node: GraphNode, parent: GraphNode or None):
        if node.step > self.m_end:
            return

        if node.step >= self.m_start:
            self.dot.node(str(id(node)), node.name)

        if parent is not None and node.step >= self.m_start + 1:
            self.dot.edge(str(id(parent)), str(id(node)))

        for child_node in node.child:
            self.__draw_func(child_node, node)

    def draw(self, root: GraphNode):
        self.__draw_func(root, None)
        self.dot.render(view=True, format='pdf')
コード例 #34
0
def imagen(gateway):
    #nodos redes activas
    temporal = sorted(nodos.items())
    nodos.clear()
    for i in temporal:
        nodos[i[0]] = i[1]
    #layouts interfaces reportadas en tabla route
    temp2 = sorted(layouts.items())
    layouts.clear()
    for interfaz in temp2:
        layouts[interfaz[0]] = interfaz[1]
    #FastEth interfaces activas incompletas
    temp2 = sorted(FastEth.items())
    FastEth.clear()
    for fa in temp2:
        FastEth[fa[0]] = fa[1]
    #Activas interfaces activas completas
    name = layouts.keys()
    for uno in name:
        for i in FastEth[uno]:
            fa = i[:i.index(' ')]
            for r in layouts[uno]:
                if fa in r:
                    i = i + r[r.index(' '):]
                    activas[uno].append(i)  #
    temp2 = sorted(activas.items())
    activas.clear()
    for fa in temp2:
        activas[fa[0]] = fa[1]

    dicredes = {}
    cad = ''
    grafica = Graph('red')
    grafica.node('linux mint', shape='rectangle', label='MV' + '\n' + gateway)
    grafica.node('switch', shape='rectangle')
    grafica.edge('linux mint', 'switch')
    for x in nodos:
        aux4 = activas[x]
        for y in aux4:
            cad = cad + y + '\n'
        grafica.node(x, label=x + '\n' + cad, shape='rectangle')
        cad = ''
        redes = nodos[x]
        for red in redes:
            if red not in dicredes.keys():
                dicredes[red] = []
                dicredes[red].append(x)
            else:
                dicredes[red].append(x)
    for d in dicredes:
        print(d + ':' + str(dicredes[d]))
        if d.find('56') >= 0:
            for each in dicredes[d]:

                grafica.edge('switch', each, label=d)
        if len(dicredes[d]) == 2 and d.find('8') == 0:
            grafica.edge(dicredes[d][0], dicredes[d][1], label=d)
    grafica.format = 'png'
    grafica.render('static/red')
コード例 #35
0
def render_graph(graph, edge_list, filename="graph", fmt="pdf"):
	g = Graph(format=fmt)
	for src in graph:
		g.node(name=str(src))
	for src in graph:
		for dst in graph[src]:
			g.edge(str(src), str(dst), color="red" if is_edge_in_list((src, dst), edge_list) else "black")
	g.render(filename=filename)
コード例 #36
0
    def render(self):
        graph = Graph(comment='All trees')

        for i in range(len(self.chromosomes)):
            tree = self.chromosomes[i].tree
            graph.subgraph(graph=tree.render(f'{i+1} [Original]'))

        graph.render('test-output/round-table.gv')
コード例 #37
0
ファイル: plot.py プロジェクト: tennapel/graph-problems
def plot(graph, engine='dot', filename='output/test'):
    """Possible engines: dot, neato, fdp, sfdp, twopi, circo"""
    g = Graph(format='png', engine=engine)
    for v in graph:
        g.node(str(index(v)))

    for v, w in graph.edges:
        g.edge(str(index(v)), str(index(w)))

    g.render(filename)
コード例 #38
0
ファイル: btrfs_graph.py プロジェクト: kekdck/BRTFS-Browser
def generateGraph():
	G = Graph(
		engine = 'dot',
		filename = 'Btrfs-Graph.dot',
		name = 'BRTFS-Browser',
		comment = 'https://github.com/Zo0MER/BRTFS-Browser.git',
		graph_attr = {'rankdir': 'RL',
						'charset':'utf-8',
						'bgcolor':'#eeeeee',
						'labelloc':'t', 
						'splines':'compound',
						'nodesep':'0.7',
						'ranksep':'5'
					},
		node_attr = {'fontsize': '18.0',
					'shape':'box'
		}
	)

	#node with title and hyperlink on github
	G.node('meta', 
		label = 'Btrfs-debug-tree \nhttps://github.com/Zo0MER/BRTFS-Browser.git', 
		href = 'https://github.com/Zo0MER/BRTFS-Browser.git',
		fontcolor = '#4d2600',
		fontsize = '30.0'
		)

	first = inode[0]
	inode.remove(inode[0])

	if (inode):
		#link first item ROOT_TREE_DIR INODE_ITEM, INODE_REF with all INODE_ITEM EXTEND_DATA
		for pair in inode:
			G.edge(''.join([str(x) for x in first]), ''.join([str(x) for x in pair]))
	else:
		G.node(first)

	#save *.dot and others
	pathout = enterPath.get()
	filenameout = enterFilename.get()

	if (filenameout):
		filenameout = filenameout + '.gv.dot'
	else:
		filenameout = "btrfs-graph"

	G.filename = filenameout + '.gv.dot'
	G.directory = pathout

	G.save()
	for t in types:
		G.format = t
		G.render()
コード例 #39
0
ファイル: rev_del_gv.py プロジェクト: Premnath7/set1
def rev_del(G,weights,count,Y,N):
  for i in range(m):
    gv = Graph('G', filename='rev_del',format='png')
    gv.node_attr.update(color='lightblue2', style='filled')
    gv.body.extend(['rankdir=LR'])
    for j in range(i+1,m):
      gv.edge(str(B[j][1]),str(B[j][2]),label=str(B[j][0]))
    for n in N: 
      gv.edge(str(B[n[3]][1]),str(B[n[3]][2]),label=str(B[n[3]][0]),color="red")
    for y in Y: 
      gv.edge(str(B[y[3]][1]),str(B[y[3]][2]),label=str(B[y[3]][0]),color="blue")
    gv.edge(str(B[i][1]),str(B[i][2]),label=str(B[i][0]),color="green")
    gv.render(str(count))
    count+=1
    count=Connectivity(G,weights[i],A,count,Y,N)
  return count
コード例 #40
0
ファイル: plot.py プロジェクト: Chiel92/graph-problems
def plot(graph, engine='dot', filename='output/test', vertex_names={}):
    """
    Possible engines: dot, neato, fdp, sfdp, twopi, circo
    Vertex_names is an optional dict from vertices to strings.
    """
    g = Graph(format='png', engine=engine)

    def vertex_to_string(v):
        return (vertex_names[v] if v in vertex_names else '') + ' ({})'.format(str(index(v)))

    for v in graph:
        g.node(vertex_to_string(v))

    for v, w in graph.edges:
        g.edge(vertex_to_string(v), vertex_to_string(w))

    g.render(filename)
コード例 #41
0
ファイル: interactions_graph.py プロジェクト: michal3141/sat
def create_conflicts_graph(clauses):
    dot = GGraph(comment='Conflicts graph', engine='sfdp')

    for i in xrange(len(clauses)):
        dot.node(str(i), label=str(i))

    for i in xrange(len(clauses)):
        for j in xrange(i+1, len(clauses)):
            clause_i = clauses[i]
            clause_j = clauses[j]
            edge_labels = []
            for lit in clause_i:
                if -lit in clause_j:
                    var = abs(lit)
                    edge_labels.append(str(var))
            if len(edge_labels) > 0:
                dot.edge(str(i), str(j), label=','.join(edge_labels)) 

    dot = _apply_styles(dot, styles)
    dot.render(os.path.join('images', 'conflicts_graph.gv'), view=True)
コード例 #42
0
ファイル: routemap.py プロジェクト: mamoit/ai-search
    def render(self, filename):
        """ Renders the graph to a file.

        Args:
            filename (str): Filename of the map file.
        """
        dot = Graph(comment='ISTravel graph', engine='fdp')
        for city in self.cities:
            dot.node(str(city))
        ploted = []
        for node in self.connections:
            for edge in self.connections[node]:
                if edge not in ploted:
                    ploted.append(edge)
                    dot.edge(
                        str(edge.nodes[0]),
                        str(edge.nodes[1]),
                        label=edge.transport[:2]
                    )
        dot.render(filename[:filename.rfind('.')]+".gv")
コード例 #43
0
ファイル: explorer.py プロジェクト: michal3141/ed
def visualize_topics(quora_data):
    dot = Graph(comment='Topics graph', engine='sfdp')
    seen_topics = set()
    for document in quora_data:
        question = _get_question(document)
        topics = document[question]['topics']
        # Iterating over topics and adding nodes for topics if necessary
        for topic in topics:
            if topic not in seen_topics:
                dot.node(topic, label=topic)
                seen_topics.add(topic)
        # Iterating over topics and adding edges between topics belonging to the same question
        for i in xrange(len(topics)):
            for j in xrange(i+1, len(topics)):
                dot.edge(topics[i], topics[j])
            #     topic1, topic2 in product(topics, topics):
            # dot.edge(topic1, topic2)
    dot = _apply_styles(dot, styles)
    # print dot.source
    dot.render(os.path.join('images', 'topics.gv'), view=True)
コード例 #44
0
ファイル: graph.py プロジェクト: atiaxi/chromabot
def main():
    source = sys.argv[1]
    with open(source, 'r') as infile:
        regions = json.load(infile)

    g = Graph('chroma', filename='chroma.graphview', format='png')
    for region in regions:
        name = region['name']
        style = {"style": "filled"}
        if "owner" in region:
            owner = region["owner"]
            if owner == 0:
                style["color"] = "orange"
            else:
                style["color"] = "blue"
                style["fontcolor"] = "white"

        g.node(name, **style)
        for conn in region['connections']:
            g.edge(name, conn)
    g.render()
コード例 #45
0
ファイル: rev_del_gv.py プロジェクト: Premnath7/set1
def Connectivity(G,e,A,count,Y,N):  #checks connectivity of graph on removing edge e
  if A[0][0]==e:
    u=A[0][1]
    v=A[0][2]
    tup=A.pop(0)  
  index=len(B)-len(A)-1
  tup.append(index)
  G[u-1][v-1]=G[v-1][u-1]=0
  L=[]
  if path(G,u,v,u,L):
    N.append(tup)
    gv = Graph('G', filename='rev_del',format='png')
    gv.node_attr.update(color='lightblue2', style='filled')
    gv.body.extend(['rankdir=LR'])
    index=len(B)-len(A)-1
    for z in range(index+1,m):
      gv.edge(str(B[z][1]),str(B[z][2]),label=str(B[z][0]))
    for n in N: 
      gv.edge(str(B[n[3]][1]),str(B[n[3]][2]),label=str(B[n[3]][0]),color="red")
    for y in Y: 
      gv.edge(str(B[y[3]][1]),str(B[y[3]][2]),label=str(B[y[3]][0]),color="blue")
    gv.render(str(count))
    count+=1
    return count
  else:
    G[u-1][v-1]=G[v-1][u-1]=e
    Y.append(tup)
    gv = Graph('G', filename='rev_del',format='png')
    gv.node_attr.update(color='lightblue2', style='filled')
    gv.body.extend(['rankdir=LR'])
    index=len(B)-len(A)-1
    for z in range(index+1,m):
      gv.edge(str(B[z][1]),str(B[z][2]),label=str(B[z][0]))
    for n in N: 
      gv.edge(str(B[n[3]][1]),str(B[n[3]][2]),label=str(B[n[3]][0]),color="red")
    for y in Y: 
      gv.edge(str(B[y[3]][1]),str(B[y[3]][2]),label=str(B[y[3]][0]),color="blue")
    gv.render(str(count))
    count+=1
    return count
コード例 #46
0
 def save_nodes(self, filename="graph", nodes = None):
     print "Saving graph..."
     from graphviz import Graph
     dot = Graph(comment='Dungeon Example')
     if nodes == None:
         nodes = self.linear_nodes(self.nodes)
     #else:
         #max_appeared = appeared.values()
         #if max_appeared == []: start = 0
         #else: start = max(max_appeared) + 1
         #print start
         #for node in nodes:
         #    if node.id not in appeared:
         #        appeared[node.id] = start
     for node in nodes:
         name = node.name
         if hasattr(node, "replace_on_room_clear"):
             replace = node.replace_on_room_clear[0]
             name += "\n"
             try:
                 name += replace.name
             except AttributeError:
                 name += replace
         amount = 255 #60+(appeared[node.id]*64)
         fill = "#%02x%02xFF"%(amount, amount)
         #print fill
         shape = "oval"
         if node is self.entrance:
             shape = "box"
         dot.node(str(node.id), name, style="filled", fillcolor=fill, shape=shape)
     done_edges = []
     for node in nodes:
         for edge in node.connections:
             if sorted([node.id, edge.id]) in done_edges: continue
             dot.edge(str(node.id), str(edge.id))
             done_edges.append(sorted([node.id, edge.id]))
     
     dot.render(filename)
     print "Graph saved"
コード例 #47
0
ファイル: inferring_genotype.py プロジェクト: amadev/tests
def graph(node, fname):
    from graphviz import Graph
    g = Graph('G')
    add_edges(node, g)
    g.render(fname, view=True)
コード例 #48
0
ファイル: rev_del_gv.py プロジェクト: Premnath7/set1
from slideshow import slideshow
from graphviz import Graph

count=1

gv = Graph('G', filename='heading',format="png")
gv.node_attr.update(color='white', style='filled',fontsize="50")
gv.node("Reverse Delete Algorithm")
gv.render(str(count))
count+=1

gv = Graph('G', filename='Description',format="png")
gv.node_attr.update(color='white', style='filled',fontsize="25")
gv.edge("Start with graph G, which contains a list of edges E.","Go through E in decreasing order of edge weights.",color="white")
gv.edge("Go through E in decreasing order of edge weights.","For each edge, check if deleting the edge will further disconnect the graph.",color="white")
gv.edge("For each edge, check if deleting the edge will further disconnect the graph.","Perform any deletion that does not lead to additional disconnection.",color="white")
gv.render(str(count))
count+=1

gv = Graph('G', filename='Legend',format="png")
gv.node_attr.update(color='white', style='filled',fontsize="30")
gv.body.extend(['rankdir=LR', 'size="8,5"'])
gv.node("green",color="green")
gv.node("red",color="red")
gv.node("blue",color="blue")
gv.edge("Current edge:","green",color="green")
gv.edge("Deleted edge/Edge not in Spanning Tree:","red",color="red")
gv.edge("Edge present in Spanning Tree:","blue",color="blue")
gv.node('Legend:', shape='Mdiamond',color="yellow")
gv.render(str(count))
count+=1
コード例 #49
0
ファイル: sna.py プロジェクト: geekdinazor/SNAnalyzer
class SNAnalyzer(object):
    def __init__(self,inPath,outPath,engine,analyzeType):
            self.network  = {}
            self.nameIndex = {}
            self.inPath = inPath
            self.outPath = outPath
            self.engine = engine
            self.aType = analyzeType
            self.networkFileParse(self.inPath)

    def random_id(self,len):
        alpha = 'abcdefghijklmnopqrstuvwxyz'
        id = ''
        for i in range(0,len):
            id += random.choice(alpha)
        return id

    def networkFileParse(self,path):
        f = open(path, 'r')
        for line in f:
            line = line.replace("\n","")
            self.nameIndex.update({line.split(":")[0]:self.random_id(3)})
            self.network.update({line.split(":")[0]:e.split(",") for e in line.split(":")[1:]})
        f.close()


    def graphUpdate(self):
            if self.aType == "tw":
                self.graph = Digraph()
            elif self.aType == "fb":
                self.graph = Graph()
            else:
                exit("Invalid Analyze Type")

            for key in self.nameIndex.keys():
                self.graph.node(self.nameIndex[key], key)
            for key in self.network.keys():
                for friend in self.network[key]:
                    if friend != "":
                        self.graph.edge(self.nameIndex[key],self.nameIndex[friend])

    def generateGraphCode(self):
        self.graphUpdate()
        return self.graph.source

    def renderGraph(self):
        self.graphUpdate()
        self.graph.engine = self.engine
        self.graph.render(self.outPath, view=True)


    def addNode(self,newNode):
            if newNode not in self.nameIndex.keys():
                self.nameIndex[newNode] = self.random_id(3)
                self.network[newNode] = []
            else:
                print("Error: Network already has that {} named Node !".format(newNode))


    def removeNode(self,targetNode):
        if targetNode in self.nameIndex.keys():
            del self.nameIndex[targetNode]
            del self.network[targetNode]
            for key in self.network.keys():
                if targetNode in self.network[key]:
                    self.network[key].remove(targetNode)
        else:
            print("Error: Network not has that {} named Node !".format(targetNode))


    def hasRelation(self,sourceNode,targetNode):
        friends = self.network[sourceNode]
        if targetNode in friends:
            return True
        else:
            return False

    def addRelation(self,sourceNode,targetNode):
        if not self.hasRelation(sourceNode,targetNode):
             self.network[sourceNode].append(targetNode)
        else:
            print("Error: The Node {} is already related to {} !".format(sourceNode, targetNode))


    def removeRelation(self,sourceNode,targetNode):
        if self.hasRelation(sourceNode,targetNode):
             self.network[sourceNode].remove(targetNode)
        else:
            print("Error: The Node {} is not related with {} !".format(sourceNode, targetNode))
コード例 #50
0
ファイル: graphs.py プロジェクト: dlawre14/ppredict
from graphviz import Graph #these are undirected
import sqlite3

#open up the db, pull everything

conn = sqlite3.connect('../db/prot.db')
c = conn.cursor()

c.execute('SELECT * from protein')
proids = {x[0]:x[1] for x in c.fetchall()}

c.execute('SELECT * from tags')
tagids = {x[0]:x[1] for x in c.fetchall()}

c.execute('SELECT * from ptag')
matches = c.fetchall()

graph = Graph('All protein tags', engine='neato')

for key in proids:
    graph.node(proids[key])
for key in tagids:
    graph.node(tagids[key])

for x,y in matches:
    graph.edge(proids[x],tagids[y],len="10.0")

graph.render('tag.gv')

conn.close()
コード例 #51
0
def main(restricted = False):
    global styles
    #gc.set_debug(gc.DEBUG_LEAK)
    
    site = input("What site to crawl?")
    maxDepth = int(input("Max depth?"))
    http = httplib2.Http()
    links = set()
    pages = set()
    #dot = Digraph(comment = site, format="png")
    dot = Graph(comment = site, format="png", engine="sfdp")
    dot.overlap = "true"
    #dot.graph_attr.update(size = "10000000,10000000")

    try:
        soup = BeautifulSoup(urllib2.urlopen(site), "html.parser")
        pageTitle = soup.title.string
        pages.add(pageTitle)
        titles[site] = pageTitle
        soup.decompose()
    except Exception as e:
        pageTitle = site
        print("Error: {0}".format(e))

    siteBase = ""
    try:
        pos1 = site.find(".")
        pos2 = site.find(".", pos1 + 1)
        siteBase = site[pos1+1:pos2]
    except Exception as e:
        print("Error: {0}".format(e))
    print (siteBase)
        
    crawlPage(site, pageTitle, maxDepth, pages, links, restricted, siteBase)
    #print(pages)
    #print(links)

    #for p in pages:
        #print("Adding node: " + p)
        #dot.node(p)
    for l in links:
        try:
            #print("Adding edge: " + l[0] + " -> " + l[1])
            dot.edge(l[0], l[1])
        except Exception as e:
            print("Error: {0}".format(e))

    #print(dot)
    #dot = apply_styles(dot, styles)
    loc = str(dot).find("{")+1
    dot = Source(str(dot)[0:loc] + "\n\tgraph [overlap = prism]\n" + str(dot)[loc:], format="png", engine="sfdp")

    #print("-------------------")

    filename = r'C:\Users\Gabe\Miniconda3\MyScripts\test-crawler15'
    
    dot.save()
    try:
        os.remove(filename)
    except Exception as e:
        print("Error: {0}".format(e))

    try:
        outFile = open(filename + ".txt", "w")
        outFile.write(str(dot))
        outFile.close()
    except Exception as e:
        print("Error: {0}".format(e))
    
    dot.render(filename, view=True)
コード例 #52
0
ファイル: visitor.py プロジェクト: dumvin/FEECSymbolic
class VisitorGraph(Visitor):
    """this class implement a tree visitor for our form"""
    def __init__(self):
        self.handler_dict = {Form.OperatorForm:(self.func_op_fo,{Form.D: (self.diff, {})\
							, Form.Wedge: (self.wed, {}), Form.Add: (self.add,{}), \
							Form.Hodge: (self.hod, {}),Form.Pullback: (self.pull, {}) }),\
							Form.TerminalForm:(self.func_term_fo,{})}
        self.dot = Graph(comment='Tree of our form')#Digraph(comment='Tree of our form') #to store the dot for vizgraph
        self.edges = [] #to store the edge for the graph
        self.post = [] #to store the post order traversal
        self.pre = [] # to store the pre order traversal
        self.comp = 0 #to differentiate the edge

    #D form
    def diff(self, form, children=None):
        """function when a diff operation is made"""
        if form.scalar == 1:
            return( 'd')
        elif form.scalar == -1:
            return( "-d" )
        else:
            return( "{}d ".format(form.scalar)  )
    
    #Wedge
    def wed(self, form, children=None):
        """function when a wedge operation is made"""
        if form.scalar == 1:
            return( '^')
        elif form.scalar == -1:
            return( "-^" )
        else:
            return( "{}^ ".format(form.scalar)  )
                    
    #Add
    def add(self, form, children=None):
        """function when a add operation is made"""
        if form.scalar == 1:
            return( '+')
        elif form.scalar == -1:
            return( "-+" )
        else:
            return( "{}+ ".format(form.scalar)  )
                    
    #Hodge
    def hod(self, form, children=None):
        """function when a hodge star operation is made"""
        if form.scalar == 1:
            return( '*')
        elif form.scalar == -1:
            return( "-*" )
        else:
            return( "{}* ".format(form.scalar)  )
    
    #Pullback
    def pull(self, form, children=None):
        """function when a hodge star operation is made"""
        if form.scalar == 1:
            return("phi")

        else:
            return( "{}phi ".format(form.scalar)  )

    #TerminalForm
    def func_term_fo(self, form):
        """function that print a terminal Form"""
        if form.scalar == 1:
            return( form.name)
        elif form.scalar == -1:
            return( "-{} ".format(form.name)  )
        else:
            return( "{}{} ".format(form.scalar, form.name)  )


    def _visit_preorder(self, form):
        """the intern preorder method for visiting the tree"""
        if not isinstance(form,Form.TerminalForm):
            children=form.forms
            inter = self.find_method(form)(form)
            self.pre.append(inter)
            for fo in children:
                self._visit_preorder(fo)
            #in post order the find_method will be there
        else:
            inter = self.find_method(form)(form)
            self.pre.append(inter)

    def visit_preorder(self, form):
        """the preorder method for visiting the tree"""
        self.pre=[]
        self._visit_preorder(form)
        return self.pre

    def _visit_postorder(self, form):
        """the intern postorder method for visiting the tree"""
        if not isinstance(form,Form.TerminalForm):
            children=form.forms
            for fo in children:
                self._visit_postorder(fo)
            inter = self.find_method(form)(form)
            self.post.append(inter)
        else:
            inter = self.find_method(form)(form)
            self.post.append(inter)
            
    def visit_postorder(self, form):
        """the postorder method for visiting the tree"""
        self.post=[]
        self._visit_postorder(form)
        return self.post

    def _create_graph(self, form, parent_name=""):
        """the method for creating a graph of the tree, the edges are store inside the edges attribute"""
        if not isinstance(form,Form.TerminalForm):
            children = form.forms
            node = (self.find_method(form)(form))
            nbr1 = str(self.comp)
            self.comp+=1
            name = nbr1
            self.dot.node(name, node)
            
            if parent_name is not "":
                inter=parent_name+name                
                self.edges.append(inter)
                self.dot.edge(parent_name, name)

            parent_name=name
            for fo in children:
                self._create_graph(fo,parent_name)
            
        else:
            node = (self.find_method(form)(form))
            nbr1 = str(self.comp)
            self.comp+=1
            name = nbr1
            #~ print(name)
            self.dot.node(name,node)
            if parent_name is not "":
                inter = parent_name+name                
                self.edges.append(inter)
                self.dot.edge(parent_name, name)
 
    def draw_graph(self, form, name='sample'):
        """the method for drawing a graph of the tree, name is the file
		name under which we want to save it"""
        self.dot = Graph(comment='Tree of our form')#Digraph(comment='Tree of our form')
        self.edges = []
        self.comp = 0
        self._create_graph(form)
        namefile='drawing/'+name+'.gv'
        self.dot.render(namefile, view=True)