Пример #1
0
def test_simplify_explicit_with_shorten(g):
    """
    Simplify using explicit mapping

    Simplify include:
    1. generate simplify mapping
    2. ensure the mapping output shorten name
    3. map to new node
    """
    output_png = os.path.join(ARTIFACTS_DIR, 'simplify_tree.png')

    mapping = g.get_simplify_mapping(shorten=True)
    assert 'start' in mapping.keys()

    # mapping = g.get_simplify_mapping(shorten=False)
    # assert '[1] start' in mapping.keys()

    df = pd.read_csv(FIXTURE)
    g_simplify = Graphitty(df,
                           id_col='ip',
                           beahivour_col='url',
                           ts_col='date',
                           node_mapping=mapping)
    assert 'start' in g_simplify.G.nodes()

    nx_tree = g_simplify.render_graph(filter_subgraph=True)
    draw(nx_tree, output_png, show=False)
Пример #2
0
def test_name_collapse(g, g2):
    combine_g = GraphCombiner(g, g2, split_weight=False)
    name_mapping = combine_g.get_simplify_mapping()

    g1_simplify = combine_g.remap_graph(g, name_mapping)
    g2_simplify = combine_g.remap_graph(g2, name_mapping)

    nx_graph1 = g1_simplify.render_graph()
    output_png = os.path.join(
        ARTIFACTS_DIR,
        'name_shortened_1.png'
    )
    draw(nx_graph1, output_png, show=False)
    assert 5 <= len(nx_graph1.nodes()) <= 25

    nx_graph2 = g2_simplify.render_graph()
    output_png2 = os.path.join(
        ARTIFACTS_DIR,
        'name_shortened_2.png'
    )
    draw(nx_graph2, output_png2, show=False)
    assert 5 <= len(nx_graph2.nodes()) <= 25

    # let's check that the name converge (nothing exotically different)
    def get_node_names(G):
        return set(nx.nodes(G))

    same = get_node_names(nx_graph1) & get_node_names(nx_graph2)
    different = get_node_names(nx_graph1) ^ get_node_names(nx_graph2)
    # print "same={}".format(same)
    # print "different={}".format(different)
    assert len(same) >= 3
    assert 1 <= len(different) <= 20
Пример #3
0
def draw_graph(G, layout='circo'):
    G.graph['rankdir'] = 'LR'
    G.graph['dpi'] = 120
    G.graph['layout'] = layout
    if layout not in {'circo', 'dot'}:
        G.graph['ranksep'] = 3
        G.graph['nodesep'] = 2.5
    draw(G)
Пример #4
0
def graph(name, nodes, edges):

    G = nx.DiGraph()
    G.graph['dpi'] = 200
    G.graph['label'] = "SBH Graph: {}".format(name)
    G.add_nodes_from(nodes)
    G.add_edges_from(edges)
    draw(G)
Пример #5
0
def test_simplification(g):
    output_png = os.path.join(ARTIFACTS_DIR, 'tree.png')

    if os.path.isfile(output_png):
        os.remove(output_png)

    g_simplify = g.simplify()
    nx_tree = g_simplify.render_graph(filter_subgraph=True)
    draw(nx_tree, output_png, show=False)
Пример #6
0
def test_simplify_comparison(g, g2):
    g = GraphCombiner(g, g2)
    simplified_g = g.get_simplifed_combine_graph()
    nx_combined = simplified_g.render_graph()
    output_png = os.path.join(
        ARTIFACTS_DIR,
        'simplify_combined.png'
    )
    draw(nx_combined, output_png, show=False)

    assert len(nx_combined.nodes()) < 25
