Esempio n. 1
0
def _topology_graph():
    g = Graph(engine='dot',
              graph_attr={
                  'ratio': '0.41',
                  'pad': '0.7 ',
                  'newrank': 'false',
                  'splines': 'compound'
              })

    for isd in ISD.objects.iterator():
        g_isd = _make_isd_graph(isd)

        # hard-coding backbone ISDs to be at the top
        if isd.isd_id in [16, 26]:
            g_isd.attr(rank='source')

        # putting core ASes into a subgraph, laid out at the top
        with g_isd.subgraph() as s:
            s.attr(rank='min')
            for as_ in isd.ases.filter(owner=None, is_core=True):
                _add_as_node(s, as_)

        # putting non-core ASes into a subgraph, without rank
        with g_isd.subgraph() as s:
            s.attr(rank='none')
            for as_ in isd.ases.filter(owner=None, is_core=False):
                _add_as_node(s, as_)

        g.subgraph(g_isd)

    for link in Link.objects.filter(interfaceA__AS__owner=None,
                                    interfaceB__AS__owner=None):
        _add_link(g, link)

    return g
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)
Esempio n. 3
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')
Esempio n. 4
0
class GraphvizVisitor(Visitor):
    def __init__(self):
        self._graph = Graph('equation')
        self._subgraph_terms = Graph('terms')
        self._terms = {}

        self._graph.attr(rankdir='BT', ordering='out')  #, splines='false')
        self._subgraph_terms.attr(rank='same', rankdir='LR')

    def visit(self, node: 'Node') -> Graph:
        node.accept(self)

        self._graph.subgraph(self._subgraph_terms)

        return self._graph

    def visit_equation(self, node: Equation):
        uid = str(uuid4())
        child_uid = node.child.accept(self)

        self._graph.node(uid, label='F', shape='square')
        self._graph.edge(uid, child_uid, penwidth='3')

        return uid

    def visit_unary_op(self, node: UnaryOperationExpression) -> str:
        uid = str(uuid4())
        child_uid = node.child.accept(self)

        self._graph.node(uid,
                         label=OPERATION_SYMBOLS[node.op],
                         shape='invtriangle')
        self._graph.edge(uid, child_uid, penwidth='3')

        return uid

    def visit_binary_op(self, node: BinaryOperationExpression) -> str:
        uid = str(uuid4())
        left_uid = node.left.accept(self)
        right_uid = node.right.accept(self)

        self._graph.node(uid,
                         label=OPERATION_SYMBOLS[node.op],
                         shape='invtriangle')
        self._graph.edge(uid, left_uid, penwidth='3')
        self._graph.edge(uid, right_uid, penwidth='3')

        return uid

    def visit_term(self, node: Term):
        name = node.name
        uid = self._terms[name] if name in self._terms else str(uuid4())
        self._terms[node.name] = uid

        self._subgraph_terms.node(uid, label=name,
                                  shape='circle')  # shape='point')

        return uid
Esempio n. 5
0
def _topology_graph():
    g = Graph(engine='dot', graph_attr={'ratio': '0.41'})
    for isd in ISD.objects.iterator():
        g_isd = _make_isd_graph(isd)
        for as_ in isd.ases.filter(owner=None):
            _add_as_node(g_isd, as_)
        g.subgraph(g_isd)
    for link in Link.objects.filter(interfaceA__AS__owner=None,
                                    interfaceB__AS__owner=None):
        _add_link(g, link)

    return g
Esempio n. 6
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'])
Esempio n. 7
0
def print_graph(fname):
    g = Graph('G', filename=fname, format='png')
    c = {}

    for node in nodes:
        # Note 'cluster_' prefix required naming
        node_name = 'cluster_' + str(node)
        c[node] = Graph(name=node_name)
        c[node].attr(style='filled')
        c[node].attr(color='lightgrey')
        c[node].node_attr.update(style='filled', color='white')
        for v in node_to_v[node]:
            c[node].node(str(v))
        c[node].attr(fontsize='8')
        c[node].attr(label=node_name)
        g.subgraph(c[node])

    for e in edges:
        g.edge(str(e[0]), str(e[1]))
    g.render(fname)
Esempio n. 8
0
def showFamilyTree(root_child_elements):
    """US52 - Displays a GEDCOM file as a family tree and saves as a PDF"""

    family = Graph('Family Tree', comment="family tree")
    family.attr(rankdir='TB')
    cluster = 0
    for element in root_child_elements:
        if isinstance(element, FamilyElement):
            husband = gedcom_parser.get_family_members(element,
                                                       members_type='HUSB')[0]
            wife = gedcom_parser.get_family_members(element, 'WIFE')[0]
            children = gedcom_parser.get_family_members(element,
                                                        members_type='CHIL')

            with family.subgraph(name=f'cluster_{cluster}') as graphGroup:
                graphGroup.attr(label=element.get_pointer())
                with graphGroup.subgraph() as s:
                    s.attr(rank='same')

                    s.node(husband.get_pointer(),
                           label=husband.get_name()[0],
                           color='blue',
                           style='filled',
                           fillcolor='red' if listErrors(husband) else 'white')
                    s.node(str(cluster), shape='point')
                    s.node(wife.get_pointer(),
                           label=wife.get_name()[0],
                           color='lightpink',
                           style='filled',
                           fillcolor='red' if listErrors(wife) else 'white')
                    family.edge(husband.get_pointer(),
                                str(cluster),
                                label='husband')
                    family.edge(str(cluster), wife.get_pointer(), label='wife')

                with graphGroup.subgraph() as s:
                    s.attr(rank='same')

                    s.node(str(cluster) + "_1", shape='point')
                    family.edge(str(cluster),
                                str(cluster) + "_1",
                                label='children')
                    for child in children:
                        s.node(
                            child.get_pointer(),
                            label=child.get_name()[0],
                            color='black',
                            style='filled',
                            fillcolor='red' if listErrors(child) else 'white')
                        family.edge(str(cluster) + "_1", child.get_pointer())
            cluster += 1

    family.view()
    return
Esempio n. 9
0
def display_ontology(ontology):
    graph = Graph()
    graph.attr(rankdir='TB')
    with graph.subgraph(name='cluster_competencies') as c:
        c.attr(rankdir='LR')
        c.attr(label='Competencies')
        for competency in ontology.competencies:
            c.node(competency.identifier, competency.name)
            for child in competency.children:
                c.edge(competency.identifier, child.identifier)
    with graph.subgraph(name='cluster_occupations') as c:
        c.attr(rankdir='RL')
        c.attr(label='Occupations')
        for occupation in ontology.occupations:
            c.node(occupation.identifier, occupation.name)
            for child in occupation.children:
                c.edge(occupation.identifier, child.identifier)

    for edge in ontology.edges:
        graph.edge(edge.competency.identifier, edge.occupation.identifier, style='dashed')

    return graph
