Python networkx 模块,get_node_attributes() 实例源码

我们从Python开源项目中,提取了以下40个代码示例,用于说明如何使用networkx.get_node_attributes()

项目:uai2017_learning_to_acquire_information    作者:evanthebouncy    | 项目源码 | 文件源码
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)
项目:loman    作者:janusassetallocation    | 项目源码 | 文件源码
def to_df(self):
        """
        Get a dataframe containing the states and value of all nodes of computation

        ::

            >>> comp = loman.Computation()
            >>> comp.add_node('foo', value=1)
            >>> comp.add_node('bar', value=2)
            >>> comp.to_df()
                           state  value  is_expansion
            bar  States.UPTODATE      2           NaN
            foo  States.UPTODATE      1           NaN
        """
        df = pd.DataFrame(index=nx.topological_sort(self.dag))
        df[_AN_STATE] = pd.Series(nx.get_node_attributes(self.dag, _AN_STATE))
        df[_AN_VALUE] = pd.Series(nx.get_node_attributes(self.dag, _AN_VALUE))
        df_timing = pd.DataFrame.from_dict(nx.get_node_attributes(self.dag, 'timing'), orient='index')
        df = pd.merge(df, df_timing, left_index=True, right_index=True, how='left')
        return df
项目:son-emu    作者:sonata-nfv    | 项目源码 | 文件源码
def get(self):
        nodes = list()
        nodes2 = list()
        links = list()
        # add all DCs
        node_attr = networkx.get_node_attributes(net.DCNetwork_graph, 'type')
        for node_name in net.DCNetwork_graph.nodes():
            nodes2.append(node_name)
            node_index = nodes2.index(node_name)
            type = node_attr[node_name]
            node_dict = {"name":node_name,"group":type}
            nodes.append(node_dict)

        # add links between other DCs
        for node1_name in net.DCNetwork_graph.nodes():
            node1_index = nodes2.index(node1_name)
            for node2_name in net.DCNetwork_graph.neighbors(node1_name):
                node2_index = nodes2.index(node2_name)
                edge_dict = {"source": node1_index, "target": node2_index, "value": 10}
                links.append(edge_dict)

        json = {"nodes":nodes, "links":links}
        return json, 200, CORS_HEADER
项目:gym-kidney    作者:camoy    | 项目源码 | 文件源码
def _render(self, mode = "human", close = False):
        if close:
            return

        import matplotlib.pyplot as plt

        if self.tick == 0:
            plt.ion()

        G = self.G
        attrs = nx.get_node_attributes(G, "ndd")
        values = ["red" if attrs[v] else "blue" for v in G.nodes()]

        plt.clf()
        nx.draw(G,
            pos = nx.circular_layout(G),
            node_color = values)
        plt.pause(0.01)

        return []
项目:atap    作者:foxbook    | 项目源码 | 文件源码
def nbest_centrality(G, metric, n=10, attr="centrality", **kwargs):
    # Compute the centrality scores for each vertex
    scores = metric(G, **kwargs)

    # Set the score as a property on each node
    nx.set_node_attributes(G, attr, scores)

    # Filter scores (do not include in book)
    ntypes = nx.get_node_attributes(G, 'type')
    phrases = [
        item for item in scores.items()
        if ntypes.get(item[0], None) == "keyphrase"
    ]

    # Find the top n scores and print them along with their index
    topn = heapq.nlargest(n, phrases, key=itemgetter(1))
    for idx, item in enumerate(topn):
        print("{}. {}: {:0.4f}".format(idx+1, *item))

    return G
项目:phriky-units    作者:unl-nimbus-lab    | 项目源码 | 文件源码
def build_function_graph(self, analysis_unit_dict):
        ''' BUILDS DIRECTED FUNCTION GRAPH 
            input:  a dictionary of functions from this dump file
            output: none.  Side effect creates a graph linked to this object
            '''
        if self.debug_verbose:
            print inspect.stack()[0][3]
        # BUILD CALL GRAPH
        self.function_graph = nx.DiGraph()
        G = self.function_graph
        for k, function_dict in analysis_unit_dict.iteritems():
            if function_dict['function']:  # MIGHT BE NONE WHEN FUNCTION IS CLASS CONSTRUCTOR (?)
                node = function_dict['function'].Id             # Id of the Function
                #if not G.has_node(node):
                G.add_node(node) #, function_dict_key=k})  # FUNCTION CPP OBJECT IS NODE
                #else:
                all_attr = nx.get_node_attributes(G, 'function_id')
                all_attr[node] = k
                nx.set_node_attributes(G, 'function_id', all_attr)
                #function_dict['is_visited'] = False
                self.add_edges_to_function_graph(function_dict, G, node)
        self.function_graph = G
