### Install Dependencies Source: https://github.com/yrsong001/gptanno/blob/master/PDF2markers/README.md Install the required Python packages for the project. ```bash pip install -r requirements.txt ``` ```bash pip install pandas numpy pypdf tqdm openai requests ``` -------------------------------- ### Install GPTAnno Source: https://github.com/yrsong001/gptanno/blob/master/README.md Install the package from GitHub using devtools. ```r # Install devtools if you haven't already install.packages("devtools") # Install GPTAnno devtools::install_github("yrsong001/GPTAnno") ``` -------------------------------- ### Initialize Ollama Server Source: https://github.com/yrsong001/gptanno/blob/master/README.md Commands to pull a model and start the local Ollama server. ```bash # In a terminal: ollama pull llama3 # or mistral, neural-chat, etc. ollama serve # default: http://localhost:11434 ``` -------------------------------- ### Ollama Setup Commands Source: https://github.com/yrsong001/gptanno/blob/master/man/call_llm.Rd Commands to prepare a local Ollama environment before calling the function. ```bash ollama pull llama2 # or another model ollama serve # start the server (runs on localhost:11434) ``` -------------------------------- ### Configure Alternative LLM Providers Source: https://github.com/yrsong001/gptanno/blob/master/vignettes/gptanno-pipeline.html Examples for configuring Anthropic or Gemini as the LLM backend. ```R llm_config <- list(provider = "anthropic", model = "claude-sonnet-4-20250514") llm_config <- list(provider = "gemini", model = "gemini-2.0-flash") ``` -------------------------------- ### Build CL Term Map Example Source: https://github.com/yrsong001/gptanno/blob/master/man/build_cl_term_map.Rd Demonstrates how to initialize an ontology object and generate the term map. ```R # cl <- ontologyIndex::get_ontology( # "http://purl.obolibrary.org/obo/cl.obo", # extract_tags = "everything" # ) # cl_term_map <- build_cl_term_map(cl) ``` -------------------------------- ### Score Annotation Distance Example Source: https://github.com/yrsong001/gptanno/blob/master/man/score_annotation_distance_ontology.Rd Demonstrates the setup of the ontology graph and the subsequent calculation of annotation distances. ```R # Build ontology and graph (one-time setup) cl <- ontologyIndex::get_ontology("http://purl.obolibrary.org/obo/cl.obo", extract_tags = "everything") graph <- build_ontology_graph(cl) cl_term_map <- build_cl_term_map(cl) # if need the up-to-date mapping # Score annotation distance dist_res <- score_annotation_distance_ontology( seurat_obj, manual_col = "celltype_manual", predicted_col = "celltype_parent", cl_term_map = cl_term_map, # leave it blank will use the built-in mapping graph = ontology_graph ) print(dist_res$mean_distance) ``` -------------------------------- ### Configure Ontology Annotation Strategy Source: https://github.com/yrsong001/gptanno/blob/master/man/prepare_ontology_strategy.Rd Examples demonstrating how to initialize the ontology object and configure annotation strategies using different restriction combinations. ```R cl <- ontologyIndex::get_ontology("http://purl.obolibrary.org/obo/cl.obo") # Use only ontology descendants config <- prepare_ontology_strategy(cl, "T cell") # Combine descendants with user list config <- prepare_ontology_strategy( cl, "T cell", user_restrict_to = c("regulatory T cell", "gamma-delta T cell"), combine_restrictions = TRUE ) # Use ONLY user list (ignore descendants) config <- prepare_ontology_strategy( cl, "T cell", user_restrict_to = c("regulatory T cell", "effector T cell"), combine_restrictions = FALSE ) ``` -------------------------------- ### Run Multi-Resolution Clustering Example Source: https://github.com/yrsong001/gptanno/blob/master/man/run_multi_resolution_clustering.Rd Demonstrates the basic usage of the function with a Seurat object and a vector of resolution parameters. ```R # result <- run_multi_resolution_clustering(seurat_obj, c(0.1, 0.2, 0.3)) ``` -------------------------------- ### Example of user_restrict_to parameter usage Source: https://github.com/yrsong001/gptanno/blob/master/man/run_subcluster_annotation_workflow.Rd Demonstrates how to define per-celltype restrictions using a named list. ```R list("T cell" = c("regulatory T cell", "effector T cell"), "B cell" = c("memory B cell", "naive B cell")) ``` -------------------------------- ### Configure Alternative LLM Providers Source: https://github.com/yrsong001/gptanno/blob/master/README.md Example of using an Anthropic model with specific decoding parameters. ```r results <- gptanno( seurat_obj = your_seurat_object, resolutions = c(0.1, 0.3, 0.5), cl = cl, graph = graph, tissue_name = "mouse heart", llm_config = list( provider = "anthropic", model = "claude-sonnet-4-20250514", params = ellmer::params(temperature = 0.2, top_p = 0.9) ), marker_dir = marker_dir, n_runs = 2 ) ``` -------------------------------- ### Calculate Mean Ontology Distance Example Source: https://github.com/yrsong001/gptanno/blob/master/man/calculate_mean_ontology_distance.Rd Basic usage example for calculating mean shortest path distance between CL IDs. ```R # res <- calculate_mean_ontology_distance(clid_df, graph) ``` -------------------------------- ### Clean and Match Cell Type Annotations Source: https://github.com/yrsong001/gptanno/blob/master/man/clean_and_match_annotation.Rd Examples demonstrating the standardization of various cell type strings. ```R clean_and_match_annotation("t cell") clean_and_match_annotation("Helper T cells") clean_and_match_annotation("unknown cell") ``` -------------------------------- ### Extracting Markers from PDFs Source: https://github.com/yrsong001/gptanno/blob/master/README.md Commands to install dependencies, configure the OpenAI API key, and execute the extraction and filtering pipeline. ```bash cd pdf2markers # Install Python dependencies pip install -r requirements.txt # Set OpenAI API key export OPENAI_API_KEY="your-api-key" # Extract markers from a paper python paper_extraction_cellNgenes.py --pdf "papers/example.pdf" --out "outputs" # Filter out ontology-annotated cell types python filterout_cell_ontology.py --input-dir ./outputs ``` -------------------------------- ### Score Annotation Agreement with Detailed Match Types Source: https://github.com/yrsong001/gptanno/blob/master/man/score_annotation_agreement_ontology_detailed.Rd Example usage of the function, including the necessary one-time setup of the ontology graph and ancestor map. ```R # Setup ontology (one-time) cl <- ontologyIndex::get_ontology("http://purl.obolibrary.org/obo/cl.obo", extract_tags = "everything") graph <- build_ontology_graph(cl) cl_term_map <- build_cl_term_map(cl) ancestor_type_map <- build_ancestor_type_map(cl) # Score annotations with detailed match types results <- score_annotation_agreement_ontology_detailed( seurat_obj, manual_col = "celltype_manual", predicted_col = "celltype_predicted", cl_term_map = cl_term_map, cl_ontology = cl, graph = graph, ancestor_type_map = ancestor_type_map, output_csv = "detailed_scores.csv" ) # View summary print(results$summary) ``` -------------------------------- ### Preprocess Seurat Object Example Source: https://github.com/yrsong001/gptanno/blob/master/man/preprocess_seurat_object.Rd Demonstrates the basic usage of the function to preprocess a Seurat object and optionally save the result to an RDS file. ```R # seurat_obj <- preprocess_seurat_object(seurat_obj, save_path = "preprocessed_seurat.rds") ``` -------------------------------- ### Run Subclustering and Marker Identification Source: https://github.com/yrsong001/gptanno/blob/master/man/subcluster_and_find_markers.Rd Example usage of the subcluster_and_find_markers function, including loading the required ontology and executing the subclustering process. ```R # Load your ontology cl <- ontologyIndex::get_ontology("http://purl.obolibrary.org/obo/cl.obo", extract_tags = "everything") # Run subclustering (only for cell types with descendants) results <- subcluster_and_find_markers( seurat_obj = my_seurat, cl = cl, predicted_celltype_column = "celltype_parent", resolutions = c(0.1, 0.2, 0.3), reduction = "pca" ) ``` -------------------------------- ### Calculate Pairwise Distances Example Source: https://github.com/yrsong001/gptanno/blob/master/man/get_cl_pairwise_distances.Rd Demonstrates calculating distances between two specific Cell Ontology terms using a graph object. ```R cl <- ontologyIndex::get_ontology("http://purl.obolibrary.org/obo/cl.obo") graph <- build_ontology_graph(cl) pairs <- data.frame(from = "CL:0000066", to = "CL:0000312") distances <- get_cl_pairwise_distances(pairs, graph) print(distances) ``` -------------------------------- ### Search Cell Ontology terms using search_ols Source: https://github.com/yrsong001/gptanno/blob/master/man/search_ols.Rd Examples demonstrating basic queries, increasing result size for ambiguous terms, and automatic synonym matching. ```R # Search for a cell type name search_ols("fibroblast") # Get more suggestions for ambiguous cell types search_ols("helper T", size = 5) # Automatic synonym matching search_ols("ventricular cardiomyocyte") # Returns "ventricular cardiac muscle cell" ``` -------------------------------- ### Retrieve common ancestors for cell types Source: https://github.com/yrsong001/gptanno/blob/master/man/get_common_ancestors.Rd Demonstrates the setup of required ontology objects and the usage of get_common_ancestors to find shared ancestors between two pairs of cell types. ```R # Setup required objects cl <- ontologyIndex::get_ontology("http://purl.obolibrary.org/obo/cl.obo", extract_tags = "everything") cl_term_map <- build_cl_term_map(cl) ancestor_type_map <- build_ancestor_type_map(cl) # Get common ancestors common <- get_common_ancestors("helper T cell", "cytotoxic T cell", cl_term_map, cl, ancestor_type_map) print(common) # Check B cell vs plasma cell common2 <- get_common_ancestors("B cell", "plasma cell", cl_term_map, cl, ancestor_type_map) print(common2) ``` -------------------------------- ### Map cell types to CL IDs in R Source: https://github.com/yrsong001/gptanno/blob/master/man/map_celltypes_to_cl.Rd Example usage of the map_celltypes_to_cl function with a character vector of cell names. ```R # cell_names <- c("fibroblast", "endothelial cell") # map_celltypes_to_cl(cell_names, GPTAnno::cl_term_map) ``` -------------------------------- ### Assign Subcluster Annotations to Seurat Object Source: https://github.com/yrsong001/gptanno/blob/master/man/assign_subcluster_annotations_to_full.Rd Examples demonstrating how to apply subcluster annotations to a full Seurat object using either automatic best-resolution selection or a manual resolution map. ```R # Using auto-selected best resolutions full_seurat <- assign_subcluster_annotations_to_full( full_seurat = my_seurat, workflow_results = workflow_results, use_best = TRUE, parent_column = "celltype_parent" ) ``` ```R # Using manual resolution selection full_seurat <- assign_subcluster_annotations_to_full( full_seurat = my_seurat, workflow_results = workflow_results, use_best = FALSE, resolution_map = c("T cell" = "res_0.2", "B cell" = "res_0.1"), parent_column = "celltype_parent" ) ``` -------------------------------- ### Configure LLM Backend Source: https://github.com/yrsong001/gptanno/blob/master/vignettes/gptanno-pipeline.Rmd Set up the LLM provider and model parameters. Supports OpenAI, Anthropic, and Gemini providers. ```r Sys.setenv(OPENAI_API_KEY = "your-api-key") llm_config <- list( provider = "openai", model = "gpt-5", params = ellmer::params(temperature = 0) ) ``` ```r llm_config <- list(provider = "anthropic", model = "claude-sonnet-4-20250514") llm_config <- list(provider = "gemini", model = "gemini-2.0-flash") ``` -------------------------------- ### Load GPTAnno Dependencies Source: https://github.com/yrsong001/gptanno/blob/master/vignettes/gptanno-pipeline.Rmd Initialize the required libraries for the GPTAnno workflow. ```r library(GPTAnno) library(Seurat) library(ontologyIndex) ``` -------------------------------- ### prepare_config() Source: https://github.com/yrsong001/gptanno/blob/master/vignettes/helper-utilities.html Merges legacy model and llm_config parameters into a unified configuration object. ```APIDOC ## prepare_config(model, llm_config) ### Description Utility to merge legacy model specifications and llm_config lists into a standard configuration format. ### Parameters - **model** (string) - Optional - The model name. - **llm_config** (list) - Optional - A list containing provider and model configuration details. ``` -------------------------------- ### Initialize Cell Ontology Objects Source: https://github.com/yrsong001/gptanno/blob/master/vignettes/helper-utilities.Rmd Sets up the ontology index and associated graph and mapping structures required for downstream analysis. ```r library(ontologyIndex) cl <- get_ontology("http://purl.obolibrary.org/obo/cl.obo", extract_tags = "everything") graph <- build_ontology_graph(cl) ancestor_type_map <- build_ancestor_type_map(cl) cl_map <- build_cl_term_map(cl) ``` -------------------------------- ### Configure OpenAI LLM Backend Source: https://github.com/yrsong001/gptanno/blob/master/vignettes/gptanno-pipeline.html Set the API key and configure the LLM provider for OpenAI. ```R Sys.setenv(OPENAI_API_KEY = "your-api-key") llm_config <- list( provider = "openai", model = "gpt-5", params = ellmer::params(temperature = 0) ) ``` -------------------------------- ### Direct LLM Provider Interaction Source: https://github.com/yrsong001/gptanno/blob/master/vignettes/helper-utilities.Rmd Use prepare_config to merge model settings and call_llm to execute prompts against a specified provider. ```r cfg <- prepare_config( model = "gpt-5", llm_config = list(provider = "openai", model = "gpt-5") ) call_llm( prompt = "Reply with the word fibroblast.", provider = cfg$provider, model = cfg$model ) ``` -------------------------------- ### Initialize Ontology Graph for gptanno Source: https://github.com/yrsong001/gptanno/blob/master/man/gptanno.Rd Required steps to prepare the ontology object and graph structure before running the annotation workflow. ```R cl <- ontologyIndex::get_ontology("http://purl.obolibrary.org/obo/cl.obo", extract_tags = "everything") graph <- build_ontology_graph(cl) ``` -------------------------------- ### Configure API Credentials Source: https://github.com/yrsong001/gptanno/blob/master/PDF2markers/README.md Set the necessary environment variables for OpenAI API access. ```bash export OPENAI_API_KEY="your-api-key" export API_USER_ID="your-user-id" # Optional export API_PASSWORD="your-api-key" # Alternative to OPENAI_API_KEY ``` -------------------------------- ### Prepare LLM Configuration Usage Source: https://github.com/yrsong001/gptanno/blob/master/man/prepare_config.Rd This function merges the model name and configuration list into a single structure for the chat client. ```R prepare_config(model = "gpt-5.2", llm_config = NULL) ``` -------------------------------- ### prepare_config(model = "gpt-5.2", llm_config = NULL) Source: https://github.com/yrsong001/gptanno/blob/master/man/prepare_config.Rd Merges a model name and an optional configuration list into a unified LLM configuration structure. ```APIDOC ## prepare_config ### Description Helper function that merges a legacy model parameter with a new llm_config structure. It provides backward compatibility while supporting new multi-provider configuration. ### Signature `prepare_config(model = "gpt-5.2", llm_config = NULL)` ### Arguments - **model** (Character) - Optional. Model name (default: "gpt-5.2"). Used if llm_config is not provided. - **llm_config** (List) - Optional. Configuration containing: provider, model, params, temperature, max_tokens, api_key, api_url, system_prompt. If `params` is provided, it should be an `ellmer::params(...)` object. ### Returns - **list** - A list containing the merged LLM configuration. ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/yrsong001/gptanno/blob/master/PDF2markers/README.md Sets required and optional environment variables for API authentication and model configuration. ```bash # Required export OPENAI_API_KEY="your-api-key" # Optional export API_USER_ID="your-user-id" export API_PASSWORD="your-api-key" # Alternative to OPENAI_API_KEY export OPENAI_BASE_URL="https://api.openai.com/v1" # Custom endpoint export OPENAI_MODEL="gpt-4o-mini" # Default model ``` -------------------------------- ### Verify LLM Model Support Source: https://github.com/yrsong001/gptanno/blob/master/README.md List available models or probe a specific model configuration for parameter compatibility. ```r ellmer::models_openai() ``` ```r call_llm( prompt = "Reply with OK", provider = "openai", model = "gpt-5", params = ellmer::params(temperature = 0) ) ``` -------------------------------- ### list_ollama_models(api_url = "http://localhost:11434") Source: https://github.com/yrsong001/gptanno/blob/master/man/list_ollama_models.Rd Lists all models currently available in Ollama. Requires Ollama to be running; returns a character vector of model names or NULL if inaccessible. ```APIDOC ## list_ollama_models ### Description Lists all models currently available in Ollama. Requires Ollama to be running. ### Usage list_ollama_models(api_url = "http://localhost:11434") ### Parameters - **api_url** (Character) - Optional - Ollama API URL (default: "http://localhost:11434") ### Returns - **Character vector** - A list of model names, or NULL if Ollama is not available. ``` -------------------------------- ### Load Cell Ontology Source: https://github.com/yrsong001/gptanno/blob/master/README.md Initialize the ontology index and build the graph required for annotation. ```r library(ontologyIndex) cl <- get_ontology("http://purl.obolibrary.org/obo/cl.obo", extract_tags = "everything") graph <- build_ontology_graph(cl) ``` -------------------------------- ### Check Cell Ontology Relationship Source: https://github.com/yrsong001/gptanno/blob/master/man/check_cl_relationship.Rd Demonstrates how to retrieve the ontology, build the graph, and check the relationship between two CL IDs. ```R cl <- ontologyIndex::get_ontology("http://purl.obolibrary.org/obo/cl.obo") graph <- build_ontology_graph(cl) rel <- check_cl_relationship("CL:0000066", "CL:0000312", cl, graph) print(rel) # Should show child relationship ``` -------------------------------- ### Prepare Marker Inheritance Strategy Configuration Source: https://github.com/yrsong001/gptanno/blob/master/man/prepare_marker_inheritance_strategy.Rd Configures the marker inheritance strategy by specifying the parent marker file, the parent cell type, and the number of top genes to include. ```R config <- prepare_marker_inheritance_strategy( parent_marker_file = "output/markers/markers_res_0.3.rds", parent_celltype = "T cell", topgenenumber = 10 ) ``` -------------------------------- ### Build Ontology Objects Source: https://github.com/yrsong001/gptanno/blob/master/vignettes/gptanno-pipeline.Rmd Download and process the Cell Ontology for use in downstream analysis. ```r cl <- get_ontology("http://purl.obolibrary.org/obo/cl.obo", extract_tags = "everything") graph <- build_ontology_graph(cl) ``` -------------------------------- ### Load and inspect GPTCelltype_mapping Source: https://github.com/yrsong001/gptanno/blob/master/man/GPTCelltype_mapping.Rd Loads the mapping dataset and displays the first few entries. ```R data(GPTCelltype_mapping) head(GPTCelltype_mapping) ``` -------------------------------- ### call_llm(prompt, provider, model, params, api_key, system_prompt, api_url) Source: https://github.com/yrsong001/gptanno/blob/master/man/call_llm.Rd Sends a prompt to a specified LLM provider and returns the generated text response. ```APIDOC ## call_llm ### Description Routes prompts to OpenAI, Anthropic, Google Gemini, or local Ollama/vLLM models via the ellmer package. ### Parameters - **prompt** (Character) - Required - The prompt to send. - **provider** (Character) - Optional - One of "openai", "anthropic", "gemini", "ollama", or "vllm". - **model** (Character) - Optional - Model name (e.g., "gpt-5.2", "claude-opus-4-6", "gemini-2.0-flash"). - **params** (Object) - Optional - An ellmer params object created by ellmer::params(). - **api_key** (Character) - Optional - API key for the provider. If NULL, uses environment variables (OPENAI_API_KEY, ANTHROPIC_API_KEY, GOOGLE_API_KEY, or GEMINI_API_KEY). - **system_prompt** (Character) - Optional - System prompt to guide the model behavior. - **api_url** (Character) - Optional - API URL for local LLMs (Ollama or vLLM). Defaults to "http://localhost:11434" for Ollama and "http://localhost:8000" for vLLM. ### Returns - **Character** - The LLM response text. ``` -------------------------------- ### Annotating Datasets with GPTAnno Source: https://github.com/yrsong001/gptanno/blob/master/README.md R workflow for setting up ontology graphs, performing multi-resolution clustering, and running GPT-based cell annotation. ```r # Download dataset (example) # aging <- readRDS("path/to/Aging_preprocessed.rds") # Setup cl <- get_ontology("http://purl.obolibrary.org/obo/cl.obo", extract_tags = "everything") graph <- build_ontology_graph(cl) # Run clustering (use same path for gptanno marker_dir) marker_dir <- "output/marker_genes" cluster_results <- run_multi_resolution_clustering( seurat_obj = aging, resolutions = c(0.1, 0.3, 0.5, 0.7), result_dir = marker_dir ) aging <- cluster_results$seurat_obj # Perform repeated GPT queries for reference-free annotation results <- gptanno( seurat_obj = aging, resolutions = c(0.1, 0.3, 0.5, 0.7), cl = cl, graph = graph, tissue_name = "mouse adult heart non-cardiomyocytes", llm_config = list(provider = "openai", model = "gpt-5"), # or "gpt-4", etc. marker_dir = marker_dir, n_runs = 10 # Multiple queries enable reproducibility assessment ) ``` -------------------------------- ### prepare_marker_inheritance_strategy(parent_marker_file, parent_celltype, user_restrict_to = NULL, topgenenumber = 10) Source: https://github.com/yrsong001/gptanno/blob/master/man/prepare_marker_inheritance_strategy.Rd Configures the strategy for marker-inheritance based subcluster annotation. ```APIDOC ## prepare_marker_inheritance_strategy ### Description Configures parameters for marker-inheritance based subcluster annotation. It combines parent cluster markers with subcluster markers to define the annotation strategy. ### Signature `prepare_marker_inheritance_strategy(parent_marker_file, parent_celltype, user_restrict_to = NULL, topgenenumber = 10)` ### Parameters - **parent_marker_file** (character) - Required - Path to the parent marker RDS file. - **parent_celltype** (character) - Required - The name of the parent cell type. - **user_restrict_to** (character vector) - Optional - User-specified cell type restrictions. - **topgenenumber** (integer) - Optional - Number of top genes to include from each source (default: 10). ### Returns - **List** - A list containing the strategy configuration. ### Example ```r config <- prepare_marker_inheritance_strategy( parent_marker_file = "output/markers/markers_res_0.3.rds", parent_celltype = "T cell", topgenenumber = 10 ) ``` ``` -------------------------------- ### Extract synonyms from a string Source: https://github.com/yrsong001/gptanno/blob/master/man/extract_synonyms.Rd Demonstrates basic usage of the extract_synonyms function with a simple character input. ```R extract_synonyms("fibroblast") ``` -------------------------------- ### build_cl_term_map(cl, verbose = TRUE) Source: https://github.com/yrsong001/gptanno/blob/master/man/build_cl_term_map.Rd Constructs a lookup table mapping CL names and synonyms to CL IDs from an ontology object. ```APIDOC ## build_cl_term_map ### Description Constructs a lookup table mapping CL names and synonyms to CL IDs. ### Signature `build_cl_term_map(cl, verbose = TRUE)` ### Parameters - **cl** (ontologyIndex object) - Required - An ontologyIndex CL ontology object. - **verbose** (logical) - Optional - Print mapping stats. Defaults to TRUE. ### Returns - **data.frame** - A data frame with columns: key, clid, cl_label. ``` -------------------------------- ### run_multi_resolution_clustering(seurat_obj, resolutions, result_dir, dims, assay, group.by, reduction, use_existing_neighbors) Source: https://github.com/yrsong001/gptanno/blob/master/man/run_multi_resolution_clustering.Rd Runs graph-based clustering at multiple resolutions and finds marker genes for each, saving results to disk. ```APIDOC ## run_multi_resolution_clustering ### Description Runs graph-based clustering at multiple resolutions and finds marker genes for each, saving results to disk. ### Parameters - **seurat_obj** (Seurat object) - Required - A Seurat object. - **resolutions** (Numeric vector) - Required - Numeric vector of resolution parameters (e.g., c(0.1, 0.2, 0.3)). - **result_dir** (Character) - Optional - Directory to save marker RDS files (default: "results/markers"). - **dims** (Numeric vector) - Optional - Which dimensions to use for clustering (default: 1:30). - **assay** (Character) - Optional - Assay to use, or NULL for current (default: NULL). - **group.by** (Character) - Optional - Metadata column to use for group assignment (default: "seurat_clusters"). - **reduction** (Character) - Optional - Reduction to use for graph construction (default: "pca"). - **use_existing_neighbors** (Logical) - Optional - Use an existing neighbor graph if present (default: TRUE). ### Returns A list with: updated Seurat object, marker lists, and cluster assignments for each resolution. ### Example ```r result <- run_multi_resolution_clustering(seurat_obj, c(0.1, 0.2, 0.3)) ``` ``` -------------------------------- ### prepare_ontology_strategy(cl, parent_celltype, user_restrict_to = NULL, combine_restrictions = TRUE) Source: https://github.com/yrsong001/gptanno/blob/master/man/prepare_ontology_strategy.Rd Configures parameters for ontology-based subcluster annotation by determining the restriction list from ontology descendants and/or user input. ```APIDOC ## prepare_ontology_strategy ### Description Configures parameters for ontology-based subcluster annotation. Determines the restriction list from ontology descendants, user input, or both. ### Arguments - **cl** (ontology object) - Required. Ontology object from the ontologyIndex package. - **parent_celltype** (character) - Required. The parent cell type name. - **user_restrict_to** (character vector) - Optional. User-specified cell type restrictions. - **combine_restrictions** (logical) - Optional. Controls how restrictions are determined. If TRUE (default) and user_restrict_to is provided, returns the union of ontology descendants and the user list. If FALSE and user_restrict_to is provided, returns only the user list. If user_restrict_to is NULL, returns ontology descendants. ### Returns - **List** - Returns a list containing strategy configuration: strategy, restrict_to, parent_celltype, tissue_context, and marker_prep_fn. ### Example ```r # Combine descendants with user list config <- prepare_ontology_strategy( cl, "T cell", user_restrict_to = c("regulatory T cell", "gamma-delta T cell"), combine_restrictions = TRUE ) ``` ``` -------------------------------- ### Preprocess Seurat Object Source: https://github.com/yrsong001/gptanno/blob/master/README.md Run this optional step to normalize and prepare a Seurat object if it lacks PCA or UMAP data. ```r seurat_obj <- preprocess_seurat_object(seurat_obj, npcs = 30, save_path = NULL) # or save_path = "path/to/preprocessed.rds" ``` -------------------------------- ### Load and inspect cl_term_map Source: https://github.com/yrsong001/gptanno/blob/master/man/cl_term_map.Rd Load the dataset into the R environment and display the first few rows to verify the structure. ```R data(cl_term_map) head(cl_term_map) ``` -------------------------------- ### Constructing an igraph from an ontologyIndex object Source: https://github.com/yrsong001/gptanno/blob/master/man/build_ontology_graph.Rd Demonstrates the conversion of a Cell Ontology object into an igraph structure using parent relationships. ```R # cl <- ontologyIndex::get_ontology( # "http://purl.obolibrary.org/obo/cl.obo", # extract_tags = "everything" # ) # graph <- build_ontology_graph(cl) ``` -------------------------------- ### Run subcluster annotation workflow Source: https://github.com/yrsong001/gptanno/blob/master/vignettes/gptanno-pipeline.Rmd Execute the annotation workflow using either an ontology-constrained or marker-inheritance strategy. ```r subcluster_workflow_results <- run_subcluster_annotation_workflow( base_dir = "output/subclusters", strategy = "ontology", cl = cl, tissue_name = "mouse adult heart", resolutions = c(0.1, 0.2, 0.3), llm_config = llm_config, n_runs = 10, select_best = TRUE ) ``` ```r subcluster_workflow_results <- run_subcluster_annotation_workflow( base_dir = "output/subclusters", strategy = "marker_inheritance", cl = cl, parent_marker_root = marker_dir, parent_res = res_val, parent_cluster_col = cluster_col, tissue_name = "mouse adult heart", llm_config = llm_config, n_runs = 10 ) ``` -------------------------------- ### Run Extraction Pipeline Source: https://github.com/yrsong001/gptanno/blob/master/PDF2markers/README.md Execute the extraction script in interactive, direct, or advanced modes. ```bash python paper_extraction_cellNgenes.py ``` ```bash python paper_extraction_cellNgenes.py --pdf "path/to/your/paper.pdf" --out "outputs" ``` ```bash python paper_extraction_cellNgenes.py \ --pdf "papers/example.pdf" \ --out "outputs" \ --model "gpt-4o-mini" \ --limit 100 ``` -------------------------------- ### Configure Ollama in R Source: https://github.com/yrsong001/gptanno/blob/master/README.md Define the llm_config list to point to the local Ollama instance for use in annotation workflows. ```r llm_config = list( provider = "ollama", model = "llama3", api_url = "http://localhost:11434" ) # Use the same llm_config in gptanno(), run_subcluster_annotation_workflow(), etc. ``` -------------------------------- ### Select Best Resolution Source: https://github.com/yrsong001/gptanno/blob/master/vignettes/gptanno-pipeline.Rmd Extracts the best resolution name and corresponding object based on the composite score. ```r best_res_name <- scores$resolution[1] best_res_obj <- annotation_results[[best_res_name]] res_val <- sub("^res_", "", best_res_name) cluster_col <- paste0("cluster_res.", res_val) ``` -------------------------------- ### Run GPTAnno Workflow Source: https://github.com/yrsong001/gptanno/blob/master/README.md Perform clustering, marker gene identification, and GPT-based annotation. ```r library(GPTAnno) library(Seurat) library(ontologyIndex) library(dplyr) # Setup Sys.setenv(OPENAI_API_KEY = "your-api-key") cl <- get_ontology("http://purl.obolibrary.org/obo/cl.obo", extract_tags = "everything") graph <- build_ontology_graph(cl) # Run clustering and find markers (writes markers to result_dir) marker_dir <- "output/marker_genes" cluster_results <- run_multi_resolution_clustering( seurat_obj = your_seurat_object, resolutions = c(0.1, 0.3, 0.5), result_dir = marker_dir ) your_seurat_object <- cluster_results$seurat_obj # Run repeated GPT queries at multiple resolutions (reads markers from marker_dir) results <- gptanno( seurat_obj = your_seurat_object, resolutions = c(0.1, 0.3, 0.5), cl = cl, graph = graph, tissue_name = "mouse heart", llm_config = list( provider = "openai", model = "gpt-5" # Optionally can change params, eg. params = ellmer::params(temperature = 1) ), marker_dir = marker_dir, n_runs = 2 # Number of independent queries for reproducibility assessment ) # Evaluate resolutions with composite scoring scores <- score_annotation_resolutions(results) print(scores) # Highest composite score is optimal resolution ``` -------------------------------- ### call_llm() Source: https://github.com/yrsong001/gptanno/blob/master/vignettes/helper-utilities.html Executes a direct call to an LLM provider. ```APIDOC ## call_llm(prompt, provider, model) ### Description Directly invokes an LLM provider with a specified prompt and model configuration. ### Parameters - **prompt** (string) - Required - The text prompt to send to the LLM. - **provider** (string) - Required - The LLM provider name. - **model** (string) - Required - The specific model identifier. ``` -------------------------------- ### summarize_gptcelltype(markers, model = "gpt-5", tissue_name = "", n_runs = 2, topgenenumber = 10, add_cl_prompt = FALSE, restrict_to = NULL, parent_celltype = NULL, llm_config = NULL) Source: https://github.com/yrsong001/gptanno/blob/master/man/summarize_gptcelltype.Rd Calls an LLM multiple times for cell type annotation and summarizes the results across runs. ```APIDOC ## summarize_gptcelltype ### Description Calls LLM multiple times for cell type annotation and summarizes results. ### Parameters - **markers** (Named character vector or list) - Required - Marker genes per cluster. - **model** (Character) - Optional - Model to use (default: 'gpt-5'). - **tissue_name** (Character) - Optional - Context for prompt. - **n_runs** (Integer) - Optional - Number of LLM calls to aggregate (default: 2). - **topgenenumber** (Integer) - Optional - Number of top marker genes per cluster (default: 10). - **add_cl_prompt** (Logical) - Optional - If TRUE, adds Cell Ontology request to prompt. - **restrict_to** (Character vector) - Optional - Restrict predictions to these cell types. - **parent_celltype** (Character) - Optional - Predict child cell type of this parent. - **llm_config** (List) - Optional - LLM configuration passed to gptcelltype (supports OpenAI, Anthropic, and Google Gemini). ### Returns - **combined_results** (List) - Raw predictions from successful runs. - **summary** (Table) - Weighted summary table. - **final_summary** (Table) - Most frequent annotation per cluster. - **run_summary** (Table) - Failed runs with note column. ``` -------------------------------- ### check_ollama_available(api_url = "http://localhost:11434") Source: https://github.com/yrsong001/gptanno/blob/master/man/check_ollama_available.Rd Checks if the Ollama service is running and accessible at the provided API URL. ```APIDOC ## check_ollama_available ### Description Checks if Ollama is running and accessible at the specified URL. This function attempts to ping the Ollama API to verify connectivity. ### Signature `check_ollama_available(api_url = "http://localhost:11434")` ### Parameters - **api_url** (Character) - Optional - Ollama API URL (default: "http://localhost:11434") ### Returns - **Logical** - TRUE if Ollama is accessible, FALSE otherwise. ### Example ```r check_ollama_available() ``` ``` -------------------------------- ### Run Multi-Resolution Clustering Source: https://github.com/yrsong001/gptanno/blob/master/vignettes/gptanno-pipeline.Rmd Perform clustering across multiple resolutions and save marker gene results to the specified directory. ```r marker_dir <- "output/marker_genes" cluster_results <- run_multi_resolution_clustering( seurat_obj = seurat_obj, resolutions = c(0.1, 0.5, 0.9, 1.2), result_dir = marker_dir, dims = 1:30 ) seurat_obj <- cluster_results$seurat_obj ``` -------------------------------- ### run_subcluster_annotation_workflow(base_dir, strategy, cl, ...) Source: https://github.com/yrsong001/gptanno/blob/master/man/run_subcluster_annotation_workflow.Rd Executes the subcluster annotation workflow using specified strategies and cell-type restrictions. ```APIDOC ## run_subcluster_annotation_workflow ### Description Executes a subcluster annotation workflow. This function allows users to define annotation strategies (ontology or marker_inheritance) and apply specific cell-type restrictions to refine the annotation process. ### Parameters - **base_dir** (string) - Required - Directory path for subcluster output. - **strategy** (string) - Required - Annotation strategy to use (e.g., "ontology", "marker_inheritance"). - **cl** (object) - Required - Cluster information object. - **user_restrict_to** (list/vector) - Optional - Cell-type restrictions to apply. - **combine_restrictions** (boolean) - Optional - Whether to combine user restrictions with ontology descendants. - **tissue_name** (string) - Optional - Name of the tissue being analyzed. - **select_best** (boolean) - Optional - Whether to select the best annotation result. - **celltypes_to_subcluster** (string) - Optional - Specific cell type to target for subclustering. - **parent_marker_root** (string) - Optional - Path to parent marker files (required for marker_inheritance). - **parent_res** (string) - Optional - Resolution of the parent clustering. - **parent_cluster_col** (string) - Optional - Column name for parent cluster identifiers. ``` -------------------------------- ### Run Ontology-based Post-processing Source: https://github.com/yrsong001/gptanno/blob/master/PDF2markers/README.md Executes the filterout_cell_ontology script to process CSV files in the specified directory. ```bash python filterout_cell_ontology.py --input-dir ./outputs ``` -------------------------------- ### Standardize and Match Annotations Source: https://github.com/yrsong001/gptanno/blob/master/vignettes/helper-utilities.Rmd Standardizes raw cell labels and attempts to map them to known Cell Ontology naming conventions. ```R library(GPTAnno) clean_and_match_annotation("Helper T cells") clean_and_match_annotation("cardiomyocytes") clean_and_match_annotation("unknown cell") ``` -------------------------------- ### Multi-Resolution Clustering and Annotation Source: https://github.com/yrsong001/gptanno/blob/master/README.md Perform adaptive clustering and use GPT to annotate cell types based on ontology and marker genes. ```r # Setup ontology cl <- get_ontology("http://purl.obolibrary.org/obo/cl.obo", extract_tags = "everything") graph <- build_ontology_graph(cl) # Step 1a: Run clustering and find markers (use same path for Step 1b marker_dir) marker_dir <- "output/marker_genes" cluster_results <- run_multi_resolution_clustering( seurat_obj = seurat_obj, resolutions = c(0.1, 0.3, 0.5, 0.7), result_dir = marker_dir, dims = 1:30 ) seurat_obj <- cluster_results$seurat_obj # Step 1b: Perform repeated GPT queries for each resolution parent_results <- gptanno( seurat_obj = seurat_obj, resolutions = c(0.1, 0.3, 0.5, 0.7), cl = cl, graph = graph, tissue_name = "mouse adult heart", llm_config = list(provider = "openai", model = "gpt-5"), # or "gpt-4", etc. marker_dir = marker_dir, n_runs = 10, # Repeated queries for reproducibility measures topgenenumber = 10 ) # Step 1c: Score resolutions using composite framework scores <- score_annotation_resolutions(parent_results) print(scores) # Step 1d: Select optimal resolution and assign annotations best_res_name <- scores$resolution[1] # e.g., "res_0.3" best_res_obj <- parent_results[[best_res_name]] res_val <- sub("^res_", "", best_res_name) # Extract "0.3" cluster_col <- paste0("cluster_res.", res_val) # "cluster_res.0.3" seurat_obj <- assign_celltype( seurat_obj = seurat_obj, annotation_summary = best_res_obj, cluster_col = cluster_col, new_celltype = "celltype_parent" ) ``` -------------------------------- ### Run Marker-Inheritance Subcluster Annotation Source: https://github.com/yrsong001/gptanno/blob/master/vignettes/gptanno-pipeline.html Use this strategy for discovery-oriented subtype annotation. ```R subcluster_workflow_results <- run_subcluster_annotation_workflow( base_dir = "output/subclusters", strategy = "marker_inheritance", cl = cl, parent_marker_root = marker_dir, parent_res = res_val, parent_cluster_col = cluster_col, tissue_name = "mouse adult heart", llm_config = llm_config, n_runs = 10 ) ``` -------------------------------- ### Evaluate annotation agreement with ontology Source: https://github.com/yrsong001/gptanno/blob/master/README.md Build an ancestor map and score agreement between manual and predicted annotations. ```r ancestor_type_map <- build_ancestor_type_map(cl) agreement <- score_annotation_agreement_ontology( seurat_obj, manual_col = "celltype_manual", predicted_col = "celltype_parent", ancestor_type_map = ancestor_type_map ) print(agreement$summary) ``` -------------------------------- ### Retrieve direct parent terms for a CL ID Source: https://github.com/yrsong001/gptanno/blob/master/man/get_cl_direct_parents.Rd Demonstrates how to load the Cell Ontology and fetch direct parents for a specific CL identifier. ```R cl <- ontologyIndex::get_ontology("http://purl.obolibrary.org/obo/cl.obo") parents <- get_cl_direct_parents("CL:0000066", cl) # epithelial cell parents print(parents) # CL:0000255 eukaryotic cell ``` -------------------------------- ### build_ontology_graph(ontology) Source: https://github.com/yrsong001/gptanno/blob/master/man/build_ontology_graph.Rd Constructs an igraph directed graph from an ontologyIndex object using 'is_a' parent relationships. ```APIDOC ## build_ontology_graph ### Description Constructs an igraph directed graph from an ontologyIndex object using 'is_a' parent relationships. The resulting graph nodes are named by their ontology term IDs. ### Signature `build_ontology_graph(ontology)` ### Parameters - **ontology** (ontologyIndex object) - Required - An ontologyIndex object containing a $parents list (e.g., as returned by ontologyIndex::get_ontology()). ### Returns - **igraph** (igraph object) - A directed graph representation of the ontology. ### Example ```r # cl <- ontologyIndex::get_ontology( # "http://purl.obolibrary.org/obo/cl.obo", # extract_tags = "everything" # ) # graph <- build_ontology_graph(cl) ``` ``` -------------------------------- ### Preprocess Seurat Object Source: https://github.com/yrsong001/gptanno/blob/master/vignettes/gptanno-pipeline.Rmd Prepare the Seurat object for clustering if it has not been normalized or reduced. ```r seurat_obj <- preprocess_seurat_object( seurat_obj, npcs = 30 ) ``` -------------------------------- ### Check Ollama Availability Source: https://github.com/yrsong001/gptanno/blob/master/man/check_ollama_available.Rd Verifies if the Ollama service is reachable at the default or specified API URL. ```R check_ollama_available() ``` -------------------------------- ### assign_subcluster_annotations_to_full(full_seurat, workflow_results, use_best = TRUE, resolution_map = NULL, parent_column = "celltype_parent", final_colname = "celltype_subcluster", annotation_col_pattern = "^annotated_sub_", clean_labels = TRUE) Source: https://github.com/yrsong001/gptanno/blob/master/man/assign_subcluster_annotations_to_full.Rd Assigns subcluster annotations to a full Seurat object based on results from the subcluster annotation workflow. ```APIDOC ## assign_subcluster_annotations_to_full ### Description Unified function that works for both ontology and marker-inheritance strategies. Takes subcluster annotation results and assigns them back to the full Seurat object. ### Parameters - **full_seurat** (Seurat object) - Required - Full Seurat object (not subset). - **workflow_results** (List) - Required - List returned by run_subcluster_annotation_workflow() containing results, scores, best, and strategy. - **use_best** (Logical) - Optional - If TRUE, use best resolution per celltype. If FALSE, user must specify resolution_map. Default: TRUE. - **resolution_map** (Named vector) - Optional - Specify resolution per celltype (e.g., c("T cell" = "res_0.1")). - **parent_column** (Character) - Optional - Metadata column with parent cell type annotation. Default: "celltype_parent". - **final_colname** (Character) - Optional - Name for new annotation column. Default: "celltype_subcluster". - **annotation_col_pattern** (Character) - Optional - Pattern to find annotation column in subset. Default: "^annotated_sub_". - **clean_labels** (Logical) - Optional - Remove " (not in GO)" suffix. Default: TRUE. ### Returns - **Seurat object** - Updated full Seurat object with subcluster annotations. ``` -------------------------------- ### Retrieve direct child terms for a CL ID Source: https://github.com/yrsong001/gptanno/blob/master/man/get_cl_direct_children.Rd Demonstrates how to load the Cell Ontology and retrieve direct children for a specific ID. ```R cl <- ontologyIndex::get_ontology("http://purl.obolibrary.org/obo/cl.obo") children <- get_cl_direct_children("CL:0000066", cl) # epithelial cell children print(children) ``` -------------------------------- ### Run LLM Annotation Across Resolutions Source: https://github.com/yrsong001/gptanno/blob/master/vignettes/gptanno-pipeline.Rmd Executes repeated LLM annotations for specified clustering resolutions and saves the results to an RDS file. ```r annotation_results <- gptanno( seurat_obj = seurat_obj, resolutions = c(0.1, 0.5, 0.9, 1.2), cl = cl, graph = graph, tissue_name = "mouse adult heart", llm_config = llm_config, marker_dir = marker_dir, n_runs = 10, topgenenumber = 10 ) saveRDS(annotation_results, "annotation_results.rds") ``` -------------------------------- ### Inspect Ontology Hierarchy Source: https://github.com/yrsong001/gptanno/blob/master/vignettes/helper-utilities.Rmd Lower-level helpers for retrieving parents, children, node depths, pairwise distances, and names for CL IDs. ```r get_cl_direct_parents("CL:0000067", cl) get_cl_direct_children("CL:0000115", cl) get_cl_node_depths(c("CL:0000067", "CL:0000115"), graph) get_cl_pairwise_distances( data.frame(from = "CL:0000067", to = "CL:0000115"), graph ) get_cl_names(c("CL:0000067", "CL:0000115"), cl) ``` -------------------------------- ### Run Subcluster Annotation with Marker Inheritance Source: https://github.com/yrsong001/gptanno/blob/master/man/run_subcluster_annotation_workflow.Rd Utilize the marker inheritance strategy by providing parent cluster information and specific cell-type restrictions. ```R workflow_results <- run_subcluster_annotation_workflow( base_dir = "output/subclusters", strategy = "marker_inheritance", cl = cl, # Required for ontology distance calculation parent_marker_root = "output/markers", parent_res = "0.3", parent_cluster_col = "cluster_res.0.3", user_restrict_to = list( "T cell" = c("Treg", "Helper T cells", "cytotoxic T cell") ), tissue_name = "mouse heart" ) ``` -------------------------------- ### clean_and_match_annotation(annotation, use_ols = FALSE) Source: https://github.com/yrsong001/gptanno/blob/master/man/clean_and_match_annotation.Rd Cleans, standardizes, and maps raw cell type predictions to Cell Ontology names. ```APIDOC ## clean_and_match_annotation ### Description Cleans, standardizes, and maps raw cell type predictions to Cell Ontology names using GPTCelltype_mapping and cl_term_map. ### Signature `clean_and_match_annotation(annotation, use_ols = FALSE)` ### Parameters - **annotation** (Character) - Required - Raw annotation string (possibly mixed or ambiguous). - **use_ols** (Logical) - Optional - Whether to use OLS search as fallback (default: FALSE). Please use this with Caution. ### Returns - **Character** - Cleaned and mapped annotation string, or the original in lower singular form if not matched. ### Examples ```r clean_and_match_annotation("t cell") clean_and_match_annotation("Helper T cells") clean_and_match_annotation("unknown cell") ``` ``` -------------------------------- ### List Ollama Models Source: https://github.com/yrsong001/gptanno/blob/master/man/list_ollama_models.Rd Retrieves the list of available models from the default Ollama API endpoint. ```R list_ollama_models() ``` -------------------------------- ### map_celltypes_to_cl(terms, cl_term_map = GPTAnno::cl_term_map, verbose = TRUE) Source: https://github.com/yrsong001/gptanno/blob/master/man/map_celltypes_to_cl.Rd Maps a character vector of cell type names to CL ontology IDs using a prebuilt mapping table. ```APIDOC ## map_celltypes_to_cl ### Description Maps a character vector of cell type names to CL ontology IDs using a prebuilt mapping table. ### Parameters - **terms** (Character vector) - Required - Character vector of cell type names. - **cl_term_map** (Data.frame) - Optional - Defaults to package built-in map, or returned by build_cl_term_map(). - **verbose** (Logical) - Optional - Print mapping results. ### Returns - **Data.frame** - Returns a data frame with columns: term, clid, cl_label. ``` -------------------------------- ### Check Cell Type Relationships Source: https://github.com/yrsong001/gptanno/blob/master/vignettes/helper-utilities.Rmd Compares two CL IDs to determine their hierarchical relationship. ```r check_cl_relationship("CL:0000066", "CL:0000312", cl, graph) ``` -------------------------------- ### Score Annotation Resolutions Source: https://github.com/yrsong001/gptanno/blob/master/vignettes/helper-utilities.Rmd Computes a composite score to rank annotation strategies. ```r score_annotation_resolutions(annotation_result_list) ```