-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBCR_GEX_Tutorial_Part2.Rmd
More file actions
1974 lines (1620 loc) · 78.5 KB
/
BCR_GEX_Tutorial_Part2.Rmd
File metadata and controls
1974 lines (1620 loc) · 78.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: "BCR + GEX Integration Tutorial -- Part 2: Seurat Analysis and Annotation"
subtitle: "From Cell Ranger GEX output to an annotated B cell Seurat object"
author: "Nachi Nathan"
date: "`r Sys.Date()`"
output:
html_document:
toc: true
toc_float: true
toc_depth: 3
theme: flatly
code_folding: show
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(
echo = TRUE,
message = TRUE,
warning = FALSE
)
```
***
# Prerequisites
Before running this part, the following must be in place.
**Input files required**
| File | Where it comes from |
|------|-------------------|
| `P1_LN_bcr_data.tsv` | Part 1 output, or download from Zenodo: https://zenodo.org/records/20324083 |
| `P1_PT_bcr_data.tsv` | Part 1 output, or download from Zenodo: https://zenodo.org/records/20324083 |
| `P1_LN_sample_filtered_feature_bc_matrix.h5` | Cell Ranger GEX output, or download from Zenodo: https://zenodo.org/records/20323951
| `P1_PT_sample_filtered_feature_bc_matrix.h5` | Cell Ranger GEX output, or download from Zenodo: https://zenodo.org/records/20323951
**R packages required**
```r
install.packages(c("dplyr", "ggplot2", "data.table", "tibble",
"viridis", "scales", "patchwork", "pheatmap"))
# Seurat v5
install.packages("Seurat")
# Optional but recommended for faster DEG computation
install.packages("devtools")
devtools::install_github("immunogenomics/presto")
```
**R version:** This tutorial was developed under R 4.3 with Seurat v5. Seurat v4
will not work with the `IntegrateLayers()` workflow used in Step 6.
***
# Overview
This part covers the complete single-cell GEX analysis pipeline, from loading
raw count matrices through to a fully annotated Seurat object. It runs in
sequence -- each step feeds directly into the next -- and produces a single
output file at the end: `integrated_S7_annotated.rds`.
The steps are:
1. **GEX QC** -- load `.h5` count matrices, inspect quality metrics, filter
low-quality cells.
2. **Doublet removal** -- keep only CD79A-positive cells and remove B cell /
non-B cell doublets.
3. **Add BCR metadata** -- join the BCR TSV from Part 1 to each Seurat object
by barcode matching.
4. **Solo GEX analysis** -- per-sample normalization, HVG selection (with IG/TCR
gene exclusion), PCA, clustering, UMAP, BCR overlay.
5. **Integration** -- RPCA batch correction across samples, joint UMAP,
joint clustering.
6. **Cluster annotation** -- DotPlot, BCR metadata, DEG analysis, final label
assignment.
***
# Setup
Set these variables before running anything else. All paths downstream are
derived from these.
```{r setup-session}
suppressPackageStartupMessages({
library(Seurat)
library(Matrix)
library(dplyr)
library(data.table)
library(tibble)
library(ggplot2)
library(viridis)
library(scales)
library(patchwork)
library(pheatmap)
})
# Root directory -- each sample has its own subfolder here
ROOT_DIR <- "C:/Users/natha/OneDrive/Documents/Immcantation/BCR_Tutorial/Github"
# RDS output directory -- all Seurat objects are written here
RDS_DIR <- file.path(ROOT_DIR, "RDS_Objects")
if (!dir.exists(RDS_DIR)) dir.create(RDS_DIR, recursive = TRUE)
# Sample definitions
samples <- list(
P1_LN = list(
sample_id = "P1_LN",
h5 = file.path(ROOT_DIR, "P1_LN/P1_LN_sample_filtered_feature_bc_matrix.h5"),
bcr_tsv = file.path(ROOT_DIR, "P1_LN/Output/P1_LN_bcr_data.tsv"),
output_dir = RDS_DIR
),
P1_PT = list(
sample_id = "P1_PT",
h5 = file.path(ROOT_DIR, "P1_PT/P1_PT_sample_filtered_feature_bc_matrix.h5"),
bcr_tsv = file.path(ROOT_DIR, "P1_PT/Output/P1_PT_bcr_data.tsv"),
output_dir = RDS_DIR
)
)
message("Ready. Samples: ", paste(names(samples), collapse = ", "))
```
***
# Step 2: GEX QC and Filtering
## 2.1 QC thresholds
The thresholds below are applied uniformly to all samples. Inspect the violin
plots in section 2.3 carefully before accepting them for your own data -- the
right values depend on the tissue and library quality.
| Parameter | Value | What it removes |
|-----------|-------|----------------|
| `min_features` | 250 | Empty droplets with almost no detected genes |
| `max_features` | 6,500 | Likely doublets with abnormally high gene counts |
| `min_UMI` | 500 | Low-quality or empty droplets |
| `max_UMI` | 35,000 | Likely doublets with abnormally high UMI counts |
| `filter_mt` | 10% | Damaged or dying cells |
When a cell is damaged or dying, cytoplasmic mRNA leaks out while mitochondrial
transcripts remain protected inside the organelle, producing a characteristic
signature of high mt% alongside low gene and UMI counts. A threshold of 10% is
appropriate for lymphoid tissue. For tumor samples with many metabolically active
cells, a slightly higher threshold may be warranted -- always inspect the
distribution first.
```{r thresholds}
min_features <- 250
max_features <- 6500
min_UMI <- 500
max_UMI <- 35000
filter_mt <- 10
mito_pattern <- "^MT-" # "^MT-" for human, "^mt-" for mouse
min_cells_gene <- 5 # genes detected in fewer cells than this are dropped
```
## 2.2 Load count matrices and create Seurat objects
We load the `.h5` count matrix for each sample and create a Seurat object.
Mitochondrial percentage is calculated immediately after loading, before any
filtering, so we have the full distribution to inspect.
We also suffix every barcode with the sample name at this stage. Cell Ranger
barcodes are not unique across samples -- both P1_LN and P1_PT contain cells
called `ACGT...TGCA-1` -- and adding the sample ID prevents collisions when
samples are merged later. This matches the barcode suffixing done on the BCR
side in Part 1.
```{r load-counts}
seurat_list <- list()
for (s in samples) {
message("Loading: ", s$sample_id)
if (!file.exists(s$h5)) {
stop("H5 file not found for ", s$sample_id, ":\n ", s$h5,
"\nCheck that the path is correct.")
}
counts <- Read10X_h5(s$h5)
if (is.list(counts)) counts <- counts[["Gene Expression"]]
obj <- CreateSeuratObject(
counts = counts,
project = s$sample_id,
min.cells = min_cells_gene,
min.features = 0
)
obj[["percent.mt"]] <- PercentageFeatureSet(obj, pattern = mito_pattern)
obj <- RenameCells(obj, new.names = paste0(colnames(obj), "_", s$sample_id))
message(" Cells: ", ncol(obj), " | Genes: ", nrow(obj))
seurat_list[[s$sample_id]] <- obj
}
```
The two samples loaded as expected:
| Sample | Cells | Genes |
|--------|-------|-------|
| P1_LN | 6,061 | 18,521 |
| P1_PT | 8,067 | 19,889 |
P1_PT has more cells and a slightly larger detected transcriptome, consistent
with the greater cellular complexity of tumor tissue.
## 2.3 Inspect QC metrics before filtering
Look at the violin plots carefully before proceeding. You are looking for a
unimodal distribution of `nFeature_RNA` with a lower tail of empty droplets and
possibly an upper tail of doublets; `percent.mt` clustered low with a tail of
damaged cells; and a linear relationship in the UMI vs genes scatter, with
cells falling well above the line being candidate doublets.
```{r qc-plots-pre, fig.width=10, fig.height=4}
for (s_id in names(seurat_list)) {
obj <- seurat_list[[s_id]]
print(
VlnPlot(obj,
features = c("nFeature_RNA", "nCount_RNA", "percent.mt"),
pt.size = 0.1,
ncol = 3) &
ggplot2::labs(title = paste0(s_id, " -- QC metrics (pre-filter)"))
)
print(FeatureScatter(obj, feature1 = "nCount_RNA", feature2 = "percent.mt") +
ggplot2::ggtitle(paste0(s_id, " -- UMI vs mt%")))
print(FeatureScatter(obj, feature1 = "nCount_RNA", feature2 = "nFeature_RNA") +
ggplot2::ggtitle(paste0(s_id, " -- UMI vs genes detected")))
}
```
```{r qc-summary-pre}
pre_stats <- lapply(names(seurat_list), function(s_id) {
obj <- seurat_list[[s_id]]
data.frame(
Sample = s_id,
Cells = ncol(obj),
Median_genes = median(obj$nFeature_RNA),
Median_UMI = median(obj$nCount_RNA),
Median_mt_pct = round(median(obj$percent.mt), 2),
Max_mt_pct = round(max(obj$percent.mt), 2),
Cells_mt_gt10 = sum(obj$percent.mt > 10),
Cells_gene_hi = sum(obj$nFeature_RNA > max_features),
Cells_gene_lo = sum(obj$nFeature_RNA < min_features),
Cells_UMI_hi = sum(obj$nCount_RNA > max_UMI),
Cells_UMI_lo = sum(obj$nCount_RNA < min_UMI)
)
})
knitr::kable(do.call(rbind, pre_stats), caption = "QC summary before filtering")
```
The two samples have notably different QC profiles, reflecting their biology
rather than any technical problem.
**P1_LN** has a median of 1,356 genes and 3,288 UMIs per cell -- consistent with
a lymph node where many cells are resting with modest transcriptional output.
The mitochondrial distribution has a median of 4.9% with 479 cells (7.9%) above
the 10% threshold, confirming a genuine tail of damaged cells. Very few cells
hit the upper gene or UMI thresholds, suggesting doublets are rare.
**P1_PT** has higher median genes (1,857) and UMIs (5,086) per cell. The mt%
distribution is actually cleaner (median 1.67%), but the maximum of 91.04% shows
some severely damaged cells are present. P1_PT has considerably more high-UMI
cells (212 above 35,000) and more low-gene cells (233 below 250), both typical
of tumor tissue which tends to be harder to dissociate cleanly.
## 2.4 Apply QC filters
```{r filter}
filter_summary <- list()
for (s_id in names(seurat_list)) {
obj <- seurat_list[[s_id]]
cells_before <- ncol(obj)
obj <- subset(
obj,
subset = nFeature_RNA >= min_features &
nFeature_RNA <= max_features &
nCount_RNA >= min_UMI &
nCount_RNA <= max_UMI &
percent.mt <= filter_mt
)
cells_after <- ncol(obj)
message(sprintf(
"%s -- Cells kept: %d / %d (%.1f%% retained, %d removed)",
s_id, cells_after, cells_before,
100 * cells_after / cells_before,
cells_before - cells_after
))
filter_summary[[s_id]] <- data.frame(
Sample = s_id,
Cells_before = cells_before,
Cells_after = cells_after,
Cells_removed = cells_before - cells_after,
Pct_retained = round(100 * cells_after / cells_before, 1)
)
seurat_list[[s_id]] <- obj
}
knitr::kable(do.call(rbind, filter_summary), caption = "Filtering summary")
```
Both samples retained over 90% of cells -- P1_LN 92.0% (485 removed) and
P1_PT 90.9% (732 removed). Most removed cells were damaged (high mt%) rather
than doublets. The higher absolute number removed from P1_PT reflects both its
larger starting size and the greater proportion of debris typical of tumor tissue.
## 2.5 Inspect QC metrics after filtering
```{r qc-plots-post, fig.width=10, fig.height=4}
for (s_id in names(seurat_list)) {
print(
VlnPlot(seurat_list[[s_id]],
features = c("nFeature_RNA", "nCount_RNA", "percent.mt"),
pt.size = 0.1,
ncol = 3) &
ggplot2::labs(title = paste0(s_id, " -- QC metrics (post-filter)"))
)
}
```
```{r qc-summary-post}
post_stats <- lapply(names(seurat_list), function(s_id) {
obj <- seurat_list[[s_id]]
data.frame(
Sample = s_id,
Cells = ncol(obj),
Median_genes = median(obj$nFeature_RNA),
Median_UMI = median(obj$nCount_RNA),
Median_mt_pct = round(median(obj$percent.mt), 2),
Max_mt_pct = round(max(obj$percent.mt), 2)
)
})
knitr::kable(do.call(rbind, post_stats), caption = "QC summary after filtering")
```
**A note on Seurat v5:** You may see a message saying `Default search for "data"
layer in "RNA" assay yielded no results; utilizing "counts" layer instead`. This
is expected -- in Seurat v5 the normalised data layer is only created after
`NormalizeData()`, which runs in Step 5. The warning is harmless.
## 2.6 Save post-QC objects
```{r save-step2}
for (s in samples) {
out_path <- file.path(s$output_dir, paste0(s$sample_id, "_S2_postQC.rds"))
saveRDS(seurat_list[[s$sample_id]], file = out_path)
message("Saved: ", out_path)
}
```
***
# Step 3: Doublet Removal and B Cell Enrichment
## 3.1 Why a dedicated doublet removal step?
Standard GEX QC (Step 2) catches many doublets by removing cells with abnormally
high gene or UMI counts. But those filters work at the level of the whole
transcriptome -- they miss a different kind of doublet: a B cell stuck to a T
cell, monocyte, or NK cell inside the same droplet. These "phenotypic doublets"
look perfectly normal by count statistics but carry the wrong GEX profile and
land in unexpected positions during clustering.
Our approach is simple and interpretable. We keep only CD79A-positive cells
(the canonical pan-B cell marker), then flag any cell that co-expresses a
non-B cell marker. This is conservative -- it removes only cells with a strong,
unambiguous signal for a contaminating cell type -- and every removed cell has
a clear reason. For datasets that are not B-cell-enriched, algorithmic doublet
detection (DoubletFinder, Scrublet) on the full object before this step would
be the standard approach.
## 3.2 Helper function
```{r doublet-helper}
# Marker-based doublet detection
# Returns barcodes of cells that are CD79A+ AND express any non-B cell marker
get_doublet_cells <- function(seurat_obj) {
non_b_markers <- c("CD3E", "CD3D", "CD4", "CD8A", # T cells
"LYZ", "CST3", # Monocytes / myeloid
"KLRD1", "KLRB1", "CD247") # NK cells
cd79a <- tryCatch(
FetchData(seurat_obj, vars = "CD79A", layer = "counts")[[1]],
error = function(e) return(NULL)
)
if (is.null(cd79a)) return(NULL)
doublet_cells <- lapply(non_b_markers, function(marker) {
tryCatch({
marker_expr <- FetchData(seurat_obj, vars = marker, layer = "counts")[[1]]
rownames(seurat_obj@meta.data)[cd79a > 0 & marker_expr > 0]
}, error = function(e) return(NULL))
})
unique(unlist(doublet_cells))
}
```
The non-B marker panel covers the three main contaminating cell types in a
B-cell-enriched suspension: T cells (`CD3E`, `CD3D`, `CD4`, `CD8A`), monocytes
and myeloid cells (`LYZ`, `CST3`), and NK cells (`KLRD1`, `KLRB1`, `CD247`).
Depending on your tissue context you may need to adjust this panel -- for example,
adding epithelial markers for mucosal tissue.
## 3.3 B cell enrichment and doublet removal
```{r filter-doublets}
summary_rows <- list()
for (s_id in names(seurat_list)) {
message(paste(rep("-", 60), collapse = ""))
message("Processing: ", s_id)
obj <- seurat_list[[s_id]]
n_total <- ncol(obj)
message(" Cells in (post-QC): ", n_total)
# Keep only B cells (CD79A > 0)
b_cells <- tryCatch({
cd79a <- FetchData(obj, vars = "CD79A", layer = "counts")[[1]]
rownames(obj@meta.data)[cd79a > 0]
}, error = function(e) {
message(" WARNING: CD79A not found -- skipping B cell filter.")
return(colnames(obj))
})
obj <- subset(obj, cells = b_cells)
n_bcells <- ncol(obj)
message(" B cells (CD79A+): ", n_bcells,
" (", round(100 * n_bcells / n_total, 1), "% of input)")
# Identify and remove doublets
doublets <- get_doublet_cells(obj)
n_doublets <- length(doublets)
message(" Doublets detected: ", n_doublets)
if (n_doublets > 0) obj <- subset(obj, cells = setdiff(colnames(obj), doublets))
n_final <- ncol(obj)
message(" Cells out (post-doublet): ", n_final,
" (", round(100 * n_final / n_bcells, 1), "% of B cells retained)")
seurat_list[[s_id]] <- obj
summary_rows[[s_id]] <- data.frame(
Sample = s_id,
Cells_in = n_total,
B_cells_CD79Apos = n_bcells,
Pct_B_cells = round(100 * n_bcells / n_total, 1),
Doublets_removed = n_doublets,
Cells_out = n_final,
Pct_retained = round(100 * n_final / n_bcells, 1)
)
}
knitr::kable(do.call(rbind, summary_rows), caption = "Doublet removal summary")
```
The most striking difference between the two samples is the B cell fraction:
46% for P1_LN versus 85.1% for P1_PT. This is not a quality issue -- P1_PT was
FACS-sorted for B cells (CD19+) before sequencing, so the non-B cell fraction
was already depleted at the library preparation stage. P1_LN was sequenced as a
bulk suspension without prior sorting, containing the full cellular composition
of the lymph node. The CD79A filter brings both objects to the same starting
point for downstream analysis.
Doublet rates are similar and expected: 272 removed from P1_LN (10.6% of CD79A+
cells) and 578 from P1_PT (9.3%). Both samples retain just under 90% of their
B cells after doublet removal.
## 3.4 Save post-doublet objects
```{r save-step3}
for (s in samples) {
out_path <- file.path(s$output_dir, paste0(s$sample_id, "_S3_postDoublet.rds"))
saveRDS(seurat_list[[s$sample_id]], file = out_path)
message("Saved: ", out_path)
}
```
***
# Step 4: Adding BCR Metadata
## 4.1 What gets added and why
The BCR TSV from Part 1 has one row per contig. Before joining to Seurat we
reshape it to one row per cell, pulling the relevant columns from the heavy and
light chain rows separately. The metadata columns added are:
| Column | Source | Description |
|--------|--------|-------------|
| `BCR` | heavy chain | TRUE if cell has a detected heavy chain |
| `c_call` | heavy chain | Isotype (IGHM, IGHG1, IGHA1 etc.) |
| `clone_id` | heavy chain | Clone identifier |
| `clone_count` | heavy chain | Number of cells in this clone |
| `v_call` | heavy chain | V gene assignment |
| `j_call` | heavy chain | J gene assignment |
| `mu_freq_H` | heavy chain | Heavy chain SHM frequency |
| `umi_count_H` | heavy chain | Heavy chain UMI count |
| `kappa_lambda` | light chain | IGK or IGL |
| `mu_freq_L` | light chain | Light chain SHM frequency |
| `umi_count_L` | light chain | Light chain UMI count |
Cells with no matching BCR entry get `BCR = FALSE` and `NA` for all other BCR
columns. These are genuine B cells (CD79A+) that did not produce a detected BCR
sequence, which can happen due to dropout or low VDJ sequencing depth.
## 4.2 Load objects and BCR TSVs, join, and save
```{r add-bcr}
summary_rows <- list()
for (s in samples) {
message(paste(rep("=", 60), collapse = ""))
message("Processing: ", s$sample_id)
# Load Seurat object
rds_path <- file.path(s$output_dir, paste0(s$sample_id, "_S3_postDoublet.rds"))
if (!file.exists(rds_path)) stop("Cannot find RDS for ", s$sample_id, " -- run Step 3 first.")
obj <- readRDS(rds_path)
message(" B cells loaded (post-doublet): ", ncol(obj))
# Load BCR TSV
if (!file.exists(s$bcr_tsv)) stop("Cannot find BCR TSV for ", s$sample_id, " -- run Part 1 first.")
bcr <- data.table::fread(s$bcr_tsv, sep = "\t", data.table = FALSE, nThread = 1)
message(" BCR TSV loaded: ", nrow(bcr), " rows")
# Sanity checks: catch any residual duplicate chains
heavy_rows <- dplyr::filter(bcr, locus == "IGH")
dup_heavy <- heavy_rows %>% dplyr::count(cell_id) %>% dplyr::filter(n > 1)
if (nrow(dup_heavy) > 0) {
warning(" ", nrow(dup_heavy), " cells have >1 heavy chain -- keeping highest UMI.")
heavy_rows <- heavy_rows %>%
dplyr::group_by(cell_id) %>%
dplyr::slice_max(umi_count, n = 1, with_ties = FALSE) %>%
dplyr::ungroup()
} else {
message(" Sanity check passed: no duplicate heavy chains")
}
light_rows <- dplyr::filter(bcr, locus %in% c("IGK", "IGL"))
dup_light <- light_rows %>% dplyr::count(cell_id) %>% dplyr::filter(n > 1)
if (nrow(dup_light) > 0) {
warning(" ", nrow(dup_light), " cells have >1 light chain -- keeping highest UMI.")
light_rows <- light_rows %>%
dplyr::group_by(cell_id) %>%
dplyr::slice_max(umi_count, n = 1, with_ties = FALSE) %>%
dplyr::ungroup()
} else {
message(" Sanity check passed: no duplicate light chains")
}
# Build per-cell metadata table
heavy_meta <- heavy_rows %>%
dplyr::transmute(cell_id, c_call, clone_id, clone_count,
v_call, j_call, mu_freq_H = mu_freq, umi_count_H = umi_count)
light_meta <- light_rows %>%
dplyr::transmute(cell_id,
kappa_lambda = ifelse(locus == "IGK", "kappa", "lambda"),
mu_freq_L = mu_freq, umi_count_L = umi_count)
# Check cell ID overlap and report match rate
b_cells <- colnames(obj)
bcr_cells <- unique(heavy_meta$cell_id)
n_matched <- length(intersect(b_cells, bcr_cells))
n_bcr_only <- length(setdiff(bcr_cells, b_cells))
n_gex_only <- length(setdiff(b_cells, bcr_cells))
pct_matched <- round(100 * n_matched / length(b_cells), 1)
message(" BCR matching:")
message(" B cells in Seurat: ", length(b_cells))
message(" Cells with BCR detected: ", length(bcr_cells))
message(" Matched: ", n_matched, " (", pct_matched, "% of B cells)")
message(" BCR only (filtered in GEX): ", n_bcr_only)
message(" B cells with no BCR: ", n_gex_only)
if (pct_matched < 30) {
warning("Less than 30% of B cells matched to BCR data for ", s$sample_id,
". Check that barcode suffixes are consistent between Part 1 and Part 2.")
}
# Join BCR metadata onto Seurat cells
meta_add <- tibble::tibble(cell_id = b_cells) %>%
dplyr::mutate(BCR = cell_id %in% bcr_cells) %>%
dplyr::left_join(heavy_meta, by = "cell_id") %>%
dplyr::left_join(light_meta, by = "cell_id")
meta_df <- as.data.frame(meta_add)
rownames(meta_df) <- meta_df$cell_id
meta_df$cell_id <- NULL
obj <- AddMetaData(obj, metadata = meta_df)
message(" BCR+ cells: ", sum(obj$BCR, na.rm = TRUE))
# Save
out_path <- file.path(s$output_dir, paste0(s$sample_id, "_S4_postBCR.rds"))
saveRDS(obj, file = out_path)
message(" Saved: ", out_path)
summary_rows[[s$sample_id]] <- data.frame(
Sample = s$sample_id,
B_cells = length(b_cells),
BCR_cells = length(bcr_cells),
Matched = n_matched,
Pct_matched = pct_matched,
BCR_plus = sum(obj$BCR, na.rm = TRUE)
)
}
knitr::kable(do.call(rbind, summary_rows), caption = "BCR matching summary")
```
P1_LN has a match rate of 90.9% -- expected for an unsorted bulk suspension
where the GEX and VDJ libraries come from the same cells. P1_PT has a lower
match rate of 59.3%. Differences in library depth between GEX and VDJ runs can
cause this -- some cells are well-represented in the GEX library but have
insufficient VDJ sequencing depth to yield a detectable BCR. This is a known
occurrence in multi-library 10x experiments. If you see a match rate below 30%
in your own data, the most likely cause is a barcode suffix mismatch between
Part 1 and Part 2.
## 4.3 Inspect BCR metadata distribution
```{r inspect-bcr}
for (s in samples) {
obj <- readRDS(file.path(s$output_dir, paste0(s$sample_id, "_S4_postBCR.rds")))
bcr_pos <- subset(obj, subset = BCR == TRUE)
message("\n--- ", s$sample_id, " ---")
message("BCR TRUE/FALSE:")
print(table(obj$BCR))
message("Isotype (BCR+ cells):")
print(table(bcr_pos$c_call, useNA = "no"))
message("Top 10 largest clones:")
top_clones <- bcr_pos@meta.data %>%
dplyr::filter(!is.na(clone_id)) %>%
dplyr::distinct(clone_id, clone_count) %>%
dplyr::arrange(dplyr::desc(clone_count)) %>%
head(10)
print(top_clones)
}
```
The isotype and clone size distributions confirm the BCR metadata joined
correctly and are biologically sensible.
**P1_LN** shows a mixed isotype composition with IgM, IgA1, and IgG1 all
represented. The clone size distribution is flat -- the largest clone has only
6 cells -- the polyclonal signature of an ongoing, diverse immune response.
**P1_PT** is strikingly different. IgG1 dominates (2,150 cells). The top clones
contain between roughly 38 and 151 cells each -- highly oligoclonal. This is
the hallmark of antigen-driven clonal selection and expansion in the tumor
microenvironment.
## 4.4 BCR summary plots
```{r bcr-plots, fig.width=8, fig.height=4}
# BCR+ vs BCR- per sample
bcr_counts <- do.call(rbind, lapply(names(samples), function(s_id) {
obj <- readRDS(file.path(samples[[s_id]]$output_dir,
paste0(s_id, "_S4_postBCR.rds")))
data.frame(Sample = s_id, Status = ifelse(obj$BCR, "BCR+", "BCR-"),
stringsAsFactors = FALSE)
}))
print(
ggplot(bcr_counts, aes(x = Sample, fill = Status)) +
geom_bar(position = "fill") +
scale_y_continuous(labels = scales::percent_format()) +
scale_fill_manual(values = c("BCR+" = "#2E86AB", "BCR-" = "#D9D9D9")) +
labs(title = "B cells with and without detected BCR",
x = NULL, y = "Percentage of B cells", fill = NULL) +
theme_classic(base_size = 13)
)
# Isotype distribution per sample
isotype_order <- c("IGHD", "IGHM", "IGHA1", "IGHA2",
"IGHG1", "IGHG2", "IGHG3", "IGHG4", "IGHE")
isotype_counts <- do.call(rbind, lapply(names(samples), function(s_id) {
obj <- readRDS(file.path(samples[[s_id]]$output_dir,
paste0(s_id, "_S4_postBCR.rds")))
bcr_pos <- subset(obj, subset = BCR == TRUE)
df <- as.data.frame(table(bcr_pos$c_call), stringsAsFactors = FALSE)
colnames(df) <- c("Isotype", "Count")
df$Pct <- 100 * df$Count / sum(df$Count)
df$Sample <- s_id
df
}))
isotype_counts$Isotype <- factor(isotype_counts$Isotype, levels = isotype_order)
print(
ggplot(isotype_counts, aes(x = Isotype, y = Pct, fill = Sample)) +
geom_col(position = "dodge") +
scale_fill_manual(values = c("P1_LN" = "#2E86AB", "P1_PT" = "#E84855")) +
labs(title = "Isotype distribution per sample (BCR+ cells)",
x = NULL, y = "% of BCR+ cells", fill = "Sample") +
theme_classic(base_size = 13) +
theme(axis.text.x = element_text(angle = 45, hjust = 1))
)
```
The isotype plot makes the LN versus PT contrast immediately visible. P1_LN has
a balanced distribution across isotypes while P1_PT is dominated by IgG1 --
a single panel that captures the core immunological difference between the two
tissue compartments.
***
# Step 5: Solo GEX Analysis
## 5.1 Why we exclude IG and TCR variable genes from HVG selection
Before running the analysis loop, this non-default choice deserves explanation.
The standard Seurat workflow selects the 2,000 most variable genes and uses them
for PCA. In B cells this has a specific problem: V(D)J recombination makes the
V gene transcripts extremely variable across cells, but this variance reflects
clonal diversity -- which antibody gene a cell expresses -- rather than
biological cell state.
If we leave these genes in, PCA and UMAP become partly driven by V gene usage.
Cells sharing a V gene get pulled together regardless of transcriptional identity,
and biologically meaningful states like germinal center, plasma cell, or memory
B cell can get distorted.
The fix: run `FindVariableFeatures()` as normal, then remove any gene matching a
V/D/J pattern from the HVG list before scaling and PCA. The genes are **not
removed from the object** -- they remain available for feature plots, DEG
analysis, and everything else. They are only excluded from the features used to
compute the embedding.
```{r gene-filter-setup}
variable_gene_patterns <- c(
"^IGHV", "^IGKV", "^IGKJ", "^IGLV", "^IGLJ",
"^IGHD[0-9]", "^IGHJ",
"^TRAV", "^TRBV", "^TRAJ", "^TRBJ", "^TRBD"
)
variable_gene_regex <- paste(variable_gene_patterns, collapse = "|")
```
One pattern worth clarifying: `^IGHD[0-9]` catches the IGHD diversity genes
(e.g. IGHD3-10), not the IgD isotype transcript. The isotype transcript is
named simply `IGHD` with no number suffix and is not matched by this regex. It
remains in the HVG list if it is variable, which is correct -- IgD expression
is one of the best markers distinguishing naive from class-switched B cells.
## 5.2 Marker panel and color scheme
Used for DotPlots and FeaturePlots throughout Steps 5, 6, and 7.
```{r marker-setup}
b_cell_markers <- c(
# B cell identity
"CD79A", "CD19", "MS4A1",
# Naive
"IGHD", "IGHM", "IL4R", "TCL1A",
# Memory
"CD27", "CD24", "TNFRSF13B",
# Germinal center
"BCL6", "AICDA", "MEF2B",
# Plasmablast / plasma cell
"JCHAIN", "MZB1", "XBP1",
# Proliferating
"MKI67", "UBE2C", "PCNA",
# Early activation
"CD83", "MYC", "CCND2", "TRAF4", "MIR155HG",
# Interferon-stimulated
"IFI6", "IFI44", "IFIT1", "IFIT2", "IFIT3",
# Atypical memory / ABCs
"FCRL4", "FCRL5", "ZBTB32", "ITGAX", "ZEB2",
# Exhaustion / regulatory
"HAVCR1", "HAVCR2", "TIGIT", "LAG3", "IL10"
)
isotype_colors <- c(
"IGHD" = "#e41a1c", "IGHM" = "#377eb8", "IGHA1" = "#a65628",
"IGHA2" = "#f781bf", "IGHG1" = "#4daf4a", "IGHG2" = "#984ea3",
"IGHG3" = "#ff7f00", "IGHG4" = "#ffff33", "IGHE" = "#66c2a5"
)
```
## 5.3 Cell cycle gene sets
```{r cc-genes}
s.genes <- cc.genes.updated.2019$s.genes
g2m.genes <- cc.genes.updated.2019$g2m.genes
```
Cell cycle scores are stored as metadata but not regressed out. In a B cell
dataset, cell cycle state is biologically meaningful -- proliferating cells are
typically dark zone GC B cells undergoing rapid division, and we want this
visible in the UMAP.
## 5.4 Per-sample processing loop
For each sample: normalize, find HVGs, exclude IG/TCR variable genes, scale,
run PCA, select PCs (fewest explaining 80% of variance, floor 10, ceiling 25),
cluster, run UMAP, score cell cycle, generate a full panel of plots, save.
```{r solo-gex, fig.width=10, fig.height=7}
set.seed(42) # ensures reproducibility of RunPCA, FindNeighbors, FindClusters, RunUMAP, and CellCycleScoring across both samples
var_expl <- 0.8
cluster_resolution <- 0.5
seurat_list <- list()
for (s in samples) {
message(paste(rep("=", 60), collapse = ""))
message("Processing: ", s$sample_id)
rds_in <- file.path(s$output_dir, paste0(s$sample_id, "_S4_postBCR.rds"))
if (!file.exists(rds_in)) stop("Cannot find input RDS for ", s$sample_id, " -- run Step 4 first.")
obj <- readRDS(rds_in)
DefaultAssay(obj) <- "RNA"
message(" Loaded: ", ncol(obj), " cells | ", nrow(obj), " genes")
# Normalize
obj <- NormalizeData(obj, normalization.method = "LogNormalize",
scale.factor = 10000, verbose = FALSE)
# Find HVGs and exclude IG/TCR variable genes
obj <- FindVariableFeatures(obj, selection.method = "vst",
nfeatures = 2000, verbose = FALSE)
genes_to_exclude <- grep(variable_gene_regex, rownames(obj), value = TRUE)
n_excluded <- length(intersect(genes_to_exclude, VariableFeatures(obj)))
message(" Excluding ", n_excluded, " IG/TCR variable genes from HVG list")
hvg_filtered <- setdiff(VariableFeatures(obj), genes_to_exclude)
if (length(hvg_filtered) < 50) {
warning(" Fewer than 50 HVGs remain after filtering. Using unfiltered list.")
hvg_filtered <- VariableFeatures(obj)
}
VariableFeatures(obj) <- hvg_filtered
message(" HVGs after filtering: ", length(hvg_filtered))
# Scale and PCA
obj <- ScaleData(obj, features = hvg_filtered, verbose = FALSE)
obj <- RunPCA(obj, features = hvg_filtered, npcs = 25, verbose = FALSE)
eigs <- obj@reductions$pca@stdev^2
cum_var <- cumsum(eigs) / sum(eigs)
n_pc <- which(cum_var >= var_expl)[1]
if (is.na(n_pc)) n_pc <- 25
n_pc <- max(n_pc, 10); n_pc <- min(n_pc, 25)
message(" PCs selected: ", n_pc,
" (explains ", round(100 * cum_var[n_pc], 1), "% of variance)")
print(
ElbowPlot(obj, ndims = 25) +
ggtitle(paste0(s$sample_id, " -- Elbow plot")) +
geom_vline(xintercept = n_pc, linetype = "dashed", color = "red") +
labs(caption = paste0("Red dashed line = PC ", n_pc,
" (", round(100 * cum_var[n_pc], 1), "% cumulative variance)"))
)
# Cluster and UMAP
obj <- FindNeighbors(obj, dims = 1:n_pc, verbose = FALSE)
obj <- FindClusters(obj, resolution = cluster_resolution, verbose = FALSE)
obj <- RunUMAP(obj, dims = 1:n_pc, verbose = FALSE)
message(" Clusters found: ", length(unique(obj$seurat_clusters)))
# Cell cycle scoring
obj <- CellCycleScoring(obj, s.features = s.genes,
g2m.features = g2m.genes, set.ident = FALSE)
obj$Phase <- factor(obj$Phase, levels = c("G1", "S", "G2M"))
# Plots
num_clusters <- table(obj$seurat_clusters)
print(
DimPlot(obj, reduction = "umap", label = TRUE, repel = TRUE, pt.size = 1.2) +
scale_color_hue(labels = paste0(names(num_clusters), " (", num_clusters, ")")) +
ggtitle(paste0(s$sample_id, " -- Clusters (res = ", cluster_resolution, ")")) +
theme(legend.text = element_text(size = 9))
)
print(
FeaturePlot(obj, reduction = "umap",
features = c("nFeature_RNA", "nCount_RNA", "percent.mt"),
order = TRUE, pt.size = 1.2) +
patchwork::plot_annotation(title = paste0(s$sample_id, " -- QC metrics on UMAP"))
)
markers_present <- intersect(b_cell_markers, rownames(obj))
print(
DotPlot(obj, features = markers_present, cols = c("gray90", "red"), dot.scale = 6) +
RotatedAxis() +
ggtitle(paste0(s$sample_id, " -- B cell marker panel")) +
theme(axis.text.x = element_text(size = 8))
)
markers_for_feature <- intersect(
c("CD79A", "IGHD", "IGHM", "CD27", "BCL6", "AICDA",
"MKI67", "PRDM1", "XBP1", "FCRL4", "FCRL5"),
rownames(obj)
)
if (length(markers_for_feature) > 0) {
print(
FeaturePlot(obj, reduction = "umap", features = markers_for_feature,
order = TRUE, pt.size = 1.2) &
scale_color_gradientn(colors = viridis::inferno(256))
)
}
Idents(obj) <- "Phase"
print(
DimPlot(obj, reduction = "umap", label = FALSE, pt.size = 1.2,
cols = c("G1" = "#AAAAAA", "S" = "#E69F00", "G2M" = "#CC79A7")) +
ggtitle(paste0(s$sample_id, " -- Cell cycle phase"))
)
Idents(obj) <- "seurat_clusters"
cc_df <- obj@meta.data %>%
dplyr::select(Phase, seurat_clusters) %>%
dplyr::group_by(seurat_clusters, Phase) %>%
dplyr::summarise(n = dplyr::n(), .groups = "drop_last") %>%
dplyr::mutate(pct = 100 * n / sum(n)) %>%
dplyr::ungroup() %>%
dplyr::mutate(Phase = factor(Phase, levels = c("G1", "S", "G2M")))
print(
ggplot(cc_df, aes(x = seurat_clusters, y = pct, fill = Phase)) +
geom_bar(stat = "identity") +
scale_fill_manual(values = c("G1" = "#AAAAAA", "S" = "#E69F00", "G2M" = "#CC79A7")) +
ylab("% of cells") + xlab("Cluster") +
theme_classic(base_size = 12) +
ggtitle(paste0(s$sample_id, " -- Cell cycle composition per cluster"))
)
# BCR overlay plots
if ("BCR" %in% colnames(obj@meta.data)) {
obj_bcr <- subset(obj, subset = !is.na(c_call) & c_call != "")
if (ncol(obj_bcr) > 0) {
obj_bcr$c_call <- factor(obj_bcr$c_call, levels = isotype_order)
present_iso <- intersect(isotype_order, levels(droplevels(obj_bcr$c_call)))
print(
DimPlot(obj_bcr, group.by = "c_call", label = FALSE, pt.size = 1.2,
cols = isotype_colors[present_iso], order = rev(present_iso)) +
ggtitle(paste0(s$sample_id, " -- Isotype (BCR+ cells)"))
)
}
if ("mu_freq_H" %in% colnames(obj@meta.data)) {
print(
FeaturePlot(obj, features = "mu_freq_H", reduction = "umap",
order = TRUE, pt.size = 1.2) +
scale_color_gradientn(colors = c("#FFFFCC", "#41B6C4", "#0C2C84"),
na.value = "grey90") +
ggtitle(paste0(s$sample_id, " -- SHM frequency, heavy chain"))
)
}
if ("clone_count" %in% colnames(obj@meta.data)) {
print(
FeaturePlot(obj, features = "clone_count", reduction = "umap",
order = TRUE, pt.size = 1.2) +
scale_color_gradientn(colors = c("#FFFFCC", "#FD8D3C", "#800026"),
na.value = "grey90") +
ggtitle(paste0(s$sample_id, " -- Clone size"))
)
}
if ("c_call" %in% colnames(obj@meta.data)) {
iso_df <- obj@meta.data %>%
dplyr::filter(!is.na(c_call), c_call != "", !is.na(seurat_clusters)) %>%
dplyr::mutate(c_call = factor(c_call, levels = isotype_order),
seurat_clusters = as.factor(seurat_clusters))
present_iso2 <- intersect(isotype_order, levels(droplevels(iso_df$c_call)))
print(
ggplot(iso_df, aes(x = seurat_clusters, y = 1, fill = c_call)) +
geom_col(position = "fill") +
scale_y_continuous(labels = scales::label_percent(accuracy = 1)) +
scale_fill_manual(values = isotype_colors[present_iso2], breaks = present_iso2) +
ylab("Percentage of BCR+ cells") + xlab("Cluster") +
theme_classic(base_size = 12) +
ggtitle(paste0(s$sample_id, " -- Isotype composition per cluster"))
)
}