SpatialQuery 0.0.5__tar.gz → 0.0.7__tar.gz

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.
Files changed (35) hide show
  1. {spatialquery-0.0.5/SpatialQuery.egg-info → spatialquery-0.0.7}/PKG-INFO +15 -2
  2. {spatialquery-0.0.5 → spatialquery-0.0.7}/README.md +14 -1
  3. {spatialquery-0.0.5 → spatialquery-0.0.7}/SpatialQuery/__init__.py +3 -1
  4. {spatialquery-0.0.5 → spatialquery-0.0.7}/SpatialQuery/plotting.py +82 -1
  5. {spatialquery-0.0.5 → spatialquery-0.0.7}/SpatialQuery/spatial_gene_covarying.py +1 -0
  6. {spatialquery-0.0.5 → spatialquery-0.0.7}/SpatialQuery/spatial_query.py +218 -27
  7. {spatialquery-0.0.5 → spatialquery-0.0.7}/SpatialQuery/spatial_query_multiple_fov.py +454 -179
  8. {spatialquery-0.0.5 → spatialquery-0.0.7}/SpatialQuery/spatial_utils.py +301 -3
  9. {spatialquery-0.0.5 → spatialquery-0.0.7/SpatialQuery.egg-info}/PKG-INFO +15 -2
  10. {spatialquery-0.0.5 → spatialquery-0.0.7}/pyproject.toml +1 -1
  11. {spatialquery-0.0.5 → spatialquery-0.0.7}/LICENSE +0 -0
  12. {spatialquery-0.0.5 → spatialquery-0.0.7}/MANIFEST.in +0 -0
  13. {spatialquery-0.0.5 → spatialquery-0.0.7}/SpatialQuery/scfind4sp/__init__.py +0 -0
  14. {spatialquery-0.0.5 → spatialquery-0.0.7}/SpatialQuery/scfind4sp/core_methods.py +0 -0
  15. {spatialquery-0.0.5 → spatialquery-0.0.7}/SpatialQuery/scfind4sp/cpp_src/EliasFano.h +0 -0
  16. {spatialquery-0.0.5 → spatialquery-0.0.7}/SpatialQuery/scfind4sp/cpp_src/QueryScore.cpp +0 -0
  17. {spatialquery-0.0.5 → spatialquery-0.0.7}/SpatialQuery/scfind4sp/cpp_src/QueryScore.h +0 -0
  18. {spatialquery-0.0.5 → spatialquery-0.0.7}/SpatialQuery/scfind4sp/cpp_src/Serialization.h +0 -0
  19. {spatialquery-0.0.5 → spatialquery-0.0.7}/SpatialQuery/scfind4sp/cpp_src/__init__.py +0 -0
  20. {spatialquery-0.0.5 → spatialquery-0.0.7}/SpatialQuery/scfind4sp/cpp_src/const.h +0 -0
  21. {spatialquery-0.0.5 → spatialquery-0.0.7}/SpatialQuery/scfind4sp/cpp_src/eliasFano.cpp +0 -0
  22. {spatialquery-0.0.5 → spatialquery-0.0.7}/SpatialQuery/scfind4sp/cpp_src/fp_growth.cpp +0 -0
  23. {spatialquery-0.0.5 → spatialquery-0.0.7}/SpatialQuery/scfind4sp/cpp_src/fp_growth.h +0 -0
  24. {spatialquery-0.0.5 → spatialquery-0.0.7}/SpatialQuery/scfind4sp/cpp_src/serialization.cpp +0 -0
  25. {spatialquery-0.0.5 → spatialquery-0.0.7}/SpatialQuery/scfind4sp/cpp_src/typedef.h +0 -0
  26. {spatialquery-0.0.5 → spatialquery-0.0.7}/SpatialQuery/scfind4sp/cpp_src/utils.cpp +0 -0
  27. {spatialquery-0.0.5 → spatialquery-0.0.7}/SpatialQuery/scfind4sp/cpp_src/utils.h +0 -0
  28. {spatialquery-0.0.5 → spatialquery-0.0.7}/SpatialQuery/spatial_differential_pattern.py +0 -0
  29. {spatialquery-0.0.5 → spatialquery-0.0.7}/SpatialQuery/utils.py +0 -0
  30. {spatialquery-0.0.5 → spatialquery-0.0.7}/SpatialQuery.egg-info/SOURCES.txt +0 -0
  31. {spatialquery-0.0.5 → spatialquery-0.0.7}/SpatialQuery.egg-info/dependency_links.txt +0 -0
  32. {spatialquery-0.0.5 → spatialquery-0.0.7}/SpatialQuery.egg-info/requires.txt +0 -0
  33. {spatialquery-0.0.5 → spatialquery-0.0.7}/SpatialQuery.egg-info/top_level.txt +0 -0
  34. {spatialquery-0.0.5 → spatialquery-0.0.7}/setup.cfg +0 -0
  35. {spatialquery-0.0.5 → spatialquery-0.0.7}/setup.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: SpatialQuery
