All files / src/hicpro parse.ts

90.97% Statements 383/421
87.17% Branches 136/156
86.66% Functions 13/15
90.97% Lines 383/421

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                                                                                      2x 2x       2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x                                                                                                                                                   2x 28x 28x 28x 28x 28x 28x 28x 28x   28x 28x 28x 28x   128x 2x 2x 2x 128x 2x 2x 2x   124x 128x 124x 128x     124x 124x 124x 128x 124x 124x 124x       124x 128x 121x 121x 121x         121x 1x 1x 1x     1x 1x 1x 120x 120x 128x 123x   123x 128x 128x 123x 128x 120x 120x 120x 120x           128x 51x 1x 1x 50x 50x 50x 128x 72x 72x 128x   28x     26x 28x           26x     28x                   26x 26x 26x 26x 26x 28x 28x 28x 28x     26x 26x 26x 26x 26x 26x 26x 26x 48x     48x 48x 48x 24x 24x   125x 125x 125x 125x 129x 129x 1x 1x   1x 1x 1x 1x     1x 1x 1x                         2x 2x                                                   38x 38x 38x 38x 38x 38x 38x 38x 38x   38x 38x                 38x 38x 38x         38x 38x 38x 38x                                   38x 38x 38x 38x 38x 38x 38x 37x 37x 37x 37x     37x 38x                       38x 38x   38x 38x 38x 38x 38x 198x 198x 198x 198x 198x 198x   37x 38x   37x 37x 37x 37x 37x 37x 37x 38x 38x 38x       2x                     38x 38x 38x 38x 38x                                                             38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x   38x 199x       199x       199x       199x 199x 199x 398x 398x 199x 199x 199x 199x 199x 199x 199x 199x 199x 398x 398x 199x 199x 199x 199x 199x 199x     199x 199x 199x 199x 1x 1x 1x 199x 425x 425x 227x 227x 227x 227x 199x 3x 3x 3x 7x 7x 4x 4x 4x 4x 4x 3x   199x 5x 5x 5x 5x 2x 2x 5x 1x 1x 5x 5x 5x 9x 9x 4x 4x 4x 4x     5x 1x 5x 199x 199x 199x 199x         199x 199x 199x 1x 1x 1x 1x   1x 1x 1x       199x 199x   199x 199x 199x 199x 199x 199x   37x 37x 37x 37x 37x 37x                                                   37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 183x 183x 183x     183x 183x 198x 24x   23x 23x 23x 23x   1x 1x 1x 174x 174x 174x 174x 174x 174x 183x 37x 37x 37x                 37x 37x 37x 37x 37x 37x 37x 37x                 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 198x 198x 198x 37x 37x     2x           369x 369x 369x 369x 369x       369x 1131x 1131x 762x 762x 762x 762x 369x 369x                                  
/**
 * Reading a HiC-Pro contact map, which is two text files and no index.
 *
 * The format is documented in HiC-Pro's own `RESULTS.md` and is as small as a
 * contact map format gets:
 *
 * - **`<prefix>_<res>_abs.bed`** — `chrom  start  end  binID`, one row per bin
 *   of the whole genome, where `binID` is **1-based and global**: it runs
 *   continuously across chromosomes rather than restarting at each.
 * - **`<prefix>_<res>.matrix`** — `binA  binB  count`, one row per non-zero
 *   pixel, referring to those ids. `MATRIX_FORMAT` decides whether the stored
 *   half is `upper` (the default), `lower`, `complete`, or `asis`.
 *
 * The BED *is* a `/bins` table, and run-length encoding its first column gives
 * the `/chroms` table and `indexes/chrom_offset` that everything above the
 * reader is written against. The matrix *is* `/pixels`. What the format does
 * not have is `indexes/bin1_offset` — and that absence is the whole of what
 * makes this container different, so it is worth being exact about it.
 *
 * ## Why the whole file is read, and why that is the end of the cost
 *
 * There is no index, and there is no index that could be *derived* without
 * reading everything: the rows are text of variable width, so byte offset and
 * bin id have no relation, and the rows need not even be sorted (`asis` says so
 * outright). So a region cannot be a bounded read the way a cooler's or a
 * `.hic`'s is, and pretending otherwise would mean scanning the file per view
 * instead of once.
 *
 * The answer is to pay it once, at open, and hand the rest of the application
 * exactly what it already knows how to use: sorted triplets and a CSR index. A
 * counting sort by `bin1` gives both in one pass, and after it every read is
 * bounded, in memory, and instant — pan and zoom cost nothing at all. Measured
 * at **6.8 M pixels/s (≈100 MB/s)** parsing, and **~300 ms per 10 M pixels** to
 * build the index; a pixel occupies 12 bytes here against about 15 as text.
 *
 * ## Why it is parsed byte by byte
 *
 * `split('\n')` on a gigabyte allocates a string per line and a string per
 * field, three of them, all garbage. The scan below never makes a string at
 * all: it walks the bytes accumulating digits, which is where the throughput
 * above comes from and why a 1 GB file is a wait rather than a crash.
 */
 
