Core Workflow#

The modality XPLR Core Workflow is a simple-to-use analysis tool that leverages bash scripting to automate key modality XPLR commands on biomodal data contained in the Zarr stores. The Core Workflow is well-suited for exploration of pilot study data, or for new users who want rapid insights from their data through a standardised, low-code approach.

For experienced users who want a deep dive into the Core Workflow script, proceed directly to the Advanced analysis workflow documentation.

This section describes how to set up and run the modality XPLR Core Workflow. The Core Workflow runs on two types of Zarr store (see Zarr stores for more details), which can be provided together or separately:

Context-level Zarr stores

Zarr stores containing CpG, CHG or CHH context methylation count data. They are used for Biological QC, region-based feature extraction and DMR calling. The region-based analyses are only applicable to context-level zarr store analyses. Region files are required to follow the BED3+ format (see Region files for details on the required format) passed to modality XPLR via the --bedfile flag.

The core workflow is pre-configured for biomodal 6-base datasets (including 5mC, 5hmC, and optionally modC) and chains together a series of analysis steps. It is compatible with any reference genome for which the duet multiomics solution has produced a Zarr store for. While any reference genome can be analysed, the core workflow is pre-configured to analyse gene bodies and promoter regions only although additional region files can be added as needed. See the Pre-prepared annotation files section in the main documentation for more information on how the pre-prepared region files were generated.

  • Gene bodies: gencode.v44.human.genes.annotation.v1.1.0.bed.gz

  • Promoter regions: gencode.v44.human.promoters.annotation.v1.1.0.bed.gz

The region-based analyses can be run on any reference genome, provided that you supply region files (BED/TSV) for that reference genome.

Fragment-level Zarr stores

Zarr stores containing duet fragmentomics data storing both fragment length and 5’ end motif information for each fragment. Fragment length and 5’ end motif features are extracted genome-wide. Regional analyses are not applicable on the fragmentomics data.

Quick runnable example

For getting up and running quickly, a small, directly runnable mouse GRCm38 example dataset can be downloaded with all relevent resources to run the core workflow, see Download a test dataset.

Analyses & Outputs#

The Core Workflow performs the following analyses and outputs:

Biological QC

  1. biological-qc to summarise the dataset and sample information, with Pearson correlation and PCA plots for genome-wide 5mC, 5hmC, and optionally modC data. See Biological QC for more information.

  2. get mean to generate a .tsv.gz data file and support violin and correlation plots, showing the mean CpG coverage in gene bodies and promoter regions. Context depth filter is not applied to this command. See Extracting methylation statistics for more information on this and other get commands.

  3. get regional-frac to generate a .tsv.gz data file and support violin and correlation plots, showing the fraction of 5mC, 5hmC, and optionally modC (over total_c) in gene bodies and promoter regions, with an optional minimum depth filter applied.

  4. get count to generate a .tsv.gz data file containing the total number of contexts (total_c) in each gene body and promoter region. Context depth filter is not applied to this command, as it is not applicable to the count command.

Biological insight

  1. dmr call to identify differentially methylated regions (DMRs) in gene bodies and promoter regions, for 5mC, 5hmC, and optionally modC contexts, across all specified groups with an optional context depth filter applied. By default, the command generates two sets of results: one with overdispersion correction (_with_od_*.bed) and one without (_without_od_*.bed), stored in a single timestamped DMR_ directory for easy comparison. This command generates separate .bed files for each methylation context and group pair. See Calling differentially methylated regions (DMRs) for more information.

  2. The DMR results can then be visualised in modality XPLR Viewer, including volcano plots, p-value distribution histograms and Manhattan plots. The Viewer allows DMR filtering by significance and export of the filtered results.

  3. The Viewer also supports generation of track plots for individual DMRs, showing the methylation signal across samples in the region. Custom track plots can be configured further using the .ini file generated with each DMR result, via the CLI command modality tracks.

  4. get fragment-stats and get end-motif-stats to extract genome-wide fragmentomics features from fragmentomics Zarr stores, for each sample: the relative frequency of each fragment length, together with the fragment size ratio and fragment size entropy, and the frequency of each 5’ end-motif. Each command generates .tsv.gz data files that can be compared between samples. Region files and the context depth filter do not apply to these commands. See Extracting fragmentomics statistics for more information.

  5. The fragmentomics results can then be visualised in the Fragmentomics Results tab of modality XPLR Viewer, including fragment length distribution, fragment length ratio by entropy and end-motif frequency plots.

The Core Workflow is well-suited for studies involving:

  • Disease vs control comparisons

  • Treatment vs untreated samples

  • Time-course experiments

  • Multi-group studies with covariates

Video: Running the modality XPLR Core Workflow#

Requirements and prerequisites#

Software requirements:

  • modality XPLR (version 1.1.0 or later is recommended, see Installation of modality XPLR)

  • Bash shell (version 4.0 or later)

  • Standard Unix utilities (awk, sed, find, etc.)

Data input and format requirements:

  • Zarr store(s): Context level and/or Fragment level Zarr store

  • Region files: Region files in BED3+ format used to define regional analyses for context-level Zarr analysis by placing in the Regions directory (not applicable for fragmentomics Zarr analysis).

  • Sample metadata: .csv or .tsv file with sample information, group names and optional covariates (also referred to as the sample sheet). See Sample sheet for the required formatting for the sample sheet.

  • Config file: Configuration file called config.txt used by the Core Workflow specifying the above input parameters as well as other CLI analysis settings. This file is generated using the generator tool (Interactive Core Workflow generator).