项目:policosm    作者:ComplexCity    | 项目源码 | 文件源码
def getRoadsBoundaries(graph):
    lons = nx.get_node_attributes(graph,'longitude').values()
    lats = nx.get_node_attributes(graph,'latitude').values()

    lon = lons[0]
    lat = lats[0]

    bounds = [lon,lat,lon,lat]

    for i in range(0,len(lons)):
        lon = lons[i]
        lat = lats[i]
        if lon < bounds[0]:
            bounds[0] = lon
        if lon > bounds[2]:
            bounds[2] = lon
        if lat < bounds[1]:
            bounds[1] = lat
        if lat > bounds[3]:
            bounds[3] = lat
    return bounds
项目:policosm    作者:ComplexCity    | 项目源码 | 文件源码
def getRoadsBoundaries(graph):
    lons = nx.get_node_attributes(graph,'longitude').values()
    lats = nx.get_node_attributes(graph,'latitude').values()

    lon = lons[0]
    lat = lats[0]

    bounds = [lon,lat,lon,lat]

    for i in range(0,len(lons)):
        lon = lons[i]
        lat = lats[i]
        if lon < bounds[0]:
            bounds[0] = lon
        if lon > bounds[2]:
            bounds[2] = lon
        if lat < bounds[1]:
            bounds[1] = lat
        if lat > bounds[3]:
            bounds[3] = lat
    return bounds
项目:exfi    作者:jlanga    | 项目源码 | 文件源码
def _compute_containments(splice_graph):
    """Compute the containment lines (w.r.t. transcriptome)

    C container orientation contained orientation position overlap
    """
    # Extract from the graph necessary data
    node2seq = nx.get_node_attributes(
        G=splice_graph,
        name='sequence'
    )
    exon2coordinates = nx.get_node_attributes(
        G=splice_graph,
        name='coordinates'
    )

    for exon_id, coordinates in sorted(exon2coordinates.items()):
        for coordinate in coordinates:
            transcript_id, start, _ = coordinate
            yield "C\t{0}\t{1}\t{2}\t{3}\t{4}\t{5}\n".format(
                transcript_id, "+",
                exon_id, "+",
                start, str(len(node2seq[exon_id])) + "M"
            )
项目:lomap    作者:wasserfeder    | 项目源码 | 文件源码
def draw_grid(ts, edgelabel='control', prop_colors=None, current_node=None):
    assert edgelabel is None or nx.is_weighted(ts.g, weight=edgelabel)
    pos = nx.get_node_attributes(ts.g, 'location')
    if current_node == 'init':
        current_node = next(ts.init.iterkeys())
    colors = dict([(v, 'w') for v in ts.g])
    if current_node:
        colors[current_node] = 'b'
    for v, d in ts.g.nodes_iter(data=True):
        if d['prop']:
            colors[v] = prop_colors[tuple(d['prop'])]
    colors = colors.values()
    labels = nx.get_node_attributes(ts.g, 'label')
    nx.draw(ts.g, pos=pos, node_color=colors)
    nx.draw_networkx_labels(ts.g, pos=pos, labels=labels)
    edge_labels = nx.get_edge_attributes(ts.g, edgelabel)
    nx.draw_networkx_edge_labels(ts.g, pos=pos,
                                 edge_labels=edge_labels)
项目:WNTR    作者:USEPA    | 项目源码 | 文件源码
def get_node_coordinates(self, name=None):
        """
        Returns node coordinates.

        Parameters
        ----------
        name: string
            Name of the node.

        Returns
        -------
        A tuple containing the coordinates of the specified node.
        Note: If name is None, this method will return a dictionary
              with the coordinates of all nodes keyed by node name.
        """
        if name is not None:
            return self._graph.node[name]['pos']
        else:
            coordinates_dict = nx.get_node_attributes(self._graph, 'pos')
            return coordinates_dict
项目:TextAsGraphClassification    作者:NightmareNyx    | 项目源码 | 文件源码
def random_walk(G, steps):
    def walk(G, node, prev_node, steps):
        if steps == 0:
            return 0
        steps -= 1
        neighs = G.neighbors(node)
        neighs_attrs = nx.get_node_attributes(G.subgraph(neighs), 'label')
        neighs_attrs = list(neighs_attrs.values())
        if prev_node is not None:
            neighs_attrs[neighs.index(prev_node)] = 0  # we don't want to return to the previous node
        choice = np.random.choice(a=len(neighs), p=neighs_attrs / np.sum(neighs_attrs))
        val = walk(G, node=neighs[choice], prev_node=node, steps=steps)
        return neighs_attrs[choice] + val

    kernel_value = 0
    for node_attr in G.nodes(data=True):
        node, attr = node_attr
        num_nodes = G.number_of_nodes(), G.number_of_nodes()
        for step in range(steps):
            neighs = G.neighbors(node)
            kernel_value += (step / steps) * walk(G, node=neighs[0], prev_node=None, steps=steps)
    return kernel_value
