Skip to main content

Cell Segmentation

Cell segmentation finds local regions, or compartments, whose protein composition differs from the rest of a cell graph. Depending on the experiment, a compartment can be a cell type inside a multiplet, the contact zone between two cells, a membrane fragment acquired by trogocytosis, or debris.

Co-culture experiments are a direct use. When two cell types interact, segmentation separates them on the PNA graph so you can measure how much of each cell is present and which proteins sit in each compartment.

After completing this tutorial, you will be able to:

  • Prepare co-culture data for segmentation: filter, integrate, and annotate the two populations you want to separate.
  • Build cell-type identity weights with cc_protein_weights.
  • Segment a component graph with segment_cell, and summarize patch size, coverage, and patches per cell.
  • Check the protein composition of the resulting compartments, then recluster them and relate T-cell activation to the Raji membrane they carry.
  • Lay a patch out in 3D, and measure how protein abundance changes with distance from a cell:cell interface.
Experimental feature

Cell segmentation is an experimental feature in pixelator and might change in the near future. Use it with caution, and please send feedback to the developers if you run into problems or have suggestions.

Setup​

The analysis uses pixelator to read the PXL files, with the usual Python libraries for clustering and figures.

import urllib.request
from pathlib import Path

import harmonypy as hm
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
import pandas as pd
import plotly.graph_objects as go
import plotly.io as pio
import scanpy as sc
import seaborn as sns
from anndata import AnnData
from pixelator import read_pna as read
import pixelator.plot as pixelator_plot
from pixelator.common.statistics import clr_transformation
from pixelator.pna.analysis import (
cc_protein_weights,
distance_from_node_set,
partition_counts,
segment_cell,
)

pio.renderers.default = "plotly_mimetype+iframe_connected"
sns.set_style("whitegrid")

COMPARTMENT_COLORS = {
"CD8T_alone": "lightgrey",
"Raji_alone": "#A53335",
"interface": "black",
"other": "#dddddd",
}

Point DATA_DIR at the folder where the layout files should be saved.

DATA_DIR = Path("./pna-analysis")

The download fetches the six layout files for this experiment when they are not already in that folder: the 24-hour co-culture, the CAR T control, and the Raji control, from two donors.

BASEURL = "https://pixelgen-technologies-datasets.s3.eu-north-1.amazonaws.com/pna-datasets/v1"
files_to_download = [
"PNA065_CARTcells_Raji_24hrs_1to1_S05_S5.layout.pxl",
"PNA065_CARTcells_S01_S1.layout.pxl",
"PNA065_Raji_S04_S4.layout.pxl",
"PNA066_CARTcells_Raji_24hrs_1to1_S05_S5.layout.pxl",
"PNA066_CARTcells_S01_S1.layout.pxl",
"PNA066_Raji_S04_S4.layout.pxl",
]

DATA_DIR.mkdir(parents=True, exist_ok=True)
for filename in files_to_download:
destination = DATA_DIR / filename
if destination.exists():
continue
urllib.request.urlretrieve(f"{BASEURL}/{filename}", destination)

Load data​

This tutorial uses chimeric antigen receptor (CAR) T cells that were co-cultured for 24 hours with Raji cells, a CD19-positive B-cell line, plus control samples of each population cultured alone. The CAR recognizes CD19, so the T cells can bind and kill Raji cells. CAR T therapy is a powerful approach to cancer, and antigen escape, T-cell exhaustion, and limited effect in solid tumors are still open problems. The arrangement of proteins on the engineered T cell is part of that story. The analysis here follows trogocytosis: during contact, a T cell can tear off a patch of Raji membrane and carry those proteins on its own surface.

That transfer can lower antigen density on the target cell, exhaust the T cell, and in some settings cause T cells to attack each other. PNA measures many of those proteins on the same cells, which makes the patches visible both as extra Raji abundance and as a spatial cluster on the T-cell graph.

The layout files hold the component graphs. Coordinates are computed from those graphs when a figure needs them.

data_files = [
DATA_DIR / "PNA065_CARTcells_Raji_24hrs_1to1_S05_S5.layout.pxl",
DATA_DIR / "PNA066_CARTcells_Raji_24hrs_1to1_S05_S5.layout.pxl",
DATA_DIR / "PNA065_CARTcells_S01_S1.layout.pxl",
DATA_DIR / "PNA066_CARTcells_S01_S1.layout.pxl",
DATA_DIR / "PNA065_Raji_S04_S4.layout.pxl",
DATA_DIR / "PNA066_Raji_S04_S4.layout.pxl",
]
pg_data = read(data_files)
adata = pg_data.adata()


def experimental_group(sample: str) -> str:
name = str(sample)
if "Raji" in name and "CART" in name:
return "coculture"
if "CART" in name:
return "cart"
if "Raji" in name:
return "raji"
raise ValueError(f"Unrecognized sample name: {name}")


def replicate(sample: str) -> int:
name = str(sample)
if "PNA065" in name:
return 1
if "PNA066" in name:
return 2
raise ValueError(f"Unrecognized sample name: {name}")


adata.obs["condition"] = adata.obs["sample"].map(experimental_group)
adata.obs["rep"] = adata.obs["sample"].map(replicate)
adata.obs["condition"] = pd.Categorical(
adata.obs["condition"],
categories=["cart", "coculture", "raji"],
ordered=True,
)
adata
AnnData object with n_obs × n_vars = 2948 × 158
obs: 'n_umi1', 'n_umi2', 'n_edges', 'reads_in_component', 'n_antibodies', 'n_umi', 'isotype_fraction', 'intracellular_fraction', 'tau_type', 'tau', 'sample', 'antibodies', 'average_k_core', 'k_core_1', 'k_core_2', 'k_core_3', 'svd_var_expl_s1', 'svd_var_expl_s2', 'svd_var_expl_s3', 'condition', 'rep'
var: 'antibody_count', 'antibody_pct', 'components', 'control', 'nuclear'
obsm: 'clr', 'log1p'

One object now holds every component from the co-culture and from the two control populations. condition records which sample a cell came from (and rep records the replicate).

Filter data​

