Пример #1
0
def bc_degree_relativity():
    song = fm.FontProperties(fname=os.path.join(base_dir, '../simsun.ttc'),
                             size=10.5)
    sns.set(style='ticks', palette='Set2')
    plt.figure(dpi=200)
    c = {
        'family': 'sans-serif',
        'sans-serif': ['Times New Roman', 'NSimSun'],
        'size': 10.5
    }
    rc('font', **c)
    plt.rcParams['axes.unicode_minus'] = False
    network = get_shanghai_subway_graph()
    bc_list = betweenness_centrality(network)
    degree_list = dict()
    for node in network.nodes:
        degree_list[node] = network.degree(node)
    fig, ax = plt.subplots(num=1, figsize=(3.54, 2.26))
    plt.subplots_adjust(right=0.99, left=0.125, bottom=0.14, top=0.975)
    x = list()  # degree
    y = list()  # bc
    for i in degree_list.keys():
        x.append(degree_list[i])
        y.append(bc_list[i])
    x1, y1 = zip(*sorted(zip(x, y)))
    p2, = ax.plot(x1, y1, 'o', ms=4)
    ax.set_xlabel('度', fontproperties=song)
    ax.set_ylabel('介数中心性', fontproperties=song)
    plt.show()
def draw_3():
    song = fm.FontProperties(fname=os.path.join(base_dir, '../simsun.ttc'), size=10.5)
    sns.set(style='ticks', palette='Set2')
    c = {'family': 'sans-serif', 'sans-serif': ['Times New Roman', 'NSimSun'], 'size': 10.5}
    rc('font', **c)
    plt.rcParams['axes.unicode_minus'] = False
    plt.figure(dpi=200)
    fig, ax = plt.subplots(num=1, figsize=(3.54, 2.26))
    plt.subplots_adjust(right=0.99, left=0.125, bottom=0.14, top=0.975)
    x1, y1 = degree_sequence(get_shanghai_subway_graph())
    p1 = ax.bar(x1, y1, width=0.35)
    x2, y2 = degree_sequence(get_chengdu_subway_graph())
    new_x2 = list()
    for i in range(0, len(x2)):
        new_x2.append(x2[i] + 0.35)
    p2 = ax.bar(new_x2, y2, width=0.35)
    ax.set_xticks([d + 0.525 for d in x1])
    ax.set_xticklabels(x1)
    ax.set_xlabel("度", fontproperties=song)
    ax.set_ylabel("比例(%)", fontproperties=song)
    ax.legend(
        [p1, p2],
        [u'上海', u'成都'],
        prop=dict(fname=os.path.join(base_dir, '../simsun.ttc'), size=10.5)
    )
    plt.show()
