Skip to content

Commit

Permalink
Update to seurat v5 nomenclature with layers replacing slots. Breaks …
Browse files Browse the repository at this point in the history
…compatibility with Seurat v4.
  • Loading branch information
nbroguiere committed Dec 7, 2023
1 parent b6db129 commit cbd9053
Show file tree
Hide file tree
Showing 33 changed files with 128 additions and 128 deletions.
2 changes: 1 addition & 1 deletion R/AnnotateWithVEP.R
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
#' MyGenotype <- AnnotateWithVEP(MyGenotype,MyVepDataFrame,min.impact="HIGH",avoid_underscores=TRUE)
#' @export

AnnotateWithVEP <- function(genotype,vep,min_impact="MODERATE",avoid_underscores=TRUE){
AnnotateWithVEP <- function(genotype, vep, min_impact="MODERATE", avoid_underscores=TRUE){
vep2 <- vep[vep$Uploaded_variation %in% genotype@metadata$VEP_ID,c("Uploaded_variation","Location","Allele","Gene","SYMBOL","IMPACT","Consequence","Protein_position","Amino_acids","CLIN_SIG")]
annotations <- data.frame(VEP_ID=genotype@metadata$VEP_ID, symbol="-",gene_ensembl_id="-",impact="-",protein_position="-",aminoacids="-", consequence="-", clinicalsign="-",summary="-",short_description="-", row.names=genotype@metadata$UNIQUE_ID)
annotations$impact <- factor(annotations$impact,levels=c("-","MODIFIER","LOW","MODERATE","HIGH"),ordered = T)
Expand Down
2 changes: 1 addition & 1 deletion R/AnnotatedVariableFeaturePlot.R
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
# # Annotate only a subset of the most variable genes:
#' AnnotatedVariableFeaturePlot(SeuratObject,500)

AnnotatedVariableFeaturePlot <- function(object, which.labels=NA, pt.size=1, text.size=2.5, log=NULL, xnudge=0, ynudge=0, colors=c("Black","Cyan"),selection.method=NULL, assay=NULL){
AnnotatedVariableFeaturePlot <- function(object, which.labels=NA, pt.size=1, text.size=2.5, log=NULL, xnudge=0, ynudge=0, colors=c("Black","Cyan"), selection.method=NULL, assay=NULL){
if(sum(is.na(which.labels))){
points <- VariableFeatures(object,assay = assay)
}else if(is.vector(which.labels,mode="numeric")){
Expand Down
8 changes: 4 additions & 4 deletions R/CellSimilarityToGenotypes.R
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,15 @@
#' @param prefix character(1). A prefix appended to the genotype names to generate the feature names in the similarity assay (Default: "Similarity-").
#' @param features.use character(n). The features (i.e. variants) to be used for the similarity calculations. Can be a vector of variants by name, or NA to use informative variants if available, or "all" (Default: "all").
#' @param assays character(3). The name of the assays within the Seurat object that contain the variant calls (sparse matrix with values 1,2,3 in vartrix conventions), and counts of reference and alt alleles (Default: c("VAR","REF","ALT")).
#' @param slots. The slots to use within the assays above (Default: c("data","data","data")).
#' @param layers The layers to use within the assays above (Default: c("data","data","data")).
#' @return Returns the Seurat object
#' @keywords compute cell similarity genotype fraction matching variants
#' @examples
#' MySeuratObject <- CellSimilarityToGenotypes(MySeuratObject,MyGenotypes)
#' DefaultAssay(MySeuratObject) <- "similarity"
#' FeaturePlot(MySeuratObject,"Similarity-MyGenotypeName1")
#' @export
CellSimilarityToGenotypes <- function(seurat, genotype, assay.name="similarity", prefix="Similarity-", features.use="all", assays=c("VAR","REF","ALT"), slots=c("data","data","data")){
CellSimilarityToGenotypes <- function(seurat, genotype, assay.name="similarity", prefix="Similarity-", features.use="all", assays=c("VAR","REF","ALT"), layers=c("data","data","data")){
# Choose the features on which the similarity is computed (default: informative variants. If not present, all variants)
if(is.na(features.use[1])){
if(length(VariableFeatures(seurat[[assays[1]]]))){
Expand All @@ -43,8 +43,8 @@ CellSimilarityToGenotypes <- function(seurat, genotype, assay.name="similarity",
features.use <- intersect(features.use,rownames(seurat[[assays[1]]]))
cat("Number of variants remaining:",length(features.use),"\n")
}
tmp0 <- Matrix::t(GetAssayData(seurat, assay = assays[1], slot = slots[1])[features.use,])
cvg0 <- Matrix::t(GetAssayData(seurat, assay = assays[2], slot = slots[2])[features.use,]+GetAssayData(seurat, assay = assays[3], slot = slots[3])[features.use,])
tmp0 <- Matrix::t(GetAssayData(seurat, assay = assays[1], layer = layers[1])[features.use,])
cvg0 <- Matrix::t(GetAssayData(seurat, assay = assays[2], layer = layers[2])[features.use,] + GetAssayData(seurat, assay = assays[3], layer = layers[3])[features.use,])
tmp1 <- Matrix::t(genotype[features.use,])

# # Previous simple version - perfect match only:
Expand Down
8 changes: 4 additions & 4 deletions R/Classify.R
Original file line number Diff line number Diff line change
Expand Up @@ -12,21 +12,21 @@
#' @param metadata.name character(1). The name of the new metadata column where cell type annotations are stored (Default: celltype)
#' @param cell.names character(n). Give only if the signature names should not be used as celltypes names, but rather be replaced by these cell names.
#' @param assay character(1). If some signatures used for classification are stored as assay features, which assay should be used in priority (Default: DefaultAssay(object)).
#' @param slot character(1). If some signatures used for classification are stored as assay features, which slot should be used (Default: "data").
#' @param layer character(1). If some signatures used for classification are stored as assay features, which layer should be used (Default: "data").
#' @param restrict.ident character(1). The name of a metadata column containing celltype annotations, which will be used to define the subset of cells that should be classified. Default: "Default", which uses current default, i.e. Idents(object).
#' @param restrict.to character(n). Which celltypes (as defined in the restrict.ident metadata column) should be classified. Default: All cells.
#' @param by.clusters character(1) or character(n) or factor(n). If not NULL, clusters instead of single cells will be classified. The parameter should indicate the name of a metadata column containing the clusters to consider (e.g. "seurat_clusters"), or the actual cluster info (e.g. object$seurat_clusters).
#' @return A Seurat object with an additional metadata column containing the cell type annotations and Idents() set to these annotations.
#' @keywords Cell type classification celltype Classifier
#' @export
#' @examples
#' # After MySeuratObject has been log-normalized in order to contain an RNA>data assay>slot and been augmented with a percent.mito metadata column:
#' # After MySeuratObject has been log-normalized in order to contain an RNA>data assay>layer and been augmented with a percent.mito metadata column:
#' # SignatureList should be a list of character vectors, each containing a series of feature/gene names. In this example, the signatures correspond to cell types, and the name of each signature is the name of the corresponding cell type (e.g. Tcell, Bcell, EpithelialCell, Fibroblasts, etc).
#' MySeuratObject <- Impute(MySeuratObject)
#' MySeuratObject <- ScoreSignatures(MySeuratObject,SignatureList)
#' MySeuratObject <- Classify(MySeuratObject,SignatureList) # Automatic annotation based on cell type signatures, stored in metadata column "celltype".

Classify <- function(object, signatures, expected.values=NA, metadata.name="celltype", cell.names=NA, assay=DefaultAssay(object), slot="data", restrict.ident="Default", restrict.to=as.character(unique(Idents(object))), by.clusters=NULL){
Classify <- function(object, signatures, expected.values=NA, metadata.name="celltype", cell.names=NA, assay=DefaultAssay(object), layer="data", restrict.ident="Default", restrict.to=as.character(unique(Idents(object))), by.clusters=NULL){

# Check that the idents requested for restriction are correct
if(length(restrict.ident) != 1){
Expand Down Expand Up @@ -86,7 +86,7 @@ Classify <- function(object, signatures, expected.values=NA, metadata.name="cell
}

# Create a df with the signatures and features to be used:
df <- GatherFeatures(object, sign.names, assay=assay, slot=slot)
df <- GatherFeatures(object, sign.names, assay=assay, layer=layer)
df <- df[cells.use,,drop=F]
if(!ncol(df)){
warning("None of the requested features/signatures were found. Did you forget to run Impute and/or ScoreSignatures?")
Expand Down
8 changes: 4 additions & 4 deletions R/ClassifyManual.R
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
#' @param gates charater(1). Gate definitions, with gates for various cell types delimited by commas (,). For each gate, the name of the cell type is given first, followed by equal (=) and a series of gates separated by AND symbol (&). Example: "celltype_a = sign_a > value_aa & sign_b < value_ab, celltype_b = sign_b > value_ba & sign_a < value_ab" where sign_a and sign_b are the names of metadata columns and value_xy are numeric values.
#' @param metadata.name The name of the new metadata column where cell type annotations are stored (Default: celltype)
#' @param assay character(1). If some signatures used for classification are stored as assay features, which assay should be used in priority (Default: DefaultAssay(object)).
#' @param slot character(1). If some signatures used for classification are stored as assay features, which slot should be used (Default: "data").
#' @param layer character(1). If some signatures used for classification are stored as assay features, which layer should be used (Default: "data").
#' @param restrict.ident character(1). The name of a metadata column containing celltype annotations, which will be used to define the subset of cells that should be classified. Default: current Idents(object).
#' @param restrict.to character(n). Which celltypes (as defined in the restrict.ident metadata column) should be classified. Default: All cells.
#' @param unclassified.name character(1). Which name should be given to the cells which do not pass any gate. Can be set to "keep" to keep the existing names for cells which don't pass any gate. Default: "None".
Expand All @@ -26,7 +26,7 @@
#' @keywords Cell type classification celltype Classifier manual gates gating
#' @export
#' @examples
#' # MySeuratObject should contain an RNA slot with log-normalized data assay.
#' # MySeuratObject should contain an RNA layer with log-normalized data assay.
#' # In this example cells are classified as T cells (TC) or Epithelial cells (EP) based on manual signatures.
#' # Note that cells that validate no gate will have cell type "None", and cells which validate several will be classified as "Multiplets".
#' # It's recommended to first do a signature scatter plot in order to choose threshold values for the gates.
Expand All @@ -44,7 +44,7 @@
#' # Mark dividing cells by adding a suffix to their cell names:
#' MySeuratObject <- ClassifyManual(MySeuratObject, gates="Dividing = PCNA > 1 & MKI67 > 1", naming.mode = "suffix", unclassified.name="")

ClassifyManual <- function(object, gates, metadata.name="celltype", assay=DefaultAssay(object), slot="data", restrict.ident="Default", restrict.to=as.character(unique(Idents(object))), unclassified.name="None", naming.mode="replace"){
ClassifyManual <- function(object, gates, metadata.name="celltype", assay=DefaultAssay(object), layer="data", restrict.ident="Default", restrict.to=as.character(unique(Idents(object))), unclassified.name="None", naming.mode="replace"){

# Check that the requested Idents to use are correct
if(!length(restrict.ident)){
Expand Down Expand Up @@ -95,7 +95,7 @@ ClassifyManual <- function(object, gates, metadata.name="celltype", assay=Defaul

# Create a df with the signatures and features to be used:
unique.signatures.needed <- unique(unlist(lapply(strsplit(unlist(subgates),"<|>"),"[",1)))
df <- GatherFeatures(object, unique.signatures.needed, assay=assay, slot=slot)
df <- GatherFeatures(object, unique.signatures.needed, assay=assay, layer=layer)
df <- df[cells.use,,drop=F]
if(!ncol(df)){
warning("None of the requested features/signatures were found. Did you forget to run Impute and/or ScoreSignatures?")
Expand Down
4 changes: 2 additions & 2 deletions R/ComputeMitoContent.R
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@ ComputeMitoContent <- function(object, name = "percent.mito", as.percent = TRUE)
return(object)
}else{
if(n_hu>n_mm){
mito.content <- Matrix::colSums(GetAssayData(object[human_mito_genes, ],"counts",assay="RNA"))/Matrix::colSums(GetAssayData(object,"counts",assay="RNA"))
mito.content <- Matrix::colSums(GetAssayData(object[human_mito_genes, ],"counts", layer="RNA"))/Matrix::colSums(GetAssayData(object,"counts", layer="RNA"))
}else{
mito.content <- Matrix::colSums(GetAssayData(object[mouse_mito_genes, ],"counts",assay="RNA"))/Matrix::colSums(GetAssayData(object,"counts",assay="RNA"))
mito.content <- Matrix::colSums(GetAssayData(object[mouse_mito_genes, ],"counts", layer="RNA"))/Matrix::colSums(GetAssayData(object,"counts", layer="RNA"))
}
if(as.percent){
mito.content <- 100*mito.content
Expand Down
4 changes: 2 additions & 2 deletions R/CreateGenotypeObject.R
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
#' @export
CreateGenotypeObject <- function(matrix=NULL, metadata=NULL, vartrix=list(), variants=NULL, ...){
if(is.null(variants)){
if(!dplyr::setequal(rownames(matrix),rownames(metadata))){
if(!dplyr::setequal(rownames(matrix), rownames(metadata))){
warning("The row names in the matrix and metadata do not match, and list of variants is not given. Aborting.")
}else{
variants <- rownames(matrix)
Expand All @@ -37,5 +37,5 @@ CreateGenotypeObject <- function(matrix=NULL, metadata=NULL, vartrix=list(), var
if(!is.null(matrix)) rownames(matrix) <- variants
if(!is.null(metadata)) rownames(metadata) <- variants
if(length(vartrix)) rownames(vartrix) <- variants
return(GenotypeObject(matrix=matrix,metadata=metadata,vartrix=vartrix,variants=variants))
return(GenotypeObject(matrix=matrix, metadata=metadata, vartrix=vartrix, variants=variants))
}
10 changes: 5 additions & 5 deletions R/CrossImpute.R
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,14 @@
#' @param knn integer(1). Number of nearest neighbors on which to compute bandiwth imputation.
#' @param t integer(1). Diffusion parameter passed to MAGIC.
#' @param n.jobs integer(1). Number of threads on which to run the imputation (Default: 6).
#' @param slot.use character(1). Name of the slot to impute (Default: "data").
#' @return Seurat object with an additional slot containing MAGIC cross-imputed data.
#' @param layer.use character(1). Name of the layer to impute (Default: "data").
#' @return Seurat object with an additional layer containing MAGIC cross-imputed data.
#' @keywords MAGIC Rmagic imputation crossimputation cross-imputation
#' @export
#' @examples
#' MySeuratObject <- CrossImpute(MySeuratObject,"other_assay_to_impute_based_on_RNA_distances")
#' MySeuratObject[["imputed-RNA"]] # Check result
CrossImpute <- function(object, impute.assay=DefaultAssay(object), name=paste0("imputed.",impute.assay), impute.features="all", reference.assay="RNA", reference.features="variable_features", npca=40, knn=3, t=2, n.jobs=6, slot.use="data"){
CrossImpute <- function(object, impute.assay=DefaultAssay(object), name=paste0("imputed.",impute.assay), impute.features="all", reference.assay="RNA", reference.features="variable_features", npca=40, knn=3, t=2, n.jobs=6, layer.use="data"){

if(!"Rmagic" %in% rownames(installed.packages())){
stop('Rmagic is not installed, but needed for imputations. Consider running: devtools::install_github("cran/Rmagic"). The python version magic-impute is also needed, see install instructions at https://github.com/cran/Rmagic.')
Expand Down Expand Up @@ -63,7 +63,7 @@ CrossImpute <- function(object, impute.assay=DefaultAssay(object), name=paste0("
warning("No features to impute available, aborting.")
return(object)
}else{
df <- t(as.matrix(GetAssayData(object = object, slot = slot.use)[impute.features,,drop=F]))
df <- t(as.matrix(GetAssayData(object = object, layer = layer.use)[impute.features,,drop=F]))
}
}

Expand All @@ -83,7 +83,7 @@ CrossImpute <- function(object, impute.assay=DefaultAssay(object), name=paste0("
warning("No reference features available, aborting.")
return(object)
}else{
df <- cbind(df,t(as.matrix(GetAssayData(object = object, slot = slot.use)[reference.features,,drop=F])))
df <- cbind(df,t(as.matrix(GetAssayData(object = object, layer = layer.use)[reference.features,,drop=F])))
}

imputed <- Rmagic::magic(data = as.matrix(df), npca=npca, knn=knn, t=t, n.jobs=n.jobs)
Expand Down
8 changes: 4 additions & 4 deletions R/Export10X.R
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
#' @param cols character(1). Name of the exported file that lists column names. Default: barcodes.tsv
#' @param counts character(1). Name of the exported file that contains the sparse raw count matrix. Default: matrix.mtx
#' @param meta character(1). Name of the exported file that contains the metadata. Default: metadata.tsv
#' @param slot character(1). Name of the slot in the Seurat object from which the count matrix is exported. Default: counts
#' @param layer character(1). Name of the layer in the Seurat object from which the count matrix is exported. Default: counts
#' @param assay character(1). Name of the assay in the Seurat object from which the count matrix is exported. Default: RNA
#' @keywords Reexport export 10X
#' @export
Expand All @@ -21,12 +21,12 @@
#' # Include only two custom metadata columns, two dimensionality reductions, and do not compress the matrices.
#' Export10X(SeuratObject, "MyDir", c("nFeature_RNA", "mito.content"), c("pca","umap"), gzip=FALSE)
#' # Export normalized CiteSeq data rather than raw RNA counts, and no metadata:
#' Export10X(SeuratObject, "MyDir", meta_columns = c(), slot="data", assay="CiteSeq")
Export10X <- function(object, dir, meta_columns = "all", append_reductions = "all", gzip=T, rows = "features.tsv", cols = "barcodes.tsv", counts = "matrix.mtx", meta = "metadata.tsv", slot="counts", assay="RNA"){
#' Export10X(SeuratObject, "MyDir", meta_columns = c(), layer="data", assay="CiteSeq")
Export10X <- function(object, dir, meta_columns = "all", append_reductions = "all", gzip=T, rows = "features.tsv", cols = "barcodes.tsv", counts = "matrix.mtx", meta = "metadata.tsv", layer="counts", assay="RNA"){
dir.backup <- getwd()
if(!dir.exists(dir)){dir.create(dir)}
setwd(dir)
data.tmp <- GetAssayData(object = object, slot = slot, assay = assay)
data.tmp <- GetAssayData(object = object, layer = layer, assay = assay)
write(colnames(data.tmp), file = cols)
write(rownames(data.tmp), file = rows)
if(length(meta_columns)){
Expand Down
Loading

0 comments on commit cbd9053

Please sign in to comment.