Esempio n. 1
0
def apply(trie: Trie, parameters: Optional[Dict[str, Any]] = None) -> Graph:
    """
    Represents the trie

    Parameters
    -----------------
    trie
        Trie
    parameters
        Parameters, including:
        - Parameters.FORMAT: the format of the visualization

    Returns
    -----------------
    graph
        Representation of the trie
    """
    if parameters is None:
        parameters = {}

    image_format = exec_utils.get_param_value(Parameters.FORMAT, parameters, "png")

    filename = tempfile.NamedTemporaryFile(suffix='.gv')
    viz = Graph("pt", filename=filename.name, engine='dot', graph_attr={'bgcolor': 'transparent'})
    viz.attr('node', shape='ellipse', fixedsize='false')

    draw_recursive(trie, None, viz)

    viz.attr(overlap='false')
    viz.attr(splines='false')
    viz.attr(rankdir='LR')
    viz.format = image_format

    return viz
Esempio n. 2
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. 3
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')
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')
Esempio n. 5
0
def apply(
    tree: ProcessTree,
    parameters: Optional[Dict[Union[str, Parameters], Any]] = None
) -> graphviz.Graph:
    """
    Obtain a Process Tree representation through GraphViz

    Parameters
    -----------
    tree
        Process tree
    parameters
        Possible parameters of the algorithm

    Returns
    -----------
    gviz
        GraphViz object
    """
    if parameters is None:
        parameters = {}

    parameters = copy(parameters)
    parameters[ROOT_NODE_PARAMETER] = tree

    filename = tempfile.NamedTemporaryFile(suffix='.gv')

    bgcolor = exec_utils.get_param_value(Parameters.BGCOLOR, parameters,
                                         "transparent")

    viz = Graph("pt",
                filename=filename.name,
                engine='dot',
                graph_attr={'bgcolor': bgcolor})
    viz.attr('node', shape='ellipse', fixedsize='false')

    image_format = exec_utils.get_param_value(Parameters.FORMAT, parameters,
                                              "png")

    enable_deepcopy = exec_utils.get_param_value(Parameters.ENABLE_DEEPCOPY,
                                                 parameters, False)

    if enable_deepcopy:
        # since the process tree object needs to be sorted in the visualization, make a deepcopy of it before
        # proceeding
        tree = deepcopy(tree)
        generic.tree_sort(tree)

    repr_tree_2(tree, viz, parameters)

    viz.attr(overlap='false')
    viz.attr(splines='false')
    viz.format = image_format

    return viz
Esempio n. 6
0
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()
Esempio n. 7
0
def build_graph(from_list, to_list):
    dot = Graph(strict=True)
    dot.format = 'svg'
    for e in from_list:
        for p in to_list:
            if e == p:
                continue
            if not '\t' + e in dot.body:
                dot.node(e)
            if not '\t' + p in dot.body:
                dot.node(p)
            dot.edge(e, p)
    print(dot.source)  # doctest: +NORMALIZE_WHITESPACE
    dot.render()
Esempio n. 8
0
 def make_graph(self, name: str, description: str) -> None:
     g = Graph('World', filename='world.gv', engine='neato')
     g.attr(label=description)
     g.attr('node', colorscheme="pastel19", style="filled")
     for t in self.territories:
         assert t.owner
         g.node(t.name,
                "{} ({:4d})".format(t.name, t.armies),
                fillcolor=str(t.owner.index + 1),
                pos=t.get_coordinates())
         for i in t.connections:
             g.edge(t.name, self.territories[i - 1].name)
     g.format = 'svg'
     g.render('outputs/{}'.format(name), view=False)
     if os.path.exists('outputs/{}'.format(name)):
         os.remove('outputs/{}'.format(name))
Esempio n. 9
0
def apply(tree, parameters=None):
    """
    Obtain a Process Tree representation through GraphViz

    Parameters
    -----------
    tree
        Process tree
    parameters
        Possible parameters of the algorithm

    Returns
    -----------
    gviz
        GraphViz object
    """
    if parameters is None:
        parameters = {}

    filename = tempfile.NamedTemporaryFile(suffix='.gv')
    viz = Graph("pt",
                filename=filename.name,
                engine='dot',
                graph_attr={'bgcolor': 'transparent'})
    viz.attr('node', shape='ellipse', fixedsize='false')

    image_format = exec_utils.get_param_value(Parameters.FORMAT, parameters,
                                              "png")
    color_map = exec_utils.get_param_value(Parameters.COLOR_MAP, parameters,
                                           {})

    enable_deepcopy = exec_utils.get_param_value(Parameters.ENABLE_DEEPCOPY,
                                                 parameters, True)

    if enable_deepcopy:
        # since the process tree object needs to be sorted in the visualization, make a deepcopy of it before
        # proceeding
        tree = deepcopy(tree)
        util.tree_sort(tree)

    repr_tree(tree, viz, color_map, parameters)

    viz.attr(overlap='false')
    viz.attr(splines='false')
    viz.format = image_format

    return viz