import { yieldToEventLoop } from '../async'
import { ViewerError } from '../errors'
import type { StorageMode } from '../constants'
 
/** Byte values the scanners compare against, named so the loops read. */
const TAB = 9
const NEWLINE = 10
const RETURN = 13
const HASH = 35
const PLUS = 43
const MINUS = 45
const DOT = 46
const ZERO = 48
const NINE = 57
const E_UPPER = 69
const E_LOWER = 101
 
/** The `/bins` half of the pair, as the reader's coordinate model wants it. */
export interface HicProBins {
  /** Sequence names, in the order the file lists them. */
  names: string[]
  /** Sequence lengths in bp — the last bin's `end`, which is the sequence end. */
  lengths: Float64Array
  /** `indexes/chrom_offset`: first bin of each sequence, plus a terminator. */
  chromOffset: Float64Array
  /** Bins in the file, which is `chromOffset`'s last entry. */
  nBins: number
  /**
   * The bin size in bp, or `null` where the rows are not a fixed grid.
   *
   * Taken from the **widest** interval rather than the first: every sequence's
   * last bin is short wherever its length is not a multiple of the resolution,
   * and on a genome whose first sequence is shorter than one bin the first row
   * *is* that short bin. The mode of the widths would be the same answer at
   * more cost; the maximum is exact for a fixed grid and is what makes a
   * variable one detectable, since there every width disagrees with it.
   */
  binsize: number | null
  /**
   * `true` when every interval is the bin size except the last of a sequence.
   *
   * §3.3 excludes variable-bin files from the whole application, and a
   * fragment-level HiC-Pro map — which is what `GENOME_FRAGMENT` produces — is
   * exactly one. Detected here because this is the only place the intervals are
   * read, and refused by the caller with the file's own numbers.
   */
  fixed: boolean
}
 
/** The `/pixels` half, sorted and indexed. */
export interface HicProPixels {
  /** Row bin of each stored pixel, 0-based, ascending. */
  bin1: Int32Array
  /** Column bin, 0-based. Upper-triangular against `bin1` after normalisation. */
  bin2: Int32Array
  /** The value column. Float32 because `iced/` matrices are not integers. */
  count: Float32Array
  /** `indexes/bin1_offset`: one cumulative entry per bin, plus a terminator. */
  binOffset: Float64Array
  /** Stored pixels, after any collapsing the normalisation did. */
  nnz: number
  /** Sum of every value, which the info panel reports as a cooler's does. */
  sum: number
  /**
   * What the file turned out to hold, before this reader normalised it.
   *
   * Reported rather than acted on: everything downstream is handed
   * `symmetric-upper` whatever came in, because the normalisation below swaps
   * the ends of any pixel stored the other way round. It is on the info panel
   * so a reader can see that a `lower` or `complete` file was understood as one.
   */
  observed: 'upper' | 'lower' | 'mixed' | 'complete'
}
 
// ---------------------------------------------------------------------------
// The bins
// ---------------------------------------------------------------------------
 
