-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDZ_Script_1_Preprocess_Samples_Final.R
More file actions
1849 lines (1613 loc) · 78 KB
/
Copy pathDZ_Script_1_Preprocess_Samples_Final.R
File metadata and controls
1849 lines (1613 loc) · 78 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
# Most up-to-date as of 3pm 5/15/26
# =========================================================
# SCRIPT 1: PER-PATIENT AND HEALTHY DONOR PROCESSING
# =========================================================
#
# Purpose:
# This script processes each cancer patient and healthy donor
# independently (one at a time) to keep RAM usage manageable,
# then saves the objects needed by downstream scripts.
#
# For each patient/donor it produces:
# 1. A full annotated Seurat object with TAM labels.
# 2. A tumor-only Seurat object (cancer patients only).
# 3. A background-only Seurat object (cancer patients only).
# 4. A macrophage/TAM-only Seurat object.
#
# Pipeline overview (per patient/donor):
# Step 1 - Read raw per-sample MTX files.
# Step 2 - Run DoubletFinder per sample to remove doublets.
# Step 3 - Merge singlet-filtered samples into one object.
# Step 4 - Final post-merge QC filtering.
# Step 5 - SCTransform normalization, PCA, Harmony batch correction,
# graph-based clustering, and UMAP embedding.
# Step 6 - Broad marker-based cell type scoring (Immune, Epithelial,
# Endothelial, Fibroblast, Mast, etc) + SingleR fine annotation
# using the HLCA centroid reference.
# Step 7 - Subset macrophage-like cells; score each cell for seven
# TAM programs based upon Ma Black Qian Trends Immuno 2022
# (IFN, INFLAM, LA, ANGIO, REG, PROLIF, TRM)
# and assign a confident TAM_subset label.
# Step 8 - Transfer TAM labels back to the full object; build
# cellchat_group column for Script 2.
# Step 9 - Save final RDS outputs and clean up memory.
#
# Cohort-level integration (Script 1.5) is handled separately.
#
# Key design principles:
# - skip_existing_outputs = TRUE means already-completed patients
# are silently skipped, making reruns safe and fast.
# - DoubletFinder is run per capture library BEFORE merging, which
# is the biologically correct level for doublet detection.
# - All intermediate SCT/PCA/graph outputs from DoubletFinder are
# deleted before returning each sample, so the merged object
# starts cleanly with only raw RNA counts as these are not needed by DoubletFinder.
#
# =========================================================
suppressPackageStartupMessages({
library(Seurat) # Single-cell analysis framework (v5).
library(Matrix) # Sparse matrix support for count data.
library(tidyverse) # Data wrangling and plotting utilities.
library(harmony) # Batch correction across samples/patients.
library(sctransform) # Regularized NB normalization (SCTransform).
library(glmGamPoi) # Fast GLM backend used by SCTransform.
library(SingleR) # Reference-based cell type annotation.
library(SingleCellExperiment) # SCE container required by SingleR.
library(future) # Parallelism control (set to sequential here).
library(DoubletFinder) # Doublet detection per capture library.
})
# Run sequentially. Harmony and SCTransform internally use multiple
# threads but future::plan("sequential") prevents nested parallelism
# that can exhaust RAM on large patient objects.
plan("sequential")
# Set future globals limit high enough for large patients (e.g. P20 ~110k cells).
options(future.globals.maxSize = 128 * 1024^3)
set.seed(777)
gc()
# =========================================================
# USER SETTINGS
# =========================================================
# All paths and tunable parameters are collected here so that
# nothing else in the script needs to be edited for a new run.
# Directory containing per-sample MTX files named as:
# <sample_id>-matrix.mtx
# <sample_id>-features.tsv
# <sample_id>-barcodes.tsv
data_dir <- "/Users/rileyjones/Desktop/BIOINFORMATICS/Thesis/Data/scRNAseq/De_Zuani_NatComm_2024_EMTAB13530/DZ_scRNAseq/All_Samples/"
# HLCA centroid reference RDS for SingleR annotation.
# Must contain named slots: $centroids (gene x cell-type matrix),
# $fine_labels (character vector), and optionally $broad_map.
centroid_rds <- "/Users/rileyjones/Desktop/BIOINFORMATICS/Thesis/Data/scRNAseq/Azimuth_HLCA_Ref/hlca_centroids_all_cells.rds"
# Root output directory. Sub-directories are created automatically.
base_outdir <- "/Users/rileyjones/Desktop/BIOINFORMATICS/Thesis/Data/scRNAseq/De_Zuani_NatComm_2024_EMTAB13530/DZ_scRNAseq"
# Output sub-directories.
outdir_full_annot <- file.path(base_outdir, "full_patient_annotated")
outdir_tumor <- file.path(base_outdir, "tumor_only")
outdir_background <- file.path(base_outdir, "background_only")
outdir_macro <- file.path(base_outdir, "macrophage_only")
outdir_qc <- file.path(base_outdir, "qc_tables")
dir.create(outdir_full_annot, showWarnings = FALSE, recursive = TRUE)
dir.create(outdir_tumor, showWarnings = FALSE, recursive = TRUE)
dir.create(outdir_background, showWarnings = FALSE, recursive = TRUE)
dir.create(outdir_macro, showWarnings = FALSE, recursive = TRUE)
dir.create(outdir_qc, showWarnings = FALSE, recursive = TRUE)
# If TRUE, patients/donors whose final output RDS files already exist
# are silently skipped. Set to TRUE for normal runs and reruns after
# partial failures. Set to FALSE only if you want to force-reprocess
# every patient from scratch.
skip_existing_outputs <- TRUE
# Whether to write per-sample DoubletFinder QC and final cell count
# summary CSVs at the end of the script.
save_doubletfinder_summary_csv <- TRUE
save_final_cell_count_summary_csv <- TRUE
# ---------------------------------------------------------
# QC thresholds
# ---------------------------------------------------------
# These are aligned closely to the De Zuani et al. (2024) paper.
# Cells failing any threshold are removed before downstream analysis.
min_features <- 180 # Minimum detected genes per cell.
max_features <- 6000 # Maximum detected genes (removes likely doublets).
min_counts <- 400 # Minimum total UMI counts per cell.
max_counts <- 100000 # Maximum total UMI counts per cell.
max_percent_mt <- 20 # Maximum mitochondrial read fraction (%).
# ---------------------------------------------------------
# Analysis settings
# ---------------------------------------------------------
# TAM margin cutoff: the difference between the top and second-best
# TAM program score must exceed this value for a cell to receive a
# confident (non-Ambiguous) label. 0.075 is intentionally conservative
# to reduce false-positive TAM subset assignments.
tam_margin_cutoff <- 0.075
# Broad label margin cutoff: same concept applied to the five broad
# cell-type categories (Immune, Epithelial, Endothelial, Fibroblast, Mast).
broad_margin_cutoff <- 0.05
# Number of PCs to use for FindNeighbors, Harmony, UMAP, and clustering.
npcs_use <- 20
# Whether to run UMAP. Set to FALSE for test runs to save time.
run_umap <- TRUE
# ---------------------------------------------------------
# DoubletFinder settings
# ---------------------------------------------------------
run_doubletfinder <- TRUE # Master switch for doublet detection.
doublet_rate <- 0.06 # Expected doublet rate (~6% for 10x & author recommendations).
doubletfinder_pcs <- 1:20 # PCs passed to DoubletFinder.
doubletfinder_pN <- 0.25 # Proportion of artificial doublets to generate.
doubletfinder_use_param_sweep <- TRUE # If TRUE, use paramSweep to estimate optimal pK.
doubletfinder_pK_default <- 0.09 # Fallback pK if paramSweep fails or is disabled.
doubletfinder_min_cells <- 100 # Skip DoubletFinder for samples below this cell count.
# =========================================================
# PATIENT METADATA
# =========================================================
# Sample IDs are auto-detected from the data directory by pattern
# matching (P<number>_<T|B><number>). The patient_meta table provides
# clinical annotations that are stamped onto every cell.
# Detect all patient sample IDs from the data directory.
sample_ID <- list.files(data_dir, full.names = FALSE) %>%
stringr::str_extract("^P\\d+_[TB]\\d+") %>%
unique() %>%
.[!is.na(.)] %>%
sort()
# Clinical metadata for all 24 cancer patients.
# Columns:
# patient_key - Short key used for file naming (P1, P2, ...).
# patient_id - Full patient label (somewhat redundant).
# dataset - Study identifier (all DZ for De Zuani et al.).
# sex - Biological sex (M/F).
# cancer_type - LC (unspecified or adenosquamous), LUSC (squamous), LUAD (adenocarcinoma).
# stage - Pathological T stage at resection.
# smoking_status - Smoking history (current/ ex (any kind of previous smoking)/ no or never smoker).
# age - Age at surgery (years, stored as character for flexibility).
# treatment - Treatment status at time of sample (all untreated here).
patient_meta <- tibble::tribble(
~patient_key, ~patient_id, ~dataset, ~sex, ~cancer_type, ~stage, ~smoking_status, ~age, ~treatment,
"P1", "Patient 1", "DZ", "F", "LC", "T2", "ex", "73", "untreated",
"P2", "Patient 2", "DZ", "F", "LUSC", "T2", "ex", "82", "untreated",
"P3", "Patient 3", "DZ", "F", "LUSC", "T4", "ex", "77", "untreated",
"P4", "Patient 4", "DZ", "M", "LUSC", "NA", "ex", "69", "untreated",
"P5", "Patient 5", "DZ", "F", "LUAD", "T2", "no", "72", "untreated",
"P6", "Patient 6", "DZ", "F", "LUAD", "T1", "current", "69", "untreated",
"P7", "Patient 7", "DZ", "M", "LUAD", "T1", "no", "58", "untreated",
"P8", "Patient 8", "DZ", "M", "LUSC", "T2", "ex", "75", "untreated",
"P9", "Patient 9", "DZ", "M", "LUAD", "T2", "ex", "79", "untreated",
"P10", "Patient 10", "DZ", "F", "LUAD", "T3", "no", "72", "untreated",
"P11", "Patient 11", "DZ", "M", "LUSC", "T3", "ex", "81", "untreated",
"P12", "Patient 12", "DZ", "F", "LC", "T1", "ex", "63", "untreated",
"P13", "Patient 13", "DZ", "F", "LUAD", "T1", "ex", "59", "untreated",
"P14", "Patient 14", "DZ", "M", "LUAD", "T4", "ex", "81", "untreated",
"P15", "Patient 15", "DZ", "F", "LUAD", "T3", "current", "73", "untreated",
"P16", "Patient 16", "DZ", "F", "LUAD", "T2", "current", "87", "untreated",
"P17", "Patient 17", "DZ", "M", "LC", "T2", "ex", "65", "untreated",
"P18", "Patient 18", "DZ", "M", "LUSC", "T2", "current", "77", "untreated",
"P19", "Patient 19", "DZ", "M", "LUSC", "T3", "ex", "78", "untreated",
"P20", "Patient 20", "DZ", "M", "LUSC", "T4", "current", "72", "untreated",
"P21", "Patient 21", "DZ", "M", "LUAD", "T1", "ex", "68", "untreated",
"P22", "Patient 22", "DZ", "M", "LUAD", "T3", "ex", "86", "untreated",
"P23", "Patient 23", "DZ", "F", "LC", "T4", "ex", "67", "untreated",
"P24", "Patient 24", "DZ", "F", "LUAD", "T3", "ex", "52", "untreated"
)
# Join sample-level metadata (auto-detected IDs) with clinical metadata.
# sample_class: T = tumor, B = background.
# sample_type: "tumor" or "background" — used throughout for subsetting.
sample_meta <- tibble(sample_id = sample_ID) %>%
mutate(
patient_key = stringr::str_extract(sample_id, "^P\\d+"),
sample_class = stringr::str_match(sample_id, "^P\\d+_([TB])\\d+$")[, 2],
sample_number = as.integer(stringr::str_match(sample_id, "^P\\d+_[TB](\\d+)$")[, 2]),
sample_type = dplyr::if_else(sample_class == "T", "tumor", "background")
) %>%
left_join(patient_meta, by = "patient_key")
# Warn if any detected sample IDs could not be matched to patient_meta.
if (any(is.na(sample_meta$patient_id))) {
warning("Some sample IDs did not match patient_meta:")
print(sample_meta %>% filter(is.na(patient_id)))
}
# Build named lookup vectors for fast metadata stamping inside
# read_one_patient_sample(). Each vector maps sample_id -> metadata value.
patient_ID_map <- setNames(sample_meta$patient_id, sample_meta$sample_id)
patient_key_map <- setNames(sample_meta$patient_key, sample_meta$sample_id)
dataset_map <- setNames(sample_meta$dataset, sample_meta$sample_id)
sex_map <- setNames(sample_meta$sex, sample_meta$sample_id)
cancer_type_map <- setNames(sample_meta$cancer_type, sample_meta$sample_id)
stage_map <- setNames(sample_meta$stage, sample_meta$sample_id)
smoking_map <- setNames(sample_meta$smoking_status, sample_meta$sample_id)
age_map <- setNames(sample_meta$age, sample_meta$sample_id)
treatment_map <- setNames(sample_meta$treatment, sample_meta$sample_id)
sample_type_map <- setNames(sample_meta$sample_type, sample_meta$sample_id)
sample_number_map <- setNames(sample_meta$sample_number, sample_meta$sample_id)
# =========================================================
# MARKER PANELS
# =========================================================
# ---------------------------------------------------------
# Broad cell-type markers
# ---------------------------------------------------------
# Used by assign_broad_labels() to score every cell for five major
# compartments before SingleR fine annotation. The top-scoring
# compartment with a margin >= broad_margin_cutoff is assigned as
# the confident broad label. Cells below the margin threshold receive
# "Ambiguous" and fall through to SingleR as the primary annotation.
broad_marker_list <- list(
Immune = c("PTPRC", "LST1", "TYROBP", "CD3D", "NKG7", "MS4A1", "FCER1A"),
Epithelial_Tumor = c("EPCAM", "KRT8", "KRT18", "KRT19", "KRT17", "TACSTD2", "MUC1"),
Endothelial = c("PECAM1", "VWF", "KDR", "EMCN", "RAMP2"),
Fibroblast_Stromal = c("COL1A1", "COL1A2", "DCN", "LUM", "COL3A1", "TAGLN"),
Mast = c("TPSAB1", "TPSB2", "CPA3", "KIT", "HDC")
)
# ---------------------------------------------------------
# TAM program gene signatures (expanded)
# ---------------------------------------------------------
# Seven macrophage polarization programs derived from
# Ma Black Qian Trends Immuno 2022. Each program
# is represented by a curated gene list. label_tams_expanded() computes
# the mean log-normalized expression of each program's genes per cell
# and assigns the highest-scoring program as the TAM_subset. The
# TAM_margin (top score minus second-best score) must exceed
# tam_margin_cutoff for the label to be considered confident.
#
# Programs:
# IFN - Interferon-stimulated macrophages (antiviral/antitumor).
# INFLAM - Inflammatory/classically activated macrophages.
# LA - Lipid-associated macrophages (TREM2+/APOE+).
# ANGIO - Angiogenic/SPP1+ pro-tumoral macrophages.
# REG - Regulatory/alternatively activated macrophages.
# PROLIF - Proliferating macrophages.
# TRM - Tissue-resident macrophages (alveolar-like, LYVE1+/FABP4+).
tam_gene_list_expanded <- list(
IFN = c("ISG15","IFIT1","IFIT2","IFIT3","IFITM1","IFITM3","CXCL9","CXCL10","CXCL11","IDO1","CD274","IRF1","IRF7","STAT1","IL4I1","TNFSF10","LAMP3"),
INFLAM = c("IL1B","IL1RN","CCL2","CCL3","CCL3L1","CCL4","CCL20","CXCL1","CXCL2","CXCL3","CXCL5","CXCL8","INHBA","S100A8","S100A9","NFKBIA"),
LA = c("ACP5","APOE","APOC1","C1QA","C1QB","C1QC","FABP5","GPNMB","LGALS3","LIPA","LPL","CD36","CTSB","CTSD","TREM2","SPP1","CHI3L1","F13A1"),
ANGIO = c("VEGFA","SPP1","FN1","VCAN","THBS1","FLT1","AREG","CCL20","CD163","CEBPB","FCN1","PPARG","SLC2A1","IL1B","IL1RN","OLR1","TIMP1","SERPINB2","BNIP3","CLEC5A"),
REG = c("ARG1","MRC1","CX3CR1","CD274","CD40","CD80","CD86","ICOSLG","IL10","TGFB2","LGALS9","HLA-DRA","HLA-DRB1","HLA-DQA1","HLA-DQB1","ITGA4","CHIT1"),
PROLIF = c("MKI67","CDK1","CDC45","STMN1","TOP2A","TYMS","RRM2","CCNA2","TUBA1B","TUBB","HMGN2","HMGB1"),
TRM = c("LYVE1","HES1","FOLR2","MARCO","FABP4","CCL18","FBP1","LGALS3","MCEMP1","MRC1","MSR1","PPARG","RBP4","VSIG4","CD5L","MS4A7","SLC40A1","VCAM1","SEPP1","PLTP")
)
# =========================================================
# HELPER FUNCTIONS
# =========================================================
# Accumulates DoubletFinder results per sample.
# Written to CSV at end of script if save_doubletfinder_summary_csv = TRUE.
doubletfinder_summary_list <- list()
# ---------------------------------------------------------
# recode_smoking_binary()
# ---------------------------------------------------------
# Converts free-text smoking history values into a two-level binary:
# "nonsmoker" - never smoked
# "smoker" - ever smoked (current or former)
# This is used for cohort-level smoking comparisons in Script 3.
recode_smoking_binary <- function(x) {
x <- tolower(trimws(as.character(x)))
out <- rep(NA_character_, length(x))
out[x %in% c("never","never smoker","never_smoker","nonsmoker",
"non-smoker","non smoker","no")] <- "nonsmoker"
out[x %in% c("former","former smoker","former_smoker","ex","ex-smoker",
"ex smoker","current","current smoker","current_smoker",
"smoker","ever","ever smoker")] <- "smoker"
out
}
# ---------------------------------------------------------
# find_existing_file()
# ---------------------------------------------------------
# Returns the first path in `paths` that exists on disk, or
# NA_character_ if none exist. Used to handle naming variants for
# donor MTX files (e.g. -matrix.mtx vs -matrix.tsv).
find_existing_file <- function(paths) {
hit <- paths[file.exists(paths)]
if (length(hit) == 0) return(NA_character_)
hit[1]
}
# ---------------------------------------------------------
# read_one_patient_sample()
# ---------------------------------------------------------
# Reads one cancer patient sample from MTX format and attaches all
# clinical metadata as cell-level columns. Cell barcodes are prefixed
# with the sample ID to ensure uniqueness after merging.
read_one_patient_sample <- function(sid) {
counts <- ReadMtx(
mtx = file.path(data_dir, paste0(sid, "-matrix.mtx")),
features = file.path(data_dir, paste0(sid, "-features.tsv")),
cells = file.path(data_dir, paste0(sid, "-barcodes.tsv"))
)
# Prefix barcodes with sample ID to avoid collisions after merge().
colnames(counts) <- paste0(sid, "_", colnames(counts))
obj <- CreateSeuratObject(counts = counts, project = sid)
# Stamp clinical metadata onto every cell using the lookup vectors
# built from patient_meta above.
obj$sample_id <- sid
obj$patient_key <- patient_key_map[[sid]]
obj$patient_id <- patient_ID_map[[sid]]
obj$cancer_type <- cancer_type_map[[sid]]
obj$dataset <- dataset_map[[sid]]
obj$stage <- stage_map[[sid]]
obj$age <- age_map[[sid]]
obj$treatment <- treatment_map[[sid]]
obj$sex <- sex_map[[sid]]
obj$smoking_status <- smoking_map[[sid]]
obj$sample_type <- sample_type_map[[sid]]
obj$sample_number <- sample_number_map[[sid]]
obj
}
# ---------------------------------------------------------
# get_donor_sample_ids()
# ---------------------------------------------------------
# Auto-detects healthy donor sample IDs by pattern-matching filenames
# in data_dir for the D<number>_<number> naming convention used by
# the De Zuani healthy donor samples.
get_donor_sample_ids <- function(data_dir) {
list.files(data_dir, full.names = FALSE) %>%
str_extract("^D\\d+_\\d+") %>%
unique() %>%
.[!is.na(.)] %>%
sort()
}
# ---------------------------------------------------------
# read_one_donor_sample()
# ---------------------------------------------------------
# Reads one healthy donor sample. Handles two filename variants for
# the matrix file (-matrix.mtx or -matrix.tsv) and for the features
# file (-features.tsv or -genes.tsv), since donor data may have been
# exported with slightly different naming conventions.
read_one_donor_sample <- function(sid) {
matrix_file <- find_existing_file(c(
file.path(data_dir, paste0(sid, "-matrix.mtx")),
file.path(data_dir, paste0(sid, "-matrix.tsv"))
))
features_file <- find_existing_file(c(
file.path(data_dir, paste0(sid, "-features.tsv")),
file.path(data_dir, paste0(sid, "-genes.tsv"))
))
barcodes_file <- find_existing_file(
file.path(data_dir, paste0(sid, "-barcodes.tsv"))
)
if (any(is.na(c(matrix_file, features_file, barcodes_file)))) {
warning("Missing matrix/features/barcodes file for donor sample: ", sid)
return(NULL)
}
counts <- ReadMtx(mtx = matrix_file, features = features_file, cells = barcodes_file)
colnames(counts) <- paste0(sid, "_", colnames(counts))
donor_key <- str_extract(sid, "^D\\d+")
donor_number <- str_match(sid, "^D\\d+_(\\d+)$")[, 2]
obj <- CreateSeuratObject(counts = counts, project = sid)
# Healthy donors get fixed metadata; clinical fields unavailable
# for donors are set to NA rather than left unset.
obj$sample_id <- sid
obj$patient_key <- donor_key
obj$patient_id <- paste("Donor", str_remove(donor_key, "^D"))
obj$cancer_type <- "Healthy"
obj$dataset <- "DZ_Healthy"
obj$stage <- NA_character_
obj$age <- NA_character_
obj$treatment <- "none"
obj$sex <- NA_character_
obj$smoking_status <- NA_character_
obj$sample_type <- "healthy"
obj$sample_number <- suppressWarnings(as.integer(donor_number))
obj
}
# ---------------------------------------------------------
# run_basic_qc()
# ---------------------------------------------------------
# Applies per-cell QC filters using the global thresholds defined
# in USER SETTINGS. Called twice per patient:
# 1. Before DoubletFinder (inside run_doubletfinder_one_sample).
# 2. After merge() on the combined patient object.
# The second call catches any low-quality cells that may have slipped
# through at the sample level due to sample-specific background noise.
run_basic_qc <- function(obj) {
DefaultAssay(obj) <- "RNA"
# Compute mitochondrial fraction if not already present.
# MT- genes are standard human mitochondrial gene prefix.
if (!("percent.mt" %in% colnames(obj@meta.data))) {
obj[["percent.mt"]] <- PercentageFeatureSet(obj, pattern = "^MT-", assay = "RNA")
}
subset(
obj,
subset = nFeature_RNA >= min_features &
nFeature_RNA <= max_features &
nCount_RNA >= min_counts &
nCount_RNA <= max_counts &
percent.mt < max_percent_mt
)
}
# ---------------------------------------------------------
# run_doubletfinder_one_sample()
# ---------------------------------------------------------
# Detects and removes doublets for a SINGLE capture library using
# DoubletFinder. Running per sample (before merging) is biologically
# correct because doublets arise within individual capture events,
# not across samples.
#
# Workflow:
# 1. QC filter the sample.
# 2. Temporarily run SCTransform + PCA + graph-based clustering
# (these are only needed by DoubletFinder and are deleted after).
# 3. Estimate optimal pK via paramSweep (or use a default).
# 4. Estimate expected doublet count, adjusted for homotypic doublets.
# 5. Call DoubletFinder.
# 6. Store classifications in metadata; filter to singlets.
# 7. Delete temporary SCT/PCA/graph objects before returning.
#
# All steps are wrapped in tryCatch so a failure for one sample
# does not abort the entire patient pipeline.
run_doubletfinder_one_sample <- function(obj, sample_id) {
df_start_time <- Sys.time()
# --- Early exit: DoubletFinder disabled globally ---
if (!run_doubletfinder) {
log_msg("DoubletFinder disabled by run_doubletfinder = FALSE for sample: ", sample_id)
obj$DoubletFinder_class <- "Not_run"
obj$DoubletFinder_pANN <- NA_real_
obj$DoubletFinder_nExp <- NA_integer_
obj$DoubletFinder_pK <- NA_real_
return(obj)
}
'
# --- Early exit: package not installed ---
if (!requireNamespace("DoubletFinder", quietly = TRUE)) {
warning("DoubletFinder not installed. Skipping doublet detection for ", sample_id)
obj$DoubletFinder_class <- "Not_run_package_missing"
obj$DoubletFinder_pANN <- NA_real_
obj$DoubletFinder_nExp <- NA_integer_
obj$DoubletFinder_pK <- NA_real_
doubletfinder_summary_list[[sample_id]] <<- data.frame(
sample_id = sample_id,
n_cells_after_QC = ncol(obj),
doublet_rate = doublet_rate,
pN = NA_real_,
pK = NA_real_,
nExp_unadjusted = NA_integer_,
homotypic_prop = NA_real_,
nExp_adjusted = NA_integer_,
n_singlet = ncol(obj),
n_doublet = NA_integer_,
status = "Not_run_package_missing",
stringsAsFactors = FALSE
)
return(obj)
}
'
log_msg("DoubletFinder START for sample: ", sample_id)
# Apply QC filter before DoubletFinder. DoubletFinder performs poorly
# on low-quality cells that can distort the simulated doublet distribution.
obj <- run_basic_qc(obj)
if (ncol(obj) == 0) {
warning("No cells remain after QC for ", sample_id)
return(NULL)
}
# --- Early exit: sample too small for reliable doublet detection ---
if (ncol(obj) < doubletfinder_min_cells) {
warning(
"Skipping DoubletFinder for ", sample_id,
" because fewer than ", doubletfinder_min_cells,
" cells remain after QC."
)
obj$DoubletFinder_class <- "Not_run_low_cell_count"
obj$DoubletFinder_pANN <- NA_real_
obj$DoubletFinder_nExp <- NA_integer_
obj$DoubletFinder_pK <- NA_real_
doubletfinder_summary_list[[sample_id]] <<- data.frame(
sample_id = sample_id,
n_cells_after_QC = ncol(obj),
doublet_rate = doublet_rate,
pN = NA_real_,
pK = NA_real_,
nExp_unadjusted = NA_integer_,
homotypic_prop = NA_real_,
nExp_adjusted = NA_integer_,
n_singlet = ncol(obj),
n_doublet = NA_integer_,
status = "Not_run_low_cell_count",
stringsAsFactors = FALSE
)
return(obj)
}
# ---------------------------------------------------------
# Temporary preprocessing for DoubletFinder
# ---------------------------------------------------------
# DoubletFinder requires a PCA embedding and cluster assignments.
# We use SCTransform here for consistency with the main pipeline,
# but conserve.memory = TRUE and return.only.var.genes = TRUE keep
# it lightweight. All SCT/PCA/graph outputs are deleted at the end
# of this function — the returned object contains only RNA counts
# and DoubletFinder metadata.
log_msg("DoubletFinder preprocessing START for sample: ", sample_id)
obj <- SCTransform(
obj,
method = "glmGamPoi",
vars.to.regress = "percent.mt",
conserve.memory = TRUE,
return.only.var.genes = TRUE,
verbose = FALSE
)
obj <- RunPCA(obj, npcs = max(doubletfinder_pcs), verbose = FALSE)
obj <- FindNeighbors(obj, reduction = "pca", dims = doubletfinder_pcs, verbose = FALSE)
# Broader resolution set here for FindClusters()
obj <- FindClusters(obj, resolution = 0.5, verbose = FALSE)
log_msg("DoubletFinder preprocessing DONE for sample: ", sample_id)
# ---------------------------------------------------------
# Resolve DoubletFinder function names across package versions
# ---------------------------------------------------------
# DoubletFinder changed its exported function names between versions
# (doubletFinder_v3 -> doubletFinder, paramSweep_v3 -> paramSweep).
# We check for both names so the script works with either version.
df_ns <- asNamespace("DoubletFinder")
doubletFinder_fun <- if (exists("doubletFinder", envir = df_ns)) {
get("doubletFinder", envir = df_ns)
} else if (exists("doubletFinder_v3", envir = df_ns)) {
get("doubletFinder_v3", envir = df_ns)
} else {
stop("Could not find doubletFinder or doubletFinder_v3 in DoubletFinder namespace.")
}
paramSweep_fun <- if (exists("paramSweep", envir = df_ns)) {
get("paramSweep", envir = df_ns)
} else if (exists("paramSweep_v3", envir = df_ns)) {
get("paramSweep_v3", envir = df_ns)
} else {
NULL
}
summarizeSweep_fun <- get("summarizeSweep", envir = df_ns)
find.pK_fun <- get("find.pK", envir = df_ns)
modelHomotypic_fun <- get("modelHomotypic", envir = df_ns)
# ---------------------------------------------------------
# Estimate optimal pK via paramSweep
# ---------------------------------------------------------
# pK is the PC neighbourhood size used by DoubletFinder to define
# the KNN graph for artificial doublet scoring. The optimal value
# is estimated by testing a range of pK values and selecting the one
# that maximises the BCmetric (bimodality coefficient). If paramSweep
# fails for any reason, we fall back to doubletfinder_pK_default.
best_pK <- doubletfinder_pK_default
if (doubletfinder_use_param_sweep && !is.null(paramSweep_fun)) {
best_pK <- tryCatch({
log_msg("DoubletFinder pK sweep START for sample: ", sample_id)
sweep_res <- paramSweep_fun(obj, PCs = doubletfinder_pcs, sct = TRUE)
log_msg("DoubletFinder pK sweep DONE for sample: ", sample_id)
log_msg("DoubletFinder pK summary START for sample: ", sample_id)
sweep_stats <- summarizeSweep_fun(sweep_res, GT = FALSE)
pK_table <- as.data.frame(find.pK_fun(sweep_stats))
pK_values <- as.numeric(as.character(unlist(pK_table[["pK"]])))
bc_values <- as.numeric(as.character(unlist(pK_table[["BCmetric"]])))
valid <- is.finite(pK_values) & is.finite(bc_values)
if (sum(valid) == 0) {
warning("No valid pK/BCmetric values found for ", sample_id, ". Using default pK.")
doubletfinder_pK_default
} else {
chosen_pK <- pK_values[valid][which.max(bc_values[valid])]
log_msg("DoubletFinder selected pK for ", sample_id, ": ", chosen_pK)
chosen_pK
}
}, error = function(e) {
warning(
"DoubletFinder pK sweep failed for ", sample_id,
". Using default pK = ", doubletfinder_pK_default,
". Error: ", e$message
)
doubletfinder_pK_default
})
} else {
log_msg("DoubletFinder pK sweep skipped for ", sample_id, "; using default pK=", best_pK)
}
# ---------------------------------------------------------
# Estimate expected doublets
# ---------------------------------------------------------
# nExp_poi: expected number of doublets given the assumed doublet_rate.
# nExp_poi_adj: adjusted downward by the estimated homotypic proportion,
# because homotypic doublets (two cells of the same type) are
# transcriptionally similar and harder for DoubletFinder to detect.
# Using the adjusted value avoids over-filtering singlets.
nExp_poi <- round(doublet_rate * ncol(obj))
if ("seurat_clusters" %in% colnames(obj@meta.data)) {
obj$seurat_clusters <- as.factor(as.character(obj@meta.data[["seurat_clusters"]]))
}
homotypic_prop <- tryCatch({
modelHomotypic_fun(as.factor(as.character(obj@meta.data[["seurat_clusters"]])))
}, error = function(e) {
warning(
"Homotypic doublet estimate failed for ", sample_id,
". Using unadjusted expected doublet count. Error: ", e$message
)
0
})
nExp_poi_adj <- max(round(nExp_poi * (1 - homotypic_prop)), 1)
# ---------------------------------------------------------
# Force DoubletFinder parameters to simple scalar values
# ---------------------------------------------------------
# The pK sweep may return a value derived from a tibble or data.frame,
# which can cause downstream errors such as:
# Error in xtfrm.data.frame(x) : cannot xtfrm data frames
# Explicitly coercing to numeric scalar [1] prevents this.
best_pK <- as.numeric(best_pK)[1]
doubletfinder_pN_use <- as.numeric(doubletfinder_pN)[1]
nExp_poi_adj <- as.integer(nExp_poi_adj)[1]
if (!is.finite(best_pK)) {
warning("best_pK was not finite for ", sample_id, ". Using default pK.")
best_pK <- as.numeric(doubletfinder_pK_default)[1]
}
if (!is.finite(doubletfinder_pN_use)) {
warning("doubletfinder_pN was not finite for ", sample_id, ". Using pN = 0.25.")
doubletfinder_pN_use <- 0.25
}
if (!is.finite(nExp_poi_adj) || nExp_poi_adj < 1) {
warning("nExp_poi_adj was invalid for ", sample_id, ". Using nExp = 1.")
nExp_poi_adj <- 1L
}
# ---------------------------------------------------------
# Run DoubletFinder
# ---------------------------------------------------------
# Wrapped in tryCatch: if DoubletFinder fails for one sample, the
# cell is marked as "DF_final_call_failed" in metadata and included
# (unfiltered) in the merged object. The pipeline continues.
log_msg(
"DoubletFinder final call START for ", sample_id,
" | pN=", doubletfinder_pN_use,
" | pK=", best_pK,
" | nExp=", nExp_poi_adj
)
df_call_success <- TRUE
obj <- tryCatch({
doubletFinder_fun(
obj,
PCs = doubletfinder_pcs,
pN = doubletfinder_pN_use,
pK = best_pK,
nExp = nExp_poi_adj,
reuse.pANN = NULL,
sct = TRUE
)
}, error = function(e) {
df_call_success <<- FALSE
warning(
"Final DoubletFinder call failed for ", sample_id,
". Returning sample without doublet filtering. Error: ", e$message
)
obj$DoubletFinder_class <- "DF_final_call_failed"
obj$DoubletFinder_pANN <- NA_real_
obj$DoubletFinder_nExp <- nExp_poi_adj
obj$DoubletFinder_pK <- best_pK
obj
})
log_msg("DoubletFinder final call DONE/EXIT for sample: ", sample_id)
# ---------------------------------------------------------
# Extract DoubletFinder classification columns safely
# ---------------------------------------------------------
# DoubletFinder writes metadata columns with auto-generated names
# like DF.classifications_0.25_0.15_119 and pANN_0.25_0.15_119.
# We extract these using obj@meta.data[[col]] (not obj$col) because
# obj$col can return a data-frame-like object in newer Seurat builds,
# which would break subsequent vector operations (e.g. %in%, which).
if (df_call_success) {
class_cols <- grep("^DF.classifications", colnames(obj@meta.data), value = TRUE)
pANN_cols <- grep("^pANN", colnames(obj@meta.data), value = TRUE)
if (length(class_cols) == 0) {
warning("No DoubletFinder classification column found for ", sample_id)
df_class_vec <- rep("Not_found", ncol(obj))
df_pANN_vec <- rep(NA_real_, ncol(obj))
status <- "Classification_not_found"
n_singlet <- NA_integer_
n_doublet <- NA_integer_
} else {
# Use the last matching column in case multiple runs left stale columns.
class_col <- tail(class_cols, 1)
pANN_col <- if (length(pANN_cols) > 0) tail(pANN_cols, 1) else NA_character_
df_class_raw <- obj@meta.data[[class_col]]
if (is.data.frame(df_class_raw)) df_class_raw <- df_class_raw[[1]]
df_class_vec <- as.character(df_class_raw)
if (!is.na(pANN_col)) {
df_pANN_raw <- obj@meta.data[[pANN_col]]
if (is.data.frame(df_pANN_raw)) df_pANN_raw <- df_pANN_raw[[1]]
df_pANN_vec <- suppressWarnings(as.numeric(df_pANN_raw))
} else {
df_pANN_vec <- rep(NA_real_, ncol(obj))
}
status <- "Completed"
n_singlet <- sum(df_class_vec == "Singlet", na.rm = TRUE)
n_doublet <- sum(df_class_vec == "Doublet", na.rm = TRUE)
}
} else {
df_class_vec <- rep("DF_final_call_failed", ncol(obj))
df_pANN_vec <- rep(NA_real_, ncol(obj))
status <- "DF_final_call_failed"
n_singlet <- NA_integer_
n_doublet <- NA_integer_
}
# ---------------------------------------------------------
# Store DoubletFinder results as plain named vectors
# ---------------------------------------------------------
# Force all classification outputs into simple named character/numeric
# vectors before writing to metadata. This prevents Seurat/tibble
# coercion issues in downstream subset() and match() calls.
df_class_vec <- as.character(df_class_vec)
df_pANN_vec <- suppressWarnings(as.numeric(df_pANN_vec))
# Guard against length mismatches (should never happen, but be safe).
if (length(df_class_vec) != ncol(obj)) {
warning(
"DoubletFinder class vector length mismatch for ", sample_id,
". Marking classifications as Not_found."
)
df_class_vec <- rep("Not_found", ncol(obj))
status <- "Classification_length_mismatch"
n_singlet <- NA_integer_
n_doublet <- NA_integer_
}
if (length(df_pANN_vec) != ncol(obj)) {
df_pANN_vec <- rep(NA_real_, ncol(obj))
}
# Name vectors by cell barcode for safe index-based assignment.
names(df_class_vec) <- colnames(obj)
names(df_pANN_vec) <- colnames(obj)
obj@meta.data[["DoubletFinder_class"]] <- df_class_vec
obj@meta.data[["DoubletFinder_pANN"]] <- df_pANN_vec
obj@meta.data[["DoubletFinder_nExp"]] <- rep(as.integer(nExp_poi_adj), ncol(obj))
obj@meta.data[["DoubletFinder_pK"]] <- rep(as.numeric(best_pK), ncol(obj))
# ---------------------------------------------------------
# Write compact DoubletFinder summary row
# ---------------------------------------------------------
# Appended to the global doubletfinder_summary_list and written
# to CSV at the end of the script. Useful for QC review and for
# identifying which patients/samples were affected by doublet issues.
doubletfinder_summary_list[[sample_id]] <<- data.frame(
sample_id = sample_id,
n_cells_after_QC = ncol(obj),
doublet_rate = doublet_rate,
pN = doubletfinder_pN_use,
pK = best_pK,
nExp_unadjusted = nExp_poi,
homotypic_prop = homotypic_prop,
nExp_adjusted = nExp_poi_adj,
n_singlet = n_singlet,
n_doublet = n_doublet,
status = status,
stringsAsFactors = FALSE
)
# ---------------------------------------------------------
# Keep singlets only
# ---------------------------------------------------------
# Direct column indexing (obj[, cells]) is used instead of
# subset(cells = ...) to avoid additional Seurat coercion behavior
# that can cause silent failures when cell names contain special chars.
if (identical(status, "Completed") && any(df_class_vec == "Doublet", na.rm = TRUE)) {
singlet_cells <- names(df_class_vec)[df_class_vec == "Singlet"]
singlet_cells <- intersect(singlet_cells, colnames(obj))
if (length(singlet_cells) == 0) {
warning("No Singlet cells found after DoubletFinder for ", sample_id, ". Returning unfiltered object.")
} else {
obj <- obj[, singlet_cells]
}
rm(singlet_cells)
}
# ---------------------------------------------------------
# Remove temporary DoubletFinder preprocessing outputs
# ---------------------------------------------------------
# SCT assay, PCA reduction, and graph objects were created only
# for DoubletFinder. Removing them here ensures the returned object
# contains only the RNA assay with raw counts, so the main pipeline
# (SCTransform + Harmony) starts from a clean slate.
if ("RNA" %in% names(obj@assays)) DefaultAssay(obj) <- "RNA"
if ("SCT" %in% names(obj@assays)) obj[["SCT"]] <- NULL
if ("pca" %in% names(obj@reductions)) obj[["pca"]] <- NULL
obj@graphs <- list()
gc()
df_elapsed <- round(as.numeric(difftime(Sys.time(), df_start_time, units = "mins")), 2)
log_msg("DoubletFinder DONE for sample: ", sample_id, " | elapsed: ", df_elapsed, " min")
obj
}
# ---------------------------------------------------------
# assign_broad_labels()
# ---------------------------------------------------------
# Scores every cell in `obj` against five broad cell-type marker sets
# using mean log-normalized expression (via AddModuleScore). The
# top-scoring compartment is assigned as broad_label. Cells where the
# margin between the top and second-best score is below
# broad_margin_cutoff receive broad_label_conf = "Ambiguous".
#
# The confident broad label is used as a fallback cell type in
# make_final_cell_type_label() when SingleR does not return a result.
#
# JoinLayers() is called before NormalizeData() to merge per-sample
# split layers into a single unified layer. Without this, AddModuleScore()
# silently reads only the first sample's data, producing near-zero
# expression for all other cells and collapsing every cell to "Ambiguous".
assign_broad_labels <- function(obj) {
DefaultAssay(obj) <- "RNA"
# Merges per-sample split RNA layers (counts.P1_T1, counts.P1_B1, ...)
# into a single unified layer before normalization. Without this,
# NormalizeData() and AddModuleScore() silently read only the first
# layer in Seurat v5, producing near-zero expression for cells from
# all other samples. JoinLayers() is a no-op when layers are already joined
if ("JoinLayers" %in% getNamespaceExports("Seurat")) {
obj <- JoinLayers(obj, assay = "RNA")
}
obj <- NormalizeData(obj, verbose = FALSE)
# Only use markers that are actually present in the dataset.
# Require at least 2 genes per compartment to produce a meaningful score.
present_marker_list <- lapply(broad_marker_list, function(g) intersect(g, rownames(obj)))
present_marker_list <- present_marker_list[lengths(present_marker_list) >= 2]
if (length(present_marker_list) == 0) {
# No usable markers — mark all cells as Ambiguous and return.
obj$broad_label <- NA_character_
obj$broad_margin <- NA_real_
obj$broad_label_conf <- "Ambiguous"
return(obj)
}
# Score each compartment. AddModuleScore appends "1" to the name
# (a quirk of the function); the rename step below strips it.
for (nm in names(present_marker_list)) {
obj <- AddModuleScore(
obj,
features = list(present_marker_list[[nm]]),
name = paste0("broad_", nm),
assay = "RNA"
)
}
# Strip the trailing "1" appended by AddModuleScore.
colnames(obj@meta.data) <- sub("^broad_(.*)1$", "broad_\\1", colnames(obj@meta.data))
# Extract the score columns and derive the top label and margin.
score_cols <- intersect(paste0("broad_", names(present_marker_list)), colnames(obj@meta.data))
score_mat <- obj@meta.data[, score_cols, drop = FALSE]
# Assign the compartment with the highest score as the broad label.
obj$broad_label <- gsub("^broad_", "", colnames(score_mat)[max.col(score_mat, ties.method = "first")])
# Margin = top score minus second-best score.
# A higher margin means the top assignment is more clearly supported.
obj$broad_margin <- if (ncol(score_mat) >= 2) {
apply(t(apply(score_mat, 1, sort, decreasing = TRUE)), 1, function(x) x[1] - x[2])
} else NA_real_
# Confident label: only assigned if margin >= broad_margin_cutoff.
obj$broad_label_conf <- ifelse(
!is.na(obj$broad_margin) & obj$broad_margin >= broad_margin_cutoff,
obj$broad_label,
"Ambiguous"
)
obj
}
# ---------------------------------------------------------
# run_singler_with_centroids()
# ---------------------------------------------------------
# Annotates cells using SingleR against pre-computed HLCA centroid
# references. Centroids are stored as a compact gene x cell-type matrix
# rather than a full reference dataset, which is much faster and uses
# less RAM than a full SCE reference.
#
# Uses the SCT-normalized assay (rather than log-normalized RNA) to
# match the expression scale expected by the HLCA reference.
#
# fine_label_broad maps SingleR fine labels back to broad HLCA
# categories via the centroid reference's broad_map (if available).
run_singler_with_centroids <- function(obj, centroid_ref) {
DefaultAssay(obj) <- "SCT"
# Convert to SingleCellExperiment for SingleR compatibility.
query_sce <- as.SingleCellExperiment(obj, assay = "SCT")
# Build a minimal SCE reference from the centroid matrix.
ref_sce <- SingleCellExperiment(assays = list(logcounts = centroid_ref$centroids))
colData(ref_sce)$label.fine <- centroid_ref$fine_labels
colData(ref_sce)$label.broad <- if (!is.null(centroid_ref$broad_map)) {
unname(centroid_ref$broad_map[centroid_ref$fine_labels])
} else NA_character_
# Restrict to genes present in both query and reference.
common_genes <- intersect(rownames(query_sce), rownames(ref_sce))
query_sce <- query_sce[common_genes, ]
ref_sce <- ref_sce[common_genes, ]
# Run SingleR annotation.
pred <- SingleR(test = query_sce, ref = ref_sce, labels = ref_sce$label.fine)
# pruned.labels removes low-confidence assignments (set to NA).
# Preference for pruned labels but fall back to labels when pruned is NA.
obj$SingleR_label <- as.character(pred$labels)
obj$SingleR_pruned_label <- as.character(pred$pruned.labels)
obj$fine_label <- ifelse(
is.na(obj$SingleR_pruned_label) | obj$SingleR_pruned_label == "",
obj$SingleR_label,
obj$SingleR_pruned_label
)
# Map fine labels back to broad HLCA categories if a broad_map is available.
obj$fine_label_broad <- if (!is.null(centroid_ref$broad_map)) {
unname(centroid_ref$broad_map[as.character(obj$fine_label)])