core.R 226 KB
Newer Older
Christian Arnold's avatar
Christian Arnold committed
1
2
######## Init GRN ########

3
4
5
#' Initialize a \code{\linkS4class{GRN}} object
#' 
#' @export
6
#' @param objectMetadata List. Default list(). Optional (named) list with an arbitrary number of elements, all of which capture metadata for the object. This is mainly used to distinguish GRN objects from one another by storing object-specific metadata along with the data.
Christian Arnold's avatar
Christian Arnold committed
7
#' @param outputFolder Absolute file path. No default. Default output folder where all pipeline output will be put unless specified otherwise. We recommend specifying an absolute path.
8
#' @param genomeAssembly Character. No default. The genome assembly of all data that to be used within this object. Currently, supported genomes are: \code{hg19}, \code{hg38}, and \code{mm10}
9
#' @return Empty \code{\linkS4class{GRN}} object
Christian Arnold's avatar
Christian Arnold committed
10
11
12
#' @examples 
#' GRN = GRN::initializeGRN(objectMetadata = objectMetadata.l, outputFolder = "output", genomeAssembly = "hg38")
#' @export
13
initializeGRN <- function(objectMetadata = list(),
14
                          outputFolder, 
15
                          genomeAssembly) {
16

17
  checkmate::assert(checkmate::checkNull(objectMetadata), checkmate::checkList(objectMetadata))
Christian Arnold's avatar
Christian Arnold committed
18
  checkmate::assertSubset(genomeAssembly, c("hg19","hg38", "mm10"))
19
20

  # Create the folder first if not yet existing
21
22
23
  if (!dir.exists(outputFolder)) {
    dir.create(outputFolder)
  }
24
25
  # Create an absolute path out of the given outputFolder now that it exists
  outputFolder = tools::file_path_as_absolute(outputFolder)
26
  checkmate::assertDirectory(outputFolder, access = "w")
27
28
29
30
31
32
33
  
  if (!endsWith(outputFolder, "/")) {
    outputFolder = paste0(outputFolder, "/")
  }
  
  
  dir_output_plots = paste0(outputFolder, "plots/")
34
35
36
  if (!dir.exists(dir_output_plots)) {
    dir.create(dir_output_plots)
  }
37
  
38
  GRN = .createGRNObject()
39
40
41
  GRN@config$functionParameters = list()
  
  GRN = .addFunctionLogToObject(GRN)
42
  
43
  GRN@config$isFiltered = FALSE
44

45
46
47
  par.l = list()
  
  packageName = utils::packageName()
48
  par.l$packageVersion = ifelse(is.null(packageName), NA, paste0(utils::packageVersion(packageName)[[1]], collapse = "."))
49
50
  par.l$genomeAssembly = genomeAssembly
  
51
52
  .checkAndInstallMissingPackages(.checkAndLoadPackagesGenomeAssembly(genomeAssembly))
  
53
54
55
56
57
58
  # Make an internal subslot
  par.l$internal = list()
  
  # Recommended to leave at 1, more permutations are currently not necessary
  par.l$internal$nPermutations = 1 
  
59
  # Step size for the TF-peak FDR calculation
60
  par.l$internal$stepsFDR = round(seq(from = -1, to = 1, by = 0.05),2)
61
62
  
  # Stringencies for AR classification
63
  par.l$internal$allClassificationThresholds = c(0.1, 0.05, 0.01, 0.001)
64
65
  
  # Minimum number of TFBS to include a TF in the heatmap
66
  par.l$internal$threshold_minNoTFBS_heatmap = 100
67
68
  
  # Colors for the different classifications
69
  par.l$internal$colorCategories = c("activator" = "#4daf4a", "undetermined" = "black", "repressor" = "#e41a1c", "not-expressed" = "Snow3") # diverging, modified
70
71
  
  
72
  GRN@config$parameters = par.l
73
  GRN@config$metadata = objectMetadata
74
75
76
  
  
  # OUTPUT
77
78
79
  GRN@config$directories$outputRoot         = outputFolder
  GRN@config$directories$output_plots       = dir_output_plots 
  GRN@config$files$output_log               = paste0(outputFolder, "GRN.log")
80

81
82
  .testExistanceAndCreateDirectoriesRecursively(c(outputFolder, dir_output_plots))
  
83
  checkmate::assertDirectory(outputFolder, access = "w")
84
85
  
  
86
  .startLogger(GRN@config$files$output_log , "INFO",  removeOldLog = FALSE)
87
88
  #.printParametersLog(par.l)
  
89
90
  futile.logger::flog.info(paste0("Empty GRN object created successfully. Type the object name (e.g., GRN) to retrieve summary information about it at any time."))
  
91
92
93
94
  
  GRN
}

Christian Arnold's avatar
Christian Arnold committed
95
96
######## Add and filter data ########