/**
 * Parse `<prefix>_<res>_abs.bed` into a coordinate system.
 *
 * The fourth column is deliberately **not** read. It is the bin id, it is
 * 1-based, and it is by construction the row number — so trusting the row
 * number costs nothing and trusting the column would mean deciding what to do
 * about a file whose ids skip, restart or disagree with their order. The one
 * thing worth checking is that the two agree, and {@link parseBins} does that
 * on the first and last rows, where a disagreement means the file is not what
 * it says it is rather than that one row is odd.
 */
export function parseBins(bytes: Uint8Array, label: string): HicProBins {
  const names: string[] = []
  const lengths: number[] = []
  const offsets: number[] = [0]
  let widest = 0
  let rows = 0
  let firstId: number | null = null
  let lastId = 0
  let sawAnyId = false
 
  const decoder = new TextDecoder()
  const n = bytes.length
  let at = 0
  while (at < n) {
    // Skip blank lines and the comment/track headers a BED may carry.
    if (bytes[at] === NEWLINE || bytes[at] === RETURN) {
      at++
      continue
    }
    if (bytes[at] === HASH || isTrackLine(bytes, at)) {
      while (at < n && bytes[at] !== NEWLINE) at++
      continue
    }
    // chrom
    const nameFrom = at
    while (at < n && bytes[at] !== TAB && bytes[at] !== NEWLINE) at++
    const name = decoder.decode(bytes.subarray(nameFrom, at))
    if (at < n && bytes[at] === NEWLINE) {
      throw badBed(label, rows + 1, 'a row with one column')
    }
    at++
    const start = readInt(bytes, at)
    at = start.at
    if (bytes[at] !== TAB) throw badBed(label, rows + 1, 'a row with two columns')
    at++
    const end = readInt(bytes, at)
    at = end.at
    // The fourth column is optional here for the reason above: a plain BED3 of
    // the same grid is the same coordinate system, and a reader who has one
    // should not be turned away over a column this never reads.
    let id: number | null = null
    if (bytes[at] === TAB) {
      at++
      const fourth = readInt(bytes, at)
      at = fourth.at
      // Present but not a number is the signal that separates a bin file from
      // an ordinary BED, whose fourth column is a feature *name*. Both are
      // valid BED4; only one is a coordinate system, and the difference is
      // visible here and nowhere else.
      if (!fourth.saw) {
        throw new ViewerError(
          'format',
          `${label} is a BED whose fourth column holds names rather than bin ids, so it ` +
            'describes features rather than a bin grid — drop it as a track instead. A ' +
            "HiC-Pro bin file numbers its bins 1…n, and is written as `<prefix>_<res>_abs.bed`.",
          { label, row: rows + 1 },
        )
      }
      id = fourth.value
    }
    while (at < n && bytes[at] !== NEWLINE) at++
    at++
 
    const width = end.value - start.value
    if (width <= 0) throw badBed(label, rows + 1, `an interval of width ${width}`)
    if (width > widest) widest = width
    rows++
    if (id !== null) {
      if (!sawAnyId) firstId = id
      sawAnyId = true
      lastId = id
    }
 
    // A new sequence starts wherever the name changes. The file is in bin
    // order by construction — that is what makes the ids global — so a name
    // that comes back later is a file this cannot read as a coordinate system,
    // and it is caught below rather than silently producing two runs.
    if (names.length === 0 || names[names.length - 1] !== name) {
      if (names.includes(name)) {
        throw badBed(label, rows, `${JSON.stringify(name)} in two separate runs of rows`)
      }
      names.push(name)
      lengths.push(end.value)
      offsets.push(rows - 1)
    } else {
      lengths[lengths.length - 1] = end.value
    }
  }
 
  if (rows === 0) throw badBed(label, 0, 'no rows at all')
  // `offsets` collected each run's *start*; the array the reader wants is those
  // starts plus a terminator at the total.
  const chromOffset = Float64Array.from([...offsets.slice(1), rows])
  if (chromOffset.length !== names.length + 1) {
    throw badBed(label, rows, `${names.length} sequences but ${chromOffset.length} offsets`)
  }
 
  // Every interval is the grid width except a sequence's last, which is short
  // wherever the sequence does not divide by it. Anything else is variable bins.
  const fixed = isFixedGrid(names.length, chromOffset, lengths, widest)
 
  // `null` is a BED3, which carries no ids to disagree with the row order.
  if (firstId !== null && (firstId !== 1 || lastId !== rows)) {
    throw new ViewerError(
      'format',
      `${label} is not a HiC-Pro bin file: its bin ids run ${firstId}…${lastId} over ${rows} ` +
        `rows, and HiC-Pro numbers them 1…n in row order. If this is an ordinary BED, it ` +
        `describes features rather than a bin grid — drop it as a track instead.`,
      { label, firstId, lastId, rows },
    )
  }
 
  return {
    names,
    lengths: Float64Array.from(lengths),
    chromOffset,
    nBins: rows,
    binsize: fixed ? widest : null,
    fixed,
  }
}
 