Core Workflow configuration#

For ease-of-use, the Core Workflow can be configured and downloaded using the Interactive Core Workflow generator tool below. This generator allows you to specify input parameters, and then download a complete .zip folder containing the:

  • Core Workflow script: core-workflow-v3.0.sh

  • Configuration file: config.txt

  • Pre-prepared region files for GRCh38: gencode.v44.human.genes.annotation.v1.1.0.bed.gz & gencode.v44.human.promoters.annotation.v1.1.0.bed.gz

Core Workflow folder contents:

modality-core-workflow_YYYYMMDD_HHMMSS/
├── core-workflow-v3.0.sh                              # The Core Workflow script
├── config.txt                                         # Configuration file for modality XPLR commands
├── Regions/                                           # Directory containing pre-prepared region files
│   ├── gencode.v44.human.genes.annotation.v1.1.0.bed.gz
│   └── gencode.v44.human.promoters.annotation.v1.1.0.bed.gz
├── README.txt                                         # Usage instructions
└── Output/                                            # Output directory(created during execution)

Interactive Core Workflow generator#

🔧 Core Workflow generator

Generate the modality XPLR Core Workflow .zip folder with a standardised directory structure. The folder name is timestamped upon creation and includes the workflow script, configuration file, and pre-prepared genomic region files. The displayed form values below are examples only, and must be replaced in order to populate the config.txt. After generating the .zip folder, a preview panel will appear. Check that your settings have been written correctly. * denotes required fields

Comma-separated paths. Used by the context-level analyses: Biological QC, region-based feature extraction and DMR calling. Provide this and/or a fragmentomics store below (at least one required).
Comma-separated paths. Used by the fragmentomics analyses (fragment-stats and end-motif-stats), which run genome-wide and do not use region files. Optional.
Path to your sample metadata CSV or TSV file. Used by both context-level and fragmentomics analyses.
Column name in your metadata CSV or TSV file for sample grouping. Used by the context-level analyses only (sample ordering in the Biological QC and feature extraction plots, and the groups compared in DMR calling). Required if you provide a context-level zarr store; not used by the fragmentomics analyses.
Space-separated order of conditions (control group first). Used by context-level DMR calling only.
Space-separated covariate column names from your metadata. Used by context-level DMR calling only.
Select a region to limit the Biological QC to a specific region e.g. "chr" or "chr:<start>-<end>". This can help to speed up analysis and reduce memory usage. Used by context-level Biological QC only.
Minimum context depth for regional-frac and DMR analysis e.g. 10. Leave blank to disable depth filtering. Used by context-level analyses only.
Include modC modification type in biological-qc, feature extraction, and DMR calling. Default is true. Used by context-level analyses only.
Overdispersion correction: "true" (with correction), "false" (without correction), or "both" (produces two result files, with and without correction). Core Workflow default is "both". Used by context-level DMR calling only.

Running the Core Workflow#

To run the Core Workflow, follow these steps:

  1. Download the Core Workflow .zip folder to your working location and extract it.

  2. In the terminal, run the following lines.

# Change to the Core Workflow directory
cd /path/to/modality-core-workflow_YYYYMMDD_HHMMSS

# Make the script executable
chmod +x core-workflow-v3.0.sh

# Run the Core Workflow script
./core-workflow-v3.0.sh
  1. Monitor the output logs for progress and any potential errors.

Advanced Core Workflow usage#

The config.txt file contains all the parameters for running the Core Workflow script. You should not need to modify this file, as it is pre-configured by the Interactive Core Workflow generator. Advanced users can modify the config.txt file to change parameters such as the Zarr store paths (context-level and fragmentomics), metadata file, group column, covariates, and minimum depth filter. In addition, the Output directory path can be changed to a different location if required. Each parameter, the format of its value and the analyses it affects are described in Advanced configuration file setup. This may be useful if you want to re-run the analysis with different parameters (e.g. context depth filter, or covariates), without needing to download the Core Workflow folder again.

It is also possible to provide additional region files in the Regions/ directory, or to change the region files used by the Core Workflow. Region files only affect the context-level analyses: each file is passed to the modality XPLR commands with the --bedfile flag, for region-based feature extraction and DMR calling. Refer to the main documentation for the required format of the Region files. Apart from the Biological QC HTML report (which operates on Zarr store(s)), the Core Workflow will perform all context-level analysis steps on each region file found in the Regions/ directory. The fragmentomics analyses are genome-wide and do not use region files.

For advanced users who are familiar with bash scripting, a description of the Core Workflow code is provided in the Advanced analysis workflow section, which can be used to customise the workflow further.

Interpreting Core Workflow outputs#

The Core Workflow generates a comprehensive set of outputs organised into structured directories. Understanding this organisation is crucial for interpreting results and sharing findings. Each analysis produces timestamped outputs and provenance metadata for traceability and reproducibility of the results.

