SpatialQuery 0.0.1__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.
SpatialQuery/utils.py ADDED
@@ -0,0 +1,130 @@
1
+ from collections import Counter
2
+ from itertools import combinations
3
+
4
+ import numpy as np
5
+ import pandas as pd
6
+ import anndata as ad
7
+ from sklearn.preprocessing import LabelEncoder
8
+ import scanpy as sc
9
+
10
+
11
+ def maximal_patterns(fp,
12
+ key: str = 'itemsets',
13
+ ):
14
+ """
15
+ Retrieve the maximal patterns in provided frequent patterns.
16
+
17
+ Parameter
18
+ ---------
19
+ fp:
20
+ DataFrame with frequent patterns
21
+ key:
22
+ Column name representing the patterns.
23
+
24
+ Return
25
+ ------
26
+ A dataframe with the maximal patterns.
27
+ """
28
+ itemsets = fp[key].apply(frozenset)
29
+
30
+ # Find all subsets of each itemset
31
+ subsets = set()
32
+ for itemset in itemsets:
33
+ for r in range(1, len(itemset)):
34
+ subsets.update(frozenset(s) for s in combinations(itemset, r))
35
+
36
+ # Identify maximal patterns (itemsets that are not subsets of any other)
37
+ maximal_patterns = [tuple(sorted(itemset)) for itemset in itemsets if itemset not in subsets]
38
+ # maximal_patterns_ = [list(p) for p in maximal_patterns]
39
+
40
+ # Filter the original DataFrame to keep only the maximal patterns
41
+ return fp[fp['itemsets'].isin(maximal_patterns)].reset_index(drop=True)
42
+
43
+
44
+ # TODO: query efficiency can be improved as in motif_enrichment_dist of single FOV, filtering cells
45
+ def retrieve_niche_pattern_freq(fp, sp, ct, max_dist):
46
+ """
47
+ Retrieve frequency of each cell type in frequent pattern (fp) around
48
+ central cell type (ct) from single FOV (sp).
49
+
50
+ Parameters:
51
+ fp: List[str]
52
+ list of cell types
53
+ sp: spatial_query object
54
+ spatial query object for single FOV
55
+ ct: str
56
+ central cell type
57
+ max_dist: float
58
+ radius of neighborhood
59
+
60
+ Return:
61
+ AnnData with central cell type and neighboring cells in fp
62
+ """
63
+ if ct not in sp.labels.unique():
64
+ print(f"{ct} does not exist in FOV.")
65
+ return pd.DataFrame(columns=fp)
66
+
67
+ cinds = [i for i, label in enumerate(sp.labels) if label == ct] # id of center cell type
68
+
69
+ # ct_pos = self.spatial_pos[cinds]
70
+ idxs = sp.kd_tree.query_ball_point(sp.spatial_pos, r=max_dist, return_sorted=False, workers=-1)
71
+
72
+ label_encoder = LabelEncoder()
73
+ int_labels = label_encoder.fit_transform(np.array(sp.labels))
74
+ int_ct = label_encoder.transform(np.array(ct, dtype=object, ndmin=1))
75
+
76
+ num_cells = len(idxs)
77
+ num_types = len(label_encoder.classes_)
78
+ idxs_filter = [np.array(ids)[np.array(ids) != i] for i, ids in enumerate(idxs)]
79
+ flat_neighbors = np.concatenate(idxs_filter)
80
+ row_indices = np.repeat(np.arange(num_cells), [len(neigh) for neigh in idxs_filter])
81
+ neighbor_labels = int_labels[flat_neighbors]
82
+
83
+ neighbor_matrix = np.zeros((num_cells, num_types), dtype=int)
84
+ np.add.at(neighbor_matrix, (row_indices, neighbor_labels), 1)
85
+
86
+ mask = int_labels == int_ct
87
+
88
+ motif_exc = [m for m in fp if m not in sp.labels.unique()]
89
+ if len(motif_exc) != 0:
90
+ print(f"Found no {motif_exc} in {sp.label_key}. Ignoring them.")
91
+ motif = [m for m in fp if m not in motif_exc]
92
+
93
+ int_motifs = label_encoder.transform(np.array(fp))
94
+
95
+ inds = np.where(np.all(neighbor_matrix[mask][:, int_motifs] > 0, axis=1))[0]
96
+ cind_with_motif = [cinds[i] for i in inds] # id of ct with fp nearby
97
+
98
+ freqs = []
99
+ for id in cind_with_motif:
100
+ ns = idxs_filter[id]
101
+ freq_all = Counter(sp.labels[ns])
102
+ freq_fp = {ct: count / len(ns) for ct, count in freq_all.items() if ct in fp}
103
+ freqs.append(freq_fp)
104
+
105
+ return pd.DataFrame(freqs)
106
+
107
+ def plot_niche_pattern_freq(freqs):
108
+ """
109
+ Heatmap plot of frequency of patterns (cell type compositions) in niche.
110
+
111
+ Parameter
112
+ ---------
113
+ freqs: Output of retrieve_niche_pattern_freq method.
114
+ """
115
+
116
+ for i, freq in freqs.items():
117
+ freq['FOV'] = f"normal_{i}"
118
+ freqs[i] = freq
119
+
120
+ freq_fp_normal = pd.concat(freqs)
121
+ freq_fp_normal.set_index(keys='FOV', drop=True, inplace=True)
122
+ fp_data = ad.AnnData(X=freq_fp_normal)
123
+ var = pd.DataFrame({'neighbor': freq_fp_normal.columns.tolist()})
124
+ var.index = freq_fp_normal.columns.tolist()
125
+ obs = pd.DataFrame({'FOV': freq_fp_normal.index.tolist()})
126
+ obs.index = freq_fp_normal.index.tolist()
127
+ fp_data.var = var
128
+ fp_data.obs = obs
129
+
130
+ sc.pl.heatmap(fp_data, var_names=fp_data.var_names, groupby='FOV', cmap='vlag')
@@ -0,0 +1,56 @@
1
+ Metadata-Version: 2.4
2
+ Name: SpatialQuery
3
+ Version: 0.0.1
4
+ Home-page: https://github.com/ShaokunAn/Spatial-Query
5
+ Author: Shaokun An
6
+ Author-email: shan12@bwh.harvard.edu
7
+ License: MIT
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: Programming Language :: Python :: 3
11
+ Requires-Python: >=3.8
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: setuptools>=68.0.0
15
+ Requires-Dist: anndata>=0.8.0
16
+ Requires-Dist: pandas>=2.0.3
17
+ Requires-Dist: scipy
18
+ Requires-Dist: matplotlib>=3.7.5
19
+ Requires-Dist: mlxtend>=0.23.1
20
+ Requires-Dist: seaborn>=0.13.2
21
+ Requires-Dist: scikit-learn>=1.3.2
22
+ Dynamic: author
23
+ Dynamic: author-email
24
+ Dynamic: classifier
25
+ Dynamic: description
26
+ Dynamic: description-content-type
27
+ Dynamic: home-page
28
+ Dynamic: license
29
+ Dynamic: license-file
30
+ Dynamic: requires-dist
31
+ Dynamic: requires-python
32
+
33
+ SpatialQuery is a package for fast query of Spatial Transcriptomics data.
34
+
35
+ ### Analysis of ST data in SpatialQuery
36
+
37
+ With annotated ST data as input, SpatialQuery first builds a k-D tree based on spatial location in each FOV for fast query of neighboring cell compositions. It is composed of methods for single-FOV and multiple-FOVs.
38
+ In single-FOV, it contains methods:
39
+
40
+ - identify frequent patterns across FOV
41
+ - identify frequent patterns around cell type of interest
42
+ - identify statistically significant patterns around cell type of interest
43
+
44
+ For multiple-FOVs data, it contains methods:
45
+
46
+ - identify frequent patterns around cell type of interest in specified datasets
47
+ - identify statistically significant patterns around cell type of interest in specified datasets
48
+ - identify differential patterns across datasets
49
+
50
+ ### Installation
51
+
52
+ ```
53
+ pip install -i https://test.pypi.org/simple/ SpatialQuery
54
+ ```
55
+
56
+ For more details, please refer to `examples/SpatialQuery-example.ipynb`.
@@ -0,0 +1,9 @@
1
+ SpatialQuery/__init__.py,sha256=m9euWH8hvuDnUAx3t9Fwxv9frDUFrGbzUMGjqOJbMa4,191
2
+ SpatialQuery/spatial_query.py,sha256=U0XMNDcEwYp18HTdTlCD7j9Zwvokmy4hjPVdYvTYQxE,57127
3
+ SpatialQuery/spatial_query_multiple_fov.py,sha256=xTcVT_0V3faIUry_d5YnXEBcJdR17CoLSbqSjPZtvRg,49287
4
+ SpatialQuery/utils.py,sha256=PvBgrp7gp6wHIdluc3V-VM-tUIyfrP7FpbvBjVP5ZM0,4350
5
+ spatialquery-0.0.1.dist-info/licenses/LICENSE,sha256=FWlbKlEJSYI5oSGvTThBwoRePIhTbb0YlvOqmNLeK78,1067
6
+ spatialquery-0.0.1.dist-info/METADATA,sha256=qKh8GAa5JIdMo1ZNyqQQ9QBshzBbk6IzqTzv1H-XSM4,1840
7
+ spatialquery-0.0.1.dist-info/WHEEL,sha256=pxyMxgL8-pra_rKaQ4drOZAegBVuX-G_4nRHjjgWbmo,91
8
+ spatialquery-0.0.1.dist-info/top_level.txt,sha256=kuI1SAjBSJ-Y0QMWXCzZAs06drSn9rM_KH_iT0jG5hw,13
9
+ spatialquery-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (79.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Shaokun An
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ SpatialQuery