Generating qseaSets

library(mesa)
library(stringr)
library(tibble)

Introduction

In this vignette we cover the generation of a qseaSet using the functions provided in mesa, rather than those in qsea. Please see the qsea package vignette vignette("qsea_tutorial", package = "qsea") for more detail, although we cover much of it here.

Sample Metadata

The first thing to prepare is the sampleTable: a data frame containing metadata for the samples to be analysed. This has three required columns:

There are also two optional fields that may be used during generation:

In addition, any further metadata columns may be included as required, and we recommend that anything you might want to query or compare the data on is included here. This includes experimental conditions (tissue, treatment, tumour status, etc.).

We also highly recommend the use of a tool such as NGSCheckMate for verifying that (human) samples come from the same individual or not. This is useful both for ensuring that the enriched and non-enriched samples do indeed come from the same individual, and to check that paired samples are actually paired (for instance when comparing pre- and post-treatment).

For the example here, we use one of the example samples in the MEDIPSData package. The package contains pairs of tumour and normal tissue from the same patients, with MeDIP-seq performed as the enrichment step. These bam files are downsampled to only contain chromosomes 20-22, and are aligned to hg19. Note, we highly recommend using the hg38/GRCh38 reference genome rather than hg19 as used here! For speed, we only use the tumour sample from the first patient, and only chromosome 21.

sampleTable <- tribble(~sample_name, ~group, ~tumour, ~patient, ~file_name,
    "Tumour1", "Tumour1", "Tumour", "Patient1", system.file(
        "extdata", "NSCLC_MeDIP_1T_fst_chr_20_21_22.bam",
        package = "MEDIPSData", mustWork = TRUE
    )
)

Making a qseaSet

The qsea tutorial details the steps involved in generating a qseaSet. We provide a function, makeQset, which wraps these up into one function, although you may still use the rest of the mesa functionality with or without using this to create your qseaSet.

Before creating the qseaSet, you need to have:

For our hg19 example data, we set BSgenome = "BSgenome.Hsapiens.UCSC.hg19", specify the chromosome used from the test dataset and give some approximate fragment length and SD values.

makeQset(sampleTable,
    BSgenome = "BSgenome.Hsapiens.UCSC.hg19",
    chrSelect = "chr21",
    windowSize = 300,
    fragmentLength = 200,
    fragmentSD = 50,
    CNVmethod = "None")
#> Detected parallel setup with 2 workers.
#> 
#> Attaching package: 'Biostrings'
#> The following object is masked from 'package:base':
#> 
#>     strsplit
#> Considering 160432 regions with total size 48129600
#> ==== Creating qsea set ====
#> restricting analysis on chr21
#> Dividing provided regions in 300nt windows
#> Scanning up to 2 files in parallel.
#> Generated objects
#> Calculated coverage
#> No CNV being calculated
#> Get genomic positions of "CG" ...
#> searching chr21 for "CG"...
#> found 380444 occurances of CG in chr21
#> estimating expected number of CGs per fragment for windows of chr21...
#>  ...done
#> selecting windows with low CpG density for background read estimation
#> 6.415% of the windows have enrichment pattern density of at most 0.05 per fragment 
#> and are used for background reads estimation
#> qseaSet object generated successfully
#> qseaSet
#> =======================================
#> 1 Samples:
#> Tumour1
#> 160432 Regions in 1 chromosomes of BSgenome.Hsapiens.UCSC.hg19

A range of messages are produced as output during this process. Note that by default the process is performed without parallelisation; this can be controlled via the setMesaParallel function and will vastly speed up the process when multiple cores are available (but use more RAM).

This function combines several steps:

Selecting the windows

The chosen chromosomes (via chrSelect) of the BSgenome object will be tiled in windowSize windows. These can be filtered for regions which have poor mappability or are overrepresented in non-enriched sequencing, by providing a GRanges object to the badRegions option. If provided, this will remove any window which overlaps with the GRanges object; ensuring that the windows remain fixed when this filtering is changed. The 2019 ENCODE exclusion regions are provided as a data object called ENCODEbadRegions.

