How to use the networkx.Graph function in networkx

To help you get started, we’ve selected a few networkx examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github stellargraph / stellargraph / tests / core / test_stellargraph.py View on Github external
def create_graph_1(is_directed=False, return_nx=False):
    g = nx.DiGraph() if is_directed else nx.Graph()
    g.add_nodes_from([0, 1, 2, 3], label="movie")
    g.add_nodes_from([4, 5], label="user")
    g.add_edges_from([(4, 0), (4, 1), (5, 1), (4, 2), (5, 3)], label="rating")
    if return_nx:
        return nx.MultiDiGraph(g) if is_directed else nx.MultiGraph(g)
    return StellarDiGraph(g) if is_directed else StellarGraph(g)
github arjun-menon / Distributed-Graph-Algorithms / Minimum-Spanning-Tree / tools.py View on Github external
def edge(n1, n2, w):
            if w in seen_w:
                raise Exception("Duplicate edge weights in graph. For a unique MST, all edge weights have to be uniqe as well.")
            seen_w.update({ w })
            return (n1, n2, {'weight':w})

        edge_list = list()

        with open(file, 'r') as f:
            edge_list = list( edge(ed.split()[0], ed.split()[1], int(ed.split()[2])) 
                for ed in 
                (e.strip() for e in f.readlines() if e.strip() != "") 
                if len(ed.split()) == 3 )

            G = nx.Graph()
            G.add_edges_from(edge_list)

            self.graph = G
            return G
github lingpy / lingpy / lingpy / compare / partial.py View on Github external
D = {}
            for vals in tmp.values():
                for k in vals:
                    D[k] = idx
                idx += 1
            self.add_entries(target, D, lambda x: x, override=override)
        elif idtype == 'loose':

            D = {}
            idx = 1
            for c in self.rows:
                idxs = self.get_list(row=c, flat=True)
                srcs = [self[k, source] for k in idxs]

                # get connected components
                g = nx.Graph()
                g.add_nodes_from(idxs)
                for (i, cogsA), (j, cogsB) in util.combinations2(zip(idxs, srcs)):
                     if [x for x in cogsA if x in cogsB]:
                         g.add_edge(i, j)
                for i,comps in enumerate(nx.connected_components(g)):
                    for comp in comps:
                        D[comp] = idx + i
                idx += (i+1)
            self.add_entries(target, D, lambda x: x, override=override)
        else:
            raise ValueError("The value you selected is not available.")
github chapmanb / bcbb / rest_apis / ensembl_remote_rest.py View on Github external
def __init__(self):
        self.graph = networkx.Graph()
github aerdem4 / kaggle-quora-dup / non_nlp_feature_extraction.py View on Github external
def get_kcore_dict(df):
    g = nx.Graph()
    g.add_nodes_from(df.qid1)
    edges = list(df[["qid1", "qid2"]].to_records(index=False))
    g.add_edges_from(edges)
    g.remove_edges_from(g.selfloop_edges())

    df_output = pd.DataFrame(data=g.nodes(), columns=["qid"])
    df_output["kcore"] = 0
    for k in range(2, NB_CORES + 1):
        ck = nx.k_core(g, k=k).nodes()
        print("kcore", k)
        df_output.ix[df_output.qid.isin(ck), "kcore"] = k

    return df_output.to_dict()["kcore"]
github nocproject / noc / services / web / apps / inv / map / layout.py View on Github external
def __init__(self):
        self.G = nx.Graph()
        self.seen_links = {}  # n1, n2 -> count
        self.link_ids = defaultdict(list)  # n1, n2 -> [link id]
        self.node_size = {}  # n -> w, h
        self.fixed_positions = {}  # n -> x, y
        self.width = None
        self.height = None
github networkx / networkx / networkx / generators / duplication.py View on Github external
References
    ----------
    .. [1] I. Ispolatov, P. L. Krapivsky, A. Yuryev,
       "Duplication-divergence model of protein interaction network",
       Phys. Rev. E, 71, 061911, 2005.

    """
    if p > 1 or p < 0:
        msg = "NetworkXError p={0} is not in [0,1].".format(p)
        raise nx.NetworkXError(msg)
    if n < 2:
        msg = 'n must be greater than or equal to 2'
        raise nx.NetworkXError(msg)

    G = nx.Graph()

    # Initialize the graph with two connected nodes.
    G.add_edge(0, 1)
    i = 2
    while i < n:
        # Choose a random node from current graph to duplicate.
        random_node = seed.choice(list(G))
        # Make the replica.
        G.add_node(i)
        # flag indicates whether at least one edge is connected on the replica.
        flag = False
        for nbr in G.neighbors(random_node):
            if seed.random() < p:
                # Link retention step.
                G.add_edge(i, nbr)
                flag = True
github mikedewar / d3py / examples / d3py_graph.py View on Github external
import d3py
import networkx as nx

import logging
logging.basicConfig(level=logging.DEBUG)

G=nx.Graph()
G.add_edge(1,2)
G.add_edge(1,3)
G.add_edge(3,2)
G.add_edge(3,4)
G.add_edge(4,2)

# use 'with' if you are writing a script and want to serve this up forever
with d3py.NetworkXFigure(G, width=500, height=500) as p:
    p += d3py.ForceLayout()
    p.show()
github rik0 / pynetsym / bin / generate.py View on Github external
def main(args):
    arguments_dictionary, module = parse_arguments(args, default_module='transitive_linking')
    output_path = arguments_dictionary.pop('output')
    format = arguments_dictionary.pop('format')
    steps = arguments_dictionary.pop('steps')

    graph = nx.Graph()

    generation.generate(graph, module, steps,
                        timer_callback=timing.execution_printer(sys.stdout),
                        **arguments_dictionary)
    ioutil.save_network(graph, output_path, format)
github pgmpy / pgmpy / pgmpy / models / SEM.py View on Github external
--------
        >>> from pgmpy.models import SEMAlg
        >>> model = SEMAlg()
        # TODO: Finish this example
        """

        err_var = {var: np.diag(self.zeta)[i] for i, var in enumerate(self.eta)}
        graph = nx.relabel_nodes(
            nx.from_numpy_matrix(self.B.T, create_using=nx.DiGraph),
            mapping={i: self.eta[i] for i in range(self.B.shape[0])},
        )
        # Fill zeta diagonal with 0's as they represent variance and would add self loops in the graph.
        zeta = self.zeta.copy()
        np.fill_diagonal(zeta, 0)
        err_graph = nx.relabel_nodes(
            nx.from_numpy_matrix(zeta.T, create_using=nx.Graph),
            mapping={i: self.eta[i] for i in range(self.zeta.shape[0])},
        )

        latents = set(self.eta) - set(self.y)

        from pgmpy.models import SEMGraph

        # TODO: Add edge weights
        sem_graph = SEMGraph(
            ebunch=graph.edges(),
            latents=latents,
            err_corr=err_graph.edges(),
            err_var=err_var,
        )
        return sem_graph