The workflow organises outputs with BioQC_ (timestamped biological QC results) and Extract_ (timestamped fragmentomics feature extraction results) directories directly under the main output directory. Region-specific subdirectories (one per region file) each contain Extract_ (in this case context-level feature extraction results) and DMR_ (DMR calling results) timestamped subdirectories. When overdispersion mode is set to both (default), each DMR analysis produces two BED files with _with_od_* and _without_od_* suffixes (followed by timestamps) for easy comparison.

Video: Reviewing Core Workflow results#

Output directory structure#

A modality_cli.log file is generated in the working directory and contains logging information relating to the modality XPLR CLI commands only (not the Core Workflow bash outputs). This file is generated automatically by modality XPLR and is not directly controlled by the Core Workflow script. Other outputs are described below.

Output/
├── BioQC_YYYYMMDD_HHMMSS/                            # Biological QC results directory
│   ├── biological_qc_report_*.html                   # Biological QC HTML report
│   └── modality_metadata_YYYYMMD_HHMMSS.json         # Provenance metadata file
├── Extract_YYYYMMDD_HHMMSS/                          # Fragment-level feature extraction results (fragment-stats)
│   ├── Extract_fragment-stats_*.tsv.gz               # Fragment length frequencies, fragment size ratio and entropy
│   └── modality_metadata_YYYYMMDD_HHMMSS.json        # Provenance metadata file
├── Extract_YYYYMMDD_HHMMSS/                          # Fragment-level feature extraction results (end-motif-stats)
│   ├── Extract_end-motif-stats_*.tsv.gz              # Epigenetic end-motif frequencies
│   ├── Extract_end-motif-stats_Genetic_*.tsv.gz      # Genetic (4-base) end-motif frequencies
│   └── modality_metadata_YYYYMMDD_HHMMSS.json        # Provenance metadata file
├── <region_file_name_1>/                             # Results for first region bedfile (e.g. genes)
│   ├── Extract_YYYYMMDD_HHMMSS/                      # Feature extraction results directory
│   │   ├── Extract_*.tsv.gz                          # Feature extraction results file (compressed)
│   │   ├── Extract_*.html                            # Violin and Correlation plots (mean and regional-frac operations only)
│   │   └── modality_metadata_YYYYMMD_HHMMSS.json     # Provenance metadata file
│   └── DMR_YYYYMMDD_HHMMSS/                          # DMR analysis results directory
│       ├── DMR_*.bed                                 # DMR result files (see note below)
│       ├── DMR_*.ini                                 # Configuration files for making track plots with the 'tracks' CLI command
│       └── modality_metadata_YYYYMMD_HHMMSS.json     # Provenance metadata file
├── <region_file_name_2>/                             # Results for second region bedfile (e.g. promoters)
│   ├── Extract_YYYYMMDD_HHMMSS/
│   └── DMR_YYYYMMDD_HHMMSS/
└── <region_file_name_N>/                             # Results for Nth region bedfile
    ├── Extract_YYYYMMDD_HHMMSS/
    └── DMR_YYYYMMDD_HHMMSS/

Note

DMR filename conventions vary by overdispersion correction setting:

  • --overdispersion both (Core Workflow default): Produces two files per analysis with patterns _with_od_*.bed (with correction) and _without_od_*.bed (without correction), where * represents the timestamp

  • --overdispersion true or --overdispersion false: Produces one file per analysis named DMR_*.bed (no suffix). The overdispersion setting is recorded in the provenance metadata JSON file.

Reviewing results#

  1. Initiate modality XPLR Viewer

    • Start a Viewer session by invoking the modality viewer command in the terminal.

    • In the command, specify the root directory (-r) as the main output directory of the Core Workflow.

    • Navigate to the indicated localhost URL in your web browser to access the Viewer interface.

  2. Biological QC

    • Click on the tab for BioQC Results and open the analysis card for the Biological QC report.

    • Check sample clustering in the genome-wide PCA analysis. Use the colour-based grouping options directly on the report page to visualise sample relationships. Groups are defined by the metadata (sample sheet) file.

    • Verify expected grouping patterns. Does the data make biological sense for your experimental design?

    • Identify any outlier samples.

    • Assess overall sample mean CpG coverage in the Sample Information table. You can optionally export the metadata table including the per-sample CpG strand-merged coverage information.

    • Click on the tab for Extract Results, and filter to the region-specific analysis cards containing the modification types of interest.

    • Review the region-specific feature extraction plots (violin plots and correlation heatmaps) for mean CpG coverage, and 5mC and 5hmC fractions (and modC if included in the analysis). These visualisations provide insights into feature distributions and sample correlations.

  3. Biological insights

    • Click on the tab for DMR Results, then filter to the region-specific analysis cards containing the group comparisons and modification types of interest.

    • By default, the Core Workflow runs with overdispersion mode set to both, which produces two BED files for each analysis: one with overdispersion correction (_with_od_*.bed) and one without (_without_od_*.bed). You can toggle between these results on the analysis card in the Viewer. The overdispersion correction is designed to improve p-value distributions and DMR detection in datasets with high variability or small sample sizes. We recommend reviewing results with overdispersion correction first, then comparing to results without correction. Be sure to check the p-value distributions to determine which setting is most appropriate for your data.

    • The DMR comparison report shows all selected analyses on one page. To view a detailed DMR Report (including p-value distribution and Manhattan plot) for a single analysis, click the report icon above the respective volcano plot.

    • Apply significance filters and plot configurations via the available settings. Export images and filtered DMR result files as needed.

    • Note the region annotations in the DMR results table, which can be used to gain further biological insights into the DMRs.

    • Select a single DMR to see tracks plot options. Alternatively use the accompanying .ini files to generate custom tracks plots using the modality tracks CLI command.

    • If a fragmentomics Zarr store was provided, click on the tab for Fragmentomics Results and select an analysis card with your``fragment-stats`` and end-motif-stats result files.

    • Compare the fragment length distribution, fragment size ratio and fragment size entropy between samples. Compare the 5’ end-motif frequencies between samples, using the epigenetic and genetic (4-base) results.

    • The fragmentomics results are written per sample. To colour or group samples by a metadata label, select a sample sheet in the analysis options of the report page. See Applying metadata labels.

  1. Validate findings

    • Check for consistency with known biology

    • Consider experimental design and potential confounders

    • Compare overdispersion-corrected vs uncorrected results (both provided when using --overdispersion both)

    • Use track plots to validate DMRs in surrounding context.

    • Plan follow-up validation experiments or to increase sample size if necessary

