├── .gitattributes ├── .gitignore ├── .Rbuildignore ├── data ├── gset.list.rda └── cc.genes.mouse.rda ├── .travis.yml ├── inst ├── extdata │ ├── byDE.cellCycle.hc.glist.gz │ ├── byZhangLab.stress.glist.gz │ ├── exclude.gene.misc.human.v3.RData │ ├── exclude.gene.misc.human.v4.RData │ ├── exclude.gene.misc.mouse.v3.RData │ ├── exclude.gene.misc.mouse.v4.RData │ ├── scibet │ │ └── model_ESCA │ │ │ ├── model.sub.B.rds │ │ │ ├── model.sub.DC.rds │ │ │ ├── model.sub.M.rds │ │ │ ├── model.sub.T8.rds │ │ │ ├── model.sub.Th.rds │ │ │ ├── model.major.all.rds │ │ │ ├── model.sub.Endo.rds │ │ │ ├── model.sub.Epi.rds │ │ │ ├── model.sub.Fibro.rds │ │ │ ├── model.sub.Glia.rds │ │ │ ├── model.sub.ILC.rds │ │ │ ├── model.sub.Mast.rds │ │ │ ├── model.sub.SMC.rds │ │ │ ├── model.sub.Treg.rds │ │ │ ├── model.sub.pDC.rds │ │ │ ├── model.sub.Neutro.rds │ │ │ └── model.sub.Plasma.rds │ └── ISG.MSigDB.BROWNE_INTERFERON_RESPONSIVE_GENES.detected.glist.gz └── script │ ├── run.MQuad.sh │ ├── make.CC.R │ ├── run.pyScenic.sh │ ├── wrapper.convertLimmaToSCE.R │ ├── run.cellRanger.count.sh │ ├── run.scibet.R │ ├── plot.scibet.R │ ├── wrapper.vireoSNP.py │ ├── wrapper.run.inte.R │ ├── report.template.sc.rmd │ ├── wrapper.run.limma.R │ ├── run.copykat.R │ ├── example │ ├── w.run.M.sh │ └── w.run.T.sh │ ├── aln.STAR.sh │ ├── run.scanpy.basic.R │ └── run.seurat3.basic.R ├── R ├── data.R └── zzz.R ├── man ├── g.geneOnUmap.list.Rd ├── gset.list.Rd ├── resetSig.Rd ├── render_KnitReport.Rd ├── run.HVG.Rd ├── run.Scanorama.Rd ├── make.geneTableLong.Rd ├── run.Leiden.Rd ├── calProliferationScore.Rd ├── sigGeneHeatmap.Rd ├── HVG.From.GeneRankTb.Rd ├── calEffectSizeFromDE.Rd ├── cal.signatureScore.gdT.Fred.Rd ├── inSilico.TGammaDelta.Rd ├── fill.contamination.Rd ├── mergeSCEDataFromFileTable.Rd ├── mergeDataFromFileTable.Rd ├── inSilico.TCell.Rd ├── convertLimmaToSCE.Rd ├── run.inte.metaClust.Rd ├── run.scanpy.Rd ├── run.rapids_singlecell.Rd └── run.Seurat3.Rd ├── README.md ├── DESCRIPTION ├── appveyor.yml ├── NAMESPACE └── LICENSE /.gitattributes: -------------------------------------------------------------------------------- 1 | *.html linguist-vendored 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .Rproj.user 2 | .Rhistory 3 | .RData 4 | .Ruserdata 5 | .swp 6 | -------------------------------------------------------------------------------- /.Rbuildignore: -------------------------------------------------------------------------------- 1 | ^.*\.Rproj$ 2 | ^\.Rproj\.user$ 3 | .travis.yml 4 | appveyor.yml 5 | -------------------------------------------------------------------------------- /data/gset.list.rda: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Japrin/scPip/HEAD/data/gset.list.rda -------------------------------------------------------------------------------- /data/cc.genes.mouse.rda: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Japrin/scPip/HEAD/data/cc.genes.mouse.rda -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: r 2 | sudo: required 3 | cache: packages 4 | bioc_packages: 5 | - SingleCellExperiment 6 | -------------------------------------------------------------------------------- /inst/extdata/byDE.cellCycle.hc.glist.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Japrin/scPip/HEAD/inst/extdata/byDE.cellCycle.hc.glist.gz -------------------------------------------------------------------------------- /inst/extdata/byZhangLab.stress.glist.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Japrin/scPip/HEAD/inst/extdata/byZhangLab.stress.glist.gz -------------------------------------------------------------------------------- /inst/extdata/exclude.gene.misc.human.v3.RData: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Japrin/scPip/HEAD/inst/extdata/exclude.gene.misc.human.v3.RData -------------------------------------------------------------------------------- /inst/extdata/exclude.gene.misc.human.v4.RData: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Japrin/scPip/HEAD/inst/extdata/exclude.gene.misc.human.v4.RData -------------------------------------------------------------------------------- /inst/extdata/exclude.gene.misc.mouse.v3.RData: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Japrin/scPip/HEAD/inst/extdata/exclude.gene.misc.mouse.v3.RData -------------------------------------------------------------------------------- /inst/extdata/exclude.gene.misc.mouse.v4.RData: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Japrin/scPip/HEAD/inst/extdata/exclude.gene.misc.mouse.v4.RData -------------------------------------------------------------------------------- /inst/extdata/scibet/model_ESCA/model.sub.B.rds: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Japrin/scPip/HEAD/inst/extdata/scibet/model_ESCA/model.sub.B.rds -------------------------------------------------------------------------------- /inst/extdata/scibet/model_ESCA/model.sub.DC.rds: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Japrin/scPip/HEAD/inst/extdata/scibet/model_ESCA/model.sub.DC.rds -------------------------------------------------------------------------------- /inst/extdata/scibet/model_ESCA/model.sub.M.rds: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Japrin/scPip/HEAD/inst/extdata/scibet/model_ESCA/model.sub.M.rds -------------------------------------------------------------------------------- /inst/extdata/scibet/model_ESCA/model.sub.T8.rds: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Japrin/scPip/HEAD/inst/extdata/scibet/model_ESCA/model.sub.T8.rds -------------------------------------------------------------------------------- /inst/extdata/scibet/model_ESCA/model.sub.Th.rds: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Japrin/scPip/HEAD/inst/extdata/scibet/model_ESCA/model.sub.Th.rds -------------------------------------------------------------------------------- /inst/extdata/scibet/model_ESCA/model.major.all.rds: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Japrin/scPip/HEAD/inst/extdata/scibet/model_ESCA/model.major.all.rds -------------------------------------------------------------------------------- /inst/extdata/scibet/model_ESCA/model.sub.Endo.rds: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Japrin/scPip/HEAD/inst/extdata/scibet/model_ESCA/model.sub.Endo.rds -------------------------------------------------------------------------------- /inst/extdata/scibet/model_ESCA/model.sub.Epi.rds: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Japrin/scPip/HEAD/inst/extdata/scibet/model_ESCA/model.sub.Epi.rds -------------------------------------------------------------------------------- /inst/extdata/scibet/model_ESCA/model.sub.Fibro.rds: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Japrin/scPip/HEAD/inst/extdata/scibet/model_ESCA/model.sub.Fibro.rds -------------------------------------------------------------------------------- /inst/extdata/scibet/model_ESCA/model.sub.Glia.rds: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Japrin/scPip/HEAD/inst/extdata/scibet/model_ESCA/model.sub.Glia.rds -------------------------------------------------------------------------------- /inst/extdata/scibet/model_ESCA/model.sub.ILC.rds: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Japrin/scPip/HEAD/inst/extdata/scibet/model_ESCA/model.sub.ILC.rds -------------------------------------------------------------------------------- /inst/extdata/scibet/model_ESCA/model.sub.Mast.rds: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Japrin/scPip/HEAD/inst/extdata/scibet/model_ESCA/model.sub.Mast.rds -------------------------------------------------------------------------------- /inst/extdata/scibet/model_ESCA/model.sub.SMC.rds: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Japrin/scPip/HEAD/inst/extdata/scibet/model_ESCA/model.sub.SMC.rds -------------------------------------------------------------------------------- /inst/extdata/scibet/model_ESCA/model.sub.Treg.rds: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Japrin/scPip/HEAD/inst/extdata/scibet/model_ESCA/model.sub.Treg.rds -------------------------------------------------------------------------------- /inst/extdata/scibet/model_ESCA/model.sub.pDC.rds: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Japrin/scPip/HEAD/inst/extdata/scibet/model_ESCA/model.sub.pDC.rds -------------------------------------------------------------------------------- /inst/extdata/scibet/model_ESCA/model.sub.Neutro.rds: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Japrin/scPip/HEAD/inst/extdata/scibet/model_ESCA/model.sub.Neutro.rds -------------------------------------------------------------------------------- /inst/extdata/scibet/model_ESCA/model.sub.Plasma.rds: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Japrin/scPip/HEAD/inst/extdata/scibet/model_ESCA/model.sub.Plasma.rds -------------------------------------------------------------------------------- /R/data.R: -------------------------------------------------------------------------------- 1 | #' lists of gene sets 2 | #' 3 | #' @name gset.list 4 | #' @docType data 5 | #' @source GO, HPA, and CSOMap 6 | #' 7 | #' list of gene sets 8 | NULL 9 | -------------------------------------------------------------------------------- /inst/extdata/ISG.MSigDB.BROWNE_INTERFERON_RESPONSIVE_GENES.detected.glist.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Japrin/scPip/HEAD/inst/extdata/ISG.MSigDB.BROWNE_INTERFERON_RESPONSIVE_GENES.detected.glist.gz -------------------------------------------------------------------------------- /man/g.geneOnUmap.list.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/zzz.R 3 | \docType{data} 4 | \name{g.geneOnUmap.list} 5 | \alias{g.geneOnUmap.list} 6 | \title{special gene list} 7 | \description{ 8 | special gene list 9 | } 10 | -------------------------------------------------------------------------------- /man/gset.list.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/data.R 3 | \docType{data} 4 | \name{gset.list} 5 | \alias{gset.list} 6 | \title{lists of gene sets} 7 | \source{ 8 | GO, HPA, and CSOMap 9 | 10 | list of gene sets 11 | } 12 | \description{ 13 | lists of gene sets 14 | } 15 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # scPip 2 | A pipeline for scRNA-seq data analysis 3 | 4 | # Installation 5 | 6 | To install this package, simply: 7 | ``` 8 | install.packages("devtools") 9 | devtools::install_github("Japrin/scPip") 10 | ``` 11 | 12 | * known issue 13 | 14 | message may pop up: 15 | Error in (function (x) : attempt to apply non-function 16 | Just ignore it. 17 | 18 | -------------------------------------------------------------------------------- /man/resetSig.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/sc.intClust.R 3 | \name{resetSig} 4 | \alias{resetSig} 5 | \title{reset the significance} 6 | \usage{ 7 | resetSig(obj) 8 | } 9 | \arguments{ 10 | \item{obj}{object of \code{SingleCellExperiment} class} 11 | } 12 | \value{ 13 | a SingleCellExperiment object 14 | } 15 | \description{ 16 | reset the significance 17 | } 18 | -------------------------------------------------------------------------------- /man/render_KnitReport.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/sc.intClust.R 3 | \name{render_KnitReport} 4 | \alias{render_KnitReport} 5 | \title{render a knitr report} 6 | \usage{ 7 | render_KnitReport(template.file, out.file, par.list = list()) 8 | } 9 | \arguments{ 10 | \item{template.file}{character; template file} 11 | 12 | \item{out.file}{character; output file} 13 | 14 | \item{par.list}{list; parameter list for rmarkdown::render} 15 | } 16 | \value{ 17 | a SingleCellExperiment object 18 | } 19 | \description{ 20 | render a knitr report 21 | } 22 | -------------------------------------------------------------------------------- /DESCRIPTION: -------------------------------------------------------------------------------- 1 | Package: scPip 2 | Type: Package 3 | Title: pipeline for scRNA-seq data analysis 4 | Version: 0.1.0 5 | Author: Liangtao Zheng 6 | Maintainer: Liangtao Zheng 7 | Description: A pipeline for scRNA-seq data analysis. 8 | License: GPL-3 + file LICENSE 9 | Encoding: UTF-8 10 | LazyData: true 11 | RoxygenNote: 7.3.1 12 | Depends: R (>= 3.5.0), SingleCellExperiment, Seurat, SummarizedExperiment 13 | Imports: data.table, cowplot, ggplot2, ggpubr, R.utils, harmony, leiden, 14 | plyr, scran, sscClust, sscVis, tibble, S4Vectors, RhpcBLASctl, 15 | doParallel, rmarkdown, dplyr, magrittr, tictoc, RColorBrewer, matrixStats 16 | -------------------------------------------------------------------------------- /man/run.HVG.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/sc.utils.R 3 | \name{run.HVG} 4 | \alias{run.HVG} 5 | \title{Wraper for highly variable genes finding} 6 | \usage{ 7 | run.HVG(seu, gene.exclude.df, n.top = 1500, measurement = "counts") 8 | } 9 | \arguments{ 10 | \item{seu}{object of \code{Seurat}} 11 | 12 | \item{gene.exclude.df}{data.frame; gene blak list. Required column: seu.id.} 13 | 14 | \item{n.top}{integer; number of top genes. (default: 1500)} 15 | 16 | \item{measurement}{character; "counts", "TPM" or "cpm". (default: "counts")} 17 | } 18 | \value{ 19 | a Seurat object 20 | } 21 | \description{ 22 | Wraper for highly variable genes finding 23 | } 24 | -------------------------------------------------------------------------------- /man/run.Scanorama.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/sc.utils.R 3 | \name{run.Scanorama} 4 | \alias{run.Scanorama} 5 | \title{Wraper for running Scanorama} 6 | \usage{ 7 | run.Scanorama(seu, col.batch = "batchV", assay.slot = "data", ...) 8 | } 9 | \arguments{ 10 | \item{seu}{object of \code{Seurat}} 11 | 12 | \item{col.batch}{character; column name indicating batches (default: "batchV")} 13 | 14 | \item{assay.slot}{character; which slot to be used? (default: "data")} 15 | 16 | \item{...}{; passed to scanorama$integrate} 17 | } 18 | \value{ 19 | a Seurat object 20 | } 21 | \description{ 22 | Wraper for running Scanorama 23 | } 24 | \details{ 25 | run the Scanorama 26 | } 27 | -------------------------------------------------------------------------------- /man/make.geneTableLong.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/sc.intClust.R 3 | \name{make.geneTableLong} 4 | \alias{make.geneTableLong} 5 | \title{make a long type gene table, given a SingleCellExperiment object} 6 | \usage{ 7 | make.geneTableLong(obj, out.prefix, th.adj.P = 0.01, th.dprime = 0.15) 8 | } 9 | \arguments{ 10 | \item{obj}{object of \code{SingleCellExperiment} class} 11 | 12 | \item{out.prefix}{output prefix} 13 | 14 | \item{th.adj.P}{double; threshold for adjusted p-value. (default: 0.01)} 15 | 16 | \item{th.dprime}{double; threshold for dprime. (default: 0.15)} 17 | } 18 | \description{ 19 | make a long type gene table, given a SingleCellExperiment object 20 | } 21 | -------------------------------------------------------------------------------- /man/run.Leiden.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/sc.intClust.R 3 | \name{run.Leiden} 4 | \alias{run.Leiden} 5 | \title{wrapper for running leiden clustering} 6 | \usage{ 7 | run.Leiden(dat.pca, SNN.k = 20, myseed = 123456, ...) 8 | } 9 | \arguments{ 10 | \item{dat.pca}{data.frame; row for sample, column for variable} 11 | 12 | \item{SNN.k}{integer; parameter k of scran::buildSNNGraph. (default: 20)} 13 | 14 | \item{myseed}{integer; seed for random number generation. (default: 123456)} 15 | 16 | \item{...}{; other parameters passed to leiden::leiden} 17 | } 18 | \value{ 19 | a object returned from leiden::leiden 20 | } 21 | \description{ 22 | wrapper for running leiden clustering 23 | } 24 | \details{ 25 | implementation in Seurat (FindClusters) can only detect singletons :-( 26 | } 27 | -------------------------------------------------------------------------------- /man/calProliferationScore.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/sc.utils.R 3 | \name{calProliferationScore} 4 | \alias{calProliferationScore} 5 | \title{calculate the proliferation score} 6 | \usage{ 7 | calProliferationScore( 8 | obj, 9 | gene.prol, 10 | assay.name = "norm_exprs", 11 | out.prefix = NULL, 12 | method = "mean" 13 | ) 14 | } 15 | \arguments{ 16 | \item{obj}{object of \code{SingleCellExperiment}} 17 | 18 | \item{gene.prol}{character vector; genes to use.} 19 | 20 | \item{assay.name}{character vector; which assay to use. (default: "norm_exprs").} 21 | 22 | \item{out.prefix}{character; output prefix. (default: NULL)} 23 | 24 | \item{method}{character; method to use. (default: "mean").} 25 | } 26 | \value{ 27 | a list 28 | } 29 | \description{ 30 | calculate the proliferation score 31 | } 32 | \details{ 33 | calculate the proliferation score. 34 | } 35 | -------------------------------------------------------------------------------- /man/sigGeneHeatmap.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/sc.intClust.R 3 | \name{sigGeneHeatmap} 4 | \alias{sigGeneHeatmap} 5 | \title{make heatmap for top signature genes} 6 | \usage{ 7 | sigGeneHeatmap( 8 | out.prefix, 9 | gene.desc.top, 10 | sce.pb, 11 | gene.to.show.tb, 12 | value.var = "comb.ES", 13 | colSet = list(), 14 | ... 15 | ) 16 | } 17 | \arguments{ 18 | \item{out.prefix}{character; output prefix} 19 | 20 | \item{gene.desc.top}{data.table; gene info table} 21 | 22 | \item{sce.pb}{object of SingleCellExperiment; gene by meta-cluster values stored in this object} 23 | 24 | \item{gene.to.show.tb}{data.table; infomation of genes to be shown} 25 | 26 | \item{value.var}{character; stored value to use. (default: "comb.ES")} 27 | 28 | \item{colSet}{list; color set to use. (default: list())} 29 | 30 | \item{...}{; parameters passed to sscVis::plotMatrix.simple} 31 | } 32 | \description{ 33 | make heatmap for top signature genes 34 | } 35 | -------------------------------------------------------------------------------- /man/HVG.From.GeneRankTb.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/sc.intClust.R 3 | \name{HVG.From.GeneRankTb} 4 | \alias{HVG.From.GeneRankTb} 5 | \title{highly variable genes finding (method using percetile rank values from F test)} 6 | \usage{ 7 | HVG.From.GeneRankTb( 8 | gene.rank.tb, 9 | n.common = 1000, 10 | n.specific = 1000, 11 | th.rank = 0.1 12 | ) 13 | } 14 | \arguments{ 15 | \item{gene.rank.tb}{data.table object} 16 | 17 | \item{n.common}{integer; number of common top genes. (default: 1000)} 18 | 19 | \item{n.specific}{integer; number of top genes with high dataset-specificities. (default: 1000)} 20 | 21 | \item{th.rank}{double; threshold for rank. (default: 0.1)} 22 | } 23 | \value{ 24 | a data.table object 25 | } 26 | \description{ 27 | highly variable genes finding (method using percetile rank values from F test) 28 | } 29 | \details{ 30 | For specific genes, the top n.specific genes with percetile rank values < th.rank are selected. 31 | } 32 | -------------------------------------------------------------------------------- /man/calEffectSizeFromDE.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/sc.intClust.R 3 | \name{calEffectSizeFromDE} 4 | \alias{calEffectSizeFromDE} 5 | \title{calculate effect size given a de.out object} 6 | \usage{ 7 | calEffectSizeFromDE(de.out, de.mode = "multiAsTwo", ncores = 8, cal.p = F) 8 | } 9 | \arguments{ 10 | \item{de.out}{list; Three components are required: two data.table named "all" and "sig", a list named "fit"} 11 | 12 | \item{de.mode}{character; mode of differential expression analysis. (default: "multiAsTwo")} 13 | 14 | \item{ncores}{integer; number of CPU cores to use. (default: 8)} 15 | 16 | \item{cal.p}{logical; whether to calculate p-values assuming normal distribution on the z-scores (default: F)} 17 | } 18 | \value{ 19 | a list contain components, "es.tb" (data.table), "ncells.vec" and "ncells.control.vec" (integer vectors) 20 | } 21 | \description{ 22 | calculate effect size given a de.out object 23 | } 24 | \details{ 25 | calculate effect size given a de.out object 26 | } 27 | -------------------------------------------------------------------------------- /man/cal.signatureScore.gdT.Fred.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/sc.utils.R 3 | \name{cal.signatureScore.gdT.Fred} 4 | \alias{cal.signatureScore.gdT.Fred} 5 | \title{Identification of gamma delta T cells (Fred's method)} 6 | \usage{ 7 | cal.signatureScore.gdT.Fred( 8 | obj, 9 | GSx = c("CD3D", "CD3E", "TRDC", "TRGC1", "TRGC2"), 10 | GSy = c("CD8A", "CD8B"), 11 | col.name = "Score.gammaDeltaT", 12 | th.score = 0.35, 13 | out.prefix = NULL 14 | ) 15 | } 16 | \arguments{ 17 | \item{obj}{object of \code{SingleCellExperiment}; assay "counts" is required.} 18 | 19 | \item{GSx}{character vector; gdT marker gene list. (default: c("CD3D","CD3E","TRDC","TRGC1","TRGC2")).} 20 | 21 | \item{GSy}{character vector; CD8 T cell marker gene list. (default: c("CD8A","CD8B")).} 22 | 23 | \item{col.name}{character; prefix of column names, to be added to obj. (default: "Score.gammaDeltaT")} 24 | 25 | \item{th.score}{double; threshold of the score. (default: 0.35)} 26 | 27 | \item{out.prefix}{character; output prefix. (default: NULL)} 28 | } 29 | \value{ 30 | a SingleCellExperiment object 31 | } 32 | \description{ 33 | Identification of gamma delta T cells (Fred's method) 34 | } 35 | -------------------------------------------------------------------------------- /man/inSilico.TGammaDelta.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/sc.utils.R 3 | \name{inSilico.TGammaDelta} 4 | \alias{inSilico.TGammaDelta} 5 | \title{Identification of gamma delta T cells (simple average-threshold method)} 6 | \usage{ 7 | inSilico.TGammaDelta( 8 | obj, 9 | out.prefix = NULL, 10 | assay.name = "norm_exprs", 11 | vis.v = c(0.25, 0.5), 12 | Th.CD3 = 0.25, 13 | Th.DC = 0.25, 14 | Th.GC1 = 0.25, 15 | Th.GC2 = 0.25 16 | ) 17 | } 18 | \arguments{ 19 | \item{obj}{object of \code{SingleCellExperiment}} 20 | 21 | \item{out.prefix}{character; output prefix. (default: NULL)} 22 | 23 | \item{assay.name}{character vector; which assay to use. (default: "norm_exprs").} 24 | 25 | \item{vis.v}{double vector; for vertical lines in visulization. (default: c(0.25,0.5)).} 26 | 27 | \item{Th.CD3}{double; threshold for T cell signature. (default: 0.25)} 28 | 29 | \item{Th.DC}{double; threshold for delta receptor constant chain. (default: 0.25)} 30 | 31 | \item{Th.GC1}{double; threshold for gamma receptor constant chain 1. (default: 0.25)} 32 | 33 | \item{Th.GC2}{double; threshold for gamma receptor constant chain 2. (default: 0.25)} 34 | } 35 | \value{ 36 | a SingleCellExperiment object 37 | } 38 | \description{ 39 | Identification of gamma delta T cells (simple average-threshold method) 40 | } 41 | -------------------------------------------------------------------------------- /inst/script/run.MQuad.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | sDir=`dirname $0` 4 | #iniFile="$sDir/../parameter/init_human.sh" 5 | #_refData="/WPSnew/zhenglt/00.database/broad/bundle/2.8/b37/human_g1k_v37_decoy.fasta" 6 | optT=8 7 | 8 | while getopts c:t: opt 9 | do 10 | case $opt in 11 | c) 12 | if [ -f $OPTARG ] 13 | then 14 | iniFile="$OPTARG" 15 | else 16 | echo "WARNING: invalid reference file ($OPTARG), default will be used" 17 | fi 18 | ;; 19 | t) 20 | optT=$OPTARG 21 | ;; 22 | '?') 23 | echo "Usage: $0 invalid option -$OPTARG" 24 | echo "Usage: $0 [-c iniFile] [-t threads, default 8] " 25 | exit 1 26 | ;; 27 | esac 28 | done 29 | shift $((OPTIND-1)) 30 | 31 | if [ $# -lt 4 ] 32 | then 33 | echo "Usage: $0 [-c iniFile] [-t threads, default 8] " 34 | exit 1 35 | fi 36 | 37 | echo begin at: `date` 38 | 39 | #source $iniFile 40 | 41 | sampleID=$1 42 | outDir=$2 43 | inBam=$3 44 | inBarcode=$4 45 | 46 | module load cellsnp/github 47 | 48 | echo begin at: `date` 49 | 50 | mkdir -p $outDir 51 | mkdir -p $outDir/mquad 52 | cd $outDir 53 | 54 | cellsnp-lite -s $inBam -b $inBarcode --outDir=$outDir --chrom=chrM --UMItag Auto --minMAF 0 --minCOUNT 0 --genotype --gzip -p $optT 55 | 56 | mquad --cellData $outDir --outDir $outDir/mquad -p $optT --minDP 5 57 | 58 | $sDir/wrapper.vireoSNP.py -i $outDir/mquad -o $outDir/mquad/vireo 59 | 60 | echo end at: `date` 61 | 62 | 63 | 64 | -------------------------------------------------------------------------------- /man/fill.contamination.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/sc.utils.R 3 | \name{fill.contamination} 4 | \alias{fill.contamination} 5 | \title{calculate the signature score of one potential contaminated cell types (simple average-threshold method)} 6 | \usage{ 7 | fill.contamination( 8 | obj, 9 | out.prefix, 10 | assay.name = "norm_exprs", 11 | g.name = "plasmaB", 12 | g.test = c("CD79A", "JCHAIN", "SDC1"), 13 | score.t = 0.75, 14 | vis.v = c(0.25, 0.5, 0.75, 1) 15 | ) 16 | } 17 | \arguments{ 18 | \item{obj}{object of \code{SingleCellExperiment} or \code{Seurat}} 19 | 20 | \item{out.prefix}{character; output prefix. (default: NULL)} 21 | 22 | \item{assay.name}{character vector; which assay to use. (default: "norm_exprs").} 23 | 24 | \item{g.name}{character; signature name of the cell type. (default: "plasmaB").} 25 | 26 | \item{g.test}{character vector; signature genes of the cell type. (default: c("CD79A", "JCHAIN", "SDC1")).} 27 | 28 | \item{score.t}{double; threshold for signature score (mean of g.test). (default: 1)} 29 | 30 | \item{vis.v}{double vector; for vertical lines in visulization. (default: c(0.25,0.5,1)).} 31 | } 32 | \value{ 33 | an object of \code{SingleCellExperiment} or \code{Seurat} 34 | } 35 | \description{ 36 | calculate the signature score of one potential contaminated cell types (simple average-threshold method) 37 | } 38 | \details{ 39 | Two columns will be added to the obj, "%s.score" and "%s.class, where %s is the g.name. 40 | } 41 | -------------------------------------------------------------------------------- /man/mergeSCEDataFromFileTable.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/sc.intClust.R 3 | \name{mergeSCEDataFromFileTable} 4 | \alias{mergeSCEDataFromFileTable} 5 | \title{collapse gene by cell expression data to gene by mini-cluster expression data, with input stored in SingleCellExperiment object} 6 | \usage{ 7 | mergeSCEDataFromFileTable( 8 | exp.list.table, 9 | gene.common, 10 | sce.list, 11 | group.vec, 12 | ncores = 6, 13 | contamination.vec = NULL, 14 | block.size = 1500 15 | ) 16 | } 17 | \arguments{ 18 | \item{exp.list.table}{data.table; one line for a dataset} 19 | 20 | \item{gene.common}{character vector; common genes across multiple datasets} 21 | 22 | \item{sce.list}{list; list containing sce objects} 23 | 24 | \item{group.vec}{character; cell id to mini-cluster mapping vector} 25 | 26 | \item{ncores}{integer; number of CPU cores to use} 27 | 28 | \item{contamination.vec}{character vector; cells to be excluded. (default: NULL)} 29 | 30 | \item{block.size}{integer; block size. To process large matrix, each time a block of [INT] genes is processed (default: 1500)} 31 | } 32 | \value{ 33 | a list, each component of which is expression matrix of gene.common by min-clusters 34 | } 35 | \description{ 36 | collapse gene by cell expression data to gene by mini-cluster expression data, with input stored in SingleCellExperiment object 37 | } 38 | \details{ 39 | For each dataset, the function first identify mini-clusters, then calculate the average expressions of mini-clusters. 40 | } 41 | -------------------------------------------------------------------------------- /appveyor.yml: -------------------------------------------------------------------------------- 1 | # DO NOT CHANGE the "init" and "install" sections below 2 | 3 | # Download script file from GitHub 4 | init: 5 | ps: | 6 | $ErrorActionPreference = "Stop" 7 | Invoke-WebRequest http://raw.github.com/krlmlr/r-appveyor/master/scripts/appveyor-tool.ps1 -OutFile "..\appveyor-tool.ps1" 8 | Import-Module '..\appveyor-tool.ps1' 9 | install: 10 | ps: Bootstrap 11 | 12 | # Adapt as necessary starting from here 13 | 14 | environment: 15 | global: 16 | R_ARCH: x64 17 | USE_RTOOLS: true 18 | matrix: 19 | - R_VERSION: stable 20 | PKGTYPE: both 21 | BIOC_USE_DEVEL: FALSE 22 | 23 | build_script: 24 | - travis-tool.sh r_binary_install BiocManager lifecycle 25 | - travis-tool.sh install_bioc SingleCellExperiment 26 | - travis-tool.sh install_deps 27 | - travis-tool.sh install_bioc_deps 28 | # - travis-tool.sh r_binary_install curl pkgmaker 29 | # - Rscript -e 'install.packages("https://cran.r-project.org/src/contrib/Archive/BiocManager/BiocManager_1.30.8.tar.gz")' 30 | # - travis-tool.sh install_r BiocManager 31 | 32 | 33 | test_script: 34 | - travis-tool.sh run_tests 35 | 36 | on_failure: 37 | - 7z a failure.zip *.Rcheck\* 38 | - appveyor PushArtifact failure.zip 39 | 40 | artifacts: 41 | - path: '*.Rcheck\**\*.log' 42 | name: Logs 43 | 44 | - path: '*.Rcheck\**\*.out' 45 | name: Logs 46 | 47 | - path: '*.Rcheck\**\*.fail' 48 | name: Logs 49 | 50 | - path: '*.Rcheck\**\*.Rout' 51 | name: Logs 52 | 53 | - path: '\*_*.tar.gz' 54 | name: Bits 55 | 56 | - path: '\*_*.zip' 57 | name: Bits 58 | -------------------------------------------------------------------------------- /inst/script/make.CC.R: -------------------------------------------------------------------------------- 1 | 2 | 3 | ###### functions from https://www.r-bloggers.com/2016/10/converting-mouse-to-human-gene-names-with-biomart-package 4 | # Basic function to convert mouse to human gene names 5 | convertMouseGeneList <- function(x){ 6 | 7 | require("biomaRt") 8 | human = useMart("ensembl", dataset = "hsapiens_gene_ensembl") 9 | mouse = useMart("ensembl", dataset = "mmusculus_gene_ensembl") 10 | 11 | genesV2 = getLDS(attributes = c("mgi_symbol"), filters = "mgi_symbol", values = x , mart = mouse, attributesL = c("hgnc_symbol"), martL = human, uniqueRows=T) 12 | humanx <- unique(genesV2[, 2]) 13 | 14 | # Print the first 6 genes found to the screen 15 | print(head(humanx)) 16 | return(humanx) 17 | } 18 | 19 | 20 | # Basic function to convert human to mouse gene names 21 | convertHumanGeneList <- function(x){ 22 | 23 | require("biomaRt") 24 | human = useMart("ensembl", dataset = "hsapiens_gene_ensembl") 25 | mouse = useMart("ensembl", dataset = "mmusculus_gene_ensembl") 26 | 27 | genesV2 = getLDS(attributes = c("hgnc_symbol"), filters = "hgnc_symbol", values = x , mart = human, attributesL = c("mgi_symbol"), martL = mouse, uniqueRows=T) 28 | 29 | humanx <- unique(genesV2[, 2]) 30 | 31 | # Print the first 6 genes found to the screen 32 | print(head(humanx)) 33 | return(humanx) 34 | } 35 | ######### 36 | 37 | data("cc.genes",package="Seurat",envir=a.env) 38 | a.env$cc.genes$s.genes 39 | a.env$cc.genes$g2m.genes 40 | 41 | cc.genes <- list("s.genes"=convertHumanGeneList(a.env$cc.genes$s.genes), 42 | "g2m.genes"=convertHumanGeneList(a.env$cc.genes$g2m.genes)) 43 | save(cc.genes,file="cc.genes.mouse.rda") 44 | -------------------------------------------------------------------------------- /man/mergeDataFromFileTable.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/sc.intClust.R 3 | \name{mergeDataFromFileTable} 4 | \alias{mergeDataFromFileTable} 5 | \title{merge data file file table} 6 | \usage{ 7 | mergeDataFromFileTable( 8 | exp.list.table, 9 | gene.de.common, 10 | seu.list, 11 | sce.list, 12 | res.hi, 13 | method.clustering = "louvain", 14 | ncores = 12, 15 | cor.var = c("S.Score", "G2M.Score", "DIG.Score1"), 16 | contamination.vec = NULL, 17 | use.harmony = F 18 | ) 19 | } 20 | \arguments{ 21 | \item{exp.list.table}{data.table; one line for a dataset} 22 | 23 | \item{gene.de.common}{character vector; common genes across multiple datasets} 24 | 25 | \item{seu.list}{list; list containing seu objects} 26 | 27 | \item{sce.list}{list; list containing sce objects} 28 | 29 | \item{res.hi}{integer; high resolution used for mini-clusters identification} 30 | 31 | \item{method.clustering}{character; clustering method for mini-clusters identification. (default: "louvain")} 32 | 33 | \item{ncores}{integer; number of CPU cores to use. (default: 12)} 34 | 35 | \item{cor.var}{character vector; subset of c("S.Score","G2M.Score","DIG.Score1","ISG.Score1","score.MALAT1")} 36 | 37 | \item{contamination.vec}{character vector; cells to be excluded. (default: NULL)} 38 | 39 | \item{use.harmony}{logical; use harmony to correct for batch effect (batches are defined in column batchV). (default: FALSE)} 40 | } 41 | \value{ 42 | a list containing 3 components: dat.avg, meta.extra.tb and clust 43 | } 44 | \description{ 45 | merge data file file table 46 | } 47 | \details{ 48 | For each dataset, the function first identify mini-clusters, then calculate the average expressions of mini-clusters. 49 | } 50 | -------------------------------------------------------------------------------- /inst/script/run.pyScenic.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | optA="" 4 | 5 | while getopts a: opt 6 | do 7 | case $opt in 8 | a) 9 | optA=$OPTARG 10 | ;; 11 | '?') 12 | echo "Usage: $0 invalid option -$OPTARG" 13 | echo "Usage: $0 <-a adj file> " 14 | exit 1 15 | ;; 16 | esac 17 | done 18 | shift $((OPTIND-1)) 19 | 20 | if [ $# -lt 2 ] 21 | then 22 | echo "Usage: $0 <-a adj file> " 23 | exit 1 24 | fi 25 | 26 | loomfile=$1 27 | out_prefix=$2 28 | 29 | outDir=`dirname $out_prefix` 30 | mkdir -p $outDir 31 | 32 | echo begin at: `date` 33 | 34 | cd $outDir 35 | 36 | export HDF5_USE_FILE_LOCKING='FALSE' 37 | 38 | ncores=8 39 | 40 | if [ -f $optA ];then 41 | gzip -cd $optA > $out_prefix.adj.csv 42 | else 43 | 44 | pyscenic grn \ 45 | -o $out_prefix.adj.csv \ 46 | -m grnboost2 \ 47 | --seed 123456 \ 48 | --num_workers $ncores \ 49 | $loomfile \ 50 | /lustre1/zeminz_pkuhpc/00.database/transcriptionalRegulatory/scenic/transcription.factor.activity.GO0003700.symbol.list 51 | 52 | ##--mask_dropouts \ 53 | 54 | fi 55 | 56 | ##-a \ 57 | 58 | pyscenic ctx \ 59 | -o $out_prefix.reg.csv \ 60 | --expression_mtx_fname $loomfile \ 61 | --num_workers $ncores \ 62 | --annotations_fname /lustre1/zeminz_pkuhpc/00.database/transcriptionalRegulatory/scenic/motifs-v9-nr.hgnc-m0.001-o0.0.tbl \ 63 | $out_prefix.adj.csv \ 64 | /lustre1/zeminz_pkuhpc/00.database/transcriptionalRegulatory/scenic/hg19-500bp-upstream-7species.mc9nr.feather \ 65 | /lustre1/zeminz_pkuhpc/00.database/transcriptionalRegulatory/scenic/hg19-tss-centered-10kb-7species.mc9nr.feather 66 | 67 | pyscenic aucell \ 68 | $loomfile \ 69 | $out_prefix.reg.csv \ 70 | --output $out_prefix.pyScenic.loom \ 71 | --seed 123456 \ 72 | --num_workers $ncores 73 | 74 | echo end at: `date` 75 | -------------------------------------------------------------------------------- /man/inSilico.TCell.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/sc.utils.R 3 | \name{inSilico.TCell} 4 | \alias{inSilico.TCell} 5 | \title{Identification of T cells (simple average-threshold method)} 6 | \usage{ 7 | inSilico.TCell( 8 | obj, 9 | out.prefix, 10 | assay.name = "norm_exprs", 11 | vis.v = c(0.25, 0.5), 12 | Th.CD3 = 0.25, 13 | Th.CD8 = 0.5, 14 | Th.CD4 = 0.5, 15 | Th.TH = 0.25, 16 | Th.TR = 0.25, 17 | do.zscore = F, 18 | Th.DC = 0.25, 19 | Th.GC1 = 0.25, 20 | Th.GC2 = 0.25, 21 | do.rescue = T 22 | ) 23 | } 24 | \arguments{ 25 | \item{obj}{object of \code{SingleCellExperiment} or \code{AnnDataR6}} 26 | 27 | \item{out.prefix}{character; output prefix. (default: NULL)} 28 | 29 | \item{assay.name}{character vector; which assay to use. (default: "norm_exprs").} 30 | 31 | \item{vis.v}{double vector; for vertical lines in visulization. (default: c(0.25,0.5)).} 32 | 33 | \item{Th.CD3}{double; threshold for T cell signature (mean of CD3D, CD3G). (default: 0.25)} 34 | 35 | \item{Th.CD8}{double; threshold for CD8 (mean of CD8A, CD8B). (default: 0.25)} 36 | 37 | \item{Th.CD4}{double; threshold for CD4 (expression of CD4). (default: 0.25)} 38 | 39 | \item{Th.TH}{double; threshold for Thelper signature (mean of CD4, CD40LG). (default: 0.25)} 40 | 41 | \item{Th.TR}{double; threshold for Treg signature (mean of CD4, FOXP3). (default: 0.25)} 42 | 43 | \item{do.zscore}{logical; whether use zscore for calculation. (default: FALSE)} 44 | 45 | \item{Th.DC}{double; threshold for delta receptor constant chain. (default: 0.25)} 46 | 47 | \item{Th.GC1}{double; threshold for gamma receptor constant chain 1. (default: 0.25)} 48 | 49 | \item{Th.GC2}{double; threshold for gamma receptor constant chain 2. (default: 0.25)} 50 | 51 | \item{do.rescue}{logical; whether use "rescue" mode. (default: FALSE)} 52 | } 53 | \value{ 54 | a SingleCellExperiment object 55 | } 56 | \description{ 57 | Identification of T cells (simple average-threshold method) 58 | } 59 | \details{ 60 | columns stype and gdType will be added to the obj 61 | } 62 | -------------------------------------------------------------------------------- /man/convertLimmaToSCE.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/sc.intClust.R 3 | \name{convertLimmaToSCE} 4 | \alias{convertLimmaToSCE} 5 | \title{convert the limma result to gene by meta-cluster data stored in an SingleCellExperiment object} 6 | \usage{ 7 | convertLimmaToSCE( 8 | de.limma.tb, 9 | out.prefix, 10 | ncores = 8, 11 | min.ncells = 30, 12 | min.ncellsStudy = 200, 13 | gset.list = NULL, 14 | direct.sig = T, 15 | TH.gene.occ = 1, 16 | de.mode = "multiAsTwo", 17 | column.exp = "meanScale", 18 | gene.used = NULL, 19 | colSet = list() 20 | ) 21 | } 22 | \arguments{ 23 | \item{de.limma.tb}{data.table; one line for a dataset. columns "data.id", "platform", and "dfile" are required} 24 | 25 | \item{out.prefix}{character; output prefix} 26 | 27 | \item{ncores}{integer; number of CPU cores to use. (default: 8)} 28 | 29 | \item{min.ncells}{integer; only meta-clusters with number of cells > min.ncells are used. (default: 30)} 30 | 31 | \item{min.ncellsStudy}{integer; only datasets with number of cells > min.ncellsStudy are used. (default: 200)} 32 | 33 | \item{gset.list}{list; list containing gene sets. (default: NULL)} 34 | 35 | \item{direct.sig}{logical; if TRUE, genes exibit significance in all datasets will be assigned "sig" directly, irrespective of combined ES and combined adjusted p vlaue. (default: TRUE)} 36 | 37 | \item{TH.gene.occ}{double; range from 0 to 1. genes present in >= TH.gene.occ datasets are used. (default: 1)} 38 | 39 | \item{de.mode}{character; mode of differential expression analysis. (default: "multiAsTwo")} 40 | 41 | \item{column.exp}{character; convert the column of limma result to assay data. (default: "meanScale")} 42 | 43 | \item{gene.used}{character; only keep genes in gene.used. (default: NULL)} 44 | 45 | \item{colSet}{list; mapping iterms in the names to colors in the values. (default: list())} 46 | } 47 | \value{ 48 | a SingleCellExperiment object 49 | } 50 | \description{ 51 | convert the limma result to gene by meta-cluster data stored in an SingleCellExperiment object 52 | } 53 | \details{ 54 | convert the limma result to gene by meta-cluster data stored in an SingleCellExperiment object 55 | } 56 | -------------------------------------------------------------------------------- /inst/script/wrapper.convertLimmaToSCE.R: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env Rscript 2 | 3 | suppressPackageStartupMessages(library("argparse")) 4 | 5 | parser <- ArgumentParser() 6 | parser$add_argument("-i", "--limmaFile", type="character", required=TRUE, help="input limma file list") 7 | parser$add_argument("-o", "--outPrefix", type="character", required=TRUE, help="outPrefix") 8 | parser$add_argument("-c", "--occ", type="double", default=0.85, help="genes detected in >= OCC datasets will be kept [default %(default)s]") 9 | parser$add_argument("-m", "--minCells", type="integer",default=30L, help="minimum number of cells in the clusters [default %(default)s]") 10 | parser$add_argument("-k", "--minStudy", type="integer",default=200L, help="minimum number of cells in the study [default %(default)s]") 11 | parser$add_argument("-n", "--ncores", type="integer",default=16L, help="[default %(default)s]") 12 | #parser$add_argument("-m", "--measurement",type="character",default="counts",help="[default %(default)s]") 13 | args <- parser$parse_args() 14 | print(args) 15 | 16 | 17 | in.file <- args$limmaFile 18 | out.prefix <- args$outPrefix 19 | opt.gene.occ <- args$occ 20 | opt.ncores <- args$ncores 21 | opt.minCells <- args$minCells 22 | opt.minStudy <- args$minStudy 23 | #opt.measurement <- args$measurement 24 | 25 | dir.create(dirname(out.prefix),F,T) 26 | 27 | ############## tune parametrs ######## 28 | library("scPip") 29 | library("data.table") 30 | library("tictoc") 31 | library("sscVis") 32 | 33 | RhpcBLASctl::omp_set_num_threads(1) 34 | doParallel::registerDoParallel(cores = opt.ncores) 35 | options(stringsAsFactors = FALSE) 36 | 37 | ###################### 38 | de.limma.tb <- fread(in.file) 39 | 40 | sce.pb.file <- sprintf("%s.sce.pb.rds",out.prefix) 41 | if(file.exists(sce.pb.file)){ 42 | loginfo(sprintf("load sce.pb file...")) 43 | sce.pb <- readRDS(sce.pb.file) 44 | }else{ 45 | tic("convertLimmaToSCE") 46 | sce.pb <- convertLimmaToSCE(de.limma.tb,out.prefix,ncores=8, 47 | min.ncells=opt.minCells,min.ncellsStudy=opt.minStudy, 48 | gset.list=NULL, 49 | de.mode="multiAsTwo",column.exp="meanScale", 50 | TH.gene.occ=opt.gene.occ, 51 | gene.used=NULL,colSet=list()) 52 | toc() 53 | } 54 | 55 | tic("make.geneTableLong()") 56 | make.geneTableLong(sce.pb,out.prefix,th.adj.P=0.01,th.dprime=0.15) 57 | toc() 58 | 59 | -------------------------------------------------------------------------------- /man/run.inte.metaClust.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/sc.intClust.R 3 | \name{run.inte.metaClust} 4 | \alias{run.inte.metaClust} 5 | \title{run the integration pipeline} 6 | \usage{ 7 | run.inte.metaClust( 8 | exp.list.table, 9 | out.prefix, 10 | gene.exclude.file, 11 | nGene.common = 1500, 12 | nGene.specific = 0, 13 | ncores = 12, 14 | npc = 15, 15 | TH.gene.occ = 1, 16 | res.hi = 50, 17 | method.clustering = "louvain", 18 | cor.var = c("S.Score", "G2M.Score", "DIG.Score1"), 19 | use.harmony = F, 20 | contamination.vec = NULL, 21 | gene.informative.file = NULL 22 | ) 23 | } 24 | \arguments{ 25 | \item{exp.list.table}{data.table; one line for a dataset} 26 | 27 | \item{out.prefix}{character; output prefix} 28 | 29 | \item{gene.exclude.file}{character; file contains the genes to be excluded} 30 | 31 | \item{nGene.common}{integer; number of common genes. (default: 1500)} 32 | 33 | \item{nGene.specific}{integer; number of dataset specific genes. (default: 0)} 34 | 35 | \item{ncores}{integer; number of CPU cores to use. (default: 12)} 36 | 37 | \item{npc}{integer; number of principal components to use. (default: 15)} 38 | 39 | \item{TH.gene.occ}{double; range from 0 to 1. genes present in >= TH.gene.occ datasets are used. (default: 1)} 40 | 41 | \item{res.hi}{integer; high resolution used for mini-clusters identification. (default: 50)} 42 | 43 | \item{method.clustering}{character; clustering method for mini-clusters identification. (default: "louvain")} 44 | 45 | \item{cor.var}{character vector; subset of c("S.Score","G2M.Score","DIG.Score1","ISG.Score1","score.MALAT1")} 46 | 47 | \item{use.harmony}{logical; use harmony to correct for batch effect (batches are defined in column batchV). (default: FALSE)} 48 | 49 | \item{contamination.vec}{character vector; cells to be excluded. (default: NULL)} 50 | 51 | \item{gene.informative.file}{character; file contains informative genes which are to be used for integration. column geneSymbol is required. (default: NULL)} 52 | } 53 | \value{ 54 | a list containing 3 components: sce.merged, seu.merged and meta.tb 55 | } 56 | \description{ 57 | run the integration pipeline 58 | } 59 | \details{ 60 | For each dataset, the function first identify mini-clusters, then calculate the average expressions of mini-clusters. The gene by mini-cluster expression data will pass the pipeline: PCA, harmony, UMAP/Clustering. 61 | } 62 | -------------------------------------------------------------------------------- /inst/script/run.cellRanger.count.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | sDir=`dirname $0` 4 | iniFile="$sDir/../parameter/init_human.sh" 5 | _refData="/WPSnew/zhenglt/00.database/broad/bundle/2.8/b37/human_g1k_v37_decoy.fasta" 6 | ###_refData="/DBS/DB_temp/zhangLab/broad/bundle/2.8/b37/human_g1k_v37_decoy.fasta" 7 | optT="--localcores 4" 8 | optM="--localmem 16" 9 | optS="human" 10 | optP="" 11 | 12 | while getopts c:t:m:s:p: opt 13 | do 14 | case $opt in 15 | c) 16 | if [ -f $OPTARG ] 17 | then 18 | iniFile="$OPTARG" 19 | else 20 | echo "WARNING: invalid reference file ($OPTARG), default will be used" 21 | fi 22 | ;; 23 | t) 24 | optT="--localcores $OPTARG" 25 | ;; 26 | m) 27 | optM="--localmem $OPTARG" 28 | ;; 29 | s) 30 | optS=$OPTARG 31 | ;; 32 | p) 33 | optP=$OPTARG 34 | ;; 35 | '?') 36 | echo "Usage: $0 invalid option -$OPTARG" 37 | echo "Usage: $0 [-c iniFile] [-t threads, default 4] [-m memrory(GB), default 16] [-s species, default human] [-p cellranger parameters] " 38 | exit 1 39 | ;; 40 | esac 41 | done 42 | shift $((OPTIND-1)) 43 | 44 | if [ $# -lt 3 ] 45 | then 46 | echo "Usage: $0 [-c iniFile] [-t threads, default 4] [-m memrory(GB), default 16] [-s species, default human] [-p cellranger parameters] " 47 | exit 1 48 | fi 49 | 50 | echo begin at: `date` 51 | 52 | source $iniFile 53 | 54 | outDir=$1 55 | inDir=$2 56 | sampleID=$3 57 | 58 | if [ "$optS" == "human" ];then 59 | transcriptomeDir="/WPSnew/zhenglt/00.database/ensemble/10X/refdata-cellranger-GRCh38-1.2.0" 60 | elif [ "$optS" == "mouse" ];then 61 | transcriptomeDir="/WPSnew/zhenglt/00.database/ensemble/10X/refdata-cellranger-mm10-1.2.0" 62 | fi 63 | 64 | mkdir -p $outDir 65 | ###export MODULESHOME=/usr/share/Modules 66 | ###. /usr/share/Modules/init/bash 67 | ###export MODULEPATH="/Share/BP/zhenglt/05.setting/modulefiles":/usr/share/Modules/modulefiles:/etc/modulefiles 68 | #module load cellranger/2.1.1 69 | module load cellranger/3.0.0 70 | 71 | #outDir=`pwd`/OUT.cellranger 72 | #mkdir -p $outDir 73 | #mkdir -p $outDir/fq 74 | 75 | echo begin at: `date` 76 | cd $outDir 77 | 78 | echo cellranger count --id=$sampleID $optT $optM \ 79 | --fastqs=$inDir \ 80 | --sample=$sampleID \ 81 | --transcriptome=$transcriptomeDir $optP 82 | 83 | 84 | cellranger count --id=$sampleID $optT $optM \ 85 | --fastqs=$inDir \ 86 | --sample=$sampleID \ 87 | --transcriptome=$transcriptomeDir $optP 88 | 89 | ####--expect-cells=3000 90 | echo end at: `date` 91 | 92 | 93 | 94 | -------------------------------------------------------------------------------- /man/run.scanpy.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/sc.utils.R 3 | \name{run.scanpy} 4 | \alias{run.scanpy} 5 | \title{Wraper for running scanpy pipeline} 6 | \usage{ 7 | run.scanpy( 8 | adata, 9 | out.prefix, 10 | gene.exclude.df, 11 | n.top = 1500, 12 | opt.res = "1", 13 | aid = "PRJ", 14 | plot.rd = c("umap"), 15 | opt.npc = 15L, 16 | ncores = 16, 17 | res.test = seq(0.1, 2.4, 0.1), 18 | cor.var = c("S_score", "G2M_score", "DIG.Score", "percent.mito"), 19 | ncell.deg = 1500, 20 | do.deg = F, 21 | hvg.batch.minNCells = 100, 22 | use.harmony = T, 23 | method.integration = NULL, 24 | specie = "human", 25 | max_iter_harmony = 30L, 26 | gene.mapping.table = NULL, 27 | res.addition = NULL, 28 | run.stage = 100 29 | ) 30 | } 31 | \arguments{ 32 | \item{adata}{object of \code{AnnData}} 33 | 34 | \item{out.prefix}{character; output prefix} 35 | 36 | \item{gene.exclude.df}{data.frame; gene blak list. Required column: seu.id.} 37 | 38 | \item{n.top}{integer; number of top genes. (default: 1500)} 39 | 40 | \item{opt.res}{character; optimal resolution (default: "1")} 41 | 42 | \item{aid}{character; an ID (default: "PRJ")} 43 | 44 | \item{plot.rd}{character vector; reducedDimNames used for plots (default: c("umap"))} 45 | 46 | \item{opt.npc}{integer; optimal number of principal componets to use (default: 15L)} 47 | 48 | \item{ncores}{integer; number of CPU cores to use (default: 16)} 49 | 50 | \item{res.test}{double; resolutions to test (default: seq(0.1,2.4,0.1) )} 51 | 52 | \item{cor.var}{character vector; Subset of c("S_score","G2M_score","DIG.Score","ISG.Score","percent.mito") or NULL. (default: c("S_score","G2M_score","DIG.Score","percent.mito")).} 53 | 54 | \item{ncell.deg}{integer; number of cell to downsample. used in the differentially expressed gene analysis. (default: 1500)} 55 | 56 | \item{do.deg}{logical; whether perform the differentially expressed gene analysis. (default: FALSE)} 57 | 58 | \item{hvg.batch.minNCells}{integer; required minimum number of cells in each batch. Batch with < hvg.batch.minNCells will not be used for HVG finding. (default: 100)} 59 | 60 | \item{use.harmony}{logical; whether use the harmony method. (default: TRUE)} 61 | 62 | \item{method.integration}{character; integration method. (default: NULL)} 63 | 64 | \item{specie}{character; specie, one of "human", "mouse". (default: "human")} 65 | 66 | \item{max_iter_harmony}{integer; max_iter_harmony of sc$external$pp$harmony_integrate(). (default: 30L)} 67 | 68 | \item{gene.mapping.table}{data.table; used for gene ID conversion. (default: NULL)} 69 | 70 | \item{res.addition}{character vector; additional resolution parameters. Internally, resolutions from 0.1 to 2.4 will be used. (default: NULL)} 71 | 72 | \item{run.stage}{integer; running stage. (default: 100)} 73 | } 74 | \value{ 75 | a list contain an object of \code{AnnData} 76 | } 77 | \description{ 78 | Wraper for running scanpy pipeline 79 | } 80 | \details{ 81 | run the scanpy pipeline 82 | } 83 | -------------------------------------------------------------------------------- /man/run.rapids_singlecell.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/sc.utils.R 3 | \name{run.rapids_singlecell} 4 | \alias{run.rapids_singlecell} 5 | \title{Wraper for running rapids_singlecell pipeline} 6 | \usage{ 7 | run.rapids_singlecell( 8 | adata, 9 | out.prefix, 10 | gene.exclude.df, 11 | n.top = 1500, 12 | opt.res = "1", 13 | aid = "PRJ", 14 | plot.rd = c("umap"), 15 | opt.npc = 15L, 16 | ncores = 16, 17 | res.test = seq(0.1, 2.4, 0.1), 18 | cor.var = c("S_score", "G2M_score", "DIG.Score", "percent.mito"), 19 | ncell.deg = 1500, 20 | do.deg = F, 21 | hvg.batch.minNCells = 100, 22 | use.harmony = T, 23 | method.integration = NULL, 24 | specie = "human", 25 | max_iter_harmony = 30L, 26 | gene.mapping.table = NULL, 27 | res.addition = NULL, 28 | run.stage = 100 29 | ) 30 | } 31 | \arguments{ 32 | \item{adata}{object of \code{AnnData}} 33 | 34 | \item{out.prefix}{character; output prefix} 35 | 36 | \item{gene.exclude.df}{data.frame; gene blak list. Required column: seu.id.} 37 | 38 | \item{n.top}{integer; number of top genes. (default: 1500)} 39 | 40 | \item{opt.res}{character; optimal resolution (default: "1")} 41 | 42 | \item{aid}{character; an ID (default: "PRJ")} 43 | 44 | \item{plot.rd}{character vector; reducedDimNames used for plots (default: c("umap"))} 45 | 46 | \item{opt.npc}{integer; optimal number of principal componets to use (default: 15L)} 47 | 48 | \item{ncores}{integer; number of CPU cores to use (default: 16)} 49 | 50 | \item{res.test}{double; resolutions to test (default: seq(0.1,2.4,0.1) )} 51 | 52 | \item{cor.var}{character vector; Subset of c("S_score","G2M_score","DIG.Score","ISG.Score","percent.mito") or NULL. (default: c("S_score","G2M_score","DIG.Score","percent.mito")).} 53 | 54 | \item{ncell.deg}{integer; number of cell to downsample. used in the differentially expressed gene analysis. (default: 1500)} 55 | 56 | \item{do.deg}{logical; whether perform the differentially expressed gene analysis. (default: FALSE)} 57 | 58 | \item{hvg.batch.minNCells}{integer; required minimum number of cells in each batch. Batch with < hvg.batch.minNCells will not be used for HVG finding. (default: 100)} 59 | 60 | \item{use.harmony}{logical; whether use the harmony method. (default: TRUE)} 61 | 62 | \item{method.integration}{character; integration method. (default: NULL)} 63 | 64 | \item{specie}{character; specie, one of "human", "mouse". (default: "human")} 65 | 66 | \item{max_iter_harmony}{integer; max_iter_harmony of sc$external$pp$harmony_integrate(). (default: 30L)} 67 | 68 | \item{gene.mapping.table}{data.table; used for gene ID conversion. (default: NULL)} 69 | 70 | \item{res.addition}{character vector; additional resolution parameters. Internally, resolutions from 0.1 to 2.4 will be used. (default: NULL)} 71 | 72 | \item{run.stage}{integer; running stage. (default: 100)} 73 | } 74 | \value{ 75 | a list contain an object of \code{AnnData} 76 | } 77 | \description{ 78 | Wraper for running rapids_singlecell pipeline 79 | } 80 | \details{ 81 | run the rapids_singlecell pipeline 82 | } 83 | -------------------------------------------------------------------------------- /man/run.Seurat3.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/sc.utils.R 3 | \name{run.Seurat3} 4 | \alias{run.Seurat3} 5 | \title{Wraper for running Seurat3 pipeline} 6 | \usage{ 7 | run.Seurat3( 8 | seu, 9 | sce, 10 | out.prefix, 11 | gene.exclude.df, 12 | n.top = 1500, 13 | measurement = "counts", 14 | platform = "10X", 15 | opt.res = "1", 16 | use.sctransform = F, 17 | aid = "PRJ", 18 | plot.rd = c("umap"), 19 | opt.npc = 15, 20 | ncores = 16, 21 | cor.var = c("S.Score", "G2M.Score", "DIG.Score1", "percent.mito", "batchV"), 22 | ncell.deg = 1500, 23 | do.deg = F, 24 | do.scale = F, 25 | use.harmony = F, 26 | method.integration = NULL, 27 | specie = "human", 28 | gene.mapping.table = NULL, 29 | res.addition = NULL, 30 | run.stage = 100 31 | ) 32 | } 33 | \arguments{ 34 | \item{seu}{object of \code{Seurat}} 35 | 36 | \item{sce}{object of \code{SingleCellExperiment}} 37 | 38 | \item{out.prefix}{character; output prefix} 39 | 40 | \item{gene.exclude.df}{data.frame; gene blak list. Required column: seu.id.} 41 | 42 | \item{n.top}{integer; number of top genes. (default: 1500)} 43 | 44 | \item{measurement}{character; "counts", "TPM" or "cpm". (default: "counts")} 45 | 46 | \item{platform}{character; "10X", "SmartSeq2", "InDrop" etc.. (default: "10X")} 47 | 48 | \item{opt.res}{character; optimal resolution (default: "1")} 49 | 50 | \item{use.sctransform}{logical; whether use scTransform method (default: FALSE)} 51 | 52 | \item{aid}{character; an ID (default: "PRJ")} 53 | 54 | \item{plot.rd}{character vector; reducedDimNames used for plots (default: c("umap"))} 55 | 56 | \item{opt.npc}{integer; optimal number of principal componets to use (default: 15)} 57 | 58 | \item{ncores}{integer; number of CPU cores to use (default: 16)} 59 | 60 | \item{cor.var}{character vector; Subset of c("S.Score","G2M.Score","DIG.Score1","ISG.Score1","percent.mito","batchV") or NULL. (default: c("S.Score","G2M.Score","DIG.Score1","percent.mito","batchV")).} 61 | 62 | \item{ncell.deg}{integer; number of cell to downsample. used in the differentially expressed gene analysis. (default: 1500)} 63 | 64 | \item{do.deg}{logical; whether perform the differentially expressed gene analysis. (default: FALSE)} 65 | 66 | \item{do.scale}{logical; whether scale the expression data. (default: FALSE)} 67 | 68 | \item{use.harmony}{logical; whether use the harmony method. (default: FALSE)} 69 | 70 | \item{method.integration}{character; integration method. (default: NULL)} 71 | 72 | \item{specie}{character; specie, one of "human", "mouse". (default: "human")} 73 | 74 | \item{gene.mapping.table}{data.table; used for gene ID conversion. (default: NULL)} 75 | 76 | \item{res.addition}{character vector; additional resolution parameters. Internally, resolutions from 0.1 to 2.4 will be used. (default: NULL)} 77 | 78 | \item{run.stage}{integer; running stage. (default: 100)} 79 | } 80 | \value{ 81 | a list contain a Seurat object and a SingleCellExperiment object 82 | } 83 | \description{ 84 | Wraper for running Seurat3 pipeline 85 | } 86 | \details{ 87 | run the Seurat3 pipeline 88 | } 89 | -------------------------------------------------------------------------------- /inst/script/run.scibet.R: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env Rscript 2 | 3 | suppressPackageStartupMessages(library("argparse")) 4 | suppressMessages(library("anndata")) 5 | suppressMessages(library("scibet")) 6 | suppressMessages(library("tidyverse")) 7 | suppressMessages(library("data.table")) 8 | suppressMessages(library("plyr")) 9 | 10 | parser <- ArgumentParser() 11 | parser$add_argument("-i", "--inFile", type="character", required=TRUE, help="input h5ad file. 'cellID' is required in the obs") 12 | parser$add_argument("-d", "--dataset", type="character", default="DataSet01", help="dataset name. [default %(default)s]") 13 | parser$add_argument("-m", "--modelPath", type="character", help="model path. If not specified, use a ESCA model stored under the directory of the package ") 14 | parser$add_argument("-o", "--outPrefix", type="character", required=TRUE, help="out prefix") 15 | args <- parser$parse_args() 16 | print(args) 17 | 18 | in.file <- args$inFile 19 | out.prefix <- args$outPrefix 20 | opt.dataset <- args$dataset 21 | model_path <- args$modelPath 22 | #in.file = c('OUT.ann.all/ESCA.HuyQDinh2021.scanpy.h5ad') 23 | #out.prefix = './OUT.scibet/PanC' 24 | #opt.dataset = 'HuyQDinh2021' 25 | dir.create(dirname(out.prefix),F,T) 26 | 27 | 28 | ##############Set larger connection buffer for reading################### 29 | #Sys.setenv ("VROOM_CONNECTION_SIZE" = 131072 * 2) 30 | if(is.null(model_path)){ 31 | model_path <- system.file("extdata/scibet/model_ESCA",package="scPip") 32 | } 33 | 34 | ############## Prediction ################################################ 35 | { 36 | 37 | cat("load model model.major.all.rds ...\n") 38 | model_all = readRDS(file.path(model_path,'model.major.all.rds')) 39 | model.sub.filepath <- list.files(model_path,'model.sub.+\\.rds',full.names = F) 40 | m <- regexec("model.sub.(.+?).rds",model.sub.filepath,perl=T) 41 | mm <- regmatches(model.sub.filepath,m) 42 | cellSubtype.vec <- sapply(mm,"[",2) 43 | #cellSubtype.vec <- c("T8","Th","Treg","ILC","B","Plasma", 44 | # "Neutro","pDC","DC","M","Mast", 45 | # "Endo","Fibro","SMC","Epi","Glia") 46 | model_sub_list <- sapply(cellSubtype.vec, function(x){ 47 | mfile <- paste0("model.sub.", x, ".rds") 48 | cat(sprintf("load model %s ...\n",mfile)) 49 | readRDS(file.path(model_path, mfile)) 50 | }) 51 | names(model_sub_list) <- cellSubtype.vec 52 | 53 | #### read and process expression matrix 54 | dat_test <- read_h5ad(in.file) 55 | dat_test_mtx = expm1(as.matrix(dat_test$X)) 56 | 57 | #### predict major cell types 58 | prd.vec = model_all(dat_test_mtx) 59 | prd.tb <- data.table("cellID"=rownames(dat_test_mtx),dataset=opt.dataset,"scibetMajor"=prd.vec) 60 | 61 | ##### within each major group, predict sub types 62 | prd.full.tb <- as.data.table(ldply(cellSubtype.vec,function(ct_sel) { 63 | prd.x.tb <- prd.tb[scibetMajor==ct_sel,] 64 | dat_test_mtx_x = dat_test_mtx[prd.x.tb$cellID,,drop=F] 65 | ### a bug: 3550 lables when only 1 cell in 'matrix' dat_test_mtx_x 66 | ### it works when convert dat_test_mtx_x from 'matrix' to 'tibble' 67 | if(nrow(dat_test_mtx_x)==1){ 68 | dat_test_mtx_x <- as_tibble(dat_test_mtx_x) 69 | } 70 | prd.x.vec <- model_sub_list[[ct_sel]](dat_test_mtx_x) 71 | prd.x.tb$scibetSub <- prd.x.vec 72 | print(sprintf("cellSubtype done (%s)!",ct_sel)) 73 | rm(dat_test_mtx_x) 74 | return(prd.x.tb) 75 | })) 76 | rm(dat_test_mtx,dat_test) 77 | gc() 78 | } 79 | 80 | saveRDS(prd.full.tb,file=sprintf("%s.ann.tb.rds",out.prefix)) 81 | 82 | cat("annotation result saved !\n") 83 | 84 | -------------------------------------------------------------------------------- /NAMESPACE: -------------------------------------------------------------------------------- 1 | # Generated by roxygen2: do not edit by hand 2 | 3 | export(cal.signatureScore.gdT.Fred) 4 | export(calEffectSizeFromDE) 5 | export(calProliferationScore) 6 | export(convertLimmaToSCE) 7 | export(fill.contamination) 8 | export(inSilico.TCell) 9 | export(inSilico.TGammaDelta) 10 | export(make.geneTableLong) 11 | export(render_KnitReport) 12 | export(run.HVG) 13 | export(run.Leiden) 14 | export(run.Scanorama) 15 | export(run.Seurat3) 16 | export(run.inte.metaClust) 17 | export(run.rapids_singlecell) 18 | export(run.scanpy) 19 | importFrom(Matrix,colMeans) 20 | importFrom(Matrix,rowMeans) 21 | importFrom(R.utils,loadToEnv) 22 | importFrom(RColorBrewer,brewer.pal) 23 | importFrom(RhpcBLASctl,omp_set_num_threads) 24 | importFrom(S4Vectors,DataFrame) 25 | importFrom(S4Vectors,`metadata<-`) 26 | importFrom(S4Vectors,metadata) 27 | importFrom(Seurat,AddModuleScore) 28 | importFrom(Seurat,CellCycleScoring) 29 | importFrom(Seurat,CreateSeuratObject) 30 | importFrom(Seurat,DimPlot) 31 | importFrom(Seurat,Embeddings) 32 | importFrom(Seurat,FindClusters) 33 | importFrom(Seurat,FindNeighbors) 34 | importFrom(Seurat,FindVariableFeatures) 35 | importFrom(Seurat,GetAssayData) 36 | importFrom(Seurat,NoLegend) 37 | importFrom(Seurat,ProjectDim) 38 | importFrom(Seurat,RunPCA) 39 | importFrom(Seurat,RunTSNE) 40 | importFrom(Seurat,RunUMAP) 41 | importFrom(Seurat,SCTransform) 42 | importFrom(Seurat,ScaleData) 43 | importFrom(Seurat,SetAssayData) 44 | importFrom(Seurat,`VariableFeatures<-`) 45 | importFrom(SingleCellExperiment,`reducedDim<-`) 46 | importFrom(SingleCellExperiment,colData) 47 | importFrom(SingleCellExperiment,reducedDim) 48 | importFrom(SingleCellExperiment,rowData) 49 | importFrom(SummarizedExperiment,`assay<-`) 50 | importFrom(SummarizedExperiment,`colData<-`) 51 | importFrom(SummarizedExperiment,`rowData<-`) 52 | importFrom(SummarizedExperiment,assay) 53 | importFrom(SummarizedExperiment,assayNames) 54 | importFrom(SummarizedExperiment,colData) 55 | importFrom(SummarizedExperiment,rowData) 56 | importFrom(cowplot,plot_grid) 57 | importFrom(cowplot,save_plot) 58 | importFrom(data.table,`:=`) 59 | importFrom(data.table,as.data.table) 60 | importFrom(data.table,data.table) 61 | importFrom(data.table,dcast) 62 | importFrom(data.table,fread) 63 | importFrom(data.table,melt) 64 | importFrom(data.table,setDT) 65 | importFrom(doParallel,registerDoParallel) 66 | importFrom(dplyr,arrange) 67 | importFrom(ggplot2,aes_string) 68 | importFrom(ggplot2,element_text) 69 | importFrom(ggplot2,facet_wrap) 70 | importFrom(ggplot2,geom_density) 71 | importFrom(ggplot2,geom_vline) 72 | importFrom(ggplot2,ggplot) 73 | importFrom(ggplot2,ggsave) 74 | importFrom(ggplot2,theme) 75 | importFrom(ggplot2,theme_bw) 76 | importFrom(ggpubr,ggboxplot) 77 | importFrom(ggpubr,ggdensity) 78 | importFrom(ggpubr,theme_pubr) 79 | importFrom(grid,gpar) 80 | importFrom(grid,unit) 81 | importFrom(harmony,RunHarmony) 82 | importFrom(leiden,leiden) 83 | importFrom(magrittr,`%>%`) 84 | importFrom(matrixStats,rowMedians) 85 | importFrom(plyr,l_ply) 86 | importFrom(plyr,ldply) 87 | importFrom(plyr,llply) 88 | importFrom(reticulate,import) 89 | importFrom(rmarkdown,render) 90 | importFrom(scran,buildSNNGraph) 91 | importFrom(sscClust,classify.outlier) 92 | importFrom(sscClust,effectsize) 93 | importFrom(sscClust,integrate.by.avg) 94 | importFrom(sscClust,rank.de.gene) 95 | importFrom(sscClust,ssc.DEGene.limma) 96 | importFrom(sscVis,collapseEffectSizeLong) 97 | importFrom(sscVis,loginfo) 98 | importFrom(sscVis,plotMatrix.simple) 99 | importFrom(sscVis,ssc.average.cell) 100 | importFrom(sscVis,ssc.build) 101 | importFrom(sscVis,ssc.plot.heatmap) 102 | importFrom(sscVis,ssc.plot.tsne) 103 | importFrom(sscVis,ssc.plot.violin) 104 | importFrom(sscVis,ssc.scale) 105 | importFrom(sscVis,ssc.toLongTable) 106 | importFrom(stats,median) 107 | importFrom(stats,p.adjust) 108 | importFrom(stats,pnorm) 109 | importFrom(stats,pt) 110 | importFrom(stats,qnorm) 111 | importFrom(tibble,rownames_to_column) 112 | importFrom(tictoc,tic) 113 | importFrom(tictoc,toc) 114 | importFrom(utils,data) 115 | importFrom(utils,head) 116 | importFrom(utils,str) 117 | importFrom(utils,write.table) 118 | -------------------------------------------------------------------------------- /inst/script/plot.scibet.R: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env Rscript 2 | 3 | suppressPackageStartupMessages(library("argparse")) 4 | 5 | parser <- ArgumentParser() 6 | parser$add_argument("-i", "--inFile", type="character", required=TRUE, help="input h5ad file. 'cellID' is required in the obs") 7 | parser$add_argument("-d", "--dataset", type="character", default="DataSet01", help="dataset name. [default %(default)s]") 8 | parser$add_argument("-a", "--annFile", type="character", required=TRUE, help="annotation file by run.scibet.R") 9 | #parser$add_argument("-o", "--outPrefix", type="character", required=TRUE, help="out prefix") 10 | args <- parser$parse_args() 11 | print(args) 12 | 13 | in.file <- args$inFile 14 | #out.prefix <- args$outPrefix 15 | opt.dataset <- args$dataset 16 | ann.file <- args$annFile 17 | out.prefix = gsub(".h5ad$","",in.file) 18 | #dir.create(dirname(out.prefix),F,T) 19 | 20 | ############ settings ########## 21 | { 22 | suppressMessages(library("R.utils")) 23 | suppressMessages(library("data.table")) 24 | suppressMessages(library("sscVis")) 25 | suppressMessages(library("tictoc")) 26 | suppressMessages(library("plyr")) 27 | suppressMessages(library("ggplot2")) 28 | suppressMessages(library("ggpubr")) 29 | suppressMessages(library("anndata")) 30 | suppressMessages(library("reticulate")) 31 | sc <- import("scanpy") 32 | plt <- import("matplotlib.pyplot") 33 | 34 | sc$set_figure_params(dpi=300,dpi_save=300,fontsize=12) 35 | 36 | RhpcBLASctl::omp_set_num_threads(1) 37 | doParallel::registerDoParallel(cores = 8) 38 | 39 | } 40 | 41 | ############ function ########## 42 | { 43 | split_umap <- function(adata,split_by,plot.ncol=4,plot.nrow=NULL,...) 44 | { 45 | 46 | my.xlim <- pretty(adata$obsm$X_umap[,1]) 47 | my.ylim <- pretty(adata$obsm$X_umap[,2]) 48 | my.xlim <- my.xlim[c(1,length(my.xlim))] 49 | my.ylim <- my.ylim[c(1,length(my.ylim))] 50 | 51 | categories <- levels(adata$obs[[split_by]]) 52 | if(is.null(plot.nrow)){ 53 | plot.nrow <- ceiling(length(categories) / plot.ncol) 54 | } 55 | fig_axs <- plt$subplots(as.integer(plot.nrow), 56 | as.integer(plot.ncol), 57 | figsize=c(5*plot.ncol, 4*plot.nrow)) 58 | names(fig_axs) <- c("fig","axs") 59 | axs <- matrix(fig_axs[["axs"]],nrow=1) 60 | for(i in seq_along(categories)){ 61 | ax <- axs[[i]] 62 | sc$pl$umap(adata[adata$obs[[split_by]] == categories[i] ], ax=ax, show=FALSE, title=categories[i],...) 63 | ax$set_xlim(my.xlim[1],my.xlim[2]) 64 | ax$set_ylim(my.ylim[1],my.ylim[2]) 65 | } 66 | plt$tight_layout() 67 | 68 | } 69 | 70 | } 71 | 72 | ############ annotation ########## 73 | { 74 | 75 | adata <- anndata::read_h5ad(in.file) 76 | ann.tb <- readRDS(ann.file) 77 | 78 | setkey(ann.tb,"cellID") 79 | ann.tb <- ann.tb[adata$obs_names,] 80 | print("all(adata$obs_names == ann.tb$cellID) ?") 81 | print(all(adata$obs_names == ann.tb$cellID)) 82 | adata$obs$scibetMajor <- ann.tb$scibetMajor 83 | adata$obs$scibetSub <- ann.tb$scibetSub 84 | 85 | ### 86 | { 87 | 88 | my.xlim <- pretty(adata$obsm$X_umap[,1]) 89 | my.ylim <- pretty(adata$obsm$X_umap[,2]) 90 | my.xlim <- my.xlim[c(1,length(my.xlim))] 91 | my.ylim <- my.ylim[c(1,length(my.ylim))] 92 | 93 | sp <- plt$subplots(figsize=c(4,4)) 94 | ax <- sp[[2]] 95 | sc$pl$umap(adata, color="scibetMajor",legend_loc='on data',ax=sp[[2]],legend_fontsize=10,title=opt.dataset) 96 | #ax$set_xlim(my.xlim[1],my.xlim[2]) 97 | #ax$set_ylim(my.ylim[1],my.ylim[2]) 98 | plt$tight_layout() 99 | plt$savefig(sprintf("%s.%s.%s.png",out.prefix,"umap","scibetMajor")) 100 | 101 | split_umap(adata,"scibetMajor",plot.ncol=4,color="scibetMajor",legend_loc='on data',legend_fontsize=10) 102 | plt$savefig(sprintf("%s.%s.%s.split.00.png",out.prefix,"umap","scibetMajor")) 103 | 104 | } 105 | 106 | tic("write_h5ad ...") 107 | adata$write_h5ad(sprintf("%s.scibet.h5ad",out.prefix)) 108 | toc() 109 | #adata <- anndata::read_h5ad(sprintf("%s.scibet.h5ad",out.prefix)) 110 | 111 | m.tb <- as.data.table(adata$obs) 112 | saveRDS(m.tb,file=sprintf("%s.m.tb.rds",out.prefix)) 113 | 114 | } 115 | 116 | -------------------------------------------------------------------------------- /inst/script/wrapper.vireoSNP.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import argparse 4 | import os 5 | import vireoSNP 6 | import numpy as np 7 | from scipy import sparse 8 | from scipy.io import mmread 9 | import matplotlib.pyplot as plt 10 | import pickle 11 | import pathlib 12 | 13 | parser = argparse.ArgumentParser(description='wrapper for running vireoSNP') 14 | parser.add_argument("-n",'--nClone', dest='opt_nClone', type=int, 15 | default=3, help='an integer for the accumulator') 16 | parser.add_argument("-i",'--inDir', dest='in_dir', required=True, type=pathlib.Path, 17 | help=('directory where the input data (passed_ad.mtx,' 18 | 'passed_dp.mtx) are stored.')) 19 | parser.add_argument("-o",'--outPrefix', dest='out_prefix', required=True, 20 | type=str, help=('output prefix')) 21 | 22 | args = parser.parse_args() 23 | 24 | print(vireoSNP.__version__) 25 | 26 | #print(args) 27 | 28 | opt_nClone = args.opt_nClone 29 | in_dir = args.in_dir 30 | out_prefix = args.out_prefix 31 | 32 | #opt_nClone = 2 33 | #in_dir = "./t.OUT/mquad/" 34 | #out_prefix = "./t.OUT/mquad/vireo" 35 | 36 | os.makedirs(os.path.dirname(out_prefix), exist_ok=True) 37 | 38 | AD = mmread("%s/passed_ad.mtx" % in_dir).tocsc() 39 | DP = mmread("%s/passed_dp.mtx" % in_dir).tocsc() 40 | 41 | #### model fitting 42 | from vireoSNP import BinomMixtureVB 43 | _model = BinomMixtureVB(n_var=AD.shape[0], n_cell=AD.shape[1], n_donor=opt_nClone) 44 | _model.fit(AD, DP, min_iter=30, n_init=50) 45 | print(_model.ELBO_iters[-1]) 46 | 47 | #### save result 48 | with open("%s.model.pkl" % out_prefix, 'wb') as out_file: 49 | pickle.dump(_model, out_file) 50 | 51 | #### visualization 52 | fig = plt.figure(figsize=(11, 4)) 53 | plt.subplot(1, 2, 1) 54 | plt.hist(_model.ELBO_inits) 55 | plt.ylabel("Frequency") 56 | plt.xlabel("ELBO in multiple initializations") 57 | 58 | plt.subplot(1, 2, 2) 59 | plt.plot(_model.ELBO_iters) 60 | plt.xlabel("Iterations") 61 | plt.ylabel("ELBO in a single initialization") 62 | 63 | plt.tight_layout() 64 | #plt.show() 65 | plt.savefig("%s.ELBO.00.pdf" % out_prefix) 66 | 67 | 68 | # In mitochondrial, allele frequency is highly informative between 0.01 to 0.1, 69 | # so we rescale the colour to give more spectrum for this region. 70 | # You can design/choose your own colors from here: 71 | # https://matplotlib.org/stable/tutorials/colors/colormaps.html 72 | 73 | from matplotlib import cm 74 | from matplotlib.colors import ListedColormap, LinearSegmentedColormap 75 | 76 | raw_col = cm.get_cmap('pink_r', 200) 77 | new_col = np.vstack((raw_col(np.linspace(0, 0.7, 10)), 78 | raw_col(np.linspace(0.7, 1, 90)))) 79 | segpink = ListedColormap(new_col, name='segpink') 80 | 81 | from vireoSNP.plot import heat_matrix 82 | 83 | fig = plt.figure(figsize=(6, 4), dpi=100) 84 | plt.subplot(1, 2, 1) 85 | im = heat_matrix(_model.ID_prob, cmap="Blues", alpha=0.8, 86 | display_value=False, row_sort=True) 87 | plt.colorbar(im, fraction=0.046, pad=0.04) 88 | plt.title("Assignment probability") 89 | plt.xlabel("Clone") 90 | plt.ylabel("%d cells" %(_model.n_cell)) 91 | plt.xticks(range(_model.n_donor)) 92 | 93 | plt.subplot(1, 2, 2) 94 | im = heat_matrix(_model.beta_mu, cmap=segpink, alpha=0.8, 95 | display_value=False, row_sort=True) 96 | plt.colorbar(im, fraction=0.046, pad=0.04) 97 | plt.title("Mean allelic ratio") 98 | plt.xlabel("Clone") 99 | plt.ylabel("%d SNPs" %(_model.n_var)) 100 | plt.xticks(range(_model.n_donor)) 101 | 102 | plt.tight_layout() 103 | #plt.show() 104 | plt.savefig("%s.prob.allelicRatio.00.pdf" % out_prefix) 105 | 106 | #### diagnosis 107 | ## repet 5 times, check the ELBO 108 | print("repeat model fitting 5 times, see whether the same (best) ELBO is found") 109 | n_init = 50 110 | for i in range(5): 111 | _model = BinomMixtureVB(n_var=AD.shape[0], n_cell=AD.shape[1], n_donor=opt_nClone) 112 | _model.fit(AD, DP, min_iter=30, n_init=n_init) 113 | print("rerun %d:" %i, _model.ELBO_iters[-1]) 114 | 115 | ## check whether the number of clones choosed is good 116 | print("check whether the number of clones choosed is good") 117 | n_init = 50 118 | n_clone_list = np.arange(2, 6) 119 | 120 | _ELBO_mat = [] 121 | for k in n_clone_list: 122 | _model = BinomMixtureVB(n_var=AD.shape[0], n_cell=AD.shape[1], n_donor=k) 123 | _model.fit(AD, DP, min_iter=30, n_init=n_init) 124 | _ELBO_mat.append(_model.ELBO_inits) 125 | 126 | fig = plt.figure(figsize=(6, 4)) 127 | plt.plot(np.arange(1, len(n_clone_list)+1), np.max(_ELBO_mat, axis=1)) 128 | plt.boxplot(_ELBO_mat) 129 | plt.xticks(np.arange(1, len(n_clone_list)+1), n_clone_list) 130 | plt.ylabel("ELBO") 131 | plt.xlabel("n_clones") 132 | plt.savefig("%s.ELBO.nClone.00.pdf" % out_prefix) 133 | #plt.show() 134 | 135 | ############## 136 | #mtSNP_ids = ['mt_variant%d' %x for x in range(AD.shape[0])] 137 | #cell_label = np.array(['clone1'] * 27 + ['clone2'] * 27 + ['clone3'] * 27) 138 | #id_uniq = ['clone1', 'clone2', 'clone3'] 139 | #vireoSNP.plot.anno_heat(AD/DP, col_anno=cell_label, col_order_ids=id_uniq, 140 | # cmap=segpink, yticklabels=mtSNP_ids) 141 | 142 | 143 | -------------------------------------------------------------------------------- /R/zzz.R: -------------------------------------------------------------------------------- 1 | #' special gene list 2 | #' 3 | #' @docType data 4 | #' @rdname g.geneOnUmap.list 5 | #' @name g.geneOnUmap.list 6 | #' 7 | NULL 8 | 9 | g.geneOnUmap.list <- list( 10 | "epithelial.01"=c("EPCAM", "SFN", "KRT8", "KRT10","KRT18", 11 | "KRT19","KRTCAP3","KRT15",""), 12 | "endothelial"=c("PECAM1","VWF","CDH5","PLVAP","CLDN5", 13 | "SLCO2A1","RAMP2","EGFL7","EMCN"), 14 | "CAF"=c("DCN", "COL1A2", "COL1A1", "COL3A1", "COL6A2", "COL6A1", 15 | "PCOLCE", "C1S", "LUM"), 16 | "SMC"=c("MYH11", "ACTA2", "TAGLN", "CNN1", "MYL9", 17 | "DES", "TPM2", "MYLK", "PLN"), 18 | "glia"=c("CRYAB", "CD9", "SPARC", "PMP22", "CDH19", "SEMA3B", "GPM6B", "NRXN1", "PLP1"), 19 | "B.01"=c("BLK", "CD19", "CD70", "CD79A","CD79B", 20 | "MS4A1","FCER2","SDC1","JCHAIN"), 21 | "B.02"=c("TCL1A","RGS13","IL4R","IGKC","IGHG1","CD27","CD22","EBI3","STAG3"), 22 | "Mast"=c("ENPP3", "KIT", "PTPRC", "TPSB2","SLC18A2", 23 | "FCER1A", "TPSAB1", "CPA3", "HPGDS"), 24 | "Neutrophil.01"=c("FUT4","CD3E","TLR2","CD14","CD33","FCGR1A","CSF3R","",""), 25 | "Neutrophil.02"=c("CD68","CSF3R","CXCR1","CXCR2","CXCR4","CXCL8","MMP9","VEGFA","ARG1"), 26 | "Monocyte"=c("CD14","VCAN", "S100A9","FCGR3A","FCEG1G", 27 | "LST1","ITGAM", "HLA-DQA1","PTPRC"), 28 | "DC.01"=c("LILRA4","CD1C", "CLEC9A","CLEC10A","FCER1A", 29 | "RSG2","LAMP3", "THBD", "IDO1"), 30 | "DC.02"=c("ITGAX","IRF4", "IRF8", "CD274", "LTB", 31 | "CCL19","CCL21","IL3RA","NRP1","CLE4C"), 32 | "Macrophase.01"=c("CD68","THBS1","CD163", "C1QA","APOE", 33 | "FCGR3A","MARCO", "S100A4","S100A9"), 34 | "Macrophase.02"=c("HLA-DQA1", "CST3", "LYZ", "ISGF6","FUT4", 35 | "SEPP1","IFI30","FCGR1A","GPNMB"), 36 | "Macrophase.03"=c("CTSK", "MMP9", "SIGLEC15", "LYVE1","SPP1", 37 | "FOLR2","C1QC","TREM2","LPL"), 38 | "Macrophase.04"=c("MT1G", "CCL18", "CD36", "CD52","FABP4", 39 | "C3","CXCL8","PDK4","HK2"), 40 | "Macrophase.05"=c("FCN1", "IL1B", "NLRP3", "PLTP","CCR2", 41 | "CCL2","CCL18","MMP9","SLC2A1"), 42 | "Macrophase.06"=c("GCHFR","CTSD","CTSL","CTSB", "APOE","APOC1", 43 | "CCL2","CCL18","SLC2A1"), 44 | "Macrophase.07"=c("S100A8","S100A9", "CXCL10", "CXCL11", "OLR1", 45 | "IDO1","CALHM6","FN1","SERPINA1"), 46 | "Macrophase.08"=c("CD14","FCGR3A", "CX3CR1", "MT1G", "CCL2", 47 | "SLC2A1","FABP4","FOLR2","LYVE1"), 48 | "Macrophase.09"=c("FCN1","IL1B","GPNMB","C1QC","SPP1","TREM2","LYZ","CSF1R","CD163"), 49 | ##"Granulocyte"=c("CEACAM1","CEACAM6","CEACAM3","ENPP3","CD3E","","","",""), 50 | "NK"=c("FCGR3A", "NCR1","NCAM1","CD3E", "NKG7", 51 | "KLRD1","KIR2DL3","KIR2DL4","KLRB1"), 52 | #"ILC"=c("IL4I1","KIT","KRT86","KRT81","ZFP36L1", "IL23R","CD83","NR4A1","EEF1A1"), 53 | "T.01"=c("CD4", "CD8A", "CD8B", "CD2", "CD3D", 54 | "CD3G", "NKG7", "GNLY", "FGFBP2"), 55 | "T.02"=c("CX3CR1", "GZMK", "ZNF683","CD40LG","FOXP3", 56 | "TNFRSF9","IL7R","IL2RA","TYROBP"), 57 | "T.03"=c("TRGC1","TRGC2","TRBC1","TRBC2","TRDC", 58 | "TRAC","TRGV9","TRDV2","TRAV1-2"), 59 | "T.04"=c("CCR7","GZMK","LAYN","HAVCR2","CXCL13", 60 | "CX3CR1","ZNF683","SLC4A10","CD160"), 61 | "T.05"=c("IL17A","RORC","IL23R","CCR6","BCL6", 62 | "CXCR5", "CXCR6","XCL1","XCL2"), 63 | "T.06"=c("TCF7","MAL","CCL5","CCL4","CCL4L2", 64 | "GZMA","GPR183","EOMES","KLRG1"), 65 | "T.07"=c("PDCD1","CTLA4","IFNG","TNF","GZMB", 66 | "RGS1","S1PR1","ITGAE","MALAT1"), 67 | "cellCycle"=c("TYMSOS","PCLAF","TYMS","ZWINT","MCM2", 68 | "MIR3917","UHRF1","TK1","MKI67"), 69 | "ISG"=c("ISG15","ISG20","IFIT1","IFIT2", 70 | "IRF7", "OAS1","OAS2","STAT1"), 71 | "DIG"=c("DNAJB1","DUSP1","FOS","JUN","HSP90AA1", 72 | "HSP90AB1","HSPA1A","HSPA6") 73 | ) 74 | 75 | 76 | .onLoad <- function(libname , pkgname) { 77 | if(getRversion() >= "2.15.1"){ 78 | utils::globalVariables(c(".",".N",".SD","variable","value","Group","x", 79 | "Dim1","Dim2", 80 | "vst.variance","vst.variance.standardized", 81 | "geneID","aid", 82 | "median.F.rank","hasSpeGene","fDataSets","medianRankSpeGene", 83 | "logFC","sig","comb.padj","comb.ES","sig.cate","meta.cluster", 84 | "freq.sig","geneSet.TF", 85 | "dataset", 86 | "dprime","vardprime","P.Value","adj.P.Val")) 87 | } 88 | } 89 | 90 | 91 | 92 | 93 | -------------------------------------------------------------------------------- /inst/script/wrapper.run.inte.R: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env Rscript 2 | 3 | suppressPackageStartupMessages(library("argparse")) 4 | suppressPackageStartupMessages(library("scPip")) 5 | suppressPackageStartupMessages(library("data.table")) 6 | suppressPackageStartupMessages(library("tictoc")) 7 | 8 | parser <- ArgumentParser() 9 | parser$add_argument("-i", "--inFile", type="character", required=TRUE, help="input files list") 10 | parser$add_argument("-o", "--outPrefix", type="character", required=TRUE, help="outPrefix") 11 | parser$add_argument("-a", "--geneFile", type="character", help="gene file, used as informative genes. If not specified, select from data automatically.") 12 | parser$add_argument("-n", "--ncores", type="integer", default=12, help="number of CPUs to use [default %(default)s]") 13 | parser$add_argument("-c", "--occ", type="double", default=0.85, help="genes detected in >= OCC datasets will be kept [default %(default)s]") 14 | parser$add_argument("-j", "--corVar", type="character", default="S.Score,G2M.Score,DIG.Score1", 15 | help="subset of S.Score,G2M.Score,DIG.Score1,ISG.Score1,score.MALAT1 [default %(default)s]") 16 | parser$add_argument("-f", "--excludeCells", type="character", 17 | help="vector containing cells to be excluded, stored in a .rds file ") 18 | ##parser$add_argument("-d", "--npc", type="integer",default=15L, help="[default %(default)s]") 19 | args <- parser$parse_args() 20 | cat(sprintf("############# arguments #############\n")) 21 | print(args) 22 | cat(sprintf("#####################################\n")) 23 | 24 | exp.list.file <- args$inFile 25 | out.prefix <- args$outPrefix 26 | #gene.file <- args$geneFile 27 | opt.cor.var <- unlist(strsplit(args$corVar,",",perl=T)) 28 | opt.excludeCells.file <- args$excludeCells 29 | opt.ncores <- args$ncores 30 | opt.occ <- args$occ 31 | opt.geneFile <- args$geneFile 32 | 33 | dir.create(dirname(out.prefix),F,T) 34 | saveRDS(args,file=sprintf("%s.args.rds",out.prefix)) 35 | ##args <- readRDS(sprintf("%s.args.rds",out.prefix)) 36 | 37 | #### 38 | #exp.list.file <- "list/obj.T.list.r1.list" 39 | #out.prefix <- "./OUT.int.S3.T.2nd/int.S3.T" 40 | dir.create(dirname(out.prefix),F,T) 41 | 42 | ###opt.cor.var <- c("S.Score","G2M.Score", "DIG.Score1") 43 | 44 | dat.ext.dir <- system.file("extdata",package="scPip") 45 | script.dir <- system.file("script",package="scPip") 46 | report.template.file <- sprintf("%s/rna/report.template.sc.rmd",script.dir) 47 | 48 | ncores <- opt.ncores 49 | ####gene.exclude.file <- sprintf("%s/exclude.gene.misc.human.v3.RData",dat.ext.dir) 50 | ### after 20220119 51 | gene.exclude.file <- sprintf("%s/exclude.gene.misc.human.v4.RData",dat.ext.dir) 52 | 53 | options(stringsAsFactors = FALSE) 54 | 55 | #env.misc <- loadToEnv(gene.exclude.file) 56 | 57 | #### data.id measurement platform defile scefile seufile 58 | exp.list.table <- fread(cmd=sprintf("awk '!/^#/' %s",exp.list.file)) 59 | 60 | RhpcBLASctl::omp_set_num_threads(1) 61 | doParallel::registerDoParallel(cores = ncores) 62 | 63 | contamination.vec <- NULL 64 | if(!is.null(opt.excludeCells.file) && file.exists(opt.excludeCells.file)){ 65 | contamination.vec <- readRDS(opt.excludeCells.file) 66 | } 67 | 68 | tic("run.inte.metaClust") 69 | ret.list <- run.inte.metaClust(exp.list.table, out.prefix, gene.exclude.file, 70 | #cor.cellCycle=T,cor.MALAT1=F,cor.DIG=T,cor.ISG=T, 71 | cor.var=opt.cor.var, 72 | contamination.vec=contamination.vec, 73 | gene.informative.file=opt.geneFile, 74 | ncores=opt.ncores,npc=15,res.hi=50,TH.gene.occ=opt.occ) 75 | toc() 76 | 77 | seu.merged <- ret.list[["seu.merged"]] 78 | sce.merged <- ret.list[["sce.merged"]] 79 | meta.tb <- ret.list[["meta.tb"]] 80 | 81 | #seu.merged <- readRDS(file=sprintf("%s.seu.merged.rds",out.prefix)) 82 | #sce.merged <- readRDS(file=sprintf("%s.sce.merged.rds",out.prefix)) 83 | #meta.tb <- readRDS(file=sprintf("%s.meta.tb.rds",out.prefix)) 84 | 85 | if(F){ 86 | tic("render_KnitReport ..") 87 | render_KnitReport(report.template.file,out.file=sprintf("%s.report.html",out.prefix), 88 | par.list=list("out.prefix"=sprintf("%s/plot.harmony.umap/%s",dirname(out.prefix),basename(out.prefix)), 89 | "meta.tb.file"=sprintf("%s.meta.tb.rds",out.prefix), 90 | "sce.file"=sprintf("%s.sce.merged.rds",out.prefix), 91 | "plot.rd"="harmony.umap", 92 | "plot.GeneOnUmap.list"=g.geneOnUmap.list)) 93 | toc() 94 | 95 | } 96 | 97 | #dataOnRDPlot(seu.merged,sce.merged, 98 | # sprintf("%s/%s/%s",dirname(out.prefix),"umap.algorithm1",basename(out.prefix)), 99 | # rd="umap",graph.name="RNA_pca_snn") 100 | scPip:::dataOnRDPlot(seu.merged,sce.merged, 101 | sprintf("%s/%s/%s",dirname(out.prefix),"harmony.umap.algorithm1",basename(out.prefix)), 102 | rd="harmony.umap") 103 | #dataOnRDPlot(seu.merged,sce.merged, 104 | # sprintf("%s/%s/%s",dirname(out.prefix),"tsne.Rtsne.algorithm1",basename(out.prefix)), 105 | # rd="tsne.Rtsne",graph.name="RNA_pca_snn") 106 | #dataOnRDPlot(seu.merged,sce.merged, 107 | # sprintf("%s/%s/%s",dirname(out.prefix),"harmony.tsne.Rtsne.algorithm1",basename(out.prefix)), 108 | # rd="harmony.tsne.Rtsne") 109 | 110 | 111 | 112 | -------------------------------------------------------------------------------- /inst/script/report.template.sc.rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Visualization of Clustering Result" 3 | output: 4 | BiocStyle::html_document: 5 | df_print: paged 6 | toc_float: true 7 | params: 8 | date: !r Sys.Date() 9 | printcode: TRUE 10 | out.prefix: "./OUT.plot/sc" 11 | meta.tb.file: NULL 12 | sce.file: NULL 13 | seu.file: NULL 14 | plot.rd: "harmony.umap" 15 | plot.GeneOnUmap.list: NULL 16 | --- 17 | 18 | ```{r, setup, include=FALSE} 19 | knitr::opts_chunk$set( 20 | fig.retina=1,fig.path=params$out.prefix, 21 | dev=c("CairoPNG"),dpi=300, 22 | echo = params$printcode 23 | ) 24 | ``` 25 | 26 | ```{r message=FALSE,warning=FALSE} 27 | library("sscVis") 28 | library("magrittr") 29 | library("data.table") 30 | library("ggpubr") 31 | library("ggplot2") 32 | library("ggrastr") 33 | library("ggrepel") 34 | library("RColorBrewer") 35 | library("grid") 36 | library("cowplot") 37 | library("plyr") 38 | library("kableExtra") 39 | 40 | meta.tb.file <- params$meta.tb.file 41 | sce.file <- params$sce.file 42 | plot.rd <- params$plot.rd 43 | plot.GeneOnUmap.list <- params$plot.GeneOnUmap.list 44 | 45 | out.prefix <- params$out.prefix 46 | dir.create(dirname(out.prefix),F,T) 47 | 48 | ``` 49 | # load data 50 | 51 | ## load the meta data 52 | ```{r loadMetaData} 53 | meta.tb <- NULL 54 | if(!is.null(meta.tb.file)){ meta.tb <- readRDS(meta.tb.file) } 55 | head(meta.tb) %>% kbl(caption = "Meta Info") %>% 56 | kable_classic(full_width = F, html_font = "Cambria") 57 | ``` 58 | ## load the gene expression data 59 | ```{r loadExpData} 60 | sce <- NULL 61 | if(!is.null(sce.file)){ sce <- readRDS(sce.file) } 62 | print(sce) 63 | ``` 64 | 65 | # UMAP plots 66 | 67 | ## datasets 68 | 69 | colored by datasets 70 | ```{r .umap.datasets,fig.width=6,fig.height=4} 71 | p <- ssc.plot.tsne(sce, columns = "dataset", 72 | reduced.name = plot.rd, 73 | colSet=list(),size=0.1,label=3, 74 | #vector.friendly=T, 75 | #par.geom_point = list(scale=1), 76 | par.geneOnTSNE=list(scales="free",pt.order="random",pt.alpha=0.8), 77 | base_aspect_ratio = 1.15) 78 | print(p) 79 | ``` 80 | 81 | colored and splitted by datasets 82 | ```{r .umap.datasets.split,fig.width=12,fig.height=4} 83 | p <- ssc.plot.tsne(sce, columns = "dataset", 84 | splitBy="dataset", 85 | reduced.name = plot.rd, 86 | colSet=list(),size=0.1,label=3, 87 | #vector.friendly=T, 88 | #par.geom_point = list(scale=1), 89 | par.geneOnTSNE=list(scales="free",pt.order="random",pt.alpha=0.8), 90 | base_aspect_ratio = 1.15) 91 | print(p) 92 | ``` 93 | 94 | ## resolutions 95 | ```{r .umap.resolution,fig.width=9,fig.height=5.5} 96 | resolution.vec <- grep("^RNA_snn_res",colnames(colData(sce)),perl=T,value=T) 97 | plot.resolution.list <- list() 98 | for(t.res in resolution.vec){ 99 | ##cate.res <- sprintf("%s_res.%s",graph.name,t.res) 100 | cate.res <- t.res 101 | plot.resolution.list[[cate.res]] <- ssc.plot.tsne(sce,columns = cate.res, 102 | reduced.name = plot.rd, 103 | colSet=list(),size=0.1,label=2, base_aspect_ratio = 1.2) 104 | } 105 | for(i in seq_len(length(plot.resolution.list)/4)) 106 | { 107 | pp <- plot_grid(plotlist=plot.resolution.list[((i-1)*4+1):(i*4)], 108 | ncol = 2,align = "hv") 109 | print(pp) 110 | } 111 | 112 | ``` 113 | 114 | ## genes 115 | ```{r} 116 | makeGeneOnTSNEPlot <- function(sce,rd,out.prefix, 117 | geneOnUmap.list=g.GeneOnUmap.list, 118 | plot.ncol=NULL,plot.nrow=NULL,plot.type="png", 119 | plot.width=NULL,plot.height=NULL,do.parallel=T,...) 120 | { 121 | if(!is.null(out.prefix)){ dir.create(dirname(out.prefix),F,T) } 122 | ## gene on umap 123 | l_ply(seq_along(geneOnUmap.list),function(i){ 124 | gene.tmp <- intersect(geneOnUmap.list[[i]],rowData(sce)$display.name) 125 | if(is.null(plot.ncol)){ 126 | plot.ncol <- if(length(gene.tmp)>3) floor(sqrt(length(gene.tmp))+0.5) else 3 127 | } 128 | if(is.null(plot.nrow)){ 129 | plot.nrow <- ceiling(length(gene.tmp)/plot.ncol) 130 | } 131 | if(is.null(plot.width)){ 132 | plot.width <- if(plot.ncol > 3) 14 else if(plot.ncol>2) 10 else if(plot.ncol>1) 7 else 3.5 133 | } 134 | if(is.null(plot.height)){ 135 | plot.height <- if(plot.nrow>3) 11 else if(plot.nrow>2) 8 else if(plot.nrow>1) 5.4 else 2.7 136 | } 137 | if(length(gene.tmp)>0){ 138 | p <- ssc.plot.tsne(sce,assay.name="exprs",adjB=NULL, 139 | gene=gene.tmp,clamp=c(-0.5,1.5), 140 | ##gene=gene.tmp,clamp=c(-0.5,0.5),par.legend=list(breaks=c(-0.5,-0.25,0,0.25,0.5)), 141 | p.ncol=plot.ncol, 142 | ##par.geneOnTSNE=list(scales="free",pt.order="random",pt.alpha = 0.5), 143 | par.geneOnTSNE=list(scales="fixed",pt.order="random",pt.alpha = 0.5), 144 | reduced.name=sprintf("%s",rd),...) 145 | if(!is.null(out.prefix)){ 146 | ggsave(sprintf("%s.%s.marker.%s.%s", out.prefix,rd, 147 | names(geneOnUmap.list)[i],plot.type), 148 | width=plot.width, height=plot.height) 149 | }else{ 150 | print(p) 151 | } 152 | } 153 | },.parallel=do.parallel) 154 | } 155 | 156 | ``` 157 | 158 | ```{r .umap.gene,fig.width=10,fig.height=8} 159 | #print(str(plot.GeneOnUmap.list)) 160 | makeGeneOnTSNEPlot(sce,rd=plot.rd,out.prefix=NULL, 161 | geneOnUmap.list=plot.GeneOnUmap.list, 162 | do.parallel=F) 163 | 164 | ``` 165 | -------------------------------------------------------------------------------- /inst/script/wrapper.run.limma.R: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env Rscript 2 | 3 | suppressPackageStartupMessages(library("argparse")) 4 | 5 | parser <- ArgumentParser() 6 | parser$add_argument("-b", "--bFile", type="character", required=TRUE, help="input sce file list") 7 | parser$add_argument("-o", "--outPrefix", type="character", required=TRUE, help="outPrefix") 8 | parser$add_argument("-p", "--platform",type="character",required=TRUE,help="platform such as 10X, SmartSeq2") 9 | parser$add_argument("-n", "--ncores", type="integer",default=16L, help="[default %(default)s]") 10 | parser$add_argument("-m", "--measurement",type="character",default="counts",help="[default %(default)s]") 11 | parser$add_argument("-w", "--ncellDEG",type="integer",default=1500, 12 | help="number of cells to downsample to for each group. used in DEG analysis. [default %(default)s]") 13 | parser$add_argument("-c", "--stype", type="character", help="only analyze stype specified (default all)") 14 | parser$add_argument("-a", "--group", type="character",default="ClusterID", help="group var (default ClusterID)") 15 | parser$add_argument("-l", "--groupList", type="character",default=NULL, help="DEG of groups to calculate. If NULL, all groups (default NULL)") 16 | parser$add_argument("-d", "--groupMode", type="character",default="multi", help="group mode (default multi)") 17 | parser$add_argument("-t", "--batch", type="character",default="batchV", help="column of colData(sce), used as batch (default %(default)s)") 18 | parser$add_argument("-q", "--filter", type="character",help="comma(,) seperated group list (default: don't apply filter)") 19 | parser$add_argument("-k", "--keep", type="character",help="format COLUMN:KEEP_VAL1,KEEP_VAL2,... (default: don't apply keeper)") 20 | parser$add_argument("-r", "--TExp", type="double",default=0.3,help="threshold of expressor (default: 0.3)") 21 | parser$add_argument("-y", "--NotUseZ", action="store_false",dest="TUseZ",help="do not use the z-score version of the data to identify expressor") 22 | args <- parser$parse_args() 23 | print(args) 24 | 25 | 26 | ############## tune parametrs ######## 27 | #sce.file <- "T.CD8.CRC.zhangLabSS2.sce.rds" 28 | #out.prefix <- "OUT.test/TEST" 29 | #opt.ncores <- 12 30 | #opt.measurement <- "counts" 31 | #opt.stype <- "all" 32 | #opt.platform <- "SmartSeq2" 33 | 34 | ###seu.file <- args$aFile 35 | sce.file <- args$bFile 36 | out.prefix <- args$outPrefix 37 | opt.ncores <- args$ncores 38 | opt.measurement <- args$measurement 39 | opt.ncellDEG <- args$ncellDEG 40 | opt.stype <- args$stype 41 | opt.platform <- args$platform 42 | opt.group <- args$group 43 | opt.groupList <- args$groupList 44 | opt.mode <- args$groupMode 45 | opt.batch <- args$batch 46 | opt.filter <- args$filter 47 | opt.keep <- args$keep 48 | opt.TUseZ <- args$TUseZ 49 | opt.TExp <- args$TExp 50 | 51 | if(!is.null(opt.groupList)){ 52 | opt.groupList <- unlist(strsplit(opt.groupList,",",perl=T)) 53 | } 54 | 55 | dir.create(dirname(out.prefix),F,T) 56 | 57 | ############## tune parametrs ######## 58 | library("sscClust") 59 | library("Seurat") 60 | library("tictoc") 61 | library("plyr") 62 | library("dplyr") 63 | library("tibble") 64 | library("doParallel") 65 | library("sscClust") 66 | library("Matrix") 67 | library("data.table") 68 | library("R.utils") 69 | library("gplots") 70 | library("ggplot2") 71 | library("ggpubr") 72 | library("cowplot") 73 | library("limma") 74 | library("reticulate") 75 | 76 | #RhpcBLASctl::omp_set_num_threads(1) 77 | #doParallel::registerDoParallel(cores = opt.ncores) 78 | options(stringsAsFactors = FALSE) 79 | 80 | ###################### 81 | if(grepl(".h5ad$",sce.file)){ 82 | ### use systemic path of python 83 | sce <- zellkonverter:::.H5ADreader(sce.file) 84 | ### use ~/.cache/R/basilisk/1.4.0/zellkonverter/... 85 | #sce <- zellkonverter::readH5AD(sce.file) 86 | assay(sce,"norm_exprs") <- assay(sce,"X") 87 | rowData(sce)$display.name <- rownames(sce) 88 | }else if(grepl("\\.rds$",sce.file)){ 89 | ##seu <- readRDS(seu.file) 90 | sce <- readRDS(sce.file) 91 | }else{ 92 | ##env.a <- loadToEnv(seu.file) 93 | ##obj.name.a <- names(env.a)[1] 94 | ##seu <- env.a[[obj.name.a]] 95 | ##rm(env.a) 96 | env.b <- loadToEnv(sce.file) 97 | obj.name.b <- names(env.b)[1] 98 | sce <- env.b[[obj.name.b]] 99 | rm(env.b) 100 | } 101 | 102 | if(!is.null(opt.stype)){ 103 | sce <- sce[,sce$stype==opt.stype] 104 | } 105 | 106 | if(!is.null(opt.filter)){ 107 | filter.group <- unlist(strsplit(opt.filter,",",perl=T)) 108 | cat(sprintf("filter groups belong to one of:\n")) 109 | print(filter.group) 110 | sce <- sce[,!(sce[[opt.group]] %in% filter.group)] 111 | #group.levels <- setdiff(levels(sce[[opt.group]]),filter.group) 112 | #sce[[opt.group]] <- factor(as.character(sce[[opt.group]]),levels=group.levels) 113 | } 114 | 115 | if(!is.null(opt.keep)){ 116 | opt.keep.vec <- unlist(strsplit(opt.keep,":",perl=T)) 117 | keep.col <- opt.keep.vec[1] 118 | keep.val <- opt.keep.vec[2] 119 | keep.val.vec <- unlist(strsplit(keep.val,",",perl=T)) 120 | cat(sprintf("keep %s belong to one of:\n",keep.col)) 121 | print(keep.val.vec) 122 | sce <- sce[,(sce[[keep.col]] %in% keep.val.vec)] 123 | #group.levels <- setdiff(levels(sce[[opt.group]]),filter.group) 124 | #sce[[opt.group]] <- factor(as.character(sce[[opt.group]]),levels=group.levels) 125 | } 126 | 127 | 128 | 129 | tic("run limma") 130 | 131 | if(!("norm_exprs" %in% assayNames(sce))) 132 | { 133 | assay(sce,"norm_exprs") <- assay(sce,"log2TPM") 134 | } 135 | assay.name <- "norm_exprs" 136 | 137 | #if(opt.measurement=="TPM"){ 138 | # #### TPM 139 | # assay.name <- "log2TPM" 140 | #}else{ 141 | # #### counts, cpm 142 | # assay.name <- "norm_exprs" 143 | #} 144 | 145 | if("meta.cluster" %in% colnames(colData(sce)) ) 146 | { 147 | m <- regexec("^CD[48]",sce$meta.cluster,perl=T) 148 | sce$stype <- sapply(regmatches(sce$meta.cluster,m),function(x){ x[1] }) 149 | print(table(sce$stype)) 150 | } 151 | 152 | n.group <- unclass(table(sce[[opt.group]])) 153 | print(n.group) 154 | n.group.flt <- n.group[n.group>=2] 155 | print(n.group.flt) 156 | 157 | sce <- sce[,sce[[opt.group]] %in% names(n.group.flt)] 158 | sce[[opt.group]] <- make.names(sce[[opt.group]]) 159 | 160 | nBatch <- length(table(colData(sce)[[opt.batch]])) 161 | 162 | set.seed(9998) 163 | tic("limma") 164 | de.out <- ssc.DEGene.limma(sce,assay.name=assay.name, 165 | ####ncell.downsample=if(opt.mode=="multi") 1500 else 25000, 166 | #ncell.downsample=if(opt.mode=="multi") 1500 else NULL, 167 | ncell.downsample=opt.ncellDEG, 168 | ####ncell.downsample=if(opt.mode=="multi") 1500 else 100, 169 | group.var=opt.group,batch=if(nBatch>1 && opt.batch!="NULL") opt.batch else NULL, 170 | group.list=opt.groupList, 171 | verbose=3, 172 | group.mode=opt.mode, 173 | out.prefix=out.prefix,n.cores=opt.ncores, 174 | #T.expr=0.3,T.bin.useZ=T, 175 | T.expr=opt.TExp,T.bin.useZ=opt.TUseZ, 176 | T.logFC=if(opt.platform=="SmartSeq2") 1 else 0.25) 177 | 178 | saveRDS(de.out,file=sprintf("%s.de.out.rda",out.prefix)) 179 | toc() 180 | 181 | 182 | -------------------------------------------------------------------------------- /inst/script/run.copykat.R: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env Rscript 2 | 3 | suppressPackageStartupMessages(library("argparse")) 4 | 5 | parser <- ArgumentParser() 6 | parser$add_argument("-o", "--outPrefix", type="character", required=TRUE, help="outPrefix") 7 | parser$add_argument("-e", "--expFile", type="character", required=TRUE, help="input /sce/seu file") 8 | parser$add_argument("-a", "--aid", type="character", default="SAMPLE_X", help="aid") 9 | parser$add_argument("-n", "--ncores", type="integer",default=8L, help="[default %(default)s]") 10 | parser$add_argument("-k", "--keep",type="character",help="Format is COLUMN_ID:COLUMN_VAL_1,COLUMN_VAL_2,COLUMN_VAL_3. Keep only cells with COLUMN_ID in one of COLUMN_VAL_1, COLUMN_VAL_2, and COLUMN_VAL_3.") 11 | parser$add_argument("-d", "--distance", type="character", default="euclidean", help="euclidean, pearson, or spearman [default %(default)s]") 12 | args <- parser$parse_args() 13 | print(args) 14 | 15 | ######## 16 | 17 | out.prefix <- args$outPrefix 18 | exp.file <- args$expFile 19 | opt.keep <- args$keep 20 | opt.ncores <- args$ncores 21 | opt.aid <- args$aid 22 | opt.distance <- args$distance 23 | 24 | #out.prefix <- "./OUT.test/test.P032" 25 | #exp.file <- "OUT.exp/ESCA.A20220210.seu.doubletFlt.all.rds" 26 | #opt.keep <- "patient:P032" 27 | #opt.ncores <- 4 28 | #opt.aid <- "P032" 29 | #opt.distance <- "euclidean" 30 | 31 | dir.create(dirname(out.prefix),F,T) 32 | 33 | library("Seurat") 34 | library("copykat") 35 | library("tictoc") 36 | library("sscVis") 37 | 38 | obj.exp <- NULL 39 | 40 | tic("readRDS(exp.file)") 41 | obj.exp <- readRDS(exp.file) 42 | toc() 43 | 44 | if(!(class(obj.exp) %in% c("SingleCellExperiment","Seurat"))){ 45 | cat(sprintf("Not supported file type: %s\n",exp.file)) 46 | q() 47 | } 48 | 49 | #### 50 | if(!is.null(obj.exp) && !is.null(opt.keep)){ 51 | if(!file.exists(opt.keep)){ 52 | col.keep <- unlist(strsplit(opt.keep,":"))[1] 53 | col.value <- unlist(strsplit(unlist(strsplit(opt.keep,":"))[2],",")) 54 | if(class(obj.exp)=="Seurat"){ 55 | if(col.keep %in% colnames(obj.exp[[]])){ 56 | cat(sprintf("keep only cells with %s in c(%s)\n",col.keep,paste(col.value,collapse=","))) 57 | f.cell <- obj.exp[[]][,col.keep] %in% col.value 58 | print(summary(f.cell)) 59 | obj.exp <- obj.exp[,f.cell] 60 | }else{ 61 | warning(sprintf("The meta-data doesnot contain %s\n",col.keep)) 62 | } 63 | }else if(class(obj.exp)=="SingleCellExperiment"){ 64 | if(col.keep %in% colnames(colData(obj.exp))){ 65 | cat(sprintf("keep only cells with %s in c(%s)\n",col.keep,paste(col.value,collapse=","))) 66 | f.cell <- obj.exp[[col.keep]] %in% col.value 67 | print(summary(f.cell)) 68 | obj.exp <- obj.exp[,f.cell] 69 | }else{ 70 | warning(sprintf("The meta-data doesnot contain %s\n",col.keep)) 71 | } 72 | } 73 | } 74 | } 75 | 76 | { 77 | 78 | if(class(obj.exp)=="Seurat"){ 79 | exp.rawdata <- as.matrix(obj.exp@assays$RNA@counts) 80 | }else if(class(obj.exp)=="SingleCellExperiment"){ 81 | exp.rawdata <- assay(obj.exp,"counts") 82 | } 83 | 84 | cDir <- getwd() 85 | setwd(dirname(out.prefix)) 86 | 87 | tic("copykat") 88 | copykat.test <- copykat(rawmat=exp.rawdata, id.type="S", 89 | sam.name=opt.aid, 90 | distance=opt.distance, 91 | n.cores=opt.ncores, 92 | output.seg="FLASE") 93 | toc() 94 | 95 | setwd(cDir) 96 | 97 | saveRDS(copykat.test,file=sprintf("%s.copykat.rds",out.prefix)) 98 | 99 | } 100 | 101 | ############# 102 | #copykat.test <- readRDS(sprintf("%s.copykat.rds",out.prefix)) 103 | 104 | pred.test <- data.frame(copykat.test$prediction) 105 | CNA.test <- data.frame(copykat.test$CNAmat) 106 | 107 | ##### heatmap plot 01 108 | { 109 | 110 | #### my_palette <- colorRampPalette(rev(RColorBrewer::brewer.pal(n = 3, name = "RdBu")))(n = 999) 111 | #### 112 | #### chr <- as.numeric(CNA.test$chrom) %% 2+1 113 | #### rbPal1 <- colorRampPalette(c('black','grey')) 114 | #### CHR <- rbPal1(2)[as.numeric(chr)] 115 | #### chr1 <- cbind(CHR,CHR) 116 | #### 117 | #### rbPal5 <- colorRampPalette(RColorBrewer::brewer.pal(n = 8, name = "Dark2")[2:1]) 118 | #### com.preN <- pred.test$copykat.pred 119 | #### pred <- rbPal5(2)[as.numeric(factor(com.preN))] 120 | #### 121 | #### cells <- rbind(pred,pred) 122 | #### col_breaks = c(seq(-1,-0.4,length=50), 123 | #### seq(-0.4,-0.2,length=150), 124 | #### seq(-0.2,0.2,length=600), 125 | #### seq(0.2,0.4,length=150), 126 | #### seq(0.4, 1,length=50)) 127 | #### 128 | #### png(sprintf("%s.heatmap.01.png",out.prefix),width=800,height=700) 129 | #### heatmap.3(t(CNA.test[,4:ncol(CNA.test)]), 130 | #### dendrogram="r", 131 | #### distfun = function(x) parallelDist::parDist(x,threads = opt.ncores, method = "euclidean"), 132 | #### hclustfun = function(x) hclust(x, method="ward.D2"), 133 | #### ColSideColors=chr1,RowSideColors=cells,Colv=NA, Rowv=TRUE, 134 | #### notecol="black",col=my_palette,breaks=col_breaks, key=TRUE, 135 | #### keysize=1, density.info="none", trace="none", 136 | #### cexRow=0.1,cexCol=0.1,cex.main=1,cex.lab=0.1, 137 | #### symm=F,symkey=F,symbreaks=T,cex=1, cex.main=4, margins=c(10,10)) 138 | #### 139 | #### legend("topright", 140 | #### paste("pred.",names(table(com.preN)),sep=""), 141 | #### pch=15, 142 | #### col=RColorBrewer::brewer.pal(n = 8, name = "Dark2")[2:1], 143 | #### cex=0.6, bty="n") 144 | #### dev.off() 145 | 146 | } 147 | 148 | ##### heatmap plot 02 149 | { 150 | 151 | my_palette <- colorRampPalette(rev(RColorBrewer::brewer.pal(n = 3, name = "RdBu")))(n = 999) 152 | 153 | chr <- as.numeric(CNA.test$chrom) %% 2+1 154 | rbPal1 <- colorRampPalette(c('black','grey')) 155 | CHR <- rbPal1(2)[as.numeric(chr)] 156 | chr1 <- cbind(CHR,CHR) 157 | 158 | tumor.cells <- pred.test$cell.names[which(pred.test$copykat.pred=="aneuploid")] 159 | tumor.mat <- CNA.test[, which(colnames(CNA.test) %in% make.names(tumor.cells))] 160 | hcc <- hclust(parallelDist::parDist(t(tumor.mat),threads = opt.ncores, method = "euclidean"), method = "ward.D2") 161 | hc.umap <- cutree(hcc,2) 162 | 163 | rbPal6 <- colorRampPalette(RColorBrewer::brewer.pal(n = 8, name = "Dark2")[3:4]) 164 | subpop <- rbPal6(2)[as.numeric(factor(hc.umap))] 165 | cells <- rbind(subpop,subpop) 166 | 167 | col_breaks = c(seq(-1,-0.4,length=50), 168 | seq(-0.4,-0.2,length=150), 169 | seq(-0.2,0.2,length=600), 170 | seq(0.2,0.4,length=150), 171 | seq(0.4, 1,length=50)) 172 | 173 | png(sprintf("%s.heatmap.02.png",out.prefix),width=800,height=700) 174 | heatmap.3(t(tumor.mat), 175 | dendrogram="r", 176 | distfun = function(x) parallelDist::parDist(x,threads =4, method = "euclidean"), 177 | hclustfun = function(x) hclust(x, method="ward.D2"), 178 | ColSideColors=chr1,RowSideColors=cells,Colv=NA, Rowv=TRUE, 179 | notecol="black",col=my_palette,breaks=col_breaks, key=TRUE, 180 | keysize=1, density.info="none", trace="none", 181 | cexRow=0.1,cexCol=0.1,cex.main=1,cex.lab=0.1, 182 | symm=F,symkey=F,symbreaks=T,cex=1, cex.main=4, margins=c(10,10)) 183 | 184 | legend("topright", 185 | c("c1","c2"), 186 | pch=15, 187 | col=RColorBrewer::brewer.pal(n = 8, name = "Dark2")[3:4], 188 | cex=0.9, bty='n') 189 | dev.off() 190 | 191 | } 192 | 193 | 194 | 195 | -------------------------------------------------------------------------------- /inst/script/example/w.run.M.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | g_prj_id="BRCA" 4 | 5 | cDir=`pwd` 6 | ### columns required in $file_obj_in: aid measurement platform seufile scefile resolution 7 | ### columns required in seurat or sce object: "patient" 8 | file_obj_in="$cDir/list/obj.M.list" 9 | file_int_in="$cDir/list/obj.M.list.r1.list" 10 | file_limma_in="$cDir/list/obj.M.list.forLimma.list" 11 | file_limma_out="$cDir/list/obj.M.list.limma.sc.list" 12 | cellType="M" 13 | oDir="$cDir/OUT.byDataset" 14 | shDir="./sh.byDataset.$cellType" 15 | mkdir -p $shDir 16 | 17 | sDir=`R --slave -e 'sDir <- system.file("script",package="scPipI"); cat(sDir)'` 18 | echo $sDir 19 | 20 | ######### 1.1 generate scripts to run Seurat for each dataset 21 | ###--removeContamination plasmaB:0.75,caf:0.75,epi:0.75,T:0.25,cd8:0.25 \\ 22 | while read aid measurement platform seufile scefile resolution 23 | do 24 | ( 25 | cat <<-HERE 26 | #!/bin/bash 27 | #SBATCH -p all 28 | #SBATCH -N 1 29 | #SBATCH --ntasks-per-node=12 30 | #SBATCH -o S.$cellType.$aid.%j.out 31 | #SBATCH -e S.$cellType.$aid.%j.err 32 | #SBATCH --no-requeue 33 | echo begin at: \`date\` host: \`hostname\` 34 | $sDir/run.seurat3.basic.R \\ 35 | -a $seufile \\ 36 | -b $scefile \\ 37 | -o $oDir/$cellType/$cellType.$aid/$cellType.$aid \\ 38 | -d 15 \\ 39 | -n 12 \\ 40 | --keep globalC:Myeloid,Mono/Macro,cDC \\ 41 | --removeContamination plasmaB:0.75,caf:0.75,epi:0.75,T:0,cd8:0 \\ 42 | --deg \\ 43 | --resolution $resolution \\ 44 | -m $measurement \\ 45 | --platform $platform 46 | HERE 47 | )>$shDir/byDataset.$cellType.$aid.sh 48 | done< <(awk 'NR>1' $file_obj_in) 49 | 50 | ########## 1.2 submit jobs to run the scripts ######## 51 | #cd $shDir 52 | #ls *.sh | awk '{print "sbatch "$0}' | bash 53 | #cd $cDir 54 | ################################################## 55 | 56 | ######## 2.1 prepare file list for integration ############ 57 | sed '1,1d' $file_obj_in \ 58 | | perl -ane 'BEGIN{ print "data.id\tmeasurement\tplatform\tdefile\tscefile\tseufile\n" } 59 | chomp; print join("\t",@F[0..2], 60 | "'$oDir'/'$cellType'/'$cellType'.$F[0]/limma/'$cellType'.$F[0].de.out.limma.rda", 61 | "'$oDir'/'$cellType'/'$cellType'.$F[0]/'$cellType'.$F[0].sce.rds", 62 | "'$oDir'/'$cellType'/'$cellType'.$F[0]/'$cellType'.$F[0].seu.rds")."\n" ' \ 63 | > $file_int_in 64 | ######################################################## 65 | 66 | 67 | ######################## first run ######################## 68 | ######## 2.2 ####### 69 | ( 70 | cat <<-HERE 71 | #!/bin/bash 72 | #SBATCH -p all 73 | #SBATCH -N 1 74 | #SBATCH --ntasks-per-node=12 75 | #SBATCH -o S.int.$cellType.%j.out 76 | #SBATCH -e S.int.$cellType.%j.err 77 | #SBATCH --no-requeue 78 | echo begin at: \`date\` host: \`hostname\` 79 | $sDir/wrapper.run.inte.R \\ 80 | --inFile $file_int_in \\ 81 | --outPrefix $cDir/OUT.int.$cellType/int.$cellType \\ 82 | --corVar S.Score,G2M.Score,DIG.Score1 83 | HERE 84 | )>$shDir/inte.$cellType.sh 85 | ######################## 86 | 87 | ########## 2.3 submit jobs to run the scripts ######## 88 | #cd $shDir 89 | #sbatch inte.$cellType.sh 90 | #cd $cDir 91 | ################################################## 92 | 93 | ######################## examine the result, find whether there are cells needed to be excluded 94 | ##./w.checkContamination.R 95 | ######################## 96 | 97 | ######################## 3.1 second run ######################## 98 | ### if need to filter out some cells, add: 99 | ### --excludeCells "$cDir/OUT.int.$cellType/int.$cellType.contamination.vec.rds" \\ 100 | ( 101 | cat <<-HERE 102 | #!/bin/bash 103 | #SBATCH -p all 104 | #SBATCH -N 1 105 | #SBATCH --ntasks-per-node=2 106 | #SBATCH -o S.int.$cellType.%j.out 107 | #SBATCH -e S.int.$cellType.%j.err 108 | #SBATCH --no-requeue 109 | echo begin at: \`date\` host: \`hostname\` 110 | $sDir/wrapper.run.inte.R \\ 111 | --inFile $file_int_in \\ 112 | --outPrefix $cDir/OUT.int.$cellType.2nd/int.$cellType \\ 113 | --corVar S.Score,G2M.Score,DIG.Score1,ISG.Score1 114 | HERE 115 | )>$shDir/inte.$cellType.2nd.sh 116 | 117 | ########## 3.2 submit jobs to run the scripts ######## 118 | #cd $shDir 119 | #sbatch inte.$cellType.2nd.sh 120 | #cd $cDir 121 | ################################################## 122 | 123 | ######################## 4. cluster annotation ######################## 124 | ./w.ann.$cellType.R 125 | 126 | ######################## 5.1 run limma per dataset ######################## 127 | join -1 1 -2 1 \ 128 | <(cut -f 1-3 $file_int_in|sort -k 1r,1) \ 129 | <(ls $cDir/OUT.int.$cellType.2nd/sce/*.sce.rds | perl -ane 'BEGIN{print "data.id\tscefile\n" } chomp; /sce\/(.+?).sce.rds/;print "$1\t$_\n"' | sort -k 1r,1) \ 130 | | sed 's/\s\+/\t/g' \ 131 | > $file_limma_in 132 | 133 | while read data_id measurement platform scefile 134 | do 135 | ( 136 | cat <<-HERE 137 | #!/bin/bash 138 | #SBATCH -p all 139 | #SBATCH -N 1 140 | #SBATCH --ntasks-per-node=8 141 | #SBATCH -o S.limma.$cellType.$data_id.%j.out 142 | #SBATCH -e S.limma.$cellType.$data_id.%j.err 143 | #SBATCH --no-requeue 144 | echo begin at: \`date\` host: \`hostname\` 145 | echo \`hostname\` 146 | $sDir/wrapper.run.limma.R \\ 147 | -b $scefile \\ 148 | -o $cDir/OUT.int.$cellType.2nd/limma.sc/$data_id/limma.sc.$data_id \\ 149 | --platform $platform \\ 150 | --group "majorCluster" \\ 151 | --groupMode "multiAsTwo" \\ 152 | -n 8 \\ 153 | -m $measurement 154 | HERE 155 | )>$shDir/limma.$cellType.$data_id.sh 156 | done < <(awk '!/^data.id/' $file_limma_in) 157 | 158 | ########## 5.2 submit jobs to run the scripts ######## 159 | #cd $shDir 160 | # ls limma.$cellType.*.sh | awk '{print "sbatch "$0}' | bash 161 | #cd $cDir 162 | ################################################## 163 | 164 | ######################## 6. limma to sce ######################## 165 | ### please check that the format of data.id is: ^(cancerType).(dataset)$, and ther are no "." (dots) in cancerType and dataset 166 | ### signature gene difference of BRCA.ElhamAzizi2018_InDrop 167 | ### | sed 's/BRCA.ElhamAzizi2018.InDrop/BRCA.ElhamAzizi2018_InDrop/' \ 168 | join -1 1 -2 1 \ 169 | <(cut -f 1-3 $file_int_in|sort -k 1r,1) \ 170 | <(ls $cDir/OUT.int.$cellType.2nd/limma.sc/*/*.de.out.rda | perl -ane 'BEGIN{print "data.id\tdfile\n" } chomp; /.+limma.sc.(.+?).de.out/;print "$1\t$_\n"' | sort -k 1r,1) \ 171 | | sed '/BRCA.ElhamAzizi2018.InDrop/d' \ 172 | | sed 's/\s\+/\t/g' \ 173 | > $file_limma_out 174 | 175 | $sDir/wrapper.convertLimmaToSCE.R \ 176 | --limmaFile $file_limma_out \ 177 | --outPrefix $cDir/OUT.int.$cellType.2nd/int.$cellType.limma.sc \ 178 | --ncores 8 179 | 180 | ######################## 7. prepare data for web ######################## 181 | mkdir $cDir/OUT.data.web 182 | ( 183 | cat <<-HERE 184 | $cDir/OUT.int.$cellType.2nd/int.$cellType.meta.tb.rds 185 | $cDir/OUT.int.$cellType.2nd/int.$cellType.sce.merged.rds 186 | $cDir/OUT.int.$cellType.2nd/int.$cellType.limma.sc.sce.pb.rds 187 | $cDir/OUT.int.$cellType.2nd/int.$cellType.limma.sc.gene.desc.tb.rds 188 | $cDir/OUT.int.$cellType.2nd/int.$cellType.limma.sc.geneTableLong.rds 189 | $cDir/OUT.int.$cellType.2nd/int.$cellType.limma.sc.geneTableLong.collapsed.rds 190 | $cDir/OUT.int.$cellType.2nd/int.$cellType.colSet.rds 191 | HERE 192 | ) | perl -ane 'chomp; ($dname,$bname)=/^(.+)\/(.+)$/; print "ln -s $_ '$cDir'/OUT.data.web/'$g_prj_id'.$bname\n"' \ 193 | | bash 194 | 195 | #,DatasetName,DatasetSource,perMiniCluster,perMetaCluster,meta.perCell,geneTableLong,geneDesc,colSet 196 | printf "$g_prj_id.$cellType,$g_prj_id.$cellType,$cellType,$g_prj_id.int.$cellType.sce.merged.rds,$g_prj_id.int.$cellType.limma.sc.sce.pb.rds,$g_prj_id.int.$cellType.meta.tb.rds,$g_prj_id.int.$cellType.limma.sc.geneTableLong.collapsed.rds,$g_prj_id.int.$cellType.limma.sc.gene.desc.tb.rds,$g_prj_id.int.$cellType.colSet.rds\n" >> $cDir/OUT.data.web/dataset_map.csv 197 | 198 | 199 | ############### final results ################### 200 | # $cDir/OUT.int.$cellType.2nd/int.$cellType.limma.sc.gene.desc.tb.rds 201 | # $cDir/OUT.int.$cellType.2nd/int.$cellType.limma.sc.sce.pb.rds 202 | # $cDir/OUT.int.$cellType.2nd/int.$cellType.meta.tb.rds 203 | # $cDir/OUT.int.$cellType.2nd/int.$cellType.seu.merged.rds 204 | # $cDir/OUT.int.$cellType.2nd/int.$cellType.sce.merged.rds 205 | 206 | ### important columns: geneID median.F.rank 207 | # OUT.int.$cellType.2nd/int.$cellType.gene.rank.tb.flt.rds 208 | 209 | 210 | 211 | -------------------------------------------------------------------------------- /inst/script/example/w.run.T.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | g_prj_id="BRCA" 4 | 5 | cDir=`pwd` 6 | ### columns required in $file_obj_in: aid measurement platform seufile scefile resolution 7 | ### columns required in seurat or sce object: "patient" 8 | file_obj_in="$cDir/list/obj.T.wRef.list" 9 | file_int_in="$cDir/list/obj.T.wRef.list.r1.list" 10 | file_limma_in="$cDir/list/obj.T.list.forLimma.list" 11 | file_limma_out="$cDir/list/obj.T.list.limma.sc.list" 12 | cellType="T" 13 | oDir="$cDir/OUT.byDataset" 14 | shDir="./sh.byDataset.$cellType" 15 | mkdir -p $shDir 16 | 17 | sDir=`R --slave -e 'sDir <- system.file("script",package="scPip"); cat(sDir)'` 18 | echo $sDir 19 | 20 | ######### 1.1 generate scripts to run Seurat for each dataset 21 | while read aid measurement platform seufile scefile resolution 22 | do 23 | ( 24 | cat <<-HERE 25 | #!/bin/bash 26 | #SBATCH -p all 27 | #SBATCH -N 1 28 | #SBATCH --ntasks-per-node=12 29 | #SBATCH -o S.$cellType.$aid.%j.out 30 | #SBATCH -e S.$cellType.$aid.%j.err 31 | #SBATCH --no-requeue 32 | echo begin at: \`date\` host: \`hostname\` 33 | $sDir/run.seurat3.basic.R \\ 34 | -a $seufile \\ 35 | -b $scefile \\ 36 | -o $oDir/$cellType/$cellType.$aid/$cellType.$aid \\ 37 | -d 15 \\ 38 | -n 12 \\ 39 | --keep globalC:T,T/NK \\ 40 | --removeContamination plasmaB:0.75,caf:0.75,epi:0.75,mac:0.75 \\ 41 | --deg \\ 42 | --resolution $resolution \\ 43 | -m $measurement \\ 44 | --platform $platform 45 | HERE 46 | )>$shDir/byDataset.$cellType.$aid.sh 47 | done< <(awk 'NR>1' $file_obj_in) 48 | 49 | ########## 1.2 submit jobs to run the scripts ######## 50 | #cd $shDir 51 | #ls *.sh | awk '{print "sbatch "$0}' | bash 52 | #cd $cDir 53 | ################################################## 54 | 55 | ######## 2.1 prepare file list for integration ############ 56 | sed '1,1d' $file_obj_in \ 57 | | perl -ane 'BEGIN{ print "data.id\tmeasurement\tplatform\tdefile\tscefile\tseufile\n" } 58 | chomp; print join("\t",@F[0..2], 59 | "'$oDir'/'$cellType'/'$cellType'.$F[0]/limma/'$cellType'.$F[0].de.out.limma.rda", 60 | "'$oDir'/'$cellType'/'$cellType'.$F[0]/'$cellType'.$F[0].sce.rds", 61 | "'$oDir'/'$cellType'/'$cellType'.$F[0]/'$cellType'.$F[0].seu.rds")."\n" ' \ 62 | > $file_int_in 63 | ######################################################## 64 | 65 | 66 | ######################## 2.2 first run ######################## 67 | ( 68 | cat <<-HERE 69 | #!/bin/bash 70 | #SBATCH -p all 71 | #SBATCH -N 1 72 | #SBATCH --ntasks-per-node=12 73 | #SBATCH -o S.int.$cellType.%j.out 74 | #SBATCH -e S.int.$cellType.%j.err 75 | #SBATCH --no-requeue 76 | echo begin at: \`date\` host: \`hostname\` 77 | $sDir/wrapper.run.inte.R \\ 78 | --inFile $file_int_in \\ 79 | --outPrefix $cDir/OUT.int.$cellType/int.$cellType \\ 80 | --corVar S.Score,G2M.Score,DIG.Score1 81 | HERE 82 | )>$shDir/inte.$cellType.sh 83 | ######################## 84 | 85 | ########## 2.3 submit jobs to run the scripts ######## 86 | #cd $shDir 87 | #sbatch inte.$cellType.sh 88 | #cd $cDir 89 | ################################################## 90 | 91 | ######################## 3.1 examine the result, find whether there are cells needed to be excluded 92 | ./w.checkContamination.T.R 93 | ######################## 94 | 95 | ######################## 3.2 second run ######################## 96 | ### if need to filter out some cells, add: 97 | ### --excludeCells "$cDir/OUT.int.$cellType/int.$cellType.contamination.vec.rds" \\ 98 | ( 99 | cat <<-HERE 100 | #!/bin/bash 101 | #SBATCH -p all 102 | #SBATCH -N 1 103 | #SBATCH --ntasks-per-node=2 104 | #SBATCH -o S.int.$cellType.2nd.%j.out 105 | #SBATCH -e S.int.$cellType.2nd.%j.err 106 | #SBATCH --no-requeue 107 | echo begin at: \`date\` host: \`hostname\` 108 | $sDir/wrapper.run.inte.R \\ 109 | --inFile $file_int_in \\ 110 | --outPrefix $cDir/OUT.int.$cellType.2nd/int.$cellType \\ 111 | --excludeCells "$cDir/OUT.int.$cellType/int.$cellType.contamination.vec.rds" \\ 112 | --corVar S.Score,G2M.Score,DIG.Score1,ISG.Score1 113 | HERE 114 | )>$shDir/inte.$cellType.2nd.sh 115 | 116 | ########## 3.3 submit jobs to run the scripts ######## 117 | #cd $shDir 118 | #sbatch inte.$cellType.2nd.sh 119 | #cd $cDir 120 | ################################################## 121 | 122 | 123 | ######################## 4. cluster annotation ######################## 124 | ./w.ann.$cellType.R 125 | 126 | ######################## 5.1 run limma per dataset ######################## 127 | join -1 1 -2 1 \ 128 | <(cut -f 1-3 $file_int_in|sort -k 1r,1) \ 129 | <(ls $cDir/OUT.int.$cellType.2nd/sce/*.sce.rds | perl -ane 'BEGIN{print "data.id\tscefile\n" } chomp; /sce\/(.+?).sce.rds/;print "$1\t$_\n"' | sort -k 1r,1) \ 130 | | sed 's/\s\+/\t/g' \ 131 | | awk -F"\t" -v OFS="\t" 'BEGIN{ print("data.id\tmeasurement\tplatform\tscefile") } !/^data.id/{print $0}' \ 132 | > $file_limma_in 133 | 134 | while read data_id measurement platform scefile 135 | do 136 | ( 137 | cat <<-HERE 138 | #!/bin/bash 139 | #SBATCH -p all 140 | #SBATCH -N 1 141 | #SBATCH --ntasks-per-node=8 142 | #SBATCH -o S.limma.$cellType.$data_id.%j.out 143 | #SBATCH -e S.limma.$cellType.$data_id.%j.err 144 | #SBATCH --no-requeue 145 | echo begin at: \`date\` host: \`hostname\` 146 | echo \`hostname\` 147 | $sDir/wrapper.run.limma.R \\ 148 | -b $scefile \\ 149 | -o $cDir/OUT.int.$cellType.2nd/limma.sc/$data_id/limma.sc.$data_id \\ 150 | --platform $platform \\ 151 | --group "majorCluster" \\ 152 | --groupMode "multiAsTwo" \\ 153 | -n 8 \\ 154 | -m $measurement 155 | HERE 156 | )>$shDir/limma.$cellType.$data_id.sh 157 | done < <(awk '!/^data.id/' $file_limma_in) 158 | 159 | ########## 5.2 submit jobs to run the scripts ######## 160 | #cd $shDir 161 | # ls limma.$cellType.*.sh | awk '{print "sbatch "$0}' | bash 162 | #cd $cDir 163 | ################################################## 164 | 165 | ######################## 6. limma to sce ######################## 166 | ### please check that the format of data.id is: ^(cancerType).(dataset)$, and ther are no "." (dots) in cancerType and dataset 167 | ### signature gene difference of BRCA.ElhamAzizi2018_InDrop 168 | ### | sed 's/BRCA.ElhamAzizi2018.InDrop/BRCA.ElhamAzizi2018_InDrop/' \ 169 | join -1 1 -2 1 \ 170 | <(cut -f 1-3 $file_int_in|sort -k 1r,1) \ 171 | <(ls $cDir/OUT.int.$cellType.2nd/limma.sc/*/*.de.out.rda | perl -ane 'BEGIN{print "data.id\tdfile\n" } chomp; /.+limma.sc.(.+?).de.out/;print "$1\t$_\n"' | sort -k 1r,1) \ 172 | | awk '!/(BRCA.ElhamAzizi2018.InDrop|HC.JiyuanZhang2020)/' \ 173 | | sed 's/\s\+/\t/g' \ 174 | | sed 's/BRCA.ElhamAzizi2018.10X/BRCA.ElhamAzizi2018_10X/' \ 175 | > $file_limma_out 176 | 177 | $sDir/wrapper.convertLimmaToSCE.R \ 178 | --limmaFile $file_limma_out \ 179 | --outPrefix $cDir/OUT.int.$cellType.2nd/int.$cellType.limma.sc \ 180 | --ncores 8 181 | 182 | ######################## 7. prepare data for web ######################## 183 | mkdir $cDir/OUT.data.web 184 | ( 185 | cat <<-HERE 186 | $cDir/OUT.int.$cellType.2nd/int.$cellType.meta.tb.rds 187 | $cDir/OUT.int.$cellType.2nd/int.$cellType.sce.merged.rds 188 | $cDir/OUT.int.$cellType.2nd/int.$cellType.limma.sc.sce.pb.rds 189 | $cDir/OUT.int.$cellType.2nd/int.$cellType.limma.sc.gene.desc.tb.rds 190 | $cDir/OUT.int.$cellType.2nd/int.$cellType.limma.sc.geneTableLong.rds 191 | $cDir/OUT.int.$cellType.2nd/int.$cellType.limma.sc.geneTableLong.collapsed.rds 192 | $cDir/OUT.int.$cellType.2nd/int.$cellType.colSet.rds 193 | HERE 194 | ) | perl -ane 'chomp; ($dname,$bname)=/^(.+)\/(.+)$/; print "ln -s $_ '$cDir'/OUT.data.web/'$g_prj_id'.$bname\n"' \ 195 | | bash 196 | 197 | #,DatasetName,DatasetSource,perMiniCluster,perMetaCluster,meta.perCell,geneTableLong,geneDesc,colSet 198 | printf "$g_prj_id.$cellType,$g_prj_id.$cellType,$cellType,$g_prj_id.int.$cellType.sce.merged.rds,$g_prj_id.int.$cellType.limma.sc.sce.pb.rds,$g_prj_id.int.$cellType.meta.tb.rds,$g_prj_id.int.$cellType.limma.sc.geneTableLong.collapsed.rds,$g_prj_id.int.$cellType.limma.sc.gene.desc.tb.rds,$g_prj_id.int.$cellType.colSet.rds\n" > $cDir/OUT.data.web/dataset_map.csv 199 | 200 | ############### final results ################### 201 | # $cDir/OUT.int.$cellType.2nd/int.$cellType.limma.sc.gene.desc.tb.rds 202 | # $cDir/OUT.int.$cellType.2nd/int.$cellType.limma.sc.sce.pb.rds 203 | # $cDir/OUT.int.$cellType.2nd/int.$cellType.meta.tb.rds 204 | # $cDir/OUT.int.$cellType.2nd/int.$cellType.seu.merged.rds 205 | # $cDir/OUT.int.$cellType.2nd/int.$cellType.sce.merged.rds 206 | 207 | ### important columns: geneID median.F.rank 208 | # OUT.int.$cellType.2nd/int.$cellType.gene.rank.tb.flt.rds 209 | 210 | 211 | 212 | -------------------------------------------------------------------------------- /inst/script/aln.STAR.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -eu 2 | 3 | 4 | sDir=`dirname $0` 5 | iniFile="$sDir/../parameter/init_human.sh" 6 | 7 | optM=30 8 | optMode="" 9 | 10 | while getopts c:m: opt 11 | do 12 | case $opt in 13 | c) 14 | if [ -f $OPTARG ] 15 | then 16 | iniFile="$OPTARG" 17 | else 18 | echo "WARNING: invalid reference file ($OPTARG), default will be used" 19 | fi 20 | ;; 21 | m) 22 | optMode=$OPTARG 23 | ;; 24 | '?') 25 | echo "Usage: $0 invalid option -$OPTARG" 26 | echo "Usage: $0 [-c iniFile] [-m mode, default ''] " 27 | exit 1 28 | ;; 29 | esac 30 | done 31 | shift $((OPTIND-1)) 32 | 33 | if [ $# -lt 4 ] 34 | then 35 | echo "Usage: $0 [-c iniFile] [-m mode, default ''] " 36 | exit 1 37 | fi 38 | 39 | source $iniFile 40 | 41 | STAR_GenomeDir=/WPSnew/zhenglt/00.database/broad/bundle/2.8/b37/star 42 | gene_model_file=/WPSnew/zhenglt/00.database/gencode/v24/gencode.v24lift37.annotation.gtf 43 | STAR_FUSION_DB_Dir=/WPSnew/zhenglt/00.database/tools/star-fusion/GRCh37_v24_mybuild/ctat_genome_lib_build_dir 44 | module load STAR/2.6.1d 45 | ###module unload java/1.7.0_79 46 | module load java/1.8.0_171 47 | ###module unload gatk/3.3-0 48 | ####module load gatk/3.8-0 49 | module load subread/1.6.3 50 | module load trimmomatic/0.33 51 | module load blast/2.8.1+ 52 | module load STAR-Fusion/1.5.0 53 | 54 | ### with ERCC 55 | #####export REF=/DBS/DB_temp/zhangLab/broad/bundle/2.8/hg19/gmap-gsnap/withERCC.v1/hg19.order.after.gsnap.fa 56 | ### without ERCC 57 | #####export REF=/DBS/DB_temp/zhangLab/broad/bundle/2.8/hg19/gmap-gsnap/hg19.order.after.gsnap.fa 58 | #####knownSites=/DBS/DB_temp/zhangLab/broad/bundle/2.8/hg19/dbsnp_138.hg19.reorder.vcf 59 | 60 | sampleID=$1 61 | fq1=$2 62 | fq2=$3 63 | outDir=$4 64 | ####REF=$5 65 | 66 | ### for most analysis, parallel mode is not supported currently 67 | optNT=1 68 | ###optNT=8 69 | 70 | optL='' 71 | optM=`echo "scale=0;$optM/1.5" | bc` 72 | max_reads=`echo 250000*$optM | bc` 73 | 74 | mkdir -p $outDir 75 | 76 | newFQ1=$fq1 77 | newFQ2=$fq2 78 | len_trim_to=101 79 | 80 | if [ "$optMode" == "trim" ];then 81 | if [ ! -f "$outDir/$sampleID.clean.P.R1.fq.gz" ] 82 | then 83 | java -Xmx${optM}g -jar $TRIMMOMATIC_DIR/trimmomatic-0.33.jar PE \ 84 | -threads 8 \ 85 | $fq1 \ 86 | $fq2 \ 87 | $outDir/$sampleID.clean.P.R1.fq.gz \ 88 | $outDir/$sampleID.clean.UP.R1.fq.gz \ 89 | $outDir/$sampleID.clean.P.R2.fq.gz \ 90 | $outDir/$sampleID.clean.UP.R2.fq.gz \ 91 | ILLUMINACLIP:$TRIMMOMATIC_DIR/adapters/NexteraPE-PE.fa:2:30:10 \ 92 | CROP:$len_trim_to \ 93 | TRAILING:3 \ 94 | MAXINFO:50:0.25 \ 95 | MINLEN:36 \ 96 | TOPHRED33 97 | echo "trimmomatic done. (" `date` ")" 98 | fi 99 | newFQ1=$outDir/$sampleID.clean.P.R1.fq.gz 100 | newFQ2=$outDir/$sampleID.clean.P.R2.fq.gz 101 | fi 102 | 103 | STAR \ 104 | --runThreadN 8 \ 105 | --genomeDir $STAR_GenomeDir \ 106 | --readFilesIn $newFQ1 $newFQ2 \ 107 | --readFilesCommand zcat \ 108 | --outFileNamePrefix $outDir/$sampleID. \ 109 | --quantMode GeneCounts \ 110 | --twopassMode Basic \ 111 | --outSAMattrRGline ID:$sampleID CN:BIOPIC LB:$sampleID PL:illumina PU:$sampleID SM:$sampleID \ 112 | --outSAMtype BAM SortedByCoordinate \ 113 | --outReadsUnmapped None \ 114 | --chimSegmentMin 12 \ 115 | --chimJunctionOverhangMin 12 \ 116 | --alignSJDBoverhangMin 10 \ 117 | --alignMatesGapMax 100000 \ 118 | --alignIntronMax 100000 \ 119 | --chimSegmentReadGapMax 3 \ 120 | --alignSJstitchMismatchNmax 5 -1 5 5 \ 121 | --outSAMstrandField intronMotif \ 122 | --chimOutJunctionFormat 1 123 | 124 | samtools index $outDir/${sampleID}.Aligned.sortedByCoord.out.bam 125 | 126 | echo "... using $max_reads reads in memory (parameter optM: $optM*1.5)" 127 | java -Xmx${optM}g -jar $PICARD/picard.jar SortSam \ 128 | I=$outDir/${sampleID}.Aligned.sortedByCoord.out.bam \ 129 | O=$outDir/${sampleID}.Aligned.sortedByRName.out.bam \ 130 | MAX_RECORDS_IN_RAM=$max_reads \ 131 | TMP_DIR=$outDir \ 132 | SO=queryname \ 133 | VALIDATION_STRINGENCY=SILENT 134 | ###samtools index $outDir/${sampleID}.Aligned.sortedByRName.out.bam 135 | 136 | ####### gene expression 137 | featureCounts -p -T 2 \ 138 | -a $gene_model_file \ 139 | -o $outDir/$sampleID.subread.exp \ 140 | $outDir/${sampleID}.Aligned.sortedByRName.out.bam 141 | ##$outDir/${sampleID}.Aligned.sortedByCoord.out.bam 142 | 143 | featureCounts -p -T 2 -O \ 144 | -a $gene_model_file \ 145 | -o $outDir/$sampleID.subread.exp.optO \ 146 | $outDir/${sampleID}.Aligned.sortedByRName.out.bam 147 | ##$outDir/${sampleID}.Aligned.sortedByCoord.out.bam 148 | 149 | rm $outDir/${sampleID}.Aligned.sortedByRName.out.bam 150 | 151 | ####### fusion 152 | STAR-Fusion --genome_lib_dir $STAR_FUSION_DB_Dir \ 153 | -J $outDir/$sampleID.Chimeric.out.junction \ 154 | --CPU 8 \ 155 | --output_dir $outDir/star-fusion 156 | 157 | exit 158 | 159 | ####### variant calling ###### 160 | 161 | inBam=$outDir/${sampleID}.Aligned.sortedByCoord.out.bam 162 | #####inBam=$outDir/${sampleID}.Aligned.sortedByCoord.out.RG.bam 163 | outBam=$outDir/$sampleID.GATK.RNA.ready.bam 164 | 165 | if [ -f $outBam ] 166 | then 167 | echo "## $outBam exists, skip this step" 168 | exit 0 169 | fi 170 | 171 | if [ ! -f $inBam.bai ] 172 | then 173 | samtools index $inBam 174 | fi 175 | 176 | echo ">>> Marking duplicates" 177 | this_bam=$outDir/$sampleID.rmDup.bam 178 | if [ ! -f $this_bam ] 179 | then 180 | echo "using $max_reads reads in memory (parameter optM: $optM*1.5)" 181 | java -Xmx${optM}g -jar $PICARD/picard.jar MarkDuplicates \ 182 | TMP_DIR=$outDir \ 183 | I=$inBam \ 184 | O=$this_bam \ 185 | M=${this_bam%.bam}.metrics \ 186 | VALIDATION_STRINGENCY=SILENT \ 187 | ASSUME_SORTED=true \ 188 | REMOVE_DUPLICATES=false \ 189 | MAX_RECORDS_IN_RAM=$max_reads 190 | 191 | rm -f ${this_bam%.bam}.bai 192 | samtools index $this_bam 193 | fi 194 | 195 | echo ">>> splitNTrim" 196 | optM=`echo "scale=0;$optM/1.5" | bc` 197 | inBam=$this_bam 198 | this_bam=$outDir/$sampleID.GATK.RNA.splitNCigar.bam 199 | if [ ! -f $this_bam.bai ] 200 | then 201 | java -Xms${optM}g -Xmx${optM}g -Djava.io.tmpdir=$outDir -jar $GATK/GenomeAnalysisTK.jar \ 202 | -T SplitNCigarReads \ 203 | -R $REF \ 204 | -I $inBam \ 205 | -o $this_bam \ 206 | -U ALLOW_N_CIGAR_READS \ 207 | -rf ReassignOneMappingQuality -RMQF 255 -RMQT 60 208 | ##-fixNDN 209 | ## for gsnap result, not nessesary: 210 | ##-rf ReassignOneMappingQuality -RMQF 255 -RMQT 60 \ 211 | ## for SplitNCigarReads, parallel mode is not supported currently 212 | ## -nt $optNT \ 213 | samtools index $this_bam 214 | fi 215 | 216 | rm $inBam 217 | rm $inBam.bai 218 | 219 | 220 | this_bam=$outDir/$sampleID.GATK.RNA.realn.bam 221 | if [ ! -f $this_bam.bai ] 222 | then 223 | echo ">>> Determining (small) suspicious intervals which are likely in need of realignment" 224 | java -Xms${optM}g -Xmx${optM}g -Djava.io.tmpdir=$outDir -jar $GATK/GenomeAnalysisTK.jar \ 225 | -T RealignerTargetCreator \ 226 | -I $outDir/$sampleID.GATK.RNA.splitNCigar.bam \ 227 | -R $REF \ 228 | -o $outDir/$sampleID.GATK.RNA.realn.intervals $optL \ 229 | -nt $optNT \ 230 | -rf BadCigar 231 | echo ">>> Running the realigner over the targeted intervals" 232 | java -Xms${optM}g -Xmx${optM}g -Djava.io.tmpdir=$outDir -jar $GATK/GenomeAnalysisTK.jar \ 233 | -T IndelRealigner \ 234 | -I $outDir/$sampleID.GATK.RNA.splitNCigar.bam \ 235 | -R $REF \ 236 | -o $outDir/$sampleID.GATK.RNA.realn.bam \ 237 | -targetIntervals $outDir/$sampleID.GATK.RNA.realn.intervals \ 238 | -LOD 5 $optL \ 239 | -nt $optNT \ 240 | -rf BadCigar 241 | samtools index $outDir/$sampleID.GATK.RNA.realn.bam 242 | fi 243 | 244 | echo $knownSites 245 | 246 | 247 | this_bam=$outDir/$sampleID.GATK.RNA.recal.bam 248 | if [ ! -f $this_bam.bai ] 249 | then 250 | echo ">>> Counting covariates" 251 | optM=`echo "scale=0;$optM/1.2" | bc` 252 | java -Djava.io.tmpdir=$outDir -Xms${optM}g -Xmx${optM}g -jar $GATK/GenomeAnalysisTK.jar \ 253 | -T BaseRecalibrator \ 254 | -R $REF \ 255 | --knownSites $knownSites \ 256 | --disable_indel_quals \ 257 | -I $outDir/$sampleID.GATK.RNA.realn.bam \ 258 | -o $outDir/$sampleID.GATK.RNA.recal.grp \ 259 | -cov ReadGroupCovariate \ 260 | -cov QualityScoreCovariate \ 261 | -cov CycleCovariate \ 262 | -cov ContextCovariate \ 263 | -rf BadCigar \ 264 | --validation_strictness SILENT 265 | 266 | echo ">> Table recalibration" 267 | if [ "`grep -v '#' $outDir/$sampleID.GATK.RNA.recal.grp | grep -v "EOF" | wc -l`" = "1" ] 268 | then 269 | echo "no recal.grp" 270 | ln $outDir/$sampleID.GATK.RNA.realn.bam $outDir/$sampleID.GATK.RNA.recal.bam 271 | else 272 | java -Djava.io.tmpdir=$outDir -Xms${optM}g -Xmx${optM}g -jar $GATK/GenomeAnalysisTK.jar \ 273 | -T PrintReads \ 274 | -R $REF \ 275 | -I $outDir/$sampleID.GATK.RNA.realn.bam \ 276 | -o $outDir/$sampleID.GATK.RNA.recal.bam \ 277 | -BQSR $outDir/$sampleID.GATK.RNA.recal.grp \ 278 | --disable_indel_quals \ 279 | -EOQ \ 280 | -rf BadCigar 281 | fi 282 | samtools index $outDir/$sampleID.GATK.RNA.recal.bam 283 | fi 284 | 285 | java -Xms${optM}g -Xmx${optM}g -Djava.io.tmpdir=$outDir -jar $GATK/GenomeAnalysisTK.jar \ 286 | -T HaplotypeCaller \ 287 | -R $REF \ 288 | -I $outDir/$sampleID.GATK.RNA.recal.bam \ 289 | -dontUseSoftClippedBases \ 290 | -stand_call_conf 20.0 \ 291 | -nt $optNT \ 292 | --num_cpu_threads_per_data_thread 4 \ 293 | -o $outDir/$sampleID.GATK.RNA.recal.var.vcf 294 | 295 | java -Xms${optM}g -Xmx${optM}g -Djava.io.tmpdir=$outDir -jar $GATK/GenomeAnalysisTK.jar \ 296 | -T VariantFiltration \ 297 | -R $REF \ 298 | -V $outDir/$sampleID.GATK.RNA.recal.var.vcf \ 299 | -window 35 -cluster 3 \ 300 | -filterName FS -filter "FS > 30.0" \ 301 | -filterName QD -filter "QD < 2.0" \ 302 | -o $outDir/$sampleID.GATK.RNA.recal.var.flt.vcf 303 | 304 | 305 | echo end at: `date` 306 | -------------------------------------------------------------------------------- /inst/script/run.scanpy.basic.R: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env Rscript 2 | 3 | suppressPackageStartupMessages(library("argparse")) 4 | 5 | parser <- ArgumentParser() 6 | parser$add_argument("-a", "--aFile", type="character", required=TRUE, help="input h5ad file") 7 | parser$add_argument("-o", "--outPrefix", type="character", required=TRUE, help="outPrefix") 8 | parser$add_argument("-q", "--specie", type="character", default="human", help="one of human, mouse [default %(default)s]") 9 | parser$add_argument("-c", "--stype", type="character", help="only analyze stype specified (default all)") 10 | parser$add_argument("-u", "--geneIDFile", type="character", help="gene id mapping file") 11 | parser$add_argument("-d", "--npc", type="integer",default=15L, help="[default %(default)s]") 12 | parser$add_argument("-n", "--ncores", type="integer",default=16L, help="[default %(default)s]") 13 | parser$add_argument("-m", "--ntop", type="integer",default=1500L, help="top HVG genes[default %(default)s]") 14 | parser$add_argument("-r", "--resolution",type="character",default="1",help="best resolution [default %(default)s]") 15 | parser$add_argument("-s", "--resTest", type="character",default="seq(0.1,2.4,0.1)", help="resolutions to test [default %(default)s]") 16 | parser$add_argument("-y", "--harmony",action="store_true",default=FALSE,help="[default %(default)s]") 17 | parser$add_argument("-i", "--integration",type="character",help="[default %(default)s]") 18 | parser$add_argument("-g", "--deg",action="store_true",default=FALSE,help="[default %(default)s]") 19 | parser$add_argument("-w", "--ncellDEG",type="integer",default=1500, 20 | help="number of cells to downsample to for each group. used in DEG analysis. [default %(default)s]") 21 | #parser$add_argument("-s", "--scale",action="store_true",default=FALSE,help="[default %(default)s]") 22 | parser$add_argument("-p", "--percentMT", type="double", default=10, help="threshold for percent.mito. [default %(default)s]") 23 | parser$add_argument("-j", "--corVar", type="character", default="S_score,G2M_score,DIG.Score,percent.mito", 24 | help="subset of S_score,G2M_score,DIG.Score,percent.mito, or NULL. [default %(default)s]") 25 | parser$add_argument("-f", "--filterout",type="character",help="Format is COLUMN_ID:COLUMN_VAL_1,COLUMN_VAL_2,COLUMN_VAL_3. Filter out cells with COLUMN_ID in one of COLUMN_VAL_1, COLUMN_VAL_2, and COLUMN_VAL_3.") 26 | parser$add_argument("-k", "--keep",type="character",help="Format is COLUMN_ID:COLUMN_VAL_1,COLUMN_VAL_2,COLUMN_VAL_3. Keep only cells with COLUMN_ID in one of COLUMN_VAL_1, COLUMN_VAL_2, and COLUMN_VAL_3.") 27 | parser$add_argument("-z", "--markerFile",type="character",help="file define cell type marker. used for --removeContamination. [default %(default)s]") 28 | parser$add_argument("-x", "--removeContamination",type="character",help="comma separated string indicates subset of predefined signature (plasmaB, caf, epi, T, cd8, and mac) will be calculated and cells with high signature scores will be removed. For example, use plasmaB:0.75,caf:0.75,epi:0.75,T:0.25 for myeloid cell analysis. The numer after colon is the threshold") 29 | args <- parser$parse_args() 30 | print(args) 31 | 32 | ############## tune parametrs ######## 33 | 34 | adata.file <- args$aFile 35 | out.prefix <- args$outPrefix 36 | ###opt.npc <- args$npc 37 | opt.npc <- as.integer(eval(parse(text = args$npc))) 38 | opt.ncores <- as.integer(args$ncores) 39 | opt.ntop <- as.integer(args$ntop) 40 | opt.resTest <- eval(parse(text=args$resTest)) 41 | opt.stype <- args$stype 42 | opt.resolution <- args$resolution 43 | opt.harmony <- args$harmony 44 | opt.integration <- args$integration 45 | opt.doDEG <- args$deg 46 | opt.ncell.deg <- args$ncellDEG 47 | #opt.scale <- args$scale 48 | opt.cor.var <- if(args$corVar=="") c("") else unlist(strsplit(args$corVar,",",perl=T)) 49 | opt.filterout <- args$filterout 50 | opt.keep <- args$keep 51 | opt.geneIDFile <- args$geneIDFile 52 | opt.markerFile <- args$markerFile 53 | opt.removeContamination <- args$removeContamination 54 | opt.specie <- args$specie 55 | opt.percentMT <- args$percentMT 56 | 57 | dir.create(dirname(out.prefix),F,T) 58 | 59 | saveRDS(args,file=sprintf("%s.args.rds",out.prefix)) 60 | ###args <- readRDS(file=sprintf("%s.args.rds",out.prefix)) 61 | 62 | ############## tune parametrs ######## 63 | suppressMessages(library("sscVis")) 64 | suppressMessages(library("anndata")) 65 | #suppressMessages(library("scanpy")) 66 | #suppressMessages(library("sscClust")) 67 | #suppressMessages(library("Seurat")) 68 | suppressMessages(library("tictoc")) 69 | suppressMessages(library("plyr")) 70 | suppressMessages(library("dplyr")) 71 | suppressMessages(library("tibble")) 72 | suppressMessages(library("doParallel")) 73 | suppressMessages(library("Matrix")) 74 | suppressMessages(library("data.table")) 75 | suppressMessages(library("R.utils")) 76 | suppressMessages(library("gplots")) 77 | suppressMessages(library("ggplot2")) 78 | suppressMessages(library("ggpubr")) 79 | suppressMessages(library("cowplot")) 80 | suppressMessages(library("limma")) 81 | suppressMessages(library("reticulate")) 82 | suppressMessages(library("scPip")) 83 | suppressMessages(library("anndata")) 84 | options(stringsAsFactors = FALSE) 85 | sc <- import("scanpy") 86 | 87 | dat.ext.dir <- system.file("extdata",package="scPip") 88 | if(opt.specie=="human"){ 89 | ###gene.exclude.file <- sprintf("%s/exclude.gene.misc.human.v3.RData",dat.ext.dir) 90 | gene.exclude.file <- sprintf("%s/exclude.gene.misc.human.v4.RData",dat.ext.dir) 91 | }else if(opt.specie=="mouse"){ 92 | ###gene.exclude.file <- sprintf("%s/exclude.gene.misc.mouse.v3.RData",dat.ext.dir) 93 | gene.exclude.file <- sprintf("%s/exclude.gene.misc.mouse.v4.RData",dat.ext.dir) 94 | }else{ 95 | gene.exclude.file <- NULL 96 | } 97 | 98 | if(!is.null(gene.exclude.file)){ 99 | env.misc <- loadToEnv(gene.exclude.file) 100 | g.all.gene.ignore.df <- env.misc$all.gene.ignore.df 101 | g.all.gene.ignore.df %>% head 102 | }else{ 103 | g.all.gene.ignore.df <- NULL 104 | } 105 | 106 | ###################### 107 | 108 | gene.mapping.table <- NULL 109 | if(!is.null(opt.geneIDFile) && file.exists(opt.geneIDFile) && grepl("\\.rds$",opt.geneIDFile,perl=T)){ 110 | gene.mapping.table <- readRDS(opt.geneIDFile) 111 | } 112 | 113 | adata <- anndata::read_h5ad(adata.file) 114 | 115 | ##### filter out doublets predictd by Scrublet 116 | if(!is.null(adata) && "pred.th" %in% colnames(adata$obs) ){ 117 | adata <- adata[adata$obs$pred.th==FALSE] 118 | } 119 | 120 | ##### check & clean sce ##### 121 | if(!is.null(adata) && "percent.mito" %in% colnames(adata$obs)){ 122 | if(all(is.na(adata$obs$percent.mito))){ 123 | adata$obs$percent.mito <- NULL 124 | } 125 | } 126 | 127 | if(!is.null(adata) && ("libraryID" %in% colnames(adata$obs)) && all(is.na(adata$obs$libraryID))){ 128 | adata$obs$libraryID <- "Unk" 129 | } 130 | 131 | ##### filter out cells with hgih percent.mito 132 | if(!is.null(adata) && "percent.mito" %in% colnames(adata$obs) ){ 133 | if(max(adata$obs$percent.mito) <1){ 134 | adata <- adata[adata$obs$percent.mito < opt.percentMT/100] 135 | }else{ 136 | adata <- adata[adata$obs$percent.mito < opt.percentMT] 137 | } 138 | } 139 | 140 | if(!is.null(adata) && !is.null(opt.filterout)){ 141 | if(!file.exists(opt.filterout)){ 142 | col.filter <- unlist(strsplit(opt.filterout,":"))[1] 143 | col.value <- unlist(strsplit(unlist(strsplit(opt.filterout,":"))[2],",")) 144 | if(col.filter %in% colnames(adata$obs)){ 145 | cat(sprintf("filter cells with %s in c(%s)\n",col.filter,paste(col.value,collapse=","))) 146 | if(length(col.value)==1 && grepl("^(>|<|=)",col.value)){ 147 | f.cell <- eval(parse(text=sprintf("adata$obs[,\'%s\'] %s",col.filter,col.value))) 148 | }else{ 149 | f.cell <- adata$obs[,col.filter] %in% col.value 150 | } 151 | 152 | print(summary(f.cell)) 153 | adata <- adata[!f.cell] 154 | }else{ 155 | warning(sprintf("The meta-data doesnot contain %s\n",col.filter)) 156 | } 157 | } 158 | } 159 | 160 | if(!is.null(adata) && !is.null(opt.keep)){ 161 | if(!file.exists(opt.keep)){ 162 | col.keep <- unlist(strsplit(opt.keep,":"))[1] 163 | col.value <- unlist(strsplit(unlist(strsplit(opt.keep,":"))[2],",")) 164 | if(col.keep %in% colnames(adata$obs)){ 165 | cat(sprintf("keep only cells with %s in c(%s)\n",col.keep,paste(col.value,collapse=","))) 166 | if(length(col.value)==1 && grepl("^(>|<|=)",col.value)){ 167 | f.cell <- eval(parse(text=sprintf("adata$obs[,\'%s\'] %s",col.keep,col.value))) 168 | }else{ 169 | f.cell <- adata$obs[,col.keep] %in% col.value 170 | } 171 | print(summary(f.cell)) 172 | adata <- adata[f.cell] 173 | }else{ 174 | warning(sprintf("The meta-data doesnot contain %s\n",col.keep)) 175 | } 176 | } 177 | } 178 | 179 | if(!is.null(opt.removeContamination)) { 180 | ### opt.removeContamination <- "plasmaB:0.75,caf:0.75,epi:0.75,T:0.25" 181 | if(is.null(opt.markerFile)){ 182 | g.cont.gene.list <- list("plasmaB"=c("JCHAIN"), 183 | "B"=c("CD79A","MS4A1"), 184 | "caf"=c("COL1A2", "COL1A1", "COL3A1","LUM"), 185 | "epi"=c("KRT18","KRT19","EPCAM"), 186 | "T"=c("CD3D","CD3G"), 187 | "cd8"=c("CD8A","CD8B"), 188 | "mac"=c("LYZ","C1QA","C1QB","CD68")) 189 | }else{ 190 | marker.rmCont.tb <- fread(opt.markerFile,head=F) 191 | g.cont.gene.list <- llply(split(marker.rmCont.tb,by=c("V1")),function(x){ x$V2 }) 192 | } 193 | 194 | sig.vec <- unlist(strsplit(opt.removeContamination,",")) 195 | sig.name <- unname(sapply(sig.vec,function(x){ unlist(strsplit(x,":"))[1] })) 196 | sig.thre <- unname(sapply(sig.vec,function(x){ as.numeric(unlist(strsplit(x,":"))[2]) })) 197 | 198 | for(i in seq_along(sig.name)){ 199 | loginfo(sprintf("calculate signature score of %s cells ...",sig.name[i])) 200 | adata <- fill.contamination(adata,out.prefix, 201 | g.name=sig.name[i], 202 | g.test=g.cont.gene.list[[sig.name[i]]], 203 | score.t=sig.thre[i], 204 | vis.v=c(0.25,0.5,0.75,1)) 205 | } 206 | 207 | idx.sig.class <- intersect(sprintf("%s.class",sig.name),colnames(adata$obs)) 208 | f.cont.mtx <- adata$obs[,idx.sig.class,drop=F] 209 | f.cont <- rowSums(f.cont.mtx) > 0 210 | loginfo(sprintf("A total number of potential contamination: %d\n",sum(f.cont))) 211 | print(colSums(f.cont.mtx==T)) 212 | adata <- adata[!f.cont] 213 | 214 | } 215 | 216 | 217 | 218 | tic("run.scanpy") 219 | obj.list <- run.scanpy(adata,out.prefix, 220 | gene.exclude.df=g.all.gene.ignore.df, 221 | n.top=opt.ntop, 222 | opt.res=opt.resolution, 223 | plot.rd=c("umap"), 224 | opt.npc=opt.npc,ncores=opt.ncores, 225 | res.test=opt.resTest, 226 | cor.var=opt.cor.var, 227 | use.harmony=opt.harmony, 228 | method.integration=opt.integration, 229 | specie=opt.specie, 230 | do.deg=opt.doDEG, 231 | ncell.deg=opt.ncell.deg, 232 | ###do.adj=T,do.scale=F, 233 | gene.mapping.table=gene.mapping.table) 234 | toc() 235 | 236 | 237 | -------------------------------------------------------------------------------- /inst/script/run.seurat3.basic.R: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env Rscript 2 | 3 | suppressPackageStartupMessages(library("argparse")) 4 | 5 | parser <- ArgumentParser() 6 | parser$add_argument("-a", "--aFile", type="character", required=TRUE, help="input seu file list") 7 | parser$add_argument("-b", "--bFile", type="character", required=TRUE, help="input sce file list") 8 | parser$add_argument("-o", "--outPrefix", type="character", required=TRUE, help="outPrefix") 9 | parser$add_argument("-q", "--specie", type="character", default="human", help="one of human, mouse [default %(default)s]") 10 | parser$add_argument("-c", "--stype", type="character", help="only analyze stype specified (default all)") 11 | parser$add_argument("-u", "--geneIDFile", type="character", help="gene id mapping file") 12 | ##parser$add_argument("-d", "--npc", type="integer",default=15L, help="[default %(default)s]") 13 | parser$add_argument("-d", "--npc", type="character",default="15", help="[default %(default)s]") 14 | parser$add_argument("-n", "--ncores", type="integer",default=16L, help="[default %(default)s]") 15 | parser$add_argument("-m", "--measurement",type="character",default="counts",help="[default %(default)s]") 16 | parser$add_argument("-r", "--resolution",type="character",default="2",help="[default %(default)s]") 17 | parser$add_argument("-t", "--scTransform",action="store_true",default=FALSE,help="[default %(default)s]") 18 | parser$add_argument("-y", "--harmony",action="store_true",default=FALSE,help="[default %(default)s]") 19 | parser$add_argument("-i", "--integration",type="character",help="[default %(default)s]") 20 | parser$add_argument("-g", "--deg",action="store_true",default=FALSE,help="[default %(default)s]") 21 | parser$add_argument("-w", "--ncellDEG",type="integer",default=1500, 22 | help="number of cells to downsample to for each group. used in DEG analysis. [default %(default)s]") 23 | parser$add_argument("-s", "--scale",action="store_true",default=FALSE,help="[default %(default)s]") 24 | parser$add_argument("-j", "--corVar", type="character", default="S.Score,G2M.Score,DIG.Score1,percent.mito,batchV", 25 | help="subset of S.Score,G2M.Score,DIG.Score1,ISG.Score1, or NULL. [default %(default)s]") 26 | parser$add_argument("-f", "--filterout",type="character",help="Format is COLUMN_ID:COLUMN_VAL_1,COLUMN_VAL_2,COLUMN_VAL_3. Filter out cells with COLUMN_ID in one of COLUMN_VAL_1, COLUMN_VAL_2, and COLUMN_VAL_3.") 27 | parser$add_argument("-k", "--keep",type="character",help="Format is COLUMN_ID:COLUMN_VAL_1,COLUMN_VAL_2,COLUMN_VAL_3. Keep only cells with COLUMN_ID in one of COLUMN_VAL_1, COLUMN_VAL_2, and COLUMN_VAL_3.") 28 | parser$add_argument("-x", "--removeContamination",type="character",help="comma separated string indicates subset of predefined signature (plasmaB, caf, epi, T, cd8, and mac) will be calculated and cells with high signature scores will be removed. For example, use plasmaB:0.75,caf:0.75,epi:0.75,T:0.25 for myeloid cell analysis. The numer after colon is the threshold") 29 | parser$add_argument("-p", "--platform",type="character",default="10X", 30 | help="platform such as 10X, SmartSeq2 [default %(default)s)]") 31 | args <- parser$parse_args() 32 | print(args) 33 | 34 | ############## tune parametrs ######## 35 | 36 | seu.file <- args$aFile 37 | sce.file <- args$bFile 38 | out.prefix <- args$outPrefix 39 | ###opt.npc <- args$npc 40 | opt.npc <- eval(parse(text = args$npc)) 41 | opt.ncores <- args$ncores 42 | opt.measurement <- args$measurement 43 | opt.platform <- args$platform 44 | opt.stype <- args$stype 45 | opt.resolution <- args$resolution 46 | opt.scTransform <- args$scTransform 47 | opt.harmony <- args$harmony 48 | opt.integration <- args$integration 49 | opt.doDEG <- args$deg 50 | opt.ncell.deg <- args$ncellDEG 51 | opt.scale <- args$scale 52 | opt.cor.var <- if(args$corVar=="") c("") else unlist(strsplit(args$corVar,",",perl=T)) 53 | opt.filterout <- args$filterout 54 | opt.keep <- args$keep 55 | opt.geneIDFile <- args$geneIDFile 56 | opt.removeContamination <- args$removeContamination 57 | opt.specie <- args$specie 58 | 59 | dir.create(dirname(out.prefix),F,T) 60 | 61 | saveRDS(args,file=sprintf("%s.args.rds",out.prefix)) 62 | ###args <- readRDS(file=sprintf("%s.args.rds",out.prefix)) 63 | 64 | ############## tune parametrs ######## 65 | suppressMessages(library("sscVis")) 66 | suppressMessages(library("sscClust")) 67 | suppressMessages(library("Seurat")) 68 | suppressMessages(library("tictoc")) 69 | suppressMessages(library("plyr")) 70 | suppressMessages(library("dplyr")) 71 | suppressMessages(library("tibble")) 72 | suppressMessages(library("doParallel")) 73 | suppressMessages(library("Matrix")) 74 | suppressMessages(library("data.table")) 75 | suppressMessages(library("R.utils")) 76 | suppressMessages(library("gplots")) 77 | suppressMessages(library("ggplot2")) 78 | suppressMessages(library("ggpubr")) 79 | suppressMessages(library("cowplot")) 80 | suppressMessages(library("limma")) 81 | suppressMessages(library("reticulate")) 82 | suppressMessages(library("scPip")) 83 | options(stringsAsFactors = FALSE) 84 | 85 | dat.ext.dir <- system.file("extdata",package="scPip") 86 | if(opt.specie=="human"){ 87 | ###gene.exclude.file <- sprintf("%s/exclude.gene.misc.human.v3.RData",dat.ext.dir) 88 | gene.exclude.file <- sprintf("%s/exclude.gene.misc.human.v4.RData",dat.ext.dir) 89 | }else if(opt.specie=="mouse"){ 90 | ###gene.exclude.file <- sprintf("%s/exclude.gene.misc.mouse.v3.RData",dat.ext.dir) 91 | gene.exclude.file <- sprintf("%s/exclude.gene.misc.mouse.v4.RData",dat.ext.dir) 92 | }else{ 93 | gene.exclude.file <- NULL 94 | } 95 | 96 | if(!is.null(gene.exclude.file)){ 97 | env.misc <- loadToEnv(gene.exclude.file) 98 | g.all.gene.ignore.df <- env.misc$all.gene.ignore.df 99 | g.all.gene.ignore.df %>% head 100 | }else{ 101 | g.all.gene.ignore.df <- NULL 102 | } 103 | 104 | ###################### 105 | 106 | gene.mapping.table <- NULL 107 | if(!is.null(opt.geneIDFile) && file.exists(opt.geneIDFile) && grepl("\\.rds$",opt.geneIDFile,perl=T)){ 108 | gene.mapping.table <- readRDS(opt.geneIDFile) 109 | } 110 | 111 | seu <- NULL 112 | sce <- NULL 113 | 114 | if(seu.file!="-" && file.exists(seu.file)){ 115 | if(grepl("\\.rds$",seu.file)){ 116 | seu <- readRDS(seu.file) 117 | }else{ 118 | env.a <- loadToEnv(seu.file) 119 | obj.name.a <- names(env.a)[1] 120 | seu <- env.a[[obj.name.a]] 121 | rm(env.a) 122 | } 123 | } 124 | if(sce.file!="-" && file.exists(sce.file)){ 125 | if(grepl("\\.rds$",sce.file)){ 126 | sce <- readRDS(sce.file) 127 | }else{ 128 | env.b <- loadToEnv(sce.file) 129 | obj.name.b <- names(env.b)[1] 130 | sce <- env.b[[obj.name.b]] 131 | rm(env.b) 132 | } 133 | } 134 | 135 | if(!is.null(seu) && !is.null(opt.stype)){ 136 | seu <- seu[,seu$stype==opt.stype] 137 | } 138 | 139 | if(!is.null(seu) && "percent.mito" %in% colnames(seu[[]])){ 140 | if(max(seu$percent.mito) <1){ 141 | seu <- subset(seu, subset = percent.mito<0.1) 142 | }else{ 143 | seu <- subset(seu, subset = percent.mito<10) 144 | } 145 | } 146 | 147 | ##### check & clean sce ##### 148 | if(!is.null(sce) && "percent.mito" %in% colnames(colData(sce))){ 149 | if(all(is.na(sce$percent.mito))){ 150 | sce$percent.mito <- NULL 151 | } 152 | } 153 | 154 | if(!is.null(sce) && !("seu.id" %in% colnames(rowData(sce)))){ 155 | rowData(sce)[["seu.id"]] <- gsub("_","-",rowData(sce)[["display.name"]]) 156 | } 157 | 158 | if(!is.null(sce) && ("libraryID" %in% colnames(colData(sce))) && all(is.na(sce$libraryID))){ 159 | sce$libraryID <- "Unk" 160 | } 161 | 162 | 163 | 164 | if(!is.null(seu) && !is.null(opt.filterout)){ 165 | if(!file.exists(opt.filterout)){ 166 | col.filter <- unlist(strsplit(opt.filterout,":"))[1] 167 | col.value <- unlist(strsplit(unlist(strsplit(opt.filterout,":"))[2],",")) 168 | if(col.filter %in% colnames(seu[[]])){ 169 | cat(sprintf("filter cells with %s in c(%s)\n",col.filter,paste(col.value,collapse=","))) 170 | f.cell <- seu[[]][,col.filter] %in% col.value 171 | print(summary(f.cell)) 172 | seu <- seu[,!f.cell] 173 | }else{ 174 | warning(sprintf("The meta-data doesnot contain %s\n",col.filter)) 175 | } 176 | } 177 | } 178 | 179 | if(!is.null(opt.keep)){ 180 | col.keep <- unlist(strsplit(opt.keep,":"))[1] 181 | col.value <- unlist(strsplit(unlist(strsplit(opt.keep,":"))[2],",")) 182 | if(!file.exists(opt.keep)){ 183 | if(!is.null(seu)){ 184 | if(col.keep %in% colnames(seu[[]])){ 185 | cat(sprintf("keep only cells with %s in c(%s)\n",col.keep,paste(col.value,collapse=","))) 186 | f.cell <- seu[[]][,col.keep] %in% col.value 187 | print(summary(f.cell)) 188 | seu <- seu[,f.cell] 189 | }else{ 190 | warning(sprintf("The meta-data doesnot contain %s\n",col.keep)) 191 | } 192 | }else if(!is.null(sce)){ 193 | if(col.keep %in% colnames(colData(sce))){ 194 | cat(sprintf("keep only cells with %s in c(%s)\n",col.keep,paste(col.value,collapse=","))) 195 | f.cell <- colData(sce)[,col.keep] %in% col.value 196 | print(summary(f.cell)) 197 | sce <- sce[,f.cell] 198 | }else{ 199 | warning(sprintf("The meta-data doesnot contain %s\n",col.keep)) 200 | } 201 | } 202 | } 203 | } 204 | 205 | if(!is.null(opt.removeContamination)){ 206 | ### opt.removeContamination <- "plasmaB:0.75,caf:0.75,epi:0.75,T:0.25" 207 | 208 | g.cont.gene.list <- list("plasmaB"=c("JCHAIN"), 209 | "B"=c("CD79A","MS4A1"), 210 | "caf"=c("COL1A2", "COL1A1", "COL3A1","LUM"), 211 | "epi"=c("KRT18","KRT19","EPCAM"), 212 | "T"=c("CD3D","CD3G"), 213 | "cd8"=c("CD8A","CD8B"), 214 | "mac"=c("LYZ","C1QA","C1QB","CD68")) 215 | 216 | sig.vec <- unlist(strsplit(opt.removeContamination,",")) 217 | sig.name <- unname(sapply(sig.vec,function(x){ unlist(strsplit(x,":"))[1] })) 218 | sig.thre <- unname(sapply(sig.vec,function(x){ as.numeric(unlist(strsplit(x,":"))[2]) })) 219 | 220 | for(i in seq_along(sig.name)){ 221 | loginfo(sprintf("calculate signature score of %s cells ...",sig.name[i])) 222 | seu <- fill.contamination(seu,out.prefix, 223 | g.name=sig.name[i], 224 | g.test=g.cont.gene.list[[sig.name[i]]], 225 | score.t=sig.thre[i], 226 | vis.v=c(0.25,0.5,0.75,1)) 227 | } 228 | 229 | idx.sig.class <- intersect(sprintf("%s.class",sig.name),colnames(seu[[]])) 230 | f.cont.mtx <- seu[[]][,idx.sig.class,drop=F] 231 | f.cont <- rowSums(f.cont.mtx) > 0 232 | loginfo(sprintf("A total number of potential contamination: %d\n",sum(f.cont))) 233 | print(colSums(f.cont.mtx==T)) 234 | seu <- seu[,!f.cont] 235 | 236 | } 237 | 238 | if(!is.null(seu) && !is.null(sce)){ 239 | f.cell <- intersect(colnames(seu),colnames(sce)) 240 | seu <- seu[,f.cell] 241 | sce <- sce[,colnames(seu)] 242 | } 243 | 244 | tic("run.Seurat3") 245 | obj.list <- run.Seurat3(seu,sce,out.prefix, 246 | gene.exclude.df=g.all.gene.ignore.df, 247 | n.top=1500, 248 | measurement=opt.measurement,platform=opt.platform, 249 | use.sctransform=opt.scTransform, 250 | use.harmony=opt.harmony, 251 | method.integration=opt.integration, 252 | do.deg=opt.doDEG, 253 | ncell.deg=opt.ncell.deg, 254 | gene.mapping.table=gene.mapping.table, 255 | ###do.adj=T,do.scale=F, 256 | cor.var=opt.cor.var, 257 | do.scale=opt.scale, 258 | plot.rd=c("umap"), 259 | opt.res=opt.resolution, 260 | opt.npc=opt.npc,ncores=opt.ncores) 261 | toc() 262 | 263 | 264 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------