Segmentation is easier to interpret on cells that passed the usual quality filters. Here we keep components with at least 10,000 UMIs and an isotype fraction below 0.001. The quality control tutorial explains how to choose those cutoffs on a new dataset.

keep = adata.obs.index[
(adata.obs["isotype_fraction"] < 0.001) & (adata.obs["n_umi"] >= 1e4)
]
adata = adata[keep].copy()
pg_data = pg_data.filter(components=keep.tolist())

Cells with too few molecules, or with a high isotype background, are removed. What follows is clustered on the cells that passed those checks.

Integrate and cluster​

A co-culture mixes cell types that are easy to tell apart in the control samples. Harmony lines the samples up on condition so that the same cell type forms one group across samples. Counts are centered CLR: each protein is compared with the average protein in that cell, then each protein is scaled across cells. Clustering uses the first 10 integrated components. The data integration and cell annotation tutorials cover these steps in more detail.

centered = pd.DataFrame(
clr_transformation(adata.to_df(), axis=1, non_negative=False),
index=adata.obs_names,
columns=adata.var_names,
)
adata.layers["clr_centered"] = centered.to_numpy()
scale = centered.std(axis=0, ddof=1).replace(0, 1.0)
scaled = ((centered - centered.mean(axis=0)) / scale).to_numpy()
adata.obsm["X_pca"] = sc.tl.pca(scaled, random_state=0)
adata.obsm["pca"] = adata.obsm["X_pca"]

harmony_out = hm.run_harmony(adata.obsm["pca"], adata.obs, "condition")
adata.obsm["X_harmony"] = harmony_out.Z_corr

sc.pp.neighbors(
adata, n_neighbors=30, n_pcs=10, use_rep="X_harmony", random_state=0
)
sc.tl.umap(adata, min_dist=0.3, random_state=0)
sc.tl.leiden(adata, random_state=0)
sc.pl.umap(adata, color="condition", legend_loc="right margin")

The UMAP is colored by condition: CAR T alone, the 24-hour co-culture, and Raji alone. After Harmony, cells of the same type from the co-culture and the matching control should sit together. Leiden clustering runs on the same embedding; the next section names those clusters from marker proteins.

Annotate cell types​

A differential test lists the proteins that are higher in each cluster. A protein has to be clearly higher, and present in more than a small fraction of the cells, before it counts. Those proteins decide the label:

  • CD8T when CD8 is the strongest identity marker
  • CD4T when CD4 is the strongest
  • Raji when CD19, CD21, or CD22 is the strongest

A cluster with a single cell is left unlabeled. Segmentation compares two populations at a time, so these labels have to separate CD8 T cells from Raji cells cleanly.

expression = adata.to_df("clr_centered")
tested_clusters = [
str(cluster)
for cluster, n in adata.obs["leiden"].value_counts().items()
if n >= 2
]
sc.tl.rank_genes_groups(
adata,
groupby="leiden",
groups=tested_clusters,
method="wilcoxon",
layer="clr_centered",
pts=True,
use_raw=False,
)

# The labels below use the difference of
# means on centered CLR, which is the same comparison the cutoffs are written for.
group = adata.obs["leiden"].astype(str)
means = expression.groupby(group, observed=True).mean()
counts = group.value_counts()
total = expression.sum(axis=0)
n_cells = len(expression)
difference = pd.concat(
[
pd.DataFrame(
{
"group": cluster,
"names": means.columns,
"difference": (
means.loc[cluster]
- (total - means.loc[cluster] * counts[cluster]) / (n_cells - counts[cluster])
).to_numpy(),
}
)
for cluster in tested_clusters
],
ignore_index=True,
)
diff_exp = sc.get.rank_genes_groups_df(adata, group=None)
diff_exp["group"] = diff_exp["group"].astype(str)
diff_exp = diff_exp.merge(difference, on=["group", "names"])
positive = diff_exp.loc[
(diff_exp["difference"] >= 0.25)
& (diff_exp[["pct_nz_group", "pct_nz_reference"]].max(axis=1) > 0.1)
]
(
diff_exp.sort_values("difference", ascending=False)
.groupby("group", observed=True)
.head(10)
.loc[:, ["group", "names", "difference"]]
)
groupnamesdifference
00CD84.201332
11067CD254.059938
4753CD403.935643
12648CD43.814302
1661CD403.795421
............
11147CD3141.708597
9586HLA-DQ1.658859
3692CD501.641638
11137CD3661.633327
9566CD79a1.631648

100 rows × 3 columns

The table lists the ten strongest proteins per cluster by mean difference on centered CLR. The dot plot in the next section is the main figure for checking labels: identity markers by celltype_condition. Here, look for CD8, CD4, and the Raji markers CD19, CD21, and CD22. If a cluster’s top proteins are a mixture, edit the rule before trusting it.

The label is saved as celltype, and combined with the culture condition. Control samples become alone. The 24-hour samples become coculture.

def celltype_from_markers(markers: pd.DataFrame) -> str:
"""Label one cluster from positive mean differences of identity markers."""
scores = markers.set_index("names")["difference"]

def strongest(names: list[str]) -> float:
found = scores.index.intersection(names)
if len(found) == 0:
return float("-inf")
return float(scores.loc[found].max())

candidates = {
"CD8T": strongest(["CD8"]),
"CD4T": strongest(["CD4"]),
"Raji": strongest(["CD19", "CD21", "CD22"]),
}
label, score = max(candidates.items(), key=lambda item: item[1])
if score == float("-inf"):
return "unassigned"
return label


cluster_labels = {
cluster: celltype_from_markers(markers)
for cluster, markers in positive.groupby("group", observed=True)
}
adata.obs["celltype"] = (
adata.obs["leiden"].astype(str).map(cluster_labels).fillna("unassigned")
)
alone = adata.obs["condition"].isin(["cart", "raji"])
adata.obs["celltype_condition"] = np.where(
alone,
adata.obs["celltype"].astype(str) + "_alone",
adata.obs["celltype"].astype(str) + "_coculture",
)
adata.obs["celltype_condition"] = pd.Categorical(adata.obs["celltype_condition"])
adata.obs["celltype_condition"].value_counts()
sc.pl.umap(adata, color="celltype_condition", legend_loc="right margin")

