示例#1
0
def ring(N, R):

    # Create glias ring
    g1 = nx.cycle_graph(N)

    for glia in range(0, N):
        for r in range(1, R + 1):
            k = glia + r
            if k > N - 1:
                k = k - N
            g1.add_edge(glia, k)
            k = glia - r
            if k < 0:
                k = k + N
            g1.add_edge(glia, k)

    # Create neurons ring
    g2 = nx.cycle_graph(N)

    # Create inter adjacency matrix
    adj_block = mx.lil_matrix(np.zeros((N * 2, N * 2)))

    adj_block[0:N, N:2 * N] = np.identity(N)
    adj_block += adj_block.T

    mg = mx.MultilayerGraph(list_of_layers=[g1, g2],
                            inter_adjacency_matrix=adj_block)
    return mg
示例#2
0
文件: multiplex.py 项目: dPys/PyNets
def build_mx_multigraph(func_mat, dwi_mat, name, namer_dir):
    """
    It creates a symmetric (undirected) MultilayerGraph object from
    vertex-aligned structural and functional connectivity matrices.

    Parameters:
    -----------
    func_mat : ndarray
        Functional adjacency matrix of size N x N.
    dwi_mat : ndarray
        Structural adjacency matrix of size N x N.
    name : str
        Intended name of the multiplex object.
    namer_dir : str
        Path to output directory.

    Returns:
    --------
    mg_path : str
        A filepath to a gpickled MultilayerGraph object

    References
    ----------
    .. [1] R. Amato, N. E Kouvaris, M. San Miguel and A. Diaz-Guilera,
      Opinion competition dynamics on multiplex networks, New J. Phys.
      DOI: https://doi.org/10.1088/1367-2630/aa936a
    .. [2] N. E. Kouvaris, S. Hata and A. Diaz-Guilera, Pattern formation
      in multiplex networks, Scientific Reports 5, 10840 (2015).
      http://www.nature.com/srep/2015/150604/srep10840/full/srep10840.html
    .. [3] A. Sole-Ribata, M. De Domenico, N. E. Kouvaris, A. Diaz-Guilera, S.
      Gomez and A. Arenas, Spectral properties of the Laplacian of a multiplex
      network, Phys. Rev. E 88, 032807 (2013).
      http://journals.aps.org/pre/abstract/10.1103/PhysRevE.88.032807

    """
    import networkx as nx
    import multinetx as mx
    import pickle5 as pickle

    mg = mx.MultilayerGraph()
    N = dwi_mat.shape[0]
    adj_block = mx.lil_matrix(np.zeros((N * 2, N * 2)))
    adj_block[0:N, N:2 * N] = np.identity(N)
    adj_block += adj_block.T
    G_dwi = nx.from_numpy_matrix(dwi_mat)
    G_func = nx.from_numpy_matrix(func_mat)
    mg.add_layer(G_dwi)
    mg.add_layer(G_func)
    mg.layers_interconnect(inter_adjacency_matrix=adj_block)
    mg.name = name

    # Save mG to pickle
    graph_dir = f"{namer_dir}/mplx_graphs"
    if not os.path.isdir(graph_dir):
        os.mkdir(graph_dir)
    mG_path = f"{graph_dir}/{name}.pkl"
    nx.write_gpickle(mg, mG_path, protocol=2)

    return mG_path
示例#3
0
def test_plot_all_struct_func(plotting_data):
    """Test structural and functional plotting."""
    import multinetx as mx
    base_dir = str(Path(__file__).parent / "examples")
    temp_dir = tempfile.TemporaryDirectory()
    dir_path = str(temp_dir.name)

    labels = plotting_data['labels'][:10]
    coords = plotting_data['coords'][:10]
    metadata = {'coords': coords, 'labels': labels}

    name = 'output_fname'

    func_file = (
        f"{base_dir}/miscellaneous/graphs/002_modality-func_rsn-Default_roi-002_parcels_re"
        f"sampled2roimask_pDMN_3_bin_raw_est-sps_nodetype-spheres-6mm_smooth-2fwhm_hpass-"
        f"FalseHz_raw.npy")
    dwi_file = (
        f"{base_dir}/miscellaneous/graphs/002_modality-dwi_rsn-Default_roi-002_parcels_res"
        f"ampled2roimask_pDMN_3_bin_raw_est-sps_parc_samples-2streams_tt-local_dg-prob_ml-"
        f"200_raw.npy")
    modality_paths = (func_file, dwi_file)

    G_func = nx.from_numpy_matrix(np.load(func_file))
    G_dwi = nx.from_numpy_matrix(np.load(dwi_file))

    mG_path = tempfile.NamedTemporaryFile(mode='w+', suffix='.gpickle')
    mG = mx.MultilayerGraph(list_of_layers=[G_func, G_dwi])

    # This is a hack to get i/o working. There is an nx inhertiance issue that prevents reading.
    intra_layer_edges = mG.intra_layer_edges
    del mG.intra_layer_edges

    nx.write_gpickle(mG, mG_path.name)

    plot_gen.plot_all_struct_func(mG_path.name, dir_path, name, modality_paths,
                                  metadata)

    temp_dir.cleanup()
    mG_path.close()