Пример #7
0
def test_read_generate_graph(g):
    if os.path.isfile(TEST_GRAPH_OUTPUT):
        os.remove(TEST_GRAPH_OUTPUT)

    nx_graph = g.render_graph(filter_subgraph=True)
    draw(nx_graph, TEST_GRAPH_OUTPUT, show=False)

    # some data is drawn
    assert os.path.isfile(TEST_GRAPH_OUTPUT)
    filesize = os.stat(TEST_GRAPH_OUTPUT).st_size
    assert filesize > 1000

    assert len(nx_graph.nodes()) > 5
    assert nx.number_connected_components(nx_graph.to_undirected()) == 1
 def render(self, path=None, save=True):
     """Draw the graph with nxpd."""
     from nxpd import draw
     try:
         get_ipython
         from nxpd import nxpdParams
         nxpdParams['show'] = 'ipynb'
     except NameError:
         pass
     nx_graph = self._convert_to_nx()
     nx_graph.graph['dpi'] = 80
     if save:
         filename = os.path.abspath(os.path.join(path, "graph.pdf"))
         draw(nx_graph, filename, format='pdf', show=False)
     else:
         return draw(nx_graph)
Пример #9
0
def draw_multiple_graphs(graphs):
    """
    draws multiple networkx graphs with graphviz and put the generated
    images in the same IPython notebook output cell.
    """
    for graph in graphs:
        display(Image(filename=draw(graph, show=False)))
Пример #10
0
 def draw_graph(self, show=False, **attributes):
     for node in self.graph:
         for key, value in node._default_graph_attributes().items():
             if not key in node._graph_attributes:
                 self.graph.nodes[node][key] = value
     for key, value in attributes.items():
         self.graph.graph[key] = value
     return draw(self.graph, show=show)
Пример #11
0
 def plot(self):
     states = self._to_nx_state()
     edges = self._to_nx_edge()
     g = nx.DiGraph()
     g.add_nodes_from(states)
     g.add_edges_from(edges)
         
     return draw(g, format = 'svg')
Пример #12
0
def drawIndividualGraphs(participants,connections):
    index=1
    for p in participants:
        con = [c for c in connections if c[0] == p]
        links = [c[1] for c in con]
        links.append(p)

        H = nx.DiGraph()
        H.add_nodes_from(links, style='filled', fillcolor='black', 
                             fontcolor='white', fontname='sans-serif', fontsize=24)

        for c in con:
            H.add_edge(c[0], c[1], label=c[2]['label'], style='dotted', fontcolor='red', fontsize=12,
                              fontname='sans-serif')

        draw(H, filename='Resources/'+str(index)+'.svg')
        index+=1
    return index
Пример #13
0
def dag_drawer(dag, scale=0.7, filename=None, style='color'):
    """Plot the directed acyclic graph (dag) to represent operation dependencies
    in a quantum circuit.

    Args:
        dag (DAGCircuit): The dag to draw.
        scale (float): scaling factor
        filename (str): file path to save image to (format inferred from name)
        style (str): 'plain': B&W graph
                     'color' (default): color input/output/op nodes

    Returns:
        Ipython.display.Image: if in Jupyter notebook and not saving to file,
            otherwise None.

    Raises:
        VisualizationError: when style is not recognized.
    """
    G = copy.deepcopy(
        dag.multi_graph)  # don't modify the original graph attributes
    G.graph['dpi'] = 100 * scale

    if style == 'plain':
        pass
    elif style == 'color':
        for node in G.nodes:
            n = G.nodes[node]
            if n['type'] == 'op':
                n['label'] = str(n['name'])
                n['color'] = 'blue'
                n['style'] = 'filled'
                n['fillcolor'] = 'lightblue'
            if n['type'] == 'in':
                n['label'] = n['name'][0] + '[' + str(n['name'][1]) + ']'
                n['color'] = 'black'
                n['style'] = 'filled'
                n['fillcolor'] = 'green'
            if n['type'] == 'out':
                n['label'] = n['name'][0] + '[' + str(n['name'][1]) + ']'
                n['color'] = 'black'
                n['style'] = 'filled'
                n['fillcolor'] = 'red'
        for e in G.edges(data=True):
            e[2]['label'] = e[2]['name'][0] + "[" + str(e[2]['name'][1]) + "]"
    else:
        raise VisualizationError("Unrecognized style for the dag_drawer.")

    show = nxpd.nxpdParams['show']
    if filename:
        show = False
    elif ('ipykernel' in sys.modules) and ('spyder' not in sys.modules):
        show = 'ipynb'
    else:
        show = True

    return nxpd.draw(G, filename=filename, show=show)