Each cell now has a type and a condition. Those groups are what the marker check, the proximity check, and the weight matrix use.

A dot plot checks that the labels make biological sense. Dot size is the share of cells in which the protein is above that cell’s own average. Color is the average level.

identity_markers = [
"CD3e",
"CD2",
"CD44",
"CD4",
"CD5",
"CD6",
"CD8",
"CD40",
"CD19",
"CD20",
"CD21",
"CD22",
]
plot_groups = [
"CD4T_alone",
"CD4T_coculture",
"CD8T_alone",
"CD8T_coculture",
"Raji_alone",
"Raji_coculture",
]
plot_adata = adata[adata.obs["celltype_condition"].isin(plot_groups)].copy()
sc.pl.dotplot(
plot_adata,
identity_markers,
groupby="celltype_condition",
categories_order=plot_groups,
layer="clr_centered",
use_raw=False,
cmap="RdBu_r",
smallest_dot=20,
)

T cells from the co-culture carry the Raji proteins CD40, CD19, CD20, CD21, and CD22. T cells cultured alone do not, and Raji cells cultured alone do not carry the T-cell markers. That is the abundance signature of Raji membrane on the T cells.

A density plot shows the same comparison one cell at a time, for a T-cell marker (CD3e) and a Raji marker (CD22).

pixelator_plot.colormap = "turbo"
fig, _ = pixelator_plot.density_scatter_plot(
adata,
marker1="CD22",
marker2="CD3e",
layer="clr_centered",
facet_column="condition",
)
labels = {
"cart": [(2, 4.5, "T cells")],
"coculture": [(2, 5.5, "T cells"), (4, -1, "Raji")],
"raji": [(2, -2, "Raji")],
}
for ax, condition in zip(fig.axes, ["cart", "coculture", "raji"]):
for x, y, label in labels[condition]:
ax.text(
x,
y,
label,
ha="center",
va="center",
bbox={"boxstyle": "round", "facecolor": "white", "alpha": 0.7},
)
plt.show()

In the CAR T control, the T cells are CD3e-high and CD22-low. In the co-culture, those T cells gain CD22. The Raji cells stay CD22-high, and some of them pick up a little CD3e. A little transfer in both directions is what contact looks like before the two cells are separated.

Raji markers clustered on T cells​

Abundance says the Raji proteins are present. Proximity asks whether they sit together. CD40, CD19, CD20, CD21, and CD22 are summed on each T cell, and a joint log2 ratio compares the contacts those proteins actually make with the contacts a random layout of the same counts would make. A cell is marked as potentially patched when that ratio is above 0.3 and it carries more than 100 molecules of these Raji proteins. The T cells cultured alone are the background.

raji_markers = ["CD40", "CD19", "CD20", "CD21", "CD22"]
t_cells = adata.obs.index[adata.obs["celltype"].isin(["CD4T", "CD8T"])].tolist()
proximity = pg_data.filter(components=t_cells).proximity().to_df()
raji_pairs = proximity[
proximity["marker_1"].isin(raji_markers) & proximity["marker_2"].isin(raji_markers)
]
joint = raji_pairs.groupby("component", as_index=False)[
["join_count", "join_count_expected_mean"]
].sum()
joint["log2_ratio"] = np.log2(
np.maximum(joint["join_count"], 1) / np.maximum(joint["join_count_expected_mean"], 1)
)
joint = joint.join(adata.obs[["celltype", "condition"]], on="component")
joint["condition"] = joint["condition"].cat.remove_unused_categories()
umi_count = adata[:, raji_markers].to_df().sum(axis=1).rename("count")
joint = joint.join(umi_count, on="component")
joint["label"] = np.where(
(joint["log2_ratio"] > 0.3) & (joint["count"] > 100),
"Potential cells with patches",
"Background",
)
joint = joint.loc[joint["celltype"].isin(["CD4T", "CD8T"])].copy()
joint["celltype"] = joint["celltype"].cat.remove_unused_categories()
sns.relplot(
data=joint,
x="count",
y="log2_ratio",
hue="label",
col="celltype",
row="condition",
height=3,
aspect=1.2,
s=12,
).set(xscale="log", xlabel="UMI count", ylabel="Joint log2 ratio")
plt.show()

Abundance and proximity agree. Virtually all co-cultured T cells sit above the background, and the T cells cultured alone do not. The Raji proteins on the co-cultured T cells are gathered in patches, which is what segmentation looks for on the graph.

Cell type weights​

Segmentation can compare two populations, and only two. Here those populations are CD8 T cells and Raji cells. cc_protein_weights builds the weight table from the pure control samples, CD8T_alone and Raji_alone. It keeps proteins that are abundant in one population and rare in the other, and drops proteins that are common to both, such as HLA-ABC and CD45. The pure cell populations from the co-culture can stand in for those controls when/if only a subset of the Raji and CD8 T cells are physically interacting. The cells that are not in contact still represent each pure population.

The column names of this table become the compartment labels on the graph.

w = cc_protein_weights(
adata,
group_by="celltype_condition",
population_1="CD8T_alone",
population_2="Raji_alone",
show_plot=True,
random_state=123,
)
w

populationCD8T_aloneRaji_alone
marker_id
CD11b0.0005880.000099
CD11c0.0011760.000097
CD180.0374820.002348
CD80.1384060.000000
TCRab0.0030440.000097
.........
VISTA0.0011360.000359
CD1370.0000690.000794
CD3690.0001520.000928
CD540.0021880.341813
CD3140.0022590.000062

68 rows × 2 columns

The strongest Raji weights are CD54, CD40, CD22, and CD21. The strongest CD8 T-cell weights are CD44, CD8, CD43, CD26, and CD3e. Shared surface proteins were already dropped, so each of these weights belongs to one population.

A usable model has several proteins above 0.1 on each side.

(w > 0.1).sum()
population
CD8T_alone 3
Raji_alone 2
dtype: int64

Both sides clear that bar, with proteins that belong to one population. The weights are ready to score the graph.

Cell segmentation limitations

Segmentation is built for two populations with distinct surface phenotypes. It will not separate similar cells, such as CD4 T cells from CD8 T cells.

Run cell segmentation​

The population where Raji patches are expected is the co-cultured CD8 T cells.