/** Whether every sequence's bins are the grid width, bar a short last one. */
function isFixedGrid(
  nSeq: number,
  chromOffset: Float64Array,
  lengths: readonly number[],
  width: number,
): boolean {
  if (width <= 0) return false
  for (let i = 0; i < nSeq; i++) {
    const bins = chromOffset[i + 1] - chromOffset[i]
    // A sequence of `bins` bins at this width covers `(bins - 1) * width` fully
    // and ends inside the last one, so its length must land in that final bin.
    const floor = (bins - 1) * width
    if (lengths[i] <= floor || lengths[i] > bins * width) return false
  }
  return true
}
 
function isTrackLine(bytes: Uint8Array, at: number): boolean {
  const word = 'track'
  if (at + word.length > bytes.length) return false
  for (let i = 0; i < word.length; i++) {
    if (bytes[at + i] !== word.charCodeAt(i)) return false
  }
  return true
}
 
function badBed(label: string, row: number, what: string): ViewerError {
  return new ViewerError(
    'format',
    `${label} is not a HiC-Pro bin file: ${what}${row > 0 ? ` at row ${row}` : ''}. ` +
      'The file beside a `.matrix` is `chrom  start  end  binID`, one row per bin of the ' +
      'whole genome, and HiC-Pro writes it as `<prefix>_<res>_abs.bed`.',
    { label, row },
  )
}
 
// ---------------------------------------------------------------------------
// The pixels
// ---------------------------------------------------------------------------
 
/** Progress, since this is the one read in the application worth reporting. */
export interface ParseProgress {
  onProgress?(done: number, total: number): void
  cancelled?(): boolean
}
 
/** The hooks' stand-ins, named so the scan loop always calls a real function. */
const noReport = (): void => {}
const notCancelled = (): boolean => false
 
/**
 * Parse `<prefix>_<res>.matrix` into sorted triplets and a CSR index.
 *
 * Three passes, and each is there for a reason worth stating:
 *
 * 1. **count the rows**, so the arrays are allocated exactly once at the right
 *    size. Growing them instead means repeated reallocation and copying of
 *    hundreds of megabytes, which costs more than this pass does;
 * 2. **read the values**, normalising 1-based ids to 0-based and swapping the
 *    ends of any pixel stored below the diagonal, so what comes out is
 *    upper-triangular whatever `MATRIX_FORMAT` the file was written with;
 * 3. **counting-sort by `bin1`**, which produces the sorted order and the
 *    cumulative `bin1_offset` together, because the offsets *are* the sort's
 *    bucket boundaries.
 *
 * Asynchronous, and only for the cancel: the loop hands the worker's event
 * loop back every hundredth of the file so a `cancel` message can be read
 * between them. Nothing here awaits I/O — the bytes are already in hand.
 *
 * A `complete` matrix stores both triangles, so normalising it would fold each
 * pixel onto its mirror and double every off-diagonal cell. That case is
 * detected — a file holding both `(a, b)` and `(b, a)` — and the lower half is
 * dropped rather than added, which is what makes the counts right.
 */
