graph-tool文档(一)- 快速开始使用Graph-tool - 2.属性映射、图的IO和Price网络
目录:
- 属性映射
-- 内部属性映射 - 图的I/O
- 构建一个 Price网络(例)
名词解释:
Property maps:属性映射
PropertyMap:一个类
scalar value types:标量值类型
pickle module:
scale-free graph:
属性映射
属性映射是一种将额外信息与顶点、边或图本身相关联的方式。
因此有这样三种类型的属性映射:顶点、边和图。
它们都是由同一个类来操作:PropertyMap。
每个创建了的属性映射都有一个与之相关联的类型的值,预定义设置的类型有如下几种:
| Type name | Alias |
|---|---|
| bool | uint8_t |
| int16_t | short |
| int32_t | int |
| int64_t | long, long long |
| double | float |
| long double | . |
| string | . |
| vector bool | vector uint8_t |
| vector int16_t | vector short |
| vector int32_t | vector int |
| vector int64_t | vector long, vector long long |
| vector double | vector float |
| vector long double | . |
| vector string | . |
| python::object | object |
可以对于每一个映射类型通过调用new_vertex_property(),new_edge_property()或new_graph_property()为一个指定的图创建新的属性映射。
然后可以通过顶点或边的描述符或图本身来访问该值,因此:
from itertools import izip
from numpy.random import randint
g = Graph()
g.add_vertex(100)
# insert some random links
for s,t in izip(randint(0, 100, 100), randint(0, 100, 100)):
g.add_edge(g.vertex(s), g.vertex(t))
vprop_double = g.new_vertex_property("double") # Double-precision floating point
vprop_double[g.vertex(10)] = 3.1416
vprop_vint = g.new_vertex_property("vector<int>") # Vector of ints
vprop_vint[g.vertex(40)] = [1, 3, 42, 54]
eprop_dict = g.new_edge_property("object") # Arbitrary python object.
eprop_dict[g.edges().next()] = {"foo": "bar", "gnu": 42} # In this case, a dict.
gprop_bool = g.new_graph_property("bool") # Boolean
gprop_bool[g] = True
标量值类型的属性映射也可以被当做numpy.ndarray来访问,通过get_array()方法,或者a属性。
from numpy.random import random
# this assigns random values to the vertex properties
vprop_double.get_array()[:] = random(g.num_vertices())
# or more conveniently (this is equivalent to the above)
vprop_double.a = random(g.num_vertices())
内部属性映射
任何创建的属性映射可以作为“内部”到相应的图上。
这意味着它将被复制并和图一起被保存到一个文件。
属性被内在化,通过将它们包括在图的类字典属性中:vertex_properties,edge_properties或graph_properties(或它们的别名,vp,ep或gp)。
当插入到图中时,属性映射必须有一个唯一的名称(相同类型的之间):
>>> eprop = g.new_edge_property("string")
>>> g.edge_properties["some name"] = eprop
>>> g.list_properties()
some name (edge) (type: string)
内部图的属性映射表现得略有不同。
它不是返回属性映射对象,值本身是从字典中返回的:
>>> gprop = g.new_graph_property("int")
>>> g.graph_properties["foo"] = gprop # this sets the actual property map
>>> g.graph_properties["foo"] = 42 # this sets its value
>>> print(g.graph_properties["foo"])
42
>>> del g.graph_properties["foo"] # the property map entry is deleted from the dictionary
为了方便起见,内部属性映射也可以通过属性来访问:
>>> vprop = g.new_vertex_property("double")
>>> g.vp.foo = vprop # equivalent to g.vertex_properties["foo"] = vprop
>>> v = g.vertex(0)
>>> g.vp.foo[v] = 3.14
>>> print(g.vp.foo[v])
3.14
图的I/O
图可以通过四种格式保存和加载:graphml、dot、gml和一个定制的二进制格式gt(见gt文件格式)。
警告:
二进制格式gt和graphml是首选的格式,因为它们是迄今为止最完整的。
这些格式都是同样完整的,但gt速度更快,需要的存储空间也更少。
图可以保存或加载到一个文件上,通过save和load方法,以一个文件名或类似文件的对象。
图也可以从光盘上加载,通过load_graph()函数,如下:
g = Graph()
# ... fill the graph ...
g.save("my_graph.xml.gz")
g2 = load_graph("my_graph.xml.gz")
# g and g2 should be copies of each other
图类也可以通过pickle模块来pickled with。
一个例子:构建一个 Price网络
Price网络是第一个已知的“无尺度”图模型,于1976年被de Solla Price发明。
它是被动态定义的,每一步添加一个新的顶点到图中,并连接到一个旧的顶点,概率与它的入度成正比。
下面的程序使用graph-tool实现了这个结构。
注意:
只使用price_network()函数将会快得多,因为它是以c++实现的,而不是像下面的脚本一样使用纯python。
下面的代码仅仅是一个如何使用该库的示例。
#! /usr/bin/env python
# We will need some things from several places
from __future__ import division, absolute_import, print_function
import sys
if sys.version_info < (3,):
range = xrange
import os
from pylab import * # for plotting
from numpy.random import * # for random sampling
seed(42)
# We need to import the graph_tool module itself
from graph_tool.all import *
# let's construct a Price network (the one that existed before Barabasi). It is
# a directed network, with preferential attachment. The algorithm below is
# very naive, and a bit slow, but quite simple.
# We start with an empty, directed graph
g = Graph()
# We want also to keep the age information for each vertex and edge. For that
# let's create some property maps
v_age = g.new_vertex_property("int")
e_age = g.new_edge_property("int")
# The final size of the network
N = 100000
# We have to start with one vertex
v = g.add_vertex()
v_age[v] = 0
# we will keep a list of the vertices. The number of times a vertex is in this
# list will give the probability of it being selected.
vlist = [v]
# let's now add the new edges and vertices
for i in range(1, N):
# create our new vertex
v = g.add_vertex()
v_age[v] = i
# we need to sample a new vertex to be the target, based on its in-degree +
# 1. For that, we simply randomly sample it from vlist.
i = randint(0, len(vlist))
target = vlist[i]
# add edge
e = g.add_edge(v, target)
e_age[e] = i
# put v and target in the list
vlist.append(target)
vlist.append(v)
# now we have a graph!
# let's do a random walk on the graph and print the age of the vertices we find,
# just for fun.
v = g.vertex(randint(0, g.num_vertices()))
while True:
print("vertex:", int(v), "in-degree:", v.in_degree(), "out-degree:",
v.out_degree(), "age:", v_age[v])
if v.out_degree() == 0:
print("Nowhere else to go... We found the main hub!")
break
n_list = []
for w in v.out_neighbours():
n_list.append(w)
v = n_list[randint(0, len(n_list))]
# let's save our graph for posterity. We want to save the age properties as
# well... To do this, they must become "internal" properties:
g.vertex_properties["age"] = v_age
g.edge_properties["age"] = e_age
# now we can save it
g.save("price.xml.gz")
# Let's plot its in-degree distribution
in_hist = vertex_hist(g, "in")
y = in_hist[0]
err = sqrt(in_hist[0])
err[err >= y] = y[err >= y] - 1e-2
figure(figsize=(6,4))
errorbar(in_hist[1][:-1], in_hist[0], fmt="o", yerr=err,
label="in")
gca().set_yscale("log")
gca().set_xscale("log")
gca().set_ylim(1e-1, 1e5)
gca().set_xlim(0.8, 1e3)
subplots_adjust(left=0.2, bottom=0.2)
xlabel("$k_{in}$")
ylabel("$NP(k_{in})$")
tight_layout()
savefig("price-deg-dist.pdf")
savefig("price-deg-dist.png")
下面是程序的运行结果:
vertex: 36063 in-degree: 0 out-degree: 1 age: 36063
vertex: 9075 in-degree: 4 out-degree: 1 age: 9075
vertex: 5967 in-degree: 3 out-degree: 1 age: 5967
vertex: 1113 in-degree: 7 out-degree: 1 age: 1113
vertex: 25 in-degree: 84 out-degree: 1 age: 25
vertex: 10 in-degree: 541 out-degree: 1 age: 10
vertex: 5 in-degree: 140 out-degree: 1 age: 5
vertex: 2 in-degree: 459 out-degree: 1 age: 2
vertex: 1 in-degree: 520 out-degree: 1 age: 1
vertex: 0 in-degree: 210 out-degree: 0 age: 0
Nowhere else to go... We found the main hub!
下面是100000个节点的度的分布。
如果你想看到一个更广泛的幂律,可以尝试增加顶点的数量到(10 ^ 6)或(10 ^ 7)。