cd8t_cells = adata.obs.index[
adata.obs["celltype_condition"] == "CD8T_coculture"
].tolist()
len(cd8t_cells)
417

That count is the co-cultured CD8 T cells.

Two small helpers read the compartment label and the size of each Raji region. A third loads one component and segments it when a figure needs the labeled graph.

def node_attribute(graph, name: str) -> pd.Series:
return pd.Series(nx.get_node_attributes(graph.raw, name), name=name)


def raji_patch_sizes(graph) -> list[int]:
labels = node_attribute(graph, "compartment")
raji_nodes = labels.index[labels == "Raji_alone"].tolist()
if not raji_nodes:
return []
return sorted(
(
len(nodes)
for nodes in nx.connected_components(graph.raw.subgraph(raji_nodes))
),
reverse=True,
)


def segment_component(component_id: str, detect_interface: bool = False):
component = next(pg_data.filter(components=[component_id]).edgelist().iterator())
return segment_cell(
component.graph,
w,
detect_interface=detect_interface,
keep_largest_comp=False,
min_comp_size=50,
verbose=False,
)

Read the compartment labels from the graph segment_cell returns. Asking the component for its graph again builds a new one, without those labels.

segment_cell scores a local neighborhood around every node with the weight table, then labels the node. detect_interface=False leaves the contact boundary unlabeled, which is what we want while counting patches. keep_largest_comp=False keeps every connected region of a label (instead of only the largest one), allowing one cell to carry more than one Raji patch. min_comp_size=50 filter these patches so based on size by setting the size of the smallest region that is kept. Nodes outside those regions are labeled other.

These graphs are large. This run has 417 co-cultured CD8 T cells, and loading all of their graphs at once takes on the order of 8GB. The loop records patch sizes and compartment counts, then lets each graph go. A larger set of cells should be handled the same way, in batches rather than all at once. A later figure segments a single cell again when it needs the labeled graph.

import gc

patch_rows = []
count_pieces = []
for n_done, component in enumerate(
pg_data.filter(components=cd8t_cells).edgelist().iterator(), start=1
):
graph = segment_cell(
component.graph,
w,
detect_interface=False,
keep_largest_comp=False,
min_comp_size=50,
verbose=False,
)
component_id = component.component_id
patch_rows.extend(
{"component": component_id, "patch": patch_id, "count": size}
for patch_id, size in enumerate(raji_patch_sizes(graph), start=1)
)
counts = partition_counts(graph, partition_column="compartment")
keep = [name for name in ("CD8T_alone", "Raji_alone") if name in counts.index]
if keep:
wide = counts.loc[keep].T
wide.columns = [f"{component_id}_{name}" for name in wide.columns]
count_pieces.append(wide)
del graph
if n_done % 25 == 0:
gc.collect()

gc.collect()
patch_sizes = pd.DataFrame(patch_rows, columns=["component", "patch", "count"])
collapsed = pd.concat(count_pieces, axis=1).fillna(0)
patch_sizes.shape, collapsed.shape
((2787, 3), (158, 816))

Each cell now has a list of Raji patch sizes and a count column for its CD8 body and its Raji regions.

Inspect one graph​

The first check is a single cell, one that carries a large Raji patch. The same cell is drawn later. After segmentation, every node has a compartment: CD8T_alone, Raji_alone, or other.

example_graph = segment_component("2a77aaf817b6376e")
node_attribute(example_graph, "compartment").value_counts()
compartment
CD8T_alone 39989
Raji_alone 5341
other 1853
Name: count, dtype: int64

Most nodes are still the T cell. A smaller set is the Raji compartment, and some nodes stay unlabeled because they never formed a region above the size cutoff.

The next lines turn that Raji compartment into patch sizes and report how much of the graph is left as the T cell.

example_patches = raji_patch_sizes(example_graph)
cd8_nodes = example_graph.raw.number_of_nodes() - sum(example_patches)
print(f"CD8 T cell subgraph size: {cd8_nodes} nodes")
print("Raji patch sizes: " + ", ".join(str(size) for size in example_patches))
CD8 T cell subgraph size: 41842 nodes
Raji patch sizes: 5279, 62

This cell carries one or more Raji regions, and the rest of the graph is the CD8 body. The same summary, across every co-cultured CD8 T cell, is what the next plots show.

Patch sizes​

count is the number of nodes in one Raji patch. fraction is that count divided by the molecule count of the original cell, so it is the share of the cell graph inside the patch. A patch that reaches about 1% of the cell is large enough to see; smaller ones are kept in the table but matter less.

patch_sizes = patch_sizes.join(adata.obs["n_umi"], on="component")
patch_sizes["fraction"] = patch_sizes["count"] / patch_sizes["n_umi"]
patch_sizes.head()
componentpatchcountn_umifraction
065411ae564cae31b1156480910.003244
165411ae564cae31b2136480910.002828
265411ae564cae31b388480910.001830
365411ae564cae31b463480910.001310
4ca1b654027adba1015343912470.058555

Each row is one retained Raji patch on one cell.

The size distribution is easier to read on a log axis, because a few patches are much larger than the rest.

sns.histplot(
patch_sizes,
x="count",
bins=30,
log_scale=True,
color="lightgrey",
edgecolor="black",
)
plt.xlabel("Patch size (nodes, log10)")
plt.ylabel("Number of patches")
plt.show()

Most patches are small. The long tail is the patches large enough to see on a layout, on the order of 1% of the cell or more.

The next plot adds those patches up within each cell. Cells with no retained patch are included as zero, so the histogram is a picture of every co-cultured CD8 T cell.

coverage = (
patch_sizes.groupby("component")["fraction"].sum().reindex(cd8t_cells, fill_value=0)
)

sns.histplot(x=coverage, bins=30, color="lightgrey", edgecolor="black")
plt.xlabel("Combined patch size")
plt.ylabel("Number of CD8 T cells")
plt.show()

Most of each cell is still the T cell. The Raji coverage is often a few percent to a few tens of percent, and a share of cells have no retained patch at all.

The number of patches per cell is the last summary. The size cutoff has already removed the tiniest regions.