Esempio n. 10
0
def draw_SCION_topology(topology_dict, n_labels, e_labels):
    """
    Draws the Scion topology from a topology dictionary
    returned by parse_gen_folder.
    :param dictionary topology_dict: dictionary returned by parse_gen_folder,
            boolean ip_addresses: indicates if node labels are drawn,
            boolean edge_labels: indicates if edge labels are drawn
    :return Dot graph: graph of the SCION topology
    """
    isd_graphs = {}
    dot = Graph(name='topology', filename='topology.gv', comment='SCION-net')
    ISDs = topology_dict["ISD"]
    # draw each ISD graph
    for ISD in ISDs:
        isd_graphs[ISD] = draw_isd_graph(ISD, ISDs[ISD]["AS"], e_labels,
                                         n_labels)
    # put all isd graphs into the same graph
    for ISD in isd_graphs:
        dot.subgraph(isd_graphs[ISD])
    # add edges between ISDs
    dot = draw_inter_ISD_edges(dot, ISDs, e_labels)
    return dot
def draw_SCION_topology(topology_dict, n_labels, l_labels, desc_labels):
    """
    Draws the Scion topology from a topology dictionary
    returned by parse_gen_folder.
    :param dictionary topology_dict: dictionary returned by parse_gen_folder,
            boolean ip_addresses: indicates if node labels are drawn,
            boolean edge_labels: indicates if edge labels are drawn
            dict desc_labels: Dictionary containing labels for ISDs and ASes
    :return Dot graph: graph of the SCION topology
    """
    isd_graphs = {}
    dot = Graph(name='topology', filename='topology.gv', comment='SCION-net')
    ISDs = topology_dict["ISD"]
    # draw each ISD graph
    for ISD in ISDs:
        isd_graphs[ISD] = draw_isd_graph(
            ISD, ISDs[ISD]["AS"], n_labels, l_labels, desc_labels)
    # put all isd graphs into the same graph
    for ISD in isd_graphs:
        dot.subgraph(isd_graphs[ISD])
    # add edges between ISDs
    dot = draw_inter_ISD_edges(dot, ISDs, n_labels)
    return dot
Esempio n. 12
0
def get_data2():
    dot = Graph('G', format="pdf")
    dot.graph_attr['rankdir '] = 'TB'
    dot.attr(compound='true', fixedsize='false')
    data =  json.loads(request.get_data().decode('UTF-8'))
    for key in data.keys():
        with dot.subgraph(name='cluster_' + key) as c:
            for aa, bb in data[key].items():
                c.attr(label=key, bgcolor='#FFEFD5', fontname='Microsoft YaHei', fontcolor='red', style='rounded',gradientangle='270')
                with c.subgraph(name='cluster_' + aa) as d:
                    d.attr(label=aa, color='white', bgcolor='#CCCC99', style='rounded', gradientangle='270',fontname="Microsoft YaHei")
                    d.attr('node', shape='box', style='filled', gradientangle='90')
                    for cc in bb:
                        d.node(cc)
    dot.render(filename="/tmp/tuopu_"+str(today_time()), view=False)
    return data
Esempio n. 13
0
def generateModelDiagram(model, labelsForModel):
    tempDirPath = state.get('tempDirPath')
    filepath = join(tempDirPath, uuid.uuid4().hex + '.gv')
    g = Graph('G', filename=filepath)
    g.format = 'png'

    for i in range(len(model.components)):
        comp = model.components[i]

        with g.subgraph(name='clusterComponent' + str(i)) 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
                        portId = port.portId
                        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(portId, label=name, style='filled')
            c.attr(label=comp.name)
            c.attr(fontsize='20')

    for edge in model.edges:
        portA = edge.getPortAId()
        portB = edge.getPortBId()
        g.edge(portA, portB)

    lStr = None
    if (not len(labelsForModel)):
        lStr = 'No predicted label available yet.'
    elif (len(labelsForModel) == 1):
        lStr = 'Predicted label: ' + labelsForModel[0]
    else:
        lStr = 'Predicted labels: ' + listAsEnumeratedString(labelsForModel)
    g.attr(label=lStr)

    g.render()
    Popen(["xdg-open", filepath + '.png'])
Esempio n. 14
0
def main(data_dir: str):
    nodes = file_io.read_nodes(data_dir)
    edges = file_io.read_edges(data_dir)
    groups = file_io.read_communities(data_dir)

    graph = Graph()
    for node in nodes:
        graph.node(node)
    graph.edges(edges)

    colors = get_colors(len(groups))
    for i in range(len(groups)):
        group = groups[i]
        color = colors[i]
        with graph.subgraph(name='cluster-' + str(i)) as subgraph:
            subgraph.attr(color=color)
            for node in group:
                subgraph.node(node, color=color, style='filled')

    graph.format = 'png'
    graph.render(data_dir + '\\graph.gv')
    graph.view()
Esempio n. 15
0
def draw(nodes):
    nodes_clustered = defaultdict(list)
    for i, node in enumerate(nodes):
        nodes_clustered[node.level].append((i, node))

    g = Graph('tree', format='png')
    g.attr(ordering="out")
    g.attr(nodesep='0.5;')
    for level, node_list in sorted(nodes_clustered.items()):
        # print(level)
        # for node in node_list:
        #     print(node)
        with g.subgraph() as s:
            s.attr(rank='same')
            for data in node_list:
                s.node(str(data[0]),
                       data[1].text,
                       shape=get_shape(data[1].text))

    for i, node in enumerate(nodes):
        if i == 0: continue
        g.edge(str(node.parent), str(i))
    g.view()
Esempio n. 16
0
#!/usr/bin/env python
# http://www.graphviz.org/Gallery/gradient/g_c_n.html

from graphviz import Graph

g = Graph('G', filename='g_c_n.gv')
g.attr(bgcolor='purple:pink', label='agraph', fontcolor='white')

with g.subgraph(name='cluster1') as c:
    c.attr(fillcolor='blue:cyan', label='acluster', fontcolor='white',
           style='filled', gradientangle='270')
    c.attr('node', shape='box', fillcolor='red:yellow',
           style='filled', gradientangle='90')
    c.node('anode')

g.view()
Esempio n. 17
0
#%%
from graphviz import Digraph, Graph, render
from pydot import Subgraph

dot = Digraph(comment = 'The Round Table')

dot.node('a',label='aa')
dot.node('b',label='bb')
dot.edges(['ab','ba'])
dot.render('test.gv')

ps = Digraph(name='pet-shop',node_attr={'shape':'plaintext'})
ps.node('parrot')
ps.node('dead')
ps.edge('parrot','dead')

