Example #1
0
def _draw_graph_diffing(graph1, graph2, differences):
    plt.subplot(121)
    pos = nx.pygraphviz_layout(graph1, prog='dot')
    nx.draw_networkx_nodes(graph1, pos,
                           graph1.nodes(), node_color='b', node_size=200)
    nx.draw_networkx_nodes(graph1, pos, differences[0],
                           node_color='r', node_size=600)
    nx.draw_networkx_nodes(graph1, pos, differences[2],
                           node_color='y', node_size=600)
    nx.draw_networkx_edges(graph1, pos, graph1.edges())
    nx.draw_networkx_labels(graph1, pos, font_size=8)
    plt.title('Graph 1')
    plt.axis('off')
    plt.subplot(122)
    pos = nx.pygraphviz_layout(graph2, prog='dot')
    nx.draw_networkx_nodes(graph2, pos, graph2.nodes(), node_color='b',
                           node_size=200)
    nx.draw_networkx_nodes(graph2, pos, differences[1], node_color='r',
                           node_size=600)
    nx.draw_networkx_nodes(graph2, pos, differences[3], node_color='g',
                           node_size=600)
    nx.draw_networkx_edges(graph2, pos, graph2.edges())
    nx.draw_networkx_labels(graph2, pos, font_size=8)
    plt.title('Graph 2')
    plt.axis('off')
    lr = plt.Circle((0, 0), 5, fc='r')
    lb = plt.Circle((0, 0), 5, fc='b')
    lg = plt.Circle((0, 0), 5, fc='g')
    ly = plt.Circle((0, 0), 5, fc='y')
    plt.legend([lb, lr, lg, ly], ['No changed', 'Changed', 'Added',
                                  'Removed'], loc=4)
    #     plt.savefig(graph1.name + '-' + graph2.name + '.png')
    plt.show()
def _draw_graph_diffing(memory_dump1, memory_dump2, differences):
    plt.subplot(121)
    pos = nx.pygraphviz_layout(memory_dump1.memory_graph, prog='dot')
    nx.draw_networkx_nodes(memory_dump1.memory_graph, pos,
           memory_dump1.memory_graph.nodes(), node_color='b', node_size=200)
    nx.draw_networkx_nodes(memory_dump1.memory_graph, pos, differences[0],
                                                node_color='r', node_size=600)
    nx.draw_networkx_nodes(memory_dump1.memory_graph, pos, differences[2],
                                                node_color='y', node_size=600)
    nx.draw_networkx_edges(memory_dump1.memory_graph, pos,
                                            memory_dump1.memory_graph.edges())
    nx.draw_networkx_labels(memory_dump1.memory_graph, pos, font_size=8)
    plt.title(memory_dump1.name)
    plt.axis('off')
    plt.subplot(122)
    pos = nx.pygraphviz_layout(memory_dump2.memory_graph, prog='dot')
    nx.draw_networkx_nodes(memory_dump2.memory_graph, pos,
            memory_dump2.memory_graph.nodes(), node_color='b', node_size=200)
    nx.draw_networkx_nodes(memory_dump2.memory_graph, pos, differences[1],
                                                node_color='r', node_size=600)
    nx.draw_networkx_nodes(memory_dump2.memory_graph, pos, differences[3],
                                                node_color='g', node_size=600)
    nx.draw_networkx_edges(memory_dump2.memory_graph, pos,
                                            memory_dump2.memory_graph.edges())
    nx.draw_networkx_labels(memory_dump2.memory_graph, pos, font_size=8)
    plt.title(memory_dump2.name)
    plt.axis('off')
    lr = plt.Circle((0, 0), 5, fc='r')
    lb = plt.Circle((0, 0), 5, fc='b')
    lg = plt.Circle((0, 0), 5, fc='g')
    ly = plt.Circle((0, 0), 5, fc='y')
    plt.legend([lb, lr, lg, ly], ['No changed', 'Changed', 'Added',
                                                            'Removed'], loc=4)
#     plt.savefig(memory_dump1.name + '-' + memory_dump2.name + '.png')
    plt.show()
def plot_dg(dg):
    plt.figure()
    #    pos = networkx.spring_layout(dg)
    pos = networkx.pygraphviz_layout(dg, 'dot')
    networkx.draw_networkx_labels(dg, pos)
    networkx.draw(dg, pos, arrows=True)
    plt.show()
Example #4
0
def draw_memory_graph(memory_dump):
    plt.title(memory_dump.name)
    #     pos = nx.spring_layout(memory_dump.memory_graph, iterations=10)
    pos = nx.pygraphviz_layout(memory_dump.memory_graph, prog='dot')
    nx.draw_networkx_nodes(memory_dump.memory_graph,
                           pos,
                           memory_dump.data_structures.values(),
                           node_size=200,
                           node_color='r')
    nx.draw_networkx_nodes(memory_dump.memory_graph,
                           pos,
                           memory_dump.modules,
                           node_color='b',
                           node_size=200)
    # nx.draw_networkx_nodes(memory_dump.memory_graph, pos,
    #                     memory_dump.g_pointers, node_color='b', node_size=200)
    nx.draw_networkx_edges(memory_dump.memory_graph, pos,
                           memory_dump.memory_graph.edges())
    nx.draw_networkx_labels(memory_dump.memory_graph, pos, font_size=8)

    lr = plt.Circle((0, 0), 5, fc='r')
    lb = plt.Circle((0, 0), 5, fc='b')
    plt.legend([lb, lr], ['Global Pointer', 'Data Structure'], loc=4)
    plt.axis('off')
    plt.savefig(memory_dump.name + '_memory_graph.png')
    plt.show()
Example #5
0
    def plot(self):
        """
        Plots an entity relation diagram (ERD) among all nodes that is part
        of the current graph.
        """
        if not self.nodes(): # There is nothing to plot
            logger.warning('Nothing to plot')
            return
        if pygraphviz_layout is None:
            logger.warning('Failed to load Pygraphviz - plotting not supported at this time')
            return

        pos = pygraphviz_layout(self, prog='dot')
        fig = plt.figure(figsize=[10, 7])
        ax = fig.add_subplot(111)
        nx.draw_networkx_nodes(self, pos, node_size=200, node_color='g')
        text_dict = nx.draw_networkx_labels(self, pos, self.node_labels)
        trans = ax.transData + \
            transforms.ScaledTranslation(12/72, 0, fig.dpi_scale_trans)
        for text in text_dict.values():
            text.set_horizontalalignment('left')
            text.set_transform(trans)
        # draw primary key relations
        nx.draw_networkx_edges(self, pos, self.pk_edges, arrows=False)
        # draw non-primary key relations
        nx.draw_networkx_edges(self, pos, self.non_pk_edges, style='dashed', arrows=False)
        apos = np.array(list(pos.values()))
        xmax = apos[:, 0].max() + 200  # TODO: use something more sensible than hard fixed number
        xmin = apos[:, 0].min() - 100
        ax.set_xlim(xmin, xmax)
        ax.axis('off')  # hide axis
Example #6
0
    def visualize(self):
        self.should_stop = False

        while not self.should_stop:
            if len(self.tasks) > 0:
                self.walk_update(self.tasks[0])

            colormap = ['red', 'yellow', 'green']

            pos = nx.pygraphviz_layout(self.graph, prog='dot')
            colors = [
                colormap[self.graph.node[n]['state']]
                for n in self.graph.nodes()
            ]
            labels = {
                n: self.graph.node[n]['label']
                for n in self.graph.nodes()
            }

            self.ax.clear()
            nx.draw(self.graph,
                    ax=self.ax,
                    pos=pos,
                    node_color=colors,
                    labels=labels,
                    node_size=2000)
            time.sleep(0.2)
Example #7
0
    def plot_scenario_tree(self):
        G = nx.DiGraph()
        G.add_node('ROOT')

        # build tree
        for scn in self.scenarios:
            genealogy = self.scenarios[scn].genealogy
            for i, node in enumerate(genealogy):
                if node != 'ROOT':
                    node_name = '{}_{}'.format(str(node), str(i))
                    if node_name not in G.nodes():
                        G.add_node(node_name)
                        if genealogy[i - 1] == 'ROOT':
                            parent = 'ROOT'
                        else:
                            parent = '{}_{}'.format(genealogy[i - 1], i - 1)
                        G.add_edge(parent, node_name)

        #nx.draw_graphviz(G, with_labels=True, arrows=True, prog='dot', node_color='black')
        # node_position = nx.graphviz_layout(G, prog='dot')
        node_position = nx.pygraphviz_layout(G, prog='dot')
        label_position = copy.deepcopy(node_position)
        for p in label_position:
            # Now sure why networkx stores position as a tuple...
            label_position[p] = list(label_position[p])
            # label_position[p][1] += 15
            label_position[p] = tuple(label_position[p])
        # nx.draw_graphviz(G, position, with_labels=False, arrows=True, prog='dot', node_color='black')
        nx.draw(G,
                node_position,
                with_labels=False,
                arrows=True,
                node_color='red')
        nx.draw_networkx_labels(G, pos=label_position)
def plot_dg(dg):
    plt.figure()
#    pos = networkx.spring_layout(dg)
    pos = networkx.pygraphviz_layout(dg,'dot')
    networkx.draw_networkx_labels(dg,pos)
    networkx.draw(dg,pos,arrows=True)
    plt.show()
Example #9
0
def autoCoordinates(meshEntry,srcdesConnection):
    G = nx.Graph()
    for cmpt,memb in list(meshEntry.items()):
        for enzObj in find_index(memb,'enzyme'):
            G.add_node(enzObj.path,label='',shape='ellipse',color='',style='filled',fontname='Helvetica',fontsize=12,fontcolor='blue')
    for cmpt,memb in list(meshEntry.items()):
        for poolObj in find_index(memb,'pool'):
            #poolinfo = moose.element(poolObj.path+'/info')
            G.add_node(poolObj.path,label = poolObj.name,shape = 'box',color = '',style = 'filled',fontname = 'Helvetica',fontsize = 12,fontcolor = 'blue')
        for cplxObj in find_index(memb,'cplx'):
            pass
        for reaObj in find_index(memb,'reaction'):
            G.add_node(reaObj.path,label='',shape='record',color='')
        
    for inn,out in list(srcdesConnection.items()):
        if (inn.className =='ZombieReac'): arrowcolor = 'green'
        elif(inn.className =='ZombieEnz'): arrowcolor = 'red'
        else: arrowcolor = 'blue'
        if isinstance(out,tuple):
            if len(out[0])== 0:
                print(inn.className + ':' +inn.name + "  doesn't have input message")
            else:
                for items in (items for items in out[0] ):
                	G.add_edge(element(items[0]).path,inn.path)
                	
            if len(out[1]) == 0:
                print(inn.className + ':' + inn.name + "doesn't have output mssg")
            else:
                for items in (items for items in out[1] ):
                	G.add_edge(inn.path,element(items[0]).path)
                	
        elif isinstance(out,list):
            if len(out) == 0:
                print("Func pool doesn't have sumtotal")
            else:
                for items in (items for items in out ):
                	G.add_edge(element(items[0]).path,inn.path)
    #from networkx.drawing.nx_agraph import graphviz_layout
    #position = graphviz_layout(G,prog='dot')

    position = nx.pygraphviz_layout(G, prog = 'dot')
    position = nx.spring_layout(G)
    #agraph = nx.to_agraph(G)
    #agraph.draw("~/out.png", format = 'png', prog = 'dot')

    sceneitems = {}
    xycord = []
    cmin = 0
    cmax = 0
    for key,value in list(position.items()):
        xycord.append(value[0])
        xycord.append(value[1])
        sceneitems[element(key)] = {'x':value[0],'y':value[1]}
    if len(xycord) > 0:
    	cmin = min(xycord)
    	cmax = max(xycord)
    return cmin,cmax,sceneitems