n_patches = patch_sizes.groupby("component").size().reindex(cd8t_cells, fill_value=0)
n_patch_distribution = n_patches.value_counts(normalize=True).sort_index()
sns.barplot(
x=n_patch_distribution.index.astype(str),
y=n_patch_distribution.to_numpy(),
color="lightgrey",
edgecolor="black",
)
plt.xlabel("Number of detected patches")
plt.ylabel("Proportion of CD8 T cells")
plt.title("Raji patches in CD8 T cells")
plt.show()

Most cells have none, one, or a few Raji patches. A longer tail of cells carries more.

Compartment protein composition​

The size summaries describe how much membrane moved. partition_counts asks what that membrane is made of. The loop stored those sums, one column per CD8 body or Raji region, so the graphs themselves did not have to stay in memory.

# Recorded in the segmentation loop, one column per kept compartment.
collapsed.shape
(158, 816)

Each column is one compartment. A Raji patch should be enriched for the Raji side of the weight table, and the remaining CD8 body for the T-cell side.

Some mixing at the edge is expected. The score uses a local neighborhood, so a node on the boundary shares neighbors with the other cell type. The heatmap keeps proteins with a weight above 0.01, rescales each compartment so those proteins sum to 1, and groups compartments and proteins by that composition.

from matplotlib.patches import Patch

markers_keep = w.index[(w > 0.01).any(axis=1)]
proportions = collapsed.T
proportions = proportions.loc[:, proportions.columns.intersection(markers_keep)]
proportions = proportions.div(proportions.sum(axis=1).replace(0, np.nan), axis=0).fillna(0)

# Diverging blue–yellow–red for composition, with a teal and salmon strip for cell type.
cell_type_colors = {"CD8T": "#00DAE0", "Raji": "#FF9289"}
cell_type = pd.Series(
np.where(proportions.index.str.contains("Raji_alone"), "Raji", "CD8T"),
index=proportions.index,
name="cell_type",
)
grid = sns.clustermap(
proportions,
method="ward",
row_colors=cell_type.map(cell_type_colors),
yticklabels=False,
xticklabels=True,
cmap="RdYlBu_r",
)
grid.ax_heatmap.legend(
handles=[
Patch(facecolor=cell_type_colors[label], edgecolor="#999999", label=label)
for label in ("CD8T", "Raji")
],
title="cell_type",
loc="upper left",
bbox_to_anchor=(1.02, 1),
frameon=False,
borderaxespad=0,
)
plt.show()

The compartments separate by cell type. Raji regions carry the Raji proteins, and CD8 regions carry the T-cell proteins. Boundary mixing shows up as a thin contamination, and the two groups stay separate.

Re-analyze segmented compartments​

The compartment counts are ordinary abundance profiles, so they can be clustered on their own. A molecule-rank plot compares the size of the Raji patches with the size of the CD8 bodies they came from. The dashed line is the 2,000-molecule cutoff used next. Normal and Low count the compartments on each side of it.

from pixelator.pna.plot import molecule_rank_plot

segmented = AnnData(collapsed.T.astype(float))
segmented.obs["n_umi"] = np.asarray(segmented.X).sum(axis=1)
segmented.obs["cell_type"] = np.where(
segmented.obs_names.str.contains("Raji_alone"), "Raji", "CD8T"
)
segmented.obs["cell_type"] = segmented.obs["cell_type"].astype("category")
segmented.obs["original_component"] = (
segmented.obs_names.str.removesuffix("_Raji_alone").str.removesuffix("_CD8T_alone")
)
_fig, ax = molecule_rank_plot(segmented.obs, group_by="cell_type")
n_umi_min = 2000
ax.axhline(n_umi_min, linestyle="--", color="red", linewidth=1)
n_umi = segmented.obs["n_umi"].to_numpy()
n_low = int((n_umi < n_umi_min).sum())
n_normal = int((n_umi >= n_umi_min).sum())
# Geometric means sit at the visual center of each band on the log axis.
ax.text(
1.5,
np.sqrt(n_umi_min * n_umi.max()),
f"Normal: {n_normal}",
color="#496389",
ha="left",
va="center",
)
if n_low:
ax.text(
1.5,
np.sqrt(n_umi.min() * n_umi_min),
f"Low: {n_low}",
color="#f94526",
ha="left",
va="center",
)
plt.show()

Many patches are small. The clustering keeps compartments with at least 2,000 molecules, so each one has enough counts to support a marker profile. The same centered CLR and scaling used on the whole cells is used here, on the first 6 components.

segmented = segmented[segmented.obs["n_umi"] >= 2000].copy()
centered = pd.DataFrame(
clr_transformation(segmented.to_df(), axis=1, non_negative=False),
index=segmented.obs_names,
columns=segmented.var_names,
)
segmented.layers["clr_centered"] = centered.to_numpy()
scale = centered.std(axis=0, ddof=1).replace(0, 1.0)
scaled = ((centered - centered.mean(axis=0)) / scale).to_numpy()
segmented.obsm["X_pca"] = sc.tl.pca(scaled, random_state=0)
sc.pp.neighbors(
segmented, n_neighbors=30, n_pcs=6, use_rep="X_pca", random_state=0
)
sc.tl.umap(segmented, min_dist=0.3, random_state=0)
sc.tl.leiden(segmented, random_state=0, resolution=0.2)
sc.pl.umap(segmented, color="leiden", legend_loc="right margin")

Each point is one compartment. The legend names the cluster the plots below refer to. One side of the map is the Raji-rich compartments. The other side is the CD8 compartments.

Compare segmented cells with the original CD8 T cells​

The left panel is the co-cultured CD8 T cells before segmentation. Each cell is one point, and that cloud is positive for both CD3e and CD22 because the Raji patch is still part of the cell. The right panel is the compartments after segmentation, which should split the cloud into a CD3e-high CD8 body and a CD22-high Raji patch.

def draw_gating_panel(adata):
fig, _ = pixelator_plot.density_scatter_plot(
adata,
marker1="CD22",
marker2="CD3e",
layer="clr_centered",
show_marginal=False,
)
scatter = max(
(ax for ax in fig.axes if ax.collections),
key=lambda ax: max(len(coll.get_offsets()) for coll in ax.collections),
)
return fig, scatter