Esempio n. 10
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. 11
0
 def __setitem__(self, key, value):
     if key in self.cache:
         self.cache.pop(key)
     else:
         # Based on the motif create svg
         dot= Graph('G', engine="circo",strict=True)
         dot.format = 'svg'
         g=Graphlet(key)
         dot.attr(bgcolor='transparent')
         dot.attr('node', shape='circle')
         dot.attr('node', color='black')
         dot.attr('node', style='filled')
         dot.attr('node', fillcolor='#8EC13A')
         #dot.attr('node', label='')
         for u,v in (g.edge_list()):
             dot.edge(str(v),str(u))
         dot.render(self.imageDirectory+"/"+str(key))
         value=self.imageDirectory+"/"+str(key)+".svg"
     self.cache[key] = value
     if len(self.cache) > self.maxLength:
         self.cache.popitem(last=False)
Esempio n. 12
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. 13
0
    def graph(data):
        dot = Graph(comment='Kanjis', strict=True)
        dot.engine = 'neato'
        dot.format = 'svg'
        dot.attr(rankdir='TB', overlap="false")
        dot.attr('node', fontsize='30')

        similaredges = defaultdict(set)
        for kanji in data.kanjis:
            #try:
            k = kanji  #.decode('utf-8')
            label = ("<b>" + kanji + "</b>\n " + data.descriptions[kanji]
                     )  #.decode('utf-8')

            shape = "circle"
            fcolor = "0 0 " + str(1 - (0.2 + 0.8 * data.ease[kanji]))
            color = fcolor
            if (kanji in Similarity.dangerzones):
                shape = "doublecircle"
                color = "red"

            node = dot.node(data.descriptions[kanji],
                            label=kanji,
                            shape=shape,
                            color=color,
                            fontcolor=fcolor,
                            fillcolor=data.colors[kanji],
                            style='filled')

            #        constraint='true'
            #        color = "black"
            #        for similar in data.similars[kanji]:
            #            color = "black"
            #            if (similar in dangerzones or kanji in dangerzones):
            #                color = "red"
            #            if not similaredges[kanji] or not similar in similaredges[kanji]:
            #                if random.random() < 0.2 and color != "red": # Random dropoff
            #                    color= "lightgrey"
            #                    constraint='false'
            #                dot.edge(data.descriptions[kanji], data.descriptions[similar], color=color, constraint=constraint)#.decode('utf-8')
            #            similaredges[kanji].add(similar)
            #            similaredges[similar].add(kanji)

            for similar in data.similars[kanji]:
                color = "black"
                style = "invis"
                if (similar in Similarity.dangerzones
                        or kanji in Similarity.dangerzones):
                    color = "red"
                    style = ""
                if not similaredges[kanji] or not similar in similaredges[
                        kanji]:
                    dot.edge(data.descriptions[kanji],
                             data.descriptions[similar],
                             color=color,
                             constraint="true",
                             style=style)  #.decode('utf-8')
                similaredges[kanji].add(similar)
                similaredges[similar].add(kanji)

            for similar in data.semilars[kanji]:
                color = "lightgrey"
                if (similar in Similarity.dangerzones
                        or kanji in Similarity.dangerzones):
                    color = "red"
                if not similaredges[kanji] or not similar in similaredges[
                        kanji]:
                    if random.random() >= 0.3:  # random dropoff
                        dot.edge(data.descriptions[kanji],
                                 data.descriptions[similar],
                                 color=color,
                                 constraint="false")  #.decode('utf-8')
                similaredges[kanji].add(similar)
                similaredges[similar].add(kanji)

        #except Exception:
        #    print("encoding fial")

        return dot
    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"
    g.render("img/"+filename)

    @route('/hello/123')
    def index():
        return template("img/" + filename + ".svg")
    run(host='localhost', port=8080)

    cur.close()
    conn.close()

else:
    print ("No Results Found On DB!!")
    
