genome_features_overlaps.R 12.5 KB
Newer Older
Aurelien Brionne's avatar
Aurelien Brionne committed
1
2
#' @title  find overlaps between genomic coordinates and features.
#' @description find overlaps between genomic coordinates and features, and store results in an \code{\link{overlapped_genome_features-class}} object.
3
#' @importFrom methods slotNames slot is
Aurelien Brionne's avatar
Aurelien Brionne committed
4
5
6
7
8
#' @importFrom AnnotationDbi as.data.frame
#' @importFrom GenomicRanges pintersect
#' @importFrom IRanges findOverlaps width
#' @importFrom S4Vectors queryHits subjectHits
#' @importFrom plotly plot_ly layout
9
#' @importFrom grDevices png colorRampPalette
Aurelien Brionne's avatar
Aurelien Brionne committed
10
11
12
#' @importFrom UpSetR upset
#' @import data.table
#' @param peaks a  \code{\link[base]{list}} of \code{\link[GenomicRanges]{GRanges}} objects elements provided by \code{\link{readPeakFile}}.
13
#' @param features a \code{\link{genome_features-class}} object.
Aurelien Brionne's avatar
Aurelien Brionne committed
14
15
16
17
18
19
20
21
22
23
24
25
26
#' @param figs_path the path where print the \code{\link[UpSetR]{upstet}} plots. ("./data/figs/", by default).
#' @param ignore.strand ignore peak coordinate orientation (defaul to TRUE).
#' @details This method build a convenient genomic features object, in order to be used for finding overlaps beetween
#' all needed features and peaks coordinates with \code{\link{genome_features_overlaps}}.
#' @return an \code{\link{overlapped_genome_features-class}} object.
#' @include overlapped_genome_features.R
#' @examples
#' ###################
#  find overlaps
#' features_overlaps<-GenomeFeatures::genome_features_overlaps(
#'  peaks,
#'  features,
#'  figs_path="./data/output/",
27
#'  ignore.strand = TRUE
Aurelien Brionne's avatar
Aurelien Brionne committed
28
#' )
29
30
31
#' @name genome_features_overlaps
#' @rdname genome_features_overlaps-methods
#' @exportMethod genome_features_overlaps
32
setGeneric(name="genome_features_overlaps",def=function(peaks,features,figs_path="./data/figs/",ignore.strand=TRUE){
33
34
  standardGeneric("genome_features_overlaps")
})
Aurelien Brionne's avatar
Aurelien Brionne committed
35

