Algorithmcore
Circular binary segmentation
Also called CBS segmentation.
Split a sequence where a permutation test finds an arc of changed mean, the largest arc t-statistic on a circle, then repeat on each part (Olshen and Venkatraman).
- Solves
- Copy number segmentation
- Time
- O(N n^3) worstO(N n^2) per_test
- Space
- O(n) extra
- Where
- N = the number of permutations per test; n = the number of points
- Model
- Real RAM
- Properties
- randomizednot exactofflinerecursive
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Adam B. Olshen, E. S. Venkatraman, Robert Lucito, Michael Wigler, 2004
Circular binary segmentation (CBS) splits a noisy sequence of numbers along a chromosome, such as log ratios of read depth, into segments of constant mean. It bends each segment into a circle and looks for the arc whose mean differs most from the rest, measured by a t-statistic. If a permutation test says the difference is real, it cuts the segment at the two ends of the arc and repeats on each part. The circle lets one test find a short change in the middle of a segment, which a split into two parts finds badly. Olshen, Venkatraman, Lucito and Wigler proposed it in 2004 for array CGH, and it is the default copy number segmentation method of the DNAcopy package.
In plain words
You have a long row of numbers that jump up or down at a few places, with noise on top. You want to find the jumps.
Join the two ends of the row so that it makes a ring. Try every stretch of the ring, and for each one, compare the average inside with the average outside, scaled by how much noise there is. Take the stretch with the biggest difference.
To see if that difference is real, shuffle the numbers many times and do the same search on each shuffle. If almost no shuffle gives a difference as big, cut the row at the two ends of the stretch. Then do the same on each piece, until no piece gives a real difference.
The problem
Given with , where is piecewise constant with a few change points and is noise, find the change points. CBS answers this with a sequence of tests, not by fitting a model with a known number of segments. See copy number segmentation for the problem and its exact solution by dynamic programming.
For a segment of length , an arc is a set of positions that are consecutive on the circle, with positions, . With the sample standard deviation of , the arc statistic and the test statistic are
An arc that starts at the first position, or ends at the last, is one change point, as in binary segmentation. Any other arc is two change points.
The algorithm
CBS(x, α, N)- 1
stack ← [(0, n)]; cuts ← empty - 2
while stack is not empty do - 3
(lo, hi) ← POP(stack) - 4
y ← x[lo..hi) - 5
(T, i, j) ← MAX-ARC(y) - 6
count ← the number of N random permutations π of y with MAX-ARC(π(y)).T ≥ T - 7
p ← (count + 1) / (N + 1) - 8
if p ≤ α then - 9
add lo + i and lo + j to cuts, the ones strictly inside (lo, hi) - 10
push the two or three parts of y onto the stack - 11
return the sorted cuts
Segments are half-open, and a segment with fewer than 2 points or a constant one is not tested. MAX-ARC scans every interval with prefix sums. By symmetry, the complement of an interval has the same , and every arc is an interval or the complement of one, so the scan over intervals covers every arc on the circle.
MAX-ARC(y)- 1
S[0] ← 0; S[t + 1] ← S[t] + y[t] for t = 0, ..., n - 1 - 2
s ← the sample standard deviation of y - 3
for each i < j with 1 ≤ j - i ≤ n - 1 do - 4
d ← (S[j] - S[i]) / k - (S[n] - S[j] + S[i]) / (n - k), with k = j - i - 5
Z(i, j) ← |d| / (s sqrt(1/k + 1/(n - k))) - 6
return the largest Z(i, j) and the first (i, j) that reaches it
The test at line L6 needs no model of the noise. A permutation does not change , so all the statistics in one test use the same scale, and the p-value of line L7 is valid for exchangeable data, such as independent values with one distribution. The code uses a fixed order of the segments (the left part first) and one random generator, so a seed gives the same result each time.
Example
Twelve values: five near 0, four near 1 and three near 0.
The standard deviation is . MAX-ARC finds the arc , the four high values, with mean 1.05 against 0.0 outside:
The best single split, at position 5, gives only , because the values after the high stretch drop back and pull the right mean down. This is why CBS uses arcs.
For the exact p-value, put the twelve values on the circle in a random order. The four high values form one arc in 12 of the ways to choose their four positions, and those placements give . A search over all other placements found that their largest is 2.918. So the exact p-value is . One run of the code with permutations gave .
At , CBS cuts at 5 and 9. The three parts give , and , and none of them passes the test, so the result is the segments , and with means 0.0, 1.05 and 0.0. A search over all ways to cut 12 points into 3 segments gives the same cuts as the least squares optimum. At , CBS returns no cut, because the exact p-value of the strongest arc is 0.0242.
Correctness
MAX-ARC is exact. Line L12 makes the sum of every interval one subtraction, lines L15 and L16 are the definition of , and because and every arc on the circle is an interval or the complement of one, the scan of line L14 covers all arcs. The test is valid: if the values are exchangeable under the null hypothesis, then the observed and the shuffled values are exchangeable, and the rank argument gives for the p-value of line L7. This holds for any and does not need normal noise.
That is a statement about each test. CBS as a whole is a heuristic for the segmentation problem: it does not minimize any stated objective, its tests are chosen from the data, and is a threshold per test, not an error rate for the whole result. The full proofs of the two lemmas are in proofs/correctness.md.
Proof: MAX-ARC returns the largest arc statistic, and the permutation p-value of CBS is validfull
Setting. A segment is a list of real numbers with . Think of as bent into a circle, so that is next to . An arc is a set of positions that are consecutive on the circle, with at least one and at most positions. For an arc with positions, let be the mean of over and the mean over the other positions. With the sample standard deviation of ,
If , all values are equal and the code returns , which never gives a split.
Lemma 1 (the arcs are the intervals). Every arc is an interval with and , or the complement of such an interval. for every arc .
Proof. An arc that does not contain both and is an interval. An arc that contains both wraps around the end of the list, and its complement does not contain or (it is not empty and the arc is consecutive on the circle), so the complement is an interval. The complement of an arc is again an arc, with positions. The formula for is symmetric under the exchange of and : the numerator changes sign inside the absolute value, and the sum does not change.
So the maximum of over all arcs equals the maximum over the intervals of Lemma 1, which are the pairs that line L14 visits.
Lemma 2 (MAX-ARC). MAX-ARC returns and the first interval , in the order of and then , that reaches it.
Proof. Line L12 sets , so the sum of over is , and the sum over the rest is . With , line L15 computes , and line L16 computes . Line L14 visits every interval of Lemma 1 once, and the code replaces the best value only on a strictly larger , so the first maximizer is kept. By Lemma 1, the largest value is .
Lemma 3 (the standard deviation does not matter for the test). For every permutation of the positions, the sample standard deviation of equals that of .
Proof. The mean and the sum of squared deviations depend only on the multiset of values.
So the permutation test compares values that all use the same , and replacing by any other function of the multiset (a robust scale, for example) gives the same test.
Theorem (validity of the p-value). Assume that under the null hypothesis the vector is exchangeable: its distribution does not change when the positions are permuted, as for independent values with the same distribution. Let lines L6 and L7 draw independent uniform random permutations and set . Then for every .
Proof. Let be a uniform random permutation independent of everything else. By exchangeability, has the same distribution as , so it is enough to prove the claim for , with the same . The permutations are independent and uniform: given , each is uniform because is, and the are independent. So the values and are exchangeable.
Let , which counts itself, so that . Fix an integer . At most indices have : if indices had it, the one among them with the smallest would have all values its own, so its would be at least . By exchangeability, each has the same probability of , so
With , the event is the event , so .
The code counts at line L6, so that two arrangements with the same statistic up to rounding count as a tie. This can only increase the count, so the p-value stays valid.
Exact p-value of the example. The page example has four high values, 1.1, 0.9, 1.0 and 1.2, among twelve. The positions of the four high values in a random permutation are a uniform set of 4 positions out of 12, and there are such sets. When the four high values form an arc, which happens for 12 of the sets, that arc has the same values as the arc of the data, so . A search over all other placements found that their largest is 2.918, below 3.2247. So the exact p-value is , which the Monte Carlo estimate at line L7 approaches as grows.
The recursion. Lines L1 to L4 and L8 to L11 keep a stack of half-open segments of that cover it without overlap. Each split at lines L9 and L10 replaces a segment by two or three parts that cover it, and adds the inner end points to the cuts. A segment of length less than 2, or with , is not split. So the returned list is sorted, every cut is strictly inside , and the segments between the cuts are exactly the parts that the last tests did not split. Each part is shorter than its parent, so the loop ends after at most splits. The theorem applies to each test on its own. The segments are chosen from the data, so the whole procedure does not have a single error level; CBS treats as a per-test threshold.
Cost. MAX-ARC takes time for a segment of length : intervals at each after the prefix sums. One test with permutations takes time. In the recursion, the segments at the same depth do not overlap, so their tests cost at most in total for each depth, and the depth is at most the number of splits.
Complexity
- One test. MAX-ARC visits intervals at each, so it is . A test with permutations is .
- The recursion. Segments at one depth of the recursion do not overlap, so the tests at one depth cost in total. The depth is at most the number of splits, so the worst case is . With a few change points that split the data into balanced parts, the cost is close to that of the first test.
- The fast version. Venkatraman and Olshen (2007) stop the permutations early when the p-value is clearly large, and replace most permutations by an approximation of the tail probability, which made CBS practical for arrays with many probes.
- Space. for the prefix sums, the copy of a segment and the stack.
Properties
- Not exact. CBS is a heuristic for segmentation; only MAX-ARC and the validity of each test are theorems.
- Randomized. The p-values come from random permutations, so two runs with different seeds can differ at a borderline split.
- Nonparametric test. The permutation test needs exchangeable noise, not normal noise. Correlated noise along the genome breaks this, and then the test splits too often.
- Top down. Each split is final; a wrong early cut is not undone.
- No number of segments needed. The number of segments comes from , not from the user.
Variants and improvements
- Pruning of splits. DNAcopy can undo splits whose parts differ by less than a set number of standard deviations (undo.splits), which removes small segments caused by noise.
- Minimum width. An arc must have at least a set number of points, so that one outlier does not make a segment.
- Smoothing of outliers. Single extreme points are pulled toward their neighbors before segmentation.
- Weights. Points with more reads or better probes can count more.
- Other segmenters. Binary segmentation with one change point per test, PELT for an exact penalized fit in about linear time, and the HMM approach, which gives each segment a copy number state.
When to use it
Use CBS to segment log ratios of copy number along a chromosome, from arrays or from read depth in windows, when you do not know the number of segments and want a method with few settings. It is the standard in many cancer pipelines and is robust to the shape of the noise. If you need integer copy numbers, call them after CBS or use an HMM. If you need the least squares optimum for a given number of segments or a penalty, use the exact dynamic program or PELT.
Pitfalls
- Too few points. For a stretch of high points among , the exact p-value is at least about , the share of placements where the high points form an arc. In the example this is , so the change is lost at .
- Uncorrected depth. GC content and mappability make waves in read depth. CBS cuts them into many segments that are not real.
- Correlated noise. Neighboring windows that share reads are not exchangeable, so the p-values are too small.
- is per test. With many tests along a genome, some false cuts are expected at any .
- Too few permutations. With permutations the smallest p-value is , so below that can never pass.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/circular-binary-segmentation/. The authors are listed in prov/6NYYG1.jsonl.
"""Circular binary segmentation (CBS) of Olshen, Venkatraman, Lucito and Wigler (2004).
The input is a list x of numbers along a chromosome, for example log2 ratios of
read depth in windows. Positions are 0-based and segments are half-open, so the
segment (lo, hi) holds x[lo], ..., x[hi - 1].
The statistic of an arc (i, j) of a segment y of length n compares the mean of
y[i:j] with the mean of the rest of y, as if y were bent into a circle:
Z(i, j) = |mean(y[i:j]) - mean(rest)| / (s * sqrt(1 / k + 1 / (n - k))), k = j - i,
with s the sample standard deviation of y. The test statistic is the largest
Z over the arcs with 1 <= k <= n - 1. Its p-value comes from random
permutations of y. Because s does not change under a permutation, the test is
exact for exchangeable data at any choice of s.
What this code leaves out compared with the DNAcopy package: the early stop of
the permutation count and the tail approximation of Venkatraman and Olshen
(2007), the check that removes a split whose parts do not differ enough, the
minimum width of an arc, outlier smoothing and weights.
"""
from __future__ import annotations
import math
import random
from typing import List, Sequence, Tuple
def max_arc(y: Sequence[float]) -> Tuple[float, int, int]:
"""Return (T, i, j): the largest arc statistic of y and its arc y[i:j].
Ties go to the first arc in the order of i, then j. A constant y gives (0.0, 0, n).
"""
n = len(y)
S = [0.0] * (n + 1) # @line L12
for k in range(n):
S[k + 1] = S[k] + y[k]
mean = S[n] / n
var = sum((v - mean) ** 2 for v in y) / (n - 1) if n > 1 else 0.0
s = math.sqrt(var) # @line L13
if s == 0.0:
return 0.0, 0, n
best, bi, bj = -1.0, 0, n
for i in range(n): # @line L14
for j in range(i + 1, n + 1):
k = j - i
if k == n:
continue
inside = S[j] - S[i]
d = inside / k - (S[n] - inside) / (n - k) # @line L15
z = abs(d) / (s * math.sqrt(1.0 / k + 1.0 / (n - k))) # @line L16
if z > best:
best, bi, bj = z, i, j
return best, bi, bj # @line L17
def permutation_p_value(y: Sequence[float], t_obs: float, rng: random.Random, n_perm: int) -> float:
"""(count + 1) / (n_perm + 1), where count is the number of shuffles with T >= t_obs.
Draw order: n_perm calls of rng.shuffle on one working copy of y.
"""
work = list(y)
count = 0
tol = 1e-12 * max(1.0, t_obs)
for _ in range(n_perm):
rng.shuffle(work)
if max_arc(work)[0] >= t_obs - tol: # @line L6
count += 1
return (count + 1) / (n_perm + 1) # @line L7
def cbs(x: Sequence[float], rng: random.Random, alpha: float = 0.01, n_perm: int = 199) -> List[int]:
"""Return the sorted change points of x: each b with 0 < b < len(x) where a new segment starts.
Segments are tested in a fixed order (a stack; the left part is tested
first), so a seed gives the same result on every run.
"""
n = len(x)
stack = [(0, n)] # @line L1
cuts: List[int] = []
while stack: # @line L2
lo, hi = stack.pop() # @line L3
y = x[lo:hi] # @line L4
if len(y) < 2:
continue
t, i, j = max_arc(y) # @line L5
if t == 0.0:
continue
p = permutation_p_value(y, t, rng, n_perm)
if p <= alpha: # @line L8
parts = [lo] + [lo + b for b in (i, j) if 0 < b < hi - lo] + [hi]
cuts.extend(parts[1:-1]) # @line L9
for a, b in reversed(list(zip(parts, parts[1:]))): # @line L10
stack.append((a, b))
return sorted(cuts) # @line L11
def segment_means(x: Sequence[float], cuts: Sequence[int]) -> List[Tuple[int, int, float]]:
"""The segments (lo, hi, mean) between the change points."""
bounds = [0] + list(cuts) + [len(x)]
return [(a, b, sum(x[a:b]) / (b - a)) for a, b in zip(bounds, bounds[1:])]
test_circular_binary_segmentation.py 118 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/circular-binary-segmentation/. The authors are listed in prov/6NYYG1.jsonl.
import itertools
import math
import random
from circular_binary_segmentation import cbs, max_arc, permutation_p_value, segment_means
EXAMPLE = [0.1, -0.2, 0.0, 0.2, -0.1, 1.1, 0.9, 1.0, 1.2, 0.0, -0.1, 0.1]
def direct_max_arc(y):
"""The arc statistic from the definition, with means computed from scratch."""
n = len(y)
mu = sum(y) / n
s = math.sqrt(sum((v - mu) ** 2 for v in y) / (n - 1))
best = (-1.0, 0, n)
for i in range(n):
for j in range(i + 1, n + 1):
if j - i == n:
continue
ins = y[i:j]
out = y[:i] + y[j:]
z = abs(sum(ins) / len(ins) - sum(out) / len(out)) / (s * math.sqrt(1 / len(ins) + 1 / len(out)))
if z > best[0] + 1e-12:
best = (z, i, j)
return best
def rss(x, cuts):
return sum(sum((v - m) ** 2 for v in x[a:b]) for a, b, m in segment_means(x, cuts))
def best_segmentation(x, k):
"""Least squares segmentation into k segments, by brute force over all cut sets."""
n = len(x)
return min(itertools.combinations(range(1, n), k - 1), key=lambda c: rss(x, list(c)))
def test_max_arc_against_definition():
rng = random.Random(1)
for _ in range(50):
n = rng.randint(2, 12)
y = [rng.gauss(0, 1) for _ in range(n)]
t, i, j = max_arc(y)
t2, i2, j2 = direct_max_arc(y)
assert abs(t - t2) < 1e-9
assert (i, j) == (i2, j2)
def test_example_statistic():
t, i, j = max_arc(EXAMPLE)
assert (i, j) == (5, 9)
assert abs(t - 3.224704) < 1e-6
def test_example_p_value_near_exact():
# The four high values form one arc in 12 of the C(12, 4) = 495 placements on the circle,
# and only those placements reach the observed statistic, so the exact p-value is 12 / 495.
t, _, _ = max_arc(EXAMPLE)
n_perm = 1999
p = permutation_p_value(EXAMPLE, t, random.Random(8), n_perm)
exact = 12 / 495
assert abs(p - exact) <= 4 * math.sqrt(exact * (1 - exact) / n_perm) + 1 / n_perm
def test_example_segmentation_matches_brute_force():
cuts = cbs(EXAMPLE, random.Random(5), alpha=0.05, n_perm=999)
assert cuts == [5, 9]
assert tuple(cuts) == best_segmentation(EXAMPLE, 3)
# At the level 0.01 the 12 points cannot show the change: the exact p-value is 0.0242.
assert cbs(EXAMPLE, random.Random(5), alpha=0.01, n_perm=999) == []
def test_single_change_point():
x = [0.0, 0.1, -0.1, 0.05, 2.0, 2.1, 1.9, 2.05, 1.95, 2.0]
cuts = cbs(x, random.Random(2), alpha=0.1, n_perm=999)
assert cuts == [4]
assert tuple(cuts) == best_segmentation(x, 2)
def test_constant_and_short():
assert cbs([1.0] * 8, random.Random(0)) == []
assert cbs([3.0], random.Random(0)) == []
assert cbs([], random.Random(0)) == []
assert max_arc([2.0, 2.0, 2.0]) == (0.0, 0, 3)
def test_p_value_bounds():
rng = random.Random(9)
y = [rng.gauss(0, 1) for _ in range(10)]
t, _, _ = max_arc(y)
p = permutation_p_value(y, t, rng, 99)
assert 1 / 100 <= p <= 1
# The observed order is one of the permutations, so a huge statistic still gives p = 1 / (P + 1).
assert permutation_p_value(y, 1e9, rng, 99) == 1 / 100
def test_pure_noise_has_few_false_splits():
rng = random.Random(31)
false_splits = 0
for _ in range(10):
y = [rng.gauss(0, 1) for _ in range(20)]
false_splits += len(cbs(y, rng, alpha=0.01, n_perm=99)) > 0
assert false_splits <= 2
def test_simulated_segments_recovered():
rng = random.Random(2004)
truth = [15, 21, 40]
levels = [0.0, 1.0, 0.0, -1.0]
bounds = [0] + truth + [50]
x = []
for (a, b), mu in zip(zip(bounds, bounds[1:]), levels):
x.extend(mu + rng.gauss(0, 0.25) for _ in range(b - a))
cuts = cbs(x, rng, alpha=0.01, n_perm=199)
assert cuts == truth
History
Olshen, Venkatraman, Lucito and Wigler (2004) proposed CBS for array comparative genomic hybridization (array CGH), as a change to binary segmentation that tests for arcs. In the same year Fridlyand et al. (2004) segmented the same kind of data with a hidden Markov model. Venkatraman and Olshen (2007) made CBS fast for arrays with many probes, and the DNAcopy package of Bioconductor made it a standard step in copy number analysis. It was later used for read depth from sequencing.
References
- Adam B. Olshen, E. S. Venkatraman, Robert Lucito and Michael Wigler, Circular binary segmentation for the analysis of array-based DNA copy number data, Biostatistics 5(4), 2004, the sections on the method (the maximal t-statistic over arcs, the permutation reference distribution and the recursive splitting)
- E. S. Venkatraman and Adam B. Olshen, A faster circular binary segmentation algorithm for the analysis of array CGH data, Bioinformatics 23(6), 2007, the sections on the early stopping of the permutations and on the approximation of the tail probability
- Jane Fridlyand, Antoine M. Snijders, Dan Pinkel, Donna G. Albertson and Ajay N. Jain, Hidden Markov models approach to the analysis of array CGH data, Journal of Multivariate Analysis 90(1), 2004, pp. 132 to 153, an HMM segmentation of the same data, for comparison
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 6NYYG1 Edit this page History Report an error Markdown