### Install SpatialVista from source Source: https://jianyang-lab.github.io/spatial-vista-py/quickstart Clones the repository and installs the package in editable mode using uv. Use this to get the latest development version. ```bash git clone https://github.com/JianYang-Lab/spatial-vista-py.git cd spatial-vista-py uv pip install -e . ``` -------------------------------- ### Minimal Jupyter example with FakeAnnData Source: https://jianyang-lab.github.io/spatial-vista-py/quickstart Verifies the installation by creating a minimal test AnnData-like object and visualizing it with spv.vis. If you see an interactive visualization, the installation is successful. ```python import numpy as np import spatialvista as spv # Create minimal test data class FakeAnnData: def __init__(self, n: int): self.obsm = {"spatial": np.random.rand(n, 3)} self.obs = {"celltype": np.random.choice(["A", "B", "C"], n)} self.var_names = [] self.X = None self.n_obs = n adata = FakeAnnData(n=10_000) # Create visualization spv.vis(adata, position="spatial", color="celltype") ``` -------------------------------- ### Install SpatialVista Source: https://jianyang-lab.github.io/spatial-vista-py?q= Install the package using pip. ```bash pip install spatialvista ``` -------------------------------- ### Install SpatialVista with uv Source: https://jianyang-lab.github.io/spatial-vista-py/quickstart Installs the spatialvista package using uv. Requires Python 3.10 or higher. ```bash uv pip install spatialvista ``` -------------------------------- ### Install and run SpatialVista command Source: https://jianyang-lab.github.io/spatial-vista-py/cli?q= Installs SpatialVista via pip and runs it with the --input flag. The server listens at http://127.0.0.1:8765 and opens a browser automatically; stop with Ctrl+C. ```bash pip install spatialvista spatialvista --input data.h5ad ``` -------------------------------- ### Open .h5ad file from command line Source: https://jianyang-lab.github.io/spatial-vista-py/quickstart Launches SpatialVista with the specified .h5ad file. It infers common obsm spatial keys and categorical obs columns, starts at http://127.0.0.1:8765, and opens the browser. ```bash spatialvista --input data.h5ad ``` -------------------------------- ### Install SpatialVista with pip Source: https://jianyang-lab.github.io/spatial-vista-py/quickstart Installs the spatialvista package using pip. Requires Python 3.10 or higher. ```bash pip install spatialvista ``` -------------------------------- ### SpatialVista data options example Source: https://jianyang-lab.github.io/spatial-vista-py/cli?q= Sets explicit coordinate, annotation, section, and layer options for reproducible commands. List options can be repeated or comma-separated. ```bash spatialvista --input sample.h5ad \ --position spatial \ --color celltype \ --section slice_id \ --annotations leiden,tissue_region \ --continuous total_counts,n_genes_by_counts \ --genes PECAM1,CD3E \ --layer normalized ``` -------------------------------- ### Run SpatialVista without installing using uvx Source: https://jianyang-lab.github.io/spatial-vista-py/quickstart Runs SpatialVista directly with uvx, without permanent installation. The --input flag specifies the .h5ad file. ```bash uvx spatialvista --input data.h5ad ``` -------------------------------- ### Set the logging level Source: https://jianyang-lab.github.io/spatial-vista-py/api Examples of setting different logging levels for the spatialvista package. ```python >>> import spatialvista as spv >>> spv.set_log_level("INFO") # Show info and above >>> spv.set_log_level("DEBUG") # Show debug and above >>> spv.set_log_level("ERROR") # Only show errors ``` -------------------------------- ### get_logger() Source: https://jianyang-lab.github.io/spatial-vista-py/api Get the configured logger instance used by the spatialvista package. ```APIDOC ## get_logger() ### Description Get the configured logger instance. ### Returns - **logger** - The configured loguru logger instance. ``` -------------------------------- ### get_log_level() Source: https://jianyang-lab.github.io/spatial-vista-py/api Get the current logging level of the spatialvista package. ```APIDOC ## get_log_level() ### Description Get the current logging level. ### Returns - **str** - The current log level (e.g., "WARNING", "INFO"). ``` -------------------------------- ### Fix spatialvista import in Jupyter: check kernel, install, create kernel Source: https://jianyang-lab.github.io/spatial-vista-py/faq?q= Diagnose and fix a Jupyter kernel environment issue where spatialvista cannot be imported. The first block checks which Python the kernel uses and whether spatialvista is installed; the second installs it in the correct environment (pip or uv); the third creates a new kernel named 'myenv' for the environment. Use these in order when the package is missing from the active kernel. ```python # Check which Python your kernel is using import sys print(sys.executable) # Check if spatialvista is installed in this environment import subprocess subprocess.run([sys.executable, "-m", "pip", "list"]) ``` ```bash # Install in the same environment as your Jupyter kernel python -m pip install spatialvista # Or with uv uv pip install spatialvista ``` ```bash # Activate your environment first, then: python -m ipykernel install --user --name=myenv --display-name="Python (myenv)" ``` -------------------------------- ### Create a SpatialVista visualization widget Source: https://jianyang-lab.github.io/spatial-vista-py/api Demonstrates basic usage of the vis function and how to enable logging for the visualization process. ```python >>> import spatialvista as spv >>> >>> # Basic usage >>> widget = spv.vis(adata, position="spatial", color="region") >>> >>> # With logging enabled >>> spv.set_log_level("INFO") >>> widget = spv.vis(adata, position="spatial", color="region") ``` -------------------------------- ### SpatialVista server options Source: https://jianyang-lab.github.io/spatial-vista-py/cli?q= Lists server configuration flags: --host, --port, --no-browser, --mode, and --height. The default loopback address keeps the server local; binding another host can expose data over a network. ```bash --host HOST Listening interface (default: 127.0.0.1) --port PORT Listening port (default: 8765; use 0 for an available port) --no-browser Do not open the browser automatically --mode {2D,3D} Initial visualization mode --height HEIGHT Visualization height in pixels ``` -------------------------------- ### Run SpatialVista with uvx Source: https://jianyang-lab.github.io/spatial-vista-py/cli?q= Launches SpatialVista in an isolated environment using uvx, opening the specified .h5ad file in a browser. ```bash uvx spatialvista --input data.h5ad ``` -------------------------------- ### Good practice for incremental widget loading Source: https://jianyang-lab.github.io/spatial-vista-py/faq?q= Load data in steps by reloading the widget with specific parameters to keep transfer sizes and memory usage low. ```python # Step 1: Start with basics widget = spv.vis( adata, position="spatial", color="celltype", annotations=["leiden"] # Just 1-2 extra annotations ) # Step 2: Later, reload with genes widget = spv.vis( adata, position="spatial", color="celltype", genes=["Gene1", "Gene2", "Gene3"] # Just a few genes ) # Step 3: Or reload with continuous values widget = spv.vis( adata, position="spatial", color="celltype", continuous=["total_counts", "n_genes"] # Just key QC metrics ) ``` -------------------------------- ### Open .h5ad file with explicit keys Source: https://jianyang-lab.github.io/spatial-vista-py/quickstart Specifies custom keys for position, color, section, annotations, continuous values, and genes. Use this when your file uses different names than the inferred defaults. ```bash spatialvista --input data.h5ad \ --position spatial \ --color celltype \ --section section \ --annotations leiden,region \ --continuous total_counts \ --genes Pecam1,Cd3e ``` -------------------------------- ### Good practice: incremental loading with spv.vis Source: https://jianyang-lab.github.io/spatial-vista-py/faq Loads only a few annotations, genes, or continuous values initially, then reloads with new parameters. Reloading is fast; recommended limits are 3-5 annotations, 5-10 genes, and 3-5 continuous values per widget. ```python # Step 1: Start with basics widget = spv.vis( adata, position="spatial", color="celltype", annotations=["leiden"] # Just 1-2 extra annotations ) # Step 2: Later, reload with genes widget = spv.vis( adata, position="spatial", color="celltype", genes=["Gene1", "Gene2", "Gene3"] # Just a few genes ) # Step 3: Or reload with continuous values widget = spv.vis( adata, position="spatial", color="celltype", continuous=["total_counts", "n_genes"] # Just key QC metrics ) ``` -------------------------------- ### Visualize Categorical Annotations Source: https://jianyang-lab.github.io/spatial-vista-py?q= Load additional categorical annotations for coloring and exploration. ```python # Color by cell type widget = spv.vis( adata, position="spatial", color="celltype", annotations=["leiden", "tissue_region"] # Additional annotations to load ) ``` -------------------------------- ### Bad practice for widget loading Source: https://jianyang-lab.github.io/spatial-vista-py/faq?q= Loading too many annotations and genes at once can cause slow performance and browser freezes. ```python # This loads 50+ annotations + 100 genes = very slow! widget = spv.vis( adata, position="spatial", color="celltype", annotations=list(adata.obs.columns), # ❌ All annotations genes=list(adata.var_names[:100]) # ❌ 100 genes ) ``` -------------------------------- ### vis(adata, position, color, section=None, annotations=None, continuous=None, genes=None, layer=None, height=600, mode='3D', _async_workers=2, _wait_for_all_sends=False) Source: https://jianyang-lab.github.io/spatial-vista-py/api Create and return a SpatialVista visualization widget. This is the primary entry point for generating interactive spatial visualizations from AnnData objects. ```APIDOC ## vis(adata, position, color, section=None, annotations=None, continuous=None, genes=None, layer=None, height=600, mode='3D', _async_workers=2, _wait_for_all_sends=False) ### Description Create and return a SpatialVista visualization widget. If _wait_for_all_sends is True, the function will block until all background sends finish. Otherwise it will return the widget immediately while sends may continue in background. ### Parameters - **adata** (AnnData) - Required - Annotated data object containing spatial information. - **position** (str) - Required - Key in adata.obsm containing spatial coordinates. - **color** (str) - Required - Key in adata.obs for default categorical coloring. - **section** (str) - Optional - Annotation key for section slicing (only relevant when mode="3D" and switching to 2D slice view in UI). Ignored when mode="2D". Default: None - **annotations** (list[str]) - Optional - List of additional categorical annotation keys to export. Default: None - **continuous** (list[str]) - Optional - List of continuous observation keys to export. Default: None - **genes** (list[str]) - Optional - List of gene names to export. Default: None - **layer** (str) - Optional - Layer to use for gene expression values. If None, uses adata.X. Default: None - **height** (int) - Optional - Height of the widget in pixels. Default: 600 - **mode** (str) - Optional - Visualization mode. "3D" for 3D point cloud, "2D" for 2D projection (z=0). Default: "3D" - **_async_workers** (int) - Optional - Number of background workers for async trait sends. Default: 2 - **_wait_for_all_sends** (bool) - Optional - Whether to wait for all background sends to complete before returning. Default: False ### Returns - **SpatialVistaWidget** - The configured widget ready for display. ### Examples ```python >>> import spatialvista as spv >>> >>> # Basic usage >>> widget = spv.vis(adata, position="spatial", color="region") >>> >>> # With logging enabled >>> spv.set_log_level("INFO") >>> widget = spv.vis(adata, position="spatial", color="region") ``` ``` -------------------------------- ### Access and apply alignment parameters Source: https://jianyang-lab.github.io/spatial-vista-py/api Shows how to retrieve alignment parameters from a widget and apply them to the AnnData object. ```python widget.alignment_parameters aligned = widget.apply_alignment(output_key="spatial_aligned") ``` -------------------------------- ### Enable detailed logging with spv.set_log_level Source: https://jianyang-lab.github.io/spatial-vista-py/faq?q= Enables detailed logging for debugging data loading issues. Use INFO to see data transfer progress or DEBUG to see everything, then create a visualization widget with spv.vis. ```python import spatialvista as spv spv.set_log_level("INFO") # See data transfer progress # or spv.set_log_level("DEBUG") # See everything widget = spv.vis(adata, position="spatial", color="celltype") ``` -------------------------------- ### Visualize Continuous Values Source: https://jianyang-lab.github.io/spatial-vista-py?q= Include continuous value fields such as QC metrics for visualization. ```python # Visualize continuous values (e.g., QC metrics) widget = spv.vis( adata, position="spatial", color="celltype", continuous=["total_counts", "n_genes"] # Continuous value fields ) ``` -------------------------------- ### Basic Usage of SpatialVista Source: https://jianyang-lab.github.io/spatial-vista-py?q= Load spatial transcriptomics data from an h5ad file and initialize the interactive visualization widget. ```python import spatialvista as spv import scanpy as sc # Load spatial transcriptomics data adata = sc.read_h5ad("spatial_data.h5ad") # Create interactive visualization widget = spv.vis( adata, position="spatial", # obsm key containing spatial coordinates color="celltype", # Default annotation for coloring height=600 # Widget height in pixels ) # Display widget widget ``` -------------------------------- ### Bad practice: loading all annotations and genes with spv.vis Source: https://jianyang-lab.github.io/spatial-vista-py/faq Loads all annotations and 100 genes, causing slow transfer and high memory usage. Avoid this pattern; it is labeled as bad practice. ```python # This loads 50+ annotations + 100 genes = very slow! widget = spv.vis( adata, position="spatial", color="celltype", annotations=list(adata.obs.columns), # ❌ All annotations genes=list(adata.var_names[:100]) # ❌ 100 genes ) ``` -------------------------------- ### Enable 2D/3D View Switching Source: https://jianyang-lab.github.io/spatial-vista-py?q= Provide a section identifier field to enable section browser controls and 2D view switching. ```python # If data has section information, switch to 2D view in UI widget = spv.vis( adata, position="spatial", color="celltype", section="slice_id", # Section identifier field for section browser ) ``` -------------------------------- ### Check coordinate bounds for LAZ transformation Source: https://jianyang-lab.github.io/spatial-vista-py/faq Check the original coordinate bounds before SpatialVista's LAZ transformation. The minimum and maximum values become the offset and are used to calculate the scale for integer compression. ```python # Your original coordinates print(adata.obsm["spatial"].min(axis=0)) # [min_x, min_y, min_z] print(adata.obsm["spatial"].max(axis=0)) # [max_x, max_y, max_z] # These become the offset and are used to calculate scale ``` -------------------------------- ### widget.apply_alignment(output_key="spatial_aligned") Source: https://jianyang-lab.github.io/spatial-vista-py/api Materialize the latest frontend alignment parameters into the AnnData object. This method is exposed on the widget returned by vis() when section is used. ```APIDOC ## widget.apply_alignment(output_key="spatial_aligned") ### Description Materialize the latest frontend alignment parameters into AnnData. Returns an (n_obs, 3) NumPy array and stores the same array in the source adata.obsm mapping. ### Parameters - **output_key** (str) - Optional - Key in adata.obsm where the aligned coordinates will be stored. Default: "spatial_aligned" ### Returns - **numpy.ndarray** - An (n_obs, 3) NumPy array containing the aligned spatial coordinates. ### Usage Example ```python widget.alignment_parameters aligned = widget.apply_alignment(output_key="spatial_aligned") ``` ``` -------------------------------- ### Downsample dataset for memory management Source: https://jianyang-lab.github.io/spatial-vista-py/faq?q= Use Scanpy's subsample function to reduce the number of cells before passing the data to the visualization widget. ```python import scanpy as sc # Option 1: Keep a fraction sc.pp.subsample(adata, fraction=0.5) # 50% of cells # Option 2: Keep exact number sc.pp.subsample(adata, n_obs=100000) # 100k cells # Then visualize widget = spv.vis(adata, position="spatial", color="celltype") ``` -------------------------------- ### Update SpatialVista Source: https://jianyang-lab.github.io/spatial-vista-py/quickstart Updates the spatialvista package to the latest version using either uv or pip. ```bash uv pip install --upgrade spatialvista # or pip install --upgrade spatialvista ``` -------------------------------- ### Check original coordinates for LAZ transformation Source: https://jianyang-lab.github.io/spatial-vista-py/faq?q= Inspect the original spatial coordinates before SpatialVista's LAZ transformation. The min and max values become the offset and are used to calculate the scale. Use this to verify the coordinate range and understand the quantization effect. ```python # Your original coordinates print(adata.obsm["spatial"].min(axis=0)) # [min_x, min_y, min_z] print(adata.obsm["spatial"].max(axis=0)) # [max_x, max_y, max_z] # These become the offset and are used to calculate scale ``` -------------------------------- ### Synchronize alignment parameters and apply alignment in Jupyter Source: https://jianyang-lab.github.io/spatial-vista-py/controls?q= In Jupyter, these commands synchronize the alignment parameters to the widget and apply the alignment, writing aligned 3D coordinates to adata.obsm["spatial_aligned"]. ```python widget.alignment_parameters widget.apply_alignment(output_key="spatial_aligned") ``` -------------------------------- ### set_log_level(level='WARNING') Source: https://jianyang-lab.github.io/spatial-vista-py/api Set the logging level for the spatialvista package. This controls the verbosity of log messages emitted by the library. ```APIDOC ## set_log_level(level='WARNING') ### Description Set the logging level for the spatialvista package. ### Parameters - **level** (str) - Optional - The logging level. Valid values are: "TRACE", "DEBUG", "INFO", "SUCCESS", "WARNING", "ERROR", "CRITICAL". Default: "WARNING" ### Raises - **ValueError** - If an invalid log level is provided. ### Examples ```python >>> import spatialvista as spv >>> spv.set_log_level("INFO") # Show info and above >>> spv.set_log_level("DEBUG") # Show debug and above >>> spv.set_log_level("ERROR") # Only show errors ``` ``` -------------------------------- ### Downsample large dataset with sc.pp.subsample before spv.vis Source: https://jianyang-lab.github.io/spatial-vista-py/faq Downsamples the AnnData object before visualization to avoid memory errors. Use either a fraction (e.g., 0.5 for 50% of cells) or an exact number of observations (e.g., 100000). ```python import scanpy as sc # Option 1: Keep a fraction sc.pp.subsample(adata, fraction=0.5) # 50% of cells # Option 2: Keep exact number sc.pp.subsample(adata, n_obs=100000) # 100k cells # Then visualize widget = spv.vis(adata, position="spatial", color="celltype") ``` -------------------------------- ### Disable logging with spv.disable_logging Source: https://jianyang-lab.github.io/spatial-vista-py/faq?q= Disables logging entirely or sets the log level to ERROR so only errors are shown. ```python spv.disable_logging() # or spv.set_log_level("ERROR") # Only show errors ``` -------------------------------- ### Visualize Gene Expression Source: https://jianyang-lab.github.io/spatial-vista-py?q= Specify a list of genes to visualize their spatial expression patterns, optionally using a specific data layer. ```python # View expression patterns of specific genes widget = spv.vis( adata, position="spatial", color="celltype", genes=["Pecam1", "Cd3e", "Epcam"], # Gene list layer="normalized" # Optional: use specific layer if available ) ``` -------------------------------- ### Fix KeyError for position/annotation keys in spv.vis Source: https://jianyang-lab.github.io/spatial-vista-py/faq?q= Resolve a KeyError when the specified position or annotation key does not exist in the data. The first lines list the available keys in adata.obsm and adata.obs; the last line shows how to pass the correct keys to spv.vis. ```python # Check available keys print("Position keys:", adata.obsm.keys()) print("Annotation keys:", adata.obs.columns.tolist()) # Use correct keys widget = spv.vis(adata, position="your_actual_key", color="your_annotation") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.