export async function parseMatrix(
  bytes: Uint8Array,
  nBins: number,
  label: string,
  hooks: ParseProgress = {},
): Promise<HicProPixels> {
  const n = bytes.length
  let rows = 0
  for (let i = 0; i < n; i++) if (bytes[i] === NEWLINE) rows++
  // A file whose last line has no terminator still holds that pixel.
  if (n > 0 && bytes[n - 1] !== NEWLINE) rows++
  if (rows === 0) {
    throw new ViewerError(
      'format',
      `${label} holds no pixels. A HiC-Pro matrix is \`binA  binB  count\`, one row per ` +
        'non-zero pixel.',
      { label },
    )
  }
 
  const bin1 = new Int32Array(rows)
  const bin2 = new Int32Array(rows)
  const count = new Float32Array(rows)
  // Which side of the diagonal each row was *stored* on, before the swap below
  // put it on the upper one. It is the only thing that separates a `complete`
  // file's mirror from a genuine repeat once both are upper-triangular, and
  // those two want opposite treatment — see {@link collapse}.
  const swapped = new Uint8Array(rows)
  const state: ScanState = { out: 0, line: 0, sawUpper: false, sawLower: false }
  let sum = 0
  let at = 0
 
  // The tight loop is a **synchronous** function called slice by slice, and the
  // yield sits between the calls rather than inside the loop. That shape is not
  // stylistic: an `await` inside the scanning loop makes the whole loop part of
  // an async function's state machine, and V8 stops optimising it — measured at
  // 40 s for a 270 MB file against 2.7 s for the same code with the await moved
  // out. The yield is still needed, because a cancel arrives as a message and a
  // worker that never returns to its event loop never reads one (`../async`).
  //
  // The hooks are resolved to real functions *here*, and calling them through
  // `?.` in the loop below would undo the paragraph above entirely. V8 inlines
  // `scanSlice` back into this function and compiles the loop as one unit; an
  // optional call that has never been made carries no type feedback, so that
  // unit is thrown away — `Insufficient type feedback for call` — on the first
  // slice, recompiled on the next, and thrown away again. The scan then runs
  // interpreted, which measured **35 s for a 270 MB file against 0.9 s** here.
  // A default that is a function makes both call sites ordinary ones.
  const report = hooks.onProgress ?? noReport
  const isCancelled = hooks.cancelled ?? notCancelled
  while (at < n) {
    const stop = lineBoundaryAfter(bytes, Math.min(n, at + SCAN_SLICE))
    at = scanSlice(bytes, at, stop, nBins, label, bin1, bin2, count, swapped, state)
    await yieldToEventLoop()
    if (isCancelled()) throw cancelled()
    report(state.out, rows)
  }
  const out = state.out
  const { sawUpper, sawLower } = state
  // A file of nothing but its diagonal is in neither triangle and is reported
  // as the default one, which is what it would have been written as.
  const observed: HicProPixels['observed'] =
    sawUpper && sawLower ? 'mixed' : sawLower ? 'lower' : 'upper'
 
  // Two stable counting sorts — by `bin2`, then by `bin1` — which together put
  // the pixels in the (row, column) order a cooler stores them in, and leave
  // the second pass's bucket boundaries as `bin1_offset` exactly.
  //
  // A radix sort rather than a sort per row band, and the difference is not
  // academic. Sorting each band on its own is quadratic in the band's width,
  // and bands are *wide*: a row of a 100 kb human matrix has thousands of
  // non-zero columns. Measured on a 211 MB file with wide bands, the per-band
  // insertion sort took 59 s where this takes about two — the parse itself runs
  // at 100 MB/s and the sort must not be what decides the wait.
  const byColumn = countingSort(bin2, out, nBins)
  const { order, offsets: binOffset } = countingSortBy(bin1, byColumn, out, nBins)
 
  const sorted1 = new Int32Array(out)
  const sorted2 = new Int32Array(out)
  const sortedV = new Float32Array(out)
  const sortedSide = new Uint8Array(out)
  for (let k = 0; k < out; k++) {
    const from = order[k]
    sorted1[k] = bin1[from]
    sorted2[k] = bin2[from]
    sortedV[k] = count[from]
    sortedSide[k] = swapped[from]
  }
 
  const folded = collapse(sorted1, sorted2, sortedV, sortedSide, binOffset, nBins)
  for (let k = 0; k < folded.nnz; k++) sum += sortedV[k]
 
  return {
    bin1: sorted1.subarray(0, folded.nnz),
    bin2: sorted2.subarray(0, folded.nnz),
    count: sortedV.subarray(0, folded.nnz),
    binOffset: folded.binOffset,
    nnz: folded.nnz,
    sum,
    observed: observed === 'mixed' && folded.mirrored > 0 ? 'complete' : observed,
  }
}
 