示例#4
0
import numpy as np
import matplotlib.pyplot as plt
import multinetx as mx

N = 10
g1 = mx.erdos_renyi_graph(N, 0.07, seed=218)
g2 = mx.erdos_renyi_graph(N, 0.07, seed=211)

adj_block = mx.lil_matrix(np.zeros((N * 2, N * 2)))

adj_block[0:N, N:2 * N] = np.identity(N)  # L_12
adj_block += adj_block.T

mg = mx.MultilayerGraph(list_of_layers=[g1, g2],
                        inter_adjacency_matrix=adj_block)
mg.set_edges_weights(inter_layer_edges_weight=2)

mg.set_intra_edges_weights(layer=0, weight=1)
mg.set_intra_edges_weights(layer=1, weight=2)

fig = plt.figure(figsize=(10, 10))

ax1 = fig.add_subplot(122)
ax1.axis('off')
ax1.set_title('regular interconnected network')
pos = mx.get_position(mg,
                      mx.fruchterman_reingold_layout(mg.get_layer(0)),
                      layer_vertical_shift=1.4,
                      layer_horizontal_shift=0.0,
                      proj_angle=7)
示例#5
0
import multinetx as mx
import numpy as np
import matplotlib.pyplot as plt

N = 50
g1 = mx.erdos_renyi_graph(N, 0.07, seed=218)
g2 = mx.erdos_renyi_graph(N, 0.07, seed=211)
g3 = mx.erdos_renyi_graph(N, 0.07, seed=208)

mg = mx.MultilayerGraph(list_of_layers=[g1, g2, g3])
mg.set_intra_edges_weights(layer=0, weight=1)
mg.set_intra_edges_weights(layer=1, weight=2)
mg.set_intra_edges_weights(layer=2, weight=3)

fig = plt.figure(figsize=(15, 5))

ax2 = fig.add_subplot(122)
ax2.axis('off')
ax2.set_title('edge colored network')
pos = mx.get_position(mg,
                      mx.fruchterman_reingold_layout(g1),
                      layer_vertical_shift=0.2,
                      layer_horizontal_shift=0.0,
                      proj_angle=47)
mx.draw_networkx(mg,
                 pos=pos,
                 ax=ax2,
                 node_size=50,
                 with_labels=False,
                 edge_color=[mg[a][b]['weight'] for a, b in mg.edges()],
                 edge_cmap=plt.cm.jet_r)