ps.graph_attr['rankdir'] = 'LR'
ps.edge_attr.update(arrowhead='vee',arrowsize='2')
ps.render('pet-shop')


p = Graph(name='parent')
p.edge('spam','eggs')

c = Graph(name='child',node_attr={'shape':'box'})
c.edge('foo','bar')
p.subgraph(c)
p.render('subgraph')
Esempio n. 18
0
def CoAuGraph(filename, targets):
    coAuthorR = []
    coAuthorRLinks = []
    institution = []
    insAu = []
    
    #access other source author and coauthors relationship
    for element in targets:
        query = "SELECT * FROM `connections` WHERE `sourceScholarID` = '" + element[1] +"' AND ("
        idx = 0
        for target in targets:
            if idx == 0:
                query += "targetScholarID = '" + target[1] +"'"
            else:
                query += " OR targetScholarID = '" + target[1] +"'"
            idx += 1
        query += ")"
        cur.execute(query)

        for row in cur:
            #change id into name
            for target in targets:
                if target[1] == row[0]:
                    rowZero = target[0]
                if target[1] == row[1]:
                    rowOne = target[0]
                    
            #avoid repeated edges
            repeat = 0
            for coA in coAuthorR:
                if (coA[0] == rowOne and coA[1] == rowZero) or (coA[0] == rowZero and coA[1] == rowOne):
                    repeat = 1
                    

            #if not repeated then insert the relationship
            if repeat == 0:
                        
                coAuthorR.append((rowZero, rowOne))


    #access institutions and scholars relationship
    for target in targets:
        query = "SELECT * FROM `institutions` WHERE `scholarID` = '" + target[1] +"'"
        cur.execute(query)

        for row in cur:
            repeat = 0

            #parse the institution name and save in "uni"
            parse = row[1].split(", ")
            for parsed in parse:
                if "University" in parsed:
                    uni = parsed
                    break
                else:
                    uni = row[1]
            
            #check when there are repeated institution name
            for ins in institution:
                if ins == uni:
                    repeat = 1
                    break
            if repeat == 0:
                institution.append(uni)

            #check if repeated institution name and author name
            repeat = 0
            for iA in insAu:
                if target[0] == iA[0] and uni == iA[1]:
                    repeat = 1
                    break
            if repeat == 0:
                insAu.append((target[0], uni))


    g = Graph('G')

    
    cCluster = []
    clusterCounter = 0
    
    #construct multiple clusters and construct its nodes
    for ins in institution:
        cCluster.append(Graph("cluster_" + str(clusterCounter)))
        cCluster[clusterCounter].body.append('style=filled')
        cCluster[clusterCounter].body.append("color=lightgrey")
        cCluster[clusterCounter].body.append('label = "' + ins +'"')
        cCluster[clusterCounter].node_attr.update(style="filled")

        for iA in insAu:
            if ins == iA[1]:
                cCluster[clusterCounter].node(iA[0], fontsize = "13") 
        clusterCounter += 1


    aCluster = Graph("cluster_"+ str(clusterCounter+1))
    aCluster.body.append('style=filled')
    aCluster.body.append("color=orange")
    aCluster.body.append('label = "Author"')
    aCluster.node(search)
    aCluster.node_attr.update(style="filled")


    for num in range(0,clusterCounter):
        g.subgraph(cCluster[num])


    for cAR in coAuthorR:
        g.edge(cAR[0], cAR[1], penwidth="1.7e")

    g.body.append('ratio = compress')
    g.body.append('size = "13,30"')
    g.body.append(' rankdir="BT"')
    g.body.append('splines=line')
    #g.body.append('nodesep="0.3"')


    g.format = "svg"
    g.render("img/"+filename)
Esempio n. 19
0
def FieldAuthorGraph(filename, authorName, targets, isPrintAuthor):
    global search

    institution = []
    insAu = []
    field = []
    fieldAu = []


    #include author when author is selected
    if isPrintAuthor == '1':
        
        #access author's field
        query = "SELECT * FROM `fields` WHERE `scholarID` = '" + search +"'"
        cur.execute(query)

        for row in cur:

            repeat = 0

            #check when there are repeated field name
            for fie in field:
                if fie == row[1]:
                    repeat = 1
            if repeat == 0:
                field.append(row[1])

            #check if repeated field name and author name
            repeat = 0
            for fA in fieldAu:
                if authorName == fA[0] and row[1] == fA[1]:
                    repeat = 1
            if repeat == 0:
                fieldAu.append((authorName, row[1]))

        #access author's institution 
        query = "SELECT * FROM `institutions` WHERE `scholarID` = '" + search +"'"
        cur.execute(query)

        for row in cur:
            repeat = 0
            
            #parse the institution name and save in "uni"
            parse = row[1].split(", ")
            for parsed in parse:
                if "University" in parsed:
                    uni = parsed
                    break
                else:
                    uni = row[1]
                    
            
            #check when there are repeated institution name
            for ins in institution:
                if ins == uni:
                    repeat = 1
                    break
            if repeat == 0:
                institution.append(uni)

            #check if repeated institution name and author name
            repeat = 0
            for iA in insAu:
                if authorName == iA[0] and uni == iA[1]:
                    repeat = 1
                    break
            if repeat == 0:
                insAu.append((authorName, uni))
    
    #access fields and scholars relationship
    for element in targets:
        query = "SELECT * FROM `fields` WHERE `scholarID` = '" + element[1] +"'"
        cur.execute(query)


       
        for row in cur:
            repeat = 0

            #check when there are repeated field name
            for fie in field:
                if fie == row[1]:
                    repeat = 1
            if repeat == 0:
                field.append(row[1])

            #check if repeated field name and author name
            repeat = 0
            for fA in fieldAu:
                if element[0] == fA[0] and row[1] == fA[1]:
                    repeat = 1
            if repeat == 0:
                #find author's name
                fieldAu.append((element[0], row[1]))
    


    #access institutions and scholars relationship
    for element in targets:
        query = "SELECT * FROM `institutions` WHERE `scholarID` = '" + element[1] +"'"
        cur.execute(query)

        for row in cur:
            repeat = 0
            
            #parse the institution name and save in "uni"
            parse = row[1].split(", ")
            for parsed in parse:
                if "University" in parsed:
                    uni = parsed
                    break
                else:
                    uni = row[1]
                    
            
            #check when there are repeated institution name
            for ins in institution:
                if ins == uni:
                    repeat = 1
                    break
            if repeat == 0:
                institution.append(uni)

            #check if repeated institution name and author name
            repeat = 0
            for iA in insAu:
                if element[0] == iA[0] and uni == iA[1]:
                    repeat = 1
                    break
            if repeat == 0:
                insAu.append((element[0], uni))

        
    

    g = Graph('G')
    colorAu= []
    cCluster = []
    clusterCounter = 0
    colorNum = 1
    
    #construct multiple clusters and construct its nodes
    for ins in institution:
        cCluster.append(Graph("cluster_" + str(clusterCounter)))
        cCluster[clusterCounter].body.append('style=filled')
        cCluster[clusterCounter].body.append("color=lightgrey")
        cCluster[clusterCounter].body.append('label = "' + ins +'"')
        cCluster[clusterCounter].node_attr.update(style="filled")

        for iA in insAu:
            #special case for the person it is searching for
            if ins == iA[1] and iA[0] == authorName:
                cCluster[clusterCounter].node(authorName, color = "cyan")
                colorAu.append((authorName, "cyan"))
                
            elif ins == iA[1]:
                cCluster[clusterCounter].node(iA[0], colorscheme="paired12",color = str(colorNum)) 
                colorAu.append((iA[0], colorNum)) #give each author a color
                #control colorNum
                colorNum += 1
                if colorNum >= 13:
                    colorNum = 1
        clusterCounter += 1
        

    fieldCluster = Graph("cluster_" + str(clusterCounter+1))
    fieldCluster.body.append('style=filled')
    fieldCluster.body.append("color=gray72")
    fieldCluster.body.append('label = "Field of Study"')
    fieldCluster.node_attr.update(style="filled")
    for fie in field:
        for fA in fieldAu:
            if fA[0] == authorName and fA[1] == fie:
                fieldCluster.node(fie, color="cyan")
            else:
                fieldCluster.node(fie)



    for x in range(0, clusterCounter):
        g.subgraph(cCluster[x])
    g.subgraph(fieldCluster)

    for fA in fieldAu:
        #find the color of that author
        for cA in colorAu:
            if fA[0] == cA[0]:
                g.edge(fA[0],fA[1], colorscheme="paired12", color = str(cA[1]), penwidth="2") #create edge

    g.body.append('ratio = compress')
    g.body.append('size = "8,30"')
    g.body.append(' rankdir="LR"')
    g.body.append('splines=line')
    #g.edge_attr.update(style='filled', color='green')
    g.format = "svg"
    g.render("img/"+filename)