Example #10
0
    def graphMeasure(self, measure = 'degree', anonymized_log = True):
        """
        Metoda twrzy rysunek grafu reprezentującego sieć kolorując węzły odpowiednio do charakteryzującej je miary centralnośći. 
        
        @param measure: nazwa miary centralności, której wartość bęðzie wykorzystana przy kolorowaniu węzłów
        @type anonymized_log: boolean
        @param anonymized_log: włączenie anonimizacji danych zapisywanch w pliku dziennika (numery zamiast pełnego imienia i nazwiska)
        """
        measureValues = self.centrality[measure]
        
        
        filename = measure + ".png"
        
        # print sorted node list on INFO
        nodesDict = dict()
        for node, data in self.graph.nodes_iter(data=True):
            nodesDict[node] = measureValues[node]
        sortedNodes = sorted(nodesDict, key=nodesDict.get, reverse = True)
        
        logger.info("******########*******" + measure + "******########*******")
        for node in sortedNodes:
            if not anonymized_log:
                logger.info(self.graph.node[node]['name'] +" (" + str(self.labels[node]) + "): " + str(nodesDict[node])) # z nazwiskami osob
            else:
                logger.info(str(self.labels[node]) + ": " + str(nodesDict[node])) # same numery
            # set my value to 0 for better colors
            if self.graph.node[node]['name'] == 'Marcin Mincer':
                measureValues[node] = 0
        
        

        # stupid hack becouse of pygraphviz utf-8 malfunction
        graph_copy = nx.Graph();
        graph_copy.add_nodes_from(self.graph.nodes())
        graph_copy.add_edges_from(self.graph.edges())
        # end stupid hack
        
        pos=nx.pygraphviz_layout(graph_copy,prog='neato')
        for i in pos:
            pos[i] = (pos[i][0]*3, pos[i][1]*3)
        
        import matplotlib.pyplot as plt
        

        
        plt.figure(figsize=(20,20))
        plt.axis('off')
        nx.draw_networkx_edges(self.graph,pos,alpha=0.2)
        nx.draw_networkx_nodes(self.graph, pos, size = 4, with_labels=False, node_color=measureValues.values(), cmap=plt.cm.get_cmap('Spectral'))
        nx.draw_networkx_labels(self.graph, pos, font_size = 10, labels = self.labels)
        plt.colorbar(orientation="horizontal", fraction = 0.04, pad = 0.01, aspect = 16)
        import config
        filename = config.PLOT_OUT_DIR+filename
        plt.savefig(filename)
Example #11
0
    def partitionGraph(self, filename = "fb_partition.png", method = 'blondelAlgorithm'):
        from thesis.sna import Cliquer
        
        cq = Cliquer(self.graph)
        function = getattr(cq, method)
        self.partition = function()
        
        # write down partition
        
        for cluster in self.partition:
            members = ""
            for member in cluster:
                members += str(self.labels[member]) + " "
            logger.info(str(self.partition.index(cluster)) + ", " + members)
        
        # partition done, making colors
        # making graph
        
        nodeList = self.partition
        colorList = [0] * self.graph.number_of_nodes()

        for nbunch in nodeList:
            for n in nbunch:
                colorList[self.graph.nodes().index(n)] = nodeList.index(nbunch)

        import matplotlib.pyplot as plt
        
        # stupid hack becouse of pygraphviz utf-8 malfunction
        graph_copy = nx.Graph();
        graph_copy.add_nodes_from(self.graph.nodes())
        graph_copy.add_edges_from(self.graph.edges())
        # end stupid hack
        
        
        pos=nx.pygraphviz_layout(graph_copy,prog='neato')
        for i in pos:
            pos[i] = (pos[i][0]*3, pos[i][1]*3)
        
        
        plt.figure(figsize=(20,20))
        plt.axis('off')
        nx.draw_networkx_edges(self.graph,pos,alpha=0.2)
        nx.draw_networkx_nodes(self.graph, pos, size = 4, node_color=colorList, with_labels=False)
        nx.draw_networkx_labels(self.graph, pos, font_size = 10, labels = self.labels)
        
        import config
        filename = config.PLOT_OUT_DIR+filename
        plt.savefig(filename)
Example #12
0
    def visualize(self):
        self.should_stop = False

        while not self.should_stop:
            if len(self.tasks) > 0:
                self.walk_update(self.tasks[0])

            colormap = ['red', 'yellow', 'green']

            pos = nx.pygraphviz_layout(self.graph, prog='dot')
            colors = [colormap[self.graph.node[n]['state']] for n in self.graph.nodes()]
            labels = {n: self.graph.node[n]['label'] for n in self.graph.nodes()}

            self.ax.clear()
            nx.draw(self.graph, ax=self.ax, pos=pos, node_color=colors, labels=labels, node_size=2000)
            time.sleep(0.2)
def draw_memory_graph_intersection(pos_dumps, nodes):
    pos = nx.pygraphviz_layout(pos_dumps[-1].memory_graph, prog='dot')
    nx.draw_networkx_nodes(pos_dumps[-1].memory_graph, pos,
           pos_dumps[-1].memory_graph.nodes(), node_color='b', node_size=200)
    nx.draw_networkx_nodes(pos_dumps[-1].memory_graph, pos, nodes,
                                                node_color='r', node_size=600)
    nx.draw_networkx_edges(pos_dumps[-1].memory_graph, pos,
                                            pos_dumps[-1].memory_graph.edges())
    nx.draw_networkx_labels(pos_dumps[-1].memory_graph, pos, font_size=8)
    plt.title('-'.join((n.name for n in pos_dumps)))
    plt.axis('off')

    lr = plt.Circle((0, 0), 5, fc='r')
    lb = plt.Circle((0, 0), 5, fc='b')
    plt.legend([lb, lr], ['No change', 'Change'], loc=4)
    plt.axis('off')
    plt.show()
Example #14
0
def display_graph(G, course=None, dist=None, draw_edge_label=True):
    labels = dict((n, d['label']) for n, d in G.nodes(data=True))
    edge_labels = nx.get_edge_attributes(G, 'w')
    # nx.draw_graphviz(G, labels=labels, node_color='c')
    pos = nx.pygraphviz_layout(G)
    nx.draw_networkx_nodes(G, pos, node_color='g', node_size=400)
    nx.draw_networkx_labels(G, pos, labels=labels, font_size=10)
    nx.draw_networkx_edges(G, pos)
    if draw_edge_label:
        nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)

    if not course is None:
        nx.draw_networkx_nodes(G, pos, nodelist=[course[0]], node_size=400, node_color='r')
        nx.draw_networkx_nodes(G, pos, nodelist=[course[-1]], node_size=400, node_color='b')
        for ind in range(len(course)-1):
            nx.draw_networkx_edges(G, pos, edgelist=[[course[ind], course[ind+1]]], edge_color='y')
        plt.title(dist[course[-1]])
    plt.show()
Example #15
0
def plot_height_portions(graph, budgets, height_portions):
    """
    For a few budget points, plot the average portion of predictions (across all accuracies)
    by filling in the ILSVRC65 nodes.
    """
    g = graph['g']
    nodes = graph['nodes']
    pos = nx.pygraphviz_layout(g, prog='twopi')

    gray = (0.75, 0.75, 0.75)
    graydark = (0.5, 0.5, 0.5)
    ns = 120

    labels = dict(zip(nodes, [g.node[node]['word'].split(',')[0] for node in nodes]))
    leaf_nodes = np.array(graph['nodes'])[graph['heights'] == 0]
    for node in leaf_nodes:
        labels[node] = ''

    cmap = plt.get_cmap('Oranges')
    fig = plt.figure(figsize=(20, 5.5))
    num_budget_points = 4
    for i, b in enumerate(np.linspace(0, len(budgets)-1, num_budget_points).astype('int')):
        for h in np.unique(graph['heights']):
            ax = fig.add_subplot(1, num_budget_points, i+1)
            h_nodes = np.array(graph['nodes'])[graph['heights'] == h].tolist()
            c = np.minimum(1, height_portions.mean(1)[h][b] / .5)
            nx.draw_networkx_nodes(g, pos, nodelist=h_nodes, node_size=ns, node_color=cmap(c), ax=ax).set_edgecolor(graydark)
            if i == 0:
                if h > 0:
                    pos_offset = pos.copy()
                    for k in pos_offset.keys():
                        pos_offset[k] = (pos_offset[k][0], pos_offset[k][1]-20)
                    nx.draw_networkx_labels(g, pos_offset, labels, font_size=12, font_color=graydark)
        nx.draw_networkx_edges(g, pos, arrows=False, edge_color=[gray] * len(g.edges()), ax=ax)
        ax.set_title('Budget: {}'.format(budgets[b]))
        plt.axis('off')
        plt.axis('equal')
    fig.tight_layout()

    fig = plt.figure()
    cmap = plt.cm.winter
    for h in range(height_portions.shape[0]):
        plt.plot(height_portions[h, 2, :], label='height {}'.format(h), color=cmap(1. * h / height_portions.shape[0]))
    plt.legend()
Example #16
0
def draw_memory_graph(memory_dump):
    plt.title(memory_dump.name)
#     pos = nx.spring_layout(memory_dump.memory_graph, iterations=10)
    pos = nx.pygraphviz_layout(memory_dump.memory_graph, prog='dot')
    nx.draw_networkx_nodes(memory_dump.memory_graph, pos,
           memory_dump.data_structures.values(), node_size=200, node_color='r')
    nx.draw_networkx_nodes(memory_dump.memory_graph, pos, memory_dump.modules,
                                                node_color='b', node_size=200)
    # nx.draw_networkx_nodes(memory_dump.memory_graph, pos,
