def __init__(self, n=0, layer=0, ntype='erdos', options={}): self.__layer = layer self.__n = n self.__ntype = ntype if self.__ntype == 'erdos': self.__graph = mx.generators.erdos_renyi_graph( self.__n, options["rand"], seed=options["seed"]) self.__adjacency_matrix = mx.adjacency_matrix(self.__graph, weight="weight") for i in range(0, self.__n): self.__nodes.append(node.Node(i, self.__layer))
def write_mx_to_json(filename, mg, nNodes, pos, nLayers, nodes_to_remove=[]): # filename the complete name of the output file (data/slide_x.json) # mx the multilayer network as a multinetx object # nNodes the number of nodes in the first layer # pos a dictionary of node coordinates # nLayers the number of layers in the second aspect. # nodes_to_remove is a list of nodes that should not exist in each layer. Default = [] # From the sparse adj, make a networkx graph and add node attributes G1 = nx.from_numpy_array( mx.adjacency_matrix(mg, weight='weight').todense()) # Remove nodes from G G1.remove_nodes_from(nodes_to_remove) # Recreate the graph G to make the rest work nicely. G = nx.from_numpy_array(nx.adjacency_matrix(G1).todense()) # Create dictionaries pretending like all nodes exist scalefact = 20 L2_classes = np.arange(nLayers) L2_array_original = np.array([]) z_shift = 2 z_array_original = np.array([]) x_orig = np.array([]) y_orig = np.array([]) L1_orig = np.array([]) for level in L2_classes: L2_array_original = np.concatenate( (L2_array_original, np.array([float(level) for i in np.arange(nNodes)]))) z_array_original = np.concatenate( (z_array_original, np.array([float(level * z_shift) for i in np.arange(nNodes)]))) x_orig = np.concatenate( (x_orig, [pos[key][0] + scalefact for key in pos])) y_orig = np.concatenate( (y_orig, [pos[key][1] + scalefact for key in pos])) L1_orig = np.concatenate((L1_orig, [i for i in np.arange(nNodes)])) # Need to delete nodes from our attribute dictionaries, too L2_array = np.delete(L2_array_original, nodes_to_remove, 0) z_array = np.delete(z_array_original, nodes_to_remove, 0) x_array = np.delete(x_orig, nodes_to_remove, 0) y_array = np.delete(y_orig, nodes_to_remove, 0) L1_array = np.delete(L1_orig, nodes_to_remove, 0) ## Each node will get attributes L1=node id, L2=slice number, x position, y position, and name/id id_dict = {i: ("id" + str(i)) for i in np.arange(nNodes * nLayers)} x_dict = {} y_dict = {} L2_dict = {i: l2 for i, l2 in enumerate(L2_array)} z_dict = {i: z_val for i, z_val in enumerate(z_array)} x_dict = {i: x_val for i, x_val in enumerate(x_array)} y_dict = {i: y_val for i, y_val in enumerate(y_array)} L1_dict = {i: L1_val for i, L1_val in enumerate(L1_array)} nx.set_node_attributes(G, id_dict, name="name") nx.set_node_attributes(G, x_dict, name="x") nx.set_node_attributes(G, y_dict, name="y") nx.set_node_attributes(G, z_dict, name="z") nx.set_node_attributes(G, L1_dict, name="L1") nx.set_node_attributes(G, L2_dict, name="L2") G_json = json_graph.node_link_data(G) # Write for visualization function G_json_viz = json.dumps(G_json, indent=4) # To save as a .json file with open(filename, 'w') as fp: json.dump(G_json, fp) print(f"done writing mx to {filename}") return G_json_viz
##Create an instance of the MultilayerGraph class mg = mx.MultilayerGraph(list_of_layers=[g1, g2, g3], inter_adjacency_matrix=adj_block) mg.set_edges_weights(inter_layer_edges_weight=4) 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) ##Plot the adjacency matrix and the multiplex networks fig = plt.figure(figsize=(15, 5)) ax1 = fig.add_subplot(121) ax1.imshow(mx.adjacency_matrix(mg, weight='weight').todense(), origin='upper', interpolation='nearest', cmap=plt.cm.jet_r) ax1.set_title('supra adjacency matrix') ax2 = fig.add_subplot(122) ax2.axis('off') ax2.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) mx.draw_networkx(mg, pos=pos,
def plot_all_struct_func(mG_path, namer_dir, name, modality_paths, metadata): """ Plot adjacency matrix and glass brain for structural-functional multiplex connectome. Parameters ---------- mG_path : str A gpickle file containing a a MultilayerGraph object (See https://github.com/nkoub/multinetx). namer_dir : str Path to output directory for multiplex data. name : str Concatenation of multimodal graph filenames. modality_paths : tuple A tuple of filepath strings to the raw structural and raw functional connectome graph files (.npy). metadata : dict Dictionary coontaining coords and labels shared by each layer of the multilayer graph. """ import numpy as np import multinetx as mx import matplotlib matplotlib.use('agg') import pkg_resources import networkx as nx import yaml import sys from matplotlib import pyplot as plt from nilearn import plotting as niplot from pynets.core import thresholding from pynets.plotting.plot_gen import create_gb_palette coords = metadata['coords'] labels = metadata['labels'] ch2better_loc = pkg_resources.resource_filename( "pynets", "templates/ch2better.nii.gz") with open(pkg_resources.resource_filename("pynets", "runconfig.yaml"), 'r') as stream: hardcoded_params = yaml.load(stream) try: color_theme_func = hardcoded_params['plotting']['functional'][ 'glassbrain']['color_theme'][0] color_theme_struct = hardcoded_params['plotting']['structural'][ 'glassbrain']['color_theme'][0] glassbrain = hardcoded_params['plotting']['glassbrain'][0] adjacency = hardcoded_params['plotting']['adjacency'][0] dpi_resolution = hardcoded_params['plotting']['dpi'][0] except KeyError: print( 'ERROR: Plotting configuration not successfully extracted from runconfig.yaml' ) sys.exit(0) stream.close() [struct_mat_path, func_mat_path] = modality_paths struct_mat, func_mat = [np.load(struct_mat_path), np.load(func_mat_path)] if adjacency is True: # Multiplex adjacency mG = nx.read_gpickle(mG_path) fig = plt.figure(figsize=(15, 5)) ax1 = fig.add_subplot(121) adj = thresholding.standardize( mx.adjacency_matrix(mG, weight='weight').todense()) [z_min, z_max] = np.abs(adj).min(), np.abs(adj).max() adj[adj == 0] = np.nan ax1.imshow(adj, origin='lower', interpolation='nearest', cmap=plt.cm.RdBu, vmin=0.01, vmax=z_max) ax1.set_title('Supra-Adjacency Matrix') ax2 = fig.add_subplot(122) ax2.axis('off') ax2.set_title(f"Functional-Structural Multiplex Connectome") pos = mx.get_position(mG, mx.fruchterman_reingold_layout(mG.get_layer(0)), layer_vertical_shift=1.0, layer_horizontal_shift=0.0, proj_angle=7) edge_intensities = [] for a, b, w in mG.edges(data=True): if w != {}: edge_intensities.append(w['weight']) else: edge_intensities.append(0) node_centralities = list( nx.algorithms.eigenvector_centrality(mG, weight='weight').values()) mx.draw_networkx(mG, pos=pos, ax=ax2, node_size=100, with_labels=False, edge_color=edge_intensities, node_color=node_centralities, edge_vmin=z_min, edge_vmax=z_max, dim=3, font_size=6, widths=3, alpha=0.7, cmap=plt.cm.RdBu) plt.savefig(f"{namer_dir}/{name[:200]}supra_adj.png", dpi=dpi_resolution) if glassbrain is True: # Multiplex glass brain views = ['x', 'y', 'z'] connectome = niplot.plot_connectome(np.zeros(shape=(1, 1)), [(0, 0, 0)], node_size=0.0001, black_bg=True) connectome.add_overlay(ch2better_loc, alpha=0.50, cmap=plt.cm.gray) [struct_mat, _, _, _, edge_sizes_struct, _, _, coords, labels] = create_gb_palette(struct_mat, color_theme_struct, coords, labels, prune=False) connectome.add_graph(struct_mat, coords, edge_threshold='50%', edge_cmap=plt.cm.binary, node_size=1, edge_kwargs={ 'alpha': 0.50, "lineStyle": 'dashed' }, node_kwargs={'alpha': 0.95}, edge_vmax=float(1), edge_vmin=float(1)) for view in views: mod_lines = [] for line, edge_size in list( zip(connectome.axes[view].ax.lines, edge_sizes_struct)): line.set_lw(edge_size) mod_lines.append(line) connectome.axes[view].ax.lines = mod_lines [ func_mat, clust_pal_edges, clust_pal_nodes, node_sizes, edge_sizes_func, z_min, z_max, coords, labels ] = create_gb_palette(func_mat, color_theme_func, coords, labels, prune=False) connectome.add_graph(func_mat, coords, edge_threshold='50%', edge_cmap=clust_pal_edges, edge_kwargs={'alpha': 0.75}, edge_vmax=float(z_max), edge_vmin=float(z_min), node_size=node_sizes, node_color=clust_pal_nodes) for view in views: mod_lines = [] for line, edge_size in list( zip( connectome.axes[view].ax. lines[len(edge_sizes_struct):], edge_sizes_func)): line.set_lw(edge_size) mod_lines.append(line) connectome.axes[view].ax.lines[len(edge_sizes_struct):] = mod_lines connectome.savefig(f"{namer_dir}/{name[:200]}glassbrain_mplx.png", dpi=dpi_resolution) return