/** Text per synchronous slice: big enough that the yield is noise, small
 * enough that a cancel is answered within a few tens of milliseconds. */
const SCAN_SLICE = 1 << 23
 
/** What the slice scanner carries between slices. */
interface ScanState {
  out: number
  line: number
  sawUpper: boolean
  sawLower: boolean
}
 
/** The first byte after the newline at or after `at`, so a slice ends on a row. */
function lineBoundaryAfter(bytes: Uint8Array, at: number): number {
  let i = at
  while (i < bytes.length && bytes[i] !== NEWLINE) i++
  return Math.min(bytes.length, i + 1)
}
 
/**
 * Scan `[from, to)` of a matrix into the arrays, and return where it stopped.
 *
 * Synchronous, and deliberately a function of its own — see the note at its one
 * call site. Everything it touches is a typed array or a number, so the loop
 * stays in the shape V8 can keep in registers.
 *
 * ## Why it reads its own digits rather than calling {@link readInt}
 *
 * It did call it, and that made this function **nineteen times slower** — but
 * only when a bin file had been parsed first, which is to say only ever in the
 * application and never in a test that timed the matrix alone. A 270 MB file
 * took 35 s where it now takes 1.8 s, and the difference was not in any of the
 * arithmetic below.
 *
 * `--trace-opt-verbose` says what happened: `delaying optimization of
 * scanSlice, IC changed`, once per tick, forever. {@link readInt} is shared
 * with {@link parseBins}, so its inline caches carry that call's feedback too —
 * a different array, different values, different shapes — and V8 will not tier
 * up a function whose caches are still moving. The scan therefore ran
 * interpreted from the first byte to the last, which is what a 30× gap looks
 * like.
 *
 * So the one hot loop in this reader owns everything it touches. That is not a
 * micro-optimisation and it is not a duplicate to be tidied away later: it is
 * the only thing separating a two-second open from a thirty-five-second one,
 * and reintroducing the call would restore the slow one silently, because every
 * test that times this file parses no bins.
 */