#                     memory_dump.g_pointers, node_color='b', node_size=200)
    nx.draw_networkx_edges(memory_dump.memory_graph, pos,
                                            memory_dump.memory_graph.edges())
    nx.draw_networkx_labels(memory_dump.memory_graph, pos, font_size=8)

    lr = plt.Circle((0, 0), 5, fc='r')
    lb = plt.Circle((0, 0), 5, fc='b')
    plt.legend([lb, lr], ['Global Pointer', 'Data Structure'], loc=4)
    plt.axis('off')
    plt.savefig(memory_dump.name + '_memory_graph.png')
    plt.show()
Example #17
0
    def plot(self):
        """
        Plots an entity relation diagram (ERD) among all nodes that is part
        of the current graph.
        """
        if not self.nodes():  # There is nothing to plot
            logger.warning('Nothing to plot')
            return
        if pygraphviz_layout is None:
            logger.warning(
                'Failed to load Pygraphviz - plotting not supported at this time'
            )
            return

        pos = pygraphviz_layout(self, prog='dot')
        fig = plt.figure(figsize=[10, 7])
        ax = fig.add_subplot(111)
        nx.draw_networkx_nodes(self, pos, node_size=200, node_color='g')
        text_dict = nx.draw_networkx_labels(self, pos, self.node_labels)
        trans = ax.transData + \
            transforms.ScaledTranslation(12/72, 0, fig.dpi_scale_trans)
        for text in text_dict.values():
            text.set_horizontalalignment('left')
            text.set_transform(trans)
        # draw primary key relations
        nx.draw_networkx_edges(self, pos, self.pk_edges, arrows=False)
        # draw non-primary key relations
        nx.draw_networkx_edges(self,
                               pos,
                               self.non_pk_edges,
                               style='dashed',
                               arrows=False)
        apos = np.array(list(pos.values()))
        xmax = apos[:, 0].max(
        ) + 200  # TODO: use something more sensible than hard fixed number
        xmin = apos[:, 0].min() - 100
        ax.set_xlim(xmin, xmax)
        ax.axis('off')  # hide axis
Example #18
0
def draw_cm_muscle_congruencies(seqs, profiles, run_id, reset = True):
    print 'computing alignments...'
    print '  ...using muscle'
    malis, mrefs, mpairs =\
            mem.getOrSet(setAlignments, 
                         **mem.rc({},
                                  seqs = seqs, profiles = profiles, 
                                  run_id = run_id, ali_type = 'muscle',
                                  reset = reset,
                                  on_fail = 'compute', 
                                  register = 'tuali_musc_{0}'.format(run_id))) 
    print '  ...using cmalign.'
    salis, srefs, spairs  =\
        mem.getOrSet(setAlignments, 
                     **mem.rc({},
                              seqs = seqs, profiles = profiles, 
                              run_id = run_id, ali_type = 'struct',
                              reset = reset,
                              on_fail = 'compute', 
                              register = 'tuali__struct_{0}'.format(run_id)))
 
    print '  ...making trees.'
    
    for idx, alis in enumerate(zip(malis, salis)):
        m, s = alis
        mtree  = phyml.tree(m,run_id, bionj = True)
        stree  = phyml.tree(s,run_id, bionj = True)
        
        maps = dict([(elt.id,i) for i, elt in enumerate(m)])
        mdists = zeros((len(maps),len(maps)))
        sdists = zeros((len(maps),len(maps)))
        for n1 in mtree.get_terminals():
            for n2 in mtree.get_terminals():
                mdists[maps[n1.name],maps[n2.name]] = \
                    mtree.distance(n1,n2)
        
        for n1 in stree.get_terminals():
            for n2 in stree.get_terminals():
                sdists[maps[n1.name],maps[n2.name]] = \
                    stree.distance(n1,n2)
        tree_similarity(sdists, mdists, '{0}_struct_{1}'.format(run_id,idx), k = len(sdists - 1))
        tree_similarity(sdists, mdists, '{0}_struct_{1}'.format(run_id,idx), k = 6)

        f = myplots.fignum(4, (8,10))
        ct = mycolors.getct(len(mtree.get_terminals()))

        import networkx

        for t, sp, ttype in zip([mtree, stree], [211,212], ['sequence', 'structural']):
            a = f.add_subplot(sp)
            layout = 'neato'
            G = phylo.to_networkx(t)
            Gi = networkx.convert_node_labels_to_integers(G, discard_old_labels=False)
            posi = networkx.pygraphviz_layout(Gi, layout, args = '')
            posn = dict((n, posi[Gi.node_labels[n]]) for n in G)


            networkx.draw(G, posn, labels = dict([(n, '') for n in G.nodes()]),
                      node_size = [100 if  n.name in maps.keys() else 0 for n in G.nodes()],
                      width = 1, edge_color = 'black',
                      ax = a,
                      node_color = [ct[maps.get(n.name, -1)] for n in G.nodes()] )
        

            a.annotate('Embedded tree for {0} alignment.'.format(ttype),
                    [0,1], xycoords = 'axes fraction', va = 'top',
                    xytext = [10,0],textcoords = 'offset pixels')
            a.annotate('Total branch length is {0}'.format(t.total_branch_length()),
                    [1,0], xycoords = 'axes fraction', ha = 'right',
                    xytext = [-10,10],textcoords = 'offset pixels')            

        #phylo.draw_graphviz(  mtree,  label_func = lambda x: '', 
        #                      node_color = [ct[maps.get(n.name, -1)] for n in G.nodes()] +\
        #                          [ct[0] for n in mtree.get_nonterminals()], axes = ax)

        datafile = cfg.dataPath('figs/gpm2/pt2_mus_cm_tree_embeddings_{0}_struct_{1}.ps'.format(run_id, idx))
        f.savefig(datafile, dpi = 200, format = 'ps')