3
- Version: 0.0.5
3
+ Version: 0.0.7
4
4
  Summary: Spatial query tools for analyzing spatial transcriptomics data
5
5
  Author-email: Shaokun An <shan12@bwh.harvard.edu>
6
6
  License-Expression: MIT
@@ -35,6 +35,10 @@ Requires-Dist: sphinx-copybutton; extra == "docs"
35
35
  Requires-Dist: myst-parser; extra == "docs"
36
36
  Dynamic: license-file
37
37
 
38
+ <p align="center">
39
+ <img src="https://raw.githubusercontent.com/ShaokunAn/Spatial-Query/main/docs/_static/img/logo.png" alt="SpatialQuery" width="480">
40
+ </p>
41
+
38
42
  # SpatialQuery
39
43
 
40
44
  SpatialQuery is a Python package for systematic spatial analysis of single-cell resolution spatial omics data. It provides a unified framework to discover, quantify, and compare recurring spatial cell type patterns — termed *motifs* — across single or multiple fields of view (FOVs).
@@ -47,6 +51,7 @@ Key capabilities include:
47
51
 
48
52
  - **Spatial motif discovery**: Identify frequent cell type patterns in local neighborhoods
49
53
  - **Motif enrichment analysis**: Statistically test whether motifs occur more than expected
54
+ - **Motif composition**: Quantify the relative abundance of each motif cell type within motif-positive neighborhoods
50
55
  - **Differential motif analysis**: Compare spatial compositions across conditions
51
56
  - **Motif-associated differential expression**: Find DE genes linked to specific motifs
52
57
  - **Cross-cell gene-gene covariation**: Detect spatially dependent intercellular gene correlations
@@ -58,13 +63,15 @@ Key capabilities include:
58
63
  pip install SpatialQuery
59
64
  ```
60
65
 
66
+ > **Note:** Installation typically takes ~5 minutes depending on your environment.
67
+
61
68
  ## Documentation
62
69
 
63
70
  Full documentation, tutorials, and API reference: **[https://spatialquery.readthedocs.io/en/latest/](https://spatialquery.readthedocs.io/en/latest/)**
64
71
 
65
72
  ## Reproducibility
66
73
 
67
- The following tutorials reproduce the main analyses presented in our manuscript:
74
+ The following tutorials reproduce the main analyses presented in our manuscript. Each tutorial takes approximately 5–20 minutes to run depending on dataset size and hardware.
68
75
 
69
76
  - [Mouse organogenesis — single-FOV analysis (seqFISH)](https://spatialquery.readthedocs.io/en/latest/tutorials/tutorial_1.html)
70
77
  - [Kidney disease atlas — multi-condition analysis (MERFISH)](https://spatialquery.readthedocs.io/en/latest/tutorials/tutorial_2.html)
@@ -90,6 +97,12 @@ spm = spatial_query_multi(adatas=adatas, datasets=datasets,
90
97
  enrich_motif = spm.motif_enrichment_dist(ct="T_cell", dataset="healthy", max_dist=10, min_support=0.5)
91
98
  ```
92
99
 