项目:sptgraph    作者:epfl-lts2    | 项目源码 | 文件源码
def _get_weighted_static_component_nx(dyn_g,  baseid_name='page_id'):
    if not HAS_NETWORKX:
        LOGGER.error('Networkx not installed, cannot use function _get_weighted_static_component_nx')
        raise ImportError('Networkx not installed, cannot use function _get_weighted_static_component_nx')

    def inc_prop(g, nid, key):
        deg = g.node[nid].get(key, None)
        if deg:
            g.node[nid][key] += 1
        else:
            g.node[nid][key] = 1

    g = nx.DiGraph()  # directed + self-edges
    g.component = dyn_g.component
    g.type = STATIC_COMP_TYPE
    # Add unique nodes
    node_hist = Counter(nx.get_node_attributes(dyn_g, baseid_name).values())
    g.add_nodes_from([(k, {'count': v}) for k, v in node_hist.iteritems()])

    for (u, v) in dyn_g.edges_iter():
        src = dyn_g.node[u][baseid_name]
        tgt = dyn_g.node[v][baseid_name]

        if g.has_edge(src, tgt):
            g[src][tgt]['count'] += 1
        else:
            g.add_edge(src, tgt, count=1)

        inc_prop(g, src, 'out_degree')
        inc_prop(g, tgt, 'in_degree')

    # Normalize counts
    for (u, v, d) in g.edges_iter(data=True):
        d['out_score'] = d['count'] / float(g.node[u]['out_degree'])
        d['in_score'] = d['count'] / float(g.node[v]['in_degree'])
        d['weight'] = (d['out_score'] + d['in_score']) / 2
        d['score'] = d['weight']  # mostly for tulip which cannot display the weight prop ...

    return g
项目:PedWorks    作者:BrnCPrz    | 项目源码 | 文件源码
def write_node_attributes(graph, filename):
    # utility function to let you print the node + various attributes in a csv format
    for node in graph.nodes(data=True):
        #    print graph.report_node_data(undir_g)
        node_idx, node_dict = node
        attrs = ','.join(str(v) for v in node_dict.values)
        print node  # nx.get_node_attributes(graph, node_idx) #, ",", ",".join(vals)
项目:loman    作者:janusassetallocation    | 项目源码 | 文件源码
def to_dict(self):
        """
        Get a dictionary containing the values of all nodes of a computation

        ::

            >>> comp = loman.Computation()
            >>> comp.add_node('foo', value=1)
            >>> comp.add_node('bar', value=2)
            >>> comp.to_dict()
            {'bar': 2, 'foo': 1}
        """
        return nx.get_node_attributes(self.dag, _AN_VALUE)
项目:loman    作者:janusassetallocation    | 项目源码 | 文件源码
def write_dill(self, file_):
        """
        Serialize a computation to a file or file-like object

        :param file_: If string, writes to a file
        :type file_: File-like object, or string
        """
        node_serialize = nx.get_node_attributes(self.dag, _AN_TAG)
        if all(serialize for name, serialize in six.iteritems(node_serialize)):
            obj = self
        else:
            obj = self.copy()
            for name, tags in six.iteritems(node_serialize):
                if _T_SERIALIZE not in tags:
                    obj._set_uninitialized(name)

        if isinstance(file_, six.string_types):
            with open(file_, 'wb') as f:
                dill.dump(obj, f)
        else:
            dill.dump(obj, file_)
项目:bytecode_simplifier    作者:extremecoders-re    | 项目源码 | 文件源码
def render_graph(bb_graph, filename):
    """
    Renders a basic block graph to file

    :param bb_graph: The Graph to render
    :type bb_graph: networkx.DiGraph
    """
    graph = pydotplus.Dot(graph_type='digraph', rankdir='TB')
    entryblock = nx.get_node_attributes(bb_graph, 'isEntry').keys()[0]
    returnblocks = nx.get_node_attributes(bb_graph, 'isTerminal').keys()

    nodedict = {}

    for bb in bb_graph.nodes_iter():
        node = render_bb(bb, bb == entryblock, bb in returnblocks)
        if bb == entryblock:
            sub = pydotplus.Subgraph('sub', rank='source')
            sub.add_node(node)
            graph.add_subgraph(sub)
        else:
            graph.add_node(node)
        nodedict[bb] = node

    for edge in bb_graph.edges_iter(data=True):
        src = nodedict[edge[0]]
        dest = nodedict[edge[1]]
        e_style = 'dashed' if edge[2]['edge_type'] == 'implicit' else 'solid'

        graph.add_edge(pydotplus.Edge(src, dest, style=e_style))
    # graph.set('splines', 'ortho')
    # graph.set_prog('neato')
    # graph.set('dpi', '100')

    graph.write(filename, format='svg')