97
98
99
100
#' Add data to a \code{\linkS4class{GRN}} object
#' 
#' @export
#' @template GRN 
101
102
103
104
105
106
#' @param counts_peaks Data frame. No default. Counts for the peaks, with raw or normalized counts for each peak (rows) across all samples (columns). In addition to the count data, it must also contain one ID column with a particular format, see the argument *idColumn_peaks* below. Row names are ignored, column names must be set to the sample names and must match those from the RNA counts and the sample metadata table.
#' @param normalization_peaks Character. Default "DESeq_sizeFactor". Normalization procedure for peak data. Must be one of "DESeq_sizeFactor", "none", or "quantile"
#' @param idColumn_peaks Character. Default "peakID". Name of the column in the counts_peaks data frame that contains peak IDs. The required format must be "{chr}:{start}-{end}", with {chr} denoting the abbreviated chromosome name, and {start} and {end} the begin and end of the peak coordinates, respectively. End must be bigger than start. Examples for valid peak IDs are chr1:400-800 or chrX:20-25.
#' @param counts_rna Data frame. No default. Counts for the RNA-seq data, with raw or normalized counts for each gene (rows) across all samples (columns). In addition to the count data, it must also contain one ID column with a particular format, see the argument *idColumn_rna* below. Row names are ignored, column names must be set to the sample names and must match those from the RNA counts and the sample metadata table.
#' @param normalization_rna Character. Default "quantile". Normalization procedure for peak data. Must be one of "DESeq_sizeFactor", "none", or "quantile"
#' @param idColumn_RNA Character. Default "ENSEMBL". Name of the column in the counts_rna data frame that contains Ensembl IDs.
107
#' @param sampleMetadata Data frame. Default NULL. Optional, additional metadata for the samples, such as age, sex, gender etc. If provided, the @seealso [plotPCA_all()] function can then incorporate and plot it. Sample names must match with those from both peak and RNA-Seq data. The first column is expected to contain the sample IDs, the actual column name is irrelevant.
Christian Arnold's avatar
Christian Arnold committed
108
#' @param allowOverlappingPeaks TRUE or FALSE. Default \code{FALSE}. Should overlapping peaks be allowed (then only a warning is issued when overlapping peaks are found) or (the default) should an error be raised?
109
#' @template forceRerun
110
#' @return The same \code{\linkS4class{GRN}} object, with added data from this function.
Christian Arnold's avatar
Christian Arnold committed
111
112
#' @examples 
#' GRN = addData(GRN, countsPeaks.df, normalization_peaks = "DESeq_sizeFactor", idColumn_peaks = idColumn_peaks, countsRNA.df, normalization_rna = "quantile", idColumn_RNA = idColumn_RNA, sampleMetadata = sampleMetadata.df, forceRerun = TRUE)
113
114
addData <- function(GRN, counts_peaks, normalization_peaks = "DESeq_sizeFactor", idColumn_peaks = "peakID", 
                    counts_rna, normalization_rna = "quantile", idColumn_RNA = "ENSEMBL", sampleMetadata = NULL,
Christian Arnold's avatar
Christian Arnold committed
115
                    allowOverlappingPeaks= FALSE,
116
                    forceRerun = FALSE) {
117
118

  GRN = .addFunctionLogToObject(GRN)      
119
  
120
121
  checkmate::assertClass(GRN, "GRN")
  checkmate::assertDataFrame(counts_peaks, min.rows = 1, min.cols = 2)
122
  checkmate::assertDataFrame(counts_rna, min.rows = 1, min.cols = 2)
123
  checkmate::assertCharacter(idColumn_peaks, min.chars = 1, len = 1)
124
  checkmate::assertCharacter(idColumn_RNA, min.chars = 1, len = 1)
125
  checkmate::assertChoice(normalization_peaks, c("none", "DESeq_sizeFactor", "quantile"))
126
127
128
  checkmate::assertChoice(normalization_rna, c("none", "DESeq_sizeFactor", "quantile"))  
  checkmate::assertFlag(forceRerun)
  
129
  if (is.null(GRN@data$peaks$counts_norm) |
130
      is.null(GRN@data$RNA$counts_norm.l) | 
131
      forceRerun) {
132
    
133
134
135
    # Store raw peaks counts as DESeq object

    #GRN@data$peaks$counts_raw = counts_peaks %>% dplyr::mutate(isFiltered = FALSE)
136
137
    
    # Normalize ID column names
138
139
    if (idColumn_peaks != "peakID") {
      counts_peaks = dplyr::rename(counts_peaks, peakID = !!(idColumn_peaks))
140
141
    }
    if (idColumn_RNA != "ENSEMBL") {
142
      counts_rna = dplyr::rename(counts_rna, ENSEMBL = !!(idColumn_RNA))
143
    }
Christian Arnold's avatar
Christian Arnold committed
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
      
    # Check ID columns for missing values and remove
    rna_missing_ID =  which(is.na(counts_rna$ENSEMBL))
    if (length(rna_missing_ID) > 0) {
        message = paste0(" Found ", length(rna_missing_ID), " missing IDs in the ID column of the RNA counts. These rows will be removed.")
        .checkAndLogWarningsAndErrors(NULL, message, isWarning = TRUE)
        counts_rna = dplyr::slice(counts_rna, -rna_missing_ID)
    }
    
    peaks_missing_ID =  which(is.na(counts_peaks$peakID))
    if (length(peaks_missing_ID) > 0) {
        message = paste0(" Found ", length(peaks_missing_ID), " missing IDs in the ID column of the peaks counts. These rows will be removed.")
        .checkAndLogWarningsAndErrors(NULL, message, isWarning = TRUE)
        counts_peaks = dplyr::slice(counts_peaks, -peaks_missing_ID)
    }
    
      
    # Remove potential scientific notation from peak IDs
    peaks_eNotation = which(grepl("e+", counts_peaks$peakID))
    if (length(peaks_eNotation) > 0) {
        message = paste0("Found at least one peak (", paste0(counts_peaks$peakID[peaks_eNotation], collapse = ",") , ") for which the position contains the scientific notation, attempting to fix.")
        .checkAndLogWarningsAndErrors(NULL, message, isWarning = TRUE)
        counts_peaks$peakID[peaks_eNotation] = .removeScientificNotation_positions(counts_peaks$peakID[peaks_eNotation])
   
        
    }
170
    
171
172
173
174
175
176
    # Clean Ensembl IDs
    counts_rna$ENSEMBL = gsub("\\..+", "", counts_rna$ENSEMBL, perl = TRUE)
    
    # Check uniqueness of IDs
    nDuplicateRows = nrow(counts_rna) - length(unique(counts_rna$ENSEMBL))
    if (nDuplicateRows > 0) {
177
      futile.logger::flog.warn(paste0(" Found ", nDuplicateRows, " duplicate rows in RNA-Seq data, consolidating them by summing them up."))
178
      counts_rna = counts_rna %>%
179
        dplyr::group_by(ENSEMBL) %>%
Christian Arnold's avatar
Christian Arnold committed
180
181
        dplyr::summarise_if(is.numeric, sum) 
        # dplyr::summarise_if(is.numeric, sum, .groups = 'drop') # the .drop caused an error with dplyr 1.0.5
182
    }
Christian Arnold's avatar
Christian Arnold committed
183
    
184

185
    # Normalize counts
186
    countsPeaks.norm.df  = .normalizeCounts(counts_peaks, method = normalization_peaks, idColumn = "peakID")
187
    countsRNA.norm.df  = .normalizeCounts(counts_rna, method = normalization_rna, idColumn = "ENSEMBL")
188
    
189
190
    GRN@config$parameters$normalization_rna = normalization_rna
    GRN@config$parameters$normalization_peaks = normalization_peaks
191
    
Christian Arnold's avatar
Christian Arnold committed
192
193
194
    # We have our first connection type, the default one; more may be added later
    GRN@config$TF_peak_connectionTypes = "expression"
    
195
    # Make sure ENSEMBL is the first column
196
    countsRNA.norm.df = dplyr::select(countsRNA.norm.df, ENSEMBL, tidyselect::everything())
197
    countsPeaks.norm.df = dplyr::select(countsPeaks.norm.df, peakID, tidyselect::everything())
198
199
    
    samples_rna  = colnames(countsRNA.norm.df)
200
201
    samples_peaks =  colnames(countsPeaks.norm.df)
    allSamples =  unique(c(samples_rna, samples_peaks)) %>% setdiff(c("ENSEMBL", "isFiltered", "peakID"))
202
    
203
204
205
    # Subset data to retain only samples that appear in both RNA and peaks
    data.l = .intersectData(countsRNA.norm.df, countsPeaks.norm.df)
    GRN@data$peaks$counts_norm = data.l[["peaks"]] %>% dplyr::mutate(isFiltered = FALSE)
206
207
208
    countsRNA.norm.df = data.l[["RNA"]]  %>% dplyr::mutate(isFiltered = FALSE)
    
    # Create permutations for RNA
209
210
    futile.logger::flog.info(paste0( "Produce ", .getMaxPermutation(GRN), " permutations of RNA-counts"))
    GRN@data$RNA$counts_norm.l = .shuffleColumns(countsRNA.norm.df, .getMaxPermutation(GRN), returnUnshuffled = TRUE, returnAsList = TRUE)
211
212

    if (!is.null(sampleMetadata)) {
Christian Arnold's avatar
Christian Arnold committed
213
214
        
      futile.logger::flog.info("Parsing provided metadata...")
215
      GRN@data$metadata = sampleMetadata %>% dplyr::distinct() %>% tibble::set_tidy_names(syntactic = TRUE, quiet = TRUE)
216
      
Christian Arnold's avatar
Christian Arnold committed
217
218
219
220
221
222
      # Force the first column to be the ID column
      if ("sampleID" %in% colnames(GRN@data$metadata)) {
          flog.warn("Renaming the first column to sampleID. However, this column already exists, it will be renamed accordingly.")
          colnames(GRN@data$metadata)[which(colnames(GRN@data$metadata) == "sampleID")] = "sampleID_original"
          
      } 
223
      colnames(GRN@data$metadata)[1] = "sampleID"
224

225
      # Assume the ID is in column 1, has to be unique
226
      if (nrow(GRN@data$metadata) > length(unique(GRN@data$metadata$sampleID))) {
227
        message = paste0("The first column in the sample metadata table must contain only unique values, as it is used as sample ID. Make sure the values are unique.")
228
229
        tbl_ids = table(GRN@data$metadata$sampleID)
        .checkAndLogWarningsAndErrors(NULL, message, isWarning = FALSE)
230
231
      }
      
232
      missingIDs = which(! allSamples %in% GRN@data$metadata$sampleID)
233
      if (length(missingIDs) > 0) {
234
        GRN@data$metadata = tibble::add_row(GRN@data$metadata, sampleID = allSamples[ missingIDs])
235
236
      }
    } else {
237
      GRN@data$metadata = tibble::tibble(sampleID = allSamples)
238
239
    }
    
240
    GRN@data$metadata =  GRN@data$metadata %>%
241
      dplyr::mutate(has_RNA = sampleID  %in% samples_rna,
242
243
244
245
                    has_peaks = sampleID %in% samples_peaks,
                    has_both = has_RNA & has_peaks
                    )

246
    GRN@config$sharedSamples = dplyr::filter(GRN@data$metadata, has_both) %>% dplyr::pull(sampleID) %>% as.character()
247
    
248
    counts_peaks = as.data.frame(counts_peaks)
249
    counts_rna = as.data.frame(counts_rna)
250
    rownames(counts_peaks) = counts_peaks$peakID
251
    rownames(counts_rna)  = counts_rna$ENSEMBL
252
    
Christian Arnold's avatar
Christian Arnold committed
253
254
    
    
255
256
257
258
    # Store the raw peaks data efficiently as DESeq object only if it contains only integers, otherwise store as normal matrix

    if (isIntegerMatrix(counts_peaks[, GRN@config$sharedSamples])) {
      GRN@data$peaks$counts_orig = DESeq2::DESeqDataSetFromMatrix(counts_peaks[, GRN@config$sharedSamples], 
259
                                                           colData = dplyr::filter(GRN@data$metadata, has_both) %>% tibble::column_to_rownames("sampleID"),
Christian Arnold's avatar
Christian Arnold committed
260
                                                           design = ~1)
261
262
    } else {
      
263
      GRN@data$peaks$counts_orig = as.matrix(counts_peaks[, GRN@config$sharedSamples])
264
    }
265
    
266
    if (isIntegerMatrix(counts_rna[, GRN@config$sharedSamples])) {
267
      GRN@data$RNA$counts_orig = DESeq2::DESeqDataSetFromMatrix(counts_rna[, GRN@config$sharedSamples], 
268
                                                          colData = dplyr::filter(GRN@data$metadata, has_both) %>% tibble::column_to_rownames("sampleID"),
Christian Arnold's avatar
Christian Arnold committed
269
                                                          design = ~1)   
270
271
    } else {
        GRN@data$RNA$counts_orig = as.matrix(counts_rna[, GRN@config$sharedSamples])
272
273
    }
    
274
275

  
276
    # Consensus peaks
Christian Arnold's avatar
Christian Arnold committed
277
278
    GRN@data$peaks$consensusPeaks = .createConsensusPeaksDF(getCounts(GRN, type = "peaks", norm = TRUE, permuted = FALSE)) 
    GRN@data$peaks$consensusPeaks = GRN@data$peaks$consensusPeaks[match(getCounts(GRN, type = "peaks", norm = TRUE, permuted = FALSE)$peakID, GRN@data$peaks$consensusPeaks$peakID), ]
279
    stopifnot(c("chr", "start", "end", "peakID", "isFiltered") %in% colnames(GRN@data$peaks$consensusPeaks))
280
    
Christian Arnold's avatar
Christian Arnold committed
281
    futile.logger::flog.info(paste0("Check for overlapping peaks..."))
Christian Arnold's avatar
Christian Arnold committed
282
283
284
285
286
287
288
289
290
    consensus.gr   = .constructGRanges(GRN@data$peaks$consensusPeaks, seqlengths = .getChrLengths(genomeAssembly), GRN@config$parameters$genomeAssembly)
    
    overlappingPeaks = which(GenomicRanges::countOverlaps(consensus.gr ,consensus.gr) >1)
    
    if (length(overlappingPeaks) > 0){
        
        ids = (consensus.gr[overlappingPeaks] %>% as.data.frame())$peakID
        
        messageAll = paste0(" ", length(overlappingPeaks), 
Christian Arnold's avatar
Christian Arnold committed
291
                            " overlapping peaks have been identified. The first ten are: ", paste0(ids[seq_len(min(10, length(ids)))], collapse = ","),
Christian Arnold's avatar
Christian Arnold committed
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
                            ". This may not be what you want, since overlapping peaks may have a heigher weight in the network. "
        )
        
        
        if (allowOverlappingPeaks) {
            
            message = paste0(messageAll, "As allowOverlappingPeaks has been set to TRUE, this is only a warning and not an error.")
            .checkAndLogWarningsAndErrors(NULL, message, isWarning = TRUE)
        } else {
            message = paste0(messageAll, "As allowOverlappingPeaks = FALSE (the default), this is an error and not a warning. You may want to regenerate the peak file, eliminate peak overlaps, and rerun this function")
            .checkAndLogWarningsAndErrors(NULL, message, isWarning = FALSE)
        }
        
    }
    
307
308
  }
  
Christian Arnold's avatar
Christian Arnold committed
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
  # Add peak annotation once
  GRN = .populatePeakAnnotation(GRN)
  
  # Add gene annotation once
  GRN = .populateGeneAnnotation(GRN)

  GRN
  
}