Esempio n. 15
0
    def layout(self, layoutType='graph'):

        ###### need domain information for generating layout using DR
        # domain = self.f[:,:-1]

        if layoutType == 'graph':
            # g = nx.Graph()
            g = Graph('ER', engine='neato')

            i = 0
            index_map = dict()
            inverse_index_map = dict()
            # for ext in self.seg.keys():
            for s in self.graph.keys():

                for ext in self.graph[s]:
                    index_map[ext] = i
                    inverse_index_map[i] = ext

                    if ext in self.previousPos.keys():
                        ppos = self.previousPos[ext]
                        # print 'previous position is provided for:', ext, ppos[0], ppos[1]
                        g.node('%d' % ext, pos="%f,%f" % (ppos[0], ppos[1]))
                    else:
                        # print "\n\n No previousPos provided for:", ext, '\n\n'
                        g.node('%d' % ext)

                    i += 1

            for s in self.graph.keys():
                index_map[s] = i
                inverse_index_map[i] = s
                if s in self.previousPos.keys():
                    ppos = self.previousPos[s]
                    # print 'previous position is provided for:', s, ppos[0], ppos[1]
                    g.node('%d' % s, pos="%f,%f" % (ppos[0], ppos[1]))
                else:
                    # print "\n\n No previousPos provided for:", ext, '\n\n'
                    g.node('%d' % s)
                i += 1

            for s in self.graph.keys():
                for ext in self.graph[s]:

                    g.edge(str(s),
                           str(ext),
                           len=str(linalg.norm(self.loc[s] - self.loc[ext])))
                    # g.add_edge(index_map[s], index_map[ext], weight=linalg.norm(f[s,:-1] - f[ext,:-1]))

            self.currentNodeSize = len(index_map)

            if self.currentNodeSize == self.previousNodeSize:
                return

            self.previousNodeSize = self.currentNodeSize
            ##print "============== Render Spine =============="

            g.format = 'plain'
            path = g.render('spine')
            input = open('spine.plain')

            for l in input.readlines():
                l = l.split()
                # print l

                if l[0] == 'node':
                    self.pos[int(l[1])] = [float(l[2]), float(l[3])]
                    #give position to all children
                    #only if l[1] is extrema
                    #init the position all the point to the extrema pos
                    ## FIXME update children extrema to the parent location
                    # print("extremaSet = ", self.extremaSet)
                    #if int(l[1]) in self.extremaSet:
                    #     self.pos.update(dict.fromkeys(self.extremaSet[int(l[1])], [float(l[2]),float(l[3])]))

        elif layoutType == 'PCA':
            if recomputePCA:
                self.pca = decomposition.PCA(n_components=2)
                self.pca.fit(domain)
            pos2D = self.pca.transform(domain).tolist()

            for index, val in enumerate(pos2D):
                self.pos[nodeIndicesList[index]] = val

        elif layoutType == 'MDS':
            mds = manifold.MDS(n_components=2, max_iter=100, n_init=1)
            pos2D = mds.fit_transform(domain).tolist()

            for index, val in enumerate(pos2D):
                self.pos[nodeIndicesList[index]] = val

        elif layoutType == 'tSNE':
            tsne = manifold.TSNE(n_components=2, init='pca', random_state=0)
            pos2D = tsne.fit_transform(domain).tolist()
            for index, val in enumerate(pos2D):
                self.pos[nodeIndicesList[index]] = val

        else:  #PCA is the default
            pca = decomposition.PCA(n_components=2)
            pos2D = pca.fit_transform(domain).tolist()
            for index, val in enumerate(pos2D):
                self.pos[nodeIndicesList[index]] = val

        #store position
        # print self.pos
        # print "compare self.pos vs self.previousPos"
        # for p in self.previousPos.keys():
        # if self.previousPos[p] != self.pos[p]:
        # print p, self.previousPos[p], self.pos[p]

        self.previousPos = self.pos

        #if only layout one point clear the position cache
        if len(self.graph.keys()) <= 1:
            self.previousPos = dict()
