SPACEc 0.0.2__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.
@@ -0,0 +1,3561 @@
1
+ # load required packages
2
+ from __future__ import annotations
3
+
4
+ import os
5
+ import platform
6
+ import subprocess
7
+ import sys
8
+ import zipfile
9
+
10
+ import requests
11
+
12
+ if platform.system() == "Windows":
13
+ vipsbin = r"c:\vips-dev-8.15\bin\vips-dev-8.15\bin"
14
+ vips_file_path = os.path.join(vipsbin, "vips.exe")
15
+
16
+ # Check if VIPS is installed
17
+ if not os.path.exists(vips_file_path):
18
+ # VIPS is not installed, download and extract it
19
+ url = "https://github.com/libvips/build-win64-mxe/releases/download/v8.15.2/vips-dev-w64-all-8.15.2.zip"
20
+ zip_file_path = "vips-dev-w64-all-8.15.2.zip"
21
+ response = requests.get(url, stream=True)
22
+
23
+ if response.status_code == 200:
24
+ with open(zip_file_path, "wb") as f:
25
+ f.write(response.raw.read())
26
+
27
+ # Extract the zip file
28
+ with zipfile.ZipFile(zip_file_path, "r") as zip_ref:
29
+ zip_ref.extractall(vipsbin)
30
+ else:
31
+ print("Error downloading the file.")
32
+
33
+ # Install pyvips
34
+ subprocess.check_call([sys.executable, "-m", "pip", "install", "pyvips"])
35
+
36
+ # Add vipsbin to the DLL search path or PATH environment variable
37
+ add_dll_dir = getattr(os, "add_dll_directory", None)
38
+ os.environ["PATH"] = os.pathsep.join((vipsbin, os.environ["PATH"]))
39
+
40
+
41
+ import argparse
42
+ import pathlib
43
+ import pickle
44
+ import time
45
+ from builtins import range
46
+ from itertools import combinations
47
+ from multiprocessing import Pool
48
+ from typing import TYPE_CHECKING
49
+
50
+ import anndata
51
+ import concave_hull
52
+ import matplotlib.pyplot as plt
53
+ import networkx as nx
54
+ import numpy as np
55
+ import pandas as pd
56
+ import scipy.stats as st
57
+ import skimage
58
+ import skimage.color
59
+ import skimage.exposure
60
+ import skimage.filters.rank
61
+ import skimage.io as io
62
+ import skimage.morphology
63
+ import skimage.transform
64
+ import statsmodels.api as sm
65
+ import tissuumaps.jupyter as tj
66
+ import torch
67
+ from concave_hull import concave_hull_indexes
68
+ from joblib import Parallel, delayed
69
+ from pyFlowSOM import map_data_to_nodes, som
70
+ from scipy import stats
71
+ from scipy.spatial import Delaunay, KDTree, distance
72
+ from scipy.spatial.distance import cdist
73
+ from scipy.stats import pearsonr, spearmanr
74
+ from skimage.io import imsave
75
+ from skimage.segmentation import find_boundaries
76
+ from sklearn.cluster import HDBSCAN, MiniBatchKMeans
77
+ from sklearn.cross_decomposition import CCA
78
+ from sklearn.ensemble import RandomForestClassifier
79
+ from sklearn.metrics import classification_report, f1_score, pairwise_distances
80
+ from sklearn.model_selection import train_test_split
81
+ from sklearn.neighbors import NearestNeighbors
82
+ from sklearn.svm import SVC
83
+ from tqdm import tqdm
84
+ from yellowbrick.cluster import KElbowVisualizer
85
+
86
+ if TYPE_CHECKING:
87
+ from anndata import AnnData
88
+
89
+ from ..helperfunctions._general import *
90
+
91
+ try:
92
+ from torch_geometric.data import ClusterData, ClusterLoader, Data, InMemoryDataset
93
+ except ImportError:
94
+ pass
95
+
96
+ try:
97
+ import cupy as cp
98
+ import rapids_singlecell as rsc
99
+ from cupyx.scipy.sparse import csc_matrix as csc_matrix_gpu
100
+ from cupyx.scipy.sparse import csr_matrix as csr_matrix_gpu
101
+ from cupyx.scipy.sparse import isspmatrix_csc as isspmatrix_csc_gpu
102
+ from cupyx.scipy.sparse import isspmatrix_csr as isspmatrix_csr_gpu
103
+ from scanpy.get import _get_obs_rep, _set_obs_rep
104
+ from scipy.sparse import isspmatrix_csc as isspmatrix_csc_cpu
105
+ from scipy.sparse import isspmatrix_csr as isspmatrix_csr_cpu
106
+ except ImportError:
107
+ pass
108
+
109
+ # Tools
110
+ ############################################################
111
+
112
+
113
+ ############
114
+ """
115
+ The function tl_cell_types_de performs differential enrichment analysis for various cell subsets between different neighborhoods using linear regression.
116
+ It takes in several inputs such as cell type frequencies, neighborhood numbers, and patient information.
117
+ The function first normalizes overall cell type frequencies and then neighborhood-specific cell type frequencies. Next, a linear regression model is fitted to find the coefficients and p-values for the group coefficient.
118
+ Finally, the function returns a dataframe with the coefficients and p-values for each cell subset. The p-values can be corrected for multiple testing after the function has been executed.
119
+ """
120
+
121
+
122
+ def tl_cell_types_de(
123
+ ct_freq, all_freqs, neighborhood_num, nbs, patients, group, cells, cells1
124
+ ):
125
+ # data prep
126
+ # normalized overall cell type frequencies
127
+ X_cts = hf_normalize(
128
+ ct_freq.reset_index().set_index("patients").loc[patients, cells]
129
+ )
130
+
131
+ # normalized neighborhood specific cell type frequencies
132
+ df_list = []
133
+
134
+ for nb in nbs:
135
+ cond_nb = (
136
+ all_freqs.loc[all_freqs[neighborhood_num] == nb, cells1]
137
+ .rename({col: col + "_" + str(nb) for col in cells}, axis=1)
138
+ .set_index("patients")
139
+ )
140
+ df_list.append(hf_normalize(cond_nb))
141
+
142
+ X_cond_nb = pd.concat(df_list, axis=1).loc[patients]
143
+
144
+ # differential enrichment for all cell subsets
145
+ changes = {}
146
+ # nbs =[0, 2, 3, 4, 6, 7, 8, 9]
147
+ for col in cells:
148
+ for nb in nbs:
149
+ # build a design matrix with a constant, group 0 or 1 and the overall frequencies
150
+ X = pd.concat(
151
+ [
152
+ X_cts[col],
153
+ group.astype("int"),
154
+ pd.Series(np.ones(len(group)), index=group.index.values),
155
+ ],
156
+ axis=1,
157
+ ).values
158
+ if col + "_%d" % nb in X_cond_nb.columns:
159
+ # set the neighborhood specific ct freqs as the outcome
160
+ Y = X_cond_nb[col + "_%d" % nb].values
161
+ X = X[~pd.isna(Y)]
162
+ Y = Y[~pd.isna(Y)]
163
+ # fit a linear regression model
164
+ results = sm.OLS(Y, X).fit()
165
+ # find the params and pvalues for the group coefficient
166
+ changes[(col, nb)] = (results.pvalues[1], results.params[1])
167
+
168
+ # make a dataframe with coeffs and pvalues
169
+ dat = pd.DataFrame(changes).loc[1].unstack()
170
+ dat = (
171
+ pd.DataFrame(np.nan_to_num(dat.values), index=dat.index, columns=dat.columns)
172
+ .T.sort_index(ascending=True)
173
+ .loc[:, X_cts.columns]
174
+ )
175
+ pvals = (
176
+ (pd.DataFrame(changes).loc[0].unstack())
177
+ .T.sort_index(ascending=True)
178
+ .loc[:, X_cts.columns]
179
+ )
180
+
181
+ # this is where you should correct pvalues for multiple testing
182
+
183
+ return dat, pvals
184
+
185
+
186
+ #########
187
+
188
+
189
+ def tl_Create_neighborhoods(
190
+ df, n_num, cluster_col, X, Y, regions, sum_cols=None, keep_cols=None, ks=[20]
191
+ ):
192
+ if sum_cols == None:
193
+ sum_cols = df[cluster_col].unique()
194
+
195
+ if keep_cols == None:
196
+ keep_cols = df.columns.values.tolist()
197
+
198
+ Neigh = Neighborhoods(
199
+ df, ks, cluster_col, sum_cols, keep_cols, X, Y, regions, add_dummies=True
200
+ )
201
+ windows = Neigh.k_windows()
202
+
203
+ return (windows, sum_cols)
204
+
205
+
206
+ ######
207
+
208
+
209
+ def tl_Chose_window_size(
210
+ windows, n_num, n_neighborhoods, sum_cols, n2_name="neigh_ofneigh"
211
+ ):
212
+ # Choose the windows size to continue with
213
+ w = windows[n_num]
214
+
215
+ k_centroids = {}
216
+
217
+ km = MiniBatchKMeans(n_clusters=n_neighborhoods, random_state=0)
218
+ labels = km.fit_predict(w[sum_cols].values)
219
+ k_centroids[n_num] = km.cluster_centers_
220
+ w[n2_name] = labels
221
+
222
+ return (w, k_centroids)
223
+
224
+
225
+ #######
226
+
227
+
228
+ def tl_calculate_neigh_combs(w, l, n_num, threshold=0.85, per_keep_thres=0.85):
229
+ w.loc[:, l]
230
+
231
+ # need to normalize by number of neighborhoods or k chosen for the neighborhoods
232
+ xm = w.loc[:, l].values / n_num
233
+
234
+ # Get the neighborhood combinations based on the threshold
235
+ simps = hf_get_thresh_simps(xm, threshold)
236
+ simp_freqs = simps.value_counts(normalize=True)
237
+ simp_sums = np.cumsum(simp_freqs)
238
+
239
+ # See the percent to keep threshold or percent of neigbhorhoods that fall above a certain threshold
240
+ test_sums_thres = simp_sums[simp_sums < per_keep_thres]
241
+ test_len = len(test_sums_thres)
242
+ per_values_above = simp_sums[test_len] - simp_sums[test_len - 1]
243
+ print(test_len, per_values_above)
244
+
245
+ w["combination"] = [tuple(l[a] for a in s) for s in simps]
246
+ w["combination_num"] = [tuple(a for a in s) for s in simps]
247
+
248
+ # this shows what proportion (y) of the total cells are assigned to the top x combinations
249
+ plt.figure(figsize=(7, 3))
250
+ plt.plot(simp_sums.values)
251
+ plt.title(
252
+ "proportion (y) of the total cells are assigned to the top x combinations"
253
+ )
254
+ plt.show()
255
+
256
+ # this shows what proportion (y) of the total cells are assigned to the top x combinations
257
+ plt.figure(figsize=(7, 3))
258
+ plt.plot(test_sums_thres.values)
259
+ plt.title(
260
+ "proportion (y) of the total cells are assigned to the top x combinations - thresholded"
261
+ )
262
+ plt.show()
263
+ # plt.xticks(range(0,350,35),range(0,350,35),rotation = 90,fontsize = 10)
264
+
265
+ return (simps, simp_freqs, simp_sums)
266
+
267
+
268
+ #######
269
+
270
+
271
+ def tl_build_graph_CN_comb_map(simp_freqs, thresh_freq=0.001):
272
+ g = nx.DiGraph()
273
+
274
+ # selected_simps = simp_sums[simp_sums<=thresh_cumulative].index.values
275
+ selected_simps = simp_freqs[simp_freqs >= thresh_freq].index.values
276
+ selected_simps
277
+
278
+ """
279
+ this builds the graph for the CN combination map
280
+ """
281
+ for e0 in selected_simps:
282
+ for e1 in selected_simps:
283
+ if (set(list(e0)) < set(list(e1))) and (len(e1) == len(e0) + 1):
284
+ g.add_edge(e0, e1)
285
+
286
+ tops = (
287
+ simp_freqs[simp_freqs >= thresh_freq]
288
+ .sort_values(ascending=False)
289
+ .index.values.tolist()[:20]
290
+ )
291
+
292
+ return (g, tops, e0, e1)
293
+
294
+
295
+ #######
296
+
297
+
298
+ def tl_spatial_context_stats(
299
+ n_num,
300
+ patient_ID_component1,
301
+ patient_ID_component2,
302
+ windows,
303
+ total_per_thres=0.9,
304
+ comb_per_thres=0.005,
305
+ tissue_column="Block type",
306
+ subset_list=["Resection"],
307
+ plot_order=["Resection", "Biopsy"],
308
+ pal_tis={"Resection": "blue", "Biopsy": "orange"},
309
+ subset_list_tissue1=["Resection"],
310
+ subset_list_tissue2=["Biopsy"],
311
+ ):
312
+ data_compare = windows[n_num]
313
+
314
+ # Prepare IDs this could for example be the combination of patient ID and tissue type. Apart from that, the function assigns a number to each name from the neighborhood column
315
+ data_compare = prepare_neighborhood_df(
316
+ data_compare,
317
+ neighborhood_column=None,
318
+ patient_ID_component1=patient_ID_component1,
319
+ patient_ID_component2=patient_ID_component2,
320
+ ) # this is a helper function
321
+
322
+ data_compare["donor_tis"].unique()
323
+
324
+ simp_df_tissue1 = hf_simp_rep(
325
+ data=data_compare,
326
+ patient_col="donor_tis",
327
+ tissue_column=tissue_column,
328
+ subset_list_tissue=subset_list_tissue1,
329
+ ttl_per_thres=total_per_thres,
330
+ comb_per_thres=comb_per_thres,
331
+ thres_num=1,
332
+ )
333
+ print(simp_df_tissue1)
334
+
335
+ simp_df_tissue2 = hf_simp_rep(
336
+ data=data_compare,
337
+ patient_col="donor_tis",
338
+ tissue_column=tissue_column,
339
+ subset_list_tissue=subset_list_tissue2,
340
+ ttl_per_thres=total_per_thres,
341
+ comb_per_thres=comb_per_thres,
342
+ thres_num=1,
343
+ )
344
+ print(simp_df_tissue2)
345
+
346
+ ##### Compare the organization at high level to see if differences in combinations - more or less structured/compartmentalized
347
+ data_simp = [simp_df_tissue1, simp_df_tissue2]
348
+ df_num_count = pl_comb_num_freq(data_list=data_simp)
349
+ print(df_num_count)
350
+
351
+ return (simp_df_tissue1, simp_df_tissue2)
352
+
353
+
354
+ ###########
355
+
356
+
357
+ def tl_xycorr(df, sample_col, y_rows, x_columns, X_pix, Y_pix):
358
+ # Make a copy for xy correction
359
+ df_XYcorr = df.copy()
360
+
361
+ df_XYcorr["Xcorr"] = 0
362
+ df_XYcorr["Ycorr"] = 0
363
+
364
+ for sample in df_XYcorr[sample_col].unique():
365
+ df_sub = df_XYcorr.loc[df_XYcorr[sample_col] == sample]
366
+ region_num = df_sub.region.max().astype(int)
367
+
368
+ # first value of tuple is y and second is x
369
+ d = list(product(range(0, y_rows, 1), range(0, x_columns, 1)))
370
+ e = list(range(1, region_num + 1, 1))
371
+ dict_corr = {}
372
+ dict_corr = dict(zip(e, d))
373
+
374
+ # Adding the pixels with the dictionary
375
+ for x in range(1, region_num + 1, 1):
376
+ df_XYcorr["Xcorr"].loc[
377
+ (df_XYcorr["region"] == x) & (df_XYcorr[sample_col] == sample)
378
+ ] = (
379
+ df_XYcorr["x"].loc[
380
+ (df_XYcorr["region"] == x) & (df_XYcorr[sample_col] == sample)
381
+ ]
382
+ + dict_corr[x][1] * X_pix
383
+ )
384
+
385
+ for x in range(1, region_num + 1, 1):
386
+ df_XYcorr["Ycorr"].loc[
387
+ (df_XYcorr["region"] == x) & (df_XYcorr[sample_col] == sample)
388
+ ] = (
389
+ df_XYcorr["y"].loc[
390
+ (df_XYcorr["region"] == x) & (df_XYcorr[sample_col] == sample)
391
+ ]
392
+ + dict_corr[x][0] * Y_pix
393
+ )
394
+
395
+ return df_XYcorr
396
+
397
+
398
+ ###############
399
+
400
+
401
+ def tl_get_distances(df, cell_list, cell_type_col):
402
+ names = cell_list
403
+ cls = {}
404
+ for i, cname in enumerate(names):
405
+ cls[i] = df[["x", "y"]][df[cell_type_col] == cname].to_numpy()
406
+ cls[i] = cls[i][~np.isnan(cls[i]).any(axis=1), :]
407
+
408
+ dists = {}
409
+
410
+ for i in range(5):
411
+ for j in range(0, i):
412
+ dists[(j, i)] = cdist(cls[j], cls[i])
413
+ dists[(i, j)] = dists[(j, i)]
414
+ return cls, dists
415
+
416
+
417
+ ###############
418
+ # clustering
419
+
420
+
421
+ def clustering(
422
+ adata,
423
+ clustering="leiden",
424
+ marker_list=None,
425
+ resolution=1,
426
+ n_neighbors=10,
427
+ reclustering=False,
428
+ key_added=None,
429
+ key_filter=None,
430
+ subset_cluster=None,
431
+ seed=42,
432
+ fs_xdim=10,
433
+ fs_ydim=10,
434
+ fs_rlen=10, # FlowSOM parameters
435
+ **cluster_kwargs,
436
+ ):
437
+ """
438
+ Perform clustering on the given annotated data matrix.
439
+
440
+ Parameters
441
+ ----------
442
+ adata : AnnData
443
+ The annotated data matrix of shape n_obs x n_vars. Rows correspond
444
+ to cells and columns to stained markers.
445
+ clustering : str, optional
446
+ The clustering algorithm to use. Options are "leiden" or "louvain". Defaults to "leiden".
447
+ marker_list : list, optional
448
+ A list of markers for clustering. Defaults to None.
449
+ resolution : int, optional
450
+ The resolution for the clustering algorithm. Defaults to 1.
451
+ n_neighbors : int, optional
452
+ The number of neighbors to use for the neighbors graph. Defaults to 10.
453
+ reclustering : bool, optional
454
+ Whether to recluster the data. Defaults to False.
455
+ key_added : str, optional
456
+ The key name to add to the adata object. Defaults to None.
457
+ key_filter : str, optional
458
+ The key name to filter the adata object. Defaults to None.
459
+ subset_cluster : list, optional
460
+ The list of clusters to subset. Defaults to None.
461
+ seed : int, optional
462
+ Seed for random state. Default is 42.
463
+ fs_xdim : int, optional
464
+ X dimension for FlowSOM. Default is 10.
465
+ fs_ydim : int, optional
466
+ Y dimension for FlowSOM. Default is 10.
467
+ fs_rlen : int, optional
468
+ Rlen for FlowSOM. Default is 10.
469
+ **cluster_kwargs : dict
470
+ Additional keyword arguments for the clustering function.
471
+
472
+ Returns
473
+ -------
474
+ AnnData
475
+ The annotated data matrix with the clustering results added.
476
+ """
477
+ if clustering not in ["leiden", "louvain", "leiden_gpu", "flowSOM"]:
478
+ print(
479
+ "Invalid clustering options. Please select from leiden, louvain, leiden_gpu or flowSOM!"
480
+ )
481
+ print("For GPU accelerated leiden clustering, please use leiden_gpu")
482
+ sys.exit()
483
+
484
+ # test if rapids_singlecell is available
485
+ if clustering == "leiden_gpu":
486
+ try:
487
+ import cudf
488
+ import cuml
489
+ import cupy
490
+ import rapids_singlecell as rsc
491
+ except ImportError:
492
+ print("Please install rapids_singlecell to use leiden_gpu!")
493
+ print("install_gpu_leiden(CUDA = your cuda version as string)")
494
+ print("For example: sp.tl.install_gpu_leiden(CUDA = '12')")
495
+ print("THIS FUNCTION DOES NOT WORK ON MacOS OR WINDOWS")
496
+ print("using leiden instead of leiden_gpu")
497
+ clustering = "leiden"
498
+
499
+ if key_added is None:
500
+ key_added = clustering + "_" + str(resolution)
501
+
502
+ if key_filter is not None:
503
+ if subset_cluster is None:
504
+ print("Please provide subset_cluster!")
505
+ sys.exit()
506
+ else:
507
+ adata_tmp = adata
508
+ adata = adata[adata.obs[key_filter].isin(subset_cluster)]
509
+
510
+ # input a list of markers for clustering
511
+ # reconstruct the anndata
512
+ if marker_list is not None:
513
+ if len(list(set(marker_list) - set(adata.var_names))) > 0:
514
+ print("Marker list not all in adata var_names! Using intersection instead!")
515
+ marker_list = list(set(marker_list) & set(adata.var_names))
516
+ print("New marker_list: " + " ".join(marker_list))
517
+ if key_filter is None:
518
+ adata_tmp = adata
519
+ adata = adata[:, marker_list]
520
+
521
+ # Compute the neighborhood relations of single cells the range 2 to 100 and usually 10
522
+ if reclustering:
523
+ if clustering == "leiden_gpu":
524
+ print("Clustering on GPU")
525
+ anndata_to_GPU(adata) # moves `.X` to the GPU
526
+ rsc.tl.leiden(
527
+ adata,
528
+ resolution=resolution,
529
+ key_added=key_added,
530
+ random_state=seed,
531
+ **cluster_kwargs,
532
+ )
533
+ anndata_to_CPU(adata) # moves `.X` to the CPU
534
+ else:
535
+ print("Clustering")
536
+ if clustering == "leiden":
537
+ sc.tl.leiden(
538
+ adata,
539
+ resolution=resolution,
540
+ key_added=key_added,
541
+ random_state=seed,
542
+ **cluster_kwargs,
543
+ )
544
+ else:
545
+ if clustering == "louvain":
546
+ print("Louvain clustering")
547
+ sc.tl.louvain(
548
+ adata,
549
+ resolution=resolution,
550
+ key_added=key_added,
551
+ random_state=seed,
552
+ **cluster_kwargs,
553
+ )
554
+ else:
555
+ print("FlowSOM clustering")
556
+ adata_df = pd.DataFrame(
557
+ adata.X, index=adata.obs.index, columns=adata.var.index
558
+ )
559
+ # df to numpy array
560
+ som_input_arr = adata_df.to_numpy()
561
+ # train the SOM
562
+ node_output = som(
563
+ som_input_arr,
564
+ xdim=fs_xdim,
565
+ ydim=fs_ydim,
566
+ rlen=fs_rlen,
567
+ seed=seed,
568
+ )
569
+ # use trained SOM to assign clusters to each observation in your data
570
+ clusters, dists = map_data_to_nodes(node_output, som_input_arr)
571
+ clusters = pd.Categorical(clusters)
572
+ # add cluster to adata
573
+ adata.obs[key_added] = clusters
574
+ else:
575
+ if clustering == "leiden_gpu":
576
+ anndata_to_GPU(adata) # moves `.X` to the GPU
577
+ print("Computing neighbors and UMAP on GPU")
578
+ rsc.pp.neighbors(adata, n_neighbors=n_neighbors)
579
+ # UMAP computation
580
+ rsc.tl.umap(adata)
581
+ print("Clustering on GPU")
582
+ # Perform leiden clustering - improved version of louvain clustering
583
+ rsc.tl.leiden(
584
+ adata, resolution=resolution, key_added=key_added, random_state=seed
585
+ )
586
+ anndata_to_CPU(adata) # moves `.X` to the CPU
587
+
588
+ else:
589
+ print("Computing neighbors and UMAP")
590
+ sc.pp.neighbors(adata, n_neighbors=n_neighbors)
591
+ # UMAP computation
592
+ sc.tl.umap(adata)
593
+ print("Clustering")
594
+ # Perform leiden clustering - improved version of louvain clustering
595
+ if clustering == "leiden":
596
+ print("Leiden clustering")
597
+ sc.tl.leiden(
598
+ adata,
599
+ resolution=resolution,
600
+ key_added=key_added,
601
+ random_state=seed,
602
+ **cluster_kwargs,
603
+ )
604
+ else:
605
+ if clustering == "louvain":
606
+ print("Louvain clustering")
607
+ sc.tl.louvain(
608
+ adata,
609
+ resolution=resolution,
610
+ key_added=key_added,
611
+ random_state=seed,
612
+ **cluster_kwargs,
613
+ )
614
+ else:
615
+ print("FlowSOM clustering")
616
+ adata_df = pd.DataFrame(
617
+ adata.X, index=adata.obs.index, columns=adata.var.index
618
+ )
619
+ # df to numpy array
620
+ som_input_arr = adata_df.to_numpy()
621
+ # train the SOM
622
+ node_output = som(
623
+ som_input_arr,
624
+ xdim=fs_xdim,
625
+ ydim=fs_ydim,
626
+ rlen=fs_rlen,
627
+ seed=seed,
628
+ )
629
+ # use trained SOM to assign clusters to each observation in your data
630
+ clusters, dists = map_data_to_nodes(node_output, som_input_arr)
631
+
632
+ # make clusters a string
633
+ clusters = clusters.astype(str)
634
+
635
+ clusters = pd.Categorical(clusters)
636
+ # add cluster to adata
637
+ adata.obs[key_added] = clusters
638
+
639
+ if key_filter is None:
640
+ if marker_list is None:
641
+ return adata
642
+ else:
643
+ adata_tmp.obs[key_added] = adata.obs[key_added].values
644
+ # append other data
645
+ adata_tmp.obsm = adata.obsm
646
+ adata_tmp.obsp = adata.obsp
647
+ adata_tmp.uns = adata.uns
648
+
649
+ if key_filter is not None:
650
+ original_df = adata_tmp.obs
651
+ donor_df = adata.obs
652
+
653
+ donor_df_cols = donor_df.loc[:, donor_df.columns != key_added].columns.tolist()
654
+ # Perform the merge operation
655
+ merged_df = pd.merge(
656
+ original_df,
657
+ donor_df,
658
+ left_on=donor_df_cols,
659
+ right_on=donor_df_cols,
660
+ how="left",
661
+ )
662
+
663
+ # Fill NA/NaN values in 'key_added' using the values from 'key_filter'
664
+ merged_df[key_filter] = merged_df[key_filter].astype(str)
665
+ merged_df[key_added] = merged_df[key_added].astype(str)
666
+
667
+ merged_df.replace("nan", np.nan, inplace=True)
668
+
669
+ merged_df[key_added].fillna(merged_df[key_filter], inplace=True)
670
+
671
+ merged_df[key_filter] = merged_df[key_filter].astype("category")
672
+ merged_df[key_added] = merged_df[key_added].astype("category")
673
+
674
+ merged_df.index = merged_df.index.astype(str)
675
+ # assign df as obs for adata_tmp
676
+ adata_tmp.obs = merged_df
677
+
678
+ return adata_tmp
679
+
680
+
681
+ ###############
682
+ # Patch analysis
683
+
684
+
685
+ def tl_generate_voronoi_plots(
686
+ df,
687
+ output_path,
688
+ grouping_col="Community",
689
+ tissue_col="tissue",
690
+ region_col="unique_region",
691
+ x_col="x",
692
+ y_col="y",
693
+ ):
694
+ """
695
+ Generate Voronoi plots for unique combinations of tissue and region.
696
+
697
+ Parameters:
698
+ df (pandas.DataFrame): Input DataFrame containing the data.
699
+ output_path (str): Output path to save the plots.
700
+ grouping_col (str): Column that contains group label that is used to color the voronoi diagrams
701
+ tissue_col (str): Column that contains tissue labels
702
+ region_col (str): Column that contains region labels
703
+ x_col (str): Column that contains x coordinates
704
+ y_col (str): Column that contains y coordinates
705
+
706
+ Returns:
707
+ None
708
+ """
709
+
710
+ unique_tissues = df[tissue_col].unique()
711
+ unique_regions = df[region_col].unique()
712
+
713
+ combinations = list(itertools.product(unique_tissues, unique_regions))
714
+
715
+ for tissue, region in combinations:
716
+ subset_df = df[(df[tissue_col] == tissue) & (df[region_col] == region)]
717
+ sorted_df = subset_df.sort_values(grouping_col)
718
+ unique_values = sorted_df[grouping_col].unique()
719
+
720
+ specific_output = os.path.join(output_path, tissue)
721
+ os.makedirs(specific_output, exist_ok=True)
722
+ specific_output = os.path.join(specific_output, region)
723
+ os.makedirs(specific_output, exist_ok=True)
724
+
725
+ for group in unique_values:
726
+ start = time.time()
727
+
728
+ output_filename = group + "_plot.png"
729
+ output_path2 = os.path.join(specific_output, output_filename)
730
+
731
+ color_dict = {}
732
+ for value in unique_values:
733
+ color_dict[value] = "black"
734
+ color_dict[group] = "white"
735
+
736
+ X = sorted_df[x_col]
737
+ Y = sorted_df[y_col]
738
+ np.random.seed(1234)
739
+ points = np.c_[X, Y]
740
+
741
+ vor = Voronoi(points)
742
+ regions, vertices = hf_voronoi_finite_polygons_2d(vor)
743
+ groups = sorted_df[grouping_col].values
744
+
745
+ fig, ax = plt.subplots()
746
+ ax.set_ylim(0, max(Y))
747
+ ax.set_xlim(0, max(X))
748
+ ax.axis("off")
749
+
750
+ for i, region in tqdm(
751
+ enumerate(regions), total=len(regions), desc="Processing regions"
752
+ ):
753
+ group = groups[i]
754
+ color = color_dict.get(group, "gray")
755
+ polygon = vertices[region]
756
+ ax.fill(*zip(*polygon), color=color)
757
+
758
+ ax.plot(points[:, 0], points[:, 1], "o", color="black", zorder=1, alpha=0)
759
+
760
+ fig.set_size_inches(9.41, 9.07 * 1.02718006795017)
761
+ fig.savefig(
762
+ output_path2, bbox_inches="tight", pad_inches=0, dpi=129.0809327846365
763
+ )
764
+ plt.close(fig)
765
+
766
+ end = time.time()
767
+ print(end - start)
768
+
769
+
770
+ def tl_generate_masks_from_images(
771
+ image_folder, mask_output, image_type=".tif", filter_size=5, threshold_value=10
772
+ ):
773
+ """
774
+ Generate binary masks from CODEX images.
775
+
776
+ Parameters:
777
+ image_folder (str): Directory that contains the images that are used to generate the masks
778
+ mask_output (str): Directory to store the generated masks
779
+ image_type (str): File type of image. By default ".tif"
780
+ filter_size (num): Size for filter disk during mask generation
781
+ threshold_value (num): Threshold value for binary mask generation
782
+
783
+ Returns:
784
+ None
785
+ """
786
+ folders_list = hf_list_folders(image_folder)
787
+ print(folders_list)
788
+ for folder in tqdm(folders_list, desc="Processing folders"):
789
+ direc = image_folder + "/" + folder
790
+ print(direc)
791
+
792
+ filelist = os.listdir(direc)
793
+ filelist = [f for f in filelist if f.endswith(image_type)]
794
+ print(filelist)
795
+
796
+ output_dir = mask_output + folder
797
+ os.makedirs(output_dir, exist_ok=True)
798
+
799
+ for f in tqdm(filelist, desc="Processing files"):
800
+ path = os.path.join(direc, f)
801
+ print(path)
802
+
803
+ tl_generate_mask(
804
+ path=path,
805
+ output_dir=output_dir,
806
+ filename="/" + f,
807
+ filter_size=filter_size,
808
+ threshold_value=threshold_value,
809
+ )
810
+
811
+
812
+ def tl_generate_info_dataframe(
813
+ df,
814
+ voronoi_output,
815
+ mask_output,
816
+ filter_list=None,
817
+ info_cols=["tissue", "donor", "unique_region", "region", "array"],
818
+ ):
819
+ """
820
+ Generate a filtered DataFrame based on specific columns and values.
821
+
822
+ Parameters:
823
+ df (pandas.DataFrame): Input DataFrame.
824
+ voronoi_output (str): Path to the Voronoi output directory.
825
+ mask_output (str): Path to the mask output directory.
826
+ info_cols (list): columns to extract from input df
827
+ filter_list (list, optional): List of values to filter.
828
+
829
+ Returns:
830
+ pandas.DataFrame: Filtered DataFrame.
831
+ """
832
+ df_info = df[info_cols].drop_duplicates()
833
+ df_info["folder_names"] = df_info["array"]
834
+ df_info["region"] = df_info["region"].astype(int)
835
+ df_info["region_long"] = ["reg00" + str(region) for region in df_info["region"]]
836
+ df_info["voronoi_path"] = (
837
+ voronoi_output + df_info["tissue"] + "/" + df_info["unique_region"]
838
+ )
839
+ df_info["mask_path"] = mask_output + df_info["folder_names"] + "/"
840
+
841
+ if filter_list != None:
842
+ # remove unwanted folders
843
+ df_info = df_info[~df_info["folder_names"].isin(filter_list)]
844
+
845
+ else:
846
+ print("no filter used")
847
+
848
+ return df_info
849
+
850
+
851
+ ###
852
+
853
+
854
+ def tl_process_files(voronoi_path, mask_path, region):
855
+ """
856
+ Process files based on the provided paths and region.
857
+
858
+ Parameters:
859
+ voronoi_path (str): Path to the Voronoi files.
860
+ mask_path (str): Path to the mask files.
861
+ region (str): Region identifier.
862
+
863
+ Returns:
864
+ None
865
+ """
866
+ png_files_list = hf_get_png_files(voronoi_path)
867
+ tiff_file_path = hf_find_tiff_file(mask_path, region)
868
+
869
+ if tiff_file_path:
870
+ print(f"Matching TIFF file found: {tiff_file_path}")
871
+ else:
872
+ print("No matching TIFF file found.")
873
+
874
+ for f in tqdm(png_files_list, desc="Processing files"):
875
+ print(f)
876
+ tl_apply_mask(f, tiff_file_path, f + "_cut.png")
877
+
878
+
879
+ ###
880
+
881
+
882
+ def tl_process_data(df_info, output_dir_csv):
883
+ """
884
+ Process data based on the information provided in the DataFrame.
885
+
886
+ Parameters:
887
+ df_info (pandas.DataFrame): DataFrame containing the information.
888
+ output_dir_csv (str): Output directory for CSV results.
889
+
890
+ Returns:
891
+ pandas.DataFrame: Concatenated DataFrame of results.
892
+ list: List of contours.
893
+ """
894
+ DF_list = []
895
+ contour_list = []
896
+
897
+ for index, row in df_info.iterrows():
898
+ voronoi_path = row["voronoi_path"]
899
+ mask_path = row["mask_path"]
900
+ region = row["region_long"]
901
+ donor = row["donor"]
902
+ unique_region = row["unique_region"]
903
+
904
+ png_files_list = hf_get_png_files(voronoi_path)
905
+ png_files_list = [
906
+ filename for filename in png_files_list if not filename.endswith("cut.png")
907
+ ]
908
+
909
+ tiff_file_path = hf_find_tiff_file(mask_path, region)
910
+
911
+ if tiff_file_path:
912
+ print(f"Matching TIFF file found: {tiff_file_path}")
913
+ else:
914
+ print("No matching TIFF file found.")
915
+
916
+ for f in png_files_list:
917
+ print(f)
918
+ g = f + "_cut" + ".png"
919
+ print(g)
920
+ tl_apply_mask(f, tiff_file_path, g)
921
+
922
+ output_dir_csv_tmp = output_dir_csv + "/" + donor + "_" + unique_region
923
+ os.makedirs(output_dir_csv_tmp, exist_ok=True)
924
+
925
+ image_dir = output_dir_csv + "/" + donor + "_" + unique_region
926
+ os.makedirs(image_dir, exist_ok=True)
927
+ print(f"Path created: {image_dir}")
928
+
929
+ image_dir = os.path.join(image_dir, os.path.basename(os.path.normpath(g)))
930
+ path = g
931
+
932
+ df, contour = tl_analyze_image(
933
+ path,
934
+ invert=False,
935
+ output_dir=image_dir,
936
+ )
937
+
938
+ df["group"] = hf_extract_filename(g)
939
+ df["unique_region"] = unique_region
940
+
941
+ DF_list.append(df)
942
+ contour_list.append(contour)
943
+
944
+ results_df = pd.concat(DF_list)
945
+ contour_list_results_df = pd.concat(DF_list)
946
+
947
+ results_df.to_csv(os.path.join(output_dir_csv, "results.csv"))
948
+
949
+ return results_df, contour_list
950
+
951
+
952
+ ###
953
+
954
+
955
+ def tl_analyze_image(
956
+ path,
957
+ output_dir,
958
+ invert=False,
959
+ properties_list=[
960
+ "label",
961
+ "centroid",
962
+ "area",
963
+ "perimeter",
964
+ "solidity",
965
+ "coords",
966
+ "axis_minor_length",
967
+ "axis_major_length",
968
+ "orientation",
969
+ "slice",
970
+ ],
971
+ ):
972
+ """
973
+ Analyze an image by performing connected component analysis on patches and storing their information.
974
+
975
+ The function applies image processing techniques such as Gaussian smoothing, thresholding, and connected component
976
+ labeling to identify and analyze patches within the image. It extracts region properties of these patches,
977
+ calculates their circularity, and stores the coordinates of their contour. The resulting information is saved
978
+ in a DataFrame along with a visualization plot.
979
+
980
+ Parameters:
981
+ path (str): Path to the input image.
982
+ output_dir (str): Directory to save the output plot.
983
+ invert (bool, optional): Flag indicating whether to invert the image (default is False).
984
+ properties_list: (list of str): Define properties to be measured (see SciKit Image), by default "label", "centroid", "area", "perimeter", "solidity", "coords", "axis_minor_length", "axis_major_length", "orientation", "slice"
985
+
986
+ Returns:
987
+ tuple: A tuple containing the DataFrame with region properties, including patch contour coordinates, and
988
+ the list of contour coordinates for each patch.
989
+ """
990
+ image = skimage.io.imread(path)
991
+
992
+ if image.ndim == 2:
993
+ print("2D array")
994
+ else:
995
+ image = image[:, :, 0]
996
+
997
+ if invert:
998
+ print(
999
+ "The original background color was white. The image was inverted for further analysis."
1000
+ )
1001
+ # image = 255 - image
1002
+ else:
1003
+ print("no inversion")
1004
+
1005
+ smooth = skimage.filters.gaussian(image, sigma=1.5)
1006
+ thresh = smooth > skimage.filters.threshold_otsu(smooth)
1007
+
1008
+ blobs_labels = skimage.measure.label(thresh, background=0)
1009
+
1010
+ properties = skimage.measure.regionprops(blobs_labels)
1011
+
1012
+ props_table = skimage.measure.regionprops_table(
1013
+ blobs_labels,
1014
+ properties=(properties_list),
1015
+ )
1016
+
1017
+ prop_df = pd.DataFrame(props_table)
1018
+
1019
+ prop_df["circularity"] = (4 * np.pi * prop_df["area"]) / (prop_df["perimeter"] ** 2)
1020
+
1021
+ # Store the contour of each patch in the DataFrame
1022
+ contour_list = []
1023
+ for index in range(1, blobs_labels.max()):
1024
+ label_i = properties[index].label
1025
+ contour = skimage.measure.find_contours(blobs_labels == label_i, 0.5)[0]
1026
+ contour_list.append(contour)
1027
+
1028
+ contour_list_df = pd.DataFrame({"contours": contour_list})
1029
+
1030
+ prop_df = pd.concat([prop_df, contour_list_df], axis=1)
1031
+
1032
+ plt.figure(figsize=(9, 3.5))
1033
+ plt.subplot(1, 2, 1)
1034
+ plt.imshow(thresh, cmap="gray")
1035
+ plt.axis("off")
1036
+ plt.subplot(1, 2, 2)
1037
+ plt.imshow(blobs_labels, cmap="nipy_spectral")
1038
+ plt.axis("off")
1039
+
1040
+ plt.tight_layout()
1041
+
1042
+ plt.savefig(output_dir)
1043
+ plt.close()
1044
+
1045
+ return prop_df, contour_list
1046
+
1047
+
1048
+ ###
1049
+
1050
+
1051
+ def tl_apply_mask(image_path, mask_path, output_path):
1052
+ """
1053
+ Apply a mask to an image and save the resulting masked image.
1054
+
1055
+ Parameters:
1056
+ image_path (str): Path to the input image.
1057
+ mask_path (str): Path to the mask image.
1058
+ output_path (str): Path to save the masked image.
1059
+
1060
+ Returns:
1061
+ None
1062
+ """
1063
+ # Load the image and the mask
1064
+ image = io.imread(image_path)
1065
+ mask = io.imread(mask_path, as_gray=True)
1066
+ mask = np.flip(mask, axis=0)
1067
+
1068
+ width = 941
1069
+ height = 907
1070
+ image = skimage.transform.resize(image, (height, width))
1071
+
1072
+ if image.ndim == 2:
1073
+ print("2D array")
1074
+ else:
1075
+ image = image[:, :, :3]
1076
+
1077
+ # Convert to grayscale
1078
+ image = skimage.color.rgb2gray(image)
1079
+
1080
+ # Convert to 8-bit
1081
+ image = skimage.img_as_ubyte(image)
1082
+
1083
+ print("Image shape:", image.shape)
1084
+ print("Mask shape:", mask.shape)
1085
+
1086
+ # Ensure the mask is binary
1087
+ mask = mask > 0
1088
+
1089
+ # Apply the mask to the image
1090
+ masked_image = image.copy()
1091
+ masked_image[~mask] = 0
1092
+
1093
+ # Check if the image has an alpha channel (transparency)
1094
+ if masked_image.ndim == 2:
1095
+ print("2D array")
1096
+ else:
1097
+ masked_image = masked_image[:, :, :3]
1098
+
1099
+ # Save the masked image
1100
+ io.imsave(output_path, skimage.img_as_ubyte(masked_image))
1101
+
1102
+
1103
+ ###
1104
+
1105
+
1106
+ def tl_generate_mask(
1107
+ path, output_dir, filename="mask.png", filter_size=5, threshold_value=5
1108
+ ):
1109
+ """
1110
+ Generate a mask from a maximum projection of an input image.
1111
+
1112
+ Parameters:
1113
+ path (str): Path to the input image.
1114
+ output_dir (str): Directory to save the generated mask and quality control plot.
1115
+ filename (str, optional): Name of the generated mask file (default is "mask.png").
1116
+ filter_size (int, optional): Size of the filter disk used for image processing (default is 5).
1117
+ threshold_value (int, optional): Threshold value for binary conversion (default is 5).
1118
+
1119
+ Returns:
1120
+ None
1121
+ """
1122
+ # Load the image
1123
+ image = io.imread(path)
1124
+
1125
+ # Perform Z projection using Maximum Intensity
1126
+ z_projection = np.max(image, axis=0)
1127
+
1128
+ # Resize the image
1129
+ width = 941
1130
+ height = 907
1131
+ resized_image = skimage.transform.resize(
1132
+ z_projection, (height, width, 3), preserve_range=True
1133
+ )
1134
+ print("Resized image shape:", resized_image.shape)
1135
+
1136
+ # Remove alpha channel if present
1137
+ if resized_image.shape[-1] == 4:
1138
+ resized_image = resized_image[:, :, :3]
1139
+
1140
+ # Convert to grayscale
1141
+ gray_image = skimage.color.rgb2gray(resized_image)
1142
+
1143
+ # Assuming gray_image has pixel values outside the range [0, 1]
1144
+ # Normalize the pixel values to the range [0, 1]
1145
+ gray_image_normalized = (gray_image - gray_image.min()) / (
1146
+ gray_image.max() - gray_image.min()
1147
+ )
1148
+
1149
+ # Convert to 8-bit
1150
+ gray_image_8bit = skimage.img_as_ubyte(gray_image_normalized)
1151
+
1152
+ # Apply maximum filter
1153
+ max_filtered = skimage.filters.rank.maximum(
1154
+ gray_image_8bit, skimage.morphology.disk(filter_size)
1155
+ )
1156
+
1157
+ # Apply minimum filter
1158
+ min_filtered = skimage.filters.rank.minimum(
1159
+ max_filtered, skimage.morphology.disk(filter_size)
1160
+ )
1161
+
1162
+ # Apply median filter
1163
+ median_filtered = skimage.filters.rank.median(
1164
+ min_filtered, skimage.morphology.disk(filter_size)
1165
+ )
1166
+
1167
+ # Manual Thresholding
1168
+ binary = median_filtered > threshold_value
1169
+
1170
+ # Convert to mask
1171
+ mask = skimage.morphology.closing(binary, skimage.morphology.square(3))
1172
+
1173
+ # Plotting
1174
+ fig, axes = plt.subplots(2, 3, figsize=(12, 6))
1175
+
1176
+ axes[0, 0].imshow(gray_image, cmap="gray")
1177
+ axes[0, 0].set_title("Grayscale Image")
1178
+
1179
+ axes[0, 1].imshow(gray_image_8bit, cmap="gray")
1180
+ axes[0, 1].set_title("8-bit Image")
1181
+
1182
+ axes[0, 2].imshow(max_filtered, cmap="gray")
1183
+ axes[0, 2].set_title("Maximum Filtered")
1184
+
1185
+ axes[1, 0].imshow(min_filtered, cmap="gray")
1186
+ axes[1, 0].set_title("Minimum Filtered")
1187
+
1188
+ axes[1, 1].imshow(median_filtered, cmap="gray")
1189
+ axes[1, 1].set_title("Median Filtered")
1190
+
1191
+ axes[1, 2].imshow(mask, cmap="gray")
1192
+ axes[1, 2].set_title("Mask")
1193
+
1194
+ for ax in axes.ravel():
1195
+ ax.axis("off")
1196
+
1197
+ plt.tight_layout()
1198
+ fig.savefig(output_dir + filename + "_QC_plot.png", dpi=300, format="png")
1199
+
1200
+ plt.show()
1201
+
1202
+ # Save the result
1203
+ io.imsave(output_dir + filename, mask)
1204
+
1205
+
1206
+ #####
1207
+
1208
+
1209
+ def tl_test_clustering_resolutions(
1210
+ adata, clustering="leiden", n_neighbors=10, resolutions=[1]
1211
+ ):
1212
+ """
1213
+ Test different resolutions for reclustering using Louvain or Leiden algorithm.
1214
+
1215
+ Parameters:
1216
+ adata (AnnData): Anndata object containing the data.
1217
+ clustering (str, optional): Clustering algorithm to use (default is 'leiden').
1218
+ n_neighbors (int, optional): Number of nearest neighbors (default is 10).
1219
+ resolutions (list, optional): List of resolutions to test (default is [1]).
1220
+
1221
+ Returns:
1222
+ None
1223
+ """
1224
+ for res in tqdm(resolutions, desc="Testing resolutions"):
1225
+ if "leiden" in clustering:
1226
+ clustering(
1227
+ adata,
1228
+ clustering="leiden",
1229
+ n_neighbors=n_neighbors,
1230
+ res=res,
1231
+ reclustering=True,
1232
+ )
1233
+ else:
1234
+ clustering(
1235
+ adata,
1236
+ clustering="louvain",
1237
+ n_neighbors=n_neighbors,
1238
+ res=res,
1239
+ reclustering=True,
1240
+ )
1241
+
1242
+ sc.pl.umap(adata, color=f"{clustering}_{res}", legend_loc="on data")
1243
+
1244
+
1245
+ def neighborhood_analysis(
1246
+ adata,
1247
+ unique_region,
1248
+ cluster_col,
1249
+ X="x",
1250
+ Y="y",
1251
+ k=35,
1252
+ n_neighborhoods=30,
1253
+ elbow=False,
1254
+ metric="distortion",
1255
+ ):
1256
+ """
1257
+ Compute for Cellular neighborhoods (CNs).
1258
+
1259
+ Parameters
1260
+ ----------
1261
+ adata : AnnData
1262
+ Annotated data matrix.
1263
+ unique_region : str
1264
+ Each region is one independent CODEX image.
1265
+ cluster_col : str
1266
+ Columns to compute CNs on, typically 'celltype'.
1267
+ X : str, optional
1268
+ X coordinate column name, by default "x".
1269
+ Y : str, optional
1270
+ Y coordinate column name, by default "y".
1271
+ k : int, optional
1272
+ Number of neighbors to compute, by default 35.
1273
+ n_neighborhoods : int, optional
1274
+ Number of neighborhoods one ends up with, by default 30.
1275
+ elbow : bool, optional
1276
+ Whether to test for optimal number of clusters and visulize as elbow plot or not, by default False. If set to true the funktion will test 1 to n_neighborhoods and plots the distortion score in an elbow plot to assist the user in finding the optimal number of clusters.
1277
+ metric : str, optional
1278
+ The metric to use when calculating distance between instances in a feature array, by default "distortion".
1279
+
1280
+ Returns
1281
+ -------
1282
+ AnnData
1283
+ Annotated data matrix with updated neighborhood information.
1284
+
1285
+ """
1286
+ df = pd.DataFrame(adata.obs[[X, Y, cluster_col, unique_region]])
1287
+
1288
+ cells = pd.concat([df, pd.get_dummies(df[cluster_col])], axis=1)
1289
+ sum_cols = cells[cluster_col].unique()
1290
+ values = cells[sum_cols].values
1291
+
1292
+ neighborhood_name = "CN" + "_k" + str(k) + "_n" + str(n_neighborhoods)
1293
+ centroids_name = "Centroid" + "_k" + str(k) + "_n" + str(n_neighborhoods)
1294
+
1295
+ n_neighbors = k
1296
+
1297
+ cells[unique_region] = cells[unique_region].astype("str")
1298
+ cells["cellid"] = cells.index.values
1299
+ cells.reset_index(inplace=True)
1300
+
1301
+ keep_cols = [X, Y, unique_region, cluster_col]
1302
+
1303
+ # Get each region
1304
+ tissue_group = cells[[X, Y, unique_region]].groupby(unique_region)
1305
+ exps = list(cells[unique_region].unique())
1306
+ tissue_chunks = [
1307
+ (time.time(), exps.index(t), t, a)
1308
+ for t, indices in tissue_group.groups.items()
1309
+ for a in np.array_split(indices, 1)
1310
+ ]
1311
+
1312
+ tissues = [
1313
+ hf_get_windows(job, n_neighbors, exps=exps, tissue_group=tissue_group, X=X, Y=Y)
1314
+ for job in tissue_chunks
1315
+ ]
1316
+
1317
+ # Loop over k to compute neighborhoods
1318
+ out_dict = {}
1319
+
1320
+ for neighbors, job in zip(tissues, tissue_chunks):
1321
+ chunk = np.arange(len(neighbors)) # indices
1322
+ tissue_name = job[2]
1323
+ indices = job[3]
1324
+ window = (
1325
+ values[neighbors[chunk, :k].flatten()]
1326
+ .reshape(len(chunk), k, len(sum_cols))
1327
+ .sum(axis=1)
1328
+ )
1329
+ out_dict[(tissue_name, k)] = (window.astype(np.float16), indices)
1330
+
1331
+ windows = {}
1332
+
1333
+ window = pd.concat(
1334
+ [
1335
+ pd.DataFrame(
1336
+ out_dict[(exp, k)][0],
1337
+ index=out_dict[(exp, k)][1].astype(int),
1338
+ columns=sum_cols,
1339
+ )
1340
+ for exp in exps
1341
+ ],
1342
+ axis=0,
1343
+ )
1344
+ window = window.loc[cells.index.values]
1345
+ window = pd.concat([cells[keep_cols], window], axis=1)
1346
+ windows[k] = window
1347
+
1348
+ # Fill in based on above
1349
+ k_centroids = {}
1350
+
1351
+ # producing what to plot
1352
+ windows2 = windows[k]
1353
+ windows2[cluster_col] = cells[cluster_col]
1354
+
1355
+ if elbow != True:
1356
+ km = MiniBatchKMeans(n_clusters=n_neighborhoods, random_state=0)
1357
+
1358
+ labels = km.fit_predict(windows2[sum_cols].values)
1359
+ k_centroids[str(k)] = km.cluster_centers_
1360
+ adata.obs[neighborhood_name] = labels
1361
+ adata.uns[centroids_name] = k_centroids
1362
+
1363
+ else:
1364
+ km = MiniBatchKMeans(random_state=0)
1365
+
1366
+ X = windows2[sum_cols].values
1367
+
1368
+ labels = km.fit_predict(X)
1369
+ k_centroids[str(k)] = km.cluster_centers_
1370
+ adata.obs[neighborhood_name] = labels
1371
+ adata.uns[centroids_name] = k_centroids
1372
+
1373
+ visualizer = KElbowVisualizer(
1374
+ km, k=(n_neighborhoods), timings=False, metric=metric
1375
+ )
1376
+ visualizer.fit(X) # Fit the data to the visualizer
1377
+ visualizer.show() # Finalize and render the figure
1378
+
1379
+ return adata
1380
+
1381
+
1382
+ def build_cn_map(
1383
+ adata,
1384
+ cn_col,
1385
+ unique_region,
1386
+ palette=None,
1387
+ k=75,
1388
+ X="x",
1389
+ Y="y",
1390
+ threshold=0.85,
1391
+ per_keep_thres=0.85,
1392
+ sub_list=None,
1393
+ sub_col=None,
1394
+ rand_seed=1,
1395
+ ):
1396
+ """
1397
+ Generate a cellular neighborhood (CN) map.
1398
+
1399
+ Parameters
1400
+ ----------
1401
+ adata : AnnData
1402
+ Annotated data matrix.
1403
+ cn_col : str
1404
+ Column name for cellular neighborhood.
1405
+ unique_region : str
1406
+ Unique region identifier.
1407
+ palette : dict, optional
1408
+ Color palette for the CN map, by default None.
1409
+ k : int, optional
1410
+ Number of neighbors to compute, by default 75.
1411
+ X : str, optional
1412
+ X coordinate column name, by default "x".
1413
+ Y : str, optional
1414
+ Y coordinate column name, by default "y".
1415
+ threshold : float, optional
1416
+ Threshold for neighborhood computation, by default 0.85.
1417
+ per_keep_thres : float, optional
1418
+ Threshold for keeping percentage, by default 0.85.
1419
+ sub_list : list, optional
1420
+ List of sub regions, by default None.
1421
+ sub_col : str, optional
1422
+ Column name for sub regions, by default None.
1423
+ rand_seed : int, optional
1424
+ Random seed for color generation, by default 1.
1425
+
1426
+ Returns
1427
+ -------
1428
+ dict
1429
+ Dictionary containing the graph, top nodes, edges and simplicial frequencies.
1430
+ """
1431
+ ks = [k]
1432
+ cells_df = pd.DataFrame(adata.obs)
1433
+ cells_df = cells_df[[X, Y, unique_region, cn_col]]
1434
+ cells_df.reset_index(inplace=True)
1435
+ sum_cols = cells_df[cn_col].unique()
1436
+ keep_cols = cells_df.columns
1437
+
1438
+ cn_colors = hf_generate_random_colors(
1439
+ len(adata.obs[cn_col].unique()), rand_seed=rand_seed
1440
+ )
1441
+
1442
+ if palette is None:
1443
+ if cn_col + "_colors" not in adata.uns.keys():
1444
+ palette = dict(zip(np.sort(adata.obs[cn_col].unique()), cn_colors))
1445
+ adata.uns[cn_col + "_colors"] = cn_colors
1446
+ else:
1447
+ palette = dict(
1448
+ zip(np.sort(adata.obs[cn_col].unique()), adata.uns[cn_col + "_colors"])
1449
+ )
1450
+
1451
+ Neigh = Neighborhoods(
1452
+ cells_df,
1453
+ ks,
1454
+ cn_col,
1455
+ sum_cols,
1456
+ keep_cols,
1457
+ X,
1458
+ Y,
1459
+ reg=unique_region,
1460
+ add_dummies=True,
1461
+ )
1462
+ windows = Neigh.k_windows()
1463
+ w = windows[k]
1464
+ if sub_list:
1465
+ # convert sub_list to list if only str is provided
1466
+ if isinstance(sub_list, str):
1467
+ sub_list = [sub_list]
1468
+ w = w[w[sub_col].isin(sub_list)]
1469
+ l = list(palette.keys())
1470
+ simps, simp_freqs, simp_sums = tl_calculate_neigh_combs(
1471
+ w, l, k, threshold=threshold, per_keep_thres=per_keep_thres # color palette
1472
+ )
1473
+ g, tops, e0, e1 = tl_build_graph_CN_comb_map(simp_freqs)
1474
+ return {
1475
+ "g": g,
1476
+ "tops": tops,
1477
+ "e0": e0,
1478
+ "e1": e1,
1479
+ "simp_freqs": simp_freqs,
1480
+ "w": w,
1481
+ "l": l,
1482
+ "k": k,
1483
+ "threshold": threshold,
1484
+ }
1485
+
1486
+
1487
+ def tl_format_for_squidpy(adata, x_col, y_col):
1488
+ """
1489
+ Format an AnnData object for use with Squidpy.
1490
+
1491
+ Parameters
1492
+ ----------
1493
+ adata : AnnData
1494
+ Annotated data matrix.
1495
+ x_col : str
1496
+ Column name for x spatial coordinates.
1497
+ y_col : str
1498
+ Column name for y spatial coordinates.
1499
+
1500
+ Returns
1501
+ -------
1502
+ AnnData
1503
+ Annotated data matrix formatted for Squidpy, with spatial data in the 'obsm' attribute.
1504
+ """
1505
+ # Extract the count data from your original AnnData object
1506
+ counts = adata.X
1507
+
1508
+ # Extract the spatial coordinates from the 'obs' metadata
1509
+ spatial_coordinates = adata.obs[[x_col, y_col]].values
1510
+
1511
+ # Create a new AnnData object with the expected format
1512
+ new_adata = ad.AnnData(counts, obsm={"spatial": spatial_coordinates})
1513
+
1514
+ return new_adata
1515
+
1516
+
1517
+ def tl_corr_cell_ad(
1518
+ adata, per_categ, grouping_col, rep, sub_column, normed=True, sub_list2=None
1519
+ ):
1520
+ """
1521
+ Perform correlation analysis on a pandas DataFrame and plot correlation scatter plots.
1522
+
1523
+ Parameters
1524
+ ----------
1525
+ data : pandas DataFrame
1526
+ The input DataFrame.
1527
+ per_categ : str
1528
+ The categorical column in the DataFrame to be used.
1529
+ grouping_col : str
1530
+ The grouping column in the DataFrame.
1531
+ rep : str
1532
+ The replicate column in the DataFrame.
1533
+ sub_column : str
1534
+ The subcategory column in the DataFrame.
1535
+ normed : bool, optional
1536
+ If the percentage should be normalized. Default is True.
1537
+ sub_list2 : list, optional
1538
+ A list of subcategories to be considered. Default is None.
1539
+
1540
+ Returns
1541
+ -------
1542
+ cmat : pandas DataFrame
1543
+ The correlation matrix DataFrame.
1544
+ cc : pandas DataFrame
1545
+ The DataFrame after pivoting and formatting for correlation function.
1546
+ """
1547
+ data = adata.obs
1548
+ cmat, cc = tl_corr_cell(
1549
+ data,
1550
+ per_categ,
1551
+ grouping_col=grouping_col,
1552
+ rep=rep,
1553
+ sub_column=sub_column,
1554
+ normed=normed,
1555
+ sub_list2=sub_list2,
1556
+ )
1557
+
1558
+ return cmat, cc
1559
+
1560
+
1561
+ def calculate_triangulation_distances(df_input, id, x_pos, y_pos, cell_type, region):
1562
+ """
1563
+ Calculate distances between cells using Delaunay triangulation.
1564
+
1565
+ Parameters
1566
+ ----------
1567
+ df_input : pandas.DataFrame
1568
+ Input dataframe containing cell information.
1569
+ id : str
1570
+ Column name for cell id.
1571
+ x_pos : str
1572
+ Column name for x position of cells.
1573
+ y_pos : str
1574
+ Column name for y position of cells.
1575
+ cell_type : str
1576
+ Column name for cell type annotations.
1577
+ region : str
1578
+ Column name for region.
1579
+
1580
+ Returns
1581
+ -------
1582
+ pandas.DataFrame
1583
+ Annotated result dataframe with calculated distances and additional information.
1584
+ """
1585
+ # Perform Delaunay triangulation
1586
+ points = df_input[[x_pos, y_pos]].values
1587
+ tri = Delaunay(points)
1588
+ indices = tri.simplices
1589
+
1590
+ # Get interactions going both directions
1591
+ edges = set()
1592
+ for simplex in indices:
1593
+ for i in range(3):
1594
+ for j in range(i + 1, 3):
1595
+ edges.add(tuple(sorted([simplex[i], simplex[j]])))
1596
+ edges = np.array(list(edges))
1597
+
1598
+ # Create dataframe from edges
1599
+ rdelaun_result = pd.DataFrame(edges, columns=["ind1", "ind2"])
1600
+ rdelaun_result[["x1", "y1"]] = df_input.iloc[rdelaun_result["ind1"]][
1601
+ [x_pos, y_pos]
1602
+ ].values
1603
+ rdelaun_result[["x2", "y2"]] = df_input.iloc[rdelaun_result["ind2"]][
1604
+ [x_pos, y_pos]
1605
+ ].values
1606
+
1607
+ # Annotate results with cell type and region information
1608
+ df_input["XYcellID"] = (
1609
+ df_input[x_pos].astype(str) + "_" + df_input[y_pos].astype(str)
1610
+ )
1611
+ rdelaun_result["cell1ID"] = (
1612
+ rdelaun_result["x1"].astype(str) + "_" + rdelaun_result["y1"].astype(str)
1613
+ )
1614
+ rdelaun_result["cell2ID"] = (
1615
+ rdelaun_result["x2"].astype(str) + "_" + rdelaun_result["y2"].astype(str)
1616
+ )
1617
+
1618
+ annotated_result = pd.merge(
1619
+ rdelaun_result, df_input, left_on="cell1ID", right_on="XYcellID"
1620
+ )
1621
+ annotated_result = annotated_result.rename(
1622
+ columns={cell_type: "celltype1", id: "celltype1_index"}
1623
+ )
1624
+ annotated_result = annotated_result.drop(columns=[x_pos, y_pos, region, "XYcellID"])
1625
+
1626
+ annotated_result = pd.merge(
1627
+ annotated_result,
1628
+ df_input,
1629
+ left_on="cell2ID",
1630
+ right_on="XYcellID",
1631
+ suffixes=(".x", ".y"),
1632
+ )
1633
+ annotated_result = annotated_result.rename(
1634
+ columns={cell_type: "celltype2", id: "celltype2_index"}
1635
+ )
1636
+ annotated_result = annotated_result.drop(columns=[x_pos, y_pos, "XYcellID"])
1637
+
1638
+ # Calculate distance
1639
+ annotated_result["distance"] = np.sqrt(
1640
+ (annotated_result["x2"] - annotated_result["x1"]) ** 2
1641
+ + (annotated_result["y2"] - annotated_result["y1"]) ** 2
1642
+ )
1643
+
1644
+ # Reorder columns
1645
+ annotated_result = annotated_result[
1646
+ [
1647
+ region,
1648
+ "celltype1_index",
1649
+ "celltype1",
1650
+ "x1",
1651
+ "y1",
1652
+ "celltype2_index",
1653
+ "celltype2",
1654
+ "x2",
1655
+ "y2",
1656
+ "distance",
1657
+ ]
1658
+ ]
1659
+ annotated_result.columns = [
1660
+ region,
1661
+ "celltype1_index",
1662
+ "celltype1",
1663
+ "celltype1_X",
1664
+ "celltype1_Y",
1665
+ "celltype2_index",
1666
+ "celltype2",
1667
+ "celltype2_X",
1668
+ "celltype2_Y",
1669
+ "distance",
1670
+ ]
1671
+
1672
+ return annotated_result
1673
+
1674
+
1675
+ # Define the process_region function at the top level
1676
+ def process_region(df, unique_region, id, x_pos, y_pos, cell_type, region):
1677
+ """
1678
+ Process a specific region of a dataframe, calculating triangulation distances.
1679
+
1680
+ Parameters
1681
+ ----------
1682
+ df : pandas.DataFrame
1683
+ Input dataframe containing cell information.
1684
+ unique_region : str
1685
+ Unique region identifier.
1686
+ id : str
1687
+ Column name for cell id.
1688
+ x_pos : str
1689
+ Column name for x position of cells.
1690
+ y_pos : str
1691
+ Column name for y position of cells.
1692
+ cell_type : str
1693
+ Column name for cell type.
1694
+ region : str
1695
+ Column name for region.
1696
+
1697
+ Returns
1698
+ -------
1699
+ pandas.DataFrame
1700
+ Result dataframe with calculated distances and additional information for the specified region.
1701
+ """
1702
+ subset = df[df[region] == unique_region].copy()
1703
+ subset["uniqueID"] = (
1704
+ subset[id].astype(str)
1705
+ + "-"
1706
+ + subset[x_pos].astype(str)
1707
+ + "-"
1708
+ + subset[y_pos].astype(str)
1709
+ )
1710
+ subset["XYcellID"] = subset[x_pos].astype(str) + "_" + subset[y_pos].astype(str)
1711
+ result = calculate_triangulation_distances(
1712
+ df_input=subset,
1713
+ id=id,
1714
+ x_pos=x_pos,
1715
+ y_pos=y_pos,
1716
+ cell_type=cell_type,
1717
+ region=region,
1718
+ )
1719
+ return result
1720
+
1721
+
1722
+ def get_triangulation_distances(
1723
+ df_input, id, x_pos, y_pos, cell_type, region, num_cores=None, correct_dtype=True
1724
+ ):
1725
+ """
1726
+ Calculate triangulation distances for each unique region in the input dataframe.
1727
+
1728
+ Parameters
1729
+ ----------
1730
+ df_input : pandas.DataFrame
1731
+ Input dataframe containing cell information.
1732
+ id : str
1733
+ Column name for cell id.
1734
+ x_pos : str
1735
+ Column name for x position of cells.
1736
+ y_pos : str
1737
+ Column name for y position of cells.
1738
+ cell_type : str
1739
+ Column name for cell type.
1740
+ region : str
1741
+ Column name for region.
1742
+ num_cores : int, optional
1743
+ Number of cores to use for parallel processing. If None, defaults to half of available cores.
1744
+ correct_dtype : bool, optional
1745
+ If True, corrects the data type of the cell_type and region columns to string.
1746
+
1747
+ Returns
1748
+ -------
1749
+ pandas.DataFrame
1750
+ Result dataframe with calculated distances and additional information for each unique region.
1751
+ """
1752
+ if correct_dtype == True:
1753
+ # change columns to pandas string
1754
+ df_input[cell_type] = df_input[cell_type].astype(str)
1755
+ df_input[region] = df_input[region].astype(str)
1756
+
1757
+ # Check if x_pos and y_pos are integers, and if not, convert them
1758
+ if not issubclass(df_input[x_pos].dtype.type, np.integer):
1759
+ print("This function expects integer values for xy coordinates.")
1760
+ print(
1761
+ x_pos
1762
+ + " and "
1763
+ + y_pos
1764
+ + " will be changed to integer. Please check the generated output!"
1765
+ )
1766
+ df_input[x_pos] = df_input[x_pos].astype(int).values
1767
+ df_input[y_pos] = df_input[y_pos].astype(int).values
1768
+
1769
+ # Get unique regions
1770
+ unique_regions = df_input[region].unique()
1771
+
1772
+ # Select only necessary columns
1773
+ df_input = df_input.loc[:, [id, x_pos, y_pos, cell_type, region]]
1774
+
1775
+ # Set up parallelization
1776
+ if num_cores is None:
1777
+ num_cores = os.cpu_count() // 2 # default to using half of available cores
1778
+
1779
+ # Parallel processing using joblib
1780
+ results = Parallel(n_jobs=num_cores)(
1781
+ delayed(process_region)(df_input, reg, id, x_pos, y_pos, cell_type, region)
1782
+ for reg in unique_regions
1783
+ )
1784
+
1785
+ triangulation_distances = pd.concat(results)
1786
+
1787
+ return triangulation_distances
1788
+
1789
+
1790
+ def shuffle_annotations(df_input, cell_type, region, permutation):
1791
+ """
1792
+ Shuffle annotations within each unique region in the input dataframe.
1793
+
1794
+ Parameters
1795
+ ----------
1796
+ df_input : pandas.DataFrame
1797
+ Input dataframe containing cell information.
1798
+ cell_type : str
1799
+ Column name for cell type annotations.
1800
+ region : str
1801
+ Column name for region.
1802
+ permutation : int
1803
+ Seed for the random number generator.
1804
+
1805
+ Returns
1806
+ -------
1807
+ pandas.DataFrame
1808
+ Result dataframe with shuffled annotations for each unique region.
1809
+ """
1810
+ # Set the seed for reproducibility
1811
+ np.random.seed(permutation + 1234)
1812
+
1813
+ # Create a copy to avoid modifying the original dataframe
1814
+ df_shuffled = df_input.copy()
1815
+
1816
+ # Shuffle annotations within each region
1817
+ for region_name in df_shuffled[region].unique():
1818
+ region_mask = df_shuffled[region] == region_name
1819
+ shuffled_values = df_shuffled.loc[region_mask, cell_type].sample(frac=1).values
1820
+ df_shuffled.loc[region_mask, "random_annotations"] = shuffled_values
1821
+
1822
+ return df_shuffled
1823
+
1824
+
1825
+ def tl_iterate_tri_distances(
1826
+ df_input, id, x_pos, y_pos, cell_type, region, num_cores=None, num_iterations=1000
1827
+ ):
1828
+ """
1829
+ Iterate over triangulation distances for each unique region in the input dataframe.
1830
+
1831
+ Parameters
1832
+ ----------
1833
+ df_input : pandas.DataFrame
1834
+ Input dataframe containing cell information.
1835
+ id : str
1836
+ Column name for cell id.
1837
+ x_pos : str
1838
+ Column name for x position of cells.
1839
+ y_pos : str
1840
+ Column name for y position of cells.
1841
+ cell_type : str
1842
+ Column name for cell type.
1843
+ region : str
1844
+ Column name for region.
1845
+ num_cores : int, optional
1846
+ Number of cores to use for parallel processing. If None, defaults to half of available cores.
1847
+ num_iterations : int, optional
1848
+ Number of iterations to perform. Defaults to 1000.
1849
+
1850
+ Returns
1851
+ -------
1852
+ pandas.DataFrame
1853
+ Result dataframe with iterative triangulation distances for each unique region.
1854
+ """
1855
+ unique_regions = df_input[region].unique()
1856
+ # Use only the necessary columns
1857
+ df_input = df_input[[id, x_pos, y_pos, cell_type, region]]
1858
+
1859
+ if num_cores is None:
1860
+ num_cores = os.cpu_count() // 2 # Default to using half of available cores
1861
+
1862
+ # Define a helper function to process each region and iteration
1863
+ def process_iteration(region_name, iteration):
1864
+ # Filter by region
1865
+ subset = df_input[df_input[region] == region_name].copy()
1866
+ # Create unique IDs
1867
+ subset.loc[:, "uniqueID"] = (
1868
+ subset[id].astype(str)
1869
+ + "-"
1870
+ + subset[x_pos].astype(str)
1871
+ + "-"
1872
+ + subset[y_pos].astype(str)
1873
+ )
1874
+ subset.loc[:, "XYcellID"] = (
1875
+ subset[x_pos].astype(str) + "_" + subset[y_pos].astype(str)
1876
+ )
1877
+
1878
+ # Shuffle annotations
1879
+ shuffled = shuffle_annotations(subset, cell_type, region, iteration)
1880
+
1881
+ # Get triangulation distances
1882
+ results = get_triangulation_distances(
1883
+ df_input=shuffled,
1884
+ id=id,
1885
+ x_pos=x_pos,
1886
+ y_pos=y_pos,
1887
+ cell_type="random_annotations",
1888
+ region=region,
1889
+ num_cores=num_cores,
1890
+ correct_dtype=False,
1891
+ )
1892
+
1893
+ # Summarize results
1894
+ per_cell_summary = (
1895
+ results.groupby(["celltype1_index", "celltype1", "celltype2"])
1896
+ .distance.mean()
1897
+ .reset_index(name="per_cell_mean_dist")
1898
+ )
1899
+
1900
+ per_celltype_summary = (
1901
+ per_cell_summary.groupby(["celltype1", "celltype2"])
1902
+ .per_cell_mean_dist.mean()
1903
+ .reset_index(name="mean_dist")
1904
+ )
1905
+ per_celltype_summary[region] = region_name
1906
+ per_celltype_summary["iteration"] = iteration
1907
+
1908
+ return per_celltype_summary
1909
+
1910
+ # TODO: remove nans valid here a good idea (attempt to fix windows unpickle issue)?
1911
+ unique_regions = [r for r in unique_regions if r != np.nan]
1912
+
1913
+ # Parallel processing for each region and iteration
1914
+ results = Parallel(n_jobs=num_cores)(
1915
+ delayed(process_iteration)(region_name, iteration)
1916
+ for region_name in unique_regions
1917
+ for iteration in range(1, num_iterations + 1)
1918
+ )
1919
+
1920
+ # Combine all results
1921
+ iterative_triangulation_distances = pd.concat(results, ignore_index=True)
1922
+ # iterative_triangulation_distances = iterative_triangulation_distances.dropna()
1923
+ return iterative_triangulation_distances
1924
+
1925
+
1926
+ def tl_iterate_tri_distances_ad(
1927
+ adata,
1928
+ id,
1929
+ x_pos,
1930
+ y_pos,
1931
+ cell_type,
1932
+ region,
1933
+ num_cores=None,
1934
+ num_iterations=1000,
1935
+ key_name=None,
1936
+ correct_dtype=True,
1937
+ ):
1938
+ """
1939
+ Iterate over triangulation distances for each unique region in the input AnnData object.
1940
+
1941
+ Parameters
1942
+ ----------
1943
+ adata : anndata.AnnData
1944
+ Annotated data matrix.
1945
+ id : str
1946
+ Column name for cell id.
1947
+ x_pos : str
1948
+ Column name for x position of cells.
1949
+ y_pos : str
1950
+ Column name for y position of cells.
1951
+ cell_type : str
1952
+ Column name for cell type.
1953
+ region : str
1954
+ Column name for region.
1955
+ num_cores : int, optional
1956
+ Number of cores to use for parallel processing. If None, defaults to half of available cores.
1957
+ num_iterations : int, optional
1958
+ Number of iterations to perform. Defaults to 1000.
1959
+ key_name : str, optional
1960
+ Key name to use when saving the result to the AnnData object. If None, defaults to "iTriDist_" + str(num_iterations).
1961
+ correct_dtype : bool, optional
1962
+ If True, corrects the data type of the cell type and region columns to string. Defaults to True.
1963
+
1964
+ Returns
1965
+ -------
1966
+ pandas.DataFrame
1967
+ Result dataframe with iterative triangulation distances for each unique region.
1968
+ """
1969
+ df_input = pd.DataFrame(adata.obs)
1970
+ df_input[id] = df_input.index
1971
+
1972
+ if correct_dtype == True:
1973
+ # change columns to pandas string
1974
+ df_input[cell_type] = df_input[cell_type].astype(str)
1975
+ df_input[region] = df_input[region].astype(str)
1976
+
1977
+ # Check if x_pos and y_pos are integers, and if not, convert them
1978
+ if not issubclass(df_input[x_pos].dtype.type, np.integer):
1979
+ print("This function expects integer values for xy coordinates.")
1980
+ print("Class will be changed to integer. Please check the generated output!")
1981
+ df_input[x_pos] = df_input[x_pos].astype(int).values
1982
+ df_input[y_pos] = df_input[y_pos].astype(int).values
1983
+
1984
+ unique_regions = df_input[region].unique()
1985
+ # Use only the necessary columns
1986
+ df_input = df_input.loc[:, [id, x_pos, y_pos, cell_type, region]]
1987
+
1988
+ if num_cores is None:
1989
+ num_cores = os.cpu_count() // 2 # Default to using half of available cores
1990
+
1991
+ # Define a helper function to process each region and iteration
1992
+ def process_iteration(region_name, iteration):
1993
+ # Filter by region
1994
+ subset = df_input.loc[df_input[region] == region_name, :].copy()
1995
+ subset.loc[:, "uniqueID"] = (
1996
+ subset[id].astype(str)
1997
+ + "-"
1998
+ + subset[x_pos].astype(str)
1999
+ + "-"
2000
+ + subset[y_pos].astype(str)
2001
+ )
2002
+ subset.loc[:, "XYcellID"] = (
2003
+ subset[x_pos].astype(str) + "_" + subset[y_pos].astype(str)
2004
+ )
2005
+
2006
+ # Shuffle annotations
2007
+ shuffled = shuffle_annotations(subset, cell_type, region, iteration)
2008
+
2009
+ # Get triangulation distances
2010
+ results = get_triangulation_distances(
2011
+ df_input=shuffled,
2012
+ id=id,
2013
+ x_pos=x_pos,
2014
+ y_pos=y_pos,
2015
+ cell_type="random_annotations",
2016
+ region=region,
2017
+ num_cores=num_cores,
2018
+ correct_dtype=False,
2019
+ )
2020
+
2021
+ # Summarize results
2022
+ per_cell_summary = (
2023
+ results.groupby(["celltype1_index", "celltype1", "celltype2"])
2024
+ .distance.mean()
2025
+ .reset_index(name="per_cell_mean_dist")
2026
+ )
2027
+
2028
+ per_celltype_summary = (
2029
+ per_cell_summary.groupby(["celltype1", "celltype2"])
2030
+ .per_cell_mean_dist.mean()
2031
+ .reset_index(name="mean_dist")
2032
+ )
2033
+ per_celltype_summary[region] = region_name
2034
+ per_celltype_summary["iteration"] = iteration
2035
+
2036
+ return per_celltype_summary
2037
+
2038
+ # Parallel processing for each region and iteration
2039
+ results = Parallel(n_jobs=num_cores)(
2040
+ delayed(process_iteration)(region_name, iteration)
2041
+ for region_name in unique_regions
2042
+ for iteration in range(1, num_iterations + 1)
2043
+ )
2044
+
2045
+ # Combine all results
2046
+ iterative_triangulation_distances = pd.concat(results, ignore_index=True)
2047
+
2048
+ # append result to adata
2049
+ if key_name is None:
2050
+ key_name = "iTriDist_" + str(num_iterations)
2051
+ adata.uns[key_name] = iterative_triangulation_distances
2052
+ print("Save iterative triangulation distance output to anndata.uns " + key_name)
2053
+
2054
+ return iterative_triangulation_distances
2055
+
2056
+
2057
+ def add_missing_columns(
2058
+ triangulation_distances, metadata, shared_column="unique_region"
2059
+ ):
2060
+ """
2061
+ Add missing columns from metadata to triangulation_distances dataframe.
2062
+
2063
+ Parameters
2064
+ ----------
2065
+ triangulation_distances : pandas.DataFrame
2066
+ DataFrame containing triangulation distances.
2067
+ metadata : pandas.DataFrame
2068
+ DataFrame containing metadata.
2069
+ shared_column : str, optional
2070
+ Column name that is shared between the two dataframes. Defaults to "unique_region".
2071
+
2072
+ Returns
2073
+ -------
2074
+ pandas.DataFrame
2075
+ Updated triangulation_distances dataframe with missing columns added.
2076
+ """
2077
+ # Find the difference in columns
2078
+ missing_columns = set(metadata.columns) - set(triangulation_distances.columns)
2079
+ # Add missing columns to triangulation_distances with NaN values
2080
+ for column in missing_columns:
2081
+ triangulation_distances[column] = pd.NA
2082
+ # Create a mapping from unique_region to tissue in metadata
2083
+ region_to_tissue = pd.Series(
2084
+ metadata[column].values, index=metadata["unique_region"]
2085
+ ).to_dict()
2086
+
2087
+ # Apply this mapping to the triangulation_distances dataframe to create/update the tissue column
2088
+ triangulation_distances[column] = triangulation_distances["unique_region"].map(
2089
+ region_to_tissue
2090
+ )
2091
+
2092
+ # Handle regions with no corresponding tissue in the metadata by filling in a default value
2093
+ triangulation_distances[column].fillna("Unknown", inplace=True)
2094
+ return triangulation_distances
2095
+
2096
+
2097
+ # Calculate p-values and log fold differences
2098
+ def calculate_pvalue(row):
2099
+ """
2100
+ Calculate the p-value using the Mann-Whitney U test.
2101
+
2102
+ Parameters
2103
+ ----------
2104
+ row : pandas.Series
2105
+ A row of data containing 'expected' and 'observed' values.
2106
+
2107
+ Returns
2108
+ -------
2109
+ float
2110
+ The calculated p-value. Returns np.nan if there is insufficient data to perform the test.
2111
+ """
2112
+ # function body here
2113
+ try:
2114
+ return st.mannwhitneyu(
2115
+ row["expected"], row["observed"], alternative="two-sided"
2116
+ ).pvalue
2117
+ except ValueError: # This handles cases with insufficient data
2118
+ return np.nan
2119
+
2120
+
2121
+ def identify_interactions(
2122
+ adata,
2123
+ cellid,
2124
+ x_pos,
2125
+ y_pos,
2126
+ cell_type,
2127
+ region,
2128
+ comparison,
2129
+ iTriDist_keyname=None,
2130
+ triDist_keyname=None,
2131
+ min_observed=10,
2132
+ distance_threshold=128,
2133
+ num_cores=None,
2134
+ num_iterations=1000,
2135
+ key_name=None,
2136
+ correct_dtype=False,
2137
+ ):
2138
+ """
2139
+ Identify interactions between cell types based on their spatial distances.
2140
+
2141
+ Parameters
2142
+ ----------
2143
+ adata : AnnData
2144
+ Annotated data matrix.
2145
+ id : str
2146
+ Identifier for cells.
2147
+ x_pos : str
2148
+ Column name for x position of cells.
2149
+ y_pos : str
2150
+ Column name for y position of cells.
2151
+ cell_type : str
2152
+ Column name for cell type.
2153
+ region : str
2154
+ Column name for region.
2155
+ comparison : str
2156
+ Column name for comparison.
2157
+ iTriDist_keyname : str, optional
2158
+ Key name for iterative triangulation distances, by default None
2159
+ triDist_keyname : str, optional
2160
+ Key name for triangulation distances, by default None
2161
+ min_observed : int, optional
2162
+ Minimum number of observed distances, by default 10
2163
+ distance_threshold : int, optional
2164
+ Threshold for distance, by default 128
2165
+ num_cores : int, optional
2166
+ Number of cores to use for computation, by default None
2167
+ num_iterations : int, optional
2168
+ Number of iterations for computation, by default 1000
2169
+ key_name : str, optional
2170
+ Key name for output, by default None
2171
+ correct_dtype : bool, optional
2172
+ Whether to correct data type or not, by default False
2173
+
2174
+ Returns
2175
+ -------
2176
+ DataFrame
2177
+ DataFrame with p-values and logfold changes for interactions.
2178
+ """
2179
+ df_input = pd.DataFrame(adata.obs)
2180
+ if cellid in df_input.columns:
2181
+ df_input.index = df_input[cellid]
2182
+ else:
2183
+ print(cellid + " is not in the adata.obs, use index as cellid instead!")
2184
+ df_input[cellid] = df_input.index
2185
+
2186
+ # change columns to pandas string
2187
+ df_input[cell_type] = df_input[cell_type].astype(str)
2188
+ df_input[region] = df_input[region].astype(str)
2189
+
2190
+ print("Computing for observed distances between cell types!")
2191
+ triangulation_distances = get_triangulation_distances(
2192
+ df_input=df_input,
2193
+ id=cellid,
2194
+ x_pos=x_pos,
2195
+ y_pos=y_pos,
2196
+ cell_type=cell_type,
2197
+ region=region,
2198
+ num_cores=num_cores,
2199
+ correct_dtype=correct_dtype,
2200
+ )
2201
+ if key_name is None:
2202
+ triDist_keyname = "triDist"
2203
+ adata.uns["triDist_keyname"] = triangulation_distances
2204
+ print("Save triangulation distances output to anndata.uns " + triDist_keyname)
2205
+
2206
+ print("Permuting data labels to obtain the randomly distributed distances!")
2207
+ print("this step can take awhile")
2208
+ iterative_triangulation_distances = tl_iterate_tri_distances(
2209
+ df_input=df_input,
2210
+ id=cellid,
2211
+ x_pos=x_pos,
2212
+ y_pos=y_pos,
2213
+ cell_type=cell_type,
2214
+ region=region,
2215
+ num_cores=num_cores,
2216
+ num_iterations=num_iterations,
2217
+ )
2218
+
2219
+ # append result to adata
2220
+ if triDist_keyname is None:
2221
+ triDist_keyname = "iTriDist_" + str(num_iterations)
2222
+ adata.uns[triDist_keyname] = iterative_triangulation_distances
2223
+ print(
2224
+ "Save iterative triangulation distance output to anndata.uns " + triDist_keyname
2225
+ )
2226
+
2227
+ metadata = df_input.loc[:, ["unique_region", comparison]].copy()
2228
+ # Reformat observed dataset
2229
+ triangulation_distances_long = add_missing_columns(
2230
+ triangulation_distances, metadata, shared_column=region
2231
+ )
2232
+
2233
+ observed_distances = (
2234
+ triangulation_distances_long.query("distance <= @distance_threshold")
2235
+ .groupby(["celltype1_index", "celltype1", "celltype2", comparison, region])
2236
+ .agg(mean_per_cell=("distance", "mean"))
2237
+ .reset_index()
2238
+ .groupby(["celltype1", "celltype2", comparison])
2239
+ .agg(observed=("mean_per_cell", list), observed_mean=("mean_per_cell", "mean"))
2240
+ .reset_index()
2241
+ )
2242
+
2243
+ # Reformat expected dataset
2244
+ iterated_triangulation_distances_long = add_missing_columns(
2245
+ iterative_triangulation_distances, metadata, shared_column=region
2246
+ )
2247
+
2248
+ expected_distances = (
2249
+ iterated_triangulation_distances_long.query("mean_dist <= @distance_threshold")
2250
+ .groupby(["celltype1", "celltype2", comparison])
2251
+ .agg(expected=("mean_dist", list), expected_mean=("mean_dist", "mean"))
2252
+ .reset_index()
2253
+ )
2254
+
2255
+ # Drop comparisons with low numbers of observations
2256
+ observed_distances["keep"] = observed_distances["observed"].apply(
2257
+ lambda x: len(x) > min_observed
2258
+ )
2259
+ observed_distances = observed_distances[observed_distances["keep"]]
2260
+
2261
+ expected_distances["keep"] = expected_distances["expected"].apply(
2262
+ lambda x: len(x) > min_observed
2263
+ )
2264
+ expected_distances = expected_distances[expected_distances["keep"]]
2265
+
2266
+ # concatenate observed and expected distances
2267
+ distance_pvals = expected_distances.merge(
2268
+ observed_distances, on=["celltype1", "celltype2", comparison], how="left"
2269
+ )
2270
+
2271
+ distance_pvals = expected_distances.merge(
2272
+ observed_distances, on=["celltype1", "celltype2", comparison], how="left"
2273
+ )
2274
+ distance_pvals["pvalue"] = distance_pvals.apply(calculate_pvalue, axis=1)
2275
+ distance_pvals["logfold_group"] = np.log2(
2276
+ distance_pvals["observed_mean"] / distance_pvals["expected_mean"]
2277
+ )
2278
+ distance_pvals["interaction"] = (
2279
+ distance_pvals["celltype1"] + " --> " + distance_pvals["celltype2"]
2280
+ )
2281
+
2282
+ # drop na from distance_pvals
2283
+ # distance_pvals = distance_pvals.dropna()
2284
+
2285
+ return distance_pvals
2286
+
2287
+
2288
+ def filter_interactions(
2289
+ distance_pvals, pvalue=0.05, logfold_group_abs=0.1, comparison="condition"
2290
+ ):
2291
+ """
2292
+ Filters interactions based on p-value, logfold change, and other conditions.
2293
+
2294
+ Parameters
2295
+ ----------
2296
+ distance_pvals : pandas.DataFrame
2297
+ DataFrame containing p-values, logfold changes, and interactions for each comparison.
2298
+ pvalue : float, optional
2299
+ The maximum p-value to consider for significance. Defaults to 0.05.
2300
+ logfold_group_abs : float, optional
2301
+ The minimum absolute logfold change to consider for significance. Defaults to 0.1.
2302
+ comparison : str, optional
2303
+ The comparison condition to filter by. Defaults to "condition".
2304
+
2305
+ Returns
2306
+ -------
2307
+ dist_table : pandas.DataFrame
2308
+ DataFrame containing logfold changes sorted into two columns by the comparison condition.
2309
+ distance_pvals_sig_sub : pandas.DataFrame
2310
+ Subset of the original DataFrame containing only significant interactions based on the specified conditions.
2311
+ """
2312
+ # calculate absolute logfold difference
2313
+ distance_pvals["logfold_group_abs"] = distance_pvals["logfold_group"].abs()
2314
+
2315
+ # Creating pairs
2316
+ distance_pvals["pairs"] = (
2317
+ distance_pvals["celltype1"] + "_" + distance_pvals["celltype2"]
2318
+ )
2319
+
2320
+ # Filter significant p-values and other specified conditions
2321
+ distance_pvals_sig = distance_pvals[
2322
+ (distance_pvals["pvalue"] < pvalue)
2323
+ & (distance_pvals["celltype1"] != distance_pvals["celltype2"])
2324
+ & (~distance_pvals["observed_mean"].isna())
2325
+ & (distance_pvals["logfold_group_abs"] > logfold_group_abs)
2326
+ ]
2327
+
2328
+ # Assuming distance_pvals_interesting2 is a pandas DataFrame with the same structure as the R dataframe.
2329
+ # pair_to = distance_pvals_sig["interaction"].unique()
2330
+ pairs = distance_pvals_sig["pairs"].unique()
2331
+
2332
+ # Filtering data
2333
+ data = distance_pvals[~distance_pvals["interaction"].isna()]
2334
+
2335
+ # Subsetting data
2336
+ distance_pvals_sig_sub = data[data["pairs"].isin(pairs)]
2337
+ distance_pvals_sig_sub_reduced = distance_pvals_sig_sub.loc[
2338
+ :, [comparison, "logfold_group", "pairs"]
2339
+ ].copy()
2340
+
2341
+ # set pairs as index
2342
+ distance_pvals_sig_sub_reduced = distance_pvals_sig_sub_reduced.set_index("pairs")
2343
+
2344
+ # sort logfold_group into two columns by tissue
2345
+ dist_table = distance_pvals_sig_sub_reduced.pivot(
2346
+ columns=comparison, values="logfold_group"
2347
+ )
2348
+ dist_table.dropna(inplace=True)
2349
+
2350
+ return dist_table, distance_pvals_sig_sub
2351
+
2352
+
2353
+ # Function for patch identification
2354
+ ## Adjust clustering parameter to get the desired number of clusters
2355
+ def apply_dbscan_clustering(df, min_cluster_size=10):
2356
+ """
2357
+ Apply DBSCAN clustering to a dataframe and update the cluster labels in the original dataframe.
2358
+
2359
+ Parameters
2360
+ ----------
2361
+ df : pandas.DataFrame
2362
+ The dataframe to be clustered.
2363
+ min_cluster_size : int, optional
2364
+ The number of samples in a neighborhood for a point to be considered as a core point, by default 10
2365
+
2366
+ Returns
2367
+ -------
2368
+ None
2369
+ """
2370
+ # Initialize a new column for cluster labels
2371
+ df["cluster"] = -1
2372
+
2373
+ # Apply DBSCAN clustering
2374
+ hdbscan = HDBSCAN(
2375
+ min_samples=None,
2376
+ min_cluster_size=min_cluster_size,
2377
+ cluster_selection_epsilon=0.0,
2378
+ max_cluster_size=None,
2379
+ metric="euclidean",
2380
+ alpha=1.0,
2381
+ cluster_selection_method="eom",
2382
+ allow_single_cluster=False,
2383
+ )
2384
+ labels = hdbscan.fit_predict(df[["x", "y"]])
2385
+
2386
+ # Number of clusters in labels, ignoring noise if present.
2387
+ n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)
2388
+ n_noise_ = list(labels).count(-1)
2389
+
2390
+ print("Estimated number of clusters: %d" % n_clusters_)
2391
+ print("Estimated number of noise points: %d" % n_noise_)
2392
+
2393
+ # Update the cluster labels in the original dataframe
2394
+ df.loc[df.index, "cluster"] = labels
2395
+
2396
+
2397
+ # plot points and identify points in radius of selected points
2398
+ def plot_selected_neighbors_with_shapes(
2399
+ full_df,
2400
+ selected_df,
2401
+ target_df,
2402
+ radius,
2403
+ plot=True,
2404
+ identification_column="community",
2405
+ ):
2406
+ # Get unique clusters from the full DataFrame
2407
+ unique_clusters = full_df[identification_column].unique()
2408
+
2409
+ # DataFrame to store points within the circle but from a different cluster
2410
+ all_in_circle_diff_cluster = []
2411
+
2412
+ # Loop through selected points
2413
+ for _, row in selected_df.iterrows():
2414
+ # Calculate distances from each point in the target DataFrame to the selected point
2415
+ distances = np.linalg.norm(
2416
+ target_df[["x", "y"]].values - np.array([row["x"], row["y"]]), axis=1
2417
+ )
2418
+
2419
+ # Identify points within the circle and from a different cluster
2420
+ in_circle = distances <= radius
2421
+ diff_cluster = target_df[identification_column] != row[identification_column]
2422
+ in_circle_diff_cluster = target_df[in_circle & diff_cluster]
2423
+
2424
+ # Append the result to the list
2425
+ all_in_circle_diff_cluster.append(in_circle_diff_cluster)
2426
+
2427
+ # Plot the points with a different shape if plot is True
2428
+ if plot:
2429
+ plt.scatter(
2430
+ in_circle_diff_cluster["x"],
2431
+ in_circle_diff_cluster["y"],
2432
+ facecolors="none",
2433
+ edgecolors="#DC0000B2",
2434
+ marker="*",
2435
+ s=100,
2436
+ zorder=5,
2437
+ label="Cell within proximity",
2438
+ )
2439
+
2440
+ # Concatenate the list of DataFrames into a single result DataFrame
2441
+ all_in_circle_diff_cluster = pd.concat(
2442
+ all_in_circle_diff_cluster, ignore_index=True
2443
+ )
2444
+
2445
+ # Plot selected points in yellow and draw circles around them if plot is True
2446
+ if plot:
2447
+ plt.scatter(
2448
+ selected_df["x"],
2449
+ selected_df["y"],
2450
+ color="#3C5488B2",
2451
+ label="Boarder cells",
2452
+ s=100,
2453
+ edgecolor="black",
2454
+ zorder=6,
2455
+ )
2456
+ for _, row in selected_df.iterrows():
2457
+ circle = plt.Circle(
2458
+ (row["x"], row["y"]),
2459
+ radius,
2460
+ color="#3C5488B2",
2461
+ fill=False,
2462
+ linestyle="--",
2463
+ alpha=0.5,
2464
+ )
2465
+ plt.gca().add_patch(circle)
2466
+
2467
+ # Set plot labels and title
2468
+ plt.xlabel("X")
2469
+ plt.ylabel("Y")
2470
+ plt.title(f"Cells within {radius} radius")
2471
+ plt.grid(False)
2472
+ plt.axis("equal")
2473
+
2474
+ # Place the legend outside the plot
2475
+ handles, labels = plt.gca().get_legend_handles_labels()
2476
+ by_label = dict(zip(labels, handles))
2477
+ plt.legend(
2478
+ by_label.values(),
2479
+ by_label.keys(),
2480
+ loc="center left",
2481
+ bbox_to_anchor=(1, 0.5),
2482
+ )
2483
+ plt.tight_layout()
2484
+ # set figure size
2485
+ plt.gcf().set_size_inches(15, 5)
2486
+
2487
+ plt.show()
2488
+
2489
+ # Remove duplicates from the final DataFrame
2490
+ all_in_circle_diff_cluster = all_in_circle_diff_cluster.drop_duplicates()
2491
+
2492
+ return all_in_circle_diff_cluster
2493
+
2494
+
2495
+ def process_cluster(args):
2496
+ (
2497
+ df,
2498
+ cluster,
2499
+ cluster_column,
2500
+ x_column,
2501
+ y_column,
2502
+ concave_hull_length_threshold,
2503
+ edge_neighbours,
2504
+ full_df,
2505
+ radius,
2506
+ plot,
2507
+ identification_column,
2508
+ ) = args
2509
+ # Filter DataFrame for the current cluster
2510
+ subset = df.loc[df[cluster_column] == cluster]
2511
+ points = subset[[x_column, y_column]].values
2512
+
2513
+ # Compute concave hull indexes
2514
+ idxes = concave_hull_indexes(
2515
+ points[:, :2],
2516
+ length_threshold=concave_hull_length_threshold,
2517
+ )
2518
+
2519
+ # Get hull points from the DataFrame
2520
+ hull_points = pd.DataFrame(points[idxes], columns=["x", "y"])
2521
+
2522
+ # Find nearest neighbors of hull points in the original DataFrame
2523
+ nbrs = NearestNeighbors(n_neighbors=edge_neighbours).fit(df[[x_column, y_column]])
2524
+ distances, indices = nbrs.kneighbors(hull_points[["x", "y"]])
2525
+
2526
+ hull_nearest_neighbors = df.iloc[indices.flatten()]
2527
+
2528
+ # Plot selected neighbors and get the DataFrame with different clusters in the circle
2529
+ prox_points = plot_selected_neighbors_with_shapes(
2530
+ full_df=full_df,
2531
+ selected_df=hull_nearest_neighbors,
2532
+ target_df=full_df,
2533
+ radius=radius,
2534
+ plot=plot,
2535
+ identification_column=identification_column,
2536
+ )
2537
+
2538
+ # Add a 'patch_id' column to identify the cluster
2539
+ prox_points["patch_id"] = cluster
2540
+
2541
+ return prox_points, hull_nearest_neighbors
2542
+
2543
+
2544
+ def identify_points_in_proximity(
2545
+ df,
2546
+ full_df,
2547
+ identification_column,
2548
+ cluster_column="cluster",
2549
+ x_column="x",
2550
+ y_column="y",
2551
+ radius=200,
2552
+ edge_neighbours=3,
2553
+ plot=True,
2554
+ concave_hull_length_threshold=50,
2555
+ ):
2556
+ num_processes = max(
2557
+ 1, os.cpu_count() - 2
2558
+ ) # Use all available CPUs minus 2, but at least 1
2559
+ with Pool(processes=num_processes) as pool:
2560
+ results = pool.map(
2561
+ process_cluster,
2562
+ [
2563
+ (
2564
+ df,
2565
+ cluster,
2566
+ cluster_column,
2567
+ x_column,
2568
+ y_column,
2569
+ concave_hull_length_threshold,
2570
+ edge_neighbours,
2571
+ full_df,
2572
+ radius,
2573
+ plot,
2574
+ identification_column,
2575
+ )
2576
+ for cluster in set(df[cluster_column]) - {-1}
2577
+ ],
2578
+ )
2579
+
2580
+ # Unpack the results
2581
+ result_list, outline_list = zip(*results)
2582
+
2583
+ # Concatenate the list of DataFrames into a single result DataFrame
2584
+ if len(result_list) > 0:
2585
+ result = pd.concat(result_list)
2586
+ else:
2587
+ result = pd.DataFrame(columns=["x", "y", "patch_id", identification_column])
2588
+
2589
+ if len(outline_list) > 0:
2590
+ outlines = pd.concat(outline_list)
2591
+ else:
2592
+ outlines = pd.DataFrame(columns=["x", "y", "patch_id", identification_column])
2593
+
2594
+ return result, outlines
2595
+
2596
+
2597
+ # This function analyzes what is in proximity of a selected group (CN, Celltype, etc...).
2598
+ def patch_proximity_analysis(
2599
+ adata,
2600
+ region_column,
2601
+ patch_column,
2602
+ group,
2603
+ min_cluster_size=80,
2604
+ x_column="x",
2605
+ y_column="y",
2606
+ radius=128,
2607
+ edge_neighbours=3,
2608
+ plot=True,
2609
+ savefig=False,
2610
+ output_dir="./",
2611
+ output_fname="",
2612
+ key_name="ppa_result",
2613
+ plot_color="#6a3d9a",
2614
+ ):
2615
+ """
2616
+ Performs a proximity analysis on patches of a given group within each region of a dataset.
2617
+
2618
+ Parameters:
2619
+ adata (AnnData): The annotated data matrix of shape n_obs x n_vars. Rows correspond to cells and columns to genes.
2620
+ region_column (str): The name of the column in the DataFrame that contains the region information.
2621
+ patch_column (str): The name of the column in the DataFrame that contains the patch information.
2622
+ group (str): The group to perform the proximity analysis on.
2623
+ min_cluster_size (int, optional): The minimum number of samples required to form a dense region. Default is 80.
2624
+ x_column (str, optional): The name of the column in the DataFrame that contains the x-coordinate. Default is 'x'.
2625
+ y_column (str, optional): The name of the column in the DataFrame that contains the y-coordinate. Default is 'y'.
2626
+ radius (int, optional): The radius within which to identify points in proximity. Default is 128.
2627
+ edge_neighbours (int, optional): The number of edge neighbours to consider. Default is 3.
2628
+ plot (bool, optional): Whether to plot the patches. Default is True.
2629
+ savefig (bool, optional): Whether to save the figure. Default is False.
2630
+ output_dir (str, optional): The directory to save the figure in. Default is "./".
2631
+ output_fname (str, optional): The filename to save the figure as. Default is "".
2632
+ key_name (str, optional): The key name to store the results in the AnnData object. Default is 'ppa_result'.
2633
+
2634
+ Returns:
2635
+ final_results (DataFrame): A DataFrame containing the results of the proximity analysis.
2636
+ outlines_results (DataFrame): A DataFrame containing the outlines of the patches.
2637
+ """
2638
+
2639
+ df = adata.obs
2640
+
2641
+ for col in df.select_dtypes(["category"]).columns:
2642
+ df[col] = df[col].astype(str)
2643
+
2644
+ # list to store results for each region
2645
+ region_results = []
2646
+ outlines = []
2647
+
2648
+ for region in df[region_column].unique():
2649
+ df_region = df[df[region_column] == region].copy()
2650
+
2651
+ df_community = df_region[df_region[patch_column] == group].copy()
2652
+
2653
+ if df_community.shape[0] < min_cluster_size:
2654
+ print(f"No {group} in {region}")
2655
+ continue
2656
+
2657
+ else:
2658
+ apply_dbscan_clustering(df_community, min_cluster_size=min_cluster_size)
2659
+
2660
+ # plot patches
2661
+ if plot:
2662
+ df_filtered = df_community[df_community["cluster"] != -1]
2663
+ fig, ax = plt.subplots(figsize=(10, 10))
2664
+ ax.scatter(df_filtered["x"], df_filtered["y"], c=plot_color, alpha=0.5)
2665
+ ax.set_title(f"HDBSCAN Clusters for {region}_{group}")
2666
+ ax.set_xlabel(x_column)
2667
+ ax.set_ylabel(y_column)
2668
+ ax.grid(False)
2669
+ ax.axis("equal")
2670
+
2671
+ if savefig:
2672
+ fig.savefig(
2673
+ output_dir
2674
+ + output_fname
2675
+ + "_"
2676
+ + str(region)
2677
+ + "_patch_proximity.pdf",
2678
+ bbox_inches="tight",
2679
+ )
2680
+ else:
2681
+ plt.show()
2682
+
2683
+ results, hull_nearest_neighbors = identify_points_in_proximity(
2684
+ df=df_community,
2685
+ full_df=df_region,
2686
+ cluster_column="cluster",
2687
+ identification_column=patch_column,
2688
+ x_column=x_column,
2689
+ y_column=y_column,
2690
+ radius=radius,
2691
+ edge_neighbours=edge_neighbours,
2692
+ plot=plot,
2693
+ )
2694
+
2695
+ # add hull_nearest_neighbors to list
2696
+ outlines.append(hull_nearest_neighbors)
2697
+
2698
+ print(f"Finished {region}_{group}")
2699
+
2700
+ # append to region_results
2701
+ region_results.append(results)
2702
+
2703
+ # Concatenate all results into a single DataFrame
2704
+ final_results = pd.concat(region_results)
2705
+
2706
+ outlines_results = pd.concat(outlines)
2707
+
2708
+ # generate new column named unique_patch_ID that combines the region, group and patch ID
2709
+ final_results["unique_patch_ID"] = (
2710
+ final_results[region_column]
2711
+ + "_"
2712
+ + final_results[patch_column]
2713
+ + "_"
2714
+ + "patch_no_"
2715
+ + final_results["patch_id"].astype(str)
2716
+ )
2717
+
2718
+ adata.uns[key_name] = final_results
2719
+
2720
+ return final_results, outlines_results
2721
+
2722
+
2723
+ def stellar_get_tonsilbe_edge_index(pos, distance_thres):
2724
+ """
2725
+ Constructs edge indexes in one region based on pairwise distances and a distance threshold.
2726
+
2727
+ Parameters:
2728
+ pos (array-like): An array-like object of shape (n_samples, n_features) representing the positions.
2729
+ distance_thres (float): The distance threshold. Pairs of positions with distances less than this threshold will be considered as edges.
2730
+
2731
+ Returns:
2732
+ edge_list (list): A list of lists where each inner list contains two indices representing an edge.
2733
+ """
2734
+ # construct edge indexes in one region
2735
+ edge_list = []
2736
+ dists = pairwise_distances(pos)
2737
+ dists_mask = dists < distance_thres
2738
+ np.fill_diagonal(dists_mask, 0)
2739
+ edge_list = np.transpose(np.nonzero(dists_mask)).tolist()
2740
+ return edge_list
2741
+
2742
+
2743
+ def adata_stellar(
2744
+ adata_train,
2745
+ adata_unannotated,
2746
+ celltype_col="coarse_anno3",
2747
+ x_col="x",
2748
+ y_col="y",
2749
+ sample_rate=0.5,
2750
+ distance_thres=50,
2751
+ epochs=50,
2752
+ key_added="stellar_pred",
2753
+ STELLAR_path="",
2754
+ ):
2755
+ """
2756
+ Applies the STELLAR algorithm to the given annotated and unannotated data.
2757
+
2758
+ Parameters:
2759
+ adata_train (AnnData): The annotated data.
2760
+ adata_unannotated (AnnData): The unannotated data.
2761
+ celltype_col (str, optional): The column name for cell types in the annotated data. Defaults to 'coarse_anno3'.
2762
+ x_col (str, optional): The column name for x coordinates in the data. Defaults to 'x'.
2763
+ y_col (str, optional): The column name for y coordinates in the data. Defaults to 'y'.
2764
+ sample_rate (float, optional): The rate at which to sample the training data. Defaults to 0.5.
2765
+ distance_thres (int, optional): The distance threshold for constructing edge indexes. Defaults to 50.
2766
+ key_added (str, optional): The key to be added to the unannotated data's obs dataframe for the predicted results. Defaults to 'stellar_pred'.
2767
+
2768
+ Returns:
2769
+ adata (AnnData): The unannotated data with the added key for the predicted results.
2770
+ """
2771
+
2772
+ sys.path.append(str(STELLAR_path))
2773
+ from datasets import GraphDataset
2774
+ from STELLAR import STELLAR
2775
+ from utils import prepare_save_dir
2776
+
2777
+ parser = argparse.ArgumentParser(description="STELLAR")
2778
+ parser.add_argument(
2779
+ "--seed", type=int, default=1, metavar="S", help="random seed (default: 1)"
2780
+ )
2781
+ parser.add_argument("--name", type=str, default="STELLAR")
2782
+ parser.add_argument("--epochs", type=int, default=50)
2783
+ parser.add_argument("--lr", type=float, default=1e-3)
2784
+ parser.add_argument("--wd", type=float, default=5e-2)
2785
+ parser.add_argument("--input-dim", type=int, default=26)
2786
+ parser.add_argument("--num-heads", type=int, default=13)
2787
+ parser.add_argument("--num-seed-class", type=int, default=3)
2788
+ parser.add_argument("--sample-rate", type=float, default=0.5)
2789
+ parser.add_argument(
2790
+ "-b", "--batch-size", default=1, type=int, metavar="N", help="mini-batch size"
2791
+ )
2792
+ parser.add_argument("--distance_thres", default=50, type=int)
2793
+ parser.add_argument("--savedir", type=str, default="./")
2794
+ args = parser.parse_args(args=[])
2795
+ args.cuda = torch.cuda.is_available()
2796
+ args.device = torch.device("cuda" if args.cuda else "cpu")
2797
+ args.epochs = 50
2798
+
2799
+ # prepare input data
2800
+ print("Preparing input data")
2801
+ train_df = adata_train.to_df()
2802
+
2803
+ # add to train_df
2804
+ positions_celltype = adata_train.obs[[x_col, y_col, celltype_col]]
2805
+
2806
+ train_df = pd.concat([train_df, positions_celltype], axis=1)
2807
+
2808
+ train_df = train_df.sample(n=round(sample_rate * len(train_df)), random_state=1)
2809
+
2810
+ train_X = train_df.iloc[:, 0:-3].values
2811
+ test_X = adata_unannotated.to_df().values
2812
+
2813
+ train_y = train_df[celltype_col].str.lower()
2814
+ train_y
2815
+
2816
+ labeled_pos = train_df.iloc[
2817
+ :, -3:-1
2818
+ ].values # x,y coordinates, indexes depend on specific datasets
2819
+ unlabeled_pos = adata_unannotated.obs[[x_col, y_col]].values
2820
+
2821
+ cell_types = np.sort(list(set(train_y))).tolist()
2822
+ cell_types
2823
+
2824
+ cell_type_dict = {}
2825
+ inverse_dict = {}
2826
+
2827
+ for i, cell_type in enumerate(cell_types):
2828
+ cell_type_dict[cell_type] = i
2829
+ inverse_dict[i] = cell_type
2830
+
2831
+ train_y = np.array([cell_type_dict[x] for x in train_y])
2832
+
2833
+ labeled_edges = stellar_get_tonsilbe_edge_index(
2834
+ labeled_pos, distance_thres=distance_thres
2835
+ )
2836
+ unlabeled_edges = stellar_get_tonsilbe_edge_index(
2837
+ unlabeled_pos, distance_thres=distance_thres
2838
+ )
2839
+
2840
+ # build dataset
2841
+ print("Building dataset")
2842
+ dataset = GraphDataset(train_X, train_y, test_X, labeled_edges, unlabeled_edges)
2843
+
2844
+ # run stellar
2845
+ print("Running STELLAR")
2846
+ stellar = STELLAR(args, dataset)
2847
+ stellar.train()
2848
+ _, results = stellar.pred()
2849
+
2850
+ results = results.astype("object")
2851
+ for i in range(len(results)):
2852
+ if results[i] in inverse_dict.keys():
2853
+ results[i] = inverse_dict[results[i]]
2854
+ adata_unannotated.obs[key_added] = pd.Categorical(results)
2855
+
2856
+ # make stellar_pred a string
2857
+ adata_unannotated.obs["stellar_pred"] = adata_unannotated.obs[
2858
+ "stellar_pred"
2859
+ ].astype(str)
2860
+
2861
+ return adata_unannotated
2862
+
2863
+
2864
+ def ml_train(
2865
+ adata_train,
2866
+ label,
2867
+ test_size=0.33,
2868
+ random_state=0,
2869
+ model="svm",
2870
+ nan_policy_y="raise",
2871
+ showfig=True,
2872
+ figsize=(10, 8),
2873
+ ):
2874
+ """
2875
+ Train a svm model on the provided data.
2876
+
2877
+ Parameters
2878
+ ----------
2879
+ adata_train : AnnData
2880
+ The training data as an AnnData object.
2881
+ label : str
2882
+ The label to predict.
2883
+ test_size : float, optional
2884
+ The proportion of the dataset to include in the test split, by default 0.33.
2885
+ random_state : int, optional
2886
+ The seed used by the random number generator, by default 0.
2887
+ model : str, optional
2888
+ The type of model to train, by default "svm".
2889
+ nan_policy_y : str, optional
2890
+ How to handle NaNs in the label, by default "raise". Can be either 'omit' or 'raise'.
2891
+ showfig : bool, optional
2892
+ Whether to show the confusion matrix as a heatmap, by default True.
2893
+
2894
+ Returns
2895
+ -------
2896
+ SVC
2897
+ The trained Support Vector Classifier model.
2898
+
2899
+ Raises
2900
+ ------
2901
+ ValueError
2902
+ If `nan_policy_y` is not 'omit' or 'raise'.
2903
+ """
2904
+ X = pd.DataFrame(adata_train.X)
2905
+ y = adata_train.obs[label].values
2906
+
2907
+ if nan_policy_y == "omit":
2908
+ y_msk = ~y.isna()
2909
+ X = X[y_msk]
2910
+ y = y[y_msk]
2911
+ elif nan_policy_y == "raise":
2912
+ pass
2913
+ else:
2914
+ raise ValueError("nan_policy_y must be either 'omit' or 'raise'")
2915
+
2916
+ X_train, X_test, y_train, y_test = train_test_split(
2917
+ X, y, test_size=test_size, random_state=random_state
2918
+ )
2919
+
2920
+ print(y.unique().sort_values())
2921
+
2922
+ print("Training now!")
2923
+ svc = SVC(kernel="linear", probability=True)
2924
+ svc.fit(X_train, y_train)
2925
+ pred = []
2926
+ y_prob = svc.predict_proba(X_test)
2927
+ y_prob = pd.DataFrame(y_prob)
2928
+ y_prob.columns = svc.classes_
2929
+
2930
+ svm_label = y_prob.idxmax(axis=1, skipna=True)
2931
+ target_names = svc.classes_
2932
+ print("Evaluating now!")
2933
+ svm_eval = classification_report(
2934
+ y_true=y_test, y_pred=svm_label, target_names=target_names, output_dict=True
2935
+ )
2936
+ if showfig:
2937
+ plt.figure(figsize=figsize)
2938
+ sns.heatmap(pd.DataFrame(svm_eval).iloc[:-1, :].T, annot=True)
2939
+ plt.show()
2940
+
2941
+ return svc
2942
+
2943
+
2944
+ def ml_predict(adata_val, svc, save_name="svm_pred", return_prob_mat=False):
2945
+ """
2946
+ Predict labels for a given dataset using a trained Support Vector Classifier (SVC) model.
2947
+
2948
+ Parameters
2949
+ ----------
2950
+ adata_val : AnnData
2951
+ The validation data as an AnnData object.
2952
+ svc : SVC
2953
+ The trained Support Vector Classifier model.
2954
+ save_name : str, optional
2955
+ The name under which the predictions will be saved in the AnnData object, by default "svm_pred".
2956
+ return_prob_mat : bool, optional
2957
+ Whether to return the probability matrix, by default False.
2958
+
2959
+ Returns
2960
+ -------
2961
+ DataFrame or None
2962
+ If `return_prob_mat` is True, returns a DataFrame with the probability matrix. Otherwise, returns None.
2963
+
2964
+ """
2965
+ print("Classifying!")
2966
+ X_val = pd.DataFrame(adata_val.X)
2967
+ y_prob_val = svc.predict_proba(X_val)
2968
+ y_prob_val = pd.DataFrame(y_prob_val)
2969
+ y_prob_val.columns = svc.classes_
2970
+ svm_label_val = y_prob_val.idxmax(axis=1, skipna=True)
2971
+ svm_label_val.index = X_val.index
2972
+ print("Saving cell type labels to adata!")
2973
+ adata_val.obs[save_name] = svm_label_val.values
2974
+ if return_prob_mat:
2975
+ print("Returning probability matrix!")
2976
+ y_prob_val.columns = svc.classes_
2977
+ svm_label_val = y_prob_val.idxmax(axis=1, skipna=True)
2978
+ return svm_label_val
2979
+
2980
+
2981
+ class ImageProcessor:
2982
+ """
2983
+ A class used to process images and compute channel means and sums.
2984
+
2985
+ ...
2986
+
2987
+ Attributes
2988
+ ----------
2989
+ flatmasks : ndarray
2990
+ 2D numpy array containing masks for each cell.
2991
+
2992
+ Methods
2993
+ -------
2994
+ update_adjacency_value(adjacency_matrix, original, neighbor):
2995
+ Updates the adjacency matrix based on the original and neighbor values.
2996
+ update_adjacency_matrix(plane_mask_flattened, width, height, adjacency_matrix, index):
2997
+ Updates the adjacency matrix based on the flattened plane mask.
2998
+ compute_channel_means_sums_compensated(image):
2999
+ Computes the channel means and sums for each cell and compensates them.
3000
+ """
3001
+
3002
+ def __init__(self, flatmasks):
3003
+ """
3004
+ Constructs all the necessary attributes for the ImageProcessor object.
3005
+
3006
+ Parameters
3007
+ ----------
3008
+ flatmasks : ndarray
3009
+ 2D numpy array containing masks for each cell.
3010
+ """
3011
+ self.flatmasks = flatmasks
3012
+
3013
+ def update_adjacency_value(self, adjacency_matrix, original, neighbor):
3014
+ # This function is copied from CellSeg
3015
+ """
3016
+ Updates the adjacency matrix based on the original and neighbor values.
3017
+
3018
+ Parameters
3019
+ ----------
3020
+ adjacency_matrix : ndarray
3021
+ 2D numpy array representing the adjacency matrix.
3022
+ original : int
3023
+ Original value.
3024
+ neighbor : int
3025
+ Neighbor value.
3026
+
3027
+ Returns
3028
+ -------
3029
+ bool
3030
+ True if the original and neighbor values are different and not zero, False otherwise.
3031
+ """
3032
+ border = False
3033
+
3034
+ if original != 0 and original != neighbor:
3035
+ border = True
3036
+ if neighbor != 0:
3037
+ adjacency_matrix[int(original - 1), int(neighbor - 1)] += 1
3038
+ return border
3039
+
3040
+ def update_adjacency_matrix(
3041
+ self, plane_mask_flattened, width, height, adjacency_matrix, index
3042
+ ):
3043
+ # This function is copied from CellSeg
3044
+ """
3045
+ Updates the adjacency matrix based on the flattened plane mask.
3046
+
3047
+ Parameters
3048
+ ----------
3049
+ plane_mask_flattened : ndarray
3050
+ 1D numpy array representing the flattened plane mask.
3051
+ width : int
3052
+ Width of the plane mask.
3053
+ height : int
3054
+ Height of the plane mask.
3055
+ adjacency_matrix : ndarray
3056
+ 2D numpy array representing the adjacency matrix.
3057
+ index : int
3058
+ Index of the current cell in the flattened plane mask.
3059
+ """
3060
+ mod_value_width = index % width
3061
+ origin_mask = plane_mask_flattened[index]
3062
+ left, right, up, down = False, False, False, False
3063
+
3064
+ if mod_value_width != 0:
3065
+ left = self.update_adjacency_value(
3066
+ adjacency_matrix, origin_mask, plane_mask_flattened[index - 1]
3067
+ )
3068
+ if mod_value_width != width - 1:
3069
+ right = self.update_adjacency_value(
3070
+ adjacency_matrix, origin_mask, plane_mask_flattened[index + 1]
3071
+ )
3072
+ if index >= width:
3073
+ up = self.update_adjacency_value(
3074
+ adjacency_matrix, origin_mask, plane_mask_flattened[index - width]
3075
+ )
3076
+ if index <= len(plane_mask_flattened) - 1 - width:
3077
+ down = self.update_adjacency_value(
3078
+ adjacency_matrix, origin_mask, plane_mask_flattened[index + width]
3079
+ )
3080
+
3081
+ if left or right or up or down:
3082
+ adjacency_matrix[int(origin_mask - 1), int(origin_mask - 1)] += 1
3083
+
3084
+ def compute_channel_means_sums_compensated(self, image):
3085
+ # This function is copied from CellSeg but modified to solve the least squares problem with torch instead of numpy
3086
+ """
3087
+ Computes the channel means and sums for each cell and compensates them.
3088
+
3089
+ Parameters
3090
+ ----------
3091
+ image : ndarray
3092
+ 3D numpy array representing the image.
3093
+
3094
+ Returns
3095
+ -------
3096
+ compensated_means : ndarray
3097
+ 2D numpy array representing the compensated means for each cell.
3098
+ means : ndarray
3099
+ 2D numpy array representing the means for each cell.
3100
+ channel_counts : ndarray
3101
+ 1D numpy array representing the counts for each cell.
3102
+ """
3103
+ height, width, n_channels = image.shape
3104
+ mask_height, mask_width = self.flatmasks.shape
3105
+ n_masks = len(np.unique(self.flatmasks)) - 1
3106
+ channel_sums = np.zeros((n_masks, n_channels))
3107
+ channel_counts = np.zeros((n_masks, n_channels))
3108
+ if n_masks == 0:
3109
+ return channel_sums, channel_sums, channel_counts
3110
+
3111
+ squashed_image = np.reshape(image, (height * width, n_channels))
3112
+
3113
+ # masklocs = np.nonzero(self.flatmasks)
3114
+ # plane_mask = np.zeros((mask_height, mask_width), dtype = np.uint32)
3115
+ # plane_mask[masklocs[0], masklocs[1]] = masklocs[2] + 1
3116
+ # plane_mask = plane_mask.flatten()
3117
+ plane_mask = self.flatmasks.flatten()
3118
+
3119
+ adjacency_matrix = np.zeros((n_masks, n_masks))
3120
+ for i in range(len(plane_mask)):
3121
+ self.update_adjacency_matrix(
3122
+ plane_mask, mask_width, mask_height, adjacency_matrix, i
3123
+ )
3124
+
3125
+ mask_val = plane_mask[i] - 1
3126
+ if mask_val != -1:
3127
+ channel_sums[mask_val.astype(np.int32)] += squashed_image[i]
3128
+ channel_counts[mask_val.astype(np.int32)] += 1
3129
+
3130
+ # Normalize adjacency matrix
3131
+ for i in range(n_masks):
3132
+ adjacency_matrix[i] = adjacency_matrix[i] / (
3133
+ max(adjacency_matrix[i, i], 1) * 2
3134
+ )
3135
+ adjacency_matrix[i, i] = 1
3136
+
3137
+ means = np.true_divide(
3138
+ channel_sums,
3139
+ channel_counts,
3140
+ out=np.zeros_like(channel_sums, dtype="float"),
3141
+ where=channel_counts != 0,
3142
+ )
3143
+ # Convert your numpy arrays to PyTorch tensors
3144
+ adjacency_matrix_torch = torch.from_numpy(adjacency_matrix)
3145
+ means_torch = torch.from_numpy(means)
3146
+
3147
+ # Solve the least squares problem
3148
+ results_torch = torch.linalg.lstsq(adjacency_matrix_torch, means_torch).solution
3149
+
3150
+ # Convert the result back to a numpy array if needed
3151
+ # Convert the result back to a numpy array if needed
3152
+ results = results_torch.numpy()
3153
+ compensated_means = np.maximum(results, np.zeros(results.shape))
3154
+
3155
+ return compensated_means, means, channel_counts[:, 0]
3156
+
3157
+
3158
+ def compensate_cell_matrix(df, image_dict, masks, overwrite=True):
3159
+ """
3160
+ Compensate cell matrix by computing channel means and sums.
3161
+
3162
+ Parameters
3163
+ ----------
3164
+ df : DataFrame
3165
+ The DataFrame to which the compensated means will be added.
3166
+ image_dict : dict
3167
+ Dictionary containing images for each channel.
3168
+ masks : ndarray
3169
+ 3D numpy array containing masks for each cell.
3170
+ overwrite : bool, optional
3171
+ If True, overwrite existing columns in df. If False, add new columns to df. Default is True.
3172
+
3173
+ Returns
3174
+ -------
3175
+ DataFrame
3176
+ The DataFrame with added compensated means.
3177
+
3178
+ Notes
3179
+ -----
3180
+ The function computes the channel means and sums for each cell, compensates them, and adds them to the DataFrame.
3181
+ The compensated means are added to the DataFrame with column names from the keys of the image_dict.
3182
+ If overwrite is True, existing columns in the DataFrame are overwritten. If overwrite is False, new columns are added to the DataFrame.
3183
+ """
3184
+ masks = masks.squeeze()
3185
+ image_list = [image_dict[channel_name] for channel_name in image_dict.keys()]
3186
+
3187
+ # Stack the 2D numpy arrays along the third dimension to create a 3D numpy array
3188
+ image = np.stack(image_list, axis=-1)
3189
+
3190
+ # Now you can use `image` as the input for the function
3191
+ processor = ImageProcessor(masks)
3192
+ (
3193
+ compensated_means,
3194
+ means,
3195
+ channel_counts,
3196
+ ) = processor.compute_channel_means_sums_compensated(image)
3197
+
3198
+ # Get the keys
3199
+ keys = list(image_dict.keys())
3200
+
3201
+ # Cycle over the keys
3202
+ for i in range(len(keys)):
3203
+ # Add the compensated_means to the DataFrame with column names from keys
3204
+
3205
+ if overwrite == True:
3206
+ df[keys[i]] = compensated_means[:, i]
3207
+ else:
3208
+ df[keys[i] + "_compensated"] = compensated_means[:, i]
3209
+
3210
+ return df
3211
+
3212
+
3213
+ def masks_to_outlines_scikit_image(masks):
3214
+ """get outlines of masks as a 0-1 array
3215
+
3216
+ Parameters
3217
+ ----------------
3218
+
3219
+ masks: int, 2D or 3D array
3220
+ size [Ly x Lx] or [Lz x Ly x Lx], 0=NO masks; 1,2,...=mask labels
3221
+
3222
+ Returns
3223
+ ----------------
3224
+
3225
+ outlines: 2D or 3D array
3226
+ size [Ly x Lx] or [Lz x Ly x Lx], True pixels are outlines
3227
+
3228
+ """
3229
+ if masks.ndim > 3 or masks.ndim < 2:
3230
+ raise ValueError(
3231
+ "masks_to_outlines takes 2D or 3D array, not %dD array" % masks.ndim
3232
+ )
3233
+
3234
+ if masks.ndim == 3:
3235
+ outlines = np.zeros(masks.shape, bool)
3236
+ for i in range(masks.shape[0]):
3237
+ outlines[i] = find_boundaries(masks[i], mode="inner")
3238
+ return outlines
3239
+ else:
3240
+ return find_boundaries(masks, mode="inner")
3241
+
3242
+
3243
+ def tm_viewer(
3244
+ adata,
3245
+ images_pickle_path,
3246
+ directory,
3247
+ region_column="unique_region",
3248
+ region="",
3249
+ xSelector="x",
3250
+ ySelector="y",
3251
+ color_by="celltype_fine",
3252
+ keep_list=None,
3253
+ include_masks=True,
3254
+ open_viewer=True,
3255
+ add_UMAP=True,
3256
+ ):
3257
+ segmented_matrix = adata.obs
3258
+
3259
+ with open(images_pickle_path, "rb") as f:
3260
+ seg_output = pickle.load(f)
3261
+
3262
+ image_dict = seg_output["image_dict"]
3263
+ masks = seg_output["masks"]
3264
+
3265
+ if keep_list == None:
3266
+ keep_list = [region_column, xSelector, ySelector, color_by]
3267
+
3268
+ print("Preparing TissUUmaps input...")
3269
+
3270
+ cache_dir = pathlib.Path(directory) / region
3271
+ cache_dir.mkdir(parents=True, exist_ok=True)
3272
+
3273
+ # only keep columns in keep_list
3274
+ segmented_matrix = segmented_matrix[keep_list]
3275
+
3276
+ if add_UMAP == True:
3277
+ # add UMAP coordinates to segmented_matrix
3278
+ segmented_matrix["UMAP_1"] = adata.obsm["X_umap"][:, 0]
3279
+ segmented_matrix["UMAP_2"] = adata.obsm["X_umap"][:, 1]
3280
+
3281
+ csv_paths = []
3282
+ # separate matrix by region and save every region as single csv file
3283
+ region_matrix = segmented_matrix.loc[segmented_matrix[region_column] == region]
3284
+
3285
+ region_matrix.to_csv(cache_dir / (region + ".csv"))
3286
+ csv_paths.append(cache_dir / (region + ".csv"))
3287
+
3288
+ # generate subdirectory for images
3289
+ image_dir = cache_dir / "images"
3290
+ image_dir.mkdir(parents=True, exist_ok=True)
3291
+
3292
+ image_list = []
3293
+ # save every image as tif file in image directory from image_dict. name by key in image_dict
3294
+ for key, image in image_dict.items():
3295
+ file_path = os.path.join(image_dir, f"{key}.tif")
3296
+ imsave(file_path, image, check_contrast=False)
3297
+ image_list.append(file_path)
3298
+
3299
+ if include_masks == True:
3300
+ # select first item from image_dict as reference image
3301
+ reference_image = list(image_dict.values())[0]
3302
+
3303
+ # make reference image black by setting all values to 0
3304
+ reference_image = np.zeros_like(reference_image)
3305
+
3306
+ # make the reference image rgb. Add empty channels
3307
+ if len(reference_image.shape) == 2:
3308
+ reference_image = np.expand_dims(reference_image, axis=-1)
3309
+ reference_image = np.repeat(reference_image, 3, axis=-1)
3310
+
3311
+ # remove last dimension from masks
3312
+ masks_3d = np.squeeze(masks)
3313
+ outlines = masks_to_outlines_scikit_image(masks_3d)
3314
+
3315
+ reference_image[outlines == True] = [255, 0, 0]
3316
+
3317
+ file_path = os.path.join(image_dir, "masks.jpg")
3318
+
3319
+ # save black pixel as transparent
3320
+ reference_image = reference_image.astype(np.uint8)
3321
+
3322
+ imsave(file_path, reference_image)
3323
+ image_list.append(file_path)
3324
+
3325
+ if open_viewer == True:
3326
+ print("Opening TissUUmaps viewer...")
3327
+ tj.loaddata(
3328
+ images=image_list,
3329
+ csvFiles=[str(p) for p in csv_paths],
3330
+ xSelector=xSelector,
3331
+ ySelector=ySelector,
3332
+ keySelector=color_by,
3333
+ nameSelector=color_by,
3334
+ colorSelector=color_by,
3335
+ piechartSelector=None,
3336
+ shapeSelector=None,
3337
+ scaleSelector=None,
3338
+ fixedShape=None,
3339
+ scaleFactor=1,
3340
+ colormap=None,
3341
+ compositeMode="source-over",
3342
+ boundingBox=None,
3343
+ port=5100,
3344
+ host="localhost",
3345
+ height=900,
3346
+ tmapFilename=region + "_project",
3347
+ plugins=[
3348
+ "Plot_Histogram",
3349
+ "Points2Regions",
3350
+ "Spot_Inspector",
3351
+ "Feature_Space",
3352
+ "ClassQC",
3353
+ ],
3354
+ )
3355
+
3356
+ return image_list, csv_paths
3357
+
3358
+
3359
+ def install_gpu_leiden(CUDA="12"):
3360
+ """
3361
+ Install the necessary packages for GPU-accelerated Leiden clustering.
3362
+
3363
+ Parameters
3364
+ ----------
3365
+ CUDA : str, optional
3366
+ The version of CUDA to use for the installation. Options are '11' and '12'. Default is '12'.
3367
+
3368
+ Returns
3369
+ -------
3370
+ None
3371
+
3372
+ Notes
3373
+ -----
3374
+ This function runs a series of pip install commands to install the necessary packages. The specific packages and versions installed depend on the CUDA
3375
+ version. The function prints the output and any errors from each command.
3376
+ """
3377
+ if platform.system() != "Linux":
3378
+ print("This feature is currently only supported on Linux.")
3379
+
3380
+ else:
3381
+ print("installing rapids_singlecell")
3382
+ # Define the commands to run
3383
+ if CUDA == "11":
3384
+ commands = [
3385
+ "pip install rapids-singlecell==0.9.5",
3386
+ "pip install --extra-index-url=https://pypi.nvidia.com cudf-cu11==24.2.* dask-cudf-cu11==24.2.* cuml-cu11==24.2.* cugraph-cu11==24.2.* cuspatial-cu11==24.2.* cuproj-cu11==24.2.* cuxfilter-cu11==24.2.* cucim-cu11==24.2.* pylibraft-cu11==24.2.* raft-dask-cu11==24.2.*",
3387
+ "pip install protobuf==3.20",
3388
+ ]
3389
+ else:
3390
+ commands = [
3391
+ "pip install rapids-singlecell==0.9.5",
3392
+ "pip install --extra-index-url=https://pypi.nvidia.com cudf-cu12==24.2.* dask-cudf-cu12==24.2.* cuml-cu12==24.2.* cugraph-cu12==24.2.* cuspatial-cu12==24.2.* cuproj-cu12==24.2.* cuxfilter-cu12==24.2.* cucim-cu12==24.2.* pylibraft-cu12==24.2.* raft-dask-cu12==24.2.*",
3393
+ "pip install protobuf==3.20",
3394
+ ]
3395
+
3396
+ # Run each command
3397
+ for command in commands:
3398
+ process = subprocess.Popen(
3399
+ command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE
3400
+ )
3401
+ stdout, stderr = process.communicate()
3402
+
3403
+ # Print the output and error, if any
3404
+ if stdout:
3405
+ print(f"Output:\n{stdout.decode()}")
3406
+ if stderr:
3407
+ print(f"Error:\n{stderr.decode()}")
3408
+
3409
+
3410
+ def anndata_to_GPU(
3411
+ adata: AnnData,
3412
+ layer: str | None = None,
3413
+ convert_all: bool = False,
3414
+ ) -> AnnData:
3415
+ """
3416
+ Transfers matrices and arrays to the GPU
3417
+
3418
+ Parameters
3419
+ ----------
3420
+ adata
3421
+ AnnData object
3422
+
3423
+ layer
3424
+ Layer to use as input instead of `X`. If `None`, `X` is used.
3425
+
3426
+ convert_all
3427
+ If True, move all supported arrays and matrices on the GPU
3428
+
3429
+ Returns
3430
+ -------
3431
+ Returns an updated copy with data on GPU
3432
+ """
3433
+
3434
+ adata_gpu = adata.copy()
3435
+
3436
+ if convert_all:
3437
+ anndata_to_GPU(adata_gpu)
3438
+ if adata_gpu.layers:
3439
+ for key in adata_gpu.layers.keys():
3440
+ anndata_to_GPU(adata_gpu, layer=key)
3441
+ else:
3442
+ X = _get_obs_rep(adata_gpu, layer=layer)
3443
+ if isspmatrix_csr_cpu(X):
3444
+ X = csr_matrix_gpu(X)
3445
+ elif isspmatrix_csc_cpu(X):
3446
+ X = csc_matrix_gpu(X)
3447
+ elif isinstance(X, np.ndarray):
3448
+ # Convert to CuPy array only when necessary for GPU computations
3449
+ X_gpu = cp.asarray(X)
3450
+ X = X_gpu
3451
+ else:
3452
+ error = layer if layer else "X"
3453
+ warnings.warn(f"{error} not supported for GPU conversion", Warning)
3454
+
3455
+ _set_obs_rep(adata_gpu, X, layer=layer)
3456
+
3457
+ return adata_gpu
3458
+
3459
+
3460
+ def anndata_to_CPU(
3461
+ adata: AnnData,
3462
+ layer: str | None = None,
3463
+ convert_all: bool = False,
3464
+ copy: bool = False,
3465
+ ) -> AnnData | None:
3466
+ """
3467
+ Transfers matrices and arrays from the GPU
3468
+
3469
+ Parameters
3470
+ ----------
3471
+ adata
3472
+ AnnData object
3473
+
3474
+ layer
3475
+ Layer to use as input instead of `X`. If `None`, `X` is used.
3476
+
3477
+ convert_all
3478
+ If True, move all GPU based arrays and matrices to the host memory
3479
+
3480
+ copy
3481
+ Whether to return a copy or update `adata`.
3482
+
3483
+ Returns
3484
+ -------
3485
+ Updates `adata` inplace or returns an updated copy
3486
+ """
3487
+
3488
+ if copy:
3489
+ adata = adata.copy()
3490
+
3491
+ if convert_all:
3492
+ anndata_to_CPU(adata)
3493
+ if adata.layers:
3494
+ for key in adata.layers.keys():
3495
+ anndata_to_CPU(adata, layer=key)
3496
+ else:
3497
+ X = _get_obs_rep(adata, layer=layer)
3498
+ if isspmatrix_csr_gpu(X):
3499
+ X = X.get()
3500
+ elif isspmatrix_csc_gpu(X):
3501
+ X = X.get()
3502
+ elif isinstance(X, cp.ndarray):
3503
+ X = X.get()
3504
+ else:
3505
+ pass
3506
+
3507
+ _set_obs_rep(adata, X, layer=layer)
3508
+
3509
+ if copy:
3510
+ return adata
3511
+
3512
+
3513
+ def install_stellar(CUDA=12):
3514
+ if CUDA == 12:
3515
+ subprocess.run(["pip3", "install", "torch"], check=True)
3516
+ subprocess.run(["pip", "install", "torch_geometric"], check=True)
3517
+ subprocess.run(
3518
+ [
3519
+ "pip",
3520
+ "install",
3521
+ "pyg_lib",
3522
+ "torch_scatter",
3523
+ "torch_sparse",
3524
+ "torch_cluster",
3525
+ "torch_spline_conv",
3526
+ "-f",
3527
+ "https://data.pyg.org/whl/torch-2.3.0+cu121.html",
3528
+ ],
3529
+ check=True,
3530
+ )
3531
+ elif CUDA == 11.8:
3532
+ subprocess.run(
3533
+ [
3534
+ "pip3",
3535
+ "install",
3536
+ "torch",
3537
+ "--index-url",
3538
+ "https://download.pytorch.org/whl/cu118",
3539
+ ],
3540
+ check=True,
3541
+ )
3542
+ subprocess.run(["pip", "install", "torch_geometric"], check=True)
3543
+ subprocess.run(
3544
+ [
3545
+ "pip",
3546
+ "install",
3547
+ "pyg_lib",
3548
+ "torch_scatter",
3549
+ "torch_sparse",
3550
+ "torch_cluster",
3551
+ "torch_spline_conv",
3552
+ "-f",
3553
+ "https://data.pyg.org/whl/torch-2.3.0+cu118.html",
3554
+ ],
3555
+ check=True,
3556
+ )
3557
+ else:
3558
+ print("Please choose between CUDA 12 or 11.8")
3559
+ print(
3560
+ "If neither is working for you check the installation guide at: https://pytorch.org/get-started/locally/ and https://pytorch-geometric.readthedocs.io/en/latest/install/installation.html"
3561
+ )