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,40 @@
1
+ import matplotlib.pyplot as plt
2
+
3
+
4
+ def tissue_lables(tissueframe, region="region1"):
5
+ """
6
+ Plot the tissue and region labels of the given DataFrame.
7
+
8
+ Parameters
9
+ ----------
10
+ tissueframe : DataFrame
11
+ The DataFrame containing the labels from the segmentation.
12
+ region : str, optional
13
+ The region to group by, by default "region1".
14
+
15
+ Returns
16
+ -------
17
+ None
18
+ """
19
+ centroids = tissueframe.groupby("tissue").mean()
20
+ fig, ax = plt.subplots()
21
+ ax.scatter(centroids["x"], centroids["y"])
22
+ ax.invert_yaxis()
23
+ plt.gca().set_aspect("equal", adjustable="box")
24
+
25
+ for i, txt in enumerate(centroids.index):
26
+ ax.annotate(txt, (list(centroids["x"])[i], list(centroids["y"])[i]))
27
+
28
+ plt.title("Tissue piece labels")
29
+ plt.show()
30
+
31
+ fig, ax = plt.subplots()
32
+ ax.scatter(centroids["x"], centroids["y"])
33
+ ax.invert_yaxis()
34
+ plt.gca().set_aspect("equal", adjustable="box")
35
+
36
+ for i, txt in enumerate(centroids[region]):
37
+ ax.annotate(int(txt), (list(centroids["x"])[i], list(centroids["y"])[i]))
38
+
39
+ plt.title("Region labels")
40
+ plt.show()
@@ -0,0 +1,227 @@
1
+ import random
2
+
3
+ import matplotlib.pyplot as plt
4
+ import numpy as np
5
+ import skimage.io
6
+ from deepcell.utils.plot_utils import create_rgb_image, make_outline_overlay
7
+ from skimage.measure import regionprops_table
8
+
9
+ from .._shared.segmentation import combine_channels, format_CODEX
10
+
11
+
12
+ # plot membrane channel selected for segmentation
13
+ def segmentation_ch(
14
+ file_name, # image for segmentation
15
+ channel_file, # all channels used for staining
16
+ output_dir,
17
+ savefig=False, # new
18
+ output_fname="", # new
19
+ extra_seg_ch_list=None, # channels used for membrane segmentation
20
+ nuclei_channel="DAPI",
21
+ input_format="Multichannel", # CODEX or Phenocycler --> This depends on the machine you are using and the resulting file format (see documentation above)
22
+ ):
23
+ """
24
+ Plot the channel selected for segmentation.
25
+
26
+ Parameters
27
+ ----------
28
+ file_name : str
29
+ The path to the image file for segmentation.
30
+ channel_file : str
31
+ The path to the file containing all channels used for staining.
32
+ output_dir : str
33
+ The directory to save the output in.
34
+ extra_seg_ch_list : list, optional
35
+ The channels used for membrane segmentation, by default None.
36
+ nuclei_channel : str, optional
37
+ The channel used for nuclei, by default "DAPI".
38
+ input_format : str, optional
39
+ The input_format used (either "CODEX", "Multichannel" or channels), by default "Multichannel".
40
+
41
+ Returns
42
+ -------
43
+ None
44
+ """
45
+ if input_format != "Channels":
46
+ # Load the image
47
+ img = skimage.io.imread(file_name)
48
+ # Read channels and store as list
49
+ with open(channel_file, "r") as f:
50
+ channel_names = f.read().splitlines()
51
+ # Function reads channels and stores them as a dictionary (storing as a dictionary allows to select specific channels by name)
52
+ image_dict = format_CODEX(
53
+ image=img,
54
+ channel_names=channel_names, # file with list of channel names (see channelnames.txt)
55
+ input_format=input_format,
56
+ )
57
+ else:
58
+ image_dict = format_CODEX(
59
+ image=file_name,
60
+ channel_names=None, # file with list of channel names (see channelnames.txt)
61
+ input_format=input_format,
62
+ )
63
+
64
+ image_dict = combine_channels(
65
+ image_dict, extra_seg_ch_list, new_channel_name="segmentation_channel"
66
+ )
67
+
68
+ fig, ax = plt.subplots(1, 2, figsize=(15, 15))
69
+ ax[0].imshow(image_dict[nuclei_channel])
70
+ ax[1].imshow(image_dict["segmentation_channel"])
71
+ ax[0].set_title("nuclei")
72
+ ax[1].set_title("membrane")
73
+
74
+ # save or plot figure
75
+ if savefig:
76
+ plt.savefig(
77
+ output_dir + output_fname + ".pdf",
78
+ format="pdf",
79
+ dpi=300,
80
+ transparent=True,
81
+ bbox_inches="tight",
82
+ )
83
+ else:
84
+ plt.show()
85
+
86
+
87
+ def show_masks(
88
+ seg_output,
89
+ nucleus_channel,
90
+ additional_channels=None,
91
+ show_subsample=True,
92
+ n=2, # need to be at least 2
93
+ tilesize=100,
94
+ idx=0,
95
+ rand_seed=1,
96
+ ):
97
+ """
98
+ Visualize the segmentation results of an image.
99
+
100
+ Parameters
101
+ ----------
102
+ seg_output : dict
103
+ The output from the segmentation process. It should contain 'image_dict' and 'masks'.
104
+ nucleus_channel : str
105
+ The name of the nucleus channel in the image_dict.
106
+ additional_channels : list of str, optional
107
+ The names of additional channels to be combined with the nucleus channel for visualization.
108
+ show_subsample : bool, optional
109
+ Whether to show a subsample of the image. Default is True.
110
+ n : int, optional
111
+ The number of subsamples to show. Default is 2.
112
+ tilesize : int, optional
113
+ The size of the tiles for subsampling. Default is 100.
114
+ idx : int, optional
115
+ The index for displaying. Default is 0.
116
+ rand_seed : int, optional
117
+ The seed for the random number generator. Default is 1.
118
+
119
+ Returns
120
+ -------
121
+ overlay_data : ndarray
122
+ The overlay of the segmentation results on the RGB images.
123
+ rgb_images : ndarray
124
+ The RGB images.
125
+
126
+ Raises
127
+ ------
128
+ ValueError
129
+ If the image size is smaller than the tile size or if there are not enough tiles to display.
130
+
131
+ """
132
+ image_dict = seg_output["image_dict"]
133
+ masks = seg_output["masks"]
134
+
135
+ # Create a combined image stack
136
+ # Assumes nuclei_image and membrane_image are numpy arrays of the same shape
137
+ if len(masks.shape) == 2:
138
+ masks = np.expand_dims(masks, axis=0)
139
+ masks = np.expand_dims(masks, axis=0)
140
+ masks = np.moveaxis(masks, 0, -1)
141
+
142
+ if additional_channels != None:
143
+ image_dict = combine_channels(
144
+ image_dict, additional_channels, new_channel_name="segmentation_channel"
145
+ )
146
+ nuclei_image = image_dict[nucleus_channel]
147
+ add_chan_image = image_dict["segmentation_channel"]
148
+ combined_image = np.stack([nuclei_image, add_chan_image], axis=-1)
149
+ # Add an extra dimension to make it compatible with Mesmer's input requirements
150
+ # Changes shape from (height, width, channels) to (1, height, width, channels)
151
+ combined_image = np.expand_dims(combined_image, axis=0)
152
+ # create rgb overlay of image data for visualization
153
+ rgb_images = create_rgb_image(combined_image, channel_colors=["green", "blue"])
154
+ else:
155
+ nuclei_image = image_dict[nucleus_channel]
156
+ combined_image = np.stack([nuclei_image], axis=-1)
157
+ # Add an extra dimension to make it compatible with Mesmer's input requirements
158
+ # Changes shape from (height, width, channels) to (1, height, width, channels)
159
+ combined_image = np.expand_dims(combined_image, axis=0)
160
+ # create rgb overlay of image data for visualization
161
+ rgb_images = create_rgb_image(combined_image, channel_colors=["blue"])
162
+
163
+ # create overlay of segmentation results
164
+ overlay_data = make_outline_overlay(rgb_data=rgb_images, predictions=masks)
165
+
166
+ # select index for displaying
167
+
168
+ # plot the data
169
+ fig, ax = plt.subplots(1, 2, figsize=(15, 15))
170
+ ax[0].imshow(rgb_images[idx, ...])
171
+ ax[1].imshow(overlay_data[idx, ...])
172
+ ax[0].set_title("Raw data")
173
+ ax[1].set_title("Predictions")
174
+ plt.show()
175
+
176
+ random.seed(rand_seed)
177
+ if show_subsample:
178
+ overlay_data = np.squeeze(overlay_data, axis=0)
179
+ rgb_images = np.squeeze(rgb_images, axis=0)
180
+
181
+ # Ensure the sizes are compatible for tile calculation
182
+ if overlay_data.shape[0] < tilesize or overlay_data.shape[1] < tilesize:
183
+ print("Image size is smaller than the tile size. Cannot display tiles.")
184
+ else:
185
+ # Calculate the number of tiles in x and y directions
186
+ y_tiles, x_tiles = (
187
+ overlay_data.shape[0] // tilesize,
188
+ overlay_data.shape[1] // tilesize,
189
+ )
190
+
191
+ # Check if either x_tiles or y_tiles is zero
192
+ if x_tiles == 0 or y_tiles == 0:
193
+ print("Not enough tiles to display.")
194
+ else:
195
+ # Split images into tiles
196
+ overlay_tiles = []
197
+ grayscale_tiles = []
198
+ for i in range(x_tiles):
199
+ for j in range(y_tiles):
200
+ x_start, y_start = i * tilesize, j * tilesize
201
+ overlay_tile = overlay_data[
202
+ y_start : y_start + tilesize, x_start : x_start + tilesize
203
+ ]
204
+ image_tile = rgb_images[
205
+ y_start : y_start + tilesize, x_start : x_start + tilesize
206
+ ]
207
+
208
+ overlay_tiles.append(overlay_tile)
209
+ grayscale_tiles.append(image_tile)
210
+
211
+ # Randomly select n tiles
212
+ random_indices = random.sample(range(len(overlay_tiles)), n)
213
+
214
+ # Plot the tiles
215
+ fig, axs = plt.subplots(n, 2, figsize=(10, 5 * n))
216
+ for i, idx in enumerate(random_indices):
217
+ axs[i, 0].imshow(grayscale_tiles[idx])
218
+ axs[i, 0].axis("off")
219
+ axs[i, 1].imshow(overlay_tiles[idx])
220
+ axs[i, 1].axis("off")
221
+
222
+ axs[i, 0].set_title("Raw data")
223
+ axs[i, 1].set_title("Predictions")
224
+ plt.tight_layout()
225
+ plt.show()
226
+
227
+ return overlay_data, rgb_images
@@ -0,0 +1,8 @@
1
+ from ._general import filter_data, format, read_segdf, remove_noise
2
+
3
+ __all__ = [
4
+ "read_segdf",
5
+ "filter_data",
6
+ "format",
7
+ "remove_noise",
8
+ ]
@@ -0,0 +1,431 @@
1
+ # load required packages
2
+ import glob
3
+ import os
4
+ import sys
5
+ from itertools import product
6
+
7
+ import matplotlib.pyplot as plt
8
+ import numpy as np
9
+ import pandas as pd
10
+ import scanpy as sc
11
+ import seaborn as sns
12
+ from scipy.stats import norm, zscore
13
+
14
+
15
+ # read the data frame output from the segmentation functions
16
+ def read_segdf(
17
+ segfile_list,
18
+ seg_method,
19
+ region_list=None, # optional information #please make sure the length of each list matches
20
+ meta_list=None, # optional information
21
+ ):
22
+ """
23
+ Read the data frame output from the segmentation functions.
24
+
25
+ Parameters
26
+ ----------
27
+ segfile_list : list
28
+ List of segmented csv files to be read.
29
+ seg_method : str
30
+ The segmentation method used.
31
+ region_list : list, optional
32
+ List of regions, by default None. Please make sure the length of each list matches.
33
+ meta_list : list, optional
34
+ List of metadata, by default None. Please make sure the length of each list matches.
35
+
36
+ Returns
37
+ -------
38
+ df : pandas.DataFrame
39
+ The concatenated DataFrame from all the segmentation files.
40
+
41
+ Raises
42
+ ------
43
+ SystemExit
44
+ If the length of region_list or meta_list does not match with segfile_list.
45
+ """
46
+ if region_list is not None:
47
+ if len(region_list) != len(segfile_list):
48
+ sys.exit("length of each list does not match!")
49
+ elif meta_list is not None:
50
+ if len(meta_list) != len(segfile_list):
51
+ sys.exit("length of each list does not match!")
52
+
53
+ df = pd.DataFrame()
54
+ # concat old dataframes
55
+ for i in range(len(segfile_list)):
56
+ tmp = pd.read_csv(segfile_list[i], index_col=0)
57
+ tmp["region_num"] = str(i)
58
+ if region_list is not None:
59
+ tmp["unique_region"] = str(region_list[i])
60
+ if meta_list is not None:
61
+ tmp["condition"] = str(meta_list[i])
62
+ df = pd.concat([df, tmp], axis=0)
63
+
64
+ if seg_method == "cellseg":
65
+ # See resultant dataframe
66
+ df.columns = df.columns.str.split(":").str[-1].tolist()
67
+ df = df.reset_index().rename(columns={"index": "first_index"})
68
+ df.columns = df.columns.str.split(":").str[-1].tolist()
69
+ df.rename(columns={"size": "area"}, inplace=True)
70
+ return df
71
+
72
+
73
+ def filter_data(
74
+ df,
75
+ nuc_thres=1,
76
+ size_thres=1,
77
+ nuc_marker="DAPI",
78
+ cell_size="area",
79
+ region_column="region_num",
80
+ color_by=None,
81
+ palette="Paired",
82
+ alpha=0.8,
83
+ size=0.4, # dot style
84
+ log_scale=False,
85
+ ):
86
+ """
87
+ Filter data based on nuclear threshold and size threshold, and visualize the data before and after filtering.
88
+
89
+ Parameters
90
+ ----------
91
+ df : pandas.DataFrame
92
+ The DataFrame to be filtered.
93
+ nuc_thres : int, optional
94
+ The nuclear threshold, by default 1.
95
+ size_thres : int, optional
96
+ The size threshold, by default 1.
97
+ nuc_marker : str, optional
98
+ The nuclear marker, by default "DAPI".
99
+ cell_size : str, optional
100
+ The cell size, by default "area".
101
+ region_column : str, optional
102
+ The region column, by default "region_num".
103
+ color_by : str, optional
104
+ The column to color by, by default None.
105
+ palette : str, optional
106
+ The color palette, by default "Paired".
107
+ alpha : float, optional
108
+ The alpha for the scatter plot, by default 0.8.
109
+ size : float, optional
110
+ The size for the scatter plot, by default 0.4.
111
+ log_scale : bool, optional
112
+ Whether to use log scale for the scatter plot, by default False.
113
+
114
+ Returns
115
+ -------
116
+ df_nuc : pandas.DataFrame
117
+ The filtered DataFrame.
118
+ """
119
+ if color_by == None:
120
+ color_by = region_column
121
+
122
+ df_nuc = df[(df[nuc_marker] > nuc_thres) * df[cell_size] > size_thres]
123
+ per_keep = len(df_nuc) / len(df)
124
+
125
+ # Create a figure with two subplots
126
+ fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(15, 5))
127
+
128
+ # Boxplot
129
+ sns.boxplot(data=df.loc[:, [cell_size, nuc_marker]], orient="h", ax=ax1)
130
+ ax1.set_title("Cell size and nuclear marker intensity")
131
+
132
+ # Plot 1
133
+ sns.scatterplot(
134
+ x=df[nuc_marker],
135
+ y=df[cell_size],
136
+ hue=df[color_by],
137
+ palette=palette,
138
+ alpha=alpha,
139
+ ax=ax2,
140
+ legend=False,
141
+ )
142
+
143
+ if log_scale == True:
144
+ ax2.set_xscale("log")
145
+ ax2.set_yscale("log")
146
+
147
+ ax2.axhline(size_thres, color="k", linestyle="dashed", linewidth=1)
148
+ ax2.axvline(nuc_thres, color="k", linestyle="dashed", linewidth=1)
149
+ ax2.legend(bbox_to_anchor=(1.2, 1), loc="upper left", borderaxespad=0)
150
+ ax2.set_title("Before filtering")
151
+
152
+ # Plot 2
153
+ sns.scatterplot(
154
+ x=df_nuc[nuc_marker],
155
+ y=df_nuc[cell_size],
156
+ hue=df_nuc[color_by],
157
+ palette=palette,
158
+ alpha=alpha,
159
+ ax=ax3,
160
+ )
161
+
162
+ if log_scale == True:
163
+ ax3.set_xscale("log")
164
+ ax3.set_yscale("log")
165
+
166
+ ax3.axhline(size_thres, color="k", linestyle="dashed", linewidth=1)
167
+ ax3.axvline(nuc_thres, color="k", linestyle="dashed", linewidth=1)
168
+ ax3.legend(bbox_to_anchor=(1.2, 1), loc="upper left", borderaxespad=0)
169
+ ax3.set_title("After filtering")
170
+
171
+ plt.show()
172
+ # show plot
173
+ plt.tight_layout()
174
+ plt.show()
175
+
176
+ # print the percentage of cells that are kept
177
+ print("Percentage of cells kept: ", per_keep * 100, "%")
178
+
179
+ return df_nuc
180
+
181
+
182
+ def format(data, list_out, list_keep, method="zscore", ArcSin_cofactor=150):
183
+ """
184
+ This function formats the data based on the specified method. It supports four methods: "zscore", "double_zscore", "MinMax", and "ArcSin".
185
+
186
+ Parameters
187
+ ----------
188
+ data : DataFrame
189
+ The input data to be formatted.
190
+ list_out : list
191
+ The list of columns to be dropped from the data.
192
+ list_keep : list
193
+ The list of columns to be kept in the data.
194
+ method : str, optional
195
+ The method to be used for normalizing the data. It can be "zscore", "double_zscore", "MinMax", or "ArcSin". By default, it is "zscore".
196
+ ArcSin_cofactor : int, optional
197
+ The cofactor to be used in the ArcSin transformation. By default, it is 150.
198
+
199
+ Returns
200
+ -------
201
+ DataFrame
202
+ The formatted data.
203
+
204
+ Raises
205
+ ------
206
+ ValueError
207
+ If the specified method is not supported.
208
+ """
209
+
210
+ list = ["zscore", "double_zscore", "MinMax", "ArcSin"]
211
+
212
+ if method not in list:
213
+ print("Please select methods from zscore, double_zscore, MinMax, ArcSin!")
214
+ exit()
215
+
216
+ ##ArcSin transformation
217
+ if method == "ArcSin":
218
+ # Drop column list
219
+ list1 = [col for col in data.columns if "blank" in col]
220
+ list_out1 = list1 + list_out
221
+
222
+ # Drop columns not interested in
223
+ dfin = data.drop(list_out1, axis=1)
224
+
225
+ # save columns for later
226
+ df_loc = dfin.loc[:, list_keep]
227
+
228
+ # dataframe for normalization
229
+ dfas = dfin.drop(list_keep, axis=1)
230
+
231
+ # parameters seit in function
232
+ # Only decrease the background if the median is higher than the background
233
+ dfa = dfas.apply(lambda x: np.arcsinh(x / ArcSin_cofactor))
234
+
235
+ # Add back labels for normalization type
236
+ dfz_all = pd.concat([dfa, df_loc], axis=1, join="inner")
237
+
238
+ return dfz_all
239
+
240
+ ##Double Z normalization
241
+ elif method == "double_zscore":
242
+ # Drop column list
243
+ list1 = [col for col in data.columns if "blank" in col]
244
+ list_out1 = list1 + list_out
245
+
246
+ # Drop columns not interested in
247
+ dfin = data.drop(list_out1, axis=1)
248
+
249
+ # save columns for later
250
+ df_loc = dfin.loc[:, list_keep]
251
+
252
+ # dataframe for normalization
253
+ dfz = dfin.drop(list_keep, axis=1)
254
+
255
+ # zscore of the column markers
256
+ dfz1 = pd.DataFrame(
257
+ zscore(dfz, 0), index=dfz.index, columns=[i for i in dfz.columns]
258
+ )
259
+
260
+ # zscore rows
261
+ dfz2 = pd.DataFrame(
262
+ zscore(dfz1, 1), index=dfz1.index, columns=[i for i in dfz1.columns]
263
+ )
264
+
265
+ # Take cumulative density function to find probability of z score across a row
266
+ dfz3 = pd.DataFrame(
267
+ norm.cdf(dfz2), index=dfz2.index, columns=[i for i in dfz2.columns]
268
+ )
269
+
270
+ # First 1-probability and then take negative logarithm so greater values demonstrate positive cell type
271
+ dflog = dfz3.apply(lambda x: -np.log(1 - x))
272
+
273
+ # Add back labels for normalization type
274
+ dfz_all = pd.concat([dflog, df_loc], axis=1, join="inner")
275
+
276
+ # print("the number of regions = "+str(len(dfz_all.region_num.unique())))
277
+
278
+ return dfz_all
279
+
280
+ # Min Max normalization
281
+ elif method == "MinMax":
282
+ # Drop column list
283
+ list1 = [col for col in data.columns if "blank" in col]
284
+ list_out1 = list1 + list_out
285
+
286
+ # Drop columns not interested in
287
+ dfin = data.drop(list_out1, axis=1)
288
+
289
+ # save columns for later
290
+ df_loc = dfin.loc[:, list_keep]
291
+
292
+ # dataframe for normalization
293
+ dfmm = dfin.drop(list_keep, axis=1)
294
+
295
+ for col in dfmm.columns:
296
+ max_value = dfmm[col].quantile(0.99)
297
+ min_value = dfmm[col].quantile(0.01)
298
+ dfmm[col].loc[dfmm[col] > max_value] = max_value
299
+ dfmm[col].loc[dfmm[col] < min_value] = min_value
300
+ dfmm[col] = (dfmm[col] - min_value) / (max_value - min_value)
301
+
302
+ # Add back labels for normalization type
303
+ dfz_all = pd.concat([dfmm, df_loc], axis=1, join="inner")
304
+
305
+ return dfz_all
306
+
307
+ ## Z normalization
308
+ else:
309
+ # Drop column list
310
+ list1 = [col for col in data.columns if "blank" in col]
311
+ list_out1 = list1 + list_out
312
+
313
+ # Drop columns not interested in
314
+ dfin = data.drop(list_out1, axis=1)
315
+
316
+ # save columns for later
317
+ df_loc = dfin.loc[:, list_keep]
318
+
319
+ # dataframe for normalization
320
+ dfz = dfin.drop(list_keep, axis=1)
321
+
322
+ # zscore of the column markers
323
+ dfz1 = pd.DataFrame(
324
+ zscore(dfz, 0), index=dfz.index, columns=[i for i in dfz.columns]
325
+ )
326
+
327
+ # Add back labels for normalization type
328
+ dfz_all = pd.concat([dfz1, df_loc], axis=1, join="inner")
329
+
330
+ # print("the number of regions = "+str(len(dfz_all.region_num.unique())))
331
+
332
+ return dfz_all
333
+
334
+
335
+ # Only useful for "classic CODEX" where samples are covered by multiple regions
336
+ # Could also be used for montages of multiple samples (tiles arraged in grid)
337
+ def xycorr(data, y_rows, x_columns, X_pix, Y_pix):
338
+ """
339
+ Corrects the x and y coordinates of the data for "classic CODEX" where samples are covered by multiple regions.
340
+ This function could also be used for montages of multiple samples (tiles arranged in a grid).
341
+
342
+ Parameters
343
+ ----------
344
+ data : DataFrame
345
+ The input data to be corrected.
346
+ y_rows : int
347
+ The number of rows in the y direction.
348
+ x_columns : int
349
+ The number of columns in the x direction.
350
+ X_pix : int
351
+ The number of pixels in the x direction.
352
+ Y_pix : int
353
+ The number of pixels in the y direction.
354
+
355
+ Returns
356
+ -------
357
+ DataFrame
358
+ The corrected data with added 'Xcorr' and 'Ycorr' columns representing the corrected x and y coordinates respectively.
359
+ """
360
+ # Make a copy for xy correction
361
+ df_XYcorr = data.copy()
362
+ df_XYcorr["Xcorr"] = 0
363
+ df_XYcorr["Ycorr"] = 0
364
+ dict_test = dict(enumerate(df_XYcorr.region_num.unique()))
365
+ dict_map = {v: k + 1 for k, v in dict_test.items()}
366
+ df_XYcorr["regloop"] = df_XYcorr["region_num"].map(dict_map)
367
+ region_num = df_XYcorr.regloop.max()
368
+
369
+ # first value of tuple is y and second is x
370
+ d = list(product(range(0, y_rows, 1), range(0, x_columns, 1)))
371
+ e = list(range(1, region_num + 1, 1))
372
+ dict_corr = {}
373
+ dict_corr = dict(zip(e, d))
374
+
375
+ # Adding the pixels with the dictionary
376
+ for reg_num in list(df_XYcorr["regloop"].unique()):
377
+ df_XYcorr["Xcorr"].loc[df_XYcorr["regloop"] == reg_num] = (
378
+ df_XYcorr["x"].loc[df_XYcorr["regloop"] == reg_num]
379
+ + dict_corr[reg_num][1] * X_pix
380
+ )
381
+
382
+ for reg_num in list(df_XYcorr["regloop"].unique()):
383
+ df_XYcorr["Ycorr"].loc[df_XYcorr["regloop"] == reg_num] = (
384
+ df_XYcorr["y"].loc[df_XYcorr["regloop"] == reg_num]
385
+ + dict_corr[reg_num][0] * Y_pix
386
+ )
387
+
388
+ df_XYcorr.drop(columns=["regloop"], inplace=True)
389
+ return df_XYcorr
390
+
391
+
392
+ # Get rid of noisy cells from dataset
393
+ def remove_noise(df, col_num, z_sum_thres, z_count_thres):
394
+ """
395
+ Removes noisy cells from the dataset based on the given thresholds.
396
+
397
+ Parameters
398
+ ----------
399
+ df : DataFrame
400
+ The input data from which noisy cells are to be removed.
401
+ col_num : int
402
+ The column number up to which the operation is performed.
403
+ z_sum_thres : float
404
+ The threshold for the sum of z-scores. Cells with a sum of z-scores greater than this threshold are considered noisy.
405
+ z_count_thres : int
406
+ The threshold for the count of z-scores. Cells with a count of z-scores greater than this threshold are considered noisy.
407
+
408
+ Returns
409
+ -------
410
+ df_want : DataFrame
411
+ The cleaned data with noisy cells removed.
412
+ cc : DataFrame
413
+ The data of the noisy cells that were removed from the original data.
414
+
415
+ """
416
+ df_z_1_copy = df.copy()
417
+ df_z_1_copy["Count"] = df_z_1_copy.iloc[:, : col_num + 1].ge(0).sum(axis=1)
418
+ df_z_1_copy["z_sum"] = df_z_1_copy.iloc[:, : col_num + 1].sum(axis=1)
419
+ cc = df_z_1_copy[
420
+ (df_z_1_copy["z_sum"] > z_sum_thres) | (df_z_1_copy["Count"] > z_count_thres)
421
+ ]
422
+ df_want = df_z_1_copy[
423
+ ~((df_z_1_copy["z_sum"] > z_sum_thres) | (df_z_1_copy["Count"] > z_count_thres))
424
+ ]
425
+ percent_removed = np.round(
426
+ 1 - (df_want.shape[0] / df_z_1_copy.shape[0]), decimals=3
427
+ )
428
+ print(str(percent_removed * 100) + "% cells are removed.")
429
+ df_want.drop(columns=["Count", "z_sum"], inplace=True)
430
+ df_want.reset_index(inplace=True, drop=True)
431
+ return df_want, cc