Skip to main content

Spatial Analyses

In this tutorial we will show you how you can analyze the spatial configuration of proteins on the cell surface of single cells, using PNA data.

Pixelator will generate a number of metrics from the graph structure inherent to the PNA data. In this tutorial we will show you how you can approach spatial analysis using the PNA proximity scores to get a deeper understanding of how proteins are organized on the cell surface.

We will load two PBMC samples, one that has undergone PHA stimulation, and an unstimulated sample.

After completing this tutorial, you will be able to:

  • Extract key features from PNA data: Analyze the inherent graph structure of PNA data to understand protein clustering (polarity) and co-abundance (colocalization) on cell surfaces.

  • Quantify spatial changes in protein clustering: Utilize PNA proximity scores and Wilcoxon Rank Sum tests to measure and compare protein clustering between different conditions, revealing spatial rearrangements upon cellular stimulation.

  • Identify changes in protein colocalization: Conduct differential proximity analysis to pinpoint protein pairs with significant changes in co-occurrence across different samples, uncovering potential protein interactions under specific conditions.

  • Visualize and interpret data: Effectively communicate your findings through volcano plots and heatmaps for differential analyses, and leverage UMAPs to explore relationships between proximity scores, identifying distinct protein groups based on their spatial dynamics.

  • Connect spatial data to biological functions: Correlate observed changes in protein organization with cellular phenotypes or functions to gain deeper insights into protein interactions and their roles in biological processes like cellular migration.

Setup​

import numpy as np
import pandas as pd
from pathlib import Path
from pixelator import read_pna as read
from pixelator.pna.analysis import (
filter_proximity_scores,
summarize_proximity_scores,
calculate_differential_proximity,
)
from pixelator.pna.plot import proximity_heatmap
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import matplotlib.colors as mcolors
import networkx as nx
from scipy.stats import mannwhitneyu, false_discovery_control, zscore
from statsmodels.stats.multitest import multipletests
import umap

sns.set_style("whitegrid")
DATA_DIR = Path("./pna-analysis")

Load data​

We begin by loading and merging the two samples, so that they can easily be analyzed together.

from pixelator.pna.pixeldataset.download import DownloadableDatasets

DATA_DIR.mkdir(parents=True, exist_ok=True)

DownloadableDatasets.download_dataset(
"pna062-unstim-pbmcs",
output_path=DATA_DIR / "PNA062_unstim_PBMCs_1000cells_S02_S2.layout.pxl",
)
DownloadableDatasets.download_dataset(
"pna062-pha-pbmcs",
output_path=DATA_DIR / "PNA062_PHA_PBMCs_1000cells_S04_S4.layout.pxl",
)
pg_data_combined_pxl_object =  read([
DATA_DIR/ "PNA062_unstim_PBMCs_1000cells_S02_S2.layout.pxl",
DATA_DIR/ "PNA062_PHA_PBMCs_1000cells_S04_S4.layout.pxl",
])
filtered_cells = list(pd.read_csv(DATA_DIR / "qc_filtered_cells.csv")["component"])
pg_data_combined_pxl_object = pg_data_combined_pxl_object.filter(components=filtered_cells)

Obtaining proximity scores for target cells​

Since T cells are the primary target of PHA, let us limit our analysis of spatial metrics to CD8 T cells. We use the cell types from the cell annotation tutorial.

annotations = pd.read_csv(DATA_DIR / "cell_type_annotations.csv").set_index("component") 
cd8t_cells = list(annotations[annotations["cell_type"] == "CD8 T"].index)
proximity_scores = pg_data_combined_pxl_object.filter(components=cd8t_cells).proximity().to_df()
proximity_scores.head()
marker_1marker_2join_countjoin_count_expected_meanjoin_count_expected_sdjoin_count_zjoin_count_pcomponentsamplemarker_1_countmarker_1_freqmarker_2_countmarker_2_freqmin_countlog2_ratio
0HLA-ABCHLA-ABC203180.0813.6734501.6762410.046845a9b381039231f96ePNA062_unstim_PBMCs_1000cells_S02_S216570.04180316570.04180316570.172842
1HLA-ABCKLRG19573.078.0179792.7351030.003118a9b381039231f96ePNA062_unstim_PBMCs_1000cells_S02_S216570.0418033390.0085523390.378648
2HLA-ABCTCRab4739.826.3887211.1238560.130537a9b381039231f96ePNA062_unstim_PBMCs_1000cells_S02_S216570.0418031890.0047681890.239168
3HLA-ABCHLA-DR-DP-DQ52.551.7943511.3653960.086064a9b381039231f96ePNA062_unstim_PBMCs_1000cells_S02_S216570.041803120.000303120.971431
4CD45RBHLA-ABC473439.1919.2446741.7568500.039472a9b381039231f96ePNA062_unstim_PBMCs_1000cells_S02_S220270.05113816570.04180316570.106995