Пример #3
0
def cal_data(shanghai=True):
    data = list()
    if shanghai:
        with open(os.path.join(base_dir, '上海BC排序.csv'), 'r',
                  encoding='utf-8') as f:
            r = csv.DictReader(f)
            for row in r:
                data.append(row['BC'])
        p = os.path.join(base_dir, '上海BC分布.csv')
        g = get_shanghai_subway_graph()
    else:
        with open(os.path.join(base_dir, 'BC排序-七号线开通后.csv'),
                  'r',
                  encoding='utf-8') as f:
            r = csv.DictReader(f)
            for row in r:
                data.append(row['BC'])
        p = os.path.join(base_dir, '成都BC分布.csv')
        g = get_chengdu_subway_graph()
    r = [0, 0, 0, 0, 0, 0]
    for i in data:
        temp = int(float(i) // 0.05)
        r[temp] += 1
    result = list()
    for i in range(0, len(r)):
        result.append({
            'num': (i + 1) * 0.05,
            'distribution': r[i] / len(g.nodes)
        })
    with open(p, 'a') as f:
        w = csv.DictWriter(f, ['num', 'distribution'])
        w.writeheader()
        w.writerows(result)
Пример #4
0
def shanghai_highest_bc_attack_list(G, fraction=0.0):
    nodes_num = len(G)
    remove_num = int(fraction * nodes_num)
    result = list()
    bc = bc_list(get_shanghai_subway_graph())
    for i in range(0, remove_num):
        result.append(bc[i][0])
    return result
Пример #5
0
def generate_shanghai_bc_list():
    """
    生成成都BC排序的结果。
    :return:
    """
    result = bc_list(get_shanghai_subway_graph())
    l = list()
    for i in result:
        l.append({'name': i[0], 'BC': i[1]})
    with open(os.path.join(base_dir, '上海BC排序.csv'), 'a',
              encoding='utf-8') as f:
        w = csv.DictWriter(f, ['name', 'BC'])
        w.writeheader()
        w.writerows(l)
Пример #6
0
def draw_map():
    dwg = svgwrite.Drawing('../picture/上海地铁位置图.svg',
                           profile='full',
                           size=('2000', '3000'))
    for i in pos:
        dwg.add(
            svgwrite.shapes.Circle(center=(i['latitude'], i['longitude']),
                                   fill='#8fddff',
                                   r=8,
                                   fill_opacity="0.5"))
        dwg.add(
            svgwrite.text.Text(
                text=i['name'],
                insert=(i['latitude'], i['longitude']),
                font_size="5",
                font_family="黑体",
                style="text-anchor: middle; dominant-baseline: central;"))
    g = get_shanghai_subway_graph()
    for e in g.edges.data():
        pos_a = get_location(e[0], pos)
        pos_b = get_location(e[1], pos)
        try:
            dwg.add(
                svgwrite.path.Path(stroke_width="1",
                                   stroke_opacity="0.5",
                                   stroke="#ffaa5c",
                                   d="M {},{} L {},{}".format(
                                       pos_a[0], pos_a[1], pos_b[0],
                                       pos_b[1])))
        except:
            print(e)
        dwg.add(
            svgwrite.text.Text(
                text=e[2]['weight'] if 'weight' in e[2].keys() else '',
                font_size="5",
                font_family="黑体",
                style="text-anchor: middle; dominant-baseline: central;",
                insert=((pos_a[0] + pos_b[0]) / 2, (pos_a[1] + pos_b[1]) / 2)))
    dwg.save()
def get_result(attack, protect):
    result = list()
    attack_name = attack.__name__.replace('_attack_list', '')
    protect_name = protect.__name__.replace('_attack_list', '')
    for i in range(0, 25):
        print('{} attack with {} protect:'.format(attack_name, protect_name))
        attack_fraction = d * i
        print('attack fraction: %.2f' % attack_fraction)
        j = 0
        g = get_shanghai_subway_graph()
        attack_list = attack(g, fraction=attack_fraction)
        protect_fraction = d * j
        print('\t protect fraction: %.2f' % protect_fraction)
        protect_list = protect(g, fraction=protect_fraction)
        for node in attack_list:
            if node not in protect_list:
                g.remove_node(node)
        result.append({
            'attack_fraction': "%.2f" % attack_fraction,
            'protect_fraction': "%.2f" % protect_fraction,
            'efficiency': global_efficiency(g)
        })
    return result
Пример #8
0
def shanghai_highest_bc_attack(fraction=0.0):
    g = get_shanghai_subway_graph()
    for i in shanghai_highest_bc_attack_list(g, fraction):
        g.remove_node(i)
    return g
Пример #9
0
def shanghai_largest_degree_attack(fraction=0.0):
    g = get_shanghai_subway_graph()
    for i in largest_degree_attack_list(g, fraction):
        g.remove_node(i)
    return g
Пример #10
0
def shanghai_random_attack(fraction=0.0):
    g = get_shanghai_subway_graph()
    for i in random_attack_list(g, fraction):
        g.remove_node(i)
    return g
Пример #11
0
    for i in l:
        result.append({'node': i})
    if shanghai:
        p = os.path.join(base_dir, '攻击0.1节点/上海')
    else:
        p = os.path.join(base_dir, '攻击0.1节点/成都')
    p = os.path.join(p, '{}.csv'.format(list_func.__name__))
    print(p)
    with open(p, 'a', encoding='gbk') as f:
        w = csv.DictWriter(f, ['node'])
        w.writeheader()
        w.writerows(result)


if __name__ == "__main__":
    fraction = 0.1
    G = get_shanghai_subway_graph()
    l = [
        random_attack_list, largest_degree_attack_list,
        shanghai_highest_bc_attack_list, highest_bt_attack_list
    ]
    for i in l:
        get_list(G, fraction, i, shanghai=True)
    G = get_chengdu_subway_graph()
    l = [
        random_attack_list, largest_degree_attack_list, highest_bc_attack_list,
        highest_bt_attack_list
    ]
    for i in l:
        get_list(G, fraction, i, shanghai=False)