Calibrate SURF predictions with SCAN.
Add uncertainty intervals to SURF predictions. Fit SCAN on DNase counts from one chromosome, check it on another, then repeat with your own assay.
Run the SURF calibration example
1. Install SCAN
git clone https://github.com/jzhoulab/SCAN.git
cd SCAN
mamba env create -f environment.yaml
mamba activate SCANThis installs R, Stan, and the required packages. You can use conda instead of mamba.
2. Prepare the tracks
Download the example tracks from the project’s Zenodo release, or generate your own using the half-track command below. You need four tracks with matching genome builds, coordinates, and chromosome lengths:
| Track | Role |
|---|---|
half.pred.bw | SURF predictions made from half the reads. |
half.tar.bw | Counts from the other half, used to fit SCAN. |
half.inp.bw | The counts given to SURF to make these predictions. |
| Full observed counts | All reads, including the exact input reads. Subtract the input to get independent test counts. |
Use hg38 chr8 to fit SCAN and chr10 to test it. Both must be excluded from SURF training. Pair each prediction with an integer count at the same position. Keep measured zeros; exclude missing predictions and unmeasured positions.
For processed coverage tracks, split reads before processing. SURF’s built-in split is for raw point counts; see the SURF guide.
3. Fit SCAN on chr8
Set the prediction and target paths in the command below. The CLI expects per-base records and treats gaps as zero. For wider records, missing predictions, or unmeasured regions, adapt the notebook’s reader before fitting.
Run four sampling chains of 1,000 iterations each, with half used for warm-up. Use SCAN’s scan_calibration.R command directly. The preparation step updates the Stan array syntax in a copy of the model for this run:
# Run from the SCAN root. Prepare a Stan file for current compilers.
mkdir -p out/surf-example
Rscript - <<'RS'
code <- readLines("nb_spline_binned.stan")
code <- sub("int<lower=0> y[N];", "array[N] int<lower=0> y;", code, fixed = TRUE)
writeLines(code, "out/surf-example/scan.stan")
RS
Rscript scan_calibration.R \
--pred_bw /path/to/half.pred.bw \
--tar_bw /path/to/half.tar.bw \
--chrom chr8 --stan_file out/surf-example/scan.stan \
--out_dir out/surf-example --prefix scan \
--chains 4 --iter 1000 --cores 4 --seed 123Check the fitted model
The CLI writes a posterior RDS file, binned_data_summary.csv, fit_summary.csv, and pred_vs_obs.pdf. Check Rhat (ideally below 1.01), effective sample sizes, and warnings about divergences or tree depth. Inspect the fitted curves, especially where high-signal counts are sparse.
The notebooks use SCAN’s nb_spline_binned.stan model and save the posterior to model_rds. Inspect summary(fit) and rstan::get_sampler_params(fit) in the fitting cell before it removes the fit. Use a new output directory or RDS path when data, splits, or settings change.
4. Check the intervals on chr10
Open the evaluation notebook from the SCAN root and select the R kernel:
jupyter lab notebooks/surf_scan_analysis_pretrained.ipynbEdit the existing assignments in its configuration cell to match your tracks and the saved fit. Use absolute paths because the R working directory may be notebooks/. These lengths are for hg38:
# Edit these assignments in the notebook's R configuration cell.
data_dir <- "/absolute/path/to/the/half-track/directory"
gt_bw <- "/absolute/path/to/full_gt.bw"
model_rds <- "/absolute/path/to/SCAN/out/surf-example/scan_stan_bsplinedisp_knots20.rds"
train_chrom <- "chr8"; train_len <- 145138636
eval_chrom <- "chr10"; eval_len <- 133797422Subtract the input from the full counts to get independent test counts. This works only if the full track contains those exact input reads. Negative differences mean the tracks need checking.
The 50/50 split gives input and calibration counts equal expected read depth. The notebook sets gt_scale to the ratio of test counts to input counts. For other splits, use test depth divided by calibration-target depth.
Run the cells in order through loading the fitted model and tracks, then check the subset assumption and depth scale before continuing:
# Run after the notebook loads the fitted model and chr10 tracks.
# neg counts positions where the full track is smaller than the input.
stopifnot(neg == 0, is.finite(gt_scale), gt_scale > 0)Continue through the interval and calibration figures. A well-calibrated 90% count interval should contain about 90% of the independent test counts. Keep observed zeros and exclude predictions outside the fitted range before calculating coverage. Report how many positions were excluded.
Quiet regions can hide poor results in active ones. Figure 2 checks several signal thresholds and interval levels; choose them before inspecting evaluation coverage. Inspect the example-region plot as well, using the paper’s PTEN window chr10:87,861,258-87,864,937 for comparison.
What the intervals mean
How SCAN estimates uncertainty
SCAN learns the average observed count and its spread at each prediction level. Smooth curves let both change with signal strength. A negative-binomial model allows counts to vary more than Poisson sampling alone would predict.
Model equations and fitting details
Here, p is the prediction, y the observed count, μ the mean, and φ the dispersion. Smaller φ means wider intervals at the same mean.
z = log(p + 1e-9)
log μ(p) = I-spline(z) · β_mean
log φ(p) = B-spline(z) · β_dispersion
y | p ~ NegativeBinomial(mean = μ, size = φ)
Variance(y | p) = μ + μ² / φFitting groups similar prediction values to reduce computation. These groups can span distant genomic positions. The mean curve is not constrained to increase.
Choose the interval for your question
- Count interval (NB): a range for a future observed count. Use this to check coverage against independent test counts.
- Signal interval (Gamma): a range for the underlying intensity, before variation from read sampling.
Both include uncertainty in the fitted model. Check coverage on independent counts: a label such as “90%” is a target, not a guarantee.
Stay within the fitted range
Exclude predictions outside the range shared by the fitted mean and dispersion curves before calculating intervals or coverage. Report exclusions, especially in high-signal regions; extrapolating the dispersion curve can produce misleading bounds.
Adjust for read depth
Set the notebook’s scale argument to test depth divided by calibration-target depth. Evaluate both curves at the original prediction, scale the fitted mean, and keep dispersion fixed. Check coverage again after changing depth.
Use your own assay
Match predictions to independent counts
Use the same steps for DNase cuts, ATAC cuts, CAGE ends, or other integer counts. Match predictions and counts by base or bin, strand, and channel. Fit separate calibrations for measurements with different count distributions.
If your test counts come from a separate experiment, use them directly and adjust for their depth relative to the calibration target. Fractions, probabilities, and normalized signals need a different statistical model.
Generate your own half tracks
# In your trained SURF checkout:
uv run surf predict -i path/to/training_output_dir \
-m best.model.checkpoint -c chrom_lengths.tsv -o pred.bw --halfCheck that all three output files exist and have different names. Keep each prediction with the input reads used to make it.
If your checkout writes half outputs to the same filename
Use distinct paths in the half-mode branch of src/surf/core/strategy.py, then regenerate the tracks:
if is_pred_half:
pred_track = os.path.join(out_path, "half.pred.bw")
inp_track = os.path.join(out_path, "half.inp.bw")
tar_track = os.path.join(out_path, "half.tar.bw")Adapt with a coding agent
Adapt the notebook’s fitting and evaluation cells to your paired predictions and counts. Keep their coordinates and a record of excluded positions.
The repository’s SCAN Agent Skill explains the fitting and evaluation steps. Ask your coding agent to follow it:
Save the fitted model, diagnostics, tracks, settings, and coverage results together. Label exported intervals with their type, level, depth scale, coordinates, and exclusions.
Continue with the analysis notebooks
To fit and evaluate in one notebook, use the fit-and-evaluate notebook to train a new fit. Select the R kernel and run cells in order.
Check the chromosome settings and lengths. When fitting in the notebook, set SCAN_STAN_FILE to the run’s scan.stan and use a new RDS path to avoid reusing an old fit. Save diagnostics before the fitting cell removes the fit.
Plots are saved in pdfs/ under the R working directory. Exclude positions outside the fitted range from both coverage checks and region plots.