示例#6
0
def main():
    data = collect_data('results/t6/')
    comm = collect_community('results/t6/')

    def find_best(data, method):
        key = max(data[method].iteritems(), key=operator.itemgetter(1))[0]
        y = data[method][key]
        return y, key, method

    print 'LART', data['lart']['9.0_1.0_1.0']
    print 'PMM', data['pmm']['30.0_140.0']
    print 'Glouvain', data['glouvain']['1.0_1.0']

    gl = find_best(data, 'glouvain')
    ll = find_best(data, 'lart')
    pl = find_best(data, 'pmm')

    print 'LART', ll
    print 'PMM', pl
    print 'Glouvain', gl

    best = max([gl, ll, pl], key=operator.itemgetter(0))
    best_comm = {}
    for b in comm[best[2]][best[1]].split('\n'):
        if b:
            a, l, c = b.split(',')
            best_comm['%s-%s' % (a, l)] = int(c)

    layers = {'RT': nx.Graph(), 'ff': nx.Graph(), 'Re': nx.Graph()}
    ids = {}

    counter = 0
    groups = []
    with open('data/t6/dk', 'r') as fd:
        for l in fd.readlines():
            a1, a2, layer = l.replace('\n', '').split(",")

            if a1 not in ids:
                ids[a1] = counter
                counter = counter + 1

            if a2 not in ids:
                ids[a2] = counter
                counter = counter + 1

            groups.append(best_comm['%s-%s' % (a1, layer)])
            groups.append(best_comm['%s-%s' % (a2, layer)])

            for k, v in layers.iteritems():
                v.add_node(ids[a1], label=best_comm['%s-%s' % (a1, layer)])
                v.add_node(ids[a2], label=best_comm['%s-%s' % (a2, layer)])

            layers[layer].add_edge(ids[a1], ids[a2])

    truth = {}
    with open('data/t6/dk_truth', 'r') as fd:
        for l in fd.readlines():
            actor, party = l.replace('\n', '').split(',')
            truth[actor] = party

    mapping = dict(zip(sorted(groups), count()))

    N, L = len(layers['ff'].nodes()), len(layers.keys())
    adj_block = mx.lil_matrix(np.zeros((N * L, N * L)))

    for i in xrange(L):
        for j in xrange(L):
            if i < j:
                adj_block[N * i:N * (i + 1),
                          N * j:(j + 1) * N] = np.identity(N)

    adj_block += adj_block.T

    mg = mx.MultilayerGraph(list_of_layers=[v for k, v in layers.items()])
    #inter_adjacency_matrix = adj_block)

    mg.set_edges_weights(intra_layer_edges_weight=1)
    #inter_layer_edges_weight=2)

    fig = plt.figure(figsize=(16, 16))
    plt.title('Twitter data of the Danish 2015 election')

    stats = collections.defaultdict(list)

    for k, v in best_comm.items():
        stats[v].append(k)

    stats2 = collections.defaultdict(dict)
    for k, v in stats.items():
        for e in v:
            actor, _ = e.split('-')

            if truth[actor] in stats2[k]:
                stats2[k][truth[actor]] += 1
            else:
                stats2[k][truth[actor]] = 1

    left = [
        'Dansk Folkeparti',
        'Venstre',
        'Liberal Alliance',
        'Det Konservative Folkeparti',
        'KristenDemokraterne',
    ]

    right = [
        'Socialistisk Folkeparti', 'Radikale Venstre', 'Socialdemokratiet',
        'Alternativet', 'Enhedslisten'
    ]
    out = 'Udenfor partierne'

    for k, v in stats2.items():
        total = 0
        for k1, v1 in v.items():
            total += v1

        pscore = 0
        for k1, v1 in v.items():
            if k1 in left:
                pscore += (stats2[k][k1] * 1)
            if k1 in right:
                pscore -= (stats2[k][k1] * 1)

            stats2[k][k1] = round(float(v1) / float(total), 2)

        stats2[k]['nodes'] = filter(
            lambda x, i=mg, k=k: i.node[x]['label'] == k, mg.node)
        stats2[k]['pscore'] = pscore / float(total)

    stats2 = dict(stats2)

    if len(sys.argv) > 1 and sys.argv[1] == 'heat':
        cmap = plt.get_cmap('RdBu_r')
        colors = [stats2[mg.node[n]['label']]['pscore'] for n in mg.nodes()]

        pos = mx.get_position(mg,
                              nx.spring_layout(layers[layers.keys()[2]],
                                               weight='pscore'),
                              layer_vertical_shift=0.2,
                              layer_horizontal_shift=0.0,
                              proj_angle=47)

        for key, val in stats2.items():
            set_trace()
            mx.draw_networkx_nodes(mg,
                                   pos=pos,
                                   node_size=100,
                                   with_labels=False,
                                   nodelist=val['nodes'],
                                   label=key,
                                   node_color=[colors[n] for n in val['']],
                                   cmap=cmap)
    else:
        val_map = {
            0: 'k',
            1: 'r',
            2: 'g',
            3: 'b',
            4: 'c',
            5: 'm',
            6: 'y',
            7: '0.75',
            8: 'w',
        }
        colors = [val_map[mg.node[n]['label']] for n in mg.nodes()]
        pos = mx.get_position(mg,
                              nx.spring_layout(layers[layers.keys()[2]]),
                              layer_vertical_shift=0.2,
                              layer_horizontal_shift=0.0,
                              proj_angle=47)

        for k, v in stats2.items():
            mx.draw_networkx_nodes(mg,
                                   pos=pos,
                                   node_size=100,
                                   with_labels=False,
                                   nodelist=v['nodes'],
                                   label=k,
                                   node_color=[colors[n] for n in v['nodes']],
                                   cmap=plt.get_cmap('Set2'))

    mx.draw_networkx_edges(mg, pos=pos, edge_color='b')

    fig.tight_layout()
    plt.legend(numpoints=1, loc=1)
    plt.xticks([])
    plt.yticks([])
    plt.show()