Пример #14
0
def draw_sentence(s, **kwds):
    import nxpd
    for node in s.nodes():
        attr = s.node[node]
        if 'word' not in attr:
            attr['label'] = str(node)
        elif attr['word'].startswith('_'):
            attr['label'] = attr['pos'] + '_%s' % node
        else:
            attr['label'] = attr['word'] + '_%s' % node
        attr['label'] = attr['label'].replace(":", "/")
    for e1, e2 in s.edges():
        attr = s.edge[e1][e2]
        if 'deptype' in attr:
            attr['label'] = attr['deptype']
        else:
            attr['label'] = 'NONE'
        attr['label'] = attr['label'].replace(":", "/")
    nxpd.draw(s, **kwds)
Пример #15
0
def draw_sentence(s, **kwds):
    import nxpd
    for node in s.nodes():
        attr = s.node[node]
        if 'word' not in attr:
            attr['label'] = str(node)
        elif attr['word'].startswith('_'):
            attr['label'] = attr['pos'] + '_%s' % node
        else:
            attr['label'] = attr['word'] + '_%s' % node
        attr['label'] = attr['label'].replace(":", "/")
    for e1, e2 in s.edges():
        attr = s.edge[e1][e2]
        if 'deptype' in attr:
            attr['label'] = attr['deptype']
        else:
            attr['label'] = 'NONE'
        attr['label'] = attr['label'].replace(":", "/")
    nxpd.draw(s, **kwds)
Пример #16
0
 def save_visualizations(graphs: dict,
                         folder_path: str,
                         formats: list = None):
     """
     :param graphs: Dictionary of pw_id (or 'input') --> networkx graph (preferably generated by visualize_output above)
     :param folder_path:
     :param formats: list of formats to output the viz in. Options: ['pdf','gv','png','svg']. Any subset of these
     can be provided. If not provided, all formats are generated.
     :return:
     """
     if not formats:
         formats = ['pdf', 'gv', 'png', 'svg']
     folder_name = os.path.join(folder_path, 'euler_visualization')
     mkdir_p(os.path.abspath(folder_name))
     for pw_id, g in graphs.items():
         for f in formats:
             draw(g,
                  format=f,
                  filename='{}/pw-{}.{}'.format(folder_name, pw_id, f),
                  show='none')
Пример #17
0
 def draw(self):
     """Draw the graph with nxpd."""
     from nxpd import draw
     try:
         get_ipython
         from nxpd import nxpdParams
         nxpdParams['show'] = 'ipynb'
     except NameError:
         pass
     G = self._convert_to_nx()
     G.graph['dpi'] = 80
     return draw(G)
Пример #18
0
    def plot(self):
        def sub(c, dic):
            if dic.get(c) == None:
                dic[c] = 1
                return str(c)
            else:
                dic[c] = dic[c] + 1
                return str(c) + '_' + str(dic[c])

        print('function invoked')
        graph = nx.Graph()
        nodes = [self.root]
        for node in nodes:
            graph.add_node(node.data)
            if node.parent != None:
                graph.add_edge(node.parent.data, node.data)
            if node.left != None:
                nodes.append(node.left)
            if node.right != None:
                nodes.append(node.right)

        draw(graph, 'ada.png')
Пример #19
0
def draw_graph(matrix, labels=ascii_lowercase, round_by=2):
    G = nx.DiGraph()
    G.graph['rankdir'] = 'LR'
    for i in range(matrix.cols):
        G.add_node(i, label=labels[i])
    for i in range(matrix.cols):
        for j in range(matrix.rows):
            p = round(matrix[j, i], round_by)
            if p > 0:
                if p < 1:
                    label = str(p)
                    G.add_edge(i, j, label=label, color='grey55')
                else:
                    G.add_edge(i, j)
    return draw(G)
Пример #20
0
 def plotConstraintGraph(self):
     if self._probType != 2:
         print("Constraint graph available only for binary constraints")
         return nx.Graph()
     else:
         G = nx.Graph()
         G.add_node(0)
         draw(G, show = 'ipynb')
         for v in range (0, self._genLength):
             G.add_node(v)
         for cons in self._constraints:
             if cons.type() == "21":
                 elem = cons.getElem()
                 weight = cons.getWeights()
                 G.add_edge(elem, elem, label = str(weight), color = 'green')
             if cons.type() == "221":
                 elems = cons.getElems()
                 weights = cons.getWeights()
                 G.add_edge(elems[0], elems[1], label = str(weights), color = 'blue')
             if cons.type() == "222":
                 elems = cons.getElems()
                 weights = cons.getWeights()
                 G.add_edge(elems[0], elems[1], label = str(weights), color = 'red')
         return G