def plot_network(Gtest, border_cols, md_network,
                 focal_node_name, edge_thresh, network_algo, map_degree, plot_border_col, draw_shortest_paths,
                 coexpression, colocalization, other, physical_interactions, predicted_interactions, shared_protein_domain):

    nodes = Gtest.nodes()
    node_series = Series(nodes)

    focal_node = list(node_series[node_series==focal_node_name].index)[0]

    numnodes = len(Gtest)

    # deal with case where no border_cols input
    if len(border_cols) < numnodes:
        border_cols = Series(np.ones(numnodes))
        border_cols.index = nodes

    # create a new dataframe mapping network_group value to edges
    e1e2 = Series(zip(list(md_network['Entity 1']), list(md_network['Entity 2']), list(md_network['Weight'])))
    e1e2NG_df = DataFrame(data={'e1e2': e1e2, 'Network_group': md_network['Network_group']})

    # find all coexpression edges
    sum(md_network['Network_group'] == 'Co-expression')


    # select 'Co-expression' edges
    edge_list_CE = list(e1e2NG_df.e1e2[e1e2NG_df.Network_group == 'Co-expression'])
    # select 'Co-localization' edges
    edge_list_CL = list(e1e2NG_df.e1e2[e1e2NG_df.Network_group == 'Co-localization'])
    # select 'Other' edges
    edge_list_OTHER = list(e1e2NG_df.e1e2[e1e2NG_df.Network_group == 'Other'])
    # select 'Physical interactions' edges
    edge_list_PI = list(e1e2NG_df.e1e2[e1e2NG_df.Network_group == 'Physical interactions'])
    # select 'Predicted' edges
    edge_list_PRED = list(e1e2NG_df.e1e2[e1e2NG_df.Network_group == 'Predicted'])
    # select 'Shared protein domain' edges
    edge_list_SPD = list(e1e2NG_df.e1e2[e1e2NG_df.Network_group == 'Shared protein domains'])

    edge_list_total = []
    if coexpression:
        edge_list_total.extend(edge_list_CE)
    if colocalization:
        edge_list_total.extend(edge_list_CL)
    if other:
        edge_list_total.extend(edge_list_OTHER)
    if physical_interactions:
        edge_list_total.extend(edge_list_PI)
    if predicted_interactions:
        edge_list_total.extend(edge_list_PRED)
    if shared_protein_domain:
        edge_list_total.extend(edge_list_SPD)

    # find edges < threshold
    elarge = [(u, v) for (u, v, d) in edge_list_total if d > edge_thresh]
    esmall = [(u, v) for (u, v, d) in edge_list_total if d <= edge_thresh]

    # create temp network for calculations
    Gtemp = nx.Graph()
    Gtemp.add_nodes_from(Gtest.nodes())
    Gtemp.add_edges_from(elarge)
    
    if network_algo == 'community':
        fig = plt.figure(figsize=(20,25))
        gs = gridspec.GridSpec(2,1,height_ratios=[2,1])
        ax = plt.subplot(gs[0])
    else:
        fig,ax=plt.subplots(figsize=(20, 15))
    pos_2pi = nx.pygraphviz_layout(Gtest,prog='twopi', root=focal_node_name)
    #pos_2pi = nx.graphviz_layout(Gtemp, prog='twopi', root=focal_node_name, args='')

    if network_algo == 'spl':

        all_SPs = nx.single_source_shortest_path_length(Gtemp, focal_node_name)
        cols = Series(index=nodes)
        all_SPs = Series(all_SPs)
        #cols[all_SPs.index]=all_SPs.values
        cols[border_cols.index]=border_cols

        pos = pos_2pi  # tree layout
        cmap = 'RdYlGn'  # inverted cool colormap
        plot_star = 'on'  # plot focal star

        vmin = np.min(cols); vmax = np.max(cols)  # anchor colormap

        cbar_label = 'fold change'  # label for colorbar

    elif network_algo == 'clustering_coefficient':
        all_CCs = nx.cluster.clustering(Gtemp, nodes=nodes)
        all_CCs = Series(all_CCs)
        cols = Series(index=nodes)
        cols[all_CCs.index] = all_CCs.values

        pos = pos_2pi  # tree layout
        cmap = 'cool_r'
        plot_star = 'on'  # plot focal star

        vmin = None; vmax = None  # don't anchor colormap

        cbar_label = 'clustering coefficient'  # label for colorbar


    elif network_algo == 'hotnet2':
        F = heat_diffusion_matrix(Gtemp, .001)
        h = np.zeros(numnodes)  # initialize heat vector
        h[focal_node] = 1
        E = heat_update(F, h)
        cols = E[:, focal_node]
        cols[focal_node] = 0  # set focal node to 0 for better cmap scale
        cols[focal_node] = max(cols)
        cols = Series(cols)

        cols.index = nodes

        pos = pos_2pi  # tree layout
        cmap = 'cool'
        plot_star = 'on'  # plot focal star

        vmin = np.min(cols); vmax = np.max(cols)  # anchor colormap

        cbar_label = 'node heat'  # label for colorbar

    elif network_algo == 'pagerank':
        pr_G = nx.pagerank(Gtemp)
        cols = Series(index=nodes)
        pr_G = Series(pr_G)
        cols[pr_G.index]=pr_G.values

        pos = nx.spring_layout(Gtemp)  #nx.spring_layout(Gtemp,k=.8)  # spring layout
        cmap = 'cool'
        plot_star = 'on'  # plot focal star

        vmin = min(cols); vmax = max(cols)  # anchor colormap

        cbar_label = 'page rank'  # label for colorbar

    elif network_algo == 'community':
        partition = community.best_partition(Gtemp)

        partition = Series(partition)

        # calculate average foldchange in each community
        avg_FC_comm = border_cols[nodes].groupby(partition[nodes]).median()
        std_FC_comm = border_cols[nodes].groupby(partition[nodes]).std()
        FC_value_counts = partition.value_counts()
        FC_df = DataFrame({'avg community FC':avg_FC_comm,'std community FC':std_FC_comm,'value counts':FC_value_counts})

        # find community of focal gene
        focal_comm = partition[focal_node_name]

        num_comms = len(partition.unique())
        vmin = 0; vmax = num_comms-1  # anchor colormap

        cols = Series(index=nodes)
        cols[nodes] = list(partition[nodes])

        pos = nx.spring_layout(Gtemp)  #nx.spring_layout(Gtemp,k=.8)
        cmap = 'hsv' #'gist_rainbow'
        plot_star = 'on'  # plot focal star

        cbar_label = 'community ID'  # label for colorbar

    # first draw border nodes
    if plot_border_col:
        nodes_col = nx.draw_networkx_nodes(Gtemp,pos=pos,node_color=border_cols,node_size=1600,alpha=.7,cmap='RdYlGn')
        cbar = fig.colorbar(nodes_col,shrink=.5)
        cbar.set_label('fold change', size=18)


    degree = Gtemp.degree()
    degree = Series(degree)
    if map_degree:
        deg_max = np.max(degree)
        degree = degree/deg_max
        degree = degree*1000
        deg_norm = degree[nodes]
    else:
        deg_norm = degree*0+1000
    not_nan_nodes = list(border_cols[~np.isnan(border_cols)].index)

    # then draw main nodes
    nodes_col = nx.draw_networkx_nodes(Gtemp,node_color=cols[not_nan_nodes],pos=pos,node_size=deg_norm[not_nan_nodes],
                                       cmap=cmap,edgelist=[],with_labels=True,labels=nodes,font_size=9,alpha=.9,
                                       font_color='k',vmin=vmin, vmax = vmax,nodelist = not_nan_nodes)
    # draw unmeasured nodes
    nan_nodes = list(border_cols[np.isnan(border_cols)].index);
    nx.draw_networkx_nodes(Gtemp,node_color = 'w',pos=pos,node_size=deg_norm[nan_nodes],
                         nodelist=nan_nodes)

    nx.draw_networkx_labels(Gtemp,pos=pos,font_size=9,font_color='k')
    xtemp = []
    ytemp = []
    for i in nodes:
        xtemp.append(pos[i][0])
        ytemp.append(pos[i][1])

    nx.draw_networkx_edges(Gtemp,pos=pos,alpha=0.05,width=2)

    if draw_shortest_paths==True:
        # highligh shortest paths from focal node
        paths = nx.all_pairs_shortest_path(Gtemp)
        path_focal = paths[focal_node_name]

        edge_list = []
        for n in path_focal.keys():
            path_temp = path_focal[n]
            edge_temp = zip(path_temp,path_temp[1:])
            edge_list.extend(edge_temp)

        nx.draw_networkx_edges(Gtemp,edgelist=edge_list,pos=pos,alpha=.2,width=4,edge_color='deepskyblue')
    else:
    	plot_star = 'off'


    if plot_star == 'on':   # only plot central star if plot_star flag is on
        if np.isnan(cols[focal_node_name]):
            col_temp = 'w'
        else:
            col_temp = cols[focal_node_name]
        nx.draw_networkx_nodes(Gtemp,pos=pos,nodelist=[focal_node_name],node_color = col_temp,
                              node_size=4000,cmap=cmap,vmin=vmin,vmax=vmax,node_shape='*')

    plt.xlim(-3,3)
    plt.axis('equal')

    if network_algo=='community':
        numcoms = len(partition.unique())
        cbar = fig.colorbar(nodes_col,shrink=.5,ticks=range(numcoms))

        # calculate modularity and a text box
        mod = community.modularity(dict(partition),Gtemp)
        #plt.text(-1,-1.1,'graph modularity = %.2f' % mod, fontsize=16)
        plt.title('graph modularity = %.2f' % mod, fontsize=16)
    else:
        cbar = fig.colorbar(nodes_col,shrink=.5)
    cbar.set_label(cbar_label, size=18)

    plt.grid('off')
    ax.set_axis_bgcolor('white')
    plt.xticks([]); plt.yticks([])

    if network_algo=='community':
        ax1 = plt.subplot(gs[1])
        df_partition_FC = DataFrame({'partition':partition,'fold_change':border_cols});
        df_partition_FC = df_partition_FC.sort(columns='partition')

        palette_temp = sns.color_palette('hls',numcoms)
        sns.boxplot(x='partition',y='fold_change',data=df_partition_FC,palette = palette_temp,saturation=.9)

        # plot location of focal datapoint if plot_star
        if plot_star == 'on':
        	ax1.plot(focal_comm,avg_FC_comm[focal_comm],marker = '*',
                    	markersize=24,markerfacecolor='w',markeredgecolor='k')

        plt.xlabel('community id',fontsize=14)
        plt.ylabel('average fold change in group', fontsize=14)

    return fig
Example #20
0
def _execute_networkx_layout(graph, nx_graph, graphtype):
    coords = nx.pygraphviz_layout(nx_graph, prog = graphtype)
    _nx_to_graph(coords, graph, True)
Example #21
0
def plot_height_portions(graph, budgets, height_portions):
    """
    For a few budget points, plot the average portion of predictions (across all accuracies)
    by filling in the ILSVRC65 nodes.
    """
    g = graph['g']
    nodes = graph['nodes']
    pos = nx.pygraphviz_layout(g, prog='twopi')

    gray = (0.75, 0.75, 0.75)
    graydark = (0.5, 0.5, 0.5)
    ns = 120

    labels = dict(
        zip(nodes, [g.node[node]['word'].split(',')[0] for node in nodes]))
    leaf_nodes = np.array(graph['nodes'])[graph['heights'] == 0]
    for node in leaf_nodes:
        labels[node] = ''

    cmap = plt.get_cmap('Oranges')
    fig = plt.figure(figsize=(20, 5.5))
    num_budget_points = 4
    for i, b in enumerate(
            np.linspace(0,
                        len(budgets) - 1, num_budget_points).astype('int')):
        for h in np.unique(graph['heights']):
            ax = fig.add_subplot(1, num_budget_points, i + 1)
            h_nodes = np.array(graph['nodes'])[graph['heights'] == h].tolist()
            c = np.minimum(1, height_portions.mean(1)[h][b] / .5)
            nx.draw_networkx_nodes(g,
                                   pos,
                                   nodelist=h_nodes,
                                   node_size=ns,
                                   node_color=cmap(c),
                                   ax=ax).set_edgecolor(graydark)
            if i == 0:
                if h > 0:
                    pos_offset = pos.copy()
                    for k in pos_offset.keys():
                        pos_offset[k] = (pos_offset[k][0],
                                         pos_offset[k][1] - 20)
                    nx.draw_networkx_labels(g,
                                            pos_offset,
                                            labels,
                                            font_size=12,
                                            font_color=graydark)
        nx.draw_networkx_edges(g,
                               pos,
                               arrows=False,
                               edge_color=[gray] * len(g.edges()),
                               ax=ax)
        ax.set_title('Budget: {}'.format(budgets[b]))
        plt.axis('off')
        plt.axis('equal')
    fig.tight_layout()

    fig = plt.figure()
    cmap = plt.cm.winter
    for h in range(height_portions.shape[0]):
        plt.plot(height_portions[h, 2, :],
                 label='height {}'.format(h),
                 color=cmap(1. * h / height_portions.shape[0]))
    plt.legend()