Common result patterns and interpretation#

Healthy DMR patterns:

  • Detection of significant DMRs between experimental groups

  • Consistent p-value distributions (uniform with some enrichment near zero)

  • Biologically meaningful effect sizes

  • Concordant patterns between 5mC and 5hmC where expected

Potential issues to watch for:

  • Poor group separation: May indicate experimental design issues

  • Skewed p-value distributions: May benefit from Overdispersion correction or other statistical adjustments

  • Very large effect sizes: May indicate technical artifacts

  • Inconsistent patterns: Could suggest batch effects or confounders

Biological interpretation guidelines:

  • Promoter hypermethylation: Often associated with deactivated regions

  • 5hmC enrichment: Often associated with active demethylation (transition to active regions), or a marker of active gene bodies.

  • Concordant changes: 5mC loss with 5hmC gain may suggest active demethylation

Advanced analysis workflow#

This section provides a more detailed description of the Core Workflow bash script, which may be beneficial to users who want to modify the script directly or build their own workflows.

The direct download link to the Core Workflow script is provided below, which provides the .sh file only.

Download: core-workflow-v3.0.sh - Core Workflow script assembled from all code sections below.

Download a test dataset#

You can download a test folder containing mouse ES-E14 data to run the Core Workflow. The outputs are not intended to reveal biological insight, as the samples are technical replicates. However, it can be used to test that the script runs to completion.

The E14-example test folder contains:

  • A sample metadata file E14_chromosome_19.tsv

  • A zarr store E14_chromosome_19.zarrz containing methylation data

  • A directory Regions containing gencode.vM25.mouse.promoters.annotation.bed

  • A config.txt file with example parameters

Download: E14-example.zip

Note

The E14-example.zip does not contain the core-workflow-v3.0.sh script. This will need to be downloaded separately and run from within the E14-example directory after extraction.

Advanced configuration file setup#

The Core Workflow uses a simple config.txt file for all settings. This design separates configuration from code, making it easy to run the same pipeline with different datasets or parameters. If you are new to modality XPLR or have not yet run the Core Workflow, we suggest using the Interactive Core Workflow generator to get started.

Configuration file:

This file must be present in your working directory before running the pipeline, with the name config.txt. Alternatively use the Advanced interactive configuration file generator below to create this file with additional options. The aim of the config.txt is to pre-define all parameters required by the workflow script. If you modify the Core Workflow script to include additional options or settings, these can be added to the config.txt as variables. See Modifying the Core Workflow script. For the Core Workflow, the config.txt file should contain the following parameters (parameter values are examples):

Zarr_Context_Level=/path/to/context_level.zarrz
Zarr_Fragmentomics=/path/to/fragment_level.zarrz
Metadata=/path/to/metadata.csv
Group_Column=label
Condition_Order=condition1 condition2
Covariates=age batch sex
QC_Region=chr1
Regions_Directory=/path/to/regions
Main_Output=/path/to/output_dir
Depth_Filter=5
Include_modC=true
Overdispersion=both

Configuration parameters explained:

Each parameter below states the analyses it affects: the context-level steps (Biological QC, context-level feature extraction and DMR calling), the fragmentomics step (fragmentomics feature extraction), or both.

  • Zarr_Context_Level: Path to one or more context-level zarr stores. Separate multiple paths with commas. Used by the context-level steps. The older parameter name Zarr is also accepted and is treated as Zarr_Context_Level

  • Zarr_Fragmentomics: Path to one or more fragmentomics zarr stores. Separate multiple paths with commas. Used by the fragmentomics step

  • Metadata: Path to .csv or .tsv sample sheet file containing sample metadata. Used by both context-level and fragmentomics analyses

  • Group_Column: Column name in the metadata file, for grouping samples (e.g., “treatment” or “condition”). Used by the context-level steps; leave it blank for a fragmentomics-only run

  • Condition_Order: Space-separated list of conditions (optional) (e.g., “control treatment”). The first condition is used as the control group. Used by context-level DMR calling

  • Covariates: Space-separated list of covariate columns (optional) (e.g., “age batch sex race”). Used by context-level DMR calling

  • QC_Region: Region specification for Biological QC analysis (optional) (e.g., “chr1” or “chr1:1000-2000”). Used by context-level Biological QC only

  • Regions_Directory: Directory containing BED/TSV files in BED3+ format, with genomic regions and annotations. See Region files for details. Each file is passed to the modality XPLR commands with --bedfile, so it is used by the context-level steps only and is not needed for a fragmentomics-only run

  • Main_Output: Base directory where all results will be written. Used by both context-level and fragmentomics analyses

  • Depth_Filter: Minimum depth filter for analyses (leave it blank to disable filtering). Used by context-level get regional-frac and DMR calling

  • Include_modC: Include modC modification type in analyses (“true” or “false”, optional, default: true). Used by the context-level steps

  • Overdispersion: Overdispersion mode for DMR analysis: “true”, “false”, or “both” (optional, Core Workflow default: both). When set to “both”, produces two BED files per analysis—one with and one without overdispersion correction. Used by context-level DMR calling