项目:gym-kidney    作者:camoy    | 项目源码 | 文件源码
def arrive(self, G, rng):
        R = self._ref
        n1 = G.order()
        n2 = rng.poisson(self.m / self.k)
        new = range(n1, n1 + n2)

        # label map
        r_to_g = self._inv(nx.get_node_attributes(G, "r_id"))

        for u in new:
            # add vertex
            r_id = rng.randint(0, R.order())
            attr_u = R.node[r_id]
            attr_u["r_id"] = r_id
            G.add_node(u, attr_u)
            self.stats["%s_patient_arrived" % attr_u["bp"]] += 1
            self.stats["%s_donor_arrived" % attr_u["bd"]] += 1

            # add to label map
            if r_id in r_to_g:
                r_to_g[r_id] += [u]
            else:
                r_to_g[r_id] = [u]

            # edges
            for vs in list(map(r_to_g.get, R.successors(r_id))):
                if vs == None: continue
                for v in vs:
                    if rng.rand() > self.p_d:
                        G.add_edge(u, v)

            for vs in list(map(r_to_g.get, R.predecessors(r_id))):
                if vs == None: continue
                for v in vs:
                    if rng.rand() > self.p_d:
                        G.add_edge(v, u)

        self.stats["arrived"] += n2
        return G
项目:gym-kidney    作者:camoy    | 项目源码 | 文件源码
def arrive(self, G, rng):
        R = self._ref
        n1 = G.order()
        n2 = rng.poisson(self.m / self.k)
        new = range(n1, n1 + n2)

        # label map
        r_to_g = self._inv(nx.get_node_attributes(G, "r_id"))

        for u in new:
            # add vertex
            r_id = rng.randint(0, R.order())
            attr_u = R.node[r_id]
            attr_u["r_id"] = r_id
            G.add_node(u, attr_u)
            self.stats["%s_patient_arrived" % attr_u["bp"]] += 1
            self.stats["%s_donor_arrived" % attr_u["bd"]] += 1

            # add to label map
            if r_id in r_to_g:
                r_to_g[r_id] += [u]
            else:
                r_to_g[r_id] = [u]
            # edges
            for vs in list(map(r_to_g.get, R.successors(r_id))):
                if vs == None: continue
                for v in vs:
                    if rng.rand() > self.p_d:
                        G.add_edge(u, v)

            for vs in list(map(r_to_g.get, R.predecessors(r_id))):
                r_id = rng.randint(0, R.order())
                if vs == None: continue
                for v in vs:
                    if rng.rand() > self.p_d:
                        G.add_edge(v, u)

        self.stats["arrived"] += n2
        return G
项目:gym-kidney    作者:camoy    | 项目源码 | 文件源码
def arrive(self, G, rng):
        R = self._ref
        n1 = G.order()
        n2 = rng.poisson(self.m / self.k)
        new = range(n1, n1 + n2)

        # label map
        r_to_g = self._inv(nx.get_node_attributes(G, "r_id"))

        for u in new:
            # add vertex
            r_id = rng.randint(0, R.order())
            attr_u = R.node[r_id]
            attr_u["r_id"] = r_id
            G.add_node(u, attr_u)
            self.stats["%s_patient_arrived" % attr_u["bp"]] += 1
            self.stats["%s_donor_arrived" % attr_u["bd"]] += 1

            # add to label map
            if r_id in r_to_g:
                r_to_g[r_id] += [u]
            else:
                r_to_g[r_id] = [u]

            # edges
            for vs in list(map(r_to_g.get, R.successors(r_id))):
                if vs == None: continue
                for v in vs:
                    G.add_edge(u, v)

            for vs in list(map(r_to_g.get, R.predecessors(r_id))):
                if vs == None: continue
                for v in vs:
                    G.add_edge(v, u)

        self.stats["arrived"] += n2
        return G
项目:gtfspy    作者:CxAalto    | 项目源码 | 文件源码
def create_walk_network_from_osm(osm_file):
    walk_network = networkx.Graph()
    assert (os.path.exists(osm_file))
    ways = []
    for i, entity in enumerate(parse_file(osm_file)):
        if isinstance(entity, Node):
            walk_network.add_node(entity.id, lat=entity.lat, lon=entity.lon)
        elif isinstance(entity, Way):
            if "highway" in entity.tags:
                if entity.tags["highway"] in OSM_HIGHWAY_WALK_TAGS:
                    ways.append(entity)
    for way in ways:
        walk_network.add_path(way.nodes)
    del ways

    # Remove all singleton nodes (note that taking the giant component does not necessarily provide proper results.
    for node, degree in walk_network.degree().items():
        if degree is 0:
            walk_network.remove_node(node)

    node_lats = networkx.get_node_attributes(walk_network, 'lat')
    node_lons = networkx.get_node_attributes(walk_network, 'lon')
    for source, dest, data in walk_network.edges(data=True):
        data["distance"] = wgs84_distance(node_lats[source],
                                          node_lons[source],
                                          node_lats[dest],
                                          node_lons[dest])
    return walk_network
项目:freecad-nurbs    作者:microelly2    | 项目源码 | 文件源码
def displayMatplot():
    # display in matplotlib
    pos=nx.get_node_attributes(g,'pos')
    nx.draw(g,pos)
    plt.show()
    # plt.savefig("/tmp/path.png")