.createConsensusPeaksDF <- function(countsPeaks, idColumn = "peakID") {
  
  checkmate::assertChoice(idColumn, colnames(countsPeaks))
  
  ids.split = strsplit(countsPeaks %>% dplyr::pull(!!(idColumn)), split = "[:-]+")
  ids.split.length = sapply(ids.split, length)
  if (!all(ids.split.length == 3)) {
    message = paste0(" At least one of the IDs in the peaks data has an unsupported format. Make sure all peakIDs are in the format \"chr:start-end\"")
    .checkAndLogWarningsAndErrors(NULL, message, isWarning = FALSE)
  }
  
  
  consensus.df = tibble::tibble(chr   = as.factor(sapply(ids.split, "[[", 1)),
                                start = as.numeric(sapply(ids.split, "[[", 2)), 
                                end   = as.numeric(sapply(ids.split, "[[", 3)),
                                peakID = paste0(chr, ":", start, "-", end),
                                isFiltered = FALSE) %>%
    dplyr::arrange(chr, start)
  
  # The sorting is necessary here for subsequent bedtools to run faster or at all
  
  consensus.df
}

.removeScientificNotation_positions <- function(peakIDs.vec) {
    ids = strsplit(peakIDs.vec, split = ":", fixed = TRUE)
    ids_chr = sapply(ids, "[[", 1)
    ids_pos = sapply(ids, "[[", 2)
    ids_pos = strsplit(ids_pos, split = "-", fixed = TRUE)
    start = sapply(ids_pos, "[[", 1)
    end   = sapply(ids_pos, "[[", 2)
    
    paste0(ids_chr, ":", format(as.integer(start), scientific = FALSE), "-", format(as.integer(end), scientific= FALSE))
}