Example #22
0
def createGraph(infile, seed, flag):
    data = loadData(infile)
    DG = nx.DiGraph()
    for node in data:
        DG.add_node(node)
        DG.node[node]['layer'] = data[node]['layer']

    for node in data:
        edges = [(node, ref) for ref in data[node]['refs'] if ref in data]
        DG.add_edges_from(edges)

    ### Plot graph, assigning each layer a different color
    outfile = "test_layer_{0}.png".format(flag)
    pos = nx.pygraphviz_layout(DG)
    colors = [DG.node[node]['layer'] for node in DG.nodes()]
    size_cm = 90
    size_sp = 180
    sizes = [size_cm + size_sp * (node == seed) for node in DG.nodes()]

    nx.draw_networkx(DG,
                     pos,
                     node_color=colors,
                     cmap=plt.get_cmap('jet'),
                     node_size=sizes,
                     with_labels=False)
    plt.savefig(outfile)
    plt.clf()

    ### Graphviz
    A = nx.to_agraph(DG)
    layer_of_nodes = []
    layer = 0

    sorted_nodes = sorted(data.items(), key=lambda x: x[1]['layer'])
    layer_of_nodes = [k[0] for k in sorted_nodes if k[1]['layer'] == layer]
    while (len(layer_of_nodes) > 0):
        A.add_subgraph(layer_of_nodes, rank='same')
        layer += 1
        layer_of_nodes = [k[0] for k in sorted_nodes if k[1]['layer'] == layer]
    outfile = "test2_{0}.png".format(flag)
    A.draw(outfile, prog='dot')

    ### Find Communities
    #seed = 7037476
    G = DG.to_undirected()
    partition = community.best_partition(G)
    num_of_communities = sorted(partition.values(), reverse=True)[0] + 1
    print "number of communities: ", num_of_communities

    # number of nodes in each communites
    values = [partition.get(node) for node in G.nodes()]
    seed_community = partition.get(seed)
    print "seed belongs to community ", seed_community
    seed_community_lst = [
        node for node in G.nodes() if partition.get(node) == seed_community
    ]
    saveSeedCommunity(seed_community_lst, 'seed_community.p')
    counter = collections.Counter(values)
    print "number of nodes in each community: ", counter.most_common(
        num_of_communities)

    outfile = "test_communities_{0}.png".format(flag)
    pos = nx.pygraphviz_layout(DG)
    colors = [partition.get(node) for node in DG.nodes()]
    size_cm = 90
    size_sp = 180
    sizes = [size_cm + size_sp * (node == seed) for node in DG.nodes()]

    nx.draw_networkx(DG,
                     pos,
                     node_color=colors,
                     cmap=plt.get_cmap('jet'),
                     node_size=sizes,
                     with_labels=False)
    #nx.draw_networkx_nodes(G, pos, nodelist=[seed], node_size=size_sp, node_color = [partition.get(seed)], with_labels=False)
    plt.savefig(outfile)
    plt.clf()

    ### Draw community graph (each community is denoted as one node)
    CG = nx.DiGraph()
    keywords = community_keywords(data, partition)
    for i in range(num_of_communities):
        CG.add_node(i)
        CG.node[i]['keywords'] = keywords[i]

    for i in range(num_of_communities):
        if i == partition.get(seed):
            CG.node[i]['distance'] = 0
        else:
            CG.node[i]['distance'] = community_distance(DG, partition, seed, i)

    print nx.get_node_attributes(CG, 'distance')
    nodes_distance_lst = sorted(CG.nodes(),
                                key=lambda x: CG.node[x]['distance'],
                                reverse=True)
    for i in range(len(nodes_distance_lst)):
        target = nodes_distance_lst[i]
        for j in range(i + 1, len(nodes_distance_lst)):
            source = nodes_distance_lst[j]
            if community_direct_connectivity(DG, partition, source, target):
                CG.add_edge(source, target)
    """
	for source in CG.nodes():
		for target in CG.nodes():
			if source != target and community_connectivity(DG, partition, source, target):
				CG.add_edge(source, target)

	for e in CG.edges():
		for k in CG.nodes():
			if e[0] != k and (e[0], k) in CG.edges() and (k, e[1]) in CG.edges():
				CG.remove_edge(e[0], e[1])
				break
	"""

    print CG.edges()
    outfile = "test_concentrate_{0}.png".format(flag)
    pos = nx.pygraphviz_layout(CG)
    colors = [node for node in CG.nodes()]
    size_cm = 180
    size_sp = 270
    sizes = [
        size_cm + size_sp * (node == partition.get(seed))
        for node in CG.nodes()
    ]

    nx.draw_networkx(CG,
                     pos,
                     node_color=colors,
                     cmap=plt.get_cmap('jet'),
                     node_size=sizes,
                     with_labels=False)
    nx.draw_networkx_labels(CG, pos, labels=keywords)
    #nx.draw_networkx_nodes(G, pos, nodelist=[seed], node_size=size_sp, node_color = [partition.get(seed)], with_labels=False)
    plt.savefig(outfile)
    plt.clf()

    ### Find representatives in each community (naive way: based on degree centrality)
    degreeCentl = nx.in_degree_centrality(DG)
    print "representatives in each community: "
    community_index = 0
    representatives = []
    while (community_index < num_of_communities):
        nodes_lst = [
            node for node in DG if partition.get(node) == community_index
        ]
        tmp = sorted(nodes_lst, key=lambda x: degreeCentl[x],
                     reverse=True)[0:len(nodes_lst) / 5]
        #tmp = sorted(nodes_lst, key = lambda x:degreeCentl[x], reverse=True)[0:1]
        print tmp
        representatives += tmp
        community_index += 1
    # add the seed node
    representatives.append(seed)

    # community representative graph
    RG = nx.DiGraph()
    for node in representatives:
        RG.add_node(node)

    nodes_time_lst = sorted(RG.nodes(), key=lambda x: getYear(data[x]['date']))
    for i in range(len(nodes_time_lst)):
        target = nodes_time_lst[i]
        for j in range(i + 1, len(nodes_time_lst)):
            source = nodes_time_lst[j]
            if nx.has_path(DG, source, target):
                RG.add_edge(source, target)
                break

    # add direct reference edge
    #for node in nodes_time_lst:
    #	tmp = [k for k in data[node]['refs'] if k in nodes_time_lst]
    #	for ref in tmp:
    #		RG.add_edge(node, ref)
    """						
	for source in representatives:
		for target in representatives:
			if source != target and nx.has_path(DG, source, target):
				RG.add_edge(source, target)
	
	edge_lst = RG.edges()
	for e in RG.edges():
		for k in representatives:
			if e[0] != k and (e[0], k) in RG.edges() and (k, e[1]) in RG.edges():
				RG.remove_edge(e[0], e[1])
				break
	"""
    outfile = "representative_graph_{0}.png".format(flag)
    pos = nx.spring_layout(RG)
    size_cm = 180
    size_sp = 270
    colors = [partition.get(node) for node in RG]
    sizes = [size_cm + size_sp * (node == seed) for node in RG]
    nx.draw_networkx(RG,
                     pos,
                     node_color=colors,
                     cmap=plt.get_cmap('jet'),
                     node_size=sizes,
                     with_labels=True)
    plt.savefig(outfile)
    plt.clf()

    # draw the "important" papers layer-by-layer
    layer = 0
    RG.node[seed]['layer'] = layer
    curr_layer = [seed]
    while (len(curr_layer) > 0):
        next_layer = list(set([e[1] for e in RG.edges()
                               if e[0] in curr_layer]))
        layer += 1
        for node in next_layer:
            RG.node[node]['layer'] = layer
        curr_layer = next_layer

    A = nx.to_agraph(RG)
    layer = 0
    layer_of_nodes = [k for k in RG.nodes() if RG.node[k]['layer'] == layer]
    while (len(layer_of_nodes) > 0):
        A.add_subgraph(layer_of_nodes, rank='same')
        layer += 1
        layer_of_nodes = [
            k for k in RG.nodes() if RG.node[k]['layer'] == layer
        ]
    outfile = "test3_{0}.png".format(flag)
    A.draw(outfile, prog='dot')
    """
Example #23
0
    def do_layout(self, size=None, force=False):
        """ Nodes of the graph will be layed out based on the the style
            attribute
        """
        if not self._graph_layout_needed or len(self.components) == 0:
            return
        import pdb

        pdb.set_trace()

        def _apply_graphviz_layout(layout):
            min_x = min([pos[0] for pos in layout.values()])
            max_y = max([pos[1] for pos in layout.values()])

            for component in self.components:
                component.x = layout[component._key][0] - min_x
                component.y = self.height - max_y + layout[component._key][1]

        if self.style == "tree":
            layout = networkx.pygraphviz_layout(self.graph, prog="dot")

            # resize the bounds to fit the graph
            depths = [v[1] for v in layout.values()]
            widths = [depths.count(d) for d in numpy.unique(depths)]
            max_width = max(widths)
            max_depth = len(widths)

            self.bounds = [
                max(75, self.components[0].width) * max_width,
                max(50, self.components[0].height) * max_depth,
            ]

            for component in self.components:
                component.x = self.width * layout[component._key][0]
                component.y = self.height * layout[component._key][1]

            _apply_graphviz_layout(layout)

        elif self.style == "shell":
            layout = networkx.shell_layout(self.graph)

            # resize the bounds to fit the graph
            radius = numpy.log2(len(layout))
            self.bounds = [
                max(75, self.components[0].width) * 2 * radius,
                max(50, self.components[0].height) * 2 * radius,
            ]

            for component in self.components:
                component.y = self.height * (1 + layout[component._key][0]) / 2
                component.x = self.width * (1 + layout[component._key][1]) / 2
        elif self.style == "circular":
            layout = networkx.pygraphviz_layout(self.graph, prog="twopi")

            # resize the bounds to fit the graph
            radius = numpy.log2(len(layout))
            self.bounds = [
                max(75, self.components[0].width) * 2 * radius,
                max(50, self.components[0].height) * 2 * radius,
            ]
            _apply_graphviz_layout(layout)
        else:
            layout = networkx.spring_layout(self.graph)

            # resize the bounds to fit the graph
            radius = numpy.log2(len(layout))
            self.bounds = [
                max(75, self.components[0].width) * 2 * radius,
                max(50, self.components[0].height) * 2 * radius,
            ]
            # print "HELLLLLLLLO"
            for component in self.components:
                component.x = self.width * layout[component._key][0]
                component.y = self.height * layout[component._key][1]

        self._graph_layout_needed = False
Example #24
0
def save_graph(gr,start_node=None,all_solutions=[],filename=None,size=(45,25),use_cloud=False):
    print "Drawing...",
    plt.figure(1,figsize=size)

    sols = all_solutions[0] if len(all_solutions) else None
    shortest_n = (len(all_solutions[0])-1) if len(all_solutions) else None # number (-1) for shortest path

    # not all labels should be displayed, only those that are part of the solution
    labels = {}
    #labels_anyway = True
    labels_anyway = False
    if sols or labels_anyway:
        for n in gr.nodes():
            if not labels_anyway and n not in sols:
                labels[n] = ""
            else:
                labels[n] = str(n)

    # labels for length of shortest path to each final node
    final_labels = {}
    for s in all_solutions:
        for i in xrange(len(s)):
            n = s[i]
            if i == len(s)-1:
                final_labels[n] = len(s)-1
                if len(s)-1 != shortest_n: # display number on only the finals which are shortest
                    final_labels[n] = ''

    # assign edges to path (to draw highlighted)
    if sols:
        path = []
        for i in xrange(len(sols)-1):
            u = sols[i]
            v = sols[i+1]
            e = (u,v)
            path.append(e)

    #pos=nx.pygraphviz_layout(gr)
    pos=nx.pygraphviz_layout(gr,prog='sfdp') # sfdp for large graphs
    #pos=nx.graphviz_layout(gr,prog="twopi",root=start_node)
    #pos=nx.graphviz_layout(gr,prog='twopi',args='')
    #pos=nx.spring_layout(gr) # positions for all nodes

    if sols:
        # begin
        nx.draw(gr,pos,edgelist=[],nodelist=[sols[0]],node_size=500,alpha=0.5,node_color='b',with_labels=False)
        # finals
        nx.draw(gr,pos,edgelist=[],nodelist=gr.graph['finals'],node_size=30,alpha=0.5,node_color='y',font_size=16,labels=final_labels)
        # end
        nx.draw(gr,pos,edgelist=[],nodelist=[sols[len(sols)-1]],node_size=500,alpha=0.5,node_color='g',with_labels=False)
        # path
        nx.draw(gr,pos,edgelist=path,nodelist=sols,width=3,node_size=10,alpha=0.5,edge_color='r',font_family="monospace",font_size=10,with_labels=False)

    # all the nodes with labels along path only
    # with_labels=(sols and len(sols)<1000),labels=labels if sols else None
    nx.draw(gr,pos,node_size=2,alpha=0.2,root=start_node,font_family="monospace",font_size=9,with_labels=False,labels=labels)

    print "done drawing"

    # either save file or return plot
    if filename:
        d = os.path.dirname(filename)
        if not os.path.exists(d):
            os.makedirs(d)
        plt.savefig(filename)
        plt.close()

        if use_cloud:
            import cloud
            cloud.files.put(filename)

    else:
        return plt
Example #25
0
def draw_graphviz(tree, label_func=str, prog='twopi', args='',
        node_color='#c0deff', **kwargs):
    """Display a tree or clade as a graph, using the graphviz engine.

    Requires NetworkX, matplotlib, Graphviz and either PyGraphviz or pydot.

    Example:

        >>> import pylab
        >>> from Bio import Phylo
        >>> tree = Phylo.read('ex/apaf.xml', 'phyloxml')
        >>> Phylo.draw_graphviz(tree)
        >>> pylab.show()
        >>> pylab.savefig('apaf.png')

    The third and fourth parameters apply to Graphviz, and the remaining
    arbitrary keyword arguments are passed directly to networkx.draw(), which
    in turn mostly wraps matplotlib/pylab.  See the documentation for Graphviz
    and networkx for detailed explanations.

    The NetworkX/matplotlib parameters are described in the docstrings for
    networkx.draw() and pylab.scatter(), but the most reasonable options to try
    are: I{ alpha, node_color, node_size, node_shape, edge_color, style,
    font_size, font_color, font_weight, font_family }

    @param label_func: A function to extract a label from a node. By default
        this is str(), but you can use a different function to select another
        string associated with each node. If this function returns None for a
        node, no label will be shown for that node.

        The label will also be silently skipped if the throws an exception
        related to ordinary attribute access (LookupError, AttributeError,
        ValueError); all other exception types will still be raised. This
        means you can use a lambda expression that simply attempts to look up
        the desired value without checking if the intermediate attributes are
        available:

            >>> Phylo.draw_graphviz(tree, lambda n: n.taxonomies[0].code)

    @param prog: The Graphviz program to use when rendering the graph. 'twopi'
        behaves the best for large graphs, reliably avoiding crossing edges, but
        for moderate graphs 'neato' looks a bit nicer.  For small directed
        graphs, 'dot' may produce the most normal-looking phylogram, but will
        cross and distort edges in larger graphs. (The programs 'circo' and
        'fdp' are not recommended.)

    @param args: String of options passed to the external graphviz program.
        Normally not needed, but offered here for completeness.
    """
    try:
        import networkx
    except ImportError:
        from Bio import MissingPythonDependencyError
        raise MissingPythonDependencyError(
                "Install NetworkX if you want to use to_networkx.")

    G = to_networkx(tree)
    Gi = networkx.convert_node_labels_to_integers(G, discard_old_labels=False)
    try:
        posi = networkx.pygraphviz_layout(Gi, prog, args=args)
    except ImportError:
        try:
            posi = networkx.pydot_layout(Gi, prog)
        except ImportError:
            raise MissingPythonDependencyError(
                    "Install PyGraphviz or Pydot if you want to use "
                    "draw_graphviz.")
    posn = dict((n, posi[Gi.node_labels[n]]) for n in G)

    def get_label_mapping(G, selection):
        for node in G.nodes():
            if (selection is None) or (node in selection):
                try:
                    label = label_func(node)
                    if label not in (None, node.__class__.__name__):
                        yield (node, label)
                except (LookupError, AttributeError, ValueError):
                    pass

    if 'nodelist' in kwargs:
        labels = dict(get_label_mapping(G, set(kwargs['nodelist'])))
    else:
        labels = dict(get_label_mapping(G, None))
    kwargs['nodelist'] = labels.keys()
    if 'edge_color' not in kwargs:
        kwargs['edge_color'] = [isinstance(e[2], dict) and
                                e[2].get('color', 'k') or 'k'
                                for e in G.edges(data=True)]
    if 'width' not in kwargs:
        kwargs['width'] = [isinstance(e[2], dict) and
                           e[2].get('width', 1.0) or 1.0
                           for e in G.edges(data=True)]
    networkx.draw(G, posn, labels=labels, node_color=node_color, **kwargs)
Example #26
0
for mouse, parents in tree_data.iteritems():
    for parent in parents:
        G.add_edge(parent, mouse, weight=1)

mouse_l = mouse2age.keys()
for mouse in mouse_l:
    if mouse2age[mouse] is None:
        mouse2age[mouse] = np.max(mouse2age.values())

mouse_l = mouse2age.keys()
age_l = mouse2age.values()
mouse_rank_l = np.argsort(np.argsort(age_l))
mouse_rank_a = np.asarray(mouse_rank_l) / float(len(mouse_rank_l))

# Draw
pos = nx.pygraphviz_layout(G, prog='dot')
#~ pos = nx.shell_layout(G)
for nmouse, mouse in enumerate(mouse_l):
    pos[mouse] = np.asarray(pos[mouse])
    #~ pos[mouse][1] = mouse_rank_a[nmouse]

for nmouse, mouse in enumerate(mouse_l):
    # Make it go R to L instead of U to D
    pos[mouse] = np.asarray(pos[mouse])[::-1]
    
    # Make it go L to R
    pos[mouse][0] = -pos[mouse][0]

f, ax = plt.subplots(figsize=(10, 10))
nx.draw(G, pos, ax=ax, with_labels=True, node_color='none', node_shape='.', node_size=0, arrows=False)
Example #27
0
File: draw.py Project: rkdarst/pcd
def layout(g):
    #pos = networkx.pydot_layout(g, prog='fdp')
    pos = networkx.pygraphviz_layout(g, prog='neato')
    return pos
def plot_network(Gtest, border_cols, md_network, focal_node_name, edge_thresh,
                 network_algo, map_degree, plot_border_col,
                 draw_shortest_paths, coexpression, colocalization, other,
                 physical_interactions, predicted_interactions,
                 shared_protein_domain):

    nodes = Gtest.nodes()
    node_series = Series(nodes)

    focal_node = list(node_series[node_series == focal_node_name].index)[0]

    numnodes = len(Gtest)

    # deal with case where no border_cols input
    if len(border_cols) < numnodes:
        border_cols = Series(np.ones(numnodes))
        border_cols.index = nodes

    # create a new dataframe mapping network_group value to edges
    e1e2 = Series(
        zip(list(md_network['Entity 1']), list(md_network['Entity 2']),
            list(md_network['Weight'])))
    e1e2NG_df = DataFrame(data={
        'e1e2': e1e2,
        'Network_group': md_network['Network_group']
    })

    # find all coexpression edges
    sum(md_network['Network_group'] == 'Co-expression')

    # select 'Co-expression' edges
    edge_list_CE = list(
        e1e2NG_df.e1e2[e1e2NG_df.Network_group == 'Co-expression'])
    # select 'Co-localization' edges
    edge_list_CL = list(
        e1e2NG_df.e1e2[e1e2NG_df.Network_group == 'Co-localization'])
    # select 'Other' edges
    edge_list_OTHER = list(e1e2NG_df.e1e2[e1e2NG_df.Network_group == 'Other'])
    # select 'Physical interactions' edges
    edge_list_PI = list(
        e1e2NG_df.e1e2[e1e2NG_df.Network_group == 'Physical interactions'])
    # select 'Predicted' edges
    edge_list_PRED = list(
        e1e2NG_df.e1e2[e1e2NG_df.Network_group == 'Predicted'])
    # select 'Shared protein domain' edges
    edge_list_SPD = list(
        e1e2NG_df.e1e2[e1e2NG_df.Network_group == 'Shared protein domains'])

    edge_list_total = []
    if coexpression:
        edge_list_total.extend(edge_list_CE)
    if colocalization:
        edge_list_total.extend(edge_list_CL)
    if other:
        edge_list_total.extend(edge_list_OTHER)
    if physical_interactions:
        edge_list_total.extend(edge_list_PI)
    if predicted_interactions:
        edge_list_total.extend(edge_list_PRED)
    if shared_protein_domain:
        edge_list_total.extend(edge_list_SPD)

    # find edges < threshold
    elarge = [(u, v) for (u, v, d) in edge_list_total if d > edge_thresh]
    esmall = [(u, v) for (u, v, d) in edge_list_total if d <= edge_thresh]

    # create temp network for calculations
    Gtemp = nx.Graph()
    Gtemp.add_nodes_from(Gtest.nodes())
    Gtemp.add_edges_from(elarge)

    if network_algo == 'community':
        fig = plt.figure(figsize=(20, 25))
        gs = gridspec.GridSpec(2, 1, height_ratios=[2, 1])
        ax = plt.subplot(gs[0])
    else:
        fig, ax = plt.subplots(figsize=(20, 15))
    pos_2pi = nx.pygraphviz_layout(Gtest, prog='twopi', root=focal_node_name)
    #pos_2pi = nx.graphviz_layout(Gtemp, prog='twopi', root=focal_node_name, args='')

    if network_algo == 'spl':

        all_SPs = nx.single_source_shortest_path_length(Gtemp, focal_node_name)
        cols = Series(index=nodes)
        all_SPs = Series(all_SPs)
        #cols[all_SPs.index]=all_SPs.values
        cols[border_cols.index] = border_cols

        pos = pos_2pi  # tree layout
        cmap = 'RdYlGn'  # inverted cool colormap
        plot_star = 'on'  # plot focal star

        vmin = np.min(cols)
        vmax = np.max(cols)  # anchor colormap

        cbar_label = 'fold change'  # label for colorbar

    elif network_algo == 'clustering_coefficient':
        all_CCs = nx.cluster.clustering(Gtemp, nodes=nodes)
        all_CCs = Series(all_CCs)
        cols = Series(index=nodes)
        cols[all_CCs.index] = all_CCs.values

        pos = pos_2pi  # tree layout
        cmap = 'cool_r'
        plot_star = 'on'  # plot focal star

        vmin = None
        vmax = None  # don't anchor colormap

        cbar_label = 'clustering coefficient'  # label for colorbar

    elif network_algo == 'hotnet2':
        F = heat_diffusion_matrix(Gtemp, .001)
        h = np.zeros(numnodes)  # initialize heat vector
        h[focal_node] = 1
        E = heat_update(F, h)
        cols = E[:, focal_node]
        cols[focal_node] = 0  # set focal node to 0 for better cmap scale
        cols[focal_node] = max(cols)
        cols = Series(cols)

        cols.index = nodes

        pos = pos_2pi  # tree layout
        cmap = 'cool'
        plot_star = 'on'  # plot focal star

        vmin = np.min(cols)
        vmax = np.max(cols)  # anchor colormap

        cbar_label = 'node heat'  # label for colorbar

    elif network_algo == 'pagerank':
        pr_G = nx.pagerank(Gtemp)
        cols = Series(index=nodes)
        pr_G = Series(pr_G)
        cols[pr_G.index] = pr_G.values

        pos = nx.spring_layout(
            Gtemp)  #nx.spring_layout(Gtemp,k=.8)  # spring layout
        cmap = 'cool'
        plot_star = 'on'  # plot focal star

        vmin = min(cols)
        vmax = max(cols)  # anchor colormap

        cbar_label = 'page rank'  # label for colorbar

    elif network_algo == 'community':
        partition = community.best_partition(Gtemp)

        partition = Series(partition)

        # calculate average foldchange in each community
        avg_FC_comm = border_cols[nodes].groupby(partition[nodes]).median()
        std_FC_comm = border_cols[nodes].groupby(partition[nodes]).std()
        FC_value_counts = partition.value_counts()
        FC_df = DataFrame({
            'avg community FC': avg_FC_comm,
            'std community FC': std_FC_comm,
            'value counts': FC_value_counts
        })

        # find community of focal gene
        focal_comm = partition[focal_node_name]

        num_comms = len(partition.unique())
        vmin = 0
        vmax = num_comms - 1  # anchor colormap

        cols = Series(index=nodes)
        cols[nodes] = list(partition[nodes])

        pos = nx.spring_layout(Gtemp)  #nx.spring_layout(Gtemp,k=.8)
        cmap = 'hsv'  #'gist_rainbow'
        plot_star = 'on'  # plot focal star

        cbar_label = 'community ID'  # label for colorbar

    # first draw border nodes
    if plot_border_col:
        nodes_col = nx.draw_networkx_nodes(Gtemp,
                                           pos=pos,
                                           node_color=border_cols,
                                           node_size=1600,
                                           alpha=.7,
                                           cmap='RdYlGn')
        cbar = fig.colorbar(nodes_col, shrink=.5)
        cbar.set_label('fold change', size=18)

    degree = Gtemp.degree()
    degree = Series(degree)
    if map_degree:
        deg_max = np.max(degree)
        degree = degree / deg_max
        degree = degree * 1000
        deg_norm = degree[nodes]
    else:
        deg_norm = degree * 0 + 1000
    not_nan_nodes = list(border_cols[~np.isnan(border_cols)].index)

    # then draw main nodes
    nodes_col = nx.draw_networkx_nodes(Gtemp,
                                       node_color=cols[not_nan_nodes],
                                       pos=pos,
                                       node_size=deg_norm[not_nan_nodes],
                                       cmap=cmap,
                                       edgelist=[],
                                       with_labels=True,
                                       labels=nodes,
                                       font_size=9,
                                       alpha=.9,
                                       font_color='k',
                                       vmin=vmin,
                                       vmax=vmax,
                                       nodelist=not_nan_nodes)
    # draw unmeasured nodes
    nan_nodes = list(border_cols[np.isnan(border_cols)].index)
    nx.draw_networkx_nodes(Gtemp,
                           node_color='w',
                           pos=pos,
                           node_size=deg_norm[nan_nodes],
                           nodelist=nan_nodes)

    nx.draw_networkx_labels(Gtemp, pos=pos, font_size=9, font_color='k')
    xtemp = []
    ytemp = []
    for i in nodes:
        xtemp.append(pos[i][0])
        ytemp.append(pos[i][1])

    nx.draw_networkx_edges(Gtemp, pos=pos, alpha=0.05, width=2)

    if draw_shortest_paths == True:
        # highligh shortest paths from focal node
        paths = nx.all_pairs_shortest_path(Gtemp)
        path_focal = paths[focal_node_name]

        edge_list = []
        for n in path_focal.keys():
            path_temp = path_focal[n]
            edge_temp = zip(path_temp, path_temp[1:])
            edge_list.extend(edge_temp)

        nx.draw_networkx_edges(Gtemp,
                               edgelist=edge_list,
                               pos=pos,
                               alpha=.2,
                               width=4,
                               edge_color='deepskyblue')
    else:
        plot_star = 'off'

    if plot_star == 'on':  # only plot central star if plot_star flag is on
        if np.isnan(cols[focal_node_name]):
            col_temp = 'w'
        else:
            col_temp = cols[focal_node_name]
        nx.draw_networkx_nodes(Gtemp,
                               pos=pos,
                               nodelist=[focal_node_name],
                               node_color=col_temp,
                               node_size=4000,
                               cmap=cmap,
                               vmin=vmin,
                               vmax=vmax,
                               node_shape='*')

    plt.xlim(-3, 3)
    plt.axis('equal')

    if network_algo == 'community':
        numcoms = len(partition.unique())
        cbar = fig.colorbar(nodes_col, shrink=.5, ticks=range(numcoms))

        # calculate modularity and a text box
        mod = community.modularity(dict(partition), Gtemp)
        #plt.text(-1,-1.1,'graph modularity = %.2f' % mod, fontsize=16)
        plt.title('graph modularity = %.2f' % mod, fontsize=16)
    else:
        cbar = fig.colorbar(nodes_col, shrink=.5)
    cbar.set_label(cbar_label, size=18)

    plt.grid('off')
    ax.set_axis_bgcolor('white')
    plt.xticks([])
    plt.yticks([])

    if network_algo == 'community':
        ax1 = plt.subplot(gs[1])
        df_partition_FC = DataFrame({
            'partition': partition,
            'fold_change': border_cols
        })
        df_partition_FC = df_partition_FC.sort(columns='partition')

        palette_temp = sns.color_palette('hls', numcoms)
        sns.boxplot(x='partition',
                    y='fold_change',
                    data=df_partition_FC,
                    palette=palette_temp,
                    saturation=.9)

        # plot location of focal datapoint if plot_star
        if plot_star == 'on':
            ax1.plot(focal_comm,
                     avg_FC_comm[focal_comm],
                     marker='*',
                     markersize=24,
                     markerfacecolor='w',
                     markeredgecolor='k')

        plt.xlabel('community id', fontsize=14)
        plt.ylabel('average fold change in group', fontsize=14)

    return fig
Example #29
0
def draw_markov_model(model, fnum=None, **kwargs):
    import plottool as pt
    fnum = pt.ensure_fnum(fnum)
    pt.figure(fnum=fnum, doclf=True)
    ax = pt.gca()
    from pgmpy.models import MarkovModel
    if isinstance(model, MarkovModel):
        markovmodel = model
    else:
        markovmodel = model.to_markov_model()
    # pos = netx.pydot_layout(markovmodel)
    pos = netx.pygraphviz_layout(markovmodel)
    # Referenecs:
    # https://groups.google.com/forum/#!topic/networkx-discuss/FwYk0ixLDuY

    # pos = netx.spring_layout(markovmodel)
    # pos = netx.circular_layout(markovmodel)
    # curved-arrow
    # markovmodel.edge_attr['curved-arrow'] = True
    # markovmodel.graph.setdefault('edge', {})['splines'] = 'curved'
    # markovmodel.graph.setdefault('graph', {})['splines'] = 'curved'
    # markovmodel.graph.setdefault('edge', {})['splines'] = 'curved'

    node_color = [pt.NEUTRAL] * len(pos)
    drawkw = dict(pos=pos, ax=ax, with_labels=True, node_color=node_color,  # NOQA
                  node_size=1100)

    from matplotlib.patches import FancyArrowPatch, Circle
    import numpy as np

    def draw_network(G, pos, ax, sg=None):
        for n in G:
            c = Circle(pos[n], radius=10, alpha=0.5, color=pt.NEUTRAL_BLUE)
            ax.add_patch(c)
            G.node[n]['patch'] = c
            x, y = pos[n]
            pt.ax_absolute_text(x, y, n, ha='center', va='center')
        seen = {}
        for (u, v, d) in G.edges(data=True):
            n1 = G.node[u]['patch']
            n2 = G.node[v]['patch']
            rad = 0.1
            if (u, v) in seen:
                rad = seen.get((u, v))
                rad = (rad + np.sign(rad) * 0.1) * -1
            alpha = 0.5
            color = 'k'

            e = FancyArrowPatch(n1.center, n2.center, patchA=n1, patchB=n2,
                                # arrowstyle='-|>',
                                arrowstyle='-',
                                connectionstyle='arc3,rad=%s' % rad,
                                mutation_scale=10.0,
                                lw=2,
                                alpha=alpha,
                                color=color)
            seen[(u, v)] = rad
            ax.add_patch(e)
        return e
    # netx.draw(markovmodel, **drawkw)
    draw_network(markovmodel, pos, ax)
    ax.autoscale()
    pt.plt.axis('equal')
    pt.plt.axis('off')

    if kwargs.get('show_title', True):
        pt.set_figtitle('Markov Model')
Example #30
0
 def show(self):
     pos = nx.pygraphviz_layout(self.g, prog='dot', root=0)
     nx.draw_networkx(self.g, pos=pos, node_color='w', node_size=500,
                      labels={n:self.g.node[n]['label'] for n in self.g.nodes()})
     plt.show()
Example #31
0
def createGraph(infile, seed, flag):
	data = loadData(infile)
	DG = nx.DiGraph()
	for node in data:
		DG.add_node(node)
		DG.node[node]['layer'] = data[node]['layer']
	
	for node in data:
		edges = [(node, ref) for ref in data[node]['refs'] if ref in data]
		DG.add_edges_from(edges)

	### Plot graph, assigning each layer a different color	
	outfile = "test_layer_{0}.png".format(flag)
	pos = nx.pygraphviz_layout(DG)
	colors = [DG.node[node]['layer'] for node in DG.nodes()]
	size_cm = 90
        size_sp = 180
        sizes = [size_cm + size_sp*(node==seed) for node in DG.nodes()]

	nx.draw_networkx(DG, pos, node_color = colors, cmap=plt.get_cmap('jet'), node_size=sizes, with_labels=False)
	plt.savefig(outfile)
	plt.clf()

	### Graphviz
	A = nx.to_agraph(DG)
	layer_of_nodes = []
	layer = 0
	
	sorted_nodes = sorted(data.items(), key = lambda x: x[1]['layer'])
	layer_of_nodes = [k[0] for k in sorted_nodes if k[1]['layer'] == layer]
	while (len(layer_of_nodes) > 0):
		A.add_subgraph(layer_of_nodes, rank='same')
		layer += 1
		layer_of_nodes = [k[0] for k in sorted_nodes if k[1]['layer'] == layer]
	outfile = "test2_{0}.png".format(flag)
	A.draw(outfile, prog='dot')	 									

	### Find Communities
	#seed = 7037476
	G = DG.to_undirected()
	partition = community.best_partition(G)
	num_of_communities = sorted(partition.values(), reverse=True)[0] + 1
	print "number of communities: ", num_of_communities

	# number of nodes in each communites
	values = [partition.get(node) for node in G.nodes()]
	seed_community = partition.get(seed)
	print "seed belongs to community ", seed_community
	seed_community_lst = [node for node in G.nodes() if partition.get(node) == seed_community]
	saveSeedCommunity(seed_community_lst, 'seed_community.p')
	counter = collections.Counter(values)
	print "number of nodes in each community: ", counter.most_common(num_of_communities)

	outfile = "test_communities_{0}.png".format(flag)
	pos = nx.pygraphviz_layout(DG)
	colors = [partition.get(node) for node in DG.nodes()]
	size_cm = 90
	size_sp = 180
	sizes = [size_cm + size_sp*(node==seed) for node in DG.nodes()]
	
	nx.draw_networkx(DG, pos, node_color = colors, cmap=plt.get_cmap('jet'), node_size = sizes, with_labels=False)
	#nx.draw_networkx_nodes(G, pos, nodelist=[seed], node_size=size_sp, node_color = [partition.get(seed)], with_labels=False)
	plt.savefig(outfile)
	plt.clf()

	
	### Draw community graph (each community is denoted as one node)
	CG = nx.DiGraph()
	keywords = community_keywords(data, partition)
	for i in range(num_of_communities):
		CG.add_node(i)
		CG.node[i]['keywords'] = keywords[i]	

	for i in range(num_of_communities):
		if i == partition.get(seed):
			CG.node[i]['distance'] = 0
		else:
			CG.node[i]['distance'] = community_distance(DG, partition, seed, i) 	

	print nx.get_node_attributes(CG, 'distance')
	nodes_distance_lst = sorted(CG.nodes(), key = lambda x: CG.node[x]['distance'], reverse=True)
	for i in range(len(nodes_distance_lst)):
                target = nodes_distance_lst[i]
                for j in range(i+1, len(nodes_distance_lst)):
                        source = nodes_distance_lst[j]
                        if community_direct_connectivity(DG, partition, source, target):
                                CG.add_edge(source, target)
	"""
	for source in CG.nodes():
		for target in CG.nodes():
			if source != target and community_connectivity(DG, partition, source, target):
				CG.add_edge(source, target)

	for e in CG.edges():
		for k in CG.nodes():
			if e[0] != k and (e[0], k) in CG.edges() and (k, e[1]) in CG.edges():
				CG.remove_edge(e[0], e[1])
				break
	"""

	print CG.edges() 
	outfile = "test_concentrate_{0}.png".format(flag)
        pos = nx.pygraphviz_layout(CG)
        colors = [node for node in CG.nodes()]
        size_cm = 180
        size_sp = 270
        sizes = [size_cm + size_sp*(node==partition.get(seed)) for node in CG.nodes()]

        nx.draw_networkx(CG, pos, node_color = colors, cmap=plt.get_cmap('jet'), node_size = sizes, with_labels=False)
        nx.draw_networkx_labels(CG, pos, labels = keywords)
	#nx.draw_networkx_nodes(G, pos, nodelist=[seed], node_size=size_sp, node_color = [partition.get(seed)], with_labels=False)
        plt.savefig(outfile)
        plt.clf()	

	### Find representatives in each community (naive way: based on degree centrality)
	degreeCentl = nx.in_degree_centrality(DG)
	print "representatives in each community: "
	community_index = 0
	representatives = []
	while(community_index < num_of_communities):
		nodes_lst = [node for node in DG if partition.get(node) == community_index]
		tmp = sorted(nodes_lst, key = lambda x:degreeCentl[x], reverse=True)[0:len(nodes_lst)/5]
		#tmp = sorted(nodes_lst, key = lambda x:degreeCentl[x], reverse=True)[0:1]
		print tmp
		representatives += tmp
		community_index += 1
	# add the seed node
	representatives.append(seed)

	# community representative graph
	RG = nx.DiGraph()
	for node in representatives:
		RG.add_node(node)
	
	nodes_time_lst = sorted(RG.nodes(), key = lambda x: getYear(data[x]['date']))
	for i in range(len(nodes_time_lst)):
		target = nodes_time_lst[i]
		for j in range(i+1, len(nodes_time_lst)):
			source = nodes_time_lst[j]
			if nx.has_path(DG, source, target):
				RG.add_edge(source, target)
				break
		
	# add direct reference edge
	#for node in nodes_time_lst:
	#	tmp = [k for k in data[node]['refs'] if k in nodes_time_lst]
	#	for ref in tmp:
	#		RG.add_edge(node, ref)
	"""						
	for source in representatives:
		for target in representatives:
			if source != target and nx.has_path(DG, source, target):
				RG.add_edge(source, target)
	
	edge_lst = RG.edges()
	for e in RG.edges():
		for k in representatives:
			if e[0] != k and (e[0], k) in RG.edges() and (k, e[1]) in RG.edges():
				RG.remove_edge(e[0], e[1])
				break
	"""	
	outfile = "representative_graph_{0}.png".format(flag)
	pos = nx.spring_layout(RG)
	size_cm = 180
	size_sp = 270
	colors = [partition.get(node) for node in RG]
	sizes = [size_cm + size_sp*(node==seed) for node in RG]
	nx.draw_networkx(RG, pos, node_color = colors, cmap=plt.get_cmap('jet'), node_size = sizes, with_labels = True)
	plt.savefig(outfile)
	plt.clf() 	
	
	# draw the "important" papers layer-by-layer
	layer = 0
	RG.node[seed]['layer'] = layer
	curr_layer = [seed]
	while(len(curr_layer) > 0):
		next_layer = list(set([e[1] for e in RG.edges() if e[0] in curr_layer]))
		layer += 1
		for node in next_layer:
			RG.node[node]['layer'] = layer
		curr_layer = next_layer
				
	A = nx.to_agraph(RG)
	layer = 0
	layer_of_nodes = [k for k in RG.nodes() if RG.node[k]['layer'] == layer]
	while (len(layer_of_nodes) > 0):
		A.add_subgraph(layer_of_nodes, rank='same')
		layer += 1
		layer_of_nodes = [k for k in RG.nodes() if RG.node[k]['layer'] == layer]
	outfile = "test3_{0}.png".format(flag)
	A.draw(outfile, prog='dot')
	"""