def graph_pedigree(individualProfileDatabase, family, genNodes, descNode,
                   save_dir):
    """
    The pedigree is graphed using graphviz library, interface for DOT engine. Diferenciates by colour the
    individuals acording to its classifier status.
    Args:
      minimum:
          individualProfileDatabase: The output of tbe individual_profile function. A dictionary which
          contains as entries, the individuals included. Each individual is labeled with the descendants,
          siblings, ascendants, partners, sex, classifier and generation variables.
          family: The family to being graphed.
          genNodes: information required to build nodes each generation. Generated with the gen_stratification function.
          descNode: information required to build nodes that link the descendants with the ascendants. Generated with
          the gen_stratification function.
          save_dir: Directory where to save results
    Returns:
          Exports pedigree graph, diferenciates by colour the individuals acording to its classifier status.
    """
    pedGen = set()
    for i in individualProfileDatabase:
        pedGen.add(individualProfileDatabase[i]["generation"][0])
    dot = Graph(engine='DOT',
                comment="ped_",
                graph_attr={
                    'splines': 'ortho',
                    'concentrate': 'true'
                },
                strict=True)
    for i in range(min(pedGen), max(pedGen) + 1):
        with dot.subgraph(name=str(i)) as subs:
            subs.attr(rank='same')
            for e in genNodes[i]:
                #set format
                if (len(e) == 3):
                    if e[1] == 1:
                        shape = "rect"
                    else:
                        shape = "ellipse"
                    if e[2] == 2:
                        color = "green"
                    else:
                        color = "red"
                    subs.node(e[0], shape=shape, style='filled', color=color)
                else:
                    nodeName = str(e[0]) + "_" + str(e[1])
                    subs.node(nodeName, shape="point")
                    subs.edge(str(e[0]), nodeName)
                    subs.edge(nodeName, str(e[1]))
        with dot.subgraph(name=str(i + 0.5)) as subs:
            for e in descNode[i + 0.5]:
                if i == (max(pedGen)):
                    pass
                else:
                    if type(e) == list:
                        nodeName = str(e[0]) + "_" + str(e[1])
                        intergenNodeName = nodeName + "_desc"
                        subs.node(intergenNodeName, shape="point")
                        subs.edge(nodeName, intergenNodeName)
                    else:
                        nodeName = str(e)
                        intergenNodeName = nodeName + "_desc"
                        subs.node(intergenNodeName, shape="point")
                        subs.edge(nodeName, intergenNodeName)
        if i == min(pedGen):
            pass
        else:
            for e in genNodes[i]:
                if type(e[0]) == str:
                    e = int(e[0])
                    ascendants = individualProfileDatabase[e]["ascendants"]
                    if len(ascendants) == 1:
                        if len(individualProfileDatabase[ascendants[0]]
                               ["descendants"]) != 1:
                            intergenNodeName = str(ascendants[0]) + "_desc"
                            dot.node(intergenNodeName, shape="point")
                            dot.edge(str(ascendants[0]), intergenNodeName)
                            dot.edge(intergenNodeName, str(e))
                        else:
                            intergenNodeName = str(ascendants[0]) + "_desc"
                            dot.edge(intergenNodeName, str(e))
                    elif len(ascendants) == 2:
                        if (ascendants in genNodes[i - 1]):
                            intergenNodeName = str(ascendants[0]) + "_" + str(
                                ascendants[1]) + "_desc"
                            dot.edge(intergenNodeName, str(e))
                        elif ([ascendants[1], ascendants[0]]
                              in genNodes[i - 1]):
                            intergenNodeName = str(ascendants[1]) + "_" + str(
                                ascendants[0]) + "_desc"
                            dot.edge(intergenNodeName, str(e))
                        else:
                            print("Unexpected input.")
                    else:
                        pass
                else:
                    pass
    dot.node("Family ID: " + str(family), shape="box")
    dot.format = 'svg'
    dot.render(save_dir + 'pedigree_family_' + str(family) + '.gv', view=True)
Esempio n. 17
0
di = counts.most_common(50)
df = pd.DataFrame(di, columns=["tag", "value"])
df = df.sort_values('value', ascending=False)
plot = df.plot(xticks=df.index, kind='bar', rot=45)
plot.set_xticklabels(df.tag)
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
print(df)
plt.show()
print(mapped[0].keys)

build_graph(mapped[0]["PERSON"], mapped[0]["GPE"])

#build_graph(prsns, prsns)
exit(0)
dot = Graph(strict=True)
dot.format = 'svg'

print(prsns)

for e in prsns:
    for p in prsns:
        if e == p:
            continue
        if not '\t' + e in dot.body:
            dot.node(e)
        if not '\t' + p in dot.body:
            dot.node(p)
        dot.edge(e, p)