At least one of Zarr_Context_Level and Zarr_Fragmentomics is required, together with Metadata and Main_Output. Regions_Directory is also required when a context-level zarr store is provided. If only one type of zarr store is provided, the steps that need the other type are skipped.

For a description of Sample sheet and Region files formats, see the linked modality XPLR documentation sections.

The config.txt can be generated using the Advanced interactive configuration file generator below or created manually in a text editor.

Advanced interactive configuration file generator#

🔧 Advanced Configuration File Generator

Use this form to generate and download your the config.txt file. A download link for the core-workflow-v3.0.sh is also provided. The displayed values are indications only, and must be replaced in order to populate the config.txt. After generating the file, a preview panel will appear. Check that your settings have been written correctly.

Comma-separated paths. Drives Biological QC, feature extraction and DMR calling. Provide this and/or a fragmentomics store below (at least one required).
Comma-separated paths for fragmentomics analyses (fragment-stats, end-motif-stats). Optional.
Column name in the metadata (sample sheet) file to be used for retrieving sample groups
Space-separated order of conditions (control group first)
Space-separated list of covariate column names, in the metadata (sample sheet) file
Select a region to limit the Biological QC to a specific region e.g. "chr" or "chr:<start>-<end>". This can help to speed up analysis and reduce memory usage.
Directory containing pre-prepared BED/TSV region definition files (e.g. promoters, genes etc.)
Main output directory, in which all results and reports will be saved.
Minimum context depth for regional-frac and DMR analysis e.g. 10. Leave blank to disable depth filtering.
Include modC modification type in biological-qc, feature extraction, and DMR calling. Default is true.
Overdispersion correction: "true" (with correction), "false" (without correction), or "both" (produces two result files, with and without correction). Core Workflow default is "both".

Core Workflow overview: step-by-step#

The Core Workflow script first reads and validates the inputs in config.txt and creates the output directories. It then runs the analysis steps described below, in order. Steps that need a Zarr store type that is not provided in config.txt are skipped.

Verbosity and logging#

The Core Workflow script prints a timestamped message at each stage of the run, so that you can monitor progress and spot problems.

Verbosity of the modality XPLR commands:

Every modality command in the script is run with -v, which displays informational messages, warnings and errors in the terminal. To display detailed debugging information, change -v to -vv. To display warnings and errors only, remove the flag. See Setting verbosity levels for more information.

Debug variable in the script:

The DEBUG variable is set near the start of the script, in the same block as CONFIG_FILE, which holds the name of the configuration file.

#------------------------------------------------------------------------------
# INITIALISATION
#------------------------------------------------------------------------------
printf "\n=======================================\n"
printf "STEP 0 - CONFIGURATION & INITIALISATION\n"
printf "=======================================\n"
log_info "Starting modality XPLR Core Workflow Pipeline"

# Default values for variables that could be customised
CONFIG_FILE="./config.txt"
DEBUG=false  # Set to true to enable debug output

Setting DEBUG to true enables the log_debug helper function, which prints messages prefixed with [DEBUG]. The script does not call log_debug itself, so changing DEBUG has no effect unless you add log_debug messages to your own modifications of the script. To get more detail from the analysis commands, use -vv as described above.

Saving the output to a log file:

To write the script output to a file as well as to the terminal, uncomment the two lines under Log file setup near the top of the script (the lines beginning # LOG_FILE= and # exec >). The output is then appended to a file named modality_pipeline_<YYYYMMDD>_<HHMMSS>.log in the working directory.

The modality XPLR commands also write their own log file, modality_cli.log, to the working directory.

Step 1: Context-level: Biological QC HTML report#

The first analysis step performs biological quality control to provide Zarr store summaries, and to identify sample relationships.

What this script block does:

  • Generates correlation matrices between samples for 5mC and 5hmC (and modC if included)

  • Creates PCA plots to visualise sample clustering for each methylation context (grouping options are available on the Viewer report page)

  • Calculates mean CpG coverage for each sample

Key parameters:

  • Uses all zarr stores specified in configuration (config.txt)

  • Allows sample metadata to be used for dynamic colour-based grouping, when available

Note

The Core Workflow does not include the --aggregate-by-group option, which could be included to aggregate sample data for technical replicates prior to QC.

Expected outputs:

  • biological_qc_report.html: HTML report with sample-wise plots and statistics.

  • Provenance metadata .json files, stored in each Results/BioQC_YYYYMMDD_HHMMSS sub-directory that is generated by each modality XPLR CLI command.

Interpreting QC results:

  • Correlation heatmaps: Correlation coefficients close to 1 indicate high similarity of 5mC and 5hmC (and modC if included) levels between samples

  • PCA plots: Separation and/or clustering between experimental groups indicates the % variability that is explained by the first two principal components, for 5mC and 5hmC (and modC if included).

  • Coverage statistics: The mean CpG coverage per sample is an indicator of the usable depth for methylation analysis. See the next step for feature extraction (region-based) coverage statistics.

  • Outlier detection: Samples that don’t cluster with their expected group may need investigation. Removing a sample from the metadata (sample sheet) file will exclude it from future analysis, without needing to modify the original Zarr file.

Step 2.1: Context-level: Region-based Biological QC#

This step used the modality get tool to extract methylation features (statistics) from user-specified genomic regions, for additional quality control and analysis. The regions can be defined in BED3+ format (.bed` or ``.tsv) files, that are accessible in the REGIONS_DIR, defined in config.txt. For the Core Workflow script to run correctly, region files must be present. Pre-prepared annotation files are provided to get started, or custom files following the same format can be used instead. Use the correct region files for the reference genome used for alignment in the duet Software.

Tip

The Annotation (e.g. gene, or promoter) and Name (e.g. associated gene name) columns should be completed for meaningful interpretation.

The pipeline performs multiple types of statistics extraction to provide comprehensive regional methylation data. Each statistic type is processed separately by modality XPLR, and the results are stored in timestamped Extract_* subdirectories within each region-specific folder.

Note

Only modality get mean and modality get regional-frac commands support plotting (correlation or violin), which are useful for visualising the distribution of methylation levels across samples. If no HTML report is generated, then the results will only be written as .tsv.gz files within the respective Extract_* timestamped subdirectories.

What this script block does:

  • Count extraction: Returns the total number of CpG contexts (total_c) for each region.

  • Mean calculation: Average coverage of CpG contexts (total_c) for each region, with violin and correlation plots for individual samples.

  • Regional fraction: Methylation fractions for 5mC and 5hmC (and modC if included) at the pre-specified minimum``DEPTH_FILTER`` value, with violin and correlation plots for individual samples.

  • Processes each region file in the REGIONS_DIR independently. Therefore, expect individual results for each region file and extraction type.

Expected outputs:

  • Extract_* directories: Organised by statistic type and region file

  • *.tsv.gz files: Compressed quantitative results for each extracted statistic, by region and sample

  • *.html reports: Interactive violin and correlation plots showing methylation statistics for mean and regional-frac extraction types.

Note

The optional regional dendrogram heatmap is not included in the Core Workflow script by default but can be added to the HTML report by modifying the modality get mean and/or modality get regional-frac command(s) to include --heatmap. Note that the heatmap will only be drawn if there are ≤200 regions in the region file, so it is not appropriate for use with all promoters and gene bodies. Instead, add a custom subset region file to the Regions directory before running the Core Workflow. Alternative tools for generating heatmaps are available in modality Viewer.

Interpreting region-based Biological QC statistics:

  • Region-specific CpG coverage: Should show adequate and consistent coverage across samples and may be used to inform the DEPTH_FILTER value for future analyses.

  • Methylation fraction distributions: Violin and correlation plots reveal methylation heterogeneity.

  • Outlier samples: Samples with unusual distributions may need investigation.

Customising statistics extraction:

You can modify this section of the script to:

  • Add different field types (see Zarr stores and Extracting methylation statistics sections in the main modality XPLR documentation).

  • Adjust minimum coverage thresholds for regional fraction extraction.

  • Include additional statistical summaries (count, mean, sum, regional-frac).

  • Add an optional --heatmap parameter to generate regional dendrogram heatmaps for mean and/or regional-frac extraction types with ≤200 regions. Alternative tools for generating heatmaps are available in modality Viewer.

Step 2.2: Fragment-level: Extracting Relative frequencies of Fragment Lengths and 5’ End-motifs#

This step uses the modality get tool to extract genome-wide fragmentomics features from a fragmentomics Zarr store provided as Zarr_Fragmentomics in config.txt. It is skipped if no fragmentomics Zarr store is provided. Unlike the region-based feature extraction above, this step does not use region files. It runs once over all fragmentomics Zarr stores, rather than once for each region file in the REGIONS_DIR.

Note

The Core Workflow does not include the --aggregate-by-group option, so the results contain one row per sample. Adding the option sums the fragment counts of the samples within each group, giving one row per group.

The pipeline performs two types of fragmentomics statistics extraction, extraction of fragment length and 5’ end-motif frequencies. Each is processed separately by modality XPLR, and the results are stored in timestamped Extract_* subdirectories.

What this script block does:

  • Fragment statistics (get fragment-stats): Returns, for each sample, the genome-wide relative frequency of each fragment length, together with the fragment size ratio (short to long fragments) and the fragment size entropy. The short fragment threshold and the entropy window are left at their default values. That is, --short-fragment-max 145 i.e., short fragments are considered as the fixed bottom limit 100 up to the provided max value 145 while long fragments are considered as those longer than 145 bp. In the case of entropy the default window is 45-145 as defined by the flags --entropy-min 45 and --entropy-max 145. These options are not passed by the Core Workflow.

  • End-motif statistics (get end-motif-stats): Returns, for each sample, the genome-wide frequency of each 5’ end-motif, normalised so that the frequencies for each sample sum to one. Motifs that contain unresolved bases (N) are excluded. The Core Workflow always passes --include-genetic, which also returns the frequencies for a 4-base (genetic) representation, where modified and unmodified cytosines are counted together.

  • If more than one fragmentomics Zarr store is provided, the stores are combined along the sample axis.

Expected outputs:

  • Extract_* directories: Written directly in the main output directory, not in the region-specific folders. Each command writes to its own timestamped directory.

  • Extract_fragment-stats_<YYYYMMDD>_<HHMMSS>.tsv.gz: Fragment statistics, with one row per sample. The entropy and fragment_size_ratio columns are followed by one column for the relative frequency of each fragment length.

  • Extract_end-motif-stats_<YYYYMMDD>_<HHMMSS>.tsv.gz: Epigenetic end-motif frequencies, with one row per sample and one column per motif. These retain the modification state of each base in the motif.

  • Extract_end-motif-stats_Genetic_<YYYYMMDD>_<HHMMSS>.tsv.gz: Genetic (4-base) end-motif frequencies, in the same format.

  • Provenance metadata .json file, stored in each Extract_* directory.

Note

These commands write .tsv.gz files only and do not generate an HTML report. The results can be visualised in the Fragmentomics Results tab of modality Viewer.

Interpreting fragmentomics statistics:

  • Fragment length distribution: The relative frequency of each fragment length shows where the fragment lengths of a sample are concentrated, which can be compared between samples.

  • Fragment size ratio: The ratio of short fragments (100 to 145 bp) to long fragments (longer than –short-fragment-max i.e., default 145 bp). Higher values indicate a greater proportion of short fragments.

  • Fragment size entropy: The normalised Shannon entropy of the fragment length distribution over the 45 to 145bp window defined by the --entropy-min and --entropy-max with defaults 45 and 145. Values range between 0 and 1, where higher values indicate a more uniform spread of fragment lengths and lower values indicate that fragment lengths are concentrated at a few lengths.

  • End-motif frequencies: The frequency of each 5’ end-motif shows the fragment end-motif profile of a sample, which can be compared between samples.

Customising fragmentomics feature extraction:

You can modify this section of the script to:

  • Add the --aggregate-by-group option to get fragment-stats and/or get end-motif-stats, to sum the fragment counts of the samples within a group. This requires the sample sheet (--sample-sheet).

  • Change the short and long fragment range definitions in get fragment-stats by setting --short-fragment-max. Lower limit is fixed at 100 i.e., –short-fragment-max of 145 means short fragments are 100-145bp and long fragments are >145 bp.

  • Change the the entropy window size get fragment-stats with --entropy-min and --entropy-max.

  • Remove --include-genetic from get end-motif-stats to skip the generation of the 4-base genetic end-motif frequencies.

  • See Extracting fragmentomics statistics for all available options.

Step 3: Context-level: DMR calling#

This step identifies differentially methylated regions using statistical modelling, processing each region file individually. DMR calling is the core analytical component that identifies regions with significant methylation differences between two experimental groups.

What this script block does:

  • Processes each .bed and .tsv file in the regions directory separately

  • Performs statistical testing for differential methylation on each region file (see Calling differentially methylated regions (DMRs))

  • Analyses 5mC and 5hmC modifications separately (and modC if included)

  • Analyses all available condition pairs from the metadata, preserving the sample sheet order for use with the --condition-order parameter. Ensure the control group is the first one listed in the metadata file; or analyses only the conditions specified in the config.txt, with the left-most condition name as the control group.

  • Applies multiple testing correction (FDR)

  • Incorporates covariates if specified

Note

The Core Workflow defaults to --overdispersion both, which runs the DMR model twice—once with and once without overdispersion correction—in a single invocation. Two BED result files are produced with _with_od_* and _without_od_* suffixes (followed by timestamps). This allows you to compare results and choose the most appropriate model for your data. For datasets with high variability or small sample sizes, overdispersion correction often improves statistical inference. For more information on when to use overdispersion, see Overdispersion correction.

Key analysis parameters:

  • Methylation contexts: Analyses mc and hmc (and modc if included)

  • Depth filtering: Should be applied according to the sequencing depth and methylation context coverage, and specified in the config.txt file

  • Covariate adjustment: Controls for confounding variables when specified in the config.txt file

Expected outputs:

  • DMR_* directory: All DMR results (for all group pairs and contexts) are stored in a single directory with a timestamp

  • *.bed files: DMR results in BED3+ format for each condition pair and methylation context

  • *.ini files: Configuration files for generating custom tracks plots via the modality XPLR CLI. One .ini file is generated for each DMR .bed result file

Advanced customisation and extension#

The Core Workflow is designed to be easily adapted for different research needs. Here are common modifications and extensions:

Modifying the Core Workflow script#

The script is organised into sections, each marked by a comment banner (for example LOAD CONFIGURATION and STEP 2: FEATURE EXTRACTION). Make the changes below in the relevant section, and keep a copy of the original script before you edit it.

Define more variables accepted by config.txt:

New variables follow the same pattern as the existing optional ones. For example, to make the group used to aggregate the fragmentomics results configurable:

  1. Declare the variable with the other config.txt variables, in the LOAD CONFIGURATION section.

  2. Add a line for it to the case statement that reads config.txt.

  3. Build the optional argument and add it to the command in the relevant step.

# 1. Declare the variable
AGGREGATE_GROUP=""      # Metadata column to aggregate fragmentomics samples by (optional)

# 2. Read it from config.txt (add this line to the case statement)
Aggregate_Group) AGGREGATE_GROUP="$value" ;;

# 3. Build the optional argument, and add it to the command
AGG_ARG=""
[[ -n "$AGGREGATE_GROUP" ]] && AGG_ARG="--aggregate-by-group $AGGREGATE_GROUP"

modality -v get fragment-stats \
  --zarr-path "${ZARR_FRAGMENT_ARRAY[@]}" \
  --sample-sheet "$METADATA" \
  $AGG_ARG \
  --output-dir "$MAIN_OUTPUT"

Then add Aggregate_Group=<column name> to config.txt, using a column that is present in the sample sheet. The Core Workflow generators only write the standard parameters, so add your own parameters to config.txt by hand. A value that never needs to change can instead be set directly in the script.

Add arguments to modality XPLR commands:

Add the option to the relevant modality command in the step you want to change, with each option on its own line ending in a backslash. The options available for each command are listed in the main documentation for Biological QC, Extracting methylation statistics, Extracting fragmentomics statistics and Calling differentially methylated regions (DMRs). To make an option conditional on a config.txt value, build it from a variable as shown above. Examples of options that the Core Workflow does not use by default are --heatmap for get mean and get regional-frac, and --aggregate-by-group for the fragmentomics commands.

Change the verbosity level or save the output to a log file:

See Verbosity and logging.

Other common changes:

  • Use a different configuration file: change CONFIG_FILE in the INITIALISATION section.

  • Add your own checks of the inputs: add them to the VALIDATE INPUTS section. Existing checks report a problem with log_error and then stop the script with exit 1.

  • Change the output directory structure: edit the SETUP OUTPUT DIRECTORIES section, and the --output-dir value passed to each command.

Customising analysis parameters#

Adjusting coverage thresholds:

# In the config.txt or script
DEPTH_FILTER=15  # Increase for higher quality regions

# Or modify specific commands directly using the --min-coverage option
modality get regional-frac \
  --zarr-path "${ZARR_ARRAY[@]}" \
  --bedfile "$bedfile" \
  --fields mc hmc modc \
  --min-coverage 15 \  # Custom minimum coverage
  --output-dir "$RESULTS_DIR"

Modify the methylation contexts in DMR calling:

# Modify the methylation contexts in DMR calling
modality dmr call \
  --methylation-contexts mc hmc \  # Exclude modc if not needed
  # ... other parameters

Note

The Core Workflow defaults to --overdispersion both, which produces two result files per analysis in the same timestamped DMR directory: one with overdispersion correction (_with_od_*.bed) and one without (_without_od_*.bed), where the suffix appears before the timestamp. This allows comparison of results under different statistical models. If --overdispersion true or false is specified instead, only one result file per analysis is produced without a suffix.

Performance optimisation tips#

For large datasets:

  • Use subset regions for initial testing

  • Implement parallel processing for independent steps

  • Monitor disk space and memory usage

  • Consider using HPC environments for large-scale analysis

For production use:

  • Add comprehensive logging and monitoring

  • Implement checkpointing for long-running analyses

  • Add email notifications for completion/failure

  • Include resource usage reporting

Script completion and monitoring#

The script includes basic completion reporting and performance tracking:

#------------------------------------------------------------------------------
# COMPLETION
#------------------------------------------------------------------------------
log_info "Pipeline completed successfully. Results are available in $MAIN_OUTPUT"

# Calculate and report duration
end_time=$(date +%s)
duration=$((end_time - start_time))
log_info "Script completed in $duration seconds"

# Exit cleanly
exit 0

Monitoring features:

  • Execution time tracking: Reports total pipeline duration

  • Success confirmation: Clear indication of successful completion

  • Output location reporting: Directs users to results

  • Clean exit handling: Proper script termination

Monitoring execution:

The script provides real-time logging output. You can also redirect output to a log file using the code below, or code it into the script as described in Verbosity and logging.

./core-workflow-v3.0.sh 2>&1 | tee workflow.log

Expected runtime:

Runtime varies significantly based on:

  • Dataset size: Number of samples and genomic regions

  • Analysis complexity: Number of methylation contexts and covariates

  • System resources: Available CPU and memory

  • Storage speed: Local vs network storage performance

This modular workflow provides a comprehensive foundation for methylation analysis using the modality XPLR toolkit. By understanding each component, you can adapt it to meet your specific research requirements while maintaining robust error handling and organised outputs.

Warning

Version compatibility: This pipeline is designed for modality XPLR version 1.1.0 and later. Results are optimised for visualisation in modality Viewer. Some features may not be available in earlier versions. Check your modality XPLR version with modality --version before running.

Tip

Getting help: If you encounter issues, first try running the modality commands with -vv for detailed logging (see Verbosity and logging). The modular design allows you to run individual sections for troubleshooting specific steps.