.loadPrecompiledAnnotationData <- function(genomeAssembly) {
  
  futile.logger::flog.info(paste0("Reading pre-compiled genome annotation data "))
  
  if (is.null(geneAnnotation[[genomeAssembly]])) {
    
    message = "The genome version you specified is not contained in the pre-compiled genome annotation list. Currently, only hg19, hg38, mm9 and mm10 are supported. Contact us."
    .checkAndLogWarningsAndErrors(NULL, message, isWarning = FALSE)
    
  } 
  
  geneAnnotation[[genomeAssembly]]
}

.getAllGeneTypesAndFrequencies <- function(genomeAssembly, verbose = TRUE) {
  
  geneAnnotation.df = .loadPrecompiledAnnotationData(genomeAssembly)
  return(table(geneAnnotation.df$gene.type))
  
}

.getKnownGeneAnnotationNew <- function(GRN, gene.types, extendRegions = NULL) {
  
  #.checkAndLoadPackages(c("GenomicRanges"), verbose = FALSE)  
  checkmate::assertCharacter(GRN@config$parameters$chrToKeep, min.len = 1)
  
  if (!is.null(extendRegions)) {
    stop("Not yet implemented")
  }
  
  genes.filt.df = .loadPrecompiledAnnotationData(GRN@config$parameters$genomeAssembly)
  
  if (!is.null(gene.types)) {
    if (! "all" %in% gene.types) {
      genes.filt.df = dplyr::filter(genes.filt.df, gene.type %in% gene.types)
    }
  }
  
  
  genes.filt.df
  
}

.populatePeakAnnotation <- function (GRN) {
    
    countsPeaks.clean = getCounts(GRN, type = "peaks", norm = TRUE, permuted = FALSE)
    
    futile.logger::flog.info(paste0(" Calculate statistics for each peak (mean and CV)"))
    
    countsPeaks.m = as.matrix(dplyr::select(countsPeaks.clean, -peakID))
    
    rowMeans_peaks   = rowMeans(countsPeaks.m)
    rowMedians_peaks = matrixStats::rowMedians(countsPeaks.m)
    CV_peaks = matrixStats::rowSds(countsPeaks.m) /  rowMeans_peaks
    
    metadata_peaks = tibble::tibble(peak.ID = countsPeaks.clean$peakID, 
                                    peak.mean = rowMeans_peaks, 
                                    peak.median = rowMedians_peaks, 
                                    peak.CV = CV_peaks)
    
    GRN@annotation$consensusPeaks = metadata_peaks
    
    if (!is.installed("ChIPseeker")) {
        message = paste0("The package ChIPseeker is currently not installed, which is needed for additional peak annotation that can be useful for further downstream analyses. ", 
                         " You may want to install it and re-run this function. However, this is optional and except for some missing additional annotation columns, there is no limitation.")
        .checkAndLogWarningsAndErrors(NULL, message, isWarning = TRUE)
    } else {
        
        futile.logger::flog.info(paste0(" Retrieve peak annotation using ChipSeeker. This may take a while"))
        genomeAssembly = GRN@config$parameters$genomeAssembly
        consensusPeaks     = GRN@data$peaks$consensusPeaks %>% dplyr::filter(!isFiltered)
        consensusPeaks.gr  = .constructGRanges(consensusPeaks, seqlengths = .getChrLengths(genomeAssembly), genomeAssembly)
        
        # Add ChIPSeeker anotation
        peaks.annotated = suppressMessages(ChIPseeker::annotatePeak(
            consensusPeaks.gr,
            tssRegion = c(-5000, 5000), # extended from 3kb to 5
            TxDb = .getGenomeObject(genomeAssembly, type = "txbd"),
            level = "gene", 
            assignGenomicAnnotation = TRUE,  # the default
            genomicAnnotationPriority = c("Promoter", "5UTR", "3UTR", "Exon", "Intron",
                                          "Downstream", "Intergenic"),  # the default
            annoDb = .getGenomeObject(genomeAssembly, type = "packageName"), # optional, if provided, extra columns including SYMBOL, GENENAME, ENSEMBL/ENTREZID will be added
            sameStrand = FALSE, # the default
            ignoreOverlap = FALSE, # the default
            ignoreUpstream = FALSE, # the default
            ignoreDownstream = FALSE, # the default
            overlap = "TSS", # the default
            verbose = TRUE # the default
        ))
        
        GRN@annotation$consensusPeaks_obj = peaks.annotated
        
        peaks.annotated.df = as.data.frame(peaks.annotated)
        peaks.annotated.df$annotation[grepl("Exon", peaks.annotated.df$annotation)] = "Exon"
        peaks.annotated.df$annotation[grepl("Intron", peaks.annotated.df$annotation)] = "Intron"
        
        GRN@annotation$consensusPeaks = dplyr::left_join(GRN@annotation$consensusPeaks, 
                                                         peaks.annotated.df  %>% 
                                                             dplyr::select(peakID, annotation, tidyselect::starts_with("gene"), -geneId, distanceToTSS, ENSEMBL, SYMBOL, GENENAME) %>%
                                                             dplyr::mutate(annotation  = as.factor(annotation), 
                                                                           ENSEMBL = as.factor(ENSEMBL), 
                                                                           GENENAME = as.factor(GENENAME),
                                                                           SYMBOL = as.factor(SYMBOL)),
                                                         by = c("peak.ID" = "peakID")) %>%
            dplyr::rename(peak.gene.chr = geneChr,
                          peak.gene.start = geneStart, 
                          peak.gene.end = geneEnd, 
                          peak.gene.length = geneLength, 
                          peak.gene.strand = geneStrand, 
                          peak.gene.name = GENENAME,
                          peak.gene.distanceToTSS = distanceToTSS,
                          peak.gene.ENSEMBL = ENSEMBL,
                          peak.gene.symbol = SYMBOL,
                          peak.annotation = annotation
            )
        
        
    }
    
    
    
    
    # Also add GC content as annotation columns
    GRN = .calcGCContentPeaks(GRN)
    
    GRN
    
}

.populateGeneAnnotation <- function (GRN) {
  
  futile.logger::flog.info(paste0(" Calculate statistics for each gene (mean and CV)"))
  
  countsRNA.clean  = getCounts(GRN, type = "rna", norm = TRUE, permuted = FALSE)
  
  countsRNA.m = as.matrix(dplyr::select(countsRNA.clean, -ENSEMBL))
  
  rowMeans_rna = rowMeans(countsRNA.m)
  rowMedians_rna = matrixStats::rowMedians(countsRNA.m)
  CV_rna = matrixStats::rowSds(countsRNA.m) /  rowMeans_rna
  
  # This object is internally loaded and lives inside the R directory within sysdata.rda
  # load("/g/scb2/zaugg/carnold/Projects/GRN_pipeline/src/GRNdev/R/sysdata.rda")
  genomeAnnotation.df = geneAnnotation[[GRN@config$parameters$genomeAssembly]]
  
  metadata_rna = tibble::tibble(gene.ENSEMBL = countsRNA.clean$ENSEMBL, 
                                gene.mean = rowMeans_rna, 
                                gene.median = rowMedians_rna, 
                                gene.CV = CV_rna) %>%
    dplyr::full_join(genomeAnnotation.df, by = c("gene.ENSEMBL"))
  
  GRN@annotation$genes = metadata_rna
  
  GRN
  
}

.populateGOAnnotation <- function(GRN, results.tbl, ontology){
516
  
Christian Arnold's avatar
Christian Arnold committed
517
  GRN@annotation$GO[[ontology]] = results.tbl[,c("GO.ID", "Term")]
518
519
520
521
  GRN
  
}