Пример #21
0
def draw_net(g, dpi=300, **kwargs):
    """
    Draw the network digram
    :param g:
    :param dpi:
    :return:
    """
    kwargs.setdefault('show', 'ipynb')
    kwargs.setdefault('layout', 'neato')
    # Set dpi
    g.graph['dpi'] = dpi

    # todo: if show=True this will return a string to the tmp location of the image
    gviz = draw(g, **kwargs)

    img = mpimg.imread(BytesIO(gviz.data))

    return img
Пример #22
0
    def view(self):

        G = nx.DiGraph()
        G.graph['rankdir'] = 'LR'
        G.graph['dpi'] = 70
        for i in range(len(self.T)):
            if self.T[i].startswith('_'):
                G.add_node(self.T[i],
                           label=' ',
                           shape='square',
                           style='filled',
                           fillcolor='black')
            else:
                G.add_node(self.T[i],
                           shape='square',
                           style='filled',
                           fillcolor='grey',
                           label=self.T[i].split('_')[0])
        for i in range(len(self.P)):
            label = self.m[i] if self.m[i] else ' '
            if i == 0:
                G.add_node(self.P[i],
                           label=label,
                           style='filled',
                           fillcolor='green')
            elif i == len(self.P) - 1:
                G.add_node(self.P[i],
                           label=label,
                           style='filled',
                           fillcolor='red')
            else:
                G.add_node(self.P[i], label=label)

        for i in range(len(self.T)):
            for j in range(len(self.P)):
                #print(D_plus[i,j])
                if self.I[i, j] == 1:
                    G.add_edge(self.P[j], self.T[i])
                #print(D_plus[i,j])
                if self.O[i, j] == 1:
                    G.add_edge(self.T[i], self.P[j])

        return draw(G)
Пример #23
0
 def render(self, show=None):
     G = nx.DiGraph()
     G.graph['dpi'] = 100
     G.graph['rankdir'] = 'RL'
     G.add_nodes_from(self.final_states, style='filled', shape='doublecircle')
     G.add_nodes_from(self.states.difference(self.final_states), shape='circle')
     G.add_nodes_from(["start"], shape='point', color='gray')
     G.add_edges_from([("start", self.initial_state, {'color': 'gray'})])
     edges = []
     loops = defaultdict(set)
     for o, trans in self.transitions.items():
         for symbol, d in trans.items():
             if o == d:
                 loops[o].add(symbol)
             else:
                 edges.append((o, d, {'label': symbol}))
     for o, symbols in loops.items():
         edges.append((o, o, {'label': '\, '.join(sorted(symbols))}))
     G.add_edges_from(edges)
     return draw(G, show=show)
Пример #24
0
 def render(self, show=None):
     G = nx.DiGraph()
     G.graph['dpi'] = 100
     G.graph['rankdir'] = 'RL'
     G.add_nodes_from(self.final_states,
                      style='filled',
                      shape='doublecircle')
     G.add_nodes_from(self.states.difference(self.final_states),
                      shape='circle')
     G.add_nodes_from(["start"], shape='point', color='gray')
     G.add_edges_from([("start", self.initial_state, {'color': 'gray'})])
     edges = []
     loops = defaultdict(set)
     for o, trans in self.transitions.items():
         for symbol, d in trans.items():
             if o == d:
                 loops[o].add(symbol)
             else:
                 edges.append((o, d, {'label': symbol}))
     for o, symbols in loops.items():
         edges.append((o, o, {'label': '\, '.join(sorted(symbols))}))
     G.add_edges_from(edges)
     return draw(G, show=show)
