34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485 | def generateThumbnails (spatialTablePath,
imagePath,
markerChannelMapPath,
markers,
markerColumnName='marker',
channelColumnName='channel',
transformation=True,
maxThumbnails=2000,
random_state=0,
localNorm=True,
globalNorm=False,
x_coordinate='X_centroid',
y_coordinate='Y_centroid',
percentiles=[2, 12, 88, 98],
windowSize=64,
restrictDensity=True,
restrictDensityNumber=None,
verbose=True,
projectDir=None):
"""
Parameters:
spatialTablePath (str):
Path to the single-cell spatial feature matrix.
imagePath (str):
Path to the image file. Recognizes `.ome.tif` image file.
markerChannelMapPath (str):
Path to a `markers.csv` file that maps the channel number with the marker information.
Create a .csv file with at least two columns named 'channel' and 'marker' that
map the channel numbers to their corresponding markers. The channel number
should use 1-based indexing.
markers (list):
Markers for which `Thumbnails` need to be generated. The function looks for
these listed names in the `single-cell spatial Table`.
markerColumnName (str):
The name of the column in the `markers.csv` file that holds the marker information.
channelColumnName (str):
The name of the column in the `markers.csv` file that holds the channel information.
transformation (bool, optional):
Performs `arcsinh` transformation on the data. If the `single-cell spatial table`
is already transformed (like log transformation), set this to `False`.
maxThumbnails (int, optional):
Maximum number of Thumbnails to generate.
random_state (int, optional):
Seed used by the random number generator.
localNorm (bool, optional):
It creates a duplicate folder of the Thumbnails, with local normalization
performed on the images. Local normalization is the process of dividing
each pixel in a thumbnail by the maximum value across the entire thumbnail.
This is helpful for visual supervised sorting of the Thumbnails.
globalNorm (bool, optional):
It creates a duplicate folder of the Thumbnails, with global normalization
performed on the images. Global normalization is the process of dividing
each pixel in a thumbnail by the maximum value of the given marker across
the entire image.
x_coordinate (str, optional):
The column name in `single-cell spatial table` that records the
X coordinates for each cell.
y_coordinate (str, optional):
The column name in `single-cell spatial table` that records the
Y coordinates for each cell.
percentiles (list, optional):
Specify the interval of percentile levels of the expression utilized to intialize
the GMM. The cells falling within these percentiles are utilized to distinguish
between negative cells (first two values) and positive cells (last two values).
windowSize (int, optional):
Size of the Thumbnails.
restrictDensity (bool, optional):
This parameter is utilized to regulate the number of positive cells
observed in a given field of view. In the case of markers that do not
exhibit a distinct spatial pattern, such as immune cells, it is
recommended to train the model using sparse cells in the field of view.
restrictDensityNumber (int, optional):
This parameter is employed in conjunction with `restrictDensity`.
By default, the program attempts to automatically identify less dense
regions when restrictDensity is set to `True` using a GMM approach.
However, `restrictDensityNumber` can be utilized to exert greater
control over the process, allowing the user to limit the number of
positive cells they wish to observe within the field of view.
This parameter requires integers.
verbose (bool, optional):
If True, print detailed information about the process to the console.
projectDir (string, optional):
Path to output directory. The result will be located at
`projectDir/CSPOT/Thumbnails/`.
Returns:
Thumbnails (image):
Saves Thumbnails of auto identified postive and negative cells the
designated output directory.
Example:
```python
# set the working directory & set paths to the example data
projectDir = '/Users/aj/Documents/cspotExampleData'
imagePath = projectDir + '/image/exampleImage.tif'
spatialTablePath = projectDir + '/quantification/exampleSpatialTable.csv'
markerChannelMapPath = projectDir + '/markers.csv'
# Run the function
cs.generateThumbnails ( spatialTablePath=spatialTablePath,
imagePath=imagePath,
markerChannelMapPath=markerChannelMapPath,
markers=["ECAD", "CD3D"],
markerColumnName='marker',
channelColumnName='channel',
transformation=True,
maxThumbnails=100,
random_state=0,
localNorm=True,
globalNorm=False,
x_coordinate='X_centroid',
y_coordinate='Y_centroid',
percentiles=[2, 12, 88, 98],
windowSize=64,
restrictDensity=True,
restrictDensityNumber=None,
verbose=True,
projectDir=cwd)
# Same function if the user wants to run it via Command Line Interface
python generateThumbnails.py \
--spatialTablePath /Users/aj/Desktop/cspotExampleData/quantification/exampleSpatialTable.csv \
--imagePath /Users/aj/Desktop/cspotExampleData/image/exampleImage.tif \
--markerChannelMapPath /Users/aj/Desktop/cspotExampleData/markers.csv \
--markers ECAD CD3D \
--maxThumbnails 100 \
--projectDir /Users/aj/Desktop/cspotExampleData/
```
"""
# read the markers.csv
maper = pd.read_csv(pathlib.Path(markerChannelMapPath))
columnnames = [word.lower() for word in maper.columns]
maper.columns = columnnames
# identify the marker column name (doing this to make it easier for people who confuse between marker and markers)
if markerColumnName not in columnnames:
if markerColumnName != 'marker':
raise ValueError('markerColumnName not found in markerChannelMap, please check')
if 'markers' in columnnames:
markerCol = 'markers'
else:
raise ValueError('markerColumnName not found in markerChannelMap, please check')
else:
markerCol = markerColumnName
# identify the channel column name (doing this to make it easier for people who confuse between channel and channels)
if channelColumnName not in columnnames:
if channelColumnName != 'channel':
raise ValueError('channelColumnName not found in markerChannelMap, please check')
if 'channels' in columnnames:
channelCol = 'channels'
else:
raise ValueError('channelColumnName not found in markerChannelMap, please check')
else:
channelCol = channelColumnName
# map the marker and channels
chmamap = dict(zip(maper[markerCol], maper[channelCol]))
# load the CSV to identify potential thumbnails
data = pd.read_csv(pathlib.Path(spatialTablePath))
#data.index = data.index.astype(str)
# subset the markers of interest
if isinstance (markers, str):
markers = [markers]
# find the corresponding channel names
markerChannels = [chmamap[key] for key in markers if key in chmamap]
# convert markerChannels to zero indexing
markerChannels = [x-1 for x in markerChannels]
# creat a dict of marker and corresponding marker channel
marker_map = dict(zip(markers,markerChannels))
# create folders if it does not exist
if projectDir is None:
projectDir = os.getcwd()
# TruePos folders
for i in markers:
pos_path = pathlib.Path(projectDir + '/CSPOT/Thumbnails/' + str(i) + '/TruePos')
neg_path = pathlib.Path(projectDir + '/CSPOT/Thumbnails/' + str(i) + '/TrueNeg')
pos2neg_path = pathlib.Path(projectDir + '/CSPOT/Thumbnails/' + str(i) + '/PosToNeg')
neg2pos_path = pathlib.Path(projectDir + '/CSPOT/Thumbnails/' + str(i) + '/NegToPos')
if not os.path.exists(pos_path):
os.makedirs(pos_path)
if not os.path.exists(neg_path):
os.makedirs(neg_path)
if not os.path.exists(pos2neg_path):
os.makedirs(pos2neg_path)
if not os.path.exists(neg2pos_path):
os.makedirs(neg2pos_path)
if localNorm is True:
local_pos_path = pathlib.Path(projectDir + '/CSPOT/Thumbnails/localNorm/' + str(i) + '/TruePos')
local_neg_path = pathlib.Path(projectDir + '/CSPOT/Thumbnails/localNorm/' + str(i) + '/TrueNeg')
local_pos2neg_path = pathlib.Path(projectDir + '/CSPOT/Thumbnails/localNorm/' + str(i) + '/PosToNeg')
local_neg2pos_path = pathlib.Path(projectDir + '/CSPOT/Thumbnails/localNorm/' + str(i) + '/NegToPos')
if not os.path.exists(local_pos_path):
os.makedirs(local_pos_path)
if not os.path.exists(local_neg_path):
os.makedirs(local_neg_path)
if not os.path.exists(local_pos2neg_path):
os.makedirs(local_pos2neg_path)
if not os.path.exists(local_neg2pos_path):
os.makedirs(local_neg2pos_path)
marker_data = data[markers]
location = data[[x_coordinate,y_coordinate]]
# clip the data to drop outliers
def clipping (x):
clip = x.clip(lower =np.percentile(x,0.01), upper=np.percentile(x,99.99)).tolist()
return clip
# return the mean between two percentiles
def meanPercentile (values, lowPercentile, highPercentile):
# Calculate the 1st percentile value
p1 = np.percentile(values, lowPercentile)
# Calculate the 20th percentile value
p20 = np.percentile(values, highPercentile)
# Select the values between the 1st and 20th percentile using numpy.where()
filtered_values = np.where((values >= p1) & (values <= p20))
# Calculate the mean of the filtered values
meanVal = np.mean(values[filtered_values])
return meanVal
# Function for GMM
def simpleGMM (data, n_components, means_init, random_state):
gmm = GaussianMixture(n_components=n_components, means_init=means_init, random_state=random_state)
gmm.fit(data)
# Predict the class labels for each sample
predictions = gmm.predict(data)
# Get the mean of each Gaussian component
means = gmm.means_.flatten()
# Sort the mean values in ascending order
sorted_means = np.sort(means)
# Assign 'pos' to rows with higher mean distribution and 'neg' to rows with lower mean distribution
labels = np.where(predictions == np.argmax(means), 'pos', 'neg')
return labels
# match two arrays and return seperate lists
def array_match (labels, names):
# Create a defaultdict with an empty list as the default value
result = defaultdict(list)
# Iterate over the labels and names arrays
for label, name in zip(labels, names):
# Add the name to the list for the corresponding label
result[label].append(name)
return result
# clip data
marker_data = marker_data.apply(clipping)
# apply transformation if requested
if transformation is True:
marker_data = np.arcsinh(marker_data)
#marker_data = np.log1p(marker_data)
# combine data
combined_data = pd.concat([marker_data, location], axis=1)
# intialize the percentiles values
percentiles.sort()
# function to identify the corner of the thumbnails
def cornerFinder (centroid):
row_start = int(centroid - windowSize // 2)
row_end = row_start + windowSize
return [row_start, row_end]
# function to crop the image and save the image
def cropImage (rowIndex, corners, imgType, zimg, npercentile, m, maxpercentile, imname):
#print(str(rowIndex))
x_start = corners.loc[rowIndex]['x_start']; x_end = corners.loc[rowIndex]['x_end']
y_start = corners.loc[rowIndex]['y_start']; y_end = corners.loc[rowIndex]['y_end']
# cropping image
crop = zimg[y_start:y_end, x_start:x_end]
# check if image is the right size
if crop.shape == (windowSize,windowSize):
# convert the image to unit8
if globalNorm is True:
fullN = ((crop/npercentile)*255).clip(0, 255).astype('uint8')
else:
fullN = ((crop/maxpercentile)*255).clip(0, 255).astype('uint8')
# construct image filename with marker name prefix
prefixed_imname = f"{m}_{imname}_{rowIndex}.tif"
# save the cropped image
if imgType == 'pos':
path = pathlib.Path(projectDir + '/CSPOT/Thumbnails/' + str(m) + '/TruePos/' + prefixed_imname)
elif imgType == 'neg':
path = pathlib.Path(projectDir + '/CSPOT/Thumbnails/' + str(m) + '/TrueNeg/' + prefixed_imname)
# write file
tifffile.imwrite(path,fullN)
# local normalization if requested
if localNorm is True:
localN = ((crop/(np.percentile(crop, 99.99)))*255).clip(0, 255).astype('uint8') #.compute()
# save image
if imgType == 'pos':
Lpath = pathlib.Path(projectDir + '/CSPOT/Thumbnails/localNorm/' + str(m) + '/TruePos/' + prefixed_imname)
elif imgType == 'neg':
Lpath = pathlib.Path(projectDir + '/CSPOT/Thumbnails/localNorm/' + str(m) + '/TrueNeg/' + prefixed_imname)
# write file
tifffile.imwrite(Lpath,localN)
# identify the cells of interest
def processMarker (marker):
if verbose is True:
print('Processing Marker: ' + str(marker))
moi = combined_data[marker].values
# figure out marker index or channel in image
markerIndex = marker_map[marker]
# mean of cells within defined threshold
lowerPercent = meanPercentile (values=moi, lowPercentile=percentiles[0], highPercentile=percentiles[1])
higherPercent = meanPercentile (values=moi, lowPercentile=percentiles[2], highPercentile=percentiles[3])
# Format mean to pass into next GMM
Pmean = np.array([[lowerPercent], [higherPercent]])
# perform GMM
labels = simpleGMM (data=moi.reshape(-1, 1), n_components=2, means_init=Pmean, random_state=random_state)
# Match the labels and index names to identify which cells are pos and neg
expCells = array_match (labels=labels, names=data.index)
# split it
pos = expCells.get('pos', []) ; neg = expCells.get('neg', [])
# determine the percentiles value for the marker of interest
#low_a = np.percentile(moi, percentiles[0]); low_b = np.percentile(moi, percentiles[1])
#high_a = np.percentile(moi, percentiles[2]); high_b = np.percentile(moi, percentiles[3])
# identify the cells that fall within the determined range
#neg = np.where(moi.between(low_a, low_b))[0]
#pos = np.where(moi.between(high_a, high_b))[0]
# shuffle the cells
random.Random(random_state).shuffle(neg); random.Random(random_state).shuffle(pos)
# identify the location of pos and neg cells
neg_location_i = location.iloc[neg]
pos_location_i = location.iloc[pos]
# divide the pos cells into two bins based on the number of neighbours
# assumption is that we will find cells that are dense and sparse
if restrictDensity is True:
# identify postive cells that are densly packed if user requests
kdt = BallTree(pos_location_i[[x_coordinate,y_coordinate]], metric='euclidean')
ind = kdt.query_radius(pos_location_i[[x_coordinate,y_coordinate]], r=windowSize+5, return_distance=False)
for i in range(0, len(ind)): ind[i] = np.delete(ind[i], np.argwhere(ind[i] == i))#remove self
neigh_length = [len(subarray) for subarray in ind]
if restrictDensityNumber is None:
# GMM for auto detection
X = np.array(neigh_length).reshape(-1, 1)
gmm_neigh = GaussianMixture(n_components=2)
gmm_neigh.fit(X)
means = gmm_neigh.means_
index = np.argmin(means)
labels_neigh = gmm_neigh.predict(X)
lower_mean_indices = np.where(labels_neigh == index)[0]
# subset the postive cells based on the index
pos_location_i = pos_location_i.iloc[lower_mean_indices]
else:
lower_mean_indices = [i for i, x in enumerate(neigh_length) if x < restrictDensityNumber]
pos_location_i = pos_location_i.iloc[lower_mean_indices]
# Find corner
# Negative cells
r_cornerFinder = lambda x: cornerFinder (centroid=x)
neg_x = pd.DataFrame(list(map(r_cornerFinder, neg_location_i[x_coordinate].values))) # x direction
neg_y = pd.DataFrame(list(map(r_cornerFinder, neg_location_i[y_coordinate].values))) # y direction
neg_x.columns = ["x_start", "x_end"]; neg_y.columns = ["y_start", "y_end"]
neg_location = pd.concat([neg_x, neg_y], axis=1)
neg_location.index = neg_location_i.index
# Positive cells
r_cornerFinder = lambda x: cornerFinder (centroid=x)
pos_x = pd.DataFrame(list(map(r_cornerFinder, pos_location_i[x_coordinate].values))) # x direction
pos_y = pd.DataFrame(list(map(r_cornerFinder, pos_location_i[y_coordinate].values))) # y direction
pos_x.columns = ["x_start", "x_end"]; pos_y.columns = ["y_start", "y_end"]
pos_location = pd.concat([pos_x, pos_y], axis=1)
pos_location.index = pos_location_i.index
# drop all coordinates with neg values (essentially edges of slide)
neg_location = neg_location[(neg_location > 0).all(1)]
pos_location = pos_location[(pos_location > 0).all(1)]
# subset max number of cells
if len(neg_location) > maxThumbnails:
neg_location = neg_location[:maxThumbnails]
if len(pos_location) > maxThumbnails:
pos_location = pos_location[:maxThumbnails]
# identify image name
imname = pathlib.Path(imagePath).stem
# load the image
zimg = tifffile.imread(str(pathlib.Path(imagePath)), level=0, key=markerIndex)
npercentile = np.percentile(zimg, 99.99)
maxpercentile = zimg.max()
# load the image (dask has issues)
#zimg = da.from_zarr(tifffile.imread(pathlib.Path(imagePath), aszarr=True, level=0, key=markerIndex))
#npercentile = np.percentile(zimg.compute(), 99.99)
#maxpercentile = zimg.max().compute()
# for older version f tifffile
#zimg = zarr.open(tifffile.imread(pathlib.Path(imagePath), aszarr=True, level=0, key=markerIndex))
# = np.percentile(zimg, 99.99)
# Cut images and write it out
# neg
r_cropImage = lambda x: cropImage (rowIndex=x, corners=neg_location, imgType='neg', zimg=zimg, npercentile=npercentile, maxpercentile=maxpercentile, m=marker, imname=imname)
process_neg = list(map(r_cropImage, list(neg_location.index)))
# pos
r_cropImage = lambda x: cropImage (rowIndex=x, corners=pos_location, imgType='pos', zimg=zimg, npercentile=npercentile, maxpercentile=maxpercentile, m=marker, imname=imname)
process_neg = list(map(r_cropImage, list(pos_location.index)))
# Run the function for each marker
r_processMarker = lambda x: processMarker (marker=x)
final = list(map(r_processMarker, markers))
# Finish Job
if verbose is True:
print('Thumbnails have been generated, head over to "' + str(projectDir) + '/CSPOT/Thumbnails" to view results')
|