pqplot 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Binary file
Binary file
pqplot/genome.py ADDED
@@ -0,0 +1,486 @@
1
+ """Genome model: chromosomes, bands, stains, regions and concatenation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from collections.abc import Iterable, Iterator
7
+ from dataclasses import dataclass
8
+ from importlib.resources import as_file, files
9
+ from os import PathLike
10
+
11
+ import numpy as np
12
+
13
+ from pqplot import cytobands
14
+
15
+ BUNDLED = {
16
+ "hg19": "hg19/cytoBand.txt.gz",
17
+ "hg38": "hg38/cytoBand.txt.gz",
18
+ "hs1": "hs1/chm13v2.0_cytobands_allchrs.bed",
19
+ "mm10": "mm10/cytoBand.txt.gz",
20
+ "mm39": "mm39/cytoBand.txt.gz",
21
+ }
22
+ PRIMARY = re.compile(r"(?:chr)?(?:\d+|[XYZW])")
23
+ LETTER_ORDER = {"X": 0, "Y": 1, "Z": 2, "W": 3, "MT": 4}
24
+
25
+
26
+ def chrom_key(name: object) -> str:
27
+ """Return the key that matches one chromosome across naming styles.
28
+
29
+ ``chr1`` and ``1`` share a key, and so do ``chrM`` and ``MT``.
30
+
31
+ Examples
32
+ --------
33
+ >>> chrom_key("chr1"), chrom_key("chrM")
34
+ ('1', 'MT')
35
+ """
36
+ key = str(name).removeprefix("chr")
37
+ return "MT" if key == "M" else key
38
+
39
+
40
+ def natural_order(name: object) -> tuple[int, int, str]:
41
+ """Return a sort key that puts numbered chromosomes first, by number.
42
+
43
+ X, Y, Z, W and the mitochondrion follow, then other names alphabetically.
44
+
45
+ Examples
46
+ --------
47
+ >>> sorted(["chrX", "chr10", "chr2"], key=natural_order)
48
+ ['chr2', 'chr10', 'chrX']
49
+ """
50
+ key = chrom_key(name)
51
+ if key.isdigit():
52
+ return (0, int(key), "")
53
+ return (1, LETTER_ORDER.get(key, len(LETTER_ORDER)), key)
54
+
55
+
56
+ @dataclass(frozen=True)
57
+ class Stain:
58
+ """Giemsa stain of a band, named as in UCSC tables.
59
+
60
+ Parameters
61
+ ----------
62
+ name : str
63
+ ``gneg``, ``gposNN``, ``acen``, ``gvar`` or ``stalk``.
64
+
65
+ Examples
66
+ --------
67
+ >>> Stain("gpos33").density
68
+ 0.33
69
+ """
70
+
71
+ name: str
72
+
73
+ @property
74
+ def density(self) -> float | None:
75
+ """Staining density from 0 (``gneg``) to 1 (``gpos100``).
76
+
77
+ Bare ``gpos`` counts as 1. Stains that are not G-bands, such as
78
+ ``acen``, ``gvar`` and ``stalk``, have no density.
79
+
80
+ Examples
81
+ --------
82
+ >>> Stain("gneg").density, Stain("gpos75").density, Stain("acen").density
83
+ (0.0, 0.75, None)
84
+ """
85
+ if self.name == "gneg":
86
+ return 0.0
87
+ if self.name.startswith("gpos"):
88
+ return int(self.name.removeprefix("gpos") or 100) / 100
89
+ return None
90
+
91
+
92
+ @dataclass(frozen=True)
93
+ class Band:
94
+ """One cytoband, in 0-based half-open bp coordinates.
95
+
96
+ Parameters
97
+ ----------
98
+ start, end : int
99
+ Span of the band.
100
+ name : str
101
+ Band name, such as ``p36.33``.
102
+ stain : Stain
103
+ Giemsa stain of the band.
104
+
105
+ Examples
106
+ --------
107
+ >>> Band(0, 2_300_000, "p36.33", Stain("gneg")).name
108
+ 'p36.33'
109
+ """
110
+
111
+ start: int
112
+ end: int
113
+ name: str
114
+ stain: Stain
115
+
116
+
117
+ @dataclass(frozen=True)
118
+ class Chromosome:
119
+ """One chromosome with its bands and centromere.
120
+
121
+ Parameters
122
+ ----------
123
+ name : str
124
+ Name as it appears in the source file, such as ``chr1``.
125
+ length : int
126
+ Length in bp.
127
+ bands : tuple of Band
128
+ Bands sorted by start. Empty when the assembly has none.
129
+ centromere : tuple of int or None
130
+ ``(start, end)`` of the centromere. ``(0, 0)`` marks a telocentric
131
+ chromosome. None means the position is unknown.
132
+
133
+ Examples
134
+ --------
135
+ >>> Chromosome("chr1", 1000, centromere=(400, 450)).telocentric
136
+ False
137
+ """
138
+
139
+ name: str
140
+ length: int
141
+ bands: tuple[Band, ...] = ()
142
+ centromere: tuple[int, int] | None = None
143
+
144
+ @property
145
+ def label(self) -> str:
146
+ """Display name without the ``chr`` prefix.
147
+
148
+ Examples
149
+ --------
150
+ >>> Chromosome("chrX", 1000).label
151
+ 'X'
152
+ """
153
+ return self.name.removeprefix("chr")
154
+
155
+ @property
156
+ def telocentric(self) -> bool:
157
+ """Whether the centromere sits at position 0.
158
+
159
+ Examples
160
+ --------
161
+ >>> Genome.bundled("mm39")["chr1"].telocentric
162
+ True
163
+ """
164
+ return self.centromere == (0, 0)
165
+
166
+
167
+ @dataclass(frozen=True)
168
+ class Region:
169
+ """A span on one chromosome.
170
+
171
+ Parameters
172
+ ----------
173
+ chrom : str
174
+ Chromosome name.
175
+ start, end : int
176
+ Span in bp.
177
+
178
+ Examples
179
+ --------
180
+ >>> Region("chr17", 43_044_295, 43_125_483).end
181
+ 43125483
182
+ """
183
+
184
+ chrom: str
185
+ start: int
186
+ end: int
187
+
188
+ @classmethod
189
+ def parse(cls, text: str) -> Region:
190
+ """Parse a locus such as ``chr17:43,044,295-43,125,483``.
191
+
192
+ Commas are optional. The numbers are kept as written, with no shift
193
+ between 1-based and 0-based coordinates.
194
+
195
+ Parameters
196
+ ----------
197
+ text : str
198
+ Locus in ``chrom:start-end`` form.
199
+
200
+ Returns
201
+ -------
202
+ Region
203
+
204
+ Raises
205
+ ------
206
+ ValueError
207
+ If the text is not a locus or start exceeds end.
208
+
209
+ Examples
210
+ --------
211
+ >>> Region.parse("chr17:43,044,295-43,125,483")
212
+ Region(chrom='chr17', start=43044295, end=43125483)
213
+ """
214
+ match = re.fullmatch(r"\s*([^:\s]+):([\d,]+)-([\d,]+)\s*", text)
215
+ if match is None:
216
+ raise ValueError(f"not a region: {text!r}")
217
+ chrom, start, end = match.groups()
218
+ start, end = int(start.replace(",", "")), int(end.replace(",", ""))
219
+ if start > end:
220
+ raise ValueError(f"region start exceeds end: {text!r}")
221
+ return cls(chrom, start, end)
222
+
223
+
224
+ class Genome:
225
+ """An ordered set of chromosomes.
226
+
227
+ Lookups match names across styles, so ``genome["1"]`` finds ``chr1``.
228
+
229
+ Parameters
230
+ ----------
231
+ chromosomes : iterable of Chromosome
232
+ Chromosomes in display order.
233
+
234
+ Examples
235
+ --------
236
+ >>> genome = Genome([Chromosome("chr1", 1000), Chromosome("chr2", 500)])
237
+ >>> genome["2"].length
238
+ 500
239
+ """
240
+
241
+ def __init__(self, chromosomes: Iterable[Chromosome]):
242
+ self._by_key = {chrom_key(c.name): c for c in chromosomes}
243
+
244
+ def __getitem__(self, name: object) -> Chromosome:
245
+ try:
246
+ return self._by_key[chrom_key(name)]
247
+ except KeyError:
248
+ raise KeyError(f"no chromosome {name!r} in genome") from None
249
+
250
+ def __contains__(self, name: object) -> bool:
251
+ return chrom_key(name) in self._by_key
252
+
253
+ def __iter__(self) -> Iterator[Chromosome]:
254
+ return iter(self._by_key.values())
255
+
256
+ def __len__(self) -> int:
257
+ return len(self._by_key)
258
+
259
+ @property
260
+ def autosomes(self) -> list[str]:
261
+ """Names of the numbered chromosomes.
262
+
263
+ Examples
264
+ --------
265
+ >>> Genome.bundled("mm39").autosomes[-1]
266
+ 'chr19'
267
+ """
268
+ return [c.name for c in self if chrom_key(c.name).isdigit()]
269
+
270
+ @classmethod
271
+ def bundled(cls, assembly: str) -> Genome:
272
+ """Load a banded assembly that ships with the package.
273
+
274
+ Parameters
275
+ ----------
276
+ assembly : str
277
+ ``hg19``, ``hg38``, ``hs1`` (T2T-CHM13), ``mm10`` or ``mm39``.
278
+
279
+ Returns
280
+ -------
281
+ Genome
282
+ The primary chromosomes, 1 to 22 (19 in mouse), X and Y.
283
+
284
+ Raises
285
+ ------
286
+ ValueError
287
+ If the assembly is not bundled.
288
+
289
+ Examples
290
+ --------
291
+ >>> hg38 = Genome.bundled("hg38")
292
+ >>> len(hg38), hg38["chr1"].centromere
293
+ (24, (121700000, 125100000))
294
+ """
295
+ if assembly not in BUNDLED:
296
+ raise ValueError(f"no bundled assembly {assembly!r}; choose from {list(BUNDLED)}")
297
+ with as_file(files("pqplot") / "data" / BUNDLED[assembly]) as path:
298
+ return cls.from_cytobands(path)
299
+
300
+ @classmethod
301
+ def from_cytobands(cls, path: str | PathLike, chroms: Iterable[str] | None = None) -> Genome:
302
+ """Read a genome from a cytoband table.
303
+
304
+ The centromere spans the ``acen`` bands. A chromosome with no ``acen``
305
+ band and no numbered p band, as in mouse, is telocentric. A
306
+ chromosome with p bands but no ``acen`` band has an unknown
307
+ centromere.
308
+
309
+ Parameters
310
+ ----------
311
+ path : str or PathLike
312
+ Table in UCSC ``cytoBand`` form, gzipped or plain.
313
+ chroms : iterable of str, optional
314
+ Chromosomes to keep, in this order. Names match across styles.
315
+ By default, the primary chromosomes in natural order. Primary
316
+ means numbered, X, Y, Z or W.
317
+
318
+ Returns
319
+ -------
320
+ Genome
321
+
322
+ Raises
323
+ ------
324
+ KeyError
325
+ If a chromosome in ``chroms`` is not in the file.
326
+
327
+ Examples
328
+ --------
329
+ >>> from importlib.resources import files
330
+ >>> path = files("pqplot") / "data/hg38/cytoBand.txt.gz"
331
+ >>> [c.name for c in Genome.from_cytobands(path, chroms=["X", "Y"])]
332
+ ['chrX', 'chrY']
333
+ """
334
+ rows = cytobands.read_bands(path)
335
+ chromosomes = []
336
+ for name in _select(rows, chroms):
337
+ bands = tuple(Band(s, e, n, Stain(stain)) for s, e, n, stain in sorted(rows[name]))
338
+ chromosomes.append(Chromosome(name, bands[-1].end, bands, _centromere(bands)))
339
+ return cls(chromosomes)
340
+
341
+ @classmethod
342
+ def from_sizes(
343
+ cls,
344
+ path: str | PathLike,
345
+ centromeres: str | PathLike | None = None,
346
+ chroms: Iterable[str] | None = None,
347
+ ) -> Genome:
348
+ """Read an unbanded genome from a ``.chrom.sizes`` or ``.fai`` file.
349
+
350
+ Parameters
351
+ ----------
352
+ path : str or PathLike
353
+ Sizes or FASTA index file.
354
+ centromeres : str or PathLike, optional
355
+ BED file of centromere spans. Names match across styles.
356
+ Chromosomes it lacks get an unknown centromere.
357
+ chroms : iterable of str, optional
358
+ Chromosomes to keep, in this order. By default, the primary
359
+ chromosomes in natural order, which drops unplaced and alt
360
+ contigs.
361
+
362
+ Returns
363
+ -------
364
+ Genome
365
+
366
+ Raises
367
+ ------
368
+ KeyError
369
+ If a chromosome in ``chroms`` is not in the file.
370
+
371
+ Examples
372
+ --------
373
+ >>> import tempfile
374
+ >>> from pathlib import Path
375
+ >>> path = Path(tempfile.mkdtemp()) / "x.chrom.sizes"
376
+ >>> _ = path.write_text("chr2\\t500\\nchrUn_1\\t9\\nchr1\\t1000\\n")
377
+ >>> [c.name for c in Genome.from_sizes(path)]
378
+ ['chr1', 'chr2']
379
+ """
380
+ sizes = cytobands.read_sizes(path)
381
+ spans = cytobands.read_centromeres(centromeres) if centromeres else {}
382
+ spans = {chrom_key(name): span for name, span in spans.items()}
383
+ return cls(
384
+ Chromosome(name, sizes[name], centromere=spans.get(chrom_key(name)))
385
+ for name in _select(sizes, chroms)
386
+ )
387
+
388
+ def concatenated(self, gap: float = 0) -> LinearGenome:
389
+ """Lay the chromosomes end to end on one axis.
390
+
391
+ Parameters
392
+ ----------
393
+ gap : float, default 0
394
+ Space in bp between neighboring chromosomes.
395
+
396
+ Returns
397
+ -------
398
+ LinearGenome
399
+
400
+ Examples
401
+ --------
402
+ >>> linear = Genome.bundled("hg38").concatenated(gap=5_000_000)
403
+ >>> linear.offset("chr2")
404
+ 253956422.0
405
+ """
406
+ return LinearGenome(self, gap)
407
+
408
+
409
+ class LinearGenome:
410
+ """Chromosomes of a genome laid end to end, for genome-wide plots.
411
+
412
+ Parameters
413
+ ----------
414
+ genome : Genome
415
+ Chromosomes in axis order.
416
+ gap : float, default 0
417
+ Space in bp between neighboring chromosomes.
418
+
419
+ Examples
420
+ --------
421
+ >>> linear = LinearGenome(Genome([Chromosome("1", 100), Chromosome("2", 50)]), gap=10)
422
+ >>> linear.length
423
+ 160.0
424
+ """
425
+
426
+ def __init__(self, genome: Genome, gap: float = 0):
427
+ self.genome = genome
428
+ starts = np.cumsum([0.0] + [c.length + gap for c in genome])
429
+ self._offsets = {chrom_key(c.name): start for c, start in zip(genome, starts, strict=False)}
430
+ self.length = float(starts[-1] - gap)
431
+
432
+ def offset(self, chrom: str) -> float:
433
+ """Return the axis position where a chromosome starts.
434
+
435
+ Examples
436
+ --------
437
+ >>> LinearGenome(Genome([Chromosome("1", 100), Chromosome("2", 50)])).offset("chr2")
438
+ 100.0
439
+ """
440
+ return float(self._offsets[chrom_key(chrom)])
441
+
442
+ def position(self, chrom: object, pos: object) -> np.ndarray:
443
+ """Map chromosome positions onto the concatenated axis.
444
+
445
+ Parameters
446
+ ----------
447
+ chrom : array-like of str or str
448
+ Chromosome of each position. Names match across styles.
449
+ pos : array-like of int or int
450
+ Position in bp on that chromosome.
451
+
452
+ Returns
453
+ -------
454
+ numpy.ndarray of float
455
+ Axis positions. NaN where the chromosome is not in the genome, so
456
+ matplotlib skips those points.
457
+
458
+ Examples
459
+ --------
460
+ >>> linear = LinearGenome(Genome([Chromosome("chr1", 100), Chromosome("chr2", 50)]))
461
+ >>> linear.position(["chr2", "1", "chrM"], [5, 7, 3])
462
+ array([105., 7., nan])
463
+ """
464
+ chroms = np.asarray(chrom).astype(str)
465
+ names, index = np.unique(chroms.ravel(), return_inverse=True)
466
+ offsets = np.array([self._offsets.get(chrom_key(n), np.nan) for n in names])
467
+ return offsets[index].reshape(chroms.shape) + np.asarray(pos, dtype=float)
468
+
469
+
470
+ def _select(names: Iterable[str], chroms: Iterable[str] | None) -> list[str]:
471
+ if chroms is None:
472
+ return sorted((n for n in names if PRIMARY.fullmatch(n)), key=natural_order)
473
+ by_key = {chrom_key(n): n for n in names}
474
+ missing = [c for c in chroms if chrom_key(c) not in by_key]
475
+ if missing:
476
+ raise KeyError(f"chromosomes not in file: {missing}")
477
+ return [by_key[chrom_key(c)] for c in chroms]
478
+
479
+
480
+ def _centromere(bands: tuple[Band, ...]) -> tuple[int, int] | None:
481
+ acen = [b for b in bands if b.stain.name == "acen"]
482
+ if acen:
483
+ return (min(b.start for b in acen), max(b.end for b in acen))
484
+ if not any(re.match(r"p\d", b.name) for b in bands):
485
+ return (0, 0)
486
+ return None