diff --git a/CHANGELOG.md b/CHANGELOG.md index 0d076c8b..7dd74ae9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,20 @@ ## Unreleased +### Changed + +- **#644. UMAP layout is explicit; embeddings do not change.** `embedding._umap` now passes + `compatibility_layout=True` to `umap.UMAP`, for the maps' UMAP and the UMAP the populations + (question 10) are clustered on. `True` is the umap-learn 0.5 layout and the 0.6 default, + so the same data, settings and seed give the same embeddings and populations as before; + the value is now explicit, so a later umap-learn default cannot change them silently. It is + recorded as `compatibility_layout` in the settings of `embed` and `find_populations`. The + floor is now `umap-learn>=0.6`. `False` (the layout umap-learn plans as its default) is + deferred: in a test with 2160 Gaussian cells and a 240-cell blob, HDBSCAN found 2 clusters + (2161 and 239 cells) with `True` and 41 with `False` (largest 358 cells, 300 unassigned), + so no main population was named. It is to be revisited with a retuning of the populations. + No cache or run identity includes the UMAP settings and no embedding is cached. + ### Removed (compatibility sweep, 2026-11-13) The code is not in production yet, so compatibility paths for earlier outputs are removed. diff --git a/docs/common/function_index.jsonl b/docs/common/function_index.jsonl index 2a107434..a297afb6 100644 --- a/docs/common/function_index.jsonl +++ b/docs/common/function_index.jsonl @@ -540,10 +540,10 @@ {"arguments": 3, "called_by": ["embedding:combined"], "calls": ["?.get", "float", "numpy.array"], "complexity": 2, "decorators": [], "hash": "6350435497b193b8", "kind": "function", "lines": 3, "module": "embedding", "name": "weighted", "public": true, "signature": "(z: np.ndarray, features: Sequence[str], weights: Mapping[str, float] | None) -> np.ndarray", "summary": "``z`` with each column times its feature's weight (1 when not given); ``z`` itself", "varargs": []} {"arguments": 1, "called_by": ["embedding:embed"], "calls": ["?.mean", "?.sum", "float", "len", "min", "numpy.abs", "numpy.argmax", "numpy.column_stack", "numpy.linalg.svd", "numpy.zeros", "numpy.zeros_like", "range"], "complexity": 7, "decorators": [], "hash": "f2f4db062b29496e", "kind": "function", "lines": 15, "module": "embedding", "name": "_pca", "public": false, "signature": "(z: np.ndarray) -> tuple[np.ndarray, np.ndarray, tuple[float, float]]", "summary": "The first two principal components, the loadings and the shares of variance.", "varargs": []} {"arguments": 3, "called_by": ["embedding:_add_umap", "sampling_unit.populations:_clusters", "separation:_group_rows"], "calls": ["?.append", "?.choice", "len", "max", "numpy.arange", "numpy.concatenate", "numpy.flatnonzero", "numpy.sort", "pandas.unique", "round"], "complexity": 3, "decorators": [], "hash": "446b0e7775ce5020", "kind": "function", "lines": 9, "module": "embedding", "name": "_sample", "public": false, "signature": "(conditions: np.ndarray, max_points: int, rng: np.random.Generator) -> np.ndarray", "summary": "Indices of a sample of the same share of every condition, ``max_points`` in all.", "varargs": []} -{"arguments": 16, "called_by": ["workflows._html_maps:_maps", "workflows.figures:embedding_plots"], "calls": ["?.any", "?.feature_matrix", "?.fromkeys", "?.items", "?.sum", "ValueError", "_checks:as_count", "_checks:check_seed", "data_check:validate_input_tables", "dict", "embedding:Embedding", "embedding:_add_umap", "embedding:_pca", "embedding:_points", "embedding:_standardised", "embedding:combined", "feature_tables:table_shares", "float", "int", "len", "list", "numpy.isnan", "pandas.DataFrame", "schema:fov_positions", "set", "sum", "zip"], "complexity": 6, "decorators": [], "hash": "9c699109d16d9825", "kind": "function", "lines": 57, "module": "embedding", "name": "embed", "public": true, "signature": "(objects: pd.DataFrame, fovs: pd.DataFrame, *, features: Sequence[str], top: Sequence[str]=(), carry: Sequence[str]=(), umap: bool=True, max_points: int=MAX_POINTS, n_neighbors: int=N_NEIGHBORS, min_dist: float=MIN_DIST, random_state: int=0, fov_col: str | None=None, group_cols: Sequence[str] | None=None, observation_unit: str | None=None, weights: Mapping[str, float] | None=None, standardised: Sequence[str] | None=None, blocks: Mapping[str, Sequence[str]] | None=None) -> Embedding", "summary": "PCA (and, with ``umap``, UMAP) of ``features`` (see the module); needs at least", "varargs": []} +{"arguments": 16, "called_by": ["workflows._html_maps:_maps", "workflows.figures:embedding_plots"], "calls": ["?.any", "?.feature_matrix", "?.fromkeys", "?.items", "?.sum", "ValueError", "_checks:as_count", "_checks:check_seed", "data_check:validate_input_tables", "dict", "embedding:Embedding", "embedding:_add_umap", "embedding:_pca", "embedding:_points", "embedding:_standardised", "embedding:combined", "feature_tables:table_shares", "float", "int", "len", "list", "numpy.isnan", "pandas.DataFrame", "schema:fov_positions", "set", "sum", "zip"], "complexity": 6, "decorators": [], "hash": "4b062f6782720fc3", "kind": "function", "lines": 58, "module": "embedding", "name": "embed", "public": true, "signature": "(objects: pd.DataFrame, fovs: pd.DataFrame, *, features: Sequence[str], top: Sequence[str]=(), carry: Sequence[str]=(), umap: bool=True, max_points: int=MAX_POINTS, n_neighbors: int=N_NEIGHBORS, min_dist: float=MIN_DIST, random_state: int=0, fov_col: str | None=None, group_cols: Sequence[str] | None=None, observation_unit: str | None=None, weights: Mapping[str, float] | None=None, standardised: Sequence[str] | None=None, blocks: Mapping[str, Sequence[str]] | None=None) -> Embedding", "summary": "PCA (and, with ``umap``, UMAP) of ``features`` (see the module); needs at least", "varargs": []} {"arguments": 8, "called_by": ["embedding:embed"], "calls": ["?.reset_index", "?.to_numpy", "enumerate", "len", "numpy.full", "pandas.DataFrame", "pandas.RangeIndex", "set"], "complexity": 9, "decorators": [], "hash": "3fd703743d9e6c12", "kind": "function", "lines": 21, "module": "embedding", "name": "_points", "public": false, "signature": "(data: ValidatedInput, positions: np.ndarray, complete: np.ndarray, kept_features: list[str], z: np.ndarray, scores: np.ndarray, carry: Sequence[str], standardised: Sequence[str] | None) -> pd.DataFrame", "summary": "One row per complete observation: its condition, repeat and field, where it came", "varargs": []} {"arguments": 6, "called_by": ["embedding:embed"], "calls": ["?.to_numpy", "embedding:_sample", "embedding:_umap", "len", "numpy.random.default_rng", "numpy.zeros"], "complexity": 2, "decorators": [], "hash": "50a98ca0f6a5a923", "kind": "function", "lines": 7, "module": "embedding", "name": "_add_umap", "public": false, "signature": "(points: pd.DataFrame, z: np.ndarray, max_points: int, n_neighbors: int, min_dist: float, random_state: int) -> int", "summary": "Fill the UMAP columns of a sample of ``points`` of the same share of every", "varargs": []} -{"arguments": 5, "called_by": ["embedding:_add_umap", "sampling_unit.populations:_embedding"], "calls": ["?.fit_transform", "len", "max", "min", "umap.UMAP", "warnings.catch_warnings", "warnings.simplefilter"], "complexity": 1, "decorators": [], "hash": "f90d81766ba4d31b", "kind": "function", "lines": 16, "module": "embedding", "name": "_umap", "public": false, "signature": "(z: np.ndarray, n_neighbors: int, min_dist: float, random_state: int, n_components: int=2) -> np.ndarray", "summary": "UMAP coordinates of ``z`` in ``n_components`` dimensions, on one thread for the seed", "varargs": []} +{"arguments": 5, "called_by": ["embedding:_add_umap", "sampling_unit.populations:_embedding"], "calls": ["?.fit_transform", "len", "max", "min", "umap.UMAP", "warnings.catch_warnings", "warnings.simplefilter"], "complexity": 1, "decorators": [], "hash": "29fd5ead50b0da0e", "kind": "function", "lines": 17, "module": "embedding", "name": "_umap", "public": false, "signature": "(z: np.ndarray, n_neighbors: int, min_dist: float, random_state: int, n_components: int=2) -> np.ndarray", "summary": "UMAP coordinates of ``z`` in ``n_components`` dimensions, on one thread for the seed", "varargs": []} {"calls": [], "kind": "module", "module": "evaluator", "name": "", "public": true, "summary": "Strategy execution utilities: analysis groups, isolated inputs, timing and results."} {"arguments": 1, "called_by": ["evaluator:restrict_input"], "calls": ["?.remove_unused_categories", "?.reset_index", "?.select_dtypes"], "complexity": 2, "decorators": [], "hash": "d4b16609a7a77afd", "kind": "function", "lines": 4, "module": "evaluator", "name": "_visible_table", "public": false, "signature": "(table: pd.DataFrame) -> pd.DataFrame", "summary": "Return a copy exposing nothing about rows that were removed.", "varargs": []} {"arguments": 1, "called_by": ["evaluator:IncrementalReplay.__init__", "evaluator:IncrementalReplay.step", "evaluator:_recompute"], "calls": ["?.copy", "?.with_tables"], "complexity": 1, "decorators": [], "hash": "1993e40b9fa2607a", "kind": "function", "lines": 1, "module": "evaluator", "name": "_isolated_input", "public": false, "signature": "(data: ValidatedInput) -> ValidatedInput", "summary": "A deep copy of the input tables for one strategy call.", "varargs": []} @@ -1979,7 +1979,7 @@ {"called_by": ["sampling_unit.populations:_clusters"], "calls": [], "decorators": [], "hash": "cb6be258e0ea56a5", "kind": "class", "module": "sampling_unit.populations", "name": "_Clusters", "public": false, "signature": "(NamedTuple)", "summary": "Each complete observation's cluster (``raw``, -1 unassigned), its field's row of the"} {"arguments": 5, "called_by": ["sampling_unit.populations:find_populations"], "calls": ["?.query", "?.reset_index", "?.sum", "?.to_numpy", "_checks:as_count", "bool", "embedding:_sample", "int", "len", "max", "numpy.arange", "numpy.full", "numpy.random.default_rng", "numpy.setdiff1d", "numpy.zeros", "round", "sampling_unit.populations:_Clusters", "sampling_unit.populations:_cluster", "sampling_unit.populations:_components", "sampling_unit.populations:_embedding", "schema:fov_positions", "scipy.spatial.cKDTree"], "complexity": 10, "decorators": [], "hash": "5a0cad8bcfb03254", "kind": "function", "lines": 22, "module": "sampling_unit.populations", "name": "_clusters", "public": false, "signature": "(data: ValidatedInput, space: _Space, min_cells: int | None, max_points: int, random_state: int) -> _Clusters", "summary": "HDBSCAN on the UMAP of at most ``max_points`` observations, balanced over the", "varargs": []} {"arguments": 7, "called_by": ["sampling_unit.populations:find_populations"], "calls": ["?.code", "?.mean", "?.nunique", "?.sum", "?.words", "float", "int", "pandas.Series", "sampling_unit._population_rule:Rule", "sampling_unit._population_rule:population_rule", "sampling_unit.populations:_defining", "sampling_unit.populations:_support", "sampling_unit.populations:defined_by"], "complexity": 5, "decorators": [], "hash": "720ce301eab57173", "kind": "function", "lines": 34, "module": "sampling_unit.populations", "name": "_population_row", "public": false, "signature": "(space: _Space, meta: pd.DataFrame, keys: Any, member: np.ndarray, name: str, judged: tuple[str | None, float], random_state: int) -> dict[str, Any]", "summary": "One population's row: its size, fields and repeats, the features that set it apart", "varargs": []} -{"arguments": 7, "called_by": ["sampling_unit.populations:find_populations"], "calls": ["?.items", "?.mean", "?.sum", "dict", "float", "int", "len", "list", "max", "min", "numpy.isin"], "complexity": 4, "decorators": [], "hash": "1ce5f1ff46f15c26", "kind": "function", "lines": 21, "module": "sampling_unit.populations", "name": "_settings", "public": false, "signature": "(data: ValidatedInput, space: _Space, clusters: _Clusters, names: dict[int, str], random_state: int, weights: Mapping[str, float] | None, blocks: Mapping[str, Sequence[str]] | None) -> dict[str, Any]", "summary": "The settings of ``find_populations``: what was clustered and how.", "varargs": []} +{"arguments": 7, "called_by": ["sampling_unit.populations:find_populations"], "calls": ["?.items", "?.mean", "?.sum", "dict", "float", "int", "len", "list", "max", "min", "numpy.isin"], "complexity": 4, "decorators": [], "hash": "4d9d9c1436b35257", "kind": "function", "lines": 22, "module": "sampling_unit.populations", "name": "_settings", "public": false, "signature": "(data: ValidatedInput, space: _Space, clusters: _Clusters, names: dict[int, str], random_state: int, weights: Mapping[str, float] | None, blocks: Mapping[str, Sequence[str]] | None) -> dict[str, Any]", "summary": "The settings of ``find_populations``: what was clustered and how.", "varargs": []} {"calls": [], "kind": "module", "module": "sampling_unit.ranking", "name": "", "public": true, "summary": "Which features separate the conditions? A gated ranking to choose what to plot."} {"called_by": ["retrospective.report:", "sampling_unit.ranking:feature_ranking", "workflows.figures:plots"], "calls": ["_frozen:owned", "dataclasses.dataclass"], "decorators": ["owned('tests', 'ranking', 'settings')", "dataclass(frozen=True)"], "hash": "4bb808ad7cc7d33d", "kind": "class", "module": "sampling_unit.ranking", "name": "FeatureRanking", "public": true, "signature": "()", "summary": "The gated tests and the ranking they give."} {"arguments": 0, "called_by": ["sampling_unit.ranking:FeatureRanking._cautions"], "calls": ["?.append", "?.format", "?.idxmax", "?.max", "?.notna", "float", "int", "len", "sampling_unit.ranking:_consequence"], "complexity": 4, "decorators": [], "hash": "b452de448b950884", "kind": "method", "lines": 24, "module": "sampling_unit.ranking", "name": "FeatureRanking._floors", "public": false, "signature": "(self) -> list[str]", "summary": "Sentences on the smallest p-value the tests can give, where it limits the gate.", "varargs": []} diff --git a/pyproject.toml b/pyproject.toml index fcc4685f..461fa6ca 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -16,7 +16,7 @@ dependencies = [ "pandas>=2.0", "scikit-learn>=1.3", "scipy>=1.11", - "umap-learn>=0.5", + "umap-learn>=0.6", ] [project.optional-dependencies] diff --git a/src/morphocoverage/embedding.py b/src/morphocoverage/embedding.py index 127ecb0a..19d33e8b 100644 --- a/src/morphocoverage/embedding.py +++ b/src/morphocoverage/embedding.py @@ -55,6 +55,12 @@ MAX_POINTS = 5000 N_NEIGHBORS = 15 MIN_DIST = 0.1 +# umap-learn 0.6's ``compatibility_layout`` (owner, 2026-11-26, #644): True is the 0.5 layout +# and today's default; it is passed explicitly so no installed version decides it, and the +# embeddings and populations are as before. ``False`` (the layout umap-learn plans as its +# default) split one Gaussian cloud into 41 HDBSCAN clusters and named no main population, so +# it waits for the populations to be retuned with it. +COMPATIBILITY_LAYOUT = True # The MorphoBricks column naming an object within its image (CellPatcher's patches). LABEL_COLUMN = "label_id" @@ -239,6 +245,7 @@ def embed( "umap_points": sampled, "n_neighbors": n_neighbors, "min_dist": float(min_dist), + "compatibility_layout": COMPATIBILITY_LAYOUT, "random_state": random_state, "observation_unit": data.observation_unit, "observation_unit_declared": data.observation_unit_declared, @@ -325,6 +332,7 @@ def _umap( n_components=n_components, random_state=random_state, n_jobs=1, + compatibility_layout=COMPATIBILITY_LAYOUT, ) with warnings.catch_warnings(): # fallback: umap-learn warns that a seed disables its parallelism: the point here diff --git a/src/morphocoverage/sampling_unit/populations.py b/src/morphocoverage/sampling_unit/populations.py index 81d804a7..cf76be66 100644 --- a/src/morphocoverage/sampling_unit/populations.py +++ b/src/morphocoverage/sampling_unit/populations.py @@ -60,7 +60,7 @@ from .._checks import as_count, check_seed from .._frozen import owned from .._identity import canonical_row_codes, row_keys -from ..embedding import _sample, _standardised, _umap, combined +from ..embedding import COMPATIBILITY_LAYOUT, _sample, _standardised, _umap, combined from ..metadata import CONDITION_COLUMN, REPEAT_COLUMN, TECHNICAL_REPEAT_COLUMN, column_names from ..schema import ValidatedInput, fov_positions, validate_input_tables from ..statistics import cohen_d @@ -449,6 +449,7 @@ def _settings( "components": clusters.components, "variance": VARIANCE, "map_components": min(MAP_COMPONENTS, max(2, len(kept))), + "compatibility_layout": COMPATIBILITY_LAYOUT, "min_cells": int(clusters.size), "purity": PURITY, "neighbours": NEIGHBOURS, diff --git a/tests/test_embedding.py b/tests/test_embedding.py index 10dc994c..b0564b93 100644 --- a/tests/test_embedding.py +++ b/tests/test_embedding.py @@ -2,6 +2,8 @@ from __future__ import annotations +from typing import ClassVar + import numpy as np import pandas as pd @@ -73,3 +75,43 @@ def test_75_the_condition_labels_do_not_change_the_loadings(): caption, _ = _pca_caption(*_shared_axis_tables()) relabelled, _ = _pca_caption(*_shared_axis_tables(("drug", "ctrl"))) assert caption == relabelled + + +class _RecordingUMAP: + """Stands in for ``umap.UMAP``: keeps the keyword arguments it was built with.""" + + calls: ClassVar[list[dict]] = [] + + def __init__(self, **kwargs): + type(self).calls.append(kwargs) + + def fit_transform(self, z): + return np.zeros((len(z), type(self).calls[-1]["n_components"])) + + +def test_umap_is_built_with_compatibility_layout_explicitly(monkeypatch): + """umap-learn 0.6 plans to change the default of ``compatibility_layout``; the layout must + not depend on the installed version, so the argument is always passed, as True (today's + layout).""" + import umap + + from morphocoverage.sampling_unit.populations import _embedding + + _RecordingUMAP.calls = [] + monkeypatch.setattr(umap, "UMAP", _RecordingUMAP) + objects, fovs = _shared_axis_tables() + embed(objects, fovs, features=["a", "b", "e", "g"], max_points=100) + _embedding(np.random.default_rng(0).normal(size=(60, 4)), 0) + assert len(_RecordingUMAP.calls) == 2 # the maps' UMAP and the populations' UMAP + for kwargs in _RecordingUMAP.calls: + assert "compatibility_layout" in kwargs + assert kwargs["compatibility_layout"] is True + + +def test_the_settings_record_the_umap_layout(): + """The layout changes the coordinates, so the run's settings say which one made them.""" + objects, fovs = _shared_axis_tables() + embedding = embed(objects, fovs, features=["a", "b", "e", "g"], max_points=100) + assert embedding.settings["compatibility_layout"] is True + without_umap = embed(objects, fovs, features=["a", "b", "e", "g"], umap=False) + assert without_umap.settings["compatibility_layout"] is True diff --git a/tests/test_populations.py b/tests/test_populations.py index bf31eb67..1fc6b1b0 100644 --- a/tests/test_populations.py +++ b/tests/test_populations.py @@ -171,6 +171,12 @@ def test_no_group_found_is_said_neutrally(): assert status is not Status.OK +def test_the_settings_record_the_umap_layout_the_populations_were_found_on(): + objects, fovs = _screen() + found = find_populations(objects, fovs, features=FEATURES, observation_unit="cell") + assert found.settings["compatibility_layout"] is True + + def test_above_the_sample_size_every_cell_still_gets_a_population(): objects, fovs = _screen() full = find_populations(objects, fovs, features=FEATURES, observation_unit="cell")