function scanSlice(
  bytes: Uint8Array,
  from: number,
  to: number,
  nBins: number,
  label: string,
  bin1: Int32Array,
  bin2: Int32Array,
  count: Float32Array,
  swapped: Uint8Array,
  state: ScanState,
): number {
  let at = from
  let out = state.out
  let line = state.line
  let sawUpper = state.sawUpper
  let sawLower = state.sawLower
 
  while (at < to) {
    if (bytes[at] === NEWLINE || bytes[at] === RETURN) {
      at++
      continue
    }
    if (bytes[at] === HASH) {
      while (at < to && bytes[at] !== NEWLINE) at++
      continue
    }
    line++
    // `binA`, then `binB`: unsigned decimal, tab-terminated. A sign here is not
    // a bin id, so it ends the number at zero digits and is reported as a row
    // that is not `binA  binB  count` — which it is.
    let a = 0
    let sawA = false
    while (at < to) {
      const c = bytes[at]
      if (c < ZERO || c > NINE) break
      a = a * 10 + (c - ZERO)
      sawA = true
      at++
    }
    if (!sawA || bytes[at] !== TAB) throw badMatrix(label, line, nBins)
    at++
    let b = 0
    let sawB = false
    while (at < to) {
      const c = bytes[at]
      if (c < ZERO || c > NINE) break
      b = b * 10 + (c - ZERO)
      sawB = true
      at++
    }
    if (!sawB || bytes[at] !== TAB) throw badMatrix(label, line, nBins)
    at++
 
    // The value column, which is an integer in `raw/` and a float in `iced/`.
    let v = 0
    let sawV = false
    let negative = false
    if (bytes[at] === MINUS) {
      negative = true
      at++
    }
    while (at < to) {
      const c = bytes[at]
      if (c < ZERO || c > NINE) break
      v = v * 10 + (c - ZERO)
      sawV = true
      at++
    }
    if (bytes[at] === DOT) {
      at++
      let scale = 0.1
      while (at < to) {
        const c = bytes[at]
        if (c < ZERO || c > NINE) break
        v += (c - ZERO) * scale
        scale /= 10
        sawV = true
        at++
      }
    }
    // An exponent, which `iced/` writes for very small bias-scaled values.
    if (bytes[at] === E_LOWER || bytes[at] === E_UPPER) {
      const mark = at
      at++
      let expSign = 1
      if (bytes[at] === MINUS) {
        expSign = -1
        at++
      } else if (bytes[at] === PLUS) {
        at++
      }
      let exp = 0
      let sawExp = false
      while (at < to) {
        const c = bytes[at]
        if (c < ZERO || c > NINE) break
        exp = exp * 10 + (c - ZERO)
        sawExp = true
        at++
      }
      // An `e` with no digits behind it is not an exponent; leave it to the
      // skip-to-newline below rather than swallowing the rest of the row.
      if (sawExp) v *= 10 ** (exp * expSign)
      else at = mark
    }
    if (!sawV) throw badMatrix(label, line, nBins)
    if (negative) v = -v
    while (at < to && bytes[at] !== NEWLINE) at++
    at++
 
    // 1-based to 0-based. A `0` in either column means the file is already
    // 0-based, which HiC-Pro does not write but a hand-made one might; it is
    // caught by the bounds check rather than silently shifting every pixel.
    const i = a - 1
    const j = b - 1
    if (i < 0 || j < 0 || i >= nBins || j >= nBins) {
      throw new ViewerError(
        'format',
        `${label} names bin ${a} × ${b} on line ${line}, and the bin file has ` +
          `${nBins} bins numbered 1…${nBins}. The two halves of the pair are for different ` +
          'resolutions, or for different genomes.',
        { label, line, bin1: a, bin2: b, nBins },
      )
    }
    // Strictly: a diagonal pixel is in neither triangle, and counting it in
    // both labelled every real file `mixed` — which every real file has, so the
    // label meant nothing until this was strict.
    if (i < j) sawUpper = true
    if (i > j) sawLower = true
    // Stored upper whichever way it arrived; `complete` is folded below.
    bin1[out] = i <= j ? i : j
    bin2[out] = i <= j ? j : i
    count[out] = v
    swapped[out] = i <= j ? 0 : 1
    out++
  }
 
  state.out = out
  state.line = line
  state.sawUpper = sawUpper
  state.sawLower = sawLower
  return at
}
 
/**
 * Collapse pixels that landed on the same cell, in place.
 *
 * One row band at a time, sorting each by column — the bands are short (a row
 * of a contact map) so an insertion sort over each beats one comparison sort
 * over the whole array, and the CSR order is preserved by construction.
 *
 * ## Mirrors are dropped; repeats are summed
 *
 * Two rows can land on one cell, and they mean opposite things:
 *
 * - a **mirror**, which is what `MATRIX_FORMAT=complete` writes: `(a, b)` and
 *   `(b, a)` are one contact stated twice, so **adding** them would double
 *   every off-diagonal cell of the map and leave the diagonal alone — a picture
 *   that still looks entirely like a contact map;
 * - a **repeat**, two rows for the same pair on the same side, which is what a
 *   file concatenated from two runs holds. Here the second is more evidence,
 *   and **dropping** it silently loses contacts.
 *
 * Once both have been swapped onto the upper triangle they are indistinguishable
 * — which is why the side each row was *stored* on is carried this far. It is
 * the only place the difference is still visible, and it is one byte per pixel
 * to keep it.
 */