Example #32
0
def _execute_networkx_layout(graph, nx_graph, graphtype):
    coords = nx.pygraphviz_layout(nx_graph, prog=graphtype)
    _nx_to_graph(coords, graph, True)
Example #33
0
def draw_graphviz(tree, label_func=str, prog='twopi', args='',
        node_color='#c0deff', **kwargs):
    """Display a tree or clade as a graph, using the graphviz engine.

    Requires NetworkX, matplotlib, Graphviz and either PyGraphviz or pydot.

    The third and fourth parameters apply to Graphviz, and the remaining
    arbitrary keyword arguments are passed directly to networkx.draw(), which
    in turn mostly wraps matplotlib/pylab.  See the documentation for Graphviz
    and networkx for detailed explanations.

    The NetworkX/matplotlib parameters are described in the docstrings for
    networkx.draw() and pylab.scatter(), but the most reasonable options to try
    are: *alpha, node_color, node_size, node_shape, edge_color, style,
    font_size, font_color, font_weight, font_family*

    :Parameters:

        label_func : callable
            A function to extract a label from a node. By default this is str(),
            but you can use a different function to select another string
            associated with each node. If this function returns None for a node,
            no label will be shown for that node.

            The label will also be silently skipped if the throws an exception
            related to ordinary attribute access (LookupError, AttributeError,
            ValueError); all other exception types will still be raised. This
            means you can use a lambda expression that simply attempts to look
            up the desired value without checking if the intermediate attributes
            are available:

                >>> Phylo.draw_graphviz(tree, lambda n: n.taxonomies[0].code)

        prog : string
            The Graphviz program to use when rendering the graph. 'twopi'
            behaves the best for large graphs, reliably avoiding crossing edges,
            but for moderate graphs 'neato' looks a bit nicer.  For small
            directed graphs, 'dot' may produce the most normal-looking
            phylogram, but will cross and distort edges in larger graphs. (The
            programs 'circo' and 'fdp' are not recommended.)
        args : string
            Options passed to the external graphviz program.  Normally not
            needed, but offered here for completeness.

    Example
    -------

    >>> import pylab
    >>> from Bio import Phylo
    >>> tree = Phylo.read('ex/apaf.xml', 'phyloxml')
    >>> Phylo.draw_graphviz(tree)
    >>> pylab.show()
    >>> pylab.savefig('apaf.png')
    """
    try:
        import networkx
    except ImportError:
        from Bio import MissingPythonDependencyError
        raise MissingPythonDependencyError(
                "Install NetworkX if you want to use to_networkx.")

    G = to_networkx(tree)
    Gi = networkx.convert_node_labels_to_integers(G, discard_old_labels=False)
    try:
        posi = networkx.pygraphviz_layout(Gi, prog, args=args)
    except ImportError:
        try:
            posi = networkx.pydot_layout(Gi, prog)
        except ImportError:
            raise MissingPythonDependencyError(
                    "Install PyGraphviz or Pydot if you want to use "
                    "draw_graphviz.")
    posn = dict((n, posi[Gi.node_labels[n]]) for n in G)

    def get_label_mapping(G, selection):
        for node in G.nodes():
            if (selection is None) or (node in selection):
                try:
                    label = label_func(node)
                    if label not in (None, node.__class__.__name__):
                        yield (node, label)
                except (LookupError, AttributeError, ValueError):
                    pass

    if 'nodelist' in kwargs:
        labels = dict(get_label_mapping(G, set(kwargs['nodelist'])))
    else:
        labels = dict(get_label_mapping(G, None))
    kwargs['nodelist'] = labels.keys()
    if 'edge_color' not in kwargs:
        kwargs['edge_color'] = [isinstance(e[2], dict) and
                                e[2].get('color', 'k') or 'k'
                                for e in G.edges(data=True)]
    if 'width' not in kwargs:
        kwargs['width'] = [isinstance(e[2], dict) and
                           e[2].get('width', 1.0) or 1.0
                           for e in G.edges(data=True)]
    networkx.draw(G, posn, labels=labels, node_color=node_color, **kwargs)
Example #34
0
def layout(g):
    #pos = networkx.pydot_layout(g, prog='fdp')
    pos = networkx.pygraphviz_layout(g, prog='neato')
    return pos