예제 #1
0
 def multilevel(self, data):
     conn_indices = np.where(data)
     weights = data[conn_indices]
     edges = zip(*conn_indices)
     G = igraph.Graph(edges=edges, directed=False)
     G.es['weight'] = weights
     comm = G.community_multilevel(weights=weights, return_levels=False)
     return comm
예제 #2
0
    def graph(self):
        """
        Draws the Graph/Network switches ...
        """
        # ---------------------------------------------------------

        N = self.G.nodes()
        d = defaultdict(list)
        E = self.G.number_of_edges()

        print
        "The number of Nodes in this Network:", N

        print
        "The number of Edges in this Network:", E

        fig = plt.figure()
        fig.canvas.set_window_title("The ERnet Topology View")
        nx.draw_networkx(self.G)
        plt.show()

        g = ig.Graph(len(self.G), zip(*zip(*nx.to_edgelist(self.G))[:2]))
        self.pt(g)
        cl = g.community_fastgreedy()

        # print cl
        membership = cl.as_clustering().membership

        print
        membership

        self.pt(g, membership)

        # print g.get_all_shortest_paths (2, 33)

        membership.pop(0)
        for q, a in zip(N, membership):
            print
            'The Node {0} --> Belongs to cluster {1}.'.format(q, a)

        # The following procedure is to get the exact nodes of each cluster
        for i in range(max(membership)):
            i += 1
            for j in range(len(N)):
                if membership[j] == i:
                    d[i].append(N[j])

        print
        d.items()

        # Test the subgraphs correctness, which is the clusters
        fig = plt.figure()
        fig.canvas.set_window_title("Sub-Graph/Clique 1 of ERnet")
        G3 = self.G.subgraph(
            d[1]
        )  # each index in dictionary "d" is considered as a one cluster/subgraph of G
        nx.draw_networkx(G3)
        plt.show()
예제 #3
0
def comm_unweighted(data):
    '''Community structure based on the multilevel
       algorithm of Blondel et al.'''

    conn_indices = np.where(data)
    edgs = zip(*conn_indices)
    G = igraph.Graph(edges=edgs, directed=False)
    comm = G.community_multilevel(weights=None, return_levels=False)
    return comm
예제 #4
0
def g2ig(g):
    """
    Converts our graph represenataion to an igraph for plotting
    """
    t = scipy.where(CG2adj(g) == 1)
    l = zip(t[0], t[1])
    ig = igr.Graph(l, directed=True)
    ig.vs["name"] = scipy.sort([u for u in g])
    ig.vs["label"] = ig.vs["name"]
    return ig
예제 #5
0
def comm_weighted(data):
    '''Community structure based on the multilevel
       algorithm of Blondel et al.'''

    conn_indices = np.where(data)
    weights = data[conn_indices]
    edges = zip(*conn_indices)
    G = igraph.Graph(edges=edges, directed=False)
    G.es['weight'] = weights
    comm = G.community_multilevel(weights=weights, return_levels=False)
    return comm
예제 #6
0
    def __init__(self,
                 file_dir,
                 embedding_dim,
                 seed,
                 shuffle,
                 model,
                 sequence_size=8,
                 stride=1,
                 neighbor_size=8):
        assert model == "pscn"
        super(PatchySanDataSet, self).__init__(file_dir, embedding_dim, seed,
                                               shuffle, model)
        n_vertices = self.graphs.shape[1]

        logger.info("generating receptive fields...")
        self.receptive_fields = []
        for i in range(self.graphs.shape[0]):
            adj = self.graphs[i]
            edges = list(zip(*np.where(adj)))
            g = igraph.Graph(edges=edges, directed=False)
            assert (g.vcount() == n_vertices)
            g.simplify()

            sequence = self.get_bfs_order(g, n_vertices - 1, sequence_size,
                                          self.influence_features[i])
            neighborhoods = np.zeros((sequence_size, neighbor_size),
                                     dtype=np.int32)
            neighborhoods.fill(-1)

            for j, v in enumerate(sequence):
                if v < 0:
                    break
                shortest = list(
                    itertools.islice(g.bfsiter(int(v), mode='ALL'),
                                     neighbor_size))
                for k, vtx in enumerate(shortest):
                    neighborhoods[j][k] = vtx.index

            neighborhoods = neighborhoods.reshape(sequence_size *
                                                  neighbor_size)
            self.receptive_fields.append(neighborhoods)
        self.receptive_fields = np.array(self.receptive_fields, dtype=np.int32)
        logger.info("receptive fields generated!")
예제 #7
0
def generateAllGraphs(V, E):
    # Goal: Return a list of all graphs on V vertices with E edges.
    allGraphs = []
    # IMPORTANT: DO NOT return any graphs with isolated vertices!
    ## (1) List every edge that can possibly occur on the V vertices.
    allPossibleEdges = list(
        itertools.combinations_with_replacement(range(0, V), 2))
    ## (2) List every possible way of choosing E edges from allPossibleEdges with replacement.
    allPossibleWaysOfChoosingTheEdges = itertools.combinations_with_replacement(
        allPossibleEdges, E)
    ## (3) For each choice in allPossibleWaysOfChoosingTheEdges, create a graph on V vertices with those edge choices.
    for choice in allPossibleWaysOfChoosingTheEdges:
        # Create a graph, g, with with V vertices and the chosen edges.
        newGraph = jgraph.Graph(V)
        newGraph.add_edges(list(choice))
        # If the resulting graph does not contain any isolated vertices then store it.
        if newGraph.degree().count(0) == 0:
            allGraphs.append(newGraph)
            del newGraph
    return allGraphs
예제 #8
0
 def load_obo(cls,
              file):  # Only building on "is_a" relation between CL terms
     import pronto
     ont = pronto.Ontology(file)
     graph, vdict = jgraph.Graph(directed=True), {}
     for item in ont:
         if not item.id.startswith("CL"):
             continue
         if "is_obsolete" in item.other and item.other["is_obsolete"][
                 0] == "true":
             continue
         graph.add_vertex(name=item.id,
                          cell_ontology_class=item.name,
                          desc=str(item.desc),
                          synonyms=[("%s (%s)" % (syn.desc, syn.scope))
                                    for syn in item.synonyms])
         assert item.id not in vdict
         vdict[item.id] = item.id
         assert item.name not in vdict
         vdict[item.name] = item.id
         for synonym in item.synonyms:
             if synonym.scope == "EXACT" and synonym.desc != item.name:
                 vdict[synonym.desc] = item.id
     for source in graph.vs:
         for relation in ont[source["name"]].relations:
             if relation.obo_name != "is_a":
                 continue
             for target in ont[source["name"]].relations[relation]:
                 if not target.id.startswith("CL"):
                     continue
                 graph.add_edge(
                     source["name"],
                     graph.vs.find(name=target.id.split()[0])["name"])
                 # Split because there are many "{is_infered...}" suffix,
                 # falsely joined to the actual id when pronto parses the
                 # obo file
     return cls(graph, vdict)
예제 #9
0
 def __init__(self, graph=None, vdict=None):
     self.graph = jgraph.Graph(directed=True) if graph is None else graph
     self.vdict = {} if vdict is None else vdict