(10 ^ 5)个节点的Price网络的入度分布。
我们可以画图来观察它的一些其他的拓扑特性。
为此,我们可以使用graph_draw()函数。
g = load_graph("price.xml.gz")
age = g.vertex_properties["age"]
pos = sfdp_layout(g)
graph_draw(g, pos, output_size=(1000, 1000), vertex_color=[1,1,1,0],
vertex_fill_color=age, vertex_size=1, edge_pen_width=1.2,
vcmap=matplotlib.cm.gist_heat_r, output="price.png")
一个有(10 ^ 5 )个节点的Price网络。
顶点颜色代表顶点的年龄,旧的(红色),新的(黑)。
原文链接:Quick start using graph-tool
graph-tool文档(一)- 快速开始使用Graph-tool - 2.属性映射、图的IO和Price网络的更多相关文章
- [Swift通天遁地]七、数据与安全-(2)对XML和HTML文档的快速解析
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★➤微信公众号:山青咏芝(shanqingyongzhi)➤博客园地址:山青咏芝(https://www.cnblogs. ...
- 空间日志编辑器:word文档图文快速粘贴到web
百度ueditor可以实现word文档图文快速粘贴到web 1.4.2之后官方并没有做功能的改动,1.4.2在word复制这块没有bug,其他版本会出现手动无法转存的情况 本文使用的后台是Java.前 ...
- jQuery---jq操作标签文本(html(),text()),jq操作文档标签(插入,删除,修改),克隆,,jq操作属性,jq操作class属性,jq操作表单value,jq操作css,jq操作盒子(重要),jq操作滚动条
jQuery---jq操作标签文本(html(),text()),jq操作文档标签(插入,删除,修改),克隆,,jq操作属性,jq操作class属性,jq操作表单value,jq操作css,jq操作盒 ...
- apidoc接口文档的快速生成
官方文档连接:http://apidocjs.com/#demo apidoc是一个轻量级的在线REST接口文档生成系统,支持多种主流语言,包括Java.C.C#.PHP和Javascript等.使用 ...
- 淘宝(阿里百川)手机客户端开发日记第十篇 阿里百川服务器环境介绍之API文档的快速链接(四)
个人感觉比较重要的快速链接: http://open.taobao.com/doc/detail.htm?id=102513 http://open.taobao.com/doc/detail.htm ...
- 转: seajs手册与文档之 -- 快速参考 ( ~~useful )
目录 快速参考 seajs.use seajs.config define require require.async exports module.exports 快速参考 该页面列举了 SeaJS ...
- 通过beego快速创建一个Restful风格API项目及API文档自动化
通过beego快速创建一个Restful风格API项目及API文档自动化 本文演示如何快速(一分钟内,不写一行代码)的根据数据库及表创建一个Restful风格的API项目,及提供便于在线测试API的界 ...
- 通过beego快速创建一个Restful风格API项目及API文档自动化(转)
通过beego快速创建一个Restful风格API项目及API文档自动化 本文演示如何快速(一分钟内,不写一行代码)的根据数据库及表创建一个Restful风格的API项目,及提供便于在线测试API的界 ...
- 快速创建vuepress项目(使用vuepress写文档)
vuepress的官方文档:https://vuepress.vuejs.org/zh/guide/ 参考:https://segmentfault.com/a/1190000016333850 ht ...
随机推荐
- 2016年11月2日 星期三 --出埃及记 Exodus 19:18
2016年11月2日 星期三 --出埃及记 Exodus 19:18 Mount Sinai was covered with smoke, because the LORD descended on ...
- 改变了一下blog的主题,很开心
调整了一下博客的样式,之前一直想改变下,一直不会这次终于摸索出来一点,不过是最简单的,就是在管理里面的设置,可以定制css代码,修改修改,页面就跟着你的想法走了,有时间好好修改下,暂时这个样子,简单大 ...
- ios获取摄像头与相册图片
iOS的一些设备上都安装了摄像头.现在绝大多数都有了. 在编程中,我们是用相应的东西来进行照相,录像等功能. 一.UIImagePickerController类 UIImagePickerCon ...
- 表头表侧边固定,方法二,丫的,复制td
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title&g ...
- C#正则表达式获取组名,按照组名输出匹配内容
最近写了个正则表达式匹配的工具,可以按照组名输出匹配内容,还是挺方便的,代码留存一下,以后用的话,直接copy了. Regex regex = new Regex(this.textBoxRegex. ...
- 【转载】COM的多线程模型
原文:COM的多线程模型 COM的多线程模型是COM技术里头最难以理解的部分之一,很多书都有涉及但是都没有很好的讲清楚.很多新人都会在这里觉得很迷惑,google大神能搜到一篇vckbase上的文章, ...
- Java——Socket编程(一)
1. 网络基础知识 两台机器之间需要进行通信,需要满足的条件: 每个机器有一个唯一的标识符(IP地址): 他们之间进行通信需要用同一种语言(协议): 每台主机上面有多个应用程序,如QQ,微博,迅雷等, ...
- DataSet.Clear Method ()
Clears the DataSet of any data by removing all rows in all tables. 需要注意的是这个方法不会清空DataSet中的DataTable, ...
- Get_File_Name Usage in Oracle Forms 6i
Get_File_Name is built-in function of Oracle Forms 6i, used to get the file name with address by bro ...
- flex中实现自动换行
有时候由于label .button等控件中需要用到text属性显示出文本,文本太长就涉及到换行问题,解决方法如下 在actionScript 需要用“ ”实现换行,在需要换行的地方加上它就OK. ...