function collapse(
  bin1: Int32Array,
  bin2: Int32Array,
  count: Float32Array,
  side: Uint8Array,
  binOffset: Float64Array,
  nBins: number,
): { nnz: number; binOffset: Float64Array; mirrored: number } {
  let write = 0
  let mirrored = 0
  const out = new Float64Array(nBins + 1)
  for (let row = 0; row < nBins; row++) {
    const lo = binOffset[row]
    const hi = binOffset[row + 1]
    out[row] = write
    // The band is already in column order, so equal cells are adjacent and one
    // linear pass settles them.
    let seenSide = -1
    for (let i = lo; i < hi; i++) {
      if (i > lo && bin2[i] === bin2[i - 1]) {
        if (side[i] !== seenSide) {
          // The mirror of one already written: one contact, stated twice.
          mirrored++
          seenSide = -2
          continue
        }
        // The same pair on the same side again: more of the same contact.
        count[write - 1] += count[i]
        continue
      }
      seenSide = side[i]
      bin1[write] = row
      bin2[write] = bin2[i]
      count[write] = count[i]
      write++
    }
  }
  out[nBins] = write
  return { nnz: write, binOffset: out, mirrored }
}
 
/**
 * A stable counting sort of `0…n` by `key`, returning the new order.
 *
 * `key` values are bin ids, so they are bounded by the bin count and a counting
 * sort is exact and linear — no comparisons, and no allocation beyond the
 * buckets and the order itself.
 */
function countingSort(key: Int32Array, n: number, buckets: number): Int32Array {
  const counts = new Int32Array(buckets + 1)
  for (let i = 0; i < n; i++) counts[key[i] + 1]++
  for (let b = 0; b < buckets; b++) counts[b + 1] += counts[b]
  const order = new Int32Array(n)
  for (let i = 0; i < n; i++) order[counts[key[i]]++] = i
  return order
}
 
/**
 * The same sort applied to an existing order, keeping it as the tie-break.
 *
 * Stability is the whole point: run over an order already sorted by column, it
 * produces (row, column) order — and its bucket boundaries, handed back, *are*
 * the cumulative `bin1_offset` a cooler stores.
 */
function countingSortBy(
  key: Int32Array,
  order: Int32Array,
  n: number,
  buckets: number,
): { order: Int32Array; offsets: Float64Array } {
  const offsets = new Float64Array(buckets + 1)
  for (let i = 0; i < n; i++) offsets[key[i] + 1]++
  for (let b = 0; b < buckets; b++) offsets[b + 1] += offsets[b]
  const cursor = Float64Array.from(offsets)
  const out = new Int32Array(n)
  for (let i = 0; i < n; i++) {
    const at = order[i]
    out[cursor[key[at]]++] = at
  }
  return { order: out, offsets }
}
 
/** The storage mode the rest of the reader is told about — always this one. */
export const HICPRO_STORAGE_MODE: StorageMode = 'symmetric-upper'
 
// ---------------------------------------------------------------------------
// Scanners
// ---------------------------------------------------------------------------
 
function readInt(bytes: Uint8Array, at: number): { value: number; at: number; saw: boolean } {
  let value = 0
  let saw = false
  let sign = 1
  if (bytes[at] === MINUS) {
    sign = -1
    at++
  }
  while (at < bytes.length) {
    const c = bytes[at]
    if (c < ZERO || c > NINE) break
    value = value * 10 + (c - ZERO)
    saw = true
    at++
  }
  return { value: value * sign, at, saw }
}
 
function badMatrix(label: string, line: number, nBins: number): ViewerError {
  return new ViewerError(
    'format',
    `${label} is not a HiC-Pro matrix: line ${line} is not \`binA  binB  count\`. ` +
      `The bin file beside it has ${nBins} bins, and the matrix names pairs of them, ` +
      'tab-separated, one pixel per line.',
    { label, line, nBins },
  )
}
 
function cancelled(): Error {
  const err = new Error('cancelled')
  err.name = 'AbortError'
  return err
}