Copy Number Variation

The copy number variation is calculated over a set of larger genomic windows as set by CNVwindowSize; this is typically much larger than the windowSize due to coverage limitations. This will be performed using the same options as the enriched samples. Once the coverage is determined, the R package HMMcopy will be used, with default parameters, to calculate the copy number variation. The non-enriched (also known as “Input”) bam files should be specified by adding a column called input_file to the sampleTable. To use this you need to provide HMMcopy with a pair of data frames containing the GC content and mappability per region you wish to calculate over, as detailed in vignette("HMMcopy", package = "HMMcopy"). There is an exception if you are using the human genome hg38 (or GRCh38), in which case files are provided for window sizes of 50kb, 500kb or 1000kb. These are stored in objects called e.g. gc_hg38_1000kb and map_hg38_1000kb; similar objects need to be generated for other genomes or window sizes using the tools gcCounter or mapCounter from the HMMcopy suite.

Alternatively, copy number variation may be calculated using an external method, for instance using the ichorCNA package. This may then be added to the qseaSet object using the qsea function addCNV.

As a further option, qsea provides a method for determining the copy number from the methylation enriched samples, using only reads which do not contain a CG; this may be selected using CNVmethod = "MeCap". We do note that for our MBD-seq experiments we found there was reasonable overall agreement, but this method did give spurious CNV compared to the non-enriched reads, although that may be due to the selectivity of our MBD-seq enrichment step being relatively high.

No copy number variation will be calculated if CNVmethod = "None".

Calculating CpG Density

One essential part of the qseaSet is the CpG_density for each region. This is calculated using the genome sequence, alongside an expected fragment size distribution via the qsea function qsea:::estimatePatternDensity().

This process works by first locating all CG dinucleotides across the genome, before modelling a distribution around each, representing the likelihood for a fragment including that dinucleotide to reach adjacent positions. This distribution is assumed to be normally distributed, with a mean and standard deviation. Thus each CG contributes to the density of the base pairs around it. Finally, these values are averaged across the windows to give a CpG_density column on the regions of the qseaSet. This method is designed to capture the fact that some captured fragments of DNA may be heavily methylated at one end, but if the fragment is long it may be counted in an adjacent window.

This calculation therefore requires the fragmentLength and fragmentSD parameters to be specified, to define these normal distributions, and is associated with the whole qseaSet. This is therefore not sample dependent, and so if samples have vastly different fragment distributions then there will be some expected variation not captured in this process. This does have a significant effect on the calculated beta values for each sample, so it is important to set the fragmentLength and fragmentSD values in an appropriate way. We also provide a fragmentType option, which hardcodes these two parameters to values derived from our initial sheared or cfDNA datasets. When fragmentType = "Sheared" is used this sets fragmentLength = 213, fragmentSD = 60, while fragmentType = "cfDNA" sets fragmentLength = 167, fragmentSD = 38, but we do emphasise that you should check your own data. Ideally the CpG_density would be a property of the fragment distribution of each individual sample, but mesa does not support this at this time.

Please note that these fragmentLength and fragmentSD parameters are only used for calculating this CG density metric; they are not used to control what reads are included in the coverage calculations.

Offset Reads

In any ME-seq experiment, there will be off-target fragments sequenced due to the imperfect nature of the enrichment process. These are used to calculate the offset; a measure of the background level of fragments in windows that do not contain CGs. The maximum CpG_density value for these windows is controlled by maxPatternDensity. If this is set too low, then qsea will give a warning saying that the offset cannot be calculated. In particular, this could be an issue if using a targeted enrichment step in your library preparation method.

Beta Calculation Fitting

