python类Graph()的实例源码

plotting.py 文件源码 项目:treecat 作者: posterior 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
def nx_plot_tree(server, node_size=200, **options):
    """Visualize the tree using the networkx package.

    This plots to the current matplotlib figure.

    Args:
        server: A DataServer instance.
        options: Options passed to networkx.draw().
    """
    import networkx as nx
    edges = server.estimate_tree()
    perplexity = server.latent_perplexity()
    feature_names = server.feature_names

    V = 1 + len(edges)
    G = nx.Graph()
    G.add_nodes_from(range(V))
    G.add_edges_from(edges)
    H = nx.relabel_nodes(G, dict(enumerate(feature_names)))
    node_size = node_size * perplexity / perplexity.max()

    options.setdefault('alpha', 0.2)
    options.setdefault('font_size', 8)
    nx.draw(H, with_labels=True, node_size=node_size, **options)
graph.py 文件源码 项目:graph 作者: Gretter74 项目源码 文件源码 阅读 57 收藏 0 点赞 0 评论 0
def graphFromDB(c, g):


    for row in c.execute ("SELECT * FROM node"):
        print (row[1])
        g.add_node(row)



    'Constructs a graph from DB data.'
    'Initialize Graph.'
    'Retrieve Nodes.'
    'For each node, insert it in graph.'

    'Possibly edges should be inserted in the same loop.'




#c.close()
#GUI

#Main loop.
simulate.py 文件源码 项目:GraphTime 作者: GlooperLabs 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def generate_graphs(self, n_edges_list, use_seed=True):
        """For each number of edges (n_edges) in n_edges_list create
        an Erdos Renyi Precision Graph that allows us to sample
        from later.

        Parameters
        ----------
        n_edges : list[int] or int
            list of number of edges for each graph or scalar
            if only one graph is wanted
        use_seed : bool
            indicates if seed shall be reset
        """
        if use_seed and self.seed is not None:
            random.seed(self.seed)

        n_edges = n_edges_list if type(n_edges_list) is list \
            else [n_edges_list]

        self.graphs = [ErdosRenyiPrecisionGraph(self.n_vertices, n_es)
                       for n_es in n_edges]
simulate.py 文件源码 项目:GraphTime 作者: GlooperLabs 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def _graph_indices(T, changepoints):
        """Describes which graphs are active for each time
        by returning a list with the graphs indices

        Parameters
        ----------
        T : int
            number of total timesteps
        changepoints : list[int]
            list of changepoint indices

        Yields
        ------
        Graph indices for all t < T
        """
        graph = count = 0
        for cp in changepoints:
            while count < cp:
                count += 1
                yield graph
            graph += 1
        while count < T:
            count += 1
            yield graph
graph_test.py 文件源码 项目:girder_worker 作者: girder 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def setUp(self):
        self.GRAPHML_NS = '{http://graphml.graphdrawing.org/xmlns}'
        self.test_input = {
            'distances': {
                'format': 'networkx',
                'data': nx.Graph([
                    ('US', 'UK', {'distance': 4242}),
                    ('US', 'Australia', {'distance': 9429}),
                    ('UK', 'Australia', {'distance': 9443}),
                    ('US', 'Japan', {'distance': 6303})
                ])
            },
            'alphabetGraph': {
                'format': 'clique.json'
            }
        }

        with open(os.path.join('tests', 'data', 'clique.json'), 'rb') as fixture:
            self.test_input['alphabetGraph']['data'] = fixture.read()
shapegraph.py 文件源码 项目:s2g 作者: caesar0301 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def subgraph_within_box(self, bounding_box):
        """
        Extract a subgraph bounded by a box.
        :param bounding_box: the bounding coordinates in
            (minx, miny, maxx, maxy) or a Polygon instance
        :return: a subgraph of nx.Graph
        """
        if isinstance(bounding_box, Polygon):
            bbox = bounding_box
        else:
            bbox = box(bounding_box[0], bounding_box[1],
                       bounding_box[2], bounding_box[3])
        nbunch = set()
        for edge in self.graph.edges():
            s, e = edge
            if bbox.intersects(LineString([self.node_xy[s], self.node_xy[e]])):
                nbunch.add(s)
                nbunch.add(e)
        return self.graph.subgraph(nbunch)
