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,1076 @@
1
+ # load required packages
2
+ import os
3
+ import random
4
+ import time
5
+ import warnings
6
+ from functools import reduce
7
+ from typing import TYPE_CHECKING
8
+
9
+ import matplotlib.colors as mcolors
10
+ import matplotlib.pyplot as plt
11
+ import numpy as np
12
+ import pandas as pd
13
+ import scanpy as sc
14
+ import scipy as sp
15
+ import seaborn as sns
16
+ import tensorflow as tf
17
+ import tifffile as tiff
18
+ from cellpose.core import use_gpu
19
+ from scipy.spatial.distance import cdist
20
+ from scipy.stats import pearsonr
21
+ from sklearn.cross_decomposition import CCA
22
+ from sklearn.neighbors import NearestNeighbors
23
+ from tqdm import tqdm
24
+
25
+ # sns.set_style("ticks")
26
+
27
+ # helper functions
28
+ ############################################################
29
+
30
+
31
+ def hf_generate_random_colors(n, rand_seed=0):
32
+ # from random import randint
33
+ random.seed(rand_seed)
34
+ color = []
35
+ for i in range(n):
36
+ color.append("#%06X" % random.randint(0, 0xFFFFFF))
37
+ return color
38
+
39
+
40
+ #########
41
+
42
+
43
+ def hf_assign_colors(names, colors):
44
+ # Printing original keys-value lists
45
+ print("Original key list is : " + str(names))
46
+ print("Original value list is : " + str(colors))
47
+
48
+ # using naive method
49
+ # to convert lists to dictionary
50
+ res = {}
51
+ for key in names:
52
+ for value in colors:
53
+ res[key] = value
54
+ colors.remove(value)
55
+ break
56
+
57
+ # Printing resultant dictionary
58
+ print("Resultant dictionary is : " + str(res))
59
+
60
+ l = list(res.keys())
61
+
62
+ SMALL_SIZE = 14
63
+ MEDIUM_SIZE = 16
64
+ BIGGER_SIZE = 18
65
+
66
+ # Settings for graph
67
+ plt.rc("font", size=SMALL_SIZE) # controls default text sizes
68
+ plt.rc("axes", titlesize=SMALL_SIZE) # fontsize of the axes title
69
+ plt.rc("axes", labelsize=MEDIUM_SIZE) # fontsize of the x and y labels
70
+ plt.rc("xtick", labelsize=SMALL_SIZE) # fontsize of the tick labels
71
+ plt.rc("ytick", labelsize=SMALL_SIZE) # fontsize of the tick labels
72
+ plt.rc("legend", fontsize=SMALL_SIZE) # legend fontsize
73
+ plt.rc("figure", titlesize=BIGGER_SIZE) # fontsize of the figure title
74
+
75
+ sns.palplot(res.values())
76
+ plt.xticks(range(len(res)), res.keys(), rotation=30, ha="right")
77
+ # plt.savefig(save_path+'color_legend.png', dpi=300)
78
+
79
+ return res
80
+
81
+
82
+ #########
83
+
84
+
85
+ def hf_per_only(data, grouping, replicate, sub_col, sub_list, per_cat, norm=True):
86
+ # Find Percentage of cell type
87
+ if norm == True:
88
+ test1 = data.loc[
89
+ data[sub_col].isin(sub_list)
90
+ ] # filters df for values by values in sub_list which are in the sub_col column
91
+ immune_list = list(
92
+ test1[per_cat].unique()
93
+ ) # stores unique values for the per_cat column
94
+ else:
95
+ test1 = data.copy()
96
+ immune_list = list(data.loc[data[sub_col].isin(sub_list)][per_cat].unique())
97
+
98
+ test1[per_cat] = test1[per_cat].astype("category")
99
+ test_freq = test1.groupby([grouping, replicate]).apply(
100
+ lambda x: x[per_cat].value_counts(normalize=True, sort=False) * 100
101
+ ) # group data by grouping variable and replicates, than applies the lambda function to count the frequency of each category in the per_cat column and normalizes by dividing by the total count.
102
+ test_freq.columns = test_freq.columns.astype(str)
103
+ test_freq.reset_index(inplace=True)
104
+ immune_list.extend(
105
+ [grouping, replicate]
106
+ ) # adds grouping and replicate column to immune_list
107
+ test_freq1 = test_freq[immune_list] # subsets test_freq by immune_list
108
+
109
+ melt_per_plot = pd.melt(
110
+ test_freq1, id_vars=[grouping, replicate]
111
+ ) # ,value_vars=immune_list) #converts columns specified in id_vars into rows
112
+ melt_per_plot.rename(
113
+ columns={"value": "percentage"}, inplace=True
114
+ ) # rename value to percentage
115
+
116
+ return melt_per_plot # returns a df which contains the group_column followed by the replicate column and the per category column, and a column specifying the percentage
117
+ # Example: percentage CD4+ TCs in unique region E08 assigned to community xxx
118
+
119
+
120
+ ########
121
+
122
+
123
+ def hf_normalize(X):
124
+ arr = np.array(X.fillna(0).values)
125
+ return pd.DataFrame(
126
+ np.log2(1e-3 + arr / arr.sum(axis=1, keepdims=True)),
127
+ index=X.index.values,
128
+ columns=X.columns,
129
+ ).fillna(0)
130
+
131
+
132
+ ########
133
+
134
+
135
+ def hf_cell_types_de_helper(
136
+ df,
137
+ ID_component1,
138
+ ID_component2,
139
+ neighborhood_col,
140
+ group_col,
141
+ group_dict,
142
+ cell_type_col,
143
+ ):
144
+ # read data
145
+ cells2 = df
146
+ cells2.reset_index(inplace=True, drop=True)
147
+ cells2
148
+
149
+ # generate unique ID
150
+ cells2["donor_tis"] = cells2[ID_component1] + "_" + cells2[ID_component2]
151
+
152
+ # This code is creating a dictionary called neigh_num that maps each unique value
153
+ # in the Neighborhood column of a pandas DataFrame cells2 to a unique integer index
154
+ # starting from 0.
155
+ neigh_num = {
156
+ list(cells2[neighborhood_col].unique())[i]: i
157
+ for i in range(len(cells2[neighborhood_col].unique()))
158
+ }
159
+ cells2["neigh_num"] = cells2[neighborhood_col].map(neigh_num)
160
+ cells2["neigh_num"].unique()
161
+
162
+ """
163
+ This Python code is performing the following data transformation operations on a pandas DataFrame named cells2:
164
+ The first three lines of code create a dictionary called treatment_dict that maps two specific strings, 'SB' and 'CL', to the integers 0 and 1, respectively. Then, the map() method is used to create a new column called group, where each value in the tissue column is replaced with its corresponding integer value from the treatment_dict dictionary.
165
+ The fourth to seventh lines of code create a new dictionary called pat_dict that maps each unique value in the donor_tis column of the cells2 DataFrame to a unique integer index starting from 0. The for loop loops through the range object and assigns each integer to the corresponding unique value in the donor_tis column, creating a dictionary that maps each unique value to a unique integer index.
166
+ The last two lines of code create a new column called patients in the cells2 DataFrame, where each value in the donor_tis column is replaced with its corresponding integer index from the pat_dict dictionary. This code assigns these integer indices to each patient in the donor_tis column. The unique() method is used to return an array of unique values in the patients column to verify that each unique value in the donor_tis column has been mapped to a unique integer index in the patients column.
167
+ Overall, the code is converting categorical data in the tissue and donor_tis columns to numerical data in the group and patients columns, respectively, which could be useful for certain types of analysis.
168
+ """
169
+ # Code treatment/group with number
170
+ cells2["group"] = cells2[group_col].map(group_dict)
171
+ cells2["group"].unique()
172
+
173
+ pat_dict = {}
174
+ for i in range(len(list(cells2["donor_tis"].unique()))):
175
+ pat_dict[list(cells2["donor_tis"].unique())[i]] = i
176
+ pat_dict
177
+
178
+ cells2["patients"] = cells2["donor_tis"].map(pat_dict)
179
+ cells2["patients"].unique()
180
+
181
+ # drop duplicates
182
+ pat_gp = cells2[["patients", "group"]].drop_duplicates()
183
+ pat_to_gp = {a: b for a, b in pat_gp.values}
184
+
185
+ # get cell type (ct) frequences per patient
186
+ ct_freq1 = cells2.groupby(["patients"]).apply(
187
+ lambda x: x[cell_type_col].value_counts(normalize=True, sort=False) * 100
188
+ )
189
+ # ct_freq = ct_freq1.to_frame()
190
+ ct_freq = ct_freq1.unstack().fillna(0)
191
+ ct_freq.reset_index(inplace=True)
192
+ ct_freq.rename(
193
+ columns={"level_1": "cell_type", "Cell Type": "Percentage"}, inplace=True
194
+ )
195
+ ct_freq
196
+
197
+ # Get frequences for every neighborhood per patient
198
+ all_freqs1 = cells2.groupby(["patients", "neigh_num"]).apply(
199
+ lambda x: x[cell_type_col].value_counts(normalize=True, sort=False) * 100
200
+ )
201
+ # all_freqs = all_freqs1.to_frame()
202
+ all_freqs = all_freqs1.unstack().fillna(0)
203
+ all_freqs.reset_index(inplace=True)
204
+ all_freqs.rename(
205
+ columns={"level_2": "cell_type", cell_type_col: "Percentage"}, inplace=True
206
+ )
207
+ all_freqs
208
+
209
+ return (cells2, ct_freq, all_freqs, pat_to_gp, neigh_num)
210
+
211
+
212
+ ##########
213
+
214
+
215
+ def hf_get_pathcells(query_database, query_dict_list):
216
+ """
217
+ Return set of cells that match query_dict path.
218
+ """
219
+ out = []
220
+
221
+ if type(query_dict_list) == dict:
222
+ query_dict_list = [query_dict_list]
223
+
224
+ for query_dict in query_dict_list:
225
+ qd = query_database
226
+ for k, v in query_dict.items():
227
+ if type(v) != list:
228
+ v = [v]
229
+ qd = qd[qd[k].isin(v)]
230
+ out += [qd]
231
+ if len(query_database) == 1:
232
+ return out[0]
233
+ return out
234
+
235
+
236
+ # annotated
237
+ """
238
+ def hf_get_pathcells(query_database: Union[Dict, List[Dict]], query_dict_list: List[Dict]) -> Union[Dict, List[Dict]]:
239
+
240
+ #Return set of cells that match query_dict path.
241
+
242
+ out: List[Dict] = [] # initialize an empty list to store results
243
+
244
+ if type(query_dict_list) == dict: # if query_dict_list is a dictionary, convert it into a list
245
+ query_dict_list = [query_dict_list]
246
+
247
+ for query_dict in query_dict_list: # loop through each dictionary in query_dict_list
248
+ qd = query_database # initialize a reference to query_database
249
+ for k,v in query_dict.items(): # loop through each key-value pair in the current dictionary
250
+ if type(v)!=list: # if the value is not a list, convert it into a list
251
+ v = [v]
252
+ qd = qd[qd[k].isin(v)] # filter the rows of qd based on the key-value pair
253
+ out+=[qd] # append the resulting qd to the out list
254
+
255
+ if len(query_database)==1: # if query_database contains only one row, return the first item in out
256
+ return out[0]
257
+ return out # otherwise, return the entire out list
258
+ """
259
+
260
+
261
+ class Neighborhoods(object):
262
+ def __init__(
263
+ self,
264
+ cells,
265
+ ks,
266
+ cluster_col,
267
+ sum_cols,
268
+ keep_cols,
269
+ X="X:X",
270
+ Y="Y:Y",
271
+ reg="Exp",
272
+ add_dummies=True,
273
+ ):
274
+ self.cells_nodumz = cells
275
+ self.X = X
276
+ self.Y = Y
277
+ self.reg = reg
278
+ self.keep_cols = keep_cols
279
+ self.sum_cols = sum_cols
280
+ self.ks = ks
281
+ self.cluster_col = cluster_col
282
+ self.n_neighbors = max(ks)
283
+ self.exps = list(self.cells_nodumz[self.reg].unique())
284
+ self.bool_add_dummies = add_dummies
285
+
286
+ def add_dummies(self):
287
+ c = self.cells_nodumz
288
+ dumz = pd.get_dummies(c[self.cluster_col])
289
+ keep = c[self.keep_cols]
290
+
291
+ self.cells = pd.concat([keep, dumz], axis=1)
292
+
293
+ def get_tissue_chunks(self):
294
+ self.tissue_group = self.cells[[self.X, self.Y, self.reg]].groupby(self.reg)
295
+
296
+ tissue_chunks = [
297
+ (time.time(), self.exps.index(t), t, a)
298
+ for t, indices in self.tissue_group.groups.items()
299
+ for a in np.array_split(indices, 1)
300
+ ]
301
+ return tissue_chunks
302
+
303
+ def make_windows(self, job):
304
+ start_time, idx, tissue_name, indices = job
305
+ job_start = time.time()
306
+
307
+ print(
308
+ "Starting:", str(idx + 1) + "/" + str(len(self.exps)), ": " + self.exps[idx]
309
+ )
310
+
311
+ tissue = self.tissue_group.get_group(tissue_name)
312
+ to_fit = tissue.loc[indices][[self.X, self.Y]].values
313
+
314
+ fit = NearestNeighbors(n_neighbors=self.n_neighbors + 1).fit(
315
+ tissue[[self.X, self.Y]].values
316
+ )
317
+ m = fit.kneighbors(to_fit)
318
+ m = m[0][:, 1:], m[1][:, 1:]
319
+
320
+ # sort_neighbors
321
+ args = m[0].argsort(axis=1)
322
+ add = np.arange(m[1].shape[0]) * m[1].shape[1]
323
+ sorted_indices = m[1].flatten()[args + add[:, None]]
324
+
325
+ neighbors = tissue.index.values[sorted_indices]
326
+
327
+ end_time = time.time()
328
+
329
+ print(
330
+ "Finishing:",
331
+ str(idx + 1) + "/" + str(len(self.exps)),
332
+ ": " + self.exps[idx],
333
+ end_time - job_start,
334
+ end_time - start_time,
335
+ )
336
+ return neighbors.astype(np.int32)
337
+
338
+ def k_windows(self):
339
+ if self.bool_add_dummies:
340
+ self.add_dummies()
341
+ else:
342
+ self.cells = self.cells_nodumz
343
+ sum_cols = list(self.sum_cols)
344
+ for col in sum_cols:
345
+ if col in self.keep_cols:
346
+ self.cells[col + "_sum"] = self.cells[col]
347
+ self.sum_cols.remove(col)
348
+ self.sum_cols += [col + "_sum"]
349
+
350
+ values = self.cells[self.sum_cols].values
351
+ tissue_chunks = self.get_tissue_chunks()
352
+ tissues = [self.make_windows(job) for job in tissue_chunks]
353
+
354
+ out_dict = {}
355
+ for k in self.ks:
356
+ for neighbors, job in zip(tissues, tissue_chunks):
357
+ chunk = np.arange(len(neighbors)) # indices
358
+ tissue_name = job[2]
359
+ indices = job[3]
360
+ window = (
361
+ values[neighbors[chunk, :k].flatten()]
362
+ .reshape(len(chunk), k, len(self.sum_cols))
363
+ .sum(axis=1)
364
+ )
365
+ out_dict[(tissue_name, k)] = (window.astype(np.float16), indices)
366
+
367
+ windows = {}
368
+ for k in self.ks:
369
+ window = pd.concat(
370
+ [
371
+ pd.DataFrame(
372
+ out_dict[(exp, k)][0],
373
+ index=out_dict[(exp, k)][1].astype(int),
374
+ columns=self.sum_cols,
375
+ )
376
+ for exp in self.exps
377
+ ],
378
+ axis=0,
379
+ )
380
+ window = window.loc[self.cells.index.values]
381
+ window = pd.concat([self.cells[self.keep_cols], window], axis=1)
382
+ windows[k] = window
383
+ return windows
384
+
385
+
386
+ ##########
387
+
388
+
389
+ # Define a Python function named `hf_get_windows` that takes two arguments: `job` and `n_neighbors`.
390
+ def hf_get_windows(job, n_neighbors, exps, tissue_group, X, Y):
391
+ # Unpack the tuple `job` into four variables: `start_time`, `idx`, `tissue_name`, and `indices`.
392
+ start_time, idx, tissue_name, indices = job
393
+
394
+ # Record the time at which the function starts.
395
+ job_start = time.time()
396
+
397
+ # Print a message indicating the start of the function execution, including the current job index and the corresponding experiment name.
398
+ print("Starting:", str(idx + 1) + "/" + str(len(exps)), ": " + exps[idx])
399
+
400
+ # Retrieve the subset of data that corresponds to the given `tissue_name`.
401
+ tissue = tissue_group.get_group(tissue_name)
402
+
403
+ # Select only the `X` and `Y` columns of the data corresponding to the given `indices`.
404
+ to_fit = tissue.loc[indices][[X, Y]].values
405
+
406
+ # Fit a model with the data that corresponds to the `X` and `Y` columns of the given `tissue`.
407
+ fit = NearestNeighbors(n_neighbors=n_neighbors).fit(tissue[[X, Y]].values)
408
+
409
+ # Find the indices of the `n_neighbors` nearest neighbors of the `to_fit` data points.
410
+ # The `m` variable contains the distances and indices of these neighbors.
411
+ m = fit.kneighbors(to_fit)
412
+
413
+ # Sort the `m[1]` array along each row, and store the resulting indices in the `args` variable.
414
+ args = m[0].argsort(axis=1)
415
+
416
+ # Create the `add` variable to offset the indices based on the number of rows in `m[1]`, and store the sorted indices in the `sorted_indices` variable.
417
+ add = np.arange(m[1].shape[0]) * m[1].shape[1]
418
+ sorted_indices = m[1].flatten()[args + add[:, None]]
419
+
420
+ # Create the `neighbors` variable by selecting the indices from the `tissue` data frame that correspond to the sorted indices.
421
+ neighbors = tissue.index.values[sorted_indices]
422
+
423
+ # Record the time at which the function ends.
424
+ end_time = time.time()
425
+
426
+ # Print a message indicating the end of the function execution, including the current job index and the corresponding experiment name, and the time it took to execute the function.
427
+ print(
428
+ "Finishing:",
429
+ str(idx + 1) + "/" + str(len(exps)),
430
+ ": " + exps[idx],
431
+ end_time - job_start,
432
+ end_time - start_time,
433
+ )
434
+
435
+ # Return the `neighbors` array as an array of 32-bit integers.
436
+ return neighbors.astype(np.int32)
437
+
438
+
439
+ ###################
440
+
441
+
442
+ def hf_index_rank(a, axis):
443
+ """
444
+ returns the index of every index in the sorted array
445
+ haven't tested on ndarray yet
446
+ """
447
+ arg = np.argsort(a, axis)
448
+
449
+ return np.arange(a.shape[axis])[np.argsort(arg, axis)]
450
+
451
+
452
+ def hf_znormalize(raw_cells, grouper, markers, clip=(-7, 7), dropinf=True):
453
+ not_inf = raw_cells[np.isinf(raw_cells[markers].values).sum(axis=1) == 0]
454
+ if not_inf.shape[0] != raw_cells.shape[0]:
455
+ print("removing cells with inf values", raw_cells.shape, not_inf.shape)
456
+ not_na = not_inf[not_inf[markers].isnull().sum(axis=1) == 0]
457
+ if not_na.shape[0] != not_inf.shape[0]:
458
+ print("removing cells with nan values", not_inf.shape, not_na.shape)
459
+
460
+ znorm = not_na.groupby(grouper).apply(
461
+ lambda x: (
462
+ (x[markers] - x[markers].mean(axis=0)) / x[markers].std(axis=0)
463
+ ).clip(clip[0], clip[1])
464
+ )
465
+ Z = not_na.drop(markers, 1).merge(znorm, left_index=True, right_index=True)
466
+ return Z
467
+
468
+
469
+ def hf_fast_divisive_cluster(X, num_clusters, metric="cosine", prints=True):
470
+ # optimized divisive_cluster. Faster because doesn't recompute distance matrix to centroids at
471
+ # each iteration
472
+ centroids = np.zeros((num_clusters, X.shape[1])) # fill with cluster centroids
473
+ dists = np.zeros((X.shape[0], num_clusters)) # fill with dist matrix
474
+
475
+ avg_seed = X.mean(axis=0, keepdims=True)
476
+ d = cdist(X, avg_seed, metric=metric)
477
+ dists[:, 0] = d[:, 0]
478
+ c1 = d.argmax()
479
+ centroids[0] = X[c1]
480
+
481
+ for x in range(1, num_clusters):
482
+ if x % 10 == 0:
483
+ print(x, "clusters")
484
+ d = cdist(X, centroids[x - 1][None, :], metric=metric)
485
+ dists[:, x] = d[:, 0]
486
+ allocs = dists[:, : x + 1].argmin(axis=1)
487
+ next_centroid = dists[np.arange(len(dists)), allocs].argmax()
488
+ centroids[x] = X[next_centroid]
489
+ return centroids, allocs
490
+
491
+
492
+ def hf_alloc_cells(X, centroids, metric="cosine"):
493
+ dists = cdist(X, centroids, metric=metric)
494
+ allocs = dists.argmin(axis=1)
495
+ return allocs
496
+
497
+
498
+ ###########
499
+
500
+
501
+ def hf_get_sum_cols(cell_cuts, panel):
502
+ arr = np.where(cell_cuts[:, 0] == panel)[0]
503
+ return slice(arr[0], arr[-1] + 1)
504
+
505
+
506
+ ###############
507
+ def hf_get_thresh_simps(x, thresh):
508
+ sorts = np.argsort(-x, axis=1)
509
+ x_sorted = -np.sort(-x, axis=1)
510
+ cumsums = np.cumsum(x_sorted, axis=1)
511
+ thresh_simps = pd.Series(
512
+ [
513
+ tuple(sorted(sorts[i, : (1 + j)]))
514
+ for i, j in enumerate(np.argmax(cumsums > thresh, axis=1))
515
+ ]
516
+ )
517
+ return thresh_simps
518
+
519
+
520
+ ###############
521
+ def hf_prepare_neighborhood_df(
522
+ cells_df, patient_ID_component1, patient_ID_component2, neighborhood_column=None
523
+ ):
524
+ # Spacer for output
525
+ print("")
526
+
527
+ # Combine two columns to form unique ID which will be stored as patients column
528
+ cells_df["patients"] = (
529
+ cells_df[patient_ID_component1] + "_" + cells_df[patient_ID_component2]
530
+ )
531
+ print("You assigned following identifiers to the column 'patients':")
532
+ print(cells_df["patients"].unique())
533
+
534
+ # Spacer for output
535
+ print("")
536
+
537
+ if neighborhood_column:
538
+ # Assign numbers to neighborhoods
539
+ neigh_num = {
540
+ list(cells_df[neighborhood_column].unique())[i]: i
541
+ for i in range(len(cells_df[neighborhood_column].unique()))
542
+ }
543
+ cells_df["neigh_num"] = cells_df[neighborhood_column].map(neigh_num)
544
+ print(
545
+ "You assigned following numbers to the column 'neigh_num'. Each number represents one neighborhood:"
546
+ )
547
+ print(cells_df["neigh_num"].unique())
548
+ cells_df["neigh_num"] = cells_df["neigh_num"].astype("category")
549
+
550
+ cells_df["patients"] = cells_df["patients"].astype("category")
551
+
552
+ return cells_df
553
+
554
+
555
+ def hf_prepare_neighborhood_df2(
556
+ cells_df, patient_ID_component1, patient_ID_component2, neighborhood_column=None
557
+ ):
558
+ # Spacer for output
559
+ print("")
560
+
561
+ # Combine two columns to form unique ID which will be stored as patients column
562
+ cells_df["unique_ID"] = (
563
+ cells_df[patient_ID_component1] + "_" + cells_df[patient_ID_component2]
564
+ )
565
+ print("You assigned following identifiers to the column 'unique_ID':")
566
+ print(cells_df["unique_ID"].unique())
567
+
568
+ # Spacer for output
569
+ print("")
570
+
571
+ if neighborhood_column:
572
+ # Assign numbers to neighborhoods
573
+ neigh_num = {
574
+ list(cells_df[neighborhood_column].unique())[i]: i
575
+ for i in range(len(cells_df[neighborhood_column].unique()))
576
+ }
577
+ cells_df["neigh_num"] = cells_df[neighborhood_column].map(neigh_num)
578
+ print(
579
+ "You assigned following numbers to the column 'neigh_num'. Each number represents one neighborhood:"
580
+ )
581
+ print(cells_df["neigh_num"].unique())
582
+ cells_df["neigh_num"] = cells_df["neigh_num"].astype("category")
583
+
584
+ cells_df["unique_ID"] = cells_df["unique_ID"].astype("category")
585
+
586
+ return cells_df
587
+
588
+
589
+ ############
590
+
591
+
592
+ def hf_cor_subset(cor_mat, threshold, cell_type):
593
+ pairs = hf_get_top_abs_correlations(cor_mat, thresh=threshold)
594
+
595
+ piar1 = pairs.loc[pairs["col1"] == cell_type]
596
+ piar2 = pairs.loc[pairs["col2"] == cell_type]
597
+ piar = pd.concat([piar1, piar2])
598
+
599
+ pair_list = list(set(list(piar["col1"].unique()) + list(piar["col2"].unique())))
600
+
601
+ return pair_list, piar, pairs
602
+
603
+
604
+ #############
605
+
606
+
607
+ # correlation analysis
608
+ def hf_get_redundant_pairs(df):
609
+ """Get diagonal and lower triangular pairs of correlation matrix"""
610
+ pairs_to_drop = set()
611
+ cols = df.columns
612
+ for i in range(0, df.shape[1]):
613
+ for j in range(0, i + 1):
614
+ pairs_to_drop.add((cols[i], cols[j]))
615
+ return pairs_to_drop
616
+
617
+
618
+ ##############
619
+
620
+ # Spatial context analysis
621
+ """
622
+ this is the code that finds the minimal combination of CNs
623
+ required to make up a threshold percentage of assignments in a window
624
+ combinations are stored as a sorted tuple
625
+ """
626
+
627
+
628
+ def hf_simp_rep(
629
+ data,
630
+ patient_col,
631
+ tissue_column,
632
+ subset_list_tissue,
633
+ ttl_per_thres,
634
+ comb_per_thres,
635
+ thres_num=3,
636
+ ):
637
+ # Choose the windows size to continue with
638
+ if tissue_column != None:
639
+ w2 = data.loc[data[tissue_column].isin(subset_list_tissue)]
640
+ print("tissue_column true")
641
+
642
+ else:
643
+ w2 = data.copy()
644
+ print("tissue_column false")
645
+
646
+ simp_list = []
647
+ for patient in list(w2[patient_col].unique()):
648
+ w = w2.loc[w2[patient_col] == patient]
649
+ xm = w.loc[:, l].values / n_num
650
+
651
+ # Get the neighborhood combinations based on the threshold
652
+ simps = hf_get_thresh_simps(xm, ttl_per_thres)
653
+ simp_freqs = simps.value_counts(normalize=True)
654
+ sf = simp_freqs.to_frame()
655
+ sf.rename(columns={0: patient}, inplace=True)
656
+ sf.reset_index(inplace=True)
657
+ sf.rename(columns={"index": "merge"}, inplace=True)
658
+ simp_list.append(sf)
659
+ # simp_sums = np.cumsum(simp_freqs)
660
+
661
+ # thresh_cumulative = .95
662
+ # selected_simps = simp_sums[simp_sums<=thresh_cumulative].index.values
663
+ # selected_simps = simp_freqs[simp_freqs>=comb_per_thres].index.values
664
+
665
+ simp_df = reduce(
666
+ lambda left, right: pd.merge(left, right, on=["merge"], how="outer"), simp_list
667
+ )
668
+ # simp_df = pd.concat(simp_list, axis=0)
669
+ # simp_df.index = simp_df.index.to_series()
670
+ simp_df.fillna(0, inplace=True)
671
+ simp_df.set_index("merge", inplace=True)
672
+ simp_out = simp_df.loc[simp_df.gt(0).sum(axis=1).ge(thres_num)]
673
+
674
+ return simp_out
675
+
676
+
677
+ ################
678
+
679
+
680
+ def hf_get_top_abs_correlations(df, thresh=0.5):
681
+ au_corr = df.corr().unstack()
682
+ labels_to_drop = hf_get_redundant_pairs(df)
683
+ au_corr = au_corr.drop(labels=labels_to_drop).sort_values(ascending=False)
684
+ cc = au_corr.to_frame()
685
+ cc.index.rename(["col1", "col2"], inplace=True)
686
+ cc.reset_index(inplace=True)
687
+ cc.rename(columns={0: "value"}, inplace=True)
688
+ gt_pair = cc.loc[cc["value"].abs().gt(thresh)]
689
+ return gt_pair
690
+
691
+
692
+ ################
693
+ # help to convert dataframe after denoising into anndata
694
+ def make_anndata(
695
+ df_nn, # data frame coming out from denoising
696
+ col_sum, # this is the column index that has the last protein feature
697
+ nonFuncAb_list, # inspect which markers work, and drop the ones that did not work from the clustering step
698
+ ):
699
+ """
700
+ Convert a denoised DataFrame into anndata format.
701
+
702
+ Parameters:
703
+ df_nn (pandas.DataFrame): Denoised data frame.
704
+ col_sum (int): Column index of the last protein feature.
705
+ nonFuncAb_list (list): List of markers that did not work in the clustering step.
706
+
707
+ Returns:
708
+ AnnData: Anndata object containing the converted data.
709
+ """
710
+ adata = sc.AnnData(X=df_nn.iloc[:, : col_sum + 1].drop(columns=nonFuncAb_list))
711
+ adata.obs = df_nn.iloc[:, col_sum + 1 :]
712
+ return adata
713
+
714
+
715
+ ################
716
+ def hf_split_channels(input_path, output_folder, channel_names_file=None):
717
+ """
718
+ Split channels of a TIFF image and save them as separate files.
719
+
720
+ Parameters:
721
+ input_path (str): Path to the input TIFF image.
722
+ output_folder (str): Path to the output folder where the channels will be saved.
723
+ channel_names_file (str, optional): Path to the file containing channel names.
724
+ If None, numbers will be used as channel names.
725
+
726
+ Raises:
727
+ FileNotFoundError: If the input_path or channel_names_file (if provided) is not found.
728
+
729
+ Returns:
730
+ None
731
+ """
732
+ # Load the large TIFF image
733
+ print("loading image file...")
734
+ image = tiff.imread(input_path)
735
+ print("Done")
736
+
737
+ print("splitting channels...")
738
+ if channel_names_file is not None:
739
+ # Read the channel names from the text file
740
+ with open(channel_names_file, "r") as f:
741
+ channel_names = f.read().splitlines()
742
+ else:
743
+ # Generate channel names as numbers
744
+ channel_names = [str(i) for i in range(image.shape[0])]
745
+ print("Done")
746
+
747
+ # Split the channels
748
+ channels = np.split(image, image.shape[0], axis=0)
749
+
750
+ # Save each channel as a TIFF file with the corresponding channel name
751
+ for i, channel in tqdm(
752
+ enumerate(channels), total=len(channels), desc="Saving channels"
753
+ ):
754
+ channel = np.squeeze(channel) # Remove single-dimensional entries
755
+
756
+ output_filename = f"{output_folder}/{channel_names[i]}.tif"
757
+ tiff.imsave(output_filename, channel)
758
+
759
+ print("Channels saved successfully!")
760
+
761
+
762
+ ##############
763
+ # Patch analysis
764
+
765
+
766
+ def hf_voronoi_finite_polygons_2d(vor, radius=None):
767
+ """
768
+ Reconstruct infinite voronoi regions in a 2D diagram to finite
769
+ regions.
770
+
771
+ Parameters
772
+ ----------
773
+ vor : Voronoi
774
+ Input diagram
775
+ radius : float, optional
776
+ Distance to 'points at infinity'.
777
+
778
+ Returns
779
+ -------
780
+ regions : list of tuples
781
+ Indices of vertices in each revised Voronoi regions.
782
+ vertices : list of tuples
783
+ Coordinates for revised Voronoi vertices. Same as coordinates
784
+ of input vertices, with 'points at infinity' appended to the
785
+ end.
786
+
787
+ """
788
+
789
+ if vor.points.shape[1] != 2:
790
+ raise ValueError("Requires 2D input")
791
+
792
+ new_regions = []
793
+ new_vertices = vor.vertices.tolist()
794
+
795
+ center = vor.points.mean(axis=0)
796
+ if radius is None:
797
+ radius = vor.points.ptp().max()
798
+
799
+ # Construct a map containing all ridges for a given point
800
+ all_ridges = {}
801
+ for (p1, p2), (v1, v2) in zip(vor.ridge_points, vor.ridge_vertices):
802
+ all_ridges.setdefault(p1, []).append((p2, v1, v2))
803
+ all_ridges.setdefault(p2, []).append((p1, v1, v2))
804
+
805
+ # Reconstruct infinite regions
806
+ for p1, region in enumerate(vor.point_region):
807
+ vertices = vor.regions[region]
808
+
809
+ if all(v >= 0 for v in vertices):
810
+ # finite region
811
+ new_regions.append(vertices)
812
+ continue
813
+
814
+ # reconstruct a non-finite region
815
+ ridges = all_ridges[p1]
816
+ new_region = [v for v in vertices if v >= 0]
817
+
818
+ for p2, v1, v2 in ridges:
819
+ if v2 < 0:
820
+ v1, v2 = v2, v1
821
+ if v1 >= 0:
822
+ # finite ridge: already in the region
823
+ continue
824
+
825
+ # Compute the missing endpoint of an infinite ridge
826
+ t = vor.points[p2] - vor.points[p1] # tangent
827
+ t /= np.linalg.norm(t)
828
+ n = np.array([-t[1], t[0]]) # normal
829
+
830
+ midpoint = vor.points[[p1, p2]].mean(axis=0)
831
+ direction = np.sign(np.dot(midpoint - center, n)) * n
832
+ far_point = vor.vertices[v2] + direction * radius * 10
833
+
834
+ new_region.append(len(new_vertices))
835
+ new_vertices.append(far_point.tolist())
836
+
837
+ # sort region counterclockwise
838
+ vs = np.asarray([new_vertices[v] for v in new_region])
839
+ c = vs.mean(axis=0)
840
+ angles = np.arctan2(vs[:, 1] - c[1], vs[:, 0] - c[0])
841
+ new_region = np.array(new_region)[np.argsort(angles)]
842
+
843
+ # finish
844
+ new_regions.append(new_region.tolist())
845
+
846
+ return new_regions, np.asarray(new_vertices)
847
+
848
+
849
+ ###
850
+
851
+
852
+ def hf_list_folders(directory):
853
+ """
854
+ Retrieve a list of folders in a given directory.
855
+
856
+ Parameters:
857
+ directory (str): Path to the directory.
858
+
859
+ Returns:
860
+ list: List of folder names within the specified directory.
861
+ """
862
+ folders = []
863
+ for item in os.listdir(directory):
864
+ item_path = os.path.join(directory, item)
865
+ if os.path.isdir(item_path):
866
+ folders.append(item)
867
+ return folders
868
+
869
+
870
+ ###
871
+
872
+
873
+ def hf_process_dataframe(df):
874
+ """
875
+ Extract information from a pandas DataFrame containing file paths and IDs.
876
+
877
+ Parameters:
878
+ df (pandas.DataFrame): The input DataFrame containing file paths and IDs.
879
+
880
+ Returns:
881
+ tuple: A tuple containing the voronoi_path, mask_path, and region for the first row.
882
+ """
883
+ for index, row in df.iterrows():
884
+ voronoi_path = row["voronoi_path"]
885
+ mask_path = row["mask_path"]
886
+ region = row["region_long"]
887
+ # Process the voronoi_path and mask_path variables as needed
888
+ # Here, we are printing them for demonstration purposes
889
+ print(f"Voronoi Path: {voronoi_path}")
890
+ print(f"Mask Path: {mask_path}")
891
+
892
+ return voronoi_path, mask_path, region
893
+
894
+
895
+ ###
896
+
897
+
898
+ def hf_get_png_files(directory):
899
+ """
900
+ Get a list of PNG files in a given directory.
901
+
902
+ Parameters:
903
+ directory (str): Path to the directory.
904
+
905
+ Returns:
906
+ list: List of PNG file paths within the specified directory.
907
+ """
908
+ png_files = []
909
+ for filename in os.listdir(directory):
910
+ if filename.endswith(".png"):
911
+ png_files.append(os.path.join(directory, filename))
912
+ return png_files
913
+
914
+
915
+ ###
916
+
917
+
918
+ def hf_find_tiff_file(directory, prefix):
919
+ """
920
+ Find a TIFF file in a given directory with a specified prefix.
921
+
922
+ Parameters:
923
+ directory (str): Path to the directory.
924
+ prefix (str): Prefix of the TIFF file name.
925
+
926
+ Returns:
927
+ str or None: Path to the found TIFF file, or None if no matching file is found.
928
+ """
929
+ for filename in os.listdir(directory):
930
+ if filename.endswith(".tif") and filename.startswith(prefix):
931
+ return os.path.join(directory, filename)
932
+ return None
933
+
934
+
935
+ ###
936
+
937
+
938
+ def hf_extract_filename(filepath):
939
+ """
940
+ Extract the filename from a given filepath.
941
+
942
+ Parameters:
943
+ filepath (str): The input filepath.
944
+
945
+ Returns:
946
+ str: The extracted filename without the extension.
947
+ """
948
+ filename = os.path.basename(filepath) # Extracts the last element of the path
949
+ filename = filename.replace(
950
+ "_plot.png_cut.png", ""
951
+ ) # Removes the ".png_cut.png" extension
952
+ return filename
953
+
954
+
955
+ ###
956
+
957
+
958
+ def hf_get_tif_filepaths(directory):
959
+ """
960
+ Recursively searches the specified directory and its subdirectories for TIFF files (.tif) and returns a list of their file paths.
961
+
962
+ Args:
963
+ directory (str): The directory path to search for TIFF files.
964
+
965
+ Returns:
966
+ list: A list of file paths for all TIFF files found in the directory and its subdirectories.
967
+ """
968
+ tif_filepaths = []
969
+ for root, dirs, files in os.walk(directory):
970
+ for file in files:
971
+ if file.endswith(".tif"):
972
+ tif_filepaths.append(os.path.join(root, file))
973
+ return tif_filepaths
974
+
975
+
976
+ ################ CCA
977
+ def hf_prepare_cca(df, neighborhood_column, subsets=None):
978
+ neigh_num = {
979
+ list(df[neighborhood_column].unique())[i]: i
980
+ for i in range(len(df[neighborhood_column].unique()))
981
+ }
982
+ df["neigh_num"] = df[neighborhood_column].map(neigh_num)
983
+ df["neigh_num"] = df["neigh_num"].astype("category")
984
+
985
+ cca = CCA(n_components=1, max_iter=5000)
986
+ func = pearsonr
987
+
988
+ # select which neighborhoods and functional subsets
989
+ cns = list(df["neigh_num"].unique())
990
+ # print(cns)
991
+
992
+ # log (1e-3 + neighborhood specific cell type frequency) of functional subsets ('nsctf')
993
+ if subsets is not None:
994
+ nsctf = np.log(
995
+ 1e-3
996
+ + df.groupby(["unique_region", "neigh_num"])[subsets]
997
+ .mean()
998
+ .reset_index()
999
+ .set_index(["neigh_num", "unique_region"])
1000
+ )
1001
+ # print(nsctf)
1002
+ else:
1003
+ nsctf = np.log(
1004
+ 1e-3
1005
+ + df.groupby(["unique_region", "neigh_num"])
1006
+ .mean()
1007
+ .reset_index()
1008
+ .set_index(["neigh_num", "unique_region"])
1009
+ )
1010
+ # print(nsctf)
1011
+
1012
+ cca = CCA(n_components=1, max_iter=5000)
1013
+ func = pearsonr
1014
+ nsctf = nsctf.fillna(1e-3)
1015
+
1016
+ return df, cns, nsctf, cca, func, neigh_num
1017
+
1018
+
1019
+ def invert_dictionary(dictionary):
1020
+ inverted_dict = {value: key for key, value in dictionary.items()}
1021
+ return inverted_dict
1022
+
1023
+
1024
+ def hf_replace_names(color_dict, name_dict):
1025
+ color_dict = hf_invert_dictionary(color_dict)
1026
+ for color, name in color_dict.items():
1027
+ if name in name_dict:
1028
+ color_dict[color] = name_dict[name]
1029
+ color_dict = hf_invert_dictionary(color_dict)
1030
+ return color_dict
1031
+
1032
+
1033
+ def hf_annotate_cor_plot(x, y, **kws):
1034
+ data = kws["data"]
1035
+ r, p = sp.stats.pearsonr(data[x], data[y])
1036
+ ax = plt.gca()
1037
+ ax.text(0.5, 0.8, f"r={r:.2f}, p={p:.2g}", transform=ax.transAxes, fontsize=14)
1038
+
1039
+
1040
+ def is_dark(color):
1041
+ """
1042
+ Determines if a color is dark based on its RGB values.
1043
+
1044
+ Parameters:
1045
+ color (str): The color to check. This can be any valid color string accepted by mcolors.to_rgb().
1046
+
1047
+ Returns:
1048
+ bool: True if the color is dark, False otherwise. A color is considered dark if its brightness is less than 0.5.
1049
+ """
1050
+ r, g, b = mcolors.to_rgb(color)
1051
+ brightness = (r * 299 + g * 587 + b * 114) / 1000
1052
+ return brightness < 0.5
1053
+
1054
+
1055
+ def check_for_gpu():
1056
+ """
1057
+ Check if a GPU is available for use by TensorFlow and PyTorch.
1058
+
1059
+ This function checks if a GPU is available for use by TensorFlow and PyTorch.
1060
+ It prints a message indicating whether a GPU is available for each library,
1061
+ and returns a boolean indicating whether a GPU is available for PyTorch.
1062
+
1063
+ Returns
1064
+ -------
1065
+ bool
1066
+ True if a GPU is available for PyTorch, False otherwise.
1067
+ """
1068
+ if tf.config.list_physical_devices("GPU"):
1069
+ print("GPU is available to Tensorflow")
1070
+ else:
1071
+ print("GPU is not available to Tensorflow")
1072
+
1073
+ use_GPU = use_gpu()
1074
+ yn = ["GPU is not available to Pytorch", "GPU is available to Pytorch"]
1075
+ print(f"{yn[use_GPU]}")
1076
+ return use_GPU