The measures in each row of the proximity scores’ table correspond to a marker pair (marker_1 and marker_2) in a given component. When marker_1 and marker_2 are the same, the measure indicates the clustering degree of that marker in the component; when they are different, the measure indicates the colocalization degree of those two markers.

Proximity measures​

There are two main values that we typically look into when analyzing spatial proximity. First one is “join_count_z” that is a z-score showing how significantly, the number of join counts, i.e. number of links between marker_1 and marker_2 antibodies, are higher or lower than expected by chance. Notice that this score is a measure of statistical significance rather than proximity degree. This means that with higher total counts, the z-score would be higher for the same proximity degree as the result becomes more significant. The second value is “log2_ratio” that is the log2 of ratio of observed edges between marker_1 and marker_2 to the number of edges expected by chance. This is a closer measure of the degree of proximity. So for questions similar to “Are these two markers colocalized?” or “Is this marker significantly clustered?” one typically looks at the “join_count_z” value and for the questions like “Has this marker increased in clustering after stimulation?” one would look at log2_ratio metric.

Filtering the low-abundance markers​

Not all proteins will always be expressed by every cell, i.e. some markers might have very low abundance in some cells. For such proteins the proximity scores should be excluded in the corresponding cells. Typically, filtration should be performed before spatial proximity analysis to reduce the potential noise from low abundance markers.

filter_proximity_scores drops pairs where either marker has too few UMI counts. That cutoff is the same value as min_count, the lower of the two marker counts in the cell. Here both markers must have at least 50 counts. We also drop pairs with fewer than 10 expected edges (join_count_expected_mean), the number of links expected if the two markers were randomly distributed. A z-score from so few expected edges is unstable.

proximity_scores = filter_proximity_scores(
proximity_scores,
background_threshold_count=50,
)
proximity_scores = proximity_scores[
proximity_scores["join_count_expected_mean"] >= 10
]
proximity_scores["condition"] = "Resting"
proximity_scores.loc[
proximity_scores["sample"].astype(str).str.contains("PHA", na=False),
"condition",
] = "PHA stimulated"
proximity_scores["condition"] = pd.Categorical(
proximity_scores["condition"],
categories=["Resting", "PHA stimulated"],
ordered=True,
)

CONDITION_ORDER = ["Resting", "PHA stimulated"]
CONDITION_PALETTE = {"Resting": "#2ca02c", "PHA stimulated": "#ff7f0e"}

Clustering analysis​

Let’s look at the significantly clustered markers in each sample. Here, we consider a marker to be significantly clustered if it is expressed in at least 50 cells and its median proximity z-score is above 2. summarize_proximity_scores collapses the per-cell scores to one row per marker and sample. With include_missing_obs set to False, that median is taken only over cells where the marker was detected.

clustering_scores = proximity_scores[proximity_scores["marker_1"] == proximity_scores["marker_2"]]
sample_clustering = summarize_proximity_scores(
clustering_scores,
proximity_metric="join_count_z",
group_vars="sample",
summary_stat="median",
include_missing_obs=False,
).drop("marker_2", axis=1)

sample_clustering[
(sample_clustering["median_join_count_z"] > 2)
& (sample_clustering["n_cells_detected"] > 50)
].sort_values("median_join_count_z", ascending=False).head(10)
samplemarker_1n_cells_detectedn_cellsn_cells_missingpct_detectedmedian_join_count_z
47PNA062_PHA_PBMCs_1000cells_S04_S4CD822023151130.64127014.520967
93PNA062_unstim_PBMCs_1000cells_S02_S2CD8138151130.9139077.097403
36PNA062_PHA_PBMCs_1000cells_S04_S4CD52292315230.9269846.236976
45PNA062_PHA_PBMCs_1000cells_S04_S4CD8294315210.9333335.065434
78PNA062_unstim_PBMCs_1000cells_S02_S2CD45RA84151670.5562914.400127
79PNA062_unstim_PBMCs_1000cells_S02_S2CD45RB131151200.8675503.841354
56PNA062_unstim_PBMCs_1000cells_S02_S2CD102132151190.8741723.286654
50PNA062_PHA_PBMCs_1000cells_S04_S4HLA-ABC31531501.0000002.940199
23PNA062_PHA_PBMCs_1000cells_S04_S4CD3e31331520.9936512.836133
10PNA062_PHA_PBMCs_1000cells_S04_S4CD230931560.9809522.678514