Christian Arnold's avatar
Christian Arnold committed
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
#' @import IRanges
#' @import rlang
.calcGCContentPeaks <- function(GRN) {
    
    futile.logger::flog.info(paste0("Calculate GC-content for peaks... "))
    start = Sys.time()
    genomeAssembly = GRN@config$parameters$genomeAssembly
    #TODO: GC content for all peaks
    genome = .getGenomeObject(genomeAssembly, type = "BSgenome")
    
    # Get peaks as GRanges object
    query   = .constructGRanges(GRN@data$peaks$consensusPeaks, 
                                seqlengths = .getChrLengths(genomeAssembly), 
                                genomeAssembly)
    
    # Get DNAStringSet object
    seqs_peaks = Biostrings::getSeq(genome, query)
    
    GC_content.df = Biostrings::letterFrequency(seqs_peaks, "GC") / Biostrings::letterFrequency(seqs_peaks, "ACGT")
    
    GC_content.df = GC_content.df %>%
        tibble::as_tibble() %>%
        dplyr::mutate(length = IRanges::width(query),
                      peak.ID = query$peakID,
                      GC_class = cut(`G|C`, breaks = seq(0,1,0.1), include.lowest = TRUE, ordered_result = TRUE))
    
    GC_classes.df = GC_content.df %>%
        dplyr::group_by(GC_class) %>%
        dplyr::summarise(n= dplyr::n(), peak_width_mean = mean(length), peak_width_sd = sd(length)) %>%
        dplyr::ungroup() %>% 
        tidyr::complete(GC_class, fill = list(n = 0)) %>%
        dplyr::mutate(n_rel = .data$n / length(query))
    
    # TODO: Put where
    #ggplot(GC_content.df, aes(GC.class)) + geom_histogram(stat = "count") + theme_bw()
    
    #ggplot(GC_classes.df , aes(GC.class, n_rel)) + geom_bar(stat = "identity") + theme_bw()
    
    GRN@annotation$consensusPeaks = dplyr::left_join(GRN@annotation$consensusPeaks, GC_content.df, by = "peak.ID") %>%
        dplyr::rename( peak.GC.perc    = `G|C`,
                       peak.width      = length,
                       peak.GC.class   = GC_class)
    
    GRN@stats$peaks = list()
    GRN@stats$peaks$GC = GC_classes.df
    
    .printExecutionTime(start)
    
    GRN
}
572

573
574
575
#' Filter data from a \code{\linkS4class{GRN}} object
#' 
#' @template GRN 
Christian Arnold's avatar
Christian Arnold committed
576
577
578
579
#' @param minNormalizedMean_peaks Numeric or \code{NULL}. Default 5. Minimum mean across all samples for a peak to be retained for the normalized counts table. Set to \code{NULL} for not applying the filter.
#' @param maxNormalizedMean_peaks Numeric or \code{NULL}. Default \code{NULL}. Maximum mean across all samples for a peak to be retained for the normalized counts table. Set to \code{NULL} for not applying the filter.
#' @param minNormalizedMeanRNA Numeric or \code{NULL}. Default 5. Minimum mean across all samples for a gene to be retained for the normalized counts table. Set to \code{NULL} for not applying the filter.
#' @param maxNormalizedMeanRNA Numeric or \code{NULL}. Default \code{NULL}. Maximum mean across all samples for a gene to be retained for the normalized counts table. Set to \code{NULL} for not applying the filter.
580
#' @param chrToKeep_peaks Character vector. Default c(paste0("chr", 1:22), "chrX", "chrY"). Vector of chromosomes that peaks are allowed to come from. This filter can be used to filter sex chromosomes from the peaks, for example.
Christian Arnold's avatar
Christian Arnold committed
581
582
583
584
585
586
#' @param minSize_peaks Integer or \code{NULL}. Default \code{NULL}. Minimum peak size (width, end - start) for a peak to be retained. Set to \code{NULL} for not applying the filter.
#' @param maxSize_peaks Integer or \code{NULL}. Default 10000. Maximum peak size (width, end - start) for a peak to be retained. Set to \code{NULL} for not applying the filter.
#' @param minCV_peaks Numeric or \code{NULL}. Default \code{NULL}. Minimum CV (coefficient of variation, a unitless measure of variation) for a peak to be retained. Set to \code{NULL} for not applying the filter.
#' @param maxCV_peaks Numeric or \code{NULL}. Default \code{NULL}. Maximum CV (coefficient of variation, a unitless measure of variation) for a peak to be retained. Set to \code{NULL} for not applying the filter.
#' @param minCV_genes Numeric or \code{NULL}. Default \code{NULL}. Minimum CV (coefficient of variation, a unitless measure of variation) for a gene to be retained. Set to \code{NULL} for not applying the filter.
#' @param maxCV_genes Numeric or \code{NULL}. Default \code{NULL}. Maximum CV (coefficient of variation, a unitless measure of variation) for a gene to be retained. Set to \code{NULL} for not applying the filter.
587
#' @template forceRerun
588
#' @return The same \code{\linkS4class{GRN}} object, with added data from this function.
Christian Arnold's avatar
Christian Arnold committed
589
590
591
592
593
594
595
596
597
598
599
#' @examples 
#' chrToKeep_peaks = c(paste0("chr", 1:22), "chrX", "chrY")
#' GRN = GRN::filterData(GRN, minNormalizedMean_peaks = 5, minNormalizedMeanRNA = 1, chrToKeep_peaks = chrToKeep_peaks, maxSize_peaks = 10000, forceRerun = TRUE)
#' @export
filterData <- function (GRN, 
                        minNormalizedMean_peaks = 5, maxNormalizedMean_peaks = NULL, 
                        minNormalizedMeanRNA = 1,  maxNormalizedMeanRNA = NULL,
                        chrToKeep_peaks = c(paste0("chr", seq_len(22)), "chrX", "chrY"),
                        minSize_peaks = NULL, maxSize_peaks = 10000,
                        minCV_peaks = NULL, maxCV_peaks = NULL,
                        minCV_genes = NULL, maxCV_genes = NULL,
600
                        forceRerun = FALSE) {
601
  GRN = .addFunctionLogToObject(GRN) 
602
  
603
604
605
  checkmate::assertClass(GRN, "GRN")
  checkmate::assertNumber(minNormalizedMean_peaks, lower = 0)
  checkmate::assertNumber(minNormalizedMeanRNA, lower = 0)
Christian Arnold's avatar
Christian Arnold committed
606
607
  checkmate::assertNumber(maxNormalizedMean_peaks, lower = minNormalizedMean_peaks , null.ok = TRUE)
  checkmate::assertNumber(maxNormalizedMeanRNA, lower = minNormalizedMeanRNA, null.ok = TRUE)
608
  checkmate::assertCharacter(chrToKeep_peaks, min.len = 1, any.missing = FALSE)
Christian Arnold's avatar
Christian Arnold committed
609
610
611
612
613
614
  checkmate::assertIntegerish(minSize_peaks, lower = 1, null.ok = TRUE)
  checkmate::assertIntegerish(maxSize_peaks, lower = dplyr::if_else(is.null(minSize_peaks), 1, minSize_peaks), null.ok = TRUE)
  checkmate::assertNumber(minCV_peaks, lower = 0, null.ok = TRUE)
  checkmate::assertNumber(maxCV_peaks, lower = dplyr::if_else(is.null(minCV_peaks), 0, minCV_peaks), null.ok = TRUE)
  checkmate::assertNumber(minCV_genes, lower = 0, null.ok = TRUE)
  checkmate::assertNumber(maxCV_genes, lower = dplyr::if_else(is.null(minCV_genes), 0, minCV_genes), null.ok = TRUE)
615
616
  checkmate::assertFlag(forceRerun)
  
617
  if (!GRN@config$isFiltered | forceRerun) {
618
    
619
620
    GRN@data$peaks$consensusPeaks$isFiltered = FALSE
    GRN@data$peaks$counts_norm$isFiltered = FALSE
621
    
622
623
    if(!is.null(GRN@data$TFs$TF_peak_overlap)) {
      GRN@data$TFs$TF_peak_overlap[, "isFiltered"] = 0
624
    }
625
  
626

Christian Arnold's avatar
Christian Arnold committed
627
628
629
630
631
    # Filter peaks
    futile.logger::flog.info("FILTER PEAKS")
    peakIDs.CV = .filterPeaksByMeanCV(GRN, 
                                      minMean = minNormalizedMean_peaks, maxMean = maxNormalizedMean_peaks, 
                                      minCV = minCV_peaks, maxCV = maxCV_peaks) 
632
633
    
    # Clean peaks from alternative contigs etc 
634
    GRN@config$parameters$chrToKeep =  chrToKeep_peaks
Christian Arnold's avatar
Christian Arnold committed
635
636
637
    peakIDs.chr = .filterPeaksByChromosomeAndSize(GRN, 
                                                  chrToKeep_peaks, 
                                                  minSize_peaks = minSize_peaks, maxSize_peaks = maxSize_peaks)
638
    
639
    nPeaksBefore = nrow(GRN@data$peaks$consensusPeaks)
Christian Arnold's avatar
Christian Arnold committed
640
    peaks_toKeep = intersect(peakIDs.chr, peakIDs.CV)
641
642
    futile.logger::flog.info(paste0("Collectively, filter ", nPeaksBefore -length(peaks_toKeep), " out of ", nPeaksBefore, " peaks."))
    futile.logger::flog.info(paste0("Number of remaining peaks: ", length(peaks_toKeep)))
643
    
644
645
646
    GRN@data$peaks$consensusPeaks$isFiltered  = ! GRN@data$peaks$consensusPeaks$peakID  %in% peaks_toKeep
    #GRN@data$peaks$counts_raw$isFiltered = ! GRN@data$peaks$counts_raw$peakID  %in% peaks_toKeep
    GRN@data$peaks$counts_norm$isFiltered = ! GRN@data$peaks$counts_norm$peakID  %in% peaks_toKeep
Christian Arnold's avatar
Christian Arnold committed
647
    
648

649
650
    if(!is.null(GRN@data$TFs$TF_peak_overlap)) {
      GRN@data$TFs$TF_peak_overlap[, "isFiltered"] = as.integer (! rownames(GRN@data$TFs$TF_peak_overlap) %in% peaks_toKeep)
651
652
653
654
655
    }
    
    
    # Remove genes with small rowMeans
    #Only for real data, not for permuted (rowmeans is equal anyway)
Christian Arnold's avatar
Christian Arnold committed
656
657
658
659
660
661
    # Filter peaks
    futile.logger::flog.info("FILTER RNA-seq")
    genes.CV = .filterGenesByMeanCV(GRN, 
                                      minMean = minNormalizedMeanRNA, maxMean = maxNormalizedMeanRNA, 
                                      minCV = minCV_genes, maxCV = maxCV_genes) 
 
662
    futile.logger::flog.info(paste0(" Number of rows in total: ", nrow(GRN@data$RNA$counts_norm.l[["0"]])))
663
664
    for (permutationCur in c(0)) {
      permIndex = as.character(permutationCur)
665
      rowMeans = rowMeans(dplyr::select(GRN@data$RNA$counts_norm.l[[permIndex]], -ENSEMBL))
Christian Arnold's avatar
Christian Arnold committed
666
      GRN@data$RNA$counts_norm.l[[permIndex]]$isFiltered = rowMeans < minNormalizedMeanRNA 
667
    }
668
    nRowsFlagged = length(which(GRN@data$RNA$counts_norm.l[["0"]]$isFiltered))
669

670
    # Raw counts are left untouched and filtered where needed only
671
    futile.logger::flog.info(paste0(" Flagged ", nRowsFlagged, " rows because the row mean was smaller than ", minNormalizedMeanRNA))
672
    
Christian Arnold's avatar
Christian Arnold committed
673
674
    # TODO: Filter genes by CV
    
675
    GRN@config$isFiltered = TRUE
676
677
678
679
680
681
  } 
  
  GRN
}


