All files / src/annotations search.ts

100% Statements 86/86
93.61% Branches 44/47
100% Functions 8/8
100% Lines 86/86

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                                                      2x   2x         2x     2x     2x                                                                                                                 2x 38x 38x 38x 35x 35x 38x 27x 27x         38x 40x 40x 8x 8x 35x 35x           27x 27x 27x 5142x 5142x 27x 27x 98x 84x 84x 84x 98x 49x 98x 98x 27x     10269x 10269x 10269x     54x 54x 54x 54x 54x         54x 54x 54x 54x 54x 54x 54x 54x 54x 54x             8x 8x 8x 8x 32x 32x 32x 32x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 8x                 2x 4x 4x                     2x 5x 5x                 2x 2x 2x 2x  
/**
 * Finding a feature by name, for whichever box a reader typed into.
 *
 * Two linear scans over the `name` arrays. **A name typed whole comes first**:
 * `RAD5` is the gene asked for, and a list in file order put RAD59, RAD57, RAD55
 * and RAD54 above it, so Enter opened RAD59. That scan has to see the whole set
 * — the one exact match may be the last feature in it — so it compares lengths
 * before it compares letters, and a million-feature set costs it a millisecond.
 * Then the prefixes, which stop at the first handful of hits. An index would be
 * the right answer for a million-feature set and is the wrong answer here: the
 * arrays are already in memory, and building an index on load would cost every
 * reader who never types in this box.
 *
 * **One feature set, the starred one.** Searching every loaded annotation at
 * once answers "GAL4" with the same gene four times over, differing only in
 * which file it came from — and the four are usually the same coordinates.
 * Which one is searched is a press on the star beside its name.
 *
 * Here rather than in the browser, which is where it was, because a contact map
 * has the same question and the same answer sitting in the same store: a
 * whole-genome map of a mammal is three pixels per chromosome arm, so "go to
 * MYC" is a question that view has to answer without asking for a click on a
 * three-pixel target. What differs between the two surfaces is the *window* each
 * one opens, in its own base, which is why this returns numbers; what a reader
 * *reads* in the list is one string on both, and {@link hitLocus} writes it.
 */
 
import { formatLocus } from '../genome/assembly'
 
import { iscnName } from './cytoband'
import type { AnnotationStore } from './store'
import type { FeatureSet } from './types'
 
/** A zoomed-to feature keeps this much of its own length as margin on each side. */
export const FEATURE_PAD = 0.25
 
/** The smallest margin a feature gets, for one too short to make its own. */
export const FEATURE_MIN_PAD = 50
 
/** How many matches a box offers before it stops looking. */
const MAX_HITS = 10
 
export interface FeatureHit {
  name: string
  /**
   * The accession, where the file gave one and it is not the name already.
   *
   * `''` otherwise, which is both "this format has no such thing" and "this gene
   * has no symbol, so the name you are reading *is* the accession" — and the
   * label wants the same thing in either case, which is to print it once.
   */
  id: string
  contig: string
  /**
   * The window to open, **0-based half-open** — padded and clamped.
   *
   * The gene's own span plus a margin, because a gene drawn edge to edge in the
   * window is a gene with no context; and 0-based because that is the base the
   * reader's own coordinates are in (`metacooler/range.ts`). A surface that
   * writes 1-based loci adds the one on the way out, where it can see that it is
   * doing so — the browser's `formatLocus` does exactly that.
   */
  start: number
  end: number
  /**
   * The feature's **own** bounds, 0-based half-open — what the file says.
   *
   * Beside the padded window rather than derived from it, because the padding is
   * a quarter of the feature's length and cannot be taken back out. This is what
   * a hit is *labelled* with: the list used to print the window's start, so a
   * search for a 600-base gene offered a coordinate a hundred and fifty bases
   * before it began — a number a biologist reads as the gene's start and pastes
   * into a primer tool or a paper.
   */
  featureStart: number
  featureEnd: number
  /** The set it came from: the starred one's label. */
  source: string
}
 
/**
 * Features whose **name or accession** starts with `text`, from the set the star
 * picks — those it names exactly first.
 *
 * Both, because genomics addresses one gene two ways and a reader uses whichever
 * the thing they are reading used. `LipL1` is what a paper calls it and
 * `PF3D7_1314600` is what the supplementary table calls it, and a box that
 * answered only the first would refuse every identifier pasted out of a
 * spreadsheet. It matters most exactly where the symbols are least useful: a
 * *Plasmodium* annotation has sixty genes called `VAR`, and the accession is the
 * only way to ask for one of them.
 *
 * Empty for a query with a colon in it — that is coordinates, and coordinates
 * have no names to suggest; a list of "no match" hanging under a perfectly good
 * locus is worse than no list. Empty below two characters for the same reason a
 * search box does not answer one letter: everything matches.
 */