env_generator.py 文件源码 项目:gym-extensions 作者: Breakend 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def merge_rectangles_into_obstacles(self, centers, widths, heights, epsilon):
        """Merges rectangles defined by centers, widths, heights. Two rectangles
        with distance < epsilon are considered part of the same object."""

        G = nx.Graph()
        obstacles = {i: Obstacle(centers[i, :], widths[i, 0], heights[i, 0]) for i in range(len(centers))}
        G.add_nodes_from(obstacles.keys())

        for i in obstacles:
            for j in obstacles:
                if i != j and obstacles[i].distance_to_obstacle(obstacles[j]) < epsilon:
                    G.add_edge(i,j)

        merged_obstacles = {}
        conn_components = nx.connected_components(G)
        for cc in conn_components:
            cc = list(cc)
            new_obs = obstacles[cc[0]]
            for i in range(1, len(cc)):
                new_obs.merge(obstacles[cc[i]])

            merged_obstacles[cc[0]] = new_obs

        return merged_obstacles
data.py 文件源码 项目:geomdn 作者: afshinrahimi 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def efficient_projected_graph(B, nodes):
    g = nx.Graph()
    nodes = set(nodes)
    g.add_nodes_from(nodes)
    b_nodes = set(B.nodes())
    i = 0
    nodes = set(nodes)
    tenpercent = len(b_nodes) / 10
    for n in b_nodes:
        if i % tenpercent == 0:
            logging.info(str(10 * i / tenpercent) + "%")
        i += 1  
        nbrs = list(set([nbr for nbr in B[n]]) & nodes - set([n]))
        if n in nodes:
            for nbr in nbrs:
                if not g.has_edge(n, nbr):
                    g.add_edge(n, nbr)
        for nbr1 in nbrs:
            for nbr2 in nbrs:
                if nbr1 < nbr2:
                    if not g.has_edge(nbr1, nbr2):
                        g.add_edge(nbr1, nbr2)
        del nbrs

    return g
data.py 文件源码 项目:geomdn 作者: afshinrahimi 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def efficient_collaboration_weighted_projected_graph2(B, nodes):
    nodes = set(nodes)
    G = nx.Graph()
    G.add_nodes_from(nodes)
    all_nodes = set(B.nodes())
    i = 0
    tenpercent = len(all_nodes) / 10
    for m in all_nodes:
        if i % tenpercent == 0:
            logging.info(str(10 * i / tenpercent) + "%")
        i += 1  

        nbrs = B[m]
        target_nbrs = [t for t in nbrs if t in nodes]
        if m in nodes:
            for n in target_nbrs:
                if m < n:
                    if not G.has_edge(m, n):
                        G.add_edge(m, n)
        for n1 in target_nbrs:
            for n2 in target_nbrs:
                if n1 < n2:
                    if not G.has_edge(n1, n2):
                        G.add_edge(n1, n2)
    return G
graph.py 文件源码 项目:uai2017_learning_to_acquire_information 作者: evanthebouncy 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def draw_graph(gv, ge, name):
  Gr = nx.Graph()
  for i in range(N):
    Gr.add_node(i, pos=gv[i])

  for i in range(N):
    for j in range(N):
      if ge[i][j]:
        Gr.add_edge(i,j)

  labels = dict()
  for i in range(N):
    labels[i] = str(i)

  pos=nx.get_node_attributes(Gr,'pos')

  nx.draw(Gr, pos=pos, 
      node_size=400, with_labels=False)
  nx.draw_networkx_labels(Gr, pos, labels)

  plt.savefig(name)
__init__.py 文件源码 项目:graphpca 作者: brandones 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def draw_graph(nx_graph):
    """
    Draws the input graph on two axes with lines between the nodes

    Positions of the nodes are determined with reduce_graph, of course.

    Parameters
    ----------
    nx_graph : :class:`nx.Graph` or :class:`nx.DiGraph`
        The graph to be plotted
    """
    import matplotlib.pyplot as plt
    reduced_2 = reduce_graph(nx_graph, 2)
    for edge in nx_graph.edges():
        plt.plot([reduced_2[0, edge[0]], reduced_2[0, edge[1]]],
                 [reduced_2[1, edge[0]], reduced_2[1, edge[1]]],
                 'b-')
    plot_2d(reduced_2)
