### Install SnapATAC2 from Source Source: https://github.com/scverse/snapatac2/blob/main/docs/install.md Installs the latest version of the library directly from the GitHub repository. ```bash pip install 'git+https://github.com/scverse/SnapATAC2.git#egg=snapatac2' ``` -------------------------------- ### Install SnapATAC2 via PyPI Source: https://github.com/scverse/snapatac2/blob/main/docs/install.md Installs the stable version of the library using pip. ```bash pip install snapatac2 ``` -------------------------------- ### Install Rust Compiler Source: https://github.com/scverse/snapatac2/blob/main/docs/install.md Installs the Rust compiler required for building SnapATAC2 from source. ```bash curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh ``` -------------------------------- ### Install Optional Dependencies Source: https://github.com/scverse/snapatac2/blob/main/docs/install.md Installs SnapATAC2 along with recommended optional packages for advanced features. ```bash pip install snapatac2[recommend] ``` -------------------------------- ### Install Nightly Build Wheel Source: https://github.com/scverse/snapatac2/blob/main/docs/install.md Installs a specific nightly build wheel file downloaded from the GitHub releases page. ```bash pip install snapatac2-x.x.x-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl ``` -------------------------------- ### Run Interactive SnapATAC2 Docker Image on Linux/MacOS (amd64) Source: https://github.com/scverse/snapatac2/blob/main/docker/README.md Run the interactive SnapATAC2 Docker image on Linux or MacOS. Mount local directories for notebooks and data. For GPU support, ensure Nvidia container toolkit is installed and add the --gpus flag. ```bash docker run --interactive --tty --rm --env LOCAL_USER_ID=`id -u $USER` --publish 8888:8888 --volume :/notebooks --volume :/data snapatac2:v2.6.0-recommend-interactive-py3.11 ``` -------------------------------- ### Import Fragments and Compute QC Metrics Source: https://context7.com/scverse/snapatac2/llms.txt Import data from fragment files and compute basic QC metrics like fragment counts, duplication rates, and mitochondrial DNA percentage. Requires fragment files and chromosome sizes. ```python import snapatac2 as snap # Import fragments from a 10X Genomics fragment file data = snap.pp.import_fragments( fragment_file="fragments.tsv.gz", chrom_sizes=snap.genome.hg38, min_num_fragments=200, sorted_by_barcode=True, n_jobs=8 ) # Result contains QC metrics in .obs print(data) # AnnData object with n_obs x n_vars = 5000 x 0 # obs: 'n_fragment', 'frac_dup', 'frac_mito' # uns: 'reference_sequences' # obsm: 'fragment_paired' # Access QC metrics print(data.obs['n_fragment'].head()) print(data.obs['frac_dup'].head()) ``` -------------------------------- ### Build Custom SnapATAC2 Docker Image with Build Args Source: https://github.com/scverse/snapatac2/blob/main/docker/README.md Build a custom SnapATAC2 Docker image by specifying Python base image and SnapATAC2 version using build arguments. Note that custom combinations are not guaranteed to be functional. ```bash DOCKER_BUILDKIT=1 docker build --platform linux/amd64 --build-arg BASE_PYTHON_IMAGE=python:3.12-slim --build-arg SNAP_ATAC_VERSION=v2.5.1 --tag snapatac2:v2.5.1-default-py3.12 . ``` -------------------------------- ### Run Interactive SnapATAC2 Docker Image on MacOS (arm64) [Experimental] Source: https://github.com/scverse/snapatac2/blob/main/docker/README.md Run the interactive SnapATAC2 Docker image on MacOS arm64. This configuration is experimental and untested. It requires the --platform linux/amd64 flag. ```bash docker run --platform linux/amd64 --interactive --tty --rm --env LOCAL_USER_ID=`id -u $USER` --publish 8888:8888 --volume :/notebooks --volume :/data snapatac2:v2.6.0-recommend-interactive-py3.11 ``` -------------------------------- ### Build Default SnapATAC2 Docker Image Source: https://github.com/scverse/snapatac2/blob/main/docker/README.md Use this command to build the default SnapATAC2 Docker image. Ensure Docker Engine version is at least 23.0. ```bash DOCKER_BUILDKIT=1 docker build --platform linux/amd64 --tag snapatac2:v2.6.0-default-py3.11 . ``` -------------------------------- ### Build Interactive SnapATAC2 Docker Image Source: https://github.com/scverse/snapatac2/blob/main/docker/README.md Use this command to build the interactive SnapATAC2 Docker image with Jupyter Lab. Ensure Docker Engine version is at least 23.0. ```bash DOCKER_BUILDKIT=1 docker build --platform linux/amd64 --tag snapatac2:v2.6.0-recommend-interactive-py3.11 . ``` -------------------------------- ### SnapATAC2 Tools Overview Source: https://github.com/scverse/snapatac2/blob/main/docs/api/tools.rst Overview of available tools in the snapatac2.tl module for data analysis and annotation. ```APIDOC ## SnapATAC2 Tools (tl) ### Description The `tl` module contains functions for data transformation and annotation. Unlike preprocessing, these tools add interpretable annotations to the data matrix. ### Available Tools - **Embeddings**: `tl.spectral`, `tl.multi_spectral`, `tl.umap` - **Clustering**: `tl.leiden`, `tl.kmeans`, `tl.dbscan`, `tl.hdbscan` - **Peak calling**: `tl.macs3`, `tl.merge_peaks` - **Differential analysis**: `tl.marker_regions`, `tl.diff_test` - **Motif analysis**: `tl.motif_enrichment` - **Network analysis (beta)**: `tl.init_network_from_annotation`, `tl.add_cor_scores`, `tl.add_regr_scores`, `tl.add_tf_binding`, `tl.link_tf_to_gene`, `tl.prune_network` - **Utilities**: `tl.aggregate_X`, `tl.aggregate_cells` ``` -------------------------------- ### Scanorama Integration for Batch Correction in SnapATAC2 Source: https://context7.com/scverse/snapatac2/llms.txt Integrate batches using Scanorama. Ensure the 'batch' information is present in `data.obs` and 'X_spectral' is the representation to integrate. ```python import snapatac2 as snap # Scanorama integration snap.pp.scanorama_integrate( data, batch='batch', use_rep='X_spectral' ) ``` -------------------------------- ### Read and Write AnnData Files Source: https://context7.com/scverse/snapatac2/llms.txt Read and write backed AnnData objects for memory-efficient processing. Includes options for configuring write compression. ```python import snapatac2 as snap # Read existing h5ad file data = snap.read("processed_data.h5ad", backed='r') # Create new backed AnnData ada = snap.AnnData(filename="new_data.h5ad") # Configure compression options snap.set_write_options(compression="zstandard", compression_level=3) ``` -------------------------------- ### Fragment Size Distribution Source: https://context7.com/scverse/snapatac2/llms.txt Compute and analyze the fragment size distribution. Includes options for maximum recorded size and plotting the distribution. ```python import snapatac2 as snap # Compute fragment size distribution snap.metrics.frag_size_distr(data, max_recorded_size=1000) # Access distribution print(data.uns['frag_size_distr'][:10]) # Plot fragment size distribution snap.pl.frag_size_distr(data, show=True) ``` -------------------------------- ### Build KNN Graph Source: https://context7.com/scverse/snapatac2/llms.txt Construct a k-nearest neighbor graph for clustering using spectral embedding. Allows specifying the number of neighbors and the method for graph construction. ```python import snapatac2 as snap # Build KNN graph using spectral embedding snap.pp.knn( data, n_neighbors=50, use_rep='X_spectral', method='kdtree' # Options: 'kdtree', 'hora', 'pynndescent' ) # Graph stored in data.obsp['distances'] print(data.obsp['distances'].shape) ``` -------------------------------- ### Generate Peak Matrix Source: https://context7.com/scverse/snapatac2/llms.txt Create a cell-by-peak count matrix from a peak file. Specify peak file and counting strategy. Can set fragment size constraints. ```python import snapatac2 as snap # Generate peak matrix from BED file peak_mat = snap.pp.make_peak_matrix( data, peak_file="peaks.bed", counting_strategy='paired-insertion', min_frag_size=None, max_frag_size=None ) print(peak_mat) # AnnData object with n_obs x n_vars = 5000 x 150000 ``` -------------------------------- ### K-means and Other Clustering Methods in SnapATAC2 Source: https://context7.com/scverse/snapatac2/llms.txt Perform K-means, DBSCAN, or HDBSCAN clustering on the spectral embedding. Ensure the 'data' object is loaded and the 'use_rep' parameter matches the desired representation. ```python import snapatac2 as snap # K-means clustering snap.tl.kmeans(data, n_clusters=10, use_rep="X_spectral") # DBSCAN clustering snap.tl.dbscan(data, eps=0.5, min_samples=5, use_rep="X_spectral") # HDBSCAN clustering snap.tl.hdbscan(data, min_cluster_size=10, use_rep="X_spectral") ``` -------------------------------- ### Raw Data Source: https://github.com/scverse/snapatac2/blob/main/docs/api/datasets.rst Download raw public datasets for SnapATAC2 analysis. ```APIDOC ## Raw Data ### Description Download raw public datasets for SnapATAC2 analysis. ### Available Raw Datasets - `datasets.pbmc500` - `datasets.pbmc5k` - `datasets.pbmc10k_multiome` - `datasets.colon` - `datasets.cre_HEA ``` -------------------------------- ### BAM/Fragment File Processing Source: https://github.com/scverse/snapatac2/blob/main/docs/api/preprocessing.rst Functions for processing BAM and fragment files, and importing related data. ```APIDOC ## `pp.make_fragment_file` ### Description Creates a fragment file from BAM files. ### Method (Not specified, likely a function call) ### Endpoint (Not applicable, this is a library function) ### Parameters (Parameters not detailed in the provided text) ### Request Example ```python import snapatac2 as snapatac snapatac.pp.make_fragment_file(filename='output.tsv', bam_files=['input.bam']) ``` ### Response (Response details not specified) ## `pp.import_fragments` ### Description Imports fragments from a fragment file. ### Method (Not specified, likely a function call) ### Endpoint (Not applicable, this is a library function) ### Parameters (Parameters not detailed in the provided text) ### Request Example ```python import snapatac2 as snapatac adata = snapatac.pp.import_fragments(filename='fragments.tsv') ``` ### Response (Response details not specified) ## `pp.import_values` ### Description Imports values from a file. ### Method (Not specified, likely a function call) ### Endpoint (Not applicable, this is a library function) ### Parameters (Parameters not detailed in the provided text) ### Request Example ```python import snapatac2 as snapatac adata = snapatac.pp.import_values(filename='values.tsv') ``` ### Response (Response details not specified) ## `pp.import_contacts` ### Description Imports contacts from a file. ### Method (Not specified, likely a function call) ### Endpoint (Not applicable, this is a library function) ### Parameters (Parameters not detailed in the provided text) ### Request Example ```python import snapatac2 as snapatac adata = snapatac.pp.import_contacts(filename='contacts.tsv') ``` ### Response (Response details not specified) ## `pp.call_cells` ### Description Calls cells based on fragment data. ### Method (Not specified, likely a function call) ### Endpoint (Not applicable, this is a library function) ### Parameters (Parameters not detailed in the provided text) ### Request Example ```python import snapatac2 as snapatac snapatac.pp.call_cells(adata) ``` ### Response (Response details not specified) ``` -------------------------------- ### Plot UMAP Visualization Source: https://context7.com/scverse/snapatac2/llms.txt Generates a UMAP visualization of cells, colored by annotations. Supports custom settings for marker size, opacity, and output file. ```python import snapatac2 as snap # Plot UMAP colored by cluster snap.pl.umap(data, color='leiden', show=True) ``` ```python # Plot with custom settings snap.pl.umap( data, color='cell_type', marker_size=2, marker_opacity=0.8, out_file="umap.html" ) ``` -------------------------------- ### Read 10X Genomics MTX Files Source: https://context7.com/scverse/snapatac2/llms.txt Read 10X Genomics-formatted matrix files from a directory. Optionally saves the result to a backed AnnData file. ```python import snapatac2 as snap # Read 10X matrix files from directory ada = snap.read_10x_mtx( path="filtered_peak_bc_matrix/", file="output.h5ad" # Optional: save to backed AnnData ) print(adata) # AnnData object with n_obs x n_vars = 5000 x 50000 ``` -------------------------------- ### Call Peaks with MACS3 in SnapATAC2 Source: https://context7.com/scverse/snapatac2/llms.txt Call peaks using MACS3 on pseudo-bulk data, either per cluster or for broad peaks. Specify parameters like `qvalue`, `shift`, `extsize`, and `call_broad_peaks` as needed. Peaks are stored in `data.uns['macs3']`. ```python import snapatac2 as snap # Call peaks per cluster snap.tl.macs3( data, groupby='leiden', qvalue=0.05, shift=-100, extsize=200, n_jobs=8 ) # Peaks stored in data.uns['macs3'] for cluster, peaks in data.uns['macs3'].items(): print(f"Cluster {cluster}: {len(peaks)} peaks") # Call broad peaks snap.tl.macs3( data, groupby='leiden', call_broad_peaks=True, broad_cutoff=0.1 ) ``` -------------------------------- ### Generate Tile Matrix Source: https://context7.com/scverse/snapatac2/llms.txt Create a cell-by-bin count matrix for downstream analysis. Requires fragment data and genome information. Excludes specified chromosomes. ```python import snapatac2 as snap # Load and import data data = snap.pp.import_fragments( "fragments.tsv.gz", chrom_sizes=snap.genome.hg38, sorted_by_barcode=False ) # Generate tile matrix with 500bp bins snap.pp.add_tile_matrix( data, bin_size=500, exclude_chroms=["chrM", "chrY"], counting_strategy='paired-insertion' ) print(data) # AnnData object with n_obs x n_vars = 5000 x 6062095 # obs: 'n_fragment', 'frac_dup', 'frac_mito' # ... ``` -------------------------------- ### Harmony Integration for Batch Correction in SnapATAC2 Source: https://context7.com/scverse/snapatac2/llms.txt Integrate data from multiple batches using Harmony. The 'batch' labels must be added to `data.obs` and 'X_spectral' should be the representation to correct. The corrected embedding is stored in `data.obsm['X_spectral_harmony']`. ```python import snapatac2 as snap # Add batch information to data.obs # data.obs['batch'] = batch_labels # Run Harmony for batch correction snap.pp.harmony( data, batch='batch', use_rep='X_spectral', use_dims=30 ) # Corrected embedding in data.obsm['X_spectral_harmony'] print(data.obsm['X_spectral_harmony'].shape) # Use corrected embedding for clustering snap.pp.knn(data, use_rep='X_spectral_harmony') snap.tl.leiden(data) ``` -------------------------------- ### snapatac2 API Modules Source: https://github.com/scverse/snapatac2/blob/main/docs/api/index.rst This section outlines the different modules available within the snapatac2 library, each covering a specific aspect of single-cell ATAC-seq data analysis. ```APIDOC ## snapatac2 API Modules Overview ### Description This documentation provides a structured overview of the snapatac2 library's API, organized into distinct modules for various functionalities. ### Modules - **io**: For input/output operations related to ATAC-seq data. - **preprocessing**: Functions for data cleaning and preparation. - **tools**: Core analytical tools for snapatac2. - **metrics**: Modules for calculating and evaluating data metrics. - **plotting**: Utilities for visualizing ATAC-seq data. - **export**: Functions for exporting data and results. - **motif**: Tools for motif analysis. - **datasets**: Access to example datasets. - **recipes**: Pre-defined workflows for common analysis tasks. ``` -------------------------------- ### Motif Analysis Classes and Functions Source: https://github.com/scverse/snapatac2/blob/main/docs/api/motif.rst Overview of the core components for motif analysis in snapatac2. ```APIDOC ## Motif Analysis in snapatac2 This section covers the motif analysis capabilities within the snapatac2 library. ### Classes - **PyDNAMotif**: Represents a DNA motif. - **PyDNAMotifScanner**: Scans DNA sequences for motifs. - **PyDNAMotifTest**: Performs statistical tests on motifs. ### Functions - **read_motifs**: Reads motif data from a file. ``` -------------------------------- ### Convert BAM to Fragment File Source: https://context7.com/scverse/snapatac2/llms.txt Convert BAM files to fragment files, performing deduplication and filtering. Requires BAM file input and specifies output file, pairing, barcode tag, mapping quality, shifts, and compression. ```python import snapatac2 as snap # Convert BAM to fragment file metrics = snap.pp.make_fragment_file( bam_file="input.bam", output_file="fragments.tsv.gz", is_paired=True, barcode_tag="CB", min_mapq=30, shift_left=4, shift_right=-5, compression="gzip" ) # Returns QC metrics print(f"Sequenced reads: {metrics['sequenced_reads']}") print(f"Fraction duplicates: {metrics['frac_duplicates']:.2%}") print(f"Fraction mapped: {metrics['frac_confidently_mapped']:.2%}") ``` -------------------------------- ### Complete Analysis Workflow Source: https://context7.com/scverse/snapatac2/llms.txt A comprehensive workflow for single-cell ATAC-seq analysis, including data import, quality control, feature matrix creation, doublet removal, dimension reduction, clustering, peak calling, gene activity calculation, visualization, and export. ```python import snapatac2 as snap # 1. Import data data = snap.pp.import_fragments( "fragments.tsv.gz", chrom_sizes=snap.genome.hg38, min_num_fragments=200 ) # 2. Quality control snap.metrics.tsse(data, gene_anno=snap.genome.hg38) snap.pp.filter_cells(data, min_counts=1000, min_tsse=5.0) # 3. Feature matrix snap.pp.add_tile_matrix(data, bin_size=500) snap.pp.select_features(data, n_features=500000) # 4. Doublet removal snap.pp.scrublet(data) snap.pp.filter_doublets(data, probability_threshold=0.5) # 5. Dimension reduction snap.tl.spectral(data, n_comps=30) snap.tl.umap(data) # 6. Clustering snap.pp.knn(data, n_neighbors=50) snap.tl.leiden(data, resolution=1.0) # 7. Peak calling snap.tl.macs3(data, groupby='leiden', qvalue=0.05) merged_peaks = snap.tl.merge_peaks(data.uns['macs3'], snap.genome.hg38) # 8. Gene activity gene_mat = snap.pp.make_gene_matrix(data, gene_anno=snap.genome.hg38) # 9. Visualization snap.pl.umap(data, color='leiden', out_file='clusters.html') snap.pl.tsse(data, out_file='qc.pdf') # 10. Export snap.ex.export_coverage(data, groupby='leiden', suffix='.bw') ``` -------------------------------- ### Genomes Source: https://github.com/scverse/snapatac2/blob/main/docs/api/datasets.rst Access predefined genome references for data analysis. ```APIDOC ## Genomes ### Description Access predefined genome references for data analysis. ### Available Genomes - `genome.Genome` - `genome.GRCh37` - `genome.GRCh38` - `genome.GRCm38` - `genome.GRCm39` - `genome.hg19` - `genome.hg38` - `genome.mm10` - `genome.mm39 ``` -------------------------------- ### Export Coverage Source: https://github.com/scverse/snapatac2/blob/main/docs/api/export.rst Exports coverage data from a SnapATAC2 object. ```APIDOC ## export_coverage ### Description Exports coverage information from the SnapATAC2 object. ### Method Function Call (snapatac2.ex.export_coverage) ### Endpoint snapatac2.ex.export_coverage ``` -------------------------------- ### Export Coverage Tracks in SnapATAC2 Source: https://context7.com/scverse/snapatac2/llms.txt Generate bigWig or bedGraph coverage tracks per cell type or group. Specify `bin_size`, `normalization`, `max_frag_length`, and output directory. The output is a dictionary mapping group names to file paths. ```python import snapatac2 as snap # Export bigWig files per cell type output_files = snap.ex.export_coverage( data, groupby='cell_type', bin_size=10, normalization="RPKM", max_frag_length=2000, out_dir="./coverage/", suffix=".bw", n_jobs=8 ) print(output_files) ``` -------------------------------- ### Export Fragments to BED Format in SnapATAC2 Source: https://context7.com/scverse/snapatac2/llms.txt Export cell-associated fragments to BED format, optionally grouped by a specified key (e.g., 'leiden'). Output files are compressed with zstandard. The output is a dictionary mapping group names to file paths. ```python import snapatac2 as snap # Export fragments by cluster output_files = snap.ex.export_fragments( data, groupby='leiden', out_dir="./fragments/", suffix=".bed.zst" ) print(output_files) # {'0': './fragments/0.bed.zst', '1': './fragments/1.bed.zst', ...} ``` -------------------------------- ### Select Features Source: https://context7.com/scverse/snapatac2/llms.txt Select the most accessible features for dimension reduction. Uses quantile filtering and an optional blacklist file. Results are stored in `data.var['selected']`. ```python import snapatac2 as snap # Select top features snap.pp.select_features( data, n_features=500000, filter_lower_quantile=0.005, filter_upper_quantile=0.005, blacklist="blacklist.bed" ) # Selected features stored in data.var['selected'] print(f"Selected features: {data.var['selected'].sum()}") ``` -------------------------------- ### Motif Enrichment Analysis in SnapATAC2 Source: https://context7.com/scverse/snapatac2/llms.txt Perform motif enrichment analysis on peak sets using a specified motif database and genome. Requires loading motifs and defining regions per cluster. Results can be visualized using `snap.pl.motif_enrichment`. ```python import snapatac2 as snap # Load motif database motifs = snap.read_motifs("JASPAR2022_CORE.pfm") # Define regions for each cluster regions = { cluster: list(peaks['peak_name']) for cluster, peaks in data.uns['macs3'].items() } # Perform motif enrichment enrichment = snap.tl.motif_enrichment( motifs=motifs, regions=regions, genome_fasta=snap.genome.hg38, method='hypergeometric' ) # Results per group for cluster, df in enrichment.items(): significant = df.filter(df['adjusted p-value'] < 0.01) print(f"Cluster {cluster}: {len(significant)} enriched motifs") print(significant.head()) # Visualize motif enrichment snap.pl.motif_enrichment(enrichment, min_log_fc=1, max_fdr=0.01) ``` -------------------------------- ### Leiden Clustering Source: https://context7.com/scverse/snapatac2/llms.txt Perform Leiden clustering on the data. Allows specifying resolution, objective function, and minimum cluster size. Results are stored in `data.obs['leiden']`. ```python import snapatac2 as snap # Perform Leiden clustering snap.tl.leiden( data, resolution=1.0, objective_function="modularity", min_cluster_size=5, random_state=0 ) # Results in data.obs['leiden'] print(data.obs['leiden'].value_counts()) ``` -------------------------------- ### AnnData I/O Operations Source: https://github.com/scverse/snapatac2/blob/main/docs/api/io.rst Functions for reading and writing AnnData objects, including various file formats. ```APIDOC ## AnnData I/O Operations ### Description Functions for reading and writing AnnData objects, including various file formats. ### Functions - **read**: Reads data from various sources into an AnnData object. - **read_mtx**: Reads data from a Matrix Market (.mtx) file. - **read_10x_mtx**: Reads data from a 10x Genomics formatted directory. - **read_dataset**: Reads a dataset from a specified source. - **concat**: Concatenates multiple AnnData objects. - **get_write_options**: Retrieves current write options for AnnData objects. - **set_write_options**: Sets write options for AnnData objects. ``` -------------------------------- ### Export Fragments Source: https://github.com/scverse/snapatac2/blob/main/docs/api/export.rst Exports fragments from a SnapATAC2 object to a specified file format. ```APIDOC ## export_fragments ### Description Exports fragments from the SnapATAC2 object to a file. ### Method Function Call (snapatac2.ex.export_fragments) ### Endpoint snapatac2.ex.export_fragments ``` -------------------------------- ### Matrix Operation Source: https://github.com/scverse/snapatac2/blob/main/docs/api/preprocessing.rst Functions for creating and manipulating various matrices. ```APIDOC ## `pp.add_tile_matrix` ### Description Adds a tile matrix to the AnnData object. ### Method (Not specified, likely a function call) ### Endpoint (Not applicable, this is a library function) ### Parameters (Parameters not detailed in the provided text) ### Request Example ```python import snapatac2 as snapatac snapatac.pp.add_tile_matrix(adata) ``` ### Response (Response details not specified) ## `pp.make_peak_matrix` ### Description Creates a peak matrix. ### Method (Not specified, likely a function call) ### Endpoint (Not applicable, this is a library function) ### Parameters (Parameters not detailed in the provided text) ### Request Example ```python import snapatac2 as snapatac snapatac.pp.make_peak_matrix(adata) ``` ### Response (Response details not specified) ## `pp.make_gene_matrix` ### Description Creates a gene matrix. ### Method (Not specified, likely a function call) ### Endpoint (Not applicable, this is a library function) ### Parameters (Parameters not detailed in the provided text) ### Request Example ```python import snapatac2 as snapatac snapatac.pp.make_gene_matrix(adata) ``` ### Response (Response details not specified) ## `pp.filter_cells` ### Description Filters cells based on specified criteria. ### Method (Not specified, likely a function call) ### Endpoint (Not applicable, this is a library function) ### Parameters (Parameters not detailed in the provided text) ### Request Example ```python import snapatac2 as snapatac snapatac.pp.filter_cells(adata, min_counts=1000) ``` ### Response (Response details not specified) ## `pp.select_features` ### Description Selects features for analysis. ### Method (Not specified, likely a function call) ### Endpoint (Not applicable, this is a library function) ### Parameters (Parameters not detailed in the provided text) ### Request Example ```python import snapatac2 as snapatac snapatac.pp.select_features(adata, n_top_genes=2000) ``` ### Response (Response details not specified) ## `pp.knn` ### Description Computes the k-nearest neighbors graph. ### Method (Not specified, likely a function call) ### Endpoint (Not applicable, this is a library function) ### Parameters (Parameters not detailed in the provided text) ### Request Example ```python import snapatac2 as snapatac snapatac.pp.knn(adata) ``` ### Response (Response details not specified) ``` -------------------------------- ### Generate Gene Activity Matrix Source: https://context7.com/scverse/snapatac2/llms.txt Create a cell-by-gene activity matrix based on regulatory domains. Can include gene body or use TSS-only regions with specified upstream/downstream distances. ```python import snapatac2 as snap # Generate gene activity matrix gene_mat = snap.pp.make_gene_matrix( data, gene_anno=snap.genome.hg38, upstream=2000, downstream=0, include_gene_body=True ) print(gene_mat) # AnnData object with n_obs x n_vars = 5000 x 60606 # Use TSS-only regions gene_mat_tss = snap.pp.make_gene_matrix( data, gene_anno=snap.genome.hg38, upstream=1000, downstream=1000, include_gene_body=False ) ``` -------------------------------- ### Find Marker Regions per Group in SnapATAC2 Source: https://context7.com/scverse/snapatac2/llms.txt Quickly identify marker regions for each group (e.g., cluster) based on a p-value threshold. Results are returned as a dictionary where keys are group names and values are lists of marker regions. ```python import snapatac2 as snap # Find marker regions markers = snap.tl.marker_regions( data, groupby='leiden', pvalue=0.01 ) # Results as dictionary for cluster, peaks in markers.items(): print(f"Cluster {cluster}: {len(peaks)} marker regions") ``` -------------------------------- ### Data Integration Source: https://github.com/scverse/snapatac2/blob/main/docs/api/preprocessing.rst Functions for integrating multiple datasets. ```APIDOC ## `pp.mnc_correct` ### Description Performs mutual nearest neighbor correction for data integration. ### Method (Not specified, likely a function call) ### Endpoint (Not applicable, this is a library function) ### Parameters (Parameters not detailed in the provided text) ### Request Example ```python import snapatac2 as snapatac snapatac.pp.mnc_correct(adata) ``` ### Response (Response details not specified) ## `pp.harmony` ### Description Integrates data using Harmony. ### Method (Not specified, likely a function call) ### Endpoint (Not applicable, this is a library function) ### Parameters (Parameters not detailed in the provided text) ### Request Example ```python import snapatac2 as snapatac snapatac.pp.harmony(adata) ``` ### Response (Response details not specified) ## `pp.scanorama_integrate` ### Description Integrates data using Scanorama. ### Method (Not specified, likely a function call) ### Endpoint (Not applicable, this is a library function) ### Parameters (Parameters not detailed in the provided text) ### Request Example ```python import snapatac2 as snapatac snapatac.pp.scanorama_integrate(adata) ``` ### Response (Response details not specified) ``` -------------------------------- ### Plot Genomic Coverage Tracks Source: https://context7.com/scverse/snapatac2/llms.txt Provides a quick visualization of signal coverage across a specified genomic region, grouped by cell type. Can be saved to a file. ```python import snapatac2 as snap # Plot coverage for a specific region snap.pl.coverage( data, region='chr1:1000000-1100000', groupby='cell_type', out_file='coverage_plot.png' ) ``` -------------------------------- ### Motifs Source: https://github.com/scverse/snapatac2/blob/main/docs/api/datasets.rst Access motif datasets for downstream analysis. ```APIDOC ## Motifs ### Description Access motif datasets for downstream analysis. ### Available Motif Datasets - `datasets.cis_bp` - `datasets.Meuleman_2020 ``` -------------------------------- ### SnapATAC2 Plotting Functions Source: https://github.com/scverse/snapatac2/blob/main/docs/api/plotting.rst A collection of plotting utilities for visualizing single-cell ATAC-seq data analysis results. ```APIDOC ## Plotting Functions (snapatac2.pl) ### Description The `pl` module provides various functions to visualize data processed by snapatac2. ### Available Functions - **pl.tsse**: Plot TSS enrichment scores. - **pl.umap**: Plot UMAP embeddings. - **pl.motif_enrichment**: Plot motif enrichment results. - **pl.regions**: Plot genomic regions. - **pl.coverage**: Plot coverage tracks. - **pl.spectral_eigenvalues**: Plot spectral eigenvalues. - **pl.network_edge_stat**: Plot network edge statistics. - **pl.render_plot**: Render generated plots. ``` -------------------------------- ### UMAP Embedding Source: https://context7.com/scverse/snapatac2/llms.txt Generate UMAP visualization from spectral embedding. Specifies the number of components, the representation to use, and dimensions. ```python import snapatac2 as snap # Compute UMAP snap.tl.umap( data, n_comps=2, use_rep="X_spectral", use_dims=30, random_state=0 ) # Results in data.obsm['X_umap'] print(data.obsm['X_umap'].shape) # (n_cells, 2) ``` -------------------------------- ### Export Coverage Data Source: https://context7.com/scverse/snapatac2/llms.txt Exports coverage data, optionally compressed, grouped by a specified key, and normalized. ```python snap.ex.export_coverage( data, groupby='leiden', suffix=".bedgraph.zst", normalization="CPM" ) ``` -------------------------------- ### Detect Doublets with Scrublet Source: https://context7.com/scverse/snapatac2/llms.txt Identify doublets using the scrublet algorithm adapted for ATAC-seq. Requires selected features and specifies parameters like number of components and simulation ratio. Results are stored in `data.obs`. ```python import snapatac2 as snap # Detect doublets snap.pp.scrublet( data, features="selected", n_comps=15, sim_doublet_ratio=2.0, expected_doublet_rate=0.1 ) # Results in data.obs print(data.obs['doublet_probability'].head()) print(data.obs['doublet_score'].head()) # Filter doublets snap.pp.filter_doublets(data, probability_threshold=0.5) print(f"Cells after doublet removal: {data.n_obs}") ``` -------------------------------- ### AnnData Object Manipulation Source: https://github.com/scverse/snapatac2/blob/main/docs/api/io.rst Provides access to AnnData and AnnDataSet objects for data manipulation. ```APIDOC ## AnnData Object Manipulation ### Description Provides access to AnnData and AnnDataSet objects for data manipulation. ### Classes - **AnnData** - **AnnDataSet** ``` -------------------------------- ### Plot TSS Enrichment Source: https://context7.com/scverse/snapatac2/llms.txt Visualizes the distribution of TSS enrichment versus fragment counts. Can be shown directly or saved to a file. ```python import snapatac2 as snap # Plot TSS enrichment fig = snap.pl.tsse(data, min_fragment=500, show=True) ``` ```python # Save to file snap.pl.tsse(data, out_file="tsse_plot.pdf") ``` -------------------------------- ### Merge Peaks from Different Groups in SnapATAC2 Source: https://context7.com/scverse/snapatac2/llms.txt Merge peaks from different groups (e.g., clusters) into a consensus peak set. Requires the `data.uns['macs3']` output and genome chromosome sizes. ```python import snapatac2 as snap # Merge peaks from different clusters merged_peaks = snap.tl.merge_peaks( data.uns['macs3'], chrom_sizes=snap.genome.hg38, half_width=250 ) print(f"Total merged peaks: {len(merged_peaks)}") ``` -------------------------------- ### Plot Spectral Eigenvalues Source: https://context7.com/scverse/snapatac2/llms.txt Visualizes eigenvalues to help assess the dimensionality of the data. The suggested number of dimensions is stored in `data.uns['num_eigen']`. ```python import snapatac2 as snap # Plot eigenvalue spectrum snap.pl.spectral_eigenvalues(data, show=True) ``` ```python # Elbow point stored in data.uns['num_eigen'] print(f"Suggested dimensions: {data.uns['num_eigen']}") ``` -------------------------------- ### Leiden Sweep Source: https://context7.com/scverse/snapatac2/llms.txt Optimize Leiden clustering resolution parameter using silhouette scores. Sweeps over a list of resolutions and utilizes multiple jobs for computation. ```python import snapatac2 as snap # Sweep over resolutions results = snap.tl.leiden_sweep( data, resolutions=[0.1, 0.5, 1.0, 2.0, 5.0], use_rep="X_spectral", n_jobs=8 ) ``` -------------------------------- ### Compute Fraction of Reads in Peaks (FRiP) Source: https://context7.com/scverse/snapatac2/llms.txt Calculate the fraction of reads overlapping specified genomic regions. Supports multiple region sets defined by BED files or coordinates, and can use pre-defined CREs. ```python import snapatac2 as snap # Compute FRiP for multiple region sets snap.metrics.frip( data, regions={ "promoter_frac": "promoters.bed", "enhancer_frac": ["chr1:100-200", "chr2:300-400"], "peaks_frac": snap.datasets.cre_HEA() }, normalized=True ) print(data.obs['peaks_frac'].head()) # AAACTGCAGACTCGGA-1 0.715930 # AAAGATGCACCTATTT-1 0.697364 # ... ``` -------------------------------- ### Filter Cells by Quality Metrics Source: https://context7.com/scverse/snapatac2/llms.txt Filter cells based on quality metrics such as fragment count and TSS enrichment. Allows specifying minimum and maximum thresholds for these metrics. ```python import snapatac2 as snap # Filter cells by fragment count and TSS enrichment snap.pp.filter_cells( data, min_counts=1000, min_tsse=5.0, max_counts=100000, inplace=True ) print(f"Cells remaining: {data.n_obs}") ``` -------------------------------- ### Multi-modal Spectral Embedding Source: https://context7.com/scverse/snapatac2/llms.txt Perform joint dimension reduction across multiple modalities. Assumes aligned AnnData objects and allows specifying features and weights for each modality. ```python import snapatac2 as snap # Assuming atac_data and rna_data are aligned AnnData objects evals, evecs = snap.tl.multi_spectral( [atac_data, rna_data], n_comps=30, features=["selected", "selected"], weights=[1.0, 1.0] ) print(evecs.shape) # (n_cells, 30) ``` -------------------------------- ### Spectral Embedding Source: https://context7.com/scverse/snapatac2/llms.txt Perform dimension reduction using Laplacian Eigenmaps with linear complexity. Can be used with a subset of data for large datasets via Nystrom approximation. ```python import snapatac2 as snap # Perform spectral embedding snap.tl.spectral( data, n_comps=30, features="selected", distance_metric="cosine", weighted_by_sd=True, random_state=0 ) # Results stored in data.obsm['X_spectral'] and data.uns['spectral_eigenvalue'] print(data.obsm['X_spectral'].shape) # (n_cells, 30) # For very large datasets (>10M cells), use Nystrom approximation snap.tl.spectral( data, n_comps=30, sample_size=100000, # Use subset for approximation sample_method="random" ) ``` -------------------------------- ### Differential Accessibility Test in SnapATAC2 Source: https://context7.com/scverse/snapatac2/llms.txt Identify differentially accessible regions between two cell groups. Define the groups using boolean masks on `data.obs` and specify parameters like `min_log_fc` and `min_pct`. Results are returned as a polars DataFrame. ```python import snapatac2 as snap # Define cell groups group1 = data.obs['leiden'] == '0' group2 = data.obs['leiden'] == '1' # Perform differential test diff_results = snap.tl.diff_test( data, cell_group1=list(group1[group1].index), cell_group2=list(group2[group2].index), direction="both", min_log_fc=0.25, min_pct=0.05 ) # Results as polars DataFrame print(diff_results.head()) # feature name | log2(fold_change) | p-value | adjusted p-value # chr1:1000-2000 | 1.5 | 1e-10 | 1e-8 # Filter significant results significant = diff_results.filter( (diff_results['adjusted p-value'] < 0.05) & (abs(diff_results['log2(fold_change)']) > 1) ) ``` -------------------------------- ### Compute TSS Enrichment Score Source: https://context7.com/scverse/snapatac2/llms.txt Calculate TSS enrichment scores for quality control using fragment data and gene annotations. Results are stored in .obs and .uns. ```python import snapatac2 as snap # Load data data = snap.pp.import_fragments( "fragments.tsv.gz", chrom_sizes=snap.genome.hg38, sorted_by_barcode=False ) # Compute TSS enrichment snap.metrics.tsse(data, gene_anno=snap.genome.hg38) # Results stored in data.obs['tsse'] and data.uns print(data.obs['tsse'].head()) # AAACTGCAGACTCGGA-1 32.129514 # AAAGATGCACCTATTT-1 22.052786 # ... print(f"Library-level TSSe: {data.uns['library_tsse']:.2f}") ``` -------------------------------- ### Doublet Removal Source: https://github.com/scverse/snapatac2/blob/main/docs/api/preprocessing.rst Functions for identifying and removing doublets. ```APIDOC ## `pp.scrublet` ### Description Removes doublets using the Scrublet algorithm. ### Method (Not specified, likely a function call) ### Endpoint (Not applicable, this is a library function) ### Parameters (Parameters not detailed in the provided text) ### Request Example ```python import snapatac2 as snapatac snapatac.pp.scrublet(adata) ``` ### Response (Response details not specified) ## `pp.filter_doublets` ### Description Filters out cells identified as doublets. ### Method (Not specified, likely a function call) ### Endpoint (Not applicable, this is a library function) ### Parameters (Parameters not detailed in the provided text) ### Request Example ```python import snapatac2 as snapatac snapatac.pp.filter_doublets(adata) ``` ### Response (Response details not specified) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.