export function findFeatures(store: AnnotationStore, text: string, limit = MAX_HITS): FeatureHit[] {
  const raw = text.trim()
  const query = raw.toLowerCase()
  if (query.length < 2 || raw.includes(':')) return []
  const hits: FeatureHit[] = []
  const source = store.searchSource()
  if (source !== null && source.payload?.kind === 'features') {
    geneHits(source.payload.data, source.label, query, limit, hits)
  }
  // …then the bands of every karyotype loaded, by their ISCN names (§8.22).
  // After the genes, so a gene is never pushed off the list by a band, and
  // from every ideogram rather than a starred one: a band's name is the same
  // name in every file that has it.
  for (const entry of store.entries) {
    if (hits.length >= limit) break
    if (entry.kind !== 'ideogram' || entry.status !== 'ready' || entry.payload?.kind !== 'features') continue
    bandHits(entry.payload.data, entry.label, query, limit, hits)
  }
  return hits
}
 
/**
 * The genes of the search source whose name or accession is `query`, then those
 * whose name or accession starts with it, in the file's order within each.
 */
function geneHits(set: FeatureSet, label: string, query: string, limit: number, hits: FeatureHit[]): void {
  const exact = new Set<number>()
  for (let i = 0; i < set.length && exact.size < limit; i++) {
    if (spells(set.name[i], query) || spells(set.id[i], query)) exact.add(i)
  }
  for (const i of exact) hits.push(geneHit(set, i, label))
  for (let i = 0; i < set.length && hits.length < limit; i++) {
    if (exact.has(i)) continue
    const name = set.name[i]
    const id = set.id[i]
    const matched =
      (name !== '' && name.toLowerCase().startsWith(query)) ||
      (id !== '' && id.toLowerCase().startsWith(query))
    if (matched) hits.push(geneHit(set, i, label))
  }
}
 
/** Whether `value` is `query` whatever its case: the length first, which rules out nearly every name for nothing. */
function spells(value: string, query: string): boolean {
  return value.length === query.length && value.toLowerCase() === query
}
 
/** Feature `i` as a hit: its own span, and the padded window that opens it. */
function geneHit(set: FeatureSet, i: number, label: string): FeatureHit {
  const name = set.name[i]
  const id = set.id[i]
  const pad = Math.max(FEATURE_MIN_PAD, Math.round((set.end[i] - set.start[i]) * FEATURE_PAD))
  return {
    // A gene the file identifies but does not name is drawn as its accession
    // already (`annotations/parse.ts`), so the two are equal rather than the
    // name being empty — and a hit found by id alone still has something to
    // print. `name` is what to read; `id` is what to read it *by*.
    name: name !== '' ? name : id,
    id: id === name ? '' : id,
    contig: set.contigs[set.contig[i]],
    start: Math.max(0, set.start[i] - pad),
    end: set.end[i] + pad,
    featureStart: set.start[i],
    featureEnd: set.end[i],
    source: label,
  }
}
 
/**
 * The bands whose ISCN name starts with `query` — `8q24` for every band of
 * 8q24, `xq28` for Xq28 — with UCSC's `chr` prefix ignored on both sides, since
 * a cytogeneticist writes neither.
 */
function bandHits(set: FeatureSet, label: string, query: string, limit: number, hits: FeatureHit[]): void {
  const wanted = query.replace(/^chr/, '')
  if (wanted.length < 2) return
  for (let i = 0; i < set.length && hits.length < limit; i++) {
    if (set.name[i] === '') continue
    const contig = set.contigs[set.contig[i]]
    const name = iscnName(contig, set.name[i])
    if (!name.toLowerCase().startsWith(wanted)) continue
    const pad = Math.max(FEATURE_MIN_PAD, Math.round((set.end[i] - set.start[i]) * FEATURE_PAD))
    hits.push({
      name,
      id: '',
      contig,
      start: Math.max(0, set.start[i] - pad),
      end: set.end[i] + pad,
      featureStart: set.start[i],
      featureEnd: set.end[i],
      source: label,
    })
  }
}
 
/**
 * How a hit names itself in either box's list: `LipL1 (PF3D7_1314600)`.
 *
 * Shared so the map's suggestions and the browser's read the same, since the two
 * lists differ only in the base they write coordinates in — which is the one
 * thing they must not share (`ui/SearchBox.ts`).
 */
export function hitLabel(hit: FeatureHit): string {
  return hit.id === '' ? hit.name : `${hit.name} (${hit.id})`
}
 
/**
 * Where a hit is, as a reader reads it: `IV:453,045-453,650`.
 *
 * The feature's own span in the display form (§26.1), through the one writer of
 * a window, so the map's list and the browser's print the same string — and so
 * that what the list says and what the locus box says after the click are the
 * same place. Each surface still *opens* its own window: that is `hit.start` and
 * `hit.end`, padded, in the base that surface's plumbing takes.
 */
export function hitLocus(hit: FeatureHit): string {
  return formatLocus({ contig: hit.contig, start: hit.featureStart, end: hit.featureEnd })
}
 
/**
 * The window a click on a feature opens, in the same padding as a search hit.
 *
 * Shared so that finding a gene by name and double-clicking the same gene land
 * on the same window — two gestures for one intention, and a reader who used
 * both would otherwise see the picture shift between them.
 */
export function paddedSpan(start: number, end: number): { start: number; end: number } {
  const pad = Math.max(FEATURE_MIN_PAD, Math.round((end - start) * FEATURE_PAD))
  return { start: Math.max(0, start - pad), end: end + pad }
}