data.py 文件源码 项目:sptgraph 作者: epfl-lts2 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def gen_graph(directed):
    g = nx.Graph()

    if directed:
        g = nx.DiGraph()

    # Add 5 nodes
    for i in xrange(1, 6):
        g.add_node(i, node_weight=i)

    # Add edges
    g.add_edge(1, 2, weight=1.0)
    g.add_edge(1, 3, weight=2.0)
    g.add_edge(1, 4, weight=3.0)
    g.add_edge(3, 4, weight=4.0)
    g.add_edge(2, 5, weight=5.0)

    return g
primitives.py 文件源码 项目:ReGraph 作者: eugeniashurko 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def add_node(graph, node_id, attrs=None):
    """Add a node to a graph.

    Parameters
    ----------
    graph : networkx.(Di)Graph
    node_id : hashable
        Prefix that is prepended to the new unique name.
    attrs : dict, optional
        Node attributes.

    Raises
    -------
    regraph.exceptions.GraphError
        Raises an error if node already exists in the graph.
    """
    new_attrs = deepcopy(attrs)
    if new_attrs is None:
        new_attrs = dict()
    if node_id not in graph.nodes():
        graph.add_node(node_id)
        normalize_attrs(new_attrs)
        graph.node[node_id] = new_attrs
    else:
        raise GraphError("Node '%s' already exists!" % node_id)
primitives.py 文件源码 项目:ReGraph 作者: eugeniashurko 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def add_nodes_from(graph, node_list):
    """Add nodes from a node list.

    Parameters
    ----------
    graph : networkx.(Di)Graph
    node_list : iterable
        Iterable containing a collection of nodes, optionally,
        with their attributes


    Examples
    --------
    >>> import networkx as nx
    >>> from regraph.primitives import add_nodes_from
    >>> G = nx.Graph()
    >>> add_nodes_from(G, [1, (2, {"a": 1}), 3])
    """
    for n in node_list:
        try:
            node_id, node_attrs = n
            add_node(graph, node_id, node_attrs)
        except (TypeError, ValueError) as e:
            add_node(graph, n)
primitives.py 文件源码 项目:ReGraph 作者: eugeniashurko 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
def remove_edge(graph, s, t):
    """Remove edge from a graph.

    Parameters
    ----------
    graph : networkx.(Di)Graph
    s : hashable, source node id.
    t : hashable, target node id.

    Raises
    ------
    GraphError
        If edge between `s` and `t` does not exist.

    """
    if graph.is_directed():
        if (s, t) not in graph.edges():
            raise GraphError(
                "Edge '%s->%s' does not exist!" % (str(s), str(t)))
    graph.remove_edge(s, t)
primitives.py 文件源码 项目:ReGraph 作者: eugeniashurko 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
def copy_node(graph, node_id):
    """Copy node.

    Create a copy of a node in a graph. A new id for the copy is
    generated by regraph.primitives.unique_node_id.

    Parameters
    ----------
    graph : networkx.(Di)Graph
    node_id : hashable, node to copy.

    Returns
    -------
    new_name
        Id of the copy node.

    """
    new_name = unique_node_id(graph, node_id)
    add_node(graph, new_name, graph.node[node_id])
    return new_name
primitives.py 文件源码 项目:ReGraph 作者: eugeniashurko 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def remove_node(graph, node_id):
    """Remove node.

    Parameters
    ----------
    graph : networkx.(Di)Graph
    node_id : hashable, node to remove.

    Raises
    ------
    GraphError
        If a node with the specified id does not exist.

    """
    if node_id in graph.nodes():
        neighbors = set(graph.__getitem__(node_id).keys())
        neighbors -= {node_id}
        graph.remove_node(node_id)
    else:
        raise GraphError("Node %s does not exist!" % str(node_id))
    return
primitives.py 文件源码 项目:ReGraph 作者: eugeniashurko 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def filter_edges_by_attributes(graph, attr_key, attr_cond):
    """Filter graph edges by attributes.

    Removes all the edges of the graph (inplace) that do not
    satisfy `attr_cond`.

    Parameters
    ----------
    graph : networkx.(Di)Graph
    attrs_key : attribute key
    attrs_cond : callable
        Condition for an attribute to satisfy: callable that returns
        `True` if condition is satisfied, `False` otherwise.

    """
    for (s, t) in graph.edges():
        if (attr_key not in graph.edge[s][t].keys() or
                not attr_cond(graph.edge[s][t][attr_key])):
            graph.remove_edge(s, t)
