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
| Name | Required | Description | Default |
|---|---|---|---|
| n_neighbors | No | Size of local neighborhood used for manifold approximation. | |
| n_pcs | No | Number of PCs to use. If None, automatically determined. | |
| use_rep | No | Key for .obsm to use as representation. | |
| knn | No | Whether to use hard threshold for neighbor restriction. | |
| method | No | Method for computing connectivities ('umap' or 'gauss'). | umap |
| transformer | No | Approximate kNN search implementation ('pynndescent' or 'rapids'). | |
| metric | No | Distance metric to use. | euclidean |
| metric_kwds | No | Options for the distance metric. | |
| random_state | No | Random seed for reproducibility. | |
| key_added | No | Key prefix for storing neighbor results. |
Implementation Reference
- src/scmcp/tool/pp.py:120-136 (handler)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
- src/scmcp/schema/pp.py:498-574 (schema)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
- src/scmcp/tool/pp.py:81-85 (registration)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(), )
- src/scmcp/tool/pp.py:88-101 (helper)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, }
- src/scmcp/server.py:67-76 (helper)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)