def place_gating_panel(src_ax, dst_ax, title, labels):
points = max(src_ax.collections, key=lambda coll: len(coll.get_offsets()))
offsets = np.asarray(points.get_offsets())
dst_ax.scatter(
offsets[:, 0],
offsets[:, 1],
c=points.get_facecolors(),
s=points.get_sizes(),
linewidths=0,
rasterized=True,
)
dst_ax.axhline(0, color="black", linewidth=1, linestyle="--")
dst_ax.axvline(0, color="black", linewidth=1, linestyle="--")
dst_ax.set_xlim(src_ax.get_xlim())
dst_ax.set_ylim(src_ax.get_ylim())
dst_ax.set_xlabel(src_ax.get_xlabel())
dst_ax.set_ylabel(src_ax.get_ylabel())
dst_ax.set_title(title)
for x, y, label in labels:
dst_ax.text(
x,
y,
label,
ha="center",
va="center",
bbox={"boxstyle": "round", "facecolor": "white", "alpha": 0.7},
)


cd8_coculture = adata[adata.obs["celltype_condition"] == "CD8T_coculture"].copy()
original_fig, original_ax = draw_gating_panel(cd8_coculture)
segmented_fig, segmented_ax = draw_gating_panel(segmented)

fig, axes = plt.subplots(1, 2, figsize=(12, 5))
place_gating_panel(
original_ax,
axes[0],
"CD8 T cells before segmentation",
[(2, 5, "Patched CD8T")],
)
place_gating_panel(
segmented_ax,
axes[1],
"Compartments after segmentation",
[(0, 5, "'pure' CD8T"), (3, 2.5, "Raji patch")],
)
plt.close(original_fig)
plt.close(segmented_fig)
fig.tight_layout()
plt.show()

The split is visible. The original cloud, positive for both markers, becomes a CD3e-high CD8 body and a CD22-high Raji patch.

Profile and annotate segmented compartments​

The clusters still need names. The heatmap shows, for each cluster, the proteins that are higher there than in the other clusters. Compartments are grouped by cluster. Color is the centered CLR after each protein is scaled across compartments and the extremes are clipped. Zero is the average for that protein, so red is high and blue is low.

tested_clusters = [
str(cluster)
for cluster, n in segmented.obs["leiden"].value_counts().items()
if n >= 2
]
sc.tl.rank_genes_groups(
segmented,
groupby="leiden",
groups=tested_clusters,
method="wilcoxon",
layer="clr_centered",
use_raw=False,
)
segmented.layers["clr_scaled"] = np.array(segmented.layers["clr_centered"], copy=True)
sc.pp.scale(segmented, layer="clr_scaled", max_value=2.5)
sc.pl.rank_genes_groups_heatmap(
segmented,
groups=tested_clusters,
n_genes=10,
groupby="leiden",
layer="clr_scaled",
use_raw=False,
cmap="RdBu_r",
vmin=-2.5,
vmax=2.5,
vcenter=0,
show_gene_labels=True,
dendrogram=False,
swap_axes=True,
)

One block is high for CD22, CD19, CD20, CD21, and the HLA and adhesion proteins that travel with them. That is the Raji patch. The other blocks are CD8 compartments.

A Raji patch is a membrane fragment, so the clusters that carry the Raji marker block should have fewer molecules than the CD8 compartments.

sc.pl.violin(
segmented,
"n_umi",
groupby="leiden",
rotation=45,
ylabel="Number of UMIs",
)

The clusters that carry the Raji marker block are the smaller ones. A few patches are much larger than the rest.

CD25 and CD279 separate the CD8 compartments into activation states. The level is centered CLR, so zero is the average protein in that compartment.

  • non-activated: CD25 low, CD279 low
  • activated: CD25 high, CD279 low
  • exhausted: CD25 high, CD279 high
sc.pl.violin(
segmented,
["CD25", "CD279"],
groupby="leiden",
layer="clr_centered",
use_raw=False,
rotation=45,
ylabel="Expression Level",
)

Three CD8 patterns are visible: one group high for both markers, one high for CD25 only, and one low for both. The Raji patch sits apart from those three. The labels below follow these patterns.

Each compartment is labeled from its own centered CLR, and the cluster takes the majority label. The lead is CD22 minus the higher of CD3e and CD8. A lead above 0.5 is a Raji patch. Every other compartment is CD8. On those, CD25 above 1 and CD279 above 0 is exhausted, CD25 above 1 with CD279 at or below 0 is activated, and the rest are non-activated. The table reports the cluster means and the fraction of compartments that carry the majority label.

markers = segmented.to_df("clr_centered")[["CD22", "CD3e", "CD8", "CD25", "CD279"]]
lead = markers["CD22"] - markers[["CD3e", "CD8"]].max(axis=1)
call = pd.Series("CD8T non-activated", index=markers.index)
is_raji = lead > 0.5
is_cd8 = ~is_raji
call.loc[is_raji] = "Raji patch"
call.loc[is_cd8 & (markers["CD25"] > 1) & (markers["CD279"] <= 0)] = "CD8T activated"
call.loc[is_cd8 & (markers["CD25"] > 1) & (markers["CD279"] > 0)] = "CD8T exhausted"
segmented.obs["cell_call"] = call

label_order = [
"Raji patch",
"CD8T non-activated",
"CD8T activated",
"CD8T exhausted",
]
rows = []
for cluster, labels in segmented.obs.groupby("leiden", observed=True)["cell_call"]:
counts = labels.value_counts()
tied = counts[counts == counts.max()].index
label = next(name for name in label_order if name in tied)
rows.append((cluster, label, float((labels == label).mean())))
summary = pd.DataFrame(rows, columns=["leiden", "celltype", "fraction"]).set_index("leiden")
state_labels = summary["celltype"]
segmented.obs["celltype"] = segmented.obs["leiden"].map(state_labels)
segmented.obs["celltype"] = pd.Categorical(
segmented.obs["celltype"],
categories=label_order,
)
sc.pl.umap(segmented, color="celltype", legend_loc="on data", legend_fontsize=8)
markers.groupby(segmented.obs["leiden"], observed=True).mean().join(summary)