primitives.py 文件源码 项目:ReGraph 作者: eugeniashurko 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def set_edge(graph, s, t, attrs):
    """Set edge attrs.

    Parameters
    ----------
    graph : networkx.(Di)Graph
    s : hashable, source node id.
    t : hashable, target node id.
    attrs : dictionary
        Dictionary with attributes to set.

    Raises
    ------
    GraphError
        If an edge between `s` and `t` does not exist.
    """
    new_attrs = deepcopy(attrs)
    if not graph.has_edge(s, t):
        raise GraphError(
            "Edge %s->%s does not exist" % (str(s), str(t)))

    normalize_attrs(new_attrs)
    graph.edge[s][t] = new_attrs
    if not graph.is_directed():
        graph.edge[t][s] = new_attrs
primitives.py 文件源码 项目:ReGraph 作者: eugeniashurko 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def unique_node_id(graph, prefix):
    """Generate a unique id starting by a prefix.

    Parameters
    ----------
    graph : networkx.Graph
    prefix : str
        Prefix that is prepended to the new unique name.


    Returns
    -------
    str
        New unique node id starting with a prefix.
    """
    if prefix not in graph.nodes():
        return prefix
    idx = 0
    new_id = "{}_{}".format(prefix, idx)
    while new_id in graph.nodes():
        idx += 1
        new_id = "{}_{}".format(prefix, idx)
    return new_id
hierarchy.py 文件源码 项目:ReGraph 作者: eugeniashurko 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def node_type(self, graph_id, node_id):
        """Get a list of the immediate types of a node."""
        if graph_id not in self.nodes():
            raise HierarchyError(
                "Graph '%s' is not defined in the hierarchy!"
                % graph_id
            )
        if node_id not in self.node[graph_id].graph.nodes():
            raise HierarchyError(
                "Graph '%s' does not have a node with id '%s'!"
                % (graph_id, node_id)
            )
        types = {}
        for _, typing in self.out_edges(graph_id):
            mapping = self.edge[graph_id][typing].mapping
            if node_id in mapping.keys():
                types[typing] = mapping[node_id]
        return types
ccc_graph.py 文件源码 项目:ccc_helper 作者: TimothyZhang 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def add_assets_to_graph(g, assets):
    """
    :param nx.Graph g:
    :param Sequence[Asset] assets:
    """
    for asset in assets:
        if not asset.referers and not asset.referents:
            continue

        add_node(g, asset)

    for asset in assets:
        if not asset.referers and not asset.referents:
            continue

        for ref in asset.referers:
            g.add_edge(ref.relative_path, asset.relative_path)
ccc_graph.py 文件源码 项目:ccc_helper 作者: TimothyZhang 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def add_node(g, asset):
    """
    :param nx.Graph g:
    :param Asset asset:
    """
    if isinstance(asset, Prefab):
        if not asset.referers:
            color = 'purple'
        elif not asset.referents:
            color = 'green'
        else:
            color = 'blue'
    else:
        color = 'red'

    if option.long:
        label = asset.relative_path
    else:
        label = asset.file.name
    g.add_node(asset.relative_path, label=label, color=color)
prims.py 文件源码 项目:Visualization-of-popular-algorithms-in-Python 作者: MUSoC 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def CreateGraph():
    G = nx.Graph()
    f = open('input.txt')
    n = int(f.readline())
    wtMatrix = []
    for i in range(n):
        list1 = map(int, (f.readline()).split())
        wtMatrix.append(list1)
    #Adds egdes along with their weights to the graph 
    for i in range(n) :
        for j in range(n)[i:] :
            if wtMatrix[i][j] > 0 :
                    G.add_edge(i, j, length = wtMatrix[i][j]) 
    return G



#draws the graph and displays the weights on the edges
egocentric_network_1_5.py 文件源码 项目:Visualization-of-popular-algorithms-in-Python 作者: MUSoC 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def CreateGraph():
    G = nx.Graph()
    f = open('input.txt')
    n = int(f.readline())
    for i in range(n):
        G.add_node(i+1)
    no_of_edges = int(f.readline())
    for i in range(no_of_edges):
        graph_edge_list = f.readline().split()
        G.add_edge(int(graph_edge_list[0]), int(graph_edge_list[1])) 
    vert = int(f.readline())
    return G, vert



