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)
python类get_node_attributes()的实例源码
graph.py 文件源码
项目:uai2017_learning_to_acquire_information
作者: evanthebouncy
项目源码
文件源码
阅读 34
收藏 0
点赞 0
评论 0
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
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
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 []
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
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
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
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
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"
)
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)
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
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
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
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)
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)
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_)
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')
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
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
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
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
def displayMatplot():
# display in matplotlib
pos=nx.get_node_attributes(g,'pos')
nx.draw(g,pos)
plt.show()
# plt.savefig("/tmp/path.png")
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)
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
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()
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])
)
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
def get_atom_features(self, node_id):
attrs = nx.get_node_attributes(self.graph, "atom_features")
return attrs[node_id]
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)
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"!')