CD22CD3eCD8CD25CD279celltypefraction
leiden
02.8011382.0289522.1207482.161245-0.717250Raji patch0.547401
11.4010893.6240324.0006414.3832310.719243CD8T exhausted0.631841
20.3954654.3860704.1584452.498086-1.497957CD8T activated0.731884
3-1.0059504.4443982.9184370.385185-1.242883CD8T non-activated0.746835

The UMAP is the same map as before, now named. Read the table next to it. A Raji patch has CD22 above CD3e and CD8. The fraction column shows how many of a cluster’s compartments actually received that label. In this run the Raji name is the narrow one: a little over half of that cluster received it. Among the CD8 clusters, CD279 above zero is the exhausted group, a high CD25 with low CD279 is the activated group, and low CD25 with CD22 below zero is the non-activated group. Those three names are carried by a clear majority of their compartments.

T-cell state and patches​

The Raji compartments are similar to each other, so this dataset does not support a link between a Raji phenotype and the CD8 states. Patches labeled Raji are kept as one group. What follows is the CD8 compartments only: how many Raji patches each activation state carries, and how much of the original graph those patches cover.

cd8_states = ["CD8T non-activated", "CD8T activated", "CD8T exhausted"]
segmented_cd8 = segmented[segmented.obs["celltype"].isin(cd8_states)].copy()
patches_per_component = patch_sizes.groupby("component").size()
segmented_cd8.obs["n_patches"] = (
segmented_cd8.obs["original_component"].map(patches_per_component).fillna(0)
)
segmented_cd8.obs["pct_patches"] = (
segmented_cd8.obs["original_component"].map(coverage).fillna(0)
)

sc.pl.violin(
segmented_cd8,
["n_patches", "pct_patches"],
groupby="celltype",
order=cd8_states,
rotation=30,
ylabel=[
"Number of detected Raji patches",
"Fraction of graph in Raji patches",
],
)

Activated CD8 T cells carry more Raji patches than non-activated cells, including a long tail of cells with many patches. Exhausted cells cover a larger share of the cell graph. That fits ordinary target engagement: activation prepares the T cell to bind Raji cells, so more contact leaves more membrane behind. Chronic antigen exposure is what drives CD279 up, and a larger patch burden is a spatial correlate of that prolonged contact. The patch is a record of the interaction that, when it persists, contributes to exhaustion.

Visualize compartments​

A layout is an abstract picture of the graph, not a microscope image of the cell. Patches vary in size and shape, and a patched graph is often more distorted than an isolated cell, because the layout follows local connectivity and that connectivity is less even where a patch sits. A clear example usually has to be picked by hand. The coordinates below are computed from each component graph with layouts(), the same on-the-fly layout as the cell visualization tutorial. Join them to compartment on the layout index, which is the node id, and color the points by compartment.

A patch is easier to see when it is a substantial fraction of the cell. The two cells below were picked from the patch table for that reason: the cell already checked above, which carries one large patch, and a second cell with two separate Raji regions. Coordinates come from a spectral 3D layout of each graph.

two_patch_graph = segment_component("441ef31c0ee76b09")


def component_layout(
component_id: str, graph, algorithm: str = "spectral_3d"
) -> pd.DataFrame:
layout = (
pg_data.filter(components=[component_id])
.layouts(algorithm=algorithm, add_marker_counts=False, random_seed=0)
.to_df()
)
layout["index"] = layout["index"].astype(str)
compartments = node_attribute(graph, "compartment")
compartments.index = compartments.index.astype(str)
return layout.merge(compartments, left_on="index", right_index=True, how="left")


one_patch_layout = component_layout("2a77aaf817b6376e", example_graph, "spectral_3d")
two_patch_layout = component_layout("441ef31c0ee76b09", two_patch_graph, "spectral_3d")

A flat view of the one-patch cell. Grey is the CD8 body. Red is the Raji compartment. Unlabeled nodes are left out so the patch is easier to see.

sns.scatterplot(
data=one_patch_layout[one_patch_layout["compartment"] != "other"],
x="x",
y="y",
hue="compartment",
palette=COMPARTMENT_COLORS,
s=8,
)
plt.title("One large Raji patch")
plt.gca().set_aspect("equal", adjustable="datalim")
plt.show()

The Raji compartment is one compact region on an otherwise T-cell graph, which is what a transferred membrane patch looks like.

The same cell in 3D. The coordinates are a spectral layout of the graph.

def plot_compartments(layout: pd.DataFrame, title: str) -> go.Figure:
plotted = layout[layout["compartment"] != "other"]
order = [name for name in COMPARTMENT_COLORS if name != "other"]
extra = [name for name in plotted["compartment"].unique() if name not in order]
traces = []
for compartment in [*order, *extra]:
part = plotted[plotted["compartment"] == compartment]
if part.empty:
continue
traces.append(
go.Scatter3d(
x=part["x"].to_numpy().round(3),
y=part["y"].to_numpy().round(3),
z=part["z"].to_numpy().round(3),
mode="markers",
name=str(compartment),
hoverinfo="name",
showlegend=False,
marker=dict(
size=2,
color=COMPARTMENT_COLORS.get(compartment, "lightgrey"),
),
)
)
fig = go.Figure(data=traces)
fig.update_layout(title=title)
return fig
plot_compartments(one_patch_layout, "One large Raji patch")

Turning the graph makes the boundary of that single patch easier to follow than the flat view.

The second example cell carries two separate Raji regions.

plot_compartments(two_patch_layout, "Two large Raji patches")

Two red regions sit apart on the same T cell. A cell can take membrane from more than one contact, or from more than one piece of the same contact.

Doublets​

The patches above are fragments on a T cell. Early or stable contact looks different: the two cells are still intact and share a boundary. A component whose Raji labels cover a large fraction of the graph is a candidate for that doublet. Separating a heavily patched T cell from a true conjugate is still a judgment call. If the question is killing and membrane transfer, keep the patches. If the question is the immune synapse, keep the conjugates and label the boundary.

detect_interface=True marks nodes that sit on an edge between the two retained cell types as interface. This call loads that component on its own, so the patch summaries from the loop stay as they were.