项目:PyCHAMELEON    作者:giovannipcarvalho    | 项目源码 | 文件源码
def plot_graph(graph):
    pos = nx.get_node_attributes(graph, 'pos')
    c = [colors[i%(len(colors))] for i in nx.get_node_attributes(graph, 'cluster').values()]
    if c: # is set
        nx.draw(graph, pos, node_color=c, node_size=0.2)
    else:
        nx.draw(graph, pos)
    plt.show(block=False)
项目:PyCHAMELEON    作者:giovannipcarvalho    | 项目源码 | 文件源码
def part_graph(graph, k, df=None):
    edgecuts, parts = metis.part_graph(graph, k)
    for i, p in enumerate(graph.nodes()):
        graph.node[p]['cluster'] = parts[i]
    if df is not None:
        df['cluster'] = nx.get_node_attributes(graph, 'cluster').values()
    return graph
项目:my_experiment    作者:Giuliao    | 项目源码 | 文件源码
def show_network(self):
        import time
        plt.figure(time.time())
        for v in self.G.nodes():
            self.G.node[v]['state'] = str(v)

        node_labels = nx.get_node_attributes(self.G, 'state')
        pos = nx.circular_layout(self.G)
        nx.draw_networkx_labels(self.G, pos, node_labels=node_labels)
        nx.draw(self.G, pos)
        plt.savefig('./assets/result2.png')
        # plt.show(block=False)
        plt.close()
项目:exfi    作者:jlanga    | 项目源码 | 文件源码
def _compute_segment_lines(splice_graph):
    """Compute the segment lines

    S node_id sequence length
    """
    node2seq = nx.get_node_attributes(
        G=splice_graph,
        name='sequence'
    )
    for node in sorted(splice_graph.nodes()):
        yield "S\t{node}\t{sequence}\tLN:i:{length}\n".format(
            node=node,
            sequence=node2seq[node],
            length=len(node2seq[node])
        )
项目:exfi    作者:jlanga    | 项目源码 | 文件源码
def compute_edge_overlaps(splice_graph):
    """Get the overlap between connected exons:
    - Positive overlap means that they overlap that number of bases,
    - Zero that they occur next to each other
    - Negative that there is a gap in the transcriptome of that number of bases (one or multiple exons of length < kmer)

    Note: the splice graph must have already the nodes written with coordinates, and the edges alredy entered too.
    """
    #Init
    edge_overlaps = {edge: None for edge in splice_graph.edges()}
    exon2coord = nx.get_node_attributes(
        G=splice_graph,
        name='coordinates'
    )

    for (node1, node2) in sorted(edge_overlaps.keys()):

        # Get the list of transcripts that they belong
        node1_transcripts = set(coordinate[0] for coordinate  in exon2coord[node1])
        node2_transcripts = set(coordinate[0] for coordinate  in exon2coord[node2])
        intersection = node1_transcripts & node2_transcripts
        a_common_transcript = intersection.pop()

        # Get the end the first
        node1_coords = exon2coord[node1]
        node1_coords_in_transcript = [x for x in node1_coords if x[0] == a_common_transcript][0]
        node1_end = node1_coords_in_transcript[2]

        # Get the start of the next
        node2_coords = exon2coord[node2]
        node2_coords_in_transcript = [x for x in node2_coords if x[0] == a_common_transcript][0]
        node2_start = node2_coords_in_transcript[1]

        # Overlap in bases, 0 means one next to the other, negative numbers a gap
        overlap = node1_end - node2_start
        edge_overlaps[(node1, node2)] = overlap

    return edge_overlaps
项目:InnerOuterRNN    作者:Chemoinformatics    | 项目源码 | 文件源码
def get_atom_features(self, node_id):
        attrs = nx.get_node_attributes(self.graph, "atom_features")
        return attrs[node_id]
项目:pathnet-pytorch    作者:kimhc6028    | 项目源码 | 文件源码
def get_fig(self, genes, e_color):

        fixed_pair = [(self.fixed_path[i], self.fixed_path[i+1]) 
                      for i in range(len(self.fixed_path) - 1)]

        for gene in genes:
            gene_pair = [(gene[i], gene[i+1]) for i in range(len(gene) - 1)]

            for layer_num, (pair, fixed) in enumerate(zip(gene_pair, fixed_pair)):
                for first_num in pair[0]:
                    for second_num in pair[1]:
                        first_node = self.node_ids[(layer_num, first_num)]
                        second_node = self.node_ids[(layer_num + 1, second_num)]
                        if self.graph.has_edge(first_node, second_node):
                            self.node_upsize(first_node)
                            self.node_upsize(second_node)
                            weight =  self.graph.get_edge_data(first_node, second_node)['weight']
                            weight += self.edge_weight_add
                            self.graph.add_edge(first_node, second_node, color = e_color, weight = weight)
                        else:
                            self.graph.add_edge(first_node, second_node, color = e_color, weight = self.init_edge_weight)

        for fixed in fixed_pair:
            for f_1 in fixed[0]:
                for f_2 in fixed[1]:
                    if (not f_1 == None) and (not f_2 == None):
                        self.graph.add_edge(f_1, f_2, color = self.fixed_color, weight = self.fixed_weight)

        nodes = self.graph.nodes(data = True)
        node_color = 'g'
        node_size = [node[1]['size'] for node in nodes]
        node_shape = 's'

        edges = self.graph.edges()
        edge_color = [self.graph[u][v]['color'] for u,v in edges]
        weights = [self.graph[u][v]['weight'] for u,v in edges]
        nx.draw_networkx_nodes(self.graph, nodes = nodes, pos=nx.get_node_attributes(self.graph,'Position'), node_color = node_color, node_size = node_size, node_shape = node_shape)
        nx.draw_networkx_edges(self.graph, edges = edges, pos=nx.get_node_attributes(self.graph,'Position'), edge_color = edge_color, width = weights)