print(dot.source)  # doctest: +NORMALIZE_WHITESPACE
Esempio n. 18
0
 def build_network(self):
     if not self.jaccard_dict:
         return 'No_dict'
     # networkxで計算
     G = nx.Graph()
     # 接点/単語(node)の追加
     nodes = set([j for pair in self.jaccard_dict.keys() for j in pair])
     G.add_nodes_from(nodes)
     # 線(edge)の追加
     for pair, coef in self.jaccard_dict.items():
         G.add_edge(pair[0], pair[1], weight=coef)
     # focusの場合
     if self.focus:
         try:
             keepnodes = list((G[self.focus]).keys())
         except KeyError:
             return 'No_focus'
         else:
             keepnodes = list((G[self.focus]).keys())
             keepnodes.append(self.focus)
             print(f'🟦{keepnodes}')
             #ノード削除
             rm_nodes = set(nodes) ^ set(keepnodes)
             G.remove_nodes_from(rm_nodes)
             G.remove_nodes_from(list(isolates(G)))
     print('Number of nodes =', G.number_of_nodes())
     print('Number of edges =', G.number_of_edges())
     # graphviz.pyで描写
     g = Graph(engine='neato')
     g.attr(overlap='false')
     g.attr(size='800,500')
     g.attr(outputorder="edgesfirst")
     # networkxのpagerankを活用して色やノードサイズを変化させる
     pagerank = nx.pagerank(G)
     print(pagerank)
     cm = plt.get_cmap('rainbow')
     for node, rank in pagerank.items():
         ncm = cm(rank * 15)
         colorhex = mcolors.to_hex(ncm)
         if node in self.emojidict.keys():
             g.attr('node',
                    shape='circle',
                    color=str(colorhex),
                    style='filled',
                    fixedsize='True',
                    height=20,
                    imagescale='both',
                    margin=' 0.001,0.001')
             emojivalue = self.emojidict[node]
             emoji_img = Image.open(
                 requests.get(emojivalue[1], stream=True).raw)
             bytes = io.BytesIO()
             emoji_img.save(bytes, format='PNG')
             g.node(bytes)
             bytes.close()
         else:
             g.attr('node',
                    shape='circle',
                    color=str(colorhex),
                    style='filled',
                    fontsize='22',
                    fontpath='SourceHanSansHW-Bold.otf',
                    fixedsize='True',
                    height=str(len(node) / 3.3 + 10 * rank))
             g.node(node)
     edges = []
     for source in G.edges(data=True):
         edges.append([source[0], source[1], source[2]['weight']])
     print(edges)
     for edge in edges:
         g.attr('edge', weight=str(min(edge[2] * 10, 30)))
         g.edge(edge[0], edge[1])
     g.format = 'png'
     datastream = io.BytesIO(g.pipe())
     datastream.seek(0)
     pngimage = discord.File(datastream,
                             filename=f'discord_network_graph.png')
     datastream.close()
     return pngimage
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 reset_dot():
    global dot
    dot = Graph('MinorC_AST')
    dot.filename = 'MinorC_AST'
    dot.format = 'png'
Esempio n. 21
0
def apply(tree, parameters=None):
    """
    Obtain a Process Tree representation through GraphViz

    Parameters
    -----------
    tree
        Process tree
    parameters
        Possible parameters of the algorithm

    Returns
    -----------
    gviz
        GraphViz object
    """
    if parameters is None:
        parameters = {}

    filename = tempfile.NamedTemporaryFile(suffix='.gv')
    viz = Graph("pt",
                filename=filename.name,
                engine='dot',
                graph_attr={'bgcolor': 'transparent'})
    image_format = exec_utils.get_param_value(Parameters.FORMAT, parameters,
                                              "png")
    color_map = exec_utils.get_param_value(Parameters.COLOR_MAP, parameters,
                                           {})
    node_color = get_color(tree, color_map)

    enable_deepcopy = exec_utils.get_param_value(Parameters.ENABLE_DEEPCOPY,
                                                 parameters, True)

    if enable_deepcopy:
        # since the process tree object needs to be sorted in the visualization, make a deepcopy of it before
        # proceeding
        tree = deepcopy(tree)
        util.tree_sort(tree)

    # add first operator
    if tree.operator:
        viz.attr('node', shape='ellipse', fixedsize='false', fontsize="14")
        op_node_identifier = str(uuid.uuid4())
        viz.node(op_node_identifier,
                 operators_mapping[str(tree.operator)],
                 color=node_color,
                 fontcolor=node_color)

        viz = repr_tree(tree, viz, op_node_identifier, 0, color_map,
                        parameters)
    else:
        viz.attr('node', shape='ellipse', fixedsize='false', fontsize="16")
        this_trans_id = str(uuid.uuid4())
        if tree.label is None:
            viz.node(this_trans_id,
                     "tau",
                     style='filled',
                     fillcolor='black',
                     shape='point',
                     width="0.075")
        else:
            viz.node(this_trans_id,
                     str(tree),
                     color=node_color,
                     fontcolor=node_color)

    viz.attr(overlap='false')
    viz.attr(fontsize='16')
    viz.attr(splines='false')
    viz.format = image_format

    return viz
Esempio n. 22
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)