#draws the graph and displays the weights on the edges
egocentric_network_2.py 文件源码 项目:Visualization-of-popular-algorithms-in-Python 作者: MUSoC 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def CreateGraph():
    G = nx.Graph()
    f = open('input.txt')
    n = int(f.readline())
    for i in range(n):
        G.add_node(i+1)
    no_of_edges = int(f.readline())
    for i in range(no_of_edges):
        graph_edge_list = f.readline().split()
        G.add_edge(int(graph_edge_list[0]), int(graph_edge_list[1])) 
    vert = int(f.readline())
    return G, vert



#draws the graph and displays the weights on the edges
egocentric_network_1.py 文件源码 项目:Visualization-of-popular-algorithms-in-Python 作者: MUSoC 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def CreateGraph():
    G = nx.Graph()
    f = open('input.txt')
    n = int(f.readline())
    for i in range(n):
        G.add_node(i+1)
    no_of_edges = int(f.readline())
    for i in range(no_of_edges):
        graph_edge_list = f.readline().split()
        G.add_edge(int(graph_edge_list[0]), int(graph_edge_list[1])) 
    vert = int(f.readline())
    return G, vert



#draws the graph and displays the weights on the edges
kruskals_quick_union.py 文件源码 项目:Visualization-of-popular-algorithms-in-Python 作者: MUSoC 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def CreateGraph():
    G = nx.Graph()
    f = open('input.txt')
    n = int(f.readline())
    wtMatrix = []
    for i in range(n):
        list1 = map(int, (f.readline()).split())
        wtMatrix.append(list1)
    # Adds egdes along with their weights to the graph 
    for i in range(n) :
        for j in range(n)[i:] :
            if wtMatrix[i][j] > 0 :
                    G.add_edge(i, j, length = wtMatrix[i][j]) 
    return G



# draws the graph and displays the weights on the edges
utils.py 文件源码 项目:PokemonGo-Bot 作者: PokemonGoF 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def find_biggest_cluster(radius, points, order=None):
    graph = nx.Graph()
    for point in points:
            if order is '9QM=':
                #is a lure module - 9QM=
                now = int(time.time())
                remaining = now - point['last_modified_timestamp_ms']
                f = point['latitude'], point['longitude'], remaining
            else:
                f = point['latitude'], point['longitude'], 0
            graph.add_node(f)
            for node in graph.nodes():
                if node != f and distance(f[0], f[1], node[0], node[1]) <= radius*2:
                    graph.add_edge(f, node)
    cliques = list(find_cliques(graph))
    if len(cliques) > 0:
        max_clique = max(list(find_cliques(graph)), key=lambda l: (len(l), sum(x[2] for x in l)))
        merc_clique = [coord2merc(x[0], x[1]) for x in max_clique]
        clique_x, clique_y = zip(*merc_clique)
        best_point = np.mean(clique_x), np.mean(clique_y)
        best_coord = merc2coord(best_point)
        return {'latitude': best_coord[0], 'longitude': best_coord[1], 'num_points': len(max_clique)}
    else:
        return None
owner_graph_metrics.py 文件源码 项目:community-networks-monitoring-tools 作者: netCommonsEU 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def getOwnerRobustness(self, graph):
        """ compute the "owner robustness """

        ownerNodes, nodeOwner = self.get_owner_distribution(graph)
        print "# owner".rjust(long_align_space), ",",\
              "main C. size".rjust(long_align_space), ",",\
              "number of components".rjust(long_align_space)
        for owner, nodes in sorted(ownerNodes.items(),
                                   key=lambda(x): -len(x[1])):
            purged_graph = nx.Graph(graph)
            for n in nodes:
                purged_graph.remove_node(n)
            comp_list = list(nx.connected_components(purged_graph))
            main_comp = sorted(comp_list, key=len, reverse=True)[0]
            print owner.rjust(long_align_space), ",",\
                str(len(main_comp)).rjust(long_align_space), ",", \
                str(len(comp_list)).rjust(long_align_space)
        print ""
        print ""

    #  ################# helper functions
    # These functions are needed to handle data structures from
    # other sources of data. You can use a database and dump the
    # data in XML from a db. You probably do not need these functions.


问题


面经


文章

微信
公众号

扫码关注公众号