SplIsoFind 0.1.0__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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Tilgner Lab
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,68 @@
1
+ Metadata-Version: 2.4
2
+ Name: SplIsoFind
3
+ Version: 0.1.0
4
+ Summary: Spatial Isoform Finder detects spatially variable isoforms in long-read spatial data
5
+ Author-email: Lieke Michielsen <lim4020@med.cornell.edu>
6
+ License: MIT License
7
+
8
+ Copyright (c) 2025 Tilgner Lab
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+ Keywords: spatial transcriptomics,long read,alternative splicing,isoform
28
+ Classifier: Development Status :: 5 - Production/Stable
29
+ Classifier: Intended Audience :: Science/Research
30
+ Classifier: License :: OSI Approved :: MIT License
31
+ Classifier: Programming Language :: Python :: 3.9
32
+ Classifier: Programming Language :: Python :: 3.10
33
+ Classifier: Programming Language :: Python :: 3.11
34
+ Classifier: Operating System :: POSIX :: Linux
35
+ Description-Content-Type: text/markdown
36
+ License-File: LICENSE
37
+ Requires-Dist: pandas==1.5.3
38
+ Requires-Dist: numpy
39
+ Requires-Dist: scanpy
40
+ Requires-Dist: scipy
41
+ Requires-Dist: statsmodels
42
+ Requires-Dist: scikit-learn
43
+ Requires-Dist: libpysal
44
+ Requires-Dist: esda
45
+ Requires-Dist: tqdm
46
+ Requires-Dist: jupyter
47
+ Requires-Dist: matplotlib
48
+ Requires-Dist: seaborn
49
+ Dynamic: license-file
50
+
51
+ # Spatial Isoform Finder (Spl-IsoFind)
52
+
53
+ Spl-IsoFind can be used to detect spatially variable isoforms in long-read spatial transcriptomics data.
54
+
55
+ ### Installation
56
+
57
+ SplIsoFind requires Python 3.9 or higher. The easiest way to install is through the following command:
58
+
59
+ ```
60
+ pip install SplIsoFind
61
+ ```
62
+
63
+ ### Tutorials
64
+
65
+ The tutorial folder contains notebooks to run Spl-IsoFind on demo data. See the documentation for more information. The demo datasets can be downloaded here:
66
+
67
+ For citation and further information please refer to our [preprint](https://www.biorxiv.org/content/10.1101/2025.06.25.661563v1)
68
+
@@ -0,0 +1,18 @@
1
+ # Spatial Isoform Finder (Spl-IsoFind)
2
+
3
+ Spl-IsoFind can be used to detect spatially variable isoforms in long-read spatial transcriptomics data.
4
+
5
+ ### Installation
6
+
7
+ SplIsoFind requires Python 3.9 or higher. The easiest way to install is through the following command:
8
+
9
+ ```
10
+ pip install SplIsoFind
11
+ ```
12
+
13
+ ### Tutorials
14
+
15
+ The tutorial folder contains notebooks to run Spl-IsoFind on demo data. See the documentation for more information. The demo datasets can be downloaded here:
16
+
17
+ For citation and further information please refer to our [preprint](https://www.biorxiv.org/content/10.1101/2025.06.25.661563v1)
18
+
@@ -0,0 +1,44 @@
1
+ [build-system]
2
+ requires = ["setuptools>=42", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "SplIsoFind"
7
+ version = "0.1.0"
8
+ description = "Spatial Isoform Finder detects spatially variable isoforms in long-read spatial data"
9
+ readme = { file = "README.md", content-type = "text/markdown" }
10
+ license = { file = "LICENSE" }
11
+ authors = [
12
+ { name = "Lieke Michielsen", email = "lim4020@med.cornell.edu" }
13
+ ]
14
+ keywords = ["spatial transcriptomics", "long read", "alternative splicing", "isoform"]
15
+ classifiers = [
16
+ "Development Status :: 5 - Production/Stable",
17
+ "Intended Audience :: Science/Research",
18
+ "License :: OSI Approved :: MIT License",
19
+ "Programming Language :: Python :: 3.9",
20
+ "Programming Language :: Python :: 3.10",
21
+ "Programming Language :: Python :: 3.11",
22
+ "Operating System :: POSIX :: Linux"
23
+ ]
24
+
25
+ dependencies = [
26
+ "pandas==1.5.3",
27
+ "numpy",
28
+ "scanpy",
29
+ "scipy",
30
+ "statsmodels",
31
+ "scikit-learn",
32
+ "libpysal",
33
+ "esda",
34
+ "tqdm",
35
+ "jupyter",
36
+ "matplotlib",
37
+ "seaborn"
38
+ ]
39
+
40
+ [tool.setuptools]
41
+ package-dir = {"" = "src"}
42
+
43
+ [tool.setuptools.packages.find]
44
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
File without changes
@@ -0,0 +1,268 @@
1
+ # SPDX-License-Identifier: MIT
2
+ """
3
+ Spatial autocorrelation functions using Moran's I.
4
+
5
+ This module provides functions to compute Moran's I for long-read spatial transcriptomics data,
6
+ including permutation-based significance testing and FDR correction.
7
+ """
8
+
9
+ from pathlib import Path
10
+ import pandas as pd
11
+ import numpy as np
12
+
13
+ from tqdm.notebook import tqdm
14
+
15
+ from statsmodels.stats.multitest import fdrcorrection
16
+
17
+ from sklearn.neighbors import NearestNeighbors
18
+ from libpysal.weights import W
19
+ import esda
20
+
21
+ def moransI(
22
+ x: pd.DataFrame,
23
+ labels: pd.DataFrame,
24
+ nperm: int = 100000,
25
+ k: int = 10,
26
+ mincells: int = 50,
27
+ imb: float = 0.05,
28
+ mincellspergroup: int = 20,
29
+ celltypes: list = ['All','ExciteNeuron','InhibNeuron','Astro','Oligo'],
30
+ x_coord: str = 'x',
31
+ y_coord: str = 'y',
32
+ output_dir: str = ''
33
+ ) -> tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame]:
34
+ """
35
+ Compute Moran's I scores, p-values, and q-values (Benjaminini-Yekutieli FDR-corrected) for each isoform and cell type.
36
+
37
+ Parameters
38
+ ----------
39
+ x : pandas.DataFrame
40
+ Feature matrix of shape (n_cells, n_isoforms), with relative expression values between 0 and 1.
41
+ labels : pandas.DataFrame
42
+ Cell metadata, must contain columns for `x_coord`, `y_coord`,
43
+ `spot_class`, and `first_type`.`spot_class` and `first_type` are used to filter cells per cell type.
44
+ nperm : int, default=100000
45
+ Number of permutations for significance testing.
46
+ k : int, default=10
47
+ Number of nearest neighbors for spatial weight matrix.
48
+ mincells : int, default=50
49
+ Minimum number of cells required to have relative expression values for an isoform.
50
+ imb : float, default=0.05
51
+ Minimum ratio of minority group to total.
52
+ mincellspergroup : int, default=20
53
+ Minimum number of cells per binary group (x > 0.5 or ≤ 0.5).
54
+ celltypes : list of str
55
+ List of cell type labels to test; 'All' computes on all cells.
56
+ x_coord, y_coord : str
57
+ Column names in `labels` for spatial coordinates.
58
+ output_dir : str
59
+ Directory path to save Moran's I scores, p-values, and q-values as CSV files.
60
+
61
+ Returns
62
+ -------
63
+ mI : pandas.DataFrame
64
+ Moran's I scores, index = isoforms, columns = celltypes.
65
+ pval : pandas.DataFrame
66
+ Permutation p-values, index = isoforms, columns = celltypes.
67
+ qval : pandas.DataFrame
68
+ FDR-corrected q-values, index = isoforms, columns = celltypes.
69
+ """
70
+ mI = pd.DataFrame(np.nan, index=x.columns, columns=celltypes)
71
+ pval = pd.DataFrame(np.nan, index=x.columns, columns=celltypes)
72
+ qval = pd.DataFrame(np.nan, index=x.columns, columns=celltypes)
73
+
74
+ for i in tqdm(range(x.shape[1])):
75
+
76
+ x_i = x.iloc[:,i].dropna()
77
+ labels_i = labels.loc[x_i.index]
78
+
79
+ _, counts = np.unique(x_i > 0.5, return_counts=True) # Check if we have enough high and low values
80
+
81
+ if (len(x_i) >= mincells) & np.all(counts >= mincellspergroup) & (x_i.var() > 0):
82
+
83
+ for ct in celltypes:
84
+ if ct == 'All':
85
+ # Check imbalance
86
+ if (np.min(counts)/len(x_i) >= imb):
87
+ w = calculate_weight_matrix_sklearn(labels_i[[x_coord, y_coord]], k)
88
+ res = esda.Moran(x_i, w, permutations=nperm, transformation='b')
89
+ mI.loc[x.columns[i], ct] = res.I
90
+ if res.I > 0:
91
+ pval.loc[x.columns[i], ct] = res.p_sim
92
+ else:
93
+ pval.loc[x.columns[i], ct] = 1
94
+ else:
95
+ tokeep_ct = (labels_i['spot_class'] == 'singlet') & (labels_i['first_type'] == ct)
96
+ x_i_ct = x_i[tokeep_ct]
97
+ _, counts_ct = np.unique(x_i_ct > 0.5, return_counts=True)
98
+
99
+ if (np.sum(tokeep_ct) >= mincells) & np.all(counts_ct >= mincellspergroup) & (x_i_ct.var() > 0):
100
+ if (np.min(counts_ct)/len(x_i_ct) >= imb):
101
+ w = calculate_weight_matrix_sklearn(labels_i.loc[tokeep_ct.values,[x_coord, y_coord]], k)
102
+ res = esda.Moran(x_i_ct, w, permutations=nperm, transformation='b')
103
+ mI.loc[x.columns[i], ct] = res.I
104
+ if res.I > 0:
105
+ pval.loc[x.columns[i], ct] = res.p_sim
106
+ else:
107
+ pval.loc[x.columns[i], ct] = 1
108
+
109
+ # BY FDR correction
110
+ for ct in celltypes:
111
+ tocorrect = pval[ct][pval[ct].notna()]
112
+ _, q = fdrcorrection(tocorrect, method='n')
113
+ qval[ct][pval[ct].notna()] = q
114
+
115
+ Path(output_dir).mkdir(parents=True, exist_ok=True)
116
+ output_mI = f"{output_dir}/MoransI_scores_nperm{nperm}_k{k}_mincells{mincells}_mincellspergroup{mincellspergroup}_imb{imb}.csv"
117
+ output_pval = f"{output_dir}/MoransI_pval_nperm{nperm}_k{k}_mincells{mincells}_mincellspergroup{mincellspergroup}_imb{imb}.csv"
118
+ output_qval = f"{output_dir}/MoransI_qval_nperm{nperm}_k{k}_mincells{mincells}_mincellspergroup{mincellspergroup}_imb{imb}.csv"
119
+
120
+ mI.to_csv(output_mI)
121
+ pval.to_csv(output_pval)
122
+ qval.to_csv(output_qval)
123
+
124
+ return mI, pval, qval
125
+
126
+
127
+ def calculate_weight_matrix_sklearn(
128
+ locations: pd.DataFrame,
129
+ k: int
130
+ ) -> W:
131
+ """
132
+ Build a libpysal spatial weights matrix via k-nearest neighbors.
133
+
134
+ Parameters
135
+ ----------
136
+ locations : pandas.DataFrame
137
+ Coordinates of cells, shape (n_cells, 2), columns = [x, y].
138
+ k : int
139
+ Number of neighbors to include (self excluded).
140
+
141
+ Returns
142
+ -------
143
+ W
144
+ libpysal.weights.W object with equal weights to k neighbors.
145
+ """
146
+
147
+ # Fit nearest neighbors model
148
+ # k+1 cause we will remove the diagonal afterwards
149
+ nn = NearestNeighbors(n_neighbors=k+1, algorithm='auto').fit(locations)
150
+
151
+ # Find k-nearest neighbors (distances and indices)
152
+ _, indices = nn.kneighbors(locations)
153
+
154
+ # Convert to libpysal object
155
+ neighbors = {i: list(indices[i, 1:]) for i in range(indices.shape[0])} # Remove self-reference
156
+ weights = {i: [1] * len(neighbors[i]) for i in neighbors} # Assign equal weights
157
+
158
+ return W(neighbors, weights)
159
+
160
+ def moransI_ctperm(
161
+ x: pd.DataFrame,
162
+ labels: pd.DataFrame,
163
+ variables: list,
164
+ nperm: int = 10000,
165
+ k: int = 10,
166
+ x_coord: str = 'x',
167
+ y_coord: str = 'y',
168
+ output_dir: str = ''
169
+ ) -> pd.DataFrame:
170
+ """
171
+ Compute Moran's I with cell-type constrained permutation.
172
+
173
+ Performs a two-phase test: original Moran's I permutation test (shuffling all cells) and
174
+ a permutation test while shuffling cells only within the same cell type.
175
+
176
+ Parameters
177
+ ----------
178
+ x : pandas.DataFrame
179
+ Feature matrix of shape (n_cells, n_isoforms), with relative expression values between 0 and 1.
180
+ labels : pandas.DataFrame
181
+ Cell metadata, must contain columns for `x_coord`, `y_coord`,
182
+ 'spot_class','first_type','first_type_weight','second_type'.
183
+ variables : list of str
184
+ Subset of columns in `x` to test.
185
+ nperm : int, default=10000
186
+ Number of random permutations for cell-type assignment.
187
+ k : int, default=10
188
+ Number of neighbors for spatial weight matrix.
189
+ x_coord, y_coord : str
190
+ Column names in `labels` for spatial coordinates.
191
+ output_dir : str
192
+ Directory path to save result as CSV files.
193
+
194
+ Returns
195
+ -------
196
+ res : pandas.DataFrame
197
+ Index = tested isoforms, columns = ['morans I','p-value (original)',
198
+ 'p-value (new)','Num cells','Imbalance'].
199
+ """
200
+ mI_score = []
201
+ p_original = []
202
+ p_new = []
203
+ num_cells = []
204
+ imb = []
205
+
206
+ for e in tqdm(variables):
207
+
208
+ perm_I = []
209
+
210
+ # Select exon of interest
211
+ x_i = x[e].dropna()
212
+ labels_i = labels.loc[x_i.index]
213
+
214
+ # Focus on singlets and doublet certain
215
+ labels_i = labels_i[((labels_i['spot_class'] == 'singlet') |
216
+ (labels_i['spot_class'] == 'doublet_certain'))]
217
+ x_i = x_i.loc[labels_i.index]
218
+
219
+ num_cells.append(len(x_i))
220
+ imb.append((x_i < 0.5).sum()/(len(x_i)))
221
+
222
+ # Original moran's I and p-value
223
+ w_i = calculate_weight_matrix_sklearn(labels_i[[x_coord, y_coord]], k)
224
+ res = esda.Moran(x_i, w_i, permutations=nperm, transformation='b', two_tailed=False)
225
+
226
+ mI_score.append(res.I)
227
+ p_original.append(res.p_sim)
228
+
229
+ for _ in range(nperm):
230
+
231
+ # Convert to NumPy arrays for faster access
232
+ first_type = labels_i['first_type'].values.copy()
233
+ spot_class = labels_i['spot_class'].values.copy()
234
+ first_type_weight = labels_i['first_type_weight'].values.copy()
235
+ second_type = labels_i['second_type'].values.copy()
236
+
237
+ # Define our temp. cell-type labels for the doublets
238
+ doublet_certain_mask = spot_class == 'doublet_certain'
239
+ rand_vals = np.random.rand(np.sum(doublet_certain_mask))
240
+ first_type[doublet_certain_mask] = np.where(
241
+ rand_vals > first_type_weight[doublet_certain_mask],
242
+ second_type[doublet_certain_mask],
243
+ first_type[doublet_certain_mask]
244
+ )
245
+
246
+ # Permutate each cell-type separately
247
+ cts = np.unique(first_type)
248
+ x_i_temp = x_i.copy()
249
+ for ct in cts:
250
+ idx_ct = np.where(first_type == ct)[0]
251
+ x_i_temp.iloc[idx_ct] = np.random.permutation(x_i_temp.iloc[idx_ct])
252
+
253
+ # Calculate new statistic
254
+ res_perm = esda.Moran(x_i_temp, w_i, permutations=0, transformation='b')
255
+ perm_I.append(res_perm.I)
256
+
257
+ # New p-value
258
+ p = (np.sum(np.array(perm_I) >= res.I)+1)/(nperm+1)
259
+ p_new.append(p)
260
+
261
+ res = pd.DataFrame([mI_score, p_original, p_new, num_cells, imb], columns=variables,
262
+ index=['morans I', 'p-value (original)', 'p-value (new)', 'Num cells', 'Imbalance']).T
263
+
264
+ Path(output_dir).mkdir(parents=True, exist_ok=True)
265
+ output_res = f"{output_dir}/MoransI_pval_nperm{nperm}_k{k}_ctconstrained.csv"
266
+ res.to_csv(output_res)
267
+
268
+ return res