doublet_component = next(pg_data.filter(components=["1fd610a2a105a2d4"]).edgelist().iterator())
doublet_graph = segment_cell(
doublet_component.graph,
w,
detect_interface=True,
)
node_attribute(doublet_graph, "compartment").value_counts()
compartment
CD8T_alone 47785
Raji_alone 29847
interface 3559
other 1251
Name: count, dtype: int64

Both cell bodies are present, and a third set of nodes is the interface, the nodes that sit on an edge between them.

The layout uses a coarsened embedding, which keeps two cells that share a boundary as two bodies. It is slower than a spectral layout, and it is the layout to use for a conjugate.

doublet_layout = component_layout(
"1fd610a2a105a2d4", doublet_graph, "coarsened_pmds_3d"
)
plot_compartments(doublet_layout, "T cell:Raji doublet")

Two intact bodies share a boundary. That is a conjugate: both cells are still whole.

partition_counts sums the protein counts in each of those three compartments. Each row is scaled to its own total, and proteins that never rise above a small share are left out.

doublet_counts = partition_counts(doublet_graph, partition_column="compartment")
order = [
name
for name in ("Raji_alone", "interface", "CD8T_alone")
if name in doublet_counts.index
]
doublet_counts = doublet_counts.loc[order]
doublet_props = doublet_counts.div(doublet_counts.sum(axis=1), axis=0)
doublet_props = doublet_props.loc[:, doublet_props.max(axis=0) > 0.01]
doublet_props.index.name = None
grid = sns.clustermap(
doublet_props,
row_cluster=False,
method="ward",
cmap="RdYlBu_r",
figsize=(12, 4),
linewidths=0.4,
linecolor="#E6E6E6",
)
grid.ax_heatmap.set_ylabel("")
plt.setp(
grid.ax_heatmap.get_yticklabels(),
rotation=0,
ha="left",
va="center",
)
plt.setp(grid.ax_heatmap.get_xticklabels(), rotation=90, ha="center", va="top")
grid.fig.subplots_adjust(right=0.82, bottom=0.28)
grid.ax_cbar.set_position((0.02, 0.42, 0.015, 0.38))
plt.show()

The Raji body carries the Raji markers, the T-cell body carries the CD8 markers, and the interface carries a mixture of both. That mixture is the contact zone.

Distance from the interface​

distance_from_node_set writes the hop distance from the interface nodes onto the graph. Signing it, negative on the Raji side and positive on the CD8 side, turns the boundary into an axis through the conjugate. The histogram is that axis. The red lines mark the window used for the abundance curves, because bands far from the boundary contain few nodes and the percentages there are noisy.

interface_nodes = node_attribute(doublet_graph, "compartment")
interface_nodes = interface_nodes.index[interface_nodes == "interface"].tolist()
doublet_graph = distance_from_node_set(doublet_graph, seed_nodes=interface_nodes)

spatial = pd.concat(
[
node_attribute(doublet_graph, "compartment"),
node_attribute(doublet_graph, "distance_from_seed"),
],
axis=1,
)
spatial = spatial.dropna(subset=["distance_from_seed"]).copy()
spatial["distance_from_interface"] = np.where(
spatial["compartment"].eq("Raji_alone"),
-spatial["distance_from_seed"],
spatial["distance_from_seed"],
)

sns.histplot(
spatial,
x="distance_from_interface",
binwidth=1,
color="lightgrey",
edgecolor="black",
)
plt.axvline(0, linestyle="--", color="black")
plt.axvline(-9, linestyle="--", color="red")
plt.axvline(10, linestyle="--", color="red")
plt.xlabel("Raji <---- interface ----> CD8 T")
plt.ylabel("Number of nodes")
plt.show()

The histogram has two peaks, one on each side of the boundary. Those peaks are the two cell bodies. The dashed line at zero is the interface, and the red lines are the window used next, from −9 hops on the Raji side to 10 hops on the CD8 side.

Inside that window, protein counts are summed in each band and turned into a share of the molecules there. CD40 stands for the Raji side and CD44 for the CD8 side.

spatial_core = spatial.loc[spatial["distance_from_interface"].between(-9, 10)].copy()
spatial_core.index = spatial_core.index.astype(str)

marker_counts = doublet_graph.node_marker_counts.copy()
marker_counts.index = marker_counts.index.astype(str)
joined = spatial_core.join(marker_counts, how="inner")
by_distance = joined.groupby("distance_from_interface")[list(marker_counts.columns)].sum()
abundance = by_distance.div(by_distance.sum(axis=1).replace(0, np.nan), axis=0)
selected_markers = [marker for marker in ("CD40", "CD44") if marker in abundance.columns]
plot_df = (
abundance[selected_markers]
.reset_index()
.melt(id_vars="distance_from_interface", var_name="marker", value_name="pct")
)
sns.lineplot(
data=plot_df,
x="distance_from_interface",
y="pct",
hue="marker",
marker="o",
)
plt.axvline(0, linestyle="--", color="black")
plt.xlabel("Raji <---- interface ----> CD8 T")
plt.ylabel("Fraction of UMI counts")
plt.show()

CD40 is high on the Raji side and falls toward the T cell. CD44 is high on the CD8 side and falls toward the Raji cell. The boundary is where the two curves meet.

One conjugate is only an illustration. Repeating this across many doublets is what turns a single boundary into a pattern you can trust.

In this tutorial a co-culture went from whole-cell abundance to compartments on the cell graph:

  • Quality control, Harmony integration, and annotation separate the samples into the two populations segmentation can compare.
  • Proximity checks that the extra Raji proteins sit together before the graph is cut.
  • cc_protein_weights turns the pure controls into a weight for each protein.
  • segment_cell labels compartments on the cell graph.
  • Patch size, coverage, and patches per cell describe how much Raji membrane each T cell carries.
  • partition_counts checks that a Raji compartment is actually made of Raji protein.
  • The segmented compartments can be clustered on their own. That separates the Raji patch from the CD8 states, and ties activation and exhaustion to how much membrane a cell still carries.
  • layouts() shows a patch as a region on the cell, and a doublet as two cells sharing a boundary.
  • distance_from_node_set places proteins along that boundary.

The same workflow applies to other pairs of populations whose surface proteins are distinct.