gotmap 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
gotmap/pl.py ADDED
@@ -0,0 +1,232 @@
1
+ """
2
+ gotmap.pl - Plotting (scanpy-compatible).
3
+
4
+ Functions:
5
+ mapping_scatter(adata, ...)
6
+ label_transfer_confidence(adata, ...)
7
+ embedding(adata, ...)
8
+ sanity_check(adata, ...)
9
+ """
10
+
11
+ import numpy as np
12
+ import scipy.sparse as sp
13
+ import scanpy as sc
14
+ import scanpy.plotting as scpl
15
+ from matplotlib import pyplot as plt
16
+ import matplotlib as mpl
17
+
18
+
19
+ def mapping_scatter(
20
+ adata,
21
+ basis="X_gotmap",
22
+ color=None,
23
+ groups=None,
24
+ save=None,
25
+ **kwargs,
26
+ ):
27
+ """
28
+ Scatter plot of mapped query cells in reference space.
29
+
30
+ Parameters
31
+ ----------
32
+ adata : AnnData
33
+ Query data with .obsm[basis].
34
+ basis : str
35
+ Key in .obsm for coordinates (default: 'X_gotmap').
36
+ color : str or list
37
+ Keys in .obs to color by.
38
+ groups : str or list
39
+ Subset of categories to show.
40
+ save : str or None
41
+ If given, save figure to this path.
42
+ """
43
+ if basis not in adata.obsm:
44
+ raise ValueError(f"{basis} not in adata.obsm. Run map_query_to_reference first.")
45
+
46
+ sc.pl.embedding(
47
+ adata, basis=basis, color=color, groups=groups,
48
+ show=False, **kwargs
49
+ )
50
+ if save:
51
+ plt.savefig(save, dpi=150, bbox_inches="tight")
52
+ plt.show()
53
+
54
+
55
+ def label_transfer_confidence(
56
+ adata,
57
+ label_key,
58
+ confidence_key=None,
59
+ save=None,
60
+ **kwargs,
61
+ ):
62
+ """
63
+ Visualize label transfer confidence.
64
+
65
+ Parameters
66
+ ----------
67
+ adata : AnnData
68
+ label_key : str
69
+ The predicted label column (without '_predicted' suffix).
70
+ confidence_key : str or None
71
+ Confidence column. If None, uses f"{label_key}_confidence".
72
+ """
73
+ if confidence_key is None:
74
+ confidence_key = f"{label_key}_confidence"
75
+
76
+ if confidence_key not in adata.obs:
77
+ raise ValueError(
78
+ f"{confidence_key} not found. Run transfer_labels first."
79
+ )
80
+
81
+ pred_key = f"{label_key}_predicted"
82
+ if pred_key in adata.obs:
83
+ fig, axes = plt.subplots(1, 2, figsize=(12, 5))
84
+
85
+ # histogram of confidence
86
+ ax = axes[0]
87
+ conf = adata.obs[confidence_key].astype(float)
88
+ ax.hist(conf, bins=30, color="#4C72B0", edgecolor="white", alpha=0.8)
89
+ ax.axvline(conf.median(), color="red", linestyle="--",
90
+ label=f"median={conf.median():.2f}")
91
+ ax.set_xlabel("Mapping Confidence")
92
+ ax.set_ylabel("Cell count")
93
+ ax.set_title("Confidence Distribution")
94
+ ax.legend()
95
+
96
+ # confidence by predicted label
97
+ ax = axes[1]
98
+ cats = adata.obs[pred_key].value_counts().index
99
+ conf_by_cat = [
100
+ adata.obs.loc[adata.obs[pred_key] == c, confidence_key].astype(float).values
101
+ for c in cats
102
+ ]
103
+ bp = ax.boxplot(conf_by_cat, labels=cats, patch_artist=True)
104
+ for patch in bp["boxes"]:
105
+ patch.set_facecolor("#DD8452")
106
+ ax.set_ylabel("Confidence")
107
+ ax.set_title("Confidence by Predicted Label")
108
+ plt.setp(ax.xaxis.get_majorticklabels(), rotation=45, ha="right")
109
+ else:
110
+ fig, ax = plt.subplots(figsize=(6, 5))
111
+ conf = adata.obs[confidence_key].astype(float)
112
+ ax.hist(conf, bins=30, color="#4C72B0", edgecolor="white", alpha=0.8)
113
+ ax.axvline(conf.median(), color="red", linestyle="--",
114
+ label=f"median={conf.median():.2f}")
115
+ ax.set_xlabel("Mapping Confidence")
116
+ ax.set_ylabel("Cell count")
117
+ ax.set_title("Mapping Confidence Distribution")
118
+ ax.legend()
119
+
120
+ plt.tight_layout()
121
+ if save:
122
+ plt.savefig(save, dpi=150, bbox_inches="tight")
123
+ plt.show()
124
+
125
+
126
+ def embedding(
127
+ adata,
128
+ basis="X_gotmap",
129
+ color=None,
130
+ title=None,
131
+ save=None,
132
+ **kwargs,
133
+ ):
134
+ """
135
+ Generic embedding scatter (wraps scanpy.pl.embedding).
136
+
137
+ Parameters
138
+ ----------
139
+ adata : AnnData
140
+ basis : str
141
+ Key in .obsm.
142
+ color : str or list
143
+ Color by obs key(s).
144
+ title : str or None
145
+ save : str or None
146
+ """
147
+ if basis not in adata.obsm:
148
+ raise ValueError(f"{basis} not found in adata.obsm")
149
+
150
+ sc.pl.embedding(adata, basis=basis, color=color, show=False, **kwargs)
151
+ if title:
152
+ plt.title(title)
153
+ if save:
154
+ plt.savefig(save, dpi=150, bbox_inches="tight")
155
+ plt.show()
156
+
157
+
158
+ def sanity_check(
159
+ reference,
160
+ query,
161
+ mapped_query=None,
162
+ label_key=None,
163
+ figsize=(16, 4),
164
+ save=None,
165
+ ):
166
+ """
167
+ Quick visual sanity check: reference vs mapped query overlay.
168
+
169
+ Parameters
170
+ ----------
171
+ reference : AnnData
172
+ Reference atlas.
173
+ query : AnnData
174
+ Original query.
175
+ mapped_query : AnnData or None
176
+ Query with .obsm['X_gotmap']. If None, only shows reference.
177
+ label_key : str or None
178
+ If given, color reference points by this label.
179
+ """
180
+ n_panels = 3 if mapped_query is not None else 1
181
+ fig, axes = plt.subplots(1, n_panels, figsize=figsize)
182
+
183
+ if n_panels == 1:
184
+ axes = [axes]
185
+
186
+ # panel 1: reference
187
+ ax = axes[0]
188
+ ref_pca = reference.obsm.get("X_pca")
189
+ if ref_pca is None:
190
+ raise ValueError("reference has no X_pca")
191
+ ax.scatter(ref_pca[:, 0], ref_pca[:, 1],
192
+ s=1, c="#4C72B0", alpha=0.5, label="reference")
193
+ if label_key and label_key in reference.obs:
194
+ cats = reference.obs[label_key].unique()
195
+ cmap = plt.cm.get_cmap("tab20", len(cats))
196
+ for i, c in enumerate(cats):
197
+ mask = reference.obs[label_key] == c
198
+ ax.scatter(ref_pca[mask.values, 0], ref_pca[mask.values, 1],
199
+ s=1, color=cmap(i), alpha=0.6, label=c)
200
+ ax.set_title("Reference Atlas")
201
+ ax.set_xlabel("PC1")
202
+ ax.set_ylabel("PC2")
203
+ ax.legend(markerscale=5, fontsize=8)
204
+
205
+ if mapped_query is not None:
206
+ # panel 2: mapped query
207
+ ax = axes[1]
208
+ mq = mapped_query.obsm.get("X_gotmap")
209
+ if mq is None:
210
+ raise ValueError("mapped_query has no X_gotmap")
211
+ ax.scatter(mq[:, 0], mq[:, 1],
212
+ s=1, c="#DD8452", alpha=0.5, label="mapped query")
213
+ ax.set_title("Mapped Query")
214
+ ax.set_xlabel("PC1")
215
+ ax.set_ylabel("PC2")
216
+ ax.legend(markerscale=5, fontsize=8)
217
+
218
+ # panel 3: overlay
219
+ ax = axes[2]
220
+ ax.scatter(ref_pca[:, 0], ref_pca[:, 1],
221
+ s=1, c="#4C72B0", alpha=0.3, label="reference")
222
+ ax.scatter(mq[:, 0], mq[:, 1],
223
+ s=1, c="#DD8452", alpha=0.5, label="mapped query")
224
+ ax.set_title("Overlay")
225
+ ax.set_xlabel("PC1")
226
+ ax.set_ylabel("PC2")
227
+ ax.legend(markerscale=5, fontsize=8)
228
+
229
+ plt.tight_layout()
230
+ if save:
231
+ plt.savefig(save, dpi=150, bbox_inches="tight")
232
+ plt.show()
gotmap/pp.py ADDED
@@ -0,0 +1,185 @@
1
+ """
2
+ gotmap.pp - Preprocessing tools (scanpy-compatible).
3
+
4
+ Functions:
5
+ preprocess_reference(adata, ...)
6
+ preprocess_query(adata, reference, ...)
7
+ normalize_and_hvg(adata, ...)
8
+ """
9
+
10
+ import numpy as np
11
+ import scanpy as sc
12
+ from .utils import check_pca
13
+
14
+
15
+ def normalize_and_hvg(
16
+ adata,
17
+ min_mean=0.0125,
18
+ max_mean=3,
19
+ min_disp=0.5,
20
+ n_top_genes=2000,
21
+ flavor="seurat",
22
+ inplace=True,
23
+ ):
24
+ """
25
+ Normalize and select highly variable genes.
26
+
27
+ Parameters
28
+ ----------
29
+ adata : AnnData
30
+ Input data.
31
+ min_mean, max_mean, min_disp : float
32
+ HVG selection parameters.
33
+ n_top_genes : int
34
+ Number of top HVGs to select.
35
+ flavor : str
36
+ HVG flavor ('seurat', 'cell_ranger', 'seurat_v3').
37
+ inplace : bool
38
+ Whether to modify adata in place.
39
+
40
+ Returns
41
+ -------
42
+ AnnData or None
43
+ """
44
+ if not inplace:
45
+ adata = adata.copy()
46
+ sc.pp.normalize_total(adata, target_sum=1e4)
47
+ sc.pp.log1p(adata)
48
+ sc.pp.highly_variable_genes(
49
+ adata,
50
+ min_mean=min_mean,
51
+ max_mean=max_mean,
52
+ min_disp=min_disp,
53
+ n_top_genes=n_top_genes,
54
+ flavor=flavor,
55
+ )
56
+ if not inplace:
57
+ return adata
58
+
59
+
60
+ def preprocess_reference(
61
+ adata,
62
+ n_comps=50,
63
+ n_top_genes=2000,
64
+ use_highly_variable=True,
65
+ normalize=True,
66
+ copy=False,
67
+ ):
68
+ """
69
+ Full preprocessing pipeline for a REFERENCE atlas.
70
+
71
+ This should be run ONCE on the reference. The result is then
72
+ wrapped in FrozenReference for repeated query mapping.
73
+
74
+ Parameters
75
+ ----------
76
+ adata : AnnData
77
+ Reference atlas (raw counts).
78
+ n_comps : int
79
+ Number of PCA components.
80
+ n_top_genes : int
81
+ Number of HVGs.
82
+ use_highly_variable : bool
83
+ If True, run PCA on HVGs only.
84
+ normalize : bool
85
+ If True, normalize and log-transform.
86
+ copy : bool
87
+ Return a copy.
88
+
89
+ Returns
90
+ -------
91
+ AnnData
92
+ Preprocessed reference with .obsm['X_pca'] and .varm['PCs'].
93
+ """
94
+ if copy:
95
+ adata = adata.copy()
96
+
97
+ if normalize:
98
+ sc.pp.normalize_total(adata, target_sum=1e4)
99
+ sc.pp.log1p(adata)
100
+
101
+ sc.pp.highly_variable_genes(
102
+ adata, n_top_genes=n_top_genes, flavor="seurat"
103
+ )
104
+
105
+ if use_highly_variable:
106
+ adata = adata[:, adata.var["highly_variable"]].copy()
107
+
108
+ sc.pp.pca(adata, n_comps=n_comps)
109
+
110
+ print(
111
+ f"[gotmap.pp] reference ready: "
112
+ f"{adata.n_obs} cells x {adata.n_vars} genes, "
113
+ f"PCA {adata.obsm['X_pca'].shape}"
114
+ )
115
+ return adata
116
+
117
+
118
+ def preprocess_query(
119
+ adata,
120
+ reference,
121
+ n_comps=50,
122
+ copy=False,
123
+ ):
124
+ """
125
+ Lightweight preprocessing for QUERY data.
126
+
127
+ Query data is projected into the REFERENCE PCA space,
128
+ NOT recomputed independently.
129
+
130
+ Parameters
131
+ ----------
132
+ adata : AnnData
133
+ Query data (raw counts).
134
+ reference : FrozenReference or AnnData
135
+ Frozen reference (with .varm['PCs']).
136
+ n_comps : int
137
+ Number of PCs (must match reference).
138
+ copy : bool
139
+
140
+ Returns
141
+ -------
142
+ AnnData
143
+ Query with .obsm['X_pca'] computed in reference space.
144
+ """
145
+ from .update import FrozenReference
146
+
147
+ if copy:
148
+ adata = adata.copy()
149
+
150
+ # normalize + log (same as reference)
151
+ sc.pp.normalize_total(adata, target_sum=1e4)
152
+ sc.pp.log1p(adata)
153
+
154
+ if isinstance(reference, FrozenReference):
155
+ pca = reference.project_query(adata)
156
+ else:
157
+ # assume AnnData with varm['PCs']
158
+ PCs = reference.varm["PCs"]
159
+ mean = (
160
+ reference.uns["pca"]["mean"]
161
+ if "pca" in reference.uns and "mean" in reference.uns["pca"]
162
+ else None
163
+ )
164
+ # align genes
165
+ common = adata.var_names.intersection(reference.var_names)
166
+ if len(common) < PCs.shape[1]:
167
+ raise ValueError(
168
+ f"Only {len(common)} genes overlap with reference"
169
+ )
170
+ adata = adata[:, common]
171
+ PCs = PCs[np.searchsorted(reference.var_names.values, common.values)]
172
+ if mean is not None:
173
+ mean = mean[np.searchsorted(reference.var_names.values, common.values)]
174
+ import scipy.sparse as sp
175
+ X = adata.X.toarray() if sp.sparse.issparse(adata.X) else adata.X
176
+ if mean is not None:
177
+ X = X - mean
178
+ pca = X @ PCs
179
+
180
+ adata.obsm["X_pca"] = pca[:, :n_comps]
181
+ print(
182
+ f"[gotmap.pp] query projected: "
183
+ f"{adata.n_obs} cells -> reference PCA space {adata.obsm['X_pca'].shape}"
184
+ )
185
+ return adata
gotmap/tl.py ADDED
@@ -0,0 +1,192 @@
1
+ """
2
+ gotmap.tl - Tools (scanpy-compatible).
3
+
4
+ Functions:
5
+ map_query_to_reference(adata, reference, ...)
6
+ transfer_labels(adata, reference, label_key, ...)
7
+ evaluate_mapping(adata, reference, ...)
8
+ """
9
+
10
+ import numpy as np
11
+ import scanpy as sc
12
+ from .mapper import GOTMap
13
+
14
+
15
+ def map_query_to_reference(
16
+ query,
17
+ reference,
18
+ pca_key="X_pca",
19
+ k=30,
20
+ p=3,
21
+ reg=0.1,
22
+ backend="batched",
23
+ method="nn",
24
+ hidden_dim=128,
25
+ epochs=200,
26
+ key_added="X_gotmap",
27
+ copy=False,
28
+ ):
29
+ """
30
+ Map a query dataset into a reference atlas.
31
+
32
+ This is the main high-level function (mirrors scanpy.tl API).
33
+
34
+ Parameters
35
+ ----------
36
+ query : AnnData
37
+ Query data (must have .obsm[pca_key]).
38
+ reference : AnnData
39
+ Reference atlas (must have .obsm[pca_key] and .varm['PCs']).
40
+ pca_key : str
41
+ Key for PCA coordinates.
42
+ k, p, reg, backend : GrassmannOT parameters.
43
+ method : str
44
+ 'nn' for neural network mapping, 'knn' for kNN projection.
45
+ hidden_dim : int
46
+ Hidden dimension for NN mapper.
47
+ epochs : int
48
+ Training epochs for NN mapper.
49
+ key_added : str
50
+ Key in .obsm where mapping result is stored.
51
+ copy : bool
52
+ Return a copy of query.
53
+
54
+ Returns
55
+ -------
56
+ AnnData or None
57
+ If copy=True, returns query with .obsm[key_added].
58
+ Otherwise modifies in place.
59
+ """
60
+ if copy:
61
+ query = query.copy()
62
+
63
+ mapper = GOTMap(
64
+ ref_adata=reference,
65
+ pca_key=pca_key,
66
+ k=k, p=p, reg=reg, backend=backend,
67
+ )
68
+ mapper.fit(query)
69
+
70
+ if method == "nn":
71
+ result = mapper.transform(
72
+ query, method="nn",
73
+ hidden_dim=hidden_dim, epochs=epochs,
74
+ )
75
+ query.obsm[key_added] = result.obsm["X_gotmap"]
76
+ else:
77
+ result = mapper.transform(query, method="knn")
78
+ query.obsm[key_added] = result
79
+
80
+ # store anchors and gamma as uns for downstream use
81
+ query.uns["gotmap_anchors"] = mapper.anchors_
82
+ query.uns["gotmap_gamma"] = mapper.gamma_
83
+
84
+ if copy:
85
+ return query
86
+
87
+
88
+ def transfer_labels(
89
+ query,
90
+ reference,
91
+ label_key,
92
+ pca_key="X_pca",
93
+ k=30,
94
+ p=3,
95
+ reg=0.1,
96
+ backend="batched",
97
+ method="weighted_knn",
98
+ key_added=None,
99
+ copy=False,
100
+ ):
101
+ """
102
+ Transfer cell-type labels from reference to query.
103
+
104
+ Parameters
105
+ ----------
106
+ query, reference : AnnData
107
+ label_key : str
108
+ Column in reference.obs containing labels to transfer.
109
+ pca_key : str
110
+ Key for PCA coordinates.
111
+ method : str
112
+ 'weighted_knn' (default) or 'nn' (requires mapping first).
113
+ key_added : str or None
114
+ Prefix for added columns. If None, uses label_key.
115
+ copy : bool
116
+
117
+ Returns
118
+ -------
119
+ AnnData or None
120
+ """
121
+ if key_added is None:
122
+ key_added = label_key
123
+
124
+ if copy:
125
+ query = query.copy()
126
+
127
+ mapper = GOTMap(
128
+ ref_adata=reference,
129
+ pca_key=pca_key,
130
+ k=k, p=p, reg=reg, backend=backend,
131
+ )
132
+ mapped = mapper.fit(query).transform(query, method="knn")
133
+
134
+ from .knn_map import weighted_knn_labels
135
+ pred, conf = weighted_knn_labels(
136
+ reference.obsm[pca_key],
137
+ mapped,
138
+ reference.obs[label_key].values,
139
+ gamma=mapper.gamma_,
140
+ anchors=mapper.anchors_,
141
+ )
142
+
143
+ query.obs[f"{key_added}_predicted"] = pred
144
+ query.obs[f"{key_added}_confidence"] = conf
145
+ query.uns["gotmap_anchors"] = mapper.anchors_
146
+ query.uns["gotmap_gamma"] = mapper.gamma_
147
+
148
+ if copy:
149
+ return query
150
+
151
+
152
+ def evaluate_mapping(
153
+ query,
154
+ reference,
155
+ pca_key="X_pca",
156
+ k=30,
157
+ p=3,
158
+ reg=0.1,
159
+ backend="batched",
160
+ key_added="gotmap_quality",
161
+ ):
162
+ """
163
+ Evaluate the quality of query-to-reference mapping.
164
+
165
+ Adds a column to query.obs with per-cell mapping confidence.
166
+
167
+ Parameters
168
+ ----------
169
+ query, reference : AnnData
170
+ pca_key : str
171
+ key_added : str
172
+ Column name in query.obs for confidence scores.
173
+
174
+ Returns
175
+ -------
176
+ dict
177
+ Summary statistics: mean_confidence, mapping_rate, n_anchors.
178
+ """
179
+ mapper = GOTMap(
180
+ ref_adata=reference,
181
+ pca_key=pca_key,
182
+ k=k, p=p, reg=reg, backend=backend,
183
+ )
184
+ quality = mapper.fit(query).evaluate_mapping(query)
185
+
186
+ query.obs[key_added] = quality["cell_confidence"]
187
+
188
+ return {
189
+ "mean_confidence": float(quality["mean_confidence"]),
190
+ "mapping_rate": float(quality["mapping_rate"]),
191
+ "n_anchors": int(quality["n_anchors"]),
192
+ }