Esempio n. 20
0
    def incidence(self,
                  timeline: Iterable[Optional[List[int]]],
                  num_vars: int,
                  colors: List,
                  edges: List,
                  inc_file: str = 'IncidenceGraphStep',
                  view: bool = False,
                  fontsize: Union[str, int] = 16,
                  penwidth: float = 2.2,
                  basefill: str = 'white',
                  sndshape: str = 'diamond',
                  neg_tail: str = 'odot',
                  var_name_one: str = '',
                  var_name_two: str = '',
                  column_distance: float = 0.5) -> None:
        """
        Creates the incidence graph emphasized for the given timeline.

        Parameters
        ----------
        timeline : Iterable of: None | [int...]
            None if no variables get highlighted in this step.
            Else the 'timeline' provides the set of variables that are
            in the bag(s) under consideration. This function computes all other
            variables that are involved in this timestep using the 'edgelist'.
        num_vars : int
            Count of variables that are used in the clauses.
        colors : Iterable of color
            Colors to use for the graph parts.
        inc_file : string
            Basis for the file created, gets appended with the step number.
        view : bool
            If true opens the created file after creation. Default is false.
        basefill : color
            Background color of all nodes. Default is 'white'.
        sndshape : string
            Description of the shape for nodes with the variables. Default diamond.
        neg_tail : string
            Description of the shape of the edge-tail indicating a
            negated variable. Default is 'odot'.
        column_distance : float
            Changes the distance between both partitions, measured in image-units.
            Default is 0.5

        Returns
        -------
        None, but outputs the files with the graph for each timestep.

        """
        _filename = self.outfolder / inc_file

        clausetag_n = var_name_one + '%d'
        vartag_n = var_name_two + '%d'

        g_incid = Graph(inc_file,
                        strict=True,
                        graph_attr={
                            'splines': 'false',
                            'ranksep': '0.2',
                            'nodesep': str(float(column_distance)),
                            'fontsize': str(int(fontsize)),
                            'compound': 'true'
                        },
                        edge_attr={
                            'penwidth': str(float(penwidth)),
                            'dir': 'back',
                            'arrowtail': 'none'
                        })
        with g_incid.subgraph(name='cluster_clause',
                              edge_attr={'style': 'invis'},
                              node_attr={
                                  'style': 'rounded,filled',
                                  'fillcolor': basefill
                              }) as clauses:
            clauses.attr(label='clauses')
            clauses.edges([(clausetag_n % (i + 1), clausetag_n % (i + 2))
                           for i in range(len(edges) - 1)])

        g_incid.attr('node',
                     shape=sndshape,
                     penwidth=str(float(penwidth)),
                     style='dotted')
        with g_incid.subgraph(name='cluster_ivar',
                              edge_attr={'style': 'invis'}) as ivars:
            ivars.attr(label='variables')
            ivars.edges([(vartag_n % (i + 1), vartag_n % (i + 2))
                         for i in range(num_vars - 1)])
            for i in range(num_vars):
                g_incid.node(vartag_n % (i + 1),
                             vartag_n % (i + 1),
                             color=colors[(i + 1) % len(colors)])

        g_incid.attr('edge', constraint='false')

        for clause in edges:
            for var in clause[1]:
                if var >= 0:
                    g_incid.edge(clausetag_n % clause[0],
                                 vartag_n % var,
                                 color=colors[var % len(colors)])
                else:
                    g_incid.edge(clausetag_n % clause[0],
                                 vartag_n % -var,
                                 color=colors[-var % len(colors)],
                                 arrowtail=neg_tail)

        # make edgelist variable-based (varX, clauseY), ...
        #  var_cl_iter [(1, 1), (4, 1), ...
        var_cl_iter = tuple(flatten([[(x, y[0]) for x in y[1]]
                                     for y in edges]))

        bodybaselen = len(g_incid.body)
        for i, variables in enumerate(timeline, start=1):  # all timesteps

            # reset highlighting
            g_incid.body = g_incid.body[:bodybaselen]
            if variables is None:
                g_incid.render(view=view,
                               format='svg',
                               filename=str(_filename) + str(i))
                continue

            emp_clause = {
                var_cl[1]
                for var_cl in var_cl_iter if abs(var_cl[0]) in variables
            }

            emp_var = {
                abs(var_cl[0])
                for var_cl in var_cl_iter if var_cl[1] in emp_clause
            }

            for var in emp_var:
                _vartag = vartag_n % abs(var)
                _style = 'solid,filled' if var in variables else 'dotted,filled'
                g_incid.node(_vartag,
                             _vartag,
                             style=_style,
                             fillcolor='yellow')

            for clause in emp_clause:
                g_incid.node(clausetag_n % clause,
                             clausetag_n % clause,
                             fillcolor='yellow')

            for edge in var_cl_iter:
                (var, clause) = edge

                _style = 'solid' if clause in emp_clause else 'dotted'
                _vartag = vartag_n % abs(var)

                if var >= 0:
                    g_incid.edge(clausetag_n % clause,
                                 _vartag,
                                 color=colors[var % len(colors)],
                                 style=_style)
                else:  # negated variable
                    g_incid.edge(clausetag_n % clause,
                                 _vartag,
                                 color=colors[-var % len(colors)],
                                 arrowtail='odot',
                                 style=_style)

            g_incid.render(view=view,
                           format='svg',
                           filename=str(_filename) + str(i))