Christian Arnold's avatar
Christian Arnold committed
682
.filterPeaksByChromosomeAndSize <- function(GRN, chrToKeep, minSize_peaks = NULL, maxSize_peaks, idColumn = "peakID") {
683
684
685
  
  startTime = Sys.time()
  
Christian Arnold's avatar
Christian Arnold committed
686
687
688
  if (is.null(minSize_peaks)) {
      minSize_peaks = 1
  }
689
  
690
  futile.logger::flog.info(paste0("Filter and sort peaks and remain only those on the following chromosomes: ", paste0(chrToKeep, collapse = ",")))
691
  futile.logger::flog.info(paste0("Filter and sort peaks by size and remain only those smaller than : ", maxSize_peaks))
Christian Arnold's avatar
Christian Arnold committed
692
693
  futile.logger::flog.info(paste0(" Number of peaks before filtering: ", nrow(GRN@data$peaks$consensusPeaks)))
  ids = strsplit(GRN@data$peaks$consensusPeaks %>% dplyr::pull(!!(idColumn)), split = ":", fixed = TRUE)
694
695
696
697
698
699
  ids_chr = sapply(ids, "[[", 1)
  ids_pos = sapply(ids, "[[", 2)
  ids_pos = strsplit(ids_pos, split = "-", fixed = TRUE)
  start = sapply(ids_pos, "[[", 1)
  end   = sapply(ids_pos, "[[", 2)
  
Christian Arnold's avatar
Christian Arnold committed
700
  countsPeaks.clean = GRN@data$peaks$consensusPeaks %>%
701
    dplyr::mutate(chr = ids_chr,
702
703
704
           start = as.numeric(start),
           end = as.numeric(end),
           size = end-start) %>%
Christian Arnold's avatar
Christian Arnold committed
705
    dplyr::filter(chr %in% chrToKeep, size <= maxSize_peaks, size >= minSize_peaks) %>%
706
707
    # arrange(chr, start) %>%
    dplyr::rename(peakID = !!(idColumn)) %>%
708
    dplyr::select(-chr,-start,-end,-size) %>%
709
    dplyr::select(peakID, tidyselect::everything())
710
  
711
  futile.logger::flog.info(paste0(" Number of peaks after filtering : ", nrow(countsPeaks.clean)))
712
713
  
  .printExecutionTime(startTime)
Christian Arnold's avatar
Christian Arnold committed
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
  countsPeaks.clean$peakID
}