As the most significant signals, we see that CD82 becomes significantly clustered only after PHA stimulation. CD52 is among the strongest after PHA, and it also sits just above the cutoff at rest, so it falls outside this top 10. CD8 is significantly clustered in both conditions.

Differential clustering analysis​

Another question is whether we can observe an increase in clustering of any proteins upon stimulation. We already expect CD82 and CD52 to be among those but we recall that join_count_z is an indication of significance, so this time, we compare degrees of clustering using the log2_ratio.

differential_clustering = calculate_differential_proximity(
clustering_scores,
contrast_column="condition",
reference="Resting",
targets=["PHA stimulated"],
metric="log2_ratio",
min_n_obs=25,
)
differential_clustering["log10_p"] = -np.log10(differential_clustering["p_adjusted"])
sc = plt.scatter(
differential_clustering["median_diff"],
differential_clustering["log10_p"],
c=differential_clustering["tgt_median"],
vmin=-1.0,
vmax=1.0,
cmap="coolwarm"
)
plt.colorbar(sc, label="Median clustering after stimulation")
for _, r in differential_clustering[differential_clustering["log10_p"]>2].iterrows():
plt.text(
r["median_diff"]+0.01,
r["log10_p"]+0.01,
r["marker_1"]
)
plt.tight_layout()
plt.xlabel("Median difference")
plt.ylabel("log10 p value")
plt.title("Differential clustering")
plt.show()

CD52 has increased in clustering after PHA stimulation, as have CD45, CD3e, HLA-ABC, and B2M. CD82’s median clustering is also higher after stimulation, though that shift is not significant at the threshold used for the labels. CD5 and CD27 have decreased in clustering. Let us now look at the clustering distributions for these markers.

sns.boxplot(
clustering_scores[
clustering_scores["marker_1"].isin(["CD3e", "CD5", "CD27", "CD52", "CD82", "CD102", "HLA-ABC", "B2M"])
],
x="marker_1",
y="log2_ratio",
hue="condition",
hue_order=CONDITION_ORDER,
palette=CONDITION_PALETTE,
showfliers=False
)
plt.title("Clustering distributions")
plt.show()

Colocalization analysis​

Another aspect of spatial organization of proteins is whether they colocalize with other proteins. So now, we focus on marker-pairs and their proximity scores. Here, we consider a marker-pair to be significantly colocalized if both markers are expressed in more than 70 cells together and their median proximity z-score is above 3. As above, summarize_proximity_scores reports that median over cells where the pair was detected.

colocalization_scores = proximity_scores[proximity_scores["marker_1"] != proximity_scores["marker_2"]]
sample_colocalization = summarize_proximity_scores(
colocalization_scores,
proximity_metric="join_count_z",
group_vars=["sample", "condition"],
summary_stat="median",
include_missing_obs=False,
)
colocalizatins_to_keep = (
(sample_colocalization["median_join_count_z"] > 3)
& (sample_colocalization["n_cells_detected"] > 70)
)
sample_colocalization[colocalizatins_to_keep].sort_values(
"median_join_count_z", ascending=False
).head(10)
sampleconditionmarker_1marker_2n_cells_detectedn_cellsn_cells_missingpct_detectedmedian_join_count_z
30925PNA062_PHA_PBMCs_1000cells_S04_S4PHA stimulatedCD81CD821313151840.4158737.567983
28379PNA062_PHA_PBMCs_1000cells_S04_S4PHA stimulatedCD53CD82733152420.2317463.944503
43893PNA062_unstim_PBMCs_1000cells_S02_S2RestingCD45RACD45RB114151370.7549673.936450
32547PNA062_PHA_PBMCs_1000cells_S04_S4PHA stimulatedHLA-ABCHLA-DR1033152120.3269843.204766
28230PNA062_PHA_PBMCs_1000cells_S04_S4PHA stimulatedCD52CD5931231530.9904763.134316
26875PNA062_PHA_PBMCs_1000cells_S04_S4PHA stimulatedCD45CD45RB30931560.9809523.100248

We find that CD81/CD82 is by far the most significantly colocalized pair in PHA stimulated CD8 T cells.

Given that there can be several colocalizing marker-pairs, marker graph is one alternative for getting an overview of colocalization patterns in a sample.

significant_colocalizations = sample_colocalization[colocalizatins_to_keep]
resting_colocalizations = significant_colocalizations[significant_colocalizations["condition"] == "Resting"]
pha_colocalizations = significant_colocalizations[significant_colocalizations["condition"] == "PHA stimulated"]
fig, axes = plt.subplots(1, 2)

resting_coloc_graph = nx.from_edgelist(resting_colocalizations[["marker_1", "marker_2"]].to_numpy())
pha_coloc_graph = nx.from_edgelist(pha_colocalizations[["marker_1", "marker_2"]].to_numpy())