项目:lomap    作者:wasserfeder    | 项目源码 | 文件源码
def visualize(self, edgelabel='prob', current_node=None,
                  draw='pygraphviz'):
        """
        Visualizes a LOMAP system model.
        """
        assert edgelabel is None or nx.is_weighted(self.g, weight=edgelabel)
        if draw == 'pygraphviz':
            nx.view_pygraphviz(self.g, edgelabel)
        elif draw == 'matplotlib':
            pos = nx.get_node_attributes(self.g, 'location')
            if len(pos) != self.g.number_of_nodes():
                pos = nx.spring_layout(self.g)
            if current_node is None:
                colors = 'r'
            else:
                if current_node == 'init':
                    current_node = next(self.init.iterkeys())
                colors = dict([(v, 'r') for v in self.g])
                colors[current_node] = 'b'
                colors = colors.values()
            nx.draw(self.g, pos=pos, node_color=colors)
            nx.draw_networkx_labels(self.g, pos=pos)
            edge_labels = nx.get_edge_attributes(self.g, edgelabel)
            nx.draw_networkx_edge_labels(self.g, pos=pos,
                                         edge_labels=edge_labels)
        else:
            raise ValueError('Expected parameter draw to be either:'
                             + '"pygraphviz" or "matplotlib"!')
项目:lomap    作者:wasserfeder    | 项目源码 | 文件源码
def visualize(self, edgelabel='control', current_node=None,
                  draw='pygraphviz'):
        """
        Visualizes a LOMAP system model.
        """
        assert edgelabel is None or nx.is_weighted(self.g, weight=edgelabel)
        if draw == 'pygraphviz':
            nx.view_pygraphviz(self.g, edgelabel)
        elif draw == 'matplotlib':
            pos = nx.get_node_attributes(self.g, 'location')
            if len(pos) != self.g.number_of_nodes():
                pos = nx.spring_layout(self.g)
            if current_node is None:
                colors = 'r'
            else:
                if current_node == 'init':
                    current_node = next(self.init.iterkeys())
                colors = dict([(v, 'r') for v in self.g])
                colors[current_node] = 'b'
                colors = colors.values()
            nx.draw(self.g, pos=pos, node_color=colors)
            nx.draw_networkx_labels(self.g, pos=pos)
            edge_labels = nx.get_edge_attributes(self.g, edgelabel)
            nx.draw_networkx_edge_labels(self.g, pos=pos,
                                         edge_labels=edge_labels)
        else:
            raise ValueError('Expected parameter draw to be either:'
                             + '"pygraphviz" or "matplotlib"!')
项目:WNTR    作者:USEPA    | 项目源码 | 文件源码
def scale_node_coordinates(self, scale):
        """
        Scales node coordinates, using 1:scale.  Scale should be in meters.

        Parameters
        -----------
        scale : float
            Coordinate scale multiplier.
        """
        pos = nx.get_node_attributes(self._graph, 'pos')

        for name, node in self._nodes.items():
            self.set_node_coordinates(name, (pos[name][0]*scale, pos[name][1]*scale))
项目:WNTR    作者:USEPA    | 项目源码 | 文件源码
def distance_to_epicenter(self, wn, element_type=wntr.network.Node):
        """
        Distance to the epicenter

        Parameters
        -----------
        wn : WaterNetworkModel

        element_type: optional (default = wntr.network.Node)

        Returns
        ---------
        R : pd.Series
            Distance to epicenter (m)
        """
        G = wn.get_graph_deep_copy()
        pos = nx.get_node_attributes(G,'pos')
        R = pd.Series()

        if element_type in [wntr.network.Link, wntr.network.Pipe, wntr.network.Pump, wntr.network.Valve]:
            # Compute pipe center position
            link_pos = {}
            for name, link in wn.links(element_type):
                start_point = pos[link.start_node]
                end_point = pos[link.end_node]
                link_pos[name] = ((end_point[0] + start_point[0])/2,
                                  (end_point[1] + start_point[1])/2)

            for name, link in wn.links(element_type):
                R[name] = distance.euclidean(self.epicenter, link_pos[name]) # m

        elif element_type in [wntr.network.Node, wntr.network.Junction, wntr.network.Tank, wntr.network.Reservoir]:
            for name, node in wn.nodes(element_type):
                R[name] = distance.euclidean(self.epicenter, pos[name]) # m

        return R