100
+ ## Citation
101
+
102
+ If you use SpatialQuery in your research, please cite:
103
+
104
+ > An, S. et al. [SpatialQuery: scalable discovery and molecular characterization of multicellular motifs from spatial omics data](https://www.biorxiv.org/content/10.64898/2026.04.22.720136v1). *bioRxiv* (2026).
105
+
93
106
  ## License
94
107
 
95
108
  MIT
@@ -1,3 +1,7 @@
1
+ <p align="center">
2
+ <img src="https://raw.githubusercontent.com/ShaokunAn/Spatial-Query/main/docs/_static/img/logo.png" alt="SpatialQuery" width="480">
3
+ </p>
4
+
1
5
  # SpatialQuery
2
6
 
3
7
  SpatialQuery is a Python package for systematic spatial analysis of single-cell resolution spatial omics data. It provides a unified framework to discover, quantify, and compare recurring spatial cell type patterns — termed *motifs* — across single or multiple fields of view (FOVs).
@@ -10,6 +14,7 @@ Key capabilities include:
10
14
 
11
15
  - **Spatial motif discovery**: Identify frequent cell type patterns in local neighborhoods
12
16
  - **Motif enrichment analysis**: Statistically test whether motifs occur more than expected
17
+ - **Motif composition**: Quantify the relative abundance of each motif cell type within motif-positive neighborhoods
13
18
  - **Differential motif analysis**: Compare spatial compositions across conditions
14
19
  - **Motif-associated differential expression**: Find DE genes linked to specific motifs
15
20
  - **Cross-cell gene-gene covariation**: Detect spatially dependent intercellular gene correlations
@@ -21,13 +26,15 @@ Key capabilities include:
21
26
  pip install SpatialQuery
22
27
  ```
23
28
 
29
+ > **Note:** Installation typically takes ~5 minutes depending on your environment.
30
+
24
31
  ## Documentation
25
32
 
26
33
  Full documentation, tutorials, and API reference: **[https://spatialquery.readthedocs.io/en/latest/](https://spatialquery.readthedocs.io/en/latest/)**
27
34
 
28
35
  ## Reproducibility
29
36
 
30
- The following tutorials reproduce the main analyses presented in our manuscript:
37
+ The following tutorials reproduce the main analyses presented in our manuscript. Each tutorial takes approximately 5–20 minutes to run depending on dataset size and hardware.
31
38
 
32
39
  - [Mouse organogenesis — single-FOV analysis (seqFISH)](https://spatialquery.readthedocs.io/en/latest/tutorials/tutorial_1.html)
33
40
  - [Kidney disease atlas — multi-condition analysis (MERFISH)](https://spatialquery.readthedocs.io/en/latest/tutorials/tutorial_2.html)
@@ -53,6 +60,12 @@ spm = spatial_query_multi(adatas=adatas, datasets=datasets,
53
60
  enrich_motif = spm.motif_enrichment_dist(ct="T_cell", dataset="healthy", max_dist=10, min_support=0.5)
54
61
  ```
55
62
 
63
+ ## Citation
64
+
65
+ If you use SpatialQuery in your research, please cite:
66
+
67
+ > An, S. et al. [SpatialQuery: scalable discovery and molecular characterization of multicellular motifs from spatial omics data](https://www.biorxiv.org/content/10.64898/2026.04.22.720136v1). *bioRxiv* (2026).
68
+
56
69
  ## License
57
70
 
58
71
  MIT
@@ -7,7 +7,8 @@ from .plotting import (
7
7
  plot_motif_grid,
8
8
  plot_motif_rand,
9
9
  plot_motif_celltype,
10
- plot_all_center_motif
10
+ plot_all_center_motif,
11
+ plot_motif_composition
11
12
  )
12
13
 
13
14
  __all__ = [
@@ -22,5 +23,6 @@ __all__ = [
22
23
  'plot_motif_rand',
23
24
  'plot_motif_celltype',
24
25
  'plot_all_center_motif',
26
+ 'plot_motif_composition',
25
27
  'interactive_motif'
26
28
  ]
@@ -670,7 +670,88 @@ def plot_motif_enrichment_heatmap(enrich_df: pd.DataFrame,
670
670
  plt.savefig(save_path, dpi=300, bbox_inches='tight')
671
671
 
672
672
  plt.show()
673
-
673
+
674
+
675
+ def plot_motif_composition(comp_df: pd.DataFrame,
676
+ motif: Optional[List[str]] = None,
677
+ bins: int = 25,
678
+ colors: Optional[List] = None,
679
+ figsize: tuple = (6, 5),
680
+ title: Optional[str] = None,
681
+ save_path: Optional[str] = None):
682
+ """
683
+ Plot the distribution of each motif cell type's proportion across motif-positive center cells.
684
+
685
+ One semi-transparent histogram per motif cell type, on fixed bins over [0, 1]; the legend
686
+ reports the median and interquartile range (IQR) of each type's proportion.
687
+
688
+ Parameters
689
+ ----------
690
+ comp_df : pd.DataFrame
691
+ Output from motif_composition_dist or motif_composition_knn.
692
+ motif : List[str], optional
693
+ Motif to plot. May be omitted when comp_df holds a single motif.
694
+ bins : int, default=25
695
+ Number of equal-width bins on [0, 1].
696
+ colors : List, optional
697
+ One color per motif cell type, in sorted cell type order. Defaults to the tab10 palette.
698
+ figsize : tuple, default=(6, 5)
699
+ Figure size.
700
+ title : str, optional
701
+ Figure title. Defaults to the center cell type and the motif.
702
+ save_path : str, optional
703
+ Path to save the figure. If None, the figure will not be saved.
704
+
705
+ Returns
706
+ -------
707
+ None
708
+ Displays a histogram of motif cell type proportions.
709
+ """
710
+ if len(comp_df) == 0:
711
+ print("No motif-positive center cells to plot.")
712
+ return
713
+
714
+ keys = comp_df['motifs'].map(spatial_utils.canonical_motif)
715
+ if motif is None:
716
+ if keys.nunique() > 1:
717
+ raise ValueError("comp_df holds several motifs; specify which one to plot with motif.")
718
+ motif_key = keys.iloc[0]
719
+ else:
720
+ motif_key = spatial_utils.canonical_motif([motif] if isinstance(motif, str) else motif)
721
+ df = comp_df[keys == motif_key]
722
+ if len(df) == 0:
723
+ raise ValueError(f"Motif {list(motif_key)} is not in comp_df.")
724
+
725
+ cell_types = list(motif_key)
726
+ if colors is None:
727
+ colors = [plt.cm.tab10(i % 10) for i in range(len(cell_types))]
728
+ bin_edges = np.linspace(0, 1, bins + 1)
729
+
730
+ fig, ax = plt.subplots(figsize=figsize)
731
+ for cell_type, color in zip(cell_types, colors):
732
+ values = df.loc[df['cell_type'] == cell_type, 'proportion'].to_numpy(dtype=float)
733
+ q25, median, q75 = np.percentile(values, [25, 50, 75])
734
+ ax.hist(values, bins=bin_edges, color=color, alpha=0.5,
735
+ label=f'{cell_type}\n(median={median:.2f}, IQR={q75 - q25:.2f})')
736
+
737
+ ax.set_xlim(-0.03, 1.03)
738
+ ax.set_xlabel('Relative abundance among motif-associated cells', fontsize=12)
739
+ ax.set_ylabel('Number of motif-positive anchors', fontsize=12)
740
+ ax.spines[['top', 'right']].set_visible(False)
741
+ ax.legend(frameon=False, fontsize=10, loc='best')
742
+
743
+ if title is None:
744
+ centers = df['center'].unique()
745
+ center = f'{centers[0]} | ' if len(centers) == 1 else ''
746
+ title = f'{center}{" + ".join(cell_types)}'
747
+ ax.set_title(title, fontsize=13)
748
+ plt.tight_layout()
749
+
750
+ if save_path is not None:
751
+ plt.savefig(save_path, dpi=300, bbox_inches='tight')
752
+
753
+ plt.show()
754
+
674
755
 
675
756
  def plot_differential_pattern_heatmap(
676
757
  diff_motif: dict,
@@ -4395,6 +4395,7 @@ def compute_gene_gene_correlation_by_type_binary_multi_fov(
4395
4395
  if len(non_center_types) == 1:
4396
4396
  print(f"Only one non-center cell type in motif: {non_center_types}. Using compute_gene_gene_correlation_binary method.")
4397
4397
  result = compute_gene_gene_correlation_binary_multi_fov(
4398
+ sq_objs=sq_objs,
4398
4399
  ct=ct,
4399
4400
  motif=motif,
4400
4401
  dataset=dataset,
@@ -157,6 +157,7 @@ class spatial_query:
157
157
  k: int = 30,
158
158
  min_support: float = 0.5,
159
159
  max_dist: float = 20,
160
+ if_max: bool = True,
160
161
  ) -> pd.DataFrame:
161
162
  """
162
163
  Find frequent patterns within the KNNs of certain cell type.
@@ -171,6 +172,9 @@ class spatial_query:
171
172
  Threshold of frequency to consider a pattern as a frequent pattern.
172
173
  max_dist : float, default=20
173
174
  Maximum distance for considering a cell as a neighbor.
175
+ if_max : bool, default=True
176
+ Return only maximal patterns. Set to False to return every frequent pattern,
177
+ which nested motif enrichment needs to look up sub-pattern supports.
174
178
 
175
179
  Returns
176
180
  -------
@@ -190,7 +194,7 @@ class spatial_query:
190
194
  k=k,
191
195
  min_support=min_support,
192
196
  max_dist=max_dist,
193
- if_max=True
197
+ if_max=if_max
194
198
  )
195
199
 
196
200
  return fp
@@ -200,6 +204,7 @@ class spatial_query:
200
204
  max_dist: float = 20,
201
205
  min_size: int = 0,
202
206
  min_support: float = 0.5,
207
+ if_max: bool = True,
203
208
  ):
204
209
  """
205
210
  Find frequent patterns within the radius of certain cell type.
@@ -214,6 +219,9 @@ class spatial_query:
214
219
  Minimum neighborhood size for each point to consider.
215
220
  min_support : float, default=0.5
216
221
  Threshold of frequency to consider a pattern as a frequent pattern.
222
+ if_max : bool, default=True
223
+ Return only maximal patterns. Set to False to return every frequent pattern,
224
+ which nested motif enrichment needs to look up sub-pattern supports.
217
225
 
218
226
  Returns
219
227
  -------
@@ -233,7 +241,8 @@ class spatial_query:
233
241
  max_dist=max_dist,
234
242
  min_size=min_size,
235
243
  min_support=min_support,
236
- cinds=cinds
244
+ cinds=cinds,
245
+ if_max=if_max
237
246
  )
238
247
 
239
248
  return fp
@@ -244,7 +253,8 @@ class spatial_query:
244
253
  k: int = 30,
245
254
  min_support: float = 0.5,
246
255
  max_dist: float = 20,
247
- return_cellID: bool = False
256
+ return_cellID: bool = False,
257
+ mode: str = 'maximal'
248
258
  ) -> pd.DataFrame:
249
259
  """
250
260
  Perform motif enrichment analysis using k-nearest neighbors (KNN).
@@ -265,6 +275,16 @@ class spatial_query:
265
275
  return_cellID : bool, default=False
266
276
  Indicate whether return cell IDs for each frequent pattern within the neighborhood of grid points.
267
277
  By defaults do not return cell ID.
278
+ mode : {'maximal', 'nested'}, default='maximal'
279
+ How the motifs to test are chosen when motifs=None. Ignored when motifs is given.
280
+
281
+ 'maximal'
282
+ Test the maximal patterns only.
283
+ 'nested'
284
+ Test the maximal patterns, then descend into the sub-patterns of any that
285
+ are not significant, stopping a branch as soon as it becomes significant or
286
+ reaches length 1. Finds cores that a maximal pattern hides when one abundant
287
+ cell type dilutes it. Multiple-testing correction covers everything tested.
268
288
 
269
289
  Returns
270
290
  -------
@@ -285,6 +305,27 @@ class spatial_query:
285
305
  if ct not in self.labels.unique():
286
306
  raise ValueError(f"Found no {ct} in {self.label_key}!")
287
307
 
308
+ if mode not in ('nested', 'maximal'):
309
+ raise ValueError(f"mode must be 'nested' or 'maximal', got {mode!r}")
310
+
311
+ # Nested descent only decides WHICH motifs get tested; each batch is scored by this
312
+ # same method, so the statistics are identical to the maximal mode's.
313
+ if mode == 'nested' and motifs is None:
314
+ fp_all = self.find_fp_knn(ct=ct, k=k, min_support=min_support,
315
+ max_dist=max_dist, if_max=False)
316
+ if len(fp_all) == 0:
317
+ return spatial_utils.apply_fdr_correction(pd.DataFrame())
318
+ # Cell IDs are DataFrame columns here, so they travel with the rows and need
319
+ # no separate merging.
320
+ return spatial_utils.nested_motif_descent(
321
+ test_motifs=lambda ms: self.motif_enrichment_knn(
322
+ ct=ct, motifs=ms, k=k, min_support=min_support, max_dist=max_dist,
323
+ return_cellID=return_cellID, mode='maximal'),
324
+ maximal_motifs=spatial_utils.find_maximal_patterns(fp_all)['itemsets'],
325
+ support_of={spatial_utils.canonical_motif(i): s
326
+ for i, s in zip(fp_all['itemsets'], fp_all['support'])},
327
+ )
328
+
288
329
  dists, idxs = self.kd_tree.query(self.spatial_pos,
289
330
  k=k + 1, workers=-1
290
331
  ) # use k+1 to find the knn except for the points themselves
@@ -398,18 +439,7 @@ class spatial_query:
398
439
  'n_motif', 'expectation', 'p-values', 'if_significant'])
399
440
  return out_pd
400
441
 
401
- if len(out_pd) == 1:
402
- out_pd['if_significant'] = True if out_pd['p-values'][0] < 0.05 else False
403
- return out_pd
404
- else:
405
- p_values = out_pd['p-values'].tolist()
406
- if_rejected, corrected_p_values = mt.fdrcorrection(p_values,
407
- alpha=0.05,
408
- method='poscorr')
409
- out_pd['adj-pval'] = corrected_p_values
410
- out_pd['if_significant'] = if_rejected
411
- out_pd = out_pd.sort_values(by='adj-pval', ignore_index=True)
412
- return out_pd
442
+ return spatial_utils.apply_fdr_correction(out_pd)
413
443
 
414
444
  def motif_enrichment_dist(self,
415
445
  ct: str,
@@ -418,6 +448,7 @@ class spatial_query:
418
448
  min_size: int = 0,
419
449
  min_support: float = 0.5,
420
450
  return_cellID: bool = False,
451
+ mode: str = 'maximal',
421
452
  ) -> DataFrame:
422
453
  """
423
454
  Perform motif enrichment analysis within a specified radius-based neighborhood.
@@ -438,6 +469,16 @@ class spatial_query:
438
469
  return_cellID : bool, default=False
439
470
  Indicate whether return cell IDs for each motif within the neighborhood of central cell type.
440
471
  By defaults do not return cell ID.
472
+ mode : {'maximal', 'nested'}, default='maximal'
473
+ How the motifs to test are chosen when motifs=None. Ignored when motifs is given.
474
+
475
+ 'maximal'
476
+ Test the maximal patterns only.
477
+ 'nested'
478
+ Test the maximal patterns, then descend into the sub-patterns of any that
479
+ are not significant, stopping a branch as soon as it becomes significant or
480
+ reaches length 1. Finds cores that a maximal pattern hides when one abundant
481
+ cell type dilutes it. Multiple-testing correction covers everything tested.
441
482
 
442
483
  Returns
443
484
  -------
@@ -458,6 +499,28 @@ class spatial_query:
458
499
  if ct not in self.labels.unique():
459
500
  raise ValueError(f"Found no {ct} in {self.label_key}!")
460
501
 
502
+ if mode not in ('nested', 'maximal'):
503
+ raise ValueError(f"mode must be 'nested' or 'maximal', got {mode!r}")
504
+
505
+ # Nested descent only decides WHICH motifs get tested; each batch is scored by this
506
+ # same method, so the statistics are identical to the maximal mode's.
507
+ if mode == 'nested' and motifs is None:
508
+ fp_all = self.find_fp_dist(ct=ct, max_dist=max_dist, min_size=min_size,
509
+ min_support=min_support, if_max=False)
510
+ if len(fp_all) == 0:
511
+ return spatial_utils.apply_fdr_correction(pd.DataFrame())
512
+ # Cell IDs are DataFrame columns here, so they travel with the rows and need
513
+ # no separate merging.
514
+ return spatial_utils.nested_motif_descent(
515
+ test_motifs=lambda ms: self.motif_enrichment_dist(
516
+ ct=ct, motifs=ms, max_dist=max_dist, min_size=min_size,
517
+ min_support=min_support, return_cellID=return_cellID,
518
+ mode='maximal'),
519
+ maximal_motifs=spatial_utils.find_maximal_patterns(fp_all)['itemsets'],
520
+ support_of={spatial_utils.canonical_motif(i): s
521
+ for i, s in zip(fp_all['itemsets'], fp_all['support'])},
522
+ )
523
+
461
524
  out = []
462
525
  if motifs is None:
463
526
  fp = self.find_fp_dist(ct=ct,
@@ -563,18 +626,110 @@ class spatial_query:
563
626
  'n_motif', 'expectation', 'p-values', 'if_significant'])
564
627
  return out_pd
565
628
 
566
- if len(out_pd) == 1:
567
- out_pd['if_significant'] = True if out_pd['p-values'][0] < 0.05 else False
568
- return out_pd
569
- else:
570
- p_values = out_pd['p-values'].tolist()
571
- if_rejected, corrected_p_values = mt.fdrcorrection(p_values,
572
- alpha=0.05,
573
- method='poscorr')
574
- out_pd['adj-pval'] = corrected_p_values
575
- out_pd['if_significant'] = if_rejected
576
- out_pd = out_pd.sort_values(by='adj-pval', ignore_index=True)
577
- return out_pd
629
+ return spatial_utils.apply_fdr_correction(out_pd)
630
+
631
+ def motif_composition_dist(self,
632
+ ct: str,
633
+ motifs: Union[str, List[str], List[List[str]]],
634
+ max_dist: float = 20,
635
+ ) -> pd.DataFrame:
636
+ """
637
+ Compute the composition of motif cell types in the radius-based neighborhoods of center cells.
638
+
639
+ Uses the same neighborhoods as motif_enrichment_dist, but performs no enrichment test.
640
+ Only center cells whose neighborhood contains every cell type of the motif (motif-positive
641
+ centers) are kept. For each of them, the proportion of a motif cell type is its number of
642
+ cells divided by the total number of motif-type cells in that neighborhood.
643
+
644
+ Parameters
645
+ ----------
646
+ ct : str
647
+ Cell type as the center cells.
648
+ motifs : str or List[str] or List[List[str]]
649
+ Motifs to analyze, e.g. the 'motifs' column of motif_enrichment_dist output.
650
+ max_dist : float, default=20
651
+ Maximum distance for considering a cell as a neighbor.
652
+
653
+ Returns
654
+ -------
655
+ pd.DataFrame
656
+ Long-format table with one row per (motif-positive center cell, motif cell type):
657
+ - center: center cell type name
658
+ - motifs: sorted list of cell types in the motif
659
+ - cell_type: motif cell type this row describes
660
+ - n_cells: number of cells of cell_type in the neighborhood
661
+ - n_motif_cells: number of motif-type cells in the neighborhood
662
+ - proportion: n_cells / n_motif_cells
663
+ """
664
+ if ct not in self.labels.unique():
665
+ raise ValueError(f"Found no {ct} in {self.label_key}!")
666
+ motifs = spatial_utils.normalize_motif_list(motifs, self.labels.unique(), self.label_key)
667
+
668
+ label_encoder = LabelEncoder()
669
+ int_labels = label_encoder.fit_transform(np.array(self.labels))
670
+ cinds = np.where(self.labels == ct)[0]
671
+ counts = spatial_utils.anchor_neighbor_counts_dist(
672
+ self.kd_tree, self.spatial_pos, cinds, int_labels,
673
+ len(label_encoder.classes_), max_dist)
674
+
675
+ out = [spatial_utils.motif_composition_table(
676
+ ct, motif, counts[:, label_encoder.transform(np.array(motif))]) for motif in motifs]
677
+ if len(out) == 0:
678
+ return pd.DataFrame(columns=spatial_utils.COMPOSITION_COLUMNS)
679
+ return pd.concat(out, ignore_index=True)
680
+
681
+ def motif_composition_knn(self,
682
+ ct: str,
683
+ motifs: Union[str, List[str], List[List[str]]],
684
+ k: int = 30,
685
+ max_dist: float = 20,
686
+ ) -> pd.DataFrame:
687
+ """
688
+ Compute the composition of motif cell types in the k-nearest-neighbor neighborhoods of center cells.
689
+
690
+ Uses the same neighborhoods as motif_enrichment_knn, but performs no enrichment test.
691
+ Only center cells whose neighborhood contains every cell type of the motif (motif-positive
692
+ centers) are kept. For each of them, the proportion of a motif cell type is its number of
693
+ cells divided by the total number of motif-type cells in that neighborhood.
694
+
695
+ Parameters
696
+ ----------
697
+ ct : str
698
+ Cell type of the center cell.
699
+ motifs : str or List[str] or List[List[str]]
700
+ Motifs to analyze, e.g. the 'motifs' column of motif_enrichment_knn output.
701
+ k : int, default=30
702
+ Number of nearest neighbors to consider.
703
+ max_dist : float, default=20
704
+ Maximum distance for neighbors.
705
+
706
+ Returns
707
+ -------
708
+ pd.DataFrame
709
+ Long-format table with one row per (motif-positive center cell, motif cell type):
710
+ - center: center cell type name
711
+ - motifs: sorted list of cell types in the motif
712
+ - cell_type: motif cell type this row describes
713
+ - n_cells: number of cells of cell_type in the neighborhood
714
+ - n_motif_cells: number of motif-type cells in the neighborhood
715
+ - proportion: n_cells / n_motif_cells
716
+ """
717
+ if ct not in self.labels.unique():
718
+ raise ValueError(f"Found no {ct} in {self.label_key}!")
719
+ motifs = spatial_utils.normalize_motif_list(motifs, self.labels.unique(), self.label_key)
720
+
721
+ label_encoder = LabelEncoder()
722
+ int_labels = label_encoder.fit_transform(np.array(self.labels))
723
+ cinds = np.where(self.labels == ct)[0]
724
+ counts = spatial_utils.anchor_neighbor_counts_knn(
725
+ self.kd_tree, self.spatial_pos, cinds, int_labels,
726
+ len(label_encoder.classes_), k, max_dist)
727
+
728
+ out = [spatial_utils.motif_composition_table(
729
+ ct, motif, counts[:, label_encoder.transform(np.array(motif))]) for motif in motifs]
730
+ if len(out) == 0:
731
+ return pd.DataFrame(columns=spatial_utils.COMPOSITION_COLUMNS)
732
+ return pd.concat(out, ignore_index=True)
578
733
 
579
734
 
580
735
  def find_patterns_grid(self,
@@ -1404,6 +1559,42 @@ class spatial_query:
1404
1559
  """
1405
1560
  return plotting.plot_motif_enrichment_heatmap(enrich_df=enrich_df, figsize=figsize,
1406
1561
  save_path=save_path, title=title, cmap=cmap)
1562
+
1563
+ def plot_motif_composition(self,
1564
+ comp_df: pd.DataFrame,
1565
+ motif: Optional[List[str]] = None,
1566
+ bins: int = 25,
1567
+ colors: Optional[List] = None,
1568
+ figsize: tuple = (6, 5),
1569
+ title: Optional[str] = None,
1570
+ save_path: Optional[str] = None):
1571
+ """
1572
+ Plot the distribution of each motif cell type's proportion across motif-positive center cells.
1573
+
1574
+ Parameters
1575
+ ----------
1576
+ comp_df : pd.DataFrame
1577
+ Output DataFrame from motif_composition_dist or motif_composition_knn.
1578
+ motif : List[str], optional
1579
+ Motif to plot. May be omitted when comp_df holds a single motif.
1580
+ bins : int, default=25
1581
+ Number of equal-width bins on [0, 1].
1582
+ colors : List, optional
1583
+ One color per motif cell type, in sorted cell type order. Defaults to the tab10 palette.
1584
+ figsize : tuple, default=(6, 5)
1585
+ Figure size.
1586
+ title : str, optional
1587
+ Figure title. Defaults to the center cell type and the motif.
1588
+ save_path : str, optional
1589
+ Path to save the figure. If None, the figure will not be saved.
1590
+
1591
+ Returns
1592
+ -------
1593
+ None
1594
+ Displays a histogram of motif cell type proportions, with median and IQR in the legend.
1595
+ """
1596
+ return plotting.plot_motif_composition(comp_df=comp_df, motif=motif, bins=bins, colors=colors,
1597
+ figsize=figsize, title=title, save_path=save_path)
1407
1598
 
1408
1599
  def plot_gene_pair_heatmap(self,
1409
1600
  gene_pair_df: pd.DataFrame,