Esempio n. 21
0
class FamilyGraph:
    """Class for creating Family Graphs.

    Attributes:
        family (Family): Instance of the Family class.
        graph (Graph): Instance of the Graph class from graphviz.
    """

    _dummy_node_attrs = {
        "shape": "point",
        "style": "invis",
        "height": "0",
        "width": "0",
        "margin": "0",
    }

    def __init__(self, family: Family, layout: str) -> None:
        """Initialises the FamilyGraph object.

        Args:
            family: The family to be viewed.
            layout: The graphviz layout option.
        """
        self.family = family
        self.graph = Graph(  # type: ignore
            name="My Family",
            graph_attr={
                "layout": layout,
                "concentrate": "true",
                "overlap": "scale",
            },
            strict=True,
        )
        self._link_family()

    def render_family(self) -> None:
        """Produces My Family.gv and My Family.gv.pdf files."""
        self.graph.render(view=True)  # type: ignore

    def _link_family(self) -> None:
        """Creates the linkages between each member of the family."""
        for couple in self.family.couples.values():
            self._couple_connection(couple)

        for person in self.family.values():
            self._person_node(person)
            if person.parents:
                self._link_parents(person)

    def _person_node(self, person: Person) -> None:
        """For adding a node containing a persons key info."""
        self.graph.node(  # type: ignore
            person.identifier,
            label="<" + person.to_html() + ">",
            shape="rectangle",
            color="black",
        )

    def _dummy_node(self, combined_id: str) -> None:
        """For creating empty nodes for linking purposes."""
        self.graph.node(combined_id, **self._dummy_node_attrs)  # type: ignore

    def _couple_connection(self, couple: Couple) -> None:
        """Connects a couple."""
        with self.graph.subgraph() as c:  # type: ignore
            c.attr(rank="same")  # type: ignore
            for person in [couple.left, couple.right]:
                c.node(  # type: ignore
                    person.identifier,
                    label="<" + person.to_html() + ">",
                    shape="rectangle",
                    color="black",
                )
            c.edge(couple.left.identifier,
                   couple.right.identifier,
                   color="red")  # type: ignore

    def _relative_edge(self, tail: str, head: str) -> None:
        """Adds an edge between two blood relatives."""
        self.graph.edge(tail, head)  # type: ignore

    def _link_parents(self, person: Person) -> None:
        """Links parents to their children via a dummy node."""
        if len(person.parents) == 1:
            # & is arbitrary, used to make dummy node ID different to person node
            comb_id = f"{person.parents[0]}&"
        else:
            comb_id = "".join(sorted(person.parents))

        for parent in person.parents:
            self._relative_edge(parent, comb_id)

        self._dummy_node(comb_id)
        self._relative_edge(comb_id, person.identifier)
Esempio n. 22
0
    def draw(self, mode, user_info, graphStyle=[]):
        output = user_info.fileName + "-20000-SM-M-01_picture"
        data = user_info.depStruct
        edgeList = []
        nodeDict = {}
        structDict = {}
        colorDict = {}
        # deal with data
        temp = data.splitlines()
        subCount = 0
        for item in temp:
            if (";" in item or ";" in item) and "#" not in item:
                s_item = item.strip(" ")
                temp_list = re.split("[;;]", s_item)
                temp_list = list(
                    filter(lambda x: x != '' and x != ' ', temp_list))
                for item_t in temp_list:
                    edge = item_t.replace(";", "").replace(";", "")
                    t = re.split("[,,]", edge)
                    t = sorted(set(t), key=t.index)
                    for i in range(len(t)):
                        t[i] = t[i].strip(" ")
                    structDict["cluster{:0>5d}".format(subCount)] = t
                    colorDict["cluster{:0>5d}_style".format(
                        subCount)] = graphStyle[subCount] if subCount < len(
                            graphStyle) else {}
                    subCount += 1
            elif "#" in item and ";" not in item and ";" not in item:
                temp_list1 = re.split("[#]", item)
                temp_list1 = list(
                    filter(lambda x: x != '' and x != ' ', temp_list1))
                for item_t in temp_list1:
                    edge = item.replace("#", "")
                    edgeList.append(edge)
            else:
                return ""
        edgeList = list(filter(lambda x: x != '', edgeList))

        #print(structDict)

        #print(nodeDict)
        # draw graph
        subG = []
        linkPoint = []
        graph = Graph(comment="graph",
                      format="png",
                      graph_attr={'rank': 'max'})
        graph.attr(_attributes={
            'compound': 'true',
            'rankdir': 'TB',
            'center': 'true'
        })
        for sub, content in structDict.items():
            subg = Graph(name=sub,
                         graph_attr={
                             'center': 'true',
                             'rankdir': 'LR',
                             'rank': 'max',
                             'ordering': 'out'
                         },
                         node_attr={
                             'fontname': 'KaiTi',
                             'shape': 'box'
                         })
            subg.attr(_attributes={'compound': 'true', 'color': 'black'})
            nodes = []
            for i in range(len(content) - 1, -1, -1):
                subg.node(
                    content[i],
                    self.formatContent(content[i],
                                       colorDict[sub + "_style"]["lineLen"]))
                nodes.append(content[i])

                if len(content) % 2 == 0 and i == len(content) / 2:
                    subg.node(sub + "e", "", {
                        'height': '0',
                        'width': '0',
                        'color': 'white'
                    })
                    linkPoint.append(sub + "e")
                    nodes.append(sub + "e")
                if len(content) % 2 == 1 and i == (len(content) - 1) / 2:
                    linkPoint.append(content[i])

            #for i in range(1, len(nodes)):
            #subg.edge(nodes[i-1], nodes[i])
            subg = self.apply_styles(subg, colorDict[sub + "_style"])
            graph.subgraph(subg)
            subG.append(sub)

        for i in range(1, len(subG)):
            graph.edge(linkPoint[i - 1],
                       linkPoint[i],
                       _attributes={
                           'ltail': subG[i - 1],
                           'lhead': subG[i]
                       })

        # single arrow
        for edge in edgeList:
            nodes = edge.split("-")
            node1 = nodes[0].strip(" ")
            node2 = nodes[1].strip(" ")
            if node1 in nodeDict:
                nodeDict[node1].append(node2)
            else:
                nodeDict[node1] = [node2]

        for node, children in nodeDict.items():
            for child in children:
                graph.edge(node, child)

        #print(graph.source)
        if mode == "preview":
            self.preview(graph)
        else:
            filename = output if output != "" else self.genName()
            self.save(graph, filename)
            user_info.picPath = self.saveDir + filename + ".png"
        return user_info
