High-accuracy epigenetic diagnostics via Nanopore methylation sequencing
MethylSense is a sort-of "semi-automated" R pipeline that trains, tests and cross-validates machine learning models to diagnose clinical infections or inflammatory conditions using (drum roll) epigenetics!
Feed it Nanopore (or Illumina) methylation calls from samples with a known diagnosis, grab a coffee, and it will take you from raw CpG calls all the way to a tested diagnostic classifier and a folder full of publication-ready figures. Rather than hunting for the pathogen itself, MethylSense listens to the host's epigenetic response written in cell-free DNA methylation, which can spot disease even when traditional culture or PCR come up empty.
In practice, the pipeline handles four jobs:
- Find differentially methylated regions (DMRs). It pools CpG calls into genomic windows and, by default, tests the positive class against
--reference_class. Extra groups stay in the classifier. Pass--omnibuswhen the DMR list should instead be every window where any group differs. The default test uses methylKit (Akalin et al., 2012) with Benjamini-Hochberg FDR correction, and batch or study covariates can be included in that same contrast. - Train and honestly validate machine learning classifiers. It turns the top DMRs into candidate marker panels and compares up to ten algorithms through caret (Kuhn, 2008), including Random Forest, SVM, XGBoost, Elastic Net and LDA. Every model can be checked four ways: an independent held-out test set, Monte Carlo cross-validation, nested cross-validation, and an optional leakage-free marker check (
--no_leakage) that satisfies even the sternest Reviewer #2. - Diagnose new, unseen samples. Once you pick a winning model, MethylSense applies it to new patient samples and reports a class prediction, a probability for every group and a confidence flag so uncertain calls are handed to a human instead of guessed blindly.
- Generate publication-ready reports and figures. You get interactive HTML reports plus ROC curves, confusion matrices, CpG-level profiles with Ensembl-style chromosome rulers and gene tracks, UMAP and PCA embeddings, marker stability plots and pre-analytical quality control.
MethylSense was originally built to diagnose Aspergillus fumigatus infection in birds from host cell-free DNA methylation, where it reached about 92% accuracy in Monte Carlo cross-validation (Drag et al., 2026).
- Before you start
- Installation
- Sample sheet
- Quick start
- Example figures
- Output folders
- Command-line reference
- How the models are validated
- Clinical use
- Troubleshooting
- Citation
- Acknowledgements
- Licence and authors
You need CpG methylation calls and genomic windows. MethylSense reads modkit pileup bedMethyl files directly. Two companion pipelines prepare those inputs for you:
| Tool | What it does |
|---|---|
| NanoporeToBED-Pipeline | Converts raw Nanopore modBAM files (from Guppy or Dorado basecalling) into 18-column CpG bedMethyl files using modkit pileup, keeping methylated and unmethylated read counts at every site. Run this first. |
| GenomeToWindows | Slices a reference genome into window BED files (for example 1 kb, 5 kb, 10 kb or 25 kb). Pooling CpGs into windows averages out single-site sequencing noise and gives the differential test enough read depth to see real biological shifts. |
System requirements. R 4.0 or newer (4.2+ recommended) on Linux, macOS or Windows. No special GPU is needed, though extra CPU cores speed up model training nicely.
| Platform | Terminal to use |
|---|---|
| Linux | The built-in Terminal |
| macOS | Terminal (Applications, then Utilities) |
| Windows | MobaXterm (recommended, includes X11 graphics) or WSL2 with Ubuntu |
Clone the repository and let the installer do the heavy lifting:
git clone https://github.com/markusdrag/MethylSense.git
cd MethylSense
Rscript MethylSense_installer.RThe installer checks every required CRAN and Bioconductor package, installs anything that is missing, and prints a clear pass-or-fail summary at the end with hints if a system library is needed. Expect 15 to 45 minutes depending on how many packages you already have, which makes it a great moment to brew a fresh pot of coffee.
Verify that everything loaded cleanly:
Rscript -e "library(methylKit); library(caret); library(xgboost)"
Rscript MethylSense_load_data.R --helpInstall the packages by hand instead
# CRAN packages
install.packages(c(
"optparse", "qs2", "caret", "pROC", "ggplot2", "hrbrthemes", "dplyr", "tidyr",
"randomForest", "e1071", "glmnet", "nnet", "class", "MASS",
"klaR", "ranger", "xgboost", "pheatmap", "RColorBrewer",
"data.table", "readxl", "reshape2", "viridis", "corrplot",
"factoextra", "ggridges", "gridExtra", "ggrepel", "naivebayes",
"tree", "rpart", "rpart.plot", "cluster", "jsonlite", "MLmetrics",
"doParallel", "foreach", "pls", "PRROC", "igraph", "umap",
"dendextend", "lme4", "nlme", "MuMIn", "ez", "fossil", "patchwork"
))
# Bioconductor packages
if (!require("BiocManager", quietly = TRUE)) install.packages("BiocManager")
BiocManager::install(c("methylKit", "GenomicRanges", "genomation", "regioneR", "IRanges"))MethylSense writes methylation objects in the fast .qs2 format. Older .qs files are still accepted as input whenever the qs package is installed. CRAN may refuse qs on R 4.6 and later, which only affects reading those older files.
Every run starts with a sample sheet in Excel (.xlsx) or CSV format, with one row per sample. Think of it as the map that tells MethylSense which bedMethyl file belongs to which individual, what group they are in, and what technical metadata to watch out for.
ID Species bedFileOrg treatMethylkit Infection
control_1 Gallus_gallus control_1.CpG.bed 0 Control
suspected_1 Gallus_gallus suspected_1.CpG.bed 1 Suspected
infected_1 Gallus_gallus infected_1.CpG.bed 2 Infected
Required columns
| Column | Why it is needed | Example |
|---|---|---|
ID |
Unique sample name stored inside the methylKit object. Duplicate IDs stop the run on purpose so samples can never get silently overwritten. | sample_001 |
Species |
Species name, used by --species so one master spreadsheet can hold several species without mixing them up. |
Gallus_gallus |
bedFileOrg |
Filename of the modkit pileup bedMethyl file (13 or 18 columns, plain or .gz), relative to --bed_dir. |
sample_001.CpG.bed |
treatMethylkit |
Whole-number group code required by methylKit, such as 0 = Control, 1 = Suspected, 2 = Infected. Put NA for unseen patient samples that will only be predicted. |
0, 1, 2 |
Numeric codes are great for computers and terrible for figures, so --group_names turns them into readable labels in ascending code order (or use --treatment_mapping 0=Control,1=Suspected,2=Infected to be explicit). Plot colours are then picked automatically from the MethylSense palette based on the group names (Control gets green, Suspected gets teal and Infected gets purple), or you can supply your own with --group_colors.
Optional columns (well worth adding)
| Column | Why it helps | Example |
|---|---|---|
Infection |
Readable group label used by the reviewer and data overview scripts. | Control |
Study |
Study or cohort name, used to check whether performance holds across cohorts. | Study_A |
Batch |
Sequencing or extraction batch, which you can adjust for during DMR calling with --covariate_cols. |
Batch_1 |
| Pre-analytical QC | Numeric lab and handling variables. The reviewer tests these against your markers to check that your "disease signature" is not secretly just which freezer or sequencer a sample sat in. It also auto-detects columns whose names include words like storage, hemolysis, concentration, extraction or quality. |
storage_time_days, hemolysis_index |
Animal_ID, Lab_ID |
Animal and laboratory identifiers for traceability. | Bird_42 |
The example_data folder ships a ready-to-run dataset: sample_metadata_30.csv lists 30 simulated chickens (ten Control, ten Suspected and ten Infected) along with their bedMethyl files and realistic technical metadata. Sample sheets from versions before 6.1.0 often include a bedFile column for legacy 8-column files, which is safely ignored so older sheets still work.
This tutorial walks through the bundled 30-sample chicken dataset from raw bedMethyl files to a full model audit and a live diagnosis of three mystery birds. On a 4-core laptop the whole walkthrough takes roughly 25 to 30 minutes (or around 20 minutes if you omit --no_leakage for a quick test).
Rscript MethylSense_load_data.R \
--species Gallus_gallus \
--sample_sheet ./example_data/sample_metadata_30.csv \
--bed_dir ./example_data \
--output_dir ./preprocessedWhat happens here: Each sample's bedMethyl file is read straight from modkit pileup, filtered to a single modification code (5mC by default) and minimum read depth, and packed into one compressed methylKit object (*_methylRaw.qs2). Before finishing, the script reads that .qs2 file back and compares it site by site against the original bedMethyl files, checking that methylated and unmethylated columns were not swapped and that read counts add up. Every sample gets a PASS, WARN or FAIL in *_load_QC_report.txt so bad inputs get caught before you spend an hour training models on nonsense. The bundled example files are written so this step finishes with PASS on every sample.
Rscript MethylSense_analysis.R \
--qs_file ./preprocessed/*_methylRaw.qs2 \
--output_dir ./training \
--window_file ./example_data/windows/windows_5kb.bed \
--group_names Control,Suspected,Infected \
--positive_class Infected \
--reference_class Control \
--models lda,svm,rf \
--marker_range 4:10 \
--cv_repeats 5 \
--nested_cv --nested_cv_repeats 3 \
--no_leakage \
--cpg_report --gtf_file ./example_data/simulated_annotations.gtfWhat happens here: This is the workhorse of MethylSense, taking about 15 to 20 minutes on the example data. Step by step, it:
- Calls DMRs across every 5 kb genomic window in
--window_file, correcting for multiple testing with Benjamini-Hochberg FDR. - Builds candidate marker panels from the top-ranked DMRs, testing every size in
--marker_range 4:10(from 4 up to 10 markers) for each algorithm in--models. - Evaluates on an independent test set. 30% of samples are held out before training (
--test_ratio 0.3), giving a clean, untouched test check. - Runs Monte Carlo CV and nested CV.
--cv_repeats 5runs repeated random 60/40 splits, while--nested_cv --nested_cv_repeats 3adds nested cross-validation that retunes hyperparameters inside each training fold without peeking at the held-out fold. - Checks for marker-selection leakage (
--no_leakage). By default, DMRs are selected once using all samples before cross-validation starts. That is fast, but it can nudge CV accuracy upward because the held-out samples helped pick the marker list. Adding--no_leakagekeeps the usual cross-validation and also runs a stricter second pass that repeats themethylKitdifferential methylation test inside each training fold, picks markers using only those training animals, and scores the held-out animals. Each fold's differential test is cached and reused across models and marker sizes, so you only pay the DMR cost once per split. The final saved model still uses the full-cohort markers (which is what you want for future patients), whilereport/ANALYSIS_REPORT.htmlprints both accuracies side by side along with the accuracy gap and how often each training fold rediscovered the same DMRs. The fold-by-fold marker lists are saved inmarker_selection_check/. - Draws CpG-level profiles (
--cpg_report --gtf_file). Zooms into the top DMRs to plot methylation at every CpG, with a genomic ruler, the genes that overlap the window, and one row per bird.
When it finishes, results live in a folder named after your settings, such as ./training_bed_q0050_cov10_..._noleakcheck/. Open report/ANALYSIS_REPORT.html first. It ranks every model, displays the top-10 table with confidence intervals, and shows the Marker-selection check table from --no_leakage.
Tips for your own data
- Colours and styling: Override group colours with
--group_colors '#1B5E20,#006064,#4A148C'(in the same order as--group_names), and switch the R figure layout with--plot_style(natureis the default, or pickclean,prism,bmjorminimal).--plot_engine autoredraws the main figures in Python when matplotlib, numpy, pandas and scipy are available, and keeps the R figures otherwise.--plot_engine rstays in ggplot.- Speeding up exploration: Drop
--no_leakageand--cpg_reportwhile experimenting with window sizes or cutoffs, then turn them back on for your final publication run.- Searching wider: On real cohorts, a broader
--marker_range(such as2:50) and several window sizes (--region_dir ./windows) are well worth testing.
Pick a strong model folder from report/ANALYSIS_REPORT.html. In our run of the example, linear discriminant analysis (lda) with 5 markers came out on top.
Rscript MethylSense_reviewer.R \
--model_dir ./training_*/windows_5kb/lda/markers_5 \
--qs_file ./preprocessed/*_methylRaw.qs2 \
--sample_sheet ./example_data/sample_metadata_30.csv \
--sample_id_column ID \
--treatment_column Infection \
--storage_column storage_time_days \
--technical_covariates cfDNA_concentration_ng_uL,hemolysis_index,time_to_processing_hours,extraction_quality_score \
--output_dir ./reportWhy bother reviewing a model that already scored well? Because a high accuracy number on its own is very good at hiding trouble. In 1 to 2 minutes, MethylSense_reviewer.R builds MODEL_EVALUATION_REPORT.html and asks all the awkward questions you would rather catch before a journal referee does:
- Do the ROC curves and confusion matrices hold up across the test set, Monte Carlo CV and nested CV?
- Do the chosen DMRs survive bootstrap resampling (
marker_stability), or were they lucky flukes? - Do the biological groups separate cleanly in UMAP and PCA space?
- Are storage time, cfDNA concentration, haemolysis or processing delay secretly driving the methylation values (
preanalytic_qc)?
Time for the actual clinical moment of truth. Three mystery birds live in example_data/unknown_samples with NA in their group columns so MethylSense has no idea what they are. First pack them into a .qs2 file just like Step 1, then run MethylSense_predict.R with your trained model:
Rscript MethylSense_load_data.R \
--species Gallus_gallus \
--sample_sheet ./example_data/unknown_samples/unknown_samples_metadata.csv \
--bed_dir ./example_data/unknown_samples \
--output_dir ./unknown_preprocessed
Rscript MethylSense_predict.R \
--model_dir ./training_*/windows_5kb/lda/markers_5 \
--qs_file ./unknown_preprocessed/*_methylRaw.qs2 \
--output_dir ./unknown_predictionsWhat happens here: The prediction script reads the exact DMR coordinates from your model folder, extracts methylation in those windows for each new sample (filling any uncovered marker with the training median saved in feature_medians.csv), and outputs a probability for every class. Samples whose highest probability reaches the confidence threshold (0.7 by default) get a clear call, while lower-confidence cases are flagged for manual review or confirmatory testing. Look inside *_predictions_detailed.csv, *_predictions_clinical_report.csv and *_prediction_summary.txt.
Drum roll, please. Here is how the 5-marker LDA model from this tutorial classifies the three mystery birds:
| Sample | True group | Predicted | Confidence | P(Control) | P(Suspected) | P(Infected) |
|---|---|---|---|---|---|---|
| unknown_1 | Control | Control | 0.987 (High) | 0.987 | 0.013 | 0.000 |
| unknown_2 | Infected | Infected | 1.000 (High) | 0.000 | 0.000 | 1.000 |
| unknown_3 | Suspected | Suspected | 0.995 (High) | 0.000 | 0.995 | 0.005 |
Three for three, all with high confidence.
Rscript MethylSense_general_data_overview.R \
--analysis_dir ./training_* \
--sample_sheet ./example_data/sample_metadata_30.csv \
--region_sizes 5000 \
--output_dir ./data_overview \
--infection_col Infection \
--sample_id_col ID \
--study_col Study \
--species_col Species \
--species Gallus_gallusThis exploratory script zooms out across your entire DMR dataset to draw volcano plots, DMR counts per window size, read-coverage distributions, chromosome ideograms, hyper-versus-hypomethylation summaries and heatmaps of the top DMRs. It shines most when you have run multiple window sizes (such as 1 kb, 5 kb, 10 kb and 25 kb) and want to see at a glance which scale captures the biology best.
Every figure below comes from the Quick start on the 30-sample chicken dataset. The model is linear discriminant analysis (LDA) with 5 markers of 5 kb, the highest cross-validated accuracy in a screen of six model types across 4 to 12 markers. These drawings are the Python figures. A run uses them automatically when matplotlib, numpy, pandas and scipy can be imported, and keeps the ggplot figures otherwise.
Marker signature
Each faint line is one bird and the bold traces are the group means. Hypermethylated markers sit on the pink side and hypomethylated markers on the blue side, with a colour tile under each marker. The lower left panel overlays the methylation densities for every marker, and the lower right panel shows the pooled nested-CV calls as jittered points.
Confusion matrices: independent test set, Monte Carlo CV and nested CV
The three panels are the held-out test set, Monte Carlo CV and nested CV. Each cell gives the count and the share of the actual group. The text under each panel name is accuracy, sensitivity and specificity, and the CV panels report those as mean ± SD across folds.
One-vs-rest ROC curves for every group, plus an overall micro-average
A small test set (here 9 samples) produces a staircase, so the Monte Carlo and nested CV curves are drawn on top. AUC for each curve is printed in the panel.
CpG-level profile with gene annotation (--cpg_report --gtf_file)
The window is chr4:33,770,000-33,775,000. Genes and regulatory features sit on the genomic ruler, each bird is a row in the middle, and the curves are group means with a standard-error band. The lollipops are the Infected-minus-Control difference at each CpG.
DMR Manhattan plot
CpG-level Manhattan plot
Technical variables against the markers
Linear models test every pre-analytical variable against every marker with FDR correction. All grey bars is the boring, wonderful result you want: none of the technical variables explains the markers.
Example classification tree
An illustrative tree of depth 3 fitted to the same 5 markers. It shows one way the panel can separate the groups.
Each script generates many more figures than shown here, so poke around the output directories for the full set.
training_bed_q0050_.../
├── 00_how_to_read.txt # Read this first
├── report/ # Ranked models, open the HTML
│ ├── ANALYSIS_REPORT.html # Ranks every model and shows the no-leakage check
│ ├── ANALYSIS_REPORT.md
│ ├── analysis_summary.csv # One row per model and marker count
│ └── analysis_settings.txt # Exact parameters and command
├── log/
│ └── run_log.txt
├── train_and_test_animals/ # Which animals trained each model, and which were held out
├── marker_selection_check/ # With --no_leakage: windows chosen inside each training set
├── methylation_at_each_cpg/ # With --cpg_report: methylation at every CpG
└── windows_5kb/ # One folder per window size
├── differential_methylation/
│ ├── tables/ # Which regions differ, and by how much
│ └── plots/ # Manhattan plot
└── lda/ # One folder per model
└── markers_5/ # This model, using 5 windows
├── model.rds
├── feature_medians.csv
├── model_summary.txt
├── windows_in_this_model/
│ ├── tables/ # Coordinates and methylation values
│ └── plots/ # Bar plot, heatmap, group summary
├── predictions/
│ ├── tables/ # Calls for animals the model did not train on
│ └── plots/ # ROC, precision-recall, confusion matrix
├── repeated_splits/
│ ├── tables/
│ └── plots/
└── random_forest/ # Only when the model is a random forest
└── plots/
report/
├── MODEL_EVALUATION_REPORT.html # Start here: full clinical and statistical review
├── MODEL_EVALUATION_REPORT.md
├── ANALYSIS_SUMMARY.txt
├── figures/ # Every figure embedded in the report
├── model_performance/ # Confusion matrix, ROC, one-vs-rest metrics
├── marker_stability/ # Bootstrap selection frequency and fragility
├── batch_effects/ # PCA and UMAP coloured by each covariate
├── preanalytic_qc/ # Technical variables tested against markers
├── dmr_network/ # Co-methylation network of the selected markers
└── qc_checks/
Every script prints its complete list of flags with --help. The tables below are grouped by task and tucked into collapsible sections so your scroll wheel survives the page. Click any script to expand it.
MethylSense_load_data.R: read bedMethyl files into a verified methylKit object
| Option | Default | Description |
|---|---|---|
--species |
required | Species to load, matching the sample sheet |
--sample_sheet |
required | Sample sheet (Excel or CSV) |
--bed_dir |
required | Folder with the bedMethyl files named in bedFileOrg |
--output_dir |
required | Writes the .qs2 object, *_load_QC_report.txt, *_load_QC.csv and *_preprocessing_summary.txt. A failed check renames the object *_QC_FAILED.qs2 and stops the run. |
--assembly |
auto | Genome assembly name |
--cores |
20 | CPU cores |
--min_coverage |
1 | Minimum reads per CpG (modified plus unmodified). 0 keeps sites with no reads. |
--mod_code |
auto | Modification code in column 4. auto uses the only code, or m (5mC) when there are several. Files made with --combine-mods use C. |
--mapq_column |
none | Sample sheet column with each sample's mean MAPQ. Use with --min_mapq. |
--min_mapq |
none | Keep samples with mean MAPQ at or above this value. Dropped samples are listed in the summary. |
--allow_missing |
off | Continue without samples whose file is missing, instead of stopping |
--write_nond |
off | Also write a legacy 8-column *_CpG_nonD.txt file per sample |
--keep_first |
off | Treat repeated sites as version 6.0.3 did, keeping the first row. Also writes the nonD files. |
--force_convert |
off | Ignored since 6.1.0. Accepted so older job scripts still run. |
--no_parallel |
off | Disable parallel processing |
Example with sample-level MAPQ filtering:
Rscript MethylSense_load_data.R \
--species Gallus_gallus \
--sample_sheet ./samples.xlsx \
--bed_dir ./bed_files \
--output_dir ./preprocessed \
--mapq_column mean_mapping_quality \
--min_mapq 25 \
--cores 8How bedMethyl columns are used. Files come straight from modkit pileup (column definitions). Files with 13 or 18 columns, plain or .gz, are accepted, including older modkit files that separate columns 10 to 18 with spaces. Column 11 may be a percent or a fraction, and is used only to confirm column 12. A swapped file or counts that do not add up stop the run. Repeated rows for the same site and strand are merged, which is reported as a warning. Both strands are kept. Rebuild objects made before 6.1.0.
| Column | modkit name | Stored as |
|---|---|---|
| 1 | chrom | chr |
| 2 | start (0-based) | start (end is start + 1) |
| 4 | modification code | one code, set with --mod_code |
| 6 | strand | strand (- stays -, anything else is +) |
| 10 | N valid coverage | not stored, used to check counts |
| 11 | fraction modified | not stored, used to confirm column 12 |
| 12 | N mod | numCs, methylated reads |
| 13 | N canonical | numTs, unmethylated reads |
| 14 | N other mod | not stored, used to check counts |
Coverage is numCs + numTs. This equals column 10 unless column 14 holds other modifications, which are left out.
MethylSense_analysis.R: find DMRs and train models
Input and models
| Option | Default | Description |
|---|---|---|
--qs_file |
required | The .qs2 object from load_data |
--output_dir |
required | Output folder prefix |
--window_file |
One window BED file, such as windows_5kb.bed |
|
--bed_files |
Several window BED files, comma-separated | |
--region_dir |
A folder of window BED files | |
--sample_sheet |
Sample sheet, needed for --covariate_cols |
|
--models |
rf,glmnet,xgboost |
Models to train (see the model table below) |
--marker_range |
2:50 |
Marker panel sizes to train, as min:max |
--cores |
8 | CPU cores |
Groups
| Option | Default | Description |
|---|---|---|
--group_names |
auto | Group names in code order, which also sets the plot order |
--group_colors |
auto | Colours in the same order as the names |
--positive_class |
required | The case group. The run stops if this is omitted. |
--reference_class |
required | The control group. The difference and the q-value are the case minus this group. The marker file stores it as negative_class. |
--omnibus |
off | Select DMRs with an any-group test. The q-value asks whether any group differs. The difference is the spread across groups, and --hyper_threshold is the minimum spread. The classifier still uses --positive_class. |
--treatment_mapping |
Explicit codes, such as 0=Control,1=Infected |
|
--min_group_size |
4 | Minimum samples per group |
--allow_small_groups |
off | Allow smaller groups (results may be unreliable) |
Validation
| Option | Default | Description |
|---|---|---|
--test_ratio |
0.3 | Share of samples held out as the independent test set |
--train_test_file |
Excel file with a predefined train and test split | |
--cv_repeats |
10 | Monte Carlo CV repeats. 0 turns CV off. |
--nested_cv |
off | Also run nested CV, which retunes the model inside each training set |
--nested_cv_repeats |
1 | Repeats of the whole nested CV with new seeds. Use 5 for publication. |
--no_leakage |
off | Also repeat the DMR test inside each CV training set (see below) |
--min_accuracy |
0.7 | Models below this test accuracy are not saved |
--reproducible |
off | Fixed random seeds |
DMR detection
| Option | Default | Description |
|---|---|---|
--qval, --qvalue_threshold |
0.05 | FDR cutoff for a DMR |
--overdispersion |
none | none (binomial test), MN, or shrinkMN |
--min_coverage |
10 | Minimum covered bases in a window |
--hyper_threshold |
5.0 | Minimum difference (%) for a hypermethylated DMR |
--hypo_threshold |
-2.0 | Maximum difference (%) for a hypomethylated DMR |
--disable_meth_filter |
off | Use the q-value only |
--covariate_cols |
Sample sheet columns to adjust for, such as Batch,Study |
|
--exclude_sex_chroms |
off | Leave out X, Y, Z and W |
--filter_standard_chroms |
off | Keep chromosomes 1 to 99 and the sex chromosomes |
--min_samples_per_region |
1.0 | Minimum share of samples covering a window |
Figures
| Option | Default | Description |
|---|---|---|
--plot_format |
png | png, jpeg, svg, all, or a pair such as png,svg |
--plot_dpi |
300 | Resolution |
--plot_style |
nature | nature, clean, prism, bmj or minimal. Used when the figures stay in R. |
--plot_engine |
auto | auto redraws the main figures in Python when matplotlib is available. python or r force one engine. |
--cpg_report |
off | CpG-level table, Manhattan plot and profiles of the top DMRs. Memory hungry on large data. |
--cpg_top_dmrs |
20 | Number of DMRs that get a CpG profile |
--gtf_file |
GTF file for the gene track in CpG profiles | |
--no_plots |
off | Skip all figures |
Other
| Option | Default | Description |
|---|---|---|
--force_ml |
off | Re-run even when cached results exist |
--verbose |
off | More output |
--debug |
off | Debug mode |
Available models
| Model | Code | Speed | Good for |
|---|---|---|---|
| Random forest | rf |
Medium | General use and feature importance |
| Fast random forest | ranger |
Medium | Large datasets |
| Support vector machine | svm |
Slow | Non-linear boundaries |
| XGBoost | xgboost |
Slow | Gradient boosting |
| Elastic net | glmnet |
Fast | Sparse, interpretable marker panels |
| Linear discriminant analysis | lda |
Fast | Small, well-separated panels |
| Logistic regression | logreg |
Fast | Linear baseline |
| Naive Bayes | nb |
Fast | Baseline |
| k-nearest neighbours | knn |
Fast | Baseline |
| Neural network | nnet |
Medium | Complex non-linear patterns |
Shortcuts for --models: all (every model), fast (knn, lda, glmnet, nb, logreg), interpretable (glmnet, lda, nb, logreg) and biomarker (xgboost, rf, glmnet, ranger, svm).
Example matching Drag et al. (2026):
Rscript MethylSense_analysis.R \
--qs_file ./preprocessed/Chicken_n124.qs2 \
--output_dir ./results/Chicken_Aspergillosis \
--region_dir ./windowed_genomes \
--group_names Control,Aspergillus_Infected \
--positive_class Aspergillus_Infected \
--reference_class Control \
--treatment_mapping '0=Control,1=Aspergillus_Infected' \
--models nnet,glmnet,lda,knn,rf,nb,svm \
--marker_range 2:50 \
--min_accuracy 0.8 \
--hyper_threshold 5.0 --hypo_threshold -2.0 \
--min_coverage 10 \
--test_ratio 0.4 \
--cv_repeats 10 --nested_cv --nested_cv_repeats 5 \
--no_leakage \
--exclude_sex_chroms --filter_standard_chroms \
--plot_format all \
--cores 8MethylSense_reviewer.R: evaluate one model in depth
Input
| Option | Default | Description |
|---|---|---|
--model_dir |
required | A markers_N folder from the analysis |
--qs_file |
required | The .qs2 object used for training |
--sample_sheet |
required | Sample sheet |
--sample_id_column |
SampleID |
Column with sample IDs (ID in the example data) |
--treatment_column |
treatment |
Column with group labels (Infection in the example data) |
--output_dir |
model_evaluation |
Output folder |
--data_dir |
Folder with the train and test files, if not in --model_dir |
|
--model_name |
auto | Name used in the report title |
--n_cores |
4 | CPU cores |
--verbose |
off | More output |
Statistics
| Option | Default | Description |
|---|---|---|
--bootstrap_iterations |
500 | Bootstrap resamples for marker stability |
--stability_threshold |
0.70 | Selection frequency for a stable marker |
--effect_size_threshold |
2.0 | Effect size (%) marked on the stability plot |
--min_effect_size |
5.0 | Minimum methylation difference (%) |
--multiple_testing |
fdr | fdr, bonferroni, holm, BY or none |
--significance_threshold |
0.05 | P-value threshold |
--stratified_cv_folds |
5 | Folds for the reviewer's own CV |
--cv_repeats |
3 | Repeats for the reviewer's own CV |
--control_group |
auto | Reference group for logistic regression |
Technical variables and time
| Option | Default | Description |
|---|---|---|
--batch_column |
Batch or platform column | |
--storage_column |
Storage time column | |
--technical_covariates |
Other technical columns, comma-separated | |
--lmm_n_markers |
all | Number of markers tested against technical variables |
--date_column |
Collection date column | |
--time_analysis |
Time point column, for longitudinal data | |
--time_categorical |
off | Treat time as categories |
Annotation and networks
| Option | Default | Description |
|---|---|---|
--enable_feature_annotation |
off | Annotate DMRs with genomic features |
--gtf_file |
GTF or GFF file with genes | |
--regulatory_gff |
Regulatory features (enhancers, CTCF) | |
--emar_gff |
EMAR regions | |
--open_chromatin_bed |
Open chromatin regions | |
--chromatin_flank_bp |
2000 | Flank around open chromatin regions |
--gene_window |
10000000 | Distance (bp) for nearest genes |
--enable_gene_annotation |
off | Gene annotation through biomaRt |
--species |
Species for annotation, such as Gallus gallus |
|
--functional_enrichment |
off | Functional enrichment |
--enable_wgcna |
off | WGCNA co-methylation network |
--prepare_pcr |
off | Primer design links for the top DMRs |
--pcr_n_dmrs |
20 | DMRs to prepare for PCR |
Report and figures
| Option | Default | Description |
|---|---|---|
--generate_markdown |
on | Markdown and HTML report |
--generate_pdf |
off | PDF report as well (needs Chrome or Chromium) |
--markdown_title |
auto | Report title |
--markdown_author |
Author names | |
--figure_format |
png | png, jpg, svg or all |
--figure_resolution |
300 | Resolution |
--plot_style |
nature | nature, clean, prism, bmj or minimal. Used when the figures stay in R. |
--plot_engine |
auto | auto redraws the main figures in Python when matplotlib is available. python or r force one engine. |
--group_colors |
auto | Group colours |
--blind_paths |
off | Hide folder paths in the report |
Example matching Drag et al. (2026):
Rscript MethylSense_reviewer.R \
--model_dir ./results/svm/markers_35 \
--qs_file ./preprocessed/Chicken_n124.qs2 \
--sample_sheet ./AsperMerged_v3.xlsx \
--model_name "Fast Model Diagnostic Test" \
--technical_covariates SEQUENCER,cfDNA_conc_ng_uL,number_of_reads,mapping_percentage,mean_coverage \
--time_analysis Sample_Week \
--bootstrap_iterations 1000 \
--stability_threshold 0.75 \
--enable_wgcna --prepare_pcr --functional_enrichment \
--enable_feature_annotation \
--gtf_file ./genomes/Gallus_gallus.GRCg7b.108.gtf \
--regulatory_gff ./genomes/Gallus_gallus.GRCg7b.regulatory_features.gff3 \
--emar_gff ./genomes/Gallus_gallus.GRCg7b.EMARs.gff \
--open_chromatin_bed ./genomes/openchrom-union.bed \
--figure_format jpg,svg \
--blind_paths --generate_pdf \
--n_cores 8MethylSense_predict.R: diagnose new samples
| Option | Default | Description |
|---|---|---|
--qs_file |
required | The .qs2 object with the new samples |
--model_dir |
required | A markers_N folder from the analysis |
--output_dir |
required | Output folder |
--sample_ids |
all | Only predict these samples, comma-separated |
--min_coverage |
10 | Minimum covered bases in a marker window |
--confidence_threshold |
0.7 | Minimum top probability for a call |
--plots |
off | Diagnostic plots |
--batch_mode |
off | Skip plots for single samples |
--verbose |
off | More output |
MethylSense_general_data_overview.R: explore the DMR landscape
| Option | Default | Description |
|---|---|---|
--analysis_dir |
required | The analysis output folder |
--sample_sheet |
required | Sample sheet |
--region_sizes |
1000,...,25000 | Window sizes (bp) to include |
--infection_col |
InfectionStatus |
Group column (Infection in the example data) |
--sample_id_col |
Lab_ID |
Sample ID column (ID in the example data) |
--study_col |
STUDY...3 |
Study column (Study in the example data) |
--species_col |
Species |
Column used by --species |
--species |
all rows | Keep only these species |
--output_dir |
dmr_landscape_overview |
Output folder |
--group_colors |
auto | Group=colour,... or colours in order |
--plot_format |
png | png, jpg, svg or pdf |
--plot_style |
nature | nature, clean, prism, bmj or minimal. Used when the figures stay in R. |
--plot_engine |
auto | auto redraws the main figures in Python when matplotlib is available. python or r force one engine. |
--plot_width, --plot_height |
12, 8 | Size in inches |
--plot_dpi |
300 | Resolution |
--volcano_meth_threshold |
5 | Methylation difference (%) in the volcano plot |
--volcano_q_threshold |
0.05 | Q-value in the volcano plot |
--top_n_label |
10 | DMRs labelled in the volcano plot |
--heatmap_top_n |
50 | DMRs in the heatmap |
--generate_pdf |
off | PDF report as well |
--blind_paths |
off | Hide folder paths in the report |
Figures for journals
All scripts write 300 DPI PNG files by default, which already fits most journals. For print submission, request vector files as well:
| Script | Options |
|---|---|
MethylSense_analysis.R |
--plot_format png,svg --plot_dpi 600 |
MethylSense_reviewer.R |
--figure_format png,svg --figure_resolution 600 |
MethylSense_general_data_overview.R |
--plot_format svg --plot_dpi 600 |
Nature and Science prefer vector formats at 300 to 600 DPI. PLoS and BMC accept 300 DPI PNG or TIFF. Elsevier asks for 300 DPI for photos and 1000 DPI for line art.
A diagnostic model is only as trustworthy as the way it was tested. MethylSense scores every model under three schemes and shows all three side by side in the confusion matrices and ROC panels.
| Independent test set | Monte Carlo CV | Nested CV | |
|---|---|---|---|
| How | 30% of samples held out from the start (--test_ratio) |
Repeated random 60/40 splits (--cv_repeats) |
K non-overlapping folds, with tuning inside each training fold (--nested_cv) |
| Tuning | On the training set | Internal CV on each training split | A separate inner loop that never sees the outer test fold |
| Speed | Fast | Fast | 5 to 10 times slower |
| Best for | A quick, clean sanity check | Development and comparing models | Publication-grade performance estimates |
| Output | predictions/tables/ |
repeated_splits/tables/cv_summary_*.csv |
repeated_splits/tables/nested_cv_summary_*.csv |
With --nested_cv_repeats N the whole nested procedure is repeated with fresh random seeds, giving K × N evaluations. Comparing Monte Carlo CV with nested CV reveals how much optimism comes from hyperparameter tuning (Varma & Simon, 2006).
In all three schemes above, the DMR list is chosen once across the whole cohort before cross-validation starts. That keeps runtime friendly, though a strict reviewer will rightly ask whether letting held-out samples participate in DMR discovery flattered the accuracy.
Add --no_leakage to answer that question directly. MethylSense still runs the regular cross-validation, and also runs a second, leakage-free pass where methylKit calls DMRs inside each outer training fold using only that fold's training animals, ranks them with the exact same q-value and methylation-difference cutoffs, trains the classifier on those fold-specific markers, and scores only the animals left out.
Rscript MethylSense_analysis.R \
--qs_file ./data.qs2 \
--output_dir ./results \
--group_names Control,Infected \
--positive_class Infected \
--reference_class Control \
--cv_repeats 10 --nested_cv --nested_cv_repeats 5 \
--no_leakageHow to read the result. report/ANALYSIS_REPORT.html and report/analysis_summary.csv report both numbers side by side:
- Gap is all-animal accuracy minus training-set-marker accuracy. A gap near zero means marker selection did not inflate your score.
- Shared markers is the share of each training fold's panel that also sits in the full-cohort panel. A value near 100% means the same DMRs keep winning no matter which animals are held out.
- Per-fold coordinates are saved under
marker_selection_check/so you can inspect exactly which markers every training fold picked.
The saved model.rds still uses the full-cohort marker list so your final diagnostic panel benefits from all available data. Because the check has to rerun the differential methylation test, it needs a fresh analysis run rather than a precomputed marker matrix. Each training split's differential test is cached and reused across all models and marker sizes. On a 27-pig cohort with 10 kb windows, each extra differential test took roughly one minute.
MethylSense is a research tool. It has not been approved by the FDA, EMA or any other regulator for clinical diagnosis, and its predictions should always be interpreted alongside clinical findings and established diagnostics. A model trained on one species needs separate validation before being used on another.
How cfDNA methylation diagnosis works
Cell-free DNA (cfDNA) enters the bloodstream when cells die, carrying the methylation signature of its tissue of origin. During infection, damaged host cells release cfDNA with characteristic methylation changes that differ from healthy individuals. MethylSense reads that host epigenetic response rather than hunting for pathogen DNA directly. This makes it a natural partner to PCR and culture, especially when pathogen load is low or tucked away in a deep lesion.
Both serum and plasma work. Serum was used in the original study and often yields slightly more cfDNA. Plasma (EDTA, citrate or heparin) can have less genomic DNA background from lysed blood cells. Whichever you choose, stick to one sample type within a study.
Sample processing used in Drag et al. (2026)
| Step | Specification |
|---|---|
| Sample | 200 µL serum or plasma |
| Pre-extraction | Centrifuge 2 min at 400 × g to remove residual cells |
| DNA extraction | Norgen Biotek cfDNA Micro Kit (cat. 55500) or another dedicated cfDNA kit |
| Quality control | Bioanalyzer 2100, High Sensitivity DNA kit, confirming a cfDNA peak near 160 to 180 bp |
| Storage | -80 °C (extracted cfDNA stays stable for months) |
| Library | Native Barcoding Ligation Kit (SQK-NBD114.24), 11 µL cfDNA input. Multiply bead clean-up ratios by 2.5× to retain short cfDNA fragments (Martignano et al., 2023). |
| Sequencer | PromethION P2 Solo or MinION (any ONT platform) |
| Flow cell | R10.4.1 (version 14 chemistry) |
| Basecalling | Guppy 6.5.7 or Dorado, high accuracy, model dna_r10.4.1_e8.2_400bps_modbases_5mc_cg_hac.cfg |
| Methylation calls | modkit 0.1.2 or later, pileup with CpG combined |
| Reference | Gallus gallus bGalGal1.mat.broiler.GRCg7b, or the matching genome for your species |
Standard genomic DNA extraction kits wash away short cfDNA fragments, so always use a cfDNA kit.
Reading a prediction
Confidence is simply the highest predicted probability across all classes for a given sample.
| Confidence | Probability | How to act on it |
|---|---|---|
| High | above 80% | Strong methylation match for the predicted group |
| Medium | 60 to 80% | Moderate signal. Confirm with another test (culture, PCR, endoscopy or imaging) before deciding treatment. |
| Low | below 60% | Weak or ambiguous signal. Do not act on it. Check sample quality or consider resequencing. |
Common reasons for low confidence include degraded cfDNA or low DNA input, genomic DNA contamination from lysed blood cells, low sequencing coverage, very early infection before the host responds, an atypical or immunocompromised patient, or a species mismatch with the training cohort.
Pre-trained models
Avian aspergillosis (chicken, n = 124). Over 95% accuracy in nested cross-validation. Trained models, DMR coordinates and validation results are available on Zenodo (10.5281/zenodo.15194046).
For other species and diseases, get in touch at markus.drag@sund.ku.dk.
| Problem | What to try |
|---|---|
| A package is missing | Run Rscript MethylSense_installer.R again |
xgboost models fail |
Install MLmetrics (the installer already includes it) |
| Too few samples per group | Add --allow_small_groups, keeping in mind that groups under 10 samples can easily overfit. 20 or more per group is much happier. |
| Out of memory | Use larger windows (--window_file windows_10kb.bed), fewer models, or leave out --cpg_report |
| Training is taking forever | Try --models fast, a narrower --marker_range, fewer --cv_repeats, or save --no_leakage for your final run |
| No model is saved | Every model landed below --min_accuracy. Lower the threshold, or inspect the group separation in the report. |
| The reviewer cannot find your samples | Point --sample_id_column and --treatment_column at the exact column names in your sample sheet |
Typical runtimes for 30 to 50 samples, two groups and 8 CPU cores:
| Step | Runtime | Memory |
|---|---|---|
| load_data | 5 to 10 min | 2 to 4 GB |
| analysis without CV | 20 to 30 min | 4 to 8 GB |
| analysis with 10 CV repeats | 60 to 90 min | 4 to 8 GB |
| analysis with nested CV | 2 to 3 hours | 4 to 8 GB |
| reviewer | 5 to 10 min | 2 to 4 GB |
| general_data_overview | 5 to 15 min | 2 to 6 GB |
| predict | 1 to 2 min | 1 to 2 GB |
When any script starts, it prints the MethylSense package version (matching the badge at the top) followed by its own script version, which can be lower when only other scripts changed.
If you use MethylSense in your research, please cite:
Drag MH, Hvilsom C, Poulsen LL, Jensen HE, Tahas SA, Leineweber C, Cray C, Bertelsen MF, Bojesen AM. MethylSense: high accuracy machine learning-based diagnostics for Aspergillus fumigatus infection in chickens using host cell-free DNA methylation and Nanopore sequencing. J Clin Microbiol. 2026;0:e01054-25. https://doi.org/10.1128/jcm.01054-25
MethylSense stands on the shoulders of the R and Bioconductor communities.
- methylKit runs the differential methylation test. Akalin A, Kormaksson M, Li S, Garrett-Bakelman FE, Figueroa ME, Melnick A, Mason CE (2012). methylKit: a comprehensive R package for the analysis of genome-wide DNA methylation profiles. Genome Biology, 13, R87. https://doi.org/10.1186/gb-2012-13-10-r87
- caret trains, tunes and cross-validates the models. Kuhn M (2008). Building Predictive Models in R Using the caret Package. Journal of Statistical Software, 28(5), 1-26. https://doi.org/10.18637/jss.v028.i05
- pROC computes ROC curves and AUC. Robin X, Turck N, Hainard A, Tiberti N, Lisacek F, Sanchez JC, Müller M (2011). pROC: an open-source package for R and S+ to analyze and compare ROC curves. BMC Bioinformatics, 12, 77. https://doi.org/10.1186/1471-2105-12-77
MethylSense also relies on GenomicRanges (Lawrence et al., 2013), ggplot2 (Wickham, 2016), patchwork, randomForest (Liaw & Wiener, 2002), xgboost (Chen & Guestrin, 2016), glmnet (Friedman et al., 2010), e1071, ranger, pheatmap and RColorBrewer.
Further references
DNA methylation
- Bird A (2002). DNA methylation patterns and epigenetic memory. Genes & Development, 16(1), 6-21.
- Jones PA (2012). Functions of DNA methylation: islands, start sites, gene bodies and beyond. Nature Reviews Genetics, 13(7), 484-492.
Nanopore methylation
- Simpson JT, Workman RE, Zuzarte PC, David M, Dursi LJ, Timp W (2017). Detecting DNA cytosine methylation using nanopore sequencing. Nature Methods, 14(4), 407-410.
Statistics
- Benjamini Y, Hochberg Y (1995). Controlling the false discovery rate: a practical and powerful approach to multiple testing. Journal of the Royal Statistical Society: Series B, 57(1), 289-300.
- Varma S, Simon R (2006). Bias in error estimation when using cross-validation for model selection. BMC Bioinformatics, 7, 91.
Licence: Academic Free License 3.0 (AFL-3.0). See LICENSE.
Lead developer: Markus Hodal Drag
Co-authors: Christina Hvilsom, Louise Ladefoged Poulsen, Henrik Elvang Jensen, Stamatios Alan Tahas, Christoph Leineweber, Carolyn Cray, Mads Frost Bertelsen, Anders Miki Bojesen
Contact: markus.drag@sund.ku.dk or GitHub Issues