Пример #25
0
def dag_drawer(dag, scale=0.7, filename=None, style='color'):
    """Plot the directed acyclic graph (dag) to represent operation dependencies
    in a quantum circuit.

    Note this function leverages
    `pydot <https://github.com/erocarrera/pydot>`_ (via
    `nxpd <https://github.com/chebee7i/nxpd`_) to generate the graph, which
    means that having `Graphviz <https://www.graphviz.org/>`_ installed on your
    system is required for this to work.

    Args:
        dag (DAGCircuit): The dag to draw.
        scale (float): scaling factor
        filename (str): file path to save image to (format inferred from name)
        style (str): 'plain': B&W graph
                     'color' (default): color input/output/op nodes

    Returns:
        Ipython.display.Image: if in Jupyter notebook and not saving to file,
            otherwise None.

    Raises:
        VisualizationError: when style is not recognized.
    """
    G = copy.deepcopy(
        dag.multi_graph)  # don't modify the original graph attributes
    G.graph['dpi'] = 100 * scale

    if style == 'plain':
        pass
    elif style == 'color':
        for node in G.nodes:
            n = G.nodes[node]
            if n['type'] == 'op':
                n['label'] = n['name']
                n['color'] = 'blue'
                n['style'] = 'filled'
                n['fillcolor'] = 'lightblue'
            if n['type'] == 'in':
                n['label'] = n['name']
                n['color'] = 'black'
                n['style'] = 'filled'
                n['fillcolor'] = 'green'
            if n['type'] == 'out':
                n['label'] = n['name']
                n['color'] = 'black'
                n['style'] = 'filled'
                n['fillcolor'] = 'red'
        for e in G.edges(data=True):
            e[2]['label'] = e[2]['name']
    else:
        raise VisualizationError("Unrecognized style for the dag_drawer.")

    show = nxpd.nxpdParams['show']
    if filename:
        show = False
    elif ('ipykernel' in sys.modules) and ('spyder' not in sys.modules):
        show = 'ipynb'
    else:
        show = True

    return nxpd.draw(G, filename=filename, show=show)
Пример #26
0
# Write index file
env = Environment(loader=FileSystemLoader('docs/templates'))
with open('docs/index.rst', 'w') as index:
    resources = {}
    for registry in REGISTRIES:
        resources.update(registry)
    try:
        graph_filename = 'images/index.png'
        graph, graph_registry = make_graph(
            registry=resources,
            ext_base=GRAPH_BASE,
        )
        nxpd.draw(
            graph,
            filename='docs/{}'.format(graph_filename),
            show=False,
        )
    except:
        print('Graphs will not be rendered in docs')
        graph_filename = None
        graph_registry = None
    template = env.get_template('index.tpl')
    index.write(template.render(
        modules=modules,
        graph=graph_filename,
    ))

# Write module files
for module in modules:
    resources = modules[module]
 def draw(self):
     return draw(a.graph)
Пример #28
0
def dag_drawer(dag, scale=0.7, filename=None, style='color'):
    """Plot the directed acyclic graph (dag) to represent operation dependencies
    in a quantum circuit.

    Note this function leverages
    `pydot <https://github.com/erocarrera/pydot>`_ (via
    `nxpd <https://github.com/chebee7i/nxpd`_) to generate the graph, which
    means that having `Graphviz <https://www.graphviz.org/>`_ installed on your
    system is required for this to work.

    Args:
        dag (DAGCircuit): The dag to draw.
        scale (float): scaling factor
        filename (str): file path to save image to (format inferred from name)
        style (str): 'plain': B&W graph
                     'color' (default): color input/output/op nodes

    Returns:
        Ipython.display.Image: if in Jupyter notebook and not saving to file,
            otherwise None.

    Raises:
        VisualizationError: when style is not recognized.
        ImportError: when nxpd or pydot not installed.
    """
    try:
        import nxpd
        import pydot  # pylint: disable=unused-import
    except ImportError:
        raise ImportError("dag_drawer requires nxpd, pydot, and Graphviz. "
                          "Run 'pip install nxpd pydot', and install graphviz")

    G = dag.to_networkx()
    G.graph['dpi'] = 100 * scale

    if style == 'plain':
        pass
    elif style == 'color':
        for node in G.nodes:
            n = G.nodes[node]
            n['label'] = node.name
            if node.type == 'op':
                n['color'] = 'blue'
                n['style'] = 'filled'
                n['fillcolor'] = 'lightblue'
            if node.type == 'in':
                n['color'] = 'black'
                n['style'] = 'filled'
                n['fillcolor'] = 'green'
            if node.type == 'out':
                n['color'] = 'black'
                n['style'] = 'filled'
                n['fillcolor'] = 'red'
        for e in G.edges(data=True):
            e[2]['label'] = e[2]['name']
    else:
        raise VisualizationError("Unrecognized style for the dag_drawer.")

    if filename:
        show = False
    elif ('ipykernel' in sys.modules) and ('spyder' not in sys.modules):
        show = 'ipynb'
    else:
        show = True

    return nxpd.draw(G, filename=filename, show=show)