示例#7
0
    def multilayer(self, filename='multilayer_network'):
        import numpy as np
        import matplotlib.pyplot as plt
        import multinetx as mx
        import networkx as nx
        from mpl_toolkits.basemap import Basemap

        # %% Define the type of interconnection between the layers
        N = len(self.poi_nodes) + len(self.user_nodes)
        N1 = len(self.poi_nodes)
        adj_block = mx.lil_matrix(np.zeros((N, N)))

        for row in self.user_poi_s.iterrows():
            user_ind = self.user_nodes[self.user_nodes['userId'] == row[1]
                                       ['userId']].index[0]
            pos_ind = self.poi_nodes[self.poi_nodes['venueId'] == row[1]
                                     ['venueId']].index[0]

            adj_block[pos_ind, user_ind] = row[1]['weight']

        adj_block += adj_block.T

        # %% multilayer network
        poi_layer = nx.Graph(layer='POI')
        poi_layer.add_nodes_from(self.poi_nodes.index.values)
        poi_layer.add_weighted_edges_from(self.poi_edges)

        user_layer = nx.DiGraph(layer='User')
        user_layer.add_nodes_from(self.user_nodes.index.values)
        user_layer.add_weighted_edges_from(self.user_edges)

        mg = mx.MultilayerGraph(list_of_layers=[poi_layer, user_layer],
                                inter_adjacency_matrix=adj_block)

        # venue position in decimal lat/lon
        lats_v = list(self.poi_nodes['latitude'])
        lons_v = list(self.poi_nodes['longitude'])

        min_lat = min(lats_v)
        max_lat = max(lats_v)
        min_lon = min(lons_v)
        max_lon = max(lons_v)

        # user position in decimal lat/lon
        lats_u = list(self.user_nodes['latitude'])
        lons_u = list(self.user_nodes['longitude'])

        min_lat = min(min_lat, min(lats_u))
        max_lat = max(max_lat, max(lats_u))
        min_lon = min(min_lon, min(lons_u))
        max_lon = max(max_lon, max(lons_u))

        m = Basemap(projection='merc',
                    llcrnrlon=min_lon,
                    llcrnrlat=min_lat,
                    urcrnrlon=max_lon,
                    urcrnrlat=max_lat,
                    lat_ts=0,
                    resolution='i',
                    suppress_ticks=True)

        # convert lat and lon to map projection
        x, y = m(lons_v, lats_v)

        ppos = {}
        n = 0
        for v in self.poi_nodes.index:
            ppos[v] = np.asarray([x[n], y[n]])
            n += 1

        # convert lat and lon to map projection
        x, y = m(lons_u, lats_u)
        n = 0
        for v in self.user_nodes.index:
            ppos[v] = np.asarray([x[n], y[n]])
            n += 1

        target_userID = list(self.similar_users['userId1'])[0]
        node_of_target_user = self.user_nodes[self.user_nodes['userId'] ==
                                              target_userID].index[0]

        for i in range(2):
            pos = mx.get_position(mg,
                                  ppos,
                                  layer_vertical_shift=1000.0,
                                  layer_horizontal_shift=400.0,
                                  proj_angle=0.2)

            fig, ax2 = plt.subplots(figsize=(10, 5))
            # ax2.axis('off')
            ax2.set_title(
                'Multilayer Network of User and PoI (Target User ID: {0})'.
                format(target_userID))

            mg.set_edges_weights(inter_layer_edges_weight=3)
            mg.set_intra_edges_weights(layer=0, weight=5)
            # mg.set_intra_edges_weights(layer=1,weight=2)

            mx.draw_networkx(
                mg,
                pos=pos,
                ax=ax2,
                node_size=50,
                with_labels=False,
                node_color=[
                    'y' if a < N1 else
                    ('brown' if a == node_of_target_user else 'g')
                    for a in mg.nodes()
                ],
                edge_color=[mg[a][b]['weight'] for a, b in mg.edges()],
                edge_cmap=plt.cm.Blues)

        # plt.show()
        plt.savefig('output/{0}.png'.format(filename),
                    dpi=500,
                    bbox_inches='tight')
示例#8
0
    pos_ind = poi_nodes[poi_nodes['venueId'] == row[1]['venueId']].index[0]

    adj_block[pos_ind, user_ind] = row[1]['weight'] 

adj_block += adj_block.T

# %% multilayer network
poi_layer = nx.Graph(layer='POI')
poi_layer.add_nodes_from(poi_nodes.index.values)
poi_layer.add_weighted_edges_from(poi_edges)

user_layer = nx.DiGraph(layer='User')
user_layer.add_nodes_from(user_nodes.index.values)
user_layer.add_weighted_edges_from(user_edges)

mg = mx.MultilayerGraph(list_of_layers=[poi_layer,user_layer], inter_adjacency_matrix=adj_block)

m = Basemap(
        projection='merc',
        llcrnrlon=lon1,
        llcrnrlat=lat1,
        urcrnrlon=lon2,
        urcrnrlat=lat2,
        lat_ts=0,
        resolution='i',
        suppress_ticks=True)

# position in decimal lat/lon
lats=list(poi_nodes['latitude'])
lons=list(poi_nodes['longitude'])
# convert lat and lon to map projection