Features Visualization
Loading Packages
[1]:
import warnings
warnings.filterwarnings('ignore')
import numpy as np
import scanpy as sc
import matplotlib.pyplot as plt
import sys
sys.path.append(r'../../../')
from SpatialCOC.utils import replace_extreme_values, rotate_spatial_coordinates
Visualization of “Background noise”
[30]:
# Define replicate numbers
replicates = ['1', '2', '3']
# Define the color map
colors = ["#457b9d", "#a8dadc", "#f1faee", "#f4f1bb", "#f4a261", "#f05d5e"]
from matplotlib.colors import LinearSegmentedColormap
cmap = LinearSegmentedColormap.from_list("my_cmap", colors)
# Set plotting parameters
plt.rcParams['font.size'] = 20
plt.rcParams['font.sans-serif'] = 'Arial'
# Loop through each replicate
for replicate in replicates:
# Load the data
adata_modality_1 = sc.read_h5ad(f"../../../Data/Mouse_Thymus_{replicate}/adata_RNA.h5ad")
print(f"Background noise of replicate {replicate}")
# If it is the third replicate, rotate the coordinates by 90 degrees
if replicate == '3':
adata_modality_1.obsm['spatial'] = rotate_spatial_coordinates(adata_modality_1.obsm['spatial'], angle_degrees=270)
# Calculate background noise
adata_modality_1.obs['background'] = np.sum(adata_modality_1.X.toarray(), axis=1).ravel()
adata_modality_1.obs['background'] = replace_extreme_values(adata_modality_1.obs['background'], n=0.05)
# Create the plot
fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(6, 6))
# Plot the spatial embedding
sc.pl.embedding(adata_modality_1, basis="spatial", color='background', ax=ax, show=False, cmap=cmap, colorbar_loc=None, s=100)
# Customize the plot
ax.set_xlabel('')
ax.set_ylabel('')
ax.set_title(f'') # Empty title
ax.invert_yaxis()
for spine in ax.spines.values():
spine.set_visible(False)
plt.tight_layout()
# Save the plot
plt.savefig(f'replicate{replicate}/Background_Noise.png', dpi=500)
plt.savefig(f'replicate{replicate}/Background_Noise.eps')
plt.show()
Background noise of replicate 1
Background noise of replicate 2
Background noise of replicate 3
Visualization of Extracted Features
[29]:
# Define replicate numbers
replicates = ['1', '2', '3']
# Define colors for the colormap
colors = ["#457b9d", "#a8dadc", "#f1faee", "#f4f1bb", "#f4a261", "#f05d5e"]
from matplotlib.colors import LinearSegmentedColormap
cmap = LinearSegmentedColormap.from_list("my_cmap", colors)
# Loop through each replicate and create a separate plot
for replicate in replicates:
# Read the data for the current replicate
adata_analysis = sc.read_h5ad(f"../../Mouse_Thymus_Replicate{replicate}.h5ad")
componts_num = 0
adata_analysis.obs[f'feat_{componts_num}'] = adata_analysis.obsm["SpaKnit"][:, 0]
adata_analysis.obs[f'feat_{componts_num}'] = replace_extreme_values(adata_analysis.obs[f'feat_{componts_num}'], n=0.005)
print(f"Extracted feature of replicate {replicate}")
# Set up the figure and axis for the current plot
plt.rcParams['font.size'] = 20
plt.rcParams['font.sans-serif'] = 'Arial'
fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(6, 6))
# Plot the spatial embedding with the extracted feature
sc.pl.embedding(adata_analysis, basis="spatial", color=f'feat_{componts_num}', ax=ax, show=False, cmap=cmap, colorbar_loc=None, s=100)
# Customize the plot
ax.set_xlabel('')
ax.set_ylabel('')
ax.set_title(f'')
ax.invert_yaxis()
for spine in ax.spines.values():
spine.set_visible(False)
plt.tight_layout()
plt.savefig(f'replicate{replicate}/Extracted_Feature.png', dpi=500)
plt.savefig(f'replicate{replicate}/Extracted_Feature.eps')
plt.show()
Extracted feature of replicate 1
Extracted feature of replicate 2
Extracted feature of replicate 3
Saving Results
[18]:
import pandas as pd
# Define replicate numbers
replicates = ['1', '2', '3']
# Result file
output_file = 'Extracted_Features.xlsx'
writer = pd.ExcelWriter(output_file, engine='openpyxl')
# Loop through each replicate
for replicate in replicates:
# Load the data for background noise
adata_modality_1 = sc.read_h5ad(f"../../../Data/Mouse_Thymus_{replicate}/adata_RNA.h5ad")
# If it is the third replicate, rotate the coordinates by 90 degrees
if replicate == '3':
adata_modality_1.obsm['spatial'] = rotate_spatial_coordinates(adata_modality_1.obsm['spatial'], angle_degrees=270)
# Calculate background noise
adata_modality_1.obs['background'] = np.sum(adata_modality_1.X.toarray(), axis=1).ravel()
# Load the data for extracted feature
adata_analysis = sc.read_h5ad(f"../../Mouse_Thymus_Replicate{replicate}.h5ad")
componts_num = 0
adata_analysis.obs[f'feat_{componts_num}'] = adata_analysis.obsm["SpatialCOC"][:, 0]
barcodes_modality = adata_modality_1.obs.index.astype(str)
barcodes_analysis = adata_analysis.obs.index.astype(str)
df_background = pd.DataFrame({
'barcode': barcodes_modality,
'background': adata_modality_1.obs['background'].values
}).set_index('barcode')
df_feature = pd.DataFrame({
'barcode': barcodes_analysis,
f'feature': adata_analysis.obs[f'feat_{componts_num}'].values
}).set_index('barcode')
spatial_coords = adata_modality_1.obsm['spatial']
df_spatial = pd.DataFrame({
'barcode': barcodes_modality,
'x': spatial_coords[:, 0],
'y': spatial_coords[:, 1]
}).set_index('barcode')
df_merged = df_background.join(df_feature, how='inner')
df_merged = df_merged.join(df_spatial, how='inner')
df_merged = df_merged.reset_index()
sheet_name = f'Replicate_{replicate}'
df_merged.to_excel(writer, sheet_name=sheet_name, index=False)
writer.close()
print(f"All data saved to: {output_file}")
All data saved to: Extracted_Features.xlsx