Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 | 2x 2x 2x 2x 28x 28x 28x 28x 28x 28x 28x 3626x 3626x 3626x 3626x 28x 28x 2x 2757824x 2757824x 2x 16x 16x 16x 16x 16x 16x 16x 16x 2x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 52x 40x 40x 3796x 3796x 3796x 3796x 3796x 3796x 3796x 2331126x 2331126x 2331126x 2331126x 16x 16x 16x 2331110x 2331126x 2331024x 2331024x 3258x 3258x 3258x 2331024x 2331126x 86x 86x 2327852x 2327852x 2331126x 2316574x 11278x 2331126x 3796x 40x 40x 14x 14x 14x 14x 14x 14x 14x 14x 14x 2777x 2777x 1129528x 1129528x 2777x 14x 14x 13x 13x 13x 18x 18x 18x 54x 54x 318x 318x 19727x 19727x 19727x 318x 54x 18x 2x 2x 15x 15x 15x 15x 15x 15x 15x 15x 15x 2x 2x 17x 17x 17x 17x 17x 17x 17x 17x 17x 2254x 2254x 2254x 17x 17x 17x 17x 2254x 2254x 2254x 2254x 2x 12x 12x 12x 12x 12x 12x 12x 12x 623x 623x 623x 740x 740x 740x 623x 623x 623x 622x 12x 12x 2x 8x 8x 8x 8x 8x 8x 65723x 65723x 65723x 2x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 264x 21216x 21216x 21216x 21216x 264x 428x 428x 428x 428x 428x 264x 5x 5x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 1262x 1262x 8027x 8027x 8027x 8027x 8027x 8027x 6765x 6765x 6765x 6765x 6765x 1262x 20x 65723x 65723x 65723x 1142x 1142x 1142x 2645x 2645x 1536x 1536x 1536x 1536x 1536x 65723x 1242x 1242x 1242x 65723x 20x 20x 20x 20x 20x 20x 20x 6x 6x 6x 6x 6x 6x 6x 6x 6x 5x 5x 5x 5x 50x 50x 50x 5x 5x 50x 50x 50x 50x 50x 5x 5x 5x 5x 5x 2x 7x 7x 7x 7x 7x 7x 3x 3x 4x 6x 2x 2x 4x 4x 2x 7x 7x 7x 7x 7x 7x 7x 7x 460x 460x 460x 460x 460x 460x 7x 7x 7x 460x 460x 460x 34000x 34000x 34000x 34000x 21566x 21566x 21566x 460x 7x 7x 15100x 15100x 7x 7x 21x 21x 21x 186x 1812x 1812x 1615x 1615x 1615x 186x 21x 21x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 2x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 155x 140x 140x 140x 140x 140x 140x 140x 140x 155x 155x 155x 155x 13x 446x 446x 446x 446x 446x 446x 446x 446x 441x 441x 441x 13x 13x 13x | /**
* Observed/expected, the correlation matrix, the eigenvectors, and the saddle.
*
* The chain §18.8 describes, as four pure functions. Each is short; what is long
* is the reasoning about missing data, because a compartment analysis is where
* dropped bins do the most damage and where the damage is least visible.
*
* **A bin the balancer dropped is excluded from the matrix, not zeroed.** A
* zeroed row asserts that its bin is uncorrelated with everything — which is a
* strong, false claim that pulls the eigenvector towards zero there, and which
* on a chromosome arm full of dropped bins produces a compartment track with a
* flat region that looks exactly like a real one. So the chain works over an
* *index* of usable bins and the caller expands the result back over the full
* grid afterwards, restoring the gaps as gaps.
*
* **Phasing is reported, not assumed.** The sign of an eigenvector is arbitrary,
* and the convention that positive means the active compartment is a convention
* — it has to be attached to something. Attaching it to a signal the reader
* chooses, and printing the correlation that was used, is what makes the track's
* sign a claim rather than an accident. Below a threshold the answer is *I could
* not tell*, which is a legitimate result and a much better one than a coin flip.
*/
import type { ExpectedCurve } from './expected'
import { expectedAt } from './expected'
import { pearsonRowsThreaded } from './pearsonThreads'
import { pearson, quantileEdges } from './stats'
/**
* The bins of a square that carry enough data to take part.
*
* A row is usable when it has at least `minFraction` finite cells. Everything
* downstream works over this index, which is what keeps a dropped bin out of the
* correlation rather than in it as a zero.
*/
export function usableBins(
values: Float32Array,
n: number,
minFraction = 0.1,
): Int32Array {
const keep: number[] = []
const needed = Math.max(1, Math.ceil(n * minFraction))
for (let r = 0; r < n; r++) {
// Counted only as far as the answer: a row of a balanced map has its tenth
// a tenth of the way along, and the square is sixteen million cells.
let seen = 0
for (let c = 0; c < n && seen < needed; c++) if (Number.isFinite(values[r * n + c])) seen++
if (seen >= needed) keep.push(r)
}
return Int32Array.from(keep)
}
/**
* What each cell of a square is divided by — **cis and trans are two questions**.
*
* A square over one chromosome has one answer: the decay curve, read at the
* separation of the two bins. A square over several has two, and conflating them
* is the mistake that makes a genome-wide eigenvector meaningless.
*
* - A **cis** cell — both bins on one sequence — is divided by *that sequence's
* own* decay at that separation. Not a pooled one: a genome-wide curve divides
* a small chromosome by the average behaviour of the large ones, which shows up
* as a spurious gradient along the eigenvector.
* - A **trans** cell has no separation at all. Genomic distance between two
* chromosomes is not a quantity, so there is no curve to read; the expectation
* is the **mean of that pair's own block**, which is what makes a trans cell a
* ratio comparable with a cis one. A per-pair mean rather than one global trans
* mean, because two chromosomes' mutual contact depends on how much of the
* nucleus they share and pooling would push every pair towards the average.
*
* `group` is which sequence each row of the square belongs to, and the groups are
* **contiguous runs** of it — which is what lets a cis separation be `|col − row|`
* rather than needing an absolute bin per row.
*/
export interface ExpectedPlan {
/** Sequence index per row of the square; `n` long, non-decreasing. */
group: Int32Array
/** One decay curve per sequence, for the cells inside it. */
cis: readonly ExpectedCurve[]
/** Mean of each ordered pair's block, `k × k` row-major. `NaN` where empty. */
trans: Float64Array
/**
* Which cells take part; the rest are gaps.
*
* `trans` is the one worth naming, because it is a method rather than a
* filter. A **trans-only** correlation is what you compute when you do not
* want the distance decay in the answer at all: the cis blocks carry a
* near-diagonal that dominates every row, and dividing it out by an expected
* curve is a correction rather than an absence. Excluding them makes the
* eigenvector a statement about which sequences share a nuclear compartment
* and nothing else — which is why it is the standard genome-wide call.
*
* `cis` here means *this square's* cis cells. It is not how a multi-sequence
* cis-only run is done — see `analysis/run/compartments.ts`, which runs one
* square per sequence for that, because a single square with its trans blocks
* removed correlates to a **block-diagonal** matrix whose leading eigenvector
* lives entirely on one chromosome and is zero on the rest.
*/
contacts: 'cis' | 'trans' | 'both'
/**
* How many diagonals of the cis blocks to leave out, cooltools' `ignore_diags`.
*
* `0` keeps every cell; `1` drops the main diagonal; `2` drops it and the two
* beside it — the rule is `|col − row| < ignoreDiags`, which is the same
* arithmetic and the same spelling as the tool everybody compares against.
*
* It matters more here than the number suggests. The near-diagonal is where a
* Hi-C map's self-ligation and unligated fragments end up, and those cells are
* both the largest in the matrix and the least related to anything structural
* — so a row's correlation with its neighbours is carried disproportionately
* by the two or three cells nearest the diagonal, which say only that the two
* bins are adjacent. Every chromosome's rows agree about that, so it enters the
* eigenvector as a component that is really a picture of the diagonal.
*
* Trans cells have no separation and are never affected.
*/
ignoreDiags: number
/**
* What a cell {@link ignoreDiags} leaves out becomes: a gap, `NaN`, unless this
* says otherwise. cooltools sets those cells to 1 — *as expected* — before it
* divides, so its percentile counts them, and {@link cooltoolsPlan} asks for
* the same.
*/
nearDiagonal?: number
/**
* Bins in each sequence that is **circular**, `0` for one that is not; one
* entry per group, absent for a square with no circular sequence in it.
*
* On a circle the separation between two bins is the shorter of the two ways
* round (§8.15), and the decay curve in {@link cis} was accumulated that way —
* so a cis cell must be looked up at the same separation, or its numerator
* would be a circle's and its denominator a line's. Each group's rows are the
* whole sequence in order, which is what makes `|col − row|` its separation
* one way and the lap minus that the other.
*/
laps?: Int32Array
}
/**
* The separation a cis cell of the square is looked up at: the straight one, or
* the short way round where its sequence is circular.
*/
export function cisSeparation(offset: number, lap: number): number {
return lap > 0 ? Math.min(offset, lap - offset) : offset
}
/**
* The plan a square over **one** sequence has: one curve, no trans.
*
* Not a special case in the arithmetic — it is the general one with `k = 1` — but
* worth a name, because it is what a single-chromosome run and every test of the
* chain builds.
*/
export function singleGroupPlan(n: number, curve: ExpectedCurve): ExpectedPlan {
return {
group: new Int32Array(n),
cis: [curve],
trans: Float64Array.from([Number.NaN]),
contacts: 'both',
ignoreDiags: 0,
}
}
/**
* The square as observed/expected, over the usable bins only.
*
* Row-major and `m × m` where `m` is `index.length`. A cell whose expected is
* unknown — past the end of the curve, at an offset nothing was measured at, or
* in a trans block with nothing in it — is `NaN` rather than the observed value:
* dividing by an unknown and keeping the numerator would put raw counts and
* ratios in the same matrix.
*
* Into `out` where one is given — a square of the same size that nothing reads
* any longer — since every cell is written.
*/
export function observedOverExpected(
values: Float32Array,
n: number,
index: Int32Array,
plan: ExpectedPlan,
out: Float64Array = new Float64Array(index.length * index.length),
): Float64Array {
const m = index.length
const k = plan.cis.length
const { group, trans, ignoreDiags } = plan
const transOnly = plan.contacts === 'trans'
const cisOnly = plan.contacts === 'cis'
const nearDiagonal = plan.nearDiagonal ?? Number.NaN
// Each sequence's expectation at every separation it has, read once rather
// than once a cell: the curve is asked the same few thousand questions
// millions of times, and the square is made twice under cooltools' method.
const decay = plan.cis.map((curve) =>
Float64Array.from({ length: curve.maxOffset + 1 }, (_, offset) => expectedAt(curve, offset)),
)
for (let r = 0; r < m; r++) {
const row = index[r]
const rowGroup = group[row]
const own = decay[rowGroup]
const lap = plan.laps?.[rowGroup] ?? 0
const at = r * m
const from = row * n
for (let c = 0; c < m; c++) {
const col = index[c]
const colGroup = group[col]
const same = rowGroup === colGroup
// A cell the mode leaves out is a gap, exactly as a cell with no
// expectation is: it takes no part in any correlation, rather than
// entering one as a zero and asserting that these two bins do not touch.
if (same ? transOnly : cisOnly) {
out[at + c] = Number.NaN
continue
}
let denominator: number
if (same) {
const offset = cisSeparation(Math.abs(col - row), lap)
// …and the near-diagonal goes the same way, for the same reason and on
// the same rule cooltools uses. Only in cis: a trans cell has no
// separation for a diagonal to be measured from.
if (offset < ignoreDiags) {
out[at + c] = nearDiagonal
continue
}
// Past the end of the curve is no expectation, as `expectedAt` says.
denominator = offset < own.length ? own[offset] : Number.NaN
} else {
denominator = trans[rowGroup * k + colGroup]
}
const observed = values[from + col]
out[at + c] =
Number.isFinite(observed) && Number.isFinite(denominator) && denominator !== 0
? observed / denominator
: Number.NaN
}
}
return out
}
/**
* The Pearson correlation between every pair of rows.
*
* This is the `m²` object §18.6 gates on, and it is built once and handed
* straight to the eigensolver, which consumes it in place. The diagonal is
* exactly 1 by construction rather than by computation — a row correlated with
* itself over pairwise-complete cells is 1, and computing it invites a
* floating-point 0.9999999 on the diagonal of a matrix that is about to be
* deflated.
*
* Computed by `pearsonRows.ts`, which says how: one matrix product in
* WebAssembly and a few numbers per pair, shared across the cores where the
* analysis worker has allowed it (`pearsonThreads.ts`) — where this used to be
* `pearson` called on every pair. The same statistic, pairwise-complete, fifty
* times sooner on one core.
*/
export async function correlationMatrix(
oe: Float64Array,
m: number,
/**
* Called once per row, before it is correlated against the rows after it.
*
* This loop is `m²` correlations of `m` cells each — cubic, and the one step of
* the chain that is. At a thousand bins it is a tenth of a second and at four
* thousand two on four cores, but at the task's 8,192 it is eight times that,
* so a genome-wide run needs to be able to report where it has got to and to
* be stopped: the callback is where the runner does both, by throwing out of
* it. Optional, because nothing about the arithmetic needs it.
*
* **Awaited**, which is what makes the stopping real. A cancel arrives as a
* message and a message is delivered in a task of its own, so a hook that
* only ever ran synchronously asked about a cancel that could not yet have
* been received however many times it asked (`analysis/job.ts`'s `breathe`).
* The `await` is per *row* and the yield inside it is the runner's to make
* every sixty-fourth, so the round trip is paid once a batch rather than
* `m` times.
*/
onRow?: (row: number) => void | Promise<void>,
): Promise<Float64Array> {
const out = new Float64Array(m * m)
await pearsonRowsThreaded(
{ m, row: (r, into) => into.set(oe.subarray(r * m, (r + 1) * m)) },
(a, line) => {
out[a * m + a] = 1
for (let b = a + 1; b < m; b++) {
// A pair with too little overlap gets 0 rather than NaN: the eigensolver
// needs a real matrix, and *no evidence of correlation* is the honest
// reading of two rows that never overlap. The statistic returning NaN is
// what distinguishes that from a computed zero, and it is why the
// substitution happens here where it can be commented rather than
// inside the statistic.
out[a * m + b] = Number.isFinite(line[b]) ? line[b] : 0
}
},
onRow,
)
mirrorUpper(out, m)
return out
}
/**
* Copy a square's upper triangle onto its lower one, in tiles.
*
* The lines come a row at a time, and writing each one's mirror as it came was
* a write per cell down a column — every one to another cache line and most to
* another page, a fifth of a second of a 4,096-bin square spent on the copy of
* numbers already computed. A tile of rows read and written transposed keeps
* both sides in the cache, and the whole copy is a tenth of that.
*/
function mirrorUpper(values: Float32Array | Float64Array, n: number): void {
const TILE = 64
for (let i0 = 0; i0 < n; i0 += TILE) {
const i1 = Math.min(n, i0 + TILE)
for (let j0 = i0; j0 < n; j0 += TILE) {
const j1 = Math.min(n, j0 + TILE)
for (let i = i0; i < i1; i++) {
const row = i * n
for (let j = Math.max(j0, i + 1); j < j1; j++) values[j * n + i] = values[row + j]
}
}
}
}
/**
* cooltools' ceiling on observed/expected: its 99.9th percentile, `eigs_cis`'s
* default `clip_percentile`.
*/
export const COOLTOOLS_CLIP_PERCENTILE = 99.9
/**
* The matrix cooltools decomposes (`cooltools.api.eigdecomp.cis_eig`), made from
* the same observed/expected the correlation is made from.
*
* The default road to the eigenvectors (§18.8): observed/expected decomposed
* **as it is**, where Lieberman-Aiden et al. (2009) decomposed the Pearson
* correlation of its rows. The correlation did three things of its own, and
* each is done here the way cooltools does it:
*
* - **clipped** — at 0 and at its 99.9th percentile, NumPy's linear one — so a
* handful of very bright cells cannot carry the leading component;
* - **one subtracted**, so each cell is its departure from expected. The
* correlation centred every row and needed nothing of the kind; without it the
* leading eigenvector of an all-positive matrix is its rows' overall level, not
* the checkerboard;
* - **every gap zero** — a cell with no value, and the near diagonal
* `ignoreDiags` removed — which after the subtraction reads *as expected*: a
* decomposition, unlike a correlation, cannot step over one.
*
* Over the usable bins alone, like the correlation: a bin the balancer dropped is
* still left out rather than zeroed — cooltools zeroes it and then keeps the zero
* row out of its solver, which comes to the same thing. The percentile is of the
* cells that have a value, which over {@link cooltoolsPlan}'s observed/expected
* includes the near diagonal's ones, as cooltools' does.
*
* `oe` is `m × m` row-major and is left as it was unless `out` is `oe` itself —
* which the runner passes for the square nothing reads afterwards, and not for the
* one the saddle reads.
*/
export function cooltoolsMatrix(
oe: Float64Array,
m: number,
percentile = COOLTOOLS_CLIP_PERCENTILE,
out: Float64Array = new Float64Array(m * m),
): Float64Array {
const ceiling = upperPercentile(oe, percentile)
for (let i = 0; i < m * m; i++) out[i] = departure(oe[i], ceiling)
return out
}
/**
* The most the two ends of one of cooltools' groups of separations are apart:
* `observed_over_expected`'s `dist_bin_edge_ratio`.
*/
export const COOLTOOLS_DIST_BIN_EDGE_RATIO = 1.03
/**
* The edges of the groups cooltools pools the separations of an `n`-bin square
* into: `0`, then `_logbins_numba(1, n, ratio)` — `n`'s logarithm cut into
* `⌊ln n / ln ratio⌋` even steps, each raised back and rounded to the nearest
* whole separation, ties to even as NumPy's `rint` breaks them, and the repeats
* dropped. Each group runs from one edge up to the next, the last up to `n`.
*/
export function cooltoolsSeparationGroups(
n: number,
ratio = COOLTOOLS_DIST_BIN_EDGE_RATIO,
): Int32Array {
const edges = [0]
if (n < 1) return Int32Array.from(edges)
const steps = Math.trunc(Math.log(n) / Math.log(ratio))
const top = Math.log10(n)
// NumPy's `linspace`: each point the step times its rank, the last the end itself.
const step = steps > 1 ? top / (steps - 1) : 0
for (let i = 0; i < steps; i++) {
const edge = halfEven(10 ** (steps > 1 && i === steps - 1 ? top : i * step))
if (edge > edges[edges.length - 1]) edges.push(edge)
}
// Both ends are there by construction past a handful of bins; a square too small
// for a step still has its one group of separations from 1.
if (edges[1] !== 1) edges.splice(1, 0, 1)
if (edges[edges.length - 1] !== n) edges.push(n)
return Int32Array.from(edges)
}
/** NumPy's `rint`: the nearest whole number, a half to the even one. */
function halfEven(value: number): number {
const up = Math.round(value)
return up - value === 0.5 && up % 2 !== 0 ? up - 1 : up
}
/**
* The distance decay as cooltools' `eigs_cis` divides by it: each separation's
* mean replaced by its group's (§18.8).
*
* `cis_eig` does not read `expected_cis`. It takes its expectation from the square
* in hand (`numutils.observed_over_expected`), and that is not a mean per
* diagonal: from about the thirty-fifth, where one separation is less than 3% past
* the one before, the diagonals are pooled in groups whose ends are at most 3%
* apart ({@link cooltoolsSeparationGroups}) and every cell of a group is divided by
* the group's mean. Over the mean of its own diagonal, the far cells of a
* chromosome sit on a sawtooth of a percent or two against cooltools' — which on
* the mouse map at 100 kb (validation § 3) left E1 at r = 0.9985 to 0.99993 with
* cooltools', chromosome by chromosome. Over this one every component is
* cooltools' to the six significant digits a track is written in.
*
* Two more of `observed_over_expected`'s rules come with it, each a cell's worth of
* cooltools' arithmetic rather than a choice:
*
* - the **near diagonal** is pooled as ones, which cooltools sets it to before it
* pools — a difference only where `ignoreDiags` reaches into a group of several;
* - a group with **no contacts at all** is left undivided, its cells the zeros they
* were, and so `1` here; `0 / 0` would be a gap, *as expected* once prepared, and
* cooltools reads those cells as nothing where something was expected. It is the
* far corner of a chromosome whose ends the map holds no contacts between.
*
* The groups are a square's of `maxOffset + 1` bins — the sequence, along a line.
* `sum` and `count` are the curve's own, per separation; only `mean` is the group's,
* so the curve answers {@link expectedAt} and is not one to merge.
*/
export function cooltoolsExpected(
curve: ExpectedCurve,
ignoreDiags: number,
ratio = COOLTOOLS_DIST_BIN_EDGE_RATIO,
): ExpectedCurve {
const n = curve.maxOffset + 1
const edges = cooltoolsSeparationGroups(n, ratio)
const mean = new Float64Array(n).fill(Number.NaN)
for (let g = 0; g + 1 < edges.length; g++) {
let sum = 0
let count = 0
for (let k = edges[g]; k < edges[g + 1]; k++) {
sum += k < ignoreDiags ? curve.count[k] : curve.sum[k]
count += curve.count[k]
}
if (count === 0) continue
const value = sum === 0 ? 1 : sum / count
for (let k = edges[g]; k < edges[g + 1]; k++) mean[k] = value
}
return { maxOffset: curve.maxOffset, sum: curve.sum, count: curve.count, mean }
}
/**
* The plan cooltools' `cis_eig` divides by: each sequence's decay pooled as
* {@link cooltoolsExpected} pools it, and the near diagonal one rather than a gap.
*
* Only for the matrix {@link cooltoolsMatrix} prepares. The saddle is cooltools'
* `saddle`, which divides by `expected_cis` — a mean per diagonal — and the
* correlation is Lieberman-Aiden's, so both keep the plan they were given. A trans
* block is divided by its pair's mean either way: `eigs_cis` has none.
*/
export function cooltoolsPlan(plan: ExpectedPlan): ExpectedPlan {
return {
...plan,
cis: plan.cis.map((curve) => cooltoolsExpected(curve, plan.ignoreDiags)),
nearDiagonal: 1,
}
}
/** One cell of {@link cooltoolsMatrix}: clipped, less one, and a gap as expected. */
function departure(value: number, ceiling: number): number {
return Number.isFinite(value) ? Math.min(Math.max(value, 0), ceiling) - 1 : 0
}
/**
* How much of the contacts each component accounts for: the share of the map's
* departure from expected that its checkerboard explains (§18.8).
*
* The departure is {@link cooltoolsMatrix}'s — every cell's observed/expected,
* clipped, less one, a gap reading as expected — which is what the contacts say
* once the distance decay is out of them. A unit vector `v` draws the
* checkerboard `v vᵀ`, and the most of the departure `A` that checkerboard can
* carry is `(vᵀ A v) v vᵀ`: so its share is `(vᵀ A v)²` over the sum of `A`'s
* cells squared.
*
* **One measure whichever matrix the components came from.** Under cooltools'
* method they are `A`'s own eigenvectors, `vᵀ A v` is the eigenvalue, and this
* is the eigenvalue squared over the sum of squares that the method has always
* reported. Under the correlation it is the one number about the contacts the
* table had not got: a correlation matrix's eigenvalue is a share of *its*
* variance, the similarity of rows to rows, and says nothing of how much of the
* map the pattern is. Orthogonal components' checkerboards are orthogonal too,
* so the shares of several add up to what they carry together, and never past
* the whole.
*
* Summed a row at a time from `oe` itself rather than from the prepared matrix,
* which at the task's 8,192 bins would be another half gigabyte for a few
* numbers. The runner hands it {@link cooltoolsPlan}'s observed/expected wherever
* the expectation is the distance decay, so that under either method the map
* measured is the one cooltools' method decomposes.
*/
export function contactShares(
oe: Float64Array,
m: number,
vectors: readonly Float64Array[],
percentile = COOLTOOLS_CLIP_PERCENTILE,
): number[] {
const ceiling = upperPercentile(oe, percentile)
const fit = new Float64Array(vectors.length)
const row = new Float64Array(m)
let whole = 0
for (let i = 0; i < m; i++) {
for (let j = 0; j < m; j++) {
const a = departure(oe[i * m + j], ceiling)
row[j] = a
whole += a * a
}
for (let k = 0; k < vectors.length; k++) {
const v = vectors[k]
let dot = 0
for (let j = 0; j < m; j++) dot += row[j] * v[j]
fit[k] += v[i] * dot
}
}
return Array.from(fit, (c) => (whole > 0 ? (c * c) / whole : Number.NaN))
}
/**
* NumPy's `percentile` of the finite values — linear between the two nearest
* ranks — from the top.
*
* Only the values at and above the rank are held, in a heap, rather than a sorted
* copy of the square: at the 8,192-bin gate the square is half a gigabyte, and the
* 99.9th percentile needs a thousandth of it.
*/
function upperPercentile(values: Float64Array, percentile: number): number {
let n = 0
for (let i = 0; i < values.length; i++) if (Number.isFinite(values[i])) n++
if (n === 0) return Number.NaN
const at = (Math.min(100, Math.max(0, percentile)) / 100) * (n - 1)
const rank = Math.floor(at)
// A min-heap of the `n − rank` largest values: its root is the value at `rank`.
const size = n - rank
const heap = new Float64Array(size)
let held = 0
const down = (from: number, count: number): void => {
let i = from
for (;;) {
const left = 2 * i + 1
const right = left + 1
let least = i
if (left < count && heap[left] < heap[least]) least = left
if (right < count && heap[right] < heap[least]) least = right
if (least === i) return
const swap = heap[i]
heap[i] = heap[least]
heap[least] = swap
i = least
}
}
for (let i = 0; i < values.length; i++) {
const value = values[i]
if (!Number.isFinite(value)) continue
if (held < size) {
let slot = held++
heap[slot] = value
while (slot > 0) {
const parent = (slot - 1) >> 1
if (heap[parent] <= heap[slot]) break
const swap = heap[parent]
heap[parent] = heap[slot]
heap[slot] = swap
slot = parent
}
} else if (value > heap[0]) {
heap[0] = value
down(0, held)
}
}
const low = heap[0]
const fraction = at - rank
if (fraction === 0 || held < 2) return low
// The next rank up is the smallest of what is left once the root is gone.
heap[0] = heap[held - 1]
down(0, held - 1)
return low + (heap[0] - low) * fraction
}
/** What {@link correlationField} produces: a square the map can draw. */
export interface CorrelationField {
/** `n * n`, row-major, `NaN` in every row and column that was dropped. */
values: Float32Array
/** Bins that took part. */
kept: number
/** Bins dropped for having too little data to correlate on. */
dropped: number
}
/**
* {@link correlationMatrix} over a **full square**, put back on the grid it came
* from — the correlation map as a picture rather than as the eigensolver's
* input.
*
* The same three steps the compartment chain takes, in the same order and
* through the same two functions, which is the point: a reader looking at this
* map is looking at the object their eigenvector was computed from, and a second
* implementation "for display" would be a second answer that agreed with the
* first until it did not.
*
* What is different is only the last step. The chain hands the correlation
* straight to the solver over the usable index and expands the *eigenvector*
* afterwards; a picture has to be expanded itself, and the expansion restores
* the dropped bins **as gaps**. A dropped row drawn as zero would be a stripe of
* "uncorrelated with everything" across a compartment map — the same false, and
* far more visible, claim this module's header refuses to make about the track.
*
* `NaN` fills what the correlation could not reach. The raster draws it
* transparent (§6.4), so a blank row on a correlation map means exactly what a
* blank row on a balanced map means, and neither is a value.
*/
export async function correlationField(
oe: Float32Array,
n: number,
onRow?: (row: number) => void | Promise<void>,
): Promise<CorrelationField> {
const index = usableBins(oe, n)
const m = index.length
const values = new Float32Array(n * n).fill(Number.NaN)
// Two bins cannot be correlated against each other and one cannot be
// correlated at all. Returning the empty field rather than throwing: a block
// with nothing usable in it is a legitimate thing to point the toggle at — a
// sparse trans corner — and it should draw as blank, not as an error card.
if (m < 2) return { values, kept: m, dropped: n - m }
// The usable rows, read straight off the square, and each row's line of
// correlations put straight back on it: the correlation matrix's own
// arithmetic (`pearsonRows.ts`), with no packed copy of the square and no
// second one of the answer — at 4,096 bins each is 64 MB.
await pearsonRowsThreaded(
{
m,
row: (r, into) => {
const from = index[r] * n
for (let c = 0; c < m; c++) into[c] = oe[from + index[c]]
},
},
(a, line) => {
const ia = index[a]
const row = ia * n
values[row + ia] = 1
// No evidence reads as no correlation, as in `correlationMatrix`.
for (let b = a + 1; b < m; b++) values[row + index[b]] = Number.isFinite(line[b]) ? line[b] : 0
},
onRow,
)
// A dropped bin's row and column are blank on both sides of the diagonal, so
// the whole square's upper triangle is the lower one's.
mirrorUpper(values, n)
return { values, kept: m, dropped: n - m }
}
/** A signal the sign of a component is attached to, over the same bins. */
export interface PhasingSignal {
name: string
/** One value per *usable* bin, in the same order as the index. */
values: Float64Array
}
export interface Phasing {
/** Whether the component was flipped. */
flipped: boolean
/** The correlation the decision was made on. */
r: number
/** `false` when |r| was too small to decide. */
confident: boolean
signal: string
}
/**
* Give a component's sign a meaning.
*
* Flips so that positive correlates with the signal, and says how strongly. The
* threshold is the caller's, and below it nothing is flipped and `confident` is
* `false` — because a sign chosen on an `r` of 0.04 is a coin flip wearing a
* decision's clothes, and a reader comparing two chromosomes phased that way
* would be comparing noise.
*/
export function phaseComponent(
component: Float64Array,
signal: PhasingSignal,
threshold: number,
): Phasing {
const r = pearson(component, signal.values)
if (!Number.isFinite(r) || Math.abs(r) < threshold) {
return { flipped: false, r: Number.isFinite(r) ? r : Number.NaN, confident: false, signal: signal.name }
}
const flipped = r < 0
if (flipped) {
for (let i = 0; i < component.length; i++) component[i] = -component[i]
}
return { flipped, r, confident: true, signal: signal.name }
}
/**
* The saddle: observed/expected averaged by the compartment rank of both bins.
*
* Bins are sorted by their eigenvector value and cut into equal groups, and each
* cell of the saddle is the mean O/E between two groups. The picture is the whole
* compartment claim in one square — AA and BB bright at the corners, AB dark off
* them — and the three numbers under it are what makes it a measurement.
*
* Quantiles of the *eigenvector*, not of the signal it was phased by: the
* eigenvector is what the matrix says, and ranking by anything else would be
* asking whether the matrix agrees with a track rather than what the matrix
* itself contains.
*/
export function saddle(
oe: Float64Array,
m: number,
component: Float64Array,
bins: number,
): { values: Float32Array; edges: Float64Array; strength: { aa: number; bb: number; ab: number } } {
const edges = quantileEdges(component, bins)
const group = new Int32Array(m).fill(-1)
for (let i = 0; i < m; i++) {
const value = component[i]
if (!Number.isFinite(value)) continue
// The last group is closed at the top, so the maximum lands inside it
// rather than in a group that does not exist.
let g = 0
while (g < bins - 1 && value >= edges[g + 1]) g++
group[i] = g
}
const sum = new Float64Array(bins * bins)
const count = new Float64Array(bins * bins)
for (let r = 0; r < m; r++) {
const gr = group[r]
if (gr < 0) continue
for (let c = 0; c < m; c++) {
const gc = group[c]
if (gc < 0) continue
const value = oe[r * m + c]
if (!Number.isFinite(value)) continue
sum[gr * bins + gc] += value
count[gr * bins + gc] += 1
}
}
const values = new Float32Array(bins * bins)
for (let i = 0; i < values.length; i++) {
values[i] = count[i] > 0 ? sum[i] / count[i] : Number.NaN
}
// The corners, over the extreme fifth of the range at each end — which is the
// conventional reading and is what makes the three numbers comparable between
// runs at different quantile counts.
const edge = Math.max(1, Math.round(bins / 5))
const mean = (r0: number, r1: number, c0: number, c1: number): number => {
let total = 0
let seen = 0
for (let r = r0; r < r1; r++) {
for (let c = c0; c < c1; c++) {
const value = values[r * bins + c]
if (!Number.isFinite(value)) continue
total += value
seen++
}
}
return seen === 0 ? Number.NaN : total / seen
}
return {
values,
edges,
strength: {
// `bb` is the *low* end of the eigenvector and `aa` the high one, which is
// only meaningful once the component has been phased — the saddle inherits
// whatever meaning phasing gave the sign, and inherits its uncertainty too.
bb: mean(0, edge, 0, edge),
aa: mean(bins - edge, bins, bins - edge, bins),
ab: mean(0, edge, bins - edge, bins),
},
}
}
// ---------------------------------------------------------------------------
// The call
// ---------------------------------------------------------------------------
/** One run of bins that E1 puts on the same side of zero. */
export interface CompartmentSegment {
/** `'A'` where E1 is positive, `'B'` where it is negative. */
side: 'A' | 'B'
/** First and last bin of the run, **inclusive**, in the index's own numbering. */
from: number
to: number
/** Mean of E1 over the run — the strength of the call. */
mean: number
/** How many bins are in it. */
bins: number
}
/**
* E1's sign, as **A and B segments** — the compartment call the track implies.
*
* The eigenvector is a number per bin and the thing everybody actually cites is
* the interval: *this arm is A, that half-megabase is B*. Getting from one to
* the other meant exporting the bigWig and thresholding it somewhere else, which
* is a second tool for one comparison against zero — and one this app can make
* without the ambiguity a downstream threshold introduces, because it knows
* which bins were excluded and does not have to guess whether a gap is a zero.
*
* Three rules, and each is a way the naive version would be wrong.
*
* **A run is consecutive bins**, and consecutive means consecutive in the file's
* own numbering rather than in the index. `index` holds only the bins that
* carried enough data to correlate, so two entries beside each other in it can
* be a megabase apart on the chromosome; joining them would draw a segment
* across a stretch that took no part in the calculation and assert a compartment
* there.
*
* **Zero and `NaN` end a run and start nothing.** A bin at exactly zero is not
* evidence of A, and a bin with no value is not evidence of anything.
*
* **The mean is carried**, so the call has a strength: it becomes the BED's
* score column, which is what lets an overlay be filtered on it and what a
* downstream tool sorts by.
*
* @param index Bins that took part, ascending, in the file's own numbering.
* @param vector E1 over those bins, one value per entry of `index`.
*/
export function compartmentSegments(
index: Int32Array,
vector: Float64Array,
): CompartmentSegment[] {
const out: CompartmentSegment[] = []
let from = -1
let last = -1
let side: 1 | -1 | 0 = 0
let total = 0
let bins = 0
const flush = (): void => {
if (from >= 0 && side !== 0) {
out.push({
side: side > 0 ? 'A' : 'B',
from,
to: last,
mean: bins === 0 ? Number.NaN : total / bins,
bins,
})
}
from = -1
total = 0
bins = 0
}
for (let i = 0; i < index.length && i < vector.length; i++) {
const bin = index[i]
const value = vector[i]
const next: 1 | -1 | 0 = Number.isFinite(value) && value > 0 ? 1 : value < 0 ? -1 : 0
if (next !== side || bin !== last + 1) flush()
side = next
last = bin
if (next === 0) continue
if (from < 0) from = bin
total += value
bins++
}
flush()
return out
}
|