Пример #29
0
no edges between nodes in the same set and every node in one set is connected with one or more node
from the other set
"""
import networkx as nx
from networkx.algorithms import bipartite
import pygraphviz as pgv
from nxpd import draw, nxpdParams
nxpdParams['show'] = 'ipynb'

B = nx.Graph()
#B.add_nodes_from([1, 2, 3, 4, 5, 6], bipartite=0)
#B.add_nodes_from(['a', 'b', 'c', 'd', 'e', 'f'], bipartite=1)
B.add_edges_from([(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b'), (2, 'd'), (3, 'b'),
                  (3, 'd'), (4, 'c'), (4, 'd'), (4, 'e'), (4, 'f'), (5, 'c'),
                  (5, 'e'), (5, 'f'), (6, 'd')])
draw(B, layout='circo')

# color Left set with Red and Right set with blue
if bipartite.is_bipartite(B):
    R_set, L_set = bipartite.sets(B)
    for v in R_set:
        B.node[v]['color'] = 'blue'
    for v in L_set:
        B.node[v]['color'] = 'red'
else:
    print("This is not a bipartite graph")

# maximum weight matching between the left set and the right set
M = nx.max_weight_matching(B)
print(M)
for v1, v2 in M.items():
Пример #30
0
def draw_with_output(g, f):
    print "Drawing: {}".format(f)
    draw(g, f, show=False)
Пример #31
0
# -*- coding: utf-8 -*-

import os
import networkx as nx
from nxpd import draw
from socialgraph.socialgraph import subgraph_by_topic, elect_committee, paint_graph


MAX_EDGES = 300
TOPIC = 'Groceries'

wiki_file = os.path.join('..', 'datasets', 'wiki.graphml')

G = nx.read_graphml(wiki_file)
print("Full graph: {0} nodes {1} edges".format(len(G.nodes()), len(G.edges())))

# Generate smaller graph and override G
subnodes = G.nodes()[:MAX_EDGES]
G = G.subgraph(subnodes)
print("Subgraph: {0} nodes {1} edges".format(len(G.nodes()), len(G.edges())))

# Filter graph by subtopic
G = subgraph_by_topic(G, TOPIC)
draw(G)

committee = elect_committee(G, 20)
print("Committee:")
print({k: len(v) for k, v in committee.items()})
draw(paint_graph(G, committee))
Пример #32
0
 def showg(self):
     draw(self.graph, filename='testmarkovnx.png', show='ipynb', format='png')
     file = open("testmarkovnx.png", "rb")
     image = file.read()
     self.graphw.value=image
Пример #33
0
def dag_drawer(dag, scale=0.7, filename=None, style='color'):
    """Plot the directed acyclic graph (dag) to represent operation dependencies
    in a quantum circuit.

    Note this function leverages
    `pydot <https://github.com/erocarrera/pydot>`_ (via
    `nxpd <https://github.com/chebee7i/nxpd`_) to generate the graph, which
    means that having `Graphviz <https://www.graphviz.org/>`_ installed on your
    system is required for this to work.

    The current release of Graphviz can be downloaded here: <https://graphviz.gitlab.io/download/>.
    Download the version of the sotware that matches your environment and follow the instructions to
    install Graph Visualization Software (Graphviz) on your operating system.

    Args:
        dag (DAGCircuit): The dag to draw.
        scale (float): scaling factor
        filename (str): file path to save image to (format inferred from name)
        style (str): 'plain': B&W graph
                     'color' (default): color input/output/op nodes

    Returns:
            Ipython.display.Image: if in Jupyter notebook and not saving to file,
            otherwise None.

    Raises:
        VisualizationError: when style is not recognized.
        ImportError: when nxpd or pydot not installed.

    Example:
        .. jupyter-execute::

            %matplotlib inline
            from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
            from qiskit.dagcircuit import DAGCircuit
            from qiskit.converters import circuit_to_dag
            from qiskit.visualization import dag_drawer

            q = QuantumRegister(3, 'q')
            c = ClassicalRegister(3, 'c')
            circ = QuantumCircuit(q, c)
            circ.h(q[0])
            circ.cx(q[0], q[1])
            circ.measure(q[0], c[0])
            circ.rz(0.5, q[1]).c_if(c, 2)

            dag = circuit_to_dag(circ)
            dag_drawer(dag)
    """
    try:
        import nxpd
        import pydot  # pylint: disable=unused-import
    except ImportError:
        raise ImportError("dag_drawer requires nxpd and pydot. "
                          "Run 'pip install nxpd pydot'.")

    G = dag.to_networkx()
    G.graph['dpi'] = 100 * scale

    if style == 'plain':
        pass
    elif style == 'color':
        for node in G.nodes:
            n = G.nodes[node]
            n['label'] = node.name
            if node.type == 'op':
                n['color'] = 'blue'
                n['style'] = 'filled'
                n['fillcolor'] = 'lightblue'
            if node.type == 'in':
                n['color'] = 'black'
                n['style'] = 'filled'
                n['fillcolor'] = 'green'
            if node.type == 'out':
                n['color'] = 'black'
                n['style'] = 'filled'
                n['fillcolor'] = 'red'
        for e in G.edges(data=True):
            e[2]['label'] = e[2]['name']
    else:
        raise VisualizationError("Unrecognized style for the dag_drawer.")

    if filename:
        show = False
    elif ('ipykernel' in sys.modules) and ('spyder' not in sys.modules):
        show = 'ipynb'
    else:
        show = True

    try:
        return nxpd.draw(G, filename=filename, show=show)
    except nxpd.pydot.InvocationException:
        raise VisualizationError(
            "dag_drawer requires GraphViz installed in the system. "
            "Check https://www.graphviz.org/download/ for details on "
            "how to install GraphViz in your system.")
Пример #34
0
import networkx as nx
import pygraphviz as pgv
from nxpd import draw, nxpdParams
nxpdParams['show'] = 'ipynb'


G = nx.DiGraph()
G.add_edge("a", "b")
G.add_edge("b", "c")
G.add_edge("c", "d")
G.add_edge("d", "e")
G.add_edge("e", "c")
G.add_edge("a", "d")
G.add_edge("b", "e")

draw(G, layout='circo')
draw(G, layout='dot')
draw(G, layout='neato')
Пример #35
0
G.add_edges_from([('a', 'b', {
    'weight': 2,
    'label': 2
}), ('a', 'c', {
    'weight': 3,
    'label': 3
}), ('a', 'd', {
    'weight': 1,
    'label': 1
}), ('a', 'e', {
    'weight': 3,
    'label': 3
}), ('b', 'c', {
    'weight': 4,
    'label': 4
}), ('c', 'd', {
    'weight': 5,
    'label': 5
}), ('d', 'e', {
    'weight': 4,
    'label': 4
}), ('e', 'a', {
    'weight': 1,
    'label': 1
})])
draw(G, layout='circo')

T = nx.minimum_spanning_tree(G)
for e in T.edges():
    G[e[0]][e[1]]['color'] = 'blue'
draw(G, layout='circo')
Пример #36
0
from nxpd import nxpdParams
import networkx as nx
from nxpd import draw

G = nx.DiGraph()
G.graph['rankdir'] = 'LR'
G.graph['dpi'] = 220
G.add_cycle(range(4))
G.add_node(0, color='red', style='filled', fillcolor='pink')
G.add_node(1, shape='square')
G.add_node(3, style='filled', fillcolor='#00ffff')
G.add_edge(0, 1, color='red', style='dashed')
G.add_edge(3, 3, label='a')
draw(G)