Esempio n. 23
0
        for igw in item[1].keys():
            resources.append(Resources.IGW(igw, item[1][igw]))

VPCs = [x for x in resources if x.getType() == 'VPC']
Subnets = [x for x in resources if x.getType() == 'Subnet']
EC2_instance = [x for x in resources if x.getType() == 'EC2']
NACLs = [x for x in resources if x.getType() == 'NACL']
SGs = [x for x in resources if x.getType() == 'Security Group']
RoutesTables = [x for x in resources if x.getType() == 'RouteTable']
Routes = [x for x in resources if x.getType() == 'Route']
IGWs = [x for x in resources if x.getType() == 'IGW']

g = Graph("G", engine='fdp')

with open('accesscontrol.txt', 'w') as fp:
    with g.subgraph(name='clusterVPC') as v:
        for igw in IGWs:
            # g.edge('clusterVPC', "IGW\n" + igw.name)
            v.node("IGW\n" + igw.name)
        for NACL in NACLs:
            for net in NACL.subnet:
                v.edge("clusterSUBNET " + net.split('.')[1],
                       f"NACL\n{NACL.name}")
            logger(NACL, fp)

        for route in RoutesTables:
            v.edge("ROUTE\n" + route.name,
                   "IGW\n" + route.route['gateway_id'].split('.')[1])
        else:
            for route in Routes:
                v.edge("ROUTE\n" + route.name,
Esempio n. 24
0
class Visualization:

    BUGGY_NODE_COLOR = 'red'
    PROVENANCE_EDGE_COLOR = 'dodgerblue'
    INVALID_COLOR = 'darkorange1'
    VALID_COLOR = 'darkolivegreen1'
    NODE_IN_EVALUATION_COLOR = 'gold2'
    PROV_PRUNED_NODE_COLOR = 'grey55'

    def __init__(self, exec_tree: ExecutionTree):
        self.exec_tree = exec_tree

    def generate_exec_tree(self, graph_name='exec_tree'):
        file_name = "{}.gv".format(graph_name)
        self.graph = Graph(graph_name, filename=file_name)
        self.graph.attr('node', shape='box')
        self.graph.attr('graph', ordering='out')
        root_node = self.exec_tree.root_node
        root_node_color = None
        if root_node.validity is Validity.UNKNOWN:
            root_node_color = 'white'
        elif root_node.validity is Validity.INVALID:
            root_node_color = self.INVALID_COLOR
        elif root_node.validity is Validity.VALID:
            root_node_color = self.VALID_COLOR
        elif root_node.validity is Validity.NOT_IN_PROV:
            root_node_color = self.PROV_PRUNED_NODE_COLOR

        self.graph.node(str(root_node.ev_id),
                        root_node.get_name(),
                        fillcolor=root_node_color,
                        style='filled')  # root node
        self.navigate(root_node)
        eval_node = self.exec_tree.node_under_evaluation
        if eval_node is not None:
            self.graph.node(str(eval_node.ev_id),
                            str(eval_node.get_name()),
                            fillcolor=self.NODE_IN_EVALUATION_COLOR,
                            style='filled')
        buggy_node = self.exec_tree.buggy_node
        if buggy_node is not None:
            self.graph.node(str(buggy_node.ev_id),
                            str(buggy_node.get_name()),
                            fillcolor=self.BUGGY_NODE_COLOR,
                            style='filled')
        if self.exec_tree.dependencies is not None:
            for d in self.exec_tree.dependencies:
                if not isinstance(d, Evaluation):
                    self.graph.edge(str(d.source.ev_id),
                                    str(d.target.ev_id),
                                    None,
                                    color=self.PROVENANCE_EDGE_COLOR,
                                    dir='back')

    def view_exec_tree(self, graph_name='exec_tree'):
        self.generate_exec_tree(graph_name)
        self.graph.view()

    def navigate(self, node: Node):
        chds = node.childrens
        for n in chds:
            self.graph.edge(str(node.ev_id), str(n.ev_id), None, dir='forward')
            if n.validity == Validity.INVALID:
                self.graph.node(str(n.ev_id),
                                str(n.get_name()),
                                fillcolor=self.INVALID_COLOR,
                                style='filled')
            elif n.validity == Validity.VALID:
                self.graph.node(str(n.ev_id),
                                str(n.get_name()),
                                fillcolor=self.VALID_COLOR,
                                style='filled')
            elif n.validity == Validity.UNKNOWN:
                self.graph.node(str(n.ev_id), str(n.get_name()))
            elif n.validity is Validity.NOT_IN_PROV:
                self.graph.node(str(n.ev_id),
                                str(n.get_name()),
                                fillcolor=self.PROV_PRUNED_NODE_COLOR,
                                style='filled')

        if len(chds) > 0:
            g = Graph()
            for c in chds:
                g.node(str(c.ev_id))
            g.graph_attr['rank'] = 'same'
            self.graph.subgraph(g)

        for n in chds:
            self.navigate(n)
Esempio n. 25
0
        if "common/platform/os_wrapper" in file or "server/plugin/" in file or "utils/encdec" in file:
            touched = True
            if commit not in ai_data_trans:
                ai_data_trans.append(commit)

        if "client/communication_adapter" in file or "server/communication_adapter" in file:
            touched = True
            if commit not in cli_server_comm:
                cli_server_comm.append(commit)
    all_commits.append(commit)

graph = Graph(comment='Semantic History Commit Slicing')
graph.attr(rankdir='RL')
graph.attr('node', shape='circle')
for commit in all_commits:
    with graph.subgraph() as s:
        s.attr(rank='same')
        s.node("all_" + str(all_commits.index(commit)), commit.hexsha[:7])
        if commit in plugin_config:
            s.node("plugin_config_" + str(plugin_config.index(commit)),
                   commit.hexsha[:7])
        if commit in plugin_integration:
            s.node(
                "plugin_integration_" + str(plugin_integration.index(commit)),
                commit.hexsha[:7])
        if commit in plugin_lifecycle:
            s.node("plugin_lifecycle_" + str(plugin_lifecycle.index(commit)),
                   commit.hexsha[:7])
        if commit in sdk_manage:
            s.node("sdk_manage_" + str(sdk_manage.index(commit)),
                   commit.hexsha[:7])
Esempio n. 26
0
from graphviz import Graph

# use subgraph to create a group of nodes
g = Graph(name='sample6', format='png')

g.attr('node', shape='circle')

with g.subgraph(name='cluster_root') as c:
    c.attr(color='white', label='root')
    #c.node('0')
    c.edges([('0', '1'), ('0', '2')])

with g.subgraph(name='cluster_01') as c:
    c.attr(color='blue')
    c.edges([('1', '3'), ('1', '4')])

    with c.subgraph(name='cluster_013') as cc0:
        cc0.attr(color='darkgreen', label='cluster_013')
        cc0.node('3')
    with c.subgraph(name='cluster_014') as cc1:
        cc1.attr(color='orchid1', label='cluster_014')
        cc1.node('4')

with g.subgraph(name='cluster_02') as c:
    c.attr(color='blue')
    c.edges([('2', '5'), ('2', '6')])

    with c.subgraph(name='cluster_025') as cc0:
        cc0.attr(color='cyan', label='cluster_025')
        cc0.node('5')
Esempio n. 27
0
#!/usr/bin/env python
# http://www.graphviz.org/Gallery/gradient/g_c_n.html

from graphviz import Graph

g = Graph('G', filename='g_c_n.gv')
g.attr(bgcolor='purple:pink', label='agraph', fontcolor='white')

with g.subgraph(name='cluster1') as c:
    c.attr(fillcolor='blue:cyan',
           label='acluster',
           fontcolor='white',
           style='filled',
           gradientangle='270')
    c.attr('node',
           shape='box',
           fillcolor='red:yellow',
           style='filled',
           gradientangle='90')
    c.node('anode')

g.view()
Esempio n. 28
0
    def draw_lattice(self):
        """
        Visualizes the surface code.

        Returns:
            A graphviz.Graph object
        """

        # Author: Nicholas
        # Version: 0.2.1

        # graph construction is now reliant on internal coordinates
        # current layout: 2020-07-29 2:00 pm PT (horizontal flip, square)
        # requirements: graphviz (package and 3rd-party python library)
        # specifically "fdp" engine, which requires version 2.38
        # on windows, due to a bug in the recent release
        # the Graph object can, for example, do the following:
        # g.source -> string that can be plugged into a graphviz compiler
        # g.render() -> produces an image (can be specified)
        # g (in Jupyter notebook) -> displays an SVG

        def add_edge(graph, isZ, tail, head):
            if isZ:
                graph.edge(tail, head, color="green")
            else:
                graph.edge(tail, head, color="orange")

        visual = Graph(name="lattice", engine="fdp", strict=True)
        visual.attr(splines="false", nodesep="0.6")
        visual.attr("node", shape="circle", fixedsize="true", width="0.6")
        visual.attr("edge", penwidth="10")

        # create nodes
        # y-coord must be flipped due to implementation

        # white data qubits
        with visual.subgraph() as dqb:
            for coord, DQB in self.coord_table[1].items():
                index = DQB[1]
                node_pos = "%f,%f!" % (coord[0], -coord[1])
                dqb.node("D" + str(index), pos=node_pos)

        # black measurement qubits
        with visual.subgraph() as mqb:
            mqb.attr("node", style="filled", fontcolor="white", color="black")
            for coord, MQB in self.coord_table[0].items():
                index = MQB[1]
                node_pos = "%f,%f!" % (coord[0], -coord[1])
                mqb.node("M" + str(index), pos=node_pos)

        # create edges
        MQB_table = self.build_MQB_table()
        for i in range(self.d**2 - 1):
            MQB = MQB_table[i]
            isZ = MQB[0]
            DQB = MQB[1]
            name = "M" + str(i)

            a = DQB[0]
            c = DQB[3]
            if isZ:  #abdc
                b = DQB[1]
                d = DQB[2]
            else:  #adbc
                d = DQB[1]
                b = DQB[2]

            if a != None: add_edge(visual, isZ, "D" + str(a), name)
            if b != None: add_edge(visual, isZ, "D" + str(b), name)
            if c != None: add_edge(visual, isZ, name, "D" + str(c))
            if d != None: add_edge(visual, isZ, name, "D" + str(d))

        return visual
Esempio n. 29
0
#!/usr/bin/env python
# fdpclust.py - http://www.graphviz.org/content/fdpclust

from graphviz import Graph

g = Graph('G', filename='fdpclust.gv', engine='fdp')

g.node('e')

with g.subgraph(name='clusterA') as a:
    a.edge('a', 'b')
    with a.subgraph(name='clusterC') as c:
        c.edge('C', 'D')

with g.subgraph(name='clusterB') as b:
    b.edge('d', 'f')

g.edge('d', 'D')
g.edge('e', 'clusterB')
g.edge('clusterC', 'clusterB')

g.view()
        for iA in insAu:
            if ins == iA[1]:
                cCluster[clusterCounter].node(iA[0], fontsize = "13") 
        clusterCounter += 1


    aCluster = Graph("cluster_"+ str(clusterCounter+1))
    aCluster.body.append('style=filled')
    aCluster.body.append("color=orange")
    aCluster.body.append('label = "Author"')
    aCluster.node(search)
    aCluster.node_attr.update(style="filled")


    for num in range(0,clusterCounter):
        g.subgraph(cCluster[num])
    #g.subgraph(aCluster)

    for cAR in coAuthorR:
        g.edge(cAR[0], cAR[1], penwidth="2")

    g.body.append('ratio = compress')
    g.body.append('size = "13,30"')
    g.body.append(' rankdir="BT"')
    g.body.append('splines=ortho')
    #g.body.append('nodesep="0.3"')


    g.format = "svg"
    g.render("img/"+filename)
    for fie in field:
        for fA in fieldAu:
            if fA[0] == search and fA[1] == fie:
                fieldCluster.node(fie, color="cyan")
            else:
                fieldCluster.node(fie)








    for x in range(0, clusterCounter):
        g.subgraph(cCluster[x])
    g.subgraph(fieldCluster)

    for fA in fieldAu:
        #find the color of that author
        for cA in colorAu:
            if fA[0] == cA[0]:
                print(cA)
                g.edge(fA[0],fA[1], colorscheme="paired12", color = str(cA[1]), penwidth="2") #create edge

    g.body.append('ratio = compress')
    g.body.append('size = "9,30"')
    g.body.append(' rankdir="LR"')
    g.body.append('splines=ortho')
    #g.edge_attr.update(style='filled', color='green')
    g.format = "svg"
Esempio n. 32
0
c1 = Graph('cluster_'+class_list[1])
c1.node_attr.update(color=col[1],shape =shp[1])
for key in key_list:
    if m_class[key] == class_list[1]:
        c1.node(key)


c2 = Graph('cluster_'+class_list[2])
c2.node_attr.update(color=col[2],shape =shp[2])
for key in key_list:
    if m_class[key] == class_list[2]:
        c2.node(key)


c3 = Graph('cluster_'+class_list[3])
c3.node_attr.update(color=col[3],shape =shp[3])
for key in key_list:
    if m_class[key] == class_list[3]:
        c3.node(key)
        
## adding subgraphs to main graph
g.subgraph(c0)
g.subgraph(c3)
g.subgraph(c1)
g.subgraph(c2)

## adding edges based on the given condition
for x in combinations(key_list,2):
    if pearsonr(m_ave_values[x[0]],m_ave_values[x[1]])[0] > 0.98:
        g.edge(x[0], x[1], penwidth = str(0.03/float(1-pearsonr(m_ave_values[x[0]],m_ave_values[x[1]])[0])) )
g.view()
Esempio n. 33
0
def generateGraph(functionName, flow):
    g = Graph('G', filename=functionName, engine='dot')
    g.attr(rank='same')
    g.attr(rankdir='LR')
    g.graph_attr = {
        'fontname': 'MS Gothic',
        'fontsize': '10',
    }
    g.node_attr = {
        'shape': 'plaintext',
        'fontname': 'MS Gothic',
        'fontsize': '10',
        'fixedsize': 'true',
        'width': '2.165',  # inch
        'height': '0.472'
    }  # inch

    nodes = []
    node = {'level': None, 'index': None, 'shape': None, 'label': None}
    index = 0
    level = 1
    maxLvl = 1
    connectWith = None
    branches = []
    for element in flow:
        elementID = element['comment']
        if elementID == 'fc:end':
            # If fc:end is in flow, we have to return one level back. This element
            # is empty element, no node is needed.
            level -= 1
            connectWith = branches[-1]
            del (branches[-1])
            continue
        if elementID == 'fc:else':
            connectWith = branches[-1]
            continue
        element['level'] = level
        element['index'] = index
        shapePath = os.path.split(os.path.abspath(__file__))[0]
        shape = os.path.join(shapePath, SHAPES[elementID])
        element['shape'] = shape
        element['connectWith'] = connectWith
        connectWith = index

        if elementID == 'fc:ifBranch' or elementID == 'fc:forLoop':
            # For loop and if we create branch which means going into new level.
            level += 1
            branches.append(index)
        if level > maxLvl:
            maxLvl = level
        nodes.append(dict(element))
        index += 1

    # Create level structure
    for level in range(1, maxLvl + 1):
        g1 = Graph(str(level))
        for node in nodes:
            if node['level'] == level:
                index = str(node['index'])
                label = node['label']
                shape = node['shape']
                comment = node['comment']

                # Only startStop element is smaller. Others are bigger.
                if comment == 'fc:startStop':
                    g1.node(index,
                            label=label,
                            image=shape,
                            width="1.299",
                            height="0.394")
                else:
                    g1.node(index, label=label, image=shape)
        g.subgraph(g1)

    # Connect nodes
    branches = []
    label = ''
    for node in nodes:
        connectWith = node['connectWith']
        index = node['index']
        comment = node['comment']

        if connectWith == None:
            continue
        else:
            label = ''
            connectingNode = nodes[connectWith]
            if connectingNode['comment'] == 'fc:ifBranch':
                if index == connectWith + 1:
                    label = 'TRUE'
                else:
                    if node['level'] != connectingNode['level']:
                        label = 'FALSE'
            if (connectingNode['comment'] == 'fc:forLoop'
                    and node['level'] != connectingNode['level']):
                label = 'loop'

            g.edge(str(connectWith), str(index), label=label)

    if VIEW:
        g.view(directory=DEST)
    else:
        g.render(directory=DEST)
Esempio n. 34
0
    def plot(self):
        g = Graph(format='png')
        styles = {
            'graph': {
                'rankdir': self.direction,
                'splines': 'line',
                'label': 'Restricted Boltzmann Machine',
                'labelloc': 't', ## t: top, b: bottom, c: center
                'labeljust': 'c', ## l: left, r: right, c: center
            },
            'edge':{
                'color': 'black',
                # 'constraint': 'false',
                'style': 'filled',
            }
        }
        self.add_styles(g, styles)

        vLayer = Graph('cluster_0')
        styles = {
            'graph': {
                'rankdir': 'LR',
                'splines': 'line',
                'label': 'Visible Units',
                'labelloc': 't', ## t: top, b: bottom, c: center
                'labeljust': 'c', ## l: left, r: right, c: center
            },
            'node': {
                'shape': 'circle',
                'color': 'lightblue3',
                'label': '',
            },
            'edge':{
                'color': 'black',
                'constraint': 'false',
                'style': 'filled',
            }
        }
        self.add_styles(vLayer, styles)
        vNodes = ['v%d'%i for i in range(self.numVisible)]
        vNodes[-2] = (vNodes[-2], {'label': '...', 'style': '', 'shape': 'circle', 'color':'white'})
        self.add_nodes(vLayer, vNodes)


        hLayer = Graph('cluster_1')
        styles = {
            'graph': {
                'rankdir': 'LR',
                'splines': 'line',
                'label': 'Hidden Units',
                'labelloc': 'b', ## t: top, b: bottom, c: center
                'labeljust': 'c', ## l: left, r: right, c: center
            },
            'node': {
                'shape': 'circle',
                'color': 'red3',
                'label': '',
            },
            'edge':{
                'color': 'black',
                'constraint': 'false',
                'style': 'filled',
            }
        }
        self.add_styles(hLayer, styles)
        hNodes = ['h%d'%i for i in range(self.numHidden)]
        hNodes[-2] = (hNodes[-2], {'label': '...', 'style': '', 'shape': 'circle', 'color':'white'})
        self.add_nodes(hLayer, hNodes)

        g.subgraph(hLayer)
        g.subgraph(vLayer)
        edges = []
        for vn in vNodes:
            for hn in hNodes:
                if isinstance(vn, tuple):
                    if isinstance(hn, tuple):
                        edges.append(((vn[0], hn[0]), {'style':'invis'}))
                    else:
                        edges.append(((vn[0], hn), {'style': 'invis'}))
                else:
                    if isinstance(hn, tuple):
                        edges.append(((vn, hn[0]), {'style':'invis'}))
                    else:
                        edges.append((vn, hn))
        self.add_edges(g, edges)
        print (g.source)
        g.view()