36
37
38
39
40
#' @rdname genome_features_overlaps-methods
#' @aliases genome_features_overlaps
setMethod(
  "genome_features_overlaps",
  methods::signature(
41
42
    peaks="CompressedGRangesList",
    features="genome_features"
43
44
  ),
  definition=function(peaks,features,figs_path,ignore.strand){
Aurelien Brionne's avatar
Aurelien Brionne committed
45
46
47
48
49
50
51

  ###################
  # check entry
  ###################

    ###################
    # check peaks and features
52
    if(base::is.null(base::names(peaks)) && base::length(base::unique(base::names(peaks)))==base::length(peaks)){
Aurelien Brionne's avatar
Aurelien Brionne committed
53
54
      base::stop("peaks must be a named list object with unique identifiers")
    }
55
56
    if(!methods::is(features,"genome_features")){
      base::stop("features must be a genome_features class object")
Aurelien Brionne's avatar
Aurelien Brionne committed
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
    }

  ###################
  # find overlaps
  ###################

    ###################
    # availables features
    Features<- methods::slotNames(features)
    Features<-Features[-base::length(Features)]

    ###################
    # check if slot is empty or not
    check=sapply(Features,function(x){
      slot=methods::slot(features,x)
      base::is.null(slot$GRanges)
    })
    Features<-Features[!check]

    ###################
    # find all overlaps between peaks and genes at proximity
    annot<-base::lapply(base::names(peaks),function(x){

      ###################
      # query
      query<-peaks[[x]]

      ###################
      # query
      query_DT<-data.table::data.table(AnnotationDbi::as.data.frame(query))

      ###################
      # find overlaps
      annot<-base::lapply(Features,function(y){

        ###################
        # subject
        subject=methods::slot(features,y)$GRanges

        ###################
        # subject DT
        subject_DT=methods::slot(features,y)$DT

        ###################
        # find overlaps
        hits=IRanges::findOverlaps(query,subject,ignore.strand=ignore.strand)

        ###################
        # if overlaps
        if(length(hits)>0){

          ###################
          # overlaps length
          overlaps_length=IRanges::width(
            GenomicRanges::pintersect(
              query[S4Vectors::queryHits(hits)],
              subject[S4Vectors::subjectHits(hits)]
            )
          )

          ###################
          # query_coverage
          peak_coverage=base::round(overlaps_length/IRanges::width(
120
          query[S4Vectors::queryHits(hits)])*100,digits=3)
Aurelien Brionne's avatar
Aurelien Brionne committed
121
122
123
124

          ###################
          # subject_coverage
          feature_coverage=base::round(overlaps_length/IRanges::width(
125
          subject[S4Vectors::subjectHits(hits)])*100,digits=3)
Aurelien Brionne's avatar
Aurelien Brionne committed
126

127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
          ###################
          # subject_coordinates
          feature_coordinates=data.table::data.table(
            base::as.data.frame(
               subject[S4Vectors::subjectHits(hits)]
            )
          )

          ###################
          # subject_coordinates collapse
          feature_coordinates=base::paste(
            feature_coordinates$seqnames,
            feature_coordinates$start,
            feature_coordinates$end,
            feature_coordinates$strand,
          sep=":")

Aurelien Brionne's avatar
Aurelien Brionne committed
144
145
146
147
148
149
150
          ###################
          # convert to table
          Data<-data.table::data.table(
            feature_type=y,
            query_DT[S4Vectors::queryHits(hits)],
            subject_DT[S4Vectors::subjectHits(hits)],
            peak_coverage,
151
152
            feature_coverage,
            feature_coordinates
Aurelien Brionne's avatar
Aurelien Brionne committed
153
154
155
156
          )

          ###################
          # remove group
157
          if(y%in%base::c("promoter","downstream")) Data[,"group":=NULL]
Aurelien Brionne's avatar
Aurelien Brionne committed
158
159
160
161
162
163
164
165
166
167
168
169
170

          ###################
          # return the data.table
          Data
        }
      })

      ###################
      # build global table
      annot<-data.table::rbindlist(annot)

      ###################
      # match index
171
      if(ignore.strand==TRUE){
Aurelien Brionne's avatar
Aurelien Brionne committed
172
173
174

        ###################
        # add tag to query
175
        query_DT[,"tag":=base::paste(seqnames,start,end)]
Aurelien Brionne's avatar
Aurelien Brionne committed
176
177
178

        ###################
        # add tag to annot
179
        annot[,"tag":=base::paste(seqnames,start,end)]
Aurelien Brionne's avatar
Aurelien Brionne committed
180
181
182
183
184

      }else{

        ###################
        # add tag to query
185
        query_DT[,"tag":=base::paste(seqnames,start,end,strand)]
Aurelien Brionne's avatar
Aurelien Brionne committed
186
187
188

        ###################
        # add tag to annot
189
        annot[,"tag":=base::paste(seqnames,start,end,strand)]
Aurelien Brionne's avatar
Aurelien Brionne committed
190
191
192
193
194
195
      }

      ###################
      # merge by tag
      annot<-merge(
        base::unique(query_DT),
196
197
198
199
200
        annot[,base::c("tag","feature_type","feature","tx_name","peak_coverage","feature_coverage","feature_coordinates"),with=FALSE],
        by="tag",
        sort=FALSE,
        all=TRUE
      )
Aurelien Brionne's avatar
Aurelien Brionne committed
201
202
203

      ###################
      # add other to feature if feature_type is NA
204
      annot[base::is.na(annot$feature_type),"feature_type":="other"]
Aurelien Brionne's avatar
Aurelien Brionne committed
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220

      ###################
      # add queru names
      data.table::data.table(condition=x,annot)
    })

    ###################
    # build global table
    annot<-data.table::rbindlist(annot)

    ###################
    # update features with other (not associated to feature)
    Features<-base::c(Features,"other")

    ###################
    # convert condition and feature_type to factor
221
222
223
224
225
    annot[,
      "feature_type":=base::factor(
        annot$feature_type,
        levels=base::unique(annot$feature_type)
      )
Aurelien Brionne's avatar
Aurelien Brionne committed
226
227
228
229
    ]

    ###################
    # count features by condition
230
    peaks_count=annot[,base::list("count"=.N),by=c("condition","tag","feature_type")]
Aurelien Brionne's avatar
Aurelien Brionne committed
231
232
233

    ###################
    # remove tag
234
    annot[,"tag":=NULL]
Aurelien Brionne's avatar
Aurelien Brionne committed
235

236
    if(base::ncol(methods::slot(features,"gene_table"))>1){
Aurelien Brionne's avatar
update    
Aurelien Brionne committed
237

Aurelien Brionne's avatar
Aurelien Brionne committed
238
239
      ###################
      # merge with overlapped features
Aurelien Brionne's avatar
upgrade    
Aurelien Brionne committed
240
241
      annot<-merge(
        annot,
242
243
244
245
246
247
248
        base::unique(
          methods::slot(features,"gene_table")[
            !is.na(transcript_id),
            base::c("type","gene_name","transcript_id","gene_id"),
            with=FALSE
          ]
        ),
Aurelien Brionne's avatar
upgrade    
Aurelien Brionne committed
249
250
        by.x="tx_name",
        by.y="transcript_id",
251
252
        all.x=TRUE,
        sort=FALSE
Aurelien Brionne's avatar
upgrade    
Aurelien Brionne committed
253
254
      )

Aurelien Brionne's avatar
update    
Aurelien Brionne committed
255
256
257
258
    }else{

      ###################
      # merge with overlapped features
259
      annot[,"gene_id":=base::gsub(":.+$","",annot$feature)]
Aurelien Brionne's avatar
Aurelien Brionne committed
260
    }
Aurelien Brionne's avatar
Aurelien Brionne committed
261
262
263
264
265
266

    ###################
    # locate feature tag
    pos=base::which("feature"==base::names(annot))

    ###################
267
    # reorder annot
268
    annot<-annot[,base::c(2:pos,1,(pos+1):base::ncol(annot)),with=FALSE]
Aurelien Brionne's avatar
Aurelien Brionne committed
269

270
271
272
273
    ###################
    # convert seqnames to character
    annot[,seqnames:=base::as.character(seqnames)]

Aurelien Brionne's avatar
Aurelien Brionne committed
274
  ###################
Aurelien Brionne's avatar
Aurelien Brionne committed
275
  # feature distribution (transcript level)
Aurelien Brionne's avatar
Aurelien Brionne committed
276
277
278
279
  ###################

    ###################
    # count features by condition
280
    features_count=annot[,base::list("count"=.N),by=c("condition","feature_type")]
Aurelien Brionne's avatar
Aurelien Brionne committed
281
282
283

    ###################
    # cast featurescount
284
285
286
287
288
    features_count=data.table::dcast(
      features_count,
      condition~feature_type,
      value.var="count"
    )
Aurelien Brionne's avatar
Aurelien Brionne committed
289
290
291
292
293
294
295

    ###################
    # replace NA by 0
    features_count[base::is.na(features_count)]<-0

    ###################
    # add the sum of count by condition
296
    features_count[,"sum":=base::sum(.SD),by="condition"]
Aurelien Brionne's avatar
Aurelien Brionne committed
297
298
299
300

    ###################
    # compute frequency
    features_frequency<-features_count[,
Aurelien Brionne's avatar
Aurelien Brionne committed
301
      base::lapply(.SD,function(x){base::round(x/sum*100,digits=3)}),
302
    .SDcols=2:(base::ncol(features_count)-1),by="condition"]
Aurelien Brionne's avatar
Aurelien Brionne committed
303
304
305
306
307
308
309

  ###################
  # graphs
  ###################

    ###################
    # format for plot
310
311
312
313
314
315
    Data=data.table::melt(
      features_frequency,
      id.vars="condition",
      variable.name = "feature",
      value.name = "frequency"
    )
Aurelien Brionne's avatar
Aurelien Brionne committed
316
317
318

    ###################
    # convert feature to factor
319
320
321
322
323
324
    Data[,
      condition:=base::factor(
        Data$condition,
        levels=base::rev(base::names(peaks))
      )
    ]
Aurelien Brionne's avatar
Aurelien Brionne committed
325
326
327
328
329
330
331

    ###################
    # ordering Data
    data.table::setorder(Data,condition)

    ###################
    # ChIPseeker color palette
332
333
    getCols <- function(n){
      col<-base::c("#a6cee3", "#1f78b4", "#b2df8a",
Aurelien Brionne's avatar
Aurelien Brionne committed
334
335
336
              "#33a02c", "#fb9a99", "#e31a1c",
              "#fdbf6f", "#ff7f00", "#cab2d6",
              "#6a3d9a", "#ffff99", "#b15928")
337
      grDevices::colorRampPalette(col)(n)
Aurelien Brionne's avatar
Aurelien Brionne committed
338
339
340
341
    }

    ###################
    # plot colors to display
342
343
    #colors=getCols(base::nlevels(Data$feature))
    colors=getCols(base::length(Features))
Aurelien Brionne's avatar
Aurelien Brionne committed
344

Aurelien Brionne's avatar
Aurelien Brionne committed
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
    ###################
    # features in bar
    ###################

      ###################
      # init plot
      p<-plotly::plot_ly(type = 'bar',
        data=Data, y = ~condition, x = ~frequency,
        color =~feature,colors=colors
      )

      ###################
      # custom margin
      bar<-plotly::layout(p,
        barmode = 'stack',
        margin=base::list(l=250),
        legend=list(traceorder="normal")
      )

    ###################
    # features in lines
    ###################

      ##################
      # init plot
      p<-plotly::plot_ly(type = 'scatter', mode = 'lines',
        data=Data, y = ~condition, x = ~frequency,
        color =~feature,colors=colors)

      ###################
      # custom margin
      lines=plotly::layout(p,
        margin=base::list(l=250),
        yaxis=base::list(title="")
      )

    ###################
    # upset plots
    ###################

    upset_plot<-base::lapply(base::unique(peaks_count$condition),function(x){

      ###################
      # peaks_count subset
      Data<-peaks_count[condition==x]

      ###################
      # cast Data
Aurelien Brionne's avatar
Aurelien Brionne committed
393
      Data<-data.table::dcast(Data,tag~feature_type,value.var="count")
Aurelien Brionne's avatar
Aurelien Brionne committed
394
395
396

      ###################
      # replace NA by 0
397
      Data[base::is.na(Data)]<-0
Aurelien Brionne's avatar
Aurelien Brionne committed
398
399
400
401
402
403
404

      ###################
      # replace  upper 0 by 1
      Data[Data>0]<-1

      ###################
      # features lost
405
      lost_features<-Features[!Features%in%base::names(Data)]
Aurelien Brionne's avatar
Aurelien Brionne committed
406
407
408
409
410
411
412

      ###################
      # add the lost feaures count
      if(base::length(lost_features)>0){

        ###################
        # for each lost feature
413
        for(i in lost_features){
Aurelien Brionne's avatar
Aurelien Brionne committed
414
415
416

          ###################
          # add var with 0 count
417
          Data[,"var":=0]
Aurelien Brionne's avatar
Aurelien Brionne committed
418
419
420
421
422
423
424
425
426

          ###################
          # rename var
          base::names(Data)[base::length(Data)]<-i
        }
      }

      ###################
      # reorder columns
427
      Data<-Data[,base::c("tag",Features),with=FALSE]
Aurelien Brionne's avatar
Aurelien Brionne committed
428
429
430
431
432
433

      ###################
      # create upset
      grDevices::png(base::paste(figs_path,"upset_",x,".png",sep=""))
        UpSetR::upset(Data,sets=base::rev(names(Data)[-1]),
        sets.bar.color=base::rev(colors),
434
        keep.order = TRUE
Aurelien Brionne's avatar
Aurelien Brionne committed
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
        )
      grDevices::dev.off()
    })

    ###################
    # create overlapped_genome_features
    ###################

      ###################
      # createoverlapped_ genome_features
      methods::new("overlapped_genome_features",
       annotation=annot,
       distribution=base::list(
         features_count=features_count,
         features_frequency= features_frequency,
         bar_plot=bar,
         lines_plot=lines
       )
      )
})