### Installing spatiomic via PyPi (CPU) Source: https://github.com/complextissue/spatiomic/blob/main/docs/source/installation.md Installs the core `spatiomic` package using pip from PyPi, providing the standard CPU-based functionality. This is the simplest and most common installation method. ```bash python3 -m pip install spatiomic ``` -------------------------------- ### Installing spatiomic from GitHub Source: https://github.com/complextissue/spatiomic/blob/main/docs/source/installation.md Installs the `spatiomic` package directly from its GitHub repository using pip. This method is useful for accessing the latest development version or for contributing to the project. ```bash python3 -m pip install git+git@github.com:complextissue/spatiomic.git ``` -------------------------------- ### Installing GPU dependencies for CUDA 11 (PyPi) Source: https://github.com/complextissue/spatiomic/blob/main/docs/source/installation.md Installs optional GPU-accelerated dependencies for `spatiomic` compatible with CUDA 11. This setup includes `cupy` and specific versions of RAPIDS packages such as `cuml`, `cugraph`, and `cucim`, enabling significant speedups for computationally intensive operations on compatible GPUs. ```bash python3 -m pip install cupy-cuda11x python3 -m pip install \ --extra-index-url=https://pypi.nvidia.com \ "cuml-cu11==25.2.*" "cugraph-cu11==25.2.*" "nx-cugraph-cu11==25.2.*" \ "cucim-cu11==25.2.*" ``` -------------------------------- ### Installing spatiomic from Source Source: https://github.com/complextissue/spatiomic/blob/main/docs/source/installation.md Clones the `spatiomic` repository and installs the package from source. This method is typically used for local development, making modifications, or building the package in a custom environment. ```bash git clone --depth 1 https://github.com/complextissue/spatiomic.git cd spatiomic make install ``` -------------------------------- ### Loading Image Data with Spatiomic in Python Source: https://github.com/complextissue/spatiomic/blob/main/docs/source/tutorials/registration.ipynb Reads an example TIFF image file using `so.data.read().read_tiff()` and selects the first channel. It then displays the loaded image using `matplotlib.pyplot.imshow()` with a grayscale colormap. This snippet prepares the initial image for registration. ```python # read the example data img_data = so.data.read().read_tiff("./data/example.tif")[:, :, 0] plt.imshow(img_data, cmap="gray") ``` -------------------------------- ### Installing spatiomic via pip in Bash Source: https://github.com/complextissue/spatiomic/blob/main/README.md This command installs the `spatiomic` computational library from PyPi using pip. It is the standard method for installing the package and its core dependencies. For optional GPU acceleration, additional packages like `cupy`, `cuml`, `cuGraph`, and `cuCIM` may need to be installed separately following RAPIDS.AI guidelines. ```bash pip install spatiomic ``` -------------------------------- ### Building spatiomic Documentation Locally in Bash Source: https://github.com/complextissue/spatiomic/blob/main/README.md This command builds the `spatiomic` project's documentation locally. It must be executed from within the `docs` folder after installing the package's development requirements and `pandoc`. The command generates HTML documentation files for offline viewing. ```bash make html ``` -------------------------------- ### Installing GPU dependencies for CUDA 12 (PyPi) Source: https://github.com/complextissue/spatiomic/blob/main/docs/source/installation.md Installs optional GPU-accelerated dependencies for `spatiomic` compatible with CUDA 12. This includes `cupy` for general GPU computation and specific versions of RAPIDS packages like `cuml`, `cugraph`, and `cucim` for optimized machine learning and image processing tasks. ```bash python3 -m pip install cupy-cuda12x python3 -m pip install \ --extra-index-url=https://pypi.nvidia.com \ "cuml-cu12==25.2.*" "cugraph-cu12==25.2.*" "nx-cugraph-cu12==25.2.*" \ "cucim-cu12==25.2.*" ``` -------------------------------- ### Loading and Downscaling TIFF Image Data - Python Source: https://github.com/complextissue/spatiomic/blob/main/docs/source/tutorials/clustering.ipynb This code reads an example TIFF image file using `spatiomic`'s data reader and then preprocesses it. The preprocessing step involves downscaling the image locally by a factor of 4 in the first two dimensions and converting it to a binary-like float array scaled to 0-255, preparing it for further analysis. ```Python img_data = so.data.read().read_tiff("./data/example.tif") img_data = (downscale_local_mean(img_data, (4, 4, 1)) + 1 > 0).astype(float) * 255 ``` -------------------------------- ### Defining Project Dependencies - Python Requirements Source: https://github.com/complextissue/spatiomic/blob/main/requirements.frozen.txt This snippet lists all Python package dependencies and their exact versions required for the 'spatiomic' project. It is typically saved in a `requirements.txt` file and used with `pip install -r` to ensure a consistent and reproducible development or deployment environment. ```Python Requirements access==1.1.9 adjustText==1.3.0 affine==2.4.0 anndata==0.11.4 array_api_compat==1.11.2 attrs==25.3.0 beautifulsoup4==4.13.4 certifi==2025.1.31 charset-normalizer==3.4.1 click==8.1.8 click-plugins==1.1.1 cligj==0.7.2 colorcet==3.1.0 contourpy==1.3.2 cycler==0.12.1 deprecation==2.1.0 esda==2.7.0 fiona==1.10.1 fonttools==4.57.0 geopandas==1.0.1 giddy==2.3.6 h5py==3.13.0 idna==3.10 igraph==0.11.8 imageio==2.37.0 inequality==1.1.1 joblib==1.4.2 kiwisolver==1.4.8 lazy_loader==0.4 libpysal==4.13.0 llvmlite==0.44.0 mapclassify==2.8.1 matplotlib==3.10.1 mgwr==2.2.1 momepy==0.9.1 mpmath==1.3.0 natsort==8.4.0 networkx==3.4.2 numba==0.61.2 numpy==2.2.4 packaging==24.2 pandas==2.2.3 patsy==1.0.1 pillow==11.2.1 platformdirs==4.3.7 pointpats==2.5.1 PuLP==3.1.1 pynndescent==0.5.13 pyogrio==0.10.0 pyparsing==3.2.3 pyproj==3.7.1 pysal==25.1 python-dateutil==2.9.0.post0 python-igraph==0.11.8 pytz==2025.2 quantecon==0.8.0 rasterio==1.4.3 rasterstats==0.20.0 requests==2.32.3 rtree==1.4.0 scikit-image==0.25.2 scikit-learn==1.6.1 scipy==1.15.2 seaborn==0.13.2 segregation==2.5.2 shapely==2.1.0 simplejson==3.20.1 six==1.17.0 soupsieve==2.6 spaghetti==1.7.6 spatiomic @ file:///Users/au734063/Documents/code/spatiomic spglm==1.1.0 spint==1.0.7 splot==1.1.7 spopt==0.6.1 spreg==1.8.2 statsmodels==0.14.4 sympy==1.13.3 texttable==1.7.0 threadpoolctl==3.6.0 tifffile==2025.3.30 tobler==0.12.1 tqdm==4.67.1 typing_extensions==4.13.2 tzdata==2025.2 umap-learn==0.5.7 urllib3==2.4.0 XPySom==1.0.7 ``` -------------------------------- ### Creating Pandas DataFrame for Multiple Image SSIM Comparison in Python Source: https://github.com/complextissue/spatiomic/blob/main/docs/source/tutorials/registration.ipynb Extends the previous DataFrame creation to include SSIM values for multiple images. This `df_register` DataFrame now contains "Before Registration" and "After Registration" SSIM scores for five different images, indexed by their names, allowing for a broader comparison of registration performance across a dataset. ```python df_register = pd.DataFrame( { "Before Registration": [ssim_before, 0.6, 0.7, 0.8, 0.9], "After Registration": [ssim_after, 0.95, 0.96, 0.97, 0.98], }, index=["Image 1", "Image 2", "Image 3", "Image 4", "Image 5"], ) ``` -------------------------------- ### Importing Libraries for Image Registration in Python Source: https://github.com/complextissue/spatiomic/blob/main/docs/source/tutorials/registration.ipynb Imports necessary libraries: `matplotlib.pyplot` for plotting, `pandas` for data manipulation, and `spatiomic` (aliased as `so`) for image processing and registration functionalities. These are prerequisites for the subsequent operations. ```python import matplotlib.pyplot as plt import pandas as pd import spatiomic as so ``` -------------------------------- ### Importing Core Libraries for Spatiomic Analysis - Python Source: https://github.com/complextissue/spatiomic/blob/main/docs/source/tutorials/clustering.ipynb This snippet imports essential Python libraries required for spatial omics data processing and analysis. It includes `numpy` for numerical operations, `seaborn` for data visualization, `skimage.transform` for image manipulation, and `spatiomic` as the primary library for the tutorial's functionalities. ```Python import numpy as np import seaborn as sns from skimage.transform import downscale_local_mean import spatiomic as so ``` -------------------------------- ### Initializing Self-Organizing Map (SOM) - Python Source: https://github.com/complextissue/spatiomic/blob/main/docs/source/tutorials/clustering.ipynb This code initializes a Self-Organizing Map (SOM) using `spatiomic`. It configures the SOM with a 30x30 grid of nodes, sets the dimension count based on the input image's channels, specifies 'euclidean' as the distance metric, disables GPU usage, and sets a random seed for reproducibility. ```Python som = so.dimension.som( node_count=(30, 30), dimension_count=img_data.shape[-1], distance_metric="euclidean", use_gpu=False, seed=42, ) ``` -------------------------------- ### Creating kNN Graph and Leiden Clustering on SOM Nodes - Python Source: https://github.com/complextissue/spatiomic/blob/main/docs/source/tutorials/clustering.ipynb This snippet first constructs a k-Nearest Neighbors (kNN) graph from the trained SOM nodes, using 100 neighbors and a Euclidean distance metric. Subsequently, it applies the Leiden graph clustering algorithm to this kNN graph to identify distinct clusters among the SOM nodes, with a specified resolution and iteration count. ```Python knn_graph = so.neighbor.knn_graph().create(som, neighbor_count=100, distance_metric="euclidean", use_gpu=False) clusters, modularity = so.cluster.leiden().predict( knn_graph, resolution=0.5, seed=42, use_gpu=False, iteration_count=10 ) ``` -------------------------------- ### Visualizing Clustered Image Data - Python Source: https://github.com/complextissue/spatiomic/blob/main/docs/source/tutorials/clustering.ipynb This snippet generates a visual representation of the clustered image data. It first creates a colormap based on the number of identified clusters using the 'glasbey' flavor, then uses `spatiomic.plot.cluster_image` to display the `labelled_data` with distinct colors for each cluster. ```Python colormap = so.plot.colormap(color_count=np.array(clusters).max() + 1, flavor="glasbey") fig = so.plot.cluster_image( labelled_data, colormap=colormap, ) ``` -------------------------------- ### Subsampling Image Data for SOM Training - Python Source: https://github.com/complextissue/spatiomic/blob/main/docs/source/tutorials/clustering.ipynb This snippet creates a subsample of the `img_data` for more efficient SOM training. It uses `spatiomic.data.subsample` to select 50% of the original data points randomly, which can significantly reduce training time for large datasets while maintaining data representativeness. ```Python img_data_subsample = so.data.subsample().fit_transform(img_data, method="fraction", fraction=0.5, seed=42) ``` -------------------------------- ### Plotting Registration Similarity for Multiple Images in Python Source: https://github.com/complextissue/spatiomic/blob/main/docs/source/tutorials/registration.ipynb Generates a plot to visualize the similarity metrics (e.g., SSIM) for multiple images before and after registration using `so.plot.registration_similarity()`. It utilizes the `df_register` DataFrame, which contains the SSIM values for several images, and custom labels for clarity, providing a comprehensive visual overview of registration performance. ```python fig = so.plot.registration_similarity( df_similarity=df_register, before_label="Before Registration", after_label="After Registration", ) ``` -------------------------------- ### Visualizing Individual Image Channels - Python Source: https://github.com/complextissue/spatiomic/blob/main/docs/source/tutorials/clustering.ipynb This snippet uses `matplotlib` to display each channel of the preprocessed image data. It creates a subplot for each of the three channels, showing them in grayscale and setting appropriate titles, allowing for a quick visual inspection of the input data. ```Python import matplotlib.pyplot as plt fig, ax = plt.subplots(1, 3) for i in range(3): ax[i].imshow(img_data[:, :, i], cmap="gray") ax[i].set_title("Channel {}".format(i)) ax[i].axis("off") plt.tight_layout() ``` -------------------------------- ### Training Self-Organizing Map (SOM) - Python Source: https://github.com/complextissue/spatiomic/blob/main/docs/source/tutorials/clustering.ipynb This code trains the previously initialized Self-Organizing Map (SOM) on the subsampled image data. The `fit` method runs the training process for 100 iterations, allowing the SOM nodes to learn the topography and features of the input dataset. ```Python som.fit(img_data_subsample, iteration_count=100) ``` -------------------------------- ### Plotting Registration Slope with Spatiomic in Python Source: https://github.com/complextissue/spatiomic/blob/main/docs/source/tutorials/registration.ipynb Generates a slope plot visualizing the change in similarity (e.g., SSIM) before and after registration using the `so.plot.registration_slope()` function. It takes the `df_register` DataFrame as input, which contains the quantitative evaluation metrics, to create a visual representation of the registration effectiveness. ```python fig = so.plot.registration_slope(df_register) ``` -------------------------------- ### Creating Pandas DataFrame for Single Image SSIM Comparison in Python Source: https://github.com/complextissue/spatiomic/blob/main/docs/source/tutorials/registration.ipynb Constructs a Pandas DataFrame named `df_register` to store the SSIM values before and after registration for a single image. This DataFrame is structured with columns "Before Registration" and "After Registration", making the SSIM comparison easily accessible for further analysis or plotting. ```python df_register = pd.DataFrame( { "Before Registration": [ssim_before], "After Registration": [ssim_after], } ) ``` -------------------------------- ### Applying a Known Shift to Image Data in Python Source: https://github.com/complextissue/spatiomic/blob/main/docs/source/tutorials/registration.ipynb Applies a predefined shift of (20, 10) pixels to the `img_data` using `so.process.register.apply_shift()`. The resulting shifted image, `img_data_shifted`, is then displayed using `matplotlib.pyplot.imshow()` to visualize the applied transformation. ```python img_data_shifted = so.process.register.apply_shift(img_data, (20, 10)) plt.imshow(img_data_shifted, cmap="gray") ``` -------------------------------- ### Visualizing Bivariate Moran's I with Heatmap - Python Source: https://github.com/complextissue/spatiomic/blob/main/docs/source/tutorials/clustering.ipynb This snippet generates a heatmap using `seaborn` to visualize the bivariate Moran's I results. The heatmap shows the correlation between each cluster and each image channel, with values ranging from -1 to 1, providing a clear overview of spatial relationships. ```Python fig, ax = plt.subplots(dpi=100, figsize=(2.5, 2.5)) sns.heatmap( df_bv_morans_i.pivot(index="cluster", columns="channel", values="morans_i"), cmap="coolwarm", vmin=-1, vmax=1, annot=True, fmt=".2f", square=True, ax=ax, ) ``` -------------------------------- ### Evaluating Image Registration with SSIM in Python Source: https://github.com/complextissue/spatiomic/blob/main/docs/source/tutorials/registration.ipynb Calculates the Structural Similarity Index Measure (SSIM) between the `img_shifted` and `img_data` (before correction) and between `img_corrected` and `img_data` (after correction) using `so.process.register.get_ssim()`. The SSIM values are then printed to quantitatively assess the improvement in similarity after registration. ```python ssim_before = so.process.register.get_ssim(img_shifted, img_data) ssim_after = so.process.register.get_ssim(img_corrected, img_data) print(f"SSIM before: {ssim_before:.2f}, SSIM after: {ssim_after:.2f}") ``` -------------------------------- ### Visualizing Image Registration Results in Python Source: https://github.com/complextissue/spatiomic/blob/main/docs/source/tutorials/registration.ipynb Crops the original, shifted, and corrected images to their overlapping region based on the detected shift. It then creates a three-subplot figure using `matplotlib.pyplot.subplots()` to display the "Original", "Shifted" (a blend of shifted and original), and "Corrected" images side-by-side for visual comparison of the registration effect. ```python # crop to the overlapping region img_corrected = img_corrected[: int(shift[0]), : int(shift[1])] img_data = img_data[: int(shift[0]), : int(shift[1])] img_shifted = img_data_shifted[: int(shift[0]), : int(shift[1])] * 0.5 + img_data * 0.5 fig, (ax0, ax1, ax2) = plt.subplots(1, 3) ax0.imshow(img_data, cmap="gray") ax0.set_title("Original") ax0.axis("off") ax1.imshow(img_shifted, cmap="gray") ax1.set_title("Shifted") ax1.axis("off") ax2.imshow(img_corrected, cmap="gray") ax2.set_title("Corrected") ax2.axis("off") ``` -------------------------------- ### Calculating Bivariate Moran's I for Cluster-Channel Correlation - Python Source: https://github.com/complextissue/spatiomic/blob/main/docs/source/tutorials/clustering.ipynb This code calculates the bivariate version of Moran's I to evaluate the spatial correlation between the identified clusters and the original image channels. It helps understand how specific clusters relate to the intensity patterns in different channels of the input data. ```Python df_bv_morans_i = so.spatial.bivariate_correlation().predict( data=labelled_data, channel_image=img_data, method="moran", ) ``` -------------------------------- ### Defining Python Module Directive in Jinja2 Source: https://github.com/complextissue/spatiomic/blob/main/docs/source/_templates/modules.rst This snippet inserts the `.. py:module::` directive into the reStructuredText output, declaring the current document as documentation for the Python module specified by `obj.name`. This is crucial for Sphinx's cross-referencing and indexing. ```Jinja2 .. py:module:: {{ obj.name }} ``` -------------------------------- ### Plotting Individual Cluster Spatial Locations - Python Source: https://github.com/complextissue/spatiomic/blob/main/docs/source/tutorials/clustering.ipynb This code visualizes the spatial distribution of individual clusters within the image. It generates a plot where each cluster's locations are highlighted, providing insights into their spatial arrangement. The figure size and layout are adjusted for better presentation. ```Python fig = so.plot.cluster_location(labelled_data) fig.set_size_inches(5, 5) fig.tight_layout(pad=2) ``` -------------------------------- ### Correcting Image Shift with Detected Values in Python Source: https://github.com/complextissue/spatiomic/blob/main/docs/source/tutorials/registration.ipynb Applies the previously detected `shift` to the `img_data_shifted` using `so.process.register.apply_shift()` to correct its position. The resulting `img_corrected` image is then displayed using `matplotlib.pyplot.imshow()` to visually confirm the registration. ```python img_corrected = so.process.register.apply_shift(img_data_shifted, shift) plt.imshow(img_corrected, cmap="gray") ``` -------------------------------- ### Assigning Cluster Labels to Original Image Pixels - Python Source: https://github.com/complextissue/spatiomic/blob/main/docs/source/tutorials/clustering.ipynb This code uses the trained SOM to assign cluster labels to each pixel in the original `img_data`. It maps each pixel to the cluster of its closest SOM node and optionally saves the resulting labelled data to a NumPy file for later use. ```Python labelled_data = som.label(img_data, clusters, save_path="./data/example_labelled.npy") ``` -------------------------------- ### Generating reStructuredText Module Title with Jinja2 Source: https://github.com/complextissue/spatiomic/blob/main/docs/source/_templates/modules.rst This Jinja2 snippet dynamically generates a reStructuredText title for a Python module. It uses the `obj.name` variable for the module name and repeats the equals sign character to create an underline of the appropriate length, adhering to reStructuredText heading conventions. ```Jinja2 :py:mod:`{{ obj.name }}`\n=========={{ "=" * obj.name|length }} ``` -------------------------------- ### Displaying Moran's I Autocorrelation Results - Python Source: https://github.com/complextissue/spatiomic/blob/main/docs/source/tutorials/clustering.ipynb This snippet simply displays the `df_morans_i` DataFrame, which contains the results of the Moran's I spatial autocorrelation calculation. This allows for direct inspection of the computed Moran's I values for each cluster. ```Python df_morans_i ``` -------------------------------- ### Conditionally Including Docstring in Jinja2 Source: https://github.com/complextissue/spatiomic/blob/main/docs/source/_templates/modules.rst This Jinja2 block checks for the presence of `obj.docstring`. If a docstring exists, it includes it in the reStructuredText output using the `.. autoapi-nested-parse::` directive, ensuring it's properly indented by 3 spaces for correct rendering. ```Jinja2 {% if obj.docstring %}\n.. autoapi-nested-parse::\n\n {{ obj.docstring|indent(3) }}\n\n{% endif %} ``` -------------------------------- ### Counting Cluster Abundances in Labelled Data - Python Source: https://github.com/complextissue/spatiomic/blob/main/docs/source/tutorials/clustering.ipynb This code calculates the abundance (pixel count) of each identified cluster within the labelled image data. It takes the path to the saved labelled data and the total number of clusters to provide a DataFrame summarizing the size of each cluster. ```Python df_cluster_abundances = so.tool.count_clusters( file_paths=["./data/example_labelled.npy"], cluster_count=labelled_data.max() + 1, ) ``` -------------------------------- ### Generating Subpackages Toctree in Jinja2 Source: https://github.com/complextissue/spatiomic/blob/main/docs/source/_templates/modules.rst This Jinja2 block generates a reStructuredText `toctree` for visible subpackages. It filters `obj.subpackages` to include only those marked for display, sets `titlesonly` and `maxdepth` options, and iterates to list each subpackage's `index.rst` path. ```Jinja2 {% block subpackages %}\n{% set visible_subpackages = obj.subpackages|selectattr("display")|list %}\n{% if visible_subpackages %}\nSubpackages\n-----------\n.. toctree::\n :titlesonly:\n :maxdepth: 3\n\n{% for subpackage in visible_subpackages %}\n {{ subpackage.short_name }}/index.rst\n{% endfor %}\n\n\n{% endif %}\n{% endblock %} ``` -------------------------------- ### Detecting Image Shift using Phase Correlation in Python Source: https://github.com/complextissue/spatiomic/blob/main/docs/source/tutorials/registration.ipynb Calculates the translational shift between the `img_data_shifted` and the original `img_data` using the `phase_correlation` method via `so.process.register.get_shift()`. Various parameters like `blur`, `threshold`, `match_histogram`, and `upsample_factor` are set to control the shift detection process. ```python shift = so.process.register.get_shift( img_data_shifted, img_data, method="phase_correlation", blur=False, threshold=False, match_histogram=False, upsample_factor=1, ) ``` -------------------------------- ### Generating Submodules Toctree in Jinja2 Source: https://github.com/complextissue/spatiomic/blob/main/docs/source/_templates/modules.rst Similar to subpackages, this Jinja2 block generates a reStructuredText `toctree` for visible submodules. It filters `obj.submodules` by the 'display' attribute, sets `titlesonly` and `maxdepth` to 1, and lists each submodule's `index.rst` path. ```J ``` -------------------------------- ### Conditionally Displaying Orphan Directive in Jinja2 Source: https://github.com/complextissue/spatiomic/blob/main/docs/source/_templates/modules.rst This snippet checks if the `obj.display` attribute is false. If so, it inserts the reStructuredText `:orphan:` directive, which prevents the document from being included in any toctree, effectively making it a standalone page. ```Jinja2 {% if not obj.display %}\n:orphan:\n\n{% endif %} ``` -------------------------------- ### Plotting Cluster Abundance Bar Chart - Python Source: https://github.com/complextissue/spatiomic/blob/main/docs/source/tutorials/clustering.ipynb This snippet generates a horizontal bar chart from the `df_cluster_abundances` DataFrame. The plot visually represents the relative sizes or counts of each cluster, making it easy to compare their prevalence in the image. ```Python df_cluster_abundances.plot.barh() ``` -------------------------------- ### Calculating Moran's I for Cluster Spatial Autocorrelation - Python Source: https://github.com/complextissue/spatiomic/blob/main/docs/source/tutorials/clustering.ipynb This snippet computes Moran's I, a measure of spatial autocorrelation, for the `labelled_data`. It assesses whether clusters are spatially correlated or randomly distributed, using the 'moran' method with 500 permutations to determine statistical significance. ```Python df_morans_i = so.spatial.autocorrelation().predict(labelled_data, method="moran", permutation_count=500) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.