Finally, the qsea beta value calculation is applied. This requires the CpG_density and the coverage, as well as some assumption about which regions are methylated, or at least how many of them are. The qsea manuscript details three methods for this assumption, two of which require external data in the form of methylation arrays or bisulphite/enzymatic sequencing. The third method, known as “blind calibration” in the qsea manuscript, is the only one implemented here. This works on a global assumption about the typical methylation levels across the human genome: that the majority of isolated CGs are methylated, while the majority of CpG islands are unmethylated. This blind calibration method therefore assumes an average methylation level of 76% in windows with a CpG_density of 1, falling along a straight line to 25% in windows with a CpG_density of 15. This method is the only one implemented here, as it does not require additional data.

We have found this blind calibration sufficient for the human genome, including being able to build classifiers using methylation arrays as our data source.

If you wish to use array data for normalisation, then this Bioconductor support post may be a good source of information, but we have only used the blind calibration method.

Note on TMM Normalisation

One thing to note is that this function does not set the library_factor for the qseaSet, which qsea suggests doing via the Trimmed Mean of M-values (TMM) method. The way qsea does this is to choose one sample (by default the first sample), and use this as the reference sample to calculate a scaling factor to adjust the total fragments by when calculating the NRPM (normalised reads per million) values.

TMM normalisation is a method used in RNA-seq to compensate for genes which are excessively expressed in a particular condition. In RNA-seq, the distribution of read counts varies over ~4 orders of magnitude, with some highly expressed genes having tens of thousands of reads while others have tens or hundreds. If in a particular tissue there is a group of genes which are extremely highly expressed that are not expressed in another tissue, then the total pool of available reads will be dominated by those genes in the first tissue, comparatively depressing the other genes. So just using the total size ends up biased towards these highly expressed genes, making it look like the other genes are less expressed, and giving many more differentially expressed genes than might actually be the case.

For example, if there are 100 reads in a sample, and 3 genes, with values:

then we want to be careful not to call the last two genes as differentially expressed, when they are really just affected by the lack of the first gene. One option could be to normalise with the median of the read distribution, although, as many genes are not expressed, this is often implemented as an upper quartile.

TMM normalisation however takes some subset of the “genes” (windows in our case), having trimmed off the very high/very low expressed “genes”, to calculate this scaling factor for total number of fragments.

However, we find that for methylation, after filtering for excluded regions, extremely few windows in any sample have more than 100 reads. So the distribution of read counts only spans roughly 0-100, removing the main reason for TMM normalisation.

There are a couple of reasons why we therefore choose not to apply TMM:

However, we note that these considerations might not apply for everyone; the qsea::addLibraryFactors() function may be used to apply this normalisation if required.

Session info