nx.draw_networkx(resting_coloc_graph, pos=nx.spring_layout(resting_coloc_graph, k=1.0, seed=0), ax=axes[0])
nx.draw_networkx(pha_coloc_graph, pos=nx.spring_layout(pha_coloc_graph, k=1.0, seed=0), ax=axes[1],)
axes[0].set_title("Resting")
axes[1].set_title("PHA stimulated")
axes[0].grid(False)
axes[1].grid(False)
plt.suptitle("Colocalization pairs")
plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0)

note

Note that the choice of removing marker pairs that are present in fewer components is likely depending on your experimental goals. If you would like to detect marker pairs that change colocalization in only a small subpopulation of cells, you might want to retain these for the downstream analysis.

Differential colocalization analysis​

Let us look at the differential marker-pair colocalizations for markers that have appeared to be colocalizing in at least one sample.

differential_colocalization = calculate_differential_proximity(
colocalization_scores,
contrast_column="condition",
reference="Resting",
targets=["PHA stimulated"],
metric="log2_ratio",
min_n_obs=50,
)
differential_colocalization["log10_p"] = -np.log10(differential_colocalization["p_adjusted"])
sc = plt.scatter(
differential_colocalization["median_diff"],
differential_colocalization["log10_p"],
c=differential_colocalization["tgt_median"],
vmin=-1.0,
vmax=1.0,
cmap="coolwarm"
)
plt.colorbar(sc, label="Median colocalization after stimulation")
for _, r in differential_colocalization[differential_colocalization["log10_p"]>20].iterrows():
plt.text(
r["median_diff"]+0.01,
r["log10_p"]+0.01,
r["marker_1"] + "/" + r["marker_2"]
)
plt.tight_layout()
plt.xlabel("Median difference")
plt.ylabel("log10 p value")
plt.title("Differential colocalization")
plt.show()


plt.show()

We observe several differentially colocalized pairs. Let us look at a clustered dot plot of the pairs with an adjusted p-value below 0.001. Color shows the median difference in log2 ratio, and larger dots mark smaller adjusted p-values.

fig, ax = proximity_heatmap(
differential_colocalization[differential_colocalization["log10_p"] > 3],
value_col="median_diff",
size_col="p_adjusted",
kind="dots",
legend_range=(-1, 1),
legend_title="Median difference",
)
plt.show()

Now let’s take a holistic view of colocalization scores and make a UMAP. We will filter the proteins we want to include to only the ones that had the largest difference in colocalization score between our two samples.

# We only pick proteins which have a high estimated difference
# and that are siginficant at out adjusted p-value threshold
proteins_of_interest = pd.unique(
differential_colocalization[
differential_colocalization["log10_p"]>3
][["marker_1", "marker_2"]].values.ravel("K")
)

# We build a matrix with each colocalization with marker pairs
# in the columns, their pearson Z score as the values, and
# the components in the rows
colocalization_scores.loc[:, "pair"] = (
colocalization_scores["marker_1"]
+"/"
+colocalization_scores["marker_2"]
).values
umap_df = colocalization_scores[
colocalization_scores["marker_1"].isin(proteins_of_interest)
& colocalization_scores["marker_2"].isin(proteins_of_interest)
].pivot(index="component", columns="pair", values="log2_ratio")
umap_df[umap_df.isna()] = 0

# Scale all marker pairs using z-scaling
scaled_data = zscore(umap_df.to_numpy(dtype="float64"), axis=0)
umap_df = pd.DataFrame(
scaled_data,
index=umap_df.index,
columns=umap_df.columns,
)

# Build a UMAP, and re-attach the sample information to it
reducer = umap.UMAP()
embedding = pd.DataFrame(
reducer.fit_transform(umap_df), index=umap_df.index, columns=["UMAP1", "UMAP2"]
)
embedding = embedding.merge(
colocalization_scores[["component", "condition"]], how="left", on="component"
)

# Plot the UMAP
umap_plot = sns.scatterplot(
embedding,
x="UMAP1",
y="UMAP2",
hue="condition",
hue_order=CONDITION_ORDER,
palette=CONDITION_PALETTE,
)
plt.show()

Armed with the powerful insights gleaned from analyzing Proximity Network Assay data, we have delved into the spatial organization of proteins on the cell surface, uncovering how they cluster and interact differently under various conditions. The next tutorial in this series takes us a step further by exploring cell graph visualizations. This exciting approach will allow us to not only see, but truly feel, the dynamic nature of proteins as they cluster and colocalize, offering a deeper understanding of their roles in shaping cellular function.