Skip to main content
Glama

neighbors

Compute nearest neighbors distance matrix and neighborhood graph for single-cell RNA sequencing analysis to identify local cellular relationships and enable downstream manifold learning.

Instructions

Compute nearest neighbors distance matrix and neighborhood graph

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
n_neighborsNoSize of local neighborhood used for manifold approximation.
n_pcsNoNumber of PCs to use. If None, automatically determined.
use_repNoKey for .obsm to use as representation.
knnNoWhether to use hard threshold for neighbor restriction.
methodNoMethod for computing connectivities ('umap' or 'gauss').umap
transformerNoApproximate kNN search implementation ('pynndescent' or 'rapids').
metricNoDistance metric to use.euclidean
metric_kwdsNoOptions for the distance metric.
random_stateNoRandom seed for reproducibility.
key_addedNoKey prefix for storing neighbor results.

Implementation Reference

  • Generic handler that executes the 'neighbors' tool by dispatching to sc.pp.neighbors via the pp_func mapping on the active AnnData object.
    def run_pp_func(ads, func, arguments): adata = ads.adata_dic[ads.active] if func not in pp_func: raise ValueError(f"不支持的函数: {func}") run_func = pp_func[func] parameters = inspect.signature(run_func).parameters arguments["inplace"] = True kwargs = {k: arguments.get(k) for k in parameters if k in arguments} try: res = run_func(adata, **kwargs) add_op_log(adata, run_func, kwargs) except KeyError as e: raise KeyError(f"Can not foud {e} column in adata.obs or adata.var") except Exception as e: raise e return res
  • Pydantic input schema (NeighborsModel) for validating parameters of the 'neighbors' tool.
    class NeighborsModel(JSONParsingModel): """Input schema for the neighbors graph construction tool.""" n_neighbors: int = Field( default=15, description="Size of local neighborhood used for manifold approximation.", gt=1, le=100 ) n_pcs: Optional[int] = Field( default=None, description="Number of PCs to use. If None, automatically determined.", ge=0 ) use_rep: Optional[str] = Field( default=None, description="Key for .obsm to use as representation." ) knn: bool = Field( default=True, description="Whether to use hard threshold for neighbor restriction." ) method: Literal['umap', 'gauss'] = Field( default='umap', description="Method for computing connectivities ('umap' or 'gauss')." ) transformer: Optional[str] = Field( default=None, description="Approximate kNN search implementation ('pynndescent' or 'rapids')." ) metric: str = Field( default='euclidean', description="Distance metric to use." ) metric_kwds: Dict[str, Any] = Field( default_factory=dict, description="Options for the distance metric." ) random_state: int = Field( default=0, description="Random seed for reproducibility." ) key_added: Optional[str] = Field( default=None, description="Key prefix for storing neighbor results." ) @field_validator('n_neighbors', 'n_pcs') def validate_positive_integers(cls, v: Optional[int]) -> Optional[int]: """Validate positive integers where applicable""" if v is not None and v <= 0: raise ValueError("must be a positive integer") return v @field_validator('method') def validate_method(cls, v: str) -> str: """Validate method is supported""" if v not in ['umap', 'gauss']: raise ValueError("method must be either 'umap' or 'gauss'") return v @field_validator('transformer') def validate_transformer(cls, v: Optional[str]) -> Optional[str]: """Validate transformer option is supported""" if v is not None and v not in ['pynndescent', 'rapids']: raise ValueError("transformer must be either 'pynndescent' or 'rapids'") return v
  • MCP tool registration for 'neighbors' using types.Tool with schema reference.
    neighbors = types.Tool( name="neighbors", description="Compute nearest neighbors distance matrix and neighborhood graph", inputSchema=NeighborsModel.model_json_schema(), )
  • Dictionary mapping 'neighbors' tool name to the actual scanpy.pp.neighbors function implementation.
    pp_func = { "filter_genes": sc.pp.filter_genes, "filter_cells": sc.pp.filter_cells, "calculate_qc_metrics": partial(sc.pp.calculate_qc_metrics, inplace=True), "log1p": sc.pp.log1p, "normalize_total": sc.pp.normalize_total, "pca": sc.pp.pca, "highly_variable_genes": sc.pp.highly_variable_genes, "regress_out": sc.pp.regress_out, "scale": sc.pp.scale, "combat": sc.pp.combat, "scrublet": sc.pp.scrublet, "neighbors": sc.pp.neighbors, }
  • Dispatch in top-level call_tool handler to route 'neighbors' (pp tools) to run_pp_func.
    elif name in pp_tools.keys(): res = run_pp_func(ads, name, arguments) elif name in tl_tools.keys(): res = run_tl_func(ads, name, arguments) elif name in pl_tools.keys(): res = run_pl_func(ads, name, arguments) elif name in util_tools.keys(): res = run_util_func(ads, name, arguments) elif name in ccc_tools.keys(): res = run_ccc_func(ads.adata_dic[ads.active], name, arguments)

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/huang-sh/scmcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server