.filterPeaksByCV <- function (GRN, minCV = 0, maxCV = 1e7) {
    
    startTime = Sys.time()
    
    if (is.null(maxCV)) {
        futile.logger::flog.info(paste0("Filter peaks by CV: Min CV = ", minCV))
        
        peaksFiltered = dplyr::filter(GRN@annotation$consensusPeaks, peak.CV >= minCV)
        
    } else {
        futile.logger::flog.info(paste0("Filter peaks by CV: Min CV = ", minCV, ", max CV = ", maxCV))
        
        peaksFiltered = dplyr::filter(GRN@annotation$consensusPeaks, peak.CV >= minCV, peak.CV <= maxCV)
    }
    
    futile.logger::flog.info(paste0(" Number of peaks after filtering : ", nrow(peaksFiltered)))
    
    .printExecutionTime(startTime)
    
    peaksFiltered$peak.ID
}

.filterPeaksByMeanCV <- function (GRN, minMean = 0, maxMean = NULL, minCV = 0, maxCV = NULL) {
    
    startTime = Sys.time()
    
    futile.logger::flog.info(paste0(" Number of peaks before filtering : ", nrow(GRN@annotation$consensusPeaks)))
    
    if (is.null(minCV)) {
        minCV = 0
    }
    
    if (is.null(maxCV)) {
        futile.logger::flog.info(paste0("  Filter peaks by CV: Min = ", minCV))
        maxCV = 9e+99
        
    } else {
        futile.logger::flog.info(paste0("  Filter peaks by CV: Min = ", minCV, ", Max = ", maxCV))
    }
    
    
    if (is.null(minMean)) {
        minMean = 0
    }
    
    if (is.null(maxMean)) {
        futile.logger::flog.info(paste0("  Filter peaks by mean: Min = ", minMean))
        maxMean = 9e+99
    } else {
        futile.logger::flog.info(paste0("  Filter peaks by mean: Min = ", minMean, ", Max = ", maxMean))  
    }   
    
    
    peaksFiltered = dplyr::filter(GRN@annotation$consensusPeaks, 
                                  peak.CV >= minCV, peak.CV <= maxCV, 
                                  peak.mean >= minMean, peak.mean <= maxMean)
    
    futile.logger::flog.info(paste0(" Number of peaks after filtering : ", nrow(peaksFiltered)))
    
    .printExecutionTime(startTime)
    
    peaksFiltered$peak.ID
}

.filterGenesByMeanCV <- function (GRN, minMean = 0, maxMean = NULL, minCV = 0, maxCV = NULL) {
    
    startTime = Sys.time()
    
    futile.logger::flog.info(paste0(" Number of genes before filtering : ", nrow(GRN@annotation$genes)))
    
    if (is.null(minCV)) {
        minCV = 0
    }
    
    if (is.null(maxCV)) {
        futile.logger::flog.info(paste0("  Filter genes by CV: Min = ", minCV))
        maxCV = 9e+99
        
    } else {
        futile.logger::flog.info(paste0("  Filter genes by CV: Min = ", minCV, ", Max = ", maxCV))
    }
    
    
    if (is.null(minMean)) {
        minMean = 0
    }
    
    
    if (is.null(maxMean)) {
        futile.logger::flog.info(paste0("  Filter genes by mean: Min = ", minMean))
        maxMean = 9e+99
    } else {
        futile.logger::flog.info(paste0("  Filter genes by mean: Min = ", minMean, ", Max = ", maxMean))  
    }   
    
    
    genesFiltered = dplyr::filter(GRN@annotation$genes, 
                                  gene.CV >= minCV, gene.CV <= maxCV, 
                                  gene.mean >= minMean, gene.mean <= maxMean)

    
    futile.logger::flog.info(paste0(" Number of genes after filtering : ", nrow(genesFiltered)))
    
    .printExecutionTime(startTime)
    
    genesFiltered$gene.ENSEMBL 
823
824
825
}


Christian Arnold's avatar
Christian Arnold committed
826
827
828

######## TFBS ########

829
830
831
#' Add TFBS to a \code{\linkS4class{GRN}} object
#' 
#' @template GRN 
832
833
834
835
#' @param motifFolder Character. No default. Path to the folder that contains the TFBS predictions. The files must be in BED format, 6 columns, one file per TF. See the other parameters for more details.
#' @param TFs Character vector. Default "all". Vector of TF names to include. The special keyword "all" can be used to include all TF found in the folder as specified by motifFolder. If "all" is specified anywhere, all TFs will be included. TF names must otherwise match the file names that are found in the folder, without the file suffix.
#' @param filesTFBSPattern Character. Default "_TFBS". Suffix for the file names in the TFBS folder that is not part of the TF name. Can be empty. For example, for the TF CTCF, if the file is called CTCF.all.TFBS.bed, set this parameter to ".all.TFBS".
#' @param fileEnding Character. Default ".bed". File ending for the files from the motif folder.
836
#' @template forceRerun
837
#' @return The same \code{\linkS4class{GRN}} object, with added data from this function.
Christian Arnold's avatar
Christian Arnold committed
838
839
840
#' @examples 
#' GRN = GRN::addTFBS(GRN, motifFolder = folder_TFBS_first50, TFs = "all", filesTFBSPattern = "_TFBS", fileEnding = ".bed.gz", forceRerun = TRUE)
#' @export
841
addTFBS <- function(GRN, motifFolder, TFs = "all", nTFMax = NULL, filesTFBSPattern = "_TFBS", fileEnding = ".bed", forceRerun = FALSE) {
842
843
844

  GRN = .addFunctionLogToObject(GRN)
    
845
846
847
848
  checkmate::assertClass(GRN, "GRN")
  checkmate::assertDirectoryExists(motifFolder)
  checkmate::assertCharacter(TFs, min.len = 1)
  checkmate::assert(checkmate::testNull(nTFMax), checkmate::testIntegerish(nTFMax, lower = 1))
Christian Arnold's avatar
Christian Arnold committed
849
  checkmate::assertCharacter(filesTFBSPattern, len = 1, min.chars = 0)
850
851
852
853
  checkmate::assertCharacter(fileEnding, len = 1, min.chars = 1)
  checkmate::assertFlag(forceRerun)
  
  if (is.null(GRN@data$TFs$translationTable) | is.null(GRN@data$TFs$translationTable) | is.null(GRN@config$allTF)  | is.null(GRN@config$directories$motifFolder) | forceRerun) {
854

Christian Arnold's avatar
Christian Arnold committed
855
856
    GRN@config$TFBS_fileEnding  = fileEnding
    GRN@config$TFBS_filePattern = filesTFBSPattern
Christian Arnold's avatar
Christian Arnold committed
857
    GRN@data$TFs$translationTable = .getFinalListOfTFs(motifFolder, filesTFBSPattern, fileEnding, TFs, nTFMax, getCounts(GRN, type = "rna", norm = TRUE, permuted = FALSE))
858
    
Christian Arnold's avatar
Christian Arnold committed
859

860
    GRN@data$TFs$translationTable = GRN@data$TFs$translationTable %>%
861
      dplyr::select(c("HOCOID", "ENSEMBL")) %>%
862
      dplyr::mutate(TF.name = HOCOID, TF.ENSEMBL = ENSEMBL) 
863
    
Christian Arnold's avatar
Christian Arnold committed
864
    # TODO: Change here and make it more logical what to put where
865
    GRN@config$allTF = GRN@data$TFs$translationTable$TF.name
866
    
Christian Arnold's avatar
Christian Arnold committed
867
868
869
870
871
872
    #Store all data-dependent TF information
    # GRN@config$TF_list = list()
    # GRN@config$TF_list[["all_TFBS"]] =GRN@config$allTF
    GRN@config$directories$motifFolder = motifFolder
  
  
873
874
875
876
877
878
879
  } 
  
  GRN
  
}