#> R version 4.6.1 (2026-06-24)
#> Platform: x86_64-pc-linux-gnu
#> Running under: Ubuntu 24.04.5 LTS
#> 
#> Matrix products: default
#> BLAS:   /home/biocbuild/bbs-3.24-bioc/R/lib/libRblas.so 
#> LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.12.0  LAPACK version 3.12.0
#> 
#> locale:
#>  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
#>  [3] LC_TIME=en_GB              LC_COLLATE=C              
#>  [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8   
#>  [7] LC_PAPER=en_US.UTF-8       LC_NAME=C                 
#>  [9] LC_ADDRESS=C               LC_TELEPHONE=C            
#> [11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C       
#> 
#> time zone: America/New_York
#> tzcode source: system (glibc)
#> 
#> attached base packages:
#> [1] stats4    stats     graphics  grDevices utils     datasets  methods  
#> [8] base     
#> 
#> other attached packages:
#>  [1] BSgenome.Hsapiens.UCSC.hg19_1.4.3 BSgenome_1.82.0                  
#>  [3] rtracklayer_1.74.0                BiocIO_1.24.0                    
#>  [5] Biostrings_2.82.0                 XVector_0.54.0                   
#>  [7] GenomicRanges_1.66.0              Seqinfo_1.4.0                    
#>  [9] tibble_3.3.1                      org.Mm.eg.db_3.24.6              
#> [11] org.Hs.eg.db_3.24.6               AnnotationDbi_1.76.0             
#> [13] IRanges_2.48.0                    S4Vectors_0.52.0                 
#> [15] Biobase_2.74.0                    BiocGenerics_0.60.0              
#> [17] generics_0.1.4                    stringr_1.6.0                    
#> [19] tidyr_1.3.2                       ggplot2_4.0.4                    
#> [21] mesa_1.0.0                        dplyr_1.2.1                      
#> [23] qsea_1.40.0                      
#> 
#> loaded via a namespace (and not attached):
#>   [1] bitops_1.1-0                             
#>   [2] ggplotify_0.1.4                          
#>   [3] polyclip_1.10-7                          
#>   [4] janitor_2.2.1                            
#>   [5] enrichit_0.2.7                           
#>   [6] XML_3.99-0.25                            
#>   [7] lifecycle_1.0.5                          
#>   [8] doParallel_1.0.17                        
#>   [9] lattice_0.23-1                           
#>  [10] MASS_7.3-66                              
#>  [11] magrittr_2.0.5                           
#>  [12] limma_4.0.0                              
#>  [13] sass_0.5.0                               
#>  [14] rmarkdown_2.32                           
#>  [15] jquerylib_0.1.4                          
#>  [16] yaml_2.3.12                              
#>  [17] plotrix_3.8-14                           
#>  [18] otel_0.3.0                               
#>  [19] ggtangle_0.1.5                           
#>  [20] DBI_1.3.0                                
#>  [21] RColorBrewer_1.1-3                       
#>  [22] lubridate_1.9.5                          
#>  [23] abind_1.4-8                              
#>  [24] purrr_1.2.2                              
#>  [25] RCurl_1.98-1.20                          
#>  [26] yulab.utils_0.2.6                        
#>  [27] tweenr_2.0.3                             
#>  [28] rappdirs_0.3.4                           
#>  [29] gdtools_0.6.0                            
#>  [30] circlize_0.4.18                          
#>  [31] enrichplot_2.0.0                         
#>  [32] ggrepel_0.9.8                            
#>  [33] tidytree_0.4.9                           
#>  [34] ChIPseeker_1.50.0                        
#>  [35] codetools_0.2-20                         
#>  [36] DelayedArray_0.40.0                      
#>  [37] DOSE_4.8.0                               
#>  [38] ggforce_0.5.0                            
#>  [39] shape_1.4.6.1                            
#>  [40] tidyselect_1.2.1                         
#>  [41] aplot_0.3.2                              
#>  [42] UCSC.utils_1.10.0                        
#>  [43] HMMcopy_1.56.0                           
#>  [44] farver_2.1.2                             
#>  [45] matrixStats_1.5.0                        
#>  [46] GenomicAlignments_1.50.0                 
#>  [47] jsonlite_2.0.0                           
#>  [48] GetoptLong_1.1.1                         
#>  [49] iterators_1.0.14                         
#>  [50] systemfonts_1.3.4                        
#>  [51] foreach_1.5.2                            
#>  [52] tools_4.6.1                              
#>  [53] ggnewscale_0.5.2                         
#>  [54] progress_1.2.3                           
#>  [55] treeio_1.38.0                            
#>  [56] TxDb.Hsapiens.UCSC.hg19.knownGene_3.24.0 
#>  [57] ragg_1.5.2                               
#>  [58] Rcpp_1.1.2                               
#>  [59] glue_1.8.1                               
#>  [60] gridExtra_2.3.1                          
#>  [61] SparseArray_1.14.0                       
#>  [62] BiocBaseUtils_1.16.0                     
#>  [63] xfun_0.62                                
#>  [64] MatrixGenerics_1.26.0                    
#>  [65] GenomeInfoDb_1.50.0                      
#>  [66] withr_3.0.3                              
#>  [67] fastmap_1.2.0                            
#>  [68] boot_1.3-32                              
#>  [69] caTools_1.18.4                           
#>  [70] digest_0.6.39                            
#>  [71] timechange_0.4.0                         
#>  [72] R6_2.6.1                                 
#>  [73] gridGraphics_0.5-1                       
#>  [74] colorspace_2.1-4                         
#>  [75] textshaping_1.1.0                        
#>  [76] Cairo_1.7-0                              
#>  [77] GO.db_3.24.0                             
#>  [78] gtools_3.9.5                             
#>  [79] dichromat_2.0-1                          
#>  [80] RSQLite_3.53.3                           
#>  [81] cigarillo_1.4.0                          
#>  [82] UpSetR_1.4.1                             
#>  [83] utf8_1.2.6                               
#>  [84] fontLiberation_0.1.0                     
#>  [85] data.table_1.18.6.1                      
#>  [86] treelayout_0.1.0                         
#>  [87] prettyunits_1.2.0                        
#>  [88] httr_1.4.9                               
#>  [89] htmlwidgets_1.6.4                        
#>  [90] S4Arrays_1.14.0                          
#>  [91] scatterpie_0.2.6                         
#>  [92] pkgconfig_2.0.3                          
#>  [93] gtable_0.3.6                             
#>  [94] MEDIPSData_1.49.0                        
#>  [95] blob_1.3.0                               
#>  [96] ComplexHeatmap_2.30.0                    
#>  [97] S7_1.0.0                                 
#>  [98] htmltools_0.5.9                          
#>  [99] fontBitstreamVera_0.1.1                  
#> [100] clue_0.3-68                              
#> [101] plyranges_1.34.0                         
#> [102] scales_1.4.0                             
#> [103] hues_0.2.0                               
#> [104] TxDb.Hsapiens.UCSC.hg38.knownGene_3.24.0 
#> [105] png_0.1-9                                
#> [106] snakecase_0.11.1                         
#> [107] ggfun_0.2.2                              
#> [108] knitr_1.52                               
#> [109] reshape2_1.4.5                           
#> [110] rjson_0.2.23                             
#> [111] nlme_3.1-172                             
#> [112] curl_8.2.0                               
#> [113] GlobalOptions_0.1.4                      
#> [114] cachem_1.1.0                             
#> [115] zoo_1.9-1                                
#> [116] KernSmooth_2.23-27                       
#> [117] parallel_4.6.1                           
#> [118] restfulr_0.0.17                          
#> [119] pillar_1.11.1                            
#> [120] grid_4.6.1                               
#> [121] vctrs_0.7.3                              
#> [122] gplots_3.3.0                             
#> [123] tidydr_0.0.7                             
#> [124] cluster_2.1.8.3                          
#> [125] evaluate_1.0.5                           
#> [126] magick_2.9.1                             
#> [127] GenomicFeatures_1.66.0                   
#> [128] cli_3.6.6                                
#> [129] compiler_4.6.1                           
#> [130] Rsamtools_2.30.0                         
#> [131] rlang_1.3.0                              
#> [132] crayon_1.5.3                             
#> [133] labeling_0.4.3                           
#> [134] plyr_1.8.9                               
#> [135] fs_2.1.0                                 
#> [136] ggiraph_0.9.7                            
#> [137] stringi_1.8.9                            
#> [138] TxDb.Mmusculus.UCSC.mm10.knownGene_3.10.0
#> [139] BiocParallel_1.48.0                      
#> [140] lazyeval_0.2.3                           
#> [141] GOSemSim_2.40.0                          
#> [142] fontquiver_0.2.1                         
#> [143] Matrix_1.7-6                             
#> [144] hms_1.1.4                                
#> [145] patchwork_1.3.2                          
#> [146] bit64_4.8.6                              
#> [147] KEGGREST_1.54.0                          
#> [148] statmod_1.5.2                            
#> [149] SummarizedExperiment_1.44.0              
#> [150] igraph_2.3.4                             
#> [151] memoise_2.0.1                            
#> [152] bslib_0.12.0                             
#> [153] ggtree_4.4.0                             
#> [154] bit_4.6.0                                
#> [155] ape_5.8-1