Upload 3 files
Browse filesFiles changed (3)
- demo/README.mdAdded+62
- demo/bulk_GSE221608.RAdded+475
- demo/scRNA_GSE263733.RAdded+985
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162# P2M.db demos
Two R scripts run from GEO source files to dataset-level analysis tables.
| Script | Dataset | Specimens || --- | --- | --- || `scRNA_GSE263733.R` | Pancreatic cancer single-cell RNA-seq | 23 primary, 7 liver metastases || `bulk_GSE221608.R` | Colorectal cancer RNA-seq | 20 primary, 18 liver metastases, 14 normal |
## Run
Edit `output_dir`, `run_stage` and the analysis parameters at the top of each script, then run:
```bashRscript demo/scRNA_GSE263733.RRscript demo/bulk_GSE221608.R```
You can also pass an output directory and stage on the command line:
```bashRscript demo/scRNA_GSE263733.R results/demo/scRNA-seq/GSE263733 allRscript demo/bulk_GSE221608.R results/demo/bulk/GSE221608 all```
Downloads are cached in `input/`, intermediate files in `work/`, and analysis tables in `analysis/`. Use a separate output directory from the published datasets. Run the single-cell example on the server because its count matrix requires substantial memory.
## R packages
Package loading is listed near the top of each script in `load_packages()`. Single-cell stages use separate R processes so Seurat and the older downstream packages can run in their respective environments.
- Single-cell: Seurat 5, Matrix, data.table, harmony, clusterProfiler, org.Hs.eg.db, CellChat 1.6.1, monocle3 1.3.7 and CytoTRACE 0.3.3.- Bulk: openxlsx, data.table, edgeR, limma, clusterProfiler, org.Hs.eg.db, e1071 and survival.- Doublet detection: Python with DoubletDetection 4.2, numpy, pandas, scipy and phenograph. Both scripts also use the system `gzip` command.
On fatnode, use these environment settings before running from `/400T/maweicheng/P2M.db`:
```bashexport P2M_CORE_RSCRIPT=/home/swyxggyjy/miniconda3/bin/Rscriptexport P2M_FUNCTIONAL_RSCRIPT=/home/swyxggyjy/miniconda3/envs/biosoft/bin/Rscriptexport P2M_CORE_RLIB=/400T/maweicheng/P2M.db/tmp/update/Rlibexport P2M_EXTRA_RLIB=/400T/maweicheng/P2M.db/tmp/update/Rlib:/400T/maweicheng/P2M.db/scRNA-seq/tmp/rerun/Rlibexport P2M_FUNCTIONAL_LIBRARY_PATH=/home/swyxggyjy/miniconda3/envs/biosoft/libexport P2M_PYTHON=/home/swyxggyjy/miniconda3/bin/python
"$P2M_CORE_RSCRIPT" demo/scRNA_GSE263733.R"$P2M_CORE_RSCRIPT" demo/bulk_GSE221608.R```
Existing bulk reference files can be supplied through `P2M_LM22`, `P2M_STRING_INFO`, `P2M_STRING_LINKS`, `P2M_KEGG_GENES` and `P2M_KEGG_NAMES`; otherwise they are downloaded automatically.
## Data and outputs
Each specimen's patient ID, group and tissue are assigned explicitly in `prepare_metadata()`. Primary is the reference group. The single-cell script checks these assignments against the author annotation; the bulk script matches them to the author workbook columns.
The single-cell script exports QC, clustering, author annotations, differential expression, GO/KEGG enrichment, CellChat interactions, trajectories, gene expression summaries and functional-state scores. Raw counts and author cell labels are retained in `GSE263733.rds`.
The bulk script retains raw and source-normalized counts separately in `expression.rds`. Differential expression uses TMM, voom and limma with a fixed patient effect. Positive log2FC indicates higher expression in metastases. Normal tissues are excluded from P/M analyses. The demo adds STRING and LM22 estimates to the released DEG and enrichment analyses. Survival is recorded as not applicable because this cohort has no survival time/event fields.
Both examples save `samples.csv`, `qc.csv`, `dataset.csv`, `modules.csv` and `analysis/software_versions.txt`. Cell-level DE and trajectories are exploratory; unreachable trajectory cells retain missing pseudotime.
To resume, pass an individual stage. Single-cell stages are `import`, `prepare`, `gc`, `deg`, `fe`, `cs`, `ci`, `ct` and `export`. For bulk, `functional` resumes enrichment, PPI, immune and survival modules from the saved expression object and DEG table.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475#!/usr/bin/env Rscript# GSE221608: GEO author counts and specimen metadata to bulk analysis tables.# Input: GEO author workbook; patient, group and tissue assignments listed below.# Output: expression.rds, samples.csv, qc.csv and flat analysis/ tables.# Run: Rscript demo/bulk_GSE221608.R results/demo/bulk/GSE221608# Requires: openxlsx, data.table, edgeR, limma, clusterProfiler, org.Hs.eg.db,# e1071 and survival. Reference URLs and cache overrides are defined below.
options(stringsAsFactors = FALSE)acc <- "GSE221608"metastatic_tissue <- "Liver"
# Paths and run options. Command-line arguments can override these two values.output_dir <- "results/demo/bulk/GSE221608"run_stage <- "all"
# Differential expression, enrichment and PPI.seed <- 42n_workers <- 4deg_p_cutoff <- 0.05deg_adjusted_p_cutoff <- 0.2deg_logfc_cutoff <- 0.5enrichment_p_cutoff <- 1enrichment_q_cutoff <- 1string_min_score <- 700
# Immune deconvolution and survival.immune_permutations <- 1000svr_nu <- 0.5svr_cost <- 1survival_min_samples <- 10survival_min_events <- 5
# R packages. Keep all package loading here, before the analysis functions.load_packages <- function(stage) { suppressPackageStartupMessages({ library(data.table) if (stage %in% c("all", "import")) library(openxlsx) if (stage %in% c("all", "deg")) { library(edgeR) library(limma) } if (stage %in% c("all", "functional", "enrichment")) { library(clusterProfiler) library(org.Hs.eg.db) } if (stage %in% c("all", "functional", "immune")) library(e1071) if (stage %in% c("all", "functional", "survival")) library(survival) })}
# Use existing files when supplied; keep incomplete transfers under .part.fetch <- function(url, path) { if (file.exists(path) && file.info(path)$size > 0) return(path) dir.create(dirname(path), recursive = TRUE, showWarnings = FALSE) options(timeout = max(1200, getOption("timeout"))) message("Downloading: ", url) status <- download.file(url, paste0(path, ".part"), mode = "wb", method = "libcurl") if (status != 0 || !file.exists(paste0(path, ".part")) || file.info(paste0(path, ".part"))$size == 0) stop("Download failed: ", url) stopifnot(file.rename(paste0(path, ".part"), path)) path}
# References can be shared with existing server runs through the named variables.reference_file <- function(name, url, out, variable = "") { local <- if (nzchar(variable)) Sys.getenv(variable) else "" if (nzchar(local)) { if (!file.exists(local)) stop("Reference not found: ", local) return(local) } fetch(url, file.path(out, "input", "resources", name))}
write_analysis <- function(x, name, out) { dir.create(file.path(out, "analysis"), showWarnings = FALSE) write.csv(x, file.path(out, "analysis", name), row.names = FALSE, na = "")}
download_inputs <- function(out) { base <- "https://ftp.ncbi.nlm.nih.gov/geo/series/GSE221nnn/GSE221608/" fetch(paste0(base, "suppl/GSE221608_processed_data.xlsx"), file.path(out, "input", "GSE221608_processed_data.xlsx"))}
# Assign each specimen using its original GEO sample name.# Values on each line: patient_id, sample_class, sampled_tissue, GSM.# Normal tissues are kept in the expression object and excluded from P/M tests.prepare_metadata <- function() { samples <- data.frame(patient_id = character(), sample_class = character(), sampled_tissue = character(), gsm = character())
samples["Group B-4", ] <- c("4", "Metastasis", "Liver", "GSM6890243") samples["Group B-15", ] <- c("15", "Metastasis", "Liver", "GSM6890271") samples["Group B-5", ] <- c("5", "Metastasis", "Liver", "GSM6890245") samples["Group B-7", ] <- c("7", "Metastasis", "Liver", "GSM6890251") samples["Group B-8", ] <- c("8", "Metastasis", "Liver", "GSM6890254") samples["Group B-3", ] <- c("3", "Metastasis", "Liver", "GSM6890240") samples["Group B-10", ] <- c("10", "Metastasis", "Liver", "GSM6890259") samples["Group B-9", ] <- c("9", "Metastasis", "Liver", "GSM6890257") samples["Group B-11", ] <- c("11", "Metastasis", "Liver", "GSM6890262") samples["Group B-12", ] <- c("12", "Metastasis", "Liver", "GSM6890265") samples["Group B-17", ] <- c("17", "Metastasis", "Liver", "GSM6890276") samples["Group B-18", ] <- c("18", "Metastasis", "Liver", "GSM6890278") samples["Group B-19", ] <- c("19", "Metastasis", "Liver", "GSM6890281") samples["Group B-16", ] <- c("16", "Metastasis", "Liver", "GSM6890274") samples["Group B-20", ] <- c("20", "Metastasis", "Liver", "GSM6890283") samples["Group B-1", ] <- c("1", "Metastasis", "Liver", "GSM6890234") samples["Group B-2", ] <- c("2", "Metastasis", "Liver", "GSM6890237") samples["Group B-6", ] <- c("6", "Metastasis", "Liver", "GSM6890248") samples["Group A-1", ] <- c("1", "Primary", "Colorectum", "GSM6890233") samples["Group A-2", ] <- c("2", "Primary", "Colorectum", "GSM6890236") samples["Group A-4", ] <- c("4", "Primary", "Colorectum", "GSM6890242") samples["Group A-15", ] <- c("15", "Primary", "Colorectum", "GSM6890270") samples["Group A-5", ] <- c("5", "Primary", "Colorectum", "GSM6890244") samples["Group A-7", ] <- c("7", "Primary", "Colorectum", "GSM6890250") samples["Group A-8", ] <- c("8", "Primary", "Colorectum", "GSM6890253") samples["Group A-3", ] <- c("3", "Primary", "Colorectum", "GSM6890239") samples["Group A-10", ] <- c("10", "Primary", "Colorectum", "GSM6890258") samples["Group A-9", ] <- c("9", "Primary", "Colorectum", "GSM6890256") samples["Group A-14", ] <- c("14", "Primary", "Colorectum", "GSM6890268") samples["Group A-12", ] <- c("12", "Primary", "Colorectum", "GSM6890264") samples["Group A-13", ] <- c("13", "Primary", "Colorectum", "GSM6890267") samples["Group A-20", ] <- c("20", "Primary", "Colorectum", "GSM6890282") samples["Group A-6", ] <- c("6", "Primary", "Colorectum", "GSM6890247") samples["Group A-11", ] <- c("11", "Primary", "Colorectum", "GSM6890261") samples["Group A-17", ] <- c("17", "Primary", "Colorectum", "GSM6890275") samples["Group A-18", ] <- c("18", "Primary", "Colorectum", "GSM6890277") samples["Group A-19", ] <- c("19", "Primary", "Colorectum", "GSM6890280") samples["Group A-16", ] <- c("16", "Primary", "Colorectum", "GSM6890273") samples["Group C-2", ] <- c("2", "Normal", "Intestinal mucosa", "GSM6890238") samples["Group C-6", ] <- c("6", "Normal", "Intestinal mucosa", "GSM6890249") samples["Group C-5", ] <- c("5", "Normal", "Intestinal mucosa", "GSM6890246") samples["Group C-8", ] <- c("8", "Normal", "Intestinal mucosa", "GSM6890255") samples["Group C-3", ] <- c("3", "Normal", "Intestinal mucosa", "GSM6890241") samples["Group C-10", ] <- c("10", "Normal", "Intestinal mucosa", "GSM6890260") samples["Group C-11", ] <- c("11", "Normal", "Intestinal mucosa", "GSM6890263") samples["Group C-14", ] <- c("14", "Normal", "Intestinal mucosa", "GSM6890269") samples["Group C-12", ] <- c("12", "Normal", "Intestinal mucosa", "GSM6890266") samples["Group C-18", ] <- c("18", "Normal", "Intestinal mucosa", "GSM6890279") samples["Group C-20", ] <- c("20", "Normal", "Intestinal mucosa", "GSM6890284") samples["Group C-1", ] <- c("1", "Normal", "Intestinal mucosa", "GSM6890235") samples["Group C-15", ] <- c("15", "Normal", "Intestinal mucosa", "GSM6890272") samples["Group C-7", ] <- c("7", "Normal", "Intestinal mucosa", "GSM6890252")
samples$sample_id <- rownames(samples) samples$sample_title <- samples$sample_id samples$patient_id <- factor(samples$patient_id) samples$sample_class <- factor(samples$sample_class, levels = c("Primary", "Metastasis", "Normal")) samples$accession <- acc samples$source_excluded <- ifelse(samples$sample_class == "Normal", "Yes", "No") samples$label_source <- "GEO sample metadata" samples$treatment_before_collection <- "No" samples$treatment_source <- "doi:10.1093/procel/pwaf092; Methods" samples}
# The first 52 specimen columns are raw counts; the next 52 repeat their labels# and contain source-normalized counts. Select blocks by position and verify names.# Do not interpret the workbook's genomic Length column as transcript length.import_data <- function(out) { samples <- prepare_metadata() path <- file.path(out, "input", "GSE221608_processed_data.xlsx") tab <- openxlsx::read.xlsx(path, startRow = 11, colNames = FALSE, check.names = FALSE) # Read the header as values so repeated labels and embedded spaces stay intact. header <- as.character(unlist(tab[1, ], use.names = FALSE)) tab <- tab[-1, , drop = FALSE] tab <- tab[!is.na(tab[[2]]) & nzchar(as.character(tab[[2]])), , drop = FALSE] raw_ids <- header[7:58]; normalized_ids <- header[59:110] stopifnot(identical(raw_ids, normalized_ids), setequal(raw_ids, samples$sample_id)) counts <- as.matrix(tab[, 7:58]); normalized <- as.matrix(tab[, 59:110]) storage.mode(counts) <- storage.mode(normalized) <- "numeric" colnames(counts) <- raw_ids; colnames(normalized) <- normalized_ids rownames(counts) <- rownames(normalized) <- as.character(tab[[2]]) stopifnot(!anyDuplicated(rownames(counts)), !anyDuplicated(colnames(counts)), all(is.finite(counts)), all(counts >= 0), all(counts == round(counts)), all(is.finite(normalized))) samples <- samples[match(colnames(counts), samples$sample_id), , drop = FALSE] features <- data.frame(feature_id = rownames(counts), gene = as.character(tab[[1]]), biotype = tab[[3]]) core <- list(expression = counts, samples = samples, features = features, source_normalized_expression = normalized, information = list(accession = acc, expression_type = "Raw counts", normalized_expression_type = "Author source-normalized counts; workbook columns 59:110", comparison = "Metastasis minus Primary; fixed patient effect")) saveRDS(core, file.path(out, "expression.rds"), compress = "gzip") write.csv(samples, file.path(out, "samples.csv"), row.names = FALSE) write.csv(features, file.path(out, "features.csv"), row.names = FALSE) write.csv(data.frame(sample_id = samples$sample_id, sample_class = samples$sample_class, total_counts = colSums(counts), detected_genes = colSums(counts > 0), zero_fraction = colMeans(counts == 0)), file.path(out, "qc.csv"), row.names = FALSE) write.csv(data.frame(accession = acc, genes = nrow(counts), samples = ncol(counts), primary = 20L, metastasis = 18L, other = 14L, patients = length(unique(samples$patient_id))), file.path(out, "dataset.csv"), row.names = FALSE) core}
# Reuse the completed count-data analysis: filterByExpr, TMM, voom and limma.# Include patient as a fixed effect; the contrast is Metastasis minus Primary.run_deg <- function(core, out) { use <- core$samples$sample_class %in% c("Primary", "Metastasis") m <- core$samples[use, ]; counts <- core$expression[, use, drop = FALSE] m$patient_id <- factor(m$patient_id) m$sample_class <- factor(m$sample_class, levels = c("Primary", "Metastasis")) design <- model.matrix(~ patient_id + sample_class, m) stopifnot(qr(design)$rank == ncol(design), nrow(design) > ncol(design)) # Filter on the P/M specimens with the patient-aware design. Normal tissues # stay in expression.rds but do not affect this comparison or its library sizes. dge <- DGEList(counts); keep <- filterByExpr(dge, design = design) dge <- dge[keep, , keep.lib.sizes = FALSE] dge <- calcNormFactors(dge, method = "TMM") # TMM adjusts library scaling; voom estimates precision weights for limma. # These analysis values are kept separately from the deposited raw counts. v <- voom(dge, design, plot = FALSE) fit <- eBayes(lmFit(v, design)) z <- topTable(fit, coef = "sample_classMetastasis", number = Inf, sort.by = "P") deg <- data.frame(feature_id = rownames(z), gene = core$features$gene[match(rownames(z), core$features$feature_id)], log2FC = z$logFC, mean_log2_expression = z$AveExpr, statistic = z$t, p_value = z$P.Value, adjusted_p_value = z$adj.P.Val, accession = acc, comparison_site = "All metastatic sites", design = "Limma voom; fixed patient effect", n_primary = sum(m$sample_class == "Primary"), n_metastasis = sum(m$sample_class == "Metastasis")) write_analysis(deg, "deg.csv", out) saveRDS(list(expression = v$E, samples = m), file.path(out, "work", "voom.rds")) deg}
# Match symbols to Entrez IDs and use tested genes as the enrichment background.# Save all returned terms, as in the released count-data analysis.run_enrichment <- function(deg, out) { prefix <- "https://huggingface.co/datasets/kmmuleelab/P2Mdb/resolve/main/code/resources/" links <- read.delim(reference_file("kegg_genes.tsv", paste0(prefix, "kegg_genes.tsv"), out, "P2M_KEGG_GENES"), header = FALSE) paths <- read.delim(reference_file("kegg_pathways.tsv", paste0(prefix, "kegg_pathways.tsv"), out, "P2M_KEGG_NAMES"), header = FALSE, quote = "") g <- if (startsWith(links[1, 1], "hsa:")) 1L else 2L kg <- data.frame(term = sub("^path:", "", links[[3L - g]]), gene = sub("^hsa:", "", links[[g]])) kn <- data.frame(term = sub("^path:", "", paths[[1]]), name = paths[[2]]) keys <- unique(deg$gene[!is.na(deg$p_value) & !is.na(deg$gene) & nzchar(deg$gene)]) mapping <- AnnotationDbi::select(org.Hs.eg.db, keys = keys, keytype = "SYMBOL", columns = "ENTREZID") mapping <- mapping[!is.na(mapping$ENTREZID), , drop = FALSE]; universe <- unique(mapping$ENTREZID) # Keep the released selection thresholds. The enrichment universe includes # tested genes with valid Entrez mappings, rather than just the selected DEGs. selected <- !is.na(deg$adjusted_p_value) & deg$p_value < deg_p_cutoff & deg$adjusted_p_value < deg_adjusted_p_cutoff & abs(deg$log2FC) > deg_logfc_cutoff ans <- list() for (direction in c("Metastasis", "Primary", "All")) { hit <- selected & (direction == "All" | if (direction == "Metastasis") deg$log2FC > 0 else deg$log2FC < 0) genes <- unique(mapping$ENTREZID[mapping$SYMBOL %in% deg$gene[hit]]) if (length(genes) < 3L) next go <- enrichGO(genes, OrgDb = org.Hs.eg.db, keyType = "ENTREZID", ont = "ALL", universe = universe, pAdjustMethod = "BH", pvalueCutoff = enrichment_p_cutoff, qvalueCutoff = enrichment_q_cutoff) ke <- enricher(genes, universe = universe, TERM2GENE = kg, TERM2NAME = kn, pAdjustMethod = "BH", pvalueCutoff = enrichment_p_cutoff, qvalueCutoff = enrichment_q_cutoff) for (kind in c("GO", "KEGG")) { t <- as.data.frame(if (kind == "GO") go else ke) if (!nrow(t)) next ans[[length(ans) + 1L]] <- data.frame(accession = acc, analysis_type = kind, group = direction, term_id = t$ID, term = t$Description, ontology = if (kind == "GO") t$ONTOLOGY else "", gene_ratio = t$GeneRatio, background_ratio = t$BgRatio, p_value = t$pvalue, adjusted_p_value = t$p.adjust, gene_ids = t$geneID, count = t$Count, comparison_site = "All metastatic sites") } } if (!length(ans)) stop("No enrichment terms returned; inspect the gene mapping") write_analysis(do.call(rbind, ans), "enrichment.csv", out)}
# Collapse duplicate symbols only for gene-based PPI and immune inputs.# Choose the highest mean expression row, breaking ties by feature ID.# The stored raw matrix and feature-level differential results remain intact.collapse_symbols <- function(x, features) { gene <- features$gene[match(rownames(x), features$feature_id)] use <- !is.na(gene) & nzchar(gene) index <- which(use)[order(-rowMeans(x[use, , drop = FALSE]), rownames(x)[use])] index <- index[!duplicated(gene[index])] x <- x[index, , drop = FALSE]; rownames(x) <- gene[index] x}
# Use the portal's linear nu-SVR estimator, with the same nu=0.5 setting.# Negative coefficients are set to zero, then the 22 relative fractions sum to 1.# These are expression-based estimates, not measured cell counts.svr_fractions <- function(signature, response) { fit <- e1071::svm(signature, response, type = "nu-regression", kernel = "linear", cost = svr_cost, nu = svr_nu, scale = FALSE) weights <- as.numeric(t(fit$coefs) %*% fit$SV) weights[weights < 0] <- 0 if (sum(weights) <= 0) stop("SVR produced no positive weights") weights <- weights / sum(weights) fitted <- as.numeric(signature %*% weights) list(weights = weights, correlation = cor(response, fitted), rmse = sqrt(mean((response - fitted)^2)))}
# Deconvolve the author's linear source-normalized expression, restricted to P/M.# Do not exponentiate these values or quantile-normalize RNA-seq data.# Permutation p values describe the deconvolution fit, not a P/M group difference.run_immune <- function(core, out) { path <- Sys.getenv("P2M_LM22", file.path(out, "input", "resources", "LM22.txt")) if (!file.exists(path)) { rda <- reference_file("lm22.rda", "https://raw.githubusercontent.com/IOBR/IOBR/9c74b8eba3fc45a9bd2bd10af5497157e9cb19b0/data/lm22.rda", out) env <- new.env(); load(rda, envir = env) if (!exists("lm22", envir = env, inherits = FALSE)) stop("LM22 object missing") x <- env$lm22 if (is.list(x) && !is.data.frame(x) && "refProfiles" %in% names(x)) x <- x$refProfiles dir.create(dirname(path), recursive = TRUE, showWarnings = FALSE) write.table(as.matrix(x), path, sep = "\t", quote = FALSE, col.names = NA) } signature <- as.matrix(read.delim(path, row.names = 1, check.names = FALSE)) use <- core$samples$sample_class %in% c("Primary", "Metastasis") tissue <- collapse_symbols(core$source_normalized_expression[, use, drop = FALSE], core$features) genes <- sort(intersect(rownames(signature), rownames(tissue))) stopifnot(length(genes) >= 100L) # Align genes by symbol before fitting; the row order in the two files can differ. signature <- signature[genes, , drop = FALSE]; tissue <- tissue[genes, , drop = FALSE] signature <- (signature - mean(signature)) / sd(as.vector(signature)) set.seed(seed) pool <- as.numeric(tissue) null <- vapply(seq_len(immune_permutations), function(i) { response <- as.numeric(scale(sample(pool, nrow(signature), replace = TRUE))) svr_fractions(signature, response)$correlation }, numeric(1)) fits <- lapply(seq_len(ncol(tissue)), function(j) svr_fractions(signature, as.numeric(scale(tissue[, j])))) fractions <- t(vapply(fits, `[[`, numeric(ncol(signature)), "weights")) colnames(fractions) <- colnames(signature) group <- core$samples$sample_class[use] stopifnot(all(is.finite(fractions)), all(abs(rowSums(fractions) - 1) < 1e-8)) detail <- data.frame(sample_id = colnames(tissue), sample_class = group, fractions, check.names = FALSE) detail$p_value <- vapply(fits, function(x) mean(null >= x$correlation), numeric(1)) detail$correlation <- vapply(fits, `[[`, numeric(1), "correlation") detail$rmse <- vapply(fits, `[[`, numeric(1), "rmse") write_analysis(detail, "immune_samples.csv", out) write_analysis(data.frame(cell_type = colnames(signature), primary_mean_fraction = colMeans(fractions[group == "Primary", , drop = FALSE]), metastasis_mean_fraction = colMeans(fractions[group == "Metastasis", , drop = FALSE]), comparison_site = metastatic_tissue), "immune.csv", out) write_analysis(data.frame(gene = genes), "immune_genes.csv", out)}
# Map selected DEG symbols to STRING preferred protein names and retain score >=700 edges.# Pearson correlations are computed across available specimens within each P/M group.# At least three finite pairs and nonzero variance are required for each correlation.run_ppi <- function(expr_mat, samples, deg, output_dir) { info_path <- reference_file("9606.protein.info.v11.0.txt.gz", "https://stringdb-static.org/download/protein.info.v11.0/9606.protein.info.v11.0.txt.gz", output_dir, "P2M_STRING_INFO") links_path <- reference_file("9606.protein.links.v11.0.txt.gz", "https://stringdb-static.org/download/protein.links.v11.0/9606.protein.links.v11.0.txt.gz", output_dir, "P2M_STRING_LINKS") info <- data.table::fread(cmd = paste("gzip -dc", shQuote(info_path)), data.table = FALSE) selected <- deg$p_value < deg_p_cutoff & deg$adjusted_p_value < deg_adjusted_p_cutoff & abs(deg$log2FC) > deg_logfc_cutoff genes <- unique(deg$gene[selected]) map <- info[info$preferred_name %in% genes, 1:2] names(map) <- c("protein", "gene") if (anyDuplicated(map$protein)) stop("Ambiguous STRING protein identifiers") links <- data.table::fread(cmd = paste("gzip -dc", shQuote(links_path)), data.table = FALSE) links <- links[links$combined_score >= string_min_score & links$protein1 %in% map$protein & links$protein2 %in% map$protein, ] links <- links[!duplicated(paste(pmin(links$protein1, links$protein2), pmax(links$protein1, links$protein2))), ] from <- map$gene[match(links$protein1, map$protein)] to <- map$gene[match(links$protein2, map$protein)] correlation <- function(a, b, group) { ids <- samples$sample_id[samples$sample_class == group] x <- expr_mat[a, ids]; y <- expr_mat[b, ids] keep <- is.finite(x) & is.finite(y) if (sum(keep) < 3L || sd(x[keep]) == 0 || sd(y[keep]) == 0) return(NA_real_) cor(x[keep], y[keep], method = "pearson") } d <- data.frame(from_gene = from, from_expression_group = deg$higher_expression_group[match(from, deg$gene)], from_log2FC = deg$log2FC[match(from, deg$gene)], to_gene = to, to_expression_group = deg$higher_expression_group[match(to, deg$gene)], to_log2FC = deg$log2FC[match(to, deg$gene)], string_combined_score = links$combined_score, primary_expression_correlation = mapply(correlation, from, to, MoreArgs = list(group = "Primary")), metastasis_expression_correlation = mapply(correlation, from, to, MoreArgs = list(group = "Metastasis")), comparison_site = rep(metastatic_tissue, length(from))) write_analysis(d, "ppi.csv", output_dir) message("STRING: ", nrow(d), " edges")}
# Run gene-wise Cox models and median-split log-rank tests when time/event fields exist.# GSE221608 does not provide these fields, so this cohort returns not_applicable.run_survival <- function(expr_mat, samples, output_dir) { if (!all(c("os_time", "os_status") %in% names(samples))) { write_analysis(data.frame(gene = character(), sample_class = character(), hazard_ratio = numeric(), ci_lower = numeric(), ci_upper = numeric(), p_value = numeric(), adjusted_p_value = numeric(), logrank_p_value = numeric()), "survival.csv", output_dir) return("not_applicable: GEO annotations do not provide survival time and event status") } tables <- list() for (group in c("Primary", "Metastasis")) for (gene in rownames(expr_mat)) { use <- samples$sample_class == group & is.finite(samples$os_time) & samples$os_time > 0 & samples$os_status %in% c(0, 1) ids <- samples$sample_id[use] d <- data.frame(time = samples$os_time[use], event = samples$os_status[use], expression = expr_mat[gene, ids]) d <- d[is.finite(d$expression), ] if (nrow(d) < survival_min_samples || sum(d$event) < survival_min_events || sd(d$expression) == 0) next fit <- survival::coxph(survival::Surv(time, event) ~ expression, data = d) z <- summary(fit) d$high <- d$expression > median(d$expression) if (length(unique(d$high)) < 2L) next logrank <- survival::survdiff(survival::Surv(time, event) ~ high, data = d) tables[[length(tables) + 1L]] <- data.frame(gene = gene, sample_class = group, hazard_ratio = z$conf.int[1, "exp(coef)"], ci_lower = z$conf.int[1, "lower .95"], ci_upper = z$conf.int[1, "upper .95"], p_value = z$coefficients[1, "Pr(>|z|)"], logrank_p_value = pchisq(logrank$chisq, df = 1, lower.tail = FALSE), specimens = nrow(d), events = sum(d$event)) } if (!length(tables)) return("not_applicable: insufficient survival observations or events") result <- do.call(rbind, tables) result$adjusted_p_value <- ave(result$p_value, result$sample_class, FUN = function(p) p.adjust(p, "BH")) write_analysis(result, "survival.csv", output_dir) "completed"}
# Use the server's functional R installation when it is explicitly configured.# This allows the same entry point to run locally in a complete R environment.main <- function() { args <- commandArgs(TRUE) out <- path.expand(if (length(args)) args[1] else output_dir) stage <- if (length(args) > 1L) args[2] else run_stage if (!stage %in% c("all", "download", "import", "deg", "enrichment", "ppi", "immune", "survival", "functional")) stop("Unknown stage: ", stage) executable <- Sys.getenv("P2M_FUNCTIONAL_RSCRIPT") if (nzchar(executable) && !"--worker" %in% args) { script <- sub("^--file=", "", grep("^--file=", commandArgs(), value = TRUE)[1]) Sys.unsetenv(c("R_HOME", "R_LIBS_SITE", "R_LIBS_USER")) shared <- Sys.getenv("P2M_FUNCTIONAL_LIBRARY_PATH") if (nzchar(shared)) Sys.setenv(LD_LIBRARY_PATH = shared) status <- system2(executable, c("--vanilla", shQuote(script), shQuote(out), stage, "--worker")) if (status != 0) stop("Bulk workflow failed") return(invisible(NULL)) } libraries <- Sys.getenv("P2M_EXTRA_RLIB") if (nzchar(libraries)) .libPaths(c(strsplit(libraries, .Platform$path.sep, fixed = TRUE)[[1]], .libPaths())) Sys.setenv(OMP_NUM_THREADS = n_workers, OPENBLAS_NUM_THREADS = n_workers, MKL_NUM_THREADS = n_workers) set.seed(seed) dir.create(out, recursive = TRUE, showWarnings = FALSE) out <- normalizePath(out) marker <- file.path(out, ".p2m_demo") if (!file.exists(marker)) { if (file.exists(file.path(out, "expression.rds")) || dir.exists(file.path(out, "analysis"))) stop("Choose a separate output directory; existing dataset results are protected") writeLines(acc, marker) } stopifnot(identical(readLines(marker), acc)) dir.create(file.path(out, "work"), showWarnings = FALSE) if (stage %in% c("all", "download", "import")) download_inputs(out) if (stage == "download") return(invisible(NULL)) load_packages(stage) core <- if (stage %in% c("all", "import")) import_data(out) else readRDS(file.path(out, "expression.rds")) if (stage == "import") return(invisible(NULL)) modules <- if (file.exists(file.path(out, "modules.csv"))) read.csv(file.path(out, "modules.csv")) else data.frame(module = character(), status = character()) record <- function(module, status = "completed") { modules <<- rbind(modules[modules$module != module, , drop = FALSE], data.frame(module = module, status = status)) write.csv(modules, file.path(out, "modules.csv"), row.names = FALSE) } stages <- if (stage == "all") c("deg", "enrichment", "ppi", "immune", "survival") else if (stage == "functional") c("enrichment", "ppi", "immune", "survival") else stage for (s in stages) { message(acc, ": ", s) if (s == "deg") { deg <- run_deg(core, out); record("Differential expression") } else if (s == "enrichment") { deg <- read.csv(file.path(out, "analysis", "deg.csv"), check.names = FALSE) run_enrichment(deg, out); record("Functional enrichment") } else if (s == "ppi") { d <- readRDS(file.path(out, "work", "voom.rds")) expression <- collapse_symbols(d$expression, core$features) deg <- read.csv(file.path(out, "analysis", "deg.csv"), check.names = FALSE) deg$higher_expression_group <- ifelse(deg$log2FC > 0, "Metastasis", "Primary") run_ppi(expression, d$samples, deg, out); record("Protein interactions") } else if (s == "immune") { run_immune(core, out); record("Immune infiltration") } else if (s == "survival") { use <- core$samples$sample_class %in% c("Primary", "Metastasis") expression <- collapse_symbols(log2(core$source_normalized_expression[, use, drop = FALSE] + 1), core$features) record("Survival", run_survival(expression, core$samples[use, ], out)) } capture.output(sessionInfo(), file = file.path(out, "analysis", "software_versions.txt")) }}
if (sys.nframe() == 0L) main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985#!/usr/bin/env Rscript# GSE263733: source counts and author labels to the P2M analysis tables.# Inputs: GEO Raw_counts and Cell_annotation files; explicit specimen assignments below.# Outputs: GSE263733.rds, samples.csv, qc.csv and the flat analysis/ directory.# Run: Rscript demo/scRNA_GSE263733.R results/demo/scRNA-seq/GSE263733# Requires: Seurat 5, Matrix, data.table, harmony, clusterProfiler, org.Hs.eg.db,# CellChat, monocle3, CytoTRACE, and Python DoubletDetection 4.2.
options(stringsAsFactors = FALSE)acc <- "GSE263733"
# Paths and run options. Command-line arguments can override these two values.output_dir <- "results/demo/scRNA-seq/GSE263733"run_stage <- "all"
# QC, normalization and embeddings.seed <- 42n_workers <- 4min_gene_cells <- 3min_cell_features <- 200min_cell_counts <- 200max_mito_percent <- 15normalization_scale <- 10000variable_genes <- 2000summary_genes <- 1000pca_components <- 30harmony_dimensions <- 1:20harmony_lambda <- 1cluster_resolution <- 0.8
# Differential expression and enrichment.min_de_cells <- 3de_min_pct <- 0.1de_test_logfc <- 0.25deg_p_cutoff <- 0.05deg_adjusted_p_cutoff <- 0.2deg_logfc_cutoff <- 0.5enrichment_p_cutoff <- 0.05enrichment_q_cutoff <- 0.2
# CellChat, functional states and CytoTRACE.cellchat_min_cells <- 10score_bins <- 24score_controls <- 100cytotrace_subsample <- 1000
# R packages. Load each group in the R environment used for that stage.load_packages <- function(stage) { suppressPackageStartupMessages({ library(Matrix) library(data.table) if (stage %in% c("import", "prepare", "deg", "cs")) library(Seurat) if (stage == "prepare") library(harmony) if (stage == "fe") { library(clusterProfiler) library(org.Hs.eg.db) } if (stage == "ci") library(CellChat) if (stage == "ct") { library(monocle3) library(CytoTRACE) b_text <- deparse(body(CytoTRACE::CytoTRACE)) target <- "mat2 <- t(data.frame(t(mat2))[colnames(a1), ])" if (any(grepl(target, b_text, fixed = TRUE))) { b_text <- sub(target, "mat2 <- NULL", b_text, fixed = TRUE) new_fn <- CytoTRACE::CytoTRACE body(new_fn) <- parse(text = paste(b_text, collapse = "\n")) environment(new_fn) <- environment(CytoTRACE::CytoTRACE) assignInNamespace("CytoTRACE", new_fn, ns = "CytoTRACE") } } })}
# Reuse cached downloads. A failed transfer never replaces a complete file.fetch <- function(url, path) { if (file.exists(path) && file.info(path)$size > 0) return(path) dir.create(dirname(path), recursive = TRUE, showWarnings = FALSE) options(timeout = max(1200, getOption("timeout"))) message("Downloading: ", url) status <- download.file(url, paste0(path, ".part"), mode = "wb", method = "libcurl") if (status != 0 || !file.exists(paste0(path, ".part")) || file.info(paste0(path, ".part"))$size == 0) stop("Download failed: ", url) stopifnot(file.rename(paste0(path, ".part"), path)) path}
# Download the original gene-by-cell counts and the authors' per-cell annotation.download_inputs <- function(out) { prefix <- "https://ftp.ncbi.nlm.nih.gov/geo/series/GSE263nnn/GSE263733/suppl/" for (name in c("GSE263733_Raw_counts.txt.gz", "GSE263733_Cell_annotation.txt.gz")) fetch(paste0(prefix, name), file.path(out, "input", name)) for (name in c("cell_states.csv", "kegg_genes.tsv", "kegg_pathways.tsv")) fetch(paste0("https://huggingface.co/datasets/kmmuleelab/P2Mdb/resolve/main/code/resources/", name), file.path(out, "input", "resources", name))}
# Assign each specimen explicitly using the original paper and author annotation.# The three values below are patient_id, sample_class and sampled_tissue.prepare_metadata <- function(out) { input <- file.path(out, "input") samples <- data.frame(patient_id = character(), sample_class = character(), sampled_tissue = character())
samples["PB2032-PAAD-T2", ] <- c("PB2032", "Primary", "Pancreas") samples["PB2032-PAAD-T", ] <- c("PB2032", "Primary", "Pancreas") samples["PB2151-PAAD-T1", ] <- c("PB2151", "Primary", "Pancreas") samples["PB2151-PAAD-T", ] <- c("PB2151", "Primary", "Pancreas") samples["PB2155-Livermeta-T", ] <- c("PB2155", "Metastasis", "Liver") samples["PB2155-PAAD-T", ] <- c("PB2155", "Primary", "Pancreas") samples["PB2191-Livermeta-T", ] <- c("PB2191", "Metastasis", "Liver") samples["PB2191-PAAD-T", ] <- c("PB2191", "Primary", "Pancreas") samples["PB2203-PAAD-T", ] <- c("PB2203", "Primary", "Pancreas") samples["PB2218-PAAD-T", ] <- c("PB2218", "Primary", "Pancreas") samples["PB2219-PAAD-T", ] <- c("PB2219", "Primary", "Pancreas") samples["PB2256-PAAD-T", ] <- c("PB2256", "Primary", "Pancreas") samples["PB2264-Livermeta-T", ] <- c("PB2264", "Metastasis", "Liver") samples["PB2264-PAAD-T", ] <- c("PB2264", "Primary", "Pancreas") samples["PB2265-PAAD-T", ] <- c("PB2265", "Primary", "Pancreas") samples["PB2266-PAAD-T", ] <- c("PB2266", "Primary", "Pancreas") samples["PB2268-PAAD-T", ] <- c("PB2268", "Primary", "Pancreas") samples["PB2281-PAAD-T", ] <- c("PB2281", "Primary", "Pancreas") samples["PB2286-PAAD-T", ] <- c("PB2286", "Primary", "Pancreas") samples["PB2287-PAAD-T", ] <- c("PB2287", "Primary", "Pancreas") samples["PB2311-Livermeta-T", ] <- c("PB2311", "Metastasis", "Liver") samples["PB2311-PAAD-T", ] <- c("PB2311", "Primary", "Pancreas") samples["PB2341-PAAD-T", ] <- c("PB2341", "Primary", "Pancreas") samples["PB2349-Livermeta-T", ] <- c("PB2349", "Metastasis", "Liver") samples["PB2349-PAAD-T", ] <- c("PB2349", "Primary", "Pancreas") samples["PB2366-PAAD-T", ] <- c("PB2366", "Primary", "Pancreas") samples["PB2409-Livermeta-T", ] <- c("PB2409", "Metastasis", "Liver") samples["PB2409-PAAD-T", ] <- c("PB2409", "Primary", "Pancreas") samples["PB2410-Livermeta-T", ] <- c("PB2410", "Metastasis", "Liver") samples["PB2410-PAAD-T", ] <- c("PB2410", "Primary", "Pancreas")
samples$sample_id <- rownames(samples) samples$sample_class <- factor(samples$sample_class, levels = c("Primary", "Metastasis")) samples$accession <- acc samples$specimen_role <- ifelse(samples$sample_class == "Primary", "primary_tumor", "metastatic_tumor") samples$treatment_status <- "untreated" samples$specimen_label_source <- "GEO author Origins field; DOI 10.1186/s12943-024-02003-0" samples$sample_identity_source <- "Original author specimen name in the cell barcode" samples$expression_file <- "GSE263733_Raw_counts.txt.gz"
# The author file supplies the cell barcodes and cell type labels. # Use the specimen prefix to attach the assignments above to individual cells. ann <- data.table::fread(cmd = paste("gzip -dc", shQuote(file.path(input, "GSE263733_Cell_annotation.txt.gz"))), data.table = FALSE) ann <- ann[ann$Origins %in% c("Pm0", "Pm1", "Lm"), , drop = FALSE] stopifnot(all(c("Barcodes", "Patients", "Origins", "Celltypes") %in% names(ann)), !anyDuplicated(ann$Barcodes), all(ann$Origins %in% c("Pm0", "Pm1", "Lm"))) ann$sample_id <- sub("_[^_]+$", "", ann$Barcodes) stopifnot(setequal(unique(ann$sample_id), samples$sample_id)) sample_index <- match(ann$sample_id, samples$sample_id)
# Check the explicit assignments against the original annotation. # Pm0 and Pm1 are primary pancreas tissues; Lm denotes liver metastasis. stopifnot(all(ann$Patients == samples$patient_id[sample_index]), all((ann$Origins == "Lm") == (samples$sample_class[sample_index] == "Metastasis"))) samples$source_origin <- ann$Origins[match(samples$sample_id, ann$sample_id)] annotations <- data.frame(sample_id = ann$sample_id, source_barcode = ann$Barcodes, cell_type = ann$Celltypes, annotation_method = "author_labels", annotation_source = "GEO GSE263733_Cell_annotation.txt.gz; DOI 10.1186/s12943-024-02003-0", author_cell_id = ann$Barcodes, author_origin = ann$Origins) write.csv(samples, file.path(input, "samples.csv"), row.names = FALSE) write.csv(annotations, file.path(input, "annotations.csv"), row.names = FALSE) invisible(samples)}
# Apply the same per-specimen QC as the completed cohort pipeline.# Genes need >=3 expressing cells; cells need >=200 genes, >200 counts and <15% MT counts.# Keep raw integer counts. No upper count cutoff or missing-value imputation is added.prepare_counts <- function(out) { input <- file.path(out, "input"); work <- file.path(out, "work", "qc") if (file.exists(file.path(work, "after_qc.rds"))) return(invisible(NULL)) dir.create(work, recursive = TRUE, showWarnings = FALSE) samples <- prepare_metadata(out) tab <- fread(cmd = paste("gzip -dc", shQuote(file.path(input, "GSE263733_Raw_counts.txt.gz"))), check.names = FALSE) # The source header omits the unnamed first gene-ID column; fread detects it. genes <- as.character(tab[[1]]) barcodes <- names(tab)[-1] stopifnot(!anyDuplicated(genes), !anyDuplicated(barcodes)) specimen <- sub("_[^_]+$", "", barcodes) keep_cells <- specimen %in% samples$sample_id stopifnot(setequal(unique(specimen[keep_cells]), samples$sample_id)) objects <- list(); qc <- list() for (i in seq_len(nrow(samples))) { s <- samples[i, ] sample_cols <- which(specimen == s$sample_id) + 1L x <- Matrix(as.matrix(tab[, sample_cols, with = FALSE]), sparse = TRUE) rownames(x) <- genes stopifnot(all(is.finite(x@x)), all(x@x >= 0), all(x@x == round(x@x))) n_input <- ncol(x) # Apply gene/cell filters within each specimen, before merging the cohort. # A gene retained in one specimen can still be absent from another specimen. o <- CreateSeuratObject(x, project = s$sample_id, min.cells = min_gene_cells, min.features = min_cell_features) n_create <- ncol(o) mt <- grep("^MT-", rownames(o), value = TRUE) if (!length(mt)) stop("Mitochondrial genes unavailable: ", s$sample_id) # Mitochondrial percentage uses raw counts and the MT- gene symbols. # These thresholds reproduce this cohort's recorded filtering step. o$percent.mt <- PercentageFeatureSet(o, features = mt) o <- subset(o, cells = colnames(o)[o$nCount_RNA > min_cell_counts & o$percent.mt < max_mito_percent]) o$source_barcode <- colnames(o) o[["RNA"]] <- AddMetaData(o[["RNA"]], data.frame(gene_symbol = genes[match(rownames(o), gsub("_", "-", genes, fixed = TRUE))], row.names = rownames(o))) for (k in setdiff(names(samples), "expression_file")) o[[k]] <- s[[k]] # Add a specimen prefix because cell barcodes can repeat between libraries. # Keep source_barcode separately for matching back to the author annotation. o <- RenameCells(o, add.cell.id = s$sample_id) folder <- file.path(work, s$sample_id); dir.create(folder, showWarnings = FALSE) writeMM(GetAssayData(o, layer = "counts"), file.path(folder, "counts.mtx")) writeLines(colnames(o), file.path(folder, "cells.txt")) objects[[s$sample_id]] <- o qc[[i]] <- data.frame(sample_id = s$sample_id, input_cells = n_input, after_create = n_create, after_qc = ncol(o)) message(s$sample_id, ": ", n_input, " input; ", ncol(o), " after QC") } rm(tab); gc() saveRDS(objects, file.path(work, "after_qc.rds"), compress = FALSE) write.csv(samples, file.path(work, "samples.csv"), row.names = FALSE) write.csv(do.call(rbind, qc), file.path(work, "qc.csv"), row.names = FALSE)}
# Remove only called doublets; retain unresolved calls and the authors' cell labels.# Match annotations by specimen and source barcode before merging specimen objects.finish_counts <- function(out) { dest <- file.path(out, paste0(acc, ".rds")) if (file.exists(dest)) return(invisible(NULL)) work <- file.path(out, "work", "qc") objects <- readRDS(file.path(work, "after_qc.rds")) samples <- read.csv(file.path(work, "samples.csv"), check.names = FALSE) qc <- read.csv(file.path(work, "qc.csv")) annotations <- read.csv(file.path(out, "input", "annotations.csv"), check.names = FALSE) key <- paste(annotations$sample_id, annotations$source_barcode, sep = "::") stopifnot(!anyDuplicated(key)) for (sample_id in names(objects)) { # DoubletDetection returns calls in the same cell order as counts.mtx. # Check the IDs before removing cells, rather than relying on row position alone. d <- data.table::fread(file.path(work, sample_id, "doublets.tsv"), data.table = FALSE) stopifnot(identical(d$cell_id, colnames(objects[[sample_id]])), all(d$label %in% c("singlet", "doublet", "unresolved"))) objects[[sample_id]]$doublet_status <- d$label objects[[sample_id]] <- objects[[sample_id]][, d$label != "doublet"] qc$after_doublet[qc$sample_id == sample_id] <- ncol(objects[[sample_id]]) qc$doublet_unresolved[qc$sample_id == sample_id] <- sum(d$label == "unresolved") } o <- JoinLayers(merge(objects[[1]], y = objects[-1]), assay = "RNA") # Seurat's merge may discard feature metadata; restore it by exact feature ID. feature_map <- vapply(rownames(o), function(g) { for (z in objects) if (g %in% rownames(z)) return(as.character(z[["RNA"]][[]][g, "gene_symbol"])) stop("Missing source feature: ", g) }, character(1)) o[["RNA"]] <- AddMetaData(o[["RNA"]], data.frame(gene_symbol = feature_map, row.names = rownames(o))) # Keep the raw counts layer. Store log1p(counts / library size * 10000) # in the data layer for expression summaries and downstream Seurat functions. o <- NormalizeData(o, normalization.method = "LogNormalize", scale.factor = normalization_scale, verbose = FALSE) o <- FindVariableFeatures(o, selection.method = "vst", nfeatures = variable_genes, verbose = FALSE) # QC and doublet filtering remove cells but do not change their annotation keys. # Require an exact author-label match for every retained cell; do not fill gaps. index <- match(paste(o$sample_id, o$source_barcode, sep = "::"), key) stopifnot(!anyNA(index)) for (k in c("cell_type", "annotation_method", "annotation_source", "author_cell_id", "author_origin")) o[[k]] <- annotations[[k]][index] o$celltype_article <- o$cell_type samples$cells <- as.integer(table(factor(o$sample_id, levels = samples$sample_id))) stopifnot(ncol(o) == sum(qc$after_doublet), !anyDuplicated(colnames(o)), identical(colnames(o), rownames(o@meta.data))) saveRDS(o, dest, compress = "gzip") write.csv(samples, file.path(out, "samples.csv"), row.names = FALSE) write.csv(qc, file.path(out, "qc.csv"), row.names = FALSE) write.csv(data.frame(accession = acc, cancer_type = "Pancreatic Ductal Adenocarcinoma", primary_site = "Pancreas", metastatic_site = "Liver", cells = ncol(o), genes = nrow(o), primary_samples = 23L, metastatic_samples = 7L), file.path(out, "dataset.csv"), row.names = FALSE)}
# Run the project's per-specimen DoubletDetection step from this R entry point.# The short Python helper is written under work/; no separate source file is needed.run_doublets <- function(out) { path <- file.path(out, "work", "doublets.py") writeLines(r"---(from pathlib import Pathimport sys, osfor key in ('OPENBLAS_NUM_THREADS', 'OMP_NUM_THREADS', 'MKL_NUM_THREADS'): os.environ[key] = '1'import multiprocessingtry: multiprocessing.set_start_method('fork')except RuntimeError: passimport numpy as npimport pandas as pdfrom scipy.io import mmreadimport doubletdetectionfrom functools import partialimport phenograph.core
if __name__ == '__main__': # Limit PhenoGraph's internal Jaccard workers as well as the classifier workers. n_jobs = int(sys.argv[2]) phenograph.core.Pool = partial(multiprocessing.Pool, processes=n_jobs) work = Path(sys.argv[1]) samples = pd.read_csv(work / 'samples.csv') for sample_id in samples.sample_id: folder = work / sample_id target = folder / 'doublets.tsv' if target.exists(): continue cells = (folder / 'cells.txt').read_text().splitlines() counts = mmread(folder / 'counts.mtx').tocsr().T.tocsr() if counts.shape[0] != len(cells): raise ValueError('Doublet input alignment mismatch: ' + sample_id) # Tiny specimens do not support the default 30-component PCA. # Keep unresolved cells; do not silently classify them as singlets. if min(counts.shape) < 30: labels = np.full(len(cells), np.nan) else: labels = doubletdetection.BoostClassifier(n_jobs=n_jobs).fit(counts).predict() if len(labels) != len(cells) or not np.isin(labels[~np.isnan(labels)], [0, 1]).all(): raise ValueError('Invalid doublet calls: ' + sample_id) pd.DataFrame({'cell_id': cells, 'label': np.where(np.isnan(labels), 'unresolved', np.where(labels == 0, 'singlet', 'doublet'))}).to_csv( str(target) + '.part', sep='\t', index=False) Path(str(target) + '.part').rename(target) print(sample_id, 'cells', len(cells), 'doublets', int((labels == 1).sum()), flush=True))---", path) python <- Sys.getenv("P2M_PYTHON", "python3") status <- system2(python, c(shQuote(path), shQuote(file.path(out, "work", "qc")), as.character(n_workers))) if (status != 0) stop("DoubletDetection failed")}
# Retain the completed cohort's analysis calls and parameters.# Cell-level Wilcoxon tests are exploratory; they do not model patient replication.# Counts remain unchanged; Harmony affects embeddings, not the expression assay.run_analysis <- function(mode, output_dir) { work <- file.path(output_dir, "work", "analysis") input <- output_dir resource_dir <- file.path(output_dir, "input", "resources") out <- file.path(work, "analysis") dir.create(work, recursive = TRUE, showWarnings = FALSE) set.seed(seed) sites <- c(liver = "Liver") methods <- c(cu = "cell_type") method_names <- c(cu = "Curated") put <- function(x, path) { dir.create(dirname(path), recursive = TRUE, showWarnings = FALSE) write.csv(x, path, row.names = FALSE, na = "") } pack <- function(x) paste(x, collapse = ";") safe_type <- function(x) gsub("[/\\\\]", "_", x) clinical_type <- function(cell_meta) paste0(cell_meta$sampled_tissue, ifelse(cell_meta$specimen_role == "primary_tumor", "(P)", "(M)"))
# 1. PCA, Harmony, clustering and UMAP. # Use the existing normalized RNA assay and the same variable genes. # Harmony adjusts the embedding by specimen; it does not change raw counts # or the normalized expression used for DE and expression summaries. if (mode == "prepare") { if (file.exists(file.path(work, "prepare.done"))) return(invisible(NULL)) seurat_obj <- readRDS(file.path(input, paste0(acc, ".rds"))) if (inherits(seurat_obj[["RNA"]], "Assay5")) seurat_obj <- JoinLayers(seurat_obj, assay = "RNA") DefaultAssay(seurat_obj) <- "RNA" if (!"data" %in% Layers(seurat_obj[["RNA"]])) seurat_obj <- NormalizeData(seurat_obj, verbose = FALSE) if (!length(VariableFeatures(seurat_obj))) seurat_obj <- FindVariableFeatures(seurat_obj, nfeatures = variable_genes, verbose = FALSE)
# Scale only the 2,000 variable genes, then compute 30 PCs. # Neighbors and UMAP use the first 20 Harmony dimensions. seurat_obj <- ScaleData(seurat_obj, features = VariableFeatures(seurat_obj), verbose = FALSE) seurat_obj <- RunPCA(seurat_obj, features = VariableFeatures(seurat_obj), npcs = pca_components, verbose = FALSE) seurat_obj <- RunHarmony(seurat_obj, group.by.vars = "sample_id", lambda = harmony_lambda, verbose = FALSE) seurat_obj <- FindNeighbors(seurat_obj, reduction = "harmony", dims = harmony_dimensions, verbose = FALSE) seurat_obj <- FindClusters(seurat_obj, resolution = cluster_resolution, verbose = FALSE) seurat_obj <- RunUMAP(seurat_obj, reduction = "harmony", dims = harmony_dimensions, seed.use = seed, verbose = FALSE) cell_meta <- seurat_obj@meta.data cell_meta$cell_id <- rownames(cell_meta) cell_meta$umap_1 <- Embeddings(seurat_obj, "umap")[, 1] cell_meta$umap_2 <- Embeddings(seurat_obj, "umap")[, 2] cell_meta$sample_type <- clinical_type(cell_meta) seurat_obj$sample_type <- cell_meta$sample_type seurat_obj$umap_1 <- cell_meta$umap_1 seurat_obj$umap_2 <- cell_meta$umap_2
# Keep the first 1,000 variable genes in a fixed order for gene summaries # and the expression values stored with the trajectory. top <- head(VariableFeatures(seurat_obj), summary_genes)
# Save the expression matrices, cell metadata and coordinates together. # All downstream stages use this same cell order. prep <- list(counts = GetAssayData(seurat_obj, assay = "RNA", layer = "counts"), data = GetAssayData(seurat_obj, assay = "RNA", layer = "data"), meta = cell_meta, features = top, umap = Embeddings(seurat_obj, "umap"), sites = sites, gene_symbols = setNames(if ("gene_symbol" %in% names(seurat_obj[["RNA"]][[]])) as.character(seurat_obj[["RNA"]][[]]$gene_symbol) else rownames(seurat_obj), rownames(seurat_obj))) stopifnot(identical(colnames(prep$data), cell_meta$cell_id), all(c("primary_tumor", "metastatic_tumor") %in% cell_meta$specimen_role)) saveRDS(prep, file.path(work, "prepared.rds"), compress = FALSE) saveRDS(seurat_obj, file.path(work, "object.rds"), compress = "gzip") put(data.frame(accession = acc, site = names(sites), tissue = unname(sites), primary_cells = sum(cell_meta$specimen_role == "primary_tumor"), metastatic_cells = vapply(sites, function(s) sum(cell_meta$specimen_role == "metastatic_tumor" & cell_meta$sampled_tissue == s), integer(1))), file.path(work, "comparisons.csv")) writeLines(capture.output(sessionInfo()), file.path(work, "prepare_session.txt")) file.create(file.path(work, "prepare.done")) message(acc, " PREPARED ", ncol(seurat_obj), " cells") return(invisible(NULL)) } prepared <- readRDS(file.path(work, "prepared.rds")) cell_meta <- prepared$meta methods <- methods[vapply(methods, function(k) k %in% names(cell_meta) && any(!is.na(cell_meta[[k]]) & nzchar(cell_meta[[k]])), logical(1))]
# Define the comparison from specimen metadata: pancreas primary tumors # versus actual liver metastases. No cells from other tissue roles enter it. pair_cells <- function(site) which(cell_meta$specimen_role == "primary_tumor" | (cell_meta$specimen_role == "metastatic_tumor" & cell_meta$sampled_tissue == sites[[site]])) pair_class <- function(cell_index) { factor(cell_meta$sample_class[cell_index], levels = c("Primary", "Metastasis")) }
# CellChat and functional-state gene sets use gene symbols. # Sum count rows that map to the same symbol, then normalize those sums. # This derived matrix is used only for these two modules; the saved RNA # assay keeps its original features and counts. symbol_expression <- function(prepared) { gene_symbols <- prepared$gene_symbols if (is.null(gene_symbols)) { seurat_obj <- readRDS(file.path(work, "object.rds")) fm <- seurat_obj[["RNA"]][[]] gene_symbols <- setNames(if ("gene_symbol" %in% names(fm)) as.character(fm$gene_symbol) else rownames(fm), rownames(fm)) rm(seurat_obj) gc() } symbols <- unname(gene_symbols[rownames(prepared$counts)]) symbols[is.na(symbols) | !nzchar(symbols)] <- rownames(prepared$counts)[is.na(symbols) | !nzchar(symbols)] unique_symbols <- unique(symbols) aggregation <- Matrix::sparseMatrix(i = match(symbols, unique_symbols), j = seq_along(symbols), x = 1, dims = c(length(unique_symbols), length(symbols)), dimnames = list(unique_symbols, rownames(prepared$counts))) counts_symbol <- aggregation %*% prepared$counts normalized_symbol <- log1p(counts_symbol %*% Matrix::Diagonal(x = normalization_scale / pmax(Matrix::colSums(counts_symbol), 1))) dimnames(normalized_symbol) <- dimnames(counts_symbol) list(counts = counts_symbol, data = normalized_symbol) }
# Count cells, specimens and patients in each group before testing. # An all-cell comparison and cell type-specific comparisons are recorded # separately, so cell counts are not mistaken for patient counts. if (mode %in% c("deg", "groups")) { groups <- list() for (site in names(sites)) for (method in names(methods)) { cell_index <- pair_cells(site) classes <- pair_class(cell_index) labels <- cell_meta[[methods[[method]]]][cell_index] for (type in c("allcell", sort(unique(na.omit(labels))))) for (group in c("Primary", "Metastasis")) { keep <- classes == group & (type == "allcell" | (!is.na(labels) & labels == type)) cells <- cell_index[which(keep)] groups[[length(groups) + 1L]] <- data.frame(accession = acc, metastatic_tissue = sites[[site]], annotation = method_names[[method]], cell_type = type, group = group, cells = length(cells), samples = length(unique(cell_meta$sample_id[cells])), patients = if ("patient_id" %in% names(cell_meta)) length(unique(cell_meta$patient_id[cells][!is.na(cell_meta$patient_id[cells]) & nzchar(cell_meta$patient_id[cells])])) else NA_integer_) } } put(do.call(rbind, groups), file.path(work, "comparison_groups.csv")) if (mode == "groups") return(invisible(NULL)) }
# 2. Differential expression: Metastasis relative to Primary. # Run Wilcoxon tests on normalized expression, for all cells and then # within each author-defined cell type. Require at least three cells per # group. These are exploratory cell-level tests, without a patient term. # Differential expression within each original author cell type. # The full tested gene tables are exported; the enrichment step applies its # recorded significance thresholds later. if (mode == "deg") { for (site in names(sites)) { cell_index <- pair_cells(site) groups <- pair_class(cell_index) labels <- cell_meta$cell_type[cell_index] seurat_obj <- CreateSeuratObject( prepared$counts[, cell_index], meta.data = cell_meta[cell_index, , drop = FALSE], min.cells = 0, min.features = 0 ) seurat_obj <- SetAssayData( seurat_obj, assay = "RNA", layer = "data", new.data = prepared$data[, cell_index] ) seurat_obj$comparison_group <- groups cell_types <- c("allcell", sort(unique(na.omit(labels[nzchar(labels)])))) for (cell_type in cell_types) { if (tolower(cell_type) %in% c("unresolved", "unknown", "unassigned")) next cells <- if (cell_type == "allcell") seq_along(cell_index) else which(labels == cell_type) n_cells <- table(factor(groups[cells], levels = c("Primary", "Metastasis"))) if (any(n_cells < min_de_cells)) next dest <- file.path(out, paste0("primary_vs_", sites[[site]]), "DEG", "Curated", paste0(safe_type(cell_type), ".csv")) if (file.exists(dest)) next
# Seurat returns positive log2 fold changes for the first group, # Metastasis. The assay contains log-normalized RNA expression. markers <- FindMarkers( seurat_obj[, cells], ident.1 = "Metastasis", ident.2 = "Primary", group.by = "comparison_group", test.use = "wilcox", min.pct = de_min_pct, logfc.threshold = de_test_logfc, verbose = FALSE ) results <- data.frame( gene = rownames(markers), cell_type = rep(cell_type, nrow(markers)), p_value = markers$p_val, log2fc = markers$avg_log2FC, pct_group1 = markers$pct.1, pct_group2 = markers$pct.2, p_adjusted = markers$p_val_adj, group1 = rep("Metastasis", nrow(markers)), group2 = rep("Primary", nrow(markers)), check.names = FALSE ) results <- results[order(results$p_adjusted, -abs(results$log2fc)), ] put(results, dest) } } }
# 3. Gene characteristics for the first 1,000 variable genes. # Detection fraction: cells with expression >0 divided by all cells of that # type in the group. Mean expression includes zeros. If a cell type is absent # from one group, its counts and summaries remain zero, as in the release. if (mode == "gc") { for (site in names(sites)) { cell_index <- pair_cells(site) groups <- pair_class(cell_index) labels <- cell_meta$cell_type[cell_index] expression <- prepared$data[prepared$features, cell_index, drop = FALSE] cell_types <- sort(unique(na.omit(labels[nzchar(labels)]))) results <- lapply(cell_types, function(cell_type) { primary <- which(groups == "Primary" & !is.na(labels) & labels == cell_type) metastasis <- which(groups == "Metastasis" & !is.na(labels) & labels == cell_type) primary_fraction <- metastasis_fraction <- primary_mean <- metastasis_mean <- numeric(nrow(expression)) if (length(primary)) { primary_fraction <- Matrix::rowSums(expression[, primary, drop = FALSE] > 0) / length(primary) primary_mean <- Matrix::rowMeans(expression[, primary, drop = FALSE]) } if (length(metastasis)) { metastasis_fraction <- Matrix::rowSums(expression[, metastasis, drop = FALSE] > 0) / length(metastasis) metastasis_mean <- Matrix::rowMeans(expression[, metastasis, drop = FALSE]) } data.frame( gene = rownames(expression), cell_type = cell_type, primary_expression_proportion = primary_fraction, metastasis_expression_proportion = metastasis_fraction, primary_mean_expression = primary_mean, metastasis_mean_expression = metastasis_mean ) }) put(do.call(rbind, results), file.path(out, paste0("primary_vs_", sites[[site]]), "GC", "Curated", "expression.csv")) } }
# 4. GO and KEGG overrepresentation analysis. # Select DE genes using P < 0.05, adjusted P < 0.2 and abs(log2fc) > 0.5. # The background is all measured, expressed genes that map to Entrez IDs, # rather than only the variable genes or the complete human genome. if (mode == "fe") { resources <- resource_dir
# Use the archived human KEGG mappings so the run does not require a # new live KEGG query. The gene and pathway files are downloaded above. kg <- data.table::fread(file.path(resources, "kegg_genes.tsv"), header = FALSE, data.table = FALSE) kn <- data.table::fread(file.path(resources, "kegg_pathways.tsv"), header = FALSE, data.table = FALSE) term2gene <- data.frame(term = sub("^path:", "", kg[[2]]), gene = sub("^hsa:", "", kg[[1]])) term2name <- data.frame(term = kn[[1]], name = gsub(" - Homo sapiens (human)", "", kn[[2]], fixed = TRUE)) valid_symbols <- AnnotationDbi::keys(org.Hs.eg.db, keytype = "SYMBOL") gene_symbols <- prepared$gene_symbols if (is.null(gene_symbols)) { seurat_obj <- readRDS(file.path(work, "object.rds")) fm <- seurat_obj[["RNA"]][[]] gene_symbols <- setNames(if ("gene_symbol" %in% names(fm)) as.character(fm$gene_symbol) else rownames(fm), rownames(fm)) rm(seurat_obj) gc() } symbol <- function(features) { x <- unname(gene_symbols[features]) x[is.na(x) | !nzchar(x)] <- features[is.na(x) | !nzchar(x)] unique(x) } measured <- rownames(prepared$counts)[Matrix::rowSums(prepared$counts) > 0] universe_symbols <- intersect(symbol(measured), valid_symbols) universe_ids <- unique(na.omit(AnnotationDbi::mapIds(org.Hs.eg.db, keys = universe_symbols, column = "ENTREZID", keytype = "SYMBOL", multiVals = "first"))) stopifnot(length(universe_ids) > 0) put(data.frame(feature = measured, gene_symbol = unname(gene_symbols[measured])), file.path(work, "enrichment_universe.csv"))
# Use identical gene mapping and background for GO and KEGG. # Write a header-only result when a selected gene set has no mapped genes. fe <- function(genes, kind) { empty <- data.frame(ONTOLOGY = character(), ID = character(), Description = character(), GeneRatio = character(), BgRatio = character(), pvalue = numeric(), p.adjust = numeric(), qvalue = numeric(), geneID = character(), Count = integer()) genes <- intersect(symbol(genes), valid_symbols) if (!length(genes)) return(empty) ids <- unique(na.omit(AnnotationDbi::mapIds(org.Hs.eg.db, keys = unique(genes), column = "ENTREZID", keytype = "SYMBOL", multiVals = "first"))) if (!length(ids)) return(empty) r <- if (kind == "GO") enrichGO(ids, universe = universe_ids, OrgDb = org.Hs.eg.db, keyType = "ENTREZID", ont = "ALL", pAdjustMethod = "BH", pvalueCutoff = enrichment_p_cutoff, qvalueCutoff = enrichment_q_cutoff, readable = TRUE) else enricher(ids, universe = universe_ids, TERM2GENE = term2gene, TERM2NAME = term2name, pAdjustMethod = "BH", pvalueCutoff = enrichment_p_cutoff, qvalueCutoff = enrichment_q_cutoff) if (is.null(r)) return(empty) r <- as.data.frame(r) if (nrow(r)) r <- r[order(r$p.adjust, r$pvalue), , drop = FALSE] r } # Test each cell type using the same measured-gene background. # For all cells combined, also save enrichment of genes higher in Primary # and genes higher in Metastasis. These directional sets are not truncated. for (site in names(sites)) { folder <- file.path(out, paste0("primary_vs_", sites[[site]]), "DEG", "Curated") files <- list.files(folder, "[.]csv$", full.names = TRUE) for (path in files) { cell_type <- tools::file_path_sans_ext(basename(path)) if (tolower(cell_type) %in% c("unresolved", "unknown", "unassigned")) next deg <- read.csv(path, check.names = FALSE) if (nrow(deg)) cell_type <- deg$cell_type[1] significant <- deg[deg$p_value < deg_p_cutoff & abs(deg$log2fc) > deg_logfc_cutoff & deg$p_adjusted < deg_adjusted_p_cutoff, , drop = FALSE] for (kind in c("GO", "KEGG")) { dest <- file.path(out, paste0("primary_vs_", sites[[site]]), "FE", "Curated", kind, paste0(safe_type(cell_type), ".csv")) if (!file.exists(dest)) put(fe(significant$gene, kind), dest) if (cell_type != "allcell") next for (group in c("Primary", "Metastasis")) { selected <- if (group == "Primary") significant$log2fc < 0 else significant$log2fc > 0 directional <- significant[selected, , drop = FALSE] directional <- directional[order(-abs(directional$log2fc)), , drop = FALSE] dest <- file.path(out, paste0("primary_vs_", sites[[site]]), "FE", kind, paste0(tolower(group), ".csv")) if (!file.exists(dest)) put(fe(directional$gene, kind), dest) } } } } }
# 5. CellChat ligand-receptor inference. # Run Primary and Metastasis separately using the original cell type labels. # Keep cell types with at least ten cells in the group and require at least # two cell types. Save the actual group coverage in ci_groups.csv. if (mode == "ci") { future::plan("sequential") normalized_symbol <- symbol_expression(prepared)$data ci_groups <- list() for (site in names(sites)) for (method in names(methods)) for (group in c("Primary", "Metastasis")) { suffix <- paste0(site, "_", method, "_", if (group == "Primary") "p" else "m") dest <- file.path(out, paste0("primary_vs_", sites[[site]]), "CI", "Curated", paste0(tolower(group), ".csv")) cell_index <- pair_cells(site) cell_index <- cell_index[pair_class(cell_index) == group] lab <- cell_meta[cell_index, methods[[method]]] keep <- !is.na(lab) & nzchar(lab) keep <- keep & !tolower(lab) %in% c("unresolved", "unknown", "unassigned") cell_index <- cell_index[keep] lab <- lab[keep] tab <- table(lab) keep <- lab %in% names(tab)[tab >= cellchat_min_cells] cell_index <- cell_index[keep] lab <- droplevels(factor(lab[keep])) applicable <- nlevels(lab) >= 2 ci_groups[[length(ci_groups) + 1L]] <- data.frame(site = sites[[site]], annotation = method_names[[method]], group = group, cells = length(cell_index), cell_types = nlevels(lab), status = if (applicable) "completed" else "not_applicable", reason = if (applicable) "" else "Fewer than two cell types with at least 10 cells") if (!applicable) next if (file.exists(dest) && file.exists(paste0(dest, ".done"))) next message(acc, " CI ", suffix, " ", length(cell_index), " cells") meta <- data.frame(labels = lab, row.names = cell_meta$cell_id[cell_index])
# Use log-normalized, symbol-level expression and the human CellChat DB. # Project signaling expression onto PPI.human before communication inference. cc <- createCellChat(normalized_symbol[, cell_index, drop = FALSE], meta = meta, group.by = "labels") cc@DB <- CellChatDB.human cc <- subsetData(cc) cc <- identifyOverExpressedGenes(cc) cc <- identifyOverExpressedInteractions(cc) cc <- projectData(cc, PPI.human) cc <- computeCommunProb(cc, raw.use = FALSE, seed.use = seed) cc <- filterCommunication(cc, min.cells = cellchat_min_cells) interactions <- subsetCommunication(cc) cc <- aggregateNet(cc)
# Save both ligand-receptor results and aggregate source-to-target weights. # Zero aggregate weights remain in the summary table. w <- cc@net$weight edges <- expand.grid(source = rownames(w), target = colnames(w), stringsAsFactors = FALSE) edges$prob <- as.vector(w) dir <- file.path(out, paste0("primary_vs_", sites[[site]]), "CI", method_names[[method]]) put(interactions, file.path(dir, paste0(tolower(group), ".csv"))) put(data.frame(cell_type = rownames(w), w, check.names = FALSE), file.path(dir, paste0(tolower(group), "_matrix.csv"))) put(edges, file.path(dir, paste0(tolower(group), "_edges.csv"))) file.create(paste0(dest, ".done")) rm(cc) gc() } if (length(ci_groups)) put(do.call(rbind, ci_groups), file.path(work, "ci_groups.csv")) }
# 6. Functional states: five cell-cycle sets and thirteen CancerSEA states. # Score each cell using the measured set genes and expression matched # control genes. Save marker coverage alongside the scores. if (mode == "cs") { resource <- file.path(resource_dir, "cell_states.csv") sets <- read.csv(resource, check.names = FALSE) states <- c("G1/S", "S", "G2/M", "M", "M/G1", "Angiogenesis", "Apoptosis", "Differentiation", "DNA damage", "DNA repair", "EMT", "Hypoxia", "Inflammation", "Invasion", "Metastasis", "Proliferation", "Quiescence", "Stemness") x <- symbol_expression(prepared) seurat_obj <- CreateSeuratObject(x$counts, min.cells = 0, min.features = 0) seurat_obj <- SetAssayData(seurat_obj, assay = "RNA", layer = "data", new.data = x$data) features <- lapply(states, function(state) intersect(unique(sets$gene_symbol[sets$state == state]), rownames(seurat_obj))) coverage <- data.frame(state = states, source_genes = vapply(states, function(k) length(unique(sets$gene_symbol[sets$state == k])), integer(1)), measured_genes = lengths(features)) put(coverage, file.path(work, "state_genes.csv")) stopifnot(length(features) == 18, all(lengths(features) > 0))
# Use 24 expression bins and 100 control genes per feature, with seed 42. # A module score is a relative expression score, not a probability. seurat_obj <- AddModuleScore(seurat_obj, features = features, name = "state_", nbin = score_bins, ctrl = score_controls, assay = "RNA", slot = "data", seed = seed, search = FALSE) scores <- seurat_obj@meta.data[, paste0("state_", seq_along(states)), drop = FALSE] names(scores) <- states stopifnot(identical(rownames(scores), cell_meta$cell_id), all(is.finite(as.matrix(scores)))) for (site in names(sites)) { cell_index <- pair_cells(site) d <- data.frame(cell_id = cell_meta$cell_id[cell_index], sample_class = pair_class(cell_index), cell_type = cell_meta$cell_type[cell_index], scores[cell_index, , drop = FALSE], check.names = FALSE) put(d, file.path(out, paste0("primary_vs_", sites[[site]]), "CS", "scores.csv")) } writeLines(capture.output(sessionInfo()), file.path(work, "cs_session.txt")) writeLines(as.character(Sys.time()), file.path(work, "cs.done")) message(acc, " cs COMPLETE") return(invisible(NULL)) }
# 7. Monocle3 trajectory and CytoTRACE. # Reuse the saved UMAP coordinates and learn a partitioned principal graph. # Within each partition containing primary cells, choose a primary-adjacent # root with the highest mean CytoTRACE score. if (mode == "ct") { for (site in names(sites)) { done <- file.path(work, paste0("ct_", site, ".done")) if (file.exists(done)) next cell_index <- pair_cells(site) meta <- cell_meta[cell_index, , drop = FALSE] meta$comparison_group <- pair_class(cell_index) counts <- prepared$counts[, cell_index, drop = FALSE] meta <- data.frame(meta, row.names = meta$cell_id) cds <- new_cell_data_set(counts, cell_metadata = meta, gene_metadata = data.frame(gene_short_name = rownames(counts), row.names = rownames(counts))) reducedDims(cds)$UMAP <- prepared$umap[cell_index, , drop = FALSE] cds <- cluster_cells(cds, random_seed = seed) cds <- learn_graph(cds, use_partition = TRUE, verbose = FALSE)
# CytoTRACE uses raw counts, not scaled or Harmony-corrected expression. # Cache this expensive step so an interrupted export can resume. cytofile <- file.path(work, paste0("cytotrace_", site, ".rds")) if (file.exists(cytofile)) ct <- readRDS(cytofile) else { message(acc, " CytoTRACE ", site) set.seed(seed) gc() ct <- CytoTRACE(as.matrix(counts), enableFast = TRUE, ncores = 1, subsamplesize = cytotrace_subsample) saveRDS(ct, cytofile) } closest <- cds@principal_graph_aux[["UMAP"]]$pr_graph_cell_proj_closest_vertex primary <- which(meta$comparison_group == "Primary") part <- monocle3::partitions(cds) roots <- vapply(unique(as.character(part[primary])), function(k) { take <- primary[as.character(part[primary]) == k] score <- tapply(ct$CytoTRACE[colnames(cds)[take]], closest[take, 1], mean, na.rm = TRUE) score <- score[is.finite(score)] if (!length(score)) return(NA_character_) igraph::V(principal_graph(cds)[["UMAP"]])$name[as.integer(names(which.max(score)))] }, character(1)) root_node <- unique(na.omit(roots)) stopifnot(length(root_node) > 0)
cds <- order_cells(cds, root_pr_nodes = root_node) time <- pseudotime(cds) coverage <- data.frame(cell_id = meta$cell_id, group = meta$comparison_group, pseudotime = as.numeric(time), cytotrace = as.numeric(ct$CytoTRACE[meta$cell_id]), status = ifelse(is.finite(time), "ordered", "no_reachable_primary_root"))
# Cells without a reachable primary root have missing pseudotime. # Record the reason in coverage.csv and keep these cells in the object. coverage$pseudotime[!is.finite(coverage$pseudotime)] <- NA_real_ put(coverage, file.path(out, paste0("primary_vs_", sites[[site]]), "CT", "coverage.csv"))
# Export normalized expression in small cell blocks to limit dense memory use. # The serialized values follow the gene order written to genes.csv. values <- character(length(cell_index)) for (start in seq(1, length(cell_index), by = 2000)) { chunk <- start:min(start + 1999, length(cell_index)) expression <- round(as.matrix(t(prepared$data[prepared$features, cell_index[chunk], drop = FALSE])), 3) values[chunk] <- apply(expression, 1, pack) } t <- data.frame(F1 = meta$cell_id, site = meta$comparison_group, umap_1 = round(prepared$umap[cell_index, 1], 3), umap_2 = round(prepared$umap[cell_index, 2], 3), pseudotime = round(coverage$pseudotime, 5), Column1 = values) columns <- c(cell_type = "curated", celltype_singler = "singler", celltype_sctype = "sctype", celltype_article = "article") for (k in intersect(names(columns), names(meta))) t[[columns[[k]]]] <- ifelse(is.na(meta[[k]]), "Unresolved", meta[[k]]) put(t, file.path(out, paste0("primary_vs_", sites[[site]]), "CT", "trajectory.csv")) g <- principal_graph(cds)[["UMAP"]] e <- igraph::as_data_frame(g, what = "edges")[, 1:2] xy <- t(cds@principal_graph_aux[["UMAP"]]$dp_mst) kp <- data.frame(F1 = seq_len(nrow(e)), UMAP_1 = xy[e[, 1], 1], UMAP_2 = xy[e[, 1], 2], UMAP_3 = xy[e[, 2], 1], UMAP_4 = xy[e[, 2], 2]) put(kp, file.path(out, paste0("primary_vs_", sites[[site]]), "CT", "trajectory_edges.csv")) put(data.frame(position = seq_along(prepared$features), gene = prepared$features), file.path(out, paste0("primary_vs_", sites[[site]]), "CT", "genes.csv")) writeLines(root_node, file.path(work, paste0("ct_", site, "_root.txt"))) file.create(done) } } writeLines(capture.output(sessionInfo()), file.path(work, paste0(mode, "_session.txt"))) writeLines(as.character(Sys.time()), file.path(work, paste0(mode, ".done"))) message(acc, " ", mode, " COMPLETE")}
# Consolidate the completed module tables using the same names as the repository.# Context columns identify the comparison, annotation and expression direction.export_analysis <- function(output_dir) { work <- file.path(output_dir, "work", "analysis") required <- c("prepare", "gc", "deg", "fe", "cs", "ci", "ct") if (!all(file.exists(file.path(work, paste0(required, ".done"))))) stop("Complete the analysis stages before export") ci <- read.csv(file.path(work, "ci_groups.csv")) ci_status <- if (nrow(ci) == 2L && all(ci$status == "completed")) "completed" else "not_applicable" raw <- file.path(work, "analysis") target <- file.path(output_dir, "analysis") dir.create(target, showWarnings = FALSE) files <- list.files(raw, "[.]csv$", recursive = TRUE, full.names = TRUE) tables <- list() aliases <- c(ONTOLOGY = "ontology", ID = "term_id", Description = "description", GeneRatio = "gene_ratio", BgRatio = "background_ratio", pvalue = "p_value", p.adjust = "p_adjusted", qvalue = "q_value", geneID = "genes", Count = "gene_count", F1 = "cell_id", site = "sample_class", group = "sample_class", Column1 = "expression_values", curated = "cell_type", article = "celltype_article", prob = "probability", pval = "p_value", "G1/S" = "g1_s", "G2/M" = "g2_m", "M/G1" = "m_g1") for (path in files) { parts <- strsplit(substring(path, nchar(raw) + 2L), .Platform$file.sep, fixed = TRUE)[[1]] module <- parts[2]; name <- tools::file_path_sans_ext(basename(path)) if (module == "CI" && endsWith(name, "_matrix")) next dest <- switch(module, DEG = "deg.csv", FE = "enrichment.csv", GC = "gene_expression.csv", CS = "function_scores.csv", CI = if (endsWith(name, "_edges")) "interaction_summary.csv" else "interaction.csv", CT = switch(name, genes = "trajectory_genes.csv", trajectory_edges = "trajectory_edges.csv", coverage = "trajectory_coverage.csv", "trajectory.csv")) d <- fread(path, data.table = FALSE, check.names = FALSE) if ("cell_type" %in% names(d) && nrow(d)) name <- as.character(d$cell_type[1]) renamed <- ifelse(names(d) %in% names(aliases), aliases[names(d)], names(d)) if (identical(dest, "trajectory_edges.csv")) renamed[renamed == "cell_id"] <- "edge_id" names(d) <- tolower(gsub("[^a-zA-Z0-9_]+", "_", renamed)) d$comparison_id <- rep(tolower(parts[1]), nrow(d)) d$metastatic_tissue <- rep("Liver", nrow(d)) if (module %in% c("DEG", "FE", "GC", "CI")) d$annotation_method <- rep("Curated", nrow(d)) if (module %in% c("DEG", "FE") && !"cell_type" %in% names(d)) d$cell_type <- rep(if (parts[3] %in% c("GO", "KEGG")) "allcell" else name, nrow(d)) if (module == "FE") { d$analysis_type <- rep(if (parts[3] %in% c("GO", "KEGG")) parts[3] else parts[4], nrow(d)) d$higher_expression_group <- rep(if (parts[3] %in% c("GO", "KEGG")) tools::toTitleCase(name) else "", nrow(d)) } if (module == "CI") d$sample_class <- rep(tools::toTitleCase(sub("_.*", "", name)), nrow(d)) tables[[dest]][[length(tables[[dest]]) + 1L]] <- d } for (name in names(tables)) fwrite(rbindlist(tables[[name]], fill = TRUE, use.names = TRUE), file.path(target, name), na = "", quote = "auto") for (name in c("comparison_groups.csv", "ci_groups.csv", "enrichment_universe.csv", "state_genes.csv")) stopifnot(file.copy(file.path(work, name), file.path(target, name), overwrite = TRUE)) p <- readRDS(file.path(work, "prepared.rds")) fwrite(p$meta, file.path(target, "cell_metadata.csv"), na = "") fwrite(data.frame(position = seq_along(p$features), gene = p$features), file.path(target, "variable_genes.csv")) write.csv(data.frame(comparison_id = "primary_vs_liver", metastatic_tissue = "Liver", primary_cells = sum(p$meta$sample_class == "Primary"), metastatic_cells = sum(p$meta$sample_class == "Metastasis"), annotation_method = "Curated", deg_direction = "Metastasis relative to Primary", ci_status = ci_status), file.path(target, "comparisons.csv"), row.names = FALSE) sessions <- list.files(work, "_session[.]txt$", full.names = TRUE) writeLines(unlist(lapply(sessions, function(f) c(basename(f), readLines(f), ""))), file.path(target, "software_versions.txt")) modules <- c("Data characteristics", "Clustering and cell annotation", "Differential expression", "Functional enrichment", "Cell interactions", "Cell trajectory", "Gene characteristics", "Functional states") status <- rep("completed", length(modules)); status[modules == "Cell interactions"] <- ci_status write.csv(data.frame(module = modules, status = status), file.path(output_dir, "modules.csv"), row.names = FALSE) stopifnot(all(file.exists(file.path(target, c("deg.csv", "enrichment.csv", "interaction.csv", "trajectory.csv", "gene_expression.csv", "function_scores.csv"))))) # Replace only this demo's initial object with its completed embedding object. stopifnot(file.copy(file.path(work, "object.rds"), file.path(output_dir, paste0(acc, ".rds")), overwrite = TRUE))}
# Run stages in separate processes to accommodate the server's two R installations.# On a machine with all compatible packages, both executables can be the same.run_worker <- function(script, out, stage) { functional <- stage %in% c("gc", "fe", "ci", "ct") executable <- Sys.getenv(if (functional) "P2M_FUNCTIONAL_RSCRIPT" else "P2M_CORE_RSCRIPT", file.path(R.home("bin"), "Rscript")) shared <- Sys.getenv(if (functional) "P2M_FUNCTIONAL_LIBRARY_PATH" else "P2M_CORE_LIBRARY_PATH") old <- Sys.getenv(c("R_HOME", "R_LIBS_SITE", "R_LIBS_USER", "LD_LIBRARY_PATH"), unset = NA_character_) on.exit(for (k in names(old)) { if (is.na(old[[k]])) Sys.unsetenv(k) else do.call(Sys.setenv, setNames(list(old[[k]]), k)) }, add = TRUE) Sys.unsetenv(c("R_HOME", "R_LIBS_SITE", "R_LIBS_USER")) if (nzchar(shared)) Sys.setenv(LD_LIBRARY_PATH = shared) status <- system2(executable, c("--vanilla", shQuote(script), shQuote(out), stage, "--worker")) if (status != 0) stop("Stage failed: ", stage)}
main <- function() { args <- commandArgs(TRUE) out <- path.expand(if (length(args)) args[1] else output_dir) stage <- if (length(args) > 1L) args[2] else run_stage allowed <- c("all", "download", "import", "prepare", "gc", "deg", "fe", "cs", "ci", "ct", "export") if (!stage %in% allowed) stop("Unknown stage: ", stage) dir.create(out, recursive = TRUE, showWarnings = FALSE) out <- normalizePath(out) marker <- file.path(out, ".p2m_demo") if (!file.exists(marker)) { if (file.exists(file.path(out, paste0(acc, ".rds"))) || dir.exists(file.path(out, "analysis"))) stop("Choose a separate output directory; existing dataset results are protected") writeLines(acc, marker) } stopifnot(identical(readLines(marker), acc)) worker <- "--worker" %in% args libraries <- Sys.getenv(if (stage %in% c("gc", "fe", "ci", "ct")) "P2M_EXTRA_RLIB" else "P2M_CORE_RLIB") if (nzchar(libraries)) .libPaths(c(strsplit(libraries, .Platform$path.sep, fixed = TRUE)[[1]], .libPaths())) Sys.setenv(OMP_NUM_THREADS = n_workers, OPENBLAS_NUM_THREADS = n_workers, MKL_NUM_THREADS = n_workers, R_MAX_VSIZE = "64Gb") if (worker) { load_packages(stage) if (stage == "import") { prepare_counts(out); run_doublets(out); finish_counts(out) } else if (stage == "export") export_analysis(out) else run_analysis(stage, out) return(invisible(NULL)) } script <- normalizePath(sub("^--file=", "", grep("^--file=", commandArgs(), value = TRUE)[1])) if (stage %in% c("all", "download", "import")) download_inputs(out) if (stage == "download") return(invisible(NULL)) stages <- if (stage == "all") c("import", "prepare", "gc", "deg", "fe", "cs", "ci", "ct", "export") else stage for (s in stages) { done <- file.path(out, "work", "analysis", paste0(s, ".done")) if (s %in% c("prepare", "gc", "deg", "fe", "cs", "ci", "ct") && file.exists(done)) next message("Running ", acc, ": ", s) run_worker(script, out, s) }}
if (sys.nframe() == 0L) main()demo/README.mdAdded+62
demo/bulk_GSE221608.RAdded+475
demo/scRNA_GSE263733.RAdded+985