880
.getFinalListOfTFs <- function(folder_input_TFBS, filesTFBSPattern, fileEnding, TFs, nTFMax, countsRNA) {
881
  
882
  futile.logger::flog.info(paste0("Checking database folder for matching files: ", folder_input_TFBS))
883
884
885
  files = .createFileList(folder_input_TFBS, "*.bed*", recursive = FALSE, ignoreCase = FALSE, verbose = FALSE)
  TFsWithTFBSPredictions = gsub(pattern = filesTFBSPattern, "", tools::file_path_sans_ext(basename(files), compression = TRUE))
  TFsWithTFBSPredictions = gsub(pattern = fileEnding, "", TFsWithTFBSPredictions)
886

887
  futile.logger::flog.info(paste0("Found ", length(TFsWithTFBSPredictions), " matching TFs: ", paste0(TFsWithTFBSPredictions, collapse = ", ")))
888

889
890
891
892
  
  # Filter TFs
  if (length(TFs) == 1 && TFs == "all") {
    
893
    futile.logger::flog.info(paste0("Use all TF from the database folder ", folder_input_TFBS))
894
895
896
    
  } else {
    
897
    futile.logger::flog.info(paste0("Subset TFs to user-specified list: ", paste0(TFs, collapse = ", ")))
898
899
900
    TFsWithTFBSPredictions = TFsWithTFBSPredictions[TFsWithTFBSPredictions %in% TFs]
    
    if (length(TFsWithTFBSPredictions) == 0) {
901
902
      message = paste0("No TFs are left after subsetting. Make sure the TF names are identical to the names in the database folder.")
      .checkAndLogWarningsAndErrors(NULL, message, isWarning = FALSE)
903
    }
904
    futile.logger::flog.info(paste0("List of TFs: ", paste0(TFs, collapse = ", ")))
905
906
907
908
    
  }
  
  file_input_HOCOMOCO = paste0(folder_input_TFBS, "/translationTable.csv")
909
  HOCOMOCO_mapping.df = .readHOCOMOCOTable(file_input_HOCOMOCO, delim = " ")
910
911
912
913
  
  TF_notExpressed = sort(dplyr::filter(HOCOMOCO_mapping.df, ! ENSEMBL %in% countsRNA$ENSEMBL, HOCOID %in% TFsWithTFBSPredictions) %>% dplyr::pull(HOCOID))
  
  if (length(TF_notExpressed) > 0) {
914
    futile.logger::flog.info(paste0("Filtering the following ", length(TF_notExpressed), " TFs as they are not present in the RNA-Seq data: ", paste0(TF_notExpressed, collapse = ",")))
915
916
917
918
919
920
921
922
923
924
925
    
  }
  
  allTF = sort(dplyr::filter(HOCOMOCO_mapping.df, ENSEMBL %in% countsRNA$ENSEMBL, HOCOID %in% TFsWithTFBSPredictions) %>% dplyr::pull(HOCOID))
  
  nTF = length(allTF)
  if (nTF == 0) {
    message = paste0("No shared Tfs.")
    .checkAndLogWarningsAndErrors(NULL, message, isWarning = FALSE)
  }
  
926
927
928
929
  if (!is.null(nTFMax)) {
    
    if (!is.null(nTFMax) && nTFMax < nTF) {
      futile.logger::flog.info(paste0("Use only the first ", nTFMax, " TFs because nTFMax has been set."))
Christian Arnold's avatar
Christian Arnold committed
930
      allTF = allTF[seq_len(nTFMax)]
931
932
      futile.logger::flog.info(paste0("Updated list of TFs: ", paste0(allTF, collapse = ", ")))
    } 
933

934
935
936
937
938
  }
  
  nTF = length(allTF)
  futile.logger::flog.info(paste0("Running the pipeline for ", nTF, " TF in total."))
  
939
940
941
942
943
944
  HOCOMOCO_mapping.df.exp = dplyr::filter(HOCOMOCO_mapping.df, HOCOID %in% allTF)
  if (nrow(HOCOMOCO_mapping.df.exp) == 0) {
    message = paste0("Number of rows of HOCOMOCO_mapping.df.exp is 0. Something is wrong with the mapping table or the filtering")
    .checkAndLogWarningsAndErrors(NULL, message, isWarning = FALSE)
  }
  
Christian Arnold's avatar
Christian Arnold committed
945
  
946
947
948
  HOCOMOCO_mapping.df.exp
}

949
#' Overlap peaks and TFBS for a \code{\linkS4class{GRN}} object
950
951
952
953
#' 
#' @template GRN
#' @template nCores
#' @template forceRerun
954
#' @return The same \code{\linkS4class{GRN}} object, with added data from this function. 
Christian Arnold's avatar
Christian Arnold committed
955
956
#' @examples 
#' GRN = overlapPeaksAndTFBS(GRN, nCores = 2, forceRerun = TRUE)
957
#' @export
958
overlapPeaksAndTFBS <- function(GRN, nCores = 2, forceRerun = FALSE) {
Christian Arnold's avatar
Christian Arnold committed
959

960
961
  GRN = .addFunctionLogToObject(GRN)
    
962
963
964
965
966
  checkmate::assertClass(GRN, "GRN")
  checkmate::assertIntegerish(nCores, lower = 1)
  checkmate::assertFlag(forceRerun)
  
  if (is.null(GRN@data$TFs$TF_peak_overlap) | forceRerun) {
967
    
968

969
    futile.logger::flog.info(paste0("Overlap peaks and TFBS using ", nCores, " cores. This may take a few minutes..."))
970

971
    genomeAssembly = GRN@config$parameters$genomeAssembly
972
    seqlengths = .getChrLengths(genomeAssembly)
Christian Arnold's avatar
Christian Arnold committed
973
974
975
976
977
978
979
980
981
    
    if (!is.null(GRN@config$TFBS_filePattern)) {
      filesTFBSPattern = GRN@config$TFBS_filePattern
    } else {
      message = "Could not retrieve value from GRN@config$TFBS_filePattern. Please rerun the function addTFBS, as this was added in a recent version of the package."
      .checkAndLogWarningsAndErrors(NULL, message, isWarning = FALSE)
    }
   
    
982
    # Check whether we have peaks on chromosomes not part of the sequence length reference. If yes, discard them
983
    annotation_discared = dplyr::filter(GRN@data$peaks$consensusPeaks, ! chr %in% names(seqlengths))
984
985
986
987
988
989
    
    if (nrow(annotation_discared) > 0) {
      
      tbl_discarded = table(annotation_discared$chr)
      tbl_discarded = tbl_discarded[which(tbl_discarded > 0)]
      
990
      futile.logger::flog.warn(paste0("Found ", sum(tbl_discarded), " regions from chromosomes without a reference length. ", 
991
992
                       "Typically, these are random fragments from known or unknown chromosomes. The following regions will be discarded: \n",
                       paste0(names(tbl_discarded), " (", tbl_discarded, ")", collapse = ",")))
993
      
994
      GRN@data$peaks$consensusPeaks = dplyr::filter(GRN@data$peaks$consensusPeaks, chr %in% names(seqlengths))
995
996
997
    }
    
    # Construct GRanges
998
    consensus.gr   = .constructGRanges(GRN@data$peaks$consensusPeaks, seqlengths = seqlengths, genomeAssembly)
999
    
1000
    res.l = .execInParallelGen(nCores, returnAsList = TRUE, listNames = GRN@config$allTF,