### Install from a local archive Source: https://github.com/graspologic-org/graspologic/blob/main/docs/reference/install.md Manually install graspologic by downloading the tar.gz file from PyPI and running pip install graspologic-VERSION.tar.gz in the download folder. ```bash pip install graspologic-VERSION.tar.gz ``` -------------------------------- ### Install graspologic to user directory Source: https://github.com/graspologic-org/graspologic/blob/main/docs/reference/install.md If you lack system-wide installation permissions, use the --user flag to install graspologic into your user directory. ```bash $ pip install --user graspologic ``` -------------------------------- ### Install graspologic from GitHub Source: https://github.com/graspologic-org/graspologic/blob/main/README.md Clone the repository and install graspologic locally. This method is useful for developers or users who need the latest unreleased code. ```bash git clone https://github.com/graspologic-org/graspologic cd graspologic python3 -m venv venv source venv/bin/activate pip install . ``` -------------------------------- ### Install graspologic with pip Source: https://github.com/graspologic-org/graspologic/blob/main/docs/reference/install.md Use this command to install the latest released version of graspologic. ```bash $ pip install graspologic ``` -------------------------------- ### Import Libraries and Setup Source: https://github.com/graspologic-org/graspologic/blob/main/docs/tutorials/embedding/AdjacencySpectralEmbed.ipynb Imports necessary libraries for graph analysis, simulations, plotting, and machine learning. Sets a random seed for reproducibility and suppresses warnings. ```python import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from sklearn.metrics import adjusted_rand_score from sklearn.cluster import KMeans from graspologic.embed import AdjacencySpectralEmbed from graspologic.simulations import sbm from graspologic.plot import heatmap, pairplot import warnings warnings.filterwarnings('ignore') np.random.seed(8889) %matplotlib inline ``` -------------------------------- ### Upgrade graspologic with pip Source: https://github.com/graspologic-org/graspologic/blob/main/docs/reference/install.md Use the --upgrade flag to install the newest release of graspologic. ```bash $ pip install --upgrade graspologic ``` -------------------------------- ### Check Conda Installation Source: https://github.com/graspologic-org/graspologic/wiki/FAQ Verify if Conda is installed and accessible in your system's PATH. ```bash conda -V ``` -------------------------------- ### Get System and Graspologic Versions Source: https://github.com/graspologic-org/graspologic/blob/main/CONTRIBUTING.md Run this code snippet to gather essential version information for your operating system, Python, and graspologic. This is crucial for bug reports. ```python import platform; print(platform.platform()) import sys; print(f"Python {sys.version}") import graspologic; print(f"graspologic {graspologic.__version__}") ``` -------------------------------- ### Install Graspologic via Pip Source: https://github.com/graspologic-org/graspologic/wiki/FAQ Install the Graspologic package into the active Conda environment using pip. Ensure your desired environment is activated first. ```bash pip install graspologic ``` -------------------------------- ### Load and Visualize Drosophila Connectome Data Source: https://github.com/graspologic-org/graspologic/blob/main/docs/tutorials/models/models.ipynb Loads the Drosophila melanogaster right mushroom body connectome, binarizes the adjacency matrix, and visualizes it using a heatmap with hierarchical labels. Ensure graspologic is installed. ```python import numpy as np from graspologic.datasets import load_drosophila_right from graspologic.plot import heatmap from graspologic.utils import binarize, symmetrize %matplotlib inline adj, labels = load_drosophila_right(return_labels=True) adj = binarize(adj) _ = heatmap(adj, inner_hier_labels=labels, title='Drosophila right MB', font_scale=1.5, sort_nodes=True) ``` -------------------------------- ### Generate Sample Data for Matrix Plotting Source: https://github.com/graspologic-org/graspologic/blob/main/docs/tutorials/plotting/matrixplot.ipynb Generates a sample adjacency matrix and metadata using the Stochastic Block Model (SBM) for use in matrix plotting examples. Sets random seed for reproducibility. ```python from numpy.random import normal N = 10 n_communities = [N, 3*N, 2*N, N] p = [[0.8, 0.1, 0.05, 0.01], [0.1, 0.4, 0.15, 0.02], [0.05, 0.15, 0.3, 0.01], [0.01, 0.02, 0.01, 0.4]] wt = [[normal]*4]*4 wtargs = [[dict(loc=5, scale=1)]*4]*4 np.random.seed(2) A = sbm(n_communities, p, wt=wt, wtargs=wtargs) meta = pd.DataFrame( data={ 'hemisphere': np.concatenate((np.full((1, 4*N), 0), np.full((1, 3*N), 1)), axis=1).flatten(), 'region': np.concatenate((np.full((1, N), 0), np.full((1, 3*N), 1), np.full((1, 2*N), 0), np.full((1, N), 1)), axis=1).flatten(), 'cell_size': np.arange(7*N), 'axon_length': np.concatenate((np.random.normal(5, 1, (1, N)), np.random.normal(2, 1, (1, 3*N)), np.random.normal(5, 1, (1, 2*N)), np.random.normal(2, 1, (1, N))), axis=1).flatten()}, ) rnd_idx = np.arange(7*N) np.random.shuffle(rnd_idx) A = A[np.ix_(rnd_idx, rnd_idx)] meta = meta.reindex(rnd_idx) ``` -------------------------------- ### Build Documentation with Tutorials Source: https://github.com/graspologic-org/graspologic/blob/main/CONTRIBUTING.md Build the project documentation, including executing and rendering tutorial Jupyter notebooks. This process may take longer due to notebook execution. ```bash uv run poe docsWithTutorials ``` -------------------------------- ### Show graspologic CLI Help Source: https://github.com/graspologic-org/graspologic/blob/main/docs/reference/cli.md Run this command to view the main help message for the graspologic CLI module, listing available subcommands. ```bash python -m graspologic.layouts --help ``` -------------------------------- ### Build Documentation Source: https://github.com/graspologic-org/graspologic/blob/main/CONTRIBUTING.md Generate the project documentation using Sphinx. This command builds the HTML documentation, which can be previewed locally. ```bash uv run poe docs ``` -------------------------------- ### Show graspologic CLI n2vumap Help Source: https://github.com/graspologic-org/graspologic/blob/main/docs/reference/cli.md Run this command to view the help message for the n2vumap subcommand, detailing its specific arguments and options. ```bash python -m graspologic.layouts n2vumap --help ``` -------------------------------- ### Matrix Plot with Scattermap and Array-like Groups Source: https://github.com/graspologic-org/graspologic/blob/main/docs/tutorials/plotting/matrixplot.ipynb This example demonstrates using `adjplot` with `plot_type='scattermap'` and providing custom `group` data as array-likes instead of metadata. ```python fig, ax = plt.subplots(1, 1, figsize=(10, 10)) adjplot( data=A, ax=ax, plot_type="scattermap", group=group, sizes=(1, 30), ) ``` -------------------------------- ### Import necessary libraries Source: https://github.com/graspologic-org/graspologic/blob/main/docs/tutorials/inference/group_connection_test.ipynb Imports NumPy, the group_connection_test function, sbm simulation, and heatmap plotting. Sets a random seed for reproducibility. ```python import numpy as np from graspologic.inference.group_connection_test import group_connection_test from graspologic.simulations import sbm from graspologic.plot import heatmap np.random.seed(8888) %matplotlib inline ``` -------------------------------- ### Incoherent Signal-Subgraph Estimation Source: https://github.com/graspologic-org/graspologic/blob/main/docs/tutorials/subgraph/subgraph.ipynb Estimates a signal-subgraph from a set of graphs using the SignalSubgraph estimator. This example generates synthetic graph data and compares the expected signal-subgraph with the estimated one. ```python from graspologic.plot import heatmap verts = 70 sedges = 20 pi = 0.5 p = 0.8 q = 0.1 nsamples = 100 np.random.seed(8888) classlabels = np.zeros(nsamples, dtype=int) classlabels[1::2] = 1 sigsubindex = np.random.choice(verts ** 2, sedges, replace=False) vect = p * np.ones(verts ** 2) vect[sigsubindex] = q vect = np.reshape(vect, (verts, verts)) expected = np.where(vect == q, 1, 0) blank = vect[:, :, None] + np.zeros(int(nsamples / 2)) A = p * np.ones((verts, verts, nsamples)) A[:, :, 1::2] = blank A = np.random.binomial(1, A) sigsub = sg.SignalSubgraph() sigsub.fit_transform(graphs=A, labels=classlabels, constraints=sedges) estimatesigsub = np.zeros((verts, verts)) estimatesigsub[sigsub.sigsub_] = 1 fig, ax = plt.subplots(ncols=2, figsize=(10, 5), constrained_layout=True) heatmap(expected, ax=ax[0], cbar=False, title="Expected Signal-Subgraph") _ = heatmap(estimatesigsub, ax=ax[1], cbar=False, title="Estimated Signal-Subgraph") ``` -------------------------------- ### Import Libraries and Set Up Plotting Source: https://github.com/graspologic-org/graspologic/blob/main/docs/tutorials/clustering/autogmm.ipynb Imports necessary libraries for numerical operations, plotting, and machine learning. Sets up the plotting environment for better visualization. ```python import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline import seaborn as sns sns.set(font_scale=1.75) sns.set_style("white") import random np.random.seed(10) ``` -------------------------------- ### Predict Latent Positions for Directed Graphs with ASE Source: https://github.com/graspologic-org/graspologic/blob/main/docs/tutorials/embedding/OutOfSampleEmbed.ipynb Fit the ASE model on the directed graph and then use the `transform` method with the out-of-sample data to get both out and in latent position predictions. ```python # Fit our directed graph X_hat_ase, Y_hat_ase = ase.fit_transform(A) # predicted latent positions w_ase = ase.transform(a) print(f"output of `ase.transform(a)` is {type(w_ase)}", "\n") print(f"out latent positions: \n{w_ase[0]}\n") print(f"in latent positions: \n{w_ase[1]}") ``` -------------------------------- ### Run SGM with 10 Seeds Source: https://github.com/graspologic-org/graspologic/blob/main/docs/tutorials/matching/sgm.ipynb This snippet initializes seeds, performs graph matching using SGM with a partial match, and visualizes the results. It then calculates and prints the match ratio. ```python seeds1 = np.sort(random.sample(list(range(n_verts)),10)) seeds1 = seeds1.astype(int) seeds2 = np.array(node_unshuffle_input[seeds1]) partial_match = np.column_stack((seeds1, seeds2)) _, perm_inds, _, _ = graph_match(A1, A2_shuffle, partial_match=partial_match, rng=rng) A2_unshuffle = A2_shuffle[perm_inds][:, perm_inds] fig, axs = plt.subplots(1, 3, figsize=(10, 5)) heatmap(A1, ax=axs[0], cbar=False, title="Graph 1") heatmap(A2_unshuffle, ax=axs[1], cbar=False, title="Graph 2 unshuffled") heatmap(A1 - A2_unshuffle, ax=axs[2], cbar=False, title="Diff (G1 - G2 unshuffled)") match_ratio = (perm_inds == node_unshuffle_input).mean() print("Match Ratio with 10 seeds: ", match_ratio) ``` -------------------------------- ### Clone Graspologic Repository Source: https://github.com/graspologic-org/graspologic/blob/main/CONTRIBUTING.md Clone your forked graspologic repository to your local machine. Ensure you are in the project directory after cloning. ```bash git clone git@github.com:YourGithubAccount/graspologic.git cd graspologic ``` -------------------------------- ### Run Unit Tests Source: https://github.com/graspologic-org/graspologic/blob/main/CONTRIBUTING.md Run all unit tests to verify the correctness of your code changes. This is crucial for ensuring that new features and bug fixes work as expected. ```bash uv run poe tests ``` -------------------------------- ### Visualize 2D layout with networkplot (Pandas DataFrame) Source: https://github.com/graspologic-org/graspologic/blob/main/docs/tutorials/plotting/networkplot.ipynb Visualizes the 2D network layout using networkplot with node data provided via a Pandas DataFrame. Edge colors are determined by target nodes in this example. ```python index = range(X.shape[0]) node_df = pd.DataFrame(index=index) node_df.loc[:, 'x'] = X[:,0] node_df.loc[:, 'y'] = X[:,1] node_df.loc[:, 'id'] = node_ids node_df.loc[:, 'degree'] = np.sum(A, axis=0) plot = networkplot(adjacency=A, node_data=node_df, x='x', y='y', node_hue='id', palette='deep', node_size='degree', node_sizes=(20, 200), edge_hue='target', edge_alpha=0.5, edge_linewidth=0.5) ``` -------------------------------- ### Import necessary libraries Source: https://github.com/graspologic-org/graspologic/blob/main/docs/tutorials/nominate/vertex_nomination_via_SGM.ipynb Imports the required classes and functions from graspologic and numpy for vertex nomination and graph simulations. ```python from graspologic.nominate import VNviaSGM from graspologic.simulations import er_np from graspologic.plot import heatmap import numpy as np import matplotlib.pyplot as plt np.set_printoptions(suppress=True) ``` -------------------------------- ### Import necessary libraries Source: https://github.com/graspologic-org/graspologic/blob/main/docs/tutorials/vertex_nomination/SpectralVertexNomination.ipynb Imports required libraries for spectral vertex nomination, SBM simulation, plotting, and numerical operations. ```python # imports import numpy as np from graspologic.nominate import SpectralVertexNomination from graspologic.simulations import sbm from graspologic.plot import heatmap from matplotlib import pyplot as plt %matplotlib inline ``` -------------------------------- ### List Conda Environments Source: https://github.com/graspologic-org/graspologic/wiki/FAQ Display a list of all available Conda environments on your system. ```bash conda info -e ``` -------------------------------- ### Graph Matching with Naive vs. Adopted Padding Source: https://github.com/graspologic-org/graspologic/blob/main/docs/tutorials/matching/padded_gm.ipynb Compares 'naive' and 'adopted' padding strategies for graph matching. Use this to visualize and quantify the differences in alignment quality between the two methods. ```python seed2 = rng.choice(np.arange(G2.shape[0]), 8) seed1 = [int(x / 75) * 25 + x for x in seed2] partial_match = np.column_stack((seed1, seed2)) naive_indices1, naive_indices2, _, _ = graph_match( G1, G2, partial_match=partial_match, padding="naive", rng=rng ) G2_naive = G2[naive_indices2][:, naive_indices2] G2_naive_full = np.zeros(G1.shape) G2_naive_full[np.ix_(naive_indices1, naive_indices1)] = G2_naive adopted_indices1, adopted_indices2, _, _ = graph_match( G1, G2, partial_match=partial_match, padding="adopted", rng=rng ) G2_adopted = G2[adopted_indices2][:, adopted_indices2] G2_adopted_full = np.zeros(G1.shape) G2_adopted_full[np.ix_(adopted_indices1, adopted_indices1)] = G2_adopted fig, axs = plt.subplots(1, 2, figsize=(14, 7)) heatmap(G2_naive_full, ax=axs[0], cbar=False, title="Naive Padding") heatmap(G2_adopted_full, ax=axs[1], cbar=False, title="Adopted Padding") def compute_match_ratio(indices1, indices2): match_ratio = 0 for i in range(len(indices2)): if (indices1[i] == keep_indices[i]) and (indices2[i] == i): match_ratio += 1 return match_ratio / len(indices2) print(f"Matching accuracy with naive padding: {compute_match_ratio(naive_indices1, naive_indices2):.2f}") print(f"Matching accuracy with adopted padding: {compute_match_ratio(adopted_indices1, adopted_indices2):.2f}") ``` -------------------------------- ### Visualizing Q matrices for alignment methods Source: https://github.com/graspologic-org/graspologic/blob/main/docs/tutorials/aligning/aligning.ipynb Generates heatmaps of the Q matrices for the original dataset and after alignment with SignFlips, OrthogonalProcrustes, and SeedlessProcrustes. Useful for analyzing the structural changes or similarities captured by each alignment method. ```python fig, (ax1, ax2, ax3, ax4) = plt.subplots(1, 4, figsize = (16, 4)) heatmap(Q, title=r'$Q$', vmin=-1, vmax=1, ax=ax1) heatmap(aligner_SF.Q_, title=r'$Q_{SF}$', vmin=-1, vmax=1, ax=ax2) heatmap(aligner_OP.Q_, title=r'$Q_{OP}$', vmin=-1, vmax=1, ax=ax3) heatmap(aligner_SP.Q_, title=r'$Q_{SP}$', vmin=-1, vmax=1, ax=ax4); ``` -------------------------------- ### Initialize and apply SignFlips aligner Source: https://github.com/graspologic-org/graspologic/blob/main/docs/tutorials/aligning/aligning.ipynb Initializes the SignFlips aligner, which assumes the orthogonal transformation is diagonal with +/-1 entries. It then transforms dataset X to align with Y. ```python from graspologic.align import SignFlips aligner_SF = SignFlips() X_prime_SF = aligner_SF.fit_transform(X, Y) ``` -------------------------------- ### Instantiate and fit SpectralVertexNomination Source: https://github.com/graspologic-org/graspologic/blob/main/docs/tutorials/vertex_nomination/SpectralVertexNomination.ipynb Initializes the SpectralVertexNomination class with a specified number of neighbors and fits it to the generated adjacency matrix. This prepares the SVN model for prediction. ```python # instantiate a default SVN svn = SpectralVertexNomination(n_neighbors=5) # fit to the adjacency matrix svn.fit(X=adj) ``` -------------------------------- ### Format Code with Black and isort Source: https://github.com/graspologic-org/graspologic/blob/main/CONTRIBUTING.md Run this command to format your code according to project standards using black and isort. This ensures code uniformity across the project. ```bash uv run poe format ``` -------------------------------- ### Compare Alignment Matrices (Heatmaps) Source: https://github.com/graspologic-org/graspologic/blob/main/docs/tutorials/aligning/aligning.ipynb Generates heatmaps to visualize and compare the alignment matrices (Q) from different methods. Useful for quantitative comparison of alignment quality. ```python fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize = (12, 4)) heatmap(Q, title=r'$Q$', vmin=-1, vmax=1, ax=ax1) heatmap(aligner_SF_unmatched.Q_, title=r'$Q_{SF}$', vmin=-1, vmax=1, ax=ax2) heatmap(aligner_SP_unmatched.Q_, title=r'$Q_{SP}$', vmin=-1, vmax=1, ax=ax3); ``` -------------------------------- ### Create and rotate datasets Source: https://github.com/graspologic-org/graspologic/blob/main/docs/tutorials/aligning/aligning.ipynb Generates two datasets, X and Y, where Y is a rotated version of X. This is used to demonstrate the alignment process. A random orthogonal matrix Q is used for rotation. ```python np.random.seed(314) X = np.random.uniform(0, 1, (15, 2)) Q = special_ortho_group.rvs(2) Y = X @ Q ``` -------------------------------- ### Simulate SBM and MMSBM for comparison Source: https://github.com/graspologic-org/graspologic/blob/main/docs/tutorials/simulations/mmsbm.ipynb Generates both a standard Stochastic Block Model (SBM) graph and an MMSBM graph with parameters designed to approximate SBM behavior for comparison. ```python from graspologic.simulations import sbm n = [50] * 4 p = [[0.8,0.2,0.2,0.2], [ 0.2,0.8,0.2,0.2], [ 0.2,0.2,0.8,0.2], [ 0.2,0.2,0.2,0.8]] G_sbm = sbm(n, p, directed=False, loops=False) n = 200 k = 4 alpha = [0.01]*k G_mmsbm = mmsbm(n, p, alpha= alpha, rng = rng) ``` -------------------------------- ### Initializing SignFlips for unmatched data Source: https://github.com/graspologic-org/graspologic/blob/main/docs/tutorials/aligning/aligning.ipynb Initializes the SignFlips aligner. This is a preparatory step before attempting to align datasets with potentially different numbers of entries, though SignFlips itself requires matched entries. ```python aligner_SF_unmatched = SignFlips() ``` -------------------------------- ### Import necessary libraries Source: https://github.com/graspologic-org/graspologic/blob/main/docs/tutorials/plotting/networkplot.ipynb Imports the graspologic library, numpy for numerical operations, and pandas for data manipulation. Also sets up matplotlib for inline plotting. ```python import graspologic import numpy as np import pandas as pd %matplotlib inline ``` -------------------------------- ### Visualizing Q matrices for shuffled alignment Source: https://github.com/graspologic-org/graspologic/blob/main/docs/tutorials/aligning/aligning.ipynb Generates heatmaps of the Q matrices for the shuffled dataset and its aligned versions. This helps in analyzing how shuffling affects the structural information captured by each alignment method. ```python fig, (ax1, ax2, ax3, ax4) = plt.subplots(1, 4, figsize = (16, 4)) heatmap(Q, title=r'$Q$', vmin=-1, vmax=1, ax=ax1) heatmap(aligner_SF_shuffled.Q_, title=r'$Q_{SF}$', vmin=-1, vmax=1, ax=ax2) heatmap(aligner_OP_shuffled.Q_, title=r'$Q_{OP}$', vmin=-1, vmax=1, ax=ax3) heatmap(aligner_SP_shuffled.Q_, title=r'$Q_{SP}$', vmin=-1, vmax=1, ax=ax4); ``` -------------------------------- ### Import necessary libraries Source: https://github.com/graspologic-org/graspologic/blob/main/docs/tutorials/aligning/aligning.ipynb Imports NumPy for numerical operations, Matplotlib for plotting, and specific Graspologic and SciPy functions for plotting and generating orthogonal matrices. ```python import numpy as np import matplotlib.pyplot as plt from graspologic.plot import heatmap from scipy.stats import special_ortho_group, ortho_group %matplotlib inline ``` -------------------------------- ### Import graspologic Subgraph Module Source: https://github.com/graspologic-org/graspologic/blob/main/docs/tutorials/subgraph/subgraph.ipynb Imports necessary libraries for subgraph analysis, plotting, and numerical operations. ```python import graspologic.subgraph as sg import matplotlib.pyplot as plt import numpy as np ``` -------------------------------- ### Prepare for multiple out-of-sample vertices Source: https://github.com/graspologic-org/graspologic/blob/main/docs/tutorials/embedding/OutOfSampleEmbed.ipynb Demonstrates how to prepare data for embedding multiple out-of-sample vertices. It selects multiple vertices to be removed from the graph and updates the in-sample adjacency matrix and the out-of-sample vertex data. ```python # Grab out-of-sample vertices labels = list(labels_) oos_idx = [0, -1] oos_labels = [labels.pop(i) for i in oos_idx] A, a = remove_vertices(undirected, indices=oos_idx, return_removed=True) ``` -------------------------------- ### Plotting a Basic Unweighted Graph Heatmap Source: https://github.com/graspologic-org/graspologic/blob/main/docs/tutorials/plotting/heatmaps.ipynb Generates and plots a heatmap for an unweighted Stochastic Block Model graph. Requires graspologic.simulations and graspologic.plot. ```python from graspologic.simulations import sbm from graspologic.plot import heatmap n_communities = [50, 50] p = [[0.8, 0.2], [0.2, 0.8]] A, labels = sbm(n_communities, p, return_labels=True) heatmap(A, title="Basic Heatmap function"); ``` -------------------------------- ### Visualize the SBM graph using a heatmap Source: https://github.com/graspologic-org/graspologic/blob/main/docs/tutorials/simulations/sbm.ipynb Displays the adjacency matrix of the simulated SBM graph as a heatmap for visualization. Requires the graspologic.plot.heatmap function. ```python from graspologic.plot import heatmap _ = heatmap(G, title ='SBM Simulation') ``` -------------------------------- ### Sample 3-Block SBM Graph Source: https://github.com/graspologic-org/graspologic/blob/main/docs/tutorials/embedding/CovariateAssistedEmbed.ipynb Generates a 3-block Stochastic Block Model (SBM) graph with 1500 nodes and 500 nodes per community. The block probability matrix is configured such that the first two communities are indistinguishable based on topology alone. ```python import warnings warnings.filterwarnings("ignore") import numpy as np np.random.seed(42) import graspologic from graspologic.simulations import sbm # Start with some simple parameters N = 1500 # Total number of nodes n = N // 3 # Nodes per community p, q = .3, .15 B = np.array([[p, p, q], [p, p, q], [q, q, p]]) # Sample from SBM A, labels = sbm([n, n, n], B, return_labels = True) ``` -------------------------------- ### Import graspologic modules Source: https://github.com/graspologic-org/graspologic/blob/main/docs/tutorials/matching/sgm.ipynb Imports specific functions for graph matching and plotting from the graspologic library. ```python from graspologic.match import graph_match from graspologic.plot import heatmap from graspologic.simulations import er_corr, sbm, sbm_corr ``` -------------------------------- ### Visualize SeedlessProcrustes Transformation Matrix Source: https://github.com/graspologic-org/graspologic/blob/main/docs/tutorials/aligning/aligning.ipynb Visualize the Q_ matrix obtained from SeedlessProcrustes. This matrix represents the orthogonal transformation component of the alignment. ```python heatmap(aligner_SP.Q_, figsize=(4,4), vmin=-1, vmax=1) aligner_SP.Q_ ``` -------------------------------- ### Import necessary libraries Source: https://github.com/graspologic-org/graspologic/blob/main/docs/tutorials/matching/sgm.ipynb Imports essential libraries for numerical operations, plotting, and graph simulations. Sets random seeds for reproducibility. ```python import numpy as np import matplotlib.pyplot as plt import seaborn as sns import random np.random.seed(8888) rng = np.random.default_rng(8888) ``` -------------------------------- ### Simulate a weighted SBM graph Source: https://github.com/graspologic-org/graspologic/blob/main/docs/tutorials/simulations/sbm.ipynb Generates a weighted undirected graph with no self-loops using the SBM. Allows specifying probability distribution functions and their arguments for sampling edge weights. ```python from numpy.random import normal, poisson n = [50, 50] p = [[0.5, 0.2], [0.2, 0.05]] wt = [[normal, poisson], [poisson, normal]] wtargs = [[dict(loc=3, scale=1), dict(lam=5)], [dict(lam=5), dict(loc=3, scale=1)]] G = sbm(n=n, p=p, wt=wt, wtargs=wtargs) ``` -------------------------------- ### MMSBM Simulation with Varying Alpha Source: https://github.com/graspologic-org/graspologic/blob/main/docs/tutorials/simulations/mmsbm.ipynb Simulate MMSBM graphs with different concentration parameter alpha values. Observe how increasing alpha progressively dissolves community structure. ```python alpha = [0.25]*k print("First increase alpha to: " + str(alpha)) G_mmsbm_25 = mmsbm(n, p, alpha= alpha, rng = rng) heatmap(G_mmsbm_25, cbar= False, title ='MMSBM Simulation(alpha = 0.25)'); ``` ```python alpha = [0.5]*k print("Then increase alpha to: " + str(alpha)) G_mmsbm_50 = mmsbm(n, p, alpha= alpha, rng = rng) heatmap(G_mmsbm_50, cbar= False, title ='MMSBM Simulation(alpha = 0.5)'); ``` ```python alpha = [1.0]*k print("Finally increase alpha to: " + str(alpha)) G_mmsbm_100 = mmsbm(n, p, alpha= alpha, rng = rng) heatmap(G_mmsbm_100, cbar= False, title ='MMSBM Simulation(alpha = 1.0)'); ``` -------------------------------- ### Create Conda Virtual Environment Source: https://github.com/graspologic-org/graspologic/wiki/FAQ Create a new Conda virtual environment with a specified Python version. Replace 'envname' with your desired environment name and 'x.x' with the Python version. ```bash conda create -n envname python=x.x anaconda ``` -------------------------------- ### Import necessary libraries Source: https://github.com/graspologic-org/graspologic/blob/main/docs/tutorials/plotting/matrixplot.ipynb Imports required libraries for graph simulation, data manipulation, plotting, and graspologic functions. ```python from graspologic.simulations import sbm import numpy as np import pandas as pd import matplotlib.pyplot as plt from graspologic.plot import adjplot, matrixplot import seaborn as sns ``` -------------------------------- ### Aligning shuffled dataset with different methods Source: https://github.com/graspologic-org/graspologic/blob/main/docs/tutorials/aligning/aligning.ipynb Applies SignFlips, OrthogonalProcrustes, and SeedlessProcrustes to a shuffled dataset. This demonstrates how alignment performance changes when vertex order is not preserved. ```python aligner_SF_shuffled = SignFlips() X_prime_SF_shuffled = aligner_SF_shuffled.fit_transform(X_shuffled, Y) aligner_OP_shuffled = OrthogonalProcrustes() X_prime_OP_shuffled = aligner_OP_shuffled.fit_transform(X_shuffled, Y) aligner_SP_shuffled = SeedlessProcrustes() X_prime_SP_shuffled = aligner_SP_shuffled.fit_transform(X_shuffled, Y) ``` -------------------------------- ### Perform vertex nomination Source: https://github.com/graspologic-org/graspologic/blob/main/docs/tutorials/nominate/vertex_nomination_via_SGM.ipynb Initializes the VNviaSGM algorithm and uses the fit_predict method to find potential matches for the vertex of interest (voi) in G1 to vertices in G2, using the specified seeds. The output is a list of potential matches with their associated probabilities. ```python VNalg = VNviaSGM() print(VNalg.fit_predict(G1, G2, voi, [kklst[0:num_seeds, 0], kklst[0:num_seeds, 1]])) ``` -------------------------------- ### Stochastic Block Model (SBM) Fitting and Sampling Source: https://github.com/graspologic-org/graspologic/blob/main/docs/tutorials/models/models.ipynb Fits the Stochastic Block Model using node community labels. It prints the block-block connection probability matrix 'B', visualizes the resulting probability matrix, and generates a sample graph. This model assumes nodes within the same block have similar connection probabilities. ```python from graspologic.models import SBMEstimator sbme = SBMEstimator(directed=True,loops=False) sbme.fit(adj, y=labels) print("SBM \"B\" matrix:") print(sbme.block_p_) heatmap(sbme.p_mat_, inner_hier_labels=labels, vmin=0, vmax=1, font_scale=1.5, title="SBM probability matrix", sort_nodes=True) _ = heatmap(sbme.sample()[0], inner_hier_labels=labels, font_scale=1.5, title="SBM sample", sort_nodes=True) ``` -------------------------------- ### Import necessary libraries Source: https://github.com/graspologic-org/graspologic/blob/main/docs/tutorials/embedding/Omnibus.ipynb Imports the graspologic library, matplotlib for plotting, and numpy for numerical operations. The %matplotlib inline magic command ensures plots are displayed within the notebook. ```python import graspologic import matplotlib.pyplot as plt import numpy as np %matplotlib inline ``` -------------------------------- ### Sample new RDPGs from latent positions Source: https://github.com/graspologic-org/graspologic/blob/main/docs/tutorials/inference/latent_position_test.ipynb Samples two new Random Dot Product Graphs (RDPGs) from the estimated latent positions. This is a prerequisite for testing if they originate from the same latent space. ```python A1 = rdpg(X, loops=False, rescale=False, directed=False) A2 = rdpg(X, loops=False, rescale=False, directed=False) Xhat1 = AdjacencySpectralEmbed(n_components=n_components).fit_transform(A1) Xhat2 = AdjacencySpectralEmbed(n_components=n_components).fit_transform(A2) heatmap(A1, title='Sampled RDPG 1 adjacency matrix') heatmap(A2, title='Sampled RDPG 2 adjacency matrix') pairplot(Xhat1, title='Sampled RDPG 1 adjacency spectral embedding') _ = pairplot(Xhat2, title='Sampled RDPG 2 adjacency spectral embedding') ``` -------------------------------- ### Perform degree-preserving edge swaps and visualize Source: https://github.com/graspologic-org/graspologic/blob/main/docs/tutorials/models/edge_swaps.ipynb Initializes EdgeSwapper with the adjacency matrix and performs 10,000 edge swaps. Visualizes the resulting swapped network. ```python swapper = EdgeSwapper(adj, seed=8888) swapped_adj, _ = swapper.swap_edges(n_swaps=10000) _ = heatmap(swapped_adj, title='Drosophila right MB swapped', font_scale=1.5, sort_nodes=True, inner_hier_labels=labels, cbar=False) ``` -------------------------------- ### Import necessary libraries Source: https://github.com/graspologic-org/graspologic/blob/main/docs/tutorials/inference/latent_distribution_test.ipynb Imports standard libraries for numerical operations, plotting, and graspologic functionalities. ```python import numpy as np import matplotlib.pyplot as plt np.random.seed(8888) from graspologic.inference import latent_distribution_test from graspologic.embed import AdjacencySpectralEmbed from graspologic.simulations import sbm, rdpg from graspologic.utils import symmetrize from graspologic.plot import heatmap, pairplot %matplotlib inline ``` -------------------------------- ### Import graph matching and simulation functions Source: https://github.com/graspologic-org/graspologic/blob/main/docs/tutorials/matching/faq.ipynb Imports the `graph_match` function for solving the graph matching problem and `er_np` for generating Erdős-Rényi random graphs. ```python from graspologic.match import graph_match from graspologic.simulations import er_np ``` -------------------------------- ### Import necessary libraries Source: https://github.com/graspologic-org/graspologic/blob/main/docs/tutorials/plotting/pairplot_with_gmm.ipynb Imports the graspologic library, numpy for numerical operations, and seaborn for plotting utilities. The %matplotlib inline magic command ensures plots are displayed within the notebook. ```python import graspologic import numpy as np import seaborn as sns %matplotlib inline ``` -------------------------------- ### Solve Graph Matching Problem and verify Source: https://github.com/graspologic-org/graspologic/blob/main/docs/tutorials/matching/faq.ipynb Applies the `graph_match` function to find the optimal node permutation between G1 and G2. The resulting G2 is permuted to match G1, and the number of edge disagreements is recalculated to show the effectiveness of the algorithm. ```python _, perm_inds, score, misc = graph_match(G1, G2) G2 = G2[perm_inds][:, perm_inds] # permute both rows and columns to preserve adjacency print("Number of edge disagreements: ", np.sum(abs(G1-G2))) ``` -------------------------------- ### Import Libraries for Density Test Source: https://github.com/graspologic-org/graspologic/blob/main/docs/tutorials/inference/density_test.ipynb Imports necessary libraries for network simulation, inference, and plotting. Ensures reproducibility with a fixed random seed. ```python import numpy as np import matplotlib.pyplot as plt from graspologic.inference.density_test import density_test from graspologic.simulations import er_np from graspologic.plot import heatmap np.random.seed(8888) %matplotlib inline ``` -------------------------------- ### Simulate a binary graph using SBM Source: https://github.com/graspologic-org/graspologic/blob/main/docs/tutorials/plotting/matrixplot.ipynb Generates a binary graph using the Stochastic Block Model (SBM) with specified community sizes and connection probabilities. Also creates a Pandas DataFrame for metadata associated with the graph nodes. ```python N = 50 n_communities = [N, N, N, N] p = [[0.8, 0.1, 0.05, 0.01], [0.1, 0.4, 0.15, 0.02], [0.05, 0.15, 0.3, 0.01], [0.01, 0.02, 0.01, 0.4]] np.random.seed(2) A = sbm(n_communities, p) meta = pd.DataFrame( data={ 'hemisphere': np.concatenate((np.full((1, 2*N), 0), np.full((1, 2*N), 1)), axis=1).flatten(), 'region': np.concatenate((np.full((1, N), 0), np.full((1, N), 1), np.full((1, N), 0), np.full((1, N), 1)), axis=1).flatten(), 'cell_size': np.arange(4*N)}, ) ``` -------------------------------- ### Import necessary libraries Source: https://github.com/graspologic-org/graspologic/blob/main/docs/tutorials/models/edge_swaps.ipynb Imports required libraries for data loading, network manipulation, plotting, and sparse matrix operations. ```python from graspologic.datasets import load_drosophila_right from graspologic.models import EdgeSwapper from graspologic.plot import heatmap from graspologic.utils import binarize, symmetrize import networkx as nx from scipy.sparse import csr_array ``` -------------------------------- ### Visualize OrthogonalProcrustes Transformation Matrix Source: https://github.com/graspologic-org/graspologic/blob/main/docs/tutorials/aligning/aligning.ipynb Visualize the Q_ matrix obtained from OrthogonalProcrustes, which represents the orthogonal transformation. This is useful for understanding the rotation and reflection applied. ```python heatmap(aligner_OP.Q_, figsize= (4, 4), vmin=-1, vmax=1) aligner_OP.Q_ ``` -------------------------------- ### Import KSample for Statistical Testing Source: https://github.com/graspologic-org/graspologic/blob/main/docs/tutorials/connectomics/mcc.ipynb Imports the KSample class from the hyppo.ksample module, which is used for performing statistical tests on multiple samples, such as comparing distributions of edges across connectomes. ```python from hyppo.ksample import KSample ``` -------------------------------- ### Visualize the rotation matrix Q Source: https://github.com/graspologic-org/graspologic/blob/main/docs/tutorials/aligning/aligning.ipynb Displays the rotation matrix Q used to transform X into Y using a heatmap. This helps visualize the orthogonal transformation applied. ```python heatmap(Q, figsize=(4,4), vmin=-1, vmax=1) Q ``` -------------------------------- ### Visualize 2D layout with networkplot (NumPy arrays) Source: https://github.com/graspologic-org/graspologic/blob/main/docs/tutorials/plotting/networkplot.ipynb Visualizes the 2D network layout using networkplot. Node colors are based on community labels, node sizes on node degrees, and edge colors on source nodes. Requires pre-calculated node positions and degrees. ```python from graspologic.plot.plot import networkplot x_pos = X[:,0] y_pos = X[:,1] degrees = np.sum(A, axis=0) plot = networkplot(adjacency=A, x=x_pos, y=y_pos, node_hue=node_ids, palette='deep', node_size=degrees, node_sizes=(20, 200), edge_hue='source', edge_alpha=0.5, edge_linewidth=0.5) ``` -------------------------------- ### Simulate an unweighted SBM graph Source: https://github.com/graspologic-org/graspologic/blob/main/docs/tutorials/simulations/sbm.ipynb Generates an unweighted undirected graph with no self-loops using the SBM. Requires specifying the number of vertices per community and the block probability matrix. ```python from graspologic.simulations import sbm n = [50, 50] p = [[0.5, 0.2], [0.2, 0.05]] np.random.seed(1) G = sbm(n=n, p=p) ``` -------------------------------- ### Simulate weighted stochastic block models Source: https://github.com/graspologic-org/graspologic/blob/main/docs/tutorials/plotting/gridplot.ipynb Generates two weighted stochastic block models (SBMs) with different weight distributions. The first SBM uses weights from a discrete uniform distribution between 1 and 10, while the second uses weights from a discrete uniform distribution between 2 and 5. This is useful for creating synthetic graph data for visualization and analysis. ```python from graspologic.simulations import sbm n_communities = [50, 50] p = np.array([[0.25, 0.05], [0.05, 0.25]]) wt = np.random.randint wtargs = dict(low=1, high=10) np.random.seed(1) A_unif1= sbm(n_communities, p, wt=wt, wtargs=wtargs) wtargs = dict(low=2, high=5) A_unif2= sbm(n_communities, p, wt=wt, wtargs=wtargs) ``` -------------------------------- ### Import necessary libraries Source: https://github.com/graspologic-org/graspologic/blob/main/docs/tutorials/inference/latent_position_test.ipynb Imports required libraries for graph generation, embedding, and testing. ```python import numpy as np np.random.seed(88889999) from graspologic.inference import latent_position_test from graspologic.embed import AdjacencySpectralEmbed from graspologic.simulations import sbm, rdpg from graspologic.utils import symmetrize from graspologic.plot import heatmap, pairplot %matplotlib inline ``` -------------------------------- ### Activate Conda Virtual Environment Source: https://github.com/graspologic-org/graspologic/wiki/FAQ Activate a specific Conda virtual environment. Replace 'envname' with the name of your environment. ```bash conda activate envname ``` -------------------------------- ### Simulate two graphs using SBM Source: https://github.com/graspologic-org/graspologic/blob/main/docs/tutorials/embedding/MASE.ipynb Generate two graphs using the Stochastic Block Model (SBM) with different block connectivity matrices. This is useful for demonstrating MASE's ability to capture differences between graphs. ```python from graspologic.simulations import sbm n = [25, 25] B1 = [[0.3, 0.1], [0.1, 0.7]] B2 = [[0.3, 0.1], [0.1, 0.3]] np.random.seed(8) G1 = sbm(n, B1) G2 = sbm(n, B2) ``` -------------------------------- ### Create a Feature Branch Source: https://github.com/graspologic-org/graspologic/blob/main/CONTRIBUTING.md Create a new branch for your development work. Always base feature branches off the 'dev' branch. ```bash git checkout -b my-feature ``` -------------------------------- ### Visualize MMSBM graphs with different alpha values Source: https://github.com/graspologic-org/graspologic/blob/main/docs/tutorials/simulations/mmsbm.ipynb Displays two MMSBM-generated graphs using heatmaps, highlighting the effect of different alpha parameter values on community structure. ```python heatmap(G_1, cbar= False, title ='MMSBM Simulation(alpha = [100, 1])'); heatmap(G_2, cbar= False, title ='MMSBM Simulation(alpha = [1, 100])'); ``` -------------------------------- ### Plot SBM and MMSBM Graphs Source: https://github.com/graspologic-org/graspologic/blob/main/docs/tutorials/simulations/mmsbm.ipynb Visualize the generated SBM and MMSBM graphs using heatmaps. Useful for comparing the structure of graphs generated by different models. ```python heatmap(G_sbm, cbar= False, title ='SBM Simulation'); heatmap(G_mmsbm, cbar= False, title ='MMSBM Simulation(alpha = 0.01)'); ``` -------------------------------- ### Import necessary libraries Source: https://github.com/graspologic-org/graspologic/blob/main/docs/tutorials/embedding/MASE.ipynb Import libraries for plotting and numerical operations. ```python import matplotlib.pyplot as plt import numpy as np %matplotlib inline ``` -------------------------------- ### Import necessary libraries Source: https://github.com/graspologic-org/graspologic/blob/main/docs/tutorials/embedding/OutOfSampleEmbed.ipynb Imports all required libraries for graph embedding, simulations, and plotting. Sets a random seed for reproducibility and suppresses warnings. ```python import numpy as np import matplotlib.pyplot as plt import pandas as pd import seaborn as sns from numpy.random import normal, poisson from graspologic.simulations import sbm from graspologic.embed import AdjacencySpectralEmbed as ASE from graspologic.embed import LaplacianSpectralEmbed as LSE from graspologic.plot import heatmap, pairplot from graspologic.utils import remove_vertices np.random.seed(1234) import warnings warnings.filterwarnings('ignore') ```