项目:WNTR    作者:USEPA    | 项目源码 | 文件源码
def _write_coordinates(self, f, wn):
        f.write('[COORDINATES]\n'.encode('ascii'))
        entry = '{:10s} {:f} {:f}\n'
        label = '{:10s} {:10s} {:10s}\n'
        f.write(label.format(';Node', 'X-Coord', 'Y-Coord').encode('ascii'))
        coord = nx.get_node_attributes(wn._graph, 'pos')
        keys = list(coord.keys())
        keys.sort()
        for key in keys:
            val = coord[key]
            f.write(entry.format(key, val[0], val[1]).encode('ascii'))
        f.write('\n'.encode('ascii'))
项目:TextAsGraphClassification    作者:NightmareNyx    | 项目源码 | 文件源码
def _node_product(G, H, label_threshold=None):
    for u, v in product(G, H):
        attrs = _dict_product(G.node[u], H.node[v])
        if label_threshold is not None:
            G_labels = nx.get_node_attributes(G, 'label')
            H_labels = nx.get_node_attributes(H, 'label')
            if abs(G_labels[u] - H_labels[v]) < label_threshold:
                new_label = G_labels[u] * H_labels[v]
                attrs['label'] = new_label
                yield ((u, v), attrs)
        else:
            yield ((u, v), attrs)
项目:TextAsGraphClassification    作者:NightmareNyx    | 项目源码 | 文件源码
def _node_product(G, H, label_threshold=None):
    for u, v in product(G, H):
        attrs = _dict_product(G.node[u], H.node[v])
        if label_threshold is not None:
            G_labels = nx.get_node_attributes(G, 'label')
            H_labels = nx.get_node_attributes(H, 'label')
            if abs(G_labels[u] - H_labels[v]) < label_threshold:
                new_label = G_labels[u] * H_labels[v]
                attrs['label'] = new_label
                yield ((u, v), attrs)
        else:
            yield ((u, v), attrs)
项目:sistercities    作者:displayn    | 项目源码 | 文件源码
def get(w, d) -> object:
    wikipedia = nx.DiGraph(w)
    wikidata = nx.DiGraph(d)

    root_nodes = nx.get_node_attributes(wikipedia, 'group')
    wikidata_root_nodes = nx.get_node_attributes(wikidata, 'group')
    assert (len(root_nodes) == len(wikidata_root_nodes)), 'Error: Graph root size should be the same!'

    url_wiki = nx.get_node_attributes(wikipedia, 'url')
    url_data = nx.get_node_attributes(wikidata, 'url')
    revision_id_wikipedia = nx.get_node_attributes(wikipedia, 'revision_id_wikipedia')
    revision_id_wikidata = nx.get_node_attributes(wikidata, 'revision_id_wikidata')
    city_list = []
    for c in root_nodes.keys():
        wg_neighbors = wikipedia.successors(c)
        wd_neighbors = wikidata.successors(c)

        pedia = set(wg_neighbors)
        data = set(wd_neighbors)

        intersection = set(pedia).intersection(data)
        wikipedia_missing = set(data) - set(pedia)
        wikidata_missing = set(pedia) - set(data)

        city_dict = {'qid': c,
                     'revision_id_wikipedia': revision_id_wikipedia[c],
                     'revision_id_wikidata': revision_id_wikidata[c],
                     'url': url_wiki[c],
                     'miss_wikipedia': city_build(url_data, wikipedia_missing),
                     'intersection': city_build(url_wiki, intersection),
                     'data_cities': city_build(url_wiki, wikidata_missing)
                     }
        city_list.append(city_dict)
    city_list = sorted(city_list, key=lambda x: x['url'])
    return city_list
项目:openanalysis    作者:OpenWeavers    | 项目源码 | 文件源码
def apply_to_graph(fun, G = None):
    """
    Applies given algorithm to random geometric graph and displays the results side by side

    :param fun: A function which has the signature f(G) and returns iterator of edges of graph G
    :param G: a networkx Graph. If None, random geometric graph is created and applied
    :return: Plot showing G and fun(G)
    """
    if G is None:
        G = nx.random_geometric_graph(100, .125)
        # position is stored as node attribute data for random_geometric_graph
        pos = nx.get_node_attributes(G, 'pos')
        nodesize = 80
        for u, v in G.edges():
            G.edge[u][v]['weight'] = ((G.node[v]['pos'][0] - G.node[u]['pos'][0]) ** 2 +
                                      (G.node[v]['pos'][1] - G.node[u]['pos'][1]) ** 2) ** .5
    else:
        pos = graphviz_layout(G)
        nodesize = 200
    # find node near center (0.5,0.5)
    color = {}
    dmin = 1
    ncenter = 0
    for n in pos:
        x, y = pos[n]
        d = (x - 0.5) ** 2 + (y - 0.5) ** 2
        color[n] = d
        if d < dmin:
            ncenter = n
            dmin = d

    res = nx.Graph(list(fun(G)))
    plt.figure(figsize=(10, 8))
    plt.suptitle(fun.__name__ + " algorithm application")
    plt.subplot(1, 2, 1)
    plt.title("Original Graph G")
    nx.draw_networkx_edges(G, pos, nodelist=[ncenter], alpha=0.4)
    nx.draw_networkx_nodes(G, pos,
                           nodelist=color.keys(),
                           node_size=nodesize,
                           node_color=list(color.values()),
                           cmap=plt.get_cmap("Reds_r")
                           ).set_edgecolor('k')
    if G is not None:
        nx.draw_networkx_labels(G,pos)
        nx.draw_networkx_edge_labels(G,pos,
                                     edge_labels=nx.get_edge_attributes(G,'weight'))
    plt.axis('off')
    plt.subplot(1, 2, 2)
    plt.title("Resultant Graph, R = {0}(G)".format(fun.__name__))
    nx.draw_networkx_edges(res, pos, nodelist=[ncenter], alpha=0.4)
    nx.draw_networkx_nodes(res, pos,
                           node_color=list(color[n] for n in res.nodes()),
                           node_size=nodesize,
                           cmap=plt.get_cmap("Greens_r")).set_edgecolor('k')
    if G is not None:
        nx.draw_networkx_labels(res,pos)
        nx.draw_networkx_edge_labels(res, pos,
                                     edge_labels=nx.get_edge_attributes(res, 'weight'))
    plt.axis('off')
    plt.show()
项目:uai2017_learning_to_acquire_information    作者:evanthebouncy    | 项目源码 | 文件源码
def get_dependency_coef(ge, link):
  broken_graph = copy.deepcopy(ge)
  iii, jjj = link
  broken_graph[iii][jjj] = 0
  broken_graph[jjj][iii] = 0

  comps = get_ccomp(broken_graph)
  halfs = dict()
  for blah in comps:
    if comps[blah] not in halfs:
      halfs[comps[blah]] = 1
    else:
      halfs[comps[blah]] += 1

  M = float(halfs[0])
  N = float(halfs[1])

  return (M * N) / ( (M + N) * (M + N - 1) )

# V = gen_pts(N)
# # G = gen_graph(V, 6)
# G = gen_spanning_tree(V)
# 
# G_V = V
# G_E = G
# 
# print G_V
# print G_E
# 
# Gr = nx.Graph()
# for i in range(N):
#   Gr.add_node(i, pos=G_V[i])
# 
# for i in range(N):
#   for j in range(N):
#     if G_E[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=250, with_labels=False)
# nx.draw_networkx_labels(Gr, pos, labels)
# 
# plt.savefig("graph.png")
项目:loman    作者:janusassetallocation    | 项目源码 | 文件源码
def _create_viz_dag(comp_dag, colors='state', cmap=None):
    colors = colors.lower()
    if colors == 'state':
        if cmap is None:
            cmap = _state_colors
    elif colors == 'timing':
        if cmap is None:
            cmap = mpl.colors.LinearSegmentedColormap.from_list('blend', ['#15b01a', '#ffff14', '#e50000'])
        timings = nx.get_node_attributes(comp_dag, _AN_TIMING)
        max_duration = max(timing.duration for timing in six.itervalues(timings) if hasattr(timing, 'duration'))
        min_duration = min(timing.duration for timing in six.itervalues(timings) if hasattr(timing, 'duration'))
    else:
        raise ValueError('{} is not a valid loman colors parameter for visualization'.format(colors))

    viz_dag = nx.DiGraph()
    node_index_map = {}
    for i, (name, data) in enumerate(comp_dag.nodes(data=True)):
        short_name = "n{}".format(i)
        attr_dict = {
            'label': name,
            'style': 'filled',
            '_group': data.get(_AN_GROUP)
        }

        if colors == 'state':
            attr_dict['fillcolor'] = cmap[data.get(_AN_STATE, None)]
        elif colors == 'timing':
            timing_data = data.get(_AN_TIMING)
            if timing_data is None:
                col = '#FFFFFF'
            else:
                duration = timing_data.duration
                norm_duration = (duration - min_duration) / (max_duration - min_duration)
                col = mpl.colors.rgb2hex(cmap(norm_duration))
            attr_dict['fillcolor'] = col

        viz_dag.add_node(short_name, **attr_dict)
        node_index_map[name] = short_name
    for name1, name2 in comp_dag.edges():
        short_name_1 = node_index_map[name1]
        short_name_2 = node_index_map[name2]

        group1 = comp_dag.node[name1].get(_AN_GROUP)
        group2 = comp_dag.node[name2].get(_AN_GROUP)
        group = group1 if group1 == group2 else None

        attr_dict = {'_group': group}

        viz_dag.add_edge(short_